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 struct channel *chann;
79 list_for_each_entry(chann, &sess->ksmbd_chann_list, chann_list) {
80 if (chann->conn == conn)
88 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
91 * Return: 0 if there is a tree connection matched or these are
92 * skipable commands, otherwise error
94 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
96 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
97 unsigned int cmd = le16_to_cpu(req_hdr->Command);
101 if (cmd == SMB2_TREE_CONNECT_HE ||
102 cmd == SMB2_CANCEL_HE ||
103 cmd == SMB2_LOGOFF_HE) {
104 ksmbd_debug(SMB, "skip to check tree connect request\n");
108 if (xa_empty(&work->sess->tree_conns)) {
109 ksmbd_debug(SMB, "NO tree connected\n");
113 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
114 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
116 pr_err("Invalid tid %d\n", tree_id);
124 * smb2_set_err_rsp() - set error response code on smb response
125 * @work: smb work containing response buffer
127 void smb2_set_err_rsp(struct ksmbd_work *work)
129 struct smb2_err_rsp *err_rsp;
131 if (work->next_smb2_rcv_hdr_off)
132 err_rsp = ksmbd_resp_buf_next(work);
134 err_rsp = smb2_get_msg(work->response_buf);
136 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
137 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
138 err_rsp->ErrorContextCount = 0;
139 err_rsp->Reserved = 0;
140 err_rsp->ByteCount = 0;
141 err_rsp->ErrorData[0] = 0;
142 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
147 * is_smb2_neg_cmd() - is it smb2 negotiation command
148 * @work: smb work containing smb header
150 * Return: true if smb2 negotiation command, otherwise false
152 bool is_smb2_neg_cmd(struct ksmbd_work *work)
154 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
156 /* is it SMB2 header ? */
157 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
160 /* make sure it is request not response message */
161 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
164 if (hdr->Command != SMB2_NEGOTIATE)
171 * is_smb2_rsp() - is it smb2 response
172 * @work: smb work containing smb response buffer
174 * Return: true if smb2 response, otherwise false
176 bool is_smb2_rsp(struct ksmbd_work *work)
178 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
180 /* is it SMB2 header ? */
181 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
184 /* make sure it is response not request message */
185 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
192 * get_smb2_cmd_val() - get smb command code from smb header
193 * @work: smb work containing smb request buffer
195 * Return: smb2 request command value
197 u16 get_smb2_cmd_val(struct ksmbd_work *work)
199 struct smb2_hdr *rcv_hdr;
201 if (work->next_smb2_rcv_hdr_off)
202 rcv_hdr = ksmbd_req_buf_next(work);
204 rcv_hdr = smb2_get_msg(work->request_buf);
205 return le16_to_cpu(rcv_hdr->Command);
209 * set_smb2_rsp_status() - set error response code on smb2 header
210 * @work: smb work containing response buffer
211 * @err: error response code
213 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
215 struct smb2_hdr *rsp_hdr;
217 if (work->next_smb2_rcv_hdr_off)
218 rsp_hdr = ksmbd_resp_buf_next(work);
220 rsp_hdr = smb2_get_msg(work->response_buf);
221 rsp_hdr->Status = err;
222 smb2_set_err_rsp(work);
226 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
227 * @work: smb work containing smb request buffer
229 * smb2 negotiate response is sent in reply of smb1 negotiate command for
230 * dialect auto-negotiation.
232 int init_smb2_neg_rsp(struct ksmbd_work *work)
234 struct smb2_hdr *rsp_hdr;
235 struct smb2_negotiate_rsp *rsp;
236 struct ksmbd_conn *conn = work->conn;
238 *(__be32 *)work->response_buf =
239 cpu_to_be32(conn->vals->header_size);
241 rsp_hdr = smb2_get_msg(work->response_buf);
242 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
243 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
244 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
245 rsp_hdr->CreditRequest = cpu_to_le16(2);
246 rsp_hdr->Command = SMB2_NEGOTIATE;
247 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
248 rsp_hdr->NextCommand = 0;
249 rsp_hdr->MessageId = 0;
250 rsp_hdr->Id.SyncId.ProcessId = 0;
251 rsp_hdr->Id.SyncId.TreeId = 0;
252 rsp_hdr->SessionId = 0;
253 memset(rsp_hdr->Signature, 0, 16);
255 rsp = smb2_get_msg(work->response_buf);
257 WARN_ON(ksmbd_conn_good(work));
259 rsp->StructureSize = cpu_to_le16(65);
260 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
261 rsp->DialectRevision = cpu_to_le16(conn->dialect);
262 /* Not setting conn guid rsp->ServerGUID, as it
263 * not used by client for identifying connection
265 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
266 /* Default Max Message Size till SMB2.0, 64K*/
267 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
268 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
269 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
271 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
272 rsp->ServerStartTime = 0;
274 rsp->SecurityBufferOffset = cpu_to_le16(128);
275 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
276 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
277 le16_to_cpu(rsp->SecurityBufferOffset));
278 inc_rfc1001_len(work->response_buf,
279 sizeof(struct smb2_negotiate_rsp) -
280 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
282 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
283 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
284 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
285 conn->use_spnego = true;
287 ksmbd_conn_set_need_negotiate(work);
292 * smb2_set_rsp_credits() - set number of credits in response buffer
293 * @work: smb work containing smb response buffer
295 int smb2_set_rsp_credits(struct ksmbd_work *work)
297 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
298 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
299 struct ksmbd_conn *conn = work->conn;
300 unsigned short credits_requested, aux_max;
301 unsigned short credit_charge, credits_granted = 0;
303 if (work->send_no_response)
306 hdr->CreditCharge = req_hdr->CreditCharge;
308 if (conn->total_credits > conn->vals->max_credits) {
309 hdr->CreditRequest = 0;
310 pr_err("Total credits overflow: %d\n", conn->total_credits);
314 credit_charge = max_t(unsigned short,
315 le16_to_cpu(req_hdr->CreditCharge), 1);
316 if (credit_charge > conn->total_credits) {
317 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
318 credit_charge, conn->total_credits);
322 conn->total_credits -= credit_charge;
323 conn->outstanding_credits -= credit_charge;
324 credits_requested = max_t(unsigned short,
325 le16_to_cpu(req_hdr->CreditRequest), 1);
327 /* according to smb2.credits smbtorture, Windows server
328 * 2016 or later grant up to 8192 credits at once.
330 * TODO: Need to adjuct CreditRequest value according to
333 if (hdr->Command == SMB2_NEGOTIATE)
336 aux_max = conn->vals->max_credits - credit_charge;
337 credits_granted = min_t(unsigned short, credits_requested, aux_max);
339 if (conn->vals->max_credits - conn->total_credits < credits_granted)
340 credits_granted = conn->vals->max_credits -
343 conn->total_credits += credits_granted;
344 work->credits_granted += credits_granted;
346 if (!req_hdr->NextCommand) {
347 /* Update CreditRequest in last request */
348 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
351 "credits: requested[%d] granted[%d] total_granted[%d]\n",
352 credits_requested, credits_granted,
353 conn->total_credits);
358 * init_chained_smb2_rsp() - initialize smb2 chained response
359 * @work: smb work containing smb response buffer
361 static void init_chained_smb2_rsp(struct ksmbd_work *work)
363 struct smb2_hdr *req = ksmbd_req_buf_next(work);
364 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
365 struct smb2_hdr *rsp_hdr;
366 struct smb2_hdr *rcv_hdr;
367 int next_hdr_offset = 0;
370 /* Len of this response = updated RFC len - offset of previous cmd
371 * in the compound rsp
374 /* Storing the current local FID which may be needed by subsequent
375 * command in the compound request
377 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
378 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
379 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
380 work->compound_sid = le64_to_cpu(rsp->SessionId);
383 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
384 next_hdr_offset = le32_to_cpu(req->NextCommand);
386 new_len = ALIGN(len, 8);
387 inc_rfc1001_len(work->response_buf,
388 sizeof(struct smb2_hdr) + new_len - len);
389 rsp->NextCommand = cpu_to_le32(new_len);
391 work->next_smb2_rcv_hdr_off += next_hdr_offset;
392 work->next_smb2_rsp_hdr_off += new_len;
394 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
395 new_len, work->next_smb2_rcv_hdr_off,
396 work->next_smb2_rsp_hdr_off);
398 rsp_hdr = ksmbd_resp_buf_next(work);
399 rcv_hdr = ksmbd_req_buf_next(work);
401 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
402 ksmbd_debug(SMB, "related flag should be set\n");
403 work->compound_fid = KSMBD_NO_FID;
404 work->compound_pfid = KSMBD_NO_FID;
406 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
407 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
408 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
409 rsp_hdr->Command = rcv_hdr->Command;
412 * Message is response. We don't grant oplock yet.
414 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
415 SMB2_FLAGS_RELATED_OPERATIONS);
416 rsp_hdr->NextCommand = 0;
417 rsp_hdr->MessageId = rcv_hdr->MessageId;
418 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
419 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
420 rsp_hdr->SessionId = rcv_hdr->SessionId;
421 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
425 * is_chained_smb2_message() - check for chained command
426 * @work: smb work containing smb request buffer
428 * Return: true if chained request, otherwise false
430 bool is_chained_smb2_message(struct ksmbd_work *work)
432 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
433 unsigned int len, next_cmd;
435 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
438 hdr = ksmbd_req_buf_next(work);
439 next_cmd = le32_to_cpu(hdr->NextCommand);
441 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
442 __SMB2_HEADER_STRUCTURE_SIZE >
443 get_rfc1002_len(work->request_buf)) {
444 pr_err("next command(%u) offset exceeds smb msg size\n",
449 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
451 pr_err("next response offset exceeds response buffer size\n");
455 ksmbd_debug(SMB, "got SMB2 chained command\n");
456 init_chained_smb2_rsp(work);
458 } else if (work->next_smb2_rcv_hdr_off) {
460 * This is last request in chained command,
461 * align response to 8 byte
463 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
464 len = len - get_rfc1002_len(work->response_buf);
466 ksmbd_debug(SMB, "padding len %u\n", len);
467 inc_rfc1001_len(work->response_buf, len);
468 if (work->aux_payload_sz)
469 work->aux_payload_sz += len;
476 * init_smb2_rsp_hdr() - initialize smb2 response
477 * @work: smb work containing smb request buffer
481 int init_smb2_rsp_hdr(struct ksmbd_work *work)
483 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
484 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
485 struct ksmbd_conn *conn = work->conn;
487 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
488 *(__be32 *)work->response_buf =
489 cpu_to_be32(conn->vals->header_size);
490 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
491 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
492 rsp_hdr->Command = rcv_hdr->Command;
495 * Message is response. We don't grant oplock yet.
497 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
498 rsp_hdr->NextCommand = 0;
499 rsp_hdr->MessageId = rcv_hdr->MessageId;
500 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
501 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
502 rsp_hdr->SessionId = rcv_hdr->SessionId;
503 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
505 work->syncronous = true;
506 if (work->async_id) {
507 ksmbd_release_id(&conn->async_ida, work->async_id);
515 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
516 * @work: smb work containing smb request buffer
518 * Return: 0 on success, otherwise -ENOMEM
520 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
522 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
523 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
524 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
525 size_t sz = small_sz;
526 int cmd = le16_to_cpu(hdr->Command);
528 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
531 if (cmd == SMB2_QUERY_INFO_HE) {
532 struct smb2_query_info_req *req;
534 req = smb2_get_msg(work->request_buf);
535 if ((req->InfoType == SMB2_O_INFO_FILE &&
536 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
537 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
538 req->InfoType == SMB2_O_INFO_SECURITY)
542 /* allocate large response buf for chained commands */
543 if (le32_to_cpu(hdr->NextCommand) > 0)
546 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
547 if (!work->response_buf)
550 work->response_sz = sz;
555 * smb2_check_user_session() - check for valid session for a user
556 * @work: smb work containing smb request buffer
558 * Return: 0 on success, otherwise error
560 int smb2_check_user_session(struct ksmbd_work *work)
562 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
563 struct ksmbd_conn *conn = work->conn;
564 unsigned int cmd = conn->ops->get_cmd_val(work);
565 unsigned long long sess_id;
569 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
570 * require a session id, so no need to validate user session's for
573 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
574 cmd == SMB2_SESSION_SETUP_HE)
577 if (!ksmbd_conn_good(work))
580 sess_id = le64_to_cpu(req_hdr->SessionId);
581 /* Check for validity of user session */
582 work->sess = ksmbd_session_lookup_all(conn, sess_id);
585 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
589 static void destroy_previous_session(struct ksmbd_conn *conn,
590 struct ksmbd_user *user, u64 id)
592 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
593 struct ksmbd_user *prev_user;
594 struct channel *chann;
599 prev_user = prev_sess->user;
602 strcmp(user->name, prev_user->name) ||
603 user->passkey_sz != prev_user->passkey_sz ||
604 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
607 prev_sess->state = SMB2_SESSION_EXPIRED;
608 write_lock(&prev_sess->chann_lock);
609 list_for_each_entry(chann, &prev_sess->ksmbd_chann_list, chann_list)
610 chann->conn->status = KSMBD_SESS_EXITING;
611 write_unlock(&prev_sess->chann_lock);
615 * smb2_get_name() - get filename string from on the wire smb format
616 * @src: source buffer
617 * @maxlen: maxlen of source string
618 * @local_nls: nls_table pointer
620 * Return: matching converted filename on success, otherwise error ptr
623 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
627 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
629 pr_err("failed to get name %ld\n", PTR_ERR(name));
633 ksmbd_conv_path_to_unix(name);
634 ksmbd_strip_last_slash(name);
638 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
640 struct smb2_hdr *rsp_hdr;
641 struct ksmbd_conn *conn = work->conn;
644 rsp_hdr = smb2_get_msg(work->response_buf);
645 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
647 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
649 pr_err("Failed to alloc async message id\n");
652 work->syncronous = false;
654 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
657 "Send interim Response to inform async request id : %d\n",
660 work->cancel_fn = fn;
661 work->cancel_argv = arg;
663 if (list_empty(&work->async_request_entry)) {
664 spin_lock(&conn->request_lock);
665 list_add_tail(&work->async_request_entry, &conn->async_requests);
666 spin_unlock(&conn->request_lock);
672 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
674 struct smb2_hdr *rsp_hdr;
676 rsp_hdr = smb2_get_msg(work->response_buf);
677 smb2_set_err_rsp(work);
678 rsp_hdr->Status = status;
681 ksmbd_conn_write(work);
686 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
688 if (S_ISDIR(mode) || S_ISREG(mode))
692 return IO_REPARSE_TAG_LX_SYMLINK_LE;
693 else if (S_ISFIFO(mode))
694 return IO_REPARSE_TAG_LX_FIFO_LE;
695 else if (S_ISSOCK(mode))
696 return IO_REPARSE_TAG_AF_UNIX_LE;
697 else if (S_ISCHR(mode))
698 return IO_REPARSE_TAG_LX_CHR_LE;
699 else if (S_ISBLK(mode))
700 return IO_REPARSE_TAG_LX_BLK_LE;
706 * smb2_get_dos_mode() - get file mode in dos format from unix mode
707 * @stat: kstat containing file mode
708 * @attribute: attribute flags
710 * Return: converted dos mode
712 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
716 if (S_ISDIR(stat->mode)) {
717 attr = FILE_ATTRIBUTE_DIRECTORY |
718 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
720 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
721 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
722 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
723 FILE_SUPPORTS_SPARSE_FILES))
724 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
726 if (smb2_get_reparse_tag_special_file(stat->mode))
727 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
733 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
736 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
737 pneg_ctxt->DataLength = cpu_to_le16(38);
738 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
739 pneg_ctxt->Reserved = cpu_to_le32(0);
740 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
741 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
742 pneg_ctxt->HashAlgorithms = hash_id;
745 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
748 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
749 pneg_ctxt->DataLength = cpu_to_le16(4);
750 pneg_ctxt->Reserved = cpu_to_le32(0);
751 pneg_ctxt->CipherCount = cpu_to_le16(1);
752 pneg_ctxt->Ciphers[0] = cipher_type;
755 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
758 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
759 pneg_ctxt->DataLength =
760 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
761 - sizeof(struct smb2_neg_context));
762 pneg_ctxt->Reserved = cpu_to_le32(0);
763 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
764 pneg_ctxt->Flags = cpu_to_le32(0);
765 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
768 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
771 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
772 pneg_ctxt->DataLength =
773 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
774 - sizeof(struct smb2_neg_context));
775 pneg_ctxt->Reserved = cpu_to_le32(0);
776 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
777 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
780 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
782 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
783 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
784 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
785 pneg_ctxt->Name[0] = 0x93;
786 pneg_ctxt->Name[1] = 0xAD;
787 pneg_ctxt->Name[2] = 0x25;
788 pneg_ctxt->Name[3] = 0x50;
789 pneg_ctxt->Name[4] = 0x9C;
790 pneg_ctxt->Name[5] = 0xB4;
791 pneg_ctxt->Name[6] = 0x11;
792 pneg_ctxt->Name[7] = 0xE7;
793 pneg_ctxt->Name[8] = 0xB4;
794 pneg_ctxt->Name[9] = 0x23;
795 pneg_ctxt->Name[10] = 0x83;
796 pneg_ctxt->Name[11] = 0xDE;
797 pneg_ctxt->Name[12] = 0x96;
798 pneg_ctxt->Name[13] = 0x8B;
799 pneg_ctxt->Name[14] = 0xCD;
800 pneg_ctxt->Name[15] = 0x7C;
803 static void assemble_neg_contexts(struct ksmbd_conn *conn,
804 struct smb2_negotiate_rsp *rsp,
807 char *pneg_ctxt = (char *)rsp +
808 le32_to_cpu(rsp->NegotiateContextOffset);
809 int neg_ctxt_cnt = 1;
813 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
814 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
815 conn->preauth_info->Preauth_HashId);
816 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
817 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
818 ctxt_size = sizeof(struct smb2_preauth_neg_context);
819 /* Round to 8 byte boundary */
820 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
822 if (conn->cipher_type) {
823 ctxt_size = round_up(ctxt_size, 8);
825 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
826 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
828 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
829 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
830 /* Round to 8 byte boundary */
832 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
836 if (conn->compress_algorithm) {
837 ctxt_size = round_up(ctxt_size, 8);
839 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
840 /* Temporarily set to SMB3_COMPRESS_NONE */
841 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
842 conn->compress_algorithm);
843 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
844 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
845 /* Round to 8 byte boundary */
846 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
850 if (conn->posix_ext_supported) {
851 ctxt_size = round_up(ctxt_size, 8);
853 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
854 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
855 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
856 ctxt_size += sizeof(struct smb2_posix_neg_context);
857 /* Round to 8 byte boundary */
858 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
861 if (conn->signing_negotiated) {
862 ctxt_size = round_up(ctxt_size, 8);
864 "assemble SMB2_SIGNING_CAPABILITIES context\n");
865 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
866 conn->signing_algorithm);
867 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
868 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
871 inc_rfc1001_len(smb2_buf_len, ctxt_size);
874 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
875 struct smb2_preauth_neg_context *pneg_ctxt,
879 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
880 * which may not be present. Only check for used HashAlgorithms[1].
882 if (len_of_ctxts < MIN_PREAUTH_CTXT_DATA_LEN)
883 return STATUS_INVALID_PARAMETER;
885 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
886 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
888 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
889 return STATUS_SUCCESS;
892 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
893 struct smb2_encryption_neg_context *pneg_ctxt,
896 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
897 int i, cphs_size = cph_cnt * sizeof(__le16);
899 conn->cipher_type = 0;
901 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
903 pr_err("Invalid cipher count(%d)\n", cph_cnt);
907 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
910 for (i = 0; i < cph_cnt; i++) {
911 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
912 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
913 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
914 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
915 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
916 pneg_ctxt->Ciphers[i]);
917 conn->cipher_type = pneg_ctxt->Ciphers[i];
924 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
925 * @conn: smb connection
927 * Return: true if connection should be encrypted, else false
929 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
931 if (!conn->ops->generate_encryptionkey)
935 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
936 * SMB 3.1.1 uses the cipher_type field.
938 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
942 static void decode_compress_ctxt(struct ksmbd_conn *conn,
943 struct smb2_compression_capabilities_context *pneg_ctxt)
945 conn->compress_algorithm = SMB3_COMPRESS_NONE;
948 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
949 struct smb2_signing_capabilities *pneg_ctxt,
952 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
953 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
955 conn->signing_negotiated = false;
957 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
959 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
963 for (i = 0; i < sign_algo_cnt; i++) {
964 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
965 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
966 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
967 pneg_ctxt->SigningAlgorithms[i]);
968 conn->signing_negotiated = true;
969 conn->signing_algorithm =
970 pneg_ctxt->SigningAlgorithms[i];
976 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
977 struct smb2_negotiate_req *req,
980 /* +4 is to account for the RFC1001 len field */
981 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
982 int i = 0, len_of_ctxts;
983 int offset = le32_to_cpu(req->NegotiateContextOffset);
984 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
985 __le32 status = STATUS_INVALID_PARAMETER;
987 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
988 if (len_of_smb <= offset) {
989 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
993 len_of_ctxts = len_of_smb - offset;
995 while (i++ < neg_ctxt_cnt) {
998 /* check that offset is not beyond end of SMB */
999 if (len_of_ctxts == 0)
1002 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1005 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1006 clen = le16_to_cpu(pctx->DataLength);
1007 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1010 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1012 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1013 if (conn->preauth_info->Preauth_HashId)
1016 status = decode_preauth_ctxt(conn,
1017 (struct smb2_preauth_neg_context *)pctx,
1019 if (status != STATUS_SUCCESS)
1021 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1023 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1024 if (conn->cipher_type)
1027 decode_encrypt_ctxt(conn,
1028 (struct smb2_encryption_neg_context *)pctx,
1030 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1032 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1033 if (conn->compress_algorithm)
1036 decode_compress_ctxt(conn,
1037 (struct smb2_compression_capabilities_context *)pctx);
1038 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1040 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1041 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1043 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1044 conn->posix_ext_supported = true;
1045 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1047 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1048 decode_sign_cap_ctxt(conn,
1049 (struct smb2_signing_capabilities *)pctx,
1053 /* offsets must be 8 byte aligned */
1054 clen = (clen + 7) & ~0x7;
1055 offset = clen + sizeof(struct smb2_neg_context);
1056 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1062 * smb2_handle_negotiate() - handler for smb2 negotiate command
1063 * @work: smb work containing smb request buffer
1067 int smb2_handle_negotiate(struct ksmbd_work *work)
1069 struct ksmbd_conn *conn = work->conn;
1070 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1071 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1073 unsigned int smb2_buf_len, smb2_neg_size;
1076 ksmbd_debug(SMB, "Received negotiate request\n");
1077 conn->need_neg = false;
1078 if (ksmbd_conn_good(work)) {
1079 pr_err("conn->tcp_status is already in CifsGood State\n");
1080 work->send_no_response = 1;
1084 if (req->DialectCount == 0) {
1085 pr_err("malformed packet\n");
1086 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1091 smb2_buf_len = get_rfc1002_len(work->request_buf);
1092 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1093 if (smb2_neg_size > smb2_buf_len) {
1094 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1099 if (conn->dialect == SMB311_PROT_ID) {
1100 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1102 if (smb2_buf_len < nego_ctxt_off) {
1103 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1108 if (smb2_neg_size > nego_ctxt_off) {
1109 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1114 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1116 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1121 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1123 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1129 conn->cli_cap = le32_to_cpu(req->Capabilities);
1130 switch (conn->dialect) {
1131 case SMB311_PROT_ID:
1132 conn->preauth_info =
1133 kzalloc(sizeof(struct preauth_integrity_info),
1135 if (!conn->preauth_info) {
1137 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1141 status = deassemble_neg_contexts(conn, req,
1142 get_rfc1002_len(work->request_buf));
1143 if (status != STATUS_SUCCESS) {
1144 pr_err("deassemble_neg_contexts error(0x%x)\n",
1146 rsp->hdr.Status = status;
1148 kfree(conn->preauth_info);
1149 conn->preauth_info = NULL;
1153 rc = init_smb3_11_server(conn);
1155 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1156 kfree(conn->preauth_info);
1157 conn->preauth_info = NULL;
1161 ksmbd_gen_preauth_integrity_hash(conn,
1163 conn->preauth_info->Preauth_HashValue);
1164 rsp->NegotiateContextOffset =
1165 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1166 assemble_neg_contexts(conn, rsp, work->response_buf);
1168 case SMB302_PROT_ID:
1169 init_smb3_02_server(conn);
1172 init_smb3_0_server(conn);
1175 init_smb2_1_server(conn);
1180 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1182 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1186 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1189 conn->connection_type = conn->dialect;
1191 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1192 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1193 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1195 memcpy(conn->ClientGUID, req->ClientGUID,
1196 SMB2_CLIENT_GUID_SIZE);
1197 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1199 rsp->StructureSize = cpu_to_le16(65);
1200 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1201 /* Not setting conn guid rsp->ServerGUID, as it
1202 * not used by client for identifying server
1204 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1206 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1207 rsp->ServerStartTime = 0;
1208 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1209 le32_to_cpu(rsp->NegotiateContextOffset),
1210 le16_to_cpu(rsp->NegotiateContextCount));
1212 rsp->SecurityBufferOffset = cpu_to_le16(128);
1213 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1214 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1215 le16_to_cpu(rsp->SecurityBufferOffset));
1216 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1217 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1219 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1220 conn->use_spnego = true;
1222 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1223 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1224 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1226 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1227 server_conf.enforced_signing = true;
1228 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1232 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1233 ksmbd_conn_set_need_negotiate(work);
1237 smb2_set_err_rsp(work);
1242 static int alloc_preauth_hash(struct ksmbd_session *sess,
1243 struct ksmbd_conn *conn)
1245 if (sess->Preauth_HashValue)
1248 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1249 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1250 if (!sess->Preauth_HashValue)
1256 static int generate_preauth_hash(struct ksmbd_work *work)
1258 struct ksmbd_conn *conn = work->conn;
1259 struct ksmbd_session *sess = work->sess;
1262 if (conn->dialect != SMB311_PROT_ID)
1265 if (conn->binding) {
1266 struct preauth_session *preauth_sess;
1268 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1269 if (!preauth_sess) {
1270 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1275 preauth_hash = preauth_sess->Preauth_HashValue;
1277 if (!sess->Preauth_HashValue)
1278 if (alloc_preauth_hash(sess, conn))
1280 preauth_hash = sess->Preauth_HashValue;
1283 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1287 static int decode_negotiation_token(struct ksmbd_conn *conn,
1288 struct negotiate_message *negblob,
1291 if (!conn->use_spnego)
1294 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1295 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1296 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1297 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1298 conn->use_spnego = false;
1304 static int ntlm_negotiate(struct ksmbd_work *work,
1305 struct negotiate_message *negblob,
1308 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1309 struct challenge_message *chgblob;
1310 unsigned char *spnego_blob = NULL;
1311 u16 spnego_blob_len;
1315 ksmbd_debug(SMB, "negotiate phase\n");
1316 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1320 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1322 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1323 memset(chgblob, 0, sizeof(struct challenge_message));
1325 if (!work->conn->use_spnego) {
1326 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1330 rsp->SecurityBufferLength = cpu_to_le16(sz);
1334 sz = sizeof(struct challenge_message);
1335 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1337 neg_blob = kzalloc(sz, GFP_KERNEL);
1341 chgblob = (struct challenge_message *)neg_blob;
1342 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1348 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1355 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1356 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1357 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1365 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1366 struct smb2_sess_setup_req *req)
1370 if (conn->use_spnego && conn->mechToken)
1371 return (struct authenticate_message *)conn->mechToken;
1373 sz = le16_to_cpu(req->SecurityBufferOffset);
1374 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1378 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1379 struct smb2_sess_setup_req *req)
1381 struct authenticate_message *authblob;
1382 struct ksmbd_user *user;
1384 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1386 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1387 if (secbuf_len < sizeof(struct authenticate_message)) {
1388 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1391 authblob = user_authblob(conn, req);
1392 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1393 name_len = le16_to_cpu(authblob->UserName.Length);
1394 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1396 if (auth_msg_len < (u64)name_off + name_len)
1399 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1404 pr_err("cannot allocate memory\n");
1408 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1409 user = ksmbd_login_user(name);
1414 static int ntlm_authenticate(struct ksmbd_work *work)
1416 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1417 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1418 struct ksmbd_conn *conn = work->conn;
1419 struct ksmbd_session *sess = work->sess;
1420 struct channel *chann = NULL;
1421 struct ksmbd_user *user;
1425 ksmbd_debug(SMB, "authenticate phase\n");
1426 if (conn->use_spnego) {
1427 unsigned char *spnego_blob;
1428 u16 spnego_blob_len;
1430 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1436 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1437 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1438 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1440 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1443 user = session_user(conn, req);
1445 ksmbd_debug(SMB, "Unknown user name or an error\n");
1449 /* Check for previous session */
1450 prev_id = le64_to_cpu(req->PreviousSessionId);
1451 if (prev_id && prev_id != sess->id)
1452 destroy_previous_session(conn, user, prev_id);
1454 if (sess->state == SMB2_SESSION_VALID) {
1456 * Reuse session if anonymous try to connect
1457 * on reauthetication.
1459 if (ksmbd_anonymous_user(user)) {
1460 ksmbd_free_user(user);
1464 if (!ksmbd_compare_user(sess->user, user)) {
1465 ksmbd_free_user(user);
1468 ksmbd_free_user(user);
1473 if (user_guest(sess->user)) {
1474 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1476 struct authenticate_message *authblob;
1478 authblob = user_authblob(conn, req);
1479 sz = le16_to_cpu(req->SecurityBufferLength);
1480 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1482 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1483 ksmbd_debug(SMB, "authentication failed\n");
1489 * If session state is SMB2_SESSION_VALID, We can assume
1490 * that it is reauthentication. And the user/password
1491 * has been verified, so return it here.
1493 if (sess->state == SMB2_SESSION_VALID) {
1495 goto binding_session;
1499 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1500 (conn->sign || server_conf.enforced_signing)) ||
1501 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1504 if (smb3_encryption_negotiated(conn) &&
1505 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1506 rc = conn->ops->generate_encryptionkey(conn, sess);
1509 "SMB3 encryption key generation failed\n");
1513 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1515 * signing is disable if encryption is enable
1522 if (conn->dialect >= SMB30_PROT_ID) {
1523 read_lock(&sess->chann_lock);
1524 chann = lookup_chann_list(sess, conn);
1525 read_unlock(&sess->chann_lock);
1527 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1532 INIT_LIST_HEAD(&chann->chann_list);
1533 write_lock(&sess->chann_lock);
1534 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1535 write_unlock(&sess->chann_lock);
1539 if (conn->ops->generate_signingkey) {
1540 rc = conn->ops->generate_signingkey(sess, conn);
1542 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1547 if (!ksmbd_conn_lookup_dialect(conn)) {
1548 pr_err("fail to verify the dialect\n");
1554 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1555 static int krb5_authenticate(struct ksmbd_work *work)
1557 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1558 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1559 struct ksmbd_conn *conn = work->conn;
1560 struct ksmbd_session *sess = work->sess;
1561 char *in_blob, *out_blob;
1562 struct channel *chann = NULL;
1564 int in_len, out_len;
1567 in_blob = (char *)&req->hdr.ProtocolId +
1568 le16_to_cpu(req->SecurityBufferOffset);
1569 in_len = le16_to_cpu(req->SecurityBufferLength);
1570 out_blob = (char *)&rsp->hdr.ProtocolId +
1571 le16_to_cpu(rsp->SecurityBufferOffset);
1572 out_len = work->response_sz -
1573 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1575 /* Check previous session */
1576 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1577 if (prev_sess_id && prev_sess_id != sess->id)
1578 destroy_previous_session(conn, sess->user, prev_sess_id);
1580 if (sess->state == SMB2_SESSION_VALID)
1581 ksmbd_free_user(sess->user);
1583 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1584 out_blob, &out_len);
1586 ksmbd_debug(SMB, "krb5 authentication failed\n");
1589 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1590 inc_rfc1001_len(work->response_buf, out_len - 1);
1592 if ((conn->sign || server_conf.enforced_signing) ||
1593 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1596 if (smb3_encryption_negotiated(conn)) {
1597 retval = conn->ops->generate_encryptionkey(conn, sess);
1600 "SMB3 encryption key generation failed\n");
1604 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1608 if (conn->dialect >= SMB30_PROT_ID) {
1609 read_lock(&sess->chann_lock);
1610 chann = lookup_chann_list(sess, conn);
1611 read_unlock(&sess->chann_lock);
1613 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1618 INIT_LIST_HEAD(&chann->chann_list);
1619 write_lock(&sess->chann_lock);
1620 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1621 write_unlock(&sess->chann_lock);
1625 if (conn->ops->generate_signingkey) {
1626 retval = conn->ops->generate_signingkey(sess, conn);
1628 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1633 if (!ksmbd_conn_lookup_dialect(conn)) {
1634 pr_err("fail to verify the dialect\n");
1640 static int krb5_authenticate(struct ksmbd_work *work)
1646 int smb2_sess_setup(struct ksmbd_work *work)
1648 struct ksmbd_conn *conn = work->conn;
1649 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1650 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1651 struct ksmbd_session *sess;
1652 struct negotiate_message *negblob;
1653 unsigned int negblob_len, negblob_off;
1656 ksmbd_debug(SMB, "Received request for session setup\n");
1658 rsp->StructureSize = cpu_to_le16(9);
1659 rsp->SessionFlags = 0;
1660 rsp->SecurityBufferOffset = cpu_to_le16(72);
1661 rsp->SecurityBufferLength = 0;
1662 inc_rfc1001_len(work->response_buf, 9);
1664 if (!req->hdr.SessionId) {
1665 sess = ksmbd_smb2_session_create();
1670 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1671 rc = ksmbd_session_register(conn, sess);
1674 } else if (conn->dialect >= SMB30_PROT_ID &&
1675 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1676 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1677 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1679 sess = ksmbd_session_lookup_slowpath(sess_id);
1685 if (conn->dialect != sess->dialect) {
1690 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1695 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1696 SMB2_CLIENT_GUID_SIZE)) {
1701 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1706 if (sess->state == SMB2_SESSION_EXPIRED) {
1711 if (ksmbd_session_lookup(conn, sess_id)) {
1716 conn->binding = true;
1717 } else if ((conn->dialect < SMB30_PROT_ID ||
1718 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1719 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1724 sess = ksmbd_session_lookup(conn,
1725 le64_to_cpu(req->hdr.SessionId));
1733 if (sess->state == SMB2_SESSION_EXPIRED)
1734 sess->state = SMB2_SESSION_IN_PROGRESS;
1736 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1737 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1738 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1739 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1744 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1747 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1748 if (conn->mechToken)
1749 negblob = (struct negotiate_message *)conn->mechToken;
1752 if (server_conf.auth_mechs & conn->auth_mechs) {
1753 rc = generate_preauth_hash(work);
1757 if (conn->preferred_auth_mech &
1758 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1759 rc = krb5_authenticate(work);
1765 ksmbd_conn_set_good(work);
1766 sess->state = SMB2_SESSION_VALID;
1767 kfree(sess->Preauth_HashValue);
1768 sess->Preauth_HashValue = NULL;
1769 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1770 if (negblob->MessageType == NtLmNegotiate) {
1771 rc = ntlm_negotiate(work, negblob, negblob_len);
1775 STATUS_MORE_PROCESSING_REQUIRED;
1777 * Note: here total size -1 is done as an
1778 * adjustment for 0 size blob
1780 inc_rfc1001_len(work->response_buf,
1781 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1783 } else if (negblob->MessageType == NtLmAuthenticate) {
1784 rc = ntlm_authenticate(work);
1788 ksmbd_conn_set_good(work);
1789 sess->state = SMB2_SESSION_VALID;
1790 if (conn->binding) {
1791 struct preauth_session *preauth_sess;
1794 ksmbd_preauth_session_lookup(conn, sess->id);
1796 list_del(&preauth_sess->preauth_entry);
1797 kfree(preauth_sess);
1800 kfree(sess->Preauth_HashValue);
1801 sess->Preauth_HashValue = NULL;
1803 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1804 le32_to_cpu(negblob->MessageType));
1808 /* TODO: need one more negotiation */
1809 pr_err("Not support the preferred authentication\n");
1813 pr_err("Not support authentication\n");
1819 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1820 else if (rc == -ENOENT)
1821 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1822 else if (rc == -EACCES)
1823 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1824 else if (rc == -EFAULT)
1825 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1826 else if (rc == -ENOMEM)
1827 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1829 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1831 if (conn->use_spnego && conn->mechToken) {
1832 kfree(conn->mechToken);
1833 conn->mechToken = NULL;
1838 * SecurityBufferOffset should be set to zero
1839 * in session setup error response.
1841 rsp->SecurityBufferOffset = 0;
1844 bool try_delay = false;
1847 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1848 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1849 * failure to make it harder to send enough random connection requests
1850 * to break into a server.
1852 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1855 xa_erase(&conn->sessions, sess->id);
1856 ksmbd_session_destroy(sess);
1867 * smb2_tree_connect() - handler for smb2 tree connect command
1868 * @work: smb work containing smb request buffer
1870 * Return: 0 on success, otherwise error
1872 int smb2_tree_connect(struct ksmbd_work *work)
1874 struct ksmbd_conn *conn = work->conn;
1875 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1876 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1877 struct ksmbd_session *sess = work->sess;
1878 char *treename = NULL, *name = NULL;
1879 struct ksmbd_tree_conn_status status;
1880 struct ksmbd_share_config *share;
1883 treename = smb_strndup_from_utf16(req->Buffer,
1884 le16_to_cpu(req->PathLength), true,
1886 if (IS_ERR(treename)) {
1887 pr_err("treename is NULL\n");
1888 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1892 name = ksmbd_extract_sharename(conn->um, treename);
1894 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1898 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1901 status = ksmbd_tree_conn_connect(conn, sess, name);
1902 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1903 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1907 share = status.tree_conn->share_conf;
1908 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1909 ksmbd_debug(SMB, "IPC share path request\n");
1910 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1911 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1912 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1913 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1914 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1915 FILE_SYNCHRONIZE_LE;
1917 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1918 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1919 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1920 if (test_tree_conn_flag(status.tree_conn,
1921 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1922 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1923 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1924 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1925 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1926 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1927 FILE_SYNCHRONIZE_LE;
1931 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1932 if (conn->posix_ext_supported)
1933 status.tree_conn->posix_extensions = true;
1935 rsp->StructureSize = cpu_to_le16(16);
1936 inc_rfc1001_len(work->response_buf, 16);
1938 rsp->Capabilities = 0;
1940 /* default manual caching */
1941 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1943 if (!IS_ERR(treename))
1948 switch (status.ret) {
1949 case KSMBD_TREE_CONN_STATUS_OK:
1950 rsp->hdr.Status = STATUS_SUCCESS;
1955 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1956 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
1959 case KSMBD_TREE_CONN_STATUS_NOMEM:
1960 rsp->hdr.Status = STATUS_NO_MEMORY;
1962 case KSMBD_TREE_CONN_STATUS_ERROR:
1963 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1964 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1965 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1968 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1971 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1974 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
1975 smb2_set_err_rsp(work);
1981 * smb2_create_open_flags() - convert smb open flags to unix open flags
1982 * @file_present: is file already present
1983 * @access: file access flags
1984 * @disposition: file disposition flags
1985 * @may_flags: set with MAY_ flags
1987 * Return: file open flags
1989 static int smb2_create_open_flags(bool file_present, __le32 access,
1993 int oflags = O_NONBLOCK | O_LARGEFILE;
1995 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1996 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1998 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1999 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2001 *may_flags = MAY_OPEN | MAY_WRITE;
2004 *may_flags = MAY_OPEN | MAY_READ;
2007 if (access == FILE_READ_ATTRIBUTES_LE)
2011 switch (disposition & FILE_CREATE_MASK_LE) {
2013 case FILE_CREATE_LE:
2015 case FILE_SUPERSEDE_LE:
2016 case FILE_OVERWRITE_LE:
2017 case FILE_OVERWRITE_IF_LE:
2024 switch (disposition & FILE_CREATE_MASK_LE) {
2025 case FILE_SUPERSEDE_LE:
2026 case FILE_CREATE_LE:
2027 case FILE_OPEN_IF_LE:
2028 case FILE_OVERWRITE_IF_LE:
2032 case FILE_OVERWRITE_LE:
2044 * smb2_tree_disconnect() - handler for smb tree connect request
2045 * @work: smb work containing request buffer
2049 int smb2_tree_disconnect(struct ksmbd_work *work)
2051 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2052 struct ksmbd_session *sess = work->sess;
2053 struct ksmbd_tree_connect *tcon = work->tcon;
2055 rsp->StructureSize = cpu_to_le16(4);
2056 inc_rfc1001_len(work->response_buf, 4);
2058 ksmbd_debug(SMB, "request\n");
2060 if (!tcon || test_and_set_bit(TREE_CONN_EXPIRE, &tcon->status)) {
2061 struct smb2_tree_disconnect_req *req =
2062 smb2_get_msg(work->request_buf);
2064 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2066 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2067 smb2_set_err_rsp(work);
2071 ksmbd_close_tree_conn_fds(work);
2072 ksmbd_tree_conn_disconnect(sess, tcon);
2078 * smb2_session_logoff() - handler for session log off request
2079 * @work: smb work containing request buffer
2083 int smb2_session_logoff(struct ksmbd_work *work)
2085 struct ksmbd_conn *conn = work->conn;
2086 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2087 struct ksmbd_session *sess = work->sess;
2089 rsp->StructureSize = cpu_to_le16(4);
2090 inc_rfc1001_len(work->response_buf, 4);
2092 ksmbd_debug(SMB, "request\n");
2094 /* setting CifsExiting here may race with start_tcp_sess */
2095 ksmbd_conn_set_need_reconnect(work);
2096 ksmbd_close_session_fds(work);
2097 ksmbd_conn_wait_idle(conn);
2099 if (ksmbd_tree_conn_session_logoff(sess)) {
2100 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2102 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2103 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2104 smb2_set_err_rsp(work);
2108 ksmbd_destroy_file_table(&sess->file_table);
2109 sess->state = SMB2_SESSION_EXPIRED;
2111 ksmbd_free_user(sess->user);
2114 /* let start_tcp_sess free connection info now */
2115 ksmbd_conn_set_need_negotiate(work);
2120 * create_smb2_pipe() - create IPC pipe
2121 * @work: smb work containing request buffer
2123 * Return: 0 on success, otherwise error
2125 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2127 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2128 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2133 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2134 1, work->conn->local_nls);
2136 rsp->hdr.Status = STATUS_NO_MEMORY;
2137 err = PTR_ERR(name);
2141 id = ksmbd_session_rpc_open(work->sess, name);
2143 pr_err("Unable to open RPC pipe: %d\n", id);
2148 rsp->hdr.Status = STATUS_SUCCESS;
2149 rsp->StructureSize = cpu_to_le16(89);
2150 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2152 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2154 rsp->CreationTime = cpu_to_le64(0);
2155 rsp->LastAccessTime = cpu_to_le64(0);
2156 rsp->ChangeTime = cpu_to_le64(0);
2157 rsp->AllocationSize = cpu_to_le64(0);
2158 rsp->EndofFile = cpu_to_le64(0);
2159 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2161 rsp->VolatileFileId = id;
2162 rsp->PersistentFileId = 0;
2163 rsp->CreateContextsOffset = 0;
2164 rsp->CreateContextsLength = 0;
2166 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2173 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2177 rsp->hdr.Status = STATUS_NO_MEMORY;
2184 smb2_set_err_rsp(work);
2189 * smb2_set_ea() - handler for setting extended attributes using set
2191 * @eabuf: set info command buffer
2192 * @buf_len: set info command buffer length
2193 * @path: dentry path for get ea
2195 * Return: 0 on success, otherwise error
2197 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2198 const struct path *path)
2200 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2201 char *attr_name = NULL, *value;
2203 unsigned int next = 0;
2205 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2206 le16_to_cpu(eabuf->EaValueLength))
2209 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2214 if (!eabuf->EaNameLength)
2218 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2219 eabuf->name, eabuf->EaNameLength,
2220 le16_to_cpu(eabuf->EaValueLength),
2221 le32_to_cpu(eabuf->NextEntryOffset));
2223 if (eabuf->EaNameLength >
2224 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2229 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2230 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2231 eabuf->EaNameLength);
2232 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2233 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2235 if (!eabuf->EaValueLength) {
2236 rc = ksmbd_vfs_casexattr_len(user_ns,
2239 XATTR_USER_PREFIX_LEN +
2240 eabuf->EaNameLength);
2242 /* delete the EA only when it exits */
2244 rc = ksmbd_vfs_remove_xattr(user_ns,
2250 "remove xattr failed(%d)\n",
2256 /* if the EA doesn't exist, just do nothing. */
2259 rc = ksmbd_vfs_setxattr(user_ns,
2260 path->dentry, attr_name, value,
2261 le16_to_cpu(eabuf->EaValueLength), 0);
2264 "ksmbd_vfs_setxattr is failed(%d)\n",
2271 next = le32_to_cpu(eabuf->NextEntryOffset);
2272 if (next == 0 || buf_len < next)
2275 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2276 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2279 } while (next != 0);
2285 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2286 struct ksmbd_file *fp,
2287 char *stream_name, int s_type)
2289 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2290 size_t xattr_stream_size;
2291 char *xattr_stream_name;
2294 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2301 fp->stream.name = xattr_stream_name;
2302 fp->stream.size = xattr_stream_size;
2304 /* Check if there is stream prefix in xattr space */
2305 rc = ksmbd_vfs_casexattr_len(user_ns,
2312 if (fp->cdoption == FILE_OPEN_LE) {
2313 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2317 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2318 xattr_stream_name, NULL, 0, 0);
2320 pr_err("Failed to store XATTR stream name :%d\n", rc);
2324 static int smb2_remove_smb_xattrs(const struct path *path)
2326 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2327 char *name, *xattr_list = NULL;
2328 ssize_t xattr_list_len;
2331 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2332 if (xattr_list_len < 0) {
2334 } else if (!xattr_list_len) {
2335 ksmbd_debug(SMB, "empty xattr in the file\n");
2339 for (name = xattr_list; name - xattr_list < xattr_list_len;
2340 name += strlen(name) + 1) {
2341 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2343 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2344 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2345 STREAM_PREFIX_LEN)) {
2346 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry,
2349 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2358 static int smb2_create_truncate(const struct path *path)
2360 int rc = vfs_truncate(path, 0);
2363 pr_err("vfs_truncate failed, rc %d\n", rc);
2367 rc = smb2_remove_smb_xattrs(path);
2368 if (rc == -EOPNOTSUPP)
2372 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2377 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2378 struct ksmbd_file *fp)
2380 struct xattr_dos_attrib da = {0};
2383 if (!test_share_config_flag(tcon->share_conf,
2384 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2388 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2389 da.itime = da.create_time = fp->create_time;
2390 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2391 XATTR_DOSINFO_ITIME;
2393 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2396 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2399 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2400 const struct path *path, struct ksmbd_file *fp)
2402 struct xattr_dos_attrib da;
2405 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2407 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2408 if (!test_share_config_flag(tcon->share_conf,
2409 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2412 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2415 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2416 fp->create_time = da.create_time;
2417 fp->itime = da.itime;
2421 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2422 int open_flags, umode_t posix_mode, bool is_dir)
2424 struct ksmbd_tree_connect *tcon = work->tcon;
2425 struct ksmbd_share_config *share = tcon->share_conf;
2429 if (!(open_flags & O_CREAT))
2432 ksmbd_debug(SMB, "file does not exist, so creating\n");
2433 if (is_dir == true) {
2434 ksmbd_debug(SMB, "creating directory\n");
2436 mode = share_config_directory_mode(share, posix_mode);
2437 rc = ksmbd_vfs_mkdir(work, name, mode);
2441 ksmbd_debug(SMB, "creating regular file\n");
2443 mode = share_config_create_mode(share, posix_mode);
2444 rc = ksmbd_vfs_create(work, name, mode);
2449 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2451 pr_err("cannot get linux path (%s), err = %d\n",
2458 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2459 struct smb2_create_req *req,
2460 const struct path *path)
2462 struct create_context *context;
2463 struct create_sd_buf_req *sd_buf;
2465 if (!req->CreateContextsOffset)
2468 /* Parse SD BUFFER create contexts */
2469 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2472 else if (IS_ERR(context))
2473 return PTR_ERR(context);
2476 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2477 sd_buf = (struct create_sd_buf_req *)context;
2478 if (le16_to_cpu(context->DataOffset) +
2479 le32_to_cpu(context->DataLength) <
2480 sizeof(struct create_sd_buf_req))
2482 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2483 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2486 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2487 struct user_namespace *mnt_userns,
2488 struct inode *inode)
2490 vfsuid_t vfsuid = i_uid_into_vfsuid(mnt_userns, inode);
2491 vfsgid_t vfsgid = i_gid_into_vfsgid(mnt_userns, inode);
2493 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2494 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2495 fattr->cf_mode = inode->i_mode;
2496 fattr->cf_acls = NULL;
2497 fattr->cf_dacls = NULL;
2499 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2500 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2501 if (S_ISDIR(inode->i_mode))
2502 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2507 * smb2_open() - handler for smb file open request
2508 * @work: smb work containing request buffer
2510 * Return: 0 on success, otherwise error
2512 int smb2_open(struct ksmbd_work *work)
2514 struct ksmbd_conn *conn = work->conn;
2515 struct ksmbd_session *sess = work->sess;
2516 struct ksmbd_tree_connect *tcon = work->tcon;
2517 struct smb2_create_req *req;
2518 struct smb2_create_rsp *rsp;
2520 struct ksmbd_share_config *share = tcon->share_conf;
2521 struct ksmbd_file *fp = NULL;
2522 struct file *filp = NULL;
2523 struct user_namespace *user_ns = NULL;
2525 struct create_context *context;
2526 struct lease_ctx_info *lc = NULL;
2527 struct create_ea_buf_req *ea_buf = NULL;
2528 struct oplock_info *opinfo;
2529 __le32 *next_ptr = NULL;
2530 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2532 int contxt_cnt = 0, query_disk_id = 0;
2533 int maximal_access_ctxt = 0, posix_ctxt = 0;
2537 char *stream_name = NULL;
2538 bool file_present = false, created = false, already_permitted = false;
2539 int share_ret, need_truncate = 0;
2541 umode_t posix_mode = 0;
2542 __le32 daccess, maximal_access = 0;
2544 WORK_BUFFERS(work, req, rsp);
2546 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2547 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2548 ksmbd_debug(SMB, "invalid flag in chained command\n");
2549 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2550 smb2_set_err_rsp(work);
2554 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2555 ksmbd_debug(SMB, "IPC pipe create request\n");
2556 return create_smb2_pipe(work);
2559 if (req->NameLength) {
2560 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2561 *(char *)req->Buffer == '\\') {
2562 pr_err("not allow directory name included leading slash\n");
2567 name = smb2_get_name(req->Buffer,
2568 le16_to_cpu(req->NameLength),
2569 work->conn->local_nls);
2578 ksmbd_debug(SMB, "converted name = %s\n", name);
2579 if (strchr(name, ':')) {
2580 if (!test_share_config_flag(work->tcon->share_conf,
2581 KSMBD_SHARE_FLAG_STREAMS)) {
2585 rc = parse_stream_name(name, &stream_name, &s_type);
2590 rc = ksmbd_validate_filename(name);
2594 if (ksmbd_share_veto_filename(share, name)) {
2596 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2601 name = kstrdup("", GFP_KERNEL);
2608 req_op_level = req->RequestedOplockLevel;
2609 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2610 lc = parse_lease_state(req);
2612 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2613 pr_err("Invalid impersonationlevel : 0x%x\n",
2614 le32_to_cpu(req->ImpersonationLevel));
2616 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2620 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2621 pr_err("Invalid create options : 0x%x\n",
2622 le32_to_cpu(req->CreateOptions));
2626 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2627 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2628 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2630 if (req->CreateOptions &
2631 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2632 FILE_RESERVE_OPFILTER_LE)) {
2637 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2638 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2641 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2642 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2647 if (le32_to_cpu(req->CreateDisposition) >
2648 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2649 pr_err("Invalid create disposition : 0x%x\n",
2650 le32_to_cpu(req->CreateDisposition));
2655 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2656 pr_err("Invalid desired access : 0x%x\n",
2657 le32_to_cpu(req->DesiredAccess));
2662 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2663 pr_err("Invalid file attribute : 0x%x\n",
2664 le32_to_cpu(req->FileAttributes));
2669 if (req->CreateContextsOffset) {
2670 /* Parse non-durable handle create contexts */
2671 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2672 if (IS_ERR(context)) {
2673 rc = PTR_ERR(context);
2675 } else if (context) {
2676 ea_buf = (struct create_ea_buf_req *)context;
2677 if (le16_to_cpu(context->DataOffset) +
2678 le32_to_cpu(context->DataLength) <
2679 sizeof(struct create_ea_buf_req)) {
2683 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2684 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2690 context = smb2_find_context_vals(req,
2691 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2692 if (IS_ERR(context)) {
2693 rc = PTR_ERR(context);
2695 } else if (context) {
2697 "get query maximal access context\n");
2698 maximal_access_ctxt = 1;
2701 context = smb2_find_context_vals(req,
2702 SMB2_CREATE_TIMEWARP_REQUEST);
2703 if (IS_ERR(context)) {
2704 rc = PTR_ERR(context);
2706 } else if (context) {
2707 ksmbd_debug(SMB, "get timewarp context\n");
2712 if (tcon->posix_extensions) {
2713 context = smb2_find_context_vals(req,
2714 SMB2_CREATE_TAG_POSIX);
2715 if (IS_ERR(context)) {
2716 rc = PTR_ERR(context);
2718 } else if (context) {
2719 struct create_posix *posix =
2720 (struct create_posix *)context;
2721 if (le16_to_cpu(context->DataOffset) +
2722 le32_to_cpu(context->DataLength) <
2723 sizeof(struct create_posix) - 4) {
2727 ksmbd_debug(SMB, "get posix context\n");
2729 posix_mode = le32_to_cpu(posix->Mode);
2735 if (ksmbd_override_fsids(work)) {
2740 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2742 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2744 * If file exists with under flags, return access
2747 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2748 req->CreateDisposition == FILE_OPEN_IF_LE) {
2754 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2756 "User does not have write permission\n");
2761 } else if (d_is_symlink(path.dentry)) {
2771 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2775 file_present = true;
2776 user_ns = mnt_user_ns(path.mnt);
2779 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2780 if (s_type == DATA_STREAM) {
2782 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2785 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2786 s_type == DATA_STREAM) {
2788 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2792 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2793 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2794 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2802 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2803 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2804 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2805 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2806 name, req->CreateOptions);
2807 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2812 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2813 !(req->CreateDisposition == FILE_CREATE_LE) &&
2814 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2815 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2820 if (!stream_name && file_present &&
2821 req->CreateDisposition == FILE_CREATE_LE) {
2826 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2828 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2829 rc = smb_check_perm_dacl(conn, &path, &daccess,
2835 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2836 if (!file_present) {
2837 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2839 rc = ksmbd_vfs_query_maximal_access(user_ns,
2844 already_permitted = true;
2846 maximal_access = daccess;
2849 open_flags = smb2_create_open_flags(file_present, daccess,
2850 req->CreateDisposition,
2853 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2854 if (open_flags & O_CREAT) {
2856 "User does not have write permission\n");
2862 /*create file if not present */
2863 if (!file_present) {
2864 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2865 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2867 if (rc == -ENOENT) {
2869 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2875 user_ns = mnt_user_ns(path.mnt);
2877 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2878 sizeof(struct smb2_ea_info)) {
2883 rc = smb2_set_ea(&ea_buf->ea,
2884 le32_to_cpu(ea_buf->ccontext.DataLength),
2886 if (rc == -EOPNOTSUPP)
2891 } else if (!already_permitted) {
2892 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2893 * because execute(search) permission on a parent directory,
2894 * is already granted.
2896 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2897 rc = inode_permission(user_ns,
2898 d_inode(path.dentry),
2903 if ((daccess & FILE_DELETE_LE) ||
2904 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2905 rc = ksmbd_vfs_may_delete(user_ns,
2913 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2914 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2920 filp = dentry_open(&path, open_flags, current_cred());
2923 pr_err("dentry open for dir failed, rc %d\n", rc);
2928 if (!(open_flags & O_TRUNC))
2929 file_info = FILE_OPENED;
2931 file_info = FILE_OVERWRITTEN;
2933 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2935 file_info = FILE_SUPERSEDED;
2936 } else if (open_flags & O_CREAT) {
2937 file_info = FILE_CREATED;
2940 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2942 /* Obtain Volatile-ID */
2943 fp = ksmbd_open_fd(work, filp);
2951 /* Get Persistent-ID */
2952 ksmbd_open_durable_fd(fp);
2953 if (!has_file_id(fp->persistent_id)) {
2958 fp->cdoption = req->CreateDisposition;
2959 fp->daccess = daccess;
2960 fp->saccess = req->ShareAccess;
2961 fp->coption = req->CreateOptions;
2963 /* Set default windows and posix acls if creating new file */
2966 struct inode *inode = d_inode(path.dentry);
2968 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2970 d_inode(path.dentry->d_parent));
2972 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2974 if (test_share_config_flag(work->tcon->share_conf,
2975 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2976 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2981 rc = smb2_create_sd_buffer(work, req, &path);
2984 ksmbd_vfs_set_init_posix_acl(user_ns,
2987 if (test_share_config_flag(work->tcon->share_conf,
2988 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2989 struct smb_fattr fattr;
2990 struct smb_ntsd *pntsd;
2991 int pntsd_size, ace_num = 0;
2993 ksmbd_acls_fattr(&fattr, user_ns, inode);
2995 ace_num = fattr.cf_acls->a_count;
2997 ace_num += fattr.cf_dacls->a_count;
2999 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3000 sizeof(struct smb_sid) * 3 +
3001 sizeof(struct smb_acl) +
3002 sizeof(struct smb_ace) * ace_num * 2,
3005 posix_acl_release(fattr.cf_acls);
3006 posix_acl_release(fattr.cf_dacls);
3010 rc = build_sec_desc(user_ns,
3015 &pntsd_size, &fattr);
3016 posix_acl_release(fattr.cf_acls);
3017 posix_acl_release(fattr.cf_dacls);
3023 rc = ksmbd_vfs_set_sd_xattr(conn,
3030 pr_err("failed to store ntacl in xattr : %d\n",
3039 rc = smb2_set_stream_name_xattr(&path,
3045 file_info = FILE_CREATED;
3048 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3049 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3050 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3051 !fp->attrib_only && !stream_name) {
3052 smb_break_all_oplock(work, fp);
3056 /* fp should be searchable through ksmbd_inode.m_fp_list
3057 * after daccess, saccess, attrib_only, and stream are
3060 write_lock(&fp->f_ci->m_lock);
3061 list_add(&fp->node, &fp->f_ci->m_fp_list);
3062 write_unlock(&fp->f_ci->m_lock);
3064 /* Check delete pending among previous fp before oplock break */
3065 if (ksmbd_inode_pending_delete(fp)) {
3070 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3071 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3072 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3073 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3074 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3079 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3080 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3082 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3083 name, req_op_level, lc->req_state);
3084 rc = find_same_lease_key(sess, fp->f_ci, lc);
3087 } else if (open_flags == O_RDONLY &&
3088 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3089 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3090 req_op_level = SMB2_OPLOCK_LEVEL_II;
3092 rc = smb_grant_oplock(work, req_op_level,
3093 fp->persistent_id, fp,
3094 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3100 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3101 ksmbd_fd_set_delete_on_close(fp, file_info);
3103 if (need_truncate) {
3104 rc = smb2_create_truncate(&path);
3109 if (req->CreateContextsOffset) {
3110 struct create_alloc_size_req *az_req;
3112 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3113 SMB2_CREATE_ALLOCATION_SIZE);
3114 if (IS_ERR(az_req)) {
3115 rc = PTR_ERR(az_req);
3117 } else if (az_req) {
3121 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3122 le32_to_cpu(az_req->ccontext.DataLength) <
3123 sizeof(struct create_alloc_size_req)) {
3127 alloc_size = le64_to_cpu(az_req->AllocationSize);
3129 "request smb2 create allocate size : %llu\n",
3131 smb_break_all_levII_oplock(work, fp, 1);
3132 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3136 "vfs_fallocate is failed : %d\n",
3140 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3141 if (IS_ERR(context)) {
3142 rc = PTR_ERR(context);
3144 } else if (context) {
3145 ksmbd_debug(SMB, "get query on disk id context\n");
3150 rc = ksmbd_vfs_getattr(&path, &stat);
3154 if (stat.result_mask & STATX_BTIME)
3155 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3157 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3158 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3160 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3163 smb2_update_xattrs(tcon, &path, fp);
3165 smb2_new_xattrs(tcon, &path, fp);
3167 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3169 rsp->StructureSize = cpu_to_le16(89);
3171 opinfo = rcu_dereference(fp->f_opinfo);
3172 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3175 rsp->CreateAction = cpu_to_le32(file_info);
3176 rsp->CreationTime = cpu_to_le64(fp->create_time);
3177 time = ksmbd_UnixTimeToNT(stat.atime);
3178 rsp->LastAccessTime = cpu_to_le64(time);
3179 time = ksmbd_UnixTimeToNT(stat.mtime);
3180 rsp->LastWriteTime = cpu_to_le64(time);
3181 time = ksmbd_UnixTimeToNT(stat.ctime);
3182 rsp->ChangeTime = cpu_to_le64(time);
3183 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3184 cpu_to_le64(stat.blocks << 9);
3185 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3186 rsp->FileAttributes = fp->f_ci->m_fattr;
3190 rsp->PersistentFileId = fp->persistent_id;
3191 rsp->VolatileFileId = fp->volatile_id;
3193 rsp->CreateContextsOffset = 0;
3194 rsp->CreateContextsLength = 0;
3195 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3197 /* If lease is request send lease context response */
3198 if (opinfo && opinfo->is_lease) {
3199 struct create_context *lease_ccontext;
3201 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3202 name, opinfo->o_lease->state);
3203 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3205 lease_ccontext = (struct create_context *)rsp->Buffer;
3207 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3208 le32_add_cpu(&rsp->CreateContextsLength,
3209 conn->vals->create_lease_size);
3210 inc_rfc1001_len(work->response_buf,
3211 conn->vals->create_lease_size);
3212 next_ptr = &lease_ccontext->Next;
3213 next_off = conn->vals->create_lease_size;
3216 if (maximal_access_ctxt) {
3217 struct create_context *mxac_ccontext;
3219 if (maximal_access == 0)
3220 ksmbd_vfs_query_maximal_access(user_ns,
3223 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3224 le32_to_cpu(rsp->CreateContextsLength));
3226 create_mxac_rsp_buf(rsp->Buffer +
3227 le32_to_cpu(rsp->CreateContextsLength),
3228 le32_to_cpu(maximal_access));
3229 le32_add_cpu(&rsp->CreateContextsLength,
3230 conn->vals->create_mxac_size);
3231 inc_rfc1001_len(work->response_buf,
3232 conn->vals->create_mxac_size);
3234 *next_ptr = cpu_to_le32(next_off);
3235 next_ptr = &mxac_ccontext->Next;
3236 next_off = conn->vals->create_mxac_size;
3239 if (query_disk_id) {
3240 struct create_context *disk_id_ccontext;
3242 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3243 le32_to_cpu(rsp->CreateContextsLength));
3245 create_disk_id_rsp_buf(rsp->Buffer +
3246 le32_to_cpu(rsp->CreateContextsLength),
3247 stat.ino, tcon->id);
3248 le32_add_cpu(&rsp->CreateContextsLength,
3249 conn->vals->create_disk_id_size);
3250 inc_rfc1001_len(work->response_buf,
3251 conn->vals->create_disk_id_size);
3253 *next_ptr = cpu_to_le32(next_off);
3254 next_ptr = &disk_id_ccontext->Next;
3255 next_off = conn->vals->create_disk_id_size;
3260 create_posix_rsp_buf(rsp->Buffer +
3261 le32_to_cpu(rsp->CreateContextsLength),
3263 le32_add_cpu(&rsp->CreateContextsLength,
3264 conn->vals->create_posix_size);
3265 inc_rfc1001_len(work->response_buf,
3266 conn->vals->create_posix_size);
3268 *next_ptr = cpu_to_le32(next_off);
3271 if (contxt_cnt > 0) {
3272 rsp->CreateContextsOffset =
3273 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3277 if (file_present || created)
3279 ksmbd_revert_fsids(work);
3283 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3284 else if (rc == -EOPNOTSUPP)
3285 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3286 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3287 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3288 else if (rc == -ENOENT)
3289 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3290 else if (rc == -EPERM)
3291 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3292 else if (rc == -EBUSY)
3293 rsp->hdr.Status = STATUS_DELETE_PENDING;
3294 else if (rc == -EBADF)
3295 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3296 else if (rc == -ENOEXEC)
3297 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3298 else if (rc == -ENXIO)
3299 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3300 else if (rc == -EEXIST)
3301 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3302 else if (rc == -EMFILE)
3303 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3304 if (!rsp->hdr.Status)
3305 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3308 ksmbd_fd_put(work, fp);
3309 smb2_set_err_rsp(work);
3310 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3319 static int readdir_info_level_struct_sz(int info_level)
3321 switch (info_level) {
3322 case FILE_FULL_DIRECTORY_INFORMATION:
3323 return sizeof(struct file_full_directory_info);
3324 case FILE_BOTH_DIRECTORY_INFORMATION:
3325 return sizeof(struct file_both_directory_info);
3326 case FILE_DIRECTORY_INFORMATION:
3327 return sizeof(struct file_directory_info);
3328 case FILE_NAMES_INFORMATION:
3329 return sizeof(struct file_names_info);
3330 case FILEID_FULL_DIRECTORY_INFORMATION:
3331 return sizeof(struct file_id_full_dir_info);
3332 case FILEID_BOTH_DIRECTORY_INFORMATION:
3333 return sizeof(struct file_id_both_directory_info);
3334 case SMB_FIND_FILE_POSIX_INFO:
3335 return sizeof(struct smb2_posix_info);
3341 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3343 switch (info_level) {
3344 case FILE_FULL_DIRECTORY_INFORMATION:
3346 struct file_full_directory_info *ffdinfo;
3348 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3349 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3350 d_info->name = ffdinfo->FileName;
3351 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3354 case FILE_BOTH_DIRECTORY_INFORMATION:
3356 struct file_both_directory_info *fbdinfo;
3358 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3359 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3360 d_info->name = fbdinfo->FileName;
3361 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3364 case FILE_DIRECTORY_INFORMATION:
3366 struct file_directory_info *fdinfo;
3368 fdinfo = (struct file_directory_info *)d_info->rptr;
3369 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3370 d_info->name = fdinfo->FileName;
3371 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3374 case FILE_NAMES_INFORMATION:
3376 struct file_names_info *fninfo;
3378 fninfo = (struct file_names_info *)d_info->rptr;
3379 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3380 d_info->name = fninfo->FileName;
3381 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3384 case FILEID_FULL_DIRECTORY_INFORMATION:
3386 struct file_id_full_dir_info *dinfo;
3388 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3389 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3390 d_info->name = dinfo->FileName;
3391 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3394 case FILEID_BOTH_DIRECTORY_INFORMATION:
3396 struct file_id_both_directory_info *fibdinfo;
3398 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3399 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3400 d_info->name = fibdinfo->FileName;
3401 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3404 case SMB_FIND_FILE_POSIX_INFO:
3406 struct smb2_posix_info *posix_info;
3408 posix_info = (struct smb2_posix_info *)d_info->rptr;
3409 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3410 d_info->name = posix_info->name;
3411 d_info->name_len = le32_to_cpu(posix_info->name_len);
3420 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3422 * @conn: connection instance
3423 * @info_level: smb information level
3424 * @d_info: structure included variables for query dir
3425 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3427 * if directory has many entries, find first can't read it fully.
3428 * find next might be called multiple times to read remaining dir entries
3430 * Return: 0 on success, otherwise error
3432 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3433 struct ksmbd_dir_info *d_info,
3434 struct ksmbd_kstat *ksmbd_kstat)
3436 int next_entry_offset = 0;
3440 int struct_sz, rc = 0;
3442 conv_name = ksmbd_convert_dir_info_name(d_info,
3448 /* Somehow the name has only terminating NULL bytes */
3451 goto free_conv_name;
3454 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3455 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3456 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3458 if (next_entry_offset > d_info->out_buf_len) {
3459 d_info->out_buf_len = 0;
3461 goto free_conv_name;
3464 kstat = d_info->wptr;
3465 if (info_level != FILE_NAMES_INFORMATION)
3466 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3468 switch (info_level) {
3469 case FILE_FULL_DIRECTORY_INFORMATION:
3471 struct file_full_directory_info *ffdinfo;
3473 ffdinfo = (struct file_full_directory_info *)kstat;
3474 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3476 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3477 if (ffdinfo->EaSize)
3478 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3479 if (d_info->hide_dot_file && d_info->name[0] == '.')
3480 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3481 memcpy(ffdinfo->FileName, conv_name, conv_len);
3482 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3485 case FILE_BOTH_DIRECTORY_INFORMATION:
3487 struct file_both_directory_info *fbdinfo;
3489 fbdinfo = (struct file_both_directory_info *)kstat;
3490 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3492 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3493 if (fbdinfo->EaSize)
3494 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3495 fbdinfo->ShortNameLength = 0;
3496 fbdinfo->Reserved = 0;
3497 if (d_info->hide_dot_file && d_info->name[0] == '.')
3498 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3499 memcpy(fbdinfo->FileName, conv_name, conv_len);
3500 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3503 case FILE_DIRECTORY_INFORMATION:
3505 struct file_directory_info *fdinfo;
3507 fdinfo = (struct file_directory_info *)kstat;
3508 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3509 if (d_info->hide_dot_file && d_info->name[0] == '.')
3510 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3511 memcpy(fdinfo->FileName, conv_name, conv_len);
3512 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3515 case FILE_NAMES_INFORMATION:
3517 struct file_names_info *fninfo;
3519 fninfo = (struct file_names_info *)kstat;
3520 fninfo->FileNameLength = cpu_to_le32(conv_len);
3521 memcpy(fninfo->FileName, conv_name, conv_len);
3522 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3525 case FILEID_FULL_DIRECTORY_INFORMATION:
3527 struct file_id_full_dir_info *dinfo;
3529 dinfo = (struct file_id_full_dir_info *)kstat;
3530 dinfo->FileNameLength = cpu_to_le32(conv_len);
3532 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3534 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3535 dinfo->Reserved = 0;
3536 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3537 if (d_info->hide_dot_file && d_info->name[0] == '.')
3538 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3539 memcpy(dinfo->FileName, conv_name, conv_len);
3540 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3543 case FILEID_BOTH_DIRECTORY_INFORMATION:
3545 struct file_id_both_directory_info *fibdinfo;
3547 fibdinfo = (struct file_id_both_directory_info *)kstat;
3548 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3550 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3551 if (fibdinfo->EaSize)
3552 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3553 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3554 fibdinfo->ShortNameLength = 0;
3555 fibdinfo->Reserved = 0;
3556 fibdinfo->Reserved2 = cpu_to_le16(0);
3557 if (d_info->hide_dot_file && d_info->name[0] == '.')
3558 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3559 memcpy(fibdinfo->FileName, conv_name, conv_len);
3560 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3563 case SMB_FIND_FILE_POSIX_INFO:
3565 struct smb2_posix_info *posix_info;
3568 posix_info = (struct smb2_posix_info *)kstat;
3569 posix_info->Ignored = 0;
3570 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3571 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3572 posix_info->ChangeTime = cpu_to_le64(time);
3573 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3574 posix_info->LastAccessTime = cpu_to_le64(time);
3575 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3576 posix_info->LastWriteTime = cpu_to_le64(time);
3577 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3578 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3579 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3580 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3581 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3582 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3583 posix_info->DosAttributes =
3584 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3585 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3586 if (d_info->hide_dot_file && d_info->name[0] == '.')
3587 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3589 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3590 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3591 * sub_auth(4 * 1(num_subauth)) + RID(4).
3593 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3594 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3595 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3596 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3597 memcpy(posix_info->name, conv_name, conv_len);
3598 posix_info->name_len = cpu_to_le32(conv_len);
3599 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3603 } /* switch (info_level) */
3605 d_info->last_entry_offset = d_info->data_count;
3606 d_info->data_count += next_entry_offset;
3607 d_info->out_buf_len -= next_entry_offset;
3608 d_info->wptr += next_entry_offset;
3611 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3612 info_level, d_info->out_buf_len,
3613 next_entry_offset, d_info->data_count);
3620 struct smb2_query_dir_private {
3621 struct ksmbd_work *work;
3622 char *search_pattern;
3623 struct ksmbd_file *dir_fp;
3625 struct ksmbd_dir_info *d_info;
3629 static void lock_dir(struct ksmbd_file *dir_fp)
3631 struct dentry *dir = dir_fp->filp->f_path.dentry;
3633 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3636 static void unlock_dir(struct ksmbd_file *dir_fp)
3638 struct dentry *dir = dir_fp->filp->f_path.dentry;
3640 inode_unlock(d_inode(dir));
3643 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3645 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3647 struct ksmbd_kstat ksmbd_kstat;
3651 for (i = 0; i < priv->d_info->num_entry; i++) {
3652 struct dentry *dent;
3654 if (dentry_name(priv->d_info, priv->info_level))
3657 lock_dir(priv->dir_fp);
3658 dent = lookup_one(user_ns, priv->d_info->name,
3659 priv->dir_fp->filp->f_path.dentry,
3660 priv->d_info->name_len);
3661 unlock_dir(priv->dir_fp);
3664 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3669 if (unlikely(d_is_negative(dent))) {
3671 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3672 priv->d_info->name);
3676 ksmbd_kstat.kstat = &kstat;
3677 if (priv->info_level != FILE_NAMES_INFORMATION)
3678 ksmbd_vfs_fill_dentry_attrs(priv->work,
3683 rc = smb2_populate_readdir_entry(priv->work->conn,
3694 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3699 int next_entry_offset;
3701 struct_sz = readdir_info_level_struct_sz(info_level);
3702 if (struct_sz == -EOPNOTSUPP)
3705 conv_len = (d_info->name_len + 1) * 2;
3706 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3707 KSMBD_DIR_INFO_ALIGNMENT);
3709 if (next_entry_offset > d_info->out_buf_len) {
3710 d_info->out_buf_len = 0;
3714 switch (info_level) {
3715 case FILE_FULL_DIRECTORY_INFORMATION:
3717 struct file_full_directory_info *ffdinfo;
3719 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3720 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3721 ffdinfo->FileName[d_info->name_len] = 0x00;
3722 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3723 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3726 case FILE_BOTH_DIRECTORY_INFORMATION:
3728 struct file_both_directory_info *fbdinfo;
3730 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3731 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3732 fbdinfo->FileName[d_info->name_len] = 0x00;
3733 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3734 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3737 case FILE_DIRECTORY_INFORMATION:
3739 struct file_directory_info *fdinfo;
3741 fdinfo = (struct file_directory_info *)d_info->wptr;
3742 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3743 fdinfo->FileName[d_info->name_len] = 0x00;
3744 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3745 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3748 case FILE_NAMES_INFORMATION:
3750 struct file_names_info *fninfo;
3752 fninfo = (struct file_names_info *)d_info->wptr;
3753 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3754 fninfo->FileName[d_info->name_len] = 0x00;
3755 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3756 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3759 case FILEID_FULL_DIRECTORY_INFORMATION:
3761 struct file_id_full_dir_info *dinfo;
3763 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3764 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3765 dinfo->FileName[d_info->name_len] = 0x00;
3766 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3767 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3770 case FILEID_BOTH_DIRECTORY_INFORMATION:
3772 struct file_id_both_directory_info *fibdinfo;
3774 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3775 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3776 fibdinfo->FileName[d_info->name_len] = 0x00;
3777 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3778 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3781 case SMB_FIND_FILE_POSIX_INFO:
3783 struct smb2_posix_info *posix_info;
3785 posix_info = (struct smb2_posix_info *)d_info->wptr;
3786 memcpy(posix_info->name, d_info->name, d_info->name_len);
3787 posix_info->name[d_info->name_len] = 0x00;
3788 posix_info->name_len = cpu_to_le32(d_info->name_len);
3789 posix_info->NextEntryOffset =
3790 cpu_to_le32(next_entry_offset);
3793 } /* switch (info_level) */
3795 d_info->num_entry++;
3796 d_info->out_buf_len -= next_entry_offset;
3797 d_info->wptr += next_entry_offset;
3801 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3802 loff_t offset, u64 ino, unsigned int d_type)
3804 struct ksmbd_readdir_data *buf;
3805 struct smb2_query_dir_private *priv;
3806 struct ksmbd_dir_info *d_info;
3809 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3810 priv = buf->private;
3811 d_info = priv->d_info;
3813 /* dot and dotdot entries are already reserved */
3814 if (!strcmp(".", name) || !strcmp("..", name))
3816 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3818 if (!match_pattern(name, namlen, priv->search_pattern))
3821 d_info->name = name;
3822 d_info->name_len = namlen;
3823 rc = reserve_populate_dentry(d_info, priv->info_level);
3826 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3827 d_info->out_buf_len = 0;
3831 static int verify_info_level(int info_level)
3833 switch (info_level) {
3834 case FILE_FULL_DIRECTORY_INFORMATION:
3835 case FILE_BOTH_DIRECTORY_INFORMATION:
3836 case FILE_DIRECTORY_INFORMATION:
3837 case FILE_NAMES_INFORMATION:
3838 case FILEID_FULL_DIRECTORY_INFORMATION:
3839 case FILEID_BOTH_DIRECTORY_INFORMATION:
3840 case SMB_FIND_FILE_POSIX_INFO:
3849 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3853 free_len = (int)(work->response_sz -
3854 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3858 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3859 unsigned short hdr2_len,
3860 unsigned int out_buf_len)
3864 if (out_buf_len > work->conn->vals->max_trans_size)
3867 free_len = smb2_resp_buf_len(work, hdr2_len);
3871 return min_t(int, out_buf_len, free_len);
3874 int smb2_query_dir(struct ksmbd_work *work)
3876 struct ksmbd_conn *conn = work->conn;
3877 struct smb2_query_directory_req *req;
3878 struct smb2_query_directory_rsp *rsp;
3879 struct ksmbd_share_config *share = work->tcon->share_conf;
3880 struct ksmbd_file *dir_fp = NULL;
3881 struct ksmbd_dir_info d_info;
3883 char *srch_ptr = NULL;
3884 unsigned char srch_flag;
3886 struct smb2_query_dir_private query_dir_private = {NULL, };
3888 WORK_BUFFERS(work, req, rsp);
3890 if (ksmbd_override_fsids(work)) {
3891 rsp->hdr.Status = STATUS_NO_MEMORY;
3892 smb2_set_err_rsp(work);
3896 rc = verify_info_level(req->FileInformationClass);
3902 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3908 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3909 inode_permission(file_mnt_user_ns(dir_fp->filp),
3910 file_inode(dir_fp->filp),
3911 MAY_READ | MAY_EXEC)) {
3912 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
3917 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3918 pr_err("can't do query dir for a file\n");
3923 srch_flag = req->Flags;
3924 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3925 le16_to_cpu(req->FileNameLength), 1,
3927 if (IS_ERR(srch_ptr)) {
3928 ksmbd_debug(SMB, "Search Pattern not found\n");
3932 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3935 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3936 ksmbd_debug(SMB, "Restart directory scan\n");
3937 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3940 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3941 d_info.wptr = (char *)rsp->Buffer;
3942 d_info.rptr = (char *)rsp->Buffer;
3943 d_info.out_buf_len =
3944 smb2_calc_max_out_buf_len(work, 8,
3945 le32_to_cpu(req->OutputBufferLength));
3946 if (d_info.out_buf_len < 0) {
3950 d_info.flags = srch_flag;
3953 * reserve dot and dotdot entries in head of buffer
3956 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3957 dir_fp, &d_info, srch_ptr,
3958 smb2_populate_readdir_entry);
3964 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3965 d_info.hide_dot_file = true;
3967 buffer_sz = d_info.out_buf_len;
3968 d_info.rptr = d_info.wptr;
3969 query_dir_private.work = work;
3970 query_dir_private.search_pattern = srch_ptr;
3971 query_dir_private.dir_fp = dir_fp;
3972 query_dir_private.d_info = &d_info;
3973 query_dir_private.info_level = req->FileInformationClass;
3974 dir_fp->readdir_data.private = &query_dir_private;
3975 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3977 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3979 * req->OutputBufferLength is too small to contain even one entry.
3980 * In this case, it immediately returns OutputBufferLength 0 to client.
3982 if (!d_info.out_buf_len && !d_info.num_entry)
3984 if (rc > 0 || rc == -ENOSPC)
3989 d_info.wptr = d_info.rptr;
3990 d_info.out_buf_len = buffer_sz;
3991 rc = process_query_dir_entries(&query_dir_private);
3995 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3996 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3997 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3999 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4000 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4002 rsp->StructureSize = cpu_to_le16(9);
4003 rsp->OutputBufferOffset = cpu_to_le16(0);
4004 rsp->OutputBufferLength = cpu_to_le32(0);
4006 inc_rfc1001_len(work->response_buf, 9);
4009 ((struct file_directory_info *)
4010 ((char *)rsp->Buffer + d_info.last_entry_offset))
4011 ->NextEntryOffset = 0;
4012 if (d_info.data_count >= d_info.last_entry_off_align)
4013 d_info.data_count -= d_info.last_entry_off_align;
4015 rsp->StructureSize = cpu_to_le16(9);
4016 rsp->OutputBufferOffset = cpu_to_le16(72);
4017 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4018 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
4022 ksmbd_fd_put(work, dir_fp);
4023 ksmbd_revert_fsids(work);
4027 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4032 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4033 else if (rc == -EACCES)
4034 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4035 else if (rc == -ENOENT)
4036 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4037 else if (rc == -EBADF)
4038 rsp->hdr.Status = STATUS_FILE_CLOSED;
4039 else if (rc == -ENOMEM)
4040 rsp->hdr.Status = STATUS_NO_MEMORY;
4041 else if (rc == -EFAULT)
4042 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4043 else if (rc == -EIO)
4044 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4045 if (!rsp->hdr.Status)
4046 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4048 smb2_set_err_rsp(work);
4049 ksmbd_fd_put(work, dir_fp);
4050 ksmbd_revert_fsids(work);
4055 * buffer_check_err() - helper function to check buffer errors
4056 * @reqOutputBufferLength: max buffer length expected in command response
4057 * @rsp: query info response buffer contains output buffer length
4058 * @rsp_org: base response buffer pointer in case of chained response
4059 * @infoclass_size: query info class response buffer size
4061 * Return: 0 on success, otherwise error
4063 static int buffer_check_err(int reqOutputBufferLength,
4064 struct smb2_query_info_rsp *rsp,
4065 void *rsp_org, int infoclass_size)
4067 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4068 if (reqOutputBufferLength < infoclass_size) {
4069 pr_err("Invalid Buffer Size Requested\n");
4070 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4071 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4075 ksmbd_debug(SMB, "Buffer Overflow\n");
4076 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4077 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4078 reqOutputBufferLength);
4079 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4084 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4087 struct smb2_file_standard_info *sinfo;
4089 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4091 sinfo->AllocationSize = cpu_to_le64(4096);
4092 sinfo->EndOfFile = cpu_to_le64(0);
4093 sinfo->NumberOfLinks = cpu_to_le32(1);
4094 sinfo->DeletePending = 1;
4095 sinfo->Directory = 0;
4096 rsp->OutputBufferLength =
4097 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4098 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4101 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4104 struct smb2_file_internal_info *file_info;
4106 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4108 /* any unique number */
4109 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4110 rsp->OutputBufferLength =
4111 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4112 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4115 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4116 struct smb2_query_info_req *req,
4117 struct smb2_query_info_rsp *rsp,
4124 * Windows can sometime send query file info request on
4125 * pipe without opening it, checking error condition here
4127 id = req->VolatileFileId;
4128 if (!ksmbd_session_rpc_method(sess, id))
4131 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4132 req->FileInfoClass, req->VolatileFileId);
4134 switch (req->FileInfoClass) {
4135 case FILE_STANDARD_INFORMATION:
4136 get_standard_info_pipe(rsp, rsp_org);
4137 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4139 FILE_STANDARD_INFORMATION_SIZE);
4141 case FILE_INTERNAL_INFORMATION:
4142 get_internal_info_pipe(rsp, id, rsp_org);
4143 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4145 FILE_INTERNAL_INFORMATION_SIZE);
4148 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4149 req->FileInfoClass);
4156 * smb2_get_ea() - handler for smb2 get extended attribute command
4157 * @work: smb work containing query info command buffer
4158 * @fp: ksmbd_file pointer
4159 * @req: get extended attribute request
4160 * @rsp: response buffer pointer
4161 * @rsp_org: base response buffer pointer in case of chained response
4163 * Return: 0 on success, otherwise error
4165 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4166 struct smb2_query_info_req *req,
4167 struct smb2_query_info_rsp *rsp, void *rsp_org)
4169 struct smb2_ea_info *eainfo, *prev_eainfo;
4170 char *name, *ptr, *xattr_list = NULL, *buf;
4171 int rc, name_len, value_len, xattr_list_len, idx;
4172 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4173 struct smb2_ea_info_req *ea_req = NULL;
4174 const struct path *path;
4175 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4177 if (!(fp->daccess & FILE_READ_EA_LE)) {
4178 pr_err("Not permitted to read ext attr : 0x%x\n",
4183 path = &fp->filp->f_path;
4184 /* single EA entry is requested with given user.* name */
4185 if (req->InputBufferLength) {
4186 if (le32_to_cpu(req->InputBufferLength) <
4187 sizeof(struct smb2_ea_info_req))
4190 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4192 /* need to send all EAs, if no specific EA is requested*/
4193 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4195 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4196 le32_to_cpu(req->Flags));
4200 smb2_calc_max_out_buf_len(work, 8,
4201 le32_to_cpu(req->OutputBufferLength));
4202 if (buf_free_len < 0)
4205 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4207 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4209 } else if (!rc) { /* there is no EA in the file */
4210 ksmbd_debug(SMB, "no ea data in the file\n");
4213 xattr_list_len = rc;
4215 ptr = (char *)rsp->Buffer;
4216 eainfo = (struct smb2_ea_info *)ptr;
4217 prev_eainfo = eainfo;
4220 while (idx < xattr_list_len) {
4221 name = xattr_list + idx;
4222 name_len = strlen(name);
4224 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4225 idx += name_len + 1;
4228 * CIFS does not support EA other than user.* namespace,
4229 * still keep the framework generic, to list other attrs
4232 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4235 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4239 if (req->InputBufferLength &&
4240 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4241 ea_req->EaNameLength))
4244 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4245 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4248 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4249 name_len -= XATTR_USER_PREFIX_LEN;
4251 ptr = (char *)(&eainfo->name + name_len + 1);
4252 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4254 /* bailout if xattr can't fit in buf_free_len */
4255 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4257 if (value_len <= 0) {
4259 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4263 buf_free_len -= value_len;
4264 if (buf_free_len < 0) {
4269 memcpy(ptr, buf, value_len);
4274 eainfo->EaNameLength = name_len;
4276 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4277 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4280 memcpy(eainfo->name, name, name_len);
4282 eainfo->name[name_len] = '\0';
4283 eainfo->EaValueLength = cpu_to_le16(value_len);
4284 next_offset = offsetof(struct smb2_ea_info, name) +
4285 name_len + 1 + value_len;
4287 /* align next xattr entry at 4 byte bundary */
4288 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4289 if (alignment_bytes) {
4290 memset(ptr, '\0', alignment_bytes);
4291 ptr += alignment_bytes;
4292 next_offset += alignment_bytes;
4293 buf_free_len -= alignment_bytes;
4295 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4296 prev_eainfo = eainfo;
4297 eainfo = (struct smb2_ea_info *)ptr;
4298 rsp_data_cnt += next_offset;
4300 if (req->InputBufferLength) {
4301 ksmbd_debug(SMB, "single entry requested\n");
4306 /* no more ea entries */
4307 prev_eainfo->NextEntryOffset = 0;
4310 if (rsp_data_cnt == 0)
4311 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4312 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4313 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4319 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4320 struct ksmbd_file *fp, void *rsp_org)
4322 struct smb2_file_access_info *file_info;
4324 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4325 file_info->AccessFlags = fp->daccess;
4326 rsp->OutputBufferLength =
4327 cpu_to_le32(sizeof(struct smb2_file_access_info));
4328 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4331 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4332 struct ksmbd_file *fp, void *rsp_org)
4334 struct smb2_file_basic_info *basic_info;
4338 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4339 pr_err("no right to read the attributes : 0x%x\n",
4344 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4345 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4347 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4348 time = ksmbd_UnixTimeToNT(stat.atime);
4349 basic_info->LastAccessTime = cpu_to_le64(time);
4350 time = ksmbd_UnixTimeToNT(stat.mtime);
4351 basic_info->LastWriteTime = cpu_to_le64(time);
4352 time = ksmbd_UnixTimeToNT(stat.ctime);
4353 basic_info->ChangeTime = cpu_to_le64(time);
4354 basic_info->Attributes = fp->f_ci->m_fattr;
4355 basic_info->Pad1 = 0;
4356 rsp->OutputBufferLength =
4357 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4358 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4362 static unsigned long long get_allocation_size(struct inode *inode,
4365 unsigned long long alloc_size = 0;
4367 if (!S_ISDIR(stat->mode)) {
4368 if ((inode->i_blocks << 9) <= stat->size)
4369 alloc_size = stat->size;
4371 alloc_size = inode->i_blocks << 9;
4377 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4378 struct ksmbd_file *fp, void *rsp_org)
4380 struct smb2_file_standard_info *sinfo;
4381 unsigned int delete_pending;
4382 struct inode *inode;
4385 inode = file_inode(fp->filp);
4386 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4388 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4389 delete_pending = ksmbd_inode_pending_delete(fp);
4391 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4392 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4393 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4394 sinfo->DeletePending = delete_pending;
4395 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4396 rsp->OutputBufferLength =
4397 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4398 inc_rfc1001_len(rsp_org,
4399 sizeof(struct smb2_file_standard_info));
4402 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4405 struct smb2_file_alignment_info *file_info;
4407 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4408 file_info->AlignmentRequirement = 0;
4409 rsp->OutputBufferLength =
4410 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4411 inc_rfc1001_len(rsp_org,
4412 sizeof(struct smb2_file_alignment_info));
4415 static int get_file_all_info(struct ksmbd_work *work,
4416 struct smb2_query_info_rsp *rsp,
4417 struct ksmbd_file *fp,
4420 struct ksmbd_conn *conn = work->conn;
4421 struct smb2_file_all_info *file_info;
4422 unsigned int delete_pending;
4423 struct inode *inode;
4429 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4430 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4435 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4436 if (IS_ERR(filename))
4437 return PTR_ERR(filename);
4439 inode = file_inode(fp->filp);
4440 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4442 ksmbd_debug(SMB, "filename = %s\n", filename);
4443 delete_pending = ksmbd_inode_pending_delete(fp);
4444 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4446 file_info->CreationTime = cpu_to_le64(fp->create_time);
4447 time = ksmbd_UnixTimeToNT(stat.atime);
4448 file_info->LastAccessTime = cpu_to_le64(time);
4449 time = ksmbd_UnixTimeToNT(stat.mtime);
4450 file_info->LastWriteTime = cpu_to_le64(time);
4451 time = ksmbd_UnixTimeToNT(stat.ctime);
4452 file_info->ChangeTime = cpu_to_le64(time);
4453 file_info->Attributes = fp->f_ci->m_fattr;
4454 file_info->Pad1 = 0;
4455 file_info->AllocationSize =
4456 cpu_to_le64(get_allocation_size(inode, &stat));
4457 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4458 file_info->NumberOfLinks =
4459 cpu_to_le32(get_nlink(&stat) - delete_pending);
4460 file_info->DeletePending = delete_pending;
4461 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4462 file_info->Pad2 = 0;
4463 file_info->IndexNumber = cpu_to_le64(stat.ino);
4464 file_info->EASize = 0;
4465 file_info->AccessFlags = fp->daccess;
4466 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4467 file_info->Mode = fp->coption;
4468 file_info->AlignmentRequirement = 0;
4469 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4470 PATH_MAX, conn->local_nls, 0);
4472 file_info->FileNameLength = cpu_to_le32(conv_len);
4473 rsp->OutputBufferLength =
4474 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4476 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4480 static void get_file_alternate_info(struct ksmbd_work *work,
4481 struct smb2_query_info_rsp *rsp,
4482 struct ksmbd_file *fp,
4485 struct ksmbd_conn *conn = work->conn;
4486 struct smb2_file_alt_name_info *file_info;
4487 struct dentry *dentry = fp->filp->f_path.dentry;
4490 spin_lock(&dentry->d_lock);
4491 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4492 conv_len = ksmbd_extract_shortname(conn,
4493 dentry->d_name.name,
4494 file_info->FileName);
4495 spin_unlock(&dentry->d_lock);
4496 file_info->FileNameLength = cpu_to_le32(conv_len);
4497 rsp->OutputBufferLength =
4498 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4499 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4502 static void get_file_stream_info(struct ksmbd_work *work,
4503 struct smb2_query_info_rsp *rsp,
4504 struct ksmbd_file *fp,
4507 struct ksmbd_conn *conn = work->conn;
4508 struct smb2_file_stream_info *file_info;
4509 char *stream_name, *xattr_list = NULL, *stream_buf;
4511 const struct path *path = &fp->filp->f_path;
4512 ssize_t xattr_list_len;
4513 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4515 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4517 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4519 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4522 smb2_calc_max_out_buf_len(work, 8,
4523 le32_to_cpu(req->OutputBufferLength));
4524 if (buf_free_len < 0)
4527 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4528 if (xattr_list_len < 0) {
4530 } else if (!xattr_list_len) {
4531 ksmbd_debug(SMB, "empty xattr in the file\n");
4535 while (idx < xattr_list_len) {
4536 stream_name = xattr_list + idx;
4537 streamlen = strlen(stream_name);
4538 idx += streamlen + 1;
4540 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4542 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4543 STREAM_PREFIX, STREAM_PREFIX_LEN))
4546 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4548 streamlen = stream_name_len;
4552 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4556 streamlen = snprintf(stream_buf, streamlen + 1,
4557 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4559 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4560 if (next > buf_free_len) {
4565 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4566 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4567 stream_buf, streamlen,
4568 conn->local_nls, 0);
4571 file_info->StreamNameLength = cpu_to_le32(streamlen);
4572 file_info->StreamSize = cpu_to_le64(stream_name_len);
4573 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4576 buf_free_len -= next;
4577 file_info->NextEntryOffset = cpu_to_le32(next);
4581 if (!S_ISDIR(stat.mode) &&
4582 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4583 file_info = (struct smb2_file_stream_info *)
4584 &rsp->Buffer[nbytes];
4585 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4586 "::$DATA", 7, conn->local_nls, 0);
4588 file_info->StreamNameLength = cpu_to_le32(streamlen);
4589 file_info->StreamSize = cpu_to_le64(stat.size);
4590 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4591 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4594 /* last entry offset should be 0 */
4595 file_info->NextEntryOffset = 0;
4598 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4599 inc_rfc1001_len(rsp_org, nbytes);
4602 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4603 struct ksmbd_file *fp, void *rsp_org)
4605 struct smb2_file_internal_info *file_info;
4608 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4610 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4611 file_info->IndexNumber = cpu_to_le64(stat.ino);
4612 rsp->OutputBufferLength =
4613 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4614 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4617 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4618 struct ksmbd_file *fp, void *rsp_org)
4620 struct smb2_file_ntwrk_info *file_info;
4621 struct inode *inode;
4625 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4626 pr_err("no right to read the attributes : 0x%x\n",
4631 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4633 inode = file_inode(fp->filp);
4634 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4636 file_info->CreationTime = cpu_to_le64(fp->create_time);
4637 time = ksmbd_UnixTimeToNT(stat.atime);
4638 file_info->LastAccessTime = cpu_to_le64(time);
4639 time = ksmbd_UnixTimeToNT(stat.mtime);
4640 file_info->LastWriteTime = cpu_to_le64(time);
4641 time = ksmbd_UnixTimeToNT(stat.ctime);
4642 file_info->ChangeTime = cpu_to_le64(time);
4643 file_info->Attributes = fp->f_ci->m_fattr;
4644 file_info->AllocationSize =
4645 cpu_to_le64(get_allocation_size(inode, &stat));
4646 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4647 file_info->Reserved = cpu_to_le32(0);
4648 rsp->OutputBufferLength =
4649 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4650 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4654 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4656 struct smb2_file_ea_info *file_info;
4658 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4659 file_info->EASize = 0;
4660 rsp->OutputBufferLength =
4661 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4662 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4665 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4666 struct ksmbd_file *fp, void *rsp_org)
4668 struct smb2_file_pos_info *file_info;
4670 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4671 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4672 rsp->OutputBufferLength =
4673 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4674 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4677 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4678 struct ksmbd_file *fp, void *rsp_org)
4680 struct smb2_file_mode_info *file_info;
4682 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4683 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4684 rsp->OutputBufferLength =
4685 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4686 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4689 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4690 struct ksmbd_file *fp, void *rsp_org)
4692 struct smb2_file_comp_info *file_info;
4695 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4698 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4699 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4700 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4701 file_info->CompressionUnitShift = 0;
4702 file_info->ChunkShift = 0;
4703 file_info->ClusterShift = 0;
4704 memset(&file_info->Reserved[0], 0, 3);
4706 rsp->OutputBufferLength =
4707 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4708 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4711 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4712 struct ksmbd_file *fp, void *rsp_org)
4714 struct smb2_file_attr_tag_info *file_info;
4716 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4717 pr_err("no right to read the attributes : 0x%x\n",
4722 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4723 file_info->FileAttributes = fp->f_ci->m_fattr;
4724 file_info->ReparseTag = 0;
4725 rsp->OutputBufferLength =
4726 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4727 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4731 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4732 struct ksmbd_file *fp, void *rsp_org)
4734 struct smb311_posix_qinfo *file_info;
4735 struct inode *inode = file_inode(fp->filp);
4736 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4737 vfsuid_t vfsuid = i_uid_into_vfsuid(user_ns, inode);
4738 vfsgid_t vfsgid = i_gid_into_vfsgid(user_ns, inode);
4740 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4742 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4743 file_info->CreationTime = cpu_to_le64(fp->create_time);
4744 time = ksmbd_UnixTimeToNT(inode->i_atime);
4745 file_info->LastAccessTime = cpu_to_le64(time);
4746 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4747 file_info->LastWriteTime = cpu_to_le64(time);
4748 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4749 file_info->ChangeTime = cpu_to_le64(time);
4750 file_info->DosAttributes = fp->f_ci->m_fattr;
4751 file_info->Inode = cpu_to_le64(inode->i_ino);
4752 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4753 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4754 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4755 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4756 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4759 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4760 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4761 * sub_auth(4 * 1(num_subauth)) + RID(4).
4763 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4764 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4765 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4766 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4768 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4769 inc_rfc1001_len(rsp_org, out_buf_len);
4773 static int smb2_get_info_file(struct ksmbd_work *work,
4774 struct smb2_query_info_req *req,
4775 struct smb2_query_info_rsp *rsp)
4777 struct ksmbd_file *fp;
4778 int fileinfoclass = 0;
4780 int file_infoclass_size;
4781 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4783 if (test_share_config_flag(work->tcon->share_conf,
4784 KSMBD_SHARE_FLAG_PIPE)) {
4785 /* smb2 info file called for pipe */
4786 return smb2_get_info_file_pipe(work->sess, req, rsp,
4787 work->response_buf);
4790 if (work->next_smb2_rcv_hdr_off) {
4791 if (!has_file_id(req->VolatileFileId)) {
4792 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4793 work->compound_fid);
4794 id = work->compound_fid;
4795 pid = work->compound_pfid;
4799 if (!has_file_id(id)) {
4800 id = req->VolatileFileId;
4801 pid = req->PersistentFileId;
4804 fp = ksmbd_lookup_fd_slow(work, id, pid);
4808 fileinfoclass = req->FileInfoClass;
4810 switch (fileinfoclass) {
4811 case FILE_ACCESS_INFORMATION:
4812 get_file_access_info(rsp, fp, work->response_buf);
4813 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4816 case FILE_BASIC_INFORMATION:
4817 rc = get_file_basic_info(rsp, fp, work->response_buf);
4818 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4821 case FILE_STANDARD_INFORMATION:
4822 get_file_standard_info(rsp, fp, work->response_buf);
4823 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4826 case FILE_ALIGNMENT_INFORMATION:
4827 get_file_alignment_info(rsp, work->response_buf);
4828 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4831 case FILE_ALL_INFORMATION:
4832 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4833 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4836 case FILE_ALTERNATE_NAME_INFORMATION:
4837 get_file_alternate_info(work, rsp, fp, work->response_buf);
4838 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4841 case FILE_STREAM_INFORMATION:
4842 get_file_stream_info(work, rsp, fp, work->response_buf);
4843 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4846 case FILE_INTERNAL_INFORMATION:
4847 get_file_internal_info(rsp, fp, work->response_buf);
4848 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4851 case FILE_NETWORK_OPEN_INFORMATION:
4852 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4853 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4856 case FILE_EA_INFORMATION:
4857 get_file_ea_info(rsp, work->response_buf);
4858 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4861 case FILE_FULL_EA_INFORMATION:
4862 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4863 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4866 case FILE_POSITION_INFORMATION:
4867 get_file_position_info(rsp, fp, work->response_buf);
4868 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4871 case FILE_MODE_INFORMATION:
4872 get_file_mode_info(rsp, fp, work->response_buf);
4873 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4876 case FILE_COMPRESSION_INFORMATION:
4877 get_file_compression_info(rsp, fp, work->response_buf);
4878 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4881 case FILE_ATTRIBUTE_TAG_INFORMATION:
4882 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4883 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4885 case SMB_FIND_FILE_POSIX_INFO:
4886 if (!work->tcon->posix_extensions) {
4887 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4890 file_infoclass_size = find_file_posix_info(rsp, fp,
4891 work->response_buf);
4895 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4900 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4901 rsp, work->response_buf,
4902 file_infoclass_size);
4903 ksmbd_fd_put(work, fp);
4907 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4908 struct smb2_query_info_req *req,
4909 struct smb2_query_info_rsp *rsp)
4911 struct ksmbd_session *sess = work->sess;
4912 struct ksmbd_conn *conn = work->conn;
4913 struct ksmbd_share_config *share = work->tcon->share_conf;
4914 int fsinfoclass = 0;
4915 struct kstatfs stfs;
4918 int fs_infoclass_size = 0;
4923 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4925 pr_err("cannot create vfs path\n");
4929 rc = vfs_statfs(&path, &stfs);
4931 pr_err("cannot do stat of path %s\n", share->path);
4936 fsinfoclass = req->FileInfoClass;
4938 switch (fsinfoclass) {
4939 case FS_DEVICE_INFORMATION:
4941 struct filesystem_device_info *info;
4943 info = (struct filesystem_device_info *)rsp->Buffer;
4945 info->DeviceType = cpu_to_le32(stfs.f_type);
4946 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4947 rsp->OutputBufferLength = cpu_to_le32(8);
4948 inc_rfc1001_len(work->response_buf, 8);
4949 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4952 case FS_ATTRIBUTE_INFORMATION:
4954 struct filesystem_attribute_info *info;
4957 info = (struct filesystem_attribute_info *)rsp->Buffer;
4958 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4959 FILE_PERSISTENT_ACLS |
4960 FILE_UNICODE_ON_DISK |
4961 FILE_CASE_PRESERVED_NAMES |
4962 FILE_CASE_SENSITIVE_SEARCH |
4963 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4965 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4967 if (test_share_config_flag(work->tcon->share_conf,
4968 KSMBD_SHARE_FLAG_STREAMS))
4969 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
4971 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4972 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4973 "NTFS", PATH_MAX, conn->local_nls, 0);
4975 info->FileSystemNameLen = cpu_to_le32(len);
4976 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4977 rsp->OutputBufferLength = cpu_to_le32(sz);
4978 inc_rfc1001_len(work->response_buf, sz);
4979 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4982 case FS_VOLUME_INFORMATION:
4984 struct filesystem_vol_info *info;
4986 unsigned int serial_crc = 0;
4988 info = (struct filesystem_vol_info *)(rsp->Buffer);
4989 info->VolumeCreationTime = 0;
4990 serial_crc = crc32_le(serial_crc, share->name,
4991 strlen(share->name));
4992 serial_crc = crc32_le(serial_crc, share->path,
4993 strlen(share->path));
4994 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4995 strlen(ksmbd_netbios_name()));
4996 /* Taking dummy value of serial number*/
4997 info->SerialNumber = cpu_to_le32(serial_crc);
4998 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4999 share->name, PATH_MAX,
5000 conn->local_nls, 0);
5002 info->VolumeLabelSize = cpu_to_le32(len);
5004 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5005 rsp->OutputBufferLength = cpu_to_le32(sz);
5006 inc_rfc1001_len(work->response_buf, sz);
5007 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
5010 case FS_SIZE_INFORMATION:
5012 struct filesystem_info *info;
5014 info = (struct filesystem_info *)(rsp->Buffer);
5015 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5016 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5017 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5018 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5019 rsp->OutputBufferLength = cpu_to_le32(24);
5020 inc_rfc1001_len(work->response_buf, 24);
5021 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
5024 case FS_FULL_SIZE_INFORMATION:
5026 struct smb2_fs_full_size_info *info;
5028 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5029 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5030 info->CallerAvailableAllocationUnits =
5031 cpu_to_le64(stfs.f_bavail);
5032 info->ActualAvailableAllocationUnits =
5033 cpu_to_le64(stfs.f_bfree);
5034 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5035 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5036 rsp->OutputBufferLength = cpu_to_le32(32);
5037 inc_rfc1001_len(work->response_buf, 32);
5038 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
5041 case FS_OBJECT_ID_INFORMATION:
5043 struct object_id_info *info;
5045 info = (struct object_id_info *)(rsp->Buffer);
5047 if (!user_guest(sess->user))
5048 memcpy(info->objid, user_passkey(sess->user), 16);
5050 memset(info->objid, 0, 16);
5052 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5053 info->extended_info.version = cpu_to_le32(1);
5054 info->extended_info.release = cpu_to_le32(1);
5055 info->extended_info.rel_date = 0;
5056 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5057 rsp->OutputBufferLength = cpu_to_le32(64);
5058 inc_rfc1001_len(work->response_buf, 64);
5059 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5062 case FS_SECTOR_SIZE_INFORMATION:
5064 struct smb3_fs_ss_info *info;
5065 unsigned int sector_size =
5066 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5068 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5070 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5071 info->PhysicalBytesPerSectorForAtomicity =
5072 cpu_to_le32(sector_size);
5073 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5074 info->FSEffPhysicalBytesPerSectorForAtomicity =
5075 cpu_to_le32(sector_size);
5076 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5077 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5078 info->ByteOffsetForSectorAlignment = 0;
5079 info->ByteOffsetForPartitionAlignment = 0;
5080 rsp->OutputBufferLength = cpu_to_le32(28);
5081 inc_rfc1001_len(work->response_buf, 28);
5082 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5085 case FS_CONTROL_INFORMATION:
5088 * TODO : The current implementation is based on
5089 * test result with win7(NTFS) server. It's need to
5090 * modify this to get valid Quota values
5093 struct smb2_fs_control_info *info;
5095 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5096 info->FreeSpaceStartFiltering = 0;
5097 info->FreeSpaceThreshold = 0;
5098 info->FreeSpaceStopFiltering = 0;
5099 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5100 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5102 rsp->OutputBufferLength = cpu_to_le32(48);
5103 inc_rfc1001_len(work->response_buf, 48);
5104 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5107 case FS_POSIX_INFORMATION:
5109 struct filesystem_posix_info *info;
5111 if (!work->tcon->posix_extensions) {
5112 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5115 info = (struct filesystem_posix_info *)(rsp->Buffer);
5116 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5117 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5118 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5119 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5120 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5121 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5122 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5123 rsp->OutputBufferLength = cpu_to_le32(56);
5124 inc_rfc1001_len(work->response_buf, 56);
5125 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5133 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5134 rsp, work->response_buf,
5140 static int smb2_get_info_sec(struct ksmbd_work *work,
5141 struct smb2_query_info_req *req,
5142 struct smb2_query_info_rsp *rsp)
5144 struct ksmbd_file *fp;
5145 struct user_namespace *user_ns;
5146 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5147 struct smb_fattr fattr = {{0}};
5148 struct inode *inode;
5149 __u32 secdesclen = 0;
5150 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5151 int addition_info = le32_to_cpu(req->AdditionalInformation);
5152 int rc = 0, ppntsd_size = 0;
5154 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5155 PROTECTED_DACL_SECINFO |
5156 UNPROTECTED_DACL_SECINFO)) {
5157 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5160 pntsd->revision = cpu_to_le16(1);
5161 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5162 pntsd->osidoffset = 0;
5163 pntsd->gsidoffset = 0;
5164 pntsd->sacloffset = 0;
5165 pntsd->dacloffset = 0;
5167 secdesclen = sizeof(struct smb_ntsd);
5168 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5169 inc_rfc1001_len(work->response_buf, secdesclen);
5174 if (work->next_smb2_rcv_hdr_off) {
5175 if (!has_file_id(req->VolatileFileId)) {
5176 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5177 work->compound_fid);
5178 id = work->compound_fid;
5179 pid = work->compound_pfid;
5183 if (!has_file_id(id)) {
5184 id = req->VolatileFileId;
5185 pid = req->PersistentFileId;
5188 fp = ksmbd_lookup_fd_slow(work, id, pid);
5192 user_ns = file_mnt_user_ns(fp->filp);
5193 inode = file_inode(fp->filp);
5194 ksmbd_acls_fattr(&fattr, user_ns, inode);
5196 if (test_share_config_flag(work->tcon->share_conf,
5197 KSMBD_SHARE_FLAG_ACL_XATTR))
5198 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5199 fp->filp->f_path.dentry,
5202 /* Check if sd buffer size exceeds response buffer size */
5203 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5204 rc = build_sec_desc(user_ns, pntsd, ppntsd, ppntsd_size,
5205 addition_info, &secdesclen, &fattr);
5206 posix_acl_release(fattr.cf_acls);
5207 posix_acl_release(fattr.cf_dacls);
5209 ksmbd_fd_put(work, fp);
5213 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5214 inc_rfc1001_len(work->response_buf, secdesclen);
5219 * smb2_query_info() - handler for smb2 query info command
5220 * @work: smb work containing query info request buffer
5222 * Return: 0 on success, otherwise error
5224 int smb2_query_info(struct ksmbd_work *work)
5226 struct smb2_query_info_req *req;
5227 struct smb2_query_info_rsp *rsp;
5230 WORK_BUFFERS(work, req, rsp);
5232 ksmbd_debug(SMB, "GOT query info request\n");
5234 switch (req->InfoType) {
5235 case SMB2_O_INFO_FILE:
5236 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5237 rc = smb2_get_info_file(work, req, rsp);
5239 case SMB2_O_INFO_FILESYSTEM:
5240 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5241 rc = smb2_get_info_filesystem(work, req, rsp);
5243 case SMB2_O_INFO_SECURITY:
5244 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5245 rc = smb2_get_info_sec(work, req, rsp);
5248 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5255 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5256 else if (rc == -ENOENT)
5257 rsp->hdr.Status = STATUS_FILE_CLOSED;
5258 else if (rc == -EIO)
5259 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5260 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5261 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5262 smb2_set_err_rsp(work);
5264 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5268 rsp->StructureSize = cpu_to_le16(9);
5269 rsp->OutputBufferOffset = cpu_to_le16(72);
5270 inc_rfc1001_len(work->response_buf, 8);
5275 * smb2_close_pipe() - handler for closing IPC pipe
5276 * @work: smb work containing close request buffer
5280 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5283 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5284 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5286 id = req->VolatileFileId;
5287 ksmbd_session_rpc_close(work->sess, id);
5289 rsp->StructureSize = cpu_to_le16(60);
5292 rsp->CreationTime = 0;
5293 rsp->LastAccessTime = 0;
5294 rsp->LastWriteTime = 0;
5295 rsp->ChangeTime = 0;
5296 rsp->AllocationSize = 0;
5298 rsp->Attributes = 0;
5299 inc_rfc1001_len(work->response_buf, 60);
5304 * smb2_close() - handler for smb2 close file command
5305 * @work: smb work containing close request buffer
5309 int smb2_close(struct ksmbd_work *work)
5311 u64 volatile_id = KSMBD_NO_FID;
5313 struct smb2_close_req *req;
5314 struct smb2_close_rsp *rsp;
5315 struct ksmbd_conn *conn = work->conn;
5316 struct ksmbd_file *fp;
5317 struct inode *inode;
5321 WORK_BUFFERS(work, req, rsp);
5323 if (test_share_config_flag(work->tcon->share_conf,
5324 KSMBD_SHARE_FLAG_PIPE)) {
5325 ksmbd_debug(SMB, "IPC pipe close request\n");
5326 return smb2_close_pipe(work);
5329 sess_id = le64_to_cpu(req->hdr.SessionId);
5330 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5331 sess_id = work->compound_sid;
5333 work->compound_sid = 0;
5334 if (check_session_id(conn, sess_id)) {
5335 work->compound_sid = sess_id;
5337 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5338 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5339 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5344 if (work->next_smb2_rcv_hdr_off &&
5345 !has_file_id(req->VolatileFileId)) {
5346 if (!has_file_id(work->compound_fid)) {
5347 /* file already closed, return FILE_CLOSED */
5348 ksmbd_debug(SMB, "file already closed\n");
5349 rsp->hdr.Status = STATUS_FILE_CLOSED;
5354 "Compound request set FID = %llu:%llu\n",
5356 work->compound_pfid);
5357 volatile_id = work->compound_fid;
5359 /* file closed, stored id is not valid anymore */
5360 work->compound_fid = KSMBD_NO_FID;
5361 work->compound_pfid = KSMBD_NO_FID;
5364 volatile_id = req->VolatileFileId;
5366 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5368 rsp->StructureSize = cpu_to_le16(60);
5371 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5372 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5378 inode = file_inode(fp->filp);
5379 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5380 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5381 cpu_to_le64(inode->i_blocks << 9);
5382 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5383 rsp->Attributes = fp->f_ci->m_fattr;
5384 rsp->CreationTime = cpu_to_le64(fp->create_time);
5385 time = ksmbd_UnixTimeToNT(inode->i_atime);
5386 rsp->LastAccessTime = cpu_to_le64(time);
5387 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5388 rsp->LastWriteTime = cpu_to_le64(time);
5389 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5390 rsp->ChangeTime = cpu_to_le64(time);
5391 ksmbd_fd_put(work, fp);
5394 rsp->AllocationSize = 0;
5396 rsp->Attributes = 0;
5397 rsp->CreationTime = 0;
5398 rsp->LastAccessTime = 0;
5399 rsp->LastWriteTime = 0;
5400 rsp->ChangeTime = 0;
5403 err = ksmbd_close_fd(work, volatile_id);
5406 if (rsp->hdr.Status == 0)
5407 rsp->hdr.Status = STATUS_FILE_CLOSED;
5408 smb2_set_err_rsp(work);
5410 inc_rfc1001_len(work->response_buf, 60);
5417 * smb2_echo() - handler for smb2 echo(ping) command
5418 * @work: smb work containing echo request buffer
5422 int smb2_echo(struct ksmbd_work *work)
5424 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5426 rsp->StructureSize = cpu_to_le16(4);
5428 inc_rfc1001_len(work->response_buf, 4);
5432 static int smb2_rename(struct ksmbd_work *work,
5433 struct ksmbd_file *fp,
5434 struct user_namespace *user_ns,
5435 struct smb2_file_rename_info *file_info,
5436 struct nls_table *local_nls)
5438 struct ksmbd_share_config *share = fp->tcon->share_conf;
5439 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5440 char *pathname = NULL;
5442 bool file_present = true;
5445 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5446 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5450 abs_oldname = file_path(fp->filp, pathname, PATH_MAX);
5451 if (IS_ERR(abs_oldname)) {
5455 old_name = strrchr(abs_oldname, '/');
5456 if (old_name && old_name[1] != '\0') {
5459 ksmbd_debug(SMB, "can't get last component in path %s\n",
5465 new_name = smb2_get_name(file_info->FileName,
5466 le32_to_cpu(file_info->FileNameLength),
5468 if (IS_ERR(new_name)) {
5469 rc = PTR_ERR(new_name);
5473 if (strchr(new_name, ':')) {
5475 char *xattr_stream_name, *stream_name = NULL;
5476 size_t xattr_stream_size;
5479 rc = parse_stream_name(new_name, &stream_name, &s_type);
5483 len = strlen(new_name);
5484 if (len > 0 && new_name[len - 1] != '/') {
5485 pr_err("not allow base filename in rename\n");
5490 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5497 rc = ksmbd_vfs_setxattr(user_ns,
5498 fp->filp->f_path.dentry,
5502 pr_err("failed to store stream name in xattr: %d\n",
5511 ksmbd_debug(SMB, "new name %s\n", new_name);
5512 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5516 file_present = false;
5521 if (ksmbd_share_veto_filename(share, new_name)) {
5523 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5527 if (file_info->ReplaceIfExists) {
5529 rc = ksmbd_vfs_remove_file(work, new_name);
5531 if (rc != -ENOTEMPTY)
5533 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5540 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5543 "cannot rename already existing file\n");
5548 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5551 if (!IS_ERR(new_name))
5556 static int smb2_create_link(struct ksmbd_work *work,
5557 struct ksmbd_share_config *share,
5558 struct smb2_file_link_info *file_info,
5559 unsigned int buf_len, struct file *filp,
5560 struct nls_table *local_nls)
5562 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5564 bool file_present = true;
5567 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5568 le32_to_cpu(file_info->FileNameLength))
5571 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5572 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5576 link_name = smb2_get_name(file_info->FileName,
5577 le32_to_cpu(file_info->FileNameLength),
5579 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5584 ksmbd_debug(SMB, "link name is %s\n", link_name);
5585 target_name = file_path(filp, pathname, PATH_MAX);
5586 if (IS_ERR(target_name)) {
5591 ksmbd_debug(SMB, "target name is %s\n", target_name);
5592 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5596 file_present = false;
5601 if (file_info->ReplaceIfExists) {
5603 rc = ksmbd_vfs_remove_file(work, link_name);
5606 ksmbd_debug(SMB, "cannot delete %s\n",
5614 ksmbd_debug(SMB, "link already exists\n");
5619 rc = ksmbd_vfs_link(work, target_name, link_name);
5623 if (!IS_ERR(link_name))
5629 static int set_file_basic_info(struct ksmbd_file *fp,
5630 struct smb2_file_basic_info *file_info,
5631 struct ksmbd_share_config *share)
5635 struct inode *inode;
5636 struct user_namespace *user_ns;
5639 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5644 inode = file_inode(filp);
5645 user_ns = file_mnt_user_ns(filp);
5647 if (file_info->CreationTime)
5648 fp->create_time = le64_to_cpu(file_info->CreationTime);
5650 if (file_info->LastAccessTime) {
5651 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5652 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5655 attrs.ia_valid |= ATTR_CTIME;
5656 if (file_info->ChangeTime)
5657 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5659 attrs.ia_ctime = inode->i_ctime;
5661 if (file_info->LastWriteTime) {
5662 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5663 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5666 if (file_info->Attributes) {
5667 if (!S_ISDIR(inode->i_mode) &&
5668 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5669 pr_err("can't change a file to a directory\n");
5673 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5674 fp->f_ci->m_fattr = file_info->Attributes |
5675 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5678 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5679 (file_info->CreationTime || file_info->Attributes)) {
5680 struct xattr_dos_attrib da = {0};
5683 da.itime = fp->itime;
5684 da.create_time = fp->create_time;
5685 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5686 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5687 XATTR_DOSINFO_ITIME;
5689 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5690 filp->f_path.dentry, &da);
5693 "failed to restore file attribute in EA\n");
5697 if (attrs.ia_valid) {
5698 struct dentry *dentry = filp->f_path.dentry;
5699 struct inode *inode = d_inode(dentry);
5701 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5705 inode->i_ctime = attrs.ia_ctime;
5706 attrs.ia_valid &= ~ATTR_CTIME;
5707 rc = notify_change(user_ns, dentry, &attrs, NULL);
5708 inode_unlock(inode);
5713 static int set_file_allocation_info(struct ksmbd_work *work,
5714 struct ksmbd_file *fp,
5715 struct smb2_file_alloc_info *file_alloc_info)
5718 * TODO : It's working fine only when store dos attributes
5719 * is not yes. need to implement a logic which works
5720 * properly with any smb.conf option
5724 struct inode *inode;
5727 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5730 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5731 inode = file_inode(fp->filp);
5733 if (alloc_blks > inode->i_blocks) {
5734 smb_break_all_levII_oplock(work, fp, 1);
5735 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5737 if (rc && rc != -EOPNOTSUPP) {
5738 pr_err("vfs_fallocate is failed : %d\n", rc);
5741 } else if (alloc_blks < inode->i_blocks) {
5745 * Allocation size could be smaller than original one
5746 * which means allocated blocks in file should be
5747 * deallocated. use truncate to cut out it, but inode
5748 * size is also updated with truncate offset.
5749 * inode size is retained by backup inode size.
5751 size = i_size_read(inode);
5752 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5754 pr_err("truncate failed!, err %d\n", rc);
5757 if (size < alloc_blks * 512)
5758 i_size_write(inode, size);
5763 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5764 struct smb2_file_eof_info *file_eof_info)
5767 struct inode *inode;
5770 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5773 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5774 inode = file_inode(fp->filp);
5777 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5778 * on FAT32 shared device, truncate execution time is too long
5779 * and network error could cause from windows client. because
5780 * truncate of some filesystem like FAT32 fill zero data in
5783 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5784 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5785 rc = ksmbd_vfs_truncate(work, fp, newsize);
5787 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5796 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5797 struct smb2_file_rename_info *rename_info,
5798 unsigned int buf_len)
5800 struct user_namespace *user_ns;
5801 struct ksmbd_file *parent_fp;
5802 struct dentry *parent;
5803 struct dentry *dentry = fp->filp->f_path.dentry;
5806 if (!(fp->daccess & FILE_DELETE_LE)) {
5807 pr_err("no right to delete : 0x%x\n", fp->daccess);
5811 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5812 le32_to_cpu(rename_info->FileNameLength))
5815 user_ns = file_mnt_user_ns(fp->filp);
5816 if (ksmbd_stream_fd(fp))
5819 parent = dget_parent(dentry);
5820 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5826 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5827 inode_unlock(d_inode(parent));
5831 if (parent_fp->daccess & FILE_DELETE_LE) {
5832 pr_err("parent dir is opened with delete access\n");
5833 ksmbd_fd_put(work, parent_fp);
5836 ksmbd_fd_put(work, parent_fp);
5839 return smb2_rename(work, fp, user_ns, rename_info,
5840 work->conn->local_nls);
5843 static int set_file_disposition_info(struct ksmbd_file *fp,
5844 struct smb2_file_disposition_info *file_info)
5846 struct inode *inode;
5848 if (!(fp->daccess & FILE_DELETE_LE)) {
5849 pr_err("no right to delete : 0x%x\n", fp->daccess);
5853 inode = file_inode(fp->filp);
5854 if (file_info->DeletePending) {
5855 if (S_ISDIR(inode->i_mode) &&
5856 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5858 ksmbd_set_inode_pending_delete(fp);
5860 ksmbd_clear_inode_pending_delete(fp);
5865 static int set_file_position_info(struct ksmbd_file *fp,
5866 struct smb2_file_pos_info *file_info)
5868 loff_t current_byte_offset;
5869 unsigned long sector_size;
5870 struct inode *inode;
5872 inode = file_inode(fp->filp);
5873 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5874 sector_size = inode->i_sb->s_blocksize;
5876 if (current_byte_offset < 0 ||
5877 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5878 current_byte_offset & (sector_size - 1))) {
5879 pr_err("CurrentByteOffset is not valid : %llu\n",
5880 current_byte_offset);
5884 fp->filp->f_pos = current_byte_offset;
5888 static int set_file_mode_info(struct ksmbd_file *fp,
5889 struct smb2_file_mode_info *file_info)
5893 mode = file_info->Mode;
5895 if ((mode & ~FILE_MODE_INFO_MASK)) {
5896 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5901 * TODO : need to implement consideration for
5902 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5904 ksmbd_vfs_set_fadvise(fp->filp, mode);
5910 * smb2_set_info_file() - handler for smb2 set info command
5911 * @work: smb work containing set info command buffer
5912 * @fp: ksmbd_file pointer
5913 * @req: request buffer pointer
5914 * @share: ksmbd_share_config pointer
5916 * Return: 0 on success, otherwise error
5917 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5919 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5920 struct smb2_set_info_req *req,
5921 struct ksmbd_share_config *share)
5923 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5925 switch (req->FileInfoClass) {
5926 case FILE_BASIC_INFORMATION:
5928 if (buf_len < sizeof(struct smb2_file_basic_info))
5931 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5933 case FILE_ALLOCATION_INFORMATION:
5935 if (buf_len < sizeof(struct smb2_file_alloc_info))
5938 return set_file_allocation_info(work, fp,
5939 (struct smb2_file_alloc_info *)req->Buffer);
5941 case FILE_END_OF_FILE_INFORMATION:
5943 if (buf_len < sizeof(struct smb2_file_eof_info))
5946 return set_end_of_file_info(work, fp,
5947 (struct smb2_file_eof_info *)req->Buffer);
5949 case FILE_RENAME_INFORMATION:
5951 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5953 "User does not have write permission\n");
5957 if (buf_len < sizeof(struct smb2_file_rename_info))
5960 return set_rename_info(work, fp,
5961 (struct smb2_file_rename_info *)req->Buffer,
5964 case FILE_LINK_INFORMATION:
5966 if (buf_len < sizeof(struct smb2_file_link_info))
5969 return smb2_create_link(work, work->tcon->share_conf,
5970 (struct smb2_file_link_info *)req->Buffer,
5972 work->conn->local_nls);
5974 case FILE_DISPOSITION_INFORMATION:
5976 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5978 "User does not have write permission\n");
5982 if (buf_len < sizeof(struct smb2_file_disposition_info))
5985 return set_file_disposition_info(fp,
5986 (struct smb2_file_disposition_info *)req->Buffer);
5988 case FILE_FULL_EA_INFORMATION:
5990 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5991 pr_err("Not permitted to write ext attr: 0x%x\n",
5996 if (buf_len < sizeof(struct smb2_ea_info))
5999 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
6000 buf_len, &fp->filp->f_path);
6002 case FILE_POSITION_INFORMATION:
6004 if (buf_len < sizeof(struct smb2_file_pos_info))
6007 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
6009 case FILE_MODE_INFORMATION:
6011 if (buf_len < sizeof(struct smb2_file_mode_info))
6014 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6018 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6022 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6023 char *buffer, int buf_len)
6025 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6027 fp->saccess |= FILE_SHARE_DELETE_LE;
6029 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6034 * smb2_set_info() - handler for smb2 set info command handler
6035 * @work: smb work containing set info request buffer
6037 * Return: 0 on success, otherwise error
6039 int smb2_set_info(struct ksmbd_work *work)
6041 struct smb2_set_info_req *req;
6042 struct smb2_set_info_rsp *rsp;
6043 struct ksmbd_file *fp;
6045 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6047 ksmbd_debug(SMB, "Received set info request\n");
6049 if (work->next_smb2_rcv_hdr_off) {
6050 req = ksmbd_req_buf_next(work);
6051 rsp = ksmbd_resp_buf_next(work);
6052 if (!has_file_id(req->VolatileFileId)) {
6053 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6054 work->compound_fid);
6055 id = work->compound_fid;
6056 pid = work->compound_pfid;
6059 req = smb2_get_msg(work->request_buf);
6060 rsp = smb2_get_msg(work->response_buf);
6063 if (!has_file_id(id)) {
6064 id = req->VolatileFileId;
6065 pid = req->PersistentFileId;
6068 fp = ksmbd_lookup_fd_slow(work, id, pid);
6070 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6075 switch (req->InfoType) {
6076 case SMB2_O_INFO_FILE:
6077 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6078 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6080 case SMB2_O_INFO_SECURITY:
6081 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6082 if (ksmbd_override_fsids(work)) {
6086 rc = smb2_set_info_sec(fp,
6087 le32_to_cpu(req->AdditionalInformation),
6089 le32_to_cpu(req->BufferLength));
6090 ksmbd_revert_fsids(work);
6099 rsp->StructureSize = cpu_to_le16(2);
6100 inc_rfc1001_len(work->response_buf, 2);
6101 ksmbd_fd_put(work, fp);
6105 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6106 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6107 else if (rc == -EINVAL)
6108 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6109 else if (rc == -ESHARE)
6110 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6111 else if (rc == -ENOENT)
6112 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6113 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6114 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6115 else if (rc == -EAGAIN)
6116 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6117 else if (rc == -EBADF || rc == -ESTALE)
6118 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6119 else if (rc == -EEXIST)
6120 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6121 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6122 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6123 smb2_set_err_rsp(work);
6124 ksmbd_fd_put(work, fp);
6125 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6130 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6131 * @work: smb work containing read IPC pipe command buffer
6133 * Return: 0 on success, otherwise error
6135 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6137 int nbytes = 0, err;
6139 struct ksmbd_rpc_command *rpc_resp;
6140 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6141 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6143 id = req->VolatileFileId;
6145 inc_rfc1001_len(work->response_buf, 16);
6146 rpc_resp = ksmbd_rpc_read(work->sess, id);
6148 if (rpc_resp->flags != KSMBD_RPC_OK) {
6153 work->aux_payload_buf =
6154 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6155 if (!work->aux_payload_buf) {
6160 memcpy(work->aux_payload_buf, rpc_resp->payload,
6161 rpc_resp->payload_sz);
6163 nbytes = rpc_resp->payload_sz;
6164 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6165 work->aux_payload_sz = nbytes;
6169 rsp->StructureSize = cpu_to_le16(17);
6170 rsp->DataOffset = 80;
6172 rsp->DataLength = cpu_to_le32(nbytes);
6173 rsp->DataRemaining = 0;
6175 inc_rfc1001_len(work->response_buf, nbytes);
6179 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6180 smb2_set_err_rsp(work);
6185 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6186 struct smb2_buffer_desc_v1 *desc,
6188 __le16 ChannelInfoLength)
6190 unsigned int i, ch_count;
6192 if (work->conn->dialect == SMB30_PROT_ID &&
6193 Channel != SMB2_CHANNEL_RDMA_V1)
6196 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6197 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6198 for (i = 0; i < ch_count; i++) {
6199 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6201 le32_to_cpu(desc[i].token),
6202 le32_to_cpu(desc[i].length));
6208 work->need_invalidate_rkey =
6209 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6210 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6211 work->remote_key = le32_to_cpu(desc->token);
6215 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6216 struct smb2_read_req *req, void *data_buf,
6221 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6222 (struct smb2_buffer_desc_v1 *)
6223 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6224 le16_to_cpu(req->ReadChannelInfoLength));
6232 * smb2_read() - handler for smb2 read from file
6233 * @work: smb work containing read command buffer
6235 * Return: 0 on success, otherwise error
6237 int smb2_read(struct ksmbd_work *work)
6239 struct ksmbd_conn *conn = work->conn;
6240 struct smb2_read_req *req;
6241 struct smb2_read_rsp *rsp;
6242 struct ksmbd_file *fp = NULL;
6244 size_t length, mincount;
6245 ssize_t nbytes = 0, remain_bytes = 0;
6247 bool is_rdma_channel = false;
6248 unsigned int max_read_size = conn->vals->max_read_size;
6250 WORK_BUFFERS(work, req, rsp);
6252 if (test_share_config_flag(work->tcon->share_conf,
6253 KSMBD_SHARE_FLAG_PIPE)) {
6254 ksmbd_debug(SMB, "IPC pipe read request\n");
6255 return smb2_read_pipe(work);
6258 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6259 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6260 is_rdma_channel = true;
6261 max_read_size = get_smbd_max_read_write_size();
6264 if (is_rdma_channel == true) {
6265 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6267 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6271 err = smb2_set_remote_key_for_rdma(work,
6272 (struct smb2_buffer_desc_v1 *)
6273 ((char *)req + ch_offset),
6275 req->ReadChannelInfoLength);
6280 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6286 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6287 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6292 offset = le64_to_cpu(req->Offset);
6293 length = le32_to_cpu(req->Length);
6294 mincount = le32_to_cpu(req->MinimumCount);
6296 if (length > max_read_size) {
6297 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6303 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6304 fp->filp, offset, length);
6306 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6307 if (!work->aux_payload_buf) {
6312 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6318 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6319 kvfree(work->aux_payload_buf);
6320 work->aux_payload_buf = NULL;
6321 rsp->hdr.Status = STATUS_END_OF_FILE;
6322 smb2_set_err_rsp(work);
6323 ksmbd_fd_put(work, fp);
6327 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6328 nbytes, offset, mincount);
6330 if (is_rdma_channel == true) {
6331 /* write data to the client using rdma channel */
6332 remain_bytes = smb2_read_rdma_channel(work, req,
6333 work->aux_payload_buf,
6335 kvfree(work->aux_payload_buf);
6336 work->aux_payload_buf = NULL;
6339 if (remain_bytes < 0) {
6340 err = (int)remain_bytes;
6345 rsp->StructureSize = cpu_to_le16(17);
6346 rsp->DataOffset = 80;
6348 rsp->DataLength = cpu_to_le32(nbytes);
6349 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6351 inc_rfc1001_len(work->response_buf, 16);
6352 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6353 work->aux_payload_sz = nbytes;
6354 inc_rfc1001_len(work->response_buf, nbytes);
6355 ksmbd_fd_put(work, fp);
6361 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6362 else if (err == -EAGAIN)
6363 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6364 else if (err == -ENOENT)
6365 rsp->hdr.Status = STATUS_FILE_CLOSED;
6366 else if (err == -EACCES)
6367 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6368 else if (err == -ESHARE)
6369 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6370 else if (err == -EINVAL)
6371 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6373 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6375 smb2_set_err_rsp(work);
6377 ksmbd_fd_put(work, fp);
6382 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6383 * @work: smb work containing write IPC pipe command buffer
6385 * Return: 0 on success, otherwise error
6387 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6389 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6390 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6391 struct ksmbd_rpc_command *rpc_resp;
6393 int err = 0, ret = 0;
6397 length = le32_to_cpu(req->Length);
6398 id = req->VolatileFileId;
6400 if ((u64)le16_to_cpu(req->DataOffset) + length >
6401 get_rfc1002_len(work->request_buf)) {
6402 pr_err("invalid write data offset %u, smb_len %u\n",
6403 le16_to_cpu(req->DataOffset),
6404 get_rfc1002_len(work->request_buf));
6409 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6410 le16_to_cpu(req->DataOffset));
6412 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6414 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6415 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6417 smb2_set_err_rsp(work);
6420 if (rpc_resp->flags != KSMBD_RPC_OK) {
6421 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6422 smb2_set_err_rsp(work);
6429 rsp->StructureSize = cpu_to_le16(17);
6430 rsp->DataOffset = 0;
6432 rsp->DataLength = cpu_to_le32(length);
6433 rsp->DataRemaining = 0;
6435 inc_rfc1001_len(work->response_buf, 16);
6439 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6440 smb2_set_err_rsp(work);
6446 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6447 struct smb2_write_req *req,
6448 struct ksmbd_file *fp,
6449 loff_t offset, size_t length, bool sync)
6455 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6459 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6460 (struct smb2_buffer_desc_v1 *)
6461 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6462 le16_to_cpu(req->WriteChannelInfoLength));
6468 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6477 * smb2_write() - handler for smb2 write from file
6478 * @work: smb work containing write command buffer
6480 * Return: 0 on success, otherwise error
6482 int smb2_write(struct ksmbd_work *work)
6484 struct smb2_write_req *req;
6485 struct smb2_write_rsp *rsp;
6486 struct ksmbd_file *fp = NULL;
6491 bool writethrough = false, is_rdma_channel = false;
6493 unsigned int max_write_size = work->conn->vals->max_write_size;
6495 WORK_BUFFERS(work, req, rsp);
6497 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6498 ksmbd_debug(SMB, "IPC pipe write request\n");
6499 return smb2_write_pipe(work);
6502 offset = le64_to_cpu(req->Offset);
6503 length = le32_to_cpu(req->Length);
6505 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6506 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6507 is_rdma_channel = true;
6508 max_write_size = get_smbd_max_read_write_size();
6509 length = le32_to_cpu(req->RemainingBytes);
6512 if (is_rdma_channel == true) {
6513 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6515 if (req->Length != 0 || req->DataOffset != 0 ||
6516 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6520 err = smb2_set_remote_key_for_rdma(work,
6521 (struct smb2_buffer_desc_v1 *)
6522 ((char *)req + ch_offset),
6524 req->WriteChannelInfoLength);
6529 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6530 ksmbd_debug(SMB, "User does not have write permission\n");
6535 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6541 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6542 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6547 if (length > max_write_size) {
6548 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6554 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6555 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6556 writethrough = true;
6558 if (is_rdma_channel == false) {
6559 if (le16_to_cpu(req->DataOffset) <
6560 offsetof(struct smb2_write_req, Buffer)) {
6565 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6566 le16_to_cpu(req->DataOffset));
6568 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6569 fp->filp, offset, length);
6570 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6571 writethrough, &nbytes);
6575 /* read data from the client using rdma channel, and
6578 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6586 rsp->StructureSize = cpu_to_le16(17);
6587 rsp->DataOffset = 0;
6589 rsp->DataLength = cpu_to_le32(nbytes);
6590 rsp->DataRemaining = 0;
6592 inc_rfc1001_len(work->response_buf, 16);
6593 ksmbd_fd_put(work, fp);
6598 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6599 else if (err == -ENOSPC || err == -EFBIG)
6600 rsp->hdr.Status = STATUS_DISK_FULL;
6601 else if (err == -ENOENT)
6602 rsp->hdr.Status = STATUS_FILE_CLOSED;
6603 else if (err == -EACCES)
6604 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6605 else if (err == -ESHARE)
6606 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6607 else if (err == -EINVAL)
6608 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6610 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6612 smb2_set_err_rsp(work);
6613 ksmbd_fd_put(work, fp);
6618 * smb2_flush() - handler for smb2 flush file - fsync
6619 * @work: smb work containing flush command buffer
6621 * Return: 0 on success, otherwise error
6623 int smb2_flush(struct ksmbd_work *work)
6625 struct smb2_flush_req *req;
6626 struct smb2_flush_rsp *rsp;
6629 WORK_BUFFERS(work, req, rsp);
6631 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6633 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6637 rsp->StructureSize = cpu_to_le16(4);
6639 inc_rfc1001_len(work->response_buf, 4);
6644 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6645 smb2_set_err_rsp(work);
6652 * smb2_cancel() - handler for smb2 cancel command
6653 * @work: smb work containing cancel command buffer
6655 * Return: 0 on success, otherwise error
6657 int smb2_cancel(struct ksmbd_work *work)
6659 struct ksmbd_conn *conn = work->conn;
6660 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6661 struct smb2_hdr *chdr;
6662 struct ksmbd_work *iter;
6663 struct list_head *command_list;
6665 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6666 hdr->MessageId, hdr->Flags);
6668 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6669 command_list = &conn->async_requests;
6671 spin_lock(&conn->request_lock);
6672 list_for_each_entry(iter, command_list,
6673 async_request_entry) {
6674 chdr = smb2_get_msg(iter->request_buf);
6676 if (iter->async_id !=
6677 le64_to_cpu(hdr->Id.AsyncId))
6681 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6682 le64_to_cpu(hdr->Id.AsyncId),
6683 le16_to_cpu(chdr->Command));
6684 iter->state = KSMBD_WORK_CANCELLED;
6685 if (iter->cancel_fn)
6686 iter->cancel_fn(iter->cancel_argv);
6689 spin_unlock(&conn->request_lock);
6691 command_list = &conn->requests;
6693 spin_lock(&conn->request_lock);
6694 list_for_each_entry(iter, command_list, request_entry) {
6695 chdr = smb2_get_msg(iter->request_buf);
6697 if (chdr->MessageId != hdr->MessageId ||
6702 "smb2 with mid %llu cancelled command = 0x%x\n",
6703 le64_to_cpu(hdr->MessageId),
6704 le16_to_cpu(chdr->Command));
6705 iter->state = KSMBD_WORK_CANCELLED;
6708 spin_unlock(&conn->request_lock);
6711 /* For SMB2_CANCEL command itself send no response*/
6712 work->send_no_response = 1;
6716 struct file_lock *smb_flock_init(struct file *f)
6718 struct file_lock *fl;
6720 fl = locks_alloc_lock();
6724 locks_init_lock(fl);
6727 fl->fl_pid = current->tgid;
6729 fl->fl_flags = FL_POSIX;
6731 fl->fl_lmops = NULL;
6737 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6741 /* Checking for wrong flag combination during lock request*/
6743 case SMB2_LOCKFLAG_SHARED:
6744 ksmbd_debug(SMB, "received shared request\n");
6746 flock->fl_type = F_RDLCK;
6747 flock->fl_flags |= FL_SLEEP;
6749 case SMB2_LOCKFLAG_EXCLUSIVE:
6750 ksmbd_debug(SMB, "received exclusive request\n");
6752 flock->fl_type = F_WRLCK;
6753 flock->fl_flags |= FL_SLEEP;
6755 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6757 "received shared & fail immediately request\n");
6759 flock->fl_type = F_RDLCK;
6761 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6763 "received exclusive & fail immediately request\n");
6765 flock->fl_type = F_WRLCK;
6767 case SMB2_LOCKFLAG_UNLOCK:
6768 ksmbd_debug(SMB, "received unlock request\n");
6769 flock->fl_type = F_UNLCK;
6777 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6778 unsigned int cmd, int flags,
6779 struct list_head *lock_list)
6781 struct ksmbd_lock *lock;
6783 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6789 lock->start = flock->fl_start;
6790 lock->end = flock->fl_end;
6791 lock->flags = flags;
6792 if (lock->start == lock->end)
6794 INIT_LIST_HEAD(&lock->clist);
6795 INIT_LIST_HEAD(&lock->flist);
6796 INIT_LIST_HEAD(&lock->llist);
6797 list_add_tail(&lock->llist, lock_list);
6802 static void smb2_remove_blocked_lock(void **argv)
6804 struct file_lock *flock = (struct file_lock *)argv[0];
6806 ksmbd_vfs_posix_lock_unblock(flock);
6807 wake_up(&flock->fl_wait);
6810 static inline bool lock_defer_pending(struct file_lock *fl)
6812 /* check pending lock waiters */
6813 return waitqueue_active(&fl->fl_wait);
6817 * smb2_lock() - handler for smb2 file lock command
6818 * @work: smb work containing lock command buffer
6820 * Return: 0 on success, otherwise error
6822 int smb2_lock(struct ksmbd_work *work)
6824 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6825 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6826 struct smb2_lock_element *lock_ele;
6827 struct ksmbd_file *fp = NULL;
6828 struct file_lock *flock = NULL;
6829 struct file *filp = NULL;
6833 int err = -EIO, i, rc = 0;
6834 u64 lock_start, lock_length;
6835 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6836 struct ksmbd_conn *conn;
6838 LIST_HEAD(lock_list);
6839 LIST_HEAD(rollback_list);
6842 ksmbd_debug(SMB, "Received lock request\n");
6843 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6845 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6851 lock_count = le16_to_cpu(req->LockCount);
6852 lock_ele = req->locks;
6854 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6860 for (i = 0; i < lock_count; i++) {
6861 flags = le32_to_cpu(lock_ele[i].Flags);
6863 flock = smb_flock_init(filp);
6867 cmd = smb2_set_flock_flags(flock, flags);
6869 lock_start = le64_to_cpu(lock_ele[i].Offset);
6870 lock_length = le64_to_cpu(lock_ele[i].Length);
6871 if (lock_start > U64_MAX - lock_length) {
6872 pr_err("Invalid lock range requested\n");
6873 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6877 if (lock_start > OFFSET_MAX)
6878 flock->fl_start = OFFSET_MAX;
6880 flock->fl_start = lock_start;
6882 lock_length = le64_to_cpu(lock_ele[i].Length);
6883 if (lock_length > OFFSET_MAX - flock->fl_start)
6884 lock_length = OFFSET_MAX - flock->fl_start;
6886 flock->fl_end = flock->fl_start + lock_length;
6888 if (flock->fl_end < flock->fl_start) {
6890 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6891 flock->fl_end, flock->fl_start);
6892 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6896 /* Check conflict locks in one request */
6897 list_for_each_entry(cmp_lock, &lock_list, llist) {
6898 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6899 cmp_lock->fl->fl_end >= flock->fl_end) {
6900 if (cmp_lock->fl->fl_type != F_UNLCK &&
6901 flock->fl_type != F_UNLCK) {
6902 pr_err("conflict two locks in one request\n");
6909 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6916 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6917 if (smb_lock->cmd < 0) {
6922 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6927 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6928 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6929 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6930 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6935 prior_lock = smb_lock->flags;
6937 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6938 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6942 /* check locks in connection list */
6943 read_lock(&conn_list_lock);
6944 list_for_each_entry(conn, &conn_list, conns_list) {
6945 spin_lock(&conn->llist_lock);
6946 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6947 if (file_inode(cmp_lock->fl->fl_file) !=
6948 file_inode(smb_lock->fl->fl_file))
6951 if (smb_lock->fl->fl_type == F_UNLCK) {
6952 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6953 cmp_lock->start == smb_lock->start &&
6954 cmp_lock->end == smb_lock->end &&
6955 !lock_defer_pending(cmp_lock->fl)) {
6957 list_del(&cmp_lock->flist);
6958 list_del(&cmp_lock->clist);
6959 spin_unlock(&conn->llist_lock);
6960 read_unlock(&conn_list_lock);
6962 locks_free_lock(cmp_lock->fl);
6969 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6970 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6973 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6977 /* check zero byte lock range */
6978 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6979 cmp_lock->start > smb_lock->start &&
6980 cmp_lock->start < smb_lock->end) {
6981 spin_unlock(&conn->llist_lock);
6982 read_unlock(&conn_list_lock);
6983 pr_err("previous lock conflict with zero byte lock range\n");
6987 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6988 smb_lock->start > cmp_lock->start &&
6989 smb_lock->start < cmp_lock->end) {
6990 spin_unlock(&conn->llist_lock);
6991 read_unlock(&conn_list_lock);
6992 pr_err("current lock conflict with zero byte lock range\n");
6996 if (((cmp_lock->start <= smb_lock->start &&
6997 cmp_lock->end > smb_lock->start) ||
6998 (cmp_lock->start < smb_lock->end &&
6999 cmp_lock->end >= smb_lock->end)) &&
7000 !cmp_lock->zero_len && !smb_lock->zero_len) {
7001 spin_unlock(&conn->llist_lock);
7002 read_unlock(&conn_list_lock);
7003 pr_err("Not allow lock operation on exclusive lock range\n");
7007 spin_unlock(&conn->llist_lock);
7009 read_unlock(&conn_list_lock);
7011 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7012 pr_err("Try to unlock nolocked range\n");
7013 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7018 if (smb_lock->zero_len) {
7023 flock = smb_lock->fl;
7024 list_del(&smb_lock->llist);
7026 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7028 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7030 ksmbd_debug(SMB, "File unlocked\n");
7031 } else if (rc == -ENOENT) {
7032 rsp->hdr.Status = STATUS_NOT_LOCKED;
7035 locks_free_lock(flock);
7038 if (rc == FILE_LOCK_DEFERRED) {
7042 "would have to wait for getting lock\n");
7043 spin_lock(&work->conn->llist_lock);
7044 list_add_tail(&smb_lock->clist,
7045 &work->conn->lock_list);
7046 spin_unlock(&work->conn->llist_lock);
7047 list_add(&smb_lock->llist, &rollback_list);
7049 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7056 rc = setup_async_work(work,
7057 smb2_remove_blocked_lock,
7063 spin_lock(&fp->f_lock);
7064 list_add(&work->fp_entry, &fp->blocked_works);
7065 spin_unlock(&fp->f_lock);
7067 smb2_send_interim_resp(work, STATUS_PENDING);
7069 ksmbd_vfs_posix_lock_wait(flock);
7071 spin_lock(&work->conn->request_lock);
7072 spin_lock(&fp->f_lock);
7073 list_del(&work->fp_entry);
7074 work->cancel_fn = NULL;
7076 spin_unlock(&fp->f_lock);
7077 spin_unlock(&work->conn->request_lock);
7079 if (work->state != KSMBD_WORK_ACTIVE) {
7080 list_del(&smb_lock->llist);
7081 spin_lock(&work->conn->llist_lock);
7082 list_del(&smb_lock->clist);
7083 spin_unlock(&work->conn->llist_lock);
7084 locks_free_lock(flock);
7086 if (work->state == KSMBD_WORK_CANCELLED) {
7090 smb2_send_interim_resp(work,
7092 work->send_no_response = 1;
7095 init_smb2_rsp_hdr(work);
7096 smb2_set_err_rsp(work);
7098 STATUS_RANGE_NOT_LOCKED;
7103 list_del(&smb_lock->llist);
7104 spin_lock(&work->conn->llist_lock);
7105 list_del(&smb_lock->clist);
7106 spin_unlock(&work->conn->llist_lock);
7110 spin_lock(&work->conn->llist_lock);
7111 list_add_tail(&smb_lock->clist,
7112 &work->conn->lock_list);
7113 list_add_tail(&smb_lock->flist,
7115 spin_unlock(&work->conn->llist_lock);
7116 list_add(&smb_lock->llist, &rollback_list);
7117 ksmbd_debug(SMB, "successful in taking lock\n");
7124 if (atomic_read(&fp->f_ci->op_count) > 1)
7125 smb_break_all_oplock(work, fp);
7127 rsp->StructureSize = cpu_to_le16(4);
7128 ksmbd_debug(SMB, "successful in taking lock\n");
7129 rsp->hdr.Status = STATUS_SUCCESS;
7131 inc_rfc1001_len(work->response_buf, 4);
7132 ksmbd_fd_put(work, fp);
7136 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7137 locks_free_lock(smb_lock->fl);
7138 list_del(&smb_lock->llist);
7142 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7143 struct file_lock *rlock = NULL;
7145 rlock = smb_flock_init(filp);
7146 rlock->fl_type = F_UNLCK;
7147 rlock->fl_start = smb_lock->start;
7148 rlock->fl_end = smb_lock->end;
7150 rc = vfs_lock_file(filp, 0, rlock, NULL);
7152 pr_err("rollback unlock fail : %d\n", rc);
7154 list_del(&smb_lock->llist);
7155 spin_lock(&work->conn->llist_lock);
7156 if (!list_empty(&smb_lock->flist))
7157 list_del(&smb_lock->flist);
7158 list_del(&smb_lock->clist);
7159 spin_unlock(&work->conn->llist_lock);
7161 locks_free_lock(smb_lock->fl);
7162 locks_free_lock(rlock);
7166 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7168 if (!rsp->hdr.Status) {
7170 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7171 else if (err == -ENOMEM)
7172 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7173 else if (err == -ENOENT)
7174 rsp->hdr.Status = STATUS_FILE_CLOSED;
7176 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7179 smb2_set_err_rsp(work);
7180 ksmbd_fd_put(work, fp);
7184 static int fsctl_copychunk(struct ksmbd_work *work,
7185 struct copychunk_ioctl_req *ci_req,
7186 unsigned int cnt_code,
7187 unsigned int input_count,
7188 unsigned long long volatile_id,
7189 unsigned long long persistent_id,
7190 struct smb2_ioctl_rsp *rsp)
7192 struct copychunk_ioctl_rsp *ci_rsp;
7193 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7194 struct srv_copychunk *chunks;
7195 unsigned int i, chunk_count, chunk_count_written = 0;
7196 unsigned int chunk_size_written = 0;
7197 loff_t total_size_written = 0;
7200 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7202 rsp->VolatileFileId = volatile_id;
7203 rsp->PersistentFileId = persistent_id;
7204 ci_rsp->ChunksWritten =
7205 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7206 ci_rsp->ChunkBytesWritten =
7207 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7208 ci_rsp->TotalBytesWritten =
7209 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7211 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7212 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7213 if (chunk_count == 0)
7215 total_size_written = 0;
7217 /* verify the SRV_COPYCHUNK_COPY packet */
7218 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7219 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7220 chunk_count * sizeof(struct srv_copychunk)) {
7221 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7225 for (i = 0; i < chunk_count; i++) {
7226 if (le32_to_cpu(chunks[i].Length) == 0 ||
7227 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7229 total_size_written += le32_to_cpu(chunks[i].Length);
7232 if (i < chunk_count ||
7233 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7234 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7238 src_fp = ksmbd_lookup_foreign_fd(work,
7239 le64_to_cpu(ci_req->ResumeKey[0]));
7240 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7243 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7244 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7249 rsp->hdr.Status = STATUS_FILE_CLOSED;
7254 * FILE_READ_DATA should only be included in
7255 * the FSCTL_COPYCHUNK case
7257 if (cnt_code == FSCTL_COPYCHUNK &&
7258 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7259 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7263 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7264 chunks, chunk_count,
7265 &chunk_count_written,
7266 &chunk_size_written,
7267 &total_size_written);
7270 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7272 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7273 else if (ret == -EBADF)
7274 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7275 else if (ret == -EFBIG || ret == -ENOSPC)
7276 rsp->hdr.Status = STATUS_DISK_FULL;
7277 else if (ret == -EINVAL)
7278 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7279 else if (ret == -EISDIR)
7280 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7281 else if (ret == -E2BIG)
7282 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7284 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7287 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7288 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7289 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7291 ksmbd_fd_put(work, src_fp);
7292 ksmbd_fd_put(work, dst_fp);
7296 static __be32 idev_ipv4_address(struct in_device *idev)
7300 struct in_ifaddr *ifa;
7303 in_dev_for_each_ifa_rcu(ifa, idev) {
7304 if (ifa->ifa_flags & IFA_F_SECONDARY)
7307 addr = ifa->ifa_address;
7314 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7315 struct smb2_ioctl_rsp *rsp,
7316 unsigned int out_buf_len)
7318 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7320 struct net_device *netdev;
7321 struct sockaddr_storage_rsp *sockaddr_storage;
7323 unsigned long long speed;
7326 for_each_netdev(&init_net, netdev) {
7327 bool ipv4_set = false;
7329 if (netdev->type == ARPHRD_LOOPBACK)
7332 flags = dev_get_flags(netdev);
7333 if (!(flags & IFF_RUNNING))
7337 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7342 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7343 &rsp->Buffer[nbytes];
7344 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7346 nii_rsp->Capability = 0;
7347 if (netdev->real_num_tx_queues > 1)
7348 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7349 if (ksmbd_rdma_capable_netdev(netdev))
7350 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7352 nii_rsp->Next = cpu_to_le32(152);
7353 nii_rsp->Reserved = 0;
7355 if (netdev->ethtool_ops->get_link_ksettings) {
7356 struct ethtool_link_ksettings cmd;
7358 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7359 speed = cmd.base.speed;
7361 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7362 "speed is unknown, defaulting to 1Gb/sec");
7367 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7369 sockaddr_storage = (struct sockaddr_storage_rsp *)
7370 nii_rsp->SockAddr_Storage;
7371 memset(sockaddr_storage, 0, 128);
7374 struct in_device *idev;
7376 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7377 sockaddr_storage->addr4.Port = 0;
7379 idev = __in_dev_get_rtnl(netdev);
7382 sockaddr_storage->addr4.IPv4address =
7383 idev_ipv4_address(idev);
7384 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7388 struct inet6_dev *idev6;
7389 struct inet6_ifaddr *ifa;
7390 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7392 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7393 sockaddr_storage->addr6.Port = 0;
7394 sockaddr_storage->addr6.FlowInfo = 0;
7396 idev6 = __in6_dev_get(netdev);
7400 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7401 if (ifa->flags & (IFA_F_TENTATIVE |
7404 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7407 sockaddr_storage->addr6.ScopeId = 0;
7408 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7413 /* zero if this is last one */
7417 rsp->PersistentFileId = SMB2_NO_FID;
7418 rsp->VolatileFileId = SMB2_NO_FID;
7422 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7423 struct validate_negotiate_info_req *neg_req,
7424 struct validate_negotiate_info_rsp *neg_rsp,
7425 unsigned int in_buf_len)
7430 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7431 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7434 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7435 neg_req->DialectCount);
7436 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7441 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7446 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7451 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7456 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7457 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7458 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7459 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7464 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7465 struct file_allocated_range_buffer *qar_req,
7466 struct file_allocated_range_buffer *qar_rsp,
7467 unsigned int in_count, unsigned int *out_count)
7469 struct ksmbd_file *fp;
7470 loff_t start, length;
7477 start = le64_to_cpu(qar_req->file_offset);
7478 length = le64_to_cpu(qar_req->length);
7480 if (start < 0 || length < 0)
7483 fp = ksmbd_lookup_fd_fast(work, id);
7487 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7488 qar_rsp, in_count, out_count);
7489 if (ret && ret != -E2BIG)
7492 ksmbd_fd_put(work, fp);
7496 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7497 unsigned int out_buf_len,
7498 struct smb2_ioctl_req *req,
7499 struct smb2_ioctl_rsp *rsp)
7501 struct ksmbd_rpc_command *rpc_resp;
7502 char *data_buf = (char *)&req->Buffer[0];
7505 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7506 le32_to_cpu(req->InputCount));
7508 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7510 * set STATUS_SOME_NOT_MAPPED response
7511 * for unknown domain sid.
7513 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7514 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7515 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7517 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7518 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7522 nbytes = rpc_resp->payload_sz;
7523 if (rpc_resp->payload_sz > out_buf_len) {
7524 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7525 nbytes = out_buf_len;
7528 if (!rpc_resp->payload_sz) {
7530 STATUS_UNEXPECTED_IO_ERROR;
7534 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7541 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7542 struct file_sparse *sparse)
7544 struct ksmbd_file *fp;
7545 struct user_namespace *user_ns;
7549 fp = ksmbd_lookup_fd_fast(work, id);
7552 user_ns = file_mnt_user_ns(fp->filp);
7554 old_fattr = fp->f_ci->m_fattr;
7555 if (sparse->SetSparse)
7556 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7558 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7560 if (fp->f_ci->m_fattr != old_fattr &&
7561 test_share_config_flag(work->tcon->share_conf,
7562 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7563 struct xattr_dos_attrib da;
7565 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7566 fp->filp->f_path.dentry, &da);
7570 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7571 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7572 fp->filp->f_path.dentry, &da);
7574 fp->f_ci->m_fattr = old_fattr;
7578 ksmbd_fd_put(work, fp);
7582 static int fsctl_request_resume_key(struct ksmbd_work *work,
7583 struct smb2_ioctl_req *req,
7584 struct resume_key_ioctl_rsp *key_rsp)
7586 struct ksmbd_file *fp;
7588 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7592 memset(key_rsp, 0, sizeof(*key_rsp));
7593 key_rsp->ResumeKey[0] = req->VolatileFileId;
7594 key_rsp->ResumeKey[1] = req->PersistentFileId;
7595 ksmbd_fd_put(work, fp);
7601 * smb2_ioctl() - handler for smb2 ioctl command
7602 * @work: smb work containing ioctl command buffer
7604 * Return: 0 on success, otherwise error
7606 int smb2_ioctl(struct ksmbd_work *work)
7608 struct smb2_ioctl_req *req;
7609 struct smb2_ioctl_rsp *rsp;
7610 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7611 u64 id = KSMBD_NO_FID;
7612 struct ksmbd_conn *conn = work->conn;
7615 if (work->next_smb2_rcv_hdr_off) {
7616 req = ksmbd_req_buf_next(work);
7617 rsp = ksmbd_resp_buf_next(work);
7618 if (!has_file_id(req->VolatileFileId)) {
7619 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7620 work->compound_fid);
7621 id = work->compound_fid;
7624 req = smb2_get_msg(work->request_buf);
7625 rsp = smb2_get_msg(work->response_buf);
7628 if (!has_file_id(id))
7629 id = req->VolatileFileId;
7631 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7632 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7636 cnt_code = le32_to_cpu(req->CtlCode);
7637 ret = smb2_calc_max_out_buf_len(work, 48,
7638 le32_to_cpu(req->MaxOutputResponse));
7640 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7643 out_buf_len = (unsigned int)ret;
7644 in_buf_len = le32_to_cpu(req->InputCount);
7647 case FSCTL_DFS_GET_REFERRALS:
7648 case FSCTL_DFS_GET_REFERRALS_EX:
7649 /* Not support DFS yet */
7650 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7652 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7654 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7656 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7657 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7661 * TODO: This is dummy implementation to pass smbtorture
7662 * Need to check correct response later
7664 memset(obj_buf->ObjectId, 0x0, 16);
7665 memset(obj_buf->BirthVolumeId, 0x0, 16);
7666 memset(obj_buf->BirthObjectId, 0x0, 16);
7667 memset(obj_buf->DomainId, 0x0, 16);
7671 case FSCTL_PIPE_TRANSCEIVE:
7672 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7673 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7675 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7676 if (conn->dialect < SMB30_PROT_ID) {
7681 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7687 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7692 ret = fsctl_validate_negotiate_info(conn,
7693 (struct validate_negotiate_info_req *)&req->Buffer[0],
7694 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7699 nbytes = sizeof(struct validate_negotiate_info_rsp);
7700 rsp->PersistentFileId = SMB2_NO_FID;
7701 rsp->VolatileFileId = SMB2_NO_FID;
7703 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7704 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7709 case FSCTL_REQUEST_RESUME_KEY:
7710 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7715 ret = fsctl_request_resume_key(work, req,
7716 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7719 rsp->PersistentFileId = req->PersistentFileId;
7720 rsp->VolatileFileId = req->VolatileFileId;
7721 nbytes = sizeof(struct resume_key_ioctl_rsp);
7723 case FSCTL_COPYCHUNK:
7724 case FSCTL_COPYCHUNK_WRITE:
7725 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7727 "User does not have write permission\n");
7732 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7737 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7742 nbytes = sizeof(struct copychunk_ioctl_rsp);
7743 rsp->VolatileFileId = req->VolatileFileId;
7744 rsp->PersistentFileId = req->PersistentFileId;
7745 fsctl_copychunk(work,
7746 (struct copychunk_ioctl_req *)&req->Buffer[0],
7747 le32_to_cpu(req->CtlCode),
7748 le32_to_cpu(req->InputCount),
7749 req->VolatileFileId,
7750 req->PersistentFileId,
7753 case FSCTL_SET_SPARSE:
7754 if (in_buf_len < sizeof(struct file_sparse)) {
7759 ret = fsctl_set_sparse(work, id,
7760 (struct file_sparse *)&req->Buffer[0]);
7764 case FSCTL_SET_ZERO_DATA:
7766 struct file_zero_data_information *zero_data;
7767 struct ksmbd_file *fp;
7768 loff_t off, len, bfz;
7770 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7772 "User does not have write permission\n");
7777 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7783 (struct file_zero_data_information *)&req->Buffer[0];
7785 off = le64_to_cpu(zero_data->FileOffset);
7786 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7787 if (off < 0 || bfz < 0 || off > bfz) {
7794 fp = ksmbd_lookup_fd_fast(work, id);
7800 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7801 ksmbd_fd_put(work, fp);
7807 case FSCTL_QUERY_ALLOCATED_RANGES:
7808 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7813 ret = fsctl_query_allocated_ranges(work, id,
7814 (struct file_allocated_range_buffer *)&req->Buffer[0],
7815 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7817 sizeof(struct file_allocated_range_buffer), &nbytes);
7818 if (ret == -E2BIG) {
7819 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7820 } else if (ret < 0) {
7825 nbytes *= sizeof(struct file_allocated_range_buffer);
7827 case FSCTL_GET_REPARSE_POINT:
7829 struct reparse_data_buffer *reparse_ptr;
7830 struct ksmbd_file *fp;
7832 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7833 fp = ksmbd_lookup_fd_fast(work, id);
7835 pr_err("not found fp!!\n");
7840 reparse_ptr->ReparseTag =
7841 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7842 reparse_ptr->ReparseDataLength = 0;
7843 ksmbd_fd_put(work, fp);
7844 nbytes = sizeof(struct reparse_data_buffer);
7847 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7849 struct ksmbd_file *fp_in, *fp_out = NULL;
7850 struct duplicate_extents_to_file *dup_ext;
7851 loff_t src_off, dst_off, length, cloned;
7853 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7858 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7860 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7861 dup_ext->PersistentFileHandle);
7863 pr_err("not found file handle in duplicate extent to file\n");
7868 fp_out = ksmbd_lookup_fd_fast(work, id);
7870 pr_err("not found fp\n");
7875 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7876 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7877 length = le64_to_cpu(dup_ext->ByteCount);
7879 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7880 * should fall back to vfs_copy_file_range(). This could be
7881 * beneficial when re-exporting nfs/smb mount, but note that
7882 * this can result in partial copy that returns an error status.
7883 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7884 * fall back to vfs_copy_file_range(), should be avoided when
7885 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7887 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7888 fp_out->filp, dst_off, length, 0);
7889 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7892 } else if (cloned != length) {
7893 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7894 fp_out->filp, dst_off,
7896 if (cloned != length) {
7905 ksmbd_fd_put(work, fp_in);
7906 ksmbd_fd_put(work, fp_out);
7912 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7918 rsp->CtlCode = cpu_to_le32(cnt_code);
7919 rsp->InputCount = cpu_to_le32(0);
7920 rsp->InputOffset = cpu_to_le32(112);
7921 rsp->OutputOffset = cpu_to_le32(112);
7922 rsp->OutputCount = cpu_to_le32(nbytes);
7923 rsp->StructureSize = cpu_to_le16(49);
7924 rsp->Reserved = cpu_to_le16(0);
7925 rsp->Flags = cpu_to_le32(0);
7926 rsp->Reserved2 = cpu_to_le32(0);
7927 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7933 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7934 else if (ret == -ENOENT)
7935 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7936 else if (ret == -EOPNOTSUPP)
7937 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7938 else if (ret == -ENOSPC)
7939 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7940 else if (ret < 0 || rsp->hdr.Status == 0)
7941 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7942 smb2_set_err_rsp(work);
7947 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7948 * @work: smb work containing oplock break command buffer
7952 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7954 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7955 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7956 struct ksmbd_file *fp;
7957 struct oplock_info *opinfo = NULL;
7960 u64 volatile_id, persistent_id;
7961 char req_oplevel = 0, rsp_oplevel = 0;
7962 unsigned int oplock_change_type;
7964 volatile_id = req->VolatileFid;
7965 persistent_id = req->PersistentFid;
7966 req_oplevel = req->OplockLevel;
7967 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7968 volatile_id, persistent_id, req_oplevel);
7970 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7972 rsp->hdr.Status = STATUS_FILE_CLOSED;
7973 smb2_set_err_rsp(work);
7977 opinfo = opinfo_get(fp);
7979 pr_err("unexpected null oplock_info\n");
7980 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7981 smb2_set_err_rsp(work);
7982 ksmbd_fd_put(work, fp);
7986 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7987 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7991 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7992 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7993 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7997 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7998 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7999 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8000 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8001 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8002 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8003 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8004 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8005 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8006 oplock_change_type = OPLOCK_READ_TO_NONE;
8007 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8008 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8009 err = STATUS_INVALID_DEVICE_STATE;
8010 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8011 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8012 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8013 oplock_change_type = OPLOCK_WRITE_TO_READ;
8014 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8015 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8016 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8017 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8018 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8019 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8020 oplock_change_type = OPLOCK_READ_TO_NONE;
8022 oplock_change_type = 0;
8025 oplock_change_type = 0;
8028 switch (oplock_change_type) {
8029 case OPLOCK_WRITE_TO_READ:
8030 ret = opinfo_write_to_read(opinfo);
8031 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8033 case OPLOCK_WRITE_TO_NONE:
8034 ret = opinfo_write_to_none(opinfo);
8035 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8037 case OPLOCK_READ_TO_NONE:
8038 ret = opinfo_read_to_none(opinfo);
8039 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8042 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8043 opinfo->level, rsp_oplevel);
8047 rsp->hdr.Status = err;
8052 ksmbd_fd_put(work, fp);
8053 opinfo->op_state = OPLOCK_STATE_NONE;
8054 wake_up_interruptible_all(&opinfo->oplock_q);
8056 rsp->StructureSize = cpu_to_le16(24);
8057 rsp->OplockLevel = rsp_oplevel;
8060 rsp->VolatileFid = volatile_id;
8061 rsp->PersistentFid = persistent_id;
8062 inc_rfc1001_len(work->response_buf, 24);
8066 opinfo->op_state = OPLOCK_STATE_NONE;
8067 wake_up_interruptible_all(&opinfo->oplock_q);
8070 ksmbd_fd_put(work, fp);
8071 smb2_set_err_rsp(work);
8074 static int check_lease_state(struct lease *lease, __le32 req_state)
8076 if ((lease->new_state ==
8077 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8078 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8079 lease->new_state = req_state;
8083 if (lease->new_state == req_state)
8090 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8091 * @work: smb work containing lease break command buffer
8095 static void smb21_lease_break_ack(struct ksmbd_work *work)
8097 struct ksmbd_conn *conn = work->conn;
8098 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8099 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8100 struct oplock_info *opinfo;
8103 unsigned int lease_change_type;
8105 struct lease *lease;
8107 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8108 le32_to_cpu(req->LeaseState));
8109 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8111 ksmbd_debug(OPLOCK, "file not opened\n");
8112 smb2_set_err_rsp(work);
8113 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8116 lease = opinfo->o_lease;
8118 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8119 pr_err("unexpected lease break state 0x%x\n",
8121 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8125 if (check_lease_state(lease, req->LeaseState)) {
8126 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8128 "req lease state: 0x%x, expected state: 0x%x\n",
8129 req->LeaseState, lease->new_state);
8133 if (!atomic_read(&opinfo->breaking_cnt)) {
8134 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8138 /* check for bad lease state */
8139 if (req->LeaseState &
8140 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8141 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8142 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8143 lease_change_type = OPLOCK_WRITE_TO_NONE;
8145 lease_change_type = OPLOCK_READ_TO_NONE;
8146 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8147 le32_to_cpu(lease->state),
8148 le32_to_cpu(req->LeaseState));
8149 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8150 req->LeaseState != SMB2_LEASE_NONE_LE) {
8151 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8152 lease_change_type = OPLOCK_READ_TO_NONE;
8153 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8154 le32_to_cpu(lease->state),
8155 le32_to_cpu(req->LeaseState));
8157 /* valid lease state changes */
8158 err = STATUS_INVALID_DEVICE_STATE;
8159 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8160 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8161 lease_change_type = OPLOCK_WRITE_TO_NONE;
8163 lease_change_type = OPLOCK_READ_TO_NONE;
8164 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8165 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8166 lease_change_type = OPLOCK_WRITE_TO_READ;
8168 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8170 lease_change_type = 0;
8174 switch (lease_change_type) {
8175 case OPLOCK_WRITE_TO_READ:
8176 ret = opinfo_write_to_read(opinfo);
8178 case OPLOCK_READ_HANDLE_TO_READ:
8179 ret = opinfo_read_handle_to_read(opinfo);
8181 case OPLOCK_WRITE_TO_NONE:
8182 ret = opinfo_write_to_none(opinfo);
8184 case OPLOCK_READ_TO_NONE:
8185 ret = opinfo_read_to_none(opinfo);
8188 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8189 le32_to_cpu(lease->state),
8190 le32_to_cpu(req->LeaseState));
8193 lease_state = lease->state;
8194 opinfo->op_state = OPLOCK_STATE_NONE;
8195 wake_up_interruptible_all(&opinfo->oplock_q);
8196 atomic_dec(&opinfo->breaking_cnt);
8197 wake_up_interruptible_all(&opinfo->oplock_brk);
8201 rsp->hdr.Status = err;
8205 rsp->StructureSize = cpu_to_le16(36);
8208 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8209 rsp->LeaseState = lease_state;
8210 rsp->LeaseDuration = 0;
8211 inc_rfc1001_len(work->response_buf, 36);
8215 opinfo->op_state = OPLOCK_STATE_NONE;
8216 wake_up_interruptible_all(&opinfo->oplock_q);
8217 atomic_dec(&opinfo->breaking_cnt);
8218 wake_up_interruptible_all(&opinfo->oplock_brk);
8221 smb2_set_err_rsp(work);
8225 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8226 * @work: smb work containing oplock/lease break command buffer
8230 int smb2_oplock_break(struct ksmbd_work *work)
8232 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8233 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8235 switch (le16_to_cpu(req->StructureSize)) {
8236 case OP_BREAK_STRUCT_SIZE_20:
8237 smb20_oplock_break_ack(work);
8239 case OP_BREAK_STRUCT_SIZE_21:
8240 smb21_lease_break_ack(work);
8243 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8244 le16_to_cpu(req->StructureSize));
8245 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8246 smb2_set_err_rsp(work);
8253 * smb2_notify() - handler for smb2 notify request
8254 * @work: smb work containing notify command buffer
8258 int smb2_notify(struct ksmbd_work *work)
8260 struct smb2_change_notify_req *req;
8261 struct smb2_change_notify_rsp *rsp;
8263 WORK_BUFFERS(work, req, rsp);
8265 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8266 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8267 smb2_set_err_rsp(work);
8271 smb2_set_err_rsp(work);
8272 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8277 * smb2_is_sign_req() - handler for checking packet signing status
8278 * @work: smb work containing notify command buffer
8279 * @command: SMB2 command id
8281 * Return: true if packed is signed, false otherwise
8283 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8285 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8287 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8288 command != SMB2_NEGOTIATE_HE &&
8289 command != SMB2_SESSION_SETUP_HE &&
8290 command != SMB2_OPLOCK_BREAK_HE)
8297 * smb2_check_sign_req() - handler for req packet sign processing
8298 * @work: smb work containing notify command buffer
8300 * Return: 1 on success, 0 otherwise
8302 int smb2_check_sign_req(struct ksmbd_work *work)
8304 struct smb2_hdr *hdr;
8305 char signature_req[SMB2_SIGNATURE_SIZE];
8306 char signature[SMB2_HMACSHA256_SIZE];
8310 hdr = smb2_get_msg(work->request_buf);
8311 if (work->next_smb2_rcv_hdr_off)
8312 hdr = ksmbd_req_buf_next(work);
8314 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8315 len = get_rfc1002_len(work->request_buf);
8316 else if (hdr->NextCommand)
8317 len = le32_to_cpu(hdr->NextCommand);
8319 len = get_rfc1002_len(work->request_buf) -
8320 work->next_smb2_rcv_hdr_off;
8322 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8323 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8325 iov[0].iov_base = (char *)&hdr->ProtocolId;
8326 iov[0].iov_len = len;
8328 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8332 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8333 pr_err("bad smb2 signature\n");
8341 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8342 * @work: smb work containing notify command buffer
8345 void smb2_set_sign_rsp(struct ksmbd_work *work)
8347 struct smb2_hdr *hdr;
8348 struct smb2_hdr *req_hdr;
8349 char signature[SMB2_HMACSHA256_SIZE];
8354 hdr = smb2_get_msg(work->response_buf);
8355 if (work->next_smb2_rsp_hdr_off)
8356 hdr = ksmbd_resp_buf_next(work);
8358 req_hdr = ksmbd_req_buf_next(work);
8360 if (!work->next_smb2_rsp_hdr_off) {
8361 len = get_rfc1002_len(work->response_buf);
8362 if (req_hdr->NextCommand)
8363 len = ALIGN(len, 8);
8365 len = get_rfc1002_len(work->response_buf) -
8366 work->next_smb2_rsp_hdr_off;
8367 len = ALIGN(len, 8);
8370 if (req_hdr->NextCommand)
8371 hdr->NextCommand = cpu_to_le32(len);
8373 hdr->Flags |= SMB2_FLAGS_SIGNED;
8374 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8376 iov[0].iov_base = (char *)&hdr->ProtocolId;
8377 iov[0].iov_len = len;
8379 if (work->aux_payload_sz) {
8380 iov[0].iov_len -= work->aux_payload_sz;
8382 iov[1].iov_base = work->aux_payload_buf;
8383 iov[1].iov_len = work->aux_payload_sz;
8387 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8389 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8393 * smb3_check_sign_req() - handler for req packet sign processing
8394 * @work: smb work containing notify command buffer
8396 * Return: 1 on success, 0 otherwise
8398 int smb3_check_sign_req(struct ksmbd_work *work)
8400 struct ksmbd_conn *conn = work->conn;
8402 struct smb2_hdr *hdr;
8403 struct channel *chann;
8404 char signature_req[SMB2_SIGNATURE_SIZE];
8405 char signature[SMB2_CMACAES_SIZE];
8409 hdr = smb2_get_msg(work->request_buf);
8410 if (work->next_smb2_rcv_hdr_off)
8411 hdr = ksmbd_req_buf_next(work);
8413 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8414 len = get_rfc1002_len(work->request_buf);
8415 else if (hdr->NextCommand)
8416 len = le32_to_cpu(hdr->NextCommand);
8418 len = get_rfc1002_len(work->request_buf) -
8419 work->next_smb2_rcv_hdr_off;
8421 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8422 signing_key = work->sess->smb3signingkey;
8424 read_lock(&work->sess->chann_lock);
8425 chann = lookup_chann_list(work->sess, conn);
8427 read_unlock(&work->sess->chann_lock);
8430 signing_key = chann->smb3signingkey;
8431 read_unlock(&work->sess->chann_lock);
8435 pr_err("SMB3 signing key is not generated\n");
8439 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8440 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8441 iov[0].iov_base = (char *)&hdr->ProtocolId;
8442 iov[0].iov_len = len;
8444 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8447 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8448 pr_err("bad smb2 signature\n");
8456 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8457 * @work: smb work containing notify command buffer
8460 void smb3_set_sign_rsp(struct ksmbd_work *work)
8462 struct ksmbd_conn *conn = work->conn;
8463 struct smb2_hdr *req_hdr, *hdr;
8464 struct channel *chann;
8465 char signature[SMB2_CMACAES_SIZE];
8471 hdr = smb2_get_msg(work->response_buf);
8472 if (work->next_smb2_rsp_hdr_off)
8473 hdr = ksmbd_resp_buf_next(work);
8475 req_hdr = ksmbd_req_buf_next(work);
8477 if (!work->next_smb2_rsp_hdr_off) {
8478 len = get_rfc1002_len(work->response_buf);
8479 if (req_hdr->NextCommand)
8480 len = ALIGN(len, 8);
8482 len = get_rfc1002_len(work->response_buf) -
8483 work->next_smb2_rsp_hdr_off;
8484 len = ALIGN(len, 8);
8487 if (conn->binding == false &&
8488 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8489 signing_key = work->sess->smb3signingkey;
8491 read_lock(&work->sess->chann_lock);
8492 chann = lookup_chann_list(work->sess, work->conn);
8494 read_unlock(&work->sess->chann_lock);
8497 signing_key = chann->smb3signingkey;
8498 read_unlock(&work->sess->chann_lock);
8504 if (req_hdr->NextCommand)
8505 hdr->NextCommand = cpu_to_le32(len);
8507 hdr->Flags |= SMB2_FLAGS_SIGNED;
8508 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8509 iov[0].iov_base = (char *)&hdr->ProtocolId;
8510 iov[0].iov_len = len;
8511 if (work->aux_payload_sz) {
8512 iov[0].iov_len -= work->aux_payload_sz;
8513 iov[1].iov_base = work->aux_payload_buf;
8514 iov[1].iov_len = work->aux_payload_sz;
8518 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8519 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8523 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8524 * @work: smb work containing response buffer
8527 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8529 struct ksmbd_conn *conn = work->conn;
8530 struct ksmbd_session *sess = work->sess;
8531 struct smb2_hdr *req, *rsp;
8533 if (conn->dialect != SMB311_PROT_ID)
8536 WORK_BUFFERS(work, req, rsp);
8538 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8540 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8541 conn->preauth_info->Preauth_HashValue);
8543 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8546 if (conn->binding) {
8547 struct preauth_session *preauth_sess;
8549 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8552 hash_value = preauth_sess->Preauth_HashValue;
8554 hash_value = sess->Preauth_HashValue;
8558 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8563 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8565 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8566 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8567 unsigned int orig_len = get_rfc1002_len(old_buf);
8569 /* tr_buf must be cleared by the caller */
8570 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8571 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8572 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8573 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8574 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8575 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8577 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8578 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8579 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8580 inc_rfc1001_len(tr_buf, orig_len);
8583 int smb3_encrypt_resp(struct ksmbd_work *work)
8585 char *buf = work->response_buf;
8588 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8590 if (ARRAY_SIZE(iov) < rq_nvec)
8593 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8597 /* fill transform header */
8598 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8600 iov[0].iov_base = work->tr_buf;
8601 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8602 buf_size += iov[0].iov_len - 4;
8604 iov[1].iov_base = buf + 4;
8605 iov[1].iov_len = get_rfc1002_len(buf);
8606 if (work->aux_payload_sz) {
8607 iov[1].iov_len = work->resp_hdr_sz - 4;
8609 iov[2].iov_base = work->aux_payload_buf;
8610 iov[2].iov_len = work->aux_payload_sz;
8611 buf_size += iov[2].iov_len;
8613 buf_size += iov[1].iov_len;
8614 work->resp_hdr_sz = iov[1].iov_len;
8616 rc = ksmbd_crypt_message(work, iov, rq_nvec, 1);
8620 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8621 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8626 bool smb3_is_transform_hdr(void *buf)
8628 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8630 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8633 int smb3_decrypt_req(struct ksmbd_work *work)
8635 struct ksmbd_session *sess;
8636 char *buf = work->request_buf;
8637 unsigned int pdu_length = get_rfc1002_len(buf);
8639 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8640 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8643 if (buf_data_size < sizeof(struct smb2_hdr)) {
8644 pr_err("Transform message is too small (%u)\n",
8646 return -ECONNABORTED;
8649 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8650 pr_err("Transform message is broken\n");
8651 return -ECONNABORTED;
8654 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8656 pr_err("invalid session id(%llx) in transform header\n",
8657 le64_to_cpu(tr_hdr->SessionId));
8658 return -ECONNABORTED;
8661 iov[0].iov_base = buf;
8662 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8663 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8664 iov[1].iov_len = buf_data_size;
8665 rc = ksmbd_crypt_message(work, iov, 2, 0);
8669 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8670 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8675 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8677 struct ksmbd_conn *conn = work->conn;
8678 struct ksmbd_session *sess = work->sess;
8679 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8681 if (conn->dialect < SMB30_PROT_ID)
8684 if (work->next_smb2_rcv_hdr_off)
8685 rsp = ksmbd_resp_buf_next(work);
8687 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8688 sess->user && !user_guest(sess->user) &&
8689 rsp->Status == STATUS_SUCCESS)