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)
877 __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
879 if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
880 conn->preauth_info->Preauth_HashId =
881 SMB2_PREAUTH_INTEGRITY_SHA512;
882 err = STATUS_SUCCESS;
888 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
889 struct smb2_encryption_neg_context *pneg_ctxt,
892 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
893 int i, cphs_size = cph_cnt * sizeof(__le16);
895 conn->cipher_type = 0;
897 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
899 pr_err("Invalid cipher count(%d)\n", cph_cnt);
903 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
906 for (i = 0; i < cph_cnt; i++) {
907 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
908 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
909 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
910 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
911 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
912 pneg_ctxt->Ciphers[i]);
913 conn->cipher_type = pneg_ctxt->Ciphers[i];
920 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
921 * @conn: smb connection
923 * Return: true if connection should be encrypted, else false
925 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
927 if (!conn->ops->generate_encryptionkey)
931 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
932 * SMB 3.1.1 uses the cipher_type field.
934 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
938 static void decode_compress_ctxt(struct ksmbd_conn *conn,
939 struct smb2_compression_capabilities_context *pneg_ctxt)
941 conn->compress_algorithm = SMB3_COMPRESS_NONE;
944 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
945 struct smb2_signing_capabilities *pneg_ctxt,
948 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
949 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
951 conn->signing_negotiated = false;
953 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
955 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
959 for (i = 0; i < sign_algo_cnt; i++) {
960 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
961 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
962 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
963 pneg_ctxt->SigningAlgorithms[i]);
964 conn->signing_negotiated = true;
965 conn->signing_algorithm =
966 pneg_ctxt->SigningAlgorithms[i];
972 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
973 struct smb2_negotiate_req *req,
976 /* +4 is to account for the RFC1001 len field */
977 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
978 int i = 0, len_of_ctxts;
979 int offset = le32_to_cpu(req->NegotiateContextOffset);
980 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
981 __le32 status = STATUS_INVALID_PARAMETER;
983 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
984 if (len_of_smb <= offset) {
985 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
989 len_of_ctxts = len_of_smb - offset;
991 while (i++ < neg_ctxt_cnt) {
994 /* check that offset is not beyond end of SMB */
995 if (len_of_ctxts == 0)
998 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1001 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1002 clen = le16_to_cpu(pctx->DataLength);
1003 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1006 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1008 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1009 if (conn->preauth_info->Preauth_HashId)
1012 status = decode_preauth_ctxt(conn,
1013 (struct smb2_preauth_neg_context *)pctx);
1014 if (status != STATUS_SUCCESS)
1016 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1018 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1019 if (conn->cipher_type)
1022 decode_encrypt_ctxt(conn,
1023 (struct smb2_encryption_neg_context *)pctx,
1025 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1027 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1028 if (conn->compress_algorithm)
1031 decode_compress_ctxt(conn,
1032 (struct smb2_compression_capabilities_context *)pctx);
1033 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1035 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1036 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1038 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1039 conn->posix_ext_supported = true;
1040 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1042 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1043 decode_sign_cap_ctxt(conn,
1044 (struct smb2_signing_capabilities *)pctx,
1048 /* offsets must be 8 byte aligned */
1049 clen = (clen + 7) & ~0x7;
1050 offset = clen + sizeof(struct smb2_neg_context);
1051 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1057 * smb2_handle_negotiate() - handler for smb2 negotiate command
1058 * @work: smb work containing smb request buffer
1062 int smb2_handle_negotiate(struct ksmbd_work *work)
1064 struct ksmbd_conn *conn = work->conn;
1065 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1066 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1068 unsigned int smb2_buf_len, smb2_neg_size;
1071 ksmbd_debug(SMB, "Received negotiate request\n");
1072 conn->need_neg = false;
1073 if (ksmbd_conn_good(work)) {
1074 pr_err("conn->tcp_status is already in CifsGood State\n");
1075 work->send_no_response = 1;
1079 if (req->DialectCount == 0) {
1080 pr_err("malformed packet\n");
1081 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1086 smb2_buf_len = get_rfc1002_len(work->request_buf);
1087 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1088 if (smb2_neg_size > smb2_buf_len) {
1089 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1094 if (conn->dialect == SMB311_PROT_ID) {
1095 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1097 if (smb2_buf_len < nego_ctxt_off) {
1098 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1103 if (smb2_neg_size > nego_ctxt_off) {
1104 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1109 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1111 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1116 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1118 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1124 conn->cli_cap = le32_to_cpu(req->Capabilities);
1125 switch (conn->dialect) {
1126 case SMB311_PROT_ID:
1127 conn->preauth_info =
1128 kzalloc(sizeof(struct preauth_integrity_info),
1130 if (!conn->preauth_info) {
1132 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1136 status = deassemble_neg_contexts(conn, req,
1137 get_rfc1002_len(work->request_buf));
1138 if (status != STATUS_SUCCESS) {
1139 pr_err("deassemble_neg_contexts error(0x%x)\n",
1141 rsp->hdr.Status = status;
1143 kfree(conn->preauth_info);
1144 conn->preauth_info = NULL;
1148 rc = init_smb3_11_server(conn);
1150 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1151 kfree(conn->preauth_info);
1152 conn->preauth_info = NULL;
1156 ksmbd_gen_preauth_integrity_hash(conn,
1158 conn->preauth_info->Preauth_HashValue);
1159 rsp->NegotiateContextOffset =
1160 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1161 assemble_neg_contexts(conn, rsp, work->response_buf);
1163 case SMB302_PROT_ID:
1164 init_smb3_02_server(conn);
1167 init_smb3_0_server(conn);
1170 init_smb2_1_server(conn);
1175 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1177 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1181 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1184 conn->connection_type = conn->dialect;
1186 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1187 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1188 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1190 memcpy(conn->ClientGUID, req->ClientGUID,
1191 SMB2_CLIENT_GUID_SIZE);
1192 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1194 rsp->StructureSize = cpu_to_le16(65);
1195 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1196 /* Not setting conn guid rsp->ServerGUID, as it
1197 * not used by client for identifying server
1199 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1201 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1202 rsp->ServerStartTime = 0;
1203 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1204 le32_to_cpu(rsp->NegotiateContextOffset),
1205 le16_to_cpu(rsp->NegotiateContextCount));
1207 rsp->SecurityBufferOffset = cpu_to_le16(128);
1208 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1209 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1210 le16_to_cpu(rsp->SecurityBufferOffset));
1211 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1212 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1214 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1215 conn->use_spnego = true;
1217 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1218 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1219 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1221 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1222 server_conf.enforced_signing = true;
1223 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1227 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1228 ksmbd_conn_set_need_negotiate(work);
1232 smb2_set_err_rsp(work);
1237 static int alloc_preauth_hash(struct ksmbd_session *sess,
1238 struct ksmbd_conn *conn)
1240 if (sess->Preauth_HashValue)
1243 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1244 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1245 if (!sess->Preauth_HashValue)
1251 static int generate_preauth_hash(struct ksmbd_work *work)
1253 struct ksmbd_conn *conn = work->conn;
1254 struct ksmbd_session *sess = work->sess;
1257 if (conn->dialect != SMB311_PROT_ID)
1260 if (conn->binding) {
1261 struct preauth_session *preauth_sess;
1263 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1264 if (!preauth_sess) {
1265 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1270 preauth_hash = preauth_sess->Preauth_HashValue;
1272 if (!sess->Preauth_HashValue)
1273 if (alloc_preauth_hash(sess, conn))
1275 preauth_hash = sess->Preauth_HashValue;
1278 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1282 static int decode_negotiation_token(struct ksmbd_conn *conn,
1283 struct negotiate_message *negblob,
1286 if (!conn->use_spnego)
1289 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1290 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1291 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1292 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1293 conn->use_spnego = false;
1299 static int ntlm_negotiate(struct ksmbd_work *work,
1300 struct negotiate_message *negblob,
1303 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1304 struct challenge_message *chgblob;
1305 unsigned char *spnego_blob = NULL;
1306 u16 spnego_blob_len;
1310 ksmbd_debug(SMB, "negotiate phase\n");
1311 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1315 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1317 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1318 memset(chgblob, 0, sizeof(struct challenge_message));
1320 if (!work->conn->use_spnego) {
1321 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1325 rsp->SecurityBufferLength = cpu_to_le16(sz);
1329 sz = sizeof(struct challenge_message);
1330 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1332 neg_blob = kzalloc(sz, GFP_KERNEL);
1336 chgblob = (struct challenge_message *)neg_blob;
1337 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1343 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1350 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1351 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1352 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1360 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1361 struct smb2_sess_setup_req *req)
1365 if (conn->use_spnego && conn->mechToken)
1366 return (struct authenticate_message *)conn->mechToken;
1368 sz = le16_to_cpu(req->SecurityBufferOffset);
1369 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1373 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1374 struct smb2_sess_setup_req *req)
1376 struct authenticate_message *authblob;
1377 struct ksmbd_user *user;
1379 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1381 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1382 if (secbuf_len < sizeof(struct authenticate_message)) {
1383 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1386 authblob = user_authblob(conn, req);
1387 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1388 name_len = le16_to_cpu(authblob->UserName.Length);
1389 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1391 if (auth_msg_len < (u64)name_off + name_len)
1394 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1399 pr_err("cannot allocate memory\n");
1403 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1404 user = ksmbd_login_user(name);
1409 static int ntlm_authenticate(struct ksmbd_work *work)
1411 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1412 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1413 struct ksmbd_conn *conn = work->conn;
1414 struct ksmbd_session *sess = work->sess;
1415 struct channel *chann = NULL;
1416 struct ksmbd_user *user;
1420 ksmbd_debug(SMB, "authenticate phase\n");
1421 if (conn->use_spnego) {
1422 unsigned char *spnego_blob;
1423 u16 spnego_blob_len;
1425 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1431 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1432 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1433 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1435 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1438 user = session_user(conn, req);
1440 ksmbd_debug(SMB, "Unknown user name or an error\n");
1444 /* Check for previous session */
1445 prev_id = le64_to_cpu(req->PreviousSessionId);
1446 if (prev_id && prev_id != sess->id)
1447 destroy_previous_session(conn, user, prev_id);
1449 if (sess->state == SMB2_SESSION_VALID) {
1451 * Reuse session if anonymous try to connect
1452 * on reauthetication.
1454 if (ksmbd_anonymous_user(user)) {
1455 ksmbd_free_user(user);
1459 if (!ksmbd_compare_user(sess->user, user)) {
1460 ksmbd_free_user(user);
1463 ksmbd_free_user(user);
1468 if (user_guest(sess->user)) {
1469 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1471 struct authenticate_message *authblob;
1473 authblob = user_authblob(conn, req);
1474 sz = le16_to_cpu(req->SecurityBufferLength);
1475 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1477 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1478 ksmbd_debug(SMB, "authentication failed\n");
1484 * If session state is SMB2_SESSION_VALID, We can assume
1485 * that it is reauthentication. And the user/password
1486 * has been verified, so return it here.
1488 if (sess->state == SMB2_SESSION_VALID) {
1490 goto binding_session;
1494 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1495 (conn->sign || server_conf.enforced_signing)) ||
1496 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1499 if (smb3_encryption_negotiated(conn) &&
1500 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1501 rc = conn->ops->generate_encryptionkey(conn, sess);
1504 "SMB3 encryption key generation failed\n");
1508 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1510 * signing is disable if encryption is enable
1517 if (conn->dialect >= SMB30_PROT_ID) {
1518 read_lock(&sess->chann_lock);
1519 chann = lookup_chann_list(sess, conn);
1520 read_unlock(&sess->chann_lock);
1522 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1527 INIT_LIST_HEAD(&chann->chann_list);
1528 write_lock(&sess->chann_lock);
1529 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1530 write_unlock(&sess->chann_lock);
1534 if (conn->ops->generate_signingkey) {
1535 rc = conn->ops->generate_signingkey(sess, conn);
1537 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1542 if (!ksmbd_conn_lookup_dialect(conn)) {
1543 pr_err("fail to verify the dialect\n");
1549 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1550 static int krb5_authenticate(struct ksmbd_work *work)
1552 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1553 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1554 struct ksmbd_conn *conn = work->conn;
1555 struct ksmbd_session *sess = work->sess;
1556 char *in_blob, *out_blob;
1557 struct channel *chann = NULL;
1559 int in_len, out_len;
1562 in_blob = (char *)&req->hdr.ProtocolId +
1563 le16_to_cpu(req->SecurityBufferOffset);
1564 in_len = le16_to_cpu(req->SecurityBufferLength);
1565 out_blob = (char *)&rsp->hdr.ProtocolId +
1566 le16_to_cpu(rsp->SecurityBufferOffset);
1567 out_len = work->response_sz -
1568 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1570 /* Check previous session */
1571 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1572 if (prev_sess_id && prev_sess_id != sess->id)
1573 destroy_previous_session(conn, sess->user, prev_sess_id);
1575 if (sess->state == SMB2_SESSION_VALID)
1576 ksmbd_free_user(sess->user);
1578 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1579 out_blob, &out_len);
1581 ksmbd_debug(SMB, "krb5 authentication failed\n");
1584 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1585 inc_rfc1001_len(work->response_buf, out_len - 1);
1587 if ((conn->sign || server_conf.enforced_signing) ||
1588 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1591 if (smb3_encryption_negotiated(conn)) {
1592 retval = conn->ops->generate_encryptionkey(conn, sess);
1595 "SMB3 encryption key generation failed\n");
1599 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1603 if (conn->dialect >= SMB30_PROT_ID) {
1604 read_lock(&sess->chann_lock);
1605 chann = lookup_chann_list(sess, conn);
1606 read_unlock(&sess->chann_lock);
1608 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1613 INIT_LIST_HEAD(&chann->chann_list);
1614 write_lock(&sess->chann_lock);
1615 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1616 write_unlock(&sess->chann_lock);
1620 if (conn->ops->generate_signingkey) {
1621 retval = conn->ops->generate_signingkey(sess, conn);
1623 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1628 if (!ksmbd_conn_lookup_dialect(conn)) {
1629 pr_err("fail to verify the dialect\n");
1635 static int krb5_authenticate(struct ksmbd_work *work)
1641 int smb2_sess_setup(struct ksmbd_work *work)
1643 struct ksmbd_conn *conn = work->conn;
1644 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1645 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1646 struct ksmbd_session *sess;
1647 struct negotiate_message *negblob;
1648 unsigned int negblob_len, negblob_off;
1651 ksmbd_debug(SMB, "Received request for session setup\n");
1653 rsp->StructureSize = cpu_to_le16(9);
1654 rsp->SessionFlags = 0;
1655 rsp->SecurityBufferOffset = cpu_to_le16(72);
1656 rsp->SecurityBufferLength = 0;
1657 inc_rfc1001_len(work->response_buf, 9);
1659 if (!req->hdr.SessionId) {
1660 sess = ksmbd_smb2_session_create();
1665 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1666 rc = ksmbd_session_register(conn, sess);
1669 } else if (conn->dialect >= SMB30_PROT_ID &&
1670 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1671 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1672 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1674 sess = ksmbd_session_lookup_slowpath(sess_id);
1680 if (conn->dialect != sess->dialect) {
1685 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1690 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1691 SMB2_CLIENT_GUID_SIZE)) {
1696 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1701 if (sess->state == SMB2_SESSION_EXPIRED) {
1706 if (ksmbd_session_lookup(conn, sess_id)) {
1711 conn->binding = true;
1712 } else if ((conn->dialect < SMB30_PROT_ID ||
1713 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1714 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1719 sess = ksmbd_session_lookup(conn,
1720 le64_to_cpu(req->hdr.SessionId));
1728 if (sess->state == SMB2_SESSION_EXPIRED)
1729 sess->state = SMB2_SESSION_IN_PROGRESS;
1731 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1732 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1733 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1734 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1739 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1742 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1743 if (conn->mechToken)
1744 negblob = (struct negotiate_message *)conn->mechToken;
1747 if (server_conf.auth_mechs & conn->auth_mechs) {
1748 rc = generate_preauth_hash(work);
1752 if (conn->preferred_auth_mech &
1753 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1754 rc = krb5_authenticate(work);
1760 ksmbd_conn_set_good(work);
1761 sess->state = SMB2_SESSION_VALID;
1762 kfree(sess->Preauth_HashValue);
1763 sess->Preauth_HashValue = NULL;
1764 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1765 if (negblob->MessageType == NtLmNegotiate) {
1766 rc = ntlm_negotiate(work, negblob, negblob_len);
1770 STATUS_MORE_PROCESSING_REQUIRED;
1772 * Note: here total size -1 is done as an
1773 * adjustment for 0 size blob
1775 inc_rfc1001_len(work->response_buf,
1776 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1778 } else if (negblob->MessageType == NtLmAuthenticate) {
1779 rc = ntlm_authenticate(work);
1783 ksmbd_conn_set_good(work);
1784 sess->state = SMB2_SESSION_VALID;
1785 if (conn->binding) {
1786 struct preauth_session *preauth_sess;
1789 ksmbd_preauth_session_lookup(conn, sess->id);
1791 list_del(&preauth_sess->preauth_entry);
1792 kfree(preauth_sess);
1795 kfree(sess->Preauth_HashValue);
1796 sess->Preauth_HashValue = NULL;
1799 /* TODO: need one more negotiation */
1800 pr_err("Not support the preferred authentication\n");
1804 pr_err("Not support authentication\n");
1810 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1811 else if (rc == -ENOENT)
1812 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1813 else if (rc == -EACCES)
1814 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1815 else if (rc == -EFAULT)
1816 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1817 else if (rc == -ENOMEM)
1818 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1820 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1822 if (conn->use_spnego && conn->mechToken) {
1823 kfree(conn->mechToken);
1824 conn->mechToken = NULL;
1829 * SecurityBufferOffset should be set to zero
1830 * in session setup error response.
1832 rsp->SecurityBufferOffset = 0;
1835 bool try_delay = false;
1838 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1839 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1840 * failure to make it harder to send enough random connection requests
1841 * to break into a server.
1843 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1846 xa_erase(&conn->sessions, sess->id);
1847 ksmbd_session_destroy(sess);
1858 * smb2_tree_connect() - handler for smb2 tree connect command
1859 * @work: smb work containing smb request buffer
1861 * Return: 0 on success, otherwise error
1863 int smb2_tree_connect(struct ksmbd_work *work)
1865 struct ksmbd_conn *conn = work->conn;
1866 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1867 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1868 struct ksmbd_session *sess = work->sess;
1869 char *treename = NULL, *name = NULL;
1870 struct ksmbd_tree_conn_status status;
1871 struct ksmbd_share_config *share;
1874 treename = smb_strndup_from_utf16(req->Buffer,
1875 le16_to_cpu(req->PathLength), true,
1877 if (IS_ERR(treename)) {
1878 pr_err("treename is NULL\n");
1879 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1883 name = ksmbd_extract_sharename(conn->um, treename);
1885 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1889 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1892 status = ksmbd_tree_conn_connect(conn, sess, name);
1893 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1894 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1898 share = status.tree_conn->share_conf;
1899 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1900 ksmbd_debug(SMB, "IPC share path request\n");
1901 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1902 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1903 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1904 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1905 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1906 FILE_SYNCHRONIZE_LE;
1908 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1909 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1910 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1911 if (test_tree_conn_flag(status.tree_conn,
1912 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1913 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1914 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1915 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1916 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1917 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1918 FILE_SYNCHRONIZE_LE;
1922 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1923 if (conn->posix_ext_supported)
1924 status.tree_conn->posix_extensions = true;
1926 rsp->StructureSize = cpu_to_le16(16);
1927 inc_rfc1001_len(work->response_buf, 16);
1929 rsp->Capabilities = 0;
1931 /* default manual caching */
1932 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1934 if (!IS_ERR(treename))
1939 switch (status.ret) {
1940 case KSMBD_TREE_CONN_STATUS_OK:
1941 rsp->hdr.Status = STATUS_SUCCESS;
1946 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1947 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
1950 case KSMBD_TREE_CONN_STATUS_NOMEM:
1951 rsp->hdr.Status = STATUS_NO_MEMORY;
1953 case KSMBD_TREE_CONN_STATUS_ERROR:
1954 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1955 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1956 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1959 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1962 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1965 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
1966 smb2_set_err_rsp(work);
1972 * smb2_create_open_flags() - convert smb open flags to unix open flags
1973 * @file_present: is file already present
1974 * @access: file access flags
1975 * @disposition: file disposition flags
1976 * @may_flags: set with MAY_ flags
1978 * Return: file open flags
1980 static int smb2_create_open_flags(bool file_present, __le32 access,
1984 int oflags = O_NONBLOCK | O_LARGEFILE;
1986 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1987 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1989 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1990 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1992 *may_flags = MAY_OPEN | MAY_WRITE;
1995 *may_flags = MAY_OPEN | MAY_READ;
1998 if (access == FILE_READ_ATTRIBUTES_LE)
2002 switch (disposition & FILE_CREATE_MASK_LE) {
2004 case FILE_CREATE_LE:
2006 case FILE_SUPERSEDE_LE:
2007 case FILE_OVERWRITE_LE:
2008 case FILE_OVERWRITE_IF_LE:
2015 switch (disposition & FILE_CREATE_MASK_LE) {
2016 case FILE_SUPERSEDE_LE:
2017 case FILE_CREATE_LE:
2018 case FILE_OPEN_IF_LE:
2019 case FILE_OVERWRITE_IF_LE:
2023 case FILE_OVERWRITE_LE:
2035 * smb2_tree_disconnect() - handler for smb tree connect request
2036 * @work: smb work containing request buffer
2040 int smb2_tree_disconnect(struct ksmbd_work *work)
2042 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2043 struct ksmbd_session *sess = work->sess;
2044 struct ksmbd_tree_connect *tcon = work->tcon;
2046 rsp->StructureSize = cpu_to_le16(4);
2047 inc_rfc1001_len(work->response_buf, 4);
2049 ksmbd_debug(SMB, "request\n");
2052 struct smb2_tree_disconnect_req *req =
2053 smb2_get_msg(work->request_buf);
2055 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2056 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2057 smb2_set_err_rsp(work);
2061 ksmbd_close_tree_conn_fds(work);
2062 ksmbd_tree_conn_disconnect(sess, tcon);
2068 * smb2_session_logoff() - handler for session log off request
2069 * @work: smb work containing request buffer
2073 int smb2_session_logoff(struct ksmbd_work *work)
2075 struct ksmbd_conn *conn = work->conn;
2076 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2077 struct ksmbd_session *sess = work->sess;
2079 rsp->StructureSize = cpu_to_le16(4);
2080 inc_rfc1001_len(work->response_buf, 4);
2082 ksmbd_debug(SMB, "request\n");
2084 /* setting CifsExiting here may race with start_tcp_sess */
2085 ksmbd_conn_set_need_reconnect(work);
2086 ksmbd_close_session_fds(work);
2087 ksmbd_conn_wait_idle(conn);
2089 if (ksmbd_tree_conn_session_logoff(sess)) {
2090 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2092 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2093 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2094 smb2_set_err_rsp(work);
2098 ksmbd_destroy_file_table(&sess->file_table);
2099 sess->state = SMB2_SESSION_EXPIRED;
2101 ksmbd_free_user(sess->user);
2104 /* let start_tcp_sess free connection info now */
2105 ksmbd_conn_set_need_negotiate(work);
2110 * create_smb2_pipe() - create IPC pipe
2111 * @work: smb work containing request buffer
2113 * Return: 0 on success, otherwise error
2115 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2117 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2118 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2123 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2124 1, work->conn->local_nls);
2126 rsp->hdr.Status = STATUS_NO_MEMORY;
2127 err = PTR_ERR(name);
2131 id = ksmbd_session_rpc_open(work->sess, name);
2133 pr_err("Unable to open RPC pipe: %d\n", id);
2138 rsp->hdr.Status = STATUS_SUCCESS;
2139 rsp->StructureSize = cpu_to_le16(89);
2140 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2142 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2144 rsp->CreationTime = cpu_to_le64(0);
2145 rsp->LastAccessTime = cpu_to_le64(0);
2146 rsp->ChangeTime = cpu_to_le64(0);
2147 rsp->AllocationSize = cpu_to_le64(0);
2148 rsp->EndofFile = cpu_to_le64(0);
2149 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2151 rsp->VolatileFileId = id;
2152 rsp->PersistentFileId = 0;
2153 rsp->CreateContextsOffset = 0;
2154 rsp->CreateContextsLength = 0;
2156 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2163 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2167 rsp->hdr.Status = STATUS_NO_MEMORY;
2174 smb2_set_err_rsp(work);
2179 * smb2_set_ea() - handler for setting extended attributes using set
2181 * @eabuf: set info command buffer
2182 * @buf_len: set info command buffer length
2183 * @path: dentry path for get ea
2185 * Return: 0 on success, otherwise error
2187 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2188 const struct path *path)
2190 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2191 char *attr_name = NULL, *value;
2193 unsigned int next = 0;
2195 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2196 le16_to_cpu(eabuf->EaValueLength))
2199 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2204 if (!eabuf->EaNameLength)
2208 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2209 eabuf->name, eabuf->EaNameLength,
2210 le16_to_cpu(eabuf->EaValueLength),
2211 le32_to_cpu(eabuf->NextEntryOffset));
2213 if (eabuf->EaNameLength >
2214 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2219 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2220 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2221 eabuf->EaNameLength);
2222 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2223 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2225 if (!eabuf->EaValueLength) {
2226 rc = ksmbd_vfs_casexattr_len(user_ns,
2229 XATTR_USER_PREFIX_LEN +
2230 eabuf->EaNameLength);
2232 /* delete the EA only when it exits */
2234 rc = ksmbd_vfs_remove_xattr(user_ns,
2240 "remove xattr failed(%d)\n",
2246 /* if the EA doesn't exist, just do nothing. */
2249 rc = ksmbd_vfs_setxattr(user_ns,
2250 path->dentry, attr_name, value,
2251 le16_to_cpu(eabuf->EaValueLength), 0);
2254 "ksmbd_vfs_setxattr is failed(%d)\n",
2261 next = le32_to_cpu(eabuf->NextEntryOffset);
2262 if (next == 0 || buf_len < next)
2265 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2266 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2269 } while (next != 0);
2275 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2276 struct ksmbd_file *fp,
2277 char *stream_name, int s_type)
2279 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2280 size_t xattr_stream_size;
2281 char *xattr_stream_name;
2284 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2291 fp->stream.name = xattr_stream_name;
2292 fp->stream.size = xattr_stream_size;
2294 /* Check if there is stream prefix in xattr space */
2295 rc = ksmbd_vfs_casexattr_len(user_ns,
2302 if (fp->cdoption == FILE_OPEN_LE) {
2303 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2307 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2308 xattr_stream_name, NULL, 0, 0);
2310 pr_err("Failed to store XATTR stream name :%d\n", rc);
2314 static int smb2_remove_smb_xattrs(const struct path *path)
2316 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2317 char *name, *xattr_list = NULL;
2318 ssize_t xattr_list_len;
2321 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2322 if (xattr_list_len < 0) {
2324 } else if (!xattr_list_len) {
2325 ksmbd_debug(SMB, "empty xattr in the file\n");
2329 for (name = xattr_list; name - xattr_list < xattr_list_len;
2330 name += strlen(name) + 1) {
2331 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2333 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2334 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2335 STREAM_PREFIX_LEN)) {
2336 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry,
2339 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2348 static int smb2_create_truncate(const struct path *path)
2350 int rc = vfs_truncate(path, 0);
2353 pr_err("vfs_truncate failed, rc %d\n", rc);
2357 rc = smb2_remove_smb_xattrs(path);
2358 if (rc == -EOPNOTSUPP)
2362 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2367 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2368 struct ksmbd_file *fp)
2370 struct xattr_dos_attrib da = {0};
2373 if (!test_share_config_flag(tcon->share_conf,
2374 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2378 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2379 da.itime = da.create_time = fp->create_time;
2380 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2381 XATTR_DOSINFO_ITIME;
2383 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2386 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2389 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2390 const struct path *path, struct ksmbd_file *fp)
2392 struct xattr_dos_attrib da;
2395 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2397 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2398 if (!test_share_config_flag(tcon->share_conf,
2399 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2402 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2405 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2406 fp->create_time = da.create_time;
2407 fp->itime = da.itime;
2411 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2412 int open_flags, umode_t posix_mode, bool is_dir)
2414 struct ksmbd_tree_connect *tcon = work->tcon;
2415 struct ksmbd_share_config *share = tcon->share_conf;
2419 if (!(open_flags & O_CREAT))
2422 ksmbd_debug(SMB, "file does not exist, so creating\n");
2423 if (is_dir == true) {
2424 ksmbd_debug(SMB, "creating directory\n");
2426 mode = share_config_directory_mode(share, posix_mode);
2427 rc = ksmbd_vfs_mkdir(work, name, mode);
2431 ksmbd_debug(SMB, "creating regular file\n");
2433 mode = share_config_create_mode(share, posix_mode);
2434 rc = ksmbd_vfs_create(work, name, mode);
2439 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2441 pr_err("cannot get linux path (%s), err = %d\n",
2448 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2449 struct smb2_create_req *req,
2450 const struct path *path)
2452 struct create_context *context;
2453 struct create_sd_buf_req *sd_buf;
2455 if (!req->CreateContextsOffset)
2458 /* Parse SD BUFFER create contexts */
2459 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2462 else if (IS_ERR(context))
2463 return PTR_ERR(context);
2466 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2467 sd_buf = (struct create_sd_buf_req *)context;
2468 if (le16_to_cpu(context->DataOffset) +
2469 le32_to_cpu(context->DataLength) <
2470 sizeof(struct create_sd_buf_req))
2472 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2473 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2476 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2477 struct user_namespace *mnt_userns,
2478 struct inode *inode)
2480 vfsuid_t vfsuid = i_uid_into_vfsuid(mnt_userns, inode);
2481 vfsgid_t vfsgid = i_gid_into_vfsgid(mnt_userns, inode);
2483 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2484 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2485 fattr->cf_mode = inode->i_mode;
2486 fattr->cf_acls = NULL;
2487 fattr->cf_dacls = NULL;
2489 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2490 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2491 if (S_ISDIR(inode->i_mode))
2492 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2497 * smb2_open() - handler for smb file open request
2498 * @work: smb work containing request buffer
2500 * Return: 0 on success, otherwise error
2502 int smb2_open(struct ksmbd_work *work)
2504 struct ksmbd_conn *conn = work->conn;
2505 struct ksmbd_session *sess = work->sess;
2506 struct ksmbd_tree_connect *tcon = work->tcon;
2507 struct smb2_create_req *req;
2508 struct smb2_create_rsp *rsp;
2510 struct ksmbd_share_config *share = tcon->share_conf;
2511 struct ksmbd_file *fp = NULL;
2512 struct file *filp = NULL;
2513 struct user_namespace *user_ns = NULL;
2515 struct create_context *context;
2516 struct lease_ctx_info *lc = NULL;
2517 struct create_ea_buf_req *ea_buf = NULL;
2518 struct oplock_info *opinfo;
2519 __le32 *next_ptr = NULL;
2520 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2522 int contxt_cnt = 0, query_disk_id = 0;
2523 int maximal_access_ctxt = 0, posix_ctxt = 0;
2527 char *stream_name = NULL;
2528 bool file_present = false, created = false, already_permitted = false;
2529 int share_ret, need_truncate = 0;
2531 umode_t posix_mode = 0;
2532 __le32 daccess, maximal_access = 0;
2534 WORK_BUFFERS(work, req, rsp);
2536 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2537 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2538 ksmbd_debug(SMB, "invalid flag in chained command\n");
2539 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2540 smb2_set_err_rsp(work);
2544 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2545 ksmbd_debug(SMB, "IPC pipe create request\n");
2546 return create_smb2_pipe(work);
2549 if (req->NameLength) {
2550 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2551 *(char *)req->Buffer == '\\') {
2552 pr_err("not allow directory name included leading slash\n");
2557 name = smb2_get_name(req->Buffer,
2558 le16_to_cpu(req->NameLength),
2559 work->conn->local_nls);
2568 ksmbd_debug(SMB, "converted name = %s\n", name);
2569 if (strchr(name, ':')) {
2570 if (!test_share_config_flag(work->tcon->share_conf,
2571 KSMBD_SHARE_FLAG_STREAMS)) {
2575 rc = parse_stream_name(name, &stream_name, &s_type);
2580 rc = ksmbd_validate_filename(name);
2584 if (ksmbd_share_veto_filename(share, name)) {
2586 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2591 name = kstrdup("", GFP_KERNEL);
2598 req_op_level = req->RequestedOplockLevel;
2599 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2600 lc = parse_lease_state(req);
2602 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2603 pr_err("Invalid impersonationlevel : 0x%x\n",
2604 le32_to_cpu(req->ImpersonationLevel));
2606 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2610 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2611 pr_err("Invalid create options : 0x%x\n",
2612 le32_to_cpu(req->CreateOptions));
2616 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2617 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2618 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2620 if (req->CreateOptions &
2621 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2622 FILE_RESERVE_OPFILTER_LE)) {
2627 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2628 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2631 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2632 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2637 if (le32_to_cpu(req->CreateDisposition) >
2638 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2639 pr_err("Invalid create disposition : 0x%x\n",
2640 le32_to_cpu(req->CreateDisposition));
2645 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2646 pr_err("Invalid desired access : 0x%x\n",
2647 le32_to_cpu(req->DesiredAccess));
2652 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2653 pr_err("Invalid file attribute : 0x%x\n",
2654 le32_to_cpu(req->FileAttributes));
2659 if (req->CreateContextsOffset) {
2660 /* Parse non-durable handle create contexts */
2661 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2662 if (IS_ERR(context)) {
2663 rc = PTR_ERR(context);
2665 } else if (context) {
2666 ea_buf = (struct create_ea_buf_req *)context;
2667 if (le16_to_cpu(context->DataOffset) +
2668 le32_to_cpu(context->DataLength) <
2669 sizeof(struct create_ea_buf_req)) {
2673 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2674 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2680 context = smb2_find_context_vals(req,
2681 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2682 if (IS_ERR(context)) {
2683 rc = PTR_ERR(context);
2685 } else if (context) {
2687 "get query maximal access context\n");
2688 maximal_access_ctxt = 1;
2691 context = smb2_find_context_vals(req,
2692 SMB2_CREATE_TIMEWARP_REQUEST);
2693 if (IS_ERR(context)) {
2694 rc = PTR_ERR(context);
2696 } else if (context) {
2697 ksmbd_debug(SMB, "get timewarp context\n");
2702 if (tcon->posix_extensions) {
2703 context = smb2_find_context_vals(req,
2704 SMB2_CREATE_TAG_POSIX);
2705 if (IS_ERR(context)) {
2706 rc = PTR_ERR(context);
2708 } else if (context) {
2709 struct create_posix *posix =
2710 (struct create_posix *)context;
2711 if (le16_to_cpu(context->DataOffset) +
2712 le32_to_cpu(context->DataLength) <
2713 sizeof(struct create_posix) - 4) {
2717 ksmbd_debug(SMB, "get posix context\n");
2719 posix_mode = le32_to_cpu(posix->Mode);
2725 if (ksmbd_override_fsids(work)) {
2730 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2732 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2734 * If file exists with under flags, return access
2737 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2738 req->CreateDisposition == FILE_OPEN_IF_LE) {
2744 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2746 "User does not have write permission\n");
2751 } else if (d_is_symlink(path.dentry)) {
2761 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2765 file_present = true;
2766 user_ns = mnt_user_ns(path.mnt);
2769 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2770 if (s_type == DATA_STREAM) {
2772 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2775 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2776 s_type == DATA_STREAM) {
2778 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2782 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2783 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2784 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2792 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2793 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2794 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2795 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2796 name, req->CreateOptions);
2797 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2802 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2803 !(req->CreateDisposition == FILE_CREATE_LE) &&
2804 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2805 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2810 if (!stream_name && file_present &&
2811 req->CreateDisposition == FILE_CREATE_LE) {
2816 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2818 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2819 rc = smb_check_perm_dacl(conn, &path, &daccess,
2825 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2826 if (!file_present) {
2827 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2829 rc = ksmbd_vfs_query_maximal_access(user_ns,
2834 already_permitted = true;
2836 maximal_access = daccess;
2839 open_flags = smb2_create_open_flags(file_present, daccess,
2840 req->CreateDisposition,
2843 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2844 if (open_flags & O_CREAT) {
2846 "User does not have write permission\n");
2852 /*create file if not present */
2853 if (!file_present) {
2854 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2855 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2857 if (rc == -ENOENT) {
2859 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2865 user_ns = mnt_user_ns(path.mnt);
2867 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2868 sizeof(struct smb2_ea_info)) {
2873 rc = smb2_set_ea(&ea_buf->ea,
2874 le32_to_cpu(ea_buf->ccontext.DataLength),
2876 if (rc == -EOPNOTSUPP)
2881 } else if (!already_permitted) {
2882 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2883 * because execute(search) permission on a parent directory,
2884 * is already granted.
2886 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2887 rc = inode_permission(user_ns,
2888 d_inode(path.dentry),
2893 if ((daccess & FILE_DELETE_LE) ||
2894 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2895 rc = ksmbd_vfs_may_delete(user_ns,
2903 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2904 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2910 filp = dentry_open(&path, open_flags, current_cred());
2913 pr_err("dentry open for dir failed, rc %d\n", rc);
2918 if (!(open_flags & O_TRUNC))
2919 file_info = FILE_OPENED;
2921 file_info = FILE_OVERWRITTEN;
2923 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2925 file_info = FILE_SUPERSEDED;
2926 } else if (open_flags & O_CREAT) {
2927 file_info = FILE_CREATED;
2930 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2932 /* Obtain Volatile-ID */
2933 fp = ksmbd_open_fd(work, filp);
2941 /* Get Persistent-ID */
2942 ksmbd_open_durable_fd(fp);
2943 if (!has_file_id(fp->persistent_id)) {
2948 fp->cdoption = req->CreateDisposition;
2949 fp->daccess = daccess;
2950 fp->saccess = req->ShareAccess;
2951 fp->coption = req->CreateOptions;
2953 /* Set default windows and posix acls if creating new file */
2956 struct inode *inode = d_inode(path.dentry);
2958 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2960 d_inode(path.dentry->d_parent));
2962 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2964 if (test_share_config_flag(work->tcon->share_conf,
2965 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2966 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2971 rc = smb2_create_sd_buffer(work, req, &path);
2974 ksmbd_vfs_set_init_posix_acl(user_ns,
2977 if (test_share_config_flag(work->tcon->share_conf,
2978 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2979 struct smb_fattr fattr;
2980 struct smb_ntsd *pntsd;
2981 int pntsd_size, ace_num = 0;
2983 ksmbd_acls_fattr(&fattr, user_ns, inode);
2985 ace_num = fattr.cf_acls->a_count;
2987 ace_num += fattr.cf_dacls->a_count;
2989 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2990 sizeof(struct smb_sid) * 3 +
2991 sizeof(struct smb_acl) +
2992 sizeof(struct smb_ace) * ace_num * 2,
2995 posix_acl_release(fattr.cf_acls);
2996 posix_acl_release(fattr.cf_dacls);
3000 rc = build_sec_desc(user_ns,
3005 &pntsd_size, &fattr);
3006 posix_acl_release(fattr.cf_acls);
3007 posix_acl_release(fattr.cf_dacls);
3013 rc = ksmbd_vfs_set_sd_xattr(conn,
3020 pr_err("failed to store ntacl in xattr : %d\n",
3029 rc = smb2_set_stream_name_xattr(&path,
3035 file_info = FILE_CREATED;
3038 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3039 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3040 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3041 !fp->attrib_only && !stream_name) {
3042 smb_break_all_oplock(work, fp);
3046 /* fp should be searchable through ksmbd_inode.m_fp_list
3047 * after daccess, saccess, attrib_only, and stream are
3050 write_lock(&fp->f_ci->m_lock);
3051 list_add(&fp->node, &fp->f_ci->m_fp_list);
3052 write_unlock(&fp->f_ci->m_lock);
3054 /* Check delete pending among previous fp before oplock break */
3055 if (ksmbd_inode_pending_delete(fp)) {
3060 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3061 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3062 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3063 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3064 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3069 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3070 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3072 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3073 name, req_op_level, lc->req_state);
3074 rc = find_same_lease_key(sess, fp->f_ci, lc);
3077 } else if (open_flags == O_RDONLY &&
3078 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3079 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3080 req_op_level = SMB2_OPLOCK_LEVEL_II;
3082 rc = smb_grant_oplock(work, req_op_level,
3083 fp->persistent_id, fp,
3084 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3090 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3091 ksmbd_fd_set_delete_on_close(fp, file_info);
3093 if (need_truncate) {
3094 rc = smb2_create_truncate(&path);
3099 if (req->CreateContextsOffset) {
3100 struct create_alloc_size_req *az_req;
3102 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3103 SMB2_CREATE_ALLOCATION_SIZE);
3104 if (IS_ERR(az_req)) {
3105 rc = PTR_ERR(az_req);
3107 } else if (az_req) {
3111 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3112 le32_to_cpu(az_req->ccontext.DataLength) <
3113 sizeof(struct create_alloc_size_req)) {
3117 alloc_size = le64_to_cpu(az_req->AllocationSize);
3119 "request smb2 create allocate size : %llu\n",
3121 smb_break_all_levII_oplock(work, fp, 1);
3122 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3126 "vfs_fallocate is failed : %d\n",
3130 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3131 if (IS_ERR(context)) {
3132 rc = PTR_ERR(context);
3134 } else if (context) {
3135 ksmbd_debug(SMB, "get query on disk id context\n");
3140 rc = ksmbd_vfs_getattr(&path, &stat);
3144 if (stat.result_mask & STATX_BTIME)
3145 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3147 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3148 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3150 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3153 smb2_update_xattrs(tcon, &path, fp);
3155 smb2_new_xattrs(tcon, &path, fp);
3157 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3159 rsp->StructureSize = cpu_to_le16(89);
3161 opinfo = rcu_dereference(fp->f_opinfo);
3162 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3165 rsp->CreateAction = cpu_to_le32(file_info);
3166 rsp->CreationTime = cpu_to_le64(fp->create_time);
3167 time = ksmbd_UnixTimeToNT(stat.atime);
3168 rsp->LastAccessTime = cpu_to_le64(time);
3169 time = ksmbd_UnixTimeToNT(stat.mtime);
3170 rsp->LastWriteTime = cpu_to_le64(time);
3171 time = ksmbd_UnixTimeToNT(stat.ctime);
3172 rsp->ChangeTime = cpu_to_le64(time);
3173 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3174 cpu_to_le64(stat.blocks << 9);
3175 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3176 rsp->FileAttributes = fp->f_ci->m_fattr;
3180 rsp->PersistentFileId = fp->persistent_id;
3181 rsp->VolatileFileId = fp->volatile_id;
3183 rsp->CreateContextsOffset = 0;
3184 rsp->CreateContextsLength = 0;
3185 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3187 /* If lease is request send lease context response */
3188 if (opinfo && opinfo->is_lease) {
3189 struct create_context *lease_ccontext;
3191 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3192 name, opinfo->o_lease->state);
3193 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3195 lease_ccontext = (struct create_context *)rsp->Buffer;
3197 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3198 le32_add_cpu(&rsp->CreateContextsLength,
3199 conn->vals->create_lease_size);
3200 inc_rfc1001_len(work->response_buf,
3201 conn->vals->create_lease_size);
3202 next_ptr = &lease_ccontext->Next;
3203 next_off = conn->vals->create_lease_size;
3206 if (maximal_access_ctxt) {
3207 struct create_context *mxac_ccontext;
3209 if (maximal_access == 0)
3210 ksmbd_vfs_query_maximal_access(user_ns,
3213 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3214 le32_to_cpu(rsp->CreateContextsLength));
3216 create_mxac_rsp_buf(rsp->Buffer +
3217 le32_to_cpu(rsp->CreateContextsLength),
3218 le32_to_cpu(maximal_access));
3219 le32_add_cpu(&rsp->CreateContextsLength,
3220 conn->vals->create_mxac_size);
3221 inc_rfc1001_len(work->response_buf,
3222 conn->vals->create_mxac_size);
3224 *next_ptr = cpu_to_le32(next_off);
3225 next_ptr = &mxac_ccontext->Next;
3226 next_off = conn->vals->create_mxac_size;
3229 if (query_disk_id) {
3230 struct create_context *disk_id_ccontext;
3232 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3233 le32_to_cpu(rsp->CreateContextsLength));
3235 create_disk_id_rsp_buf(rsp->Buffer +
3236 le32_to_cpu(rsp->CreateContextsLength),
3237 stat.ino, tcon->id);
3238 le32_add_cpu(&rsp->CreateContextsLength,
3239 conn->vals->create_disk_id_size);
3240 inc_rfc1001_len(work->response_buf,
3241 conn->vals->create_disk_id_size);
3243 *next_ptr = cpu_to_le32(next_off);
3244 next_ptr = &disk_id_ccontext->Next;
3245 next_off = conn->vals->create_disk_id_size;
3250 create_posix_rsp_buf(rsp->Buffer +
3251 le32_to_cpu(rsp->CreateContextsLength),
3253 le32_add_cpu(&rsp->CreateContextsLength,
3254 conn->vals->create_posix_size);
3255 inc_rfc1001_len(work->response_buf,
3256 conn->vals->create_posix_size);
3258 *next_ptr = cpu_to_le32(next_off);
3261 if (contxt_cnt > 0) {
3262 rsp->CreateContextsOffset =
3263 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3267 if (file_present || created)
3269 ksmbd_revert_fsids(work);
3273 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3274 else if (rc == -EOPNOTSUPP)
3275 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3276 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3277 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3278 else if (rc == -ENOENT)
3279 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3280 else if (rc == -EPERM)
3281 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3282 else if (rc == -EBUSY)
3283 rsp->hdr.Status = STATUS_DELETE_PENDING;
3284 else if (rc == -EBADF)
3285 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3286 else if (rc == -ENOEXEC)
3287 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3288 else if (rc == -ENXIO)
3289 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3290 else if (rc == -EEXIST)
3291 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3292 else if (rc == -EMFILE)
3293 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3294 if (!rsp->hdr.Status)
3295 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3298 ksmbd_fd_put(work, fp);
3299 smb2_set_err_rsp(work);
3300 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3309 static int readdir_info_level_struct_sz(int info_level)
3311 switch (info_level) {
3312 case FILE_FULL_DIRECTORY_INFORMATION:
3313 return sizeof(struct file_full_directory_info);
3314 case FILE_BOTH_DIRECTORY_INFORMATION:
3315 return sizeof(struct file_both_directory_info);
3316 case FILE_DIRECTORY_INFORMATION:
3317 return sizeof(struct file_directory_info);
3318 case FILE_NAMES_INFORMATION:
3319 return sizeof(struct file_names_info);
3320 case FILEID_FULL_DIRECTORY_INFORMATION:
3321 return sizeof(struct file_id_full_dir_info);
3322 case FILEID_BOTH_DIRECTORY_INFORMATION:
3323 return sizeof(struct file_id_both_directory_info);
3324 case SMB_FIND_FILE_POSIX_INFO:
3325 return sizeof(struct smb2_posix_info);
3331 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3333 switch (info_level) {
3334 case FILE_FULL_DIRECTORY_INFORMATION:
3336 struct file_full_directory_info *ffdinfo;
3338 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3339 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3340 d_info->name = ffdinfo->FileName;
3341 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3344 case FILE_BOTH_DIRECTORY_INFORMATION:
3346 struct file_both_directory_info *fbdinfo;
3348 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3349 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3350 d_info->name = fbdinfo->FileName;
3351 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3354 case FILE_DIRECTORY_INFORMATION:
3356 struct file_directory_info *fdinfo;
3358 fdinfo = (struct file_directory_info *)d_info->rptr;
3359 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3360 d_info->name = fdinfo->FileName;
3361 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3364 case FILE_NAMES_INFORMATION:
3366 struct file_names_info *fninfo;
3368 fninfo = (struct file_names_info *)d_info->rptr;
3369 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3370 d_info->name = fninfo->FileName;
3371 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3374 case FILEID_FULL_DIRECTORY_INFORMATION:
3376 struct file_id_full_dir_info *dinfo;
3378 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3379 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3380 d_info->name = dinfo->FileName;
3381 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3384 case FILEID_BOTH_DIRECTORY_INFORMATION:
3386 struct file_id_both_directory_info *fibdinfo;
3388 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3389 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3390 d_info->name = fibdinfo->FileName;
3391 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3394 case SMB_FIND_FILE_POSIX_INFO:
3396 struct smb2_posix_info *posix_info;
3398 posix_info = (struct smb2_posix_info *)d_info->rptr;
3399 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3400 d_info->name = posix_info->name;
3401 d_info->name_len = le32_to_cpu(posix_info->name_len);
3410 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3412 * @conn: connection instance
3413 * @info_level: smb information level
3414 * @d_info: structure included variables for query dir
3415 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3417 * if directory has many entries, find first can't read it fully.
3418 * find next might be called multiple times to read remaining dir entries
3420 * Return: 0 on success, otherwise error
3422 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3423 struct ksmbd_dir_info *d_info,
3424 struct ksmbd_kstat *ksmbd_kstat)
3426 int next_entry_offset = 0;
3430 int struct_sz, rc = 0;
3432 conv_name = ksmbd_convert_dir_info_name(d_info,
3438 /* Somehow the name has only terminating NULL bytes */
3441 goto free_conv_name;
3444 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3445 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3446 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3448 if (next_entry_offset > d_info->out_buf_len) {
3449 d_info->out_buf_len = 0;
3451 goto free_conv_name;
3454 kstat = d_info->wptr;
3455 if (info_level != FILE_NAMES_INFORMATION)
3456 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3458 switch (info_level) {
3459 case FILE_FULL_DIRECTORY_INFORMATION:
3461 struct file_full_directory_info *ffdinfo;
3463 ffdinfo = (struct file_full_directory_info *)kstat;
3464 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3466 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3467 if (ffdinfo->EaSize)
3468 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3469 if (d_info->hide_dot_file && d_info->name[0] == '.')
3470 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3471 memcpy(ffdinfo->FileName, conv_name, conv_len);
3472 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3475 case FILE_BOTH_DIRECTORY_INFORMATION:
3477 struct file_both_directory_info *fbdinfo;
3479 fbdinfo = (struct file_both_directory_info *)kstat;
3480 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3482 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3483 if (fbdinfo->EaSize)
3484 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3485 fbdinfo->ShortNameLength = 0;
3486 fbdinfo->Reserved = 0;
3487 if (d_info->hide_dot_file && d_info->name[0] == '.')
3488 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3489 memcpy(fbdinfo->FileName, conv_name, conv_len);
3490 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3493 case FILE_DIRECTORY_INFORMATION:
3495 struct file_directory_info *fdinfo;
3497 fdinfo = (struct file_directory_info *)kstat;
3498 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3499 if (d_info->hide_dot_file && d_info->name[0] == '.')
3500 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3501 memcpy(fdinfo->FileName, conv_name, conv_len);
3502 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3505 case FILE_NAMES_INFORMATION:
3507 struct file_names_info *fninfo;
3509 fninfo = (struct file_names_info *)kstat;
3510 fninfo->FileNameLength = cpu_to_le32(conv_len);
3511 memcpy(fninfo->FileName, conv_name, conv_len);
3512 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3515 case FILEID_FULL_DIRECTORY_INFORMATION:
3517 struct file_id_full_dir_info *dinfo;
3519 dinfo = (struct file_id_full_dir_info *)kstat;
3520 dinfo->FileNameLength = cpu_to_le32(conv_len);
3522 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3524 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3525 dinfo->Reserved = 0;
3526 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3527 if (d_info->hide_dot_file && d_info->name[0] == '.')
3528 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3529 memcpy(dinfo->FileName, conv_name, conv_len);
3530 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3533 case FILEID_BOTH_DIRECTORY_INFORMATION:
3535 struct file_id_both_directory_info *fibdinfo;
3537 fibdinfo = (struct file_id_both_directory_info *)kstat;
3538 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3540 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3541 if (fibdinfo->EaSize)
3542 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3543 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3544 fibdinfo->ShortNameLength = 0;
3545 fibdinfo->Reserved = 0;
3546 fibdinfo->Reserved2 = cpu_to_le16(0);
3547 if (d_info->hide_dot_file && d_info->name[0] == '.')
3548 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3549 memcpy(fibdinfo->FileName, conv_name, conv_len);
3550 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3553 case SMB_FIND_FILE_POSIX_INFO:
3555 struct smb2_posix_info *posix_info;
3558 posix_info = (struct smb2_posix_info *)kstat;
3559 posix_info->Ignored = 0;
3560 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3561 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3562 posix_info->ChangeTime = cpu_to_le64(time);
3563 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3564 posix_info->LastAccessTime = cpu_to_le64(time);
3565 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3566 posix_info->LastWriteTime = cpu_to_le64(time);
3567 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3568 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3569 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3570 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3571 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3572 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3573 posix_info->DosAttributes =
3574 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3575 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3576 if (d_info->hide_dot_file && d_info->name[0] == '.')
3577 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3579 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3580 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3581 * sub_auth(4 * 1(num_subauth)) + RID(4).
3583 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3584 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3585 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3586 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3587 memcpy(posix_info->name, conv_name, conv_len);
3588 posix_info->name_len = cpu_to_le32(conv_len);
3589 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3593 } /* switch (info_level) */
3595 d_info->last_entry_offset = d_info->data_count;
3596 d_info->data_count += next_entry_offset;
3597 d_info->out_buf_len -= next_entry_offset;
3598 d_info->wptr += next_entry_offset;
3601 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3602 info_level, d_info->out_buf_len,
3603 next_entry_offset, d_info->data_count);
3610 struct smb2_query_dir_private {
3611 struct ksmbd_work *work;
3612 char *search_pattern;
3613 struct ksmbd_file *dir_fp;
3615 struct ksmbd_dir_info *d_info;
3619 static void lock_dir(struct ksmbd_file *dir_fp)
3621 struct dentry *dir = dir_fp->filp->f_path.dentry;
3623 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3626 static void unlock_dir(struct ksmbd_file *dir_fp)
3628 struct dentry *dir = dir_fp->filp->f_path.dentry;
3630 inode_unlock(d_inode(dir));
3633 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3635 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3637 struct ksmbd_kstat ksmbd_kstat;
3641 for (i = 0; i < priv->d_info->num_entry; i++) {
3642 struct dentry *dent;
3644 if (dentry_name(priv->d_info, priv->info_level))
3647 lock_dir(priv->dir_fp);
3648 dent = lookup_one(user_ns, priv->d_info->name,
3649 priv->dir_fp->filp->f_path.dentry,
3650 priv->d_info->name_len);
3651 unlock_dir(priv->dir_fp);
3654 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3659 if (unlikely(d_is_negative(dent))) {
3661 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3662 priv->d_info->name);
3666 ksmbd_kstat.kstat = &kstat;
3667 if (priv->info_level != FILE_NAMES_INFORMATION)
3668 ksmbd_vfs_fill_dentry_attrs(priv->work,
3673 rc = smb2_populate_readdir_entry(priv->work->conn,
3684 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3689 int next_entry_offset;
3691 struct_sz = readdir_info_level_struct_sz(info_level);
3692 if (struct_sz == -EOPNOTSUPP)
3695 conv_len = (d_info->name_len + 1) * 2;
3696 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3697 KSMBD_DIR_INFO_ALIGNMENT);
3699 if (next_entry_offset > d_info->out_buf_len) {
3700 d_info->out_buf_len = 0;
3704 switch (info_level) {
3705 case FILE_FULL_DIRECTORY_INFORMATION:
3707 struct file_full_directory_info *ffdinfo;
3709 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3710 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3711 ffdinfo->FileName[d_info->name_len] = 0x00;
3712 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3713 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3716 case FILE_BOTH_DIRECTORY_INFORMATION:
3718 struct file_both_directory_info *fbdinfo;
3720 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3721 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3722 fbdinfo->FileName[d_info->name_len] = 0x00;
3723 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3724 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3727 case FILE_DIRECTORY_INFORMATION:
3729 struct file_directory_info *fdinfo;
3731 fdinfo = (struct file_directory_info *)d_info->wptr;
3732 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3733 fdinfo->FileName[d_info->name_len] = 0x00;
3734 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3735 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3738 case FILE_NAMES_INFORMATION:
3740 struct file_names_info *fninfo;
3742 fninfo = (struct file_names_info *)d_info->wptr;
3743 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3744 fninfo->FileName[d_info->name_len] = 0x00;
3745 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3746 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3749 case FILEID_FULL_DIRECTORY_INFORMATION:
3751 struct file_id_full_dir_info *dinfo;
3753 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3754 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3755 dinfo->FileName[d_info->name_len] = 0x00;
3756 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3757 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3760 case FILEID_BOTH_DIRECTORY_INFORMATION:
3762 struct file_id_both_directory_info *fibdinfo;
3764 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3765 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3766 fibdinfo->FileName[d_info->name_len] = 0x00;
3767 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3768 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3771 case SMB_FIND_FILE_POSIX_INFO:
3773 struct smb2_posix_info *posix_info;
3775 posix_info = (struct smb2_posix_info *)d_info->wptr;
3776 memcpy(posix_info->name, d_info->name, d_info->name_len);
3777 posix_info->name[d_info->name_len] = 0x00;
3778 posix_info->name_len = cpu_to_le32(d_info->name_len);
3779 posix_info->NextEntryOffset =
3780 cpu_to_le32(next_entry_offset);
3783 } /* switch (info_level) */
3785 d_info->num_entry++;
3786 d_info->out_buf_len -= next_entry_offset;
3787 d_info->wptr += next_entry_offset;
3791 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3792 loff_t offset, u64 ino, unsigned int d_type)
3794 struct ksmbd_readdir_data *buf;
3795 struct smb2_query_dir_private *priv;
3796 struct ksmbd_dir_info *d_info;
3799 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3800 priv = buf->private;
3801 d_info = priv->d_info;
3803 /* dot and dotdot entries are already reserved */
3804 if (!strcmp(".", name) || !strcmp("..", name))
3806 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3808 if (!match_pattern(name, namlen, priv->search_pattern))
3811 d_info->name = name;
3812 d_info->name_len = namlen;
3813 rc = reserve_populate_dentry(d_info, priv->info_level);
3816 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3817 d_info->out_buf_len = 0;
3821 static int verify_info_level(int info_level)
3823 switch (info_level) {
3824 case FILE_FULL_DIRECTORY_INFORMATION:
3825 case FILE_BOTH_DIRECTORY_INFORMATION:
3826 case FILE_DIRECTORY_INFORMATION:
3827 case FILE_NAMES_INFORMATION:
3828 case FILEID_FULL_DIRECTORY_INFORMATION:
3829 case FILEID_BOTH_DIRECTORY_INFORMATION:
3830 case SMB_FIND_FILE_POSIX_INFO:
3839 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3843 free_len = (int)(work->response_sz -
3844 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3848 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3849 unsigned short hdr2_len,
3850 unsigned int out_buf_len)
3854 if (out_buf_len > work->conn->vals->max_trans_size)
3857 free_len = smb2_resp_buf_len(work, hdr2_len);
3861 return min_t(int, out_buf_len, free_len);
3864 int smb2_query_dir(struct ksmbd_work *work)
3866 struct ksmbd_conn *conn = work->conn;
3867 struct smb2_query_directory_req *req;
3868 struct smb2_query_directory_rsp *rsp;
3869 struct ksmbd_share_config *share = work->tcon->share_conf;
3870 struct ksmbd_file *dir_fp = NULL;
3871 struct ksmbd_dir_info d_info;
3873 char *srch_ptr = NULL;
3874 unsigned char srch_flag;
3876 struct smb2_query_dir_private query_dir_private = {NULL, };
3878 WORK_BUFFERS(work, req, rsp);
3880 if (ksmbd_override_fsids(work)) {
3881 rsp->hdr.Status = STATUS_NO_MEMORY;
3882 smb2_set_err_rsp(work);
3886 rc = verify_info_level(req->FileInformationClass);
3892 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3898 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3899 inode_permission(file_mnt_user_ns(dir_fp->filp),
3900 file_inode(dir_fp->filp),
3901 MAY_READ | MAY_EXEC)) {
3902 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
3907 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3908 pr_err("can't do query dir for a file\n");
3913 srch_flag = req->Flags;
3914 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3915 le16_to_cpu(req->FileNameLength), 1,
3917 if (IS_ERR(srch_ptr)) {
3918 ksmbd_debug(SMB, "Search Pattern not found\n");
3922 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3925 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3926 ksmbd_debug(SMB, "Restart directory scan\n");
3927 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3930 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3931 d_info.wptr = (char *)rsp->Buffer;
3932 d_info.rptr = (char *)rsp->Buffer;
3933 d_info.out_buf_len =
3934 smb2_calc_max_out_buf_len(work, 8,
3935 le32_to_cpu(req->OutputBufferLength));
3936 if (d_info.out_buf_len < 0) {
3940 d_info.flags = srch_flag;
3943 * reserve dot and dotdot entries in head of buffer
3946 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3947 dir_fp, &d_info, srch_ptr,
3948 smb2_populate_readdir_entry);
3954 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3955 d_info.hide_dot_file = true;
3957 buffer_sz = d_info.out_buf_len;
3958 d_info.rptr = d_info.wptr;
3959 query_dir_private.work = work;
3960 query_dir_private.search_pattern = srch_ptr;
3961 query_dir_private.dir_fp = dir_fp;
3962 query_dir_private.d_info = &d_info;
3963 query_dir_private.info_level = req->FileInformationClass;
3964 dir_fp->readdir_data.private = &query_dir_private;
3965 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3967 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3969 * req->OutputBufferLength is too small to contain even one entry.
3970 * In this case, it immediately returns OutputBufferLength 0 to client.
3972 if (!d_info.out_buf_len && !d_info.num_entry)
3974 if (rc > 0 || rc == -ENOSPC)
3979 d_info.wptr = d_info.rptr;
3980 d_info.out_buf_len = buffer_sz;
3981 rc = process_query_dir_entries(&query_dir_private);
3985 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3986 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3987 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3989 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3990 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3992 rsp->StructureSize = cpu_to_le16(9);
3993 rsp->OutputBufferOffset = cpu_to_le16(0);
3994 rsp->OutputBufferLength = cpu_to_le32(0);
3996 inc_rfc1001_len(work->response_buf, 9);
3999 ((struct file_directory_info *)
4000 ((char *)rsp->Buffer + d_info.last_entry_offset))
4001 ->NextEntryOffset = 0;
4002 if (d_info.data_count >= d_info.last_entry_off_align)
4003 d_info.data_count -= d_info.last_entry_off_align;
4005 rsp->StructureSize = cpu_to_le16(9);
4006 rsp->OutputBufferOffset = cpu_to_le16(72);
4007 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4008 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
4012 ksmbd_fd_put(work, dir_fp);
4013 ksmbd_revert_fsids(work);
4017 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4022 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4023 else if (rc == -EACCES)
4024 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4025 else if (rc == -ENOENT)
4026 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4027 else if (rc == -EBADF)
4028 rsp->hdr.Status = STATUS_FILE_CLOSED;
4029 else if (rc == -ENOMEM)
4030 rsp->hdr.Status = STATUS_NO_MEMORY;
4031 else if (rc == -EFAULT)
4032 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4033 else if (rc == -EIO)
4034 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4035 if (!rsp->hdr.Status)
4036 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4038 smb2_set_err_rsp(work);
4039 ksmbd_fd_put(work, dir_fp);
4040 ksmbd_revert_fsids(work);
4045 * buffer_check_err() - helper function to check buffer errors
4046 * @reqOutputBufferLength: max buffer length expected in command response
4047 * @rsp: query info response buffer contains output buffer length
4048 * @rsp_org: base response buffer pointer in case of chained response
4049 * @infoclass_size: query info class response buffer size
4051 * Return: 0 on success, otherwise error
4053 static int buffer_check_err(int reqOutputBufferLength,
4054 struct smb2_query_info_rsp *rsp,
4055 void *rsp_org, int infoclass_size)
4057 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4058 if (reqOutputBufferLength < infoclass_size) {
4059 pr_err("Invalid Buffer Size Requested\n");
4060 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4061 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4065 ksmbd_debug(SMB, "Buffer Overflow\n");
4066 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4067 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4068 reqOutputBufferLength);
4069 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4074 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4077 struct smb2_file_standard_info *sinfo;
4079 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4081 sinfo->AllocationSize = cpu_to_le64(4096);
4082 sinfo->EndOfFile = cpu_to_le64(0);
4083 sinfo->NumberOfLinks = cpu_to_le32(1);
4084 sinfo->DeletePending = 1;
4085 sinfo->Directory = 0;
4086 rsp->OutputBufferLength =
4087 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4088 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4091 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4094 struct smb2_file_internal_info *file_info;
4096 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4098 /* any unique number */
4099 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4100 rsp->OutputBufferLength =
4101 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4102 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4105 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4106 struct smb2_query_info_req *req,
4107 struct smb2_query_info_rsp *rsp,
4114 * Windows can sometime send query file info request on
4115 * pipe without opening it, checking error condition here
4117 id = req->VolatileFileId;
4118 if (!ksmbd_session_rpc_method(sess, id))
4121 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4122 req->FileInfoClass, req->VolatileFileId);
4124 switch (req->FileInfoClass) {
4125 case FILE_STANDARD_INFORMATION:
4126 get_standard_info_pipe(rsp, rsp_org);
4127 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4129 FILE_STANDARD_INFORMATION_SIZE);
4131 case FILE_INTERNAL_INFORMATION:
4132 get_internal_info_pipe(rsp, id, rsp_org);
4133 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4135 FILE_INTERNAL_INFORMATION_SIZE);
4138 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4139 req->FileInfoClass);
4146 * smb2_get_ea() - handler for smb2 get extended attribute command
4147 * @work: smb work containing query info command buffer
4148 * @fp: ksmbd_file pointer
4149 * @req: get extended attribute request
4150 * @rsp: response buffer pointer
4151 * @rsp_org: base response buffer pointer in case of chained response
4153 * Return: 0 on success, otherwise error
4155 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4156 struct smb2_query_info_req *req,
4157 struct smb2_query_info_rsp *rsp, void *rsp_org)
4159 struct smb2_ea_info *eainfo, *prev_eainfo;
4160 char *name, *ptr, *xattr_list = NULL, *buf;
4161 int rc, name_len, value_len, xattr_list_len, idx;
4162 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4163 struct smb2_ea_info_req *ea_req = NULL;
4164 const struct path *path;
4165 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4167 if (!(fp->daccess & FILE_READ_EA_LE)) {
4168 pr_err("Not permitted to read ext attr : 0x%x\n",
4173 path = &fp->filp->f_path;
4174 /* single EA entry is requested with given user.* name */
4175 if (req->InputBufferLength) {
4176 if (le32_to_cpu(req->InputBufferLength) <
4177 sizeof(struct smb2_ea_info_req))
4180 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4182 /* need to send all EAs, if no specific EA is requested*/
4183 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4185 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4186 le32_to_cpu(req->Flags));
4190 smb2_calc_max_out_buf_len(work, 8,
4191 le32_to_cpu(req->OutputBufferLength));
4192 if (buf_free_len < 0)
4195 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4197 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4199 } else if (!rc) { /* there is no EA in the file */
4200 ksmbd_debug(SMB, "no ea data in the file\n");
4203 xattr_list_len = rc;
4205 ptr = (char *)rsp->Buffer;
4206 eainfo = (struct smb2_ea_info *)ptr;
4207 prev_eainfo = eainfo;
4210 while (idx < xattr_list_len) {
4211 name = xattr_list + idx;
4212 name_len = strlen(name);
4214 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4215 idx += name_len + 1;
4218 * CIFS does not support EA other than user.* namespace,
4219 * still keep the framework generic, to list other attrs
4222 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4225 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4229 if (req->InputBufferLength &&
4230 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4231 ea_req->EaNameLength))
4234 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4235 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4238 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4239 name_len -= XATTR_USER_PREFIX_LEN;
4241 ptr = (char *)(&eainfo->name + name_len + 1);
4242 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4244 /* bailout if xattr can't fit in buf_free_len */
4245 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4247 if (value_len <= 0) {
4249 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4253 buf_free_len -= value_len;
4254 if (buf_free_len < 0) {
4259 memcpy(ptr, buf, value_len);
4264 eainfo->EaNameLength = name_len;
4266 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4267 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4270 memcpy(eainfo->name, name, name_len);
4272 eainfo->name[name_len] = '\0';
4273 eainfo->EaValueLength = cpu_to_le16(value_len);
4274 next_offset = offsetof(struct smb2_ea_info, name) +
4275 name_len + 1 + value_len;
4277 /* align next xattr entry at 4 byte bundary */
4278 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4279 if (alignment_bytes) {
4280 memset(ptr, '\0', alignment_bytes);
4281 ptr += alignment_bytes;
4282 next_offset += alignment_bytes;
4283 buf_free_len -= alignment_bytes;
4285 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4286 prev_eainfo = eainfo;
4287 eainfo = (struct smb2_ea_info *)ptr;
4288 rsp_data_cnt += next_offset;
4290 if (req->InputBufferLength) {
4291 ksmbd_debug(SMB, "single entry requested\n");
4296 /* no more ea entries */
4297 prev_eainfo->NextEntryOffset = 0;
4300 if (rsp_data_cnt == 0)
4301 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4302 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4303 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4309 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4310 struct ksmbd_file *fp, void *rsp_org)
4312 struct smb2_file_access_info *file_info;
4314 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4315 file_info->AccessFlags = fp->daccess;
4316 rsp->OutputBufferLength =
4317 cpu_to_le32(sizeof(struct smb2_file_access_info));
4318 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4321 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4322 struct ksmbd_file *fp, void *rsp_org)
4324 struct smb2_file_basic_info *basic_info;
4328 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4329 pr_err("no right to read the attributes : 0x%x\n",
4334 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4335 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4337 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4338 time = ksmbd_UnixTimeToNT(stat.atime);
4339 basic_info->LastAccessTime = cpu_to_le64(time);
4340 time = ksmbd_UnixTimeToNT(stat.mtime);
4341 basic_info->LastWriteTime = cpu_to_le64(time);
4342 time = ksmbd_UnixTimeToNT(stat.ctime);
4343 basic_info->ChangeTime = cpu_to_le64(time);
4344 basic_info->Attributes = fp->f_ci->m_fattr;
4345 basic_info->Pad1 = 0;
4346 rsp->OutputBufferLength =
4347 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4348 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4352 static unsigned long long get_allocation_size(struct inode *inode,
4355 unsigned long long alloc_size = 0;
4357 if (!S_ISDIR(stat->mode)) {
4358 if ((inode->i_blocks << 9) <= stat->size)
4359 alloc_size = stat->size;
4361 alloc_size = inode->i_blocks << 9;
4367 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4368 struct ksmbd_file *fp, void *rsp_org)
4370 struct smb2_file_standard_info *sinfo;
4371 unsigned int delete_pending;
4372 struct inode *inode;
4375 inode = file_inode(fp->filp);
4376 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4378 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4379 delete_pending = ksmbd_inode_pending_delete(fp);
4381 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4382 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4383 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4384 sinfo->DeletePending = delete_pending;
4385 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4386 rsp->OutputBufferLength =
4387 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4388 inc_rfc1001_len(rsp_org,
4389 sizeof(struct smb2_file_standard_info));
4392 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4395 struct smb2_file_alignment_info *file_info;
4397 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4398 file_info->AlignmentRequirement = 0;
4399 rsp->OutputBufferLength =
4400 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4401 inc_rfc1001_len(rsp_org,
4402 sizeof(struct smb2_file_alignment_info));
4405 static int get_file_all_info(struct ksmbd_work *work,
4406 struct smb2_query_info_rsp *rsp,
4407 struct ksmbd_file *fp,
4410 struct ksmbd_conn *conn = work->conn;
4411 struct smb2_file_all_info *file_info;
4412 unsigned int delete_pending;
4413 struct inode *inode;
4419 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4420 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4425 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4426 if (IS_ERR(filename))
4427 return PTR_ERR(filename);
4429 inode = file_inode(fp->filp);
4430 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4432 ksmbd_debug(SMB, "filename = %s\n", filename);
4433 delete_pending = ksmbd_inode_pending_delete(fp);
4434 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4436 file_info->CreationTime = cpu_to_le64(fp->create_time);
4437 time = ksmbd_UnixTimeToNT(stat.atime);
4438 file_info->LastAccessTime = cpu_to_le64(time);
4439 time = ksmbd_UnixTimeToNT(stat.mtime);
4440 file_info->LastWriteTime = cpu_to_le64(time);
4441 time = ksmbd_UnixTimeToNT(stat.ctime);
4442 file_info->ChangeTime = cpu_to_le64(time);
4443 file_info->Attributes = fp->f_ci->m_fattr;
4444 file_info->Pad1 = 0;
4445 file_info->AllocationSize =
4446 cpu_to_le64(get_allocation_size(inode, &stat));
4447 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4448 file_info->NumberOfLinks =
4449 cpu_to_le32(get_nlink(&stat) - delete_pending);
4450 file_info->DeletePending = delete_pending;
4451 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4452 file_info->Pad2 = 0;
4453 file_info->IndexNumber = cpu_to_le64(stat.ino);
4454 file_info->EASize = 0;
4455 file_info->AccessFlags = fp->daccess;
4456 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4457 file_info->Mode = fp->coption;
4458 file_info->AlignmentRequirement = 0;
4459 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4460 PATH_MAX, conn->local_nls, 0);
4462 file_info->FileNameLength = cpu_to_le32(conv_len);
4463 rsp->OutputBufferLength =
4464 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4466 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4470 static void get_file_alternate_info(struct ksmbd_work *work,
4471 struct smb2_query_info_rsp *rsp,
4472 struct ksmbd_file *fp,
4475 struct ksmbd_conn *conn = work->conn;
4476 struct smb2_file_alt_name_info *file_info;
4477 struct dentry *dentry = fp->filp->f_path.dentry;
4480 spin_lock(&dentry->d_lock);
4481 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4482 conv_len = ksmbd_extract_shortname(conn,
4483 dentry->d_name.name,
4484 file_info->FileName);
4485 spin_unlock(&dentry->d_lock);
4486 file_info->FileNameLength = cpu_to_le32(conv_len);
4487 rsp->OutputBufferLength =
4488 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4489 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4492 static void get_file_stream_info(struct ksmbd_work *work,
4493 struct smb2_query_info_rsp *rsp,
4494 struct ksmbd_file *fp,
4497 struct ksmbd_conn *conn = work->conn;
4498 struct smb2_file_stream_info *file_info;
4499 char *stream_name, *xattr_list = NULL, *stream_buf;
4501 const struct path *path = &fp->filp->f_path;
4502 ssize_t xattr_list_len;
4503 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4505 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4507 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4509 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4512 smb2_calc_max_out_buf_len(work, 8,
4513 le32_to_cpu(req->OutputBufferLength));
4514 if (buf_free_len < 0)
4517 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4518 if (xattr_list_len < 0) {
4520 } else if (!xattr_list_len) {
4521 ksmbd_debug(SMB, "empty xattr in the file\n");
4525 while (idx < xattr_list_len) {
4526 stream_name = xattr_list + idx;
4527 streamlen = strlen(stream_name);
4528 idx += streamlen + 1;
4530 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4532 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4533 STREAM_PREFIX, STREAM_PREFIX_LEN))
4536 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4538 streamlen = stream_name_len;
4542 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4546 streamlen = snprintf(stream_buf, streamlen + 1,
4547 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4549 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4550 if (next > buf_free_len) {
4555 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4556 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4557 stream_buf, streamlen,
4558 conn->local_nls, 0);
4561 file_info->StreamNameLength = cpu_to_le32(streamlen);
4562 file_info->StreamSize = cpu_to_le64(stream_name_len);
4563 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4566 buf_free_len -= next;
4567 file_info->NextEntryOffset = cpu_to_le32(next);
4571 if (!S_ISDIR(stat.mode) &&
4572 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4573 file_info = (struct smb2_file_stream_info *)
4574 &rsp->Buffer[nbytes];
4575 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4576 "::$DATA", 7, conn->local_nls, 0);
4578 file_info->StreamNameLength = cpu_to_le32(streamlen);
4579 file_info->StreamSize = cpu_to_le64(stat.size);
4580 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4581 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4584 /* last entry offset should be 0 */
4585 file_info->NextEntryOffset = 0;
4588 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4589 inc_rfc1001_len(rsp_org, nbytes);
4592 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4593 struct ksmbd_file *fp, void *rsp_org)
4595 struct smb2_file_internal_info *file_info;
4598 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4600 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4601 file_info->IndexNumber = cpu_to_le64(stat.ino);
4602 rsp->OutputBufferLength =
4603 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4604 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4607 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4608 struct ksmbd_file *fp, void *rsp_org)
4610 struct smb2_file_ntwrk_info *file_info;
4611 struct inode *inode;
4615 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4616 pr_err("no right to read the attributes : 0x%x\n",
4621 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4623 inode = file_inode(fp->filp);
4624 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4626 file_info->CreationTime = cpu_to_le64(fp->create_time);
4627 time = ksmbd_UnixTimeToNT(stat.atime);
4628 file_info->LastAccessTime = cpu_to_le64(time);
4629 time = ksmbd_UnixTimeToNT(stat.mtime);
4630 file_info->LastWriteTime = cpu_to_le64(time);
4631 time = ksmbd_UnixTimeToNT(stat.ctime);
4632 file_info->ChangeTime = cpu_to_le64(time);
4633 file_info->Attributes = fp->f_ci->m_fattr;
4634 file_info->AllocationSize =
4635 cpu_to_le64(get_allocation_size(inode, &stat));
4636 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4637 file_info->Reserved = cpu_to_le32(0);
4638 rsp->OutputBufferLength =
4639 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4640 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4644 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4646 struct smb2_file_ea_info *file_info;
4648 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4649 file_info->EASize = 0;
4650 rsp->OutputBufferLength =
4651 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4652 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4655 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4656 struct ksmbd_file *fp, void *rsp_org)
4658 struct smb2_file_pos_info *file_info;
4660 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4661 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4662 rsp->OutputBufferLength =
4663 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4664 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4667 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4668 struct ksmbd_file *fp, void *rsp_org)
4670 struct smb2_file_mode_info *file_info;
4672 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4673 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4674 rsp->OutputBufferLength =
4675 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4676 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4679 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4680 struct ksmbd_file *fp, void *rsp_org)
4682 struct smb2_file_comp_info *file_info;
4685 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4688 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4689 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4690 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4691 file_info->CompressionUnitShift = 0;
4692 file_info->ChunkShift = 0;
4693 file_info->ClusterShift = 0;
4694 memset(&file_info->Reserved[0], 0, 3);
4696 rsp->OutputBufferLength =
4697 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4698 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4701 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4702 struct ksmbd_file *fp, void *rsp_org)
4704 struct smb2_file_attr_tag_info *file_info;
4706 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4707 pr_err("no right to read the attributes : 0x%x\n",
4712 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4713 file_info->FileAttributes = fp->f_ci->m_fattr;
4714 file_info->ReparseTag = 0;
4715 rsp->OutputBufferLength =
4716 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4717 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4721 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4722 struct ksmbd_file *fp, void *rsp_org)
4724 struct smb311_posix_qinfo *file_info;
4725 struct inode *inode = file_inode(fp->filp);
4726 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4727 vfsuid_t vfsuid = i_uid_into_vfsuid(user_ns, inode);
4728 vfsgid_t vfsgid = i_gid_into_vfsgid(user_ns, inode);
4730 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4732 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4733 file_info->CreationTime = cpu_to_le64(fp->create_time);
4734 time = ksmbd_UnixTimeToNT(inode->i_atime);
4735 file_info->LastAccessTime = cpu_to_le64(time);
4736 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4737 file_info->LastWriteTime = cpu_to_le64(time);
4738 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4739 file_info->ChangeTime = cpu_to_le64(time);
4740 file_info->DosAttributes = fp->f_ci->m_fattr;
4741 file_info->Inode = cpu_to_le64(inode->i_ino);
4742 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4743 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4744 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4745 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4746 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4749 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4750 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4751 * sub_auth(4 * 1(num_subauth)) + RID(4).
4753 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4754 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4755 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4756 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4758 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4759 inc_rfc1001_len(rsp_org, out_buf_len);
4763 static int smb2_get_info_file(struct ksmbd_work *work,
4764 struct smb2_query_info_req *req,
4765 struct smb2_query_info_rsp *rsp)
4767 struct ksmbd_file *fp;
4768 int fileinfoclass = 0;
4770 int file_infoclass_size;
4771 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4773 if (test_share_config_flag(work->tcon->share_conf,
4774 KSMBD_SHARE_FLAG_PIPE)) {
4775 /* smb2 info file called for pipe */
4776 return smb2_get_info_file_pipe(work->sess, req, rsp,
4777 work->response_buf);
4780 if (work->next_smb2_rcv_hdr_off) {
4781 if (!has_file_id(req->VolatileFileId)) {
4782 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4783 work->compound_fid);
4784 id = work->compound_fid;
4785 pid = work->compound_pfid;
4789 if (!has_file_id(id)) {
4790 id = req->VolatileFileId;
4791 pid = req->PersistentFileId;
4794 fp = ksmbd_lookup_fd_slow(work, id, pid);
4798 fileinfoclass = req->FileInfoClass;
4800 switch (fileinfoclass) {
4801 case FILE_ACCESS_INFORMATION:
4802 get_file_access_info(rsp, fp, work->response_buf);
4803 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4806 case FILE_BASIC_INFORMATION:
4807 rc = get_file_basic_info(rsp, fp, work->response_buf);
4808 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4811 case FILE_STANDARD_INFORMATION:
4812 get_file_standard_info(rsp, fp, work->response_buf);
4813 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4816 case FILE_ALIGNMENT_INFORMATION:
4817 get_file_alignment_info(rsp, work->response_buf);
4818 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4821 case FILE_ALL_INFORMATION:
4822 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4823 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4826 case FILE_ALTERNATE_NAME_INFORMATION:
4827 get_file_alternate_info(work, rsp, fp, work->response_buf);
4828 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4831 case FILE_STREAM_INFORMATION:
4832 get_file_stream_info(work, rsp, fp, work->response_buf);
4833 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4836 case FILE_INTERNAL_INFORMATION:
4837 get_file_internal_info(rsp, fp, work->response_buf);
4838 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4841 case FILE_NETWORK_OPEN_INFORMATION:
4842 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4843 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4846 case FILE_EA_INFORMATION:
4847 get_file_ea_info(rsp, work->response_buf);
4848 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4851 case FILE_FULL_EA_INFORMATION:
4852 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4853 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4856 case FILE_POSITION_INFORMATION:
4857 get_file_position_info(rsp, fp, work->response_buf);
4858 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4861 case FILE_MODE_INFORMATION:
4862 get_file_mode_info(rsp, fp, work->response_buf);
4863 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4866 case FILE_COMPRESSION_INFORMATION:
4867 get_file_compression_info(rsp, fp, work->response_buf);
4868 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4871 case FILE_ATTRIBUTE_TAG_INFORMATION:
4872 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4873 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4875 case SMB_FIND_FILE_POSIX_INFO:
4876 if (!work->tcon->posix_extensions) {
4877 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4880 file_infoclass_size = find_file_posix_info(rsp, fp,
4881 work->response_buf);
4885 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4890 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4891 rsp, work->response_buf,
4892 file_infoclass_size);
4893 ksmbd_fd_put(work, fp);
4897 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4898 struct smb2_query_info_req *req,
4899 struct smb2_query_info_rsp *rsp)
4901 struct ksmbd_session *sess = work->sess;
4902 struct ksmbd_conn *conn = work->conn;
4903 struct ksmbd_share_config *share = work->tcon->share_conf;
4904 int fsinfoclass = 0;
4905 struct kstatfs stfs;
4908 int fs_infoclass_size = 0;
4910 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4912 pr_err("cannot create vfs path\n");
4916 rc = vfs_statfs(&path, &stfs);
4918 pr_err("cannot do stat of path %s\n", share->path);
4923 fsinfoclass = req->FileInfoClass;
4925 switch (fsinfoclass) {
4926 case FS_DEVICE_INFORMATION:
4928 struct filesystem_device_info *info;
4930 info = (struct filesystem_device_info *)rsp->Buffer;
4932 info->DeviceType = cpu_to_le32(stfs.f_type);
4933 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4934 rsp->OutputBufferLength = cpu_to_le32(8);
4935 inc_rfc1001_len(work->response_buf, 8);
4936 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4939 case FS_ATTRIBUTE_INFORMATION:
4941 struct filesystem_attribute_info *info;
4944 info = (struct filesystem_attribute_info *)rsp->Buffer;
4945 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4946 FILE_PERSISTENT_ACLS |
4947 FILE_UNICODE_ON_DISK |
4948 FILE_CASE_PRESERVED_NAMES |
4949 FILE_CASE_SENSITIVE_SEARCH |
4950 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4952 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4954 if (test_share_config_flag(work->tcon->share_conf,
4955 KSMBD_SHARE_FLAG_STREAMS))
4956 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
4958 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4959 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4960 "NTFS", PATH_MAX, conn->local_nls, 0);
4962 info->FileSystemNameLen = cpu_to_le32(len);
4963 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4964 rsp->OutputBufferLength = cpu_to_le32(sz);
4965 inc_rfc1001_len(work->response_buf, sz);
4966 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4969 case FS_VOLUME_INFORMATION:
4971 struct filesystem_vol_info *info;
4973 unsigned int serial_crc = 0;
4975 info = (struct filesystem_vol_info *)(rsp->Buffer);
4976 info->VolumeCreationTime = 0;
4977 serial_crc = crc32_le(serial_crc, share->name,
4978 strlen(share->name));
4979 serial_crc = crc32_le(serial_crc, share->path,
4980 strlen(share->path));
4981 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4982 strlen(ksmbd_netbios_name()));
4983 /* Taking dummy value of serial number*/
4984 info->SerialNumber = cpu_to_le32(serial_crc);
4985 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4986 share->name, PATH_MAX,
4987 conn->local_nls, 0);
4989 info->VolumeLabelSize = cpu_to_le32(len);
4991 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4992 rsp->OutputBufferLength = cpu_to_le32(sz);
4993 inc_rfc1001_len(work->response_buf, sz);
4994 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4997 case FS_SIZE_INFORMATION:
4999 struct filesystem_info *info;
5001 info = (struct filesystem_info *)(rsp->Buffer);
5002 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5003 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5004 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5005 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5006 rsp->OutputBufferLength = cpu_to_le32(24);
5007 inc_rfc1001_len(work->response_buf, 24);
5008 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
5011 case FS_FULL_SIZE_INFORMATION:
5013 struct smb2_fs_full_size_info *info;
5015 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5016 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5017 info->CallerAvailableAllocationUnits =
5018 cpu_to_le64(stfs.f_bavail);
5019 info->ActualAvailableAllocationUnits =
5020 cpu_to_le64(stfs.f_bfree);
5021 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5022 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5023 rsp->OutputBufferLength = cpu_to_le32(32);
5024 inc_rfc1001_len(work->response_buf, 32);
5025 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
5028 case FS_OBJECT_ID_INFORMATION:
5030 struct object_id_info *info;
5032 info = (struct object_id_info *)(rsp->Buffer);
5034 if (!user_guest(sess->user))
5035 memcpy(info->objid, user_passkey(sess->user), 16);
5037 memset(info->objid, 0, 16);
5039 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5040 info->extended_info.version = cpu_to_le32(1);
5041 info->extended_info.release = cpu_to_le32(1);
5042 info->extended_info.rel_date = 0;
5043 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5044 rsp->OutputBufferLength = cpu_to_le32(64);
5045 inc_rfc1001_len(work->response_buf, 64);
5046 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5049 case FS_SECTOR_SIZE_INFORMATION:
5051 struct smb3_fs_ss_info *info;
5052 unsigned int sector_size =
5053 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5055 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5057 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5058 info->PhysicalBytesPerSectorForAtomicity =
5059 cpu_to_le32(sector_size);
5060 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5061 info->FSEffPhysicalBytesPerSectorForAtomicity =
5062 cpu_to_le32(sector_size);
5063 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5064 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5065 info->ByteOffsetForSectorAlignment = 0;
5066 info->ByteOffsetForPartitionAlignment = 0;
5067 rsp->OutputBufferLength = cpu_to_le32(28);
5068 inc_rfc1001_len(work->response_buf, 28);
5069 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5072 case FS_CONTROL_INFORMATION:
5075 * TODO : The current implementation is based on
5076 * test result with win7(NTFS) server. It's need to
5077 * modify this to get valid Quota values
5080 struct smb2_fs_control_info *info;
5082 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5083 info->FreeSpaceStartFiltering = 0;
5084 info->FreeSpaceThreshold = 0;
5085 info->FreeSpaceStopFiltering = 0;
5086 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5087 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5089 rsp->OutputBufferLength = cpu_to_le32(48);
5090 inc_rfc1001_len(work->response_buf, 48);
5091 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5094 case FS_POSIX_INFORMATION:
5096 struct filesystem_posix_info *info;
5098 if (!work->tcon->posix_extensions) {
5099 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5102 info = (struct filesystem_posix_info *)(rsp->Buffer);
5103 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5104 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5105 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5106 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5107 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5108 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5109 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5110 rsp->OutputBufferLength = cpu_to_le32(56);
5111 inc_rfc1001_len(work->response_buf, 56);
5112 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5120 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5121 rsp, work->response_buf,
5127 static int smb2_get_info_sec(struct ksmbd_work *work,
5128 struct smb2_query_info_req *req,
5129 struct smb2_query_info_rsp *rsp)
5131 struct ksmbd_file *fp;
5132 struct user_namespace *user_ns;
5133 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5134 struct smb_fattr fattr = {{0}};
5135 struct inode *inode;
5136 __u32 secdesclen = 0;
5137 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5138 int addition_info = le32_to_cpu(req->AdditionalInformation);
5139 int rc = 0, ppntsd_size = 0;
5141 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5142 PROTECTED_DACL_SECINFO |
5143 UNPROTECTED_DACL_SECINFO)) {
5144 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5147 pntsd->revision = cpu_to_le16(1);
5148 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5149 pntsd->osidoffset = 0;
5150 pntsd->gsidoffset = 0;
5151 pntsd->sacloffset = 0;
5152 pntsd->dacloffset = 0;
5154 secdesclen = sizeof(struct smb_ntsd);
5155 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5156 inc_rfc1001_len(work->response_buf, secdesclen);
5161 if (work->next_smb2_rcv_hdr_off) {
5162 if (!has_file_id(req->VolatileFileId)) {
5163 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5164 work->compound_fid);
5165 id = work->compound_fid;
5166 pid = work->compound_pfid;
5170 if (!has_file_id(id)) {
5171 id = req->VolatileFileId;
5172 pid = req->PersistentFileId;
5175 fp = ksmbd_lookup_fd_slow(work, id, pid);
5179 user_ns = file_mnt_user_ns(fp->filp);
5180 inode = file_inode(fp->filp);
5181 ksmbd_acls_fattr(&fattr, user_ns, inode);
5183 if (test_share_config_flag(work->tcon->share_conf,
5184 KSMBD_SHARE_FLAG_ACL_XATTR))
5185 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5186 fp->filp->f_path.dentry,
5189 /* Check if sd buffer size exceeds response buffer size */
5190 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5191 rc = build_sec_desc(user_ns, pntsd, ppntsd, ppntsd_size,
5192 addition_info, &secdesclen, &fattr);
5193 posix_acl_release(fattr.cf_acls);
5194 posix_acl_release(fattr.cf_dacls);
5196 ksmbd_fd_put(work, fp);
5200 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5201 inc_rfc1001_len(work->response_buf, secdesclen);
5206 * smb2_query_info() - handler for smb2 query info command
5207 * @work: smb work containing query info request buffer
5209 * Return: 0 on success, otherwise error
5211 int smb2_query_info(struct ksmbd_work *work)
5213 struct smb2_query_info_req *req;
5214 struct smb2_query_info_rsp *rsp;
5217 WORK_BUFFERS(work, req, rsp);
5219 ksmbd_debug(SMB, "GOT query info request\n");
5221 switch (req->InfoType) {
5222 case SMB2_O_INFO_FILE:
5223 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5224 rc = smb2_get_info_file(work, req, rsp);
5226 case SMB2_O_INFO_FILESYSTEM:
5227 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5228 rc = smb2_get_info_filesystem(work, req, rsp);
5230 case SMB2_O_INFO_SECURITY:
5231 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5232 rc = smb2_get_info_sec(work, req, rsp);
5235 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5242 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5243 else if (rc == -ENOENT)
5244 rsp->hdr.Status = STATUS_FILE_CLOSED;
5245 else if (rc == -EIO)
5246 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5247 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5248 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5249 smb2_set_err_rsp(work);
5251 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5255 rsp->StructureSize = cpu_to_le16(9);
5256 rsp->OutputBufferOffset = cpu_to_le16(72);
5257 inc_rfc1001_len(work->response_buf, 8);
5262 * smb2_close_pipe() - handler for closing IPC pipe
5263 * @work: smb work containing close request buffer
5267 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5270 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5271 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5273 id = req->VolatileFileId;
5274 ksmbd_session_rpc_close(work->sess, id);
5276 rsp->StructureSize = cpu_to_le16(60);
5279 rsp->CreationTime = 0;
5280 rsp->LastAccessTime = 0;
5281 rsp->LastWriteTime = 0;
5282 rsp->ChangeTime = 0;
5283 rsp->AllocationSize = 0;
5285 rsp->Attributes = 0;
5286 inc_rfc1001_len(work->response_buf, 60);
5291 * smb2_close() - handler for smb2 close file command
5292 * @work: smb work containing close request buffer
5296 int smb2_close(struct ksmbd_work *work)
5298 u64 volatile_id = KSMBD_NO_FID;
5300 struct smb2_close_req *req;
5301 struct smb2_close_rsp *rsp;
5302 struct ksmbd_conn *conn = work->conn;
5303 struct ksmbd_file *fp;
5304 struct inode *inode;
5308 WORK_BUFFERS(work, req, rsp);
5310 if (test_share_config_flag(work->tcon->share_conf,
5311 KSMBD_SHARE_FLAG_PIPE)) {
5312 ksmbd_debug(SMB, "IPC pipe close request\n");
5313 return smb2_close_pipe(work);
5316 sess_id = le64_to_cpu(req->hdr.SessionId);
5317 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5318 sess_id = work->compound_sid;
5320 work->compound_sid = 0;
5321 if (check_session_id(conn, sess_id)) {
5322 work->compound_sid = sess_id;
5324 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5325 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5326 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5331 if (work->next_smb2_rcv_hdr_off &&
5332 !has_file_id(req->VolatileFileId)) {
5333 if (!has_file_id(work->compound_fid)) {
5334 /* file already closed, return FILE_CLOSED */
5335 ksmbd_debug(SMB, "file already closed\n");
5336 rsp->hdr.Status = STATUS_FILE_CLOSED;
5341 "Compound request set FID = %llu:%llu\n",
5343 work->compound_pfid);
5344 volatile_id = work->compound_fid;
5346 /* file closed, stored id is not valid anymore */
5347 work->compound_fid = KSMBD_NO_FID;
5348 work->compound_pfid = KSMBD_NO_FID;
5351 volatile_id = req->VolatileFileId;
5353 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5355 rsp->StructureSize = cpu_to_le16(60);
5358 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5359 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5365 inode = file_inode(fp->filp);
5366 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5367 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5368 cpu_to_le64(inode->i_blocks << 9);
5369 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5370 rsp->Attributes = fp->f_ci->m_fattr;
5371 rsp->CreationTime = cpu_to_le64(fp->create_time);
5372 time = ksmbd_UnixTimeToNT(inode->i_atime);
5373 rsp->LastAccessTime = cpu_to_le64(time);
5374 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5375 rsp->LastWriteTime = cpu_to_le64(time);
5376 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5377 rsp->ChangeTime = cpu_to_le64(time);
5378 ksmbd_fd_put(work, fp);
5381 rsp->AllocationSize = 0;
5383 rsp->Attributes = 0;
5384 rsp->CreationTime = 0;
5385 rsp->LastAccessTime = 0;
5386 rsp->LastWriteTime = 0;
5387 rsp->ChangeTime = 0;
5390 err = ksmbd_close_fd(work, volatile_id);
5393 if (rsp->hdr.Status == 0)
5394 rsp->hdr.Status = STATUS_FILE_CLOSED;
5395 smb2_set_err_rsp(work);
5397 inc_rfc1001_len(work->response_buf, 60);
5404 * smb2_echo() - handler for smb2 echo(ping) command
5405 * @work: smb work containing echo request buffer
5409 int smb2_echo(struct ksmbd_work *work)
5411 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5413 rsp->StructureSize = cpu_to_le16(4);
5415 inc_rfc1001_len(work->response_buf, 4);
5419 static int smb2_rename(struct ksmbd_work *work,
5420 struct ksmbd_file *fp,
5421 struct user_namespace *user_ns,
5422 struct smb2_file_rename_info *file_info,
5423 struct nls_table *local_nls)
5425 struct ksmbd_share_config *share = fp->tcon->share_conf;
5426 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5427 char *pathname = NULL;
5429 bool file_present = true;
5432 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5433 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5437 abs_oldname = file_path(fp->filp, pathname, PATH_MAX);
5438 if (IS_ERR(abs_oldname)) {
5442 old_name = strrchr(abs_oldname, '/');
5443 if (old_name && old_name[1] != '\0') {
5446 ksmbd_debug(SMB, "can't get last component in path %s\n",
5452 new_name = smb2_get_name(file_info->FileName,
5453 le32_to_cpu(file_info->FileNameLength),
5455 if (IS_ERR(new_name)) {
5456 rc = PTR_ERR(new_name);
5460 if (strchr(new_name, ':')) {
5462 char *xattr_stream_name, *stream_name = NULL;
5463 size_t xattr_stream_size;
5466 rc = parse_stream_name(new_name, &stream_name, &s_type);
5470 len = strlen(new_name);
5471 if (len > 0 && new_name[len - 1] != '/') {
5472 pr_err("not allow base filename in rename\n");
5477 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5484 rc = ksmbd_vfs_setxattr(user_ns,
5485 fp->filp->f_path.dentry,
5489 pr_err("failed to store stream name in xattr: %d\n",
5498 ksmbd_debug(SMB, "new name %s\n", new_name);
5499 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5503 file_present = false;
5508 if (ksmbd_share_veto_filename(share, new_name)) {
5510 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5514 if (file_info->ReplaceIfExists) {
5516 rc = ksmbd_vfs_remove_file(work, new_name);
5518 if (rc != -ENOTEMPTY)
5520 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5527 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5530 "cannot rename already existing file\n");
5535 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5538 if (!IS_ERR(new_name))
5543 static int smb2_create_link(struct ksmbd_work *work,
5544 struct ksmbd_share_config *share,
5545 struct smb2_file_link_info *file_info,
5546 unsigned int buf_len, struct file *filp,
5547 struct nls_table *local_nls)
5549 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5551 bool file_present = true;
5554 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5555 le32_to_cpu(file_info->FileNameLength))
5558 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5559 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5563 link_name = smb2_get_name(file_info->FileName,
5564 le32_to_cpu(file_info->FileNameLength),
5566 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5571 ksmbd_debug(SMB, "link name is %s\n", link_name);
5572 target_name = file_path(filp, pathname, PATH_MAX);
5573 if (IS_ERR(target_name)) {
5578 ksmbd_debug(SMB, "target name is %s\n", target_name);
5579 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5583 file_present = false;
5588 if (file_info->ReplaceIfExists) {
5590 rc = ksmbd_vfs_remove_file(work, link_name);
5593 ksmbd_debug(SMB, "cannot delete %s\n",
5601 ksmbd_debug(SMB, "link already exists\n");
5606 rc = ksmbd_vfs_link(work, target_name, link_name);
5610 if (!IS_ERR(link_name))
5616 static int set_file_basic_info(struct ksmbd_file *fp,
5617 struct smb2_file_basic_info *file_info,
5618 struct ksmbd_share_config *share)
5622 struct inode *inode;
5623 struct user_namespace *user_ns;
5626 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5631 inode = file_inode(filp);
5632 user_ns = file_mnt_user_ns(filp);
5634 if (file_info->CreationTime)
5635 fp->create_time = le64_to_cpu(file_info->CreationTime);
5637 if (file_info->LastAccessTime) {
5638 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5639 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5642 attrs.ia_valid |= ATTR_CTIME;
5643 if (file_info->ChangeTime)
5644 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5646 attrs.ia_ctime = inode->i_ctime;
5648 if (file_info->LastWriteTime) {
5649 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5650 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5653 if (file_info->Attributes) {
5654 if (!S_ISDIR(inode->i_mode) &&
5655 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5656 pr_err("can't change a file to a directory\n");
5660 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5661 fp->f_ci->m_fattr = file_info->Attributes |
5662 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5665 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5666 (file_info->CreationTime || file_info->Attributes)) {
5667 struct xattr_dos_attrib da = {0};
5670 da.itime = fp->itime;
5671 da.create_time = fp->create_time;
5672 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5673 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5674 XATTR_DOSINFO_ITIME;
5676 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5677 filp->f_path.dentry, &da);
5680 "failed to restore file attribute in EA\n");
5684 if (attrs.ia_valid) {
5685 struct dentry *dentry = filp->f_path.dentry;
5686 struct inode *inode = d_inode(dentry);
5688 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5692 inode->i_ctime = attrs.ia_ctime;
5693 attrs.ia_valid &= ~ATTR_CTIME;
5694 rc = notify_change(user_ns, dentry, &attrs, NULL);
5695 inode_unlock(inode);
5700 static int set_file_allocation_info(struct ksmbd_work *work,
5701 struct ksmbd_file *fp,
5702 struct smb2_file_alloc_info *file_alloc_info)
5705 * TODO : It's working fine only when store dos attributes
5706 * is not yes. need to implement a logic which works
5707 * properly with any smb.conf option
5711 struct inode *inode;
5714 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5717 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5718 inode = file_inode(fp->filp);
5720 if (alloc_blks > inode->i_blocks) {
5721 smb_break_all_levII_oplock(work, fp, 1);
5722 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5724 if (rc && rc != -EOPNOTSUPP) {
5725 pr_err("vfs_fallocate is failed : %d\n", rc);
5728 } else if (alloc_blks < inode->i_blocks) {
5732 * Allocation size could be smaller than original one
5733 * which means allocated blocks in file should be
5734 * deallocated. use truncate to cut out it, but inode
5735 * size is also updated with truncate offset.
5736 * inode size is retained by backup inode size.
5738 size = i_size_read(inode);
5739 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5741 pr_err("truncate failed!, err %d\n", rc);
5744 if (size < alloc_blks * 512)
5745 i_size_write(inode, size);
5750 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5751 struct smb2_file_eof_info *file_eof_info)
5754 struct inode *inode;
5757 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5760 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5761 inode = file_inode(fp->filp);
5764 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5765 * on FAT32 shared device, truncate execution time is too long
5766 * and network error could cause from windows client. because
5767 * truncate of some filesystem like FAT32 fill zero data in
5770 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5771 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5772 rc = ksmbd_vfs_truncate(work, fp, newsize);
5774 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5783 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5784 struct smb2_file_rename_info *rename_info,
5785 unsigned int buf_len)
5787 struct user_namespace *user_ns;
5788 struct ksmbd_file *parent_fp;
5789 struct dentry *parent;
5790 struct dentry *dentry = fp->filp->f_path.dentry;
5793 if (!(fp->daccess & FILE_DELETE_LE)) {
5794 pr_err("no right to delete : 0x%x\n", fp->daccess);
5798 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5799 le32_to_cpu(rename_info->FileNameLength))
5802 user_ns = file_mnt_user_ns(fp->filp);
5803 if (ksmbd_stream_fd(fp))
5806 parent = dget_parent(dentry);
5807 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5813 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5814 inode_unlock(d_inode(parent));
5818 if (parent_fp->daccess & FILE_DELETE_LE) {
5819 pr_err("parent dir is opened with delete access\n");
5820 ksmbd_fd_put(work, parent_fp);
5823 ksmbd_fd_put(work, parent_fp);
5826 return smb2_rename(work, fp, user_ns, rename_info,
5827 work->conn->local_nls);
5830 static int set_file_disposition_info(struct ksmbd_file *fp,
5831 struct smb2_file_disposition_info *file_info)
5833 struct inode *inode;
5835 if (!(fp->daccess & FILE_DELETE_LE)) {
5836 pr_err("no right to delete : 0x%x\n", fp->daccess);
5840 inode = file_inode(fp->filp);
5841 if (file_info->DeletePending) {
5842 if (S_ISDIR(inode->i_mode) &&
5843 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5845 ksmbd_set_inode_pending_delete(fp);
5847 ksmbd_clear_inode_pending_delete(fp);
5852 static int set_file_position_info(struct ksmbd_file *fp,
5853 struct smb2_file_pos_info *file_info)
5855 loff_t current_byte_offset;
5856 unsigned long sector_size;
5857 struct inode *inode;
5859 inode = file_inode(fp->filp);
5860 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5861 sector_size = inode->i_sb->s_blocksize;
5863 if (current_byte_offset < 0 ||
5864 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5865 current_byte_offset & (sector_size - 1))) {
5866 pr_err("CurrentByteOffset is not valid : %llu\n",
5867 current_byte_offset);
5871 fp->filp->f_pos = current_byte_offset;
5875 static int set_file_mode_info(struct ksmbd_file *fp,
5876 struct smb2_file_mode_info *file_info)
5880 mode = file_info->Mode;
5882 if ((mode & ~FILE_MODE_INFO_MASK)) {
5883 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5888 * TODO : need to implement consideration for
5889 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5891 ksmbd_vfs_set_fadvise(fp->filp, mode);
5897 * smb2_set_info_file() - handler for smb2 set info command
5898 * @work: smb work containing set info command buffer
5899 * @fp: ksmbd_file pointer
5900 * @req: request buffer pointer
5901 * @share: ksmbd_share_config pointer
5903 * Return: 0 on success, otherwise error
5904 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5906 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5907 struct smb2_set_info_req *req,
5908 struct ksmbd_share_config *share)
5910 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5912 switch (req->FileInfoClass) {
5913 case FILE_BASIC_INFORMATION:
5915 if (buf_len < sizeof(struct smb2_file_basic_info))
5918 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5920 case FILE_ALLOCATION_INFORMATION:
5922 if (buf_len < sizeof(struct smb2_file_alloc_info))
5925 return set_file_allocation_info(work, fp,
5926 (struct smb2_file_alloc_info *)req->Buffer);
5928 case FILE_END_OF_FILE_INFORMATION:
5930 if (buf_len < sizeof(struct smb2_file_eof_info))
5933 return set_end_of_file_info(work, fp,
5934 (struct smb2_file_eof_info *)req->Buffer);
5936 case FILE_RENAME_INFORMATION:
5938 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5940 "User does not have write permission\n");
5944 if (buf_len < sizeof(struct smb2_file_rename_info))
5947 return set_rename_info(work, fp,
5948 (struct smb2_file_rename_info *)req->Buffer,
5951 case FILE_LINK_INFORMATION:
5953 if (buf_len < sizeof(struct smb2_file_link_info))
5956 return smb2_create_link(work, work->tcon->share_conf,
5957 (struct smb2_file_link_info *)req->Buffer,
5959 work->conn->local_nls);
5961 case FILE_DISPOSITION_INFORMATION:
5963 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5965 "User does not have write permission\n");
5969 if (buf_len < sizeof(struct smb2_file_disposition_info))
5972 return set_file_disposition_info(fp,
5973 (struct smb2_file_disposition_info *)req->Buffer);
5975 case FILE_FULL_EA_INFORMATION:
5977 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5978 pr_err("Not permitted to write ext attr: 0x%x\n",
5983 if (buf_len < sizeof(struct smb2_ea_info))
5986 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5987 buf_len, &fp->filp->f_path);
5989 case FILE_POSITION_INFORMATION:
5991 if (buf_len < sizeof(struct smb2_file_pos_info))
5994 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5996 case FILE_MODE_INFORMATION:
5998 if (buf_len < sizeof(struct smb2_file_mode_info))
6001 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6005 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6009 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6010 char *buffer, int buf_len)
6012 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6014 fp->saccess |= FILE_SHARE_DELETE_LE;
6016 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6021 * smb2_set_info() - handler for smb2 set info command handler
6022 * @work: smb work containing set info request buffer
6024 * Return: 0 on success, otherwise error
6026 int smb2_set_info(struct ksmbd_work *work)
6028 struct smb2_set_info_req *req;
6029 struct smb2_set_info_rsp *rsp;
6030 struct ksmbd_file *fp;
6032 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6034 ksmbd_debug(SMB, "Received set info request\n");
6036 if (work->next_smb2_rcv_hdr_off) {
6037 req = ksmbd_req_buf_next(work);
6038 rsp = ksmbd_resp_buf_next(work);
6039 if (!has_file_id(req->VolatileFileId)) {
6040 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6041 work->compound_fid);
6042 id = work->compound_fid;
6043 pid = work->compound_pfid;
6046 req = smb2_get_msg(work->request_buf);
6047 rsp = smb2_get_msg(work->response_buf);
6050 if (!has_file_id(id)) {
6051 id = req->VolatileFileId;
6052 pid = req->PersistentFileId;
6055 fp = ksmbd_lookup_fd_slow(work, id, pid);
6057 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6062 switch (req->InfoType) {
6063 case SMB2_O_INFO_FILE:
6064 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6065 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6067 case SMB2_O_INFO_SECURITY:
6068 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6069 if (ksmbd_override_fsids(work)) {
6073 rc = smb2_set_info_sec(fp,
6074 le32_to_cpu(req->AdditionalInformation),
6076 le32_to_cpu(req->BufferLength));
6077 ksmbd_revert_fsids(work);
6086 rsp->StructureSize = cpu_to_le16(2);
6087 inc_rfc1001_len(work->response_buf, 2);
6088 ksmbd_fd_put(work, fp);
6092 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6093 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6094 else if (rc == -EINVAL)
6095 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6096 else if (rc == -ESHARE)
6097 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6098 else if (rc == -ENOENT)
6099 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6100 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6101 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6102 else if (rc == -EAGAIN)
6103 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6104 else if (rc == -EBADF || rc == -ESTALE)
6105 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6106 else if (rc == -EEXIST)
6107 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6108 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6109 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6110 smb2_set_err_rsp(work);
6111 ksmbd_fd_put(work, fp);
6112 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6117 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6118 * @work: smb work containing read IPC pipe command buffer
6120 * Return: 0 on success, otherwise error
6122 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6124 int nbytes = 0, err;
6126 struct ksmbd_rpc_command *rpc_resp;
6127 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6128 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6130 id = req->VolatileFileId;
6132 inc_rfc1001_len(work->response_buf, 16);
6133 rpc_resp = ksmbd_rpc_read(work->sess, id);
6135 if (rpc_resp->flags != KSMBD_RPC_OK) {
6140 work->aux_payload_buf =
6141 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6142 if (!work->aux_payload_buf) {
6147 memcpy(work->aux_payload_buf, rpc_resp->payload,
6148 rpc_resp->payload_sz);
6150 nbytes = rpc_resp->payload_sz;
6151 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6152 work->aux_payload_sz = nbytes;
6156 rsp->StructureSize = cpu_to_le16(17);
6157 rsp->DataOffset = 80;
6159 rsp->DataLength = cpu_to_le32(nbytes);
6160 rsp->DataRemaining = 0;
6162 inc_rfc1001_len(work->response_buf, nbytes);
6166 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6167 smb2_set_err_rsp(work);
6172 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6173 struct smb2_buffer_desc_v1 *desc,
6175 __le16 ChannelInfoLength)
6177 unsigned int i, ch_count;
6179 if (work->conn->dialect == SMB30_PROT_ID &&
6180 Channel != SMB2_CHANNEL_RDMA_V1)
6183 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6184 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6185 for (i = 0; i < ch_count; i++) {
6186 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6188 le32_to_cpu(desc[i].token),
6189 le32_to_cpu(desc[i].length));
6195 work->need_invalidate_rkey =
6196 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6197 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6198 work->remote_key = le32_to_cpu(desc->token);
6202 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6203 struct smb2_read_req *req, void *data_buf,
6208 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6209 (struct smb2_buffer_desc_v1 *)
6210 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6211 le16_to_cpu(req->ReadChannelInfoLength));
6219 * smb2_read() - handler for smb2 read from file
6220 * @work: smb work containing read command buffer
6222 * Return: 0 on success, otherwise error
6224 int smb2_read(struct ksmbd_work *work)
6226 struct ksmbd_conn *conn = work->conn;
6227 struct smb2_read_req *req;
6228 struct smb2_read_rsp *rsp;
6229 struct ksmbd_file *fp = NULL;
6231 size_t length, mincount;
6232 ssize_t nbytes = 0, remain_bytes = 0;
6234 bool is_rdma_channel = false;
6235 unsigned int max_read_size = conn->vals->max_read_size;
6237 WORK_BUFFERS(work, req, rsp);
6239 if (test_share_config_flag(work->tcon->share_conf,
6240 KSMBD_SHARE_FLAG_PIPE)) {
6241 ksmbd_debug(SMB, "IPC pipe read request\n");
6242 return smb2_read_pipe(work);
6245 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6246 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6247 is_rdma_channel = true;
6248 max_read_size = get_smbd_max_read_write_size();
6251 if (is_rdma_channel == true) {
6252 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6254 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6258 err = smb2_set_remote_key_for_rdma(work,
6259 (struct smb2_buffer_desc_v1 *)
6260 ((char *)req + ch_offset),
6262 req->ReadChannelInfoLength);
6267 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6273 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6274 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6279 offset = le64_to_cpu(req->Offset);
6280 length = le32_to_cpu(req->Length);
6281 mincount = le32_to_cpu(req->MinimumCount);
6283 if (length > max_read_size) {
6284 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6290 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6291 fp->filp, offset, length);
6293 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6294 if (!work->aux_payload_buf) {
6299 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6305 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6306 kvfree(work->aux_payload_buf);
6307 work->aux_payload_buf = NULL;
6308 rsp->hdr.Status = STATUS_END_OF_FILE;
6309 smb2_set_err_rsp(work);
6310 ksmbd_fd_put(work, fp);
6314 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6315 nbytes, offset, mincount);
6317 if (is_rdma_channel == true) {
6318 /* write data to the client using rdma channel */
6319 remain_bytes = smb2_read_rdma_channel(work, req,
6320 work->aux_payload_buf,
6322 kvfree(work->aux_payload_buf);
6323 work->aux_payload_buf = NULL;
6326 if (remain_bytes < 0) {
6327 err = (int)remain_bytes;
6332 rsp->StructureSize = cpu_to_le16(17);
6333 rsp->DataOffset = 80;
6335 rsp->DataLength = cpu_to_le32(nbytes);
6336 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6338 inc_rfc1001_len(work->response_buf, 16);
6339 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6340 work->aux_payload_sz = nbytes;
6341 inc_rfc1001_len(work->response_buf, nbytes);
6342 ksmbd_fd_put(work, fp);
6348 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6349 else if (err == -EAGAIN)
6350 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6351 else if (err == -ENOENT)
6352 rsp->hdr.Status = STATUS_FILE_CLOSED;
6353 else if (err == -EACCES)
6354 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6355 else if (err == -ESHARE)
6356 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6357 else if (err == -EINVAL)
6358 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6360 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6362 smb2_set_err_rsp(work);
6364 ksmbd_fd_put(work, fp);
6369 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6370 * @work: smb work containing write IPC pipe command buffer
6372 * Return: 0 on success, otherwise error
6374 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6376 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6377 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6378 struct ksmbd_rpc_command *rpc_resp;
6380 int err = 0, ret = 0;
6384 length = le32_to_cpu(req->Length);
6385 id = req->VolatileFileId;
6387 if ((u64)le16_to_cpu(req->DataOffset) + length >
6388 get_rfc1002_len(work->request_buf)) {
6389 pr_err("invalid write data offset %u, smb_len %u\n",
6390 le16_to_cpu(req->DataOffset),
6391 get_rfc1002_len(work->request_buf));
6396 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6397 le16_to_cpu(req->DataOffset));
6399 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6401 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6402 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6404 smb2_set_err_rsp(work);
6407 if (rpc_resp->flags != KSMBD_RPC_OK) {
6408 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6409 smb2_set_err_rsp(work);
6416 rsp->StructureSize = cpu_to_le16(17);
6417 rsp->DataOffset = 0;
6419 rsp->DataLength = cpu_to_le32(length);
6420 rsp->DataRemaining = 0;
6422 inc_rfc1001_len(work->response_buf, 16);
6426 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6427 smb2_set_err_rsp(work);
6433 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6434 struct smb2_write_req *req,
6435 struct ksmbd_file *fp,
6436 loff_t offset, size_t length, bool sync)
6442 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6446 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6447 (struct smb2_buffer_desc_v1 *)
6448 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6449 le16_to_cpu(req->WriteChannelInfoLength));
6455 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6464 * smb2_write() - handler for smb2 write from file
6465 * @work: smb work containing write command buffer
6467 * Return: 0 on success, otherwise error
6469 int smb2_write(struct ksmbd_work *work)
6471 struct smb2_write_req *req;
6472 struct smb2_write_rsp *rsp;
6473 struct ksmbd_file *fp = NULL;
6478 bool writethrough = false, is_rdma_channel = false;
6480 unsigned int max_write_size = work->conn->vals->max_write_size;
6482 WORK_BUFFERS(work, req, rsp);
6484 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6485 ksmbd_debug(SMB, "IPC pipe write request\n");
6486 return smb2_write_pipe(work);
6489 offset = le64_to_cpu(req->Offset);
6490 length = le32_to_cpu(req->Length);
6492 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6493 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6494 is_rdma_channel = true;
6495 max_write_size = get_smbd_max_read_write_size();
6496 length = le32_to_cpu(req->RemainingBytes);
6499 if (is_rdma_channel == true) {
6500 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6502 if (req->Length != 0 || req->DataOffset != 0 ||
6503 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6507 err = smb2_set_remote_key_for_rdma(work,
6508 (struct smb2_buffer_desc_v1 *)
6509 ((char *)req + ch_offset),
6511 req->WriteChannelInfoLength);
6516 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6517 ksmbd_debug(SMB, "User does not have write permission\n");
6522 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6528 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6529 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6534 if (length > max_write_size) {
6535 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6541 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6542 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6543 writethrough = true;
6545 if (is_rdma_channel == false) {
6546 if (le16_to_cpu(req->DataOffset) <
6547 offsetof(struct smb2_write_req, Buffer)) {
6552 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6553 le16_to_cpu(req->DataOffset));
6555 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6556 fp->filp, offset, length);
6557 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6558 writethrough, &nbytes);
6562 /* read data from the client using rdma channel, and
6565 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6573 rsp->StructureSize = cpu_to_le16(17);
6574 rsp->DataOffset = 0;
6576 rsp->DataLength = cpu_to_le32(nbytes);
6577 rsp->DataRemaining = 0;
6579 inc_rfc1001_len(work->response_buf, 16);
6580 ksmbd_fd_put(work, fp);
6585 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6586 else if (err == -ENOSPC || err == -EFBIG)
6587 rsp->hdr.Status = STATUS_DISK_FULL;
6588 else if (err == -ENOENT)
6589 rsp->hdr.Status = STATUS_FILE_CLOSED;
6590 else if (err == -EACCES)
6591 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6592 else if (err == -ESHARE)
6593 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6594 else if (err == -EINVAL)
6595 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6597 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6599 smb2_set_err_rsp(work);
6600 ksmbd_fd_put(work, fp);
6605 * smb2_flush() - handler for smb2 flush file - fsync
6606 * @work: smb work containing flush command buffer
6608 * Return: 0 on success, otherwise error
6610 int smb2_flush(struct ksmbd_work *work)
6612 struct smb2_flush_req *req;
6613 struct smb2_flush_rsp *rsp;
6616 WORK_BUFFERS(work, req, rsp);
6618 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6620 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6624 rsp->StructureSize = cpu_to_le16(4);
6626 inc_rfc1001_len(work->response_buf, 4);
6631 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6632 smb2_set_err_rsp(work);
6639 * smb2_cancel() - handler for smb2 cancel command
6640 * @work: smb work containing cancel command buffer
6642 * Return: 0 on success, otherwise error
6644 int smb2_cancel(struct ksmbd_work *work)
6646 struct ksmbd_conn *conn = work->conn;
6647 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6648 struct smb2_hdr *chdr;
6649 struct ksmbd_work *iter;
6650 struct list_head *command_list;
6652 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6653 hdr->MessageId, hdr->Flags);
6655 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6656 command_list = &conn->async_requests;
6658 spin_lock(&conn->request_lock);
6659 list_for_each_entry(iter, command_list,
6660 async_request_entry) {
6661 chdr = smb2_get_msg(iter->request_buf);
6663 if (iter->async_id !=
6664 le64_to_cpu(hdr->Id.AsyncId))
6668 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6669 le64_to_cpu(hdr->Id.AsyncId),
6670 le16_to_cpu(chdr->Command));
6671 iter->state = KSMBD_WORK_CANCELLED;
6672 if (iter->cancel_fn)
6673 iter->cancel_fn(iter->cancel_argv);
6676 spin_unlock(&conn->request_lock);
6678 command_list = &conn->requests;
6680 spin_lock(&conn->request_lock);
6681 list_for_each_entry(iter, command_list, request_entry) {
6682 chdr = smb2_get_msg(iter->request_buf);
6684 if (chdr->MessageId != hdr->MessageId ||
6689 "smb2 with mid %llu cancelled command = 0x%x\n",
6690 le64_to_cpu(hdr->MessageId),
6691 le16_to_cpu(chdr->Command));
6692 iter->state = KSMBD_WORK_CANCELLED;
6695 spin_unlock(&conn->request_lock);
6698 /* For SMB2_CANCEL command itself send no response*/
6699 work->send_no_response = 1;
6703 struct file_lock *smb_flock_init(struct file *f)
6705 struct file_lock *fl;
6707 fl = locks_alloc_lock();
6711 locks_init_lock(fl);
6714 fl->fl_pid = current->tgid;
6716 fl->fl_flags = FL_POSIX;
6718 fl->fl_lmops = NULL;
6724 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6728 /* Checking for wrong flag combination during lock request*/
6730 case SMB2_LOCKFLAG_SHARED:
6731 ksmbd_debug(SMB, "received shared request\n");
6733 flock->fl_type = F_RDLCK;
6734 flock->fl_flags |= FL_SLEEP;
6736 case SMB2_LOCKFLAG_EXCLUSIVE:
6737 ksmbd_debug(SMB, "received exclusive request\n");
6739 flock->fl_type = F_WRLCK;
6740 flock->fl_flags |= FL_SLEEP;
6742 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6744 "received shared & fail immediately request\n");
6746 flock->fl_type = F_RDLCK;
6748 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6750 "received exclusive & fail immediately request\n");
6752 flock->fl_type = F_WRLCK;
6754 case SMB2_LOCKFLAG_UNLOCK:
6755 ksmbd_debug(SMB, "received unlock request\n");
6756 flock->fl_type = F_UNLCK;
6764 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6765 unsigned int cmd, int flags,
6766 struct list_head *lock_list)
6768 struct ksmbd_lock *lock;
6770 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6776 lock->start = flock->fl_start;
6777 lock->end = flock->fl_end;
6778 lock->flags = flags;
6779 if (lock->start == lock->end)
6781 INIT_LIST_HEAD(&lock->clist);
6782 INIT_LIST_HEAD(&lock->flist);
6783 INIT_LIST_HEAD(&lock->llist);
6784 list_add_tail(&lock->llist, lock_list);
6789 static void smb2_remove_blocked_lock(void **argv)
6791 struct file_lock *flock = (struct file_lock *)argv[0];
6793 ksmbd_vfs_posix_lock_unblock(flock);
6794 wake_up(&flock->fl_wait);
6797 static inline bool lock_defer_pending(struct file_lock *fl)
6799 /* check pending lock waiters */
6800 return waitqueue_active(&fl->fl_wait);
6804 * smb2_lock() - handler for smb2 file lock command
6805 * @work: smb work containing lock command buffer
6807 * Return: 0 on success, otherwise error
6809 int smb2_lock(struct ksmbd_work *work)
6811 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6812 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6813 struct smb2_lock_element *lock_ele;
6814 struct ksmbd_file *fp = NULL;
6815 struct file_lock *flock = NULL;
6816 struct file *filp = NULL;
6820 int err = -EIO, i, rc = 0;
6821 u64 lock_start, lock_length;
6822 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6823 struct ksmbd_conn *conn;
6825 LIST_HEAD(lock_list);
6826 LIST_HEAD(rollback_list);
6829 ksmbd_debug(SMB, "Received lock request\n");
6830 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6832 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6838 lock_count = le16_to_cpu(req->LockCount);
6839 lock_ele = req->locks;
6841 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6847 for (i = 0; i < lock_count; i++) {
6848 flags = le32_to_cpu(lock_ele[i].Flags);
6850 flock = smb_flock_init(filp);
6854 cmd = smb2_set_flock_flags(flock, flags);
6856 lock_start = le64_to_cpu(lock_ele[i].Offset);
6857 lock_length = le64_to_cpu(lock_ele[i].Length);
6858 if (lock_start > U64_MAX - lock_length) {
6859 pr_err("Invalid lock range requested\n");
6860 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6864 if (lock_start > OFFSET_MAX)
6865 flock->fl_start = OFFSET_MAX;
6867 flock->fl_start = lock_start;
6869 lock_length = le64_to_cpu(lock_ele[i].Length);
6870 if (lock_length > OFFSET_MAX - flock->fl_start)
6871 lock_length = OFFSET_MAX - flock->fl_start;
6873 flock->fl_end = flock->fl_start + lock_length;
6875 if (flock->fl_end < flock->fl_start) {
6877 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6878 flock->fl_end, flock->fl_start);
6879 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6883 /* Check conflict locks in one request */
6884 list_for_each_entry(cmp_lock, &lock_list, llist) {
6885 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6886 cmp_lock->fl->fl_end >= flock->fl_end) {
6887 if (cmp_lock->fl->fl_type != F_UNLCK &&
6888 flock->fl_type != F_UNLCK) {
6889 pr_err("conflict two locks in one request\n");
6896 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6903 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6904 if (smb_lock->cmd < 0) {
6909 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6914 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6915 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6916 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6917 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6922 prior_lock = smb_lock->flags;
6924 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6925 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6929 /* check locks in connection list */
6930 read_lock(&conn_list_lock);
6931 list_for_each_entry(conn, &conn_list, conns_list) {
6932 spin_lock(&conn->llist_lock);
6933 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6934 if (file_inode(cmp_lock->fl->fl_file) !=
6935 file_inode(smb_lock->fl->fl_file))
6938 if (smb_lock->fl->fl_type == F_UNLCK) {
6939 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6940 cmp_lock->start == smb_lock->start &&
6941 cmp_lock->end == smb_lock->end &&
6942 !lock_defer_pending(cmp_lock->fl)) {
6944 list_del(&cmp_lock->flist);
6945 list_del(&cmp_lock->clist);
6946 spin_unlock(&conn->llist_lock);
6947 read_unlock(&conn_list_lock);
6949 locks_free_lock(cmp_lock->fl);
6956 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6957 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6960 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6964 /* check zero byte lock range */
6965 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6966 cmp_lock->start > smb_lock->start &&
6967 cmp_lock->start < smb_lock->end) {
6968 spin_unlock(&conn->llist_lock);
6969 read_unlock(&conn_list_lock);
6970 pr_err("previous lock conflict with zero byte lock range\n");
6974 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6975 smb_lock->start > cmp_lock->start &&
6976 smb_lock->start < cmp_lock->end) {
6977 spin_unlock(&conn->llist_lock);
6978 read_unlock(&conn_list_lock);
6979 pr_err("current lock conflict with zero byte lock range\n");
6983 if (((cmp_lock->start <= smb_lock->start &&
6984 cmp_lock->end > smb_lock->start) ||
6985 (cmp_lock->start < smb_lock->end &&
6986 cmp_lock->end >= smb_lock->end)) &&
6987 !cmp_lock->zero_len && !smb_lock->zero_len) {
6988 spin_unlock(&conn->llist_lock);
6989 read_unlock(&conn_list_lock);
6990 pr_err("Not allow lock operation on exclusive lock range\n");
6994 spin_unlock(&conn->llist_lock);
6996 read_unlock(&conn_list_lock);
6998 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6999 pr_err("Try to unlock nolocked range\n");
7000 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7005 if (smb_lock->zero_len) {
7010 flock = smb_lock->fl;
7011 list_del(&smb_lock->llist);
7013 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7015 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7017 ksmbd_debug(SMB, "File unlocked\n");
7018 } else if (rc == -ENOENT) {
7019 rsp->hdr.Status = STATUS_NOT_LOCKED;
7022 locks_free_lock(flock);
7025 if (rc == FILE_LOCK_DEFERRED) {
7029 "would have to wait for getting lock\n");
7030 spin_lock(&work->conn->llist_lock);
7031 list_add_tail(&smb_lock->clist,
7032 &work->conn->lock_list);
7033 spin_unlock(&work->conn->llist_lock);
7034 list_add(&smb_lock->llist, &rollback_list);
7036 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7043 rc = setup_async_work(work,
7044 smb2_remove_blocked_lock,
7050 spin_lock(&fp->f_lock);
7051 list_add(&work->fp_entry, &fp->blocked_works);
7052 spin_unlock(&fp->f_lock);
7054 smb2_send_interim_resp(work, STATUS_PENDING);
7056 ksmbd_vfs_posix_lock_wait(flock);
7058 spin_lock(&work->conn->request_lock);
7059 spin_lock(&fp->f_lock);
7060 list_del(&work->fp_entry);
7061 work->cancel_fn = NULL;
7063 spin_unlock(&fp->f_lock);
7064 spin_unlock(&work->conn->request_lock);
7066 if (work->state != KSMBD_WORK_ACTIVE) {
7067 list_del(&smb_lock->llist);
7068 spin_lock(&work->conn->llist_lock);
7069 list_del(&smb_lock->clist);
7070 spin_unlock(&work->conn->llist_lock);
7071 locks_free_lock(flock);
7073 if (work->state == KSMBD_WORK_CANCELLED) {
7077 smb2_send_interim_resp(work,
7079 work->send_no_response = 1;
7082 init_smb2_rsp_hdr(work);
7083 smb2_set_err_rsp(work);
7085 STATUS_RANGE_NOT_LOCKED;
7090 list_del(&smb_lock->llist);
7091 spin_lock(&work->conn->llist_lock);
7092 list_del(&smb_lock->clist);
7093 spin_unlock(&work->conn->llist_lock);
7097 spin_lock(&work->conn->llist_lock);
7098 list_add_tail(&smb_lock->clist,
7099 &work->conn->lock_list);
7100 list_add_tail(&smb_lock->flist,
7102 spin_unlock(&work->conn->llist_lock);
7103 list_add(&smb_lock->llist, &rollback_list);
7104 ksmbd_debug(SMB, "successful in taking lock\n");
7111 if (atomic_read(&fp->f_ci->op_count) > 1)
7112 smb_break_all_oplock(work, fp);
7114 rsp->StructureSize = cpu_to_le16(4);
7115 ksmbd_debug(SMB, "successful in taking lock\n");
7116 rsp->hdr.Status = STATUS_SUCCESS;
7118 inc_rfc1001_len(work->response_buf, 4);
7119 ksmbd_fd_put(work, fp);
7123 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7124 locks_free_lock(smb_lock->fl);
7125 list_del(&smb_lock->llist);
7129 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7130 struct file_lock *rlock = NULL;
7132 rlock = smb_flock_init(filp);
7133 rlock->fl_type = F_UNLCK;
7134 rlock->fl_start = smb_lock->start;
7135 rlock->fl_end = smb_lock->end;
7137 rc = vfs_lock_file(filp, 0, rlock, NULL);
7139 pr_err("rollback unlock fail : %d\n", rc);
7141 list_del(&smb_lock->llist);
7142 spin_lock(&work->conn->llist_lock);
7143 if (!list_empty(&smb_lock->flist))
7144 list_del(&smb_lock->flist);
7145 list_del(&smb_lock->clist);
7146 spin_unlock(&work->conn->llist_lock);
7148 locks_free_lock(smb_lock->fl);
7149 locks_free_lock(rlock);
7153 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7155 if (!rsp->hdr.Status) {
7157 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7158 else if (err == -ENOMEM)
7159 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7160 else if (err == -ENOENT)
7161 rsp->hdr.Status = STATUS_FILE_CLOSED;
7163 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7166 smb2_set_err_rsp(work);
7167 ksmbd_fd_put(work, fp);
7171 static int fsctl_copychunk(struct ksmbd_work *work,
7172 struct copychunk_ioctl_req *ci_req,
7173 unsigned int cnt_code,
7174 unsigned int input_count,
7175 unsigned long long volatile_id,
7176 unsigned long long persistent_id,
7177 struct smb2_ioctl_rsp *rsp)
7179 struct copychunk_ioctl_rsp *ci_rsp;
7180 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7181 struct srv_copychunk *chunks;
7182 unsigned int i, chunk_count, chunk_count_written = 0;
7183 unsigned int chunk_size_written = 0;
7184 loff_t total_size_written = 0;
7187 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7189 rsp->VolatileFileId = volatile_id;
7190 rsp->PersistentFileId = persistent_id;
7191 ci_rsp->ChunksWritten =
7192 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7193 ci_rsp->ChunkBytesWritten =
7194 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7195 ci_rsp->TotalBytesWritten =
7196 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7198 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7199 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7200 if (chunk_count == 0)
7202 total_size_written = 0;
7204 /* verify the SRV_COPYCHUNK_COPY packet */
7205 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7206 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7207 chunk_count * sizeof(struct srv_copychunk)) {
7208 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7212 for (i = 0; i < chunk_count; i++) {
7213 if (le32_to_cpu(chunks[i].Length) == 0 ||
7214 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7216 total_size_written += le32_to_cpu(chunks[i].Length);
7219 if (i < chunk_count ||
7220 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7221 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7225 src_fp = ksmbd_lookup_foreign_fd(work,
7226 le64_to_cpu(ci_req->ResumeKey[0]));
7227 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7230 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7231 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7236 rsp->hdr.Status = STATUS_FILE_CLOSED;
7241 * FILE_READ_DATA should only be included in
7242 * the FSCTL_COPYCHUNK case
7244 if (cnt_code == FSCTL_COPYCHUNK &&
7245 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7246 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7250 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7251 chunks, chunk_count,
7252 &chunk_count_written,
7253 &chunk_size_written,
7254 &total_size_written);
7257 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7259 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7260 else if (ret == -EBADF)
7261 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7262 else if (ret == -EFBIG || ret == -ENOSPC)
7263 rsp->hdr.Status = STATUS_DISK_FULL;
7264 else if (ret == -EINVAL)
7265 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7266 else if (ret == -EISDIR)
7267 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7268 else if (ret == -E2BIG)
7269 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7271 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7274 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7275 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7276 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7278 ksmbd_fd_put(work, src_fp);
7279 ksmbd_fd_put(work, dst_fp);
7283 static __be32 idev_ipv4_address(struct in_device *idev)
7287 struct in_ifaddr *ifa;
7290 in_dev_for_each_ifa_rcu(ifa, idev) {
7291 if (ifa->ifa_flags & IFA_F_SECONDARY)
7294 addr = ifa->ifa_address;
7301 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7302 struct smb2_ioctl_rsp *rsp,
7303 unsigned int out_buf_len)
7305 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7307 struct net_device *netdev;
7308 struct sockaddr_storage_rsp *sockaddr_storage;
7310 unsigned long long speed;
7313 for_each_netdev(&init_net, netdev) {
7314 bool ipv4_set = false;
7316 if (netdev->type == ARPHRD_LOOPBACK)
7319 flags = dev_get_flags(netdev);
7320 if (!(flags & IFF_RUNNING))
7324 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7329 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7330 &rsp->Buffer[nbytes];
7331 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7333 nii_rsp->Capability = 0;
7334 if (netdev->real_num_tx_queues > 1)
7335 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7336 if (ksmbd_rdma_capable_netdev(netdev))
7337 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7339 nii_rsp->Next = cpu_to_le32(152);
7340 nii_rsp->Reserved = 0;
7342 if (netdev->ethtool_ops->get_link_ksettings) {
7343 struct ethtool_link_ksettings cmd;
7345 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7346 speed = cmd.base.speed;
7348 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7349 "speed is unknown, defaulting to 1Gb/sec");
7354 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7356 sockaddr_storage = (struct sockaddr_storage_rsp *)
7357 nii_rsp->SockAddr_Storage;
7358 memset(sockaddr_storage, 0, 128);
7361 struct in_device *idev;
7363 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7364 sockaddr_storage->addr4.Port = 0;
7366 idev = __in_dev_get_rtnl(netdev);
7369 sockaddr_storage->addr4.IPv4address =
7370 idev_ipv4_address(idev);
7371 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7375 struct inet6_dev *idev6;
7376 struct inet6_ifaddr *ifa;
7377 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7379 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7380 sockaddr_storage->addr6.Port = 0;
7381 sockaddr_storage->addr6.FlowInfo = 0;
7383 idev6 = __in6_dev_get(netdev);
7387 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7388 if (ifa->flags & (IFA_F_TENTATIVE |
7391 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7394 sockaddr_storage->addr6.ScopeId = 0;
7395 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7400 /* zero if this is last one */
7404 rsp->PersistentFileId = SMB2_NO_FID;
7405 rsp->VolatileFileId = SMB2_NO_FID;
7409 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7410 struct validate_negotiate_info_req *neg_req,
7411 struct validate_negotiate_info_rsp *neg_rsp,
7412 unsigned int in_buf_len)
7417 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7418 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7421 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7422 neg_req->DialectCount);
7423 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7428 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7433 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7438 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7443 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7444 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7445 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7446 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7451 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7452 struct file_allocated_range_buffer *qar_req,
7453 struct file_allocated_range_buffer *qar_rsp,
7454 unsigned int in_count, unsigned int *out_count)
7456 struct ksmbd_file *fp;
7457 loff_t start, length;
7464 start = le64_to_cpu(qar_req->file_offset);
7465 length = le64_to_cpu(qar_req->length);
7467 if (start < 0 || length < 0)
7470 fp = ksmbd_lookup_fd_fast(work, id);
7474 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7475 qar_rsp, in_count, out_count);
7476 if (ret && ret != -E2BIG)
7479 ksmbd_fd_put(work, fp);
7483 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7484 unsigned int out_buf_len,
7485 struct smb2_ioctl_req *req,
7486 struct smb2_ioctl_rsp *rsp)
7488 struct ksmbd_rpc_command *rpc_resp;
7489 char *data_buf = (char *)&req->Buffer[0];
7492 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7493 le32_to_cpu(req->InputCount));
7495 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7497 * set STATUS_SOME_NOT_MAPPED response
7498 * for unknown domain sid.
7500 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7501 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7502 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7504 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7505 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7509 nbytes = rpc_resp->payload_sz;
7510 if (rpc_resp->payload_sz > out_buf_len) {
7511 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7512 nbytes = out_buf_len;
7515 if (!rpc_resp->payload_sz) {
7517 STATUS_UNEXPECTED_IO_ERROR;
7521 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7528 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7529 struct file_sparse *sparse)
7531 struct ksmbd_file *fp;
7532 struct user_namespace *user_ns;
7536 fp = ksmbd_lookup_fd_fast(work, id);
7539 user_ns = file_mnt_user_ns(fp->filp);
7541 old_fattr = fp->f_ci->m_fattr;
7542 if (sparse->SetSparse)
7543 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7545 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7547 if (fp->f_ci->m_fattr != old_fattr &&
7548 test_share_config_flag(work->tcon->share_conf,
7549 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7550 struct xattr_dos_attrib da;
7552 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7553 fp->filp->f_path.dentry, &da);
7557 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7558 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7559 fp->filp->f_path.dentry, &da);
7561 fp->f_ci->m_fattr = old_fattr;
7565 ksmbd_fd_put(work, fp);
7569 static int fsctl_request_resume_key(struct ksmbd_work *work,
7570 struct smb2_ioctl_req *req,
7571 struct resume_key_ioctl_rsp *key_rsp)
7573 struct ksmbd_file *fp;
7575 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7579 memset(key_rsp, 0, sizeof(*key_rsp));
7580 key_rsp->ResumeKey[0] = req->VolatileFileId;
7581 key_rsp->ResumeKey[1] = req->PersistentFileId;
7582 ksmbd_fd_put(work, fp);
7588 * smb2_ioctl() - handler for smb2 ioctl command
7589 * @work: smb work containing ioctl command buffer
7591 * Return: 0 on success, otherwise error
7593 int smb2_ioctl(struct ksmbd_work *work)
7595 struct smb2_ioctl_req *req;
7596 struct smb2_ioctl_rsp *rsp;
7597 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7598 u64 id = KSMBD_NO_FID;
7599 struct ksmbd_conn *conn = work->conn;
7602 if (work->next_smb2_rcv_hdr_off) {
7603 req = ksmbd_req_buf_next(work);
7604 rsp = ksmbd_resp_buf_next(work);
7605 if (!has_file_id(req->VolatileFileId)) {
7606 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7607 work->compound_fid);
7608 id = work->compound_fid;
7611 req = smb2_get_msg(work->request_buf);
7612 rsp = smb2_get_msg(work->response_buf);
7615 if (!has_file_id(id))
7616 id = req->VolatileFileId;
7618 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7619 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7623 cnt_code = le32_to_cpu(req->CtlCode);
7624 ret = smb2_calc_max_out_buf_len(work, 48,
7625 le32_to_cpu(req->MaxOutputResponse));
7627 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7630 out_buf_len = (unsigned int)ret;
7631 in_buf_len = le32_to_cpu(req->InputCount);
7634 case FSCTL_DFS_GET_REFERRALS:
7635 case FSCTL_DFS_GET_REFERRALS_EX:
7636 /* Not support DFS yet */
7637 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7639 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7641 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7643 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7644 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7648 * TODO: This is dummy implementation to pass smbtorture
7649 * Need to check correct response later
7651 memset(obj_buf->ObjectId, 0x0, 16);
7652 memset(obj_buf->BirthVolumeId, 0x0, 16);
7653 memset(obj_buf->BirthObjectId, 0x0, 16);
7654 memset(obj_buf->DomainId, 0x0, 16);
7658 case FSCTL_PIPE_TRANSCEIVE:
7659 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7660 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7662 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7663 if (conn->dialect < SMB30_PROT_ID) {
7668 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7674 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7679 ret = fsctl_validate_negotiate_info(conn,
7680 (struct validate_negotiate_info_req *)&req->Buffer[0],
7681 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7686 nbytes = sizeof(struct validate_negotiate_info_rsp);
7687 rsp->PersistentFileId = SMB2_NO_FID;
7688 rsp->VolatileFileId = SMB2_NO_FID;
7690 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7691 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7696 case FSCTL_REQUEST_RESUME_KEY:
7697 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7702 ret = fsctl_request_resume_key(work, req,
7703 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7706 rsp->PersistentFileId = req->PersistentFileId;
7707 rsp->VolatileFileId = req->VolatileFileId;
7708 nbytes = sizeof(struct resume_key_ioctl_rsp);
7710 case FSCTL_COPYCHUNK:
7711 case FSCTL_COPYCHUNK_WRITE:
7712 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7714 "User does not have write permission\n");
7719 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7724 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7729 nbytes = sizeof(struct copychunk_ioctl_rsp);
7730 rsp->VolatileFileId = req->VolatileFileId;
7731 rsp->PersistentFileId = req->PersistentFileId;
7732 fsctl_copychunk(work,
7733 (struct copychunk_ioctl_req *)&req->Buffer[0],
7734 le32_to_cpu(req->CtlCode),
7735 le32_to_cpu(req->InputCount),
7736 req->VolatileFileId,
7737 req->PersistentFileId,
7740 case FSCTL_SET_SPARSE:
7741 if (in_buf_len < sizeof(struct file_sparse)) {
7746 ret = fsctl_set_sparse(work, id,
7747 (struct file_sparse *)&req->Buffer[0]);
7751 case FSCTL_SET_ZERO_DATA:
7753 struct file_zero_data_information *zero_data;
7754 struct ksmbd_file *fp;
7755 loff_t off, len, bfz;
7757 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7759 "User does not have write permission\n");
7764 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7770 (struct file_zero_data_information *)&req->Buffer[0];
7772 off = le64_to_cpu(zero_data->FileOffset);
7773 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7774 if (off < 0 || bfz < 0 || off > bfz) {
7781 fp = ksmbd_lookup_fd_fast(work, id);
7787 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7788 ksmbd_fd_put(work, fp);
7794 case FSCTL_QUERY_ALLOCATED_RANGES:
7795 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7800 ret = fsctl_query_allocated_ranges(work, id,
7801 (struct file_allocated_range_buffer *)&req->Buffer[0],
7802 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7804 sizeof(struct file_allocated_range_buffer), &nbytes);
7805 if (ret == -E2BIG) {
7806 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7807 } else if (ret < 0) {
7812 nbytes *= sizeof(struct file_allocated_range_buffer);
7814 case FSCTL_GET_REPARSE_POINT:
7816 struct reparse_data_buffer *reparse_ptr;
7817 struct ksmbd_file *fp;
7819 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7820 fp = ksmbd_lookup_fd_fast(work, id);
7822 pr_err("not found fp!!\n");
7827 reparse_ptr->ReparseTag =
7828 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7829 reparse_ptr->ReparseDataLength = 0;
7830 ksmbd_fd_put(work, fp);
7831 nbytes = sizeof(struct reparse_data_buffer);
7834 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7836 struct ksmbd_file *fp_in, *fp_out = NULL;
7837 struct duplicate_extents_to_file *dup_ext;
7838 loff_t src_off, dst_off, length, cloned;
7840 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7845 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7847 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7848 dup_ext->PersistentFileHandle);
7850 pr_err("not found file handle in duplicate extent to file\n");
7855 fp_out = ksmbd_lookup_fd_fast(work, id);
7857 pr_err("not found fp\n");
7862 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7863 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7864 length = le64_to_cpu(dup_ext->ByteCount);
7866 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7867 * should fall back to vfs_copy_file_range(). This could be
7868 * beneficial when re-exporting nfs/smb mount, but note that
7869 * this can result in partial copy that returns an error status.
7870 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7871 * fall back to vfs_copy_file_range(), should be avoided when
7872 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7874 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7875 fp_out->filp, dst_off, length, 0);
7876 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7879 } else if (cloned != length) {
7880 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7881 fp_out->filp, dst_off,
7883 if (cloned != length) {
7892 ksmbd_fd_put(work, fp_in);
7893 ksmbd_fd_put(work, fp_out);
7899 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7905 rsp->CtlCode = cpu_to_le32(cnt_code);
7906 rsp->InputCount = cpu_to_le32(0);
7907 rsp->InputOffset = cpu_to_le32(112);
7908 rsp->OutputOffset = cpu_to_le32(112);
7909 rsp->OutputCount = cpu_to_le32(nbytes);
7910 rsp->StructureSize = cpu_to_le16(49);
7911 rsp->Reserved = cpu_to_le16(0);
7912 rsp->Flags = cpu_to_le32(0);
7913 rsp->Reserved2 = cpu_to_le32(0);
7914 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7920 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7921 else if (ret == -ENOENT)
7922 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7923 else if (ret == -EOPNOTSUPP)
7924 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7925 else if (ret == -ENOSPC)
7926 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7927 else if (ret < 0 || rsp->hdr.Status == 0)
7928 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7929 smb2_set_err_rsp(work);
7934 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7935 * @work: smb work containing oplock break command buffer
7939 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7941 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7942 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7943 struct ksmbd_file *fp;
7944 struct oplock_info *opinfo = NULL;
7947 u64 volatile_id, persistent_id;
7948 char req_oplevel = 0, rsp_oplevel = 0;
7949 unsigned int oplock_change_type;
7951 volatile_id = req->VolatileFid;
7952 persistent_id = req->PersistentFid;
7953 req_oplevel = req->OplockLevel;
7954 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7955 volatile_id, persistent_id, req_oplevel);
7957 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7959 rsp->hdr.Status = STATUS_FILE_CLOSED;
7960 smb2_set_err_rsp(work);
7964 opinfo = opinfo_get(fp);
7966 pr_err("unexpected null oplock_info\n");
7967 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7968 smb2_set_err_rsp(work);
7969 ksmbd_fd_put(work, fp);
7973 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7974 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7978 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7979 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7980 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7984 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7985 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7986 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7987 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7988 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7989 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7990 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7991 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7992 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7993 oplock_change_type = OPLOCK_READ_TO_NONE;
7994 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7995 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7996 err = STATUS_INVALID_DEVICE_STATE;
7997 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7998 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7999 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8000 oplock_change_type = OPLOCK_WRITE_TO_READ;
8001 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8002 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8003 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8004 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8005 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8006 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8007 oplock_change_type = OPLOCK_READ_TO_NONE;
8009 oplock_change_type = 0;
8012 oplock_change_type = 0;
8015 switch (oplock_change_type) {
8016 case OPLOCK_WRITE_TO_READ:
8017 ret = opinfo_write_to_read(opinfo);
8018 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8020 case OPLOCK_WRITE_TO_NONE:
8021 ret = opinfo_write_to_none(opinfo);
8022 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8024 case OPLOCK_READ_TO_NONE:
8025 ret = opinfo_read_to_none(opinfo);
8026 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8029 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8030 opinfo->level, rsp_oplevel);
8034 rsp->hdr.Status = err;
8039 ksmbd_fd_put(work, fp);
8040 opinfo->op_state = OPLOCK_STATE_NONE;
8041 wake_up_interruptible_all(&opinfo->oplock_q);
8043 rsp->StructureSize = cpu_to_le16(24);
8044 rsp->OplockLevel = rsp_oplevel;
8047 rsp->VolatileFid = volatile_id;
8048 rsp->PersistentFid = persistent_id;
8049 inc_rfc1001_len(work->response_buf, 24);
8053 opinfo->op_state = OPLOCK_STATE_NONE;
8054 wake_up_interruptible_all(&opinfo->oplock_q);
8057 ksmbd_fd_put(work, fp);
8058 smb2_set_err_rsp(work);
8061 static int check_lease_state(struct lease *lease, __le32 req_state)
8063 if ((lease->new_state ==
8064 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8065 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8066 lease->new_state = req_state;
8070 if (lease->new_state == req_state)
8077 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8078 * @work: smb work containing lease break command buffer
8082 static void smb21_lease_break_ack(struct ksmbd_work *work)
8084 struct ksmbd_conn *conn = work->conn;
8085 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8086 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8087 struct oplock_info *opinfo;
8090 unsigned int lease_change_type;
8092 struct lease *lease;
8094 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8095 le32_to_cpu(req->LeaseState));
8096 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8098 ksmbd_debug(OPLOCK, "file not opened\n");
8099 smb2_set_err_rsp(work);
8100 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8103 lease = opinfo->o_lease;
8105 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8106 pr_err("unexpected lease break state 0x%x\n",
8108 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8112 if (check_lease_state(lease, req->LeaseState)) {
8113 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8115 "req lease state: 0x%x, expected state: 0x%x\n",
8116 req->LeaseState, lease->new_state);
8120 if (!atomic_read(&opinfo->breaking_cnt)) {
8121 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8125 /* check for bad lease state */
8126 if (req->LeaseState &
8127 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8128 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8129 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8130 lease_change_type = OPLOCK_WRITE_TO_NONE;
8132 lease_change_type = OPLOCK_READ_TO_NONE;
8133 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8134 le32_to_cpu(lease->state),
8135 le32_to_cpu(req->LeaseState));
8136 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8137 req->LeaseState != SMB2_LEASE_NONE_LE) {
8138 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8139 lease_change_type = OPLOCK_READ_TO_NONE;
8140 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8141 le32_to_cpu(lease->state),
8142 le32_to_cpu(req->LeaseState));
8144 /* valid lease state changes */
8145 err = STATUS_INVALID_DEVICE_STATE;
8146 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8147 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8148 lease_change_type = OPLOCK_WRITE_TO_NONE;
8150 lease_change_type = OPLOCK_READ_TO_NONE;
8151 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8152 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8153 lease_change_type = OPLOCK_WRITE_TO_READ;
8155 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8157 lease_change_type = 0;
8161 switch (lease_change_type) {
8162 case OPLOCK_WRITE_TO_READ:
8163 ret = opinfo_write_to_read(opinfo);
8165 case OPLOCK_READ_HANDLE_TO_READ:
8166 ret = opinfo_read_handle_to_read(opinfo);
8168 case OPLOCK_WRITE_TO_NONE:
8169 ret = opinfo_write_to_none(opinfo);
8171 case OPLOCK_READ_TO_NONE:
8172 ret = opinfo_read_to_none(opinfo);
8175 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8176 le32_to_cpu(lease->state),
8177 le32_to_cpu(req->LeaseState));
8180 lease_state = lease->state;
8181 opinfo->op_state = OPLOCK_STATE_NONE;
8182 wake_up_interruptible_all(&opinfo->oplock_q);
8183 atomic_dec(&opinfo->breaking_cnt);
8184 wake_up_interruptible_all(&opinfo->oplock_brk);
8188 rsp->hdr.Status = err;
8192 rsp->StructureSize = cpu_to_le16(36);
8195 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8196 rsp->LeaseState = lease_state;
8197 rsp->LeaseDuration = 0;
8198 inc_rfc1001_len(work->response_buf, 36);
8202 opinfo->op_state = OPLOCK_STATE_NONE;
8203 wake_up_interruptible_all(&opinfo->oplock_q);
8204 atomic_dec(&opinfo->breaking_cnt);
8205 wake_up_interruptible_all(&opinfo->oplock_brk);
8208 smb2_set_err_rsp(work);
8212 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8213 * @work: smb work containing oplock/lease break command buffer
8217 int smb2_oplock_break(struct ksmbd_work *work)
8219 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8220 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8222 switch (le16_to_cpu(req->StructureSize)) {
8223 case OP_BREAK_STRUCT_SIZE_20:
8224 smb20_oplock_break_ack(work);
8226 case OP_BREAK_STRUCT_SIZE_21:
8227 smb21_lease_break_ack(work);
8230 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8231 le16_to_cpu(req->StructureSize));
8232 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8233 smb2_set_err_rsp(work);
8240 * smb2_notify() - handler for smb2 notify request
8241 * @work: smb work containing notify command buffer
8245 int smb2_notify(struct ksmbd_work *work)
8247 struct smb2_change_notify_req *req;
8248 struct smb2_change_notify_rsp *rsp;
8250 WORK_BUFFERS(work, req, rsp);
8252 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8253 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8254 smb2_set_err_rsp(work);
8258 smb2_set_err_rsp(work);
8259 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8264 * smb2_is_sign_req() - handler for checking packet signing status
8265 * @work: smb work containing notify command buffer
8266 * @command: SMB2 command id
8268 * Return: true if packed is signed, false otherwise
8270 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8272 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8274 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8275 command != SMB2_NEGOTIATE_HE &&
8276 command != SMB2_SESSION_SETUP_HE &&
8277 command != SMB2_OPLOCK_BREAK_HE)
8284 * smb2_check_sign_req() - handler for req packet sign processing
8285 * @work: smb work containing notify command buffer
8287 * Return: 1 on success, 0 otherwise
8289 int smb2_check_sign_req(struct ksmbd_work *work)
8291 struct smb2_hdr *hdr;
8292 char signature_req[SMB2_SIGNATURE_SIZE];
8293 char signature[SMB2_HMACSHA256_SIZE];
8297 hdr = smb2_get_msg(work->request_buf);
8298 if (work->next_smb2_rcv_hdr_off)
8299 hdr = ksmbd_req_buf_next(work);
8301 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8302 len = get_rfc1002_len(work->request_buf);
8303 else if (hdr->NextCommand)
8304 len = le32_to_cpu(hdr->NextCommand);
8306 len = get_rfc1002_len(work->request_buf) -
8307 work->next_smb2_rcv_hdr_off;
8309 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8310 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8312 iov[0].iov_base = (char *)&hdr->ProtocolId;
8313 iov[0].iov_len = len;
8315 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8319 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8320 pr_err("bad smb2 signature\n");
8328 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8329 * @work: smb work containing notify command buffer
8332 void smb2_set_sign_rsp(struct ksmbd_work *work)
8334 struct smb2_hdr *hdr;
8335 struct smb2_hdr *req_hdr;
8336 char signature[SMB2_HMACSHA256_SIZE];
8341 hdr = smb2_get_msg(work->response_buf);
8342 if (work->next_smb2_rsp_hdr_off)
8343 hdr = ksmbd_resp_buf_next(work);
8345 req_hdr = ksmbd_req_buf_next(work);
8347 if (!work->next_smb2_rsp_hdr_off) {
8348 len = get_rfc1002_len(work->response_buf);
8349 if (req_hdr->NextCommand)
8350 len = ALIGN(len, 8);
8352 len = get_rfc1002_len(work->response_buf) -
8353 work->next_smb2_rsp_hdr_off;
8354 len = ALIGN(len, 8);
8357 if (req_hdr->NextCommand)
8358 hdr->NextCommand = cpu_to_le32(len);
8360 hdr->Flags |= SMB2_FLAGS_SIGNED;
8361 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8363 iov[0].iov_base = (char *)&hdr->ProtocolId;
8364 iov[0].iov_len = len;
8366 if (work->aux_payload_sz) {
8367 iov[0].iov_len -= work->aux_payload_sz;
8369 iov[1].iov_base = work->aux_payload_buf;
8370 iov[1].iov_len = work->aux_payload_sz;
8374 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8376 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8380 * smb3_check_sign_req() - handler for req packet sign processing
8381 * @work: smb work containing notify command buffer
8383 * Return: 1 on success, 0 otherwise
8385 int smb3_check_sign_req(struct ksmbd_work *work)
8387 struct ksmbd_conn *conn = work->conn;
8389 struct smb2_hdr *hdr;
8390 struct channel *chann;
8391 char signature_req[SMB2_SIGNATURE_SIZE];
8392 char signature[SMB2_CMACAES_SIZE];
8396 hdr = smb2_get_msg(work->request_buf);
8397 if (work->next_smb2_rcv_hdr_off)
8398 hdr = ksmbd_req_buf_next(work);
8400 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8401 len = get_rfc1002_len(work->request_buf);
8402 else if (hdr->NextCommand)
8403 len = le32_to_cpu(hdr->NextCommand);
8405 len = get_rfc1002_len(work->request_buf) -
8406 work->next_smb2_rcv_hdr_off;
8408 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8409 signing_key = work->sess->smb3signingkey;
8411 read_lock(&work->sess->chann_lock);
8412 chann = lookup_chann_list(work->sess, conn);
8414 read_unlock(&work->sess->chann_lock);
8417 signing_key = chann->smb3signingkey;
8418 read_unlock(&work->sess->chann_lock);
8422 pr_err("SMB3 signing key is not generated\n");
8426 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8427 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8428 iov[0].iov_base = (char *)&hdr->ProtocolId;
8429 iov[0].iov_len = len;
8431 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8434 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8435 pr_err("bad smb2 signature\n");
8443 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8444 * @work: smb work containing notify command buffer
8447 void smb3_set_sign_rsp(struct ksmbd_work *work)
8449 struct ksmbd_conn *conn = work->conn;
8450 struct smb2_hdr *req_hdr, *hdr;
8451 struct channel *chann;
8452 char signature[SMB2_CMACAES_SIZE];
8458 hdr = smb2_get_msg(work->response_buf);
8459 if (work->next_smb2_rsp_hdr_off)
8460 hdr = ksmbd_resp_buf_next(work);
8462 req_hdr = ksmbd_req_buf_next(work);
8464 if (!work->next_smb2_rsp_hdr_off) {
8465 len = get_rfc1002_len(work->response_buf);
8466 if (req_hdr->NextCommand)
8467 len = ALIGN(len, 8);
8469 len = get_rfc1002_len(work->response_buf) -
8470 work->next_smb2_rsp_hdr_off;
8471 len = ALIGN(len, 8);
8474 if (conn->binding == false &&
8475 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8476 signing_key = work->sess->smb3signingkey;
8478 read_lock(&work->sess->chann_lock);
8479 chann = lookup_chann_list(work->sess, work->conn);
8481 read_unlock(&work->sess->chann_lock);
8484 signing_key = chann->smb3signingkey;
8485 read_unlock(&work->sess->chann_lock);
8491 if (req_hdr->NextCommand)
8492 hdr->NextCommand = cpu_to_le32(len);
8494 hdr->Flags |= SMB2_FLAGS_SIGNED;
8495 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8496 iov[0].iov_base = (char *)&hdr->ProtocolId;
8497 iov[0].iov_len = len;
8498 if (work->aux_payload_sz) {
8499 iov[0].iov_len -= work->aux_payload_sz;
8500 iov[1].iov_base = work->aux_payload_buf;
8501 iov[1].iov_len = work->aux_payload_sz;
8505 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8506 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8510 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8511 * @work: smb work containing response buffer
8514 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8516 struct ksmbd_conn *conn = work->conn;
8517 struct ksmbd_session *sess = work->sess;
8518 struct smb2_hdr *req, *rsp;
8520 if (conn->dialect != SMB311_PROT_ID)
8523 WORK_BUFFERS(work, req, rsp);
8525 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8527 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8528 conn->preauth_info->Preauth_HashValue);
8530 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8533 if (conn->binding) {
8534 struct preauth_session *preauth_sess;
8536 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8539 hash_value = preauth_sess->Preauth_HashValue;
8541 hash_value = sess->Preauth_HashValue;
8545 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8550 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8552 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8553 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8554 unsigned int orig_len = get_rfc1002_len(old_buf);
8556 /* tr_buf must be cleared by the caller */
8557 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8558 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8559 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8560 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8561 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8562 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8564 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8565 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8566 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8567 inc_rfc1001_len(tr_buf, orig_len);
8570 int smb3_encrypt_resp(struct ksmbd_work *work)
8572 char *buf = work->response_buf;
8575 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8577 if (ARRAY_SIZE(iov) < rq_nvec)
8580 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8584 /* fill transform header */
8585 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8587 iov[0].iov_base = work->tr_buf;
8588 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8589 buf_size += iov[0].iov_len - 4;
8591 iov[1].iov_base = buf + 4;
8592 iov[1].iov_len = get_rfc1002_len(buf);
8593 if (work->aux_payload_sz) {
8594 iov[1].iov_len = work->resp_hdr_sz - 4;
8596 iov[2].iov_base = work->aux_payload_buf;
8597 iov[2].iov_len = work->aux_payload_sz;
8598 buf_size += iov[2].iov_len;
8600 buf_size += iov[1].iov_len;
8601 work->resp_hdr_sz = iov[1].iov_len;
8603 rc = ksmbd_crypt_message(work, iov, rq_nvec, 1);
8607 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8608 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8613 bool smb3_is_transform_hdr(void *buf)
8615 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8617 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8620 int smb3_decrypt_req(struct ksmbd_work *work)
8622 struct ksmbd_session *sess;
8623 char *buf = work->request_buf;
8624 unsigned int pdu_length = get_rfc1002_len(buf);
8626 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8627 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8630 if (buf_data_size < sizeof(struct smb2_hdr)) {
8631 pr_err("Transform message is too small (%u)\n",
8633 return -ECONNABORTED;
8636 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8637 pr_err("Transform message is broken\n");
8638 return -ECONNABORTED;
8641 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8643 pr_err("invalid session id(%llx) in transform header\n",
8644 le64_to_cpu(tr_hdr->SessionId));
8645 return -ECONNABORTED;
8648 iov[0].iov_base = buf;
8649 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8650 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8651 iov[1].iov_len = buf_data_size;
8652 rc = ksmbd_crypt_message(work, iov, 2, 0);
8656 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8657 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8662 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8664 struct ksmbd_conn *conn = work->conn;
8665 struct ksmbd_session *sess = work->sess;
8666 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8668 if (conn->dialect < SMB30_PROT_ID)
8671 if (work->next_smb2_rcv_hdr_off)
8672 rsp = ksmbd_resp_buf_next(work);
8674 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8675 sess->user && !user_guest(sess->user) &&
8676 rsp->Status == STATUS_SUCCESS)