1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
15 #include <linux/filelock.h>
24 #include "connection.h"
25 #include "transport_ipc.h"
26 #include "transport_rdma.h"
28 #include "vfs_cache.h"
32 #include "smb_common.h"
33 #include "smbstatus.h"
34 #include "ksmbd_work.h"
35 #include "mgmt/user_config.h"
36 #include "mgmt/share_config.h"
37 #include "mgmt/tree_connect.h"
38 #include "mgmt/user_session.h"
39 #include "mgmt/ksmbd_ida.h"
42 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
44 if (work->next_smb2_rcv_hdr_off) {
45 *req = ksmbd_req_buf_next(work);
46 *rsp = ksmbd_resp_buf_next(work);
48 *req = smb2_get_msg(work->request_buf);
49 *rsp = smb2_get_msg(work->response_buf);
53 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
56 * check_session_id() - check for valid session id in smb header
57 * @conn: connection instance
58 * @id: session id from smb header
60 * Return: 1 if valid session id, otherwise 0
62 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
64 struct ksmbd_session *sess;
66 if (id == 0 || id == -1)
69 sess = ksmbd_session_lookup_all(conn, id);
72 pr_err("Invalid user session id: %llu\n", id);
76 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
78 return xa_load(&sess->ksmbd_chann_list, (long)conn);
82 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
85 * Return: 0 if there is a tree connection matched or these are
86 * skipable commands, otherwise error
88 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
90 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
91 unsigned int cmd = le16_to_cpu(req_hdr->Command);
95 if (cmd == SMB2_TREE_CONNECT_HE ||
96 cmd == SMB2_CANCEL_HE ||
97 cmd == SMB2_LOGOFF_HE) {
98 ksmbd_debug(SMB, "skip to check tree connect request\n");
102 if (xa_empty(&work->sess->tree_conns)) {
103 ksmbd_debug(SMB, "NO tree connected\n");
107 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
108 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
110 pr_err("Invalid tid %d\n", tree_id);
118 * smb2_set_err_rsp() - set error response code on smb response
119 * @work: smb work containing response buffer
121 void smb2_set_err_rsp(struct ksmbd_work *work)
123 struct smb2_err_rsp *err_rsp;
125 if (work->next_smb2_rcv_hdr_off)
126 err_rsp = ksmbd_resp_buf_next(work);
128 err_rsp = smb2_get_msg(work->response_buf);
130 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
131 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
132 err_rsp->ErrorContextCount = 0;
133 err_rsp->Reserved = 0;
134 err_rsp->ByteCount = 0;
135 err_rsp->ErrorData[0] = 0;
136 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
141 * is_smb2_neg_cmd() - is it smb2 negotiation command
142 * @work: smb work containing smb header
144 * Return: true if smb2 negotiation command, otherwise false
146 bool is_smb2_neg_cmd(struct ksmbd_work *work)
148 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
150 /* is it SMB2 header ? */
151 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
154 /* make sure it is request not response message */
155 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
158 if (hdr->Command != SMB2_NEGOTIATE)
165 * is_smb2_rsp() - is it smb2 response
166 * @work: smb work containing smb response buffer
168 * Return: true if smb2 response, otherwise false
170 bool is_smb2_rsp(struct ksmbd_work *work)
172 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
174 /* is it SMB2 header ? */
175 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
178 /* make sure it is response not request message */
179 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
186 * get_smb2_cmd_val() - get smb command code from smb header
187 * @work: smb work containing smb request buffer
189 * Return: smb2 request command value
191 u16 get_smb2_cmd_val(struct ksmbd_work *work)
193 struct smb2_hdr *rcv_hdr;
195 if (work->next_smb2_rcv_hdr_off)
196 rcv_hdr = ksmbd_req_buf_next(work);
198 rcv_hdr = smb2_get_msg(work->request_buf);
199 return le16_to_cpu(rcv_hdr->Command);
203 * set_smb2_rsp_status() - set error response code on smb2 header
204 * @work: smb work containing response buffer
205 * @err: error response code
207 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
209 struct smb2_hdr *rsp_hdr;
211 if (work->next_smb2_rcv_hdr_off)
212 rsp_hdr = ksmbd_resp_buf_next(work);
214 rsp_hdr = smb2_get_msg(work->response_buf);
215 rsp_hdr->Status = err;
216 smb2_set_err_rsp(work);
220 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
221 * @work: smb work containing smb request buffer
223 * smb2 negotiate response is sent in reply of smb1 negotiate command for
224 * dialect auto-negotiation.
226 int init_smb2_neg_rsp(struct ksmbd_work *work)
228 struct smb2_hdr *rsp_hdr;
229 struct smb2_negotiate_rsp *rsp;
230 struct ksmbd_conn *conn = work->conn;
232 *(__be32 *)work->response_buf =
233 cpu_to_be32(conn->vals->header_size);
235 rsp_hdr = smb2_get_msg(work->response_buf);
236 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
237 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
238 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
239 rsp_hdr->CreditRequest = cpu_to_le16(2);
240 rsp_hdr->Command = SMB2_NEGOTIATE;
241 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
242 rsp_hdr->NextCommand = 0;
243 rsp_hdr->MessageId = 0;
244 rsp_hdr->Id.SyncId.ProcessId = 0;
245 rsp_hdr->Id.SyncId.TreeId = 0;
246 rsp_hdr->SessionId = 0;
247 memset(rsp_hdr->Signature, 0, 16);
249 rsp = smb2_get_msg(work->response_buf);
251 WARN_ON(ksmbd_conn_good(conn));
253 rsp->StructureSize = cpu_to_le16(65);
254 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
255 rsp->DialectRevision = cpu_to_le16(conn->dialect);
256 /* Not setting conn guid rsp->ServerGUID, as it
257 * not used by client for identifying connection
259 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
260 /* Default Max Message Size till SMB2.0, 64K*/
261 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
262 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
263 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
265 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
266 rsp->ServerStartTime = 0;
268 rsp->SecurityBufferOffset = cpu_to_le16(128);
269 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
270 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
271 le16_to_cpu(rsp->SecurityBufferOffset));
272 inc_rfc1001_len(work->response_buf,
273 sizeof(struct smb2_negotiate_rsp) -
274 sizeof(struct smb2_hdr) + AUTH_GSS_LENGTH);
275 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
276 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
277 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
278 conn->use_spnego = true;
280 ksmbd_conn_set_need_negotiate(conn);
285 * smb2_set_rsp_credits() - set number of credits in response buffer
286 * @work: smb work containing smb response buffer
288 int smb2_set_rsp_credits(struct ksmbd_work *work)
290 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
291 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
292 struct ksmbd_conn *conn = work->conn;
293 unsigned short credits_requested, aux_max;
294 unsigned short credit_charge, credits_granted = 0;
296 if (work->send_no_response)
299 hdr->CreditCharge = req_hdr->CreditCharge;
301 if (conn->total_credits > conn->vals->max_credits) {
302 hdr->CreditRequest = 0;
303 pr_err("Total credits overflow: %d\n", conn->total_credits);
307 credit_charge = max_t(unsigned short,
308 le16_to_cpu(req_hdr->CreditCharge), 1);
309 if (credit_charge > conn->total_credits) {
310 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
311 credit_charge, conn->total_credits);
315 conn->total_credits -= credit_charge;
316 conn->outstanding_credits -= credit_charge;
317 credits_requested = max_t(unsigned short,
318 le16_to_cpu(req_hdr->CreditRequest), 1);
320 /* according to smb2.credits smbtorture, Windows server
321 * 2016 or later grant up to 8192 credits at once.
323 * TODO: Need to adjuct CreditRequest value according to
326 if (hdr->Command == SMB2_NEGOTIATE)
329 aux_max = conn->vals->max_credits - credit_charge;
330 credits_granted = min_t(unsigned short, credits_requested, aux_max);
332 if (conn->vals->max_credits - conn->total_credits < credits_granted)
333 credits_granted = conn->vals->max_credits -
336 conn->total_credits += credits_granted;
337 work->credits_granted += credits_granted;
339 if (!req_hdr->NextCommand) {
340 /* Update CreditRequest in last request */
341 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
344 "credits: requested[%d] granted[%d] total_granted[%d]\n",
345 credits_requested, credits_granted,
346 conn->total_credits);
351 * init_chained_smb2_rsp() - initialize smb2 chained response
352 * @work: smb work containing smb response buffer
354 static void init_chained_smb2_rsp(struct ksmbd_work *work)
356 struct smb2_hdr *req = ksmbd_req_buf_next(work);
357 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
358 struct smb2_hdr *rsp_hdr;
359 struct smb2_hdr *rcv_hdr;
360 int next_hdr_offset = 0;
363 /* Len of this response = updated RFC len - offset of previous cmd
364 * in the compound rsp
367 /* Storing the current local FID which may be needed by subsequent
368 * command in the compound request
370 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
371 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
372 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
373 work->compound_sid = le64_to_cpu(rsp->SessionId);
376 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
377 next_hdr_offset = le32_to_cpu(req->NextCommand);
379 new_len = ALIGN(len, 8);
380 inc_rfc1001_len(work->response_buf,
381 sizeof(struct smb2_hdr) + new_len - len);
382 rsp->NextCommand = cpu_to_le32(new_len);
384 work->next_smb2_rcv_hdr_off += next_hdr_offset;
385 work->next_smb2_rsp_hdr_off += new_len;
387 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
388 new_len, work->next_smb2_rcv_hdr_off,
389 work->next_smb2_rsp_hdr_off);
391 rsp_hdr = ksmbd_resp_buf_next(work);
392 rcv_hdr = ksmbd_req_buf_next(work);
394 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
395 ksmbd_debug(SMB, "related flag should be set\n");
396 work->compound_fid = KSMBD_NO_FID;
397 work->compound_pfid = KSMBD_NO_FID;
399 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
400 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
401 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
402 rsp_hdr->Command = rcv_hdr->Command;
405 * Message is response. We don't grant oplock yet.
407 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
408 SMB2_FLAGS_RELATED_OPERATIONS);
409 rsp_hdr->NextCommand = 0;
410 rsp_hdr->MessageId = rcv_hdr->MessageId;
411 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
412 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
413 rsp_hdr->SessionId = rcv_hdr->SessionId;
414 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
418 * is_chained_smb2_message() - check for chained command
419 * @work: smb work containing smb request buffer
421 * Return: true if chained request, otherwise false
423 bool is_chained_smb2_message(struct ksmbd_work *work)
425 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
426 unsigned int len, next_cmd;
428 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
431 hdr = ksmbd_req_buf_next(work);
432 next_cmd = le32_to_cpu(hdr->NextCommand);
434 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
435 __SMB2_HEADER_STRUCTURE_SIZE >
436 get_rfc1002_len(work->request_buf)) {
437 pr_err("next command(%u) offset exceeds smb msg size\n",
442 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
444 pr_err("next response offset exceeds response buffer size\n");
448 ksmbd_debug(SMB, "got SMB2 chained command\n");
449 init_chained_smb2_rsp(work);
451 } else if (work->next_smb2_rcv_hdr_off) {
453 * This is last request in chained command,
454 * align response to 8 byte
456 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
457 len = len - get_rfc1002_len(work->response_buf);
459 ksmbd_debug(SMB, "padding len %u\n", len);
460 inc_rfc1001_len(work->response_buf, len);
461 if (work->aux_payload_sz)
462 work->aux_payload_sz += len;
469 * init_smb2_rsp_hdr() - initialize smb2 response
470 * @work: smb work containing smb request buffer
474 int init_smb2_rsp_hdr(struct ksmbd_work *work)
476 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
477 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
478 struct ksmbd_conn *conn = work->conn;
480 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
481 *(__be32 *)work->response_buf =
482 cpu_to_be32(conn->vals->header_size);
483 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
484 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
485 rsp_hdr->Command = rcv_hdr->Command;
488 * Message is response. We don't grant oplock yet.
490 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
491 rsp_hdr->NextCommand = 0;
492 rsp_hdr->MessageId = rcv_hdr->MessageId;
493 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
494 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
495 rsp_hdr->SessionId = rcv_hdr->SessionId;
496 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
502 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
503 * @work: smb work containing smb request buffer
505 * Return: 0 on success, otherwise -ENOMEM
507 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
509 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
510 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
511 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
512 size_t sz = small_sz;
513 int cmd = le16_to_cpu(hdr->Command);
515 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
518 if (cmd == SMB2_QUERY_INFO_HE) {
519 struct smb2_query_info_req *req;
521 req = smb2_get_msg(work->request_buf);
522 if ((req->InfoType == SMB2_O_INFO_FILE &&
523 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
524 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
525 req->InfoType == SMB2_O_INFO_SECURITY)
529 /* allocate large response buf for chained commands */
530 if (le32_to_cpu(hdr->NextCommand) > 0)
533 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
534 if (!work->response_buf)
537 work->response_sz = sz;
542 * smb2_check_user_session() - check for valid session for a user
543 * @work: smb work containing smb request buffer
545 * Return: 0 on success, otherwise error
547 int smb2_check_user_session(struct ksmbd_work *work)
549 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
550 struct ksmbd_conn *conn = work->conn;
551 unsigned int cmd = conn->ops->get_cmd_val(work);
552 unsigned long long sess_id;
556 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
557 * require a session id, so no need to validate user session's for
560 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
561 cmd == SMB2_SESSION_SETUP_HE)
564 if (!ksmbd_conn_good(conn))
567 sess_id = le64_to_cpu(req_hdr->SessionId);
568 /* Check for validity of user session */
569 work->sess = ksmbd_session_lookup_all(conn, sess_id);
572 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
576 static void destroy_previous_session(struct ksmbd_conn *conn,
577 struct ksmbd_user *user, u64 id)
579 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
580 struct ksmbd_user *prev_user;
581 struct channel *chann;
587 prev_user = prev_sess->user;
590 strcmp(user->name, prev_user->name) ||
591 user->passkey_sz != prev_user->passkey_sz ||
592 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
595 prev_sess->state = SMB2_SESSION_EXPIRED;
596 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
597 ksmbd_conn_set_exiting(chann->conn);
601 * smb2_get_name() - get filename string from on the wire smb format
602 * @src: source buffer
603 * @maxlen: maxlen of source string
604 * @local_nls: nls_table pointer
606 * Return: matching converted filename on success, otherwise error ptr
609 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
613 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
615 pr_err("failed to get name %ld\n", PTR_ERR(name));
619 ksmbd_conv_path_to_unix(name);
620 ksmbd_strip_last_slash(name);
624 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
626 struct smb2_hdr *rsp_hdr;
627 struct ksmbd_conn *conn = work->conn;
630 rsp_hdr = smb2_get_msg(work->response_buf);
631 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
633 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
635 pr_err("Failed to alloc async message id\n");
638 work->asynchronous = true;
640 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
643 "Send interim Response to inform async request id : %d\n",
646 work->cancel_fn = fn;
647 work->cancel_argv = arg;
649 if (list_empty(&work->async_request_entry)) {
650 spin_lock(&conn->request_lock);
651 list_add_tail(&work->async_request_entry, &conn->async_requests);
652 spin_unlock(&conn->request_lock);
658 void release_async_work(struct ksmbd_work *work)
660 struct ksmbd_conn *conn = work->conn;
662 spin_lock(&conn->request_lock);
663 list_del_init(&work->async_request_entry);
664 spin_unlock(&conn->request_lock);
666 work->asynchronous = 0;
667 work->cancel_fn = NULL;
668 kfree(work->cancel_argv);
669 work->cancel_argv = NULL;
670 if (work->async_id) {
671 ksmbd_release_id(&conn->async_ida, work->async_id);
676 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
678 struct smb2_hdr *rsp_hdr;
680 rsp_hdr = smb2_get_msg(work->response_buf);
681 smb2_set_err_rsp(work);
682 rsp_hdr->Status = status;
685 ksmbd_conn_write(work);
690 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
692 if (S_ISDIR(mode) || S_ISREG(mode))
696 return IO_REPARSE_TAG_LX_SYMLINK_LE;
697 else if (S_ISFIFO(mode))
698 return IO_REPARSE_TAG_LX_FIFO_LE;
699 else if (S_ISSOCK(mode))
700 return IO_REPARSE_TAG_AF_UNIX_LE;
701 else if (S_ISCHR(mode))
702 return IO_REPARSE_TAG_LX_CHR_LE;
703 else if (S_ISBLK(mode))
704 return IO_REPARSE_TAG_LX_BLK_LE;
710 * smb2_get_dos_mode() - get file mode in dos format from unix mode
711 * @stat: kstat containing file mode
712 * @attribute: attribute flags
714 * Return: converted dos mode
716 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
720 if (S_ISDIR(stat->mode)) {
721 attr = FILE_ATTRIBUTE_DIRECTORY |
722 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
724 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
725 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
726 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
727 FILE_SUPPORTS_SPARSE_FILES))
728 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
730 if (smb2_get_reparse_tag_special_file(stat->mode))
731 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
737 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
740 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
741 pneg_ctxt->DataLength = cpu_to_le16(38);
742 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
743 pneg_ctxt->Reserved = cpu_to_le32(0);
744 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
745 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
746 pneg_ctxt->HashAlgorithms = hash_id;
749 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
752 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
753 pneg_ctxt->DataLength = cpu_to_le16(4);
754 pneg_ctxt->Reserved = cpu_to_le32(0);
755 pneg_ctxt->CipherCount = cpu_to_le16(1);
756 pneg_ctxt->Ciphers[0] = cipher_type;
759 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
762 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
763 pneg_ctxt->DataLength =
764 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
765 - sizeof(struct smb2_neg_context));
766 pneg_ctxt->Reserved = cpu_to_le32(0);
767 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
768 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
771 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
773 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
774 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
775 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
776 pneg_ctxt->Name[0] = 0x93;
777 pneg_ctxt->Name[1] = 0xAD;
778 pneg_ctxt->Name[2] = 0x25;
779 pneg_ctxt->Name[3] = 0x50;
780 pneg_ctxt->Name[4] = 0x9C;
781 pneg_ctxt->Name[5] = 0xB4;
782 pneg_ctxt->Name[6] = 0x11;
783 pneg_ctxt->Name[7] = 0xE7;
784 pneg_ctxt->Name[8] = 0xB4;
785 pneg_ctxt->Name[9] = 0x23;
786 pneg_ctxt->Name[10] = 0x83;
787 pneg_ctxt->Name[11] = 0xDE;
788 pneg_ctxt->Name[12] = 0x96;
789 pneg_ctxt->Name[13] = 0x8B;
790 pneg_ctxt->Name[14] = 0xCD;
791 pneg_ctxt->Name[15] = 0x7C;
794 static void assemble_neg_contexts(struct ksmbd_conn *conn,
795 struct smb2_negotiate_rsp *rsp,
798 char * const pneg_ctxt = (char *)rsp +
799 le32_to_cpu(rsp->NegotiateContextOffset);
800 int neg_ctxt_cnt = 1;
804 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
805 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
806 conn->preauth_info->Preauth_HashId);
807 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
808 ctxt_size = sizeof(struct smb2_preauth_neg_context);
810 if (conn->cipher_type) {
811 /* Round to 8 byte boundary */
812 ctxt_size = round_up(ctxt_size, 8);
814 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
815 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
816 (pneg_ctxt + ctxt_size),
819 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
822 /* compression context not yet supported */
823 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
825 if (conn->posix_ext_supported) {
826 ctxt_size = round_up(ctxt_size, 8);
828 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
829 build_posix_ctxt((struct smb2_posix_neg_context *)
830 (pneg_ctxt + ctxt_size));
832 ctxt_size += sizeof(struct smb2_posix_neg_context);
835 if (conn->signing_negotiated) {
836 ctxt_size = round_up(ctxt_size, 8);
838 "assemble SMB2_SIGNING_CAPABILITIES context\n");
839 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
840 (pneg_ctxt + ctxt_size),
841 conn->signing_algorithm);
843 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
846 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
847 inc_rfc1001_len(smb2_buf_len, ctxt_size);
850 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
851 struct smb2_preauth_neg_context *pneg_ctxt,
855 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
856 * which may not be present. Only check for used HashAlgorithms[1].
858 if (len_of_ctxts < MIN_PREAUTH_CTXT_DATA_LEN)
859 return STATUS_INVALID_PARAMETER;
861 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
862 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
864 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
865 return STATUS_SUCCESS;
868 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
869 struct smb2_encryption_neg_context *pneg_ctxt,
872 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
873 int i, cphs_size = cph_cnt * sizeof(__le16);
875 conn->cipher_type = 0;
877 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
879 pr_err("Invalid cipher count(%d)\n", cph_cnt);
883 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
886 for (i = 0; i < cph_cnt; i++) {
887 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
888 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
889 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
890 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
891 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
892 pneg_ctxt->Ciphers[i]);
893 conn->cipher_type = pneg_ctxt->Ciphers[i];
900 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
901 * @conn: smb connection
903 * Return: true if connection should be encrypted, else false
905 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
907 if (!conn->ops->generate_encryptionkey)
911 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
912 * SMB 3.1.1 uses the cipher_type field.
914 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
918 static void decode_compress_ctxt(struct ksmbd_conn *conn,
919 struct smb2_compression_capabilities_context *pneg_ctxt)
921 conn->compress_algorithm = SMB3_COMPRESS_NONE;
924 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
925 struct smb2_signing_capabilities *pneg_ctxt,
928 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
929 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
931 conn->signing_negotiated = false;
933 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
935 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
939 for (i = 0; i < sign_algo_cnt; i++) {
940 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
941 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
942 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
943 pneg_ctxt->SigningAlgorithms[i]);
944 conn->signing_negotiated = true;
945 conn->signing_algorithm =
946 pneg_ctxt->SigningAlgorithms[i];
952 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
953 struct smb2_negotiate_req *req,
956 /* +4 is to account for the RFC1001 len field */
957 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
958 int i = 0, len_of_ctxts;
959 int offset = le32_to_cpu(req->NegotiateContextOffset);
960 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
961 __le32 status = STATUS_INVALID_PARAMETER;
963 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
964 if (len_of_smb <= offset) {
965 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
969 len_of_ctxts = len_of_smb - offset;
971 while (i++ < neg_ctxt_cnt) {
974 /* check that offset is not beyond end of SMB */
975 if (len_of_ctxts == 0)
978 if (len_of_ctxts < sizeof(struct smb2_neg_context))
981 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
982 clen = le16_to_cpu(pctx->DataLength);
983 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
986 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
988 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
989 if (conn->preauth_info->Preauth_HashId)
992 status = decode_preauth_ctxt(conn,
993 (struct smb2_preauth_neg_context *)pctx,
995 if (status != STATUS_SUCCESS)
997 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
999 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1000 if (conn->cipher_type)
1003 decode_encrypt_ctxt(conn,
1004 (struct smb2_encryption_neg_context *)pctx,
1006 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1008 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1009 if (conn->compress_algorithm)
1012 decode_compress_ctxt(conn,
1013 (struct smb2_compression_capabilities_context *)pctx);
1014 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1016 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1017 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1019 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1020 conn->posix_ext_supported = true;
1021 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1023 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1024 decode_sign_cap_ctxt(conn,
1025 (struct smb2_signing_capabilities *)pctx,
1029 /* offsets must be 8 byte aligned */
1030 clen = (clen + 7) & ~0x7;
1031 offset = clen + sizeof(struct smb2_neg_context);
1032 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1038 * smb2_handle_negotiate() - handler for smb2 negotiate command
1039 * @work: smb work containing smb request buffer
1043 int smb2_handle_negotiate(struct ksmbd_work *work)
1045 struct ksmbd_conn *conn = work->conn;
1046 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1047 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1049 unsigned int smb2_buf_len, smb2_neg_size;
1052 ksmbd_debug(SMB, "Received negotiate request\n");
1053 conn->need_neg = false;
1054 if (ksmbd_conn_good(conn)) {
1055 pr_err("conn->tcp_status is already in CifsGood State\n");
1056 work->send_no_response = 1;
1060 if (req->DialectCount == 0) {
1061 pr_err("malformed packet\n");
1062 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1067 smb2_buf_len = get_rfc1002_len(work->request_buf);
1068 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1069 if (smb2_neg_size > smb2_buf_len) {
1070 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1075 if (conn->dialect == SMB311_PROT_ID) {
1076 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1078 if (smb2_buf_len < nego_ctxt_off) {
1079 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1084 if (smb2_neg_size > nego_ctxt_off) {
1085 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1090 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1092 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1097 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1099 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1105 conn->cli_cap = le32_to_cpu(req->Capabilities);
1106 switch (conn->dialect) {
1107 case SMB311_PROT_ID:
1108 conn->preauth_info =
1109 kzalloc(sizeof(struct preauth_integrity_info),
1111 if (!conn->preauth_info) {
1113 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1117 status = deassemble_neg_contexts(conn, req,
1118 get_rfc1002_len(work->request_buf));
1119 if (status != STATUS_SUCCESS) {
1120 pr_err("deassemble_neg_contexts error(0x%x)\n",
1122 rsp->hdr.Status = status;
1124 kfree(conn->preauth_info);
1125 conn->preauth_info = NULL;
1129 rc = init_smb3_11_server(conn);
1131 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1132 kfree(conn->preauth_info);
1133 conn->preauth_info = NULL;
1137 ksmbd_gen_preauth_integrity_hash(conn,
1139 conn->preauth_info->Preauth_HashValue);
1140 rsp->NegotiateContextOffset =
1141 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1142 assemble_neg_contexts(conn, rsp, work->response_buf);
1144 case SMB302_PROT_ID:
1145 init_smb3_02_server(conn);
1148 init_smb3_0_server(conn);
1151 init_smb2_1_server(conn);
1156 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1158 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1162 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1165 conn->connection_type = conn->dialect;
1167 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1168 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1169 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1171 memcpy(conn->ClientGUID, req->ClientGUID,
1172 SMB2_CLIENT_GUID_SIZE);
1173 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1175 rsp->StructureSize = cpu_to_le16(65);
1176 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1177 /* Not setting conn guid rsp->ServerGUID, as it
1178 * not used by client for identifying server
1180 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1182 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1183 rsp->ServerStartTime = 0;
1184 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1185 le32_to_cpu(rsp->NegotiateContextOffset),
1186 le16_to_cpu(rsp->NegotiateContextCount));
1188 rsp->SecurityBufferOffset = cpu_to_le16(128);
1189 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1190 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1191 le16_to_cpu(rsp->SecurityBufferOffset));
1192 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1193 sizeof(struct smb2_hdr) + AUTH_GSS_LENGTH);
1194 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1195 conn->use_spnego = true;
1197 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1198 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1199 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1201 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1202 server_conf.enforced_signing = true;
1203 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1207 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1208 ksmbd_conn_set_need_negotiate(conn);
1212 smb2_set_err_rsp(work);
1217 static int alloc_preauth_hash(struct ksmbd_session *sess,
1218 struct ksmbd_conn *conn)
1220 if (sess->Preauth_HashValue)
1223 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1224 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1225 if (!sess->Preauth_HashValue)
1231 static int generate_preauth_hash(struct ksmbd_work *work)
1233 struct ksmbd_conn *conn = work->conn;
1234 struct ksmbd_session *sess = work->sess;
1237 if (conn->dialect != SMB311_PROT_ID)
1240 if (conn->binding) {
1241 struct preauth_session *preauth_sess;
1243 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1244 if (!preauth_sess) {
1245 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1250 preauth_hash = preauth_sess->Preauth_HashValue;
1252 if (!sess->Preauth_HashValue)
1253 if (alloc_preauth_hash(sess, conn))
1255 preauth_hash = sess->Preauth_HashValue;
1258 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1262 static int decode_negotiation_token(struct ksmbd_conn *conn,
1263 struct negotiate_message *negblob,
1266 if (!conn->use_spnego)
1269 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1270 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1271 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1272 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1273 conn->use_spnego = false;
1279 static int ntlm_negotiate(struct ksmbd_work *work,
1280 struct negotiate_message *negblob,
1283 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1284 struct challenge_message *chgblob;
1285 unsigned char *spnego_blob = NULL;
1286 u16 spnego_blob_len;
1290 ksmbd_debug(SMB, "negotiate phase\n");
1291 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1295 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1297 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1298 memset(chgblob, 0, sizeof(struct challenge_message));
1300 if (!work->conn->use_spnego) {
1301 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1305 rsp->SecurityBufferLength = cpu_to_le16(sz);
1309 sz = sizeof(struct challenge_message);
1310 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1312 neg_blob = kzalloc(sz, GFP_KERNEL);
1316 chgblob = (struct challenge_message *)neg_blob;
1317 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1323 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1330 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1331 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1332 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1340 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1341 struct smb2_sess_setup_req *req)
1345 if (conn->use_spnego && conn->mechToken)
1346 return (struct authenticate_message *)conn->mechToken;
1348 sz = le16_to_cpu(req->SecurityBufferOffset);
1349 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1353 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1354 struct smb2_sess_setup_req *req)
1356 struct authenticate_message *authblob;
1357 struct ksmbd_user *user;
1359 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1361 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1362 if (secbuf_len < sizeof(struct authenticate_message)) {
1363 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1366 authblob = user_authblob(conn, req);
1367 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1368 name_len = le16_to_cpu(authblob->UserName.Length);
1369 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1371 if (auth_msg_len < (u64)name_off + name_len)
1374 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1379 pr_err("cannot allocate memory\n");
1383 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1384 user = ksmbd_login_user(name);
1389 static int ntlm_authenticate(struct ksmbd_work *work)
1391 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1392 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1393 struct ksmbd_conn *conn = work->conn;
1394 struct ksmbd_session *sess = work->sess;
1395 struct channel *chann = NULL;
1396 struct ksmbd_user *user;
1400 ksmbd_debug(SMB, "authenticate phase\n");
1401 if (conn->use_spnego) {
1402 unsigned char *spnego_blob;
1403 u16 spnego_blob_len;
1405 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1411 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1412 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1413 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1415 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1418 user = session_user(conn, req);
1420 ksmbd_debug(SMB, "Unknown user name or an error\n");
1424 /* Check for previous session */
1425 prev_id = le64_to_cpu(req->PreviousSessionId);
1426 if (prev_id && prev_id != sess->id)
1427 destroy_previous_session(conn, user, prev_id);
1429 if (sess->state == SMB2_SESSION_VALID) {
1431 * Reuse session if anonymous try to connect
1432 * on reauthetication.
1434 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1435 ksmbd_free_user(user);
1439 if (!ksmbd_compare_user(sess->user, user)) {
1440 ksmbd_free_user(user);
1443 ksmbd_free_user(user);
1448 if (conn->binding == false && user_guest(sess->user)) {
1449 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1451 struct authenticate_message *authblob;
1453 authblob = user_authblob(conn, req);
1454 sz = le16_to_cpu(req->SecurityBufferLength);
1455 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1457 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1458 ksmbd_debug(SMB, "authentication failed\n");
1464 * If session state is SMB2_SESSION_VALID, We can assume
1465 * that it is reauthentication. And the user/password
1466 * has been verified, so return it here.
1468 if (sess->state == SMB2_SESSION_VALID) {
1470 goto binding_session;
1474 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1475 (conn->sign || server_conf.enforced_signing)) ||
1476 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1479 if (smb3_encryption_negotiated(conn) &&
1480 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1481 rc = conn->ops->generate_encryptionkey(conn, sess);
1484 "SMB3 encryption key generation failed\n");
1488 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1489 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1491 * signing is disable if encryption is enable
1498 if (conn->dialect >= SMB30_PROT_ID) {
1499 chann = lookup_chann_list(sess, conn);
1501 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1506 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1510 if (conn->ops->generate_signingkey) {
1511 rc = conn->ops->generate_signingkey(sess, conn);
1513 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1518 if (!ksmbd_conn_lookup_dialect(conn)) {
1519 pr_err("fail to verify the dialect\n");
1525 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1526 static int krb5_authenticate(struct ksmbd_work *work)
1528 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1529 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1530 struct ksmbd_conn *conn = work->conn;
1531 struct ksmbd_session *sess = work->sess;
1532 char *in_blob, *out_blob;
1533 struct channel *chann = NULL;
1535 int in_len, out_len;
1538 in_blob = (char *)&req->hdr.ProtocolId +
1539 le16_to_cpu(req->SecurityBufferOffset);
1540 in_len = le16_to_cpu(req->SecurityBufferLength);
1541 out_blob = (char *)&rsp->hdr.ProtocolId +
1542 le16_to_cpu(rsp->SecurityBufferOffset);
1543 out_len = work->response_sz -
1544 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1546 /* Check previous session */
1547 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1548 if (prev_sess_id && prev_sess_id != sess->id)
1549 destroy_previous_session(conn, sess->user, prev_sess_id);
1551 if (sess->state == SMB2_SESSION_VALID)
1552 ksmbd_free_user(sess->user);
1554 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1555 out_blob, &out_len);
1557 ksmbd_debug(SMB, "krb5 authentication failed\n");
1560 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1561 inc_rfc1001_len(work->response_buf, out_len - 1);
1563 if ((conn->sign || server_conf.enforced_signing) ||
1564 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1567 if (smb3_encryption_negotiated(conn)) {
1568 retval = conn->ops->generate_encryptionkey(conn, sess);
1571 "SMB3 encryption key generation failed\n");
1575 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1576 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1580 if (conn->dialect >= SMB30_PROT_ID) {
1581 chann = lookup_chann_list(sess, conn);
1583 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1588 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1592 if (conn->ops->generate_signingkey) {
1593 retval = conn->ops->generate_signingkey(sess, conn);
1595 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1600 if (!ksmbd_conn_lookup_dialect(conn)) {
1601 pr_err("fail to verify the dialect\n");
1607 static int krb5_authenticate(struct ksmbd_work *work)
1613 int smb2_sess_setup(struct ksmbd_work *work)
1615 struct ksmbd_conn *conn = work->conn;
1616 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1617 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1618 struct ksmbd_session *sess;
1619 struct negotiate_message *negblob;
1620 unsigned int negblob_len, negblob_off;
1623 ksmbd_debug(SMB, "Received request for session setup\n");
1625 rsp->StructureSize = cpu_to_le16(9);
1626 rsp->SessionFlags = 0;
1627 rsp->SecurityBufferOffset = cpu_to_le16(72);
1628 rsp->SecurityBufferLength = 0;
1629 inc_rfc1001_len(work->response_buf, 9);
1631 ksmbd_conn_lock(conn);
1632 if (!req->hdr.SessionId) {
1633 sess = ksmbd_smb2_session_create();
1638 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1639 rc = ksmbd_session_register(conn, sess);
1642 } else if (conn->dialect >= SMB30_PROT_ID &&
1643 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1644 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1645 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1647 sess = ksmbd_session_lookup_slowpath(sess_id);
1653 if (conn->dialect != sess->dialect) {
1658 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1663 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1664 SMB2_CLIENT_GUID_SIZE)) {
1669 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1674 if (sess->state == SMB2_SESSION_EXPIRED) {
1679 if (ksmbd_conn_need_reconnect(conn)) {
1685 if (ksmbd_session_lookup(conn, sess_id)) {
1690 if (user_guest(sess->user)) {
1695 conn->binding = true;
1696 } else if ((conn->dialect < SMB30_PROT_ID ||
1697 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1698 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1703 sess = ksmbd_session_lookup(conn,
1704 le64_to_cpu(req->hdr.SessionId));
1710 if (sess->state == SMB2_SESSION_EXPIRED) {
1715 if (ksmbd_conn_need_reconnect(conn)) {
1723 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1724 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1725 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1726 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1731 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1734 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1735 if (conn->mechToken)
1736 negblob = (struct negotiate_message *)conn->mechToken;
1739 if (server_conf.auth_mechs & conn->auth_mechs) {
1740 rc = generate_preauth_hash(work);
1744 if (conn->preferred_auth_mech &
1745 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1746 rc = krb5_authenticate(work);
1752 if (!ksmbd_conn_need_reconnect(conn)) {
1753 ksmbd_conn_set_good(conn);
1754 sess->state = SMB2_SESSION_VALID;
1756 kfree(sess->Preauth_HashValue);
1757 sess->Preauth_HashValue = NULL;
1758 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1759 if (negblob->MessageType == NtLmNegotiate) {
1760 rc = ntlm_negotiate(work, negblob, negblob_len);
1764 STATUS_MORE_PROCESSING_REQUIRED;
1766 * Note: here total size -1 is done as an
1767 * adjustment for 0 size blob
1769 inc_rfc1001_len(work->response_buf,
1770 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1772 } else if (negblob->MessageType == NtLmAuthenticate) {
1773 rc = ntlm_authenticate(work);
1777 if (!ksmbd_conn_need_reconnect(conn)) {
1778 ksmbd_conn_set_good(conn);
1779 sess->state = SMB2_SESSION_VALID;
1781 if (conn->binding) {
1782 struct preauth_session *preauth_sess;
1785 ksmbd_preauth_session_lookup(conn, sess->id);
1787 list_del(&preauth_sess->preauth_entry);
1788 kfree(preauth_sess);
1791 kfree(sess->Preauth_HashValue);
1792 sess->Preauth_HashValue = NULL;
1794 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1795 le32_to_cpu(negblob->MessageType));
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;
1819 else if (rc == -EOPNOTSUPP)
1820 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1822 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1824 if (conn->use_spnego && conn->mechToken) {
1825 kfree(conn->mechToken);
1826 conn->mechToken = NULL;
1831 * SecurityBufferOffset should be set to zero
1832 * in session setup error response.
1834 rsp->SecurityBufferOffset = 0;
1837 bool try_delay = false;
1840 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1841 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1842 * failure to make it harder to send enough random connection requests
1843 * to break into a server.
1845 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1848 sess->last_active = jiffies;
1849 sess->state = SMB2_SESSION_EXPIRED;
1851 ksmbd_conn_set_need_reconnect(conn);
1853 ksmbd_conn_set_need_negotiate(conn);
1858 ksmbd_conn_unlock(conn);
1863 * smb2_tree_connect() - handler for smb2 tree connect command
1864 * @work: smb work containing smb request buffer
1866 * Return: 0 on success, otherwise error
1868 int smb2_tree_connect(struct ksmbd_work *work)
1870 struct ksmbd_conn *conn = work->conn;
1871 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1872 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1873 struct ksmbd_session *sess = work->sess;
1874 char *treename = NULL, *name = NULL;
1875 struct ksmbd_tree_conn_status status;
1876 struct ksmbd_share_config *share;
1879 treename = smb_strndup_from_utf16(req->Buffer,
1880 le16_to_cpu(req->PathLength), true,
1882 if (IS_ERR(treename)) {
1883 pr_err("treename is NULL\n");
1884 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1888 name = ksmbd_extract_sharename(conn->um, treename);
1890 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1894 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1897 status = ksmbd_tree_conn_connect(conn, sess, name);
1898 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1899 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1903 share = status.tree_conn->share_conf;
1904 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1905 ksmbd_debug(SMB, "IPC share path request\n");
1906 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1907 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1908 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1909 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1910 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1911 FILE_SYNCHRONIZE_LE;
1913 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1914 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1915 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1916 if (test_tree_conn_flag(status.tree_conn,
1917 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1918 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1919 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1920 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1921 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1922 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1923 FILE_SYNCHRONIZE_LE;
1927 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1928 if (conn->posix_ext_supported)
1929 status.tree_conn->posix_extensions = true;
1931 rsp->StructureSize = cpu_to_le16(16);
1932 inc_rfc1001_len(work->response_buf, 16);
1934 rsp->Capabilities = 0;
1936 /* default manual caching */
1937 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1939 if (!IS_ERR(treename))
1944 switch (status.ret) {
1945 case KSMBD_TREE_CONN_STATUS_OK:
1946 rsp->hdr.Status = STATUS_SUCCESS;
1951 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1952 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
1955 case KSMBD_TREE_CONN_STATUS_NOMEM:
1956 rsp->hdr.Status = STATUS_NO_MEMORY;
1958 case KSMBD_TREE_CONN_STATUS_ERROR:
1959 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1960 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1961 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1964 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1967 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1970 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
1971 smb2_set_err_rsp(work);
1977 * smb2_create_open_flags() - convert smb open flags to unix open flags
1978 * @file_present: is file already present
1979 * @access: file access flags
1980 * @disposition: file disposition flags
1981 * @may_flags: set with MAY_ flags
1983 * Return: file open flags
1985 static int smb2_create_open_flags(bool file_present, __le32 access,
1989 int oflags = O_NONBLOCK | O_LARGEFILE;
1991 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1992 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1994 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1995 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1997 *may_flags = MAY_OPEN | MAY_WRITE;
2000 *may_flags = MAY_OPEN | MAY_READ;
2003 if (access == FILE_READ_ATTRIBUTES_LE)
2007 switch (disposition & FILE_CREATE_MASK_LE) {
2009 case FILE_CREATE_LE:
2011 case FILE_SUPERSEDE_LE:
2012 case FILE_OVERWRITE_LE:
2013 case FILE_OVERWRITE_IF_LE:
2020 switch (disposition & FILE_CREATE_MASK_LE) {
2021 case FILE_SUPERSEDE_LE:
2022 case FILE_CREATE_LE:
2023 case FILE_OPEN_IF_LE:
2024 case FILE_OVERWRITE_IF_LE:
2028 case FILE_OVERWRITE_LE:
2040 * smb2_tree_disconnect() - handler for smb tree connect request
2041 * @work: smb work containing request buffer
2045 int smb2_tree_disconnect(struct ksmbd_work *work)
2047 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2048 struct ksmbd_session *sess = work->sess;
2049 struct ksmbd_tree_connect *tcon = work->tcon;
2051 rsp->StructureSize = cpu_to_le16(4);
2052 inc_rfc1001_len(work->response_buf, 4);
2054 ksmbd_debug(SMB, "request\n");
2057 struct smb2_tree_disconnect_req *req =
2058 smb2_get_msg(work->request_buf);
2060 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2061 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2062 smb2_set_err_rsp(work);
2066 ksmbd_close_tree_conn_fds(work);
2067 ksmbd_tree_conn_disconnect(sess, tcon);
2073 * smb2_session_logoff() - handler for session log off request
2074 * @work: smb work containing request buffer
2078 int smb2_session_logoff(struct ksmbd_work *work)
2080 struct ksmbd_conn *conn = work->conn;
2081 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2082 struct ksmbd_session *sess;
2083 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2085 rsp->StructureSize = cpu_to_le16(4);
2086 inc_rfc1001_len(work->response_buf, 4);
2088 ksmbd_debug(SMB, "request\n");
2090 ksmbd_conn_set_need_reconnect(conn);
2091 ksmbd_close_session_fds(work);
2092 ksmbd_conn_wait_idle(conn);
2095 * Re-lookup session to validate if session is deleted
2096 * while waiting request complete
2098 sess = ksmbd_session_lookup(conn, le64_to_cpu(req->hdr.SessionId));
2099 if (ksmbd_tree_conn_session_logoff(sess)) {
2100 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2101 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2102 smb2_set_err_rsp(work);
2106 ksmbd_destroy_file_table(&sess->file_table);
2107 sess->state = SMB2_SESSION_EXPIRED;
2109 ksmbd_free_user(sess->user);
2111 ksmbd_conn_set_need_negotiate(conn);
2116 * create_smb2_pipe() - create IPC pipe
2117 * @work: smb work containing request buffer
2119 * Return: 0 on success, otherwise error
2121 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2123 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2124 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2129 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2130 1, work->conn->local_nls);
2132 rsp->hdr.Status = STATUS_NO_MEMORY;
2133 err = PTR_ERR(name);
2137 id = ksmbd_session_rpc_open(work->sess, name);
2139 pr_err("Unable to open RPC pipe: %d\n", id);
2144 rsp->hdr.Status = STATUS_SUCCESS;
2145 rsp->StructureSize = cpu_to_le16(89);
2146 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2148 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2150 rsp->CreationTime = cpu_to_le64(0);
2151 rsp->LastAccessTime = cpu_to_le64(0);
2152 rsp->ChangeTime = cpu_to_le64(0);
2153 rsp->AllocationSize = cpu_to_le64(0);
2154 rsp->EndofFile = cpu_to_le64(0);
2155 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2157 rsp->VolatileFileId = id;
2158 rsp->PersistentFileId = 0;
2159 rsp->CreateContextsOffset = 0;
2160 rsp->CreateContextsLength = 0;
2162 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2169 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2173 rsp->hdr.Status = STATUS_NO_MEMORY;
2180 smb2_set_err_rsp(work);
2185 * smb2_set_ea() - handler for setting extended attributes using set
2187 * @eabuf: set info command buffer
2188 * @buf_len: set info command buffer length
2189 * @path: dentry path for get ea
2191 * Return: 0 on success, otherwise error
2193 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2194 const struct path *path)
2196 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2197 char *attr_name = NULL, *value;
2199 unsigned int next = 0;
2201 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2202 le16_to_cpu(eabuf->EaValueLength))
2205 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2210 if (!eabuf->EaNameLength)
2214 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2215 eabuf->name, eabuf->EaNameLength,
2216 le16_to_cpu(eabuf->EaValueLength),
2217 le32_to_cpu(eabuf->NextEntryOffset));
2219 if (eabuf->EaNameLength >
2220 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2225 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2226 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2227 eabuf->EaNameLength);
2228 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2229 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2231 if (!eabuf->EaValueLength) {
2232 rc = ksmbd_vfs_casexattr_len(idmap,
2235 XATTR_USER_PREFIX_LEN +
2236 eabuf->EaNameLength);
2238 /* delete the EA only when it exits */
2240 rc = ksmbd_vfs_remove_xattr(idmap,
2246 "remove xattr failed(%d)\n",
2252 /* if the EA doesn't exist, just do nothing. */
2255 rc = ksmbd_vfs_setxattr(idmap,
2256 path->dentry, attr_name, value,
2257 le16_to_cpu(eabuf->EaValueLength), 0);
2260 "ksmbd_vfs_setxattr is failed(%d)\n",
2267 next = le32_to_cpu(eabuf->NextEntryOffset);
2268 if (next == 0 || buf_len < next)
2271 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2272 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2275 } while (next != 0);
2281 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2282 struct ksmbd_file *fp,
2283 char *stream_name, int s_type)
2285 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2286 size_t xattr_stream_size;
2287 char *xattr_stream_name;
2290 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2297 fp->stream.name = xattr_stream_name;
2298 fp->stream.size = xattr_stream_size;
2300 /* Check if there is stream prefix in xattr space */
2301 rc = ksmbd_vfs_casexattr_len(idmap,
2308 if (fp->cdoption == FILE_OPEN_LE) {
2309 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2313 rc = ksmbd_vfs_setxattr(idmap, path->dentry,
2314 xattr_stream_name, NULL, 0, 0);
2316 pr_err("Failed to store XATTR stream name :%d\n", rc);
2320 static int smb2_remove_smb_xattrs(const struct path *path)
2322 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2323 char *name, *xattr_list = NULL;
2324 ssize_t xattr_list_len;
2327 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2328 if (xattr_list_len < 0) {
2330 } else if (!xattr_list_len) {
2331 ksmbd_debug(SMB, "empty xattr in the file\n");
2335 for (name = xattr_list; name - xattr_list < xattr_list_len;
2336 name += strlen(name) + 1) {
2337 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2339 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2340 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2341 STREAM_PREFIX_LEN)) {
2342 err = ksmbd_vfs_remove_xattr(idmap, path->dentry,
2345 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2354 static int smb2_create_truncate(const struct path *path)
2356 int rc = vfs_truncate(path, 0);
2359 pr_err("vfs_truncate failed, rc %d\n", rc);
2363 rc = smb2_remove_smb_xattrs(path);
2364 if (rc == -EOPNOTSUPP)
2368 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2373 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2374 struct ksmbd_file *fp)
2376 struct xattr_dos_attrib da = {0};
2379 if (!test_share_config_flag(tcon->share_conf,
2380 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2384 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2385 da.itime = da.create_time = fp->create_time;
2386 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2387 XATTR_DOSINFO_ITIME;
2389 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt),
2392 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2395 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2396 const struct path *path, struct ksmbd_file *fp)
2398 struct xattr_dos_attrib da;
2401 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2403 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2404 if (!test_share_config_flag(tcon->share_conf,
2405 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2408 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2411 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2412 fp->create_time = da.create_time;
2413 fp->itime = da.itime;
2417 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2418 int open_flags, umode_t posix_mode, bool is_dir)
2420 struct ksmbd_tree_connect *tcon = work->tcon;
2421 struct ksmbd_share_config *share = tcon->share_conf;
2425 if (!(open_flags & O_CREAT))
2428 ksmbd_debug(SMB, "file does not exist, so creating\n");
2429 if (is_dir == true) {
2430 ksmbd_debug(SMB, "creating directory\n");
2432 mode = share_config_directory_mode(share, posix_mode);
2433 rc = ksmbd_vfs_mkdir(work, name, mode);
2437 ksmbd_debug(SMB, "creating regular file\n");
2439 mode = share_config_create_mode(share, posix_mode);
2440 rc = ksmbd_vfs_create(work, name, mode);
2445 rc = ksmbd_vfs_kern_path_locked(work, name, 0, path, 0);
2447 pr_err("cannot get linux path (%s), err = %d\n",
2454 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2455 struct smb2_create_req *req,
2456 const struct path *path)
2458 struct create_context *context;
2459 struct create_sd_buf_req *sd_buf;
2461 if (!req->CreateContextsOffset)
2464 /* Parse SD BUFFER create contexts */
2465 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2468 else if (IS_ERR(context))
2469 return PTR_ERR(context);
2472 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2473 sd_buf = (struct create_sd_buf_req *)context;
2474 if (le16_to_cpu(context->DataOffset) +
2475 le32_to_cpu(context->DataLength) <
2476 sizeof(struct create_sd_buf_req))
2478 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2479 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2482 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2483 struct mnt_idmap *idmap,
2484 struct inode *inode)
2486 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2487 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2489 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2490 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2491 fattr->cf_mode = inode->i_mode;
2492 fattr->cf_acls = NULL;
2493 fattr->cf_dacls = NULL;
2495 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2496 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2497 if (S_ISDIR(inode->i_mode))
2498 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2503 * smb2_open() - handler for smb file open request
2504 * @work: smb work containing request buffer
2506 * Return: 0 on success, otherwise error
2508 int smb2_open(struct ksmbd_work *work)
2510 struct ksmbd_conn *conn = work->conn;
2511 struct ksmbd_session *sess = work->sess;
2512 struct ksmbd_tree_connect *tcon = work->tcon;
2513 struct smb2_create_req *req;
2514 struct smb2_create_rsp *rsp;
2516 struct ksmbd_share_config *share = tcon->share_conf;
2517 struct ksmbd_file *fp = NULL;
2518 struct file *filp = NULL;
2519 struct mnt_idmap *idmap = NULL;
2521 struct create_context *context;
2522 struct lease_ctx_info *lc = NULL;
2523 struct create_ea_buf_req *ea_buf = NULL;
2524 struct oplock_info *opinfo;
2525 __le32 *next_ptr = NULL;
2526 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2528 int contxt_cnt = 0, query_disk_id = 0;
2529 int maximal_access_ctxt = 0, posix_ctxt = 0;
2533 char *stream_name = NULL;
2534 bool file_present = false, created = false, already_permitted = false;
2535 int share_ret, need_truncate = 0;
2537 umode_t posix_mode = 0;
2538 __le32 daccess, maximal_access = 0;
2540 WORK_BUFFERS(work, req, rsp);
2542 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2543 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2544 ksmbd_debug(SMB, "invalid flag in chained command\n");
2545 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2546 smb2_set_err_rsp(work);
2550 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2551 ksmbd_debug(SMB, "IPC pipe create request\n");
2552 return create_smb2_pipe(work);
2555 if (req->NameLength) {
2556 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2557 *(char *)req->Buffer == '\\') {
2558 pr_err("not allow directory name included leading slash\n");
2563 name = smb2_get_name(req->Buffer,
2564 le16_to_cpu(req->NameLength),
2565 work->conn->local_nls);
2574 ksmbd_debug(SMB, "converted name = %s\n", name);
2575 if (strchr(name, ':')) {
2576 if (!test_share_config_flag(work->tcon->share_conf,
2577 KSMBD_SHARE_FLAG_STREAMS)) {
2581 rc = parse_stream_name(name, &stream_name, &s_type);
2586 rc = ksmbd_validate_filename(name);
2590 if (ksmbd_share_veto_filename(share, name)) {
2592 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2597 name = kstrdup("", GFP_KERNEL);
2604 req_op_level = req->RequestedOplockLevel;
2605 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2606 lc = parse_lease_state(req);
2608 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2609 pr_err("Invalid impersonationlevel : 0x%x\n",
2610 le32_to_cpu(req->ImpersonationLevel));
2612 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2616 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2617 pr_err("Invalid create options : 0x%x\n",
2618 le32_to_cpu(req->CreateOptions));
2622 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2623 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2624 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2626 if (req->CreateOptions &
2627 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2628 FILE_RESERVE_OPFILTER_LE)) {
2633 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2634 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2637 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2638 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2643 if (le32_to_cpu(req->CreateDisposition) >
2644 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2645 pr_err("Invalid create disposition : 0x%x\n",
2646 le32_to_cpu(req->CreateDisposition));
2651 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2652 pr_err("Invalid desired access : 0x%x\n",
2653 le32_to_cpu(req->DesiredAccess));
2658 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2659 pr_err("Invalid file attribute : 0x%x\n",
2660 le32_to_cpu(req->FileAttributes));
2665 if (req->CreateContextsOffset) {
2666 /* Parse non-durable handle create contexts */
2667 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2668 if (IS_ERR(context)) {
2669 rc = PTR_ERR(context);
2671 } else if (context) {
2672 ea_buf = (struct create_ea_buf_req *)context;
2673 if (le16_to_cpu(context->DataOffset) +
2674 le32_to_cpu(context->DataLength) <
2675 sizeof(struct create_ea_buf_req)) {
2679 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2680 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2686 context = smb2_find_context_vals(req,
2687 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2688 if (IS_ERR(context)) {
2689 rc = PTR_ERR(context);
2691 } else if (context) {
2693 "get query maximal access context\n");
2694 maximal_access_ctxt = 1;
2697 context = smb2_find_context_vals(req,
2698 SMB2_CREATE_TIMEWARP_REQUEST);
2699 if (IS_ERR(context)) {
2700 rc = PTR_ERR(context);
2702 } else if (context) {
2703 ksmbd_debug(SMB, "get timewarp context\n");
2708 if (tcon->posix_extensions) {
2709 context = smb2_find_context_vals(req,
2710 SMB2_CREATE_TAG_POSIX);
2711 if (IS_ERR(context)) {
2712 rc = PTR_ERR(context);
2714 } else if (context) {
2715 struct create_posix *posix =
2716 (struct create_posix *)context;
2717 if (le16_to_cpu(context->DataOffset) +
2718 le32_to_cpu(context->DataLength) <
2719 sizeof(struct create_posix) - 4) {
2723 ksmbd_debug(SMB, "get posix context\n");
2725 posix_mode = le32_to_cpu(posix->Mode);
2731 if (ksmbd_override_fsids(work)) {
2736 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2738 file_present = true;
2740 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2742 * If file exists with under flags, return access
2745 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2746 req->CreateDisposition == FILE_OPEN_IF_LE) {
2751 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2753 "User does not have write permission\n");
2757 } else if (d_is_symlink(path.dentry)) {
2762 file_present = true;
2763 idmap = mnt_idmap(path.mnt);
2767 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2773 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2774 if (s_type == DATA_STREAM) {
2776 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2779 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2780 s_type == DATA_STREAM) {
2782 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2786 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2787 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2788 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2796 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2797 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2798 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2799 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2800 name, req->CreateOptions);
2801 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2806 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2807 !(req->CreateDisposition == FILE_CREATE_LE) &&
2808 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2809 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2814 if (!stream_name && file_present &&
2815 req->CreateDisposition == FILE_CREATE_LE) {
2820 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2822 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2823 rc = smb_check_perm_dacl(conn, &path, &daccess,
2829 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2830 if (!file_present) {
2831 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2833 rc = ksmbd_vfs_query_maximal_access(idmap,
2838 already_permitted = true;
2840 maximal_access = daccess;
2843 open_flags = smb2_create_open_flags(file_present, daccess,
2844 req->CreateDisposition,
2847 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2848 if (open_flags & O_CREAT) {
2850 "User does not have write permission\n");
2856 /*create file if not present */
2857 if (!file_present) {
2858 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2859 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2861 if (rc == -ENOENT) {
2863 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2869 idmap = mnt_idmap(path.mnt);
2871 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2872 sizeof(struct smb2_ea_info)) {
2877 rc = smb2_set_ea(&ea_buf->ea,
2878 le32_to_cpu(ea_buf->ccontext.DataLength),
2880 if (rc == -EOPNOTSUPP)
2885 } else if (!already_permitted) {
2886 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2887 * because execute(search) permission on a parent directory,
2888 * is already granted.
2890 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2891 rc = inode_permission(idmap,
2892 d_inode(path.dentry),
2897 if ((daccess & FILE_DELETE_LE) ||
2898 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2899 rc = inode_permission(idmap,
2900 d_inode(path.dentry->d_parent),
2901 MAY_EXEC | MAY_WRITE);
2908 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2909 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2915 filp = dentry_open(&path, open_flags, current_cred());
2918 pr_err("dentry open for dir failed, rc %d\n", rc);
2923 if (!(open_flags & O_TRUNC))
2924 file_info = FILE_OPENED;
2926 file_info = FILE_OVERWRITTEN;
2928 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2930 file_info = FILE_SUPERSEDED;
2931 } else if (open_flags & O_CREAT) {
2932 file_info = FILE_CREATED;
2935 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2937 /* Obtain Volatile-ID */
2938 fp = ksmbd_open_fd(work, filp);
2946 /* Get Persistent-ID */
2947 ksmbd_open_durable_fd(fp);
2948 if (!has_file_id(fp->persistent_id)) {
2953 fp->cdoption = req->CreateDisposition;
2954 fp->daccess = daccess;
2955 fp->saccess = req->ShareAccess;
2956 fp->coption = req->CreateOptions;
2958 /* Set default windows and posix acls if creating new file */
2961 struct inode *inode = d_inode(path.dentry);
2963 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
2965 d_inode(path.dentry->d_parent));
2967 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2969 if (test_share_config_flag(work->tcon->share_conf,
2970 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2971 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2976 rc = smb2_create_sd_buffer(work, req, &path);
2979 ksmbd_vfs_set_init_posix_acl(idmap,
2982 if (test_share_config_flag(work->tcon->share_conf,
2983 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2984 struct smb_fattr fattr;
2985 struct smb_ntsd *pntsd;
2986 int pntsd_size, ace_num = 0;
2988 ksmbd_acls_fattr(&fattr, idmap, inode);
2990 ace_num = fattr.cf_acls->a_count;
2992 ace_num += fattr.cf_dacls->a_count;
2994 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2995 sizeof(struct smb_sid) * 3 +
2996 sizeof(struct smb_acl) +
2997 sizeof(struct smb_ace) * ace_num * 2,
3000 posix_acl_release(fattr.cf_acls);
3001 posix_acl_release(fattr.cf_dacls);
3005 rc = build_sec_desc(idmap,
3010 &pntsd_size, &fattr);
3011 posix_acl_release(fattr.cf_acls);
3012 posix_acl_release(fattr.cf_dacls);
3018 rc = ksmbd_vfs_set_sd_xattr(conn,
3025 pr_err("failed to store ntacl in xattr : %d\n",
3034 rc = smb2_set_stream_name_xattr(&path,
3040 file_info = FILE_CREATED;
3043 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3044 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3045 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3046 !fp->attrib_only && !stream_name) {
3047 smb_break_all_oplock(work, fp);
3051 /* fp should be searchable through ksmbd_inode.m_fp_list
3052 * after daccess, saccess, attrib_only, and stream are
3055 write_lock(&fp->f_ci->m_lock);
3056 list_add(&fp->node, &fp->f_ci->m_fp_list);
3057 write_unlock(&fp->f_ci->m_lock);
3059 /* Check delete pending among previous fp before oplock break */
3060 if (ksmbd_inode_pending_delete(fp)) {
3065 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3066 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3067 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3068 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3069 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3074 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3075 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3077 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3078 name, req_op_level, lc->req_state);
3079 rc = find_same_lease_key(sess, fp->f_ci, lc);
3082 } else if (open_flags == O_RDONLY &&
3083 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3084 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3085 req_op_level = SMB2_OPLOCK_LEVEL_II;
3087 rc = smb_grant_oplock(work, req_op_level,
3088 fp->persistent_id, fp,
3089 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3095 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3096 ksmbd_fd_set_delete_on_close(fp, file_info);
3098 if (need_truncate) {
3099 rc = smb2_create_truncate(&path);
3104 if (req->CreateContextsOffset) {
3105 struct create_alloc_size_req *az_req;
3107 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3108 SMB2_CREATE_ALLOCATION_SIZE);
3109 if (IS_ERR(az_req)) {
3110 rc = PTR_ERR(az_req);
3112 } else if (az_req) {
3116 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3117 le32_to_cpu(az_req->ccontext.DataLength) <
3118 sizeof(struct create_alloc_size_req)) {
3122 alloc_size = le64_to_cpu(az_req->AllocationSize);
3124 "request smb2 create allocate size : %llu\n",
3126 smb_break_all_levII_oplock(work, fp, 1);
3127 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3131 "vfs_fallocate is failed : %d\n",
3135 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3136 if (IS_ERR(context)) {
3137 rc = PTR_ERR(context);
3139 } else if (context) {
3140 ksmbd_debug(SMB, "get query on disk id context\n");
3145 rc = ksmbd_vfs_getattr(&path, &stat);
3149 if (stat.result_mask & STATX_BTIME)
3150 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3152 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3153 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3155 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3158 smb2_update_xattrs(tcon, &path, fp);
3160 smb2_new_xattrs(tcon, &path, fp);
3162 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3164 rsp->StructureSize = cpu_to_le16(89);
3166 opinfo = rcu_dereference(fp->f_opinfo);
3167 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3170 rsp->CreateAction = cpu_to_le32(file_info);
3171 rsp->CreationTime = cpu_to_le64(fp->create_time);
3172 time = ksmbd_UnixTimeToNT(stat.atime);
3173 rsp->LastAccessTime = cpu_to_le64(time);
3174 time = ksmbd_UnixTimeToNT(stat.mtime);
3175 rsp->LastWriteTime = cpu_to_le64(time);
3176 time = ksmbd_UnixTimeToNT(stat.ctime);
3177 rsp->ChangeTime = cpu_to_le64(time);
3178 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3179 cpu_to_le64(stat.blocks << 9);
3180 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3181 rsp->FileAttributes = fp->f_ci->m_fattr;
3185 rsp->PersistentFileId = fp->persistent_id;
3186 rsp->VolatileFileId = fp->volatile_id;
3188 rsp->CreateContextsOffset = 0;
3189 rsp->CreateContextsLength = 0;
3190 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3192 /* If lease is request send lease context response */
3193 if (opinfo && opinfo->is_lease) {
3194 struct create_context *lease_ccontext;
3196 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3197 name, opinfo->o_lease->state);
3198 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3200 lease_ccontext = (struct create_context *)rsp->Buffer;
3202 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3203 le32_add_cpu(&rsp->CreateContextsLength,
3204 conn->vals->create_lease_size);
3205 inc_rfc1001_len(work->response_buf,
3206 conn->vals->create_lease_size);
3207 next_ptr = &lease_ccontext->Next;
3208 next_off = conn->vals->create_lease_size;
3211 if (maximal_access_ctxt) {
3212 struct create_context *mxac_ccontext;
3214 if (maximal_access == 0)
3215 ksmbd_vfs_query_maximal_access(idmap,
3218 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3219 le32_to_cpu(rsp->CreateContextsLength));
3221 create_mxac_rsp_buf(rsp->Buffer +
3222 le32_to_cpu(rsp->CreateContextsLength),
3223 le32_to_cpu(maximal_access));
3224 le32_add_cpu(&rsp->CreateContextsLength,
3225 conn->vals->create_mxac_size);
3226 inc_rfc1001_len(work->response_buf,
3227 conn->vals->create_mxac_size);
3229 *next_ptr = cpu_to_le32(next_off);
3230 next_ptr = &mxac_ccontext->Next;
3231 next_off = conn->vals->create_mxac_size;
3234 if (query_disk_id) {
3235 struct create_context *disk_id_ccontext;
3237 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3238 le32_to_cpu(rsp->CreateContextsLength));
3240 create_disk_id_rsp_buf(rsp->Buffer +
3241 le32_to_cpu(rsp->CreateContextsLength),
3242 stat.ino, tcon->id);
3243 le32_add_cpu(&rsp->CreateContextsLength,
3244 conn->vals->create_disk_id_size);
3245 inc_rfc1001_len(work->response_buf,
3246 conn->vals->create_disk_id_size);
3248 *next_ptr = cpu_to_le32(next_off);
3249 next_ptr = &disk_id_ccontext->Next;
3250 next_off = conn->vals->create_disk_id_size;
3255 create_posix_rsp_buf(rsp->Buffer +
3256 le32_to_cpu(rsp->CreateContextsLength),
3258 le32_add_cpu(&rsp->CreateContextsLength,
3259 conn->vals->create_posix_size);
3260 inc_rfc1001_len(work->response_buf,
3261 conn->vals->create_posix_size);
3263 *next_ptr = cpu_to_le32(next_off);
3266 if (contxt_cnt > 0) {
3267 rsp->CreateContextsOffset =
3268 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3272 if (file_present || created) {
3273 inode_unlock(d_inode(path.dentry->d_parent));
3276 ksmbd_revert_fsids(work);
3281 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3282 else if (rc == -EOPNOTSUPP)
3283 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3284 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3285 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3286 else if (rc == -ENOENT)
3287 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3288 else if (rc == -EPERM)
3289 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3290 else if (rc == -EBUSY)
3291 rsp->hdr.Status = STATUS_DELETE_PENDING;
3292 else if (rc == -EBADF)
3293 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3294 else if (rc == -ENOEXEC)
3295 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3296 else if (rc == -ENXIO)
3297 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3298 else if (rc == -EEXIST)
3299 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3300 else if (rc == -EMFILE)
3301 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3302 if (!rsp->hdr.Status)
3303 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3306 ksmbd_fd_put(work, fp);
3307 smb2_set_err_rsp(work);
3308 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3317 static int readdir_info_level_struct_sz(int info_level)
3319 switch (info_level) {
3320 case FILE_FULL_DIRECTORY_INFORMATION:
3321 return sizeof(struct file_full_directory_info);
3322 case FILE_BOTH_DIRECTORY_INFORMATION:
3323 return sizeof(struct file_both_directory_info);
3324 case FILE_DIRECTORY_INFORMATION:
3325 return sizeof(struct file_directory_info);
3326 case FILE_NAMES_INFORMATION:
3327 return sizeof(struct file_names_info);
3328 case FILEID_FULL_DIRECTORY_INFORMATION:
3329 return sizeof(struct file_id_full_dir_info);
3330 case FILEID_BOTH_DIRECTORY_INFORMATION:
3331 return sizeof(struct file_id_both_directory_info);
3332 case SMB_FIND_FILE_POSIX_INFO:
3333 return sizeof(struct smb2_posix_info);
3339 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3341 switch (info_level) {
3342 case FILE_FULL_DIRECTORY_INFORMATION:
3344 struct file_full_directory_info *ffdinfo;
3346 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3347 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3348 d_info->name = ffdinfo->FileName;
3349 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3352 case FILE_BOTH_DIRECTORY_INFORMATION:
3354 struct file_both_directory_info *fbdinfo;
3356 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3357 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3358 d_info->name = fbdinfo->FileName;
3359 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3362 case FILE_DIRECTORY_INFORMATION:
3364 struct file_directory_info *fdinfo;
3366 fdinfo = (struct file_directory_info *)d_info->rptr;
3367 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3368 d_info->name = fdinfo->FileName;
3369 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3372 case FILE_NAMES_INFORMATION:
3374 struct file_names_info *fninfo;
3376 fninfo = (struct file_names_info *)d_info->rptr;
3377 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3378 d_info->name = fninfo->FileName;
3379 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3382 case FILEID_FULL_DIRECTORY_INFORMATION:
3384 struct file_id_full_dir_info *dinfo;
3386 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3387 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3388 d_info->name = dinfo->FileName;
3389 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3392 case FILEID_BOTH_DIRECTORY_INFORMATION:
3394 struct file_id_both_directory_info *fibdinfo;
3396 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3397 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3398 d_info->name = fibdinfo->FileName;
3399 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3402 case SMB_FIND_FILE_POSIX_INFO:
3404 struct smb2_posix_info *posix_info;
3406 posix_info = (struct smb2_posix_info *)d_info->rptr;
3407 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3408 d_info->name = posix_info->name;
3409 d_info->name_len = le32_to_cpu(posix_info->name_len);
3418 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3420 * @conn: connection instance
3421 * @info_level: smb information level
3422 * @d_info: structure included variables for query dir
3423 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3425 * if directory has many entries, find first can't read it fully.
3426 * find next might be called multiple times to read remaining dir entries
3428 * Return: 0 on success, otherwise error
3430 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3431 struct ksmbd_dir_info *d_info,
3432 struct ksmbd_kstat *ksmbd_kstat)
3434 int next_entry_offset = 0;
3438 int struct_sz, rc = 0;
3440 conv_name = ksmbd_convert_dir_info_name(d_info,
3446 /* Somehow the name has only terminating NULL bytes */
3449 goto free_conv_name;
3452 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3453 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3454 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3456 if (next_entry_offset > d_info->out_buf_len) {
3457 d_info->out_buf_len = 0;
3459 goto free_conv_name;
3462 kstat = d_info->wptr;
3463 if (info_level != FILE_NAMES_INFORMATION)
3464 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3466 switch (info_level) {
3467 case FILE_FULL_DIRECTORY_INFORMATION:
3469 struct file_full_directory_info *ffdinfo;
3471 ffdinfo = (struct file_full_directory_info *)kstat;
3472 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3474 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3475 if (ffdinfo->EaSize)
3476 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3477 if (d_info->hide_dot_file && d_info->name[0] == '.')
3478 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3479 memcpy(ffdinfo->FileName, conv_name, conv_len);
3480 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3483 case FILE_BOTH_DIRECTORY_INFORMATION:
3485 struct file_both_directory_info *fbdinfo;
3487 fbdinfo = (struct file_both_directory_info *)kstat;
3488 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3490 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3491 if (fbdinfo->EaSize)
3492 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3493 fbdinfo->ShortNameLength = 0;
3494 fbdinfo->Reserved = 0;
3495 if (d_info->hide_dot_file && d_info->name[0] == '.')
3496 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3497 memcpy(fbdinfo->FileName, conv_name, conv_len);
3498 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3501 case FILE_DIRECTORY_INFORMATION:
3503 struct file_directory_info *fdinfo;
3505 fdinfo = (struct file_directory_info *)kstat;
3506 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3507 if (d_info->hide_dot_file && d_info->name[0] == '.')
3508 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3509 memcpy(fdinfo->FileName, conv_name, conv_len);
3510 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3513 case FILE_NAMES_INFORMATION:
3515 struct file_names_info *fninfo;
3517 fninfo = (struct file_names_info *)kstat;
3518 fninfo->FileNameLength = cpu_to_le32(conv_len);
3519 memcpy(fninfo->FileName, conv_name, conv_len);
3520 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3523 case FILEID_FULL_DIRECTORY_INFORMATION:
3525 struct file_id_full_dir_info *dinfo;
3527 dinfo = (struct file_id_full_dir_info *)kstat;
3528 dinfo->FileNameLength = cpu_to_le32(conv_len);
3530 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3532 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3533 dinfo->Reserved = 0;
3534 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3535 if (d_info->hide_dot_file && d_info->name[0] == '.')
3536 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3537 memcpy(dinfo->FileName, conv_name, conv_len);
3538 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3541 case FILEID_BOTH_DIRECTORY_INFORMATION:
3543 struct file_id_both_directory_info *fibdinfo;
3545 fibdinfo = (struct file_id_both_directory_info *)kstat;
3546 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3548 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3549 if (fibdinfo->EaSize)
3550 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3551 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3552 fibdinfo->ShortNameLength = 0;
3553 fibdinfo->Reserved = 0;
3554 fibdinfo->Reserved2 = cpu_to_le16(0);
3555 if (d_info->hide_dot_file && d_info->name[0] == '.')
3556 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3557 memcpy(fibdinfo->FileName, conv_name, conv_len);
3558 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3561 case SMB_FIND_FILE_POSIX_INFO:
3563 struct smb2_posix_info *posix_info;
3566 posix_info = (struct smb2_posix_info *)kstat;
3567 posix_info->Ignored = 0;
3568 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3569 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3570 posix_info->ChangeTime = cpu_to_le64(time);
3571 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3572 posix_info->LastAccessTime = cpu_to_le64(time);
3573 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3574 posix_info->LastWriteTime = cpu_to_le64(time);
3575 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3576 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3577 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3578 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3579 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3580 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3581 posix_info->DosAttributes =
3582 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3583 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3584 if (d_info->hide_dot_file && d_info->name[0] == '.')
3585 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3587 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3588 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3589 * sub_auth(4 * 1(num_subauth)) + RID(4).
3591 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3592 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3593 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3594 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3595 memcpy(posix_info->name, conv_name, conv_len);
3596 posix_info->name_len = cpu_to_le32(conv_len);
3597 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3601 } /* switch (info_level) */
3603 d_info->last_entry_offset = d_info->data_count;
3604 d_info->data_count += next_entry_offset;
3605 d_info->out_buf_len -= next_entry_offset;
3606 d_info->wptr += next_entry_offset;
3609 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3610 info_level, d_info->out_buf_len,
3611 next_entry_offset, d_info->data_count);
3618 struct smb2_query_dir_private {
3619 struct ksmbd_work *work;
3620 char *search_pattern;
3621 struct ksmbd_file *dir_fp;
3623 struct ksmbd_dir_info *d_info;
3627 static void lock_dir(struct ksmbd_file *dir_fp)
3629 struct dentry *dir = dir_fp->filp->f_path.dentry;
3631 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3634 static void unlock_dir(struct ksmbd_file *dir_fp)
3636 struct dentry *dir = dir_fp->filp->f_path.dentry;
3638 inode_unlock(d_inode(dir));
3641 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3643 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
3645 struct ksmbd_kstat ksmbd_kstat;
3649 for (i = 0; i < priv->d_info->num_entry; i++) {
3650 struct dentry *dent;
3652 if (dentry_name(priv->d_info, priv->info_level))
3655 lock_dir(priv->dir_fp);
3656 dent = lookup_one(idmap, priv->d_info->name,
3657 priv->dir_fp->filp->f_path.dentry,
3658 priv->d_info->name_len);
3659 unlock_dir(priv->dir_fp);
3662 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3667 if (unlikely(d_is_negative(dent))) {
3669 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3670 priv->d_info->name);
3674 ksmbd_kstat.kstat = &kstat;
3675 if (priv->info_level != FILE_NAMES_INFORMATION)
3676 ksmbd_vfs_fill_dentry_attrs(priv->work,
3681 rc = smb2_populate_readdir_entry(priv->work->conn,
3692 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3697 int next_entry_offset;
3699 struct_sz = readdir_info_level_struct_sz(info_level);
3700 if (struct_sz == -EOPNOTSUPP)
3703 conv_len = (d_info->name_len + 1) * 2;
3704 next_entry_offset = ALIGN(struct_sz + conv_len,
3705 KSMBD_DIR_INFO_ALIGNMENT);
3707 if (next_entry_offset > d_info->out_buf_len) {
3708 d_info->out_buf_len = 0;
3712 switch (info_level) {
3713 case FILE_FULL_DIRECTORY_INFORMATION:
3715 struct file_full_directory_info *ffdinfo;
3717 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3718 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3719 ffdinfo->FileName[d_info->name_len] = 0x00;
3720 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3721 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3724 case FILE_BOTH_DIRECTORY_INFORMATION:
3726 struct file_both_directory_info *fbdinfo;
3728 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3729 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3730 fbdinfo->FileName[d_info->name_len] = 0x00;
3731 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3732 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3735 case FILE_DIRECTORY_INFORMATION:
3737 struct file_directory_info *fdinfo;
3739 fdinfo = (struct file_directory_info *)d_info->wptr;
3740 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3741 fdinfo->FileName[d_info->name_len] = 0x00;
3742 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3743 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3746 case FILE_NAMES_INFORMATION:
3748 struct file_names_info *fninfo;
3750 fninfo = (struct file_names_info *)d_info->wptr;
3751 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3752 fninfo->FileName[d_info->name_len] = 0x00;
3753 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3754 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3757 case FILEID_FULL_DIRECTORY_INFORMATION:
3759 struct file_id_full_dir_info *dinfo;
3761 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3762 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3763 dinfo->FileName[d_info->name_len] = 0x00;
3764 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3765 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3768 case FILEID_BOTH_DIRECTORY_INFORMATION:
3770 struct file_id_both_directory_info *fibdinfo;
3772 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3773 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3774 fibdinfo->FileName[d_info->name_len] = 0x00;
3775 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3776 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3779 case SMB_FIND_FILE_POSIX_INFO:
3781 struct smb2_posix_info *posix_info;
3783 posix_info = (struct smb2_posix_info *)d_info->wptr;
3784 memcpy(posix_info->name, d_info->name, d_info->name_len);
3785 posix_info->name[d_info->name_len] = 0x00;
3786 posix_info->name_len = cpu_to_le32(d_info->name_len);
3787 posix_info->NextEntryOffset =
3788 cpu_to_le32(next_entry_offset);
3791 } /* switch (info_level) */
3793 d_info->num_entry++;
3794 d_info->out_buf_len -= next_entry_offset;
3795 d_info->wptr += next_entry_offset;
3799 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3800 loff_t offset, u64 ino, unsigned int d_type)
3802 struct ksmbd_readdir_data *buf;
3803 struct smb2_query_dir_private *priv;
3804 struct ksmbd_dir_info *d_info;
3807 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3808 priv = buf->private;
3809 d_info = priv->d_info;
3811 /* dot and dotdot entries are already reserved */
3812 if (!strcmp(".", name) || !strcmp("..", name))
3814 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3816 if (!match_pattern(name, namlen, priv->search_pattern))
3819 d_info->name = name;
3820 d_info->name_len = namlen;
3821 rc = reserve_populate_dentry(d_info, priv->info_level);
3824 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3825 d_info->out_buf_len = 0;
3829 static int verify_info_level(int info_level)
3831 switch (info_level) {
3832 case FILE_FULL_DIRECTORY_INFORMATION:
3833 case FILE_BOTH_DIRECTORY_INFORMATION:
3834 case FILE_DIRECTORY_INFORMATION:
3835 case FILE_NAMES_INFORMATION:
3836 case FILEID_FULL_DIRECTORY_INFORMATION:
3837 case FILEID_BOTH_DIRECTORY_INFORMATION:
3838 case SMB_FIND_FILE_POSIX_INFO:
3847 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3851 free_len = (int)(work->response_sz -
3852 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3856 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3857 unsigned short hdr2_len,
3858 unsigned int out_buf_len)
3862 if (out_buf_len > work->conn->vals->max_trans_size)
3865 free_len = smb2_resp_buf_len(work, hdr2_len);
3869 return min_t(int, out_buf_len, free_len);
3872 int smb2_query_dir(struct ksmbd_work *work)
3874 struct ksmbd_conn *conn = work->conn;
3875 struct smb2_query_directory_req *req;
3876 struct smb2_query_directory_rsp *rsp;
3877 struct ksmbd_share_config *share = work->tcon->share_conf;
3878 struct ksmbd_file *dir_fp = NULL;
3879 struct ksmbd_dir_info d_info;
3881 char *srch_ptr = NULL;
3882 unsigned char srch_flag;
3884 struct smb2_query_dir_private query_dir_private = {NULL, };
3886 WORK_BUFFERS(work, req, rsp);
3888 if (ksmbd_override_fsids(work)) {
3889 rsp->hdr.Status = STATUS_NO_MEMORY;
3890 smb2_set_err_rsp(work);
3894 rc = verify_info_level(req->FileInformationClass);
3900 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3906 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3907 inode_permission(file_mnt_idmap(dir_fp->filp),
3908 file_inode(dir_fp->filp),
3909 MAY_READ | MAY_EXEC)) {
3910 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
3915 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3916 pr_err("can't do query dir for a file\n");
3921 srch_flag = req->Flags;
3922 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3923 le16_to_cpu(req->FileNameLength), 1,
3925 if (IS_ERR(srch_ptr)) {
3926 ksmbd_debug(SMB, "Search Pattern not found\n");
3930 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3933 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3934 ksmbd_debug(SMB, "Restart directory scan\n");
3935 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3938 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3939 d_info.wptr = (char *)rsp->Buffer;
3940 d_info.rptr = (char *)rsp->Buffer;
3941 d_info.out_buf_len =
3942 smb2_calc_max_out_buf_len(work, 8,
3943 le32_to_cpu(req->OutputBufferLength));
3944 if (d_info.out_buf_len < 0) {
3948 d_info.flags = srch_flag;
3951 * reserve dot and dotdot entries in head of buffer
3954 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3955 dir_fp, &d_info, srch_ptr,
3956 smb2_populate_readdir_entry);
3962 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3963 d_info.hide_dot_file = true;
3965 buffer_sz = d_info.out_buf_len;
3966 d_info.rptr = d_info.wptr;
3967 query_dir_private.work = work;
3968 query_dir_private.search_pattern = srch_ptr;
3969 query_dir_private.dir_fp = dir_fp;
3970 query_dir_private.d_info = &d_info;
3971 query_dir_private.info_level = req->FileInformationClass;
3972 dir_fp->readdir_data.private = &query_dir_private;
3973 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3975 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3977 * req->OutputBufferLength is too small to contain even one entry.
3978 * In this case, it immediately returns OutputBufferLength 0 to client.
3980 if (!d_info.out_buf_len && !d_info.num_entry)
3982 if (rc > 0 || rc == -ENOSPC)
3987 d_info.wptr = d_info.rptr;
3988 d_info.out_buf_len = buffer_sz;
3989 rc = process_query_dir_entries(&query_dir_private);
3993 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3994 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3995 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3997 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3998 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4000 rsp->StructureSize = cpu_to_le16(9);
4001 rsp->OutputBufferOffset = cpu_to_le16(0);
4002 rsp->OutputBufferLength = cpu_to_le32(0);
4004 inc_rfc1001_len(work->response_buf, 9);
4007 ((struct file_directory_info *)
4008 ((char *)rsp->Buffer + d_info.last_entry_offset))
4009 ->NextEntryOffset = 0;
4010 if (d_info.data_count >= d_info.last_entry_off_align)
4011 d_info.data_count -= d_info.last_entry_off_align;
4013 rsp->StructureSize = cpu_to_le16(9);
4014 rsp->OutputBufferOffset = cpu_to_le16(72);
4015 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4016 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
4020 ksmbd_fd_put(work, dir_fp);
4021 ksmbd_revert_fsids(work);
4025 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4030 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4031 else if (rc == -EACCES)
4032 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4033 else if (rc == -ENOENT)
4034 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4035 else if (rc == -EBADF)
4036 rsp->hdr.Status = STATUS_FILE_CLOSED;
4037 else if (rc == -ENOMEM)
4038 rsp->hdr.Status = STATUS_NO_MEMORY;
4039 else if (rc == -EFAULT)
4040 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4041 else if (rc == -EIO)
4042 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4043 if (!rsp->hdr.Status)
4044 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4046 smb2_set_err_rsp(work);
4047 ksmbd_fd_put(work, dir_fp);
4048 ksmbd_revert_fsids(work);
4053 * buffer_check_err() - helper function to check buffer errors
4054 * @reqOutputBufferLength: max buffer length expected in command response
4055 * @rsp: query info response buffer contains output buffer length
4056 * @rsp_org: base response buffer pointer in case of chained response
4057 * @infoclass_size: query info class response buffer size
4059 * Return: 0 on success, otherwise error
4061 static int buffer_check_err(int reqOutputBufferLength,
4062 struct smb2_query_info_rsp *rsp,
4063 void *rsp_org, int infoclass_size)
4065 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4066 if (reqOutputBufferLength < infoclass_size) {
4067 pr_err("Invalid Buffer Size Requested\n");
4068 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4069 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4073 ksmbd_debug(SMB, "Buffer Overflow\n");
4074 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4075 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4076 reqOutputBufferLength);
4077 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4082 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4085 struct smb2_file_standard_info *sinfo;
4087 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4089 sinfo->AllocationSize = cpu_to_le64(4096);
4090 sinfo->EndOfFile = cpu_to_le64(0);
4091 sinfo->NumberOfLinks = cpu_to_le32(1);
4092 sinfo->DeletePending = 1;
4093 sinfo->Directory = 0;
4094 rsp->OutputBufferLength =
4095 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4096 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4099 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4102 struct smb2_file_internal_info *file_info;
4104 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4106 /* any unique number */
4107 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4108 rsp->OutputBufferLength =
4109 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4110 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4113 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4114 struct smb2_query_info_req *req,
4115 struct smb2_query_info_rsp *rsp,
4122 * Windows can sometime send query file info request on
4123 * pipe without opening it, checking error condition here
4125 id = req->VolatileFileId;
4126 if (!ksmbd_session_rpc_method(sess, id))
4129 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4130 req->FileInfoClass, req->VolatileFileId);
4132 switch (req->FileInfoClass) {
4133 case FILE_STANDARD_INFORMATION:
4134 get_standard_info_pipe(rsp, rsp_org);
4135 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4137 FILE_STANDARD_INFORMATION_SIZE);
4139 case FILE_INTERNAL_INFORMATION:
4140 get_internal_info_pipe(rsp, id, rsp_org);
4141 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4143 FILE_INTERNAL_INFORMATION_SIZE);
4146 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4147 req->FileInfoClass);
4154 * smb2_get_ea() - handler for smb2 get extended attribute command
4155 * @work: smb work containing query info command buffer
4156 * @fp: ksmbd_file pointer
4157 * @req: get extended attribute request
4158 * @rsp: response buffer pointer
4159 * @rsp_org: base response buffer pointer in case of chained response
4161 * Return: 0 on success, otherwise error
4163 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4164 struct smb2_query_info_req *req,
4165 struct smb2_query_info_rsp *rsp, void *rsp_org)
4167 struct smb2_ea_info *eainfo, *prev_eainfo;
4168 char *name, *ptr, *xattr_list = NULL, *buf;
4169 int rc, name_len, value_len, xattr_list_len, idx;
4170 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4171 struct smb2_ea_info_req *ea_req = NULL;
4172 const struct path *path;
4173 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4175 if (!(fp->daccess & FILE_READ_EA_LE)) {
4176 pr_err("Not permitted to read ext attr : 0x%x\n",
4181 path = &fp->filp->f_path;
4182 /* single EA entry is requested with given user.* name */
4183 if (req->InputBufferLength) {
4184 if (le32_to_cpu(req->InputBufferLength) <
4185 sizeof(struct smb2_ea_info_req))
4188 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4190 /* need to send all EAs, if no specific EA is requested*/
4191 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4193 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4194 le32_to_cpu(req->Flags));
4198 smb2_calc_max_out_buf_len(work, 8,
4199 le32_to_cpu(req->OutputBufferLength));
4200 if (buf_free_len < 0)
4203 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4205 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4207 } else if (!rc) { /* there is no EA in the file */
4208 ksmbd_debug(SMB, "no ea data in the file\n");
4211 xattr_list_len = rc;
4213 ptr = (char *)rsp->Buffer;
4214 eainfo = (struct smb2_ea_info *)ptr;
4215 prev_eainfo = eainfo;
4218 while (idx < xattr_list_len) {
4219 name = xattr_list + idx;
4220 name_len = strlen(name);
4222 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4223 idx += name_len + 1;
4226 * CIFS does not support EA other than user.* namespace,
4227 * still keep the framework generic, to list other attrs
4230 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4233 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4237 if (req->InputBufferLength &&
4238 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4239 ea_req->EaNameLength))
4242 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4243 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4246 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4247 name_len -= XATTR_USER_PREFIX_LEN;
4249 ptr = (char *)(&eainfo->name + name_len + 1);
4250 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4252 /* bailout if xattr can't fit in buf_free_len */
4253 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4255 if (value_len <= 0) {
4257 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4261 buf_free_len -= value_len;
4262 if (buf_free_len < 0) {
4267 memcpy(ptr, buf, value_len);
4272 eainfo->EaNameLength = name_len;
4274 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4275 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4278 memcpy(eainfo->name, name, name_len);
4280 eainfo->name[name_len] = '\0';
4281 eainfo->EaValueLength = cpu_to_le16(value_len);
4282 next_offset = offsetof(struct smb2_ea_info, name) +
4283 name_len + 1 + value_len;
4285 /* align next xattr entry at 4 byte bundary */
4286 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4287 if (alignment_bytes) {
4288 memset(ptr, '\0', alignment_bytes);
4289 ptr += alignment_bytes;
4290 next_offset += alignment_bytes;
4291 buf_free_len -= alignment_bytes;
4293 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4294 prev_eainfo = eainfo;
4295 eainfo = (struct smb2_ea_info *)ptr;
4296 rsp_data_cnt += next_offset;
4298 if (req->InputBufferLength) {
4299 ksmbd_debug(SMB, "single entry requested\n");
4304 /* no more ea entries */
4305 prev_eainfo->NextEntryOffset = 0;
4308 if (rsp_data_cnt == 0)
4309 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4310 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4311 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4317 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4318 struct ksmbd_file *fp, void *rsp_org)
4320 struct smb2_file_access_info *file_info;
4322 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4323 file_info->AccessFlags = fp->daccess;
4324 rsp->OutputBufferLength =
4325 cpu_to_le32(sizeof(struct smb2_file_access_info));
4326 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4329 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4330 struct ksmbd_file *fp, void *rsp_org)
4332 struct smb2_file_basic_info *basic_info;
4336 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4337 pr_err("no right to read the attributes : 0x%x\n",
4342 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4343 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4345 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4346 time = ksmbd_UnixTimeToNT(stat.atime);
4347 basic_info->LastAccessTime = cpu_to_le64(time);
4348 time = ksmbd_UnixTimeToNT(stat.mtime);
4349 basic_info->LastWriteTime = cpu_to_le64(time);
4350 time = ksmbd_UnixTimeToNT(stat.ctime);
4351 basic_info->ChangeTime = cpu_to_le64(time);
4352 basic_info->Attributes = fp->f_ci->m_fattr;
4353 basic_info->Pad1 = 0;
4354 rsp->OutputBufferLength =
4355 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4356 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4360 static unsigned long long get_allocation_size(struct inode *inode,
4363 unsigned long long alloc_size = 0;
4365 if (!S_ISDIR(stat->mode)) {
4366 if ((inode->i_blocks << 9) <= stat->size)
4367 alloc_size = stat->size;
4369 alloc_size = inode->i_blocks << 9;
4375 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4376 struct ksmbd_file *fp, void *rsp_org)
4378 struct smb2_file_standard_info *sinfo;
4379 unsigned int delete_pending;
4380 struct inode *inode;
4383 inode = file_inode(fp->filp);
4384 generic_fillattr(file_mnt_idmap(fp->filp), inode, &stat);
4386 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4387 delete_pending = ksmbd_inode_pending_delete(fp);
4389 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4390 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4391 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4392 sinfo->DeletePending = delete_pending;
4393 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4394 rsp->OutputBufferLength =
4395 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4396 inc_rfc1001_len(rsp_org,
4397 sizeof(struct smb2_file_standard_info));
4400 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4403 struct smb2_file_alignment_info *file_info;
4405 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4406 file_info->AlignmentRequirement = 0;
4407 rsp->OutputBufferLength =
4408 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4409 inc_rfc1001_len(rsp_org,
4410 sizeof(struct smb2_file_alignment_info));
4413 static int get_file_all_info(struct ksmbd_work *work,
4414 struct smb2_query_info_rsp *rsp,
4415 struct ksmbd_file *fp,
4418 struct ksmbd_conn *conn = work->conn;
4419 struct smb2_file_all_info *file_info;
4420 unsigned int delete_pending;
4421 struct inode *inode;
4427 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4428 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4433 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4434 if (IS_ERR(filename))
4435 return PTR_ERR(filename);
4437 inode = file_inode(fp->filp);
4438 generic_fillattr(file_mnt_idmap(fp->filp), inode, &stat);
4440 ksmbd_debug(SMB, "filename = %s\n", filename);
4441 delete_pending = ksmbd_inode_pending_delete(fp);
4442 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4444 file_info->CreationTime = cpu_to_le64(fp->create_time);
4445 time = ksmbd_UnixTimeToNT(stat.atime);
4446 file_info->LastAccessTime = cpu_to_le64(time);
4447 time = ksmbd_UnixTimeToNT(stat.mtime);
4448 file_info->LastWriteTime = cpu_to_le64(time);
4449 time = ksmbd_UnixTimeToNT(stat.ctime);
4450 file_info->ChangeTime = cpu_to_le64(time);
4451 file_info->Attributes = fp->f_ci->m_fattr;
4452 file_info->Pad1 = 0;
4453 file_info->AllocationSize =
4454 cpu_to_le64(get_allocation_size(inode, &stat));
4455 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4456 file_info->NumberOfLinks =
4457 cpu_to_le32(get_nlink(&stat) - delete_pending);
4458 file_info->DeletePending = delete_pending;
4459 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4460 file_info->Pad2 = 0;
4461 file_info->IndexNumber = cpu_to_le64(stat.ino);
4462 file_info->EASize = 0;
4463 file_info->AccessFlags = fp->daccess;
4464 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4465 file_info->Mode = fp->coption;
4466 file_info->AlignmentRequirement = 0;
4467 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4468 PATH_MAX, conn->local_nls, 0);
4470 file_info->FileNameLength = cpu_to_le32(conv_len);
4471 rsp->OutputBufferLength =
4472 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4474 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4478 static void get_file_alternate_info(struct ksmbd_work *work,
4479 struct smb2_query_info_rsp *rsp,
4480 struct ksmbd_file *fp,
4483 struct ksmbd_conn *conn = work->conn;
4484 struct smb2_file_alt_name_info *file_info;
4485 struct dentry *dentry = fp->filp->f_path.dentry;
4488 spin_lock(&dentry->d_lock);
4489 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4490 conv_len = ksmbd_extract_shortname(conn,
4491 dentry->d_name.name,
4492 file_info->FileName);
4493 spin_unlock(&dentry->d_lock);
4494 file_info->FileNameLength = cpu_to_le32(conv_len);
4495 rsp->OutputBufferLength =
4496 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4497 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4500 static void get_file_stream_info(struct ksmbd_work *work,
4501 struct smb2_query_info_rsp *rsp,
4502 struct ksmbd_file *fp,
4505 struct ksmbd_conn *conn = work->conn;
4506 struct smb2_file_stream_info *file_info;
4507 char *stream_name, *xattr_list = NULL, *stream_buf;
4509 const struct path *path = &fp->filp->f_path;
4510 ssize_t xattr_list_len;
4511 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4513 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4515 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4517 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4520 smb2_calc_max_out_buf_len(work, 8,
4521 le32_to_cpu(req->OutputBufferLength));
4522 if (buf_free_len < 0)
4525 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4526 if (xattr_list_len < 0) {
4528 } else if (!xattr_list_len) {
4529 ksmbd_debug(SMB, "empty xattr in the file\n");
4533 while (idx < xattr_list_len) {
4534 stream_name = xattr_list + idx;
4535 streamlen = strlen(stream_name);
4536 idx += streamlen + 1;
4538 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4540 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4541 STREAM_PREFIX, STREAM_PREFIX_LEN))
4544 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4546 streamlen = stream_name_len;
4550 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4554 streamlen = snprintf(stream_buf, streamlen + 1,
4555 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4557 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4558 if (next > buf_free_len) {
4563 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4564 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4565 stream_buf, streamlen,
4566 conn->local_nls, 0);
4569 file_info->StreamNameLength = cpu_to_le32(streamlen);
4570 file_info->StreamSize = cpu_to_le64(stream_name_len);
4571 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4574 buf_free_len -= next;
4575 file_info->NextEntryOffset = cpu_to_le32(next);
4579 if (!S_ISDIR(stat.mode) &&
4580 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4581 file_info = (struct smb2_file_stream_info *)
4582 &rsp->Buffer[nbytes];
4583 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4584 "::$DATA", 7, conn->local_nls, 0);
4586 file_info->StreamNameLength = cpu_to_le32(streamlen);
4587 file_info->StreamSize = cpu_to_le64(stat.size);
4588 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4589 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4592 /* last entry offset should be 0 */
4593 file_info->NextEntryOffset = 0;
4596 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4597 inc_rfc1001_len(rsp_org, nbytes);
4600 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4601 struct ksmbd_file *fp, void *rsp_org)
4603 struct smb2_file_internal_info *file_info;
4606 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4608 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4609 file_info->IndexNumber = cpu_to_le64(stat.ino);
4610 rsp->OutputBufferLength =
4611 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4612 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4615 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4616 struct ksmbd_file *fp, void *rsp_org)
4618 struct smb2_file_ntwrk_info *file_info;
4619 struct inode *inode;
4623 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4624 pr_err("no right to read the attributes : 0x%x\n",
4629 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4631 inode = file_inode(fp->filp);
4632 generic_fillattr(file_mnt_idmap(fp->filp), inode, &stat);
4634 file_info->CreationTime = cpu_to_le64(fp->create_time);
4635 time = ksmbd_UnixTimeToNT(stat.atime);
4636 file_info->LastAccessTime = cpu_to_le64(time);
4637 time = ksmbd_UnixTimeToNT(stat.mtime);
4638 file_info->LastWriteTime = cpu_to_le64(time);
4639 time = ksmbd_UnixTimeToNT(stat.ctime);
4640 file_info->ChangeTime = cpu_to_le64(time);
4641 file_info->Attributes = fp->f_ci->m_fattr;
4642 file_info->AllocationSize =
4643 cpu_to_le64(get_allocation_size(inode, &stat));
4644 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4645 file_info->Reserved = cpu_to_le32(0);
4646 rsp->OutputBufferLength =
4647 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4648 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4652 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4654 struct smb2_file_ea_info *file_info;
4656 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4657 file_info->EASize = 0;
4658 rsp->OutputBufferLength =
4659 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4660 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4663 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4664 struct ksmbd_file *fp, void *rsp_org)
4666 struct smb2_file_pos_info *file_info;
4668 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4669 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4670 rsp->OutputBufferLength =
4671 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4672 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4675 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4676 struct ksmbd_file *fp, void *rsp_org)
4678 struct smb2_file_mode_info *file_info;
4680 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4681 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4682 rsp->OutputBufferLength =
4683 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4684 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4687 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4688 struct ksmbd_file *fp, void *rsp_org)
4690 struct smb2_file_comp_info *file_info;
4693 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4696 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4697 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4698 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4699 file_info->CompressionUnitShift = 0;
4700 file_info->ChunkShift = 0;
4701 file_info->ClusterShift = 0;
4702 memset(&file_info->Reserved[0], 0, 3);
4704 rsp->OutputBufferLength =
4705 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4706 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4709 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4710 struct ksmbd_file *fp, void *rsp_org)
4712 struct smb2_file_attr_tag_info *file_info;
4714 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4715 pr_err("no right to read the attributes : 0x%x\n",
4720 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4721 file_info->FileAttributes = fp->f_ci->m_fattr;
4722 file_info->ReparseTag = 0;
4723 rsp->OutputBufferLength =
4724 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4725 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4729 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4730 struct ksmbd_file *fp, void *rsp_org)
4732 struct smb311_posix_qinfo *file_info;
4733 struct inode *inode = file_inode(fp->filp);
4734 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4735 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
4736 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
4738 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4740 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4741 file_info->CreationTime = cpu_to_le64(fp->create_time);
4742 time = ksmbd_UnixTimeToNT(inode->i_atime);
4743 file_info->LastAccessTime = cpu_to_le64(time);
4744 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4745 file_info->LastWriteTime = cpu_to_le64(time);
4746 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4747 file_info->ChangeTime = cpu_to_le64(time);
4748 file_info->DosAttributes = fp->f_ci->m_fattr;
4749 file_info->Inode = cpu_to_le64(inode->i_ino);
4750 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4751 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4752 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4753 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4754 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4757 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4758 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4759 * sub_auth(4 * 1(num_subauth)) + RID(4).
4761 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4762 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4763 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4764 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4766 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4767 inc_rfc1001_len(rsp_org, out_buf_len);
4771 static int smb2_get_info_file(struct ksmbd_work *work,
4772 struct smb2_query_info_req *req,
4773 struct smb2_query_info_rsp *rsp)
4775 struct ksmbd_file *fp;
4776 int fileinfoclass = 0;
4778 int file_infoclass_size;
4779 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4781 if (test_share_config_flag(work->tcon->share_conf,
4782 KSMBD_SHARE_FLAG_PIPE)) {
4783 /* smb2 info file called for pipe */
4784 return smb2_get_info_file_pipe(work->sess, req, rsp,
4785 work->response_buf);
4788 if (work->next_smb2_rcv_hdr_off) {
4789 if (!has_file_id(req->VolatileFileId)) {
4790 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4791 work->compound_fid);
4792 id = work->compound_fid;
4793 pid = work->compound_pfid;
4797 if (!has_file_id(id)) {
4798 id = req->VolatileFileId;
4799 pid = req->PersistentFileId;
4802 fp = ksmbd_lookup_fd_slow(work, id, pid);
4806 fileinfoclass = req->FileInfoClass;
4808 switch (fileinfoclass) {
4809 case FILE_ACCESS_INFORMATION:
4810 get_file_access_info(rsp, fp, work->response_buf);
4811 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4814 case FILE_BASIC_INFORMATION:
4815 rc = get_file_basic_info(rsp, fp, work->response_buf);
4816 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4819 case FILE_STANDARD_INFORMATION:
4820 get_file_standard_info(rsp, fp, work->response_buf);
4821 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4824 case FILE_ALIGNMENT_INFORMATION:
4825 get_file_alignment_info(rsp, work->response_buf);
4826 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4829 case FILE_ALL_INFORMATION:
4830 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4831 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4834 case FILE_ALTERNATE_NAME_INFORMATION:
4835 get_file_alternate_info(work, rsp, fp, work->response_buf);
4836 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4839 case FILE_STREAM_INFORMATION:
4840 get_file_stream_info(work, rsp, fp, work->response_buf);
4841 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4844 case FILE_INTERNAL_INFORMATION:
4845 get_file_internal_info(rsp, fp, work->response_buf);
4846 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4849 case FILE_NETWORK_OPEN_INFORMATION:
4850 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4851 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4854 case FILE_EA_INFORMATION:
4855 get_file_ea_info(rsp, work->response_buf);
4856 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4859 case FILE_FULL_EA_INFORMATION:
4860 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4861 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4864 case FILE_POSITION_INFORMATION:
4865 get_file_position_info(rsp, fp, work->response_buf);
4866 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4869 case FILE_MODE_INFORMATION:
4870 get_file_mode_info(rsp, fp, work->response_buf);
4871 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4874 case FILE_COMPRESSION_INFORMATION:
4875 get_file_compression_info(rsp, fp, work->response_buf);
4876 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4879 case FILE_ATTRIBUTE_TAG_INFORMATION:
4880 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4881 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4883 case SMB_FIND_FILE_POSIX_INFO:
4884 if (!work->tcon->posix_extensions) {
4885 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4888 file_infoclass_size = find_file_posix_info(rsp, fp,
4889 work->response_buf);
4893 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4898 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4899 rsp, work->response_buf,
4900 file_infoclass_size);
4901 ksmbd_fd_put(work, fp);
4905 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4906 struct smb2_query_info_req *req,
4907 struct smb2_query_info_rsp *rsp)
4909 struct ksmbd_session *sess = work->sess;
4910 struct ksmbd_conn *conn = work->conn;
4911 struct ksmbd_share_config *share = work->tcon->share_conf;
4912 int fsinfoclass = 0;
4913 struct kstatfs stfs;
4916 int fs_infoclass_size = 0;
4921 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4923 pr_err("cannot create vfs path\n");
4927 rc = vfs_statfs(&path, &stfs);
4929 pr_err("cannot do stat of path %s\n", share->path);
4934 fsinfoclass = req->FileInfoClass;
4936 switch (fsinfoclass) {
4937 case FS_DEVICE_INFORMATION:
4939 struct filesystem_device_info *info;
4941 info = (struct filesystem_device_info *)rsp->Buffer;
4943 info->DeviceType = cpu_to_le32(stfs.f_type);
4944 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4945 rsp->OutputBufferLength = cpu_to_le32(8);
4946 inc_rfc1001_len(work->response_buf, 8);
4947 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4950 case FS_ATTRIBUTE_INFORMATION:
4952 struct filesystem_attribute_info *info;
4955 info = (struct filesystem_attribute_info *)rsp->Buffer;
4956 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4957 FILE_PERSISTENT_ACLS |
4958 FILE_UNICODE_ON_DISK |
4959 FILE_CASE_PRESERVED_NAMES |
4960 FILE_CASE_SENSITIVE_SEARCH |
4961 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4963 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4965 if (test_share_config_flag(work->tcon->share_conf,
4966 KSMBD_SHARE_FLAG_STREAMS))
4967 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
4969 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4970 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4971 "NTFS", PATH_MAX, conn->local_nls, 0);
4973 info->FileSystemNameLen = cpu_to_le32(len);
4974 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4975 rsp->OutputBufferLength = cpu_to_le32(sz);
4976 inc_rfc1001_len(work->response_buf, sz);
4977 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4980 case FS_VOLUME_INFORMATION:
4982 struct filesystem_vol_info *info;
4984 unsigned int serial_crc = 0;
4986 info = (struct filesystem_vol_info *)(rsp->Buffer);
4987 info->VolumeCreationTime = 0;
4988 serial_crc = crc32_le(serial_crc, share->name,
4989 strlen(share->name));
4990 serial_crc = crc32_le(serial_crc, share->path,
4991 strlen(share->path));
4992 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4993 strlen(ksmbd_netbios_name()));
4994 /* Taking dummy value of serial number*/
4995 info->SerialNumber = cpu_to_le32(serial_crc);
4996 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4997 share->name, PATH_MAX,
4998 conn->local_nls, 0);
5000 info->VolumeLabelSize = cpu_to_le32(len);
5002 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5003 rsp->OutputBufferLength = cpu_to_le32(sz);
5004 inc_rfc1001_len(work->response_buf, sz);
5005 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
5008 case FS_SIZE_INFORMATION:
5010 struct filesystem_info *info;
5012 info = (struct filesystem_info *)(rsp->Buffer);
5013 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5014 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5015 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5016 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5017 rsp->OutputBufferLength = cpu_to_le32(24);
5018 inc_rfc1001_len(work->response_buf, 24);
5019 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
5022 case FS_FULL_SIZE_INFORMATION:
5024 struct smb2_fs_full_size_info *info;
5026 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5027 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5028 info->CallerAvailableAllocationUnits =
5029 cpu_to_le64(stfs.f_bavail);
5030 info->ActualAvailableAllocationUnits =
5031 cpu_to_le64(stfs.f_bfree);
5032 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5033 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5034 rsp->OutputBufferLength = cpu_to_le32(32);
5035 inc_rfc1001_len(work->response_buf, 32);
5036 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
5039 case FS_OBJECT_ID_INFORMATION:
5041 struct object_id_info *info;
5043 info = (struct object_id_info *)(rsp->Buffer);
5045 if (!user_guest(sess->user))
5046 memcpy(info->objid, user_passkey(sess->user), 16);
5048 memset(info->objid, 0, 16);
5050 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5051 info->extended_info.version = cpu_to_le32(1);
5052 info->extended_info.release = cpu_to_le32(1);
5053 info->extended_info.rel_date = 0;
5054 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5055 rsp->OutputBufferLength = cpu_to_le32(64);
5056 inc_rfc1001_len(work->response_buf, 64);
5057 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5060 case FS_SECTOR_SIZE_INFORMATION:
5062 struct smb3_fs_ss_info *info;
5063 unsigned int sector_size =
5064 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5066 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5068 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5069 info->PhysicalBytesPerSectorForAtomicity =
5070 cpu_to_le32(sector_size);
5071 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5072 info->FSEffPhysicalBytesPerSectorForAtomicity =
5073 cpu_to_le32(sector_size);
5074 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5075 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5076 info->ByteOffsetForSectorAlignment = 0;
5077 info->ByteOffsetForPartitionAlignment = 0;
5078 rsp->OutputBufferLength = cpu_to_le32(28);
5079 inc_rfc1001_len(work->response_buf, 28);
5080 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5083 case FS_CONTROL_INFORMATION:
5086 * TODO : The current implementation is based on
5087 * test result with win7(NTFS) server. It's need to
5088 * modify this to get valid Quota values
5091 struct smb2_fs_control_info *info;
5093 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5094 info->FreeSpaceStartFiltering = 0;
5095 info->FreeSpaceThreshold = 0;
5096 info->FreeSpaceStopFiltering = 0;
5097 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5098 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5100 rsp->OutputBufferLength = cpu_to_le32(48);
5101 inc_rfc1001_len(work->response_buf, 48);
5102 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5105 case FS_POSIX_INFORMATION:
5107 struct filesystem_posix_info *info;
5109 if (!work->tcon->posix_extensions) {
5110 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5113 info = (struct filesystem_posix_info *)(rsp->Buffer);
5114 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5115 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5116 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5117 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5118 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5119 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5120 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5121 rsp->OutputBufferLength = cpu_to_le32(56);
5122 inc_rfc1001_len(work->response_buf, 56);
5123 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5131 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5132 rsp, work->response_buf,
5138 static int smb2_get_info_sec(struct ksmbd_work *work,
5139 struct smb2_query_info_req *req,
5140 struct smb2_query_info_rsp *rsp)
5142 struct ksmbd_file *fp;
5143 struct mnt_idmap *idmap;
5144 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5145 struct smb_fattr fattr = {{0}};
5146 struct inode *inode;
5147 __u32 secdesclen = 0;
5148 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5149 int addition_info = le32_to_cpu(req->AdditionalInformation);
5150 int rc = 0, ppntsd_size = 0;
5152 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5153 PROTECTED_DACL_SECINFO |
5154 UNPROTECTED_DACL_SECINFO)) {
5155 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5158 pntsd->revision = cpu_to_le16(1);
5159 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5160 pntsd->osidoffset = 0;
5161 pntsd->gsidoffset = 0;
5162 pntsd->sacloffset = 0;
5163 pntsd->dacloffset = 0;
5165 secdesclen = sizeof(struct smb_ntsd);
5166 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5167 inc_rfc1001_len(work->response_buf, secdesclen);
5172 if (work->next_smb2_rcv_hdr_off) {
5173 if (!has_file_id(req->VolatileFileId)) {
5174 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5175 work->compound_fid);
5176 id = work->compound_fid;
5177 pid = work->compound_pfid;
5181 if (!has_file_id(id)) {
5182 id = req->VolatileFileId;
5183 pid = req->PersistentFileId;
5186 fp = ksmbd_lookup_fd_slow(work, id, pid);
5190 idmap = file_mnt_idmap(fp->filp);
5191 inode = file_inode(fp->filp);
5192 ksmbd_acls_fattr(&fattr, idmap, inode);
5194 if (test_share_config_flag(work->tcon->share_conf,
5195 KSMBD_SHARE_FLAG_ACL_XATTR))
5196 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5197 fp->filp->f_path.dentry,
5200 /* Check if sd buffer size exceeds response buffer size */
5201 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5202 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5203 addition_info, &secdesclen, &fattr);
5204 posix_acl_release(fattr.cf_acls);
5205 posix_acl_release(fattr.cf_dacls);
5207 ksmbd_fd_put(work, fp);
5211 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5212 inc_rfc1001_len(work->response_buf, secdesclen);
5217 * smb2_query_info() - handler for smb2 query info command
5218 * @work: smb work containing query info request buffer
5220 * Return: 0 on success, otherwise error
5222 int smb2_query_info(struct ksmbd_work *work)
5224 struct smb2_query_info_req *req;
5225 struct smb2_query_info_rsp *rsp;
5228 WORK_BUFFERS(work, req, rsp);
5230 ksmbd_debug(SMB, "GOT query info request\n");
5232 switch (req->InfoType) {
5233 case SMB2_O_INFO_FILE:
5234 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5235 rc = smb2_get_info_file(work, req, rsp);
5237 case SMB2_O_INFO_FILESYSTEM:
5238 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5239 rc = smb2_get_info_filesystem(work, req, rsp);
5241 case SMB2_O_INFO_SECURITY:
5242 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5243 rc = smb2_get_info_sec(work, req, rsp);
5246 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5253 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5254 else if (rc == -ENOENT)
5255 rsp->hdr.Status = STATUS_FILE_CLOSED;
5256 else if (rc == -EIO)
5257 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5258 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5259 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5260 smb2_set_err_rsp(work);
5262 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5266 rsp->StructureSize = cpu_to_le16(9);
5267 rsp->OutputBufferOffset = cpu_to_le16(72);
5268 inc_rfc1001_len(work->response_buf, 8);
5273 * smb2_close_pipe() - handler for closing IPC pipe
5274 * @work: smb work containing close request buffer
5278 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5281 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5282 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5284 id = req->VolatileFileId;
5285 ksmbd_session_rpc_close(work->sess, id);
5287 rsp->StructureSize = cpu_to_le16(60);
5290 rsp->CreationTime = 0;
5291 rsp->LastAccessTime = 0;
5292 rsp->LastWriteTime = 0;
5293 rsp->ChangeTime = 0;
5294 rsp->AllocationSize = 0;
5296 rsp->Attributes = 0;
5297 inc_rfc1001_len(work->response_buf, 60);
5302 * smb2_close() - handler for smb2 close file command
5303 * @work: smb work containing close request buffer
5307 int smb2_close(struct ksmbd_work *work)
5309 u64 volatile_id = KSMBD_NO_FID;
5311 struct smb2_close_req *req;
5312 struct smb2_close_rsp *rsp;
5313 struct ksmbd_conn *conn = work->conn;
5314 struct ksmbd_file *fp;
5315 struct inode *inode;
5319 WORK_BUFFERS(work, req, rsp);
5321 if (test_share_config_flag(work->tcon->share_conf,
5322 KSMBD_SHARE_FLAG_PIPE)) {
5323 ksmbd_debug(SMB, "IPC pipe close request\n");
5324 return smb2_close_pipe(work);
5327 sess_id = le64_to_cpu(req->hdr.SessionId);
5328 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5329 sess_id = work->compound_sid;
5331 work->compound_sid = 0;
5332 if (check_session_id(conn, sess_id)) {
5333 work->compound_sid = sess_id;
5335 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5336 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5337 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5342 if (work->next_smb2_rcv_hdr_off &&
5343 !has_file_id(req->VolatileFileId)) {
5344 if (!has_file_id(work->compound_fid)) {
5345 /* file already closed, return FILE_CLOSED */
5346 ksmbd_debug(SMB, "file already closed\n");
5347 rsp->hdr.Status = STATUS_FILE_CLOSED;
5352 "Compound request set FID = %llu:%llu\n",
5354 work->compound_pfid);
5355 volatile_id = work->compound_fid;
5357 /* file closed, stored id is not valid anymore */
5358 work->compound_fid = KSMBD_NO_FID;
5359 work->compound_pfid = KSMBD_NO_FID;
5362 volatile_id = req->VolatileFileId;
5364 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5366 rsp->StructureSize = cpu_to_le16(60);
5369 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5370 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5376 inode = file_inode(fp->filp);
5377 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5378 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5379 cpu_to_le64(inode->i_blocks << 9);
5380 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5381 rsp->Attributes = fp->f_ci->m_fattr;
5382 rsp->CreationTime = cpu_to_le64(fp->create_time);
5383 time = ksmbd_UnixTimeToNT(inode->i_atime);
5384 rsp->LastAccessTime = cpu_to_le64(time);
5385 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5386 rsp->LastWriteTime = cpu_to_le64(time);
5387 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5388 rsp->ChangeTime = cpu_to_le64(time);
5389 ksmbd_fd_put(work, fp);
5392 rsp->AllocationSize = 0;
5394 rsp->Attributes = 0;
5395 rsp->CreationTime = 0;
5396 rsp->LastAccessTime = 0;
5397 rsp->LastWriteTime = 0;
5398 rsp->ChangeTime = 0;
5401 err = ksmbd_close_fd(work, volatile_id);
5404 if (rsp->hdr.Status == 0)
5405 rsp->hdr.Status = STATUS_FILE_CLOSED;
5406 smb2_set_err_rsp(work);
5408 inc_rfc1001_len(work->response_buf, 60);
5415 * smb2_echo() - handler for smb2 echo(ping) command
5416 * @work: smb work containing echo request buffer
5420 int smb2_echo(struct ksmbd_work *work)
5422 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5424 rsp->StructureSize = cpu_to_le16(4);
5426 inc_rfc1001_len(work->response_buf, 4);
5430 static int smb2_rename(struct ksmbd_work *work,
5431 struct ksmbd_file *fp,
5432 struct smb2_file_rename_info *file_info,
5433 struct nls_table *local_nls)
5435 struct ksmbd_share_config *share = fp->tcon->share_conf;
5436 char *new_name = NULL;
5439 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5440 new_name = smb2_get_name(file_info->FileName,
5441 le32_to_cpu(file_info->FileNameLength),
5443 if (IS_ERR(new_name))
5444 return PTR_ERR(new_name);
5446 if (strchr(new_name, ':')) {
5448 char *xattr_stream_name, *stream_name = NULL;
5449 size_t xattr_stream_size;
5452 rc = parse_stream_name(new_name, &stream_name, &s_type);
5456 len = strlen(new_name);
5457 if (len > 0 && new_name[len - 1] != '/') {
5458 pr_err("not allow base filename in rename\n");
5463 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5470 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5471 fp->filp->f_path.dentry,
5475 pr_err("failed to store stream name in xattr: %d\n",
5484 ksmbd_debug(SMB, "new name %s\n", new_name);
5485 if (ksmbd_share_veto_filename(share, new_name)) {
5487 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5491 if (!file_info->ReplaceIfExists)
5492 flags = RENAME_NOREPLACE;
5494 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5500 static int smb2_create_link(struct ksmbd_work *work,
5501 struct ksmbd_share_config *share,
5502 struct smb2_file_link_info *file_info,
5503 unsigned int buf_len, struct file *filp,
5504 struct nls_table *local_nls)
5506 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5508 bool file_present = true;
5511 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5512 le32_to_cpu(file_info->FileNameLength))
5515 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5516 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5520 link_name = smb2_get_name(file_info->FileName,
5521 le32_to_cpu(file_info->FileNameLength),
5523 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5528 ksmbd_debug(SMB, "link name is %s\n", link_name);
5529 target_name = file_path(filp, pathname, PATH_MAX);
5530 if (IS_ERR(target_name)) {
5535 ksmbd_debug(SMB, "target name is %s\n", target_name);
5536 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5541 file_present = false;
5544 if (file_info->ReplaceIfExists) {
5546 rc = ksmbd_vfs_remove_file(work, &path);
5549 ksmbd_debug(SMB, "cannot delete %s\n",
5557 ksmbd_debug(SMB, "link already exists\n");
5562 rc = ksmbd_vfs_link(work, target_name, link_name);
5567 inode_unlock(d_inode(path.dentry->d_parent));
5570 if (!IS_ERR(link_name))
5576 static int set_file_basic_info(struct ksmbd_file *fp,
5577 struct smb2_file_basic_info *file_info,
5578 struct ksmbd_share_config *share)
5582 struct inode *inode;
5583 struct mnt_idmap *idmap;
5586 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5591 inode = file_inode(filp);
5592 idmap = file_mnt_idmap(filp);
5594 if (file_info->CreationTime)
5595 fp->create_time = le64_to_cpu(file_info->CreationTime);
5597 if (file_info->LastAccessTime) {
5598 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5599 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5602 attrs.ia_valid |= ATTR_CTIME;
5603 if (file_info->ChangeTime)
5604 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5606 attrs.ia_ctime = inode->i_ctime;
5608 if (file_info->LastWriteTime) {
5609 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5610 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5613 if (file_info->Attributes) {
5614 if (!S_ISDIR(inode->i_mode) &&
5615 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5616 pr_err("can't change a file to a directory\n");
5620 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5621 fp->f_ci->m_fattr = file_info->Attributes |
5622 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5625 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5626 (file_info->CreationTime || file_info->Attributes)) {
5627 struct xattr_dos_attrib da = {0};
5630 da.itime = fp->itime;
5631 da.create_time = fp->create_time;
5632 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5633 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5634 XATTR_DOSINFO_ITIME;
5636 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap,
5637 filp->f_path.dentry, &da);
5640 "failed to restore file attribute in EA\n");
5644 if (attrs.ia_valid) {
5645 struct dentry *dentry = filp->f_path.dentry;
5646 struct inode *inode = d_inode(dentry);
5648 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5652 inode->i_ctime = attrs.ia_ctime;
5653 attrs.ia_valid &= ~ATTR_CTIME;
5654 rc = notify_change(idmap, dentry, &attrs, NULL);
5655 inode_unlock(inode);
5660 static int set_file_allocation_info(struct ksmbd_work *work,
5661 struct ksmbd_file *fp,
5662 struct smb2_file_alloc_info *file_alloc_info)
5665 * TODO : It's working fine only when store dos attributes
5666 * is not yes. need to implement a logic which works
5667 * properly with any smb.conf option
5671 struct inode *inode;
5674 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5677 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5678 inode = file_inode(fp->filp);
5680 if (alloc_blks > inode->i_blocks) {
5681 smb_break_all_levII_oplock(work, fp, 1);
5682 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5684 if (rc && rc != -EOPNOTSUPP) {
5685 pr_err("vfs_fallocate is failed : %d\n", rc);
5688 } else if (alloc_blks < inode->i_blocks) {
5692 * Allocation size could be smaller than original one
5693 * which means allocated blocks in file should be
5694 * deallocated. use truncate to cut out it, but inode
5695 * size is also updated with truncate offset.
5696 * inode size is retained by backup inode size.
5698 size = i_size_read(inode);
5699 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5701 pr_err("truncate failed!, err %d\n", rc);
5704 if (size < alloc_blks * 512)
5705 i_size_write(inode, size);
5710 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5711 struct smb2_file_eof_info *file_eof_info)
5714 struct inode *inode;
5717 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5720 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5721 inode = file_inode(fp->filp);
5724 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5725 * on FAT32 shared device, truncate execution time is too long
5726 * and network error could cause from windows client. because
5727 * truncate of some filesystem like FAT32 fill zero data in
5730 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5731 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5732 rc = ksmbd_vfs_truncate(work, fp, newsize);
5734 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5743 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5744 struct smb2_file_rename_info *rename_info,
5745 unsigned int buf_len)
5747 if (!(fp->daccess & FILE_DELETE_LE)) {
5748 pr_err("no right to delete : 0x%x\n", fp->daccess);
5752 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5753 le32_to_cpu(rename_info->FileNameLength))
5756 if (!le32_to_cpu(rename_info->FileNameLength))
5759 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5762 static int set_file_disposition_info(struct ksmbd_file *fp,
5763 struct smb2_file_disposition_info *file_info)
5765 struct inode *inode;
5767 if (!(fp->daccess & FILE_DELETE_LE)) {
5768 pr_err("no right to delete : 0x%x\n", fp->daccess);
5772 inode = file_inode(fp->filp);
5773 if (file_info->DeletePending) {
5774 if (S_ISDIR(inode->i_mode) &&
5775 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5777 ksmbd_set_inode_pending_delete(fp);
5779 ksmbd_clear_inode_pending_delete(fp);
5784 static int set_file_position_info(struct ksmbd_file *fp,
5785 struct smb2_file_pos_info *file_info)
5787 loff_t current_byte_offset;
5788 unsigned long sector_size;
5789 struct inode *inode;
5791 inode = file_inode(fp->filp);
5792 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5793 sector_size = inode->i_sb->s_blocksize;
5795 if (current_byte_offset < 0 ||
5796 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5797 current_byte_offset & (sector_size - 1))) {
5798 pr_err("CurrentByteOffset is not valid : %llu\n",
5799 current_byte_offset);
5803 fp->filp->f_pos = current_byte_offset;
5807 static int set_file_mode_info(struct ksmbd_file *fp,
5808 struct smb2_file_mode_info *file_info)
5812 mode = file_info->Mode;
5814 if ((mode & ~FILE_MODE_INFO_MASK)) {
5815 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5820 * TODO : need to implement consideration for
5821 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5823 ksmbd_vfs_set_fadvise(fp->filp, mode);
5829 * smb2_set_info_file() - handler for smb2 set info command
5830 * @work: smb work containing set info command buffer
5831 * @fp: ksmbd_file pointer
5832 * @req: request buffer pointer
5833 * @share: ksmbd_share_config pointer
5835 * Return: 0 on success, otherwise error
5836 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5838 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5839 struct smb2_set_info_req *req,
5840 struct ksmbd_share_config *share)
5842 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5844 switch (req->FileInfoClass) {
5845 case FILE_BASIC_INFORMATION:
5847 if (buf_len < sizeof(struct smb2_file_basic_info))
5850 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5852 case FILE_ALLOCATION_INFORMATION:
5854 if (buf_len < sizeof(struct smb2_file_alloc_info))
5857 return set_file_allocation_info(work, fp,
5858 (struct smb2_file_alloc_info *)req->Buffer);
5860 case FILE_END_OF_FILE_INFORMATION:
5862 if (buf_len < sizeof(struct smb2_file_eof_info))
5865 return set_end_of_file_info(work, fp,
5866 (struct smb2_file_eof_info *)req->Buffer);
5868 case FILE_RENAME_INFORMATION:
5870 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5872 "User does not have write permission\n");
5876 if (buf_len < sizeof(struct smb2_file_rename_info))
5879 return set_rename_info(work, fp,
5880 (struct smb2_file_rename_info *)req->Buffer,
5883 case FILE_LINK_INFORMATION:
5885 if (buf_len < sizeof(struct smb2_file_link_info))
5888 return smb2_create_link(work, work->tcon->share_conf,
5889 (struct smb2_file_link_info *)req->Buffer,
5891 work->conn->local_nls);
5893 case FILE_DISPOSITION_INFORMATION:
5895 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5897 "User does not have write permission\n");
5901 if (buf_len < sizeof(struct smb2_file_disposition_info))
5904 return set_file_disposition_info(fp,
5905 (struct smb2_file_disposition_info *)req->Buffer);
5907 case FILE_FULL_EA_INFORMATION:
5909 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5910 pr_err("Not permitted to write ext attr: 0x%x\n",
5915 if (buf_len < sizeof(struct smb2_ea_info))
5918 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5919 buf_len, &fp->filp->f_path);
5921 case FILE_POSITION_INFORMATION:
5923 if (buf_len < sizeof(struct smb2_file_pos_info))
5926 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5928 case FILE_MODE_INFORMATION:
5930 if (buf_len < sizeof(struct smb2_file_mode_info))
5933 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5937 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5941 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5942 char *buffer, int buf_len)
5944 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5946 fp->saccess |= FILE_SHARE_DELETE_LE;
5948 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5953 * smb2_set_info() - handler for smb2 set info command handler
5954 * @work: smb work containing set info request buffer
5956 * Return: 0 on success, otherwise error
5958 int smb2_set_info(struct ksmbd_work *work)
5960 struct smb2_set_info_req *req;
5961 struct smb2_set_info_rsp *rsp;
5962 struct ksmbd_file *fp;
5964 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5966 ksmbd_debug(SMB, "Received set info request\n");
5968 if (work->next_smb2_rcv_hdr_off) {
5969 req = ksmbd_req_buf_next(work);
5970 rsp = ksmbd_resp_buf_next(work);
5971 if (!has_file_id(req->VolatileFileId)) {
5972 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5973 work->compound_fid);
5974 id = work->compound_fid;
5975 pid = work->compound_pfid;
5978 req = smb2_get_msg(work->request_buf);
5979 rsp = smb2_get_msg(work->response_buf);
5982 if (!has_file_id(id)) {
5983 id = req->VolatileFileId;
5984 pid = req->PersistentFileId;
5987 fp = ksmbd_lookup_fd_slow(work, id, pid);
5989 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
5994 switch (req->InfoType) {
5995 case SMB2_O_INFO_FILE:
5996 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5997 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
5999 case SMB2_O_INFO_SECURITY:
6000 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6001 if (ksmbd_override_fsids(work)) {
6005 rc = smb2_set_info_sec(fp,
6006 le32_to_cpu(req->AdditionalInformation),
6008 le32_to_cpu(req->BufferLength));
6009 ksmbd_revert_fsids(work);
6018 rsp->StructureSize = cpu_to_le16(2);
6019 inc_rfc1001_len(work->response_buf, 2);
6020 ksmbd_fd_put(work, fp);
6024 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6025 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6026 else if (rc == -EINVAL)
6027 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6028 else if (rc == -ESHARE)
6029 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6030 else if (rc == -ENOENT)
6031 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6032 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6033 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6034 else if (rc == -EAGAIN)
6035 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6036 else if (rc == -EBADF || rc == -ESTALE)
6037 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6038 else if (rc == -EEXIST)
6039 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6040 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6041 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6042 smb2_set_err_rsp(work);
6043 ksmbd_fd_put(work, fp);
6044 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6049 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6050 * @work: smb work containing read IPC pipe command buffer
6052 * Return: 0 on success, otherwise error
6054 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6056 int nbytes = 0, err;
6058 struct ksmbd_rpc_command *rpc_resp;
6059 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6060 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6062 id = req->VolatileFileId;
6064 inc_rfc1001_len(work->response_buf, 16);
6065 rpc_resp = ksmbd_rpc_read(work->sess, id);
6067 if (rpc_resp->flags != KSMBD_RPC_OK) {
6072 work->aux_payload_buf =
6073 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6074 if (!work->aux_payload_buf) {
6079 memcpy(work->aux_payload_buf, rpc_resp->payload,
6080 rpc_resp->payload_sz);
6082 nbytes = rpc_resp->payload_sz;
6083 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6084 work->aux_payload_sz = nbytes;
6088 rsp->StructureSize = cpu_to_le16(17);
6089 rsp->DataOffset = 80;
6091 rsp->DataLength = cpu_to_le32(nbytes);
6092 rsp->DataRemaining = 0;
6094 inc_rfc1001_len(work->response_buf, nbytes);
6098 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6099 smb2_set_err_rsp(work);
6104 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6105 struct smb2_buffer_desc_v1 *desc,
6107 __le16 ChannelInfoLength)
6109 unsigned int i, ch_count;
6111 if (work->conn->dialect == SMB30_PROT_ID &&
6112 Channel != SMB2_CHANNEL_RDMA_V1)
6115 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6116 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6117 for (i = 0; i < ch_count; i++) {
6118 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6120 le32_to_cpu(desc[i].token),
6121 le32_to_cpu(desc[i].length));
6127 work->need_invalidate_rkey =
6128 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6129 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6130 work->remote_key = le32_to_cpu(desc->token);
6134 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6135 struct smb2_read_req *req, void *data_buf,
6140 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6141 (struct smb2_buffer_desc_v1 *)
6142 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6143 le16_to_cpu(req->ReadChannelInfoLength));
6151 * smb2_read() - handler for smb2 read from file
6152 * @work: smb work containing read command buffer
6154 * Return: 0 on success, otherwise error
6156 int smb2_read(struct ksmbd_work *work)
6158 struct ksmbd_conn *conn = work->conn;
6159 struct smb2_read_req *req;
6160 struct smb2_read_rsp *rsp;
6161 struct ksmbd_file *fp = NULL;
6163 size_t length, mincount;
6164 ssize_t nbytes = 0, remain_bytes = 0;
6166 bool is_rdma_channel = false;
6167 unsigned int max_read_size = conn->vals->max_read_size;
6169 WORK_BUFFERS(work, req, rsp);
6171 if (test_share_config_flag(work->tcon->share_conf,
6172 KSMBD_SHARE_FLAG_PIPE)) {
6173 ksmbd_debug(SMB, "IPC pipe read request\n");
6174 return smb2_read_pipe(work);
6177 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6178 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6179 is_rdma_channel = true;
6180 max_read_size = get_smbd_max_read_write_size();
6183 if (is_rdma_channel == true) {
6184 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6186 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6190 err = smb2_set_remote_key_for_rdma(work,
6191 (struct smb2_buffer_desc_v1 *)
6192 ((char *)req + ch_offset),
6194 req->ReadChannelInfoLength);
6199 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6205 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6206 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6211 offset = le64_to_cpu(req->Offset);
6212 length = le32_to_cpu(req->Length);
6213 mincount = le32_to_cpu(req->MinimumCount);
6215 if (length > max_read_size) {
6216 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6222 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6223 fp->filp, offset, length);
6225 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6226 if (!work->aux_payload_buf) {
6231 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6237 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6238 kvfree(work->aux_payload_buf);
6239 work->aux_payload_buf = NULL;
6240 rsp->hdr.Status = STATUS_END_OF_FILE;
6241 smb2_set_err_rsp(work);
6242 ksmbd_fd_put(work, fp);
6246 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6247 nbytes, offset, mincount);
6249 if (is_rdma_channel == true) {
6250 /* write data to the client using rdma channel */
6251 remain_bytes = smb2_read_rdma_channel(work, req,
6252 work->aux_payload_buf,
6254 kvfree(work->aux_payload_buf);
6255 work->aux_payload_buf = NULL;
6258 if (remain_bytes < 0) {
6259 err = (int)remain_bytes;
6264 rsp->StructureSize = cpu_to_le16(17);
6265 rsp->DataOffset = 80;
6267 rsp->DataLength = cpu_to_le32(nbytes);
6268 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6270 inc_rfc1001_len(work->response_buf, 16);
6271 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6272 work->aux_payload_sz = nbytes;
6273 inc_rfc1001_len(work->response_buf, nbytes);
6274 ksmbd_fd_put(work, fp);
6280 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6281 else if (err == -EAGAIN)
6282 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6283 else if (err == -ENOENT)
6284 rsp->hdr.Status = STATUS_FILE_CLOSED;
6285 else if (err == -EACCES)
6286 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6287 else if (err == -ESHARE)
6288 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6289 else if (err == -EINVAL)
6290 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6292 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6294 smb2_set_err_rsp(work);
6296 ksmbd_fd_put(work, fp);
6301 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6302 * @work: smb work containing write IPC pipe command buffer
6304 * Return: 0 on success, otherwise error
6306 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6308 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6309 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6310 struct ksmbd_rpc_command *rpc_resp;
6312 int err = 0, ret = 0;
6316 length = le32_to_cpu(req->Length);
6317 id = req->VolatileFileId;
6319 if ((u64)le16_to_cpu(req->DataOffset) + length >
6320 get_rfc1002_len(work->request_buf)) {
6321 pr_err("invalid write data offset %u, smb_len %u\n",
6322 le16_to_cpu(req->DataOffset),
6323 get_rfc1002_len(work->request_buf));
6328 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6329 le16_to_cpu(req->DataOffset));
6331 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6333 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6334 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6336 smb2_set_err_rsp(work);
6339 if (rpc_resp->flags != KSMBD_RPC_OK) {
6340 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6341 smb2_set_err_rsp(work);
6348 rsp->StructureSize = cpu_to_le16(17);
6349 rsp->DataOffset = 0;
6351 rsp->DataLength = cpu_to_le32(length);
6352 rsp->DataRemaining = 0;
6354 inc_rfc1001_len(work->response_buf, 16);
6358 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6359 smb2_set_err_rsp(work);
6365 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6366 struct smb2_write_req *req,
6367 struct ksmbd_file *fp,
6368 loff_t offset, size_t length, bool sync)
6374 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6378 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6379 (struct smb2_buffer_desc_v1 *)
6380 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6381 le16_to_cpu(req->WriteChannelInfoLength));
6387 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6396 * smb2_write() - handler for smb2 write from file
6397 * @work: smb work containing write command buffer
6399 * Return: 0 on success, otherwise error
6401 int smb2_write(struct ksmbd_work *work)
6403 struct smb2_write_req *req;
6404 struct smb2_write_rsp *rsp;
6405 struct ksmbd_file *fp = NULL;
6410 bool writethrough = false, is_rdma_channel = false;
6412 unsigned int max_write_size = work->conn->vals->max_write_size;
6414 WORK_BUFFERS(work, req, rsp);
6416 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6417 ksmbd_debug(SMB, "IPC pipe write request\n");
6418 return smb2_write_pipe(work);
6421 offset = le64_to_cpu(req->Offset);
6422 length = le32_to_cpu(req->Length);
6424 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6425 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6426 is_rdma_channel = true;
6427 max_write_size = get_smbd_max_read_write_size();
6428 length = le32_to_cpu(req->RemainingBytes);
6431 if (is_rdma_channel == true) {
6432 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6434 if (req->Length != 0 || req->DataOffset != 0 ||
6435 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6439 err = smb2_set_remote_key_for_rdma(work,
6440 (struct smb2_buffer_desc_v1 *)
6441 ((char *)req + ch_offset),
6443 req->WriteChannelInfoLength);
6448 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6449 ksmbd_debug(SMB, "User does not have write permission\n");
6454 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6460 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6461 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6466 if (length > max_write_size) {
6467 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6473 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6474 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6475 writethrough = true;
6477 if (is_rdma_channel == false) {
6478 if (le16_to_cpu(req->DataOffset) <
6479 offsetof(struct smb2_write_req, Buffer)) {
6484 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6485 le16_to_cpu(req->DataOffset));
6487 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6488 fp->filp, offset, length);
6489 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6490 writethrough, &nbytes);
6494 /* read data from the client using rdma channel, and
6497 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6505 rsp->StructureSize = cpu_to_le16(17);
6506 rsp->DataOffset = 0;
6508 rsp->DataLength = cpu_to_le32(nbytes);
6509 rsp->DataRemaining = 0;
6511 inc_rfc1001_len(work->response_buf, 16);
6512 ksmbd_fd_put(work, fp);
6517 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6518 else if (err == -ENOSPC || err == -EFBIG)
6519 rsp->hdr.Status = STATUS_DISK_FULL;
6520 else if (err == -ENOENT)
6521 rsp->hdr.Status = STATUS_FILE_CLOSED;
6522 else if (err == -EACCES)
6523 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6524 else if (err == -ESHARE)
6525 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6526 else if (err == -EINVAL)
6527 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6529 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6531 smb2_set_err_rsp(work);
6532 ksmbd_fd_put(work, fp);
6537 * smb2_flush() - handler for smb2 flush file - fsync
6538 * @work: smb work containing flush command buffer
6540 * Return: 0 on success, otherwise error
6542 int smb2_flush(struct ksmbd_work *work)
6544 struct smb2_flush_req *req;
6545 struct smb2_flush_rsp *rsp;
6548 WORK_BUFFERS(work, req, rsp);
6550 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6552 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6556 rsp->StructureSize = cpu_to_le16(4);
6558 inc_rfc1001_len(work->response_buf, 4);
6563 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6564 smb2_set_err_rsp(work);
6571 * smb2_cancel() - handler for smb2 cancel command
6572 * @work: smb work containing cancel command buffer
6574 * Return: 0 on success, otherwise error
6576 int smb2_cancel(struct ksmbd_work *work)
6578 struct ksmbd_conn *conn = work->conn;
6579 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6580 struct smb2_hdr *chdr;
6581 struct ksmbd_work *iter;
6582 struct list_head *command_list;
6584 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6585 hdr->MessageId, hdr->Flags);
6587 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6588 command_list = &conn->async_requests;
6590 spin_lock(&conn->request_lock);
6591 list_for_each_entry(iter, command_list,
6592 async_request_entry) {
6593 chdr = smb2_get_msg(iter->request_buf);
6595 if (iter->async_id !=
6596 le64_to_cpu(hdr->Id.AsyncId))
6600 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6601 le64_to_cpu(hdr->Id.AsyncId),
6602 le16_to_cpu(chdr->Command));
6603 iter->state = KSMBD_WORK_CANCELLED;
6604 if (iter->cancel_fn)
6605 iter->cancel_fn(iter->cancel_argv);
6608 spin_unlock(&conn->request_lock);
6610 command_list = &conn->requests;
6612 spin_lock(&conn->request_lock);
6613 list_for_each_entry(iter, command_list, request_entry) {
6614 chdr = smb2_get_msg(iter->request_buf);
6616 if (chdr->MessageId != hdr->MessageId ||
6621 "smb2 with mid %llu cancelled command = 0x%x\n",
6622 le64_to_cpu(hdr->MessageId),
6623 le16_to_cpu(chdr->Command));
6624 iter->state = KSMBD_WORK_CANCELLED;
6627 spin_unlock(&conn->request_lock);
6630 /* For SMB2_CANCEL command itself send no response*/
6631 work->send_no_response = 1;
6635 struct file_lock *smb_flock_init(struct file *f)
6637 struct file_lock *fl;
6639 fl = locks_alloc_lock();
6643 locks_init_lock(fl);
6646 fl->fl_pid = current->tgid;
6648 fl->fl_flags = FL_POSIX;
6650 fl->fl_lmops = NULL;
6656 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6660 /* Checking for wrong flag combination during lock request*/
6662 case SMB2_LOCKFLAG_SHARED:
6663 ksmbd_debug(SMB, "received shared request\n");
6665 flock->fl_type = F_RDLCK;
6666 flock->fl_flags |= FL_SLEEP;
6668 case SMB2_LOCKFLAG_EXCLUSIVE:
6669 ksmbd_debug(SMB, "received exclusive request\n");
6671 flock->fl_type = F_WRLCK;
6672 flock->fl_flags |= FL_SLEEP;
6674 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6676 "received shared & fail immediately request\n");
6678 flock->fl_type = F_RDLCK;
6680 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6682 "received exclusive & fail immediately request\n");
6684 flock->fl_type = F_WRLCK;
6686 case SMB2_LOCKFLAG_UNLOCK:
6687 ksmbd_debug(SMB, "received unlock request\n");
6688 flock->fl_type = F_UNLCK;
6696 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6697 unsigned int cmd, int flags,
6698 struct list_head *lock_list)
6700 struct ksmbd_lock *lock;
6702 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6708 lock->start = flock->fl_start;
6709 lock->end = flock->fl_end;
6710 lock->flags = flags;
6711 if (lock->start == lock->end)
6713 INIT_LIST_HEAD(&lock->clist);
6714 INIT_LIST_HEAD(&lock->flist);
6715 INIT_LIST_HEAD(&lock->llist);
6716 list_add_tail(&lock->llist, lock_list);
6721 static void smb2_remove_blocked_lock(void **argv)
6723 struct file_lock *flock = (struct file_lock *)argv[0];
6725 ksmbd_vfs_posix_lock_unblock(flock);
6726 wake_up(&flock->fl_wait);
6729 static inline bool lock_defer_pending(struct file_lock *fl)
6731 /* check pending lock waiters */
6732 return waitqueue_active(&fl->fl_wait);
6736 * smb2_lock() - handler for smb2 file lock command
6737 * @work: smb work containing lock command buffer
6739 * Return: 0 on success, otherwise error
6741 int smb2_lock(struct ksmbd_work *work)
6743 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6744 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6745 struct smb2_lock_element *lock_ele;
6746 struct ksmbd_file *fp = NULL;
6747 struct file_lock *flock = NULL;
6748 struct file *filp = NULL;
6752 int err = -EIO, i, rc = 0;
6753 u64 lock_start, lock_length;
6754 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6755 struct ksmbd_conn *conn;
6757 LIST_HEAD(lock_list);
6758 LIST_HEAD(rollback_list);
6761 ksmbd_debug(SMB, "Received lock request\n");
6762 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6764 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6770 lock_count = le16_to_cpu(req->LockCount);
6771 lock_ele = req->locks;
6773 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6779 for (i = 0; i < lock_count; i++) {
6780 flags = le32_to_cpu(lock_ele[i].Flags);
6782 flock = smb_flock_init(filp);
6786 cmd = smb2_set_flock_flags(flock, flags);
6788 lock_start = le64_to_cpu(lock_ele[i].Offset);
6789 lock_length = le64_to_cpu(lock_ele[i].Length);
6790 if (lock_start > U64_MAX - lock_length) {
6791 pr_err("Invalid lock range requested\n");
6792 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6793 locks_free_lock(flock);
6797 if (lock_start > OFFSET_MAX)
6798 flock->fl_start = OFFSET_MAX;
6800 flock->fl_start = lock_start;
6802 lock_length = le64_to_cpu(lock_ele[i].Length);
6803 if (lock_length > OFFSET_MAX - flock->fl_start)
6804 lock_length = OFFSET_MAX - flock->fl_start;
6806 flock->fl_end = flock->fl_start + lock_length;
6808 if (flock->fl_end < flock->fl_start) {
6810 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6811 flock->fl_end, flock->fl_start);
6812 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6813 locks_free_lock(flock);
6817 /* Check conflict locks in one request */
6818 list_for_each_entry(cmp_lock, &lock_list, llist) {
6819 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6820 cmp_lock->fl->fl_end >= flock->fl_end) {
6821 if (cmp_lock->fl->fl_type != F_UNLCK &&
6822 flock->fl_type != F_UNLCK) {
6823 pr_err("conflict two locks in one request\n");
6825 locks_free_lock(flock);
6831 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6834 locks_free_lock(flock);
6839 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6840 if (smb_lock->cmd < 0) {
6845 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6850 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6851 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6852 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6853 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6858 prior_lock = smb_lock->flags;
6860 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6861 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6865 /* check locks in connection list */
6866 read_lock(&conn_list_lock);
6867 list_for_each_entry(conn, &conn_list, conns_list) {
6868 spin_lock(&conn->llist_lock);
6869 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6870 if (file_inode(cmp_lock->fl->fl_file) !=
6871 file_inode(smb_lock->fl->fl_file))
6874 if (smb_lock->fl->fl_type == F_UNLCK) {
6875 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6876 cmp_lock->start == smb_lock->start &&
6877 cmp_lock->end == smb_lock->end &&
6878 !lock_defer_pending(cmp_lock->fl)) {
6880 list_del(&cmp_lock->flist);
6881 list_del(&cmp_lock->clist);
6882 spin_unlock(&conn->llist_lock);
6883 read_unlock(&conn_list_lock);
6885 locks_free_lock(cmp_lock->fl);
6892 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6893 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6896 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6900 /* check zero byte lock range */
6901 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6902 cmp_lock->start > smb_lock->start &&
6903 cmp_lock->start < smb_lock->end) {
6904 spin_unlock(&conn->llist_lock);
6905 read_unlock(&conn_list_lock);
6906 pr_err("previous lock conflict with zero byte lock range\n");
6910 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6911 smb_lock->start > cmp_lock->start &&
6912 smb_lock->start < cmp_lock->end) {
6913 spin_unlock(&conn->llist_lock);
6914 read_unlock(&conn_list_lock);
6915 pr_err("current lock conflict with zero byte lock range\n");
6919 if (((cmp_lock->start <= smb_lock->start &&
6920 cmp_lock->end > smb_lock->start) ||
6921 (cmp_lock->start < smb_lock->end &&
6922 cmp_lock->end >= smb_lock->end)) &&
6923 !cmp_lock->zero_len && !smb_lock->zero_len) {
6924 spin_unlock(&conn->llist_lock);
6925 read_unlock(&conn_list_lock);
6926 pr_err("Not allow lock operation on exclusive lock range\n");
6930 spin_unlock(&conn->llist_lock);
6932 read_unlock(&conn_list_lock);
6934 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6935 pr_err("Try to unlock nolocked range\n");
6936 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6941 if (smb_lock->zero_len) {
6946 flock = smb_lock->fl;
6947 list_del(&smb_lock->llist);
6949 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6951 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6953 ksmbd_debug(SMB, "File unlocked\n");
6954 } else if (rc == -ENOENT) {
6955 rsp->hdr.Status = STATUS_NOT_LOCKED;
6958 locks_free_lock(flock);
6961 if (rc == FILE_LOCK_DEFERRED) {
6965 "would have to wait for getting lock\n");
6966 spin_lock(&work->conn->llist_lock);
6967 list_add_tail(&smb_lock->clist,
6968 &work->conn->lock_list);
6969 spin_unlock(&work->conn->llist_lock);
6970 list_add(&smb_lock->llist, &rollback_list);
6972 argv = kmalloc(sizeof(void *), GFP_KERNEL);
6979 rc = setup_async_work(work,
6980 smb2_remove_blocked_lock,
6986 spin_lock(&fp->f_lock);
6987 list_add(&work->fp_entry, &fp->blocked_works);
6988 spin_unlock(&fp->f_lock);
6990 smb2_send_interim_resp(work, STATUS_PENDING);
6992 ksmbd_vfs_posix_lock_wait(flock);
6994 spin_lock(&fp->f_lock);
6995 list_del(&work->fp_entry);
6996 spin_unlock(&fp->f_lock);
6998 if (work->state != KSMBD_WORK_ACTIVE) {
6999 list_del(&smb_lock->llist);
7000 spin_lock(&work->conn->llist_lock);
7001 list_del(&smb_lock->clist);
7002 spin_unlock(&work->conn->llist_lock);
7003 locks_free_lock(flock);
7005 if (work->state == KSMBD_WORK_CANCELLED) {
7009 smb2_send_interim_resp(work,
7011 work->send_no_response = 1;
7015 init_smb2_rsp_hdr(work);
7016 smb2_set_err_rsp(work);
7018 STATUS_RANGE_NOT_LOCKED;
7023 list_del(&smb_lock->llist);
7024 spin_lock(&work->conn->llist_lock);
7025 list_del(&smb_lock->clist);
7026 spin_unlock(&work->conn->llist_lock);
7027 release_async_work(work);
7030 spin_lock(&work->conn->llist_lock);
7031 list_add_tail(&smb_lock->clist,
7032 &work->conn->lock_list);
7033 list_add_tail(&smb_lock->flist,
7035 spin_unlock(&work->conn->llist_lock);
7036 list_add(&smb_lock->llist, &rollback_list);
7037 ksmbd_debug(SMB, "successful in taking lock\n");
7044 if (atomic_read(&fp->f_ci->op_count) > 1)
7045 smb_break_all_oplock(work, fp);
7047 rsp->StructureSize = cpu_to_le16(4);
7048 ksmbd_debug(SMB, "successful in taking lock\n");
7049 rsp->hdr.Status = STATUS_SUCCESS;
7051 inc_rfc1001_len(work->response_buf, 4);
7052 ksmbd_fd_put(work, fp);
7056 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7057 locks_free_lock(smb_lock->fl);
7058 list_del(&smb_lock->llist);
7062 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7063 struct file_lock *rlock = NULL;
7065 rlock = smb_flock_init(filp);
7066 rlock->fl_type = F_UNLCK;
7067 rlock->fl_start = smb_lock->start;
7068 rlock->fl_end = smb_lock->end;
7070 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7072 pr_err("rollback unlock fail : %d\n", rc);
7074 list_del(&smb_lock->llist);
7075 spin_lock(&work->conn->llist_lock);
7076 if (!list_empty(&smb_lock->flist))
7077 list_del(&smb_lock->flist);
7078 list_del(&smb_lock->clist);
7079 spin_unlock(&work->conn->llist_lock);
7081 locks_free_lock(smb_lock->fl);
7082 locks_free_lock(rlock);
7086 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7088 if (!rsp->hdr.Status) {
7090 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7091 else if (err == -ENOMEM)
7092 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7093 else if (err == -ENOENT)
7094 rsp->hdr.Status = STATUS_FILE_CLOSED;
7096 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7099 smb2_set_err_rsp(work);
7100 ksmbd_fd_put(work, fp);
7104 static int fsctl_copychunk(struct ksmbd_work *work,
7105 struct copychunk_ioctl_req *ci_req,
7106 unsigned int cnt_code,
7107 unsigned int input_count,
7108 unsigned long long volatile_id,
7109 unsigned long long persistent_id,
7110 struct smb2_ioctl_rsp *rsp)
7112 struct copychunk_ioctl_rsp *ci_rsp;
7113 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7114 struct srv_copychunk *chunks;
7115 unsigned int i, chunk_count, chunk_count_written = 0;
7116 unsigned int chunk_size_written = 0;
7117 loff_t total_size_written = 0;
7120 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7122 rsp->VolatileFileId = volatile_id;
7123 rsp->PersistentFileId = persistent_id;
7124 ci_rsp->ChunksWritten =
7125 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7126 ci_rsp->ChunkBytesWritten =
7127 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7128 ci_rsp->TotalBytesWritten =
7129 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7131 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7132 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7133 if (chunk_count == 0)
7135 total_size_written = 0;
7137 /* verify the SRV_COPYCHUNK_COPY packet */
7138 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7139 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7140 chunk_count * sizeof(struct srv_copychunk)) {
7141 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7145 for (i = 0; i < chunk_count; i++) {
7146 if (le32_to_cpu(chunks[i].Length) == 0 ||
7147 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7149 total_size_written += le32_to_cpu(chunks[i].Length);
7152 if (i < chunk_count ||
7153 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7154 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7158 src_fp = ksmbd_lookup_foreign_fd(work,
7159 le64_to_cpu(ci_req->ResumeKey[0]));
7160 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7163 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7164 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7169 rsp->hdr.Status = STATUS_FILE_CLOSED;
7174 * FILE_READ_DATA should only be included in
7175 * the FSCTL_COPYCHUNK case
7177 if (cnt_code == FSCTL_COPYCHUNK &&
7178 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7179 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7183 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7184 chunks, chunk_count,
7185 &chunk_count_written,
7186 &chunk_size_written,
7187 &total_size_written);
7190 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7192 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7193 else if (ret == -EBADF)
7194 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7195 else if (ret == -EFBIG || ret == -ENOSPC)
7196 rsp->hdr.Status = STATUS_DISK_FULL;
7197 else if (ret == -EINVAL)
7198 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7199 else if (ret == -EISDIR)
7200 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7201 else if (ret == -E2BIG)
7202 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7204 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7207 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7208 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7209 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7211 ksmbd_fd_put(work, src_fp);
7212 ksmbd_fd_put(work, dst_fp);
7216 static __be32 idev_ipv4_address(struct in_device *idev)
7220 struct in_ifaddr *ifa;
7223 in_dev_for_each_ifa_rcu(ifa, idev) {
7224 if (ifa->ifa_flags & IFA_F_SECONDARY)
7227 addr = ifa->ifa_address;
7234 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7235 struct smb2_ioctl_rsp *rsp,
7236 unsigned int out_buf_len)
7238 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7240 struct net_device *netdev;
7241 struct sockaddr_storage_rsp *sockaddr_storage;
7243 unsigned long long speed;
7246 for_each_netdev(&init_net, netdev) {
7247 bool ipv4_set = false;
7249 if (netdev->type == ARPHRD_LOOPBACK)
7252 flags = dev_get_flags(netdev);
7253 if (!(flags & IFF_RUNNING))
7257 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7262 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7263 &rsp->Buffer[nbytes];
7264 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7266 nii_rsp->Capability = 0;
7267 if (netdev->real_num_tx_queues > 1)
7268 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7269 if (ksmbd_rdma_capable_netdev(netdev))
7270 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7272 nii_rsp->Next = cpu_to_le32(152);
7273 nii_rsp->Reserved = 0;
7275 if (netdev->ethtool_ops->get_link_ksettings) {
7276 struct ethtool_link_ksettings cmd;
7278 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7279 speed = cmd.base.speed;
7281 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7282 "speed is unknown, defaulting to 1Gb/sec");
7287 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7289 sockaddr_storage = (struct sockaddr_storage_rsp *)
7290 nii_rsp->SockAddr_Storage;
7291 memset(sockaddr_storage, 0, 128);
7294 struct in_device *idev;
7296 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7297 sockaddr_storage->addr4.Port = 0;
7299 idev = __in_dev_get_rtnl(netdev);
7302 sockaddr_storage->addr4.IPv4address =
7303 idev_ipv4_address(idev);
7304 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7308 struct inet6_dev *idev6;
7309 struct inet6_ifaddr *ifa;
7310 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7312 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7313 sockaddr_storage->addr6.Port = 0;
7314 sockaddr_storage->addr6.FlowInfo = 0;
7316 idev6 = __in6_dev_get(netdev);
7320 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7321 if (ifa->flags & (IFA_F_TENTATIVE |
7324 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7327 sockaddr_storage->addr6.ScopeId = 0;
7328 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7333 /* zero if this is last one */
7337 rsp->PersistentFileId = SMB2_NO_FID;
7338 rsp->VolatileFileId = SMB2_NO_FID;
7342 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7343 struct validate_negotiate_info_req *neg_req,
7344 struct validate_negotiate_info_rsp *neg_rsp,
7345 unsigned int in_buf_len)
7350 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7351 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7354 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7355 neg_req->DialectCount);
7356 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7361 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7366 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7371 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7376 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7377 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7378 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7379 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7384 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7385 struct file_allocated_range_buffer *qar_req,
7386 struct file_allocated_range_buffer *qar_rsp,
7387 unsigned int in_count, unsigned int *out_count)
7389 struct ksmbd_file *fp;
7390 loff_t start, length;
7397 start = le64_to_cpu(qar_req->file_offset);
7398 length = le64_to_cpu(qar_req->length);
7400 if (start < 0 || length < 0)
7403 fp = ksmbd_lookup_fd_fast(work, id);
7407 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7408 qar_rsp, in_count, out_count);
7409 if (ret && ret != -E2BIG)
7412 ksmbd_fd_put(work, fp);
7416 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7417 unsigned int out_buf_len,
7418 struct smb2_ioctl_req *req,
7419 struct smb2_ioctl_rsp *rsp)
7421 struct ksmbd_rpc_command *rpc_resp;
7422 char *data_buf = (char *)&req->Buffer[0];
7425 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7426 le32_to_cpu(req->InputCount));
7428 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7430 * set STATUS_SOME_NOT_MAPPED response
7431 * for unknown domain sid.
7433 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7434 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7435 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7437 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7438 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7442 nbytes = rpc_resp->payload_sz;
7443 if (rpc_resp->payload_sz > out_buf_len) {
7444 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7445 nbytes = out_buf_len;
7448 if (!rpc_resp->payload_sz) {
7450 STATUS_UNEXPECTED_IO_ERROR;
7454 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7461 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7462 struct file_sparse *sparse)
7464 struct ksmbd_file *fp;
7465 struct mnt_idmap *idmap;
7469 fp = ksmbd_lookup_fd_fast(work, id);
7472 idmap = file_mnt_idmap(fp->filp);
7474 old_fattr = fp->f_ci->m_fattr;
7475 if (sparse->SetSparse)
7476 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7478 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7480 if (fp->f_ci->m_fattr != old_fattr &&
7481 test_share_config_flag(work->tcon->share_conf,
7482 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7483 struct xattr_dos_attrib da;
7485 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7486 fp->filp->f_path.dentry, &da);
7490 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7491 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7492 fp->filp->f_path.dentry, &da);
7494 fp->f_ci->m_fattr = old_fattr;
7498 ksmbd_fd_put(work, fp);
7502 static int fsctl_request_resume_key(struct ksmbd_work *work,
7503 struct smb2_ioctl_req *req,
7504 struct resume_key_ioctl_rsp *key_rsp)
7506 struct ksmbd_file *fp;
7508 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7512 memset(key_rsp, 0, sizeof(*key_rsp));
7513 key_rsp->ResumeKey[0] = req->VolatileFileId;
7514 key_rsp->ResumeKey[1] = req->PersistentFileId;
7515 ksmbd_fd_put(work, fp);
7521 * smb2_ioctl() - handler for smb2 ioctl command
7522 * @work: smb work containing ioctl command buffer
7524 * Return: 0 on success, otherwise error
7526 int smb2_ioctl(struct ksmbd_work *work)
7528 struct smb2_ioctl_req *req;
7529 struct smb2_ioctl_rsp *rsp;
7530 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7531 u64 id = KSMBD_NO_FID;
7532 struct ksmbd_conn *conn = work->conn;
7535 if (work->next_smb2_rcv_hdr_off) {
7536 req = ksmbd_req_buf_next(work);
7537 rsp = ksmbd_resp_buf_next(work);
7538 if (!has_file_id(req->VolatileFileId)) {
7539 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7540 work->compound_fid);
7541 id = work->compound_fid;
7544 req = smb2_get_msg(work->request_buf);
7545 rsp = smb2_get_msg(work->response_buf);
7548 if (!has_file_id(id))
7549 id = req->VolatileFileId;
7551 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7552 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7556 cnt_code = le32_to_cpu(req->CtlCode);
7557 ret = smb2_calc_max_out_buf_len(work, 48,
7558 le32_to_cpu(req->MaxOutputResponse));
7560 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7563 out_buf_len = (unsigned int)ret;
7564 in_buf_len = le32_to_cpu(req->InputCount);
7567 case FSCTL_DFS_GET_REFERRALS:
7568 case FSCTL_DFS_GET_REFERRALS_EX:
7569 /* Not support DFS yet */
7570 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7572 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7574 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7576 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7577 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7581 * TODO: This is dummy implementation to pass smbtorture
7582 * Need to check correct response later
7584 memset(obj_buf->ObjectId, 0x0, 16);
7585 memset(obj_buf->BirthVolumeId, 0x0, 16);
7586 memset(obj_buf->BirthObjectId, 0x0, 16);
7587 memset(obj_buf->DomainId, 0x0, 16);
7591 case FSCTL_PIPE_TRANSCEIVE:
7592 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7593 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7595 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7596 if (conn->dialect < SMB30_PROT_ID) {
7601 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7607 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7612 ret = fsctl_validate_negotiate_info(conn,
7613 (struct validate_negotiate_info_req *)&req->Buffer[0],
7614 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7619 nbytes = sizeof(struct validate_negotiate_info_rsp);
7620 rsp->PersistentFileId = SMB2_NO_FID;
7621 rsp->VolatileFileId = SMB2_NO_FID;
7623 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7624 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7629 case FSCTL_REQUEST_RESUME_KEY:
7630 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7635 ret = fsctl_request_resume_key(work, req,
7636 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7639 rsp->PersistentFileId = req->PersistentFileId;
7640 rsp->VolatileFileId = req->VolatileFileId;
7641 nbytes = sizeof(struct resume_key_ioctl_rsp);
7643 case FSCTL_COPYCHUNK:
7644 case FSCTL_COPYCHUNK_WRITE:
7645 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7647 "User does not have write permission\n");
7652 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7657 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7662 nbytes = sizeof(struct copychunk_ioctl_rsp);
7663 rsp->VolatileFileId = req->VolatileFileId;
7664 rsp->PersistentFileId = req->PersistentFileId;
7665 fsctl_copychunk(work,
7666 (struct copychunk_ioctl_req *)&req->Buffer[0],
7667 le32_to_cpu(req->CtlCode),
7668 le32_to_cpu(req->InputCount),
7669 req->VolatileFileId,
7670 req->PersistentFileId,
7673 case FSCTL_SET_SPARSE:
7674 if (in_buf_len < sizeof(struct file_sparse)) {
7679 ret = fsctl_set_sparse(work, id,
7680 (struct file_sparse *)&req->Buffer[0]);
7684 case FSCTL_SET_ZERO_DATA:
7686 struct file_zero_data_information *zero_data;
7687 struct ksmbd_file *fp;
7688 loff_t off, len, bfz;
7690 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7692 "User does not have write permission\n");
7697 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7703 (struct file_zero_data_information *)&req->Buffer[0];
7705 off = le64_to_cpu(zero_data->FileOffset);
7706 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7707 if (off < 0 || bfz < 0 || off > bfz) {
7714 fp = ksmbd_lookup_fd_fast(work, id);
7720 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7721 ksmbd_fd_put(work, fp);
7727 case FSCTL_QUERY_ALLOCATED_RANGES:
7728 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7733 ret = fsctl_query_allocated_ranges(work, id,
7734 (struct file_allocated_range_buffer *)&req->Buffer[0],
7735 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7737 sizeof(struct file_allocated_range_buffer), &nbytes);
7738 if (ret == -E2BIG) {
7739 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7740 } else if (ret < 0) {
7745 nbytes *= sizeof(struct file_allocated_range_buffer);
7747 case FSCTL_GET_REPARSE_POINT:
7749 struct reparse_data_buffer *reparse_ptr;
7750 struct ksmbd_file *fp;
7752 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7753 fp = ksmbd_lookup_fd_fast(work, id);
7755 pr_err("not found fp!!\n");
7760 reparse_ptr->ReparseTag =
7761 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7762 reparse_ptr->ReparseDataLength = 0;
7763 ksmbd_fd_put(work, fp);
7764 nbytes = sizeof(struct reparse_data_buffer);
7767 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7769 struct ksmbd_file *fp_in, *fp_out = NULL;
7770 struct duplicate_extents_to_file *dup_ext;
7771 loff_t src_off, dst_off, length, cloned;
7773 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7778 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7780 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7781 dup_ext->PersistentFileHandle);
7783 pr_err("not found file handle in duplicate extent to file\n");
7788 fp_out = ksmbd_lookup_fd_fast(work, id);
7790 pr_err("not found fp\n");
7795 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7796 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7797 length = le64_to_cpu(dup_ext->ByteCount);
7799 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7800 * should fall back to vfs_copy_file_range(). This could be
7801 * beneficial when re-exporting nfs/smb mount, but note that
7802 * this can result in partial copy that returns an error status.
7803 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7804 * fall back to vfs_copy_file_range(), should be avoided when
7805 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7807 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7808 fp_out->filp, dst_off, length, 0);
7809 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7812 } else if (cloned != length) {
7813 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7814 fp_out->filp, dst_off,
7816 if (cloned != length) {
7825 ksmbd_fd_put(work, fp_in);
7826 ksmbd_fd_put(work, fp_out);
7832 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7838 rsp->CtlCode = cpu_to_le32(cnt_code);
7839 rsp->InputCount = cpu_to_le32(0);
7840 rsp->InputOffset = cpu_to_le32(112);
7841 rsp->OutputOffset = cpu_to_le32(112);
7842 rsp->OutputCount = cpu_to_le32(nbytes);
7843 rsp->StructureSize = cpu_to_le16(49);
7844 rsp->Reserved = cpu_to_le16(0);
7845 rsp->Flags = cpu_to_le32(0);
7846 rsp->Reserved2 = cpu_to_le32(0);
7847 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7853 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7854 else if (ret == -ENOENT)
7855 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7856 else if (ret == -EOPNOTSUPP)
7857 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7858 else if (ret == -ENOSPC)
7859 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7860 else if (ret < 0 || rsp->hdr.Status == 0)
7861 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7862 smb2_set_err_rsp(work);
7867 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7868 * @work: smb work containing oplock break command buffer
7872 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7874 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7875 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7876 struct ksmbd_file *fp;
7877 struct oplock_info *opinfo = NULL;
7880 u64 volatile_id, persistent_id;
7881 char req_oplevel = 0, rsp_oplevel = 0;
7882 unsigned int oplock_change_type;
7884 volatile_id = req->VolatileFid;
7885 persistent_id = req->PersistentFid;
7886 req_oplevel = req->OplockLevel;
7887 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7888 volatile_id, persistent_id, req_oplevel);
7890 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7892 rsp->hdr.Status = STATUS_FILE_CLOSED;
7893 smb2_set_err_rsp(work);
7897 opinfo = opinfo_get(fp);
7899 pr_err("unexpected null oplock_info\n");
7900 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7901 smb2_set_err_rsp(work);
7902 ksmbd_fd_put(work, fp);
7906 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7907 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7911 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7912 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7913 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7917 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7918 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7919 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7920 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7921 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7922 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7923 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7924 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7925 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7926 oplock_change_type = OPLOCK_READ_TO_NONE;
7927 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7928 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7929 err = STATUS_INVALID_DEVICE_STATE;
7930 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7931 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7932 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7933 oplock_change_type = OPLOCK_WRITE_TO_READ;
7934 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7935 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7936 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7937 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7938 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7939 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7940 oplock_change_type = OPLOCK_READ_TO_NONE;
7942 oplock_change_type = 0;
7945 oplock_change_type = 0;
7948 switch (oplock_change_type) {
7949 case OPLOCK_WRITE_TO_READ:
7950 ret = opinfo_write_to_read(opinfo);
7951 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7953 case OPLOCK_WRITE_TO_NONE:
7954 ret = opinfo_write_to_none(opinfo);
7955 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7957 case OPLOCK_READ_TO_NONE:
7958 ret = opinfo_read_to_none(opinfo);
7959 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7962 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7963 opinfo->level, rsp_oplevel);
7967 rsp->hdr.Status = err;
7972 ksmbd_fd_put(work, fp);
7973 opinfo->op_state = OPLOCK_STATE_NONE;
7974 wake_up_interruptible_all(&opinfo->oplock_q);
7976 rsp->StructureSize = cpu_to_le16(24);
7977 rsp->OplockLevel = rsp_oplevel;
7980 rsp->VolatileFid = volatile_id;
7981 rsp->PersistentFid = persistent_id;
7982 inc_rfc1001_len(work->response_buf, 24);
7986 opinfo->op_state = OPLOCK_STATE_NONE;
7987 wake_up_interruptible_all(&opinfo->oplock_q);
7990 ksmbd_fd_put(work, fp);
7991 smb2_set_err_rsp(work);
7994 static int check_lease_state(struct lease *lease, __le32 req_state)
7996 if ((lease->new_state ==
7997 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
7998 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
7999 lease->new_state = req_state;
8003 if (lease->new_state == req_state)
8010 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8011 * @work: smb work containing lease break command buffer
8015 static void smb21_lease_break_ack(struct ksmbd_work *work)
8017 struct ksmbd_conn *conn = work->conn;
8018 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8019 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8020 struct oplock_info *opinfo;
8023 unsigned int lease_change_type;
8025 struct lease *lease;
8027 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8028 le32_to_cpu(req->LeaseState));
8029 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8031 ksmbd_debug(OPLOCK, "file not opened\n");
8032 smb2_set_err_rsp(work);
8033 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8036 lease = opinfo->o_lease;
8038 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8039 pr_err("unexpected lease break state 0x%x\n",
8041 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8045 if (check_lease_state(lease, req->LeaseState)) {
8046 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8048 "req lease state: 0x%x, expected state: 0x%x\n",
8049 req->LeaseState, lease->new_state);
8053 if (!atomic_read(&opinfo->breaking_cnt)) {
8054 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8058 /* check for bad lease state */
8059 if (req->LeaseState &
8060 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8061 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8062 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8063 lease_change_type = OPLOCK_WRITE_TO_NONE;
8065 lease_change_type = OPLOCK_READ_TO_NONE;
8066 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8067 le32_to_cpu(lease->state),
8068 le32_to_cpu(req->LeaseState));
8069 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8070 req->LeaseState != SMB2_LEASE_NONE_LE) {
8071 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8072 lease_change_type = OPLOCK_READ_TO_NONE;
8073 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8074 le32_to_cpu(lease->state),
8075 le32_to_cpu(req->LeaseState));
8077 /* valid lease state changes */
8078 err = STATUS_INVALID_DEVICE_STATE;
8079 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8080 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8081 lease_change_type = OPLOCK_WRITE_TO_NONE;
8083 lease_change_type = OPLOCK_READ_TO_NONE;
8084 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8085 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8086 lease_change_type = OPLOCK_WRITE_TO_READ;
8088 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8090 lease_change_type = 0;
8094 switch (lease_change_type) {
8095 case OPLOCK_WRITE_TO_READ:
8096 ret = opinfo_write_to_read(opinfo);
8098 case OPLOCK_READ_HANDLE_TO_READ:
8099 ret = opinfo_read_handle_to_read(opinfo);
8101 case OPLOCK_WRITE_TO_NONE:
8102 ret = opinfo_write_to_none(opinfo);
8104 case OPLOCK_READ_TO_NONE:
8105 ret = opinfo_read_to_none(opinfo);
8108 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8109 le32_to_cpu(lease->state),
8110 le32_to_cpu(req->LeaseState));
8113 lease_state = lease->state;
8114 opinfo->op_state = OPLOCK_STATE_NONE;
8115 wake_up_interruptible_all(&opinfo->oplock_q);
8116 atomic_dec(&opinfo->breaking_cnt);
8117 wake_up_interruptible_all(&opinfo->oplock_brk);
8121 rsp->hdr.Status = err;
8125 rsp->StructureSize = cpu_to_le16(36);
8128 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8129 rsp->LeaseState = lease_state;
8130 rsp->LeaseDuration = 0;
8131 inc_rfc1001_len(work->response_buf, 36);
8135 opinfo->op_state = OPLOCK_STATE_NONE;
8136 wake_up_interruptible_all(&opinfo->oplock_q);
8137 atomic_dec(&opinfo->breaking_cnt);
8138 wake_up_interruptible_all(&opinfo->oplock_brk);
8141 smb2_set_err_rsp(work);
8145 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8146 * @work: smb work containing oplock/lease break command buffer
8150 int smb2_oplock_break(struct ksmbd_work *work)
8152 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8153 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8155 switch (le16_to_cpu(req->StructureSize)) {
8156 case OP_BREAK_STRUCT_SIZE_20:
8157 smb20_oplock_break_ack(work);
8159 case OP_BREAK_STRUCT_SIZE_21:
8160 smb21_lease_break_ack(work);
8163 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8164 le16_to_cpu(req->StructureSize));
8165 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8166 smb2_set_err_rsp(work);
8173 * smb2_notify() - handler for smb2 notify request
8174 * @work: smb work containing notify command buffer
8178 int smb2_notify(struct ksmbd_work *work)
8180 struct smb2_change_notify_req *req;
8181 struct smb2_change_notify_rsp *rsp;
8183 WORK_BUFFERS(work, req, rsp);
8185 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8186 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8187 smb2_set_err_rsp(work);
8191 smb2_set_err_rsp(work);
8192 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8197 * smb2_is_sign_req() - handler for checking packet signing status
8198 * @work: smb work containing notify command buffer
8199 * @command: SMB2 command id
8201 * Return: true if packed is signed, false otherwise
8203 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8205 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8207 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8208 command != SMB2_NEGOTIATE_HE &&
8209 command != SMB2_SESSION_SETUP_HE &&
8210 command != SMB2_OPLOCK_BREAK_HE)
8217 * smb2_check_sign_req() - handler for req packet sign processing
8218 * @work: smb work containing notify command buffer
8220 * Return: 1 on success, 0 otherwise
8222 int smb2_check_sign_req(struct ksmbd_work *work)
8224 struct smb2_hdr *hdr;
8225 char signature_req[SMB2_SIGNATURE_SIZE];
8226 char signature[SMB2_HMACSHA256_SIZE];
8230 hdr = smb2_get_msg(work->request_buf);
8231 if (work->next_smb2_rcv_hdr_off)
8232 hdr = ksmbd_req_buf_next(work);
8234 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8235 len = get_rfc1002_len(work->request_buf);
8236 else if (hdr->NextCommand)
8237 len = le32_to_cpu(hdr->NextCommand);
8239 len = get_rfc1002_len(work->request_buf) -
8240 work->next_smb2_rcv_hdr_off;
8242 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8243 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8245 iov[0].iov_base = (char *)&hdr->ProtocolId;
8246 iov[0].iov_len = len;
8248 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8252 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8253 pr_err("bad smb2 signature\n");
8261 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8262 * @work: smb work containing notify command buffer
8265 void smb2_set_sign_rsp(struct ksmbd_work *work)
8267 struct smb2_hdr *hdr;
8268 struct smb2_hdr *req_hdr;
8269 char signature[SMB2_HMACSHA256_SIZE];
8274 hdr = smb2_get_msg(work->response_buf);
8275 if (work->next_smb2_rsp_hdr_off)
8276 hdr = ksmbd_resp_buf_next(work);
8278 req_hdr = ksmbd_req_buf_next(work);
8280 if (!work->next_smb2_rsp_hdr_off) {
8281 len = get_rfc1002_len(work->response_buf);
8282 if (req_hdr->NextCommand)
8283 len = ALIGN(len, 8);
8285 len = get_rfc1002_len(work->response_buf) -
8286 work->next_smb2_rsp_hdr_off;
8287 len = ALIGN(len, 8);
8290 if (req_hdr->NextCommand)
8291 hdr->NextCommand = cpu_to_le32(len);
8293 hdr->Flags |= SMB2_FLAGS_SIGNED;
8294 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8296 iov[0].iov_base = (char *)&hdr->ProtocolId;
8297 iov[0].iov_len = len;
8299 if (work->aux_payload_sz) {
8300 iov[0].iov_len -= work->aux_payload_sz;
8302 iov[1].iov_base = work->aux_payload_buf;
8303 iov[1].iov_len = work->aux_payload_sz;
8307 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8309 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8313 * smb3_check_sign_req() - handler for req packet sign processing
8314 * @work: smb work containing notify command buffer
8316 * Return: 1 on success, 0 otherwise
8318 int smb3_check_sign_req(struct ksmbd_work *work)
8320 struct ksmbd_conn *conn = work->conn;
8322 struct smb2_hdr *hdr;
8323 struct channel *chann;
8324 char signature_req[SMB2_SIGNATURE_SIZE];
8325 char signature[SMB2_CMACAES_SIZE];
8329 hdr = smb2_get_msg(work->request_buf);
8330 if (work->next_smb2_rcv_hdr_off)
8331 hdr = ksmbd_req_buf_next(work);
8333 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8334 len = get_rfc1002_len(work->request_buf);
8335 else if (hdr->NextCommand)
8336 len = le32_to_cpu(hdr->NextCommand);
8338 len = get_rfc1002_len(work->request_buf) -
8339 work->next_smb2_rcv_hdr_off;
8341 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8342 signing_key = work->sess->smb3signingkey;
8344 chann = lookup_chann_list(work->sess, conn);
8348 signing_key = chann->smb3signingkey;
8352 pr_err("SMB3 signing key is not generated\n");
8356 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8357 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8358 iov[0].iov_base = (char *)&hdr->ProtocolId;
8359 iov[0].iov_len = len;
8361 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8364 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8365 pr_err("bad smb2 signature\n");
8373 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8374 * @work: smb work containing notify command buffer
8377 void smb3_set_sign_rsp(struct ksmbd_work *work)
8379 struct ksmbd_conn *conn = work->conn;
8380 struct smb2_hdr *req_hdr, *hdr;
8381 struct channel *chann;
8382 char signature[SMB2_CMACAES_SIZE];
8388 hdr = smb2_get_msg(work->response_buf);
8389 if (work->next_smb2_rsp_hdr_off)
8390 hdr = ksmbd_resp_buf_next(work);
8392 req_hdr = ksmbd_req_buf_next(work);
8394 if (!work->next_smb2_rsp_hdr_off) {
8395 len = get_rfc1002_len(work->response_buf);
8396 if (req_hdr->NextCommand)
8397 len = ALIGN(len, 8);
8399 len = get_rfc1002_len(work->response_buf) -
8400 work->next_smb2_rsp_hdr_off;
8401 len = ALIGN(len, 8);
8404 if (conn->binding == false &&
8405 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8406 signing_key = work->sess->smb3signingkey;
8408 chann = lookup_chann_list(work->sess, work->conn);
8412 signing_key = chann->smb3signingkey;
8418 if (req_hdr->NextCommand)
8419 hdr->NextCommand = cpu_to_le32(len);
8421 hdr->Flags |= SMB2_FLAGS_SIGNED;
8422 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8423 iov[0].iov_base = (char *)&hdr->ProtocolId;
8424 iov[0].iov_len = len;
8425 if (work->aux_payload_sz) {
8426 iov[0].iov_len -= work->aux_payload_sz;
8427 iov[1].iov_base = work->aux_payload_buf;
8428 iov[1].iov_len = work->aux_payload_sz;
8432 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8433 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8437 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8438 * @work: smb work containing response buffer
8441 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8443 struct ksmbd_conn *conn = work->conn;
8444 struct ksmbd_session *sess = work->sess;
8445 struct smb2_hdr *req, *rsp;
8447 if (conn->dialect != SMB311_PROT_ID)
8450 WORK_BUFFERS(work, req, rsp);
8452 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8454 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8455 conn->preauth_info->Preauth_HashValue);
8457 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8460 if (conn->binding) {
8461 struct preauth_session *preauth_sess;
8463 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8466 hash_value = preauth_sess->Preauth_HashValue;
8468 hash_value = sess->Preauth_HashValue;
8472 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8477 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8479 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8480 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8481 unsigned int orig_len = get_rfc1002_len(old_buf);
8483 /* tr_buf must be cleared by the caller */
8484 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8485 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8486 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8487 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8488 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8489 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8491 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8492 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8493 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8494 inc_rfc1001_len(tr_buf, orig_len);
8497 int smb3_encrypt_resp(struct ksmbd_work *work)
8499 char *buf = work->response_buf;
8502 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8504 if (ARRAY_SIZE(iov) < rq_nvec)
8507 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8511 /* fill transform header */
8512 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8514 iov[0].iov_base = work->tr_buf;
8515 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8516 buf_size += iov[0].iov_len - 4;
8518 iov[1].iov_base = buf + 4;
8519 iov[1].iov_len = get_rfc1002_len(buf);
8520 if (work->aux_payload_sz) {
8521 iov[1].iov_len = work->resp_hdr_sz - 4;
8523 iov[2].iov_base = work->aux_payload_buf;
8524 iov[2].iov_len = work->aux_payload_sz;
8525 buf_size += iov[2].iov_len;
8527 buf_size += iov[1].iov_len;
8528 work->resp_hdr_sz = iov[1].iov_len;
8530 rc = ksmbd_crypt_message(work, iov, rq_nvec, 1);
8534 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8535 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8540 bool smb3_is_transform_hdr(void *buf)
8542 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8544 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8547 int smb3_decrypt_req(struct ksmbd_work *work)
8549 struct ksmbd_session *sess;
8550 char *buf = work->request_buf;
8551 unsigned int pdu_length = get_rfc1002_len(buf);
8553 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8554 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8557 if (buf_data_size < sizeof(struct smb2_hdr)) {
8558 pr_err("Transform message is too small (%u)\n",
8560 return -ECONNABORTED;
8563 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8564 pr_err("Transform message is broken\n");
8565 return -ECONNABORTED;
8568 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8570 pr_err("invalid session id(%llx) in transform header\n",
8571 le64_to_cpu(tr_hdr->SessionId));
8572 return -ECONNABORTED;
8575 iov[0].iov_base = buf;
8576 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8577 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8578 iov[1].iov_len = buf_data_size;
8579 rc = ksmbd_crypt_message(work, iov, 2, 0);
8583 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8584 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8589 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8591 struct ksmbd_conn *conn = work->conn;
8592 struct ksmbd_session *sess = work->sess;
8593 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8595 if (conn->dialect < SMB30_PROT_ID)
8598 if (work->next_smb2_rcv_hdr_off)
8599 rsp = ksmbd_resp_buf_next(work);
8601 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8602 sess->user && !user_guest(sess->user) &&
8603 rsp->Status == STATUS_SUCCESS)