1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
23 #include "connection.h"
24 #include "transport_ipc.h"
25 #include "transport_rdma.h"
27 #include "vfs_cache.h"
31 #include "smb_common.h"
32 #include "smbstatus.h"
33 #include "ksmbd_work.h"
34 #include "mgmt/user_config.h"
35 #include "mgmt/share_config.h"
36 #include "mgmt/tree_connect.h"
37 #include "mgmt/user_session.h"
38 #include "mgmt/ksmbd_ida.h"
41 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
43 if (work->next_smb2_rcv_hdr_off) {
44 *req = ksmbd_req_buf_next(work);
45 *rsp = ksmbd_resp_buf_next(work);
47 *req = smb2_get_msg(work->request_buf);
48 *rsp = smb2_get_msg(work->response_buf);
52 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
55 * check_session_id() - check for valid session id in smb header
56 * @conn: connection instance
57 * @id: session id from smb header
59 * Return: 1 if valid session id, otherwise 0
61 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
63 struct ksmbd_session *sess;
65 if (id == 0 || id == -1)
68 sess = ksmbd_session_lookup_all(conn, id);
71 pr_err("Invalid user session id: %llu\n", id);
75 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
77 return xa_load(&sess->ksmbd_chann_list, (long)conn);
81 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
84 * Return: 0 if there is a tree connection matched or these are
85 * skipable commands, otherwise error
87 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
89 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
90 unsigned int cmd = le16_to_cpu(req_hdr->Command);
93 if (cmd == SMB2_TREE_CONNECT_HE ||
94 cmd == SMB2_CANCEL_HE ||
95 cmd == SMB2_LOGOFF_HE) {
96 ksmbd_debug(SMB, "skip to check tree connect request\n");
100 if (xa_empty(&work->sess->tree_conns)) {
101 ksmbd_debug(SMB, "NO tree connected\n");
105 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
108 * If request is not the first in Compound request,
109 * Just validate tree id in header with work->tcon->id.
111 if (work->next_smb2_rcv_hdr_off) {
113 pr_err("The first operation in the compound does not have tcon\n");
116 if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
117 pr_err("tree id(%u) is different with id(%u) in first operation\n",
118 tree_id, work->tcon->id);
124 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
126 pr_err("Invalid tid %d\n", tree_id);
134 * smb2_set_err_rsp() - set error response code on smb response
135 * @work: smb work containing response buffer
137 void smb2_set_err_rsp(struct ksmbd_work *work)
139 struct smb2_err_rsp *err_rsp;
141 if (work->next_smb2_rcv_hdr_off)
142 err_rsp = ksmbd_resp_buf_next(work);
144 err_rsp = smb2_get_msg(work->response_buf);
146 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
149 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
150 err_rsp->ErrorContextCount = 0;
151 err_rsp->Reserved = 0;
152 err_rsp->ByteCount = 0;
153 err_rsp->ErrorData[0] = 0;
154 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
155 __SMB2_HEADER_STRUCTURE_SIZE +
156 SMB2_ERROR_STRUCTURE_SIZE2);
158 work->send_no_response = 1;
163 * is_smb2_neg_cmd() - is it smb2 negotiation command
164 * @work: smb work containing smb header
166 * Return: true if smb2 negotiation command, otherwise false
168 bool is_smb2_neg_cmd(struct ksmbd_work *work)
170 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
172 /* is it SMB2 header ? */
173 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
176 /* make sure it is request not response message */
177 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
180 if (hdr->Command != SMB2_NEGOTIATE)
187 * is_smb2_rsp() - is it smb2 response
188 * @work: smb work containing smb response buffer
190 * Return: true if smb2 response, otherwise false
192 bool is_smb2_rsp(struct ksmbd_work *work)
194 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
196 /* is it SMB2 header ? */
197 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
200 /* make sure it is response not request message */
201 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
208 * get_smb2_cmd_val() - get smb command code from smb header
209 * @work: smb work containing smb request buffer
211 * Return: smb2 request command value
213 u16 get_smb2_cmd_val(struct ksmbd_work *work)
215 struct smb2_hdr *rcv_hdr;
217 if (work->next_smb2_rcv_hdr_off)
218 rcv_hdr = ksmbd_req_buf_next(work);
220 rcv_hdr = smb2_get_msg(work->request_buf);
221 return le16_to_cpu(rcv_hdr->Command);
225 * set_smb2_rsp_status() - set error response code on smb2 header
226 * @work: smb work containing response buffer
227 * @err: error response code
229 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
231 struct smb2_hdr *rsp_hdr;
233 rsp_hdr = smb2_get_msg(work->response_buf);
234 rsp_hdr->Status = err;
238 work->next_smb2_rcv_hdr_off = 0;
239 smb2_set_err_rsp(work);
243 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
244 * @work: smb work containing smb request buffer
246 * smb2 negotiate response is sent in reply of smb1 negotiate command for
247 * dialect auto-negotiation.
249 int init_smb2_neg_rsp(struct ksmbd_work *work)
251 struct smb2_hdr *rsp_hdr;
252 struct smb2_negotiate_rsp *rsp;
253 struct ksmbd_conn *conn = work->conn;
256 rsp_hdr = smb2_get_msg(work->response_buf);
257 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
258 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
259 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
260 rsp_hdr->CreditRequest = cpu_to_le16(2);
261 rsp_hdr->Command = SMB2_NEGOTIATE;
262 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
263 rsp_hdr->NextCommand = 0;
264 rsp_hdr->MessageId = 0;
265 rsp_hdr->Id.SyncId.ProcessId = 0;
266 rsp_hdr->Id.SyncId.TreeId = 0;
267 rsp_hdr->SessionId = 0;
268 memset(rsp_hdr->Signature, 0, 16);
270 rsp = smb2_get_msg(work->response_buf);
272 WARN_ON(ksmbd_conn_good(conn));
274 rsp->StructureSize = cpu_to_le16(65);
275 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
276 rsp->DialectRevision = cpu_to_le16(conn->dialect);
277 /* Not setting conn guid rsp->ServerGUID, as it
278 * not used by client for identifying connection
280 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
281 /* Default Max Message Size till SMB2.0, 64K*/
282 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
283 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
284 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
286 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
287 rsp->ServerStartTime = 0;
289 rsp->SecurityBufferOffset = cpu_to_le16(128);
290 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
291 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
292 le16_to_cpu(rsp->SecurityBufferOffset));
293 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
294 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
295 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
296 err = ksmbd_iov_pin_rsp(work, rsp,
297 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
300 conn->use_spnego = true;
302 ksmbd_conn_set_need_negotiate(conn);
307 * smb2_set_rsp_credits() - set number of credits in response buffer
308 * @work: smb work containing smb response buffer
310 int smb2_set_rsp_credits(struct ksmbd_work *work)
312 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
313 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
314 struct ksmbd_conn *conn = work->conn;
315 unsigned short credits_requested, aux_max;
316 unsigned short credit_charge, credits_granted = 0;
318 if (work->send_no_response)
321 hdr->CreditCharge = req_hdr->CreditCharge;
323 if (conn->total_credits > conn->vals->max_credits) {
324 hdr->CreditRequest = 0;
325 pr_err("Total credits overflow: %d\n", conn->total_credits);
329 credit_charge = max_t(unsigned short,
330 le16_to_cpu(req_hdr->CreditCharge), 1);
331 if (credit_charge > conn->total_credits) {
332 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
333 credit_charge, conn->total_credits);
337 conn->total_credits -= credit_charge;
338 conn->outstanding_credits -= credit_charge;
339 credits_requested = max_t(unsigned short,
340 le16_to_cpu(req_hdr->CreditRequest), 1);
342 /* according to smb2.credits smbtorture, Windows server
343 * 2016 or later grant up to 8192 credits at once.
345 * TODO: Need to adjuct CreditRequest value according to
348 if (hdr->Command == SMB2_NEGOTIATE)
351 aux_max = conn->vals->max_credits - conn->total_credits;
352 credits_granted = min_t(unsigned short, credits_requested, aux_max);
354 conn->total_credits += credits_granted;
355 work->credits_granted += credits_granted;
357 if (!req_hdr->NextCommand) {
358 /* Update CreditRequest in last request */
359 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
362 "credits: requested[%d] granted[%d] total_granted[%d]\n",
363 credits_requested, credits_granted,
364 conn->total_credits);
369 * init_chained_smb2_rsp() - initialize smb2 chained response
370 * @work: smb work containing smb response buffer
372 static void init_chained_smb2_rsp(struct ksmbd_work *work)
374 struct smb2_hdr *req = ksmbd_req_buf_next(work);
375 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
376 struct smb2_hdr *rsp_hdr;
377 struct smb2_hdr *rcv_hdr;
378 int next_hdr_offset = 0;
381 /* Len of this response = updated RFC len - offset of previous cmd
382 * in the compound rsp
385 /* Storing the current local FID which may be needed by subsequent
386 * command in the compound request
388 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
389 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
390 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
391 work->compound_sid = le64_to_cpu(rsp->SessionId);
394 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
395 next_hdr_offset = le32_to_cpu(req->NextCommand);
397 new_len = ALIGN(len, 8);
398 work->iov[work->iov_idx].iov_len += (new_len - len);
399 inc_rfc1001_len(work->response_buf, new_len - len);
400 rsp->NextCommand = cpu_to_le32(new_len);
402 work->next_smb2_rcv_hdr_off += next_hdr_offset;
403 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
404 work->next_smb2_rsp_hdr_off += new_len;
406 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
407 new_len, work->next_smb2_rcv_hdr_off,
408 work->next_smb2_rsp_hdr_off);
410 rsp_hdr = ksmbd_resp_buf_next(work);
411 rcv_hdr = ksmbd_req_buf_next(work);
413 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
414 ksmbd_debug(SMB, "related flag should be set\n");
415 work->compound_fid = KSMBD_NO_FID;
416 work->compound_pfid = KSMBD_NO_FID;
418 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
419 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
420 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
421 rsp_hdr->Command = rcv_hdr->Command;
424 * Message is response. We don't grant oplock yet.
426 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
427 SMB2_FLAGS_RELATED_OPERATIONS);
428 rsp_hdr->NextCommand = 0;
429 rsp_hdr->MessageId = rcv_hdr->MessageId;
430 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
431 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
432 rsp_hdr->SessionId = rcv_hdr->SessionId;
433 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
437 * is_chained_smb2_message() - check for chained command
438 * @work: smb work containing smb request buffer
440 * Return: true if chained request, otherwise false
442 bool is_chained_smb2_message(struct ksmbd_work *work)
444 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
445 unsigned int len, next_cmd;
447 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
450 hdr = ksmbd_req_buf_next(work);
451 next_cmd = le32_to_cpu(hdr->NextCommand);
453 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
454 __SMB2_HEADER_STRUCTURE_SIZE >
455 get_rfc1002_len(work->request_buf)) {
456 pr_err("next command(%u) offset exceeds smb msg size\n",
461 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
463 pr_err("next response offset exceeds response buffer size\n");
467 ksmbd_debug(SMB, "got SMB2 chained command\n");
468 init_chained_smb2_rsp(work);
470 } else if (work->next_smb2_rcv_hdr_off) {
472 * This is last request in chained command,
473 * align response to 8 byte
475 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
476 len = len - get_rfc1002_len(work->response_buf);
478 ksmbd_debug(SMB, "padding len %u\n", len);
479 work->iov[work->iov_idx].iov_len += len;
480 inc_rfc1001_len(work->response_buf, len);
482 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
488 * init_smb2_rsp_hdr() - initialize smb2 response
489 * @work: smb work containing smb request buffer
493 int init_smb2_rsp_hdr(struct ksmbd_work *work)
495 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
496 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
498 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
499 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
500 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
501 rsp_hdr->Command = rcv_hdr->Command;
504 * Message is response. We don't grant oplock yet.
506 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
507 rsp_hdr->NextCommand = 0;
508 rsp_hdr->MessageId = rcv_hdr->MessageId;
509 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
510 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
511 rsp_hdr->SessionId = rcv_hdr->SessionId;
512 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
518 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
519 * @work: smb work containing smb request buffer
521 * Return: 0 on success, otherwise -ENOMEM
523 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
525 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
526 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
527 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
528 size_t sz = small_sz;
529 int cmd = le16_to_cpu(hdr->Command);
531 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
534 if (cmd == SMB2_QUERY_INFO_HE) {
535 struct smb2_query_info_req *req;
537 req = smb2_get_msg(work->request_buf);
538 if ((req->InfoType == SMB2_O_INFO_FILE &&
539 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
540 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
541 req->InfoType == SMB2_O_INFO_SECURITY)
545 /* allocate large response buf for chained commands */
546 if (le32_to_cpu(hdr->NextCommand) > 0)
549 work->response_buf = kvzalloc(sz, GFP_KERNEL);
550 if (!work->response_buf)
553 work->response_sz = sz;
558 * smb2_check_user_session() - check for valid session for a user
559 * @work: smb work containing smb request buffer
561 * Return: 0 on success, otherwise error
563 int smb2_check_user_session(struct ksmbd_work *work)
565 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
566 struct ksmbd_conn *conn = work->conn;
567 unsigned int cmd = le16_to_cpu(req_hdr->Command);
568 unsigned long long sess_id;
571 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
572 * require a session id, so no need to validate user session's for
575 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
576 cmd == SMB2_SESSION_SETUP_HE)
579 if (!ksmbd_conn_good(conn))
582 sess_id = le64_to_cpu(req_hdr->SessionId);
585 * If request is not the first in Compound request,
586 * Just validate session id in header with work->sess->id.
588 if (work->next_smb2_rcv_hdr_off) {
590 pr_err("The first operation in the compound does not have sess\n");
593 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
594 pr_err("session id(%llu) is different with the first operation(%lld)\n",
595 sess_id, work->sess->id);
601 /* Check for validity of user session */
602 work->sess = ksmbd_session_lookup_all(conn, sess_id);
605 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
609 static void destroy_previous_session(struct ksmbd_conn *conn,
610 struct ksmbd_user *user, u64 id)
612 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
613 struct ksmbd_user *prev_user;
614 struct channel *chann;
620 prev_user = prev_sess->user;
623 strcmp(user->name, prev_user->name) ||
624 user->passkey_sz != prev_user->passkey_sz ||
625 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
628 prev_sess->state = SMB2_SESSION_EXPIRED;
629 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
630 ksmbd_conn_set_exiting(chann->conn);
634 * smb2_get_name() - get filename string from on the wire smb format
635 * @src: source buffer
636 * @maxlen: maxlen of source string
637 * @local_nls: nls_table pointer
639 * Return: matching converted filename on success, otherwise error ptr
642 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
646 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
648 pr_err("failed to get name %ld\n", PTR_ERR(name));
652 ksmbd_conv_path_to_unix(name);
653 ksmbd_strip_last_slash(name);
657 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
659 struct ksmbd_conn *conn = work->conn;
662 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
664 pr_err("Failed to alloc async message id\n");
667 work->asynchronous = true;
671 "Send interim Response to inform async request id : %d\n",
674 work->cancel_fn = fn;
675 work->cancel_argv = arg;
677 if (list_empty(&work->async_request_entry)) {
678 spin_lock(&conn->request_lock);
679 list_add_tail(&work->async_request_entry, &conn->async_requests);
680 spin_unlock(&conn->request_lock);
686 void release_async_work(struct ksmbd_work *work)
688 struct ksmbd_conn *conn = work->conn;
690 spin_lock(&conn->request_lock);
691 list_del_init(&work->async_request_entry);
692 spin_unlock(&conn->request_lock);
694 work->asynchronous = 0;
695 work->cancel_fn = NULL;
696 kfree(work->cancel_argv);
697 work->cancel_argv = NULL;
698 if (work->async_id) {
699 ksmbd_release_id(&conn->async_ida, work->async_id);
704 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
706 struct smb2_hdr *rsp_hdr;
707 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
709 if (allocate_interim_rsp_buf(in_work)) {
710 pr_err("smb_allocate_rsp_buf failed!\n");
711 ksmbd_free_work_struct(in_work);
715 in_work->conn = work->conn;
716 memcpy(smb2_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
717 __SMB2_HEADER_STRUCTURE_SIZE);
719 rsp_hdr = smb2_get_msg(in_work->response_buf);
720 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
721 rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
722 smb2_set_err_rsp(in_work);
723 rsp_hdr->Status = status;
725 ksmbd_conn_write(in_work);
726 ksmbd_free_work_struct(in_work);
729 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
731 if (S_ISDIR(mode) || S_ISREG(mode))
735 return IO_REPARSE_TAG_LX_SYMLINK_LE;
736 else if (S_ISFIFO(mode))
737 return IO_REPARSE_TAG_LX_FIFO_LE;
738 else if (S_ISSOCK(mode))
739 return IO_REPARSE_TAG_AF_UNIX_LE;
740 else if (S_ISCHR(mode))
741 return IO_REPARSE_TAG_LX_CHR_LE;
742 else if (S_ISBLK(mode))
743 return IO_REPARSE_TAG_LX_BLK_LE;
749 * smb2_get_dos_mode() - get file mode in dos format from unix mode
750 * @stat: kstat containing file mode
751 * @attribute: attribute flags
753 * Return: converted dos mode
755 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
759 if (S_ISDIR(stat->mode)) {
760 attr = FILE_ATTRIBUTE_DIRECTORY |
761 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
763 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
764 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
765 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
766 FILE_SUPPORTS_SPARSE_FILES))
767 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
769 if (smb2_get_reparse_tag_special_file(stat->mode))
770 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
776 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
779 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
780 pneg_ctxt->DataLength = cpu_to_le16(38);
781 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
782 pneg_ctxt->Reserved = cpu_to_le32(0);
783 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
784 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
785 pneg_ctxt->HashAlgorithms = hash_id;
788 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
791 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
792 pneg_ctxt->DataLength = cpu_to_le16(4);
793 pneg_ctxt->Reserved = cpu_to_le32(0);
794 pneg_ctxt->CipherCount = cpu_to_le16(1);
795 pneg_ctxt->Ciphers[0] = cipher_type;
798 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
801 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
802 pneg_ctxt->DataLength =
803 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
804 - sizeof(struct smb2_neg_context));
805 pneg_ctxt->Reserved = cpu_to_le32(0);
806 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
807 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
810 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
812 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
813 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
814 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
815 pneg_ctxt->Name[0] = 0x93;
816 pneg_ctxt->Name[1] = 0xAD;
817 pneg_ctxt->Name[2] = 0x25;
818 pneg_ctxt->Name[3] = 0x50;
819 pneg_ctxt->Name[4] = 0x9C;
820 pneg_ctxt->Name[5] = 0xB4;
821 pneg_ctxt->Name[6] = 0x11;
822 pneg_ctxt->Name[7] = 0xE7;
823 pneg_ctxt->Name[8] = 0xB4;
824 pneg_ctxt->Name[9] = 0x23;
825 pneg_ctxt->Name[10] = 0x83;
826 pneg_ctxt->Name[11] = 0xDE;
827 pneg_ctxt->Name[12] = 0x96;
828 pneg_ctxt->Name[13] = 0x8B;
829 pneg_ctxt->Name[14] = 0xCD;
830 pneg_ctxt->Name[15] = 0x7C;
833 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
834 struct smb2_negotiate_rsp *rsp)
836 char * const pneg_ctxt = (char *)rsp +
837 le32_to_cpu(rsp->NegotiateContextOffset);
838 int neg_ctxt_cnt = 1;
842 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
843 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
844 conn->preauth_info->Preauth_HashId);
845 ctxt_size = sizeof(struct smb2_preauth_neg_context);
847 if (conn->cipher_type) {
848 /* Round to 8 byte boundary */
849 ctxt_size = round_up(ctxt_size, 8);
851 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
852 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
853 (pneg_ctxt + ctxt_size),
856 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
859 /* compression context not yet supported */
860 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
862 if (conn->posix_ext_supported) {
863 ctxt_size = round_up(ctxt_size, 8);
865 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
866 build_posix_ctxt((struct smb2_posix_neg_context *)
867 (pneg_ctxt + ctxt_size));
869 ctxt_size += sizeof(struct smb2_posix_neg_context);
872 if (conn->signing_negotiated) {
873 ctxt_size = round_up(ctxt_size, 8);
875 "assemble SMB2_SIGNING_CAPABILITIES context\n");
876 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
877 (pneg_ctxt + ctxt_size),
878 conn->signing_algorithm);
880 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
883 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
884 return ctxt_size + AUTH_GSS_PADDING;
887 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
888 struct smb2_preauth_neg_context *pneg_ctxt,
892 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
893 * which may not be present. Only check for used HashAlgorithms[1].
896 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
897 return STATUS_INVALID_PARAMETER;
899 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
900 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
902 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
903 return STATUS_SUCCESS;
906 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
907 struct smb2_encryption_neg_context *pneg_ctxt,
913 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
914 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
918 conn->cipher_type = 0;
920 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
921 cphs_size = cph_cnt * sizeof(__le16);
923 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
925 pr_err("Invalid cipher count(%d)\n", cph_cnt);
929 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
932 for (i = 0; i < cph_cnt; i++) {
933 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
934 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
935 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
936 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
937 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
938 pneg_ctxt->Ciphers[i]);
939 conn->cipher_type = pneg_ctxt->Ciphers[i];
946 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
947 * @conn: smb connection
949 * Return: true if connection should be encrypted, else false
951 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
953 if (!conn->ops->generate_encryptionkey)
957 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
958 * SMB 3.1.1 uses the cipher_type field.
960 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
964 static void decode_compress_ctxt(struct ksmbd_conn *conn,
965 struct smb2_compression_capabilities_context *pneg_ctxt)
967 conn->compress_algorithm = SMB3_COMPRESS_NONE;
970 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
971 struct smb2_signing_capabilities *pneg_ctxt,
975 int i, sign_alos_size;
977 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
978 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
982 conn->signing_negotiated = false;
983 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
984 sign_alos_size = sign_algo_cnt * sizeof(__le16);
986 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
988 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
992 for (i = 0; i < sign_algo_cnt; i++) {
993 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
994 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
995 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
996 pneg_ctxt->SigningAlgorithms[i]);
997 conn->signing_negotiated = true;
998 conn->signing_algorithm =
999 pneg_ctxt->SigningAlgorithms[i];
1005 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1006 struct smb2_negotiate_req *req,
1007 unsigned int len_of_smb)
1009 /* +4 is to account for the RFC1001 len field */
1010 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1011 int i = 0, len_of_ctxts;
1012 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1013 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1014 __le32 status = STATUS_INVALID_PARAMETER;
1016 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1017 if (len_of_smb <= offset) {
1018 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1022 len_of_ctxts = len_of_smb - offset;
1024 while (i++ < neg_ctxt_cnt) {
1027 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1030 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1031 clen = le16_to_cpu(pctx->DataLength);
1032 ctxt_len = clen + sizeof(struct smb2_neg_context);
1034 if (ctxt_len > len_of_ctxts)
1037 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1039 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1040 if (conn->preauth_info->Preauth_HashId)
1043 status = decode_preauth_ctxt(conn,
1044 (struct smb2_preauth_neg_context *)pctx,
1046 if (status != STATUS_SUCCESS)
1048 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1050 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1051 if (conn->cipher_type)
1054 decode_encrypt_ctxt(conn,
1055 (struct smb2_encryption_neg_context *)pctx,
1057 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1059 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1060 if (conn->compress_algorithm)
1063 decode_compress_ctxt(conn,
1064 (struct smb2_compression_capabilities_context *)pctx);
1065 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1067 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1068 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1070 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1071 conn->posix_ext_supported = true;
1072 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1074 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1076 decode_sign_cap_ctxt(conn,
1077 (struct smb2_signing_capabilities *)pctx,
1081 /* offsets must be 8 byte aligned */
1082 offset = (ctxt_len + 7) & ~0x7;
1083 len_of_ctxts -= offset;
1089 * smb2_handle_negotiate() - handler for smb2 negotiate command
1090 * @work: smb work containing smb request buffer
1094 int smb2_handle_negotiate(struct ksmbd_work *work)
1096 struct ksmbd_conn *conn = work->conn;
1097 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1098 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1100 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1103 ksmbd_debug(SMB, "Received negotiate request\n");
1104 conn->need_neg = false;
1105 if (ksmbd_conn_good(conn)) {
1106 pr_err("conn->tcp_status is already in CifsGood State\n");
1107 work->send_no_response = 1;
1111 smb2_buf_len = get_rfc1002_len(work->request_buf);
1112 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1113 if (smb2_neg_size > smb2_buf_len) {
1114 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1119 if (req->DialectCount == 0) {
1120 pr_err("malformed packet\n");
1121 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1126 if (conn->dialect == SMB311_PROT_ID) {
1127 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1129 if (smb2_buf_len < nego_ctxt_off) {
1130 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1135 if (smb2_neg_size > nego_ctxt_off) {
1136 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1141 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1143 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1148 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1150 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1156 conn->cli_cap = le32_to_cpu(req->Capabilities);
1157 switch (conn->dialect) {
1158 case SMB311_PROT_ID:
1159 conn->preauth_info =
1160 kzalloc(sizeof(struct preauth_integrity_info),
1162 if (!conn->preauth_info) {
1164 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1168 status = deassemble_neg_contexts(conn, req,
1169 get_rfc1002_len(work->request_buf));
1170 if (status != STATUS_SUCCESS) {
1171 pr_err("deassemble_neg_contexts error(0x%x)\n",
1173 rsp->hdr.Status = status;
1175 kfree(conn->preauth_info);
1176 conn->preauth_info = NULL;
1180 rc = init_smb3_11_server(conn);
1182 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1183 kfree(conn->preauth_info);
1184 conn->preauth_info = NULL;
1188 ksmbd_gen_preauth_integrity_hash(conn,
1190 conn->preauth_info->Preauth_HashValue);
1191 rsp->NegotiateContextOffset =
1192 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1193 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1195 case SMB302_PROT_ID:
1196 init_smb3_02_server(conn);
1199 init_smb3_0_server(conn);
1202 init_smb2_1_server(conn);
1207 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1209 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1213 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1216 conn->connection_type = conn->dialect;
1218 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1219 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1220 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1222 memcpy(conn->ClientGUID, req->ClientGUID,
1223 SMB2_CLIENT_GUID_SIZE);
1224 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1226 rsp->StructureSize = cpu_to_le16(65);
1227 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1228 /* Not setting conn guid rsp->ServerGUID, as it
1229 * not used by client for identifying server
1231 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1233 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1234 rsp->ServerStartTime = 0;
1235 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1236 le32_to_cpu(rsp->NegotiateContextOffset),
1237 le16_to_cpu(rsp->NegotiateContextCount));
1239 rsp->SecurityBufferOffset = cpu_to_le16(128);
1240 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1241 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1242 le16_to_cpu(rsp->SecurityBufferOffset));
1243 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1244 conn->use_spnego = true;
1246 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1247 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1248 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1250 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1251 server_conf.enforced_signing = true;
1252 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1256 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1257 ksmbd_conn_set_need_negotiate(conn);
1261 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1264 rc = ksmbd_iov_pin_rsp(work, rsp,
1265 sizeof(struct smb2_negotiate_rsp) +
1266 AUTH_GSS_LENGTH + neg_ctxt_len);
1268 smb2_set_err_rsp(work);
1272 static int alloc_preauth_hash(struct ksmbd_session *sess,
1273 struct ksmbd_conn *conn)
1275 if (sess->Preauth_HashValue)
1278 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1279 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1280 if (!sess->Preauth_HashValue)
1286 static int generate_preauth_hash(struct ksmbd_work *work)
1288 struct ksmbd_conn *conn = work->conn;
1289 struct ksmbd_session *sess = work->sess;
1292 if (conn->dialect != SMB311_PROT_ID)
1295 if (conn->binding) {
1296 struct preauth_session *preauth_sess;
1298 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1299 if (!preauth_sess) {
1300 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1305 preauth_hash = preauth_sess->Preauth_HashValue;
1307 if (!sess->Preauth_HashValue)
1308 if (alloc_preauth_hash(sess, conn))
1310 preauth_hash = sess->Preauth_HashValue;
1313 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1317 static int decode_negotiation_token(struct ksmbd_conn *conn,
1318 struct negotiate_message *negblob,
1321 if (!conn->use_spnego)
1324 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1325 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1326 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1327 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1328 conn->use_spnego = false;
1334 static int ntlm_negotiate(struct ksmbd_work *work,
1335 struct negotiate_message *negblob,
1336 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1338 struct challenge_message *chgblob;
1339 unsigned char *spnego_blob = NULL;
1340 u16 spnego_blob_len;
1344 ksmbd_debug(SMB, "negotiate phase\n");
1345 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1349 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1351 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1352 memset(chgblob, 0, sizeof(struct challenge_message));
1354 if (!work->conn->use_spnego) {
1355 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1359 rsp->SecurityBufferLength = cpu_to_le16(sz);
1363 sz = sizeof(struct challenge_message);
1364 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1366 neg_blob = kzalloc(sz, GFP_KERNEL);
1370 chgblob = (struct challenge_message *)neg_blob;
1371 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1377 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1384 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1385 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1386 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1394 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1395 struct smb2_sess_setup_req *req)
1399 if (conn->use_spnego && conn->mechToken)
1400 return (struct authenticate_message *)conn->mechToken;
1402 sz = le16_to_cpu(req->SecurityBufferOffset);
1403 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1407 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1408 struct smb2_sess_setup_req *req)
1410 struct authenticate_message *authblob;
1411 struct ksmbd_user *user;
1413 unsigned int name_off, name_len, secbuf_len;
1415 if (conn->use_spnego && conn->mechToken)
1416 secbuf_len = conn->mechTokenLen;
1418 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1419 if (secbuf_len < sizeof(struct authenticate_message)) {
1420 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1423 authblob = user_authblob(conn, req);
1424 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1425 name_len = le16_to_cpu(authblob->UserName.Length);
1427 if (secbuf_len < (u64)name_off + name_len)
1430 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1435 pr_err("cannot allocate memory\n");
1439 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1440 user = ksmbd_login_user(name);
1445 static int ntlm_authenticate(struct ksmbd_work *work,
1446 struct smb2_sess_setup_req *req,
1447 struct smb2_sess_setup_rsp *rsp)
1449 struct ksmbd_conn *conn = work->conn;
1450 struct ksmbd_session *sess = work->sess;
1451 struct channel *chann = NULL;
1452 struct ksmbd_user *user;
1456 ksmbd_debug(SMB, "authenticate phase\n");
1457 if (conn->use_spnego) {
1458 unsigned char *spnego_blob;
1459 u16 spnego_blob_len;
1461 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1467 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1468 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1469 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1473 user = session_user(conn, req);
1475 ksmbd_debug(SMB, "Unknown user name or an error\n");
1479 /* Check for previous session */
1480 prev_id = le64_to_cpu(req->PreviousSessionId);
1481 if (prev_id && prev_id != sess->id)
1482 destroy_previous_session(conn, user, prev_id);
1484 if (sess->state == SMB2_SESSION_VALID) {
1486 * Reuse session if anonymous try to connect
1487 * on reauthetication.
1489 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1490 ksmbd_free_user(user);
1494 if (!ksmbd_compare_user(sess->user, user)) {
1495 ksmbd_free_user(user);
1498 ksmbd_free_user(user);
1503 if (conn->binding == false && user_guest(sess->user)) {
1504 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1506 struct authenticate_message *authblob;
1508 authblob = user_authblob(conn, req);
1509 if (conn->use_spnego && conn->mechToken)
1510 sz = conn->mechTokenLen;
1512 sz = le16_to_cpu(req->SecurityBufferLength);
1513 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1515 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1516 ksmbd_debug(SMB, "authentication failed\n");
1522 * If session state is SMB2_SESSION_VALID, We can assume
1523 * that it is reauthentication. And the user/password
1524 * has been verified, so return it here.
1526 if (sess->state == SMB2_SESSION_VALID) {
1528 goto binding_session;
1532 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1533 (conn->sign || server_conf.enforced_signing)) ||
1534 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1537 if (smb3_encryption_negotiated(conn) &&
1538 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1539 rc = conn->ops->generate_encryptionkey(conn, sess);
1542 "SMB3 encryption key generation failed\n");
1546 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1547 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1549 * signing is disable if encryption is enable
1556 if (conn->dialect >= SMB30_PROT_ID) {
1557 chann = lookup_chann_list(sess, conn);
1559 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1564 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1568 if (conn->ops->generate_signingkey) {
1569 rc = conn->ops->generate_signingkey(sess, conn);
1571 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1576 if (!ksmbd_conn_lookup_dialect(conn)) {
1577 pr_err("fail to verify the dialect\n");
1583 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1584 static int krb5_authenticate(struct ksmbd_work *work,
1585 struct smb2_sess_setup_req *req,
1586 struct smb2_sess_setup_rsp *rsp)
1588 struct ksmbd_conn *conn = work->conn;
1589 struct ksmbd_session *sess = work->sess;
1590 char *in_blob, *out_blob;
1591 struct channel *chann = NULL;
1593 int in_len, out_len;
1596 in_blob = (char *)&req->hdr.ProtocolId +
1597 le16_to_cpu(req->SecurityBufferOffset);
1598 in_len = le16_to_cpu(req->SecurityBufferLength);
1599 out_blob = (char *)&rsp->hdr.ProtocolId +
1600 le16_to_cpu(rsp->SecurityBufferOffset);
1601 out_len = work->response_sz -
1602 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1604 /* Check previous session */
1605 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1606 if (prev_sess_id && prev_sess_id != sess->id)
1607 destroy_previous_session(conn, sess->user, prev_sess_id);
1609 if (sess->state == SMB2_SESSION_VALID)
1610 ksmbd_free_user(sess->user);
1612 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1613 out_blob, &out_len);
1615 ksmbd_debug(SMB, "krb5 authentication failed\n");
1618 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1620 if ((conn->sign || server_conf.enforced_signing) ||
1621 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1624 if (smb3_encryption_negotiated(conn)) {
1625 retval = conn->ops->generate_encryptionkey(conn, sess);
1628 "SMB3 encryption key generation failed\n");
1632 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1633 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1637 if (conn->dialect >= SMB30_PROT_ID) {
1638 chann = lookup_chann_list(sess, conn);
1640 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1645 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1649 if (conn->ops->generate_signingkey) {
1650 retval = conn->ops->generate_signingkey(sess, conn);
1652 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1657 if (!ksmbd_conn_lookup_dialect(conn)) {
1658 pr_err("fail to verify the dialect\n");
1664 static int krb5_authenticate(struct ksmbd_work *work,
1665 struct smb2_sess_setup_req *req,
1666 struct smb2_sess_setup_rsp *rsp)
1672 int smb2_sess_setup(struct ksmbd_work *work)
1674 struct ksmbd_conn *conn = work->conn;
1675 struct smb2_sess_setup_req *req;
1676 struct smb2_sess_setup_rsp *rsp;
1677 struct ksmbd_session *sess;
1678 struct negotiate_message *negblob;
1679 unsigned int negblob_len, negblob_off;
1682 ksmbd_debug(SMB, "Received request for session setup\n");
1684 WORK_BUFFERS(work, req, rsp);
1686 rsp->StructureSize = cpu_to_le16(9);
1687 rsp->SessionFlags = 0;
1688 rsp->SecurityBufferOffset = cpu_to_le16(72);
1689 rsp->SecurityBufferLength = 0;
1691 ksmbd_conn_lock(conn);
1692 if (!req->hdr.SessionId) {
1693 sess = ksmbd_smb2_session_create();
1698 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1699 rc = ksmbd_session_register(conn, sess);
1702 } else if (conn->dialect >= SMB30_PROT_ID &&
1703 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1704 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1705 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1707 sess = ksmbd_session_lookup_slowpath(sess_id);
1713 if (conn->dialect != sess->dialect) {
1718 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1723 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1724 SMB2_CLIENT_GUID_SIZE)) {
1729 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1734 if (sess->state == SMB2_SESSION_EXPIRED) {
1739 if (ksmbd_conn_need_reconnect(conn)) {
1745 if (ksmbd_session_lookup(conn, sess_id)) {
1750 if (user_guest(sess->user)) {
1755 conn->binding = true;
1756 } else if ((conn->dialect < SMB30_PROT_ID ||
1757 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1758 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1763 sess = ksmbd_session_lookup(conn,
1764 le64_to_cpu(req->hdr.SessionId));
1770 if (sess->state == SMB2_SESSION_EXPIRED) {
1775 if (ksmbd_conn_need_reconnect(conn)) {
1783 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1784 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1785 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
1790 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1793 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1794 if (conn->mechToken) {
1795 negblob = (struct negotiate_message *)conn->mechToken;
1796 negblob_len = conn->mechTokenLen;
1800 if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1805 if (server_conf.auth_mechs & conn->auth_mechs) {
1806 rc = generate_preauth_hash(work);
1810 if (conn->preferred_auth_mech &
1811 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1812 rc = krb5_authenticate(work, req, rsp);
1818 if (!ksmbd_conn_need_reconnect(conn)) {
1819 ksmbd_conn_set_good(conn);
1820 sess->state = SMB2_SESSION_VALID;
1822 kfree(sess->Preauth_HashValue);
1823 sess->Preauth_HashValue = NULL;
1824 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1825 if (negblob->MessageType == NtLmNegotiate) {
1826 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1830 STATUS_MORE_PROCESSING_REQUIRED;
1831 } else if (negblob->MessageType == NtLmAuthenticate) {
1832 rc = ntlm_authenticate(work, req, rsp);
1836 if (!ksmbd_conn_need_reconnect(conn)) {
1837 ksmbd_conn_set_good(conn);
1838 sess->state = SMB2_SESSION_VALID;
1840 if (conn->binding) {
1841 struct preauth_session *preauth_sess;
1844 ksmbd_preauth_session_lookup(conn, sess->id);
1846 list_del(&preauth_sess->preauth_entry);
1847 kfree(preauth_sess);
1850 kfree(sess->Preauth_HashValue);
1851 sess->Preauth_HashValue = NULL;
1853 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1854 le32_to_cpu(negblob->MessageType));
1858 /* TODO: need one more negotiation */
1859 pr_err("Not support the preferred authentication\n");
1863 pr_err("Not support authentication\n");
1869 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1870 else if (rc == -ENOENT)
1871 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1872 else if (rc == -EACCES)
1873 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1874 else if (rc == -EFAULT)
1875 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1876 else if (rc == -ENOMEM)
1877 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1878 else if (rc == -EOPNOTSUPP)
1879 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1881 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1883 if (conn->use_spnego && conn->mechToken) {
1884 kfree(conn->mechToken);
1885 conn->mechToken = NULL;
1890 * SecurityBufferOffset should be set to zero
1891 * in session setup error response.
1893 rsp->SecurityBufferOffset = 0;
1896 bool try_delay = false;
1899 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1900 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1901 * failure to make it harder to send enough random connection requests
1902 * to break into a server.
1904 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1907 sess->last_active = jiffies;
1908 sess->state = SMB2_SESSION_EXPIRED;
1910 ksmbd_conn_set_need_reconnect(conn);
1912 ksmbd_conn_set_need_negotiate(conn);
1915 smb2_set_err_rsp(work);
1917 unsigned int iov_len;
1919 if (rsp->SecurityBufferLength)
1920 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1921 le16_to_cpu(rsp->SecurityBufferLength);
1923 iov_len = sizeof(struct smb2_sess_setup_rsp);
1924 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1926 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1929 ksmbd_conn_unlock(conn);
1934 * smb2_tree_connect() - handler for smb2 tree connect command
1935 * @work: smb work containing smb request buffer
1937 * Return: 0 on success, otherwise error
1939 int smb2_tree_connect(struct ksmbd_work *work)
1941 struct ksmbd_conn *conn = work->conn;
1942 struct smb2_tree_connect_req *req;
1943 struct smb2_tree_connect_rsp *rsp;
1944 struct ksmbd_session *sess = work->sess;
1945 char *treename = NULL, *name = NULL;
1946 struct ksmbd_tree_conn_status status;
1947 struct ksmbd_share_config *share;
1950 WORK_BUFFERS(work, req, rsp);
1952 treename = smb_strndup_from_utf16(req->Buffer,
1953 le16_to_cpu(req->PathLength), true,
1955 if (IS_ERR(treename)) {
1956 pr_err("treename is NULL\n");
1957 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1961 name = ksmbd_extract_sharename(conn->um, treename);
1963 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1967 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1970 status = ksmbd_tree_conn_connect(conn, sess, name);
1971 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1972 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1976 share = status.tree_conn->share_conf;
1977 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1978 ksmbd_debug(SMB, "IPC share path request\n");
1979 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1980 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1981 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1982 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1983 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1984 FILE_SYNCHRONIZE_LE;
1986 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1987 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1988 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1989 if (test_tree_conn_flag(status.tree_conn,
1990 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1991 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1992 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1993 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1994 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1995 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1996 FILE_SYNCHRONIZE_LE;
2000 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2001 if (conn->posix_ext_supported)
2002 status.tree_conn->posix_extensions = true;
2004 write_lock(&sess->tree_conns_lock);
2005 status.tree_conn->t_state = TREE_CONNECTED;
2006 write_unlock(&sess->tree_conns_lock);
2007 rsp->StructureSize = cpu_to_le16(16);
2009 rsp->Capabilities = 0;
2011 /* default manual caching */
2012 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2014 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2016 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2018 if (!IS_ERR(treename))
2023 switch (status.ret) {
2024 case KSMBD_TREE_CONN_STATUS_OK:
2025 rsp->hdr.Status = STATUS_SUCCESS;
2030 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2031 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2034 case KSMBD_TREE_CONN_STATUS_NOMEM:
2035 rsp->hdr.Status = STATUS_NO_MEMORY;
2037 case KSMBD_TREE_CONN_STATUS_ERROR:
2038 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2039 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2040 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2043 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2046 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2049 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2050 smb2_set_err_rsp(work);
2056 * smb2_create_open_flags() - convert smb open flags to unix open flags
2057 * @file_present: is file already present
2058 * @access: file access flags
2059 * @disposition: file disposition flags
2060 * @may_flags: set with MAY_ flags
2062 * Return: file open flags
2064 static int smb2_create_open_flags(bool file_present, __le32 access,
2068 int oflags = O_NONBLOCK | O_LARGEFILE;
2070 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2071 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2073 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2074 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2076 *may_flags = MAY_OPEN | MAY_WRITE;
2079 *may_flags = MAY_OPEN | MAY_READ;
2082 if (access == FILE_READ_ATTRIBUTES_LE)
2086 switch (disposition & FILE_CREATE_MASK_LE) {
2088 case FILE_CREATE_LE:
2090 case FILE_SUPERSEDE_LE:
2091 case FILE_OVERWRITE_LE:
2092 case FILE_OVERWRITE_IF_LE:
2099 switch (disposition & FILE_CREATE_MASK_LE) {
2100 case FILE_SUPERSEDE_LE:
2101 case FILE_CREATE_LE:
2102 case FILE_OPEN_IF_LE:
2103 case FILE_OVERWRITE_IF_LE:
2107 case FILE_OVERWRITE_LE:
2119 * smb2_tree_disconnect() - handler for smb tree connect request
2120 * @work: smb work containing request buffer
2124 int smb2_tree_disconnect(struct ksmbd_work *work)
2126 struct smb2_tree_disconnect_rsp *rsp;
2127 struct smb2_tree_disconnect_req *req;
2128 struct ksmbd_session *sess = work->sess;
2129 struct ksmbd_tree_connect *tcon = work->tcon;
2132 WORK_BUFFERS(work, req, rsp);
2134 ksmbd_debug(SMB, "request\n");
2137 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2139 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2144 ksmbd_close_tree_conn_fds(work);
2146 write_lock(&sess->tree_conns_lock);
2147 if (tcon->t_state == TREE_DISCONNECTED) {
2148 write_unlock(&sess->tree_conns_lock);
2149 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2154 WARN_ON_ONCE(atomic_dec_and_test(&tcon->refcount));
2155 tcon->t_state = TREE_DISCONNECTED;
2156 write_unlock(&sess->tree_conns_lock);
2158 err = ksmbd_tree_conn_disconnect(sess, tcon);
2160 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2166 rsp->StructureSize = cpu_to_le16(4);
2167 err = ksmbd_iov_pin_rsp(work, rsp,
2168 sizeof(struct smb2_tree_disconnect_rsp));
2170 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2177 smb2_set_err_rsp(work);
2183 * smb2_session_logoff() - handler for session log off request
2184 * @work: smb work containing request buffer
2188 int smb2_session_logoff(struct ksmbd_work *work)
2190 struct ksmbd_conn *conn = work->conn;
2191 struct smb2_logoff_req *req;
2192 struct smb2_logoff_rsp *rsp;
2193 struct ksmbd_session *sess;
2197 WORK_BUFFERS(work, req, rsp);
2199 ksmbd_debug(SMB, "request\n");
2201 ksmbd_conn_lock(conn);
2202 if (!ksmbd_conn_good(conn)) {
2203 ksmbd_conn_unlock(conn);
2204 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2205 smb2_set_err_rsp(work);
2208 sess_id = le64_to_cpu(req->hdr.SessionId);
2209 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2210 ksmbd_conn_unlock(conn);
2212 ksmbd_close_session_fds(work);
2213 ksmbd_conn_wait_idle(conn, sess_id);
2216 * Re-lookup session to validate if session is deleted
2217 * while waiting request complete
2219 sess = ksmbd_session_lookup_all(conn, sess_id);
2220 if (ksmbd_tree_conn_session_logoff(sess)) {
2221 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2222 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2223 smb2_set_err_rsp(work);
2227 ksmbd_destroy_file_table(&sess->file_table);
2228 sess->state = SMB2_SESSION_EXPIRED;
2230 ksmbd_free_user(sess->user);
2232 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2234 rsp->StructureSize = cpu_to_le16(4);
2235 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2237 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2238 smb2_set_err_rsp(work);
2245 * create_smb2_pipe() - create IPC pipe
2246 * @work: smb work containing request buffer
2248 * Return: 0 on success, otherwise error
2250 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2252 struct smb2_create_rsp *rsp;
2253 struct smb2_create_req *req;
2258 WORK_BUFFERS(work, req, rsp);
2260 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2261 1, work->conn->local_nls);
2263 rsp->hdr.Status = STATUS_NO_MEMORY;
2264 err = PTR_ERR(name);
2268 id = ksmbd_session_rpc_open(work->sess, name);
2270 pr_err("Unable to open RPC pipe: %d\n", id);
2275 rsp->hdr.Status = STATUS_SUCCESS;
2276 rsp->StructureSize = cpu_to_le16(89);
2277 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2279 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2281 rsp->CreationTime = cpu_to_le64(0);
2282 rsp->LastAccessTime = cpu_to_le64(0);
2283 rsp->ChangeTime = cpu_to_le64(0);
2284 rsp->AllocationSize = cpu_to_le64(0);
2285 rsp->EndofFile = cpu_to_le64(0);
2286 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2288 rsp->VolatileFileId = id;
2289 rsp->PersistentFileId = 0;
2290 rsp->CreateContextsOffset = 0;
2291 rsp->CreateContextsLength = 0;
2293 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2303 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2307 rsp->hdr.Status = STATUS_NO_MEMORY;
2314 smb2_set_err_rsp(work);
2319 * smb2_set_ea() - handler for setting extended attributes using set
2321 * @eabuf: set info command buffer
2322 * @buf_len: set info command buffer length
2323 * @path: dentry path for get ea
2324 * @get_write: get write access to a mount
2326 * Return: 0 on success, otherwise error
2328 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2329 const struct path *path, bool get_write)
2331 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2332 char *attr_name = NULL, *value;
2334 unsigned int next = 0;
2336 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2337 le16_to_cpu(eabuf->EaValueLength))
2340 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2345 if (!eabuf->EaNameLength)
2349 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2350 eabuf->name, eabuf->EaNameLength,
2351 le16_to_cpu(eabuf->EaValueLength),
2352 le32_to_cpu(eabuf->NextEntryOffset));
2354 if (eabuf->EaNameLength >
2355 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2360 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2361 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2362 eabuf->EaNameLength);
2363 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2364 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2366 if (!eabuf->EaValueLength) {
2367 rc = ksmbd_vfs_casexattr_len(user_ns,
2370 XATTR_USER_PREFIX_LEN +
2371 eabuf->EaNameLength);
2373 /* delete the EA only when it exits */
2375 rc = ksmbd_vfs_remove_xattr(user_ns,
2381 "remove xattr failed(%d)\n",
2387 /* if the EA doesn't exist, just do nothing. */
2390 rc = ksmbd_vfs_setxattr(user_ns, path, attr_name, value,
2391 le16_to_cpu(eabuf->EaValueLength),
2395 "ksmbd_vfs_setxattr is failed(%d)\n",
2402 next = le32_to_cpu(eabuf->NextEntryOffset);
2403 if (next == 0 || buf_len < next)
2406 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2407 if (buf_len < sizeof(struct smb2_ea_info)) {
2412 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2413 le16_to_cpu(eabuf->EaValueLength)) {
2417 } while (next != 0);
2423 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2424 struct ksmbd_file *fp,
2425 char *stream_name, int s_type)
2427 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2428 size_t xattr_stream_size;
2429 char *xattr_stream_name;
2432 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2439 fp->stream.name = xattr_stream_name;
2440 fp->stream.size = xattr_stream_size;
2442 /* Check if there is stream prefix in xattr space */
2443 rc = ksmbd_vfs_casexattr_len(user_ns,
2450 if (fp->cdoption == FILE_OPEN_LE) {
2451 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2455 rc = ksmbd_vfs_setxattr(user_ns, path, xattr_stream_name, NULL, 0, 0, false);
2457 pr_err("Failed to store XATTR stream name :%d\n", rc);
2461 static int smb2_remove_smb_xattrs(const struct path *path)
2463 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2464 char *name, *xattr_list = NULL;
2465 ssize_t xattr_list_len;
2468 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2469 if (xattr_list_len < 0) {
2471 } else if (!xattr_list_len) {
2472 ksmbd_debug(SMB, "empty xattr in the file\n");
2476 for (name = xattr_list; name - xattr_list < xattr_list_len;
2477 name += strlen(name) + 1) {
2478 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2480 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2481 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2482 STREAM_PREFIX_LEN)) {
2483 err = ksmbd_vfs_remove_xattr(user_ns, path,
2486 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2495 static int smb2_create_truncate(const struct path *path)
2497 int rc = vfs_truncate(path, 0);
2500 pr_err("vfs_truncate failed, rc %d\n", rc);
2504 rc = smb2_remove_smb_xattrs(path);
2505 if (rc == -EOPNOTSUPP)
2509 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2514 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2515 struct ksmbd_file *fp)
2517 struct xattr_dos_attrib da = {0};
2520 if (!test_share_config_flag(tcon->share_conf,
2521 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2525 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2526 da.itime = da.create_time = fp->create_time;
2527 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2528 XATTR_DOSINFO_ITIME;
2530 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt), path, &da, true);
2532 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2535 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2536 const struct path *path, struct ksmbd_file *fp)
2538 struct xattr_dos_attrib da;
2541 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2543 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2544 if (!test_share_config_flag(tcon->share_conf,
2545 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2548 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2551 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2552 fp->create_time = da.create_time;
2553 fp->itime = da.itime;
2557 static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2558 struct path *path, char *name, int open_flags,
2559 umode_t posix_mode, bool is_dir)
2561 struct ksmbd_tree_connect *tcon = work->tcon;
2562 struct ksmbd_share_config *share = tcon->share_conf;
2566 if (!(open_flags & O_CREAT))
2569 ksmbd_debug(SMB, "file does not exist, so creating\n");
2570 if (is_dir == true) {
2571 ksmbd_debug(SMB, "creating directory\n");
2573 mode = share_config_directory_mode(share, posix_mode);
2574 rc = ksmbd_vfs_mkdir(work, name, mode);
2578 ksmbd_debug(SMB, "creating regular file\n");
2580 mode = share_config_create_mode(share, posix_mode);
2581 rc = ksmbd_vfs_create(work, name, mode);
2586 rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2588 pr_err("cannot get linux path (%s), err = %d\n",
2595 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2596 struct smb2_create_req *req,
2597 const struct path *path)
2599 struct create_context *context;
2600 struct create_sd_buf_req *sd_buf;
2602 if (!req->CreateContextsOffset)
2605 /* Parse SD BUFFER create contexts */
2606 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2609 else if (IS_ERR(context))
2610 return PTR_ERR(context);
2613 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2614 sd_buf = (struct create_sd_buf_req *)context;
2615 if (le16_to_cpu(context->DataOffset) +
2616 le32_to_cpu(context->DataLength) <
2617 sizeof(struct create_sd_buf_req))
2619 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2620 le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2623 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2624 struct user_namespace *mnt_userns,
2625 struct inode *inode)
2627 vfsuid_t vfsuid = i_uid_into_vfsuid(mnt_userns, inode);
2628 vfsgid_t vfsgid = i_gid_into_vfsgid(mnt_userns, inode);
2630 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2631 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2632 fattr->cf_mode = inode->i_mode;
2633 fattr->cf_acls = NULL;
2634 fattr->cf_dacls = NULL;
2636 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2637 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2638 if (S_ISDIR(inode->i_mode))
2639 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2644 * smb2_open() - handler for smb file open request
2645 * @work: smb work containing request buffer
2647 * Return: 0 on success, otherwise error
2649 int smb2_open(struct ksmbd_work *work)
2651 struct ksmbd_conn *conn = work->conn;
2652 struct ksmbd_session *sess = work->sess;
2653 struct ksmbd_tree_connect *tcon = work->tcon;
2654 struct smb2_create_req *req;
2655 struct smb2_create_rsp *rsp;
2656 struct path path, parent_path;
2657 struct ksmbd_share_config *share = tcon->share_conf;
2658 struct ksmbd_file *fp = NULL;
2659 struct file *filp = NULL;
2660 struct user_namespace *user_ns = NULL;
2662 struct create_context *context;
2663 struct lease_ctx_info *lc = NULL;
2664 struct create_ea_buf_req *ea_buf = NULL;
2665 struct oplock_info *opinfo;
2666 __le32 *next_ptr = NULL;
2667 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2669 int contxt_cnt = 0, query_disk_id = 0;
2670 int maximal_access_ctxt = 0, posix_ctxt = 0;
2674 char *stream_name = NULL;
2675 bool file_present = false, created = false, already_permitted = false;
2676 int share_ret, need_truncate = 0;
2678 umode_t posix_mode = 0;
2679 __le32 daccess, maximal_access = 0;
2682 WORK_BUFFERS(work, req, rsp);
2684 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2685 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2686 ksmbd_debug(SMB, "invalid flag in chained command\n");
2687 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2688 smb2_set_err_rsp(work);
2692 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2693 ksmbd_debug(SMB, "IPC pipe create request\n");
2694 return create_smb2_pipe(work);
2697 if (req->NameLength) {
2698 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2699 *(char *)req->Buffer == '\\') {
2700 pr_err("not allow directory name included leading slash\n");
2705 name = smb2_get_name(req->Buffer,
2706 le16_to_cpu(req->NameLength),
2707 work->conn->local_nls);
2716 ksmbd_debug(SMB, "converted name = %s\n", name);
2717 if (strchr(name, ':')) {
2718 if (!test_share_config_flag(work->tcon->share_conf,
2719 KSMBD_SHARE_FLAG_STREAMS)) {
2723 rc = parse_stream_name(name, &stream_name, &s_type);
2728 rc = ksmbd_validate_filename(name);
2732 if (ksmbd_share_veto_filename(share, name)) {
2734 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2739 name = kstrdup("", GFP_KERNEL);
2746 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2747 pr_err("Invalid impersonationlevel : 0x%x\n",
2748 le32_to_cpu(req->ImpersonationLevel));
2750 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2754 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2755 pr_err("Invalid create options : 0x%x\n",
2756 le32_to_cpu(req->CreateOptions));
2760 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2761 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2762 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2764 if (req->CreateOptions &
2765 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2766 FILE_RESERVE_OPFILTER_LE)) {
2771 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2772 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2775 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2776 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2781 if (le32_to_cpu(req->CreateDisposition) >
2782 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2783 pr_err("Invalid create disposition : 0x%x\n",
2784 le32_to_cpu(req->CreateDisposition));
2789 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2790 pr_err("Invalid desired access : 0x%x\n",
2791 le32_to_cpu(req->DesiredAccess));
2796 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2797 pr_err("Invalid file attribute : 0x%x\n",
2798 le32_to_cpu(req->FileAttributes));
2803 if (req->CreateContextsOffset) {
2804 /* Parse non-durable handle create contexts */
2805 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2806 if (IS_ERR(context)) {
2807 rc = PTR_ERR(context);
2809 } else if (context) {
2810 ea_buf = (struct create_ea_buf_req *)context;
2811 if (le16_to_cpu(context->DataOffset) +
2812 le32_to_cpu(context->DataLength) <
2813 sizeof(struct create_ea_buf_req)) {
2817 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2818 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2824 context = smb2_find_context_vals(req,
2825 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2826 if (IS_ERR(context)) {
2827 rc = PTR_ERR(context);
2829 } else if (context) {
2831 "get query maximal access context\n");
2832 maximal_access_ctxt = 1;
2835 context = smb2_find_context_vals(req,
2836 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2837 if (IS_ERR(context)) {
2838 rc = PTR_ERR(context);
2840 } else if (context) {
2841 ksmbd_debug(SMB, "get timewarp context\n");
2846 if (tcon->posix_extensions) {
2847 context = smb2_find_context_vals(req,
2848 SMB2_CREATE_TAG_POSIX, 16);
2849 if (IS_ERR(context)) {
2850 rc = PTR_ERR(context);
2852 } else if (context) {
2853 struct create_posix *posix =
2854 (struct create_posix *)context;
2855 if (le16_to_cpu(context->DataOffset) +
2856 le32_to_cpu(context->DataLength) <
2857 sizeof(struct create_posix) - 4) {
2861 ksmbd_debug(SMB, "get posix context\n");
2863 posix_mode = le32_to_cpu(posix->Mode);
2869 if (ksmbd_override_fsids(work)) {
2874 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
2875 &parent_path, &path, 1);
2877 file_present = true;
2879 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2881 * If file exists with under flags, return access
2884 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2885 req->CreateDisposition == FILE_OPEN_IF_LE) {
2890 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2892 "User does not have write permission\n");
2896 } else if (d_is_symlink(path.dentry)) {
2901 file_present = true;
2902 user_ns = mnt_user_ns(path.mnt);
2906 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2912 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2913 if (s_type == DATA_STREAM) {
2915 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2918 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2919 s_type == DATA_STREAM) {
2921 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2925 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2926 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2927 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2935 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2936 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2937 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2938 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2939 name, req->CreateOptions);
2940 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2945 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2946 !(req->CreateDisposition == FILE_CREATE_LE) &&
2947 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2948 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2953 if (!stream_name && file_present &&
2954 req->CreateDisposition == FILE_CREATE_LE) {
2959 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2961 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2962 rc = smb_check_perm_dacl(conn, &path, &daccess,
2968 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2969 if (!file_present) {
2970 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2972 ksmbd_vfs_query_maximal_access(user_ns,
2975 already_permitted = true;
2977 maximal_access = daccess;
2980 open_flags = smb2_create_open_flags(file_present, daccess,
2981 req->CreateDisposition,
2984 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2985 if (open_flags & (O_CREAT | O_TRUNC)) {
2987 "User does not have write permission\n");
2993 /*create file if not present */
2994 if (!file_present) {
2995 rc = smb2_creat(work, &parent_path, &path, name, open_flags,
2997 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2999 if (rc == -ENOENT) {
3001 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3007 user_ns = mnt_user_ns(path.mnt);
3009 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3010 sizeof(struct smb2_ea_info)) {
3015 rc = smb2_set_ea(&ea_buf->ea,
3016 le32_to_cpu(ea_buf->ccontext.DataLength),
3018 if (rc == -EOPNOTSUPP)
3023 } else if (!already_permitted) {
3024 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3025 * because execute(search) permission on a parent directory,
3026 * is already granted.
3028 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3029 rc = inode_permission(user_ns,
3030 d_inode(path.dentry),
3035 if ((daccess & FILE_DELETE_LE) ||
3036 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3037 rc = inode_permission(user_ns,
3038 d_inode(path.dentry->d_parent),
3039 MAY_EXEC | MAY_WRITE);
3046 rc = ksmbd_query_inode_status(path.dentry->d_parent);
3047 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3053 filp = dentry_open(&path, open_flags, current_cred());
3056 pr_err("dentry open for dir failed, rc %d\n", rc);
3061 if (!(open_flags & O_TRUNC))
3062 file_info = FILE_OPENED;
3064 file_info = FILE_OVERWRITTEN;
3066 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3068 file_info = FILE_SUPERSEDED;
3069 } else if (open_flags & O_CREAT) {
3070 file_info = FILE_CREATED;
3073 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3075 /* Obtain Volatile-ID */
3076 fp = ksmbd_open_fd(work, filp);
3084 /* Get Persistent-ID */
3085 ksmbd_open_durable_fd(fp);
3086 if (!has_file_id(fp->persistent_id)) {
3091 fp->cdoption = req->CreateDisposition;
3092 fp->daccess = daccess;
3093 fp->saccess = req->ShareAccess;
3094 fp->coption = req->CreateOptions;
3096 /* Set default windows and posix acls if creating new file */
3099 struct inode *inode = d_inode(path.dentry);
3101 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
3103 d_inode(path.dentry->d_parent));
3105 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3107 if (test_share_config_flag(work->tcon->share_conf,
3108 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3109 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3114 rc = smb2_create_sd_buffer(work, req, &path);
3117 ksmbd_vfs_set_init_posix_acl(user_ns,
3120 if (test_share_config_flag(work->tcon->share_conf,
3121 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3122 struct smb_fattr fattr;
3123 struct smb_ntsd *pntsd;
3124 int pntsd_size, ace_num = 0;
3126 ksmbd_acls_fattr(&fattr, user_ns, inode);
3128 ace_num = fattr.cf_acls->a_count;
3130 ace_num += fattr.cf_dacls->a_count;
3132 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3133 sizeof(struct smb_sid) * 3 +
3134 sizeof(struct smb_acl) +
3135 sizeof(struct smb_ace) * ace_num * 2,
3138 posix_acl_release(fattr.cf_acls);
3139 posix_acl_release(fattr.cf_dacls);
3143 rc = build_sec_desc(user_ns,
3148 &pntsd_size, &fattr);
3149 posix_acl_release(fattr.cf_acls);
3150 posix_acl_release(fattr.cf_dacls);
3156 rc = ksmbd_vfs_set_sd_xattr(conn,
3164 pr_err("failed to store ntacl in xattr : %d\n",
3173 rc = smb2_set_stream_name_xattr(&path,
3179 file_info = FILE_CREATED;
3182 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3183 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3185 /* fp should be searchable through ksmbd_inode.m_fp_list
3186 * after daccess, saccess, attrib_only, and stream are
3189 write_lock(&fp->f_ci->m_lock);
3190 list_add(&fp->node, &fp->f_ci->m_fp_list);
3191 write_unlock(&fp->f_ci->m_lock);
3193 /* Check delete pending among previous fp before oplock break */
3194 if (ksmbd_inode_pending_delete(fp)) {
3199 if (file_present || created)
3200 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3202 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3203 !fp->attrib_only && !stream_name) {
3204 smb_break_all_oplock(work, fp);
3208 req_op_level = req->RequestedOplockLevel;
3209 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3210 lc = parse_lease_state(req, S_ISDIR(file_inode(filp)->i_mode));
3212 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3213 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3214 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3215 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3216 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3221 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3223 * Compare parent lease using parent key. If there is no
3224 * a lease that has same parent key, Send lease break
3227 smb_send_parent_lease_break_noti(fp, lc);
3229 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3231 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3232 name, req_op_level, lc->req_state);
3233 rc = find_same_lease_key(sess, fp->f_ci, lc);
3236 } else if (open_flags == O_RDONLY &&
3237 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3238 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3239 req_op_level = SMB2_OPLOCK_LEVEL_II;
3241 rc = smb_grant_oplock(work, req_op_level,
3242 fp->persistent_id, fp,
3243 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3249 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3250 ksmbd_fd_set_delete_on_close(fp, file_info);
3252 if (need_truncate) {
3253 rc = smb2_create_truncate(&fp->filp->f_path);
3258 if (req->CreateContextsOffset) {
3259 struct create_alloc_size_req *az_req;
3261 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3262 SMB2_CREATE_ALLOCATION_SIZE, 4);
3263 if (IS_ERR(az_req)) {
3264 rc = PTR_ERR(az_req);
3266 } else if (az_req) {
3270 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3271 le32_to_cpu(az_req->ccontext.DataLength) <
3272 sizeof(struct create_alloc_size_req)) {
3276 alloc_size = le64_to_cpu(az_req->AllocationSize);
3278 "request smb2 create allocate size : %llu\n",
3280 smb_break_all_levII_oplock(work, fp, 1);
3281 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3285 "vfs_fallocate is failed : %d\n",
3289 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3290 if (IS_ERR(context)) {
3291 rc = PTR_ERR(context);
3293 } else if (context) {
3294 ksmbd_debug(SMB, "get query on disk id context\n");
3299 rc = ksmbd_vfs_getattr(&path, &stat);
3303 if (stat.result_mask & STATX_BTIME)
3304 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3306 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3307 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3309 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3312 smb2_update_xattrs(tcon, &path, fp);
3314 smb2_new_xattrs(tcon, &path, fp);
3316 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3318 rsp->StructureSize = cpu_to_le16(89);
3320 opinfo = rcu_dereference(fp->f_opinfo);
3321 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3324 rsp->CreateAction = cpu_to_le32(file_info);
3325 rsp->CreationTime = cpu_to_le64(fp->create_time);
3326 time = ksmbd_UnixTimeToNT(stat.atime);
3327 rsp->LastAccessTime = cpu_to_le64(time);
3328 time = ksmbd_UnixTimeToNT(stat.mtime);
3329 rsp->LastWriteTime = cpu_to_le64(time);
3330 time = ksmbd_UnixTimeToNT(stat.ctime);
3331 rsp->ChangeTime = cpu_to_le64(time);
3332 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3333 cpu_to_le64(stat.blocks << 9);
3334 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3335 rsp->FileAttributes = fp->f_ci->m_fattr;
3339 rsp->PersistentFileId = fp->persistent_id;
3340 rsp->VolatileFileId = fp->volatile_id;
3342 rsp->CreateContextsOffset = 0;
3343 rsp->CreateContextsLength = 0;
3344 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3346 /* If lease is request send lease context response */
3347 if (opinfo && opinfo->is_lease) {
3348 struct create_context *lease_ccontext;
3350 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3351 name, opinfo->o_lease->state);
3352 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3354 lease_ccontext = (struct create_context *)rsp->Buffer;
3356 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3357 le32_add_cpu(&rsp->CreateContextsLength,
3358 conn->vals->create_lease_size);
3359 iov_len += conn->vals->create_lease_size;
3360 next_ptr = &lease_ccontext->Next;
3361 next_off = conn->vals->create_lease_size;
3364 if (maximal_access_ctxt) {
3365 struct create_context *mxac_ccontext;
3367 if (maximal_access == 0)
3368 ksmbd_vfs_query_maximal_access(user_ns,
3371 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3372 le32_to_cpu(rsp->CreateContextsLength));
3374 create_mxac_rsp_buf(rsp->Buffer +
3375 le32_to_cpu(rsp->CreateContextsLength),
3376 le32_to_cpu(maximal_access));
3377 le32_add_cpu(&rsp->CreateContextsLength,
3378 conn->vals->create_mxac_size);
3379 iov_len += conn->vals->create_mxac_size;
3381 *next_ptr = cpu_to_le32(next_off);
3382 next_ptr = &mxac_ccontext->Next;
3383 next_off = conn->vals->create_mxac_size;
3386 if (query_disk_id) {
3387 struct create_context *disk_id_ccontext;
3389 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3390 le32_to_cpu(rsp->CreateContextsLength));
3392 create_disk_id_rsp_buf(rsp->Buffer +
3393 le32_to_cpu(rsp->CreateContextsLength),
3394 stat.ino, tcon->id);
3395 le32_add_cpu(&rsp->CreateContextsLength,
3396 conn->vals->create_disk_id_size);
3397 iov_len += conn->vals->create_disk_id_size;
3399 *next_ptr = cpu_to_le32(next_off);
3400 next_ptr = &disk_id_ccontext->Next;
3401 next_off = conn->vals->create_disk_id_size;
3406 create_posix_rsp_buf(rsp->Buffer +
3407 le32_to_cpu(rsp->CreateContextsLength),
3409 le32_add_cpu(&rsp->CreateContextsLength,
3410 conn->vals->create_posix_size);
3411 iov_len += conn->vals->create_posix_size;
3413 *next_ptr = cpu_to_le32(next_off);
3416 if (contxt_cnt > 0) {
3417 rsp->CreateContextsOffset =
3418 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3422 if (rc && (file_present || created))
3423 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3426 ksmbd_revert_fsids(work);
3430 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3431 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3435 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3436 else if (rc == -EOPNOTSUPP)
3437 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3438 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3439 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3440 else if (rc == -ENOENT)
3441 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3442 else if (rc == -EPERM)
3443 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3444 else if (rc == -EBUSY)
3445 rsp->hdr.Status = STATUS_DELETE_PENDING;
3446 else if (rc == -EBADF)
3447 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3448 else if (rc == -ENOEXEC)
3449 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3450 else if (rc == -ENXIO)
3451 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3452 else if (rc == -EEXIST)
3453 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3454 else if (rc == -EMFILE)
3455 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3456 if (!rsp->hdr.Status)
3457 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3460 ksmbd_fd_put(work, fp);
3461 smb2_set_err_rsp(work);
3462 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3471 static int readdir_info_level_struct_sz(int info_level)
3473 switch (info_level) {
3474 case FILE_FULL_DIRECTORY_INFORMATION:
3475 return sizeof(struct file_full_directory_info);
3476 case FILE_BOTH_DIRECTORY_INFORMATION:
3477 return sizeof(struct file_both_directory_info);
3478 case FILE_DIRECTORY_INFORMATION:
3479 return sizeof(struct file_directory_info);
3480 case FILE_NAMES_INFORMATION:
3481 return sizeof(struct file_names_info);
3482 case FILEID_FULL_DIRECTORY_INFORMATION:
3483 return sizeof(struct file_id_full_dir_info);
3484 case FILEID_BOTH_DIRECTORY_INFORMATION:
3485 return sizeof(struct file_id_both_directory_info);
3486 case SMB_FIND_FILE_POSIX_INFO:
3487 return sizeof(struct smb2_posix_info);
3493 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3495 switch (info_level) {
3496 case FILE_FULL_DIRECTORY_INFORMATION:
3498 struct file_full_directory_info *ffdinfo;
3500 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3501 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3502 d_info->name = ffdinfo->FileName;
3503 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3506 case FILE_BOTH_DIRECTORY_INFORMATION:
3508 struct file_both_directory_info *fbdinfo;
3510 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3511 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3512 d_info->name = fbdinfo->FileName;
3513 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3516 case FILE_DIRECTORY_INFORMATION:
3518 struct file_directory_info *fdinfo;
3520 fdinfo = (struct file_directory_info *)d_info->rptr;
3521 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3522 d_info->name = fdinfo->FileName;
3523 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3526 case FILE_NAMES_INFORMATION:
3528 struct file_names_info *fninfo;
3530 fninfo = (struct file_names_info *)d_info->rptr;
3531 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3532 d_info->name = fninfo->FileName;
3533 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3536 case FILEID_FULL_DIRECTORY_INFORMATION:
3538 struct file_id_full_dir_info *dinfo;
3540 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3541 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3542 d_info->name = dinfo->FileName;
3543 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3546 case FILEID_BOTH_DIRECTORY_INFORMATION:
3548 struct file_id_both_directory_info *fibdinfo;
3550 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3551 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3552 d_info->name = fibdinfo->FileName;
3553 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3556 case SMB_FIND_FILE_POSIX_INFO:
3558 struct smb2_posix_info *posix_info;
3560 posix_info = (struct smb2_posix_info *)d_info->rptr;
3561 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3562 d_info->name = posix_info->name;
3563 d_info->name_len = le32_to_cpu(posix_info->name_len);
3572 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3574 * @conn: connection instance
3575 * @info_level: smb information level
3576 * @d_info: structure included variables for query dir
3577 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3579 * if directory has many entries, find first can't read it fully.
3580 * find next might be called multiple times to read remaining dir entries
3582 * Return: 0 on success, otherwise error
3584 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3585 struct ksmbd_dir_info *d_info,
3586 struct ksmbd_kstat *ksmbd_kstat)
3588 int next_entry_offset = 0;
3592 int struct_sz, rc = 0;
3594 conv_name = ksmbd_convert_dir_info_name(d_info,
3600 /* Somehow the name has only terminating NULL bytes */
3603 goto free_conv_name;
3606 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3607 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3608 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3610 if (next_entry_offset > d_info->out_buf_len) {
3611 d_info->out_buf_len = 0;
3613 goto free_conv_name;
3616 kstat = d_info->wptr;
3617 if (info_level != FILE_NAMES_INFORMATION)
3618 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3620 switch (info_level) {
3621 case FILE_FULL_DIRECTORY_INFORMATION:
3623 struct file_full_directory_info *ffdinfo;
3625 ffdinfo = (struct file_full_directory_info *)kstat;
3626 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3628 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3629 if (ffdinfo->EaSize)
3630 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3631 if (d_info->hide_dot_file && d_info->name[0] == '.')
3632 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3633 memcpy(ffdinfo->FileName, conv_name, conv_len);
3634 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3637 case FILE_BOTH_DIRECTORY_INFORMATION:
3639 struct file_both_directory_info *fbdinfo;
3641 fbdinfo = (struct file_both_directory_info *)kstat;
3642 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3644 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3645 if (fbdinfo->EaSize)
3646 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3647 fbdinfo->ShortNameLength = 0;
3648 fbdinfo->Reserved = 0;
3649 if (d_info->hide_dot_file && d_info->name[0] == '.')
3650 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3651 memcpy(fbdinfo->FileName, conv_name, conv_len);
3652 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3655 case FILE_DIRECTORY_INFORMATION:
3657 struct file_directory_info *fdinfo;
3659 fdinfo = (struct file_directory_info *)kstat;
3660 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3661 if (d_info->hide_dot_file && d_info->name[0] == '.')
3662 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3663 memcpy(fdinfo->FileName, conv_name, conv_len);
3664 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3667 case FILE_NAMES_INFORMATION:
3669 struct file_names_info *fninfo;
3671 fninfo = (struct file_names_info *)kstat;
3672 fninfo->FileNameLength = cpu_to_le32(conv_len);
3673 memcpy(fninfo->FileName, conv_name, conv_len);
3674 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3677 case FILEID_FULL_DIRECTORY_INFORMATION:
3679 struct file_id_full_dir_info *dinfo;
3681 dinfo = (struct file_id_full_dir_info *)kstat;
3682 dinfo->FileNameLength = cpu_to_le32(conv_len);
3684 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3686 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3687 dinfo->Reserved = 0;
3688 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3689 if (d_info->hide_dot_file && d_info->name[0] == '.')
3690 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3691 memcpy(dinfo->FileName, conv_name, conv_len);
3692 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3695 case FILEID_BOTH_DIRECTORY_INFORMATION:
3697 struct file_id_both_directory_info *fibdinfo;
3699 fibdinfo = (struct file_id_both_directory_info *)kstat;
3700 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3702 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3703 if (fibdinfo->EaSize)
3704 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3705 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3706 fibdinfo->ShortNameLength = 0;
3707 fibdinfo->Reserved = 0;
3708 fibdinfo->Reserved2 = cpu_to_le16(0);
3709 if (d_info->hide_dot_file && d_info->name[0] == '.')
3710 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3711 memcpy(fibdinfo->FileName, conv_name, conv_len);
3712 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3715 case SMB_FIND_FILE_POSIX_INFO:
3717 struct smb2_posix_info *posix_info;
3720 posix_info = (struct smb2_posix_info *)kstat;
3721 posix_info->Ignored = 0;
3722 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3723 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3724 posix_info->ChangeTime = cpu_to_le64(time);
3725 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3726 posix_info->LastAccessTime = cpu_to_le64(time);
3727 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3728 posix_info->LastWriteTime = cpu_to_le64(time);
3729 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3730 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3731 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3732 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3733 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3734 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3735 posix_info->DosAttributes =
3736 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3737 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3738 if (d_info->hide_dot_file && d_info->name[0] == '.')
3739 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3741 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3742 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3743 * sub_auth(4 * 1(num_subauth)) + RID(4).
3745 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3746 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3747 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3748 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3749 memcpy(posix_info->name, conv_name, conv_len);
3750 posix_info->name_len = cpu_to_le32(conv_len);
3751 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3755 } /* switch (info_level) */
3757 d_info->last_entry_offset = d_info->data_count;
3758 d_info->data_count += next_entry_offset;
3759 d_info->out_buf_len -= next_entry_offset;
3760 d_info->wptr += next_entry_offset;
3763 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3764 info_level, d_info->out_buf_len,
3765 next_entry_offset, d_info->data_count);
3772 struct smb2_query_dir_private {
3773 struct ksmbd_work *work;
3774 char *search_pattern;
3775 struct ksmbd_file *dir_fp;
3777 struct ksmbd_dir_info *d_info;
3781 static void lock_dir(struct ksmbd_file *dir_fp)
3783 struct dentry *dir = dir_fp->filp->f_path.dentry;
3785 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3788 static void unlock_dir(struct ksmbd_file *dir_fp)
3790 struct dentry *dir = dir_fp->filp->f_path.dentry;
3792 inode_unlock(d_inode(dir));
3795 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3797 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3799 struct ksmbd_kstat ksmbd_kstat;
3803 for (i = 0; i < priv->d_info->num_entry; i++) {
3804 struct dentry *dent;
3806 if (dentry_name(priv->d_info, priv->info_level))
3809 lock_dir(priv->dir_fp);
3810 dent = lookup_one(user_ns, priv->d_info->name,
3811 priv->dir_fp->filp->f_path.dentry,
3812 priv->d_info->name_len);
3813 unlock_dir(priv->dir_fp);
3816 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3821 if (unlikely(d_is_negative(dent))) {
3823 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3824 priv->d_info->name);
3828 ksmbd_kstat.kstat = &kstat;
3829 if (priv->info_level != FILE_NAMES_INFORMATION)
3830 ksmbd_vfs_fill_dentry_attrs(priv->work,
3835 rc = smb2_populate_readdir_entry(priv->work->conn,
3846 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3851 int next_entry_offset;
3853 struct_sz = readdir_info_level_struct_sz(info_level);
3854 if (struct_sz == -EOPNOTSUPP)
3857 conv_len = (d_info->name_len + 1) * 2;
3858 next_entry_offset = ALIGN(struct_sz + conv_len,
3859 KSMBD_DIR_INFO_ALIGNMENT);
3861 if (next_entry_offset > d_info->out_buf_len) {
3862 d_info->out_buf_len = 0;
3866 switch (info_level) {
3867 case FILE_FULL_DIRECTORY_INFORMATION:
3869 struct file_full_directory_info *ffdinfo;
3871 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3872 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3873 ffdinfo->FileName[d_info->name_len] = 0x00;
3874 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3875 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3878 case FILE_BOTH_DIRECTORY_INFORMATION:
3880 struct file_both_directory_info *fbdinfo;
3882 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3883 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3884 fbdinfo->FileName[d_info->name_len] = 0x00;
3885 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3886 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3889 case FILE_DIRECTORY_INFORMATION:
3891 struct file_directory_info *fdinfo;
3893 fdinfo = (struct file_directory_info *)d_info->wptr;
3894 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3895 fdinfo->FileName[d_info->name_len] = 0x00;
3896 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3897 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3900 case FILE_NAMES_INFORMATION:
3902 struct file_names_info *fninfo;
3904 fninfo = (struct file_names_info *)d_info->wptr;
3905 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3906 fninfo->FileName[d_info->name_len] = 0x00;
3907 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3908 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3911 case FILEID_FULL_DIRECTORY_INFORMATION:
3913 struct file_id_full_dir_info *dinfo;
3915 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3916 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3917 dinfo->FileName[d_info->name_len] = 0x00;
3918 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3919 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3922 case FILEID_BOTH_DIRECTORY_INFORMATION:
3924 struct file_id_both_directory_info *fibdinfo;
3926 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3927 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3928 fibdinfo->FileName[d_info->name_len] = 0x00;
3929 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3930 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3933 case SMB_FIND_FILE_POSIX_INFO:
3935 struct smb2_posix_info *posix_info;
3937 posix_info = (struct smb2_posix_info *)d_info->wptr;
3938 memcpy(posix_info->name, d_info->name, d_info->name_len);
3939 posix_info->name[d_info->name_len] = 0x00;
3940 posix_info->name_len = cpu_to_le32(d_info->name_len);
3941 posix_info->NextEntryOffset =
3942 cpu_to_le32(next_entry_offset);
3945 } /* switch (info_level) */
3947 d_info->num_entry++;
3948 d_info->out_buf_len -= next_entry_offset;
3949 d_info->wptr += next_entry_offset;
3953 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3954 loff_t offset, u64 ino, unsigned int d_type)
3956 struct ksmbd_readdir_data *buf;
3957 struct smb2_query_dir_private *priv;
3958 struct ksmbd_dir_info *d_info;
3961 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3962 priv = buf->private;
3963 d_info = priv->d_info;
3965 /* dot and dotdot entries are already reserved */
3966 if (!strcmp(".", name) || !strcmp("..", name))
3968 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3970 if (!match_pattern(name, namlen, priv->search_pattern))
3973 d_info->name = name;
3974 d_info->name_len = namlen;
3975 rc = reserve_populate_dentry(d_info, priv->info_level);
3978 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3979 d_info->out_buf_len = 0;
3983 static int verify_info_level(int info_level)
3985 switch (info_level) {
3986 case FILE_FULL_DIRECTORY_INFORMATION:
3987 case FILE_BOTH_DIRECTORY_INFORMATION:
3988 case FILE_DIRECTORY_INFORMATION:
3989 case FILE_NAMES_INFORMATION:
3990 case FILEID_FULL_DIRECTORY_INFORMATION:
3991 case FILEID_BOTH_DIRECTORY_INFORMATION:
3992 case SMB_FIND_FILE_POSIX_INFO:
4001 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4005 free_len = (int)(work->response_sz -
4006 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4010 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4011 unsigned short hdr2_len,
4012 unsigned int out_buf_len)
4016 if (out_buf_len > work->conn->vals->max_trans_size)
4019 free_len = smb2_resp_buf_len(work, hdr2_len);
4023 return min_t(int, out_buf_len, free_len);
4026 int smb2_query_dir(struct ksmbd_work *work)
4028 struct ksmbd_conn *conn = work->conn;
4029 struct smb2_query_directory_req *req;
4030 struct smb2_query_directory_rsp *rsp;
4031 struct ksmbd_share_config *share = work->tcon->share_conf;
4032 struct ksmbd_file *dir_fp = NULL;
4033 struct ksmbd_dir_info d_info;
4035 char *srch_ptr = NULL;
4036 unsigned char srch_flag;
4038 struct smb2_query_dir_private query_dir_private = {NULL, };
4040 WORK_BUFFERS(work, req, rsp);
4042 if (ksmbd_override_fsids(work)) {
4043 rsp->hdr.Status = STATUS_NO_MEMORY;
4044 smb2_set_err_rsp(work);
4048 rc = verify_info_level(req->FileInformationClass);
4054 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4060 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4061 inode_permission(file_mnt_user_ns(dir_fp->filp),
4062 file_inode(dir_fp->filp),
4063 MAY_READ | MAY_EXEC)) {
4064 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4069 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4070 pr_err("can't do query dir for a file\n");
4075 srch_flag = req->Flags;
4076 srch_ptr = smb_strndup_from_utf16(req->Buffer,
4077 le16_to_cpu(req->FileNameLength), 1,
4079 if (IS_ERR(srch_ptr)) {
4080 ksmbd_debug(SMB, "Search Pattern not found\n");
4084 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4087 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4088 ksmbd_debug(SMB, "Restart directory scan\n");
4089 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4092 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4093 d_info.wptr = (char *)rsp->Buffer;
4094 d_info.rptr = (char *)rsp->Buffer;
4095 d_info.out_buf_len =
4096 smb2_calc_max_out_buf_len(work, 8,
4097 le32_to_cpu(req->OutputBufferLength));
4098 if (d_info.out_buf_len < 0) {
4102 d_info.flags = srch_flag;
4105 * reserve dot and dotdot entries in head of buffer
4108 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4109 dir_fp, &d_info, srch_ptr,
4110 smb2_populate_readdir_entry);
4116 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4117 d_info.hide_dot_file = true;
4119 buffer_sz = d_info.out_buf_len;
4120 d_info.rptr = d_info.wptr;
4121 query_dir_private.work = work;
4122 query_dir_private.search_pattern = srch_ptr;
4123 query_dir_private.dir_fp = dir_fp;
4124 query_dir_private.d_info = &d_info;
4125 query_dir_private.info_level = req->FileInformationClass;
4126 dir_fp->readdir_data.private = &query_dir_private;
4127 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4129 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4131 * req->OutputBufferLength is too small to contain even one entry.
4132 * In this case, it immediately returns OutputBufferLength 0 to client.
4134 if (!d_info.out_buf_len && !d_info.num_entry)
4136 if (rc > 0 || rc == -ENOSPC)
4141 d_info.wptr = d_info.rptr;
4142 d_info.out_buf_len = buffer_sz;
4143 rc = process_query_dir_entries(&query_dir_private);
4147 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4148 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4149 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4151 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4152 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4154 rsp->StructureSize = cpu_to_le16(9);
4155 rsp->OutputBufferOffset = cpu_to_le16(0);
4156 rsp->OutputBufferLength = cpu_to_le32(0);
4158 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4159 sizeof(struct smb2_query_directory_rsp));
4164 ((struct file_directory_info *)
4165 ((char *)rsp->Buffer + d_info.last_entry_offset))
4166 ->NextEntryOffset = 0;
4167 if (d_info.data_count >= d_info.last_entry_off_align)
4168 d_info.data_count -= d_info.last_entry_off_align;
4170 rsp->StructureSize = cpu_to_le16(9);
4171 rsp->OutputBufferOffset = cpu_to_le16(72);
4172 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4173 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4174 offsetof(struct smb2_query_directory_rsp, Buffer) +
4181 ksmbd_fd_put(work, dir_fp);
4182 ksmbd_revert_fsids(work);
4186 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4191 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4192 else if (rc == -EACCES)
4193 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4194 else if (rc == -ENOENT)
4195 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4196 else if (rc == -EBADF)
4197 rsp->hdr.Status = STATUS_FILE_CLOSED;
4198 else if (rc == -ENOMEM)
4199 rsp->hdr.Status = STATUS_NO_MEMORY;
4200 else if (rc == -EFAULT)
4201 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4202 else if (rc == -EIO)
4203 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4204 if (!rsp->hdr.Status)
4205 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4207 smb2_set_err_rsp(work);
4208 ksmbd_fd_put(work, dir_fp);
4209 ksmbd_revert_fsids(work);
4214 * buffer_check_err() - helper function to check buffer errors
4215 * @reqOutputBufferLength: max buffer length expected in command response
4216 * @rsp: query info response buffer contains output buffer length
4217 * @rsp_org: base response buffer pointer in case of chained response
4219 * Return: 0 on success, otherwise error
4221 static int buffer_check_err(int reqOutputBufferLength,
4222 struct smb2_query_info_rsp *rsp,
4225 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4226 pr_err("Invalid Buffer Size Requested\n");
4227 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4228 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4234 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4237 struct smb2_file_standard_info *sinfo;
4239 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4241 sinfo->AllocationSize = cpu_to_le64(4096);
4242 sinfo->EndOfFile = cpu_to_le64(0);
4243 sinfo->NumberOfLinks = cpu_to_le32(1);
4244 sinfo->DeletePending = 1;
4245 sinfo->Directory = 0;
4246 rsp->OutputBufferLength =
4247 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4250 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4253 struct smb2_file_internal_info *file_info;
4255 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4257 /* any unique number */
4258 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4259 rsp->OutputBufferLength =
4260 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4263 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4264 struct smb2_query_info_req *req,
4265 struct smb2_query_info_rsp *rsp,
4272 * Windows can sometime send query file info request on
4273 * pipe without opening it, checking error condition here
4275 id = req->VolatileFileId;
4276 if (!ksmbd_session_rpc_method(sess, id))
4279 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4280 req->FileInfoClass, req->VolatileFileId);
4282 switch (req->FileInfoClass) {
4283 case FILE_STANDARD_INFORMATION:
4284 get_standard_info_pipe(rsp, rsp_org);
4285 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4288 case FILE_INTERNAL_INFORMATION:
4289 get_internal_info_pipe(rsp, id, rsp_org);
4290 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4294 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4295 req->FileInfoClass);
4302 * smb2_get_ea() - handler for smb2 get extended attribute command
4303 * @work: smb work containing query info command buffer
4304 * @fp: ksmbd_file pointer
4305 * @req: get extended attribute request
4306 * @rsp: response buffer pointer
4307 * @rsp_org: base response buffer pointer in case of chained response
4309 * Return: 0 on success, otherwise error
4311 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4312 struct smb2_query_info_req *req,
4313 struct smb2_query_info_rsp *rsp, void *rsp_org)
4315 struct smb2_ea_info *eainfo, *prev_eainfo;
4316 char *name, *ptr, *xattr_list = NULL, *buf;
4317 int rc, name_len, value_len, xattr_list_len, idx;
4318 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4319 struct smb2_ea_info_req *ea_req = NULL;
4320 const struct path *path;
4321 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4323 if (!(fp->daccess & FILE_READ_EA_LE)) {
4324 pr_err("Not permitted to read ext attr : 0x%x\n",
4329 path = &fp->filp->f_path;
4330 /* single EA entry is requested with given user.* name */
4331 if (req->InputBufferLength) {
4332 if (le32_to_cpu(req->InputBufferLength) <
4333 sizeof(struct smb2_ea_info_req))
4336 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4338 /* need to send all EAs, if no specific EA is requested*/
4339 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4341 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4342 le32_to_cpu(req->Flags));
4346 smb2_calc_max_out_buf_len(work, 8,
4347 le32_to_cpu(req->OutputBufferLength));
4348 if (buf_free_len < 0)
4351 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4353 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4355 } else if (!rc) { /* there is no EA in the file */
4356 ksmbd_debug(SMB, "no ea data in the file\n");
4359 xattr_list_len = rc;
4361 ptr = (char *)rsp->Buffer;
4362 eainfo = (struct smb2_ea_info *)ptr;
4363 prev_eainfo = eainfo;
4366 while (idx < xattr_list_len) {
4367 name = xattr_list + idx;
4368 name_len = strlen(name);
4370 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4371 idx += name_len + 1;
4374 * CIFS does not support EA other than user.* namespace,
4375 * still keep the framework generic, to list other attrs
4378 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4381 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4385 if (req->InputBufferLength &&
4386 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4387 ea_req->EaNameLength))
4390 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4391 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4394 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4395 name_len -= XATTR_USER_PREFIX_LEN;
4397 ptr = eainfo->name + name_len + 1;
4398 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4400 /* bailout if xattr can't fit in buf_free_len */
4401 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4403 if (value_len <= 0) {
4405 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4409 buf_free_len -= value_len;
4410 if (buf_free_len < 0) {
4415 memcpy(ptr, buf, value_len);
4420 eainfo->EaNameLength = name_len;
4422 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4423 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4426 memcpy(eainfo->name, name, name_len);
4428 eainfo->name[name_len] = '\0';
4429 eainfo->EaValueLength = cpu_to_le16(value_len);
4430 next_offset = offsetof(struct smb2_ea_info, name) +
4431 name_len + 1 + value_len;
4433 /* align next xattr entry at 4 byte bundary */
4434 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4435 if (alignment_bytes) {
4436 memset(ptr, '\0', alignment_bytes);
4437 ptr += alignment_bytes;
4438 next_offset += alignment_bytes;
4439 buf_free_len -= alignment_bytes;
4441 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4442 prev_eainfo = eainfo;
4443 eainfo = (struct smb2_ea_info *)ptr;
4444 rsp_data_cnt += next_offset;
4446 if (req->InputBufferLength) {
4447 ksmbd_debug(SMB, "single entry requested\n");
4452 /* no more ea entries */
4453 prev_eainfo->NextEntryOffset = 0;
4456 if (rsp_data_cnt == 0)
4457 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4458 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4464 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4465 struct ksmbd_file *fp, void *rsp_org)
4467 struct smb2_file_access_info *file_info;
4469 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4470 file_info->AccessFlags = fp->daccess;
4471 rsp->OutputBufferLength =
4472 cpu_to_le32(sizeof(struct smb2_file_access_info));
4475 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4476 struct ksmbd_file *fp, void *rsp_org)
4478 struct smb2_file_basic_info *basic_info;
4482 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4483 pr_err("no right to read the attributes : 0x%x\n",
4488 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4489 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4491 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4492 time = ksmbd_UnixTimeToNT(stat.atime);
4493 basic_info->LastAccessTime = cpu_to_le64(time);
4494 time = ksmbd_UnixTimeToNT(stat.mtime);
4495 basic_info->LastWriteTime = cpu_to_le64(time);
4496 time = ksmbd_UnixTimeToNT(stat.ctime);
4497 basic_info->ChangeTime = cpu_to_le64(time);
4498 basic_info->Attributes = fp->f_ci->m_fattr;
4499 basic_info->Pad1 = 0;
4500 rsp->OutputBufferLength =
4501 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4505 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4506 struct ksmbd_file *fp, void *rsp_org)
4508 struct smb2_file_standard_info *sinfo;
4509 unsigned int delete_pending;
4510 struct inode *inode;
4513 inode = file_inode(fp->filp);
4514 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4516 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4517 delete_pending = ksmbd_inode_pending_delete(fp);
4519 sinfo->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4520 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4521 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4522 sinfo->DeletePending = delete_pending;
4523 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4524 rsp->OutputBufferLength =
4525 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4528 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4531 struct smb2_file_alignment_info *file_info;
4533 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4534 file_info->AlignmentRequirement = 0;
4535 rsp->OutputBufferLength =
4536 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4539 static int get_file_all_info(struct ksmbd_work *work,
4540 struct smb2_query_info_rsp *rsp,
4541 struct ksmbd_file *fp,
4544 struct ksmbd_conn *conn = work->conn;
4545 struct smb2_file_all_info *file_info;
4546 unsigned int delete_pending;
4547 struct inode *inode;
4553 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4554 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4559 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4560 if (IS_ERR(filename))
4561 return PTR_ERR(filename);
4563 inode = file_inode(fp->filp);
4564 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4566 ksmbd_debug(SMB, "filename = %s\n", filename);
4567 delete_pending = ksmbd_inode_pending_delete(fp);
4568 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4570 file_info->CreationTime = cpu_to_le64(fp->create_time);
4571 time = ksmbd_UnixTimeToNT(stat.atime);
4572 file_info->LastAccessTime = cpu_to_le64(time);
4573 time = ksmbd_UnixTimeToNT(stat.mtime);
4574 file_info->LastWriteTime = cpu_to_le64(time);
4575 time = ksmbd_UnixTimeToNT(stat.ctime);
4576 file_info->ChangeTime = cpu_to_le64(time);
4577 file_info->Attributes = fp->f_ci->m_fattr;
4578 file_info->Pad1 = 0;
4579 file_info->AllocationSize =
4580 cpu_to_le64(inode->i_blocks << 9);
4581 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4582 file_info->NumberOfLinks =
4583 cpu_to_le32(get_nlink(&stat) - delete_pending);
4584 file_info->DeletePending = delete_pending;
4585 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4586 file_info->Pad2 = 0;
4587 file_info->IndexNumber = cpu_to_le64(stat.ino);
4588 file_info->EASize = 0;
4589 file_info->AccessFlags = fp->daccess;
4590 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4591 file_info->Mode = fp->coption;
4592 file_info->AlignmentRequirement = 0;
4593 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4594 PATH_MAX, conn->local_nls, 0);
4596 file_info->FileNameLength = cpu_to_le32(conv_len);
4597 rsp->OutputBufferLength =
4598 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4603 static void get_file_alternate_info(struct ksmbd_work *work,
4604 struct smb2_query_info_rsp *rsp,
4605 struct ksmbd_file *fp,
4608 struct ksmbd_conn *conn = work->conn;
4609 struct smb2_file_alt_name_info *file_info;
4610 struct dentry *dentry = fp->filp->f_path.dentry;
4613 spin_lock(&dentry->d_lock);
4614 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4615 conv_len = ksmbd_extract_shortname(conn,
4616 dentry->d_name.name,
4617 file_info->FileName);
4618 spin_unlock(&dentry->d_lock);
4619 file_info->FileNameLength = cpu_to_le32(conv_len);
4620 rsp->OutputBufferLength =
4621 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4624 static void get_file_stream_info(struct ksmbd_work *work,
4625 struct smb2_query_info_rsp *rsp,
4626 struct ksmbd_file *fp,
4629 struct ksmbd_conn *conn = work->conn;
4630 struct smb2_file_stream_info *file_info;
4631 char *stream_name, *xattr_list = NULL, *stream_buf;
4633 const struct path *path = &fp->filp->f_path;
4634 ssize_t xattr_list_len;
4635 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4637 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4639 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4641 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4644 smb2_calc_max_out_buf_len(work, 8,
4645 le32_to_cpu(req->OutputBufferLength));
4646 if (buf_free_len < 0)
4649 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4650 if (xattr_list_len < 0) {
4652 } else if (!xattr_list_len) {
4653 ksmbd_debug(SMB, "empty xattr in the file\n");
4657 while (idx < xattr_list_len) {
4658 stream_name = xattr_list + idx;
4659 streamlen = strlen(stream_name);
4660 idx += streamlen + 1;
4662 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4664 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4665 STREAM_PREFIX, STREAM_PREFIX_LEN))
4668 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4670 streamlen = stream_name_len;
4674 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4678 streamlen = snprintf(stream_buf, streamlen + 1,
4679 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4681 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4682 if (next > buf_free_len) {
4687 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4688 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4689 stream_buf, streamlen,
4690 conn->local_nls, 0);
4693 file_info->StreamNameLength = cpu_to_le32(streamlen);
4694 file_info->StreamSize = cpu_to_le64(stream_name_len);
4695 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4698 buf_free_len -= next;
4699 file_info->NextEntryOffset = cpu_to_le32(next);
4703 if (!S_ISDIR(stat.mode) &&
4704 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4705 file_info = (struct smb2_file_stream_info *)
4706 &rsp->Buffer[nbytes];
4707 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4708 "::$DATA", 7, conn->local_nls, 0);
4710 file_info->StreamNameLength = cpu_to_le32(streamlen);
4711 file_info->StreamSize = cpu_to_le64(stat.size);
4712 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4713 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4716 /* last entry offset should be 0 */
4717 file_info->NextEntryOffset = 0;
4720 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4723 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4724 struct ksmbd_file *fp, void *rsp_org)
4726 struct smb2_file_internal_info *file_info;
4729 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4731 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4732 file_info->IndexNumber = cpu_to_le64(stat.ino);
4733 rsp->OutputBufferLength =
4734 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4737 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4738 struct ksmbd_file *fp, void *rsp_org)
4740 struct smb2_file_ntwrk_info *file_info;
4741 struct inode *inode;
4745 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4746 pr_err("no right to read the attributes : 0x%x\n",
4751 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4753 inode = file_inode(fp->filp);
4754 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4756 file_info->CreationTime = cpu_to_le64(fp->create_time);
4757 time = ksmbd_UnixTimeToNT(stat.atime);
4758 file_info->LastAccessTime = cpu_to_le64(time);
4759 time = ksmbd_UnixTimeToNT(stat.mtime);
4760 file_info->LastWriteTime = cpu_to_le64(time);
4761 time = ksmbd_UnixTimeToNT(stat.ctime);
4762 file_info->ChangeTime = cpu_to_le64(time);
4763 file_info->Attributes = fp->f_ci->m_fattr;
4764 file_info->AllocationSize =
4765 cpu_to_le64(inode->i_blocks << 9);
4766 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4767 file_info->Reserved = cpu_to_le32(0);
4768 rsp->OutputBufferLength =
4769 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4773 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4775 struct smb2_file_ea_info *file_info;
4777 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4778 file_info->EASize = 0;
4779 rsp->OutputBufferLength =
4780 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4783 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4784 struct ksmbd_file *fp, void *rsp_org)
4786 struct smb2_file_pos_info *file_info;
4788 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4789 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4790 rsp->OutputBufferLength =
4791 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4794 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4795 struct ksmbd_file *fp, void *rsp_org)
4797 struct smb2_file_mode_info *file_info;
4799 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4800 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4801 rsp->OutputBufferLength =
4802 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4805 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4806 struct ksmbd_file *fp, void *rsp_org)
4808 struct smb2_file_comp_info *file_info;
4811 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4814 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4815 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4816 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4817 file_info->CompressionUnitShift = 0;
4818 file_info->ChunkShift = 0;
4819 file_info->ClusterShift = 0;
4820 memset(&file_info->Reserved[0], 0, 3);
4822 rsp->OutputBufferLength =
4823 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4826 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4827 struct ksmbd_file *fp, void *rsp_org)
4829 struct smb2_file_attr_tag_info *file_info;
4831 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4832 pr_err("no right to read the attributes : 0x%x\n",
4837 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4838 file_info->FileAttributes = fp->f_ci->m_fattr;
4839 file_info->ReparseTag = 0;
4840 rsp->OutputBufferLength =
4841 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4845 static void find_file_posix_info(struct smb2_query_info_rsp *rsp,
4846 struct ksmbd_file *fp, void *rsp_org)
4848 struct smb311_posix_qinfo *file_info;
4849 struct inode *inode = file_inode(fp->filp);
4850 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4851 vfsuid_t vfsuid = i_uid_into_vfsuid(user_ns, inode);
4852 vfsgid_t vfsgid = i_gid_into_vfsgid(user_ns, inode);
4854 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4856 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4857 file_info->CreationTime = cpu_to_le64(fp->create_time);
4858 time = ksmbd_UnixTimeToNT(inode->i_atime);
4859 file_info->LastAccessTime = cpu_to_le64(time);
4860 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4861 file_info->LastWriteTime = cpu_to_le64(time);
4862 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4863 file_info->ChangeTime = cpu_to_le64(time);
4864 file_info->DosAttributes = fp->f_ci->m_fattr;
4865 file_info->Inode = cpu_to_le64(inode->i_ino);
4866 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4867 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4868 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4869 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4870 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4873 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4874 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4875 * sub_auth(4 * 1(num_subauth)) + RID(4).
4877 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4878 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4879 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4880 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4882 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4885 static int smb2_get_info_file(struct ksmbd_work *work,
4886 struct smb2_query_info_req *req,
4887 struct smb2_query_info_rsp *rsp)
4889 struct ksmbd_file *fp;
4890 int fileinfoclass = 0;
4892 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4894 if (test_share_config_flag(work->tcon->share_conf,
4895 KSMBD_SHARE_FLAG_PIPE)) {
4896 /* smb2 info file called for pipe */
4897 return smb2_get_info_file_pipe(work->sess, req, rsp,
4898 work->response_buf);
4901 if (work->next_smb2_rcv_hdr_off) {
4902 if (!has_file_id(req->VolatileFileId)) {
4903 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4904 work->compound_fid);
4905 id = work->compound_fid;
4906 pid = work->compound_pfid;
4910 if (!has_file_id(id)) {
4911 id = req->VolatileFileId;
4912 pid = req->PersistentFileId;
4915 fp = ksmbd_lookup_fd_slow(work, id, pid);
4919 fileinfoclass = req->FileInfoClass;
4921 switch (fileinfoclass) {
4922 case FILE_ACCESS_INFORMATION:
4923 get_file_access_info(rsp, fp, work->response_buf);
4926 case FILE_BASIC_INFORMATION:
4927 rc = get_file_basic_info(rsp, fp, work->response_buf);
4930 case FILE_STANDARD_INFORMATION:
4931 get_file_standard_info(rsp, fp, work->response_buf);
4934 case FILE_ALIGNMENT_INFORMATION:
4935 get_file_alignment_info(rsp, work->response_buf);
4938 case FILE_ALL_INFORMATION:
4939 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4942 case FILE_ALTERNATE_NAME_INFORMATION:
4943 get_file_alternate_info(work, rsp, fp, work->response_buf);
4946 case FILE_STREAM_INFORMATION:
4947 get_file_stream_info(work, rsp, fp, work->response_buf);
4950 case FILE_INTERNAL_INFORMATION:
4951 get_file_internal_info(rsp, fp, work->response_buf);
4954 case FILE_NETWORK_OPEN_INFORMATION:
4955 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4958 case FILE_EA_INFORMATION:
4959 get_file_ea_info(rsp, work->response_buf);
4962 case FILE_FULL_EA_INFORMATION:
4963 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4966 case FILE_POSITION_INFORMATION:
4967 get_file_position_info(rsp, fp, work->response_buf);
4970 case FILE_MODE_INFORMATION:
4971 get_file_mode_info(rsp, fp, work->response_buf);
4974 case FILE_COMPRESSION_INFORMATION:
4975 get_file_compression_info(rsp, fp, work->response_buf);
4978 case FILE_ATTRIBUTE_TAG_INFORMATION:
4979 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4981 case SMB_FIND_FILE_POSIX_INFO:
4982 if (!work->tcon->posix_extensions) {
4983 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4986 find_file_posix_info(rsp, fp, work->response_buf);
4990 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4995 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4996 rsp, work->response_buf);
4997 ksmbd_fd_put(work, fp);
5001 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5002 struct smb2_query_info_req *req,
5003 struct smb2_query_info_rsp *rsp)
5005 struct ksmbd_session *sess = work->sess;
5006 struct ksmbd_conn *conn = work->conn;
5007 struct ksmbd_share_config *share = work->tcon->share_conf;
5008 int fsinfoclass = 0;
5009 struct kstatfs stfs;
5016 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5018 pr_err("cannot create vfs path\n");
5022 rc = vfs_statfs(&path, &stfs);
5024 pr_err("cannot do stat of path %s\n", share->path);
5029 fsinfoclass = req->FileInfoClass;
5031 switch (fsinfoclass) {
5032 case FS_DEVICE_INFORMATION:
5034 struct filesystem_device_info *info;
5036 info = (struct filesystem_device_info *)rsp->Buffer;
5038 info->DeviceType = cpu_to_le32(stfs.f_type);
5039 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
5040 rsp->OutputBufferLength = cpu_to_le32(8);
5043 case FS_ATTRIBUTE_INFORMATION:
5045 struct filesystem_attribute_info *info;
5048 info = (struct filesystem_attribute_info *)rsp->Buffer;
5049 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5050 FILE_PERSISTENT_ACLS |
5051 FILE_UNICODE_ON_DISK |
5052 FILE_CASE_PRESERVED_NAMES |
5053 FILE_CASE_SENSITIVE_SEARCH |
5054 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5056 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5058 if (test_share_config_flag(work->tcon->share_conf,
5059 KSMBD_SHARE_FLAG_STREAMS))
5060 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5062 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5063 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5064 "NTFS", PATH_MAX, conn->local_nls, 0);
5066 info->FileSystemNameLen = cpu_to_le32(len);
5067 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5068 rsp->OutputBufferLength = cpu_to_le32(sz);
5071 case FS_VOLUME_INFORMATION:
5073 struct filesystem_vol_info *info;
5075 unsigned int serial_crc = 0;
5077 info = (struct filesystem_vol_info *)(rsp->Buffer);
5078 info->VolumeCreationTime = 0;
5079 serial_crc = crc32_le(serial_crc, share->name,
5080 strlen(share->name));
5081 serial_crc = crc32_le(serial_crc, share->path,
5082 strlen(share->path));
5083 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5084 strlen(ksmbd_netbios_name()));
5085 /* Taking dummy value of serial number*/
5086 info->SerialNumber = cpu_to_le32(serial_crc);
5087 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5088 share->name, PATH_MAX,
5089 conn->local_nls, 0);
5091 info->VolumeLabelSize = cpu_to_le32(len);
5093 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5094 rsp->OutputBufferLength = cpu_to_le32(sz);
5097 case FS_SIZE_INFORMATION:
5099 struct filesystem_info *info;
5101 info = (struct filesystem_info *)(rsp->Buffer);
5102 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5103 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5104 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5105 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5106 rsp->OutputBufferLength = cpu_to_le32(24);
5109 case FS_FULL_SIZE_INFORMATION:
5111 struct smb2_fs_full_size_info *info;
5113 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5114 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5115 info->CallerAvailableAllocationUnits =
5116 cpu_to_le64(stfs.f_bavail);
5117 info->ActualAvailableAllocationUnits =
5118 cpu_to_le64(stfs.f_bfree);
5119 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5120 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5121 rsp->OutputBufferLength = cpu_to_le32(32);
5124 case FS_OBJECT_ID_INFORMATION:
5126 struct object_id_info *info;
5128 info = (struct object_id_info *)(rsp->Buffer);
5130 if (!user_guest(sess->user))
5131 memcpy(info->objid, user_passkey(sess->user), 16);
5133 memset(info->objid, 0, 16);
5135 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5136 info->extended_info.version = cpu_to_le32(1);
5137 info->extended_info.release = cpu_to_le32(1);
5138 info->extended_info.rel_date = 0;
5139 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5140 rsp->OutputBufferLength = cpu_to_le32(64);
5143 case FS_SECTOR_SIZE_INFORMATION:
5145 struct smb3_fs_ss_info *info;
5146 unsigned int sector_size =
5147 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5149 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5151 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5152 info->PhysicalBytesPerSectorForAtomicity =
5153 cpu_to_le32(sector_size);
5154 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5155 info->FSEffPhysicalBytesPerSectorForAtomicity =
5156 cpu_to_le32(sector_size);
5157 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5158 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5159 info->ByteOffsetForSectorAlignment = 0;
5160 info->ByteOffsetForPartitionAlignment = 0;
5161 rsp->OutputBufferLength = cpu_to_le32(28);
5164 case FS_CONTROL_INFORMATION:
5167 * TODO : The current implementation is based on
5168 * test result with win7(NTFS) server. It's need to
5169 * modify this to get valid Quota values
5172 struct smb2_fs_control_info *info;
5174 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5175 info->FreeSpaceStartFiltering = 0;
5176 info->FreeSpaceThreshold = 0;
5177 info->FreeSpaceStopFiltering = 0;
5178 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5179 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5181 rsp->OutputBufferLength = cpu_to_le32(48);
5184 case FS_POSIX_INFORMATION:
5186 struct filesystem_posix_info *info;
5188 if (!work->tcon->posix_extensions) {
5189 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5192 info = (struct filesystem_posix_info *)(rsp->Buffer);
5193 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5194 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5195 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5196 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5197 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5198 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5199 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5200 rsp->OutputBufferLength = cpu_to_le32(56);
5208 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5209 rsp, work->response_buf);
5214 static int smb2_get_info_sec(struct ksmbd_work *work,
5215 struct smb2_query_info_req *req,
5216 struct smb2_query_info_rsp *rsp)
5218 struct ksmbd_file *fp;
5219 struct user_namespace *user_ns;
5220 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5221 struct smb_fattr fattr = {{0}};
5222 struct inode *inode;
5223 __u32 secdesclen = 0;
5224 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5225 int addition_info = le32_to_cpu(req->AdditionalInformation);
5226 int rc = 0, ppntsd_size = 0;
5228 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5229 PROTECTED_DACL_SECINFO |
5230 UNPROTECTED_DACL_SECINFO)) {
5231 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5234 pntsd->revision = cpu_to_le16(1);
5235 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5236 pntsd->osidoffset = 0;
5237 pntsd->gsidoffset = 0;
5238 pntsd->sacloffset = 0;
5239 pntsd->dacloffset = 0;
5241 secdesclen = sizeof(struct smb_ntsd);
5242 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5247 if (work->next_smb2_rcv_hdr_off) {
5248 if (!has_file_id(req->VolatileFileId)) {
5249 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5250 work->compound_fid);
5251 id = work->compound_fid;
5252 pid = work->compound_pfid;
5256 if (!has_file_id(id)) {
5257 id = req->VolatileFileId;
5258 pid = req->PersistentFileId;
5261 fp = ksmbd_lookup_fd_slow(work, id, pid);
5265 user_ns = file_mnt_user_ns(fp->filp);
5266 inode = file_inode(fp->filp);
5267 ksmbd_acls_fattr(&fattr, user_ns, inode);
5269 if (test_share_config_flag(work->tcon->share_conf,
5270 KSMBD_SHARE_FLAG_ACL_XATTR))
5271 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5272 fp->filp->f_path.dentry,
5275 /* Check if sd buffer size exceeds response buffer size */
5276 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5277 rc = build_sec_desc(user_ns, pntsd, ppntsd, ppntsd_size,
5278 addition_info, &secdesclen, &fattr);
5279 posix_acl_release(fattr.cf_acls);
5280 posix_acl_release(fattr.cf_dacls);
5282 ksmbd_fd_put(work, fp);
5286 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5291 * smb2_query_info() - handler for smb2 query info command
5292 * @work: smb work containing query info request buffer
5294 * Return: 0 on success, otherwise error
5296 int smb2_query_info(struct ksmbd_work *work)
5298 struct smb2_query_info_req *req;
5299 struct smb2_query_info_rsp *rsp;
5302 WORK_BUFFERS(work, req, rsp);
5304 ksmbd_debug(SMB, "GOT query info request\n");
5306 switch (req->InfoType) {
5307 case SMB2_O_INFO_FILE:
5308 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5309 rc = smb2_get_info_file(work, req, rsp);
5311 case SMB2_O_INFO_FILESYSTEM:
5312 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5313 rc = smb2_get_info_filesystem(work, req, rsp);
5315 case SMB2_O_INFO_SECURITY:
5316 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5317 rc = smb2_get_info_sec(work, req, rsp);
5320 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5326 rsp->StructureSize = cpu_to_le16(9);
5327 rsp->OutputBufferOffset = cpu_to_le16(72);
5328 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5329 offsetof(struct smb2_query_info_rsp, Buffer) +
5330 le32_to_cpu(rsp->OutputBufferLength));
5335 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5336 else if (rc == -ENOENT)
5337 rsp->hdr.Status = STATUS_FILE_CLOSED;
5338 else if (rc == -EIO)
5339 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5340 else if (rc == -ENOMEM)
5341 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5342 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5343 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5344 smb2_set_err_rsp(work);
5346 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5354 * smb2_close_pipe() - handler for closing IPC pipe
5355 * @work: smb work containing close request buffer
5359 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5362 struct smb2_close_req *req;
5363 struct smb2_close_rsp *rsp;
5365 WORK_BUFFERS(work, req, rsp);
5367 id = req->VolatileFileId;
5368 ksmbd_session_rpc_close(work->sess, id);
5370 rsp->StructureSize = cpu_to_le16(60);
5373 rsp->CreationTime = 0;
5374 rsp->LastAccessTime = 0;
5375 rsp->LastWriteTime = 0;
5376 rsp->ChangeTime = 0;
5377 rsp->AllocationSize = 0;
5379 rsp->Attributes = 0;
5381 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5382 sizeof(struct smb2_close_rsp));
5386 * smb2_close() - handler for smb2 close file command
5387 * @work: smb work containing close request buffer
5391 int smb2_close(struct ksmbd_work *work)
5393 u64 volatile_id = KSMBD_NO_FID;
5395 struct smb2_close_req *req;
5396 struct smb2_close_rsp *rsp;
5397 struct ksmbd_conn *conn = work->conn;
5398 struct ksmbd_file *fp;
5399 struct inode *inode;
5403 WORK_BUFFERS(work, req, rsp);
5405 if (test_share_config_flag(work->tcon->share_conf,
5406 KSMBD_SHARE_FLAG_PIPE)) {
5407 ksmbd_debug(SMB, "IPC pipe close request\n");
5408 return smb2_close_pipe(work);
5411 sess_id = le64_to_cpu(req->hdr.SessionId);
5412 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5413 sess_id = work->compound_sid;
5415 work->compound_sid = 0;
5416 if (check_session_id(conn, sess_id)) {
5417 work->compound_sid = sess_id;
5419 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5420 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5421 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5426 if (work->next_smb2_rcv_hdr_off &&
5427 !has_file_id(req->VolatileFileId)) {
5428 if (!has_file_id(work->compound_fid)) {
5429 /* file already closed, return FILE_CLOSED */
5430 ksmbd_debug(SMB, "file already closed\n");
5431 rsp->hdr.Status = STATUS_FILE_CLOSED;
5436 "Compound request set FID = %llu:%llu\n",
5438 work->compound_pfid);
5439 volatile_id = work->compound_fid;
5441 /* file closed, stored id is not valid anymore */
5442 work->compound_fid = KSMBD_NO_FID;
5443 work->compound_pfid = KSMBD_NO_FID;
5446 volatile_id = req->VolatileFileId;
5448 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5450 rsp->StructureSize = cpu_to_le16(60);
5453 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5454 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5460 inode = file_inode(fp->filp);
5461 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5462 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5463 cpu_to_le64(inode->i_blocks << 9);
5464 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5465 rsp->Attributes = fp->f_ci->m_fattr;
5466 rsp->CreationTime = cpu_to_le64(fp->create_time);
5467 time = ksmbd_UnixTimeToNT(inode->i_atime);
5468 rsp->LastAccessTime = cpu_to_le64(time);
5469 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5470 rsp->LastWriteTime = cpu_to_le64(time);
5471 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5472 rsp->ChangeTime = cpu_to_le64(time);
5473 ksmbd_fd_put(work, fp);
5476 rsp->AllocationSize = 0;
5478 rsp->Attributes = 0;
5479 rsp->CreationTime = 0;
5480 rsp->LastAccessTime = 0;
5481 rsp->LastWriteTime = 0;
5482 rsp->ChangeTime = 0;
5485 err = ksmbd_close_fd(work, volatile_id);
5488 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5489 sizeof(struct smb2_close_rsp));
5492 if (rsp->hdr.Status == 0)
5493 rsp->hdr.Status = STATUS_FILE_CLOSED;
5494 smb2_set_err_rsp(work);
5501 * smb2_echo() - handler for smb2 echo(ping) command
5502 * @work: smb work containing echo request buffer
5506 int smb2_echo(struct ksmbd_work *work)
5508 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5510 if (work->next_smb2_rcv_hdr_off)
5511 rsp = ksmbd_resp_buf_next(work);
5513 rsp->StructureSize = cpu_to_le16(4);
5515 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5518 static int smb2_rename(struct ksmbd_work *work,
5519 struct ksmbd_file *fp,
5520 struct smb2_file_rename_info *file_info,
5521 struct nls_table *local_nls)
5523 struct ksmbd_share_config *share = fp->tcon->share_conf;
5524 char *new_name = NULL;
5527 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5528 new_name = smb2_get_name(file_info->FileName,
5529 le32_to_cpu(file_info->FileNameLength),
5531 if (IS_ERR(new_name))
5532 return PTR_ERR(new_name);
5534 if (strchr(new_name, ':')) {
5536 char *xattr_stream_name, *stream_name = NULL;
5537 size_t xattr_stream_size;
5540 rc = parse_stream_name(new_name, &stream_name, &s_type);
5544 len = strlen(new_name);
5545 if (len > 0 && new_name[len - 1] != '/') {
5546 pr_err("not allow base filename in rename\n");
5551 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5558 rc = ksmbd_vfs_setxattr(file_mnt_user_ns(fp->filp),
5563 pr_err("failed to store stream name in xattr: %d\n",
5572 ksmbd_debug(SMB, "new name %s\n", new_name);
5573 if (ksmbd_share_veto_filename(share, new_name)) {
5575 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5579 if (!file_info->ReplaceIfExists)
5580 flags = RENAME_NOREPLACE;
5582 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5584 smb_break_all_levII_oplock(work, fp, 0);
5590 static int smb2_create_link(struct ksmbd_work *work,
5591 struct ksmbd_share_config *share,
5592 struct smb2_file_link_info *file_info,
5593 unsigned int buf_len, struct file *filp,
5594 struct nls_table *local_nls)
5596 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5597 struct path path, parent_path;
5598 bool file_present = false;
5601 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5602 le32_to_cpu(file_info->FileNameLength))
5605 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5606 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5610 link_name = smb2_get_name(file_info->FileName,
5611 le32_to_cpu(file_info->FileNameLength),
5613 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5618 ksmbd_debug(SMB, "link name is %s\n", link_name);
5619 target_name = file_path(filp, pathname, PATH_MAX);
5620 if (IS_ERR(target_name)) {
5625 ksmbd_debug(SMB, "target name is %s\n", target_name);
5626 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5627 &parent_path, &path, 0);
5632 file_present = true;
5634 if (file_info->ReplaceIfExists) {
5636 rc = ksmbd_vfs_remove_file(work, &path);
5639 ksmbd_debug(SMB, "cannot delete %s\n",
5647 ksmbd_debug(SMB, "link already exists\n");
5652 rc = ksmbd_vfs_link(work, target_name, link_name);
5657 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
5659 if (!IS_ERR(link_name))
5665 static int set_file_basic_info(struct ksmbd_file *fp,
5666 struct smb2_file_basic_info *file_info,
5667 struct ksmbd_share_config *share)
5671 struct inode *inode;
5672 struct user_namespace *user_ns;
5675 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5680 inode = file_inode(filp);
5681 user_ns = file_mnt_user_ns(filp);
5683 if (file_info->CreationTime)
5684 fp->create_time = le64_to_cpu(file_info->CreationTime);
5686 if (file_info->LastAccessTime) {
5687 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5688 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5691 attrs.ia_valid |= ATTR_CTIME;
5692 if (file_info->ChangeTime)
5693 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5695 attrs.ia_ctime = inode->i_ctime;
5697 if (file_info->LastWriteTime) {
5698 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5699 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5702 if (file_info->Attributes) {
5703 if (!S_ISDIR(inode->i_mode) &&
5704 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5705 pr_err("can't change a file to a directory\n");
5709 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5710 fp->f_ci->m_fattr = file_info->Attributes |
5711 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5714 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5715 (file_info->CreationTime || file_info->Attributes)) {
5716 struct xattr_dos_attrib da = {0};
5719 da.itime = fp->itime;
5720 da.create_time = fp->create_time;
5721 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5722 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5723 XATTR_DOSINFO_ITIME;
5725 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns, &filp->f_path, &da,
5729 "failed to restore file attribute in EA\n");
5733 if (attrs.ia_valid) {
5734 struct dentry *dentry = filp->f_path.dentry;
5735 struct inode *inode = d_inode(dentry);
5737 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5741 inode->i_ctime = attrs.ia_ctime;
5742 attrs.ia_valid &= ~ATTR_CTIME;
5743 rc = notify_change(user_ns, dentry, &attrs, NULL);
5744 inode_unlock(inode);
5749 static int set_file_allocation_info(struct ksmbd_work *work,
5750 struct ksmbd_file *fp,
5751 struct smb2_file_alloc_info *file_alloc_info)
5754 * TODO : It's working fine only when store dos attributes
5755 * is not yes. need to implement a logic which works
5756 * properly with any smb.conf option
5760 struct inode *inode;
5764 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5767 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5768 AT_STATX_SYNC_AS_STAT);
5772 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5773 inode = file_inode(fp->filp);
5775 if (alloc_blks > stat.blocks) {
5776 smb_break_all_levII_oplock(work, fp, 1);
5777 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5779 if (rc && rc != -EOPNOTSUPP) {
5780 pr_err("vfs_fallocate is failed : %d\n", rc);
5783 } else if (alloc_blks < stat.blocks) {
5787 * Allocation size could be smaller than original one
5788 * which means allocated blocks in file should be
5789 * deallocated. use truncate to cut out it, but inode
5790 * size is also updated with truncate offset.
5791 * inode size is retained by backup inode size.
5793 size = i_size_read(inode);
5794 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5796 pr_err("truncate failed!, err %d\n", rc);
5799 if (size < alloc_blks * 512)
5800 i_size_write(inode, size);
5805 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5806 struct smb2_file_eof_info *file_eof_info)
5809 struct inode *inode;
5812 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5815 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5816 inode = file_inode(fp->filp);
5819 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5820 * on FAT32 shared device, truncate execution time is too long
5821 * and network error could cause from windows client. because
5822 * truncate of some filesystem like FAT32 fill zero data in
5825 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5826 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5827 rc = ksmbd_vfs_truncate(work, fp, newsize);
5829 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5838 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5839 struct smb2_file_rename_info *rename_info,
5840 unsigned int buf_len)
5842 if (!(fp->daccess & FILE_DELETE_LE)) {
5843 pr_err("no right to delete : 0x%x\n", fp->daccess);
5847 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5848 le32_to_cpu(rename_info->FileNameLength))
5851 if (!le32_to_cpu(rename_info->FileNameLength))
5854 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5857 static int set_file_disposition_info(struct ksmbd_file *fp,
5858 struct smb2_file_disposition_info *file_info)
5860 struct inode *inode;
5862 if (!(fp->daccess & FILE_DELETE_LE)) {
5863 pr_err("no right to delete : 0x%x\n", fp->daccess);
5867 inode = file_inode(fp->filp);
5868 if (file_info->DeletePending) {
5869 if (S_ISDIR(inode->i_mode) &&
5870 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5872 ksmbd_set_inode_pending_delete(fp);
5874 ksmbd_clear_inode_pending_delete(fp);
5879 static int set_file_position_info(struct ksmbd_file *fp,
5880 struct smb2_file_pos_info *file_info)
5882 loff_t current_byte_offset;
5883 unsigned long sector_size;
5884 struct inode *inode;
5886 inode = file_inode(fp->filp);
5887 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5888 sector_size = inode->i_sb->s_blocksize;
5890 if (current_byte_offset < 0 ||
5891 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5892 current_byte_offset & (sector_size - 1))) {
5893 pr_err("CurrentByteOffset is not valid : %llu\n",
5894 current_byte_offset);
5898 fp->filp->f_pos = current_byte_offset;
5902 static int set_file_mode_info(struct ksmbd_file *fp,
5903 struct smb2_file_mode_info *file_info)
5907 mode = file_info->Mode;
5909 if ((mode & ~FILE_MODE_INFO_MASK)) {
5910 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5915 * TODO : need to implement consideration for
5916 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5918 ksmbd_vfs_set_fadvise(fp->filp, mode);
5924 * smb2_set_info_file() - handler for smb2 set info command
5925 * @work: smb work containing set info command buffer
5926 * @fp: ksmbd_file pointer
5927 * @req: request buffer pointer
5928 * @share: ksmbd_share_config pointer
5930 * Return: 0 on success, otherwise error
5931 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5933 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5934 struct smb2_set_info_req *req,
5935 struct ksmbd_share_config *share)
5937 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5939 switch (req->FileInfoClass) {
5940 case FILE_BASIC_INFORMATION:
5942 if (buf_len < sizeof(struct smb2_file_basic_info))
5945 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5947 case FILE_ALLOCATION_INFORMATION:
5949 if (buf_len < sizeof(struct smb2_file_alloc_info))
5952 return set_file_allocation_info(work, fp,
5953 (struct smb2_file_alloc_info *)req->Buffer);
5955 case FILE_END_OF_FILE_INFORMATION:
5957 if (buf_len < sizeof(struct smb2_file_eof_info))
5960 return set_end_of_file_info(work, fp,
5961 (struct smb2_file_eof_info *)req->Buffer);
5963 case FILE_RENAME_INFORMATION:
5965 if (buf_len < sizeof(struct smb2_file_rename_info))
5968 return set_rename_info(work, fp,
5969 (struct smb2_file_rename_info *)req->Buffer,
5972 case FILE_LINK_INFORMATION:
5974 if (buf_len < sizeof(struct smb2_file_link_info))
5977 return smb2_create_link(work, work->tcon->share_conf,
5978 (struct smb2_file_link_info *)req->Buffer,
5980 work->conn->local_nls);
5982 case FILE_DISPOSITION_INFORMATION:
5984 if (buf_len < sizeof(struct smb2_file_disposition_info))
5987 return set_file_disposition_info(fp,
5988 (struct smb2_file_disposition_info *)req->Buffer);
5990 case FILE_FULL_EA_INFORMATION:
5992 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5993 pr_err("Not permitted to write ext attr: 0x%x\n",
5998 if (buf_len < sizeof(struct smb2_ea_info))
6001 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
6002 buf_len, &fp->filp->f_path, true);
6004 case FILE_POSITION_INFORMATION:
6006 if (buf_len < sizeof(struct smb2_file_pos_info))
6009 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
6011 case FILE_MODE_INFORMATION:
6013 if (buf_len < sizeof(struct smb2_file_mode_info))
6016 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6020 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6024 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6025 char *buffer, int buf_len)
6027 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6029 fp->saccess |= FILE_SHARE_DELETE_LE;
6031 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6032 buf_len, false, true);
6036 * smb2_set_info() - handler for smb2 set info command handler
6037 * @work: smb work containing set info request buffer
6039 * Return: 0 on success, otherwise error
6041 int smb2_set_info(struct ksmbd_work *work)
6043 struct smb2_set_info_req *req;
6044 struct smb2_set_info_rsp *rsp;
6045 struct ksmbd_file *fp = NULL;
6047 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6049 ksmbd_debug(SMB, "Received set info request\n");
6051 if (work->next_smb2_rcv_hdr_off) {
6052 req = ksmbd_req_buf_next(work);
6053 rsp = ksmbd_resp_buf_next(work);
6054 if (!has_file_id(req->VolatileFileId)) {
6055 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6056 work->compound_fid);
6057 id = work->compound_fid;
6058 pid = work->compound_pfid;
6061 req = smb2_get_msg(work->request_buf);
6062 rsp = smb2_get_msg(work->response_buf);
6065 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6066 ksmbd_debug(SMB, "User does not have write permission\n");
6067 pr_err("User does not have write permission\n");
6072 if (!has_file_id(id)) {
6073 id = req->VolatileFileId;
6074 pid = req->PersistentFileId;
6077 fp = ksmbd_lookup_fd_slow(work, id, pid);
6079 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6084 switch (req->InfoType) {
6085 case SMB2_O_INFO_FILE:
6086 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6087 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6089 case SMB2_O_INFO_SECURITY:
6090 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6091 if (ksmbd_override_fsids(work)) {
6095 rc = smb2_set_info_sec(fp,
6096 le32_to_cpu(req->AdditionalInformation),
6098 le32_to_cpu(req->BufferLength));
6099 ksmbd_revert_fsids(work);
6108 rsp->StructureSize = cpu_to_le16(2);
6109 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6110 sizeof(struct smb2_set_info_rsp));
6113 ksmbd_fd_put(work, fp);
6117 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6118 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6119 else if (rc == -EINVAL)
6120 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6121 else if (rc == -ESHARE)
6122 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6123 else if (rc == -ENOENT)
6124 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6125 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6126 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6127 else if (rc == -EAGAIN)
6128 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6129 else if (rc == -EBADF || rc == -ESTALE)
6130 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6131 else if (rc == -EEXIST)
6132 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6133 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6134 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6135 smb2_set_err_rsp(work);
6136 ksmbd_fd_put(work, fp);
6137 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6142 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6143 * @work: smb work containing read IPC pipe command buffer
6145 * Return: 0 on success, otherwise error
6147 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6149 int nbytes = 0, err;
6151 struct ksmbd_rpc_command *rpc_resp;
6152 struct smb2_read_req *req;
6153 struct smb2_read_rsp *rsp;
6155 WORK_BUFFERS(work, req, rsp);
6157 id = req->VolatileFileId;
6159 rpc_resp = ksmbd_rpc_read(work->sess, id);
6161 void *aux_payload_buf;
6163 if (rpc_resp->flags != KSMBD_RPC_OK) {
6169 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6170 if (!aux_payload_buf) {
6175 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6177 nbytes = rpc_resp->payload_sz;
6178 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6179 offsetof(struct smb2_read_rsp, Buffer),
6180 aux_payload_buf, nbytes);
6182 kvfree(aux_payload_buf);
6187 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6188 offsetof(struct smb2_read_rsp, Buffer));
6193 rsp->StructureSize = cpu_to_le16(17);
6194 rsp->DataOffset = 80;
6196 rsp->DataLength = cpu_to_le32(nbytes);
6197 rsp->DataRemaining = 0;
6202 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6203 smb2_set_err_rsp(work);
6208 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6209 struct smb2_buffer_desc_v1 *desc,
6211 __le16 ChannelInfoLength)
6213 unsigned int i, ch_count;
6215 if (work->conn->dialect == SMB30_PROT_ID &&
6216 Channel != SMB2_CHANNEL_RDMA_V1)
6219 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6220 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6221 for (i = 0; i < ch_count; i++) {
6222 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6224 le32_to_cpu(desc[i].token),
6225 le32_to_cpu(desc[i].length));
6231 work->need_invalidate_rkey =
6232 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6233 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6234 work->remote_key = le32_to_cpu(desc->token);
6238 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6239 struct smb2_read_req *req, void *data_buf,
6244 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6245 (struct smb2_buffer_desc_v1 *)
6246 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6247 le16_to_cpu(req->ReadChannelInfoLength));
6255 * smb2_read() - handler for smb2 read from file
6256 * @work: smb work containing read command buffer
6258 * Return: 0 on success, otherwise error
6260 int smb2_read(struct ksmbd_work *work)
6262 struct ksmbd_conn *conn = work->conn;
6263 struct smb2_read_req *req;
6264 struct smb2_read_rsp *rsp;
6265 struct ksmbd_file *fp = NULL;
6267 size_t length, mincount;
6268 ssize_t nbytes = 0, remain_bytes = 0;
6270 bool is_rdma_channel = false;
6271 unsigned int max_read_size = conn->vals->max_read_size;
6272 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6273 void *aux_payload_buf;
6275 if (test_share_config_flag(work->tcon->share_conf,
6276 KSMBD_SHARE_FLAG_PIPE)) {
6277 ksmbd_debug(SMB, "IPC pipe read request\n");
6278 return smb2_read_pipe(work);
6281 if (work->next_smb2_rcv_hdr_off) {
6282 req = ksmbd_req_buf_next(work);
6283 rsp = ksmbd_resp_buf_next(work);
6284 if (!has_file_id(req->VolatileFileId)) {
6285 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6286 work->compound_fid);
6287 id = work->compound_fid;
6288 pid = work->compound_pfid;
6291 req = smb2_get_msg(work->request_buf);
6292 rsp = smb2_get_msg(work->response_buf);
6295 if (!has_file_id(id)) {
6296 id = req->VolatileFileId;
6297 pid = req->PersistentFileId;
6300 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6301 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6302 is_rdma_channel = true;
6303 max_read_size = get_smbd_max_read_write_size();
6306 if (is_rdma_channel == true) {
6307 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6309 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6313 err = smb2_set_remote_key_for_rdma(work,
6314 (struct smb2_buffer_desc_v1 *)
6315 ((char *)req + ch_offset),
6317 req->ReadChannelInfoLength);
6322 fp = ksmbd_lookup_fd_slow(work, id, pid);
6328 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6329 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6334 offset = le64_to_cpu(req->Offset);
6335 length = le32_to_cpu(req->Length);
6336 mincount = le32_to_cpu(req->MinimumCount);
6338 if (length > max_read_size) {
6339 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6345 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6346 fp->filp, offset, length);
6348 aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6349 if (!aux_payload_buf) {
6354 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6360 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6361 kvfree(aux_payload_buf);
6362 rsp->hdr.Status = STATUS_END_OF_FILE;
6363 smb2_set_err_rsp(work);
6364 ksmbd_fd_put(work, fp);
6368 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6369 nbytes, offset, mincount);
6371 if (is_rdma_channel == true) {
6372 /* write data to the client using rdma channel */
6373 remain_bytes = smb2_read_rdma_channel(work, req,
6376 kvfree(aux_payload_buf);
6377 aux_payload_buf = NULL;
6379 if (remain_bytes < 0) {
6380 err = (int)remain_bytes;
6385 rsp->StructureSize = cpu_to_le16(17);
6386 rsp->DataOffset = 80;
6388 rsp->DataLength = cpu_to_le32(nbytes);
6389 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6391 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6392 offsetof(struct smb2_read_rsp, Buffer),
6393 aux_payload_buf, nbytes);
6395 kvfree(aux_payload_buf);
6398 ksmbd_fd_put(work, fp);
6404 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6405 else if (err == -EAGAIN)
6406 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6407 else if (err == -ENOENT)
6408 rsp->hdr.Status = STATUS_FILE_CLOSED;
6409 else if (err == -EACCES)
6410 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6411 else if (err == -ESHARE)
6412 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6413 else if (err == -EINVAL)
6414 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6416 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6418 smb2_set_err_rsp(work);
6420 ksmbd_fd_put(work, fp);
6425 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6426 * @work: smb work containing write IPC pipe command buffer
6428 * Return: 0 on success, otherwise error
6430 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6432 struct smb2_write_req *req;
6433 struct smb2_write_rsp *rsp;
6434 struct ksmbd_rpc_command *rpc_resp;
6436 int err = 0, ret = 0;
6440 WORK_BUFFERS(work, req, rsp);
6442 length = le32_to_cpu(req->Length);
6443 id = req->VolatileFileId;
6445 if ((u64)le16_to_cpu(req->DataOffset) + length >
6446 get_rfc1002_len(work->request_buf)) {
6447 pr_err("invalid write data offset %u, smb_len %u\n",
6448 le16_to_cpu(req->DataOffset),
6449 get_rfc1002_len(work->request_buf));
6454 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6455 le16_to_cpu(req->DataOffset));
6457 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6459 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6460 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6462 smb2_set_err_rsp(work);
6465 if (rpc_resp->flags != KSMBD_RPC_OK) {
6466 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6467 smb2_set_err_rsp(work);
6474 rsp->StructureSize = cpu_to_le16(17);
6475 rsp->DataOffset = 0;
6477 rsp->DataLength = cpu_to_le32(length);
6478 rsp->DataRemaining = 0;
6480 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6481 offsetof(struct smb2_write_rsp, Buffer));
6484 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6485 smb2_set_err_rsp(work);
6491 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6492 struct smb2_write_req *req,
6493 struct ksmbd_file *fp,
6494 loff_t offset, size_t length, bool sync)
6500 data_buf = kvzalloc(length, GFP_KERNEL);
6504 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6505 (struct smb2_buffer_desc_v1 *)
6506 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6507 le16_to_cpu(req->WriteChannelInfoLength));
6513 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6522 * smb2_write() - handler for smb2 write from file
6523 * @work: smb work containing write command buffer
6525 * Return: 0 on success, otherwise error
6527 int smb2_write(struct ksmbd_work *work)
6529 struct smb2_write_req *req;
6530 struct smb2_write_rsp *rsp;
6531 struct ksmbd_file *fp = NULL;
6536 bool writethrough = false, is_rdma_channel = false;
6538 unsigned int max_write_size = work->conn->vals->max_write_size;
6540 WORK_BUFFERS(work, req, rsp);
6542 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6543 ksmbd_debug(SMB, "IPC pipe write request\n");
6544 return smb2_write_pipe(work);
6547 offset = le64_to_cpu(req->Offset);
6548 length = le32_to_cpu(req->Length);
6550 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6551 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6552 is_rdma_channel = true;
6553 max_write_size = get_smbd_max_read_write_size();
6554 length = le32_to_cpu(req->RemainingBytes);
6557 if (is_rdma_channel == true) {
6558 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6560 if (req->Length != 0 || req->DataOffset != 0 ||
6561 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6565 err = smb2_set_remote_key_for_rdma(work,
6566 (struct smb2_buffer_desc_v1 *)
6567 ((char *)req + ch_offset),
6569 req->WriteChannelInfoLength);
6574 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6575 ksmbd_debug(SMB, "User does not have write permission\n");
6580 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6586 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6587 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6592 if (length > max_write_size) {
6593 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6599 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6600 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6601 writethrough = true;
6603 if (is_rdma_channel == false) {
6604 if (le16_to_cpu(req->DataOffset) <
6605 offsetof(struct smb2_write_req, Buffer)) {
6610 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6611 le16_to_cpu(req->DataOffset));
6613 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6614 fp->filp, offset, length);
6615 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6616 writethrough, &nbytes);
6620 /* read data from the client using rdma channel, and
6623 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6631 rsp->StructureSize = cpu_to_le16(17);
6632 rsp->DataOffset = 0;
6634 rsp->DataLength = cpu_to_le32(nbytes);
6635 rsp->DataRemaining = 0;
6637 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6640 ksmbd_fd_put(work, fp);
6645 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6646 else if (err == -ENOSPC || err == -EFBIG)
6647 rsp->hdr.Status = STATUS_DISK_FULL;
6648 else if (err == -ENOENT)
6649 rsp->hdr.Status = STATUS_FILE_CLOSED;
6650 else if (err == -EACCES)
6651 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6652 else if (err == -ESHARE)
6653 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6654 else if (err == -EINVAL)
6655 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6657 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6659 smb2_set_err_rsp(work);
6660 ksmbd_fd_put(work, fp);
6665 * smb2_flush() - handler for smb2 flush file - fsync
6666 * @work: smb work containing flush command buffer
6668 * Return: 0 on success, otherwise error
6670 int smb2_flush(struct ksmbd_work *work)
6672 struct smb2_flush_req *req;
6673 struct smb2_flush_rsp *rsp;
6676 WORK_BUFFERS(work, req, rsp);
6678 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6680 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6684 rsp->StructureSize = cpu_to_le16(4);
6686 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6689 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6690 smb2_set_err_rsp(work);
6695 * smb2_cancel() - handler for smb2 cancel command
6696 * @work: smb work containing cancel command buffer
6698 * Return: 0 on success, otherwise error
6700 int smb2_cancel(struct ksmbd_work *work)
6702 struct ksmbd_conn *conn = work->conn;
6703 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6704 struct smb2_hdr *chdr;
6705 struct ksmbd_work *iter;
6706 struct list_head *command_list;
6708 if (work->next_smb2_rcv_hdr_off)
6709 hdr = ksmbd_resp_buf_next(work);
6711 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6712 hdr->MessageId, hdr->Flags);
6714 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6715 command_list = &conn->async_requests;
6717 spin_lock(&conn->request_lock);
6718 list_for_each_entry(iter, command_list,
6719 async_request_entry) {
6720 chdr = smb2_get_msg(iter->request_buf);
6722 if (iter->async_id !=
6723 le64_to_cpu(hdr->Id.AsyncId))
6727 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6728 le64_to_cpu(hdr->Id.AsyncId),
6729 le16_to_cpu(chdr->Command));
6730 iter->state = KSMBD_WORK_CANCELLED;
6731 if (iter->cancel_fn)
6732 iter->cancel_fn(iter->cancel_argv);
6735 spin_unlock(&conn->request_lock);
6737 command_list = &conn->requests;
6739 spin_lock(&conn->request_lock);
6740 list_for_each_entry(iter, command_list, request_entry) {
6741 chdr = smb2_get_msg(iter->request_buf);
6743 if (chdr->MessageId != hdr->MessageId ||
6748 "smb2 with mid %llu cancelled command = 0x%x\n",
6749 le64_to_cpu(hdr->MessageId),
6750 le16_to_cpu(chdr->Command));
6751 iter->state = KSMBD_WORK_CANCELLED;
6754 spin_unlock(&conn->request_lock);
6757 /* For SMB2_CANCEL command itself send no response*/
6758 work->send_no_response = 1;
6762 struct file_lock *smb_flock_init(struct file *f)
6764 struct file_lock *fl;
6766 fl = locks_alloc_lock();
6770 locks_init_lock(fl);
6773 fl->fl_pid = current->tgid;
6775 fl->fl_flags = FL_POSIX;
6777 fl->fl_lmops = NULL;
6783 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6787 /* Checking for wrong flag combination during lock request*/
6789 case SMB2_LOCKFLAG_SHARED:
6790 ksmbd_debug(SMB, "received shared request\n");
6792 flock->fl_type = F_RDLCK;
6793 flock->fl_flags |= FL_SLEEP;
6795 case SMB2_LOCKFLAG_EXCLUSIVE:
6796 ksmbd_debug(SMB, "received exclusive request\n");
6798 flock->fl_type = F_WRLCK;
6799 flock->fl_flags |= FL_SLEEP;
6801 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6803 "received shared & fail immediately request\n");
6805 flock->fl_type = F_RDLCK;
6807 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6809 "received exclusive & fail immediately request\n");
6811 flock->fl_type = F_WRLCK;
6813 case SMB2_LOCKFLAG_UNLOCK:
6814 ksmbd_debug(SMB, "received unlock request\n");
6815 flock->fl_type = F_UNLCK;
6823 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6824 unsigned int cmd, int flags,
6825 struct list_head *lock_list)
6827 struct ksmbd_lock *lock;
6829 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6835 lock->start = flock->fl_start;
6836 lock->end = flock->fl_end;
6837 lock->flags = flags;
6838 if (lock->start == lock->end)
6840 INIT_LIST_HEAD(&lock->clist);
6841 INIT_LIST_HEAD(&lock->flist);
6842 INIT_LIST_HEAD(&lock->llist);
6843 list_add_tail(&lock->llist, lock_list);
6848 static void smb2_remove_blocked_lock(void **argv)
6850 struct file_lock *flock = (struct file_lock *)argv[0];
6852 ksmbd_vfs_posix_lock_unblock(flock);
6853 wake_up(&flock->fl_wait);
6856 static inline bool lock_defer_pending(struct file_lock *fl)
6858 /* check pending lock waiters */
6859 return waitqueue_active(&fl->fl_wait);
6863 * smb2_lock() - handler for smb2 file lock command
6864 * @work: smb work containing lock command buffer
6866 * Return: 0 on success, otherwise error
6868 int smb2_lock(struct ksmbd_work *work)
6870 struct smb2_lock_req *req;
6871 struct smb2_lock_rsp *rsp;
6872 struct smb2_lock_element *lock_ele;
6873 struct ksmbd_file *fp = NULL;
6874 struct file_lock *flock = NULL;
6875 struct file *filp = NULL;
6879 int err = -EIO, i, rc = 0;
6880 u64 lock_start, lock_length;
6881 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6882 struct ksmbd_conn *conn;
6884 LIST_HEAD(lock_list);
6885 LIST_HEAD(rollback_list);
6888 WORK_BUFFERS(work, req, rsp);
6890 ksmbd_debug(SMB, "Received lock request\n");
6891 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6893 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6899 lock_count = le16_to_cpu(req->LockCount);
6900 lock_ele = req->locks;
6902 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6908 for (i = 0; i < lock_count; i++) {
6909 flags = le32_to_cpu(lock_ele[i].Flags);
6911 flock = smb_flock_init(filp);
6915 cmd = smb2_set_flock_flags(flock, flags);
6917 lock_start = le64_to_cpu(lock_ele[i].Offset);
6918 lock_length = le64_to_cpu(lock_ele[i].Length);
6919 if (lock_start > U64_MAX - lock_length) {
6920 pr_err("Invalid lock range requested\n");
6921 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6922 locks_free_lock(flock);
6926 if (lock_start > OFFSET_MAX)
6927 flock->fl_start = OFFSET_MAX;
6929 flock->fl_start = lock_start;
6931 lock_length = le64_to_cpu(lock_ele[i].Length);
6932 if (lock_length > OFFSET_MAX - flock->fl_start)
6933 lock_length = OFFSET_MAX - flock->fl_start;
6935 flock->fl_end = flock->fl_start + lock_length;
6937 if (flock->fl_end < flock->fl_start) {
6939 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6940 flock->fl_end, flock->fl_start);
6941 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6942 locks_free_lock(flock);
6946 /* Check conflict locks in one request */
6947 list_for_each_entry(cmp_lock, &lock_list, llist) {
6948 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6949 cmp_lock->fl->fl_end >= flock->fl_end) {
6950 if (cmp_lock->fl->fl_type != F_UNLCK &&
6951 flock->fl_type != F_UNLCK) {
6952 pr_err("conflict two locks in one request\n");
6954 locks_free_lock(flock);
6960 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6963 locks_free_lock(flock);
6968 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6969 if (smb_lock->cmd < 0) {
6974 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6979 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6980 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6981 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6982 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6987 prior_lock = smb_lock->flags;
6989 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6990 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6994 /* check locks in connection list */
6995 down_read(&conn_list_lock);
6996 list_for_each_entry(conn, &conn_list, conns_list) {
6997 spin_lock(&conn->llist_lock);
6998 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6999 if (file_inode(cmp_lock->fl->fl_file) !=
7000 file_inode(smb_lock->fl->fl_file))
7003 if (smb_lock->fl->fl_type == F_UNLCK) {
7004 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
7005 cmp_lock->start == smb_lock->start &&
7006 cmp_lock->end == smb_lock->end &&
7007 !lock_defer_pending(cmp_lock->fl)) {
7009 list_del(&cmp_lock->flist);
7010 list_del(&cmp_lock->clist);
7011 spin_unlock(&conn->llist_lock);
7012 up_read(&conn_list_lock);
7014 locks_free_lock(cmp_lock->fl);
7021 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
7022 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7025 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7029 /* check zero byte lock range */
7030 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7031 cmp_lock->start > smb_lock->start &&
7032 cmp_lock->start < smb_lock->end) {
7033 spin_unlock(&conn->llist_lock);
7034 up_read(&conn_list_lock);
7035 pr_err("previous lock conflict with zero byte lock range\n");
7039 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7040 smb_lock->start > cmp_lock->start &&
7041 smb_lock->start < cmp_lock->end) {
7042 spin_unlock(&conn->llist_lock);
7043 up_read(&conn_list_lock);
7044 pr_err("current lock conflict with zero byte lock range\n");
7048 if (((cmp_lock->start <= smb_lock->start &&
7049 cmp_lock->end > smb_lock->start) ||
7050 (cmp_lock->start < smb_lock->end &&
7051 cmp_lock->end >= smb_lock->end)) &&
7052 !cmp_lock->zero_len && !smb_lock->zero_len) {
7053 spin_unlock(&conn->llist_lock);
7054 up_read(&conn_list_lock);
7055 pr_err("Not allow lock operation on exclusive lock range\n");
7059 spin_unlock(&conn->llist_lock);
7061 up_read(&conn_list_lock);
7063 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7064 pr_err("Try to unlock nolocked range\n");
7065 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7070 if (smb_lock->zero_len) {
7075 flock = smb_lock->fl;
7076 list_del(&smb_lock->llist);
7078 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7080 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7082 ksmbd_debug(SMB, "File unlocked\n");
7083 } else if (rc == -ENOENT) {
7084 rsp->hdr.Status = STATUS_NOT_LOCKED;
7087 locks_free_lock(flock);
7090 if (rc == FILE_LOCK_DEFERRED) {
7094 "would have to wait for getting lock\n");
7095 list_add(&smb_lock->llist, &rollback_list);
7097 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7104 rc = setup_async_work(work,
7105 smb2_remove_blocked_lock,
7112 spin_lock(&fp->f_lock);
7113 list_add(&work->fp_entry, &fp->blocked_works);
7114 spin_unlock(&fp->f_lock);
7116 smb2_send_interim_resp(work, STATUS_PENDING);
7118 ksmbd_vfs_posix_lock_wait(flock);
7120 spin_lock(&fp->f_lock);
7121 list_del(&work->fp_entry);
7122 spin_unlock(&fp->f_lock);
7124 if (work->state != KSMBD_WORK_ACTIVE) {
7125 list_del(&smb_lock->llist);
7126 locks_free_lock(flock);
7128 if (work->state == KSMBD_WORK_CANCELLED) {
7132 smb2_send_interim_resp(work,
7134 work->send_no_response = 1;
7139 STATUS_RANGE_NOT_LOCKED;
7144 list_del(&smb_lock->llist);
7145 release_async_work(work);
7148 list_add(&smb_lock->llist, &rollback_list);
7149 spin_lock(&work->conn->llist_lock);
7150 list_add_tail(&smb_lock->clist,
7151 &work->conn->lock_list);
7152 list_add_tail(&smb_lock->flist,
7154 spin_unlock(&work->conn->llist_lock);
7155 ksmbd_debug(SMB, "successful in taking lock\n");
7162 if (atomic_read(&fp->f_ci->op_count) > 1)
7163 smb_break_all_oplock(work, fp);
7165 rsp->StructureSize = cpu_to_le16(4);
7166 ksmbd_debug(SMB, "successful in taking lock\n");
7167 rsp->hdr.Status = STATUS_SUCCESS;
7169 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7173 ksmbd_fd_put(work, fp);
7177 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7178 locks_free_lock(smb_lock->fl);
7179 list_del(&smb_lock->llist);
7183 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7184 struct file_lock *rlock = NULL;
7186 rlock = smb_flock_init(filp);
7187 rlock->fl_type = F_UNLCK;
7188 rlock->fl_start = smb_lock->start;
7189 rlock->fl_end = smb_lock->end;
7191 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7193 pr_err("rollback unlock fail : %d\n", rc);
7195 list_del(&smb_lock->llist);
7196 spin_lock(&work->conn->llist_lock);
7197 if (!list_empty(&smb_lock->flist))
7198 list_del(&smb_lock->flist);
7199 list_del(&smb_lock->clist);
7200 spin_unlock(&work->conn->llist_lock);
7202 locks_free_lock(smb_lock->fl);
7203 locks_free_lock(rlock);
7207 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7209 if (!rsp->hdr.Status) {
7211 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7212 else if (err == -ENOMEM)
7213 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7214 else if (err == -ENOENT)
7215 rsp->hdr.Status = STATUS_FILE_CLOSED;
7217 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7220 smb2_set_err_rsp(work);
7221 ksmbd_fd_put(work, fp);
7225 static int fsctl_copychunk(struct ksmbd_work *work,
7226 struct copychunk_ioctl_req *ci_req,
7227 unsigned int cnt_code,
7228 unsigned int input_count,
7229 unsigned long long volatile_id,
7230 unsigned long long persistent_id,
7231 struct smb2_ioctl_rsp *rsp)
7233 struct copychunk_ioctl_rsp *ci_rsp;
7234 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7235 struct srv_copychunk *chunks;
7236 unsigned int i, chunk_count, chunk_count_written = 0;
7237 unsigned int chunk_size_written = 0;
7238 loff_t total_size_written = 0;
7241 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7243 rsp->VolatileFileId = volatile_id;
7244 rsp->PersistentFileId = persistent_id;
7245 ci_rsp->ChunksWritten =
7246 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7247 ci_rsp->ChunkBytesWritten =
7248 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7249 ci_rsp->TotalBytesWritten =
7250 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7252 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7253 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7254 if (chunk_count == 0)
7256 total_size_written = 0;
7258 /* verify the SRV_COPYCHUNK_COPY packet */
7259 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7260 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7261 chunk_count * sizeof(struct srv_copychunk)) {
7262 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7266 for (i = 0; i < chunk_count; i++) {
7267 if (le32_to_cpu(chunks[i].Length) == 0 ||
7268 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7270 total_size_written += le32_to_cpu(chunks[i].Length);
7273 if (i < chunk_count ||
7274 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7275 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7279 src_fp = ksmbd_lookup_foreign_fd(work,
7280 le64_to_cpu(ci_req->ResumeKey[0]));
7281 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7284 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7285 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7290 rsp->hdr.Status = STATUS_FILE_CLOSED;
7295 * FILE_READ_DATA should only be included in
7296 * the FSCTL_COPYCHUNK case
7298 if (cnt_code == FSCTL_COPYCHUNK &&
7299 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7300 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7304 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7305 chunks, chunk_count,
7306 &chunk_count_written,
7307 &chunk_size_written,
7308 &total_size_written);
7311 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7313 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7314 else if (ret == -EBADF)
7315 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7316 else if (ret == -EFBIG || ret == -ENOSPC)
7317 rsp->hdr.Status = STATUS_DISK_FULL;
7318 else if (ret == -EINVAL)
7319 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7320 else if (ret == -EISDIR)
7321 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7322 else if (ret == -E2BIG)
7323 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7325 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7328 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7329 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7330 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7332 ksmbd_fd_put(work, src_fp);
7333 ksmbd_fd_put(work, dst_fp);
7337 static __be32 idev_ipv4_address(struct in_device *idev)
7341 struct in_ifaddr *ifa;
7344 in_dev_for_each_ifa_rcu(ifa, idev) {
7345 if (ifa->ifa_flags & IFA_F_SECONDARY)
7348 addr = ifa->ifa_address;
7355 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7356 struct smb2_ioctl_rsp *rsp,
7357 unsigned int out_buf_len)
7359 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7361 struct net_device *netdev;
7362 struct sockaddr_storage_rsp *sockaddr_storage;
7364 unsigned long long speed;
7367 for_each_netdev(&init_net, netdev) {
7368 bool ipv4_set = false;
7370 if (netdev->type == ARPHRD_LOOPBACK)
7373 flags = dev_get_flags(netdev);
7374 if (!(flags & IFF_RUNNING))
7378 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7383 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7384 &rsp->Buffer[nbytes];
7385 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7387 nii_rsp->Capability = 0;
7388 if (netdev->real_num_tx_queues > 1)
7389 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7390 if (ksmbd_rdma_capable_netdev(netdev))
7391 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7393 nii_rsp->Next = cpu_to_le32(152);
7394 nii_rsp->Reserved = 0;
7396 if (netdev->ethtool_ops->get_link_ksettings) {
7397 struct ethtool_link_ksettings cmd;
7399 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7400 speed = cmd.base.speed;
7402 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7403 "speed is unknown, defaulting to 1Gb/sec");
7408 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7410 sockaddr_storage = (struct sockaddr_storage_rsp *)
7411 nii_rsp->SockAddr_Storage;
7412 memset(sockaddr_storage, 0, 128);
7415 struct in_device *idev;
7417 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7418 sockaddr_storage->addr4.Port = 0;
7420 idev = __in_dev_get_rtnl(netdev);
7423 sockaddr_storage->addr4.IPv4address =
7424 idev_ipv4_address(idev);
7425 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7429 struct inet6_dev *idev6;
7430 struct inet6_ifaddr *ifa;
7431 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7433 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7434 sockaddr_storage->addr6.Port = 0;
7435 sockaddr_storage->addr6.FlowInfo = 0;
7437 idev6 = __in6_dev_get(netdev);
7441 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7442 if (ifa->flags & (IFA_F_TENTATIVE |
7445 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7448 sockaddr_storage->addr6.ScopeId = 0;
7449 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7454 /* zero if this is last one */
7458 rsp->PersistentFileId = SMB2_NO_FID;
7459 rsp->VolatileFileId = SMB2_NO_FID;
7463 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7464 struct validate_negotiate_info_req *neg_req,
7465 struct validate_negotiate_info_rsp *neg_rsp,
7466 unsigned int in_buf_len)
7471 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7472 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7475 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7476 neg_req->DialectCount);
7477 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7482 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7487 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7492 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7497 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7498 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7499 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7500 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7505 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7506 struct file_allocated_range_buffer *qar_req,
7507 struct file_allocated_range_buffer *qar_rsp,
7508 unsigned int in_count, unsigned int *out_count)
7510 struct ksmbd_file *fp;
7511 loff_t start, length;
7518 start = le64_to_cpu(qar_req->file_offset);
7519 length = le64_to_cpu(qar_req->length);
7521 if (start < 0 || length < 0)
7524 fp = ksmbd_lookup_fd_fast(work, id);
7528 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7529 qar_rsp, in_count, out_count);
7530 if (ret && ret != -E2BIG)
7533 ksmbd_fd_put(work, fp);
7537 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7538 unsigned int out_buf_len,
7539 struct smb2_ioctl_req *req,
7540 struct smb2_ioctl_rsp *rsp)
7542 struct ksmbd_rpc_command *rpc_resp;
7543 char *data_buf = (char *)&req->Buffer[0];
7546 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7547 le32_to_cpu(req->InputCount));
7549 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7551 * set STATUS_SOME_NOT_MAPPED response
7552 * for unknown domain sid.
7554 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7555 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7556 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7558 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7559 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7563 nbytes = rpc_resp->payload_sz;
7564 if (rpc_resp->payload_sz > out_buf_len) {
7565 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7566 nbytes = out_buf_len;
7569 if (!rpc_resp->payload_sz) {
7571 STATUS_UNEXPECTED_IO_ERROR;
7575 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7582 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7583 struct file_sparse *sparse)
7585 struct ksmbd_file *fp;
7586 struct user_namespace *user_ns;
7590 fp = ksmbd_lookup_fd_fast(work, id);
7593 user_ns = file_mnt_user_ns(fp->filp);
7595 old_fattr = fp->f_ci->m_fattr;
7596 if (sparse->SetSparse)
7597 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7599 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7601 if (fp->f_ci->m_fattr != old_fattr &&
7602 test_share_config_flag(work->tcon->share_conf,
7603 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7604 struct xattr_dos_attrib da;
7606 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7607 fp->filp->f_path.dentry, &da);
7611 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7612 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7616 fp->f_ci->m_fattr = old_fattr;
7620 ksmbd_fd_put(work, fp);
7624 static int fsctl_request_resume_key(struct ksmbd_work *work,
7625 struct smb2_ioctl_req *req,
7626 struct resume_key_ioctl_rsp *key_rsp)
7628 struct ksmbd_file *fp;
7630 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7634 memset(key_rsp, 0, sizeof(*key_rsp));
7635 key_rsp->ResumeKey[0] = req->VolatileFileId;
7636 key_rsp->ResumeKey[1] = req->PersistentFileId;
7637 ksmbd_fd_put(work, fp);
7643 * smb2_ioctl() - handler for smb2 ioctl command
7644 * @work: smb work containing ioctl command buffer
7646 * Return: 0 on success, otherwise error
7648 int smb2_ioctl(struct ksmbd_work *work)
7650 struct smb2_ioctl_req *req;
7651 struct smb2_ioctl_rsp *rsp;
7652 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7653 u64 id = KSMBD_NO_FID;
7654 struct ksmbd_conn *conn = work->conn;
7657 if (work->next_smb2_rcv_hdr_off) {
7658 req = ksmbd_req_buf_next(work);
7659 rsp = ksmbd_resp_buf_next(work);
7660 if (!has_file_id(req->VolatileFileId)) {
7661 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7662 work->compound_fid);
7663 id = work->compound_fid;
7666 req = smb2_get_msg(work->request_buf);
7667 rsp = smb2_get_msg(work->response_buf);
7670 if (!has_file_id(id))
7671 id = req->VolatileFileId;
7673 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7674 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7678 cnt_code = le32_to_cpu(req->CtlCode);
7679 ret = smb2_calc_max_out_buf_len(work, 48,
7680 le32_to_cpu(req->MaxOutputResponse));
7682 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7685 out_buf_len = (unsigned int)ret;
7686 in_buf_len = le32_to_cpu(req->InputCount);
7689 case FSCTL_DFS_GET_REFERRALS:
7690 case FSCTL_DFS_GET_REFERRALS_EX:
7691 /* Not support DFS yet */
7692 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7694 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7696 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7698 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7699 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7703 * TODO: This is dummy implementation to pass smbtorture
7704 * Need to check correct response later
7706 memset(obj_buf->ObjectId, 0x0, 16);
7707 memset(obj_buf->BirthVolumeId, 0x0, 16);
7708 memset(obj_buf->BirthObjectId, 0x0, 16);
7709 memset(obj_buf->DomainId, 0x0, 16);
7713 case FSCTL_PIPE_TRANSCEIVE:
7714 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7715 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7717 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7718 if (conn->dialect < SMB30_PROT_ID) {
7723 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7729 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7734 ret = fsctl_validate_negotiate_info(conn,
7735 (struct validate_negotiate_info_req *)&req->Buffer[0],
7736 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7741 nbytes = sizeof(struct validate_negotiate_info_rsp);
7742 rsp->PersistentFileId = SMB2_NO_FID;
7743 rsp->VolatileFileId = SMB2_NO_FID;
7745 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7746 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7751 case FSCTL_REQUEST_RESUME_KEY:
7752 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7757 ret = fsctl_request_resume_key(work, req,
7758 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7761 rsp->PersistentFileId = req->PersistentFileId;
7762 rsp->VolatileFileId = req->VolatileFileId;
7763 nbytes = sizeof(struct resume_key_ioctl_rsp);
7765 case FSCTL_COPYCHUNK:
7766 case FSCTL_COPYCHUNK_WRITE:
7767 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7769 "User does not have write permission\n");
7774 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7779 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7784 nbytes = sizeof(struct copychunk_ioctl_rsp);
7785 rsp->VolatileFileId = req->VolatileFileId;
7786 rsp->PersistentFileId = req->PersistentFileId;
7787 fsctl_copychunk(work,
7788 (struct copychunk_ioctl_req *)&req->Buffer[0],
7789 le32_to_cpu(req->CtlCode),
7790 le32_to_cpu(req->InputCount),
7791 req->VolatileFileId,
7792 req->PersistentFileId,
7795 case FSCTL_SET_SPARSE:
7796 if (in_buf_len < sizeof(struct file_sparse)) {
7801 ret = fsctl_set_sparse(work, id,
7802 (struct file_sparse *)&req->Buffer[0]);
7806 case FSCTL_SET_ZERO_DATA:
7808 struct file_zero_data_information *zero_data;
7809 struct ksmbd_file *fp;
7810 loff_t off, len, bfz;
7812 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7814 "User does not have write permission\n");
7819 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7825 (struct file_zero_data_information *)&req->Buffer[0];
7827 off = le64_to_cpu(zero_data->FileOffset);
7828 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7829 if (off < 0 || bfz < 0 || off > bfz) {
7836 fp = ksmbd_lookup_fd_fast(work, id);
7842 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7843 ksmbd_fd_put(work, fp);
7849 case FSCTL_QUERY_ALLOCATED_RANGES:
7850 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7855 ret = fsctl_query_allocated_ranges(work, id,
7856 (struct file_allocated_range_buffer *)&req->Buffer[0],
7857 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7859 sizeof(struct file_allocated_range_buffer), &nbytes);
7860 if (ret == -E2BIG) {
7861 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7862 } else if (ret < 0) {
7867 nbytes *= sizeof(struct file_allocated_range_buffer);
7869 case FSCTL_GET_REPARSE_POINT:
7871 struct reparse_data_buffer *reparse_ptr;
7872 struct ksmbd_file *fp;
7874 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7875 fp = ksmbd_lookup_fd_fast(work, id);
7877 pr_err("not found fp!!\n");
7882 reparse_ptr->ReparseTag =
7883 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7884 reparse_ptr->ReparseDataLength = 0;
7885 ksmbd_fd_put(work, fp);
7886 nbytes = sizeof(struct reparse_data_buffer);
7889 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7891 struct ksmbd_file *fp_in, *fp_out = NULL;
7892 struct duplicate_extents_to_file *dup_ext;
7893 loff_t src_off, dst_off, length, cloned;
7895 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7900 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7902 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7903 dup_ext->PersistentFileHandle);
7905 pr_err("not found file handle in duplicate extent to file\n");
7910 fp_out = ksmbd_lookup_fd_fast(work, id);
7912 pr_err("not found fp\n");
7917 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7918 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7919 length = le64_to_cpu(dup_ext->ByteCount);
7921 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7922 * should fall back to vfs_copy_file_range(). This could be
7923 * beneficial when re-exporting nfs/smb mount, but note that
7924 * this can result in partial copy that returns an error status.
7925 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7926 * fall back to vfs_copy_file_range(), should be avoided when
7927 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7929 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7930 fp_out->filp, dst_off, length, 0);
7931 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7934 } else if (cloned != length) {
7935 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7936 fp_out->filp, dst_off,
7938 if (cloned != length) {
7947 ksmbd_fd_put(work, fp_in);
7948 ksmbd_fd_put(work, fp_out);
7954 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7960 rsp->CtlCode = cpu_to_le32(cnt_code);
7961 rsp->InputCount = cpu_to_le32(0);
7962 rsp->InputOffset = cpu_to_le32(112);
7963 rsp->OutputOffset = cpu_to_le32(112);
7964 rsp->OutputCount = cpu_to_le32(nbytes);
7965 rsp->StructureSize = cpu_to_le16(49);
7966 rsp->Reserved = cpu_to_le16(0);
7967 rsp->Flags = cpu_to_le32(0);
7968 rsp->Reserved2 = cpu_to_le32(0);
7969 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
7975 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7976 else if (ret == -ENOENT)
7977 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7978 else if (ret == -EOPNOTSUPP)
7979 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7980 else if (ret == -ENOSPC)
7981 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7982 else if (ret < 0 || rsp->hdr.Status == 0)
7983 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7984 smb2_set_err_rsp(work);
7989 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7990 * @work: smb work containing oplock break command buffer
7994 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7996 struct smb2_oplock_break *req;
7997 struct smb2_oplock_break *rsp;
7998 struct ksmbd_file *fp;
7999 struct oplock_info *opinfo = NULL;
8002 u64 volatile_id, persistent_id;
8003 char req_oplevel = 0, rsp_oplevel = 0;
8004 unsigned int oplock_change_type;
8006 WORK_BUFFERS(work, req, rsp);
8008 volatile_id = req->VolatileFid;
8009 persistent_id = req->PersistentFid;
8010 req_oplevel = req->OplockLevel;
8011 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8012 volatile_id, persistent_id, req_oplevel);
8014 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8016 rsp->hdr.Status = STATUS_FILE_CLOSED;
8017 smb2_set_err_rsp(work);
8021 opinfo = opinfo_get(fp);
8023 pr_err("unexpected null oplock_info\n");
8024 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8025 smb2_set_err_rsp(work);
8026 ksmbd_fd_put(work, fp);
8030 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8031 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8035 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8036 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8037 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8041 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8042 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8043 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8044 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8045 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8046 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8047 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8048 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8049 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8050 oplock_change_type = OPLOCK_READ_TO_NONE;
8051 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8052 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8053 err = STATUS_INVALID_DEVICE_STATE;
8054 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8055 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8056 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8057 oplock_change_type = OPLOCK_WRITE_TO_READ;
8058 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8059 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8060 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8061 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8062 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8063 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8064 oplock_change_type = OPLOCK_READ_TO_NONE;
8066 oplock_change_type = 0;
8069 oplock_change_type = 0;
8072 switch (oplock_change_type) {
8073 case OPLOCK_WRITE_TO_READ:
8074 ret = opinfo_write_to_read(opinfo);
8075 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8077 case OPLOCK_WRITE_TO_NONE:
8078 ret = opinfo_write_to_none(opinfo);
8079 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8081 case OPLOCK_READ_TO_NONE:
8082 ret = opinfo_read_to_none(opinfo);
8083 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8086 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8087 opinfo->level, rsp_oplevel);
8091 rsp->hdr.Status = err;
8095 opinfo->op_state = OPLOCK_STATE_NONE;
8096 wake_up_interruptible_all(&opinfo->oplock_q);
8098 ksmbd_fd_put(work, fp);
8100 rsp->StructureSize = cpu_to_le16(24);
8101 rsp->OplockLevel = rsp_oplevel;
8104 rsp->VolatileFid = volatile_id;
8105 rsp->PersistentFid = persistent_id;
8106 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8111 opinfo->op_state = OPLOCK_STATE_NONE;
8112 wake_up_interruptible_all(&opinfo->oplock_q);
8115 ksmbd_fd_put(work, fp);
8116 smb2_set_err_rsp(work);
8119 static int check_lease_state(struct lease *lease, __le32 req_state)
8121 if ((lease->new_state ==
8122 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8123 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8124 lease->new_state = req_state;
8128 if (lease->new_state == req_state)
8135 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8136 * @work: smb work containing lease break command buffer
8140 static void smb21_lease_break_ack(struct ksmbd_work *work)
8142 struct ksmbd_conn *conn = work->conn;
8143 struct smb2_lease_ack *req;
8144 struct smb2_lease_ack *rsp;
8145 struct oplock_info *opinfo;
8148 unsigned int lease_change_type;
8150 struct lease *lease;
8152 WORK_BUFFERS(work, req, rsp);
8154 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8155 le32_to_cpu(req->LeaseState));
8156 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8158 ksmbd_debug(OPLOCK, "file not opened\n");
8159 smb2_set_err_rsp(work);
8160 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8163 lease = opinfo->o_lease;
8165 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8166 pr_err("unexpected lease break state 0x%x\n",
8168 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8172 if (check_lease_state(lease, req->LeaseState)) {
8173 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8175 "req lease state: 0x%x, expected state: 0x%x\n",
8176 req->LeaseState, lease->new_state);
8180 if (!atomic_read(&opinfo->breaking_cnt)) {
8181 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8185 /* check for bad lease state */
8186 if (req->LeaseState &
8187 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8188 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8189 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8190 lease_change_type = OPLOCK_WRITE_TO_NONE;
8192 lease_change_type = OPLOCK_READ_TO_NONE;
8193 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8194 le32_to_cpu(lease->state),
8195 le32_to_cpu(req->LeaseState));
8196 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8197 req->LeaseState != SMB2_LEASE_NONE_LE) {
8198 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8199 lease_change_type = OPLOCK_READ_TO_NONE;
8200 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8201 le32_to_cpu(lease->state),
8202 le32_to_cpu(req->LeaseState));
8204 /* valid lease state changes */
8205 err = STATUS_INVALID_DEVICE_STATE;
8206 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8207 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8208 lease_change_type = OPLOCK_WRITE_TO_NONE;
8210 lease_change_type = OPLOCK_READ_TO_NONE;
8211 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8212 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8213 lease_change_type = OPLOCK_WRITE_TO_READ;
8215 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8217 lease_change_type = 0;
8221 switch (lease_change_type) {
8222 case OPLOCK_WRITE_TO_READ:
8223 ret = opinfo_write_to_read(opinfo);
8225 case OPLOCK_READ_HANDLE_TO_READ:
8226 ret = opinfo_read_handle_to_read(opinfo);
8228 case OPLOCK_WRITE_TO_NONE:
8229 ret = opinfo_write_to_none(opinfo);
8231 case OPLOCK_READ_TO_NONE:
8232 ret = opinfo_read_to_none(opinfo);
8235 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8236 le32_to_cpu(lease->state),
8237 le32_to_cpu(req->LeaseState));
8241 rsp->hdr.Status = err;
8245 lease_state = lease->state;
8246 opinfo->op_state = OPLOCK_STATE_NONE;
8247 wake_up_interruptible_all(&opinfo->oplock_q);
8248 atomic_dec(&opinfo->breaking_cnt);
8249 wake_up_interruptible_all(&opinfo->oplock_brk);
8252 rsp->StructureSize = cpu_to_le16(36);
8255 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8256 rsp->LeaseState = lease_state;
8257 rsp->LeaseDuration = 0;
8258 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8263 wake_up_interruptible_all(&opinfo->oplock_q);
8264 atomic_dec(&opinfo->breaking_cnt);
8265 wake_up_interruptible_all(&opinfo->oplock_brk);
8268 smb2_set_err_rsp(work);
8272 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8273 * @work: smb work containing oplock/lease break command buffer
8277 int smb2_oplock_break(struct ksmbd_work *work)
8279 struct smb2_oplock_break *req;
8280 struct smb2_oplock_break *rsp;
8282 WORK_BUFFERS(work, req, rsp);
8284 switch (le16_to_cpu(req->StructureSize)) {
8285 case OP_BREAK_STRUCT_SIZE_20:
8286 smb20_oplock_break_ack(work);
8288 case OP_BREAK_STRUCT_SIZE_21:
8289 smb21_lease_break_ack(work);
8292 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8293 le16_to_cpu(req->StructureSize));
8294 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8295 smb2_set_err_rsp(work);
8302 * smb2_notify() - handler for smb2 notify request
8303 * @work: smb work containing notify command buffer
8307 int smb2_notify(struct ksmbd_work *work)
8309 struct smb2_change_notify_req *req;
8310 struct smb2_change_notify_rsp *rsp;
8312 WORK_BUFFERS(work, req, rsp);
8314 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8315 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8316 smb2_set_err_rsp(work);
8320 smb2_set_err_rsp(work);
8321 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8326 * smb2_is_sign_req() - handler for checking packet signing status
8327 * @work: smb work containing notify command buffer
8328 * @command: SMB2 command id
8330 * Return: true if packed is signed, false otherwise
8332 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8334 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8336 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8337 command != SMB2_NEGOTIATE_HE &&
8338 command != SMB2_SESSION_SETUP_HE &&
8339 command != SMB2_OPLOCK_BREAK_HE)
8346 * smb2_check_sign_req() - handler for req packet sign processing
8347 * @work: smb work containing notify command buffer
8349 * Return: 1 on success, 0 otherwise
8351 int smb2_check_sign_req(struct ksmbd_work *work)
8353 struct smb2_hdr *hdr;
8354 char signature_req[SMB2_SIGNATURE_SIZE];
8355 char signature[SMB2_HMACSHA256_SIZE];
8359 hdr = smb2_get_msg(work->request_buf);
8360 if (work->next_smb2_rcv_hdr_off)
8361 hdr = ksmbd_req_buf_next(work);
8363 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8364 len = get_rfc1002_len(work->request_buf);
8365 else if (hdr->NextCommand)
8366 len = le32_to_cpu(hdr->NextCommand);
8368 len = get_rfc1002_len(work->request_buf) -
8369 work->next_smb2_rcv_hdr_off;
8371 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8372 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8374 iov[0].iov_base = (char *)&hdr->ProtocolId;
8375 iov[0].iov_len = len;
8377 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8381 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8382 pr_err("bad smb2 signature\n");
8390 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8391 * @work: smb work containing notify command buffer
8394 void smb2_set_sign_rsp(struct ksmbd_work *work)
8396 struct smb2_hdr *hdr;
8397 char signature[SMB2_HMACSHA256_SIZE];
8401 hdr = ksmbd_resp_buf_curr(work);
8402 hdr->Flags |= SMB2_FLAGS_SIGNED;
8403 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8405 if (hdr->Command == SMB2_READ) {
8406 iov = &work->iov[work->iov_idx - 1];
8409 iov = &work->iov[work->iov_idx];
8412 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8414 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8418 * smb3_check_sign_req() - handler for req packet sign processing
8419 * @work: smb work containing notify command buffer
8421 * Return: 1 on success, 0 otherwise
8423 int smb3_check_sign_req(struct ksmbd_work *work)
8425 struct ksmbd_conn *conn = work->conn;
8427 struct smb2_hdr *hdr;
8428 struct channel *chann;
8429 char signature_req[SMB2_SIGNATURE_SIZE];
8430 char signature[SMB2_CMACAES_SIZE];
8434 hdr = smb2_get_msg(work->request_buf);
8435 if (work->next_smb2_rcv_hdr_off)
8436 hdr = ksmbd_req_buf_next(work);
8438 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8439 len = get_rfc1002_len(work->request_buf);
8440 else if (hdr->NextCommand)
8441 len = le32_to_cpu(hdr->NextCommand);
8443 len = get_rfc1002_len(work->request_buf) -
8444 work->next_smb2_rcv_hdr_off;
8446 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8447 signing_key = work->sess->smb3signingkey;
8449 chann = lookup_chann_list(work->sess, conn);
8453 signing_key = chann->smb3signingkey;
8457 pr_err("SMB3 signing key is not generated\n");
8461 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8462 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8463 iov[0].iov_base = (char *)&hdr->ProtocolId;
8464 iov[0].iov_len = len;
8466 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8469 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8470 pr_err("bad smb2 signature\n");
8478 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8479 * @work: smb work containing notify command buffer
8482 void smb3_set_sign_rsp(struct ksmbd_work *work)
8484 struct ksmbd_conn *conn = work->conn;
8485 struct smb2_hdr *hdr;
8486 struct channel *chann;
8487 char signature[SMB2_CMACAES_SIZE];
8492 hdr = ksmbd_resp_buf_curr(work);
8494 if (conn->binding == false &&
8495 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8496 signing_key = work->sess->smb3signingkey;
8498 chann = lookup_chann_list(work->sess, work->conn);
8502 signing_key = chann->smb3signingkey;
8508 hdr->Flags |= SMB2_FLAGS_SIGNED;
8509 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8511 if (hdr->Command == SMB2_READ) {
8512 iov = &work->iov[work->iov_idx - 1];
8515 iov = &work->iov[work->iov_idx];
8518 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8520 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8524 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8525 * @work: smb work containing response buffer
8528 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8530 struct ksmbd_conn *conn = work->conn;
8531 struct ksmbd_session *sess = work->sess;
8532 struct smb2_hdr *req, *rsp;
8534 if (conn->dialect != SMB311_PROT_ID)
8537 WORK_BUFFERS(work, req, rsp);
8539 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8541 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8542 conn->preauth_info->Preauth_HashValue);
8544 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8547 if (conn->binding) {
8548 struct preauth_session *preauth_sess;
8550 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8553 hash_value = preauth_sess->Preauth_HashValue;
8555 hash_value = sess->Preauth_HashValue;
8559 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8564 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8566 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8567 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8568 unsigned int orig_len = get_rfc1002_len(old_buf);
8570 /* tr_buf must be cleared by the caller */
8571 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8572 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8573 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8574 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8575 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8576 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8578 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8579 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8580 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8581 inc_rfc1001_len(tr_buf, orig_len);
8584 int smb3_encrypt_resp(struct ksmbd_work *work)
8586 struct kvec *iov = work->iov;
8590 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8594 /* fill transform header */
8595 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8597 iov[0].iov_base = tr_buf;
8598 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8599 work->tr_buf = tr_buf;
8601 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8604 bool smb3_is_transform_hdr(void *buf)
8606 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8608 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8611 int smb3_decrypt_req(struct ksmbd_work *work)
8613 struct ksmbd_session *sess;
8614 char *buf = work->request_buf;
8615 unsigned int pdu_length = get_rfc1002_len(buf);
8617 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8618 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8621 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8622 buf_data_size < sizeof(struct smb2_hdr)) {
8623 pr_err("Transform message is too small (%u)\n",
8625 return -ECONNABORTED;
8628 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8629 pr_err("Transform message is broken\n");
8630 return -ECONNABORTED;
8633 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8635 pr_err("invalid session id(%llx) in transform header\n",
8636 le64_to_cpu(tr_hdr->SessionId));
8637 return -ECONNABORTED;
8640 iov[0].iov_base = buf;
8641 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8642 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8643 iov[1].iov_len = buf_data_size;
8644 rc = ksmbd_crypt_message(work, iov, 2, 0);
8648 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8649 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8654 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8656 struct ksmbd_conn *conn = work->conn;
8657 struct ksmbd_session *sess = work->sess;
8658 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8660 if (conn->dialect < SMB30_PROT_ID)
8663 if (work->next_smb2_rcv_hdr_off)
8664 rsp = ksmbd_resp_buf_next(work);
8666 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8667 sess->user && !user_guest(sess->user) &&
8668 rsp->Status == STATUS_SUCCESS)