ksmbd: fix racy issue while destroying session on multichannel
[linux-block.git] / fs / ksmbd / smb2pdu.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5  */
6
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
15
16 #include "glob.h"
17 #include "smbfsctl.h"
18 #include "oplock.h"
19 #include "smbacl.h"
20
21 #include "auth.h"
22 #include "asn1.h"
23 #include "connection.h"
24 #include "transport_ipc.h"
25 #include "transport_rdma.h"
26 #include "vfs.h"
27 #include "vfs_cache.h"
28 #include "misc.h"
29
30 #include "server.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"
39 #include "ndr.h"
40
41 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
42 {
43         if (work->next_smb2_rcv_hdr_off) {
44                 *req = ksmbd_req_buf_next(work);
45                 *rsp = ksmbd_resp_buf_next(work);
46         } else {
47                 *req = smb2_get_msg(work->request_buf);
48                 *rsp = smb2_get_msg(work->response_buf);
49         }
50 }
51
52 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
53
54 /**
55  * check_session_id() - check for valid session id in smb header
56  * @conn:       connection instance
57  * @id:         session id from smb header
58  *
59  * Return:      1 if valid session id, otherwise 0
60  */
61 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
62 {
63         struct ksmbd_session *sess;
64
65         if (id == 0 || id == -1)
66                 return false;
67
68         sess = ksmbd_session_lookup_all(conn, id);
69         if (sess)
70                 return true;
71         pr_err("Invalid user session id: %llu\n", id);
72         return false;
73 }
74
75 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
76 {
77         struct channel *chann;
78
79         list_for_each_entry(chann, &sess->ksmbd_chann_list, chann_list) {
80                 if (chann->conn == conn)
81                         return chann;
82         }
83
84         return NULL;
85 }
86
87 /**
88  * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
89  * @work:       smb work
90  *
91  * Return:      0 if there is a tree connection matched or these are
92  *              skipable commands, otherwise error
93  */
94 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
95 {
96         struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
97         unsigned int cmd = le16_to_cpu(req_hdr->Command);
98         int tree_id;
99
100         work->tcon = NULL;
101         if (cmd == SMB2_TREE_CONNECT_HE ||
102             cmd ==  SMB2_CANCEL_HE ||
103             cmd ==  SMB2_LOGOFF_HE) {
104                 ksmbd_debug(SMB, "skip to check tree connect request\n");
105                 return 0;
106         }
107
108         if (xa_empty(&work->sess->tree_conns)) {
109                 ksmbd_debug(SMB, "NO tree connected\n");
110                 return -ENOENT;
111         }
112
113         tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
114         work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
115         if (!work->tcon) {
116                 pr_err("Invalid tid %d\n", tree_id);
117                 return -EINVAL;
118         }
119
120         return 1;
121 }
122
123 /**
124  * smb2_set_err_rsp() - set error response code on smb response
125  * @work:       smb work containing response buffer
126  */
127 void smb2_set_err_rsp(struct ksmbd_work *work)
128 {
129         struct smb2_err_rsp *err_rsp;
130
131         if (work->next_smb2_rcv_hdr_off)
132                 err_rsp = ksmbd_resp_buf_next(work);
133         else
134                 err_rsp = smb2_get_msg(work->response_buf);
135
136         if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
137                 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
138                 err_rsp->ErrorContextCount = 0;
139                 err_rsp->Reserved = 0;
140                 err_rsp->ByteCount = 0;
141                 err_rsp->ErrorData[0] = 0;
142                 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
143         }
144 }
145
146 /**
147  * is_smb2_neg_cmd() - is it smb2 negotiation command
148  * @work:       smb work containing smb header
149  *
150  * Return:      true if smb2 negotiation command, otherwise false
151  */
152 bool is_smb2_neg_cmd(struct ksmbd_work *work)
153 {
154         struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
155
156         /* is it SMB2 header ? */
157         if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
158                 return false;
159
160         /* make sure it is request not response message */
161         if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
162                 return false;
163
164         if (hdr->Command != SMB2_NEGOTIATE)
165                 return false;
166
167         return true;
168 }
169
170 /**
171  * is_smb2_rsp() - is it smb2 response
172  * @work:       smb work containing smb response buffer
173  *
174  * Return:      true if smb2 response, otherwise false
175  */
176 bool is_smb2_rsp(struct ksmbd_work *work)
177 {
178         struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
179
180         /* is it SMB2 header ? */
181         if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
182                 return false;
183
184         /* make sure it is response not request message */
185         if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
186                 return false;
187
188         return true;
189 }
190
191 /**
192  * get_smb2_cmd_val() - get smb command code from smb header
193  * @work:       smb work containing smb request buffer
194  *
195  * Return:      smb2 request command value
196  */
197 u16 get_smb2_cmd_val(struct ksmbd_work *work)
198 {
199         struct smb2_hdr *rcv_hdr;
200
201         if (work->next_smb2_rcv_hdr_off)
202                 rcv_hdr = ksmbd_req_buf_next(work);
203         else
204                 rcv_hdr = smb2_get_msg(work->request_buf);
205         return le16_to_cpu(rcv_hdr->Command);
206 }
207
208 /**
209  * set_smb2_rsp_status() - set error response code on smb2 header
210  * @work:       smb work containing response buffer
211  * @err:        error response code
212  */
213 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
214 {
215         struct smb2_hdr *rsp_hdr;
216
217         if (work->next_smb2_rcv_hdr_off)
218                 rsp_hdr = ksmbd_resp_buf_next(work);
219         else
220                 rsp_hdr = smb2_get_msg(work->response_buf);
221         rsp_hdr->Status = err;
222         smb2_set_err_rsp(work);
223 }
224
225 /**
226  * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
227  * @work:       smb work containing smb request buffer
228  *
229  * smb2 negotiate response is sent in reply of smb1 negotiate command for
230  * dialect auto-negotiation.
231  */
232 int init_smb2_neg_rsp(struct ksmbd_work *work)
233 {
234         struct smb2_hdr *rsp_hdr;
235         struct smb2_negotiate_rsp *rsp;
236         struct ksmbd_conn *conn = work->conn;
237
238         if (conn->need_neg == false)
239                 return -EINVAL;
240
241         *(__be32 *)work->response_buf =
242                 cpu_to_be32(conn->vals->header_size);
243
244         rsp_hdr = smb2_get_msg(work->response_buf);
245         memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
246         rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
247         rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
248         rsp_hdr->CreditRequest = cpu_to_le16(2);
249         rsp_hdr->Command = SMB2_NEGOTIATE;
250         rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
251         rsp_hdr->NextCommand = 0;
252         rsp_hdr->MessageId = 0;
253         rsp_hdr->Id.SyncId.ProcessId = 0;
254         rsp_hdr->Id.SyncId.TreeId = 0;
255         rsp_hdr->SessionId = 0;
256         memset(rsp_hdr->Signature, 0, 16);
257
258         rsp = smb2_get_msg(work->response_buf);
259
260         WARN_ON(ksmbd_conn_good(work));
261
262         rsp->StructureSize = cpu_to_le16(65);
263         ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
264         rsp->DialectRevision = cpu_to_le16(conn->dialect);
265         /* Not setting conn guid rsp->ServerGUID, as it
266          * not used by client for identifying connection
267          */
268         rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
269         /* Default Max Message Size till SMB2.0, 64K*/
270         rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
271         rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
272         rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
273
274         rsp->SystemTime = cpu_to_le64(ksmbd_systime());
275         rsp->ServerStartTime = 0;
276
277         rsp->SecurityBufferOffset = cpu_to_le16(128);
278         rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
279         ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
280                 le16_to_cpu(rsp->SecurityBufferOffset));
281         inc_rfc1001_len(work->response_buf,
282                         sizeof(struct smb2_negotiate_rsp) -
283                         sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
284                         AUTH_GSS_LENGTH);
285         rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
286         if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
287                 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
288         conn->use_spnego = true;
289
290         ksmbd_conn_set_need_negotiate(work);
291         return 0;
292 }
293
294 /**
295  * smb2_set_rsp_credits() - set number of credits in response buffer
296  * @work:       smb work containing smb response buffer
297  */
298 int smb2_set_rsp_credits(struct ksmbd_work *work)
299 {
300         struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
301         struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
302         struct ksmbd_conn *conn = work->conn;
303         unsigned short credits_requested, aux_max;
304         unsigned short credit_charge, credits_granted = 0;
305
306         if (work->send_no_response)
307                 return 0;
308
309         hdr->CreditCharge = req_hdr->CreditCharge;
310
311         if (conn->total_credits > conn->vals->max_credits) {
312                 hdr->CreditRequest = 0;
313                 pr_err("Total credits overflow: %d\n", conn->total_credits);
314                 return -EINVAL;
315         }
316
317         credit_charge = max_t(unsigned short,
318                               le16_to_cpu(req_hdr->CreditCharge), 1);
319         if (credit_charge > conn->total_credits) {
320                 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
321                             credit_charge, conn->total_credits);
322                 return -EINVAL;
323         }
324
325         conn->total_credits -= credit_charge;
326         conn->outstanding_credits -= credit_charge;
327         credits_requested = max_t(unsigned short,
328                                   le16_to_cpu(req_hdr->CreditRequest), 1);
329
330         /* according to smb2.credits smbtorture, Windows server
331          * 2016 or later grant up to 8192 credits at once.
332          *
333          * TODO: Need to adjuct CreditRequest value according to
334          * current cpu load
335          */
336         if (hdr->Command == SMB2_NEGOTIATE)
337                 aux_max = 1;
338         else
339                 aux_max = conn->vals->max_credits - credit_charge;
340         credits_granted = min_t(unsigned short, credits_requested, aux_max);
341
342         if (conn->vals->max_credits - conn->total_credits < credits_granted)
343                 credits_granted = conn->vals->max_credits -
344                         conn->total_credits;
345
346         conn->total_credits += credits_granted;
347         work->credits_granted += credits_granted;
348
349         if (!req_hdr->NextCommand) {
350                 /* Update CreditRequest in last request */
351                 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
352         }
353         ksmbd_debug(SMB,
354                     "credits: requested[%d] granted[%d] total_granted[%d]\n",
355                     credits_requested, credits_granted,
356                     conn->total_credits);
357         return 0;
358 }
359
360 /**
361  * init_chained_smb2_rsp() - initialize smb2 chained response
362  * @work:       smb work containing smb response buffer
363  */
364 static void init_chained_smb2_rsp(struct ksmbd_work *work)
365 {
366         struct smb2_hdr *req = ksmbd_req_buf_next(work);
367         struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
368         struct smb2_hdr *rsp_hdr;
369         struct smb2_hdr *rcv_hdr;
370         int next_hdr_offset = 0;
371         int len, new_len;
372
373         /* Len of this response = updated RFC len - offset of previous cmd
374          * in the compound rsp
375          */
376
377         /* Storing the current local FID which may be needed by subsequent
378          * command in the compound request
379          */
380         if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
381                 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
382                 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
383                 work->compound_sid = le64_to_cpu(rsp->SessionId);
384         }
385
386         len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
387         next_hdr_offset = le32_to_cpu(req->NextCommand);
388
389         new_len = ALIGN(len, 8);
390         inc_rfc1001_len(work->response_buf,
391                         sizeof(struct smb2_hdr) + new_len - len);
392         rsp->NextCommand = cpu_to_le32(new_len);
393
394         work->next_smb2_rcv_hdr_off += next_hdr_offset;
395         work->next_smb2_rsp_hdr_off += new_len;
396         ksmbd_debug(SMB,
397                     "Compound req new_len = %d rcv off = %d rsp off = %d\n",
398                     new_len, work->next_smb2_rcv_hdr_off,
399                     work->next_smb2_rsp_hdr_off);
400
401         rsp_hdr = ksmbd_resp_buf_next(work);
402         rcv_hdr = ksmbd_req_buf_next(work);
403
404         if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
405                 ksmbd_debug(SMB, "related flag should be set\n");
406                 work->compound_fid = KSMBD_NO_FID;
407                 work->compound_pfid = KSMBD_NO_FID;
408         }
409         memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
410         rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
411         rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
412         rsp_hdr->Command = rcv_hdr->Command;
413
414         /*
415          * Message is response. We don't grant oplock yet.
416          */
417         rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
418                                 SMB2_FLAGS_RELATED_OPERATIONS);
419         rsp_hdr->NextCommand = 0;
420         rsp_hdr->MessageId = rcv_hdr->MessageId;
421         rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
422         rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
423         rsp_hdr->SessionId = rcv_hdr->SessionId;
424         memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
425 }
426
427 /**
428  * is_chained_smb2_message() - check for chained command
429  * @work:       smb work containing smb request buffer
430  *
431  * Return:      true if chained request, otherwise false
432  */
433 bool is_chained_smb2_message(struct ksmbd_work *work)
434 {
435         struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
436         unsigned int len, next_cmd;
437
438         if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
439                 return false;
440
441         hdr = ksmbd_req_buf_next(work);
442         next_cmd = le32_to_cpu(hdr->NextCommand);
443         if (next_cmd > 0) {
444                 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
445                         __SMB2_HEADER_STRUCTURE_SIZE >
446                     get_rfc1002_len(work->request_buf)) {
447                         pr_err("next command(%u) offset exceeds smb msg size\n",
448                                next_cmd);
449                         return false;
450                 }
451
452                 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
453                     work->response_sz) {
454                         pr_err("next response offset exceeds response buffer size\n");
455                         return false;
456                 }
457
458                 ksmbd_debug(SMB, "got SMB2 chained command\n");
459                 init_chained_smb2_rsp(work);
460                 return true;
461         } else if (work->next_smb2_rcv_hdr_off) {
462                 /*
463                  * This is last request in chained command,
464                  * align response to 8 byte
465                  */
466                 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
467                 len = len - get_rfc1002_len(work->response_buf);
468                 if (len) {
469                         ksmbd_debug(SMB, "padding len %u\n", len);
470                         inc_rfc1001_len(work->response_buf, len);
471                         if (work->aux_payload_sz)
472                                 work->aux_payload_sz += len;
473                 }
474         }
475         return false;
476 }
477
478 /**
479  * init_smb2_rsp_hdr() - initialize smb2 response
480  * @work:       smb work containing smb request buffer
481  *
482  * Return:      0
483  */
484 int init_smb2_rsp_hdr(struct ksmbd_work *work)
485 {
486         struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
487         struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
488         struct ksmbd_conn *conn = work->conn;
489
490         memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
491         *(__be32 *)work->response_buf =
492                 cpu_to_be32(conn->vals->header_size);
493         rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
494         rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
495         rsp_hdr->Command = rcv_hdr->Command;
496
497         /*
498          * Message is response. We don't grant oplock yet.
499          */
500         rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
501         rsp_hdr->NextCommand = 0;
502         rsp_hdr->MessageId = rcv_hdr->MessageId;
503         rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
504         rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
505         rsp_hdr->SessionId = rcv_hdr->SessionId;
506         memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
507
508         work->syncronous = true;
509         if (work->async_id) {
510                 ksmbd_release_id(&conn->async_ida, work->async_id);
511                 work->async_id = 0;
512         }
513
514         return 0;
515 }
516
517 /**
518  * smb2_allocate_rsp_buf() - allocate smb2 response buffer
519  * @work:       smb work containing smb request buffer
520  *
521  * Return:      0 on success, otherwise -ENOMEM
522  */
523 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
524 {
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);
530
531         if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
532                 sz = large_sz;
533
534         if (cmd == SMB2_QUERY_INFO_HE) {
535                 struct smb2_query_info_req *req;
536
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                         sz = large_sz;
542         }
543
544         /* allocate large response buf for chained commands */
545         if (le32_to_cpu(hdr->NextCommand) > 0)
546                 sz = large_sz;
547
548         work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
549         if (!work->response_buf)
550                 return -ENOMEM;
551
552         work->response_sz = sz;
553         return 0;
554 }
555
556 /**
557  * smb2_check_user_session() - check for valid session for a user
558  * @work:       smb work containing smb request buffer
559  *
560  * Return:      0 on success, otherwise error
561  */
562 int smb2_check_user_session(struct ksmbd_work *work)
563 {
564         struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
565         struct ksmbd_conn *conn = work->conn;
566         unsigned int cmd = conn->ops->get_cmd_val(work);
567         unsigned long long sess_id;
568
569         work->sess = NULL;
570         /*
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
573          * these commands.
574          */
575         if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
576             cmd == SMB2_SESSION_SETUP_HE)
577                 return 0;
578
579         if (!ksmbd_conn_good(work))
580                 return -EINVAL;
581
582         sess_id = le64_to_cpu(req_hdr->SessionId);
583         /* Check for validity of user session */
584         work->sess = ksmbd_session_lookup_all(conn, sess_id);
585         if (work->sess)
586                 return 1;
587         ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
588         return -EINVAL;
589 }
590
591 static void destroy_previous_session(struct ksmbd_conn *conn,
592                                      struct ksmbd_user *user, u64 id)
593 {
594         struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
595         struct ksmbd_user *prev_user;
596         struct channel *chann;
597
598         if (!prev_sess)
599                 return;
600
601         prev_user = prev_sess->user;
602
603         if (!prev_user ||
604             strcmp(user->name, prev_user->name) ||
605             user->passkey_sz != prev_user->passkey_sz ||
606             memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
607                 return;
608
609         prev_sess->state = SMB2_SESSION_EXPIRED;
610         write_lock(&prev_sess->chann_lock);
611         list_for_each_entry(chann, &prev_sess->ksmbd_chann_list, chann_list)
612                 chann->conn->status = KSMBD_SESS_EXITING;
613         write_unlock(&prev_sess->chann_lock);
614 }
615
616 /**
617  * smb2_get_name() - get filename string from on the wire smb format
618  * @src:        source buffer
619  * @maxlen:     maxlen of source string
620  * @local_nls:  nls_table pointer
621  *
622  * Return:      matching converted filename on success, otherwise error ptr
623  */
624 static char *
625 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
626 {
627         char *name;
628
629         name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
630         if (IS_ERR(name)) {
631                 pr_err("failed to get name %ld\n", PTR_ERR(name));
632                 return name;
633         }
634
635         ksmbd_conv_path_to_unix(name);
636         ksmbd_strip_last_slash(name);
637         return name;
638 }
639
640 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
641 {
642         struct smb2_hdr *rsp_hdr;
643         struct ksmbd_conn *conn = work->conn;
644         int id;
645
646         rsp_hdr = smb2_get_msg(work->response_buf);
647         rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
648
649         id = ksmbd_acquire_async_msg_id(&conn->async_ida);
650         if (id < 0) {
651                 pr_err("Failed to alloc async message id\n");
652                 return id;
653         }
654         work->syncronous = false;
655         work->async_id = id;
656         rsp_hdr->Id.AsyncId = cpu_to_le64(id);
657
658         ksmbd_debug(SMB,
659                     "Send interim Response to inform async request id : %d\n",
660                     work->async_id);
661
662         work->cancel_fn = fn;
663         work->cancel_argv = arg;
664
665         if (list_empty(&work->async_request_entry)) {
666                 spin_lock(&conn->request_lock);
667                 list_add_tail(&work->async_request_entry, &conn->async_requests);
668                 spin_unlock(&conn->request_lock);
669         }
670
671         return 0;
672 }
673
674 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
675 {
676         struct smb2_hdr *rsp_hdr;
677
678         rsp_hdr = smb2_get_msg(work->response_buf);
679         smb2_set_err_rsp(work);
680         rsp_hdr->Status = status;
681
682         work->multiRsp = 1;
683         ksmbd_conn_write(work);
684         rsp_hdr->Status = 0;
685         work->multiRsp = 0;
686 }
687
688 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
689 {
690         if (S_ISDIR(mode) || S_ISREG(mode))
691                 return 0;
692
693         if (S_ISLNK(mode))
694                 return IO_REPARSE_TAG_LX_SYMLINK_LE;
695         else if (S_ISFIFO(mode))
696                 return IO_REPARSE_TAG_LX_FIFO_LE;
697         else if (S_ISSOCK(mode))
698                 return IO_REPARSE_TAG_AF_UNIX_LE;
699         else if (S_ISCHR(mode))
700                 return IO_REPARSE_TAG_LX_CHR_LE;
701         else if (S_ISBLK(mode))
702                 return IO_REPARSE_TAG_LX_BLK_LE;
703
704         return 0;
705 }
706
707 /**
708  * smb2_get_dos_mode() - get file mode in dos format from unix mode
709  * @stat:       kstat containing file mode
710  * @attribute:  attribute flags
711  *
712  * Return:      converted dos mode
713  */
714 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
715 {
716         int attr = 0;
717
718         if (S_ISDIR(stat->mode)) {
719                 attr = FILE_ATTRIBUTE_DIRECTORY |
720                         (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
721         } else {
722                 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
723                 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
724                 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
725                                 FILE_SUPPORTS_SPARSE_FILES))
726                         attr |= FILE_ATTRIBUTE_SPARSE_FILE;
727
728                 if (smb2_get_reparse_tag_special_file(stat->mode))
729                         attr |= FILE_ATTRIBUTE_REPARSE_POINT;
730         }
731
732         return attr;
733 }
734
735 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
736                                __le16 hash_id)
737 {
738         pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
739         pneg_ctxt->DataLength = cpu_to_le16(38);
740         pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
741         pneg_ctxt->Reserved = cpu_to_le32(0);
742         pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
743         get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
744         pneg_ctxt->HashAlgorithms = hash_id;
745 }
746
747 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
748                                __le16 cipher_type)
749 {
750         pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
751         pneg_ctxt->DataLength = cpu_to_le16(4);
752         pneg_ctxt->Reserved = cpu_to_le32(0);
753         pneg_ctxt->CipherCount = cpu_to_le16(1);
754         pneg_ctxt->Ciphers[0] = cipher_type;
755 }
756
757 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
758                                    __le16 comp_algo)
759 {
760         pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
761         pneg_ctxt->DataLength =
762                 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
763                         - sizeof(struct smb2_neg_context));
764         pneg_ctxt->Reserved = cpu_to_le32(0);
765         pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
766         pneg_ctxt->Flags = cpu_to_le32(0);
767         pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
768 }
769
770 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
771                                 __le16 sign_algo)
772 {
773         pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
774         pneg_ctxt->DataLength =
775                 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
776                         - sizeof(struct smb2_neg_context));
777         pneg_ctxt->Reserved = cpu_to_le32(0);
778         pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
779         pneg_ctxt->SigningAlgorithms[0] = sign_algo;
780 }
781
782 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
783 {
784         pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
785         pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
786         /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
787         pneg_ctxt->Name[0] = 0x93;
788         pneg_ctxt->Name[1] = 0xAD;
789         pneg_ctxt->Name[2] = 0x25;
790         pneg_ctxt->Name[3] = 0x50;
791         pneg_ctxt->Name[4] = 0x9C;
792         pneg_ctxt->Name[5] = 0xB4;
793         pneg_ctxt->Name[6] = 0x11;
794         pneg_ctxt->Name[7] = 0xE7;
795         pneg_ctxt->Name[8] = 0xB4;
796         pneg_ctxt->Name[9] = 0x23;
797         pneg_ctxt->Name[10] = 0x83;
798         pneg_ctxt->Name[11] = 0xDE;
799         pneg_ctxt->Name[12] = 0x96;
800         pneg_ctxt->Name[13] = 0x8B;
801         pneg_ctxt->Name[14] = 0xCD;
802         pneg_ctxt->Name[15] = 0x7C;
803 }
804
805 static void assemble_neg_contexts(struct ksmbd_conn *conn,
806                                   struct smb2_negotiate_rsp *rsp,
807                                   void *smb2_buf_len)
808 {
809         char *pneg_ctxt = (char *)rsp +
810                         le32_to_cpu(rsp->NegotiateContextOffset);
811         int neg_ctxt_cnt = 1;
812         int ctxt_size;
813
814         ksmbd_debug(SMB,
815                     "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
816         build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
817                            conn->preauth_info->Preauth_HashId);
818         rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
819         inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
820         ctxt_size = sizeof(struct smb2_preauth_neg_context);
821         /* Round to 8 byte boundary */
822         pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
823
824         if (conn->cipher_type) {
825                 ctxt_size = round_up(ctxt_size, 8);
826                 ksmbd_debug(SMB,
827                             "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
828                 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
829                                    conn->cipher_type);
830                 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
831                 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
832                 /* Round to 8 byte boundary */
833                 pneg_ctxt +=
834                         round_up(sizeof(struct smb2_encryption_neg_context) + 2,
835                                  8);
836         }
837
838         if (conn->compress_algorithm) {
839                 ctxt_size = round_up(ctxt_size, 8);
840                 ksmbd_debug(SMB,
841                             "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
842                 /* Temporarily set to SMB3_COMPRESS_NONE */
843                 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
844                                        conn->compress_algorithm);
845                 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
846                 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
847                 /* Round to 8 byte boundary */
848                 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
849                                       8);
850         }
851
852         if (conn->posix_ext_supported) {
853                 ctxt_size = round_up(ctxt_size, 8);
854                 ksmbd_debug(SMB,
855                             "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
856                 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
857                 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
858                 ctxt_size += sizeof(struct smb2_posix_neg_context);
859                 /* Round to 8 byte boundary */
860                 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
861         }
862
863         if (conn->signing_negotiated) {
864                 ctxt_size = round_up(ctxt_size, 8);
865                 ksmbd_debug(SMB,
866                             "assemble SMB2_SIGNING_CAPABILITIES context\n");
867                 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
868                                     conn->signing_algorithm);
869                 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
870                 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
871         }
872
873         inc_rfc1001_len(smb2_buf_len, ctxt_size);
874 }
875
876 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
877                                   struct smb2_preauth_neg_context *pneg_ctxt)
878 {
879         __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
880
881         if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
882                 conn->preauth_info->Preauth_HashId =
883                         SMB2_PREAUTH_INTEGRITY_SHA512;
884                 err = STATUS_SUCCESS;
885         }
886
887         return err;
888 }
889
890 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
891                                 struct smb2_encryption_neg_context *pneg_ctxt,
892                                 int len_of_ctxts)
893 {
894         int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
895         int i, cphs_size = cph_cnt * sizeof(__le16);
896
897         conn->cipher_type = 0;
898
899         if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
900             len_of_ctxts) {
901                 pr_err("Invalid cipher count(%d)\n", cph_cnt);
902                 return;
903         }
904
905         if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
906                 return;
907
908         for (i = 0; i < cph_cnt; i++) {
909                 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
910                     pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
911                     pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
912                     pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
913                         ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
914                                     pneg_ctxt->Ciphers[i]);
915                         conn->cipher_type = pneg_ctxt->Ciphers[i];
916                         break;
917                 }
918         }
919 }
920
921 /**
922  * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
923  * @conn:       smb connection
924  *
925  * Return:      true if connection should be encrypted, else false
926  */
927 static bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
928 {
929         if (!conn->ops->generate_encryptionkey)
930                 return false;
931
932         /*
933          * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
934          * SMB 3.1.1 uses the cipher_type field.
935          */
936         return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
937             conn->cipher_type;
938 }
939
940 static void decode_compress_ctxt(struct ksmbd_conn *conn,
941                                  struct smb2_compression_capabilities_context *pneg_ctxt)
942 {
943         conn->compress_algorithm = SMB3_COMPRESS_NONE;
944 }
945
946 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
947                                  struct smb2_signing_capabilities *pneg_ctxt,
948                                  int len_of_ctxts)
949 {
950         int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
951         int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
952
953         conn->signing_negotiated = false;
954
955         if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
956             len_of_ctxts) {
957                 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
958                 return;
959         }
960
961         for (i = 0; i < sign_algo_cnt; i++) {
962                 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
963                     pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
964                         ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
965                                     pneg_ctxt->SigningAlgorithms[i]);
966                         conn->signing_negotiated = true;
967                         conn->signing_algorithm =
968                                 pneg_ctxt->SigningAlgorithms[i];
969                         break;
970                 }
971         }
972 }
973
974 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
975                                       struct smb2_negotiate_req *req,
976                                       int len_of_smb)
977 {
978         /* +4 is to account for the RFC1001 len field */
979         struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
980         int i = 0, len_of_ctxts;
981         int offset = le32_to_cpu(req->NegotiateContextOffset);
982         int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
983         __le32 status = STATUS_INVALID_PARAMETER;
984
985         ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
986         if (len_of_smb <= offset) {
987                 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
988                 return status;
989         }
990
991         len_of_ctxts = len_of_smb - offset;
992
993         while (i++ < neg_ctxt_cnt) {
994                 int clen;
995
996                 /* check that offset is not beyond end of SMB */
997                 if (len_of_ctxts == 0)
998                         break;
999
1000                 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1001                         break;
1002
1003                 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1004                 clen = le16_to_cpu(pctx->DataLength);
1005                 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1006                         break;
1007
1008                 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1009                         ksmbd_debug(SMB,
1010                                     "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1011                         if (conn->preauth_info->Preauth_HashId)
1012                                 break;
1013
1014                         status = decode_preauth_ctxt(conn,
1015                                                      (struct smb2_preauth_neg_context *)pctx);
1016                         if (status != STATUS_SUCCESS)
1017                                 break;
1018                 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1019                         ksmbd_debug(SMB,
1020                                     "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1021                         if (conn->cipher_type)
1022                                 break;
1023
1024                         decode_encrypt_ctxt(conn,
1025                                             (struct smb2_encryption_neg_context *)pctx,
1026                                             len_of_ctxts);
1027                 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1028                         ksmbd_debug(SMB,
1029                                     "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1030                         if (conn->compress_algorithm)
1031                                 break;
1032
1033                         decode_compress_ctxt(conn,
1034                                              (struct smb2_compression_capabilities_context *)pctx);
1035                 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1036                         ksmbd_debug(SMB,
1037                                     "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1038                 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1039                         ksmbd_debug(SMB,
1040                                     "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1041                         conn->posix_ext_supported = true;
1042                 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1043                         ksmbd_debug(SMB,
1044                                     "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1045                         decode_sign_cap_ctxt(conn,
1046                                              (struct smb2_signing_capabilities *)pctx,
1047                                              len_of_ctxts);
1048                 }
1049
1050                 /* offsets must be 8 byte aligned */
1051                 clen = (clen + 7) & ~0x7;
1052                 offset = clen + sizeof(struct smb2_neg_context);
1053                 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1054         }
1055         return status;
1056 }
1057
1058 /**
1059  * smb2_handle_negotiate() - handler for smb2 negotiate command
1060  * @work:       smb work containing smb request buffer
1061  *
1062  * Return:      0
1063  */
1064 int smb2_handle_negotiate(struct ksmbd_work *work)
1065 {
1066         struct ksmbd_conn *conn = work->conn;
1067         struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1068         struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1069         int rc = 0;
1070         unsigned int smb2_buf_len, smb2_neg_size;
1071         __le32 status;
1072
1073         ksmbd_debug(SMB, "Received negotiate request\n");
1074         conn->need_neg = false;
1075         if (ksmbd_conn_good(work)) {
1076                 pr_err("conn->tcp_status is already in CifsGood State\n");
1077                 work->send_no_response = 1;
1078                 return rc;
1079         }
1080
1081         if (req->DialectCount == 0) {
1082                 pr_err("malformed packet\n");
1083                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1084                 rc = -EINVAL;
1085                 goto err_out;
1086         }
1087
1088         smb2_buf_len = get_rfc1002_len(work->request_buf);
1089         smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1090         if (smb2_neg_size > smb2_buf_len) {
1091                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1092                 rc = -EINVAL;
1093                 goto err_out;
1094         }
1095
1096         if (conn->dialect == SMB311_PROT_ID) {
1097                 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1098
1099                 if (smb2_buf_len < nego_ctxt_off) {
1100                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1101                         rc = -EINVAL;
1102                         goto err_out;
1103                 }
1104
1105                 if (smb2_neg_size > nego_ctxt_off) {
1106                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1107                         rc = -EINVAL;
1108                         goto err_out;
1109                 }
1110
1111                 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1112                     nego_ctxt_off) {
1113                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1114                         rc = -EINVAL;
1115                         goto err_out;
1116                 }
1117         } else {
1118                 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1119                     smb2_buf_len) {
1120                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1121                         rc = -EINVAL;
1122                         goto err_out;
1123                 }
1124         }
1125
1126         conn->cli_cap = le32_to_cpu(req->Capabilities);
1127         switch (conn->dialect) {
1128         case SMB311_PROT_ID:
1129                 conn->preauth_info =
1130                         kzalloc(sizeof(struct preauth_integrity_info),
1131                                 GFP_KERNEL);
1132                 if (!conn->preauth_info) {
1133                         rc = -ENOMEM;
1134                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1135                         goto err_out;
1136                 }
1137
1138                 status = deassemble_neg_contexts(conn, req,
1139                                                  get_rfc1002_len(work->request_buf));
1140                 if (status != STATUS_SUCCESS) {
1141                         pr_err("deassemble_neg_contexts error(0x%x)\n",
1142                                status);
1143                         rsp->hdr.Status = status;
1144                         rc = -EINVAL;
1145                         goto err_out;
1146                 }
1147
1148                 rc = init_smb3_11_server(conn);
1149                 if (rc < 0) {
1150                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1151                         goto err_out;
1152                 }
1153
1154                 ksmbd_gen_preauth_integrity_hash(conn,
1155                                                  work->request_buf,
1156                                                  conn->preauth_info->Preauth_HashValue);
1157                 rsp->NegotiateContextOffset =
1158                                 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1159                 assemble_neg_contexts(conn, rsp, work->response_buf);
1160                 break;
1161         case SMB302_PROT_ID:
1162                 init_smb3_02_server(conn);
1163                 break;
1164         case SMB30_PROT_ID:
1165                 init_smb3_0_server(conn);
1166                 break;
1167         case SMB21_PROT_ID:
1168                 init_smb2_1_server(conn);
1169                 break;
1170         case SMB2X_PROT_ID:
1171         case BAD_PROT_ID:
1172         default:
1173                 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1174                             conn->dialect);
1175                 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1176                 rc = -EINVAL;
1177                 goto err_out;
1178         }
1179         rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1180
1181         /* For stats */
1182         conn->connection_type = conn->dialect;
1183
1184         rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1185         rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1186         rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1187
1188         memcpy(conn->ClientGUID, req->ClientGUID,
1189                         SMB2_CLIENT_GUID_SIZE);
1190         conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1191
1192         rsp->StructureSize = cpu_to_le16(65);
1193         rsp->DialectRevision = cpu_to_le16(conn->dialect);
1194         /* Not setting conn guid rsp->ServerGUID, as it
1195          * not used by client for identifying server
1196          */
1197         memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1198
1199         rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1200         rsp->ServerStartTime = 0;
1201         ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1202                     le32_to_cpu(rsp->NegotiateContextOffset),
1203                     le16_to_cpu(rsp->NegotiateContextCount));
1204
1205         rsp->SecurityBufferOffset = cpu_to_le16(128);
1206         rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1207         ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1208                                   le16_to_cpu(rsp->SecurityBufferOffset));
1209         inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1210                         sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1211                          AUTH_GSS_LENGTH);
1212         rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1213         conn->use_spnego = true;
1214
1215         if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1216              server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1217             req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1218                 conn->sign = true;
1219         else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1220                 server_conf.enforced_signing = true;
1221                 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1222                 conn->sign = true;
1223         }
1224
1225         conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1226         ksmbd_conn_set_need_negotiate(work);
1227
1228 err_out:
1229         if (rc < 0)
1230                 smb2_set_err_rsp(work);
1231
1232         return rc;
1233 }
1234
1235 static int alloc_preauth_hash(struct ksmbd_session *sess,
1236                               struct ksmbd_conn *conn)
1237 {
1238         if (sess->Preauth_HashValue)
1239                 return 0;
1240
1241         sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1242                                           PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1243         if (!sess->Preauth_HashValue)
1244                 return -ENOMEM;
1245
1246         return 0;
1247 }
1248
1249 static int generate_preauth_hash(struct ksmbd_work *work)
1250 {
1251         struct ksmbd_conn *conn = work->conn;
1252         struct ksmbd_session *sess = work->sess;
1253         u8 *preauth_hash;
1254
1255         if (conn->dialect != SMB311_PROT_ID)
1256                 return 0;
1257
1258         if (conn->binding) {
1259                 struct preauth_session *preauth_sess;
1260
1261                 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1262                 if (!preauth_sess) {
1263                         preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1264                         if (!preauth_sess)
1265                                 return -ENOMEM;
1266                 }
1267
1268                 preauth_hash = preauth_sess->Preauth_HashValue;
1269         } else {
1270                 if (!sess->Preauth_HashValue)
1271                         if (alloc_preauth_hash(sess, conn))
1272                                 return -ENOMEM;
1273                 preauth_hash = sess->Preauth_HashValue;
1274         }
1275
1276         ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1277         return 0;
1278 }
1279
1280 static int decode_negotiation_token(struct ksmbd_conn *conn,
1281                                     struct negotiate_message *negblob,
1282                                     size_t sz)
1283 {
1284         if (!conn->use_spnego)
1285                 return -EINVAL;
1286
1287         if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1288                 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1289                         conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1290                         conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1291                         conn->use_spnego = false;
1292                 }
1293         }
1294         return 0;
1295 }
1296
1297 static int ntlm_negotiate(struct ksmbd_work *work,
1298                           struct negotiate_message *negblob,
1299                           size_t negblob_len)
1300 {
1301         struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1302         struct challenge_message *chgblob;
1303         unsigned char *spnego_blob = NULL;
1304         u16 spnego_blob_len;
1305         char *neg_blob;
1306         int sz, rc;
1307
1308         ksmbd_debug(SMB, "negotiate phase\n");
1309         rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1310         if (rc)
1311                 return rc;
1312
1313         sz = le16_to_cpu(rsp->SecurityBufferOffset);
1314         chgblob =
1315                 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1316         memset(chgblob, 0, sizeof(struct challenge_message));
1317
1318         if (!work->conn->use_spnego) {
1319                 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1320                 if (sz < 0)
1321                         return -ENOMEM;
1322
1323                 rsp->SecurityBufferLength = cpu_to_le16(sz);
1324                 return 0;
1325         }
1326
1327         sz = sizeof(struct challenge_message);
1328         sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1329
1330         neg_blob = kzalloc(sz, GFP_KERNEL);
1331         if (!neg_blob)
1332                 return -ENOMEM;
1333
1334         chgblob = (struct challenge_message *)neg_blob;
1335         sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1336         if (sz < 0) {
1337                 rc = -ENOMEM;
1338                 goto out;
1339         }
1340
1341         rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1342                                            neg_blob, sz);
1343         if (rc) {
1344                 rc = -ENOMEM;
1345                 goto out;
1346         }
1347
1348         sz = le16_to_cpu(rsp->SecurityBufferOffset);
1349         memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1350         rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1351
1352 out:
1353         kfree(spnego_blob);
1354         kfree(neg_blob);
1355         return rc;
1356 }
1357
1358 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1359                                                   struct smb2_sess_setup_req *req)
1360 {
1361         int sz;
1362
1363         if (conn->use_spnego && conn->mechToken)
1364                 return (struct authenticate_message *)conn->mechToken;
1365
1366         sz = le16_to_cpu(req->SecurityBufferOffset);
1367         return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1368                                                + sz);
1369 }
1370
1371 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1372                                        struct smb2_sess_setup_req *req)
1373 {
1374         struct authenticate_message *authblob;
1375         struct ksmbd_user *user;
1376         char *name;
1377         unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1378
1379         secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1380         if (secbuf_len < sizeof(struct authenticate_message)) {
1381                 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1382                 return NULL;
1383         }
1384         authblob = user_authblob(conn, req);
1385         name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1386         name_len = le16_to_cpu(authblob->UserName.Length);
1387         auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1388
1389         if (auth_msg_len < (u64)name_off + name_len)
1390                 return NULL;
1391
1392         name = smb_strndup_from_utf16((const char *)authblob + name_off,
1393                                       name_len,
1394                                       true,
1395                                       conn->local_nls);
1396         if (IS_ERR(name)) {
1397                 pr_err("cannot allocate memory\n");
1398                 return NULL;
1399         }
1400
1401         ksmbd_debug(SMB, "session setup request for user %s\n", name);
1402         user = ksmbd_login_user(name);
1403         kfree(name);
1404         return user;
1405 }
1406
1407 static int ntlm_authenticate(struct ksmbd_work *work)
1408 {
1409         struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1410         struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1411         struct ksmbd_conn *conn = work->conn;
1412         struct ksmbd_session *sess = work->sess;
1413         struct channel *chann = NULL;
1414         struct ksmbd_user *user;
1415         u64 prev_id;
1416         int sz, rc;
1417
1418         ksmbd_debug(SMB, "authenticate phase\n");
1419         if (conn->use_spnego) {
1420                 unsigned char *spnego_blob;
1421                 u16 spnego_blob_len;
1422
1423                 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1424                                                     &spnego_blob_len,
1425                                                     0);
1426                 if (rc)
1427                         return -ENOMEM;
1428
1429                 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1430                 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1431                 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1432                 kfree(spnego_blob);
1433                 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1434         }
1435
1436         user = session_user(conn, req);
1437         if (!user) {
1438                 ksmbd_debug(SMB, "Unknown user name or an error\n");
1439                 return -EPERM;
1440         }
1441
1442         /* Check for previous session */
1443         prev_id = le64_to_cpu(req->PreviousSessionId);
1444         if (prev_id && prev_id != sess->id)
1445                 destroy_previous_session(conn, user, prev_id);
1446
1447         if (sess->state == SMB2_SESSION_VALID) {
1448                 /*
1449                  * Reuse session if anonymous try to connect
1450                  * on reauthetication.
1451                  */
1452                 if (ksmbd_anonymous_user(user)) {
1453                         ksmbd_free_user(user);
1454                         return 0;
1455                 }
1456
1457                 if (!ksmbd_compare_user(sess->user, user)) {
1458                         ksmbd_free_user(user);
1459                         return -EPERM;
1460                 }
1461                 ksmbd_free_user(user);
1462         } else {
1463                 sess->user = user;
1464         }
1465
1466         if (user_guest(sess->user)) {
1467                 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1468         } else {
1469                 struct authenticate_message *authblob;
1470
1471                 authblob = user_authblob(conn, req);
1472                 sz = le16_to_cpu(req->SecurityBufferLength);
1473                 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1474                 if (rc) {
1475                         set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1476                         ksmbd_debug(SMB, "authentication failed\n");
1477                         return -EPERM;
1478                 }
1479         }
1480
1481         /*
1482          * If session state is SMB2_SESSION_VALID, We can assume
1483          * that it is reauthentication. And the user/password
1484          * has been verified, so return it here.
1485          */
1486         if (sess->state == SMB2_SESSION_VALID) {
1487                 if (conn->binding)
1488                         goto binding_session;
1489                 return 0;
1490         }
1491
1492         if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1493              (conn->sign || server_conf.enforced_signing)) ||
1494             (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1495                 sess->sign = true;
1496
1497         if (smb3_encryption_negotiated(conn) &&
1498                         !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1499                 rc = conn->ops->generate_encryptionkey(conn, sess);
1500                 if (rc) {
1501                         ksmbd_debug(SMB,
1502                                         "SMB3 encryption key generation failed\n");
1503                         return -EINVAL;
1504                 }
1505                 sess->enc = true;
1506                 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1507                 /*
1508                  * signing is disable if encryption is enable
1509                  * on this session
1510                  */
1511                 sess->sign = false;
1512         }
1513
1514 binding_session:
1515         if (conn->dialect >= SMB30_PROT_ID) {
1516                 read_lock(&sess->chann_lock);
1517                 chann = lookup_chann_list(sess, conn);
1518                 read_unlock(&sess->chann_lock);
1519                 if (!chann) {
1520                         chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1521                         if (!chann)
1522                                 return -ENOMEM;
1523
1524                         chann->conn = conn;
1525                         INIT_LIST_HEAD(&chann->chann_list);
1526                         write_lock(&sess->chann_lock);
1527                         list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1528                         write_unlock(&sess->chann_lock);
1529                 }
1530         }
1531
1532         if (conn->ops->generate_signingkey) {
1533                 rc = conn->ops->generate_signingkey(sess, conn);
1534                 if (rc) {
1535                         ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1536                         return -EINVAL;
1537                 }
1538         }
1539
1540         if (!ksmbd_conn_lookup_dialect(conn)) {
1541                 pr_err("fail to verify the dialect\n");
1542                 return -ENOENT;
1543         }
1544         return 0;
1545 }
1546
1547 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1548 static int krb5_authenticate(struct ksmbd_work *work)
1549 {
1550         struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1551         struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1552         struct ksmbd_conn *conn = work->conn;
1553         struct ksmbd_session *sess = work->sess;
1554         char *in_blob, *out_blob;
1555         struct channel *chann = NULL;
1556         u64 prev_sess_id;
1557         int in_len, out_len;
1558         int retval;
1559
1560         in_blob = (char *)&req->hdr.ProtocolId +
1561                 le16_to_cpu(req->SecurityBufferOffset);
1562         in_len = le16_to_cpu(req->SecurityBufferLength);
1563         out_blob = (char *)&rsp->hdr.ProtocolId +
1564                 le16_to_cpu(rsp->SecurityBufferOffset);
1565         out_len = work->response_sz -
1566                 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1567
1568         /* Check previous session */
1569         prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1570         if (prev_sess_id && prev_sess_id != sess->id)
1571                 destroy_previous_session(conn, sess->user, prev_sess_id);
1572
1573         if (sess->state == SMB2_SESSION_VALID)
1574                 ksmbd_free_user(sess->user);
1575
1576         retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1577                                          out_blob, &out_len);
1578         if (retval) {
1579                 ksmbd_debug(SMB, "krb5 authentication failed\n");
1580                 return -EINVAL;
1581         }
1582         rsp->SecurityBufferLength = cpu_to_le16(out_len);
1583         inc_rfc1001_len(work->response_buf, out_len - 1);
1584
1585         if ((conn->sign || server_conf.enforced_signing) ||
1586             (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1587                 sess->sign = true;
1588
1589         if (smb3_encryption_negotiated(conn)) {
1590                 retval = conn->ops->generate_encryptionkey(conn, sess);
1591                 if (retval) {
1592                         ksmbd_debug(SMB,
1593                                     "SMB3 encryption key generation failed\n");
1594                         return -EINVAL;
1595                 }
1596                 sess->enc = true;
1597                 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1598                 sess->sign = false;
1599         }
1600
1601         if (conn->dialect >= SMB30_PROT_ID) {
1602                 read_lock(&sess->chann_lock);
1603                 chann = lookup_chann_list(sess, conn);
1604                 read_unlock(&sess->chann_lock);
1605                 if (!chann) {
1606                         chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1607                         if (!chann)
1608                                 return -ENOMEM;
1609
1610                         chann->conn = conn;
1611                         INIT_LIST_HEAD(&chann->chann_list);
1612                         write_lock(&sess->chann_lock);
1613                         list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1614                         write_unlock(&sess->chann_lock);
1615                 }
1616         }
1617
1618         if (conn->ops->generate_signingkey) {
1619                 retval = conn->ops->generate_signingkey(sess, conn);
1620                 if (retval) {
1621                         ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1622                         return -EINVAL;
1623                 }
1624         }
1625
1626         if (!ksmbd_conn_lookup_dialect(conn)) {
1627                 pr_err("fail to verify the dialect\n");
1628                 return -ENOENT;
1629         }
1630         return 0;
1631 }
1632 #else
1633 static int krb5_authenticate(struct ksmbd_work *work)
1634 {
1635         return -EOPNOTSUPP;
1636 }
1637 #endif
1638
1639 int smb2_sess_setup(struct ksmbd_work *work)
1640 {
1641         struct ksmbd_conn *conn = work->conn;
1642         struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1643         struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1644         struct ksmbd_session *sess;
1645         struct negotiate_message *negblob;
1646         unsigned int negblob_len, negblob_off;
1647         int rc = 0;
1648
1649         ksmbd_debug(SMB, "Received request for session setup\n");
1650
1651         rsp->StructureSize = cpu_to_le16(9);
1652         rsp->SessionFlags = 0;
1653         rsp->SecurityBufferOffset = cpu_to_le16(72);
1654         rsp->SecurityBufferLength = 0;
1655         inc_rfc1001_len(work->response_buf, 9);
1656
1657         if (!req->hdr.SessionId) {
1658                 sess = ksmbd_smb2_session_create();
1659                 if (!sess) {
1660                         rc = -ENOMEM;
1661                         goto out_err;
1662                 }
1663                 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1664                 rc = ksmbd_session_register(conn, sess);
1665                 if (rc)
1666                         goto out_err;
1667         } else if (conn->dialect >= SMB30_PROT_ID &&
1668                    (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1669                    req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1670                 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1671
1672                 sess = ksmbd_session_lookup_slowpath(sess_id);
1673                 if (!sess) {
1674                         rc = -ENOENT;
1675                         goto out_err;
1676                 }
1677
1678                 if (conn->dialect != sess->dialect) {
1679                         rc = -EINVAL;
1680                         goto out_err;
1681                 }
1682
1683                 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1684                         rc = -EINVAL;
1685                         goto out_err;
1686                 }
1687
1688                 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1689                             SMB2_CLIENT_GUID_SIZE)) {
1690                         rc = -ENOENT;
1691                         goto out_err;
1692                 }
1693
1694                 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1695                         rc = -EACCES;
1696                         goto out_err;
1697                 }
1698
1699                 if (sess->state == SMB2_SESSION_EXPIRED) {
1700                         rc = -EFAULT;
1701                         goto out_err;
1702                 }
1703
1704                 if (ksmbd_session_lookup(conn, sess_id)) {
1705                         rc = -EACCES;
1706                         goto out_err;
1707                 }
1708
1709                 conn->binding = true;
1710         } else if ((conn->dialect < SMB30_PROT_ID ||
1711                     server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1712                    (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1713                 sess = NULL;
1714                 rc = -EACCES;
1715                 goto out_err;
1716         } else {
1717                 sess = ksmbd_session_lookup(conn,
1718                                             le64_to_cpu(req->hdr.SessionId));
1719                 if (!sess) {
1720                         rc = -ENOENT;
1721                         goto out_err;
1722                 }
1723         }
1724         work->sess = sess;
1725
1726         if (sess->state == SMB2_SESSION_EXPIRED)
1727                 sess->state = SMB2_SESSION_IN_PROGRESS;
1728
1729         negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1730         negblob_len = le16_to_cpu(req->SecurityBufferLength);
1731         if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1732             negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1733                 rc = -EINVAL;
1734                 goto out_err;
1735         }
1736
1737         negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1738                         negblob_off);
1739
1740         if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1741                 if (conn->mechToken)
1742                         negblob = (struct negotiate_message *)conn->mechToken;
1743         }
1744
1745         if (server_conf.auth_mechs & conn->auth_mechs) {
1746                 rc = generate_preauth_hash(work);
1747                 if (rc)
1748                         goto out_err;
1749
1750                 if (conn->preferred_auth_mech &
1751                                 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1752                         rc = krb5_authenticate(work);
1753                         if (rc) {
1754                                 rc = -EINVAL;
1755                                 goto out_err;
1756                         }
1757
1758                         ksmbd_conn_set_good(work);
1759                         sess->state = SMB2_SESSION_VALID;
1760                         kfree(sess->Preauth_HashValue);
1761                         sess->Preauth_HashValue = NULL;
1762                 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1763                         if (negblob->MessageType == NtLmNegotiate) {
1764                                 rc = ntlm_negotiate(work, negblob, negblob_len);
1765                                 if (rc)
1766                                         goto out_err;
1767                                 rsp->hdr.Status =
1768                                         STATUS_MORE_PROCESSING_REQUIRED;
1769                                 /*
1770                                  * Note: here total size -1 is done as an
1771                                  * adjustment for 0 size blob
1772                                  */
1773                                 inc_rfc1001_len(work->response_buf,
1774                                                 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1775
1776                         } else if (negblob->MessageType == NtLmAuthenticate) {
1777                                 rc = ntlm_authenticate(work);
1778                                 if (rc)
1779                                         goto out_err;
1780
1781                                 ksmbd_conn_set_good(work);
1782                                 sess->state = SMB2_SESSION_VALID;
1783                                 if (conn->binding) {
1784                                         struct preauth_session *preauth_sess;
1785
1786                                         preauth_sess =
1787                                                 ksmbd_preauth_session_lookup(conn, sess->id);
1788                                         if (preauth_sess) {
1789                                                 list_del(&preauth_sess->preauth_entry);
1790                                                 kfree(preauth_sess);
1791                                         }
1792                                 }
1793                                 kfree(sess->Preauth_HashValue);
1794                                 sess->Preauth_HashValue = NULL;
1795                         }
1796                 } else {
1797                         /* TODO: need one more negotiation */
1798                         pr_err("Not support the preferred authentication\n");
1799                         rc = -EINVAL;
1800                 }
1801         } else {
1802                 pr_err("Not support authentication\n");
1803                 rc = -EINVAL;
1804         }
1805
1806 out_err:
1807         if (rc == -EINVAL)
1808                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1809         else if (rc == -ENOENT)
1810                 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1811         else if (rc == -EACCES)
1812                 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1813         else if (rc == -EFAULT)
1814                 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1815         else if (rc == -ENOMEM)
1816                 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1817         else if (rc)
1818                 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1819
1820         if (conn->use_spnego && conn->mechToken) {
1821                 kfree(conn->mechToken);
1822                 conn->mechToken = NULL;
1823         }
1824
1825         if (rc < 0) {
1826                 /*
1827                  * SecurityBufferOffset should be set to zero
1828                  * in session setup error response.
1829                  */
1830                 rsp->SecurityBufferOffset = 0;
1831
1832                 if (sess) {
1833                         bool try_delay = false;
1834
1835                         /*
1836                          * To avoid dictionary attacks (repeated session setups rapidly sent) to
1837                          * connect to server, ksmbd make a delay of a 5 seconds on session setup
1838                          * failure to make it harder to send enough random connection requests
1839                          * to break into a server.
1840                          */
1841                         if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1842                                 try_delay = true;
1843
1844                         xa_erase(&conn->sessions, sess->id);
1845                         ksmbd_session_destroy(sess);
1846                         work->sess = NULL;
1847                         if (try_delay)
1848                                 ssleep(5);
1849                 }
1850         }
1851
1852         return rc;
1853 }
1854
1855 /**
1856  * smb2_tree_connect() - handler for smb2 tree connect command
1857  * @work:       smb work containing smb request buffer
1858  *
1859  * Return:      0 on success, otherwise error
1860  */
1861 int smb2_tree_connect(struct ksmbd_work *work)
1862 {
1863         struct ksmbd_conn *conn = work->conn;
1864         struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1865         struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1866         struct ksmbd_session *sess = work->sess;
1867         char *treename = NULL, *name = NULL;
1868         struct ksmbd_tree_conn_status status;
1869         struct ksmbd_share_config *share;
1870         int rc = -EINVAL;
1871
1872         treename = smb_strndup_from_utf16(req->Buffer,
1873                                           le16_to_cpu(req->PathLength), true,
1874                                           conn->local_nls);
1875         if (IS_ERR(treename)) {
1876                 pr_err("treename is NULL\n");
1877                 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1878                 goto out_err1;
1879         }
1880
1881         name = ksmbd_extract_sharename(treename);
1882         if (IS_ERR(name)) {
1883                 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1884                 goto out_err1;
1885         }
1886
1887         ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1888                     name, treename);
1889
1890         status = ksmbd_tree_conn_connect(conn, sess, name);
1891         if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1892                 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1893         else
1894                 goto out_err1;
1895
1896         share = status.tree_conn->share_conf;
1897         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1898                 ksmbd_debug(SMB, "IPC share path request\n");
1899                 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1900                 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1901                         FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1902                         FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1903                         FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1904                         FILE_SYNCHRONIZE_LE;
1905         } else {
1906                 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1907                 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1908                         FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1909                 if (test_tree_conn_flag(status.tree_conn,
1910                                         KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1911                         rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1912                                 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1913                                 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1914                                 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1915                                 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1916                                 FILE_SYNCHRONIZE_LE;
1917                 }
1918         }
1919
1920         status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1921         if (conn->posix_ext_supported)
1922                 status.tree_conn->posix_extensions = true;
1923
1924 out_err1:
1925         rsp->StructureSize = cpu_to_le16(16);
1926         rsp->Capabilities = 0;
1927         rsp->Reserved = 0;
1928         /* default manual caching */
1929         rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1930         inc_rfc1001_len(work->response_buf, 16);
1931
1932         if (!IS_ERR(treename))
1933                 kfree(treename);
1934         if (!IS_ERR(name))
1935                 kfree(name);
1936
1937         switch (status.ret) {
1938         case KSMBD_TREE_CONN_STATUS_OK:
1939                 rsp->hdr.Status = STATUS_SUCCESS;
1940                 rc = 0;
1941                 break;
1942         case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1943                 rsp->hdr.Status = STATUS_BAD_NETWORK_PATH;
1944                 break;
1945         case -ENOMEM:
1946         case KSMBD_TREE_CONN_STATUS_NOMEM:
1947                 rsp->hdr.Status = STATUS_NO_MEMORY;
1948                 break;
1949         case KSMBD_TREE_CONN_STATUS_ERROR:
1950         case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1951         case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1952                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1953                 break;
1954         case -EINVAL:
1955                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1956                 break;
1957         default:
1958                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1959         }
1960
1961         return rc;
1962 }
1963
1964 /**
1965  * smb2_create_open_flags() - convert smb open flags to unix open flags
1966  * @file_present:       is file already present
1967  * @access:             file access flags
1968  * @disposition:        file disposition flags
1969  * @may_flags:          set with MAY_ flags
1970  *
1971  * Return:      file open flags
1972  */
1973 static int smb2_create_open_flags(bool file_present, __le32 access,
1974                                   __le32 disposition,
1975                                   int *may_flags)
1976 {
1977         int oflags = O_NONBLOCK | O_LARGEFILE;
1978
1979         if (access & FILE_READ_DESIRED_ACCESS_LE &&
1980             access & FILE_WRITE_DESIRE_ACCESS_LE) {
1981                 oflags |= O_RDWR;
1982                 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1983         } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1984                 oflags |= O_WRONLY;
1985                 *may_flags = MAY_OPEN | MAY_WRITE;
1986         } else {
1987                 oflags |= O_RDONLY;
1988                 *may_flags = MAY_OPEN | MAY_READ;
1989         }
1990
1991         if (access == FILE_READ_ATTRIBUTES_LE)
1992                 oflags |= O_PATH;
1993
1994         if (file_present) {
1995                 switch (disposition & FILE_CREATE_MASK_LE) {
1996                 case FILE_OPEN_LE:
1997                 case FILE_CREATE_LE:
1998                         break;
1999                 case FILE_SUPERSEDE_LE:
2000                 case FILE_OVERWRITE_LE:
2001                 case FILE_OVERWRITE_IF_LE:
2002                         oflags |= O_TRUNC;
2003                         break;
2004                 default:
2005                         break;
2006                 }
2007         } else {
2008                 switch (disposition & FILE_CREATE_MASK_LE) {
2009                 case FILE_SUPERSEDE_LE:
2010                 case FILE_CREATE_LE:
2011                 case FILE_OPEN_IF_LE:
2012                 case FILE_OVERWRITE_IF_LE:
2013                         oflags |= O_CREAT;
2014                         break;
2015                 case FILE_OPEN_LE:
2016                 case FILE_OVERWRITE_LE:
2017                         oflags &= ~O_CREAT;
2018                         break;
2019                 default:
2020                         break;
2021                 }
2022         }
2023
2024         return oflags;
2025 }
2026
2027 /**
2028  * smb2_tree_disconnect() - handler for smb tree connect request
2029  * @work:       smb work containing request buffer
2030  *
2031  * Return:      0
2032  */
2033 int smb2_tree_disconnect(struct ksmbd_work *work)
2034 {
2035         struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2036         struct ksmbd_session *sess = work->sess;
2037         struct ksmbd_tree_connect *tcon = work->tcon;
2038
2039         rsp->StructureSize = cpu_to_le16(4);
2040         inc_rfc1001_len(work->response_buf, 4);
2041
2042         ksmbd_debug(SMB, "request\n");
2043
2044         if (!tcon) {
2045                 struct smb2_tree_disconnect_req *req =
2046                         smb2_get_msg(work->request_buf);
2047
2048                 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2049                 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2050                 smb2_set_err_rsp(work);
2051                 return 0;
2052         }
2053
2054         ksmbd_close_tree_conn_fds(work);
2055         ksmbd_tree_conn_disconnect(sess, tcon);
2056         return 0;
2057 }
2058
2059 /**
2060  * smb2_session_logoff() - handler for session log off request
2061  * @work:       smb work containing request buffer
2062  *
2063  * Return:      0
2064  */
2065 int smb2_session_logoff(struct ksmbd_work *work)
2066 {
2067         struct ksmbd_conn *conn = work->conn;
2068         struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2069         struct ksmbd_session *sess = work->sess;
2070
2071         rsp->StructureSize = cpu_to_le16(4);
2072         inc_rfc1001_len(work->response_buf, 4);
2073
2074         ksmbd_debug(SMB, "request\n");
2075
2076         /* setting CifsExiting here may race with start_tcp_sess */
2077         ksmbd_conn_set_need_reconnect(work);
2078         ksmbd_close_session_fds(work);
2079         ksmbd_conn_wait_idle(conn);
2080
2081         if (ksmbd_tree_conn_session_logoff(sess)) {
2082                 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2083
2084                 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2085                 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2086                 smb2_set_err_rsp(work);
2087                 return 0;
2088         }
2089
2090         ksmbd_destroy_file_table(&sess->file_table);
2091         sess->state = SMB2_SESSION_EXPIRED;
2092
2093         ksmbd_free_user(sess->user);
2094         sess->user = NULL;
2095
2096         /* let start_tcp_sess free connection info now */
2097         ksmbd_conn_set_need_negotiate(work);
2098         return 0;
2099 }
2100
2101 /**
2102  * create_smb2_pipe() - create IPC pipe
2103  * @work:       smb work containing request buffer
2104  *
2105  * Return:      0 on success, otherwise error
2106  */
2107 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2108 {
2109         struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2110         struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2111         int id;
2112         int err;
2113         char *name;
2114
2115         name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2116                                       1, work->conn->local_nls);
2117         if (IS_ERR(name)) {
2118                 rsp->hdr.Status = STATUS_NO_MEMORY;
2119                 err = PTR_ERR(name);
2120                 goto out;
2121         }
2122
2123         id = ksmbd_session_rpc_open(work->sess, name);
2124         if (id < 0) {
2125                 pr_err("Unable to open RPC pipe: %d\n", id);
2126                 err = id;
2127                 goto out;
2128         }
2129
2130         rsp->hdr.Status = STATUS_SUCCESS;
2131         rsp->StructureSize = cpu_to_le16(89);
2132         rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2133         rsp->Flags = 0;
2134         rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2135
2136         rsp->CreationTime = cpu_to_le64(0);
2137         rsp->LastAccessTime = cpu_to_le64(0);
2138         rsp->ChangeTime = cpu_to_le64(0);
2139         rsp->AllocationSize = cpu_to_le64(0);
2140         rsp->EndofFile = cpu_to_le64(0);
2141         rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2142         rsp->Reserved2 = 0;
2143         rsp->VolatileFileId = id;
2144         rsp->PersistentFileId = 0;
2145         rsp->CreateContextsOffset = 0;
2146         rsp->CreateContextsLength = 0;
2147
2148         inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2149         kfree(name);
2150         return 0;
2151
2152 out:
2153         switch (err) {
2154         case -EINVAL:
2155                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2156                 break;
2157         case -ENOSPC:
2158         case -ENOMEM:
2159                 rsp->hdr.Status = STATUS_NO_MEMORY;
2160                 break;
2161         }
2162
2163         if (!IS_ERR(name))
2164                 kfree(name);
2165
2166         smb2_set_err_rsp(work);
2167         return err;
2168 }
2169
2170 /**
2171  * smb2_set_ea() - handler for setting extended attributes using set
2172  *              info command
2173  * @eabuf:      set info command buffer
2174  * @buf_len:    set info command buffer length
2175  * @path:       dentry path for get ea
2176  *
2177  * Return:      0 on success, otherwise error
2178  */
2179 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2180                        struct path *path)
2181 {
2182         struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2183         char *attr_name = NULL, *value;
2184         int rc = 0;
2185         unsigned int next = 0;
2186
2187         if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2188                         le16_to_cpu(eabuf->EaValueLength))
2189                 return -EINVAL;
2190
2191         attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2192         if (!attr_name)
2193                 return -ENOMEM;
2194
2195         do {
2196                 if (!eabuf->EaNameLength)
2197                         goto next;
2198
2199                 ksmbd_debug(SMB,
2200                             "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2201                             eabuf->name, eabuf->EaNameLength,
2202                             le16_to_cpu(eabuf->EaValueLength),
2203                             le32_to_cpu(eabuf->NextEntryOffset));
2204
2205                 if (eabuf->EaNameLength >
2206                     (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2207                         rc = -EINVAL;
2208                         break;
2209                 }
2210
2211                 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2212                 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2213                        eabuf->EaNameLength);
2214                 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2215                 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2216
2217                 if (!eabuf->EaValueLength) {
2218                         rc = ksmbd_vfs_casexattr_len(user_ns,
2219                                                      path->dentry,
2220                                                      attr_name,
2221                                                      XATTR_USER_PREFIX_LEN +
2222                                                      eabuf->EaNameLength);
2223
2224                         /* delete the EA only when it exits */
2225                         if (rc > 0) {
2226                                 rc = ksmbd_vfs_remove_xattr(user_ns,
2227                                                             path->dentry,
2228                                                             attr_name);
2229
2230                                 if (rc < 0) {
2231                                         ksmbd_debug(SMB,
2232                                                     "remove xattr failed(%d)\n",
2233                                                     rc);
2234                                         break;
2235                                 }
2236                         }
2237
2238                         /* if the EA doesn't exist, just do nothing. */
2239                         rc = 0;
2240                 } else {
2241                         rc = ksmbd_vfs_setxattr(user_ns,
2242                                                 path->dentry, attr_name, value,
2243                                                 le16_to_cpu(eabuf->EaValueLength), 0);
2244                         if (rc < 0) {
2245                                 ksmbd_debug(SMB,
2246                                             "ksmbd_vfs_setxattr is failed(%d)\n",
2247                                             rc);
2248                                 break;
2249                         }
2250                 }
2251
2252 next:
2253                 next = le32_to_cpu(eabuf->NextEntryOffset);
2254                 if (next == 0 || buf_len < next)
2255                         break;
2256                 buf_len -= next;
2257                 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2258                 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2259                         break;
2260
2261         } while (next != 0);
2262
2263         kfree(attr_name);
2264         return rc;
2265 }
2266
2267 static noinline int smb2_set_stream_name_xattr(struct path *path,
2268                                                struct ksmbd_file *fp,
2269                                                char *stream_name, int s_type)
2270 {
2271         struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2272         size_t xattr_stream_size;
2273         char *xattr_stream_name;
2274         int rc;
2275
2276         rc = ksmbd_vfs_xattr_stream_name(stream_name,
2277                                          &xattr_stream_name,
2278                                          &xattr_stream_size,
2279                                          s_type);
2280         if (rc)
2281                 return rc;
2282
2283         fp->stream.name = xattr_stream_name;
2284         fp->stream.size = xattr_stream_size;
2285
2286         /* Check if there is stream prefix in xattr space */
2287         rc = ksmbd_vfs_casexattr_len(user_ns,
2288                                      path->dentry,
2289                                      xattr_stream_name,
2290                                      xattr_stream_size);
2291         if (rc >= 0)
2292                 return 0;
2293
2294         if (fp->cdoption == FILE_OPEN_LE) {
2295                 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2296                 return -EBADF;
2297         }
2298
2299         rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2300                                 xattr_stream_name, NULL, 0, 0);
2301         if (rc < 0)
2302                 pr_err("Failed to store XATTR stream name :%d\n", rc);
2303         return 0;
2304 }
2305
2306 static int smb2_remove_smb_xattrs(struct path *path)
2307 {
2308         struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2309         char *name, *xattr_list = NULL;
2310         ssize_t xattr_list_len;
2311         int err = 0;
2312
2313         xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2314         if (xattr_list_len < 0) {
2315                 goto out;
2316         } else if (!xattr_list_len) {
2317                 ksmbd_debug(SMB, "empty xattr in the file\n");
2318                 goto out;
2319         }
2320
2321         for (name = xattr_list; name - xattr_list < xattr_list_len;
2322                         name += strlen(name) + 1) {
2323                 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2324
2325                 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2326                     strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2327                             DOS_ATTRIBUTE_PREFIX_LEN) &&
2328                     strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2329                         continue;
2330
2331                 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2332                 if (err)
2333                         ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2334         }
2335 out:
2336         kvfree(xattr_list);
2337         return err;
2338 }
2339
2340 static int smb2_create_truncate(struct path *path)
2341 {
2342         int rc = vfs_truncate(path, 0);
2343
2344         if (rc) {
2345                 pr_err("vfs_truncate failed, rc %d\n", rc);
2346                 return rc;
2347         }
2348
2349         rc = smb2_remove_smb_xattrs(path);
2350         if (rc == -EOPNOTSUPP)
2351                 rc = 0;
2352         if (rc)
2353                 ksmbd_debug(SMB,
2354                             "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2355                             rc);
2356         return rc;
2357 }
2358
2359 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2360                             struct ksmbd_file *fp)
2361 {
2362         struct xattr_dos_attrib da = {0};
2363         int rc;
2364
2365         if (!test_share_config_flag(tcon->share_conf,
2366                                     KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2367                 return;
2368
2369         da.version = 4;
2370         da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2371         da.itime = da.create_time = fp->create_time;
2372         da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2373                 XATTR_DOSINFO_ITIME;
2374
2375         rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2376                                             path->dentry, &da);
2377         if (rc)
2378                 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2379 }
2380
2381 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2382                                struct path *path, struct ksmbd_file *fp)
2383 {
2384         struct xattr_dos_attrib da;
2385         int rc;
2386
2387         fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2388
2389         /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2390         if (!test_share_config_flag(tcon->share_conf,
2391                                     KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2392                 return;
2393
2394         rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2395                                             path->dentry, &da);
2396         if (rc > 0) {
2397                 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2398                 fp->create_time = da.create_time;
2399                 fp->itime = da.itime;
2400         }
2401 }
2402
2403 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2404                       int open_flags, umode_t posix_mode, bool is_dir)
2405 {
2406         struct ksmbd_tree_connect *tcon = work->tcon;
2407         struct ksmbd_share_config *share = tcon->share_conf;
2408         umode_t mode;
2409         int rc;
2410
2411         if (!(open_flags & O_CREAT))
2412                 return -EBADF;
2413
2414         ksmbd_debug(SMB, "file does not exist, so creating\n");
2415         if (is_dir == true) {
2416                 ksmbd_debug(SMB, "creating directory\n");
2417
2418                 mode = share_config_directory_mode(share, posix_mode);
2419                 rc = ksmbd_vfs_mkdir(work, name, mode);
2420                 if (rc)
2421                         return rc;
2422         } else {
2423                 ksmbd_debug(SMB, "creating regular file\n");
2424
2425                 mode = share_config_create_mode(share, posix_mode);
2426                 rc = ksmbd_vfs_create(work, name, mode);
2427                 if (rc)
2428                         return rc;
2429         }
2430
2431         rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2432         if (rc) {
2433                 pr_err("cannot get linux path (%s), err = %d\n",
2434                        name, rc);
2435                 return rc;
2436         }
2437         return 0;
2438 }
2439
2440 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2441                                  struct smb2_create_req *req,
2442                                  struct path *path)
2443 {
2444         struct create_context *context;
2445         struct create_sd_buf_req *sd_buf;
2446
2447         if (!req->CreateContextsOffset)
2448                 return -ENOENT;
2449
2450         /* Parse SD BUFFER create contexts */
2451         context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2452         if (!context)
2453                 return -ENOENT;
2454         else if (IS_ERR(context))
2455                 return PTR_ERR(context);
2456
2457         ksmbd_debug(SMB,
2458                     "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2459         sd_buf = (struct create_sd_buf_req *)context;
2460         if (le16_to_cpu(context->DataOffset) +
2461             le32_to_cpu(context->DataLength) <
2462             sizeof(struct create_sd_buf_req))
2463                 return -EINVAL;
2464         return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2465                             le32_to_cpu(sd_buf->ccontext.DataLength), true);
2466 }
2467
2468 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2469                              struct user_namespace *mnt_userns,
2470                              struct inode *inode)
2471 {
2472         fattr->cf_uid = i_uid_into_mnt(mnt_userns, inode);
2473         fattr->cf_gid = i_gid_into_mnt(mnt_userns, inode);
2474         fattr->cf_mode = inode->i_mode;
2475         fattr->cf_acls = NULL;
2476         fattr->cf_dacls = NULL;
2477
2478         if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2479                 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2480                 if (S_ISDIR(inode->i_mode))
2481                         fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2482         }
2483 }
2484
2485 /**
2486  * smb2_open() - handler for smb file open request
2487  * @work:       smb work containing request buffer
2488  *
2489  * Return:      0 on success, otherwise error
2490  */
2491 int smb2_open(struct ksmbd_work *work)
2492 {
2493         struct ksmbd_conn *conn = work->conn;
2494         struct ksmbd_session *sess = work->sess;
2495         struct ksmbd_tree_connect *tcon = work->tcon;
2496         struct smb2_create_req *req;
2497         struct smb2_create_rsp *rsp;
2498         struct path path;
2499         struct ksmbd_share_config *share = tcon->share_conf;
2500         struct ksmbd_file *fp = NULL;
2501         struct file *filp = NULL;
2502         struct user_namespace *user_ns = NULL;
2503         struct kstat stat;
2504         struct create_context *context;
2505         struct lease_ctx_info *lc = NULL;
2506         struct create_ea_buf_req *ea_buf = NULL;
2507         struct oplock_info *opinfo;
2508         __le32 *next_ptr = NULL;
2509         int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2510         int rc = 0;
2511         int contxt_cnt = 0, query_disk_id = 0;
2512         int maximal_access_ctxt = 0, posix_ctxt = 0;
2513         int s_type = 0;
2514         int next_off = 0;
2515         char *name = NULL;
2516         char *stream_name = NULL;
2517         bool file_present = false, created = false, already_permitted = false;
2518         int share_ret, need_truncate = 0;
2519         u64 time;
2520         umode_t posix_mode = 0;
2521         __le32 daccess, maximal_access = 0;
2522
2523         WORK_BUFFERS(work, req, rsp);
2524
2525         if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2526             (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2527                 ksmbd_debug(SMB, "invalid flag in chained command\n");
2528                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2529                 smb2_set_err_rsp(work);
2530                 return -EINVAL;
2531         }
2532
2533         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2534                 ksmbd_debug(SMB, "IPC pipe create request\n");
2535                 return create_smb2_pipe(work);
2536         }
2537
2538         if (req->NameLength) {
2539                 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2540                     *(char *)req->Buffer == '\\') {
2541                         pr_err("not allow directory name included leading slash\n");
2542                         rc = -EINVAL;
2543                         goto err_out1;
2544                 }
2545
2546                 name = smb2_get_name(req->Buffer,
2547                                      le16_to_cpu(req->NameLength),
2548                                      work->conn->local_nls);
2549                 if (IS_ERR(name)) {
2550                         rc = PTR_ERR(name);
2551                         if (rc != -ENOMEM)
2552                                 rc = -ENOENT;
2553                         name = NULL;
2554                         goto err_out1;
2555                 }
2556
2557                 ksmbd_debug(SMB, "converted name = %s\n", name);
2558                 if (strchr(name, ':')) {
2559                         if (!test_share_config_flag(work->tcon->share_conf,
2560                                                     KSMBD_SHARE_FLAG_STREAMS)) {
2561                                 rc = -EBADF;
2562                                 goto err_out1;
2563                         }
2564                         rc = parse_stream_name(name, &stream_name, &s_type);
2565                         if (rc < 0)
2566                                 goto err_out1;
2567                 }
2568
2569                 rc = ksmbd_validate_filename(name);
2570                 if (rc < 0)
2571                         goto err_out1;
2572
2573                 if (ksmbd_share_veto_filename(share, name)) {
2574                         rc = -ENOENT;
2575                         ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2576                                     name);
2577                         goto err_out1;
2578                 }
2579         } else {
2580                 name = kstrdup("", GFP_KERNEL);
2581                 if (!name) {
2582                         rc = -ENOMEM;
2583                         goto err_out1;
2584                 }
2585         }
2586
2587         req_op_level = req->RequestedOplockLevel;
2588         if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2589                 lc = parse_lease_state(req);
2590
2591         if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2592                 pr_err("Invalid impersonationlevel : 0x%x\n",
2593                        le32_to_cpu(req->ImpersonationLevel));
2594                 rc = -EIO;
2595                 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2596                 goto err_out1;
2597         }
2598
2599         if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2600                 pr_err("Invalid create options : 0x%x\n",
2601                        le32_to_cpu(req->CreateOptions));
2602                 rc = -EINVAL;
2603                 goto err_out1;
2604         } else {
2605                 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2606                     req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2607                         req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2608
2609                 if (req->CreateOptions &
2610                     (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2611                      FILE_RESERVE_OPFILTER_LE)) {
2612                         rc = -EOPNOTSUPP;
2613                         goto err_out1;
2614                 }
2615
2616                 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2617                         if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2618                                 rc = -EINVAL;
2619                                 goto err_out1;
2620                         } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2621                                 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2622                         }
2623                 }
2624         }
2625
2626         if (le32_to_cpu(req->CreateDisposition) >
2627             le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2628                 pr_err("Invalid create disposition : 0x%x\n",
2629                        le32_to_cpu(req->CreateDisposition));
2630                 rc = -EINVAL;
2631                 goto err_out1;
2632         }
2633
2634         if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2635                 pr_err("Invalid desired access : 0x%x\n",
2636                        le32_to_cpu(req->DesiredAccess));
2637                 rc = -EACCES;
2638                 goto err_out1;
2639         }
2640
2641         if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2642                 pr_err("Invalid file attribute : 0x%x\n",
2643                        le32_to_cpu(req->FileAttributes));
2644                 rc = -EINVAL;
2645                 goto err_out1;
2646         }
2647
2648         if (req->CreateContextsOffset) {
2649                 /* Parse non-durable handle create contexts */
2650                 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2651                 if (IS_ERR(context)) {
2652                         rc = PTR_ERR(context);
2653                         goto err_out1;
2654                 } else if (context) {
2655                         ea_buf = (struct create_ea_buf_req *)context;
2656                         if (le16_to_cpu(context->DataOffset) +
2657                             le32_to_cpu(context->DataLength) <
2658                             sizeof(struct create_ea_buf_req)) {
2659                                 rc = -EINVAL;
2660                                 goto err_out1;
2661                         }
2662                         if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2663                                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2664                                 rc = -EACCES;
2665                                 goto err_out1;
2666                         }
2667                 }
2668
2669                 context = smb2_find_context_vals(req,
2670                                                  SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2671                 if (IS_ERR(context)) {
2672                         rc = PTR_ERR(context);
2673                         goto err_out1;
2674                 } else if (context) {
2675                         ksmbd_debug(SMB,
2676                                     "get query maximal access context\n");
2677                         maximal_access_ctxt = 1;
2678                 }
2679
2680                 context = smb2_find_context_vals(req,
2681                                                  SMB2_CREATE_TIMEWARP_REQUEST);
2682                 if (IS_ERR(context)) {
2683                         rc = PTR_ERR(context);
2684                         goto err_out1;
2685                 } else if (context) {
2686                         ksmbd_debug(SMB, "get timewarp context\n");
2687                         rc = -EBADF;
2688                         goto err_out1;
2689                 }
2690
2691                 if (tcon->posix_extensions) {
2692                         context = smb2_find_context_vals(req,
2693                                                          SMB2_CREATE_TAG_POSIX);
2694                         if (IS_ERR(context)) {
2695                                 rc = PTR_ERR(context);
2696                                 goto err_out1;
2697                         } else if (context) {
2698                                 struct create_posix *posix =
2699                                         (struct create_posix *)context;
2700                                 if (le16_to_cpu(context->DataOffset) +
2701                                     le32_to_cpu(context->DataLength) <
2702                                     sizeof(struct create_posix) - 4) {
2703                                         rc = -EINVAL;
2704                                         goto err_out1;
2705                                 }
2706                                 ksmbd_debug(SMB, "get posix context\n");
2707
2708                                 posix_mode = le32_to_cpu(posix->Mode);
2709                                 posix_ctxt = 1;
2710                         }
2711                 }
2712         }
2713
2714         if (ksmbd_override_fsids(work)) {
2715                 rc = -ENOMEM;
2716                 goto err_out1;
2717         }
2718
2719         rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2720         if (!rc) {
2721                 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2722                         /*
2723                          * If file exists with under flags, return access
2724                          * denied error.
2725                          */
2726                         if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2727                             req->CreateDisposition == FILE_OPEN_IF_LE) {
2728                                 rc = -EACCES;
2729                                 path_put(&path);
2730                                 goto err_out;
2731                         }
2732
2733                         if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2734                                 ksmbd_debug(SMB,
2735                                             "User does not have write permission\n");
2736                                 rc = -EACCES;
2737                                 path_put(&path);
2738                                 goto err_out;
2739                         }
2740                 } else if (d_is_symlink(path.dentry)) {
2741                         rc = -EACCES;
2742                         path_put(&path);
2743                         goto err_out;
2744                 }
2745         }
2746
2747         if (rc) {
2748                 if (rc != -ENOENT)
2749                         goto err_out;
2750                 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2751                             name, rc);
2752                 rc = 0;
2753         } else {
2754                 file_present = true;
2755                 user_ns = mnt_user_ns(path.mnt);
2756                 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2757         }
2758         if (stream_name) {
2759                 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2760                         if (s_type == DATA_STREAM) {
2761                                 rc = -EIO;
2762                                 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2763                         }
2764                 } else {
2765                         if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2766                                 rc = -EIO;
2767                                 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2768                         }
2769                 }
2770
2771                 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2772                     req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2773                         rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2774                         rc = -EIO;
2775                 }
2776
2777                 if (rc < 0)
2778                         goto err_out;
2779         }
2780
2781         if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2782             S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2783                 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2784                             name, req->CreateOptions);
2785                 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2786                 rc = -EIO;
2787                 goto err_out;
2788         }
2789
2790         if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2791             !(req->CreateDisposition == FILE_CREATE_LE) &&
2792             !S_ISDIR(stat.mode)) {
2793                 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2794                 rc = -EIO;
2795                 goto err_out;
2796         }
2797
2798         if (!stream_name && file_present &&
2799             req->CreateDisposition == FILE_CREATE_LE) {
2800                 rc = -EEXIST;
2801                 goto err_out;
2802         }
2803
2804         daccess = smb_map_generic_desired_access(req->DesiredAccess);
2805
2806         if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2807                 rc = smb_check_perm_dacl(conn, &path, &daccess,
2808                                          sess->user->uid);
2809                 if (rc)
2810                         goto err_out;
2811         }
2812
2813         if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2814                 if (!file_present) {
2815                         daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2816                 } else {
2817                         rc = ksmbd_vfs_query_maximal_access(user_ns,
2818                                                             path.dentry,
2819                                                             &daccess);
2820                         if (rc)
2821                                 goto err_out;
2822                         already_permitted = true;
2823                 }
2824                 maximal_access = daccess;
2825         }
2826
2827         open_flags = smb2_create_open_flags(file_present, daccess,
2828                                             req->CreateDisposition,
2829                                             &may_flags);
2830
2831         if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2832                 if (open_flags & O_CREAT) {
2833                         ksmbd_debug(SMB,
2834                                     "User does not have write permission\n");
2835                         rc = -EACCES;
2836                         goto err_out;
2837                 }
2838         }
2839
2840         /*create file if not present */
2841         if (!file_present) {
2842                 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2843                                 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2844                 if (rc) {
2845                         if (rc == -ENOENT) {
2846                                 rc = -EIO;
2847                                 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2848                         }
2849                         goto err_out;
2850                 }
2851
2852                 created = true;
2853                 user_ns = mnt_user_ns(path.mnt);
2854                 if (ea_buf) {
2855                         if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2856                             sizeof(struct smb2_ea_info)) {
2857                                 rc = -EINVAL;
2858                                 goto err_out;
2859                         }
2860
2861                         rc = smb2_set_ea(&ea_buf->ea,
2862                                          le32_to_cpu(ea_buf->ccontext.DataLength),
2863                                          &path);
2864                         if (rc == -EOPNOTSUPP)
2865                                 rc = 0;
2866                         else if (rc)
2867                                 goto err_out;
2868                 }
2869         } else if (!already_permitted) {
2870                 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2871                  * because execute(search) permission on a parent directory,
2872                  * is already granted.
2873                  */
2874                 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2875                         rc = inode_permission(user_ns,
2876                                               d_inode(path.dentry),
2877                                               may_flags);
2878                         if (rc)
2879                                 goto err_out;
2880
2881                         if ((daccess & FILE_DELETE_LE) ||
2882                             (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2883                                 rc = ksmbd_vfs_may_delete(user_ns,
2884                                                           path.dentry);
2885                                 if (rc)
2886                                         goto err_out;
2887                         }
2888                 }
2889         }
2890
2891         rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2892         if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2893                 rc = -EBUSY;
2894                 goto err_out;
2895         }
2896
2897         rc = 0;
2898         filp = dentry_open(&path, open_flags, current_cred());
2899         if (IS_ERR(filp)) {
2900                 rc = PTR_ERR(filp);
2901                 pr_err("dentry open for dir failed, rc %d\n", rc);
2902                 goto err_out;
2903         }
2904
2905         if (file_present) {
2906                 if (!(open_flags & O_TRUNC))
2907                         file_info = FILE_OPENED;
2908                 else
2909                         file_info = FILE_OVERWRITTEN;
2910
2911                 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2912                     FILE_SUPERSEDE_LE)
2913                         file_info = FILE_SUPERSEDED;
2914         } else if (open_flags & O_CREAT) {
2915                 file_info = FILE_CREATED;
2916         }
2917
2918         ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2919
2920         /* Obtain Volatile-ID */
2921         fp = ksmbd_open_fd(work, filp);
2922         if (IS_ERR(fp)) {
2923                 fput(filp);
2924                 rc = PTR_ERR(fp);
2925                 fp = NULL;
2926                 goto err_out;
2927         }
2928
2929         /* Get Persistent-ID */
2930         ksmbd_open_durable_fd(fp);
2931         if (!has_file_id(fp->persistent_id)) {
2932                 rc = -ENOMEM;
2933                 goto err_out;
2934         }
2935
2936         fp->cdoption = req->CreateDisposition;
2937         fp->daccess = daccess;
2938         fp->saccess = req->ShareAccess;
2939         fp->coption = req->CreateOptions;
2940
2941         /* Set default windows and posix acls if creating new file */
2942         if (created) {
2943                 int posix_acl_rc;
2944                 struct inode *inode = d_inode(path.dentry);
2945
2946                 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2947                                                            inode,
2948                                                            d_inode(path.dentry->d_parent));
2949                 if (posix_acl_rc)
2950                         ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2951
2952                 if (test_share_config_flag(work->tcon->share_conf,
2953                                            KSMBD_SHARE_FLAG_ACL_XATTR)) {
2954                         rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2955                                               sess->user->gid);
2956                 }
2957
2958                 if (rc) {
2959                         rc = smb2_create_sd_buffer(work, req, &path);
2960                         if (rc) {
2961                                 if (posix_acl_rc)
2962                                         ksmbd_vfs_set_init_posix_acl(user_ns,
2963                                                                      inode);
2964
2965                                 if (test_share_config_flag(work->tcon->share_conf,
2966                                                            KSMBD_SHARE_FLAG_ACL_XATTR)) {
2967                                         struct smb_fattr fattr;
2968                                         struct smb_ntsd *pntsd;
2969                                         int pntsd_size, ace_num = 0;
2970
2971                                         ksmbd_acls_fattr(&fattr, user_ns, inode);
2972                                         if (fattr.cf_acls)
2973                                                 ace_num = fattr.cf_acls->a_count;
2974                                         if (fattr.cf_dacls)
2975                                                 ace_num += fattr.cf_dacls->a_count;
2976
2977                                         pntsd = kmalloc(sizeof(struct smb_ntsd) +
2978                                                         sizeof(struct smb_sid) * 3 +
2979                                                         sizeof(struct smb_acl) +
2980                                                         sizeof(struct smb_ace) * ace_num * 2,
2981                                                         GFP_KERNEL);
2982                                         if (!pntsd)
2983                                                 goto err_out;
2984
2985                                         rc = build_sec_desc(user_ns,
2986                                                             pntsd, NULL,
2987                                                             OWNER_SECINFO |
2988                                                             GROUP_SECINFO |
2989                                                             DACL_SECINFO,
2990                                                             &pntsd_size, &fattr);
2991                                         posix_acl_release(fattr.cf_acls);
2992                                         posix_acl_release(fattr.cf_dacls);
2993                                         if (rc) {
2994                                                 kfree(pntsd);
2995                                                 goto err_out;
2996                                         }
2997
2998                                         rc = ksmbd_vfs_set_sd_xattr(conn,
2999                                                                     user_ns,
3000                                                                     path.dentry,
3001                                                                     pntsd,
3002                                                                     pntsd_size);
3003                                         kfree(pntsd);
3004                                         if (rc)
3005                                                 pr_err("failed to store ntacl in xattr : %d\n",
3006                                                        rc);
3007                                 }
3008                         }
3009                 }
3010                 rc = 0;
3011         }
3012
3013         if (stream_name) {
3014                 rc = smb2_set_stream_name_xattr(&path,
3015                                                 fp,
3016                                                 stream_name,
3017                                                 s_type);
3018                 if (rc)
3019                         goto err_out;
3020                 file_info = FILE_CREATED;
3021         }
3022
3023         fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3024                         FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3025         if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3026             !fp->attrib_only && !stream_name) {
3027                 smb_break_all_oplock(work, fp);
3028                 need_truncate = 1;
3029         }
3030
3031         /* fp should be searchable through ksmbd_inode.m_fp_list
3032          * after daccess, saccess, attrib_only, and stream are
3033          * initialized.
3034          */
3035         write_lock(&fp->f_ci->m_lock);
3036         list_add(&fp->node, &fp->f_ci->m_fp_list);
3037         write_unlock(&fp->f_ci->m_lock);
3038
3039         rc = ksmbd_vfs_getattr(&path, &stat);
3040         if (rc) {
3041                 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
3042                 rc = 0;
3043         }
3044
3045         /* Check delete pending among previous fp before oplock break */
3046         if (ksmbd_inode_pending_delete(fp)) {
3047                 rc = -EBUSY;
3048                 goto err_out;
3049         }
3050
3051         share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3052         if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3053             (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3054              !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3055                 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3056                         rc = share_ret;
3057                         goto err_out;
3058                 }
3059         } else {
3060                 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3061                         req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3062                         ksmbd_debug(SMB,
3063                                     "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3064                                     name, req_op_level, lc->req_state);
3065                         rc = find_same_lease_key(sess, fp->f_ci, lc);
3066                         if (rc)
3067                                 goto err_out;
3068                 } else if (open_flags == O_RDONLY &&
3069                            (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3070                             req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3071                         req_op_level = SMB2_OPLOCK_LEVEL_II;
3072
3073                 rc = smb_grant_oplock(work, req_op_level,
3074                                       fp->persistent_id, fp,
3075                                       le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3076                                       lc, share_ret);
3077                 if (rc < 0)
3078                         goto err_out;
3079         }
3080
3081         if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3082                 ksmbd_fd_set_delete_on_close(fp, file_info);
3083
3084         if (need_truncate) {
3085                 rc = smb2_create_truncate(&path);
3086                 if (rc)
3087                         goto err_out;
3088         }
3089
3090         if (req->CreateContextsOffset) {
3091                 struct create_alloc_size_req *az_req;
3092
3093                 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3094                                         SMB2_CREATE_ALLOCATION_SIZE);
3095                 if (IS_ERR(az_req)) {
3096                         rc = PTR_ERR(az_req);
3097                         goto err_out;
3098                 } else if (az_req) {
3099                         loff_t alloc_size;
3100                         int err;
3101
3102                         if (le16_to_cpu(az_req->ccontext.DataOffset) +
3103                             le32_to_cpu(az_req->ccontext.DataLength) <
3104                             sizeof(struct create_alloc_size_req)) {
3105                                 rc = -EINVAL;
3106                                 goto err_out;
3107                         }
3108                         alloc_size = le64_to_cpu(az_req->AllocationSize);
3109                         ksmbd_debug(SMB,
3110                                     "request smb2 create allocate size : %llu\n",
3111                                     alloc_size);
3112                         smb_break_all_levII_oplock(work, fp, 1);
3113                         err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3114                                             alloc_size);
3115                         if (err < 0)
3116                                 ksmbd_debug(SMB,
3117                                             "vfs_fallocate is failed : %d\n",
3118                                             err);
3119                 }
3120
3121                 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3122                 if (IS_ERR(context)) {
3123                         rc = PTR_ERR(context);
3124                         goto err_out;
3125                 } else if (context) {
3126                         ksmbd_debug(SMB, "get query on disk id context\n");
3127                         query_disk_id = 1;
3128                 }
3129         }
3130
3131         if (stat.result_mask & STATX_BTIME)
3132                 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3133         else
3134                 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3135         if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3136                 fp->f_ci->m_fattr =
3137                         cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3138
3139         if (!created)
3140                 smb2_update_xattrs(tcon, &path, fp);
3141         else
3142                 smb2_new_xattrs(tcon, &path, fp);
3143
3144         memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3145
3146         generic_fillattr(user_ns, file_inode(fp->filp),
3147                          &stat);
3148
3149         rsp->StructureSize = cpu_to_le16(89);
3150         rcu_read_lock();
3151         opinfo = rcu_dereference(fp->f_opinfo);
3152         rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3153         rcu_read_unlock();
3154         rsp->Flags = 0;
3155         rsp->CreateAction = cpu_to_le32(file_info);
3156         rsp->CreationTime = cpu_to_le64(fp->create_time);
3157         time = ksmbd_UnixTimeToNT(stat.atime);
3158         rsp->LastAccessTime = cpu_to_le64(time);
3159         time = ksmbd_UnixTimeToNT(stat.mtime);
3160         rsp->LastWriteTime = cpu_to_le64(time);
3161         time = ksmbd_UnixTimeToNT(stat.ctime);
3162         rsp->ChangeTime = cpu_to_le64(time);
3163         rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3164                 cpu_to_le64(stat.blocks << 9);
3165         rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3166         rsp->FileAttributes = fp->f_ci->m_fattr;
3167
3168         rsp->Reserved2 = 0;
3169
3170         rsp->PersistentFileId = fp->persistent_id;
3171         rsp->VolatileFileId = fp->volatile_id;
3172
3173         rsp->CreateContextsOffset = 0;
3174         rsp->CreateContextsLength = 0;
3175         inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3176
3177         /* If lease is request send lease context response */
3178         if (opinfo && opinfo->is_lease) {
3179                 struct create_context *lease_ccontext;
3180
3181                 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3182                             name, opinfo->o_lease->state);
3183                 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3184
3185                 lease_ccontext = (struct create_context *)rsp->Buffer;
3186                 contxt_cnt++;
3187                 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3188                 le32_add_cpu(&rsp->CreateContextsLength,
3189                              conn->vals->create_lease_size);
3190                 inc_rfc1001_len(work->response_buf,
3191                                 conn->vals->create_lease_size);
3192                 next_ptr = &lease_ccontext->Next;
3193                 next_off = conn->vals->create_lease_size;
3194         }
3195
3196         if (maximal_access_ctxt) {
3197                 struct create_context *mxac_ccontext;
3198
3199                 if (maximal_access == 0)
3200                         ksmbd_vfs_query_maximal_access(user_ns,
3201                                                        path.dentry,
3202                                                        &maximal_access);
3203                 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3204                                 le32_to_cpu(rsp->CreateContextsLength));
3205                 contxt_cnt++;
3206                 create_mxac_rsp_buf(rsp->Buffer +
3207                                 le32_to_cpu(rsp->CreateContextsLength),
3208                                 le32_to_cpu(maximal_access));
3209                 le32_add_cpu(&rsp->CreateContextsLength,
3210                              conn->vals->create_mxac_size);
3211                 inc_rfc1001_len(work->response_buf,
3212                                 conn->vals->create_mxac_size);
3213                 if (next_ptr)
3214                         *next_ptr = cpu_to_le32(next_off);
3215                 next_ptr = &mxac_ccontext->Next;
3216                 next_off = conn->vals->create_mxac_size;
3217         }
3218
3219         if (query_disk_id) {
3220                 struct create_context *disk_id_ccontext;
3221
3222                 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3223                                 le32_to_cpu(rsp->CreateContextsLength));
3224                 contxt_cnt++;
3225                 create_disk_id_rsp_buf(rsp->Buffer +
3226                                 le32_to_cpu(rsp->CreateContextsLength),
3227                                 stat.ino, tcon->id);
3228                 le32_add_cpu(&rsp->CreateContextsLength,
3229                              conn->vals->create_disk_id_size);
3230                 inc_rfc1001_len(work->response_buf,
3231                                 conn->vals->create_disk_id_size);
3232                 if (next_ptr)
3233                         *next_ptr = cpu_to_le32(next_off);
3234                 next_ptr = &disk_id_ccontext->Next;
3235                 next_off = conn->vals->create_disk_id_size;
3236         }
3237
3238         if (posix_ctxt) {
3239                 contxt_cnt++;
3240                 create_posix_rsp_buf(rsp->Buffer +
3241                                 le32_to_cpu(rsp->CreateContextsLength),
3242                                 fp);
3243                 le32_add_cpu(&rsp->CreateContextsLength,
3244                              conn->vals->create_posix_size);
3245                 inc_rfc1001_len(work->response_buf,
3246                                 conn->vals->create_posix_size);
3247                 if (next_ptr)
3248                         *next_ptr = cpu_to_le32(next_off);
3249         }
3250
3251         if (contxt_cnt > 0) {
3252                 rsp->CreateContextsOffset =
3253                         cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3254         }
3255
3256 err_out:
3257         if (file_present || created)
3258                 path_put(&path);
3259         ksmbd_revert_fsids(work);
3260 err_out1:
3261         if (rc) {
3262                 if (rc == -EINVAL)
3263                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3264                 else if (rc == -EOPNOTSUPP)
3265                         rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3266                 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3267                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
3268                 else if (rc == -ENOENT)
3269                         rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3270                 else if (rc == -EPERM)
3271                         rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3272                 else if (rc == -EBUSY)
3273                         rsp->hdr.Status = STATUS_DELETE_PENDING;
3274                 else if (rc == -EBADF)
3275                         rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3276                 else if (rc == -ENOEXEC)
3277                         rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3278                 else if (rc == -ENXIO)
3279                         rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3280                 else if (rc == -EEXIST)
3281                         rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3282                 else if (rc == -EMFILE)
3283                         rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3284                 if (!rsp->hdr.Status)
3285                         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3286
3287                 if (fp)
3288                         ksmbd_fd_put(work, fp);
3289                 smb2_set_err_rsp(work);
3290                 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3291         }
3292
3293         kfree(name);
3294         kfree(lc);
3295
3296         return 0;
3297 }
3298
3299 static int readdir_info_level_struct_sz(int info_level)
3300 {
3301         switch (info_level) {
3302         case FILE_FULL_DIRECTORY_INFORMATION:
3303                 return sizeof(struct file_full_directory_info);
3304         case FILE_BOTH_DIRECTORY_INFORMATION:
3305                 return sizeof(struct file_both_directory_info);
3306         case FILE_DIRECTORY_INFORMATION:
3307                 return sizeof(struct file_directory_info);
3308         case FILE_NAMES_INFORMATION:
3309                 return sizeof(struct file_names_info);
3310         case FILEID_FULL_DIRECTORY_INFORMATION:
3311                 return sizeof(struct file_id_full_dir_info);
3312         case FILEID_BOTH_DIRECTORY_INFORMATION:
3313                 return sizeof(struct file_id_both_directory_info);
3314         case SMB_FIND_FILE_POSIX_INFO:
3315                 return sizeof(struct smb2_posix_info);
3316         default:
3317                 return -EOPNOTSUPP;
3318         }
3319 }
3320
3321 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3322 {
3323         switch (info_level) {
3324         case FILE_FULL_DIRECTORY_INFORMATION:
3325         {
3326                 struct file_full_directory_info *ffdinfo;
3327
3328                 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3329                 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3330                 d_info->name = ffdinfo->FileName;
3331                 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3332                 return 0;
3333         }
3334         case FILE_BOTH_DIRECTORY_INFORMATION:
3335         {
3336                 struct file_both_directory_info *fbdinfo;
3337
3338                 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3339                 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3340                 d_info->name = fbdinfo->FileName;
3341                 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3342                 return 0;
3343         }
3344         case FILE_DIRECTORY_INFORMATION:
3345         {
3346                 struct file_directory_info *fdinfo;
3347
3348                 fdinfo = (struct file_directory_info *)d_info->rptr;
3349                 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3350                 d_info->name = fdinfo->FileName;
3351                 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3352                 return 0;
3353         }
3354         case FILE_NAMES_INFORMATION:
3355         {
3356                 struct file_names_info *fninfo;
3357
3358                 fninfo = (struct file_names_info *)d_info->rptr;
3359                 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3360                 d_info->name = fninfo->FileName;
3361                 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3362                 return 0;
3363         }
3364         case FILEID_FULL_DIRECTORY_INFORMATION:
3365         {
3366                 struct file_id_full_dir_info *dinfo;
3367
3368                 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3369                 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3370                 d_info->name = dinfo->FileName;
3371                 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3372                 return 0;
3373         }
3374         case FILEID_BOTH_DIRECTORY_INFORMATION:
3375         {
3376                 struct file_id_both_directory_info *fibdinfo;
3377
3378                 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3379                 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3380                 d_info->name = fibdinfo->FileName;
3381                 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3382                 return 0;
3383         }
3384         case SMB_FIND_FILE_POSIX_INFO:
3385         {
3386                 struct smb2_posix_info *posix_info;
3387
3388                 posix_info = (struct smb2_posix_info *)d_info->rptr;
3389                 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3390                 d_info->name = posix_info->name;
3391                 d_info->name_len = le32_to_cpu(posix_info->name_len);
3392                 return 0;
3393         }
3394         default:
3395                 return -EINVAL;
3396         }
3397 }
3398
3399 /**
3400  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3401  * buffer
3402  * @conn:       connection instance
3403  * @info_level: smb information level
3404  * @d_info:     structure included variables for query dir
3405  * @ksmbd_kstat:        ksmbd wrapper of dirent stat information
3406  *
3407  * if directory has many entries, find first can't read it fully.
3408  * find next might be called multiple times to read remaining dir entries
3409  *
3410  * Return:      0 on success, otherwise error
3411  */
3412 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3413                                        struct ksmbd_dir_info *d_info,
3414                                        struct ksmbd_kstat *ksmbd_kstat)
3415 {
3416         int next_entry_offset = 0;
3417         char *conv_name;
3418         int conv_len;
3419         void *kstat;
3420         int struct_sz, rc = 0;
3421
3422         conv_name = ksmbd_convert_dir_info_name(d_info,
3423                                                 conn->local_nls,
3424                                                 &conv_len);
3425         if (!conv_name)
3426                 return -ENOMEM;
3427
3428         /* Somehow the name has only terminating NULL bytes */
3429         if (conv_len < 0) {
3430                 rc = -EINVAL;
3431                 goto free_conv_name;
3432         }
3433
3434         struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3435         next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3436         d_info->last_entry_off_align = next_entry_offset - struct_sz;
3437
3438         if (next_entry_offset > d_info->out_buf_len) {
3439                 d_info->out_buf_len = 0;
3440                 rc = -ENOSPC;
3441                 goto free_conv_name;
3442         }
3443
3444         kstat = d_info->wptr;
3445         if (info_level != FILE_NAMES_INFORMATION)
3446                 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3447
3448         switch (info_level) {
3449         case FILE_FULL_DIRECTORY_INFORMATION:
3450         {
3451                 struct file_full_directory_info *ffdinfo;
3452
3453                 ffdinfo = (struct file_full_directory_info *)kstat;
3454                 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3455                 ffdinfo->EaSize =
3456                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3457                 if (ffdinfo->EaSize)
3458                         ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3459                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3460                         ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3461                 memcpy(ffdinfo->FileName, conv_name, conv_len);
3462                 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3463                 break;
3464         }
3465         case FILE_BOTH_DIRECTORY_INFORMATION:
3466         {
3467                 struct file_both_directory_info *fbdinfo;
3468
3469                 fbdinfo = (struct file_both_directory_info *)kstat;
3470                 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3471                 fbdinfo->EaSize =
3472                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3473                 if (fbdinfo->EaSize)
3474                         fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3475                 fbdinfo->ShortNameLength = 0;
3476                 fbdinfo->Reserved = 0;
3477                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3478                         fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3479                 memcpy(fbdinfo->FileName, conv_name, conv_len);
3480                 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3481                 break;
3482         }
3483         case FILE_DIRECTORY_INFORMATION:
3484         {
3485                 struct file_directory_info *fdinfo;
3486
3487                 fdinfo = (struct file_directory_info *)kstat;
3488                 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3489                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3490                         fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3491                 memcpy(fdinfo->FileName, conv_name, conv_len);
3492                 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3493                 break;
3494         }
3495         case FILE_NAMES_INFORMATION:
3496         {
3497                 struct file_names_info *fninfo;
3498
3499                 fninfo = (struct file_names_info *)kstat;
3500                 fninfo->FileNameLength = cpu_to_le32(conv_len);
3501                 memcpy(fninfo->FileName, conv_name, conv_len);
3502                 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3503                 break;
3504         }
3505         case FILEID_FULL_DIRECTORY_INFORMATION:
3506         {
3507                 struct file_id_full_dir_info *dinfo;
3508
3509                 dinfo = (struct file_id_full_dir_info *)kstat;
3510                 dinfo->FileNameLength = cpu_to_le32(conv_len);
3511                 dinfo->EaSize =
3512                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3513                 if (dinfo->EaSize)
3514                         dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3515                 dinfo->Reserved = 0;
3516                 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3517                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3518                         dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3519                 memcpy(dinfo->FileName, conv_name, conv_len);
3520                 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3521                 break;
3522         }
3523         case FILEID_BOTH_DIRECTORY_INFORMATION:
3524         {
3525                 struct file_id_both_directory_info *fibdinfo;
3526
3527                 fibdinfo = (struct file_id_both_directory_info *)kstat;
3528                 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3529                 fibdinfo->EaSize =
3530                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3531                 if (fibdinfo->EaSize)
3532                         fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3533                 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3534                 fibdinfo->ShortNameLength = 0;
3535                 fibdinfo->Reserved = 0;
3536                 fibdinfo->Reserved2 = cpu_to_le16(0);
3537                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3538                         fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3539                 memcpy(fibdinfo->FileName, conv_name, conv_len);
3540                 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3541                 break;
3542         }
3543         case SMB_FIND_FILE_POSIX_INFO:
3544         {
3545                 struct smb2_posix_info *posix_info;
3546                 u64 time;
3547
3548                 posix_info = (struct smb2_posix_info *)kstat;
3549                 posix_info->Ignored = 0;
3550                 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3551                 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3552                 posix_info->ChangeTime = cpu_to_le64(time);
3553                 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3554                 posix_info->LastAccessTime = cpu_to_le64(time);
3555                 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3556                 posix_info->LastWriteTime = cpu_to_le64(time);
3557                 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3558                 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3559                 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3560                 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3561                 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3562                 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3563                 posix_info->DosAttributes =
3564                         S_ISDIR(ksmbd_kstat->kstat->mode) ?
3565                                 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3566                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3567                         posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3568                 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3569                           SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3570                 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3571                           SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3572                 memcpy(posix_info->name, conv_name, conv_len);
3573                 posix_info->name_len = cpu_to_le32(conv_len);
3574                 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3575                 break;
3576         }
3577
3578         } /* switch (info_level) */
3579
3580         d_info->last_entry_offset = d_info->data_count;
3581         d_info->data_count += next_entry_offset;
3582         d_info->out_buf_len -= next_entry_offset;
3583         d_info->wptr += next_entry_offset;
3584
3585         ksmbd_debug(SMB,
3586                     "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3587                     info_level, d_info->out_buf_len,
3588                     next_entry_offset, d_info->data_count);
3589
3590 free_conv_name:
3591         kfree(conv_name);
3592         return rc;
3593 }
3594
3595 struct smb2_query_dir_private {
3596         struct ksmbd_work       *work;
3597         char                    *search_pattern;
3598         struct ksmbd_file       *dir_fp;
3599
3600         struct ksmbd_dir_info   *d_info;
3601         int                     info_level;
3602 };
3603
3604 static void lock_dir(struct ksmbd_file *dir_fp)
3605 {
3606         struct dentry *dir = dir_fp->filp->f_path.dentry;
3607
3608         inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3609 }
3610
3611 static void unlock_dir(struct ksmbd_file *dir_fp)
3612 {
3613         struct dentry *dir = dir_fp->filp->f_path.dentry;
3614
3615         inode_unlock(d_inode(dir));
3616 }
3617
3618 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3619 {
3620         struct user_namespace   *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3621         struct kstat            kstat;
3622         struct ksmbd_kstat      ksmbd_kstat;
3623         int                     rc;
3624         int                     i;
3625
3626         for (i = 0; i < priv->d_info->num_entry; i++) {
3627                 struct dentry *dent;
3628
3629                 if (dentry_name(priv->d_info, priv->info_level))
3630                         return -EINVAL;
3631
3632                 lock_dir(priv->dir_fp);
3633                 dent = lookup_one(user_ns, priv->d_info->name,
3634                                   priv->dir_fp->filp->f_path.dentry,
3635                                   priv->d_info->name_len);
3636                 unlock_dir(priv->dir_fp);
3637
3638                 if (IS_ERR(dent)) {
3639                         ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3640                                     priv->d_info->name,
3641                                     PTR_ERR(dent));
3642                         continue;
3643                 }
3644                 if (unlikely(d_is_negative(dent))) {
3645                         dput(dent);
3646                         ksmbd_debug(SMB, "Negative dentry `%s'\n",
3647                                     priv->d_info->name);
3648                         continue;
3649                 }
3650
3651                 ksmbd_kstat.kstat = &kstat;
3652                 if (priv->info_level != FILE_NAMES_INFORMATION)
3653                         ksmbd_vfs_fill_dentry_attrs(priv->work,
3654                                                     user_ns,
3655                                                     dent,
3656                                                     &ksmbd_kstat);
3657
3658                 rc = smb2_populate_readdir_entry(priv->work->conn,
3659                                                  priv->info_level,
3660                                                  priv->d_info,
3661                                                  &ksmbd_kstat);
3662                 dput(dent);
3663                 if (rc)
3664                         return rc;
3665         }
3666         return 0;
3667 }
3668
3669 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3670                                    int info_level)
3671 {
3672         int struct_sz;
3673         int conv_len;
3674         int next_entry_offset;
3675
3676         struct_sz = readdir_info_level_struct_sz(info_level);
3677         if (struct_sz == -EOPNOTSUPP)
3678                 return -EOPNOTSUPP;
3679
3680         conv_len = (d_info->name_len + 1) * 2;
3681         next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3682                                   KSMBD_DIR_INFO_ALIGNMENT);
3683
3684         if (next_entry_offset > d_info->out_buf_len) {
3685                 d_info->out_buf_len = 0;
3686                 return -ENOSPC;
3687         }
3688
3689         switch (info_level) {
3690         case FILE_FULL_DIRECTORY_INFORMATION:
3691         {
3692                 struct file_full_directory_info *ffdinfo;
3693
3694                 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3695                 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3696                 ffdinfo->FileName[d_info->name_len] = 0x00;
3697                 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3698                 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3699                 break;
3700         }
3701         case FILE_BOTH_DIRECTORY_INFORMATION:
3702         {
3703                 struct file_both_directory_info *fbdinfo;
3704
3705                 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3706                 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3707                 fbdinfo->FileName[d_info->name_len] = 0x00;
3708                 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3709                 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3710                 break;
3711         }
3712         case FILE_DIRECTORY_INFORMATION:
3713         {
3714                 struct file_directory_info *fdinfo;
3715
3716                 fdinfo = (struct file_directory_info *)d_info->wptr;
3717                 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3718                 fdinfo->FileName[d_info->name_len] = 0x00;
3719                 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3720                 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3721                 break;
3722         }
3723         case FILE_NAMES_INFORMATION:
3724         {
3725                 struct file_names_info *fninfo;
3726
3727                 fninfo = (struct file_names_info *)d_info->wptr;
3728                 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3729                 fninfo->FileName[d_info->name_len] = 0x00;
3730                 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3731                 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3732                 break;
3733         }
3734         case FILEID_FULL_DIRECTORY_INFORMATION:
3735         {
3736                 struct file_id_full_dir_info *dinfo;
3737
3738                 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3739                 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3740                 dinfo->FileName[d_info->name_len] = 0x00;
3741                 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3742                 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3743                 break;
3744         }
3745         case FILEID_BOTH_DIRECTORY_INFORMATION:
3746         {
3747                 struct file_id_both_directory_info *fibdinfo;
3748
3749                 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3750                 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3751                 fibdinfo->FileName[d_info->name_len] = 0x00;
3752                 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3753                 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3754                 break;
3755         }
3756         case SMB_FIND_FILE_POSIX_INFO:
3757         {
3758                 struct smb2_posix_info *posix_info;
3759
3760                 posix_info = (struct smb2_posix_info *)d_info->wptr;
3761                 memcpy(posix_info->name, d_info->name, d_info->name_len);
3762                 posix_info->name[d_info->name_len] = 0x00;
3763                 posix_info->name_len = cpu_to_le32(d_info->name_len);
3764                 posix_info->NextEntryOffset =
3765                         cpu_to_le32(next_entry_offset);
3766                 break;
3767         }
3768         } /* switch (info_level) */
3769
3770         d_info->num_entry++;
3771         d_info->out_buf_len -= next_entry_offset;
3772         d_info->wptr += next_entry_offset;
3773         return 0;
3774 }
3775
3776 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3777                        loff_t offset, u64 ino, unsigned int d_type)
3778 {
3779         struct ksmbd_readdir_data       *buf;
3780         struct smb2_query_dir_private   *priv;
3781         struct ksmbd_dir_info           *d_info;
3782         int                             rc;
3783
3784         buf     = container_of(ctx, struct ksmbd_readdir_data, ctx);
3785         priv    = buf->private;
3786         d_info  = priv->d_info;
3787
3788         /* dot and dotdot entries are already reserved */
3789         if (!strcmp(".", name) || !strcmp("..", name))
3790                 return 0;
3791         if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3792                 return 0;
3793         if (!match_pattern(name, namlen, priv->search_pattern))
3794                 return 0;
3795
3796         d_info->name            = name;
3797         d_info->name_len        = namlen;
3798         rc = reserve_populate_dentry(d_info, priv->info_level);
3799         if (rc)
3800                 return rc;
3801         if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3802                 d_info->out_buf_len = 0;
3803                 return 0;
3804         }
3805         return 0;
3806 }
3807
3808 static void restart_ctx(struct dir_context *ctx)
3809 {
3810         ctx->pos = 0;
3811 }
3812
3813 static int verify_info_level(int info_level)
3814 {
3815         switch (info_level) {
3816         case FILE_FULL_DIRECTORY_INFORMATION:
3817         case FILE_BOTH_DIRECTORY_INFORMATION:
3818         case FILE_DIRECTORY_INFORMATION:
3819         case FILE_NAMES_INFORMATION:
3820         case FILEID_FULL_DIRECTORY_INFORMATION:
3821         case FILEID_BOTH_DIRECTORY_INFORMATION:
3822         case SMB_FIND_FILE_POSIX_INFO:
3823                 break;
3824         default:
3825                 return -EOPNOTSUPP;
3826         }
3827
3828         return 0;
3829 }
3830
3831 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3832                                      unsigned short hdr2_len,
3833                                      unsigned int out_buf_len)
3834 {
3835         int free_len;
3836
3837         if (out_buf_len > work->conn->vals->max_trans_size)
3838                 return -EINVAL;
3839
3840         free_len = (int)(work->response_sz -
3841                          (get_rfc1002_len(work->response_buf) + 4)) -
3842                 hdr2_len;
3843         if (free_len < 0)
3844                 return -EINVAL;
3845
3846         return min_t(int, out_buf_len, free_len);
3847 }
3848
3849 int smb2_query_dir(struct ksmbd_work *work)
3850 {
3851         struct ksmbd_conn *conn = work->conn;
3852         struct smb2_query_directory_req *req;
3853         struct smb2_query_directory_rsp *rsp;
3854         struct ksmbd_share_config *share = work->tcon->share_conf;
3855         struct ksmbd_file *dir_fp = NULL;
3856         struct ksmbd_dir_info d_info;
3857         int rc = 0;
3858         char *srch_ptr = NULL;
3859         unsigned char srch_flag;
3860         int buffer_sz;
3861         struct smb2_query_dir_private query_dir_private = {NULL, };
3862
3863         WORK_BUFFERS(work, req, rsp);
3864
3865         if (ksmbd_override_fsids(work)) {
3866                 rsp->hdr.Status = STATUS_NO_MEMORY;
3867                 smb2_set_err_rsp(work);
3868                 return -ENOMEM;
3869         }
3870
3871         rc = verify_info_level(req->FileInformationClass);
3872         if (rc) {
3873                 rc = -EFAULT;
3874                 goto err_out2;
3875         }
3876
3877         dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3878         if (!dir_fp) {
3879                 rc = -EBADF;
3880                 goto err_out2;
3881         }
3882
3883         if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3884             inode_permission(file_mnt_user_ns(dir_fp->filp),
3885                              file_inode(dir_fp->filp),
3886                              MAY_READ | MAY_EXEC)) {
3887                 pr_err("no right to enumerate directory (%pd)\n",
3888                        dir_fp->filp->f_path.dentry);
3889                 rc = -EACCES;
3890                 goto err_out2;
3891         }
3892
3893         if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3894                 pr_err("can't do query dir for a file\n");
3895                 rc = -EINVAL;
3896                 goto err_out2;
3897         }
3898
3899         srch_flag = req->Flags;
3900         srch_ptr = smb_strndup_from_utf16(req->Buffer,
3901                                           le16_to_cpu(req->FileNameLength), 1,
3902                                           conn->local_nls);
3903         if (IS_ERR(srch_ptr)) {
3904                 ksmbd_debug(SMB, "Search Pattern not found\n");
3905                 rc = -EINVAL;
3906                 goto err_out2;
3907         } else {
3908                 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3909         }
3910
3911         if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3912                 ksmbd_debug(SMB, "Restart directory scan\n");
3913                 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3914                 restart_ctx(&dir_fp->readdir_data.ctx);
3915         }
3916
3917         memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3918         d_info.wptr = (char *)rsp->Buffer;
3919         d_info.rptr = (char *)rsp->Buffer;
3920         d_info.out_buf_len =
3921                 smb2_calc_max_out_buf_len(work, 8,
3922                                           le32_to_cpu(req->OutputBufferLength));
3923         if (d_info.out_buf_len < 0) {
3924                 rc = -EINVAL;
3925                 goto err_out;
3926         }
3927         d_info.flags = srch_flag;
3928
3929         /*
3930          * reserve dot and dotdot entries in head of buffer
3931          * in first response
3932          */
3933         rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3934                                                dir_fp, &d_info, srch_ptr,
3935                                                smb2_populate_readdir_entry);
3936         if (rc == -ENOSPC)
3937                 rc = 0;
3938         else if (rc)
3939                 goto err_out;
3940
3941         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3942                 d_info.hide_dot_file = true;
3943
3944         buffer_sz                               = d_info.out_buf_len;
3945         d_info.rptr                             = d_info.wptr;
3946         query_dir_private.work                  = work;
3947         query_dir_private.search_pattern        = srch_ptr;
3948         query_dir_private.dir_fp                = dir_fp;
3949         query_dir_private.d_info                = &d_info;
3950         query_dir_private.info_level            = req->FileInformationClass;
3951         dir_fp->readdir_data.private            = &query_dir_private;
3952         set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3953
3954         rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3955         /*
3956          * req->OutputBufferLength is too small to contain even one entry.
3957          * In this case, it immediately returns OutputBufferLength 0 to client.
3958          */
3959         if (!d_info.out_buf_len && !d_info.num_entry)
3960                 goto no_buf_len;
3961         if (rc == 0)
3962                 restart_ctx(&dir_fp->readdir_data.ctx);
3963         if (rc == -ENOSPC)
3964                 rc = 0;
3965         if (rc)
3966                 goto err_out;
3967
3968         d_info.wptr = d_info.rptr;
3969         d_info.out_buf_len = buffer_sz;
3970         rc = process_query_dir_entries(&query_dir_private);
3971         if (rc)
3972                 goto err_out;
3973
3974         if (!d_info.data_count && d_info.out_buf_len >= 0) {
3975                 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3976                         rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3977                 } else {
3978                         dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3979                         rsp->hdr.Status = STATUS_NO_MORE_FILES;
3980                 }
3981                 rsp->StructureSize = cpu_to_le16(9);
3982                 rsp->OutputBufferOffset = cpu_to_le16(0);
3983                 rsp->OutputBufferLength = cpu_to_le32(0);
3984                 rsp->Buffer[0] = 0;
3985                 inc_rfc1001_len(work->response_buf, 9);
3986         } else {
3987 no_buf_len:
3988                 ((struct file_directory_info *)
3989                 ((char *)rsp->Buffer + d_info.last_entry_offset))
3990                 ->NextEntryOffset = 0;
3991                 if (d_info.data_count >= d_info.last_entry_off_align)
3992                         d_info.data_count -= d_info.last_entry_off_align;
3993
3994                 rsp->StructureSize = cpu_to_le16(9);
3995                 rsp->OutputBufferOffset = cpu_to_le16(72);
3996                 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3997                 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
3998         }
3999
4000         kfree(srch_ptr);
4001         ksmbd_fd_put(work, dir_fp);
4002         ksmbd_revert_fsids(work);
4003         return 0;
4004
4005 err_out:
4006         pr_err("error while processing smb2 query dir rc = %d\n", rc);
4007         kfree(srch_ptr);
4008
4009 err_out2:
4010         if (rc == -EINVAL)
4011                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4012         else if (rc == -EACCES)
4013                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4014         else if (rc == -ENOENT)
4015                 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4016         else if (rc == -EBADF)
4017                 rsp->hdr.Status = STATUS_FILE_CLOSED;
4018         else if (rc == -ENOMEM)
4019                 rsp->hdr.Status = STATUS_NO_MEMORY;
4020         else if (rc == -EFAULT)
4021                 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4022         if (!rsp->hdr.Status)
4023                 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4024
4025         smb2_set_err_rsp(work);
4026         ksmbd_fd_put(work, dir_fp);
4027         ksmbd_revert_fsids(work);
4028         return 0;
4029 }
4030
4031 /**
4032  * buffer_check_err() - helper function to check buffer errors
4033  * @reqOutputBufferLength:      max buffer length expected in command response
4034  * @rsp:                query info response buffer contains output buffer length
4035  * @rsp_org:            base response buffer pointer in case of chained response
4036  * @infoclass_size:     query info class response buffer size
4037  *
4038  * Return:      0 on success, otherwise error
4039  */
4040 static int buffer_check_err(int reqOutputBufferLength,
4041                             struct smb2_query_info_rsp *rsp,
4042                             void *rsp_org, int infoclass_size)
4043 {
4044         if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4045                 if (reqOutputBufferLength < infoclass_size) {
4046                         pr_err("Invalid Buffer Size Requested\n");
4047                         rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4048                         *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4049                         return -EINVAL;
4050                 }
4051
4052                 ksmbd_debug(SMB, "Buffer Overflow\n");
4053                 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4054                 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4055                                 reqOutputBufferLength);
4056                 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4057         }
4058         return 0;
4059 }
4060
4061 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4062                                    void *rsp_org)
4063 {
4064         struct smb2_file_standard_info *sinfo;
4065
4066         sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4067
4068         sinfo->AllocationSize = cpu_to_le64(4096);
4069         sinfo->EndOfFile = cpu_to_le64(0);
4070         sinfo->NumberOfLinks = cpu_to_le32(1);
4071         sinfo->DeletePending = 1;
4072         sinfo->Directory = 0;
4073         rsp->OutputBufferLength =
4074                 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4075         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4076 }
4077
4078 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4079                                    void *rsp_org)
4080 {
4081         struct smb2_file_internal_info *file_info;
4082
4083         file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4084
4085         /* any unique number */
4086         file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4087         rsp->OutputBufferLength =
4088                 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4089         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4090 }
4091
4092 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4093                                    struct smb2_query_info_req *req,
4094                                    struct smb2_query_info_rsp *rsp,
4095                                    void *rsp_org)
4096 {
4097         u64 id;
4098         int rc;
4099
4100         /*
4101          * Windows can sometime send query file info request on
4102          * pipe without opening it, checking error condition here
4103          */
4104         id = req->VolatileFileId;
4105         if (!ksmbd_session_rpc_method(sess, id))
4106                 return -ENOENT;
4107
4108         ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4109                     req->FileInfoClass, req->VolatileFileId);
4110
4111         switch (req->FileInfoClass) {
4112         case FILE_STANDARD_INFORMATION:
4113                 get_standard_info_pipe(rsp, rsp_org);
4114                 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4115                                       rsp, rsp_org,
4116                                       FILE_STANDARD_INFORMATION_SIZE);
4117                 break;
4118         case FILE_INTERNAL_INFORMATION:
4119                 get_internal_info_pipe(rsp, id, rsp_org);
4120                 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4121                                       rsp, rsp_org,
4122                                       FILE_INTERNAL_INFORMATION_SIZE);
4123                 break;
4124         default:
4125                 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4126                             req->FileInfoClass);
4127                 rc = -EOPNOTSUPP;
4128         }
4129         return rc;
4130 }
4131
4132 /**
4133  * smb2_get_ea() - handler for smb2 get extended attribute command
4134  * @work:       smb work containing query info command buffer
4135  * @fp:         ksmbd_file pointer
4136  * @req:        get extended attribute request
4137  * @rsp:        response buffer pointer
4138  * @rsp_org:    base response buffer pointer in case of chained response
4139  *
4140  * Return:      0 on success, otherwise error
4141  */
4142 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4143                        struct smb2_query_info_req *req,
4144                        struct smb2_query_info_rsp *rsp, void *rsp_org)
4145 {
4146         struct smb2_ea_info *eainfo, *prev_eainfo;
4147         char *name, *ptr, *xattr_list = NULL, *buf;
4148         int rc, name_len, value_len, xattr_list_len, idx;
4149         ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4150         struct smb2_ea_info_req *ea_req = NULL;
4151         struct path *path;
4152         struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4153
4154         if (!(fp->daccess & FILE_READ_EA_LE)) {
4155                 pr_err("Not permitted to read ext attr : 0x%x\n",
4156                        fp->daccess);
4157                 return -EACCES;
4158         }
4159
4160         path = &fp->filp->f_path;
4161         /* single EA entry is requested with given user.* name */
4162         if (req->InputBufferLength) {
4163                 if (le32_to_cpu(req->InputBufferLength) <
4164                     sizeof(struct smb2_ea_info_req))
4165                         return -EINVAL;
4166
4167                 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4168         } else {
4169                 /* need to send all EAs, if no specific EA is requested*/
4170                 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4171                         ksmbd_debug(SMB,
4172                                     "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4173                                     le32_to_cpu(req->Flags));
4174         }
4175
4176         buf_free_len =
4177                 smb2_calc_max_out_buf_len(work, 8,
4178                                           le32_to_cpu(req->OutputBufferLength));
4179         if (buf_free_len < 0)
4180                 return -EINVAL;
4181
4182         rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4183         if (rc < 0) {
4184                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4185                 goto out;
4186         } else if (!rc) { /* there is no EA in the file */
4187                 ksmbd_debug(SMB, "no ea data in the file\n");
4188                 goto done;
4189         }
4190         xattr_list_len = rc;
4191
4192         ptr = (char *)rsp->Buffer;
4193         eainfo = (struct smb2_ea_info *)ptr;
4194         prev_eainfo = eainfo;
4195         idx = 0;
4196
4197         while (idx < xattr_list_len) {
4198                 name = xattr_list + idx;
4199                 name_len = strlen(name);
4200
4201                 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4202                 idx += name_len + 1;
4203
4204                 /*
4205                  * CIFS does not support EA other than user.* namespace,
4206                  * still keep the framework generic, to list other attrs
4207                  * in future.
4208                  */
4209                 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4210                         continue;
4211
4212                 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4213                              STREAM_PREFIX_LEN))
4214                         continue;
4215
4216                 if (req->InputBufferLength &&
4217                     strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4218                             ea_req->EaNameLength))
4219                         continue;
4220
4221                 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4222                              DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4223                         continue;
4224
4225                 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4226                         name_len -= XATTR_USER_PREFIX_LEN;
4227
4228                 ptr = (char *)(&eainfo->name + name_len + 1);
4229                 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4230                                 name_len + 1);
4231                 /* bailout if xattr can't fit in buf_free_len */
4232                 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4233                                                name, &buf);
4234                 if (value_len <= 0) {
4235                         rc = -ENOENT;
4236                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
4237                         goto out;
4238                 }
4239
4240                 buf_free_len -= value_len;
4241                 if (buf_free_len < 0) {
4242                         kfree(buf);
4243                         break;
4244                 }
4245
4246                 memcpy(ptr, buf, value_len);
4247                 kfree(buf);
4248
4249                 ptr += value_len;
4250                 eainfo->Flags = 0;
4251                 eainfo->EaNameLength = name_len;
4252
4253                 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4254                         memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4255                                name_len);
4256                 else
4257                         memcpy(eainfo->name, name, name_len);
4258
4259                 eainfo->name[name_len] = '\0';
4260                 eainfo->EaValueLength = cpu_to_le16(value_len);
4261                 next_offset = offsetof(struct smb2_ea_info, name) +
4262                         name_len + 1 + value_len;
4263
4264                 /* align next xattr entry at 4 byte bundary */
4265                 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4266                 if (alignment_bytes) {
4267                         memset(ptr, '\0', alignment_bytes);
4268                         ptr += alignment_bytes;
4269                         next_offset += alignment_bytes;
4270                         buf_free_len -= alignment_bytes;
4271                 }
4272                 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4273                 prev_eainfo = eainfo;
4274                 eainfo = (struct smb2_ea_info *)ptr;
4275                 rsp_data_cnt += next_offset;
4276
4277                 if (req->InputBufferLength) {
4278                         ksmbd_debug(SMB, "single entry requested\n");
4279                         break;
4280                 }
4281         }
4282
4283         /* no more ea entries */
4284         prev_eainfo->NextEntryOffset = 0;
4285 done:
4286         rc = 0;
4287         if (rsp_data_cnt == 0)
4288                 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4289         rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4290         inc_rfc1001_len(rsp_org, rsp_data_cnt);
4291 out:
4292         kvfree(xattr_list);
4293         return rc;
4294 }
4295
4296 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4297                                  struct ksmbd_file *fp, void *rsp_org)
4298 {
4299         struct smb2_file_access_info *file_info;
4300
4301         file_info = (struct smb2_file_access_info *)rsp->Buffer;
4302         file_info->AccessFlags = fp->daccess;
4303         rsp->OutputBufferLength =
4304                 cpu_to_le32(sizeof(struct smb2_file_access_info));
4305         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4306 }
4307
4308 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4309                                struct ksmbd_file *fp, void *rsp_org)
4310 {
4311         struct smb2_file_basic_info *basic_info;
4312         struct kstat stat;
4313         u64 time;
4314
4315         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4316                 pr_err("no right to read the attributes : 0x%x\n",
4317                        fp->daccess);
4318                 return -EACCES;
4319         }
4320
4321         basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4322         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4323                          &stat);
4324         basic_info->CreationTime = cpu_to_le64(fp->create_time);
4325         time = ksmbd_UnixTimeToNT(stat.atime);
4326         basic_info->LastAccessTime = cpu_to_le64(time);
4327         time = ksmbd_UnixTimeToNT(stat.mtime);
4328         basic_info->LastWriteTime = cpu_to_le64(time);
4329         time = ksmbd_UnixTimeToNT(stat.ctime);
4330         basic_info->ChangeTime = cpu_to_le64(time);
4331         basic_info->Attributes = fp->f_ci->m_fattr;
4332         basic_info->Pad1 = 0;
4333         rsp->OutputBufferLength =
4334                 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4335         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4336         return 0;
4337 }
4338
4339 static unsigned long long get_allocation_size(struct inode *inode,
4340                                               struct kstat *stat)
4341 {
4342         unsigned long long alloc_size = 0;
4343
4344         if (!S_ISDIR(stat->mode)) {
4345                 if ((inode->i_blocks << 9) <= stat->size)
4346                         alloc_size = stat->size;
4347                 else
4348                         alloc_size = inode->i_blocks << 9;
4349         }
4350
4351         return alloc_size;
4352 }
4353
4354 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4355                                    struct ksmbd_file *fp, void *rsp_org)
4356 {
4357         struct smb2_file_standard_info *sinfo;
4358         unsigned int delete_pending;
4359         struct inode *inode;
4360         struct kstat stat;
4361
4362         inode = file_inode(fp->filp);
4363         generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4364
4365         sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4366         delete_pending = ksmbd_inode_pending_delete(fp);
4367
4368         sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4369         sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4370         sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4371         sinfo->DeletePending = delete_pending;
4372         sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4373         rsp->OutputBufferLength =
4374                 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4375         inc_rfc1001_len(rsp_org,
4376                         sizeof(struct smb2_file_standard_info));
4377 }
4378
4379 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4380                                     void *rsp_org)
4381 {
4382         struct smb2_file_alignment_info *file_info;
4383
4384         file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4385         file_info->AlignmentRequirement = 0;
4386         rsp->OutputBufferLength =
4387                 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4388         inc_rfc1001_len(rsp_org,
4389                         sizeof(struct smb2_file_alignment_info));
4390 }
4391
4392 static int get_file_all_info(struct ksmbd_work *work,
4393                              struct smb2_query_info_rsp *rsp,
4394                              struct ksmbd_file *fp,
4395                              void *rsp_org)
4396 {
4397         struct ksmbd_conn *conn = work->conn;
4398         struct smb2_file_all_info *file_info;
4399         unsigned int delete_pending;
4400         struct inode *inode;
4401         struct kstat stat;
4402         int conv_len;
4403         char *filename;
4404         u64 time;
4405
4406         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4407                 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4408                             fp->daccess);
4409                 return -EACCES;
4410         }
4411
4412         filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4413         if (IS_ERR(filename))
4414                 return PTR_ERR(filename);
4415
4416         inode = file_inode(fp->filp);
4417         generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4418
4419         ksmbd_debug(SMB, "filename = %s\n", filename);
4420         delete_pending = ksmbd_inode_pending_delete(fp);
4421         file_info = (struct smb2_file_all_info *)rsp->Buffer;
4422
4423         file_info->CreationTime = cpu_to_le64(fp->create_time);
4424         time = ksmbd_UnixTimeToNT(stat.atime);
4425         file_info->LastAccessTime = cpu_to_le64(time);
4426         time = ksmbd_UnixTimeToNT(stat.mtime);
4427         file_info->LastWriteTime = cpu_to_le64(time);
4428         time = ksmbd_UnixTimeToNT(stat.ctime);
4429         file_info->ChangeTime = cpu_to_le64(time);
4430         file_info->Attributes = fp->f_ci->m_fattr;
4431         file_info->Pad1 = 0;
4432         file_info->AllocationSize =
4433                 cpu_to_le64(get_allocation_size(inode, &stat));
4434         file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4435         file_info->NumberOfLinks =
4436                         cpu_to_le32(get_nlink(&stat) - delete_pending);
4437         file_info->DeletePending = delete_pending;
4438         file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4439         file_info->Pad2 = 0;
4440         file_info->IndexNumber = cpu_to_le64(stat.ino);
4441         file_info->EASize = 0;
4442         file_info->AccessFlags = fp->daccess;
4443         file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4444         file_info->Mode = fp->coption;
4445         file_info->AlignmentRequirement = 0;
4446         conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4447                                      PATH_MAX, conn->local_nls, 0);
4448         conv_len *= 2;
4449         file_info->FileNameLength = cpu_to_le32(conv_len);
4450         rsp->OutputBufferLength =
4451                 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4452         kfree(filename);
4453         inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4454         return 0;
4455 }
4456
4457 static void get_file_alternate_info(struct ksmbd_work *work,
4458                                     struct smb2_query_info_rsp *rsp,
4459                                     struct ksmbd_file *fp,
4460                                     void *rsp_org)
4461 {
4462         struct ksmbd_conn *conn = work->conn;
4463         struct smb2_file_alt_name_info *file_info;
4464         struct dentry *dentry = fp->filp->f_path.dentry;
4465         int conv_len;
4466
4467         spin_lock(&dentry->d_lock);
4468         file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4469         conv_len = ksmbd_extract_shortname(conn,
4470                                            dentry->d_name.name,
4471                                            file_info->FileName);
4472         spin_unlock(&dentry->d_lock);
4473         file_info->FileNameLength = cpu_to_le32(conv_len);
4474         rsp->OutputBufferLength =
4475                 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4476         inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4477 }
4478
4479 static void get_file_stream_info(struct ksmbd_work *work,
4480                                  struct smb2_query_info_rsp *rsp,
4481                                  struct ksmbd_file *fp,
4482                                  void *rsp_org)
4483 {
4484         struct ksmbd_conn *conn = work->conn;
4485         struct smb2_file_stream_info *file_info;
4486         char *stream_name, *xattr_list = NULL, *stream_buf;
4487         struct kstat stat;
4488         struct path *path = &fp->filp->f_path;
4489         ssize_t xattr_list_len;
4490         int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4491         int buf_free_len;
4492         struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4493
4494         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4495                          &stat);
4496         file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4497
4498         buf_free_len =
4499                 smb2_calc_max_out_buf_len(work, 8,
4500                                           le32_to_cpu(req->OutputBufferLength));
4501         if (buf_free_len < 0)
4502                 goto out;
4503
4504         xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4505         if (xattr_list_len < 0) {
4506                 goto out;
4507         } else if (!xattr_list_len) {
4508                 ksmbd_debug(SMB, "empty xattr in the file\n");
4509                 goto out;
4510         }
4511
4512         while (idx < xattr_list_len) {
4513                 stream_name = xattr_list + idx;
4514                 streamlen = strlen(stream_name);
4515                 idx += streamlen + 1;
4516
4517                 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4518
4519                 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4520                             STREAM_PREFIX, STREAM_PREFIX_LEN))
4521                         continue;
4522
4523                 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4524                                 STREAM_PREFIX_LEN);
4525                 streamlen = stream_name_len;
4526
4527                 /* plus : size */
4528                 streamlen += 1;
4529                 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4530                 if (!stream_buf)
4531                         break;
4532
4533                 streamlen = snprintf(stream_buf, streamlen + 1,
4534                                      ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4535
4536                 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4537                 if (next > buf_free_len) {
4538                         kfree(stream_buf);
4539                         break;
4540                 }
4541
4542                 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4543                 streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
4544                                                stream_buf, streamlen,
4545                                                conn->local_nls, 0);
4546                 streamlen *= 2;
4547                 kfree(stream_buf);
4548                 file_info->StreamNameLength = cpu_to_le32(streamlen);
4549                 file_info->StreamSize = cpu_to_le64(stream_name_len);
4550                 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4551
4552                 nbytes += next;
4553                 buf_free_len -= next;
4554                 file_info->NextEntryOffset = cpu_to_le32(next);
4555         }
4556
4557 out:
4558         if (!S_ISDIR(stat.mode) &&
4559             buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4560                 file_info = (struct smb2_file_stream_info *)
4561                         &rsp->Buffer[nbytes];
4562                 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4563                                               "::$DATA", 7, conn->local_nls, 0);
4564                 streamlen *= 2;
4565                 file_info->StreamNameLength = cpu_to_le32(streamlen);
4566                 file_info->StreamSize = cpu_to_le64(stat.size);
4567                 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4568                 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4569         }
4570
4571         /* last entry offset should be 0 */
4572         file_info->NextEntryOffset = 0;
4573         kvfree(xattr_list);
4574
4575         rsp->OutputBufferLength = cpu_to_le32(nbytes);
4576         inc_rfc1001_len(rsp_org, nbytes);
4577 }
4578
4579 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4580                                    struct ksmbd_file *fp, void *rsp_org)
4581 {
4582         struct smb2_file_internal_info *file_info;
4583         struct kstat stat;
4584
4585         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4586                          &stat);
4587         file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4588         file_info->IndexNumber = cpu_to_le64(stat.ino);
4589         rsp->OutputBufferLength =
4590                 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4591         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4592 }
4593
4594 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4595                                       struct ksmbd_file *fp, void *rsp_org)
4596 {
4597         struct smb2_file_ntwrk_info *file_info;
4598         struct inode *inode;
4599         struct kstat stat;
4600         u64 time;
4601
4602         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4603                 pr_err("no right to read the attributes : 0x%x\n",
4604                        fp->daccess);
4605                 return -EACCES;
4606         }
4607
4608         file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4609
4610         inode = file_inode(fp->filp);
4611         generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4612
4613         file_info->CreationTime = cpu_to_le64(fp->create_time);
4614         time = ksmbd_UnixTimeToNT(stat.atime);
4615         file_info->LastAccessTime = cpu_to_le64(time);
4616         time = ksmbd_UnixTimeToNT(stat.mtime);
4617         file_info->LastWriteTime = cpu_to_le64(time);
4618         time = ksmbd_UnixTimeToNT(stat.ctime);
4619         file_info->ChangeTime = cpu_to_le64(time);
4620         file_info->Attributes = fp->f_ci->m_fattr;
4621         file_info->AllocationSize =
4622                 cpu_to_le64(get_allocation_size(inode, &stat));
4623         file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4624         file_info->Reserved = cpu_to_le32(0);
4625         rsp->OutputBufferLength =
4626                 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4627         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4628         return 0;
4629 }
4630
4631 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4632 {
4633         struct smb2_file_ea_info *file_info;
4634
4635         file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4636         file_info->EASize = 0;
4637         rsp->OutputBufferLength =
4638                 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4639         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4640 }
4641
4642 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4643                                    struct ksmbd_file *fp, void *rsp_org)
4644 {
4645         struct smb2_file_pos_info *file_info;
4646
4647         file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4648         file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4649         rsp->OutputBufferLength =
4650                 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4651         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4652 }
4653
4654 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4655                                struct ksmbd_file *fp, void *rsp_org)
4656 {
4657         struct smb2_file_mode_info *file_info;
4658
4659         file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4660         file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4661         rsp->OutputBufferLength =
4662                 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4663         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4664 }
4665
4666 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4667                                       struct ksmbd_file *fp, void *rsp_org)
4668 {
4669         struct smb2_file_comp_info *file_info;
4670         struct kstat stat;
4671
4672         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4673                          &stat);
4674
4675         file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4676         file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4677         file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4678         file_info->CompressionUnitShift = 0;
4679         file_info->ChunkShift = 0;
4680         file_info->ClusterShift = 0;
4681         memset(&file_info->Reserved[0], 0, 3);
4682
4683         rsp->OutputBufferLength =
4684                 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4685         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4686 }
4687
4688 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4689                                        struct ksmbd_file *fp, void *rsp_org)
4690 {
4691         struct smb2_file_attr_tag_info *file_info;
4692
4693         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4694                 pr_err("no right to read the attributes : 0x%x\n",
4695                        fp->daccess);
4696                 return -EACCES;
4697         }
4698
4699         file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4700         file_info->FileAttributes = fp->f_ci->m_fattr;
4701         file_info->ReparseTag = 0;
4702         rsp->OutputBufferLength =
4703                 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4704         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4705         return 0;
4706 }
4707
4708 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4709                                 struct ksmbd_file *fp, void *rsp_org)
4710 {
4711         struct smb311_posix_qinfo *file_info;
4712         struct inode *inode = file_inode(fp->filp);
4713         u64 time;
4714
4715         file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4716         file_info->CreationTime = cpu_to_le64(fp->create_time);
4717         time = ksmbd_UnixTimeToNT(inode->i_atime);
4718         file_info->LastAccessTime = cpu_to_le64(time);
4719         time = ksmbd_UnixTimeToNT(inode->i_mtime);
4720         file_info->LastWriteTime = cpu_to_le64(time);
4721         time = ksmbd_UnixTimeToNT(inode->i_ctime);
4722         file_info->ChangeTime = cpu_to_le64(time);
4723         file_info->DosAttributes = fp->f_ci->m_fattr;
4724         file_info->Inode = cpu_to_le64(inode->i_ino);
4725         file_info->EndOfFile = cpu_to_le64(inode->i_size);
4726         file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4727         file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4728         file_info->Mode = cpu_to_le32(inode->i_mode);
4729         file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4730         rsp->OutputBufferLength =
4731                 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4732         inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4733         return 0;
4734 }
4735
4736 static int smb2_get_info_file(struct ksmbd_work *work,
4737                               struct smb2_query_info_req *req,
4738                               struct smb2_query_info_rsp *rsp)
4739 {
4740         struct ksmbd_file *fp;
4741         int fileinfoclass = 0;
4742         int rc = 0;
4743         int file_infoclass_size;
4744         unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4745
4746         if (test_share_config_flag(work->tcon->share_conf,
4747                                    KSMBD_SHARE_FLAG_PIPE)) {
4748                 /* smb2 info file called for pipe */
4749                 return smb2_get_info_file_pipe(work->sess, req, rsp,
4750                                                work->response_buf);
4751         }
4752
4753         if (work->next_smb2_rcv_hdr_off) {
4754                 if (!has_file_id(req->VolatileFileId)) {
4755                         ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4756                                     work->compound_fid);
4757                         id = work->compound_fid;
4758                         pid = work->compound_pfid;
4759                 }
4760         }
4761
4762         if (!has_file_id(id)) {
4763                 id = req->VolatileFileId;
4764                 pid = req->PersistentFileId;
4765         }
4766
4767         fp = ksmbd_lookup_fd_slow(work, id, pid);
4768         if (!fp)
4769                 return -ENOENT;
4770
4771         fileinfoclass = req->FileInfoClass;
4772
4773         switch (fileinfoclass) {
4774         case FILE_ACCESS_INFORMATION:
4775                 get_file_access_info(rsp, fp, work->response_buf);
4776                 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4777                 break;
4778
4779         case FILE_BASIC_INFORMATION:
4780                 rc = get_file_basic_info(rsp, fp, work->response_buf);
4781                 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4782                 break;
4783
4784         case FILE_STANDARD_INFORMATION:
4785                 get_file_standard_info(rsp, fp, work->response_buf);
4786                 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4787                 break;
4788
4789         case FILE_ALIGNMENT_INFORMATION:
4790                 get_file_alignment_info(rsp, work->response_buf);
4791                 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4792                 break;
4793
4794         case FILE_ALL_INFORMATION:
4795                 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4796                 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4797                 break;
4798
4799         case FILE_ALTERNATE_NAME_INFORMATION:
4800                 get_file_alternate_info(work, rsp, fp, work->response_buf);
4801                 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4802                 break;
4803
4804         case FILE_STREAM_INFORMATION:
4805                 get_file_stream_info(work, rsp, fp, work->response_buf);
4806                 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4807                 break;
4808
4809         case FILE_INTERNAL_INFORMATION:
4810                 get_file_internal_info(rsp, fp, work->response_buf);
4811                 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4812                 break;
4813
4814         case FILE_NETWORK_OPEN_INFORMATION:
4815                 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4816                 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4817                 break;
4818
4819         case FILE_EA_INFORMATION:
4820                 get_file_ea_info(rsp, work->response_buf);
4821                 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4822                 break;
4823
4824         case FILE_FULL_EA_INFORMATION:
4825                 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4826                 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4827                 break;
4828
4829         case FILE_POSITION_INFORMATION:
4830                 get_file_position_info(rsp, fp, work->response_buf);
4831                 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4832                 break;
4833
4834         case FILE_MODE_INFORMATION:
4835                 get_file_mode_info(rsp, fp, work->response_buf);
4836                 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4837                 break;
4838
4839         case FILE_COMPRESSION_INFORMATION:
4840                 get_file_compression_info(rsp, fp, work->response_buf);
4841                 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4842                 break;
4843
4844         case FILE_ATTRIBUTE_TAG_INFORMATION:
4845                 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4846                 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4847                 break;
4848         case SMB_FIND_FILE_POSIX_INFO:
4849                 if (!work->tcon->posix_extensions) {
4850                         pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4851                         rc = -EOPNOTSUPP;
4852                 } else {
4853                         rc = find_file_posix_info(rsp, fp, work->response_buf);
4854                         file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4855                 }
4856                 break;
4857         default:
4858                 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4859                             fileinfoclass);
4860                 rc = -EOPNOTSUPP;
4861         }
4862         if (!rc)
4863                 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4864                                       rsp, work->response_buf,
4865                                       file_infoclass_size);
4866         ksmbd_fd_put(work, fp);
4867         return rc;
4868 }
4869
4870 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4871                                     struct smb2_query_info_req *req,
4872                                     struct smb2_query_info_rsp *rsp)
4873 {
4874         struct ksmbd_session *sess = work->sess;
4875         struct ksmbd_conn *conn = work->conn;
4876         struct ksmbd_share_config *share = work->tcon->share_conf;
4877         int fsinfoclass = 0;
4878         struct kstatfs stfs;
4879         struct path path;
4880         int rc = 0, len;
4881         int fs_infoclass_size = 0;
4882
4883         rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4884         if (rc) {
4885                 pr_err("cannot create vfs path\n");
4886                 return -EIO;
4887         }
4888
4889         rc = vfs_statfs(&path, &stfs);
4890         if (rc) {
4891                 pr_err("cannot do stat of path %s\n", share->path);
4892                 path_put(&path);
4893                 return -EIO;
4894         }
4895
4896         fsinfoclass = req->FileInfoClass;
4897
4898         switch (fsinfoclass) {
4899         case FS_DEVICE_INFORMATION:
4900         {
4901                 struct filesystem_device_info *info;
4902
4903                 info = (struct filesystem_device_info *)rsp->Buffer;
4904
4905                 info->DeviceType = cpu_to_le32(stfs.f_type);
4906                 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4907                 rsp->OutputBufferLength = cpu_to_le32(8);
4908                 inc_rfc1001_len(work->response_buf, 8);
4909                 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4910                 break;
4911         }
4912         case FS_ATTRIBUTE_INFORMATION:
4913         {
4914                 struct filesystem_attribute_info *info;
4915                 size_t sz;
4916
4917                 info = (struct filesystem_attribute_info *)rsp->Buffer;
4918                 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4919                                                FILE_PERSISTENT_ACLS |
4920                                                FILE_UNICODE_ON_DISK |
4921                                                FILE_CASE_PRESERVED_NAMES |
4922                                                FILE_CASE_SENSITIVE_SEARCH |
4923                                                FILE_SUPPORTS_BLOCK_REFCOUNTING);
4924
4925                 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4926
4927                 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4928                 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4929                                         "NTFS", PATH_MAX, conn->local_nls, 0);
4930                 len = len * 2;
4931                 info->FileSystemNameLen = cpu_to_le32(len);
4932                 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4933                 rsp->OutputBufferLength = cpu_to_le32(sz);
4934                 inc_rfc1001_len(work->response_buf, sz);
4935                 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4936                 break;
4937         }
4938         case FS_VOLUME_INFORMATION:
4939         {
4940                 struct filesystem_vol_info *info;
4941                 size_t sz;
4942                 unsigned int serial_crc = 0;
4943
4944                 info = (struct filesystem_vol_info *)(rsp->Buffer);
4945                 info->VolumeCreationTime = 0;
4946                 serial_crc = crc32_le(serial_crc, share->name,
4947                                       strlen(share->name));
4948                 serial_crc = crc32_le(serial_crc, share->path,
4949                                       strlen(share->path));
4950                 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4951                                       strlen(ksmbd_netbios_name()));
4952                 /* Taking dummy value of serial number*/
4953                 info->SerialNumber = cpu_to_le32(serial_crc);
4954                 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4955                                         share->name, PATH_MAX,
4956                                         conn->local_nls, 0);
4957                 len = len * 2;
4958                 info->VolumeLabelSize = cpu_to_le32(len);
4959                 info->Reserved = 0;
4960                 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4961                 rsp->OutputBufferLength = cpu_to_le32(sz);
4962                 inc_rfc1001_len(work->response_buf, sz);
4963                 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4964                 break;
4965         }
4966         case FS_SIZE_INFORMATION:
4967         {
4968                 struct filesystem_info *info;
4969
4970                 info = (struct filesystem_info *)(rsp->Buffer);
4971                 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4972                 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4973                 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4974                 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4975                 rsp->OutputBufferLength = cpu_to_le32(24);
4976                 inc_rfc1001_len(work->response_buf, 24);
4977                 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4978                 break;
4979         }
4980         case FS_FULL_SIZE_INFORMATION:
4981         {
4982                 struct smb2_fs_full_size_info *info;
4983
4984                 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4985                 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4986                 info->CallerAvailableAllocationUnits =
4987                                         cpu_to_le64(stfs.f_bavail);
4988                 info->ActualAvailableAllocationUnits =
4989                                         cpu_to_le64(stfs.f_bfree);
4990                 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4991                 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4992                 rsp->OutputBufferLength = cpu_to_le32(32);
4993                 inc_rfc1001_len(work->response_buf, 32);
4994                 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4995                 break;
4996         }
4997         case FS_OBJECT_ID_INFORMATION:
4998         {
4999                 struct object_id_info *info;
5000
5001                 info = (struct object_id_info *)(rsp->Buffer);
5002
5003                 if (!user_guest(sess->user))
5004                         memcpy(info->objid, user_passkey(sess->user), 16);
5005                 else
5006                         memset(info->objid, 0, 16);
5007
5008                 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5009                 info->extended_info.version = cpu_to_le32(1);
5010                 info->extended_info.release = cpu_to_le32(1);
5011                 info->extended_info.rel_date = 0;
5012                 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5013                 rsp->OutputBufferLength = cpu_to_le32(64);
5014                 inc_rfc1001_len(work->response_buf, 64);
5015                 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5016                 break;
5017         }
5018         case FS_SECTOR_SIZE_INFORMATION:
5019         {
5020                 struct smb3_fs_ss_info *info;
5021                 unsigned int sector_size =
5022                         min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5023
5024                 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5025
5026                 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5027                 info->PhysicalBytesPerSectorForAtomicity =
5028                                 cpu_to_le32(sector_size);
5029                 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5030                 info->FSEffPhysicalBytesPerSectorForAtomicity =
5031                                 cpu_to_le32(sector_size);
5032                 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5033                                     SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5034                 info->ByteOffsetForSectorAlignment = 0;
5035                 info->ByteOffsetForPartitionAlignment = 0;
5036                 rsp->OutputBufferLength = cpu_to_le32(28);
5037                 inc_rfc1001_len(work->response_buf, 28);
5038                 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5039                 break;
5040         }
5041         case FS_CONTROL_INFORMATION:
5042         {
5043                 /*
5044                  * TODO : The current implementation is based on
5045                  * test result with win7(NTFS) server. It's need to
5046                  * modify this to get valid Quota values
5047                  * from Linux kernel
5048                  */
5049                 struct smb2_fs_control_info *info;
5050
5051                 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5052                 info->FreeSpaceStartFiltering = 0;
5053                 info->FreeSpaceThreshold = 0;
5054                 info->FreeSpaceStopFiltering = 0;
5055                 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5056                 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5057                 info->Padding = 0;
5058                 rsp->OutputBufferLength = cpu_to_le32(48);
5059                 inc_rfc1001_len(work->response_buf, 48);
5060                 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5061                 break;
5062         }
5063         case FS_POSIX_INFORMATION:
5064         {
5065                 struct filesystem_posix_info *info;
5066
5067                 if (!work->tcon->posix_extensions) {
5068                         pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5069                         rc = -EOPNOTSUPP;
5070                 } else {
5071                         info = (struct filesystem_posix_info *)(rsp->Buffer);
5072                         info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5073                         info->BlockSize = cpu_to_le32(stfs.f_bsize);
5074                         info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5075                         info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5076                         info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5077                         info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5078                         info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5079                         rsp->OutputBufferLength = cpu_to_le32(56);
5080                         inc_rfc1001_len(work->response_buf, 56);
5081                         fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5082                 }
5083                 break;
5084         }
5085         default:
5086                 path_put(&path);
5087                 return -EOPNOTSUPP;
5088         }
5089         rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5090                               rsp, work->response_buf,
5091                               fs_infoclass_size);
5092         path_put(&path);
5093         return rc;
5094 }
5095
5096 static int smb2_get_info_sec(struct ksmbd_work *work,
5097                              struct smb2_query_info_req *req,
5098                              struct smb2_query_info_rsp *rsp)
5099 {
5100         struct ksmbd_file *fp;
5101         struct user_namespace *user_ns;
5102         struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5103         struct smb_fattr fattr = {{0}};
5104         struct inode *inode;
5105         __u32 secdesclen;
5106         unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5107         int addition_info = le32_to_cpu(req->AdditionalInformation);
5108         int rc;
5109
5110         if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5111                               PROTECTED_DACL_SECINFO |
5112                               UNPROTECTED_DACL_SECINFO)) {
5113                 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5114                        addition_info);
5115
5116                 pntsd->revision = cpu_to_le16(1);
5117                 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5118                 pntsd->osidoffset = 0;
5119                 pntsd->gsidoffset = 0;
5120                 pntsd->sacloffset = 0;
5121                 pntsd->dacloffset = 0;
5122
5123                 secdesclen = sizeof(struct smb_ntsd);
5124                 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5125                 inc_rfc1001_len(work->response_buf, secdesclen);
5126
5127                 return 0;
5128         }
5129
5130         if (work->next_smb2_rcv_hdr_off) {
5131                 if (!has_file_id(req->VolatileFileId)) {
5132                         ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5133                                     work->compound_fid);
5134                         id = work->compound_fid;
5135                         pid = work->compound_pfid;
5136                 }
5137         }
5138
5139         if (!has_file_id(id)) {
5140                 id = req->VolatileFileId;
5141                 pid = req->PersistentFileId;
5142         }
5143
5144         fp = ksmbd_lookup_fd_slow(work, id, pid);
5145         if (!fp)
5146                 return -ENOENT;
5147
5148         user_ns = file_mnt_user_ns(fp->filp);
5149         inode = file_inode(fp->filp);
5150         ksmbd_acls_fattr(&fattr, user_ns, inode);
5151
5152         if (test_share_config_flag(work->tcon->share_conf,
5153                                    KSMBD_SHARE_FLAG_ACL_XATTR))
5154                 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5155                                        fp->filp->f_path.dentry, &ppntsd);
5156
5157         rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5158                             &secdesclen, &fattr);
5159         posix_acl_release(fattr.cf_acls);
5160         posix_acl_release(fattr.cf_dacls);
5161         kfree(ppntsd);
5162         ksmbd_fd_put(work, fp);
5163         if (rc)
5164                 return rc;
5165
5166         rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5167         inc_rfc1001_len(work->response_buf, secdesclen);
5168         return 0;
5169 }
5170
5171 /**
5172  * smb2_query_info() - handler for smb2 query info command
5173  * @work:       smb work containing query info request buffer
5174  *
5175  * Return:      0 on success, otherwise error
5176  */
5177 int smb2_query_info(struct ksmbd_work *work)
5178 {
5179         struct smb2_query_info_req *req;
5180         struct smb2_query_info_rsp *rsp;
5181         int rc = 0;
5182
5183         WORK_BUFFERS(work, req, rsp);
5184
5185         ksmbd_debug(SMB, "GOT query info request\n");
5186
5187         switch (req->InfoType) {
5188         case SMB2_O_INFO_FILE:
5189                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5190                 rc = smb2_get_info_file(work, req, rsp);
5191                 break;
5192         case SMB2_O_INFO_FILESYSTEM:
5193                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5194                 rc = smb2_get_info_filesystem(work, req, rsp);
5195                 break;
5196         case SMB2_O_INFO_SECURITY:
5197                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5198                 rc = smb2_get_info_sec(work, req, rsp);
5199                 break;
5200         default:
5201                 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5202                             req->InfoType);
5203                 rc = -EOPNOTSUPP;
5204         }
5205
5206         if (rc < 0) {
5207                 if (rc == -EACCES)
5208                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
5209                 else if (rc == -ENOENT)
5210                         rsp->hdr.Status = STATUS_FILE_CLOSED;
5211                 else if (rc == -EIO)
5212                         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5213                 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5214                         rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5215                 smb2_set_err_rsp(work);
5216
5217                 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5218                             rc);
5219                 return rc;
5220         }
5221         rsp->StructureSize = cpu_to_le16(9);
5222         rsp->OutputBufferOffset = cpu_to_le16(72);
5223         inc_rfc1001_len(work->response_buf, 8);
5224         return 0;
5225 }
5226
5227 /**
5228  * smb2_close_pipe() - handler for closing IPC pipe
5229  * @work:       smb work containing close request buffer
5230  *
5231  * Return:      0
5232  */
5233 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5234 {
5235         u64 id;
5236         struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5237         struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5238
5239         id = req->VolatileFileId;
5240         ksmbd_session_rpc_close(work->sess, id);
5241
5242         rsp->StructureSize = cpu_to_le16(60);
5243         rsp->Flags = 0;
5244         rsp->Reserved = 0;
5245         rsp->CreationTime = 0;
5246         rsp->LastAccessTime = 0;
5247         rsp->LastWriteTime = 0;
5248         rsp->ChangeTime = 0;
5249         rsp->AllocationSize = 0;
5250         rsp->EndOfFile = 0;
5251         rsp->Attributes = 0;
5252         inc_rfc1001_len(work->response_buf, 60);
5253         return 0;
5254 }
5255
5256 /**
5257  * smb2_close() - handler for smb2 close file command
5258  * @work:       smb work containing close request buffer
5259  *
5260  * Return:      0
5261  */
5262 int smb2_close(struct ksmbd_work *work)
5263 {
5264         u64 volatile_id = KSMBD_NO_FID;
5265         u64 sess_id;
5266         struct smb2_close_req *req;
5267         struct smb2_close_rsp *rsp;
5268         struct ksmbd_conn *conn = work->conn;
5269         struct ksmbd_file *fp;
5270         struct inode *inode;
5271         u64 time;
5272         int err = 0;
5273
5274         WORK_BUFFERS(work, req, rsp);
5275
5276         if (test_share_config_flag(work->tcon->share_conf,
5277                                    KSMBD_SHARE_FLAG_PIPE)) {
5278                 ksmbd_debug(SMB, "IPC pipe close request\n");
5279                 return smb2_close_pipe(work);
5280         }
5281
5282         sess_id = le64_to_cpu(req->hdr.SessionId);
5283         if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5284                 sess_id = work->compound_sid;
5285
5286         work->compound_sid = 0;
5287         if (check_session_id(conn, sess_id)) {
5288                 work->compound_sid = sess_id;
5289         } else {
5290                 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5291                 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5292                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5293                 err = -EBADF;
5294                 goto out;
5295         }
5296
5297         if (work->next_smb2_rcv_hdr_off &&
5298             !has_file_id(req->VolatileFileId)) {
5299                 if (!has_file_id(work->compound_fid)) {
5300                         /* file already closed, return FILE_CLOSED */
5301                         ksmbd_debug(SMB, "file already closed\n");
5302                         rsp->hdr.Status = STATUS_FILE_CLOSED;
5303                         err = -EBADF;
5304                         goto out;
5305                 } else {
5306                         ksmbd_debug(SMB,
5307                                     "Compound request set FID = %llu:%llu\n",
5308                                     work->compound_fid,
5309                                     work->compound_pfid);
5310                         volatile_id = work->compound_fid;
5311
5312                         /* file closed, stored id is not valid anymore */
5313                         work->compound_fid = KSMBD_NO_FID;
5314                         work->compound_pfid = KSMBD_NO_FID;
5315                 }
5316         } else {
5317                 volatile_id = req->VolatileFileId;
5318         }
5319         ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5320
5321         rsp->StructureSize = cpu_to_le16(60);
5322         rsp->Reserved = 0;
5323
5324         if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5325                 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5326                 if (!fp) {
5327                         err = -ENOENT;
5328                         goto out;
5329                 }
5330
5331                 inode = file_inode(fp->filp);
5332                 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5333                 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5334                         cpu_to_le64(inode->i_blocks << 9);
5335                 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5336                 rsp->Attributes = fp->f_ci->m_fattr;
5337                 rsp->CreationTime = cpu_to_le64(fp->create_time);
5338                 time = ksmbd_UnixTimeToNT(inode->i_atime);
5339                 rsp->LastAccessTime = cpu_to_le64(time);
5340                 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5341                 rsp->LastWriteTime = cpu_to_le64(time);
5342                 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5343                 rsp->ChangeTime = cpu_to_le64(time);
5344                 ksmbd_fd_put(work, fp);
5345         } else {
5346                 rsp->Flags = 0;
5347                 rsp->AllocationSize = 0;
5348                 rsp->EndOfFile = 0;
5349                 rsp->Attributes = 0;
5350                 rsp->CreationTime = 0;
5351                 rsp->LastAccessTime = 0;
5352                 rsp->LastWriteTime = 0;
5353                 rsp->ChangeTime = 0;
5354         }
5355
5356         err = ksmbd_close_fd(work, volatile_id);
5357 out:
5358         if (err) {
5359                 if (rsp->hdr.Status == 0)
5360                         rsp->hdr.Status = STATUS_FILE_CLOSED;
5361                 smb2_set_err_rsp(work);
5362         } else {
5363                 inc_rfc1001_len(work->response_buf, 60);
5364         }
5365
5366         return 0;
5367 }
5368
5369 /**
5370  * smb2_echo() - handler for smb2 echo(ping) command
5371  * @work:       smb work containing echo request buffer
5372  *
5373  * Return:      0
5374  */
5375 int smb2_echo(struct ksmbd_work *work)
5376 {
5377         struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5378
5379         rsp->StructureSize = cpu_to_le16(4);
5380         rsp->Reserved = 0;
5381         inc_rfc1001_len(work->response_buf, 4);
5382         return 0;
5383 }
5384
5385 static int smb2_rename(struct ksmbd_work *work,
5386                        struct ksmbd_file *fp,
5387                        struct user_namespace *user_ns,
5388                        struct smb2_file_rename_info *file_info,
5389                        struct nls_table *local_nls)
5390 {
5391         struct ksmbd_share_config *share = fp->tcon->share_conf;
5392         char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5393         char *pathname = NULL;
5394         struct path path;
5395         bool file_present = true;
5396         int rc;
5397
5398         ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5399         pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5400         if (!pathname)
5401                 return -ENOMEM;
5402
5403         abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5404         if (IS_ERR(abs_oldname)) {
5405                 rc = -EINVAL;
5406                 goto out;
5407         }
5408         old_name = strrchr(abs_oldname, '/');
5409         if (old_name && old_name[1] != '\0') {
5410                 old_name++;
5411         } else {
5412                 ksmbd_debug(SMB, "can't get last component in path %s\n",
5413                             abs_oldname);
5414                 rc = -ENOENT;
5415                 goto out;
5416         }
5417
5418         new_name = smb2_get_name(file_info->FileName,
5419                                  le32_to_cpu(file_info->FileNameLength),
5420                                  local_nls);
5421         if (IS_ERR(new_name)) {
5422                 rc = PTR_ERR(new_name);
5423                 goto out;
5424         }
5425
5426         if (strchr(new_name, ':')) {
5427                 int s_type;
5428                 char *xattr_stream_name, *stream_name = NULL;
5429                 size_t xattr_stream_size;
5430                 int len;
5431
5432                 rc = parse_stream_name(new_name, &stream_name, &s_type);
5433                 if (rc < 0)
5434                         goto out;
5435
5436                 len = strlen(new_name);
5437                 if (len > 0 && new_name[len - 1] != '/') {
5438                         pr_err("not allow base filename in rename\n");
5439                         rc = -ESHARE;
5440                         goto out;
5441                 }
5442
5443                 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5444                                                  &xattr_stream_name,
5445                                                  &xattr_stream_size,
5446                                                  s_type);
5447                 if (rc)
5448                         goto out;
5449
5450                 rc = ksmbd_vfs_setxattr(user_ns,
5451                                         fp->filp->f_path.dentry,
5452                                         xattr_stream_name,
5453                                         NULL, 0, 0);
5454                 if (rc < 0) {
5455                         pr_err("failed to store stream name in xattr: %d\n",
5456                                rc);
5457                         rc = -EINVAL;
5458                         goto out;
5459                 }
5460
5461                 goto out;
5462         }
5463
5464         ksmbd_debug(SMB, "new name %s\n", new_name);
5465         rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5466         if (rc) {
5467                 if (rc != -ENOENT)
5468                         goto out;
5469                 file_present = false;
5470         } else {
5471                 path_put(&path);
5472         }
5473
5474         if (ksmbd_share_veto_filename(share, new_name)) {
5475                 rc = -ENOENT;
5476                 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5477                 goto out;
5478         }
5479
5480         if (file_info->ReplaceIfExists) {
5481                 if (file_present) {
5482                         rc = ksmbd_vfs_remove_file(work, new_name);
5483                         if (rc) {
5484                                 if (rc != -ENOTEMPTY)
5485                                         rc = -EINVAL;
5486                                 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5487                                             new_name, rc);
5488                                 goto out;
5489                         }
5490                 }
5491         } else {
5492                 if (file_present &&
5493                     strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5494                         rc = -EEXIST;
5495                         ksmbd_debug(SMB,
5496                                     "cannot rename already existing file\n");
5497                         goto out;
5498                 }
5499         }
5500
5501         rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5502 out:
5503         kfree(pathname);
5504         if (!IS_ERR(new_name))
5505                 kfree(new_name);
5506         return rc;
5507 }
5508
5509 static int smb2_create_link(struct ksmbd_work *work,
5510                             struct ksmbd_share_config *share,
5511                             struct smb2_file_link_info *file_info,
5512                             unsigned int buf_len, struct file *filp,
5513                             struct nls_table *local_nls)
5514 {
5515         char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5516         struct path path;
5517         bool file_present = true;
5518         int rc;
5519
5520         if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5521                         le32_to_cpu(file_info->FileNameLength))
5522                 return -EINVAL;
5523
5524         ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5525         pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5526         if (!pathname)
5527                 return -ENOMEM;
5528
5529         link_name = smb2_get_name(file_info->FileName,
5530                                   le32_to_cpu(file_info->FileNameLength),
5531                                   local_nls);
5532         if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5533                 rc = -EINVAL;
5534                 goto out;
5535         }
5536
5537         ksmbd_debug(SMB, "link name is %s\n", link_name);
5538         target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5539         if (IS_ERR(target_name)) {
5540                 rc = -EINVAL;
5541                 goto out;
5542         }
5543
5544         ksmbd_debug(SMB, "target name is %s\n", target_name);
5545         rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5546         if (rc) {
5547                 if (rc != -ENOENT)
5548                         goto out;
5549                 file_present = false;
5550         } else {
5551                 path_put(&path);
5552         }
5553
5554         if (file_info->ReplaceIfExists) {
5555                 if (file_present) {
5556                         rc = ksmbd_vfs_remove_file(work, link_name);
5557                         if (rc) {
5558                                 rc = -EINVAL;
5559                                 ksmbd_debug(SMB, "cannot delete %s\n",
5560                                             link_name);
5561                                 goto out;
5562                         }
5563                 }
5564         } else {
5565                 if (file_present) {
5566                         rc = -EEXIST;
5567                         ksmbd_debug(SMB, "link already exists\n");
5568                         goto out;
5569                 }
5570         }
5571
5572         rc = ksmbd_vfs_link(work, target_name, link_name);
5573         if (rc)
5574                 rc = -EINVAL;
5575 out:
5576         if (!IS_ERR(link_name))
5577                 kfree(link_name);
5578         kfree(pathname);
5579         return rc;
5580 }
5581
5582 static int set_file_basic_info(struct ksmbd_file *fp,
5583                                struct smb2_file_basic_info *file_info,
5584                                struct ksmbd_share_config *share)
5585 {
5586         struct iattr attrs;
5587         struct file *filp;
5588         struct inode *inode;
5589         struct user_namespace *user_ns;
5590         int rc = 0;
5591
5592         if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5593                 return -EACCES;
5594
5595         attrs.ia_valid = 0;
5596         filp = fp->filp;
5597         inode = file_inode(filp);
5598         user_ns = file_mnt_user_ns(filp);
5599
5600         if (file_info->CreationTime)
5601                 fp->create_time = le64_to_cpu(file_info->CreationTime);
5602
5603         if (file_info->LastAccessTime) {
5604                 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5605                 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5606         }
5607
5608         attrs.ia_valid |= ATTR_CTIME;
5609         if (file_info->ChangeTime)
5610                 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5611         else
5612                 attrs.ia_ctime = inode->i_ctime;
5613
5614         if (file_info->LastWriteTime) {
5615                 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5616                 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5617         }
5618
5619         if (file_info->Attributes) {
5620                 if (!S_ISDIR(inode->i_mode) &&
5621                     file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5622                         pr_err("can't change a file to a directory\n");
5623                         return -EINVAL;
5624                 }
5625
5626                 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5627                         fp->f_ci->m_fattr = file_info->Attributes |
5628                                 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5629         }
5630
5631         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5632             (file_info->CreationTime || file_info->Attributes)) {
5633                 struct xattr_dos_attrib da = {0};
5634
5635                 da.version = 4;
5636                 da.itime = fp->itime;
5637                 da.create_time = fp->create_time;
5638                 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5639                 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5640                         XATTR_DOSINFO_ITIME;
5641
5642                 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5643                                                     filp->f_path.dentry, &da);
5644                 if (rc)
5645                         ksmbd_debug(SMB,
5646                                     "failed to restore file attribute in EA\n");
5647                 rc = 0;
5648         }
5649
5650         if (attrs.ia_valid) {
5651                 struct dentry *dentry = filp->f_path.dentry;
5652                 struct inode *inode = d_inode(dentry);
5653
5654                 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5655                         return -EACCES;
5656
5657                 inode_lock(inode);
5658                 inode->i_ctime = attrs.ia_ctime;
5659                 attrs.ia_valid &= ~ATTR_CTIME;
5660                 rc = notify_change(user_ns, dentry, &attrs, NULL);
5661                 inode_unlock(inode);
5662         }
5663         return rc;
5664 }
5665
5666 static int set_file_allocation_info(struct ksmbd_work *work,
5667                                     struct ksmbd_file *fp,
5668                                     struct smb2_file_alloc_info *file_alloc_info)
5669 {
5670         /*
5671          * TODO : It's working fine only when store dos attributes
5672          * is not yes. need to implement a logic which works
5673          * properly with any smb.conf option
5674          */
5675
5676         loff_t alloc_blks;
5677         struct inode *inode;
5678         int rc;
5679
5680         if (!(fp->daccess & FILE_WRITE_DATA_LE))
5681                 return -EACCES;
5682
5683         alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5684         inode = file_inode(fp->filp);
5685
5686         if (alloc_blks > inode->i_blocks) {
5687                 smb_break_all_levII_oplock(work, fp, 1);
5688                 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5689                                    alloc_blks * 512);
5690                 if (rc && rc != -EOPNOTSUPP) {
5691                         pr_err("vfs_fallocate is failed : %d\n", rc);
5692                         return rc;
5693                 }
5694         } else if (alloc_blks < inode->i_blocks) {
5695                 loff_t size;
5696
5697                 /*
5698                  * Allocation size could be smaller than original one
5699                  * which means allocated blocks in file should be
5700                  * deallocated. use truncate to cut out it, but inode
5701                  * size is also updated with truncate offset.
5702                  * inode size is retained by backup inode size.
5703                  */
5704                 size = i_size_read(inode);
5705                 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5706                 if (rc) {
5707                         pr_err("truncate failed!, err %d\n", rc);
5708                         return rc;
5709                 }
5710                 if (size < alloc_blks * 512)
5711                         i_size_write(inode, size);
5712         }
5713         return 0;
5714 }
5715
5716 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5717                                 struct smb2_file_eof_info *file_eof_info)
5718 {
5719         loff_t newsize;
5720         struct inode *inode;
5721         int rc;
5722
5723         if (!(fp->daccess & FILE_WRITE_DATA_LE))
5724                 return -EACCES;
5725
5726         newsize = le64_to_cpu(file_eof_info->EndOfFile);
5727         inode = file_inode(fp->filp);
5728
5729         /*
5730          * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5731          * on FAT32 shared device, truncate execution time is too long
5732          * and network error could cause from windows client. because
5733          * truncate of some filesystem like FAT32 fill zero data in
5734          * truncated range.
5735          */
5736         if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5737                 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5738                 rc = ksmbd_vfs_truncate(work, fp, newsize);
5739                 if (rc) {
5740                         ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5741                         if (rc != -EAGAIN)
5742                                 rc = -EBADF;
5743                         return rc;
5744                 }
5745         }
5746         return 0;
5747 }
5748
5749 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5750                            struct smb2_file_rename_info *rename_info,
5751                            unsigned int buf_len)
5752 {
5753         struct user_namespace *user_ns;
5754         struct ksmbd_file *parent_fp;
5755         struct dentry *parent;
5756         struct dentry *dentry = fp->filp->f_path.dentry;
5757         int ret;
5758
5759         if (!(fp->daccess & FILE_DELETE_LE)) {
5760                 pr_err("no right to delete : 0x%x\n", fp->daccess);
5761                 return -EACCES;
5762         }
5763
5764         if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5765                         le32_to_cpu(rename_info->FileNameLength))
5766                 return -EINVAL;
5767
5768         user_ns = file_mnt_user_ns(fp->filp);
5769         if (ksmbd_stream_fd(fp))
5770                 goto next;
5771
5772         parent = dget_parent(dentry);
5773         ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5774         if (ret) {
5775                 dput(parent);
5776                 return ret;
5777         }
5778
5779         parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5780         inode_unlock(d_inode(parent));
5781         dput(parent);
5782
5783         if (parent_fp) {
5784                 if (parent_fp->daccess & FILE_DELETE_LE) {
5785                         pr_err("parent dir is opened with delete access\n");
5786                         ksmbd_fd_put(work, parent_fp);
5787                         return -ESHARE;
5788                 }
5789                 ksmbd_fd_put(work, parent_fp);
5790         }
5791 next:
5792         return smb2_rename(work, fp, user_ns, rename_info,
5793                            work->conn->local_nls);
5794 }
5795
5796 static int set_file_disposition_info(struct ksmbd_file *fp,
5797                                      struct smb2_file_disposition_info *file_info)
5798 {
5799         struct inode *inode;
5800
5801         if (!(fp->daccess & FILE_DELETE_LE)) {
5802                 pr_err("no right to delete : 0x%x\n", fp->daccess);
5803                 return -EACCES;
5804         }
5805
5806         inode = file_inode(fp->filp);
5807         if (file_info->DeletePending) {
5808                 if (S_ISDIR(inode->i_mode) &&
5809                     ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5810                         return -EBUSY;
5811                 ksmbd_set_inode_pending_delete(fp);
5812         } else {
5813                 ksmbd_clear_inode_pending_delete(fp);
5814         }
5815         return 0;
5816 }
5817
5818 static int set_file_position_info(struct ksmbd_file *fp,
5819                                   struct smb2_file_pos_info *file_info)
5820 {
5821         loff_t current_byte_offset;
5822         unsigned long sector_size;
5823         struct inode *inode;
5824
5825         inode = file_inode(fp->filp);
5826         current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5827         sector_size = inode->i_sb->s_blocksize;
5828
5829         if (current_byte_offset < 0 ||
5830             (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5831              current_byte_offset & (sector_size - 1))) {
5832                 pr_err("CurrentByteOffset is not valid : %llu\n",
5833                        current_byte_offset);
5834                 return -EINVAL;
5835         }
5836
5837         fp->filp->f_pos = current_byte_offset;
5838         return 0;
5839 }
5840
5841 static int set_file_mode_info(struct ksmbd_file *fp,
5842                               struct smb2_file_mode_info *file_info)
5843 {
5844         __le32 mode;
5845
5846         mode = file_info->Mode;
5847
5848         if ((mode & ~FILE_MODE_INFO_MASK)) {
5849                 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5850                 return -EINVAL;
5851         }
5852
5853         /*
5854          * TODO : need to implement consideration for
5855          * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5856          */
5857         ksmbd_vfs_set_fadvise(fp->filp, mode);
5858         fp->coption = mode;
5859         return 0;
5860 }
5861
5862 /**
5863  * smb2_set_info_file() - handler for smb2 set info command
5864  * @work:       smb work containing set info command buffer
5865  * @fp:         ksmbd_file pointer
5866  * @req:        request buffer pointer
5867  * @share:      ksmbd_share_config pointer
5868  *
5869  * Return:      0 on success, otherwise error
5870  * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5871  */
5872 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5873                               struct smb2_set_info_req *req,
5874                               struct ksmbd_share_config *share)
5875 {
5876         unsigned int buf_len = le32_to_cpu(req->BufferLength);
5877
5878         switch (req->FileInfoClass) {
5879         case FILE_BASIC_INFORMATION:
5880         {
5881                 if (buf_len < sizeof(struct smb2_file_basic_info))
5882                         return -EINVAL;
5883
5884                 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5885         }
5886         case FILE_ALLOCATION_INFORMATION:
5887         {
5888                 if (buf_len < sizeof(struct smb2_file_alloc_info))
5889                         return -EINVAL;
5890
5891                 return set_file_allocation_info(work, fp,
5892                                                 (struct smb2_file_alloc_info *)req->Buffer);
5893         }
5894         case FILE_END_OF_FILE_INFORMATION:
5895         {
5896                 if (buf_len < sizeof(struct smb2_file_eof_info))
5897                         return -EINVAL;
5898
5899                 return set_end_of_file_info(work, fp,
5900                                             (struct smb2_file_eof_info *)req->Buffer);
5901         }
5902         case FILE_RENAME_INFORMATION:
5903         {
5904                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5905                         ksmbd_debug(SMB,
5906                                     "User does not have write permission\n");
5907                         return -EACCES;
5908                 }
5909
5910                 if (buf_len < sizeof(struct smb2_file_rename_info))
5911                         return -EINVAL;
5912
5913                 return set_rename_info(work, fp,
5914                                        (struct smb2_file_rename_info *)req->Buffer,
5915                                        buf_len);
5916         }
5917         case FILE_LINK_INFORMATION:
5918         {
5919                 if (buf_len < sizeof(struct smb2_file_link_info))
5920                         return -EINVAL;
5921
5922                 return smb2_create_link(work, work->tcon->share_conf,
5923                                         (struct smb2_file_link_info *)req->Buffer,
5924                                         buf_len, fp->filp,
5925                                         work->conn->local_nls);
5926         }
5927         case FILE_DISPOSITION_INFORMATION:
5928         {
5929                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5930                         ksmbd_debug(SMB,
5931                                     "User does not have write permission\n");
5932                         return -EACCES;
5933                 }
5934
5935                 if (buf_len < sizeof(struct smb2_file_disposition_info))
5936                         return -EINVAL;
5937
5938                 return set_file_disposition_info(fp,
5939                                                  (struct smb2_file_disposition_info *)req->Buffer);
5940         }
5941         case FILE_FULL_EA_INFORMATION:
5942         {
5943                 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5944                         pr_err("Not permitted to write ext  attr: 0x%x\n",
5945                                fp->daccess);
5946                         return -EACCES;
5947                 }
5948
5949                 if (buf_len < sizeof(struct smb2_ea_info))
5950                         return -EINVAL;
5951
5952                 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5953                                    buf_len, &fp->filp->f_path);
5954         }
5955         case FILE_POSITION_INFORMATION:
5956         {
5957                 if (buf_len < sizeof(struct smb2_file_pos_info))
5958                         return -EINVAL;
5959
5960                 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5961         }
5962         case FILE_MODE_INFORMATION:
5963         {
5964                 if (buf_len < sizeof(struct smb2_file_mode_info))
5965                         return -EINVAL;
5966
5967                 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5968         }
5969         }
5970
5971         pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5972         return -EOPNOTSUPP;
5973 }
5974
5975 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5976                              char *buffer, int buf_len)
5977 {
5978         struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5979
5980         fp->saccess |= FILE_SHARE_DELETE_LE;
5981
5982         return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5983                         buf_len, false);
5984 }
5985
5986 /**
5987  * smb2_set_info() - handler for smb2 set info command handler
5988  * @work:       smb work containing set info request buffer
5989  *
5990  * Return:      0 on success, otherwise error
5991  */
5992 int smb2_set_info(struct ksmbd_work *work)
5993 {
5994         struct smb2_set_info_req *req;
5995         struct smb2_set_info_rsp *rsp;
5996         struct ksmbd_file *fp;
5997         int rc = 0;
5998         unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5999
6000         ksmbd_debug(SMB, "Received set info request\n");
6001
6002         if (work->next_smb2_rcv_hdr_off) {
6003                 req = ksmbd_req_buf_next(work);
6004                 rsp = ksmbd_resp_buf_next(work);
6005                 if (!has_file_id(req->VolatileFileId)) {
6006                         ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6007                                     work->compound_fid);
6008                         id = work->compound_fid;
6009                         pid = work->compound_pfid;
6010                 }
6011         } else {
6012                 req = smb2_get_msg(work->request_buf);
6013                 rsp = smb2_get_msg(work->response_buf);
6014         }
6015
6016         if (!has_file_id(id)) {
6017                 id = req->VolatileFileId;
6018                 pid = req->PersistentFileId;
6019         }
6020
6021         fp = ksmbd_lookup_fd_slow(work, id, pid);
6022         if (!fp) {
6023                 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6024                 rc = -ENOENT;
6025                 goto err_out;
6026         }
6027
6028         switch (req->InfoType) {
6029         case SMB2_O_INFO_FILE:
6030                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6031                 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6032                 break;
6033         case SMB2_O_INFO_SECURITY:
6034                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6035                 if (ksmbd_override_fsids(work)) {
6036                         rc = -ENOMEM;
6037                         goto err_out;
6038                 }
6039                 rc = smb2_set_info_sec(fp,
6040                                        le32_to_cpu(req->AdditionalInformation),
6041                                        req->Buffer,
6042                                        le32_to_cpu(req->BufferLength));
6043                 ksmbd_revert_fsids(work);
6044                 break;
6045         default:
6046                 rc = -EOPNOTSUPP;
6047         }
6048
6049         if (rc < 0)
6050                 goto err_out;
6051
6052         rsp->StructureSize = cpu_to_le16(2);
6053         inc_rfc1001_len(work->response_buf, 2);
6054         ksmbd_fd_put(work, fp);
6055         return 0;
6056
6057 err_out:
6058         if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6059                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6060         else if (rc == -EINVAL)
6061                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6062         else if (rc == -ESHARE)
6063                 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6064         else if (rc == -ENOENT)
6065                 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6066         else if (rc == -EBUSY || rc == -ENOTEMPTY)
6067                 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6068         else if (rc == -EAGAIN)
6069                 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6070         else if (rc == -EBADF || rc == -ESTALE)
6071                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6072         else if (rc == -EEXIST)
6073                 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6074         else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6075                 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6076         smb2_set_err_rsp(work);
6077         ksmbd_fd_put(work, fp);
6078         ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6079         return rc;
6080 }
6081
6082 /**
6083  * smb2_read_pipe() - handler for smb2 read from IPC pipe
6084  * @work:       smb work containing read IPC pipe command buffer
6085  *
6086  * Return:      0 on success, otherwise error
6087  */
6088 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6089 {
6090         int nbytes = 0, err;
6091         u64 id;
6092         struct ksmbd_rpc_command *rpc_resp;
6093         struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6094         struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6095
6096         id = req->VolatileFileId;
6097
6098         inc_rfc1001_len(work->response_buf, 16);
6099         rpc_resp = ksmbd_rpc_read(work->sess, id);
6100         if (rpc_resp) {
6101                 if (rpc_resp->flags != KSMBD_RPC_OK) {
6102                         err = -EINVAL;
6103                         goto out;
6104                 }
6105
6106                 work->aux_payload_buf =
6107                         kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6108                 if (!work->aux_payload_buf) {
6109                         err = -ENOMEM;
6110                         goto out;
6111                 }
6112
6113                 memcpy(work->aux_payload_buf, rpc_resp->payload,
6114                        rpc_resp->payload_sz);
6115
6116                 nbytes = rpc_resp->payload_sz;
6117                 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6118                 work->aux_payload_sz = nbytes;
6119                 kvfree(rpc_resp);
6120         }
6121
6122         rsp->StructureSize = cpu_to_le16(17);
6123         rsp->DataOffset = 80;
6124         rsp->Reserved = 0;
6125         rsp->DataLength = cpu_to_le32(nbytes);
6126         rsp->DataRemaining = 0;
6127         rsp->Flags = 0;
6128         inc_rfc1001_len(work->response_buf, nbytes);
6129         return 0;
6130
6131 out:
6132         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6133         smb2_set_err_rsp(work);
6134         kvfree(rpc_resp);
6135         return err;
6136 }
6137
6138 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6139                                         struct smb2_buffer_desc_v1 *desc,
6140                                         __le32 Channel,
6141                                         __le16 ChannelInfoLength)
6142 {
6143         unsigned int i, ch_count;
6144
6145         if (work->conn->dialect == SMB30_PROT_ID &&
6146             Channel != SMB2_CHANNEL_RDMA_V1)
6147                 return -EINVAL;
6148
6149         ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6150         if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6151                 for (i = 0; i < ch_count; i++) {
6152                         pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6153                                 i,
6154                                 le32_to_cpu(desc[i].token),
6155                                 le32_to_cpu(desc[i].length));
6156                 }
6157         }
6158         if (!ch_count)
6159                 return -EINVAL;
6160
6161         work->need_invalidate_rkey =
6162                 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6163         if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6164                 work->remote_key = le32_to_cpu(desc->token);
6165         return 0;
6166 }
6167
6168 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6169                                       struct smb2_read_req *req, void *data_buf,
6170                                       size_t length)
6171 {
6172         int err;
6173
6174         err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6175                                     (struct smb2_buffer_desc_v1 *)
6176                                     ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6177                                     le16_to_cpu(req->ReadChannelInfoLength));
6178         if (err)
6179                 return err;
6180
6181         return length;
6182 }
6183
6184 /**
6185  * smb2_read() - handler for smb2 read from file
6186  * @work:       smb work containing read command buffer
6187  *
6188  * Return:      0 on success, otherwise error
6189  */
6190 int smb2_read(struct ksmbd_work *work)
6191 {
6192         struct ksmbd_conn *conn = work->conn;
6193         struct smb2_read_req *req;
6194         struct smb2_read_rsp *rsp;
6195         struct ksmbd_file *fp = NULL;
6196         loff_t offset;
6197         size_t length, mincount;
6198         ssize_t nbytes = 0, remain_bytes = 0;
6199         int err = 0;
6200         bool is_rdma_channel = false;
6201         unsigned int max_read_size = conn->vals->max_read_size;
6202
6203         WORK_BUFFERS(work, req, rsp);
6204
6205         if (test_share_config_flag(work->tcon->share_conf,
6206                                    KSMBD_SHARE_FLAG_PIPE)) {
6207                 ksmbd_debug(SMB, "IPC pipe read request\n");
6208                 return smb2_read_pipe(work);
6209         }
6210
6211         if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6212             req->Channel == SMB2_CHANNEL_RDMA_V1) {
6213                 is_rdma_channel = true;
6214                 max_read_size = get_smbd_max_read_write_size();
6215         }
6216
6217         if (is_rdma_channel == true) {
6218                 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6219
6220                 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6221                         err = -EINVAL;
6222                         goto out;
6223                 }
6224                 err = smb2_set_remote_key_for_rdma(work,
6225                                                    (struct smb2_buffer_desc_v1 *)
6226                                                    ((char *)req + ch_offset),
6227                                                    req->Channel,
6228                                                    req->ReadChannelInfoLength);
6229                 if (err)
6230                         goto out;
6231         }
6232
6233         fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6234         if (!fp) {
6235                 err = -ENOENT;
6236                 goto out;
6237         }
6238
6239         if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6240                 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6241                 err = -EACCES;
6242                 goto out;
6243         }
6244
6245         offset = le64_to_cpu(req->Offset);
6246         length = le32_to_cpu(req->Length);
6247         mincount = le32_to_cpu(req->MinimumCount);
6248
6249         if (length > max_read_size) {
6250                 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6251                             max_read_size);
6252                 err = -EINVAL;
6253                 goto out;
6254         }
6255
6256         ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6257                     fp->filp->f_path.dentry, offset, length);
6258
6259         work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6260         if (!work->aux_payload_buf) {
6261                 err = -ENOMEM;
6262                 goto out;
6263         }
6264
6265         nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6266         if (nbytes < 0) {
6267                 err = nbytes;
6268                 goto out;
6269         }
6270
6271         if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6272                 kvfree(work->aux_payload_buf);
6273                 work->aux_payload_buf = NULL;
6274                 rsp->hdr.Status = STATUS_END_OF_FILE;
6275                 smb2_set_err_rsp(work);
6276                 ksmbd_fd_put(work, fp);
6277                 return 0;
6278         }
6279
6280         ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6281                     nbytes, offset, mincount);
6282
6283         if (is_rdma_channel == true) {
6284                 /* write data to the client using rdma channel */
6285                 remain_bytes = smb2_read_rdma_channel(work, req,
6286                                                       work->aux_payload_buf,
6287                                                       nbytes);
6288                 kvfree(work->aux_payload_buf);
6289                 work->aux_payload_buf = NULL;
6290
6291                 nbytes = 0;
6292                 if (remain_bytes < 0) {
6293                         err = (int)remain_bytes;
6294                         goto out;
6295                 }
6296         }
6297
6298         rsp->StructureSize = cpu_to_le16(17);
6299         rsp->DataOffset = 80;
6300         rsp->Reserved = 0;
6301         rsp->DataLength = cpu_to_le32(nbytes);
6302         rsp->DataRemaining = cpu_to_le32(remain_bytes);
6303         rsp->Flags = 0;
6304         inc_rfc1001_len(work->response_buf, 16);
6305         work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6306         work->aux_payload_sz = nbytes;
6307         inc_rfc1001_len(work->response_buf, nbytes);
6308         ksmbd_fd_put(work, fp);
6309         return 0;
6310
6311 out:
6312         if (err) {
6313                 if (err == -EISDIR)
6314                         rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6315                 else if (err == -EAGAIN)
6316                         rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6317                 else if (err == -ENOENT)
6318                         rsp->hdr.Status = STATUS_FILE_CLOSED;
6319                 else if (err == -EACCES)
6320                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
6321                 else if (err == -ESHARE)
6322                         rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6323                 else if (err == -EINVAL)
6324                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6325                 else
6326                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
6327
6328                 smb2_set_err_rsp(work);
6329         }
6330         ksmbd_fd_put(work, fp);
6331         return err;
6332 }
6333
6334 /**
6335  * smb2_write_pipe() - handler for smb2 write on IPC pipe
6336  * @work:       smb work containing write IPC pipe command buffer
6337  *
6338  * Return:      0 on success, otherwise error
6339  */
6340 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6341 {
6342         struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6343         struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6344         struct ksmbd_rpc_command *rpc_resp;
6345         u64 id = 0;
6346         int err = 0, ret = 0;
6347         char *data_buf;
6348         size_t length;
6349
6350         length = le32_to_cpu(req->Length);
6351         id = req->VolatileFileId;
6352
6353         if ((u64)le16_to_cpu(req->DataOffset) + length >
6354             get_rfc1002_len(work->request_buf)) {
6355                 pr_err("invalid write data offset %u, smb_len %u\n",
6356                        le16_to_cpu(req->DataOffset),
6357                        get_rfc1002_len(work->request_buf));
6358                 err = -EINVAL;
6359                 goto out;
6360         }
6361
6362         data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6363                            le16_to_cpu(req->DataOffset));
6364
6365         rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6366         if (rpc_resp) {
6367                 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6368                         rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6369                         kvfree(rpc_resp);
6370                         smb2_set_err_rsp(work);
6371                         return -EOPNOTSUPP;
6372                 }
6373                 if (rpc_resp->flags != KSMBD_RPC_OK) {
6374                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
6375                         smb2_set_err_rsp(work);
6376                         kvfree(rpc_resp);
6377                         return ret;
6378                 }
6379                 kvfree(rpc_resp);
6380         }
6381
6382         rsp->StructureSize = cpu_to_le16(17);
6383         rsp->DataOffset = 0;
6384         rsp->Reserved = 0;
6385         rsp->DataLength = cpu_to_le32(length);
6386         rsp->DataRemaining = 0;
6387         rsp->Reserved2 = 0;
6388         inc_rfc1001_len(work->response_buf, 16);
6389         return 0;
6390 out:
6391         if (err) {
6392                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6393                 smb2_set_err_rsp(work);
6394         }
6395
6396         return err;
6397 }
6398
6399 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6400                                        struct smb2_write_req *req,
6401                                        struct ksmbd_file *fp,
6402                                        loff_t offset, size_t length, bool sync)
6403 {
6404         char *data_buf;
6405         int ret;
6406         ssize_t nbytes;
6407
6408         data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6409         if (!data_buf)
6410                 return -ENOMEM;
6411
6412         ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6413                                    (struct smb2_buffer_desc_v1 *)
6414                                    ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6415                                    le16_to_cpu(req->WriteChannelInfoLength));
6416         if (ret < 0) {
6417                 kvfree(data_buf);
6418                 return ret;
6419         }
6420
6421         ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6422         kvfree(data_buf);
6423         if (ret < 0)
6424                 return ret;
6425
6426         return nbytes;
6427 }
6428
6429 /**
6430  * smb2_write() - handler for smb2 write from file
6431  * @work:       smb work containing write command buffer
6432  *
6433  * Return:      0 on success, otherwise error
6434  */
6435 int smb2_write(struct ksmbd_work *work)
6436 {
6437         struct smb2_write_req *req;
6438         struct smb2_write_rsp *rsp;
6439         struct ksmbd_file *fp = NULL;
6440         loff_t offset;
6441         size_t length;
6442         ssize_t nbytes;
6443         char *data_buf;
6444         bool writethrough = false, is_rdma_channel = false;
6445         int err = 0;
6446         unsigned int max_write_size = work->conn->vals->max_write_size;
6447
6448         WORK_BUFFERS(work, req, rsp);
6449
6450         if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6451                 ksmbd_debug(SMB, "IPC pipe write request\n");
6452                 return smb2_write_pipe(work);
6453         }
6454
6455         offset = le64_to_cpu(req->Offset);
6456         length = le32_to_cpu(req->Length);
6457
6458         if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6459             req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6460                 is_rdma_channel = true;
6461                 max_write_size = get_smbd_max_read_write_size();
6462                 length = le32_to_cpu(req->RemainingBytes);
6463         }
6464
6465         if (is_rdma_channel == true) {
6466                 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6467
6468                 if (req->Length != 0 || req->DataOffset != 0 ||
6469                     ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6470                         err = -EINVAL;
6471                         goto out;
6472                 }
6473                 err = smb2_set_remote_key_for_rdma(work,
6474                                                    (struct smb2_buffer_desc_v1 *)
6475                                                    ((char *)req + ch_offset),
6476                                                    req->Channel,
6477                                                    req->WriteChannelInfoLength);
6478                 if (err)
6479                         goto out;
6480         }
6481
6482         if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6483                 ksmbd_debug(SMB, "User does not have write permission\n");
6484                 err = -EACCES;
6485                 goto out;
6486         }
6487
6488         fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6489         if (!fp) {
6490                 err = -ENOENT;
6491                 goto out;
6492         }
6493
6494         if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6495                 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6496                 err = -EACCES;
6497                 goto out;
6498         }
6499
6500         if (length > max_write_size) {
6501                 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6502                             max_write_size);
6503                 err = -EINVAL;
6504                 goto out;
6505         }
6506
6507         ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6508         if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6509                 writethrough = true;
6510
6511         if (is_rdma_channel == false) {
6512                 if ((u64)le16_to_cpu(req->DataOffset) + length >
6513                     get_rfc1002_len(work->request_buf)) {
6514                         pr_err("invalid write data offset %u, smb_len %u\n",
6515                                le16_to_cpu(req->DataOffset),
6516                                get_rfc1002_len(work->request_buf));
6517                         err = -EINVAL;
6518                         goto out;
6519                 }
6520                 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6521                                     le16_to_cpu(req->DataOffset));
6522
6523                 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6524                             fp->filp->f_path.dentry, offset, length);
6525                 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6526                                       writethrough, &nbytes);
6527                 if (err < 0)
6528                         goto out;
6529         } else {
6530                 /* read data from the client using rdma channel, and
6531                  * write the data.
6532                  */
6533                 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6534                                                  writethrough);
6535                 if (nbytes < 0) {
6536                         err = (int)nbytes;
6537                         goto out;
6538                 }
6539         }
6540
6541         rsp->StructureSize = cpu_to_le16(17);
6542         rsp->DataOffset = 0;
6543         rsp->Reserved = 0;
6544         rsp->DataLength = cpu_to_le32(nbytes);
6545         rsp->DataRemaining = 0;
6546         rsp->Reserved2 = 0;
6547         inc_rfc1001_len(work->response_buf, 16);
6548         ksmbd_fd_put(work, fp);
6549         return 0;
6550
6551 out:
6552         if (err == -EAGAIN)
6553                 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6554         else if (err == -ENOSPC || err == -EFBIG)
6555                 rsp->hdr.Status = STATUS_DISK_FULL;
6556         else if (err == -ENOENT)
6557                 rsp->hdr.Status = STATUS_FILE_CLOSED;
6558         else if (err == -EACCES)
6559                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6560         else if (err == -ESHARE)
6561                 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6562         else if (err == -EINVAL)
6563                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6564         else
6565                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6566
6567         smb2_set_err_rsp(work);
6568         ksmbd_fd_put(work, fp);
6569         return err;
6570 }
6571
6572 /**
6573  * smb2_flush() - handler for smb2 flush file - fsync
6574  * @work:       smb work containing flush command buffer
6575  *
6576  * Return:      0 on success, otherwise error
6577  */
6578 int smb2_flush(struct ksmbd_work *work)
6579 {
6580         struct smb2_flush_req *req;
6581         struct smb2_flush_rsp *rsp;
6582         int err;
6583
6584         WORK_BUFFERS(work, req, rsp);
6585
6586         ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6587
6588         err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6589         if (err)
6590                 goto out;
6591
6592         rsp->StructureSize = cpu_to_le16(4);
6593         rsp->Reserved = 0;
6594         inc_rfc1001_len(work->response_buf, 4);
6595         return 0;
6596
6597 out:
6598         if (err) {
6599                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6600                 smb2_set_err_rsp(work);
6601         }
6602
6603         return err;
6604 }
6605
6606 /**
6607  * smb2_cancel() - handler for smb2 cancel command
6608  * @work:       smb work containing cancel command buffer
6609  *
6610  * Return:      0 on success, otherwise error
6611  */
6612 int smb2_cancel(struct ksmbd_work *work)
6613 {
6614         struct ksmbd_conn *conn = work->conn;
6615         struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6616         struct smb2_hdr *chdr;
6617         struct ksmbd_work *cancel_work = NULL, *iter;
6618         struct list_head *command_list;
6619
6620         ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6621                     hdr->MessageId, hdr->Flags);
6622
6623         if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6624                 command_list = &conn->async_requests;
6625
6626                 spin_lock(&conn->request_lock);
6627                 list_for_each_entry(iter, command_list,
6628                                     async_request_entry) {
6629                         chdr = smb2_get_msg(iter->request_buf);
6630
6631                         if (iter->async_id !=
6632                             le64_to_cpu(hdr->Id.AsyncId))
6633                                 continue;
6634
6635                         ksmbd_debug(SMB,
6636                                     "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6637                                     le64_to_cpu(hdr->Id.AsyncId),
6638                                     le16_to_cpu(chdr->Command));
6639                         cancel_work = iter;
6640                         break;
6641                 }
6642                 spin_unlock(&conn->request_lock);
6643         } else {
6644                 command_list = &conn->requests;
6645
6646                 spin_lock(&conn->request_lock);
6647                 list_for_each_entry(iter, command_list, request_entry) {
6648                         chdr = smb2_get_msg(iter->request_buf);
6649
6650                         if (chdr->MessageId != hdr->MessageId ||
6651                             iter == work)
6652                                 continue;
6653
6654                         ksmbd_debug(SMB,
6655                                     "smb2 with mid %llu cancelled command = 0x%x\n",
6656                                     le64_to_cpu(hdr->MessageId),
6657                                     le16_to_cpu(chdr->Command));
6658                         cancel_work = iter;
6659                         break;
6660                 }
6661                 spin_unlock(&conn->request_lock);
6662         }
6663
6664         if (cancel_work) {
6665                 cancel_work->state = KSMBD_WORK_CANCELLED;
6666                 if (cancel_work->cancel_fn)
6667                         cancel_work->cancel_fn(cancel_work->cancel_argv);
6668         }
6669
6670         /* For SMB2_CANCEL command itself send no response*/
6671         work->send_no_response = 1;
6672         return 0;
6673 }
6674
6675 struct file_lock *smb_flock_init(struct file *f)
6676 {
6677         struct file_lock *fl;
6678
6679         fl = locks_alloc_lock();
6680         if (!fl)
6681                 goto out;
6682
6683         locks_init_lock(fl);
6684
6685         fl->fl_owner = f;
6686         fl->fl_pid = current->tgid;
6687         fl->fl_file = f;
6688         fl->fl_flags = FL_POSIX;
6689         fl->fl_ops = NULL;
6690         fl->fl_lmops = NULL;
6691
6692 out:
6693         return fl;
6694 }
6695
6696 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6697 {
6698         int cmd = -EINVAL;
6699
6700         /* Checking for wrong flag combination during lock request*/
6701         switch (flags) {
6702         case SMB2_LOCKFLAG_SHARED:
6703                 ksmbd_debug(SMB, "received shared request\n");
6704                 cmd = F_SETLKW;
6705                 flock->fl_type = F_RDLCK;
6706                 flock->fl_flags |= FL_SLEEP;
6707                 break;
6708         case SMB2_LOCKFLAG_EXCLUSIVE:
6709                 ksmbd_debug(SMB, "received exclusive request\n");
6710                 cmd = F_SETLKW;
6711                 flock->fl_type = F_WRLCK;
6712                 flock->fl_flags |= FL_SLEEP;
6713                 break;
6714         case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6715                 ksmbd_debug(SMB,
6716                             "received shared & fail immediately request\n");
6717                 cmd = F_SETLK;
6718                 flock->fl_type = F_RDLCK;
6719                 break;
6720         case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6721                 ksmbd_debug(SMB,
6722                             "received exclusive & fail immediately request\n");
6723                 cmd = F_SETLK;
6724                 flock->fl_type = F_WRLCK;
6725                 break;
6726         case SMB2_LOCKFLAG_UNLOCK:
6727                 ksmbd_debug(SMB, "received unlock request\n");
6728                 flock->fl_type = F_UNLCK;
6729                 cmd = 0;
6730                 break;
6731         }
6732
6733         return cmd;
6734 }
6735
6736 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6737                                          unsigned int cmd, int flags,
6738                                          struct list_head *lock_list)
6739 {
6740         struct ksmbd_lock *lock;
6741
6742         lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6743         if (!lock)
6744                 return NULL;
6745
6746         lock->cmd = cmd;
6747         lock->fl = flock;
6748         lock->start = flock->fl_start;
6749         lock->end = flock->fl_end;
6750         lock->flags = flags;
6751         if (lock->start == lock->end)
6752                 lock->zero_len = 1;
6753         INIT_LIST_HEAD(&lock->clist);
6754         INIT_LIST_HEAD(&lock->flist);
6755         INIT_LIST_HEAD(&lock->llist);
6756         list_add_tail(&lock->llist, lock_list);
6757
6758         return lock;
6759 }
6760
6761 static void smb2_remove_blocked_lock(void **argv)
6762 {
6763         struct file_lock *flock = (struct file_lock *)argv[0];
6764
6765         ksmbd_vfs_posix_lock_unblock(flock);
6766         wake_up(&flock->fl_wait);
6767 }
6768
6769 static inline bool lock_defer_pending(struct file_lock *fl)
6770 {
6771         /* check pending lock waiters */
6772         return waitqueue_active(&fl->fl_wait);
6773 }
6774
6775 /**
6776  * smb2_lock() - handler for smb2 file lock command
6777  * @work:       smb work containing lock command buffer
6778  *
6779  * Return:      0 on success, otherwise error
6780  */
6781 int smb2_lock(struct ksmbd_work *work)
6782 {
6783         struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6784         struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6785         struct smb2_lock_element *lock_ele;
6786         struct ksmbd_file *fp = NULL;
6787         struct file_lock *flock = NULL;
6788         struct file *filp = NULL;
6789         int lock_count;
6790         int flags = 0;
6791         int cmd = 0;
6792         int err = -EIO, i, rc = 0;
6793         u64 lock_start, lock_length;
6794         struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6795         struct ksmbd_conn *conn;
6796         int nolock = 0;
6797         LIST_HEAD(lock_list);
6798         LIST_HEAD(rollback_list);
6799         int prior_lock = 0;
6800
6801         ksmbd_debug(SMB, "Received lock request\n");
6802         fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6803         if (!fp) {
6804                 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6805                 err = -ENOENT;
6806                 goto out2;
6807         }
6808
6809         filp = fp->filp;
6810         lock_count = le16_to_cpu(req->LockCount);
6811         lock_ele = req->locks;
6812
6813         ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6814         if (!lock_count) {
6815                 err = -EINVAL;
6816                 goto out2;
6817         }
6818
6819         for (i = 0; i < lock_count; i++) {
6820                 flags = le32_to_cpu(lock_ele[i].Flags);
6821
6822                 flock = smb_flock_init(filp);
6823                 if (!flock)
6824                         goto out;
6825
6826                 cmd = smb2_set_flock_flags(flock, flags);
6827
6828                 lock_start = le64_to_cpu(lock_ele[i].Offset);
6829                 lock_length = le64_to_cpu(lock_ele[i].Length);
6830                 if (lock_start > U64_MAX - lock_length) {
6831                         pr_err("Invalid lock range requested\n");
6832                         rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6833                         goto out;
6834                 }
6835
6836                 if (lock_start > OFFSET_MAX)
6837                         flock->fl_start = OFFSET_MAX;
6838                 else
6839                         flock->fl_start = lock_start;
6840
6841                 lock_length = le64_to_cpu(lock_ele[i].Length);
6842                 if (lock_length > OFFSET_MAX - flock->fl_start)
6843                         lock_length = OFFSET_MAX - flock->fl_start;
6844
6845                 flock->fl_end = flock->fl_start + lock_length;
6846
6847                 if (flock->fl_end < flock->fl_start) {
6848                         ksmbd_debug(SMB,
6849                                     "the end offset(%llx) is smaller than the start offset(%llx)\n",
6850                                     flock->fl_end, flock->fl_start);
6851                         rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6852                         goto out;
6853                 }
6854
6855                 /* Check conflict locks in one request */
6856                 list_for_each_entry(cmp_lock, &lock_list, llist) {
6857                         if (cmp_lock->fl->fl_start <= flock->fl_start &&
6858                             cmp_lock->fl->fl_end >= flock->fl_end) {
6859                                 if (cmp_lock->fl->fl_type != F_UNLCK &&
6860                                     flock->fl_type != F_UNLCK) {
6861                                         pr_err("conflict two locks in one request\n");
6862                                         err = -EINVAL;
6863                                         goto out;
6864                                 }
6865                         }
6866                 }
6867
6868                 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6869                 if (!smb_lock) {
6870                         err = -EINVAL;
6871                         goto out;
6872                 }
6873         }
6874
6875         list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6876                 if (smb_lock->cmd < 0) {
6877                         err = -EINVAL;
6878                         goto out;
6879                 }
6880
6881                 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6882                         err = -EINVAL;
6883                         goto out;
6884                 }
6885
6886                 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6887                      smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6888                     (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6889                      !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6890                         err = -EINVAL;
6891                         goto out;
6892                 }
6893
6894                 prior_lock = smb_lock->flags;
6895
6896                 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6897                     !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6898                         goto no_check_cl;
6899
6900                 nolock = 1;
6901                 /* check locks in connection list */
6902                 read_lock(&conn_list_lock);
6903                 list_for_each_entry(conn, &conn_list, conns_list) {
6904                         spin_lock(&conn->llist_lock);
6905                         list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6906                                 if (file_inode(cmp_lock->fl->fl_file) !=
6907                                     file_inode(smb_lock->fl->fl_file))
6908                                         continue;
6909
6910                                 if (smb_lock->fl->fl_type == F_UNLCK) {
6911                                         if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6912                                             cmp_lock->start == smb_lock->start &&
6913                                             cmp_lock->end == smb_lock->end &&
6914                                             !lock_defer_pending(cmp_lock->fl)) {
6915                                                 nolock = 0;
6916                                                 list_del(&cmp_lock->flist);
6917                                                 list_del(&cmp_lock->clist);
6918                                                 spin_unlock(&conn->llist_lock);
6919                                                 read_unlock(&conn_list_lock);
6920
6921                                                 locks_free_lock(cmp_lock->fl);
6922                                                 kfree(cmp_lock);
6923                                                 goto out_check_cl;
6924                                         }
6925                                         continue;
6926                                 }
6927
6928                                 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6929                                         if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6930                                                 continue;
6931                                 } else {
6932                                         if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6933                                                 continue;
6934                                 }
6935
6936                                 /* check zero byte lock range */
6937                                 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6938                                     cmp_lock->start > smb_lock->start &&
6939                                     cmp_lock->start < smb_lock->end) {
6940                                         spin_unlock(&conn->llist_lock);
6941                                         read_unlock(&conn_list_lock);
6942                                         pr_err("previous lock conflict with zero byte lock range\n");
6943                                         goto out;
6944                                 }
6945
6946                                 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6947                                     smb_lock->start > cmp_lock->start &&
6948                                     smb_lock->start < cmp_lock->end) {
6949                                         spin_unlock(&conn->llist_lock);
6950                                         read_unlock(&conn_list_lock);
6951                                         pr_err("current lock conflict with zero byte lock range\n");
6952                                         goto out;
6953                                 }
6954
6955                                 if (((cmp_lock->start <= smb_lock->start &&
6956                                       cmp_lock->end > smb_lock->start) ||
6957                                      (cmp_lock->start < smb_lock->end &&
6958                                       cmp_lock->end >= smb_lock->end)) &&
6959                                     !cmp_lock->zero_len && !smb_lock->zero_len) {
6960                                         spin_unlock(&conn->llist_lock);
6961                                         read_unlock(&conn_list_lock);
6962                                         pr_err("Not allow lock operation on exclusive lock range\n");
6963                                         goto out;
6964                                 }
6965                         }
6966                         spin_unlock(&conn->llist_lock);
6967                 }
6968                 read_unlock(&conn_list_lock);
6969 out_check_cl:
6970                 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6971                         pr_err("Try to unlock nolocked range\n");
6972                         rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6973                         goto out;
6974                 }
6975
6976 no_check_cl:
6977                 if (smb_lock->zero_len) {
6978                         err = 0;
6979                         goto skip;
6980                 }
6981
6982                 flock = smb_lock->fl;
6983                 list_del(&smb_lock->llist);
6984 retry:
6985                 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6986 skip:
6987                 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6988                         if (!rc) {
6989                                 ksmbd_debug(SMB, "File unlocked\n");
6990                         } else if (rc == -ENOENT) {
6991                                 rsp->hdr.Status = STATUS_NOT_LOCKED;
6992                                 goto out;
6993                         }
6994                         locks_free_lock(flock);
6995                         kfree(smb_lock);
6996                 } else {
6997                         if (rc == FILE_LOCK_DEFERRED) {
6998                                 void **argv;
6999
7000                                 ksmbd_debug(SMB,
7001                                             "would have to wait for getting lock\n");
7002                                 spin_lock(&work->conn->llist_lock);
7003                                 list_add_tail(&smb_lock->clist,
7004                                               &work->conn->lock_list);
7005                                 spin_unlock(&work->conn->llist_lock);
7006                                 list_add(&smb_lock->llist, &rollback_list);
7007
7008                                 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7009                                 if (!argv) {
7010                                         err = -ENOMEM;
7011                                         goto out;
7012                                 }
7013                                 argv[0] = flock;
7014
7015                                 rc = setup_async_work(work,
7016                                                       smb2_remove_blocked_lock,
7017                                                       argv);
7018                                 if (rc) {
7019                                         err = -ENOMEM;
7020                                         goto out;
7021                                 }
7022                                 spin_lock(&fp->f_lock);
7023                                 list_add(&work->fp_entry, &fp->blocked_works);
7024                                 spin_unlock(&fp->f_lock);
7025
7026                                 smb2_send_interim_resp(work, STATUS_PENDING);
7027
7028                                 ksmbd_vfs_posix_lock_wait(flock);
7029
7030                                 if (work->state != KSMBD_WORK_ACTIVE) {
7031                                         list_del(&smb_lock->llist);
7032                                         spin_lock(&work->conn->llist_lock);
7033                                         list_del(&smb_lock->clist);
7034                                         spin_unlock(&work->conn->llist_lock);
7035                                         locks_free_lock(flock);
7036
7037                                         if (work->state == KSMBD_WORK_CANCELLED) {
7038                                                 spin_lock(&fp->f_lock);
7039                                                 list_del(&work->fp_entry);
7040                                                 spin_unlock(&fp->f_lock);
7041                                                 rsp->hdr.Status =
7042                                                         STATUS_CANCELLED;
7043                                                 kfree(smb_lock);
7044                                                 smb2_send_interim_resp(work,
7045                                                                        STATUS_CANCELLED);
7046                                                 work->send_no_response = 1;
7047                                                 goto out;
7048                                         }
7049                                         init_smb2_rsp_hdr(work);
7050                                         smb2_set_err_rsp(work);
7051                                         rsp->hdr.Status =
7052                                                 STATUS_RANGE_NOT_LOCKED;
7053                                         kfree(smb_lock);
7054                                         goto out2;
7055                                 }
7056
7057                                 list_del(&smb_lock->llist);
7058                                 spin_lock(&work->conn->llist_lock);
7059                                 list_del(&smb_lock->clist);
7060                                 spin_unlock(&work->conn->llist_lock);
7061
7062                                 spin_lock(&fp->f_lock);
7063                                 list_del(&work->fp_entry);
7064                                 spin_unlock(&fp->f_lock);
7065                                 goto retry;
7066                         } else if (!rc) {
7067                                 spin_lock(&work->conn->llist_lock);
7068                                 list_add_tail(&smb_lock->clist,
7069                                               &work->conn->lock_list);
7070                                 list_add_tail(&smb_lock->flist,
7071                                               &fp->lock_list);
7072                                 spin_unlock(&work->conn->llist_lock);
7073                                 list_add(&smb_lock->llist, &rollback_list);
7074                                 ksmbd_debug(SMB, "successful in taking lock\n");
7075                         } else {
7076                                 goto out;
7077                         }
7078                 }
7079         }
7080
7081         if (atomic_read(&fp->f_ci->op_count) > 1)
7082                 smb_break_all_oplock(work, fp);
7083
7084         rsp->StructureSize = cpu_to_le16(4);
7085         ksmbd_debug(SMB, "successful in taking lock\n");
7086         rsp->hdr.Status = STATUS_SUCCESS;
7087         rsp->Reserved = 0;
7088         inc_rfc1001_len(work->response_buf, 4);
7089         ksmbd_fd_put(work, fp);
7090         return 0;
7091
7092 out:
7093         list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7094                 locks_free_lock(smb_lock->fl);
7095                 list_del(&smb_lock->llist);
7096                 kfree(smb_lock);
7097         }
7098
7099         list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7100                 struct file_lock *rlock = NULL;
7101
7102                 rlock = smb_flock_init(filp);
7103                 rlock->fl_type = F_UNLCK;
7104                 rlock->fl_start = smb_lock->start;
7105                 rlock->fl_end = smb_lock->end;
7106
7107                 rc = vfs_lock_file(filp, 0, rlock, NULL);
7108                 if (rc)
7109                         pr_err("rollback unlock fail : %d\n", rc);
7110
7111                 list_del(&smb_lock->llist);
7112                 spin_lock(&work->conn->llist_lock);
7113                 if (!list_empty(&smb_lock->flist))
7114                         list_del(&smb_lock->flist);
7115                 list_del(&smb_lock->clist);
7116                 spin_unlock(&work->conn->llist_lock);
7117
7118                 locks_free_lock(smb_lock->fl);
7119                 locks_free_lock(rlock);
7120                 kfree(smb_lock);
7121         }
7122 out2:
7123         ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7124
7125         if (!rsp->hdr.Status) {
7126                 if (err == -EINVAL)
7127                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7128                 else if (err == -ENOMEM)
7129                         rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7130                 else if (err == -ENOENT)
7131                         rsp->hdr.Status = STATUS_FILE_CLOSED;
7132                 else
7133                         rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7134         }
7135
7136         smb2_set_err_rsp(work);
7137         ksmbd_fd_put(work, fp);
7138         return err;
7139 }
7140
7141 static int fsctl_copychunk(struct ksmbd_work *work,
7142                            struct copychunk_ioctl_req *ci_req,
7143                            unsigned int cnt_code,
7144                            unsigned int input_count,
7145                            unsigned long long volatile_id,
7146                            unsigned long long persistent_id,
7147                            struct smb2_ioctl_rsp *rsp)
7148 {
7149         struct copychunk_ioctl_rsp *ci_rsp;
7150         struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7151         struct srv_copychunk *chunks;
7152         unsigned int i, chunk_count, chunk_count_written = 0;
7153         unsigned int chunk_size_written = 0;
7154         loff_t total_size_written = 0;
7155         int ret = 0;
7156
7157         ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7158
7159         rsp->VolatileFileId = volatile_id;
7160         rsp->PersistentFileId = persistent_id;
7161         ci_rsp->ChunksWritten =
7162                 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7163         ci_rsp->ChunkBytesWritten =
7164                 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7165         ci_rsp->TotalBytesWritten =
7166                 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7167
7168         chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7169         chunk_count = le32_to_cpu(ci_req->ChunkCount);
7170         if (chunk_count == 0)
7171                 goto out;
7172         total_size_written = 0;
7173
7174         /* verify the SRV_COPYCHUNK_COPY packet */
7175         if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7176             input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7177              chunk_count * sizeof(struct srv_copychunk)) {
7178                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7179                 return -EINVAL;
7180         }
7181
7182         for (i = 0; i < chunk_count; i++) {
7183                 if (le32_to_cpu(chunks[i].Length) == 0 ||
7184                     le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7185                         break;
7186                 total_size_written += le32_to_cpu(chunks[i].Length);
7187         }
7188
7189         if (i < chunk_count ||
7190             total_size_written > ksmbd_server_side_copy_max_total_size()) {
7191                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7192                 return -EINVAL;
7193         }
7194
7195         src_fp = ksmbd_lookup_foreign_fd(work,
7196                                          le64_to_cpu(ci_req->ResumeKey[0]));
7197         dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7198         ret = -EINVAL;
7199         if (!src_fp ||
7200             src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7201                 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7202                 goto out;
7203         }
7204
7205         if (!dst_fp) {
7206                 rsp->hdr.Status = STATUS_FILE_CLOSED;
7207                 goto out;
7208         }
7209
7210         /*
7211          * FILE_READ_DATA should only be included in
7212          * the FSCTL_COPYCHUNK case
7213          */
7214         if (cnt_code == FSCTL_COPYCHUNK &&
7215             !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7216                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7217                 goto out;
7218         }
7219
7220         ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7221                                          chunks, chunk_count,
7222                                          &chunk_count_written,
7223                                          &chunk_size_written,
7224                                          &total_size_written);
7225         if (ret < 0) {
7226                 if (ret == -EACCES)
7227                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
7228                 if (ret == -EAGAIN)
7229                         rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7230                 else if (ret == -EBADF)
7231                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
7232                 else if (ret == -EFBIG || ret == -ENOSPC)
7233                         rsp->hdr.Status = STATUS_DISK_FULL;
7234                 else if (ret == -EINVAL)
7235                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7236                 else if (ret == -EISDIR)
7237                         rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7238                 else if (ret == -E2BIG)
7239                         rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7240                 else
7241                         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7242         }
7243
7244         ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7245         ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7246         ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7247 out:
7248         ksmbd_fd_put(work, src_fp);
7249         ksmbd_fd_put(work, dst_fp);
7250         return ret;
7251 }
7252
7253 static __be32 idev_ipv4_address(struct in_device *idev)
7254 {
7255         __be32 addr = 0;
7256
7257         struct in_ifaddr *ifa;
7258
7259         rcu_read_lock();
7260         in_dev_for_each_ifa_rcu(ifa, idev) {
7261                 if (ifa->ifa_flags & IFA_F_SECONDARY)
7262                         continue;
7263
7264                 addr = ifa->ifa_address;
7265                 break;
7266         }
7267         rcu_read_unlock();
7268         return addr;
7269 }
7270
7271 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7272                                         struct smb2_ioctl_rsp *rsp,
7273                                         unsigned int out_buf_len)
7274 {
7275         struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7276         int nbytes = 0;
7277         struct net_device *netdev;
7278         struct sockaddr_storage_rsp *sockaddr_storage;
7279         unsigned int flags;
7280         unsigned long long speed;
7281
7282         rtnl_lock();
7283         for_each_netdev(&init_net, netdev) {
7284                 bool ipv4_set = false;
7285
7286                 if (netdev->type == ARPHRD_LOOPBACK)
7287                         continue;
7288
7289                 flags = dev_get_flags(netdev);
7290                 if (!(flags & IFF_RUNNING))
7291                         continue;
7292 ipv6_retry:
7293                 if (out_buf_len <
7294                     nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7295                         rtnl_unlock();
7296                         return -ENOSPC;
7297                 }
7298
7299                 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7300                                 &rsp->Buffer[nbytes];
7301                 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7302
7303                 nii_rsp->Capability = 0;
7304                 if (netdev->real_num_tx_queues > 1)
7305                         nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7306                 if (ksmbd_rdma_capable_netdev(netdev))
7307                         nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7308
7309                 nii_rsp->Next = cpu_to_le32(152);
7310                 nii_rsp->Reserved = 0;
7311
7312                 if (netdev->ethtool_ops->get_link_ksettings) {
7313                         struct ethtool_link_ksettings cmd;
7314
7315                         netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7316                         speed = cmd.base.speed;
7317                 } else {
7318                         ksmbd_debug(SMB, "%s %s\n", netdev->name,
7319                                     "speed is unknown, defaulting to 1Gb/sec");
7320                         speed = SPEED_1000;
7321                 }
7322
7323                 speed *= 1000000;
7324                 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7325
7326                 sockaddr_storage = (struct sockaddr_storage_rsp *)
7327                                         nii_rsp->SockAddr_Storage;
7328                 memset(sockaddr_storage, 0, 128);
7329
7330                 if (!ipv4_set) {
7331                         struct in_device *idev;
7332
7333                         sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7334                         sockaddr_storage->addr4.Port = 0;
7335
7336                         idev = __in_dev_get_rtnl(netdev);
7337                         if (!idev)
7338                                 continue;
7339                         sockaddr_storage->addr4.IPv4address =
7340                                                 idev_ipv4_address(idev);
7341                         nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7342                         ipv4_set = true;
7343                         goto ipv6_retry;
7344                 } else {
7345                         struct inet6_dev *idev6;
7346                         struct inet6_ifaddr *ifa;
7347                         __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7348
7349                         sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7350                         sockaddr_storage->addr6.Port = 0;
7351                         sockaddr_storage->addr6.FlowInfo = 0;
7352
7353                         idev6 = __in6_dev_get(netdev);
7354                         if (!idev6)
7355                                 continue;
7356
7357                         list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7358                                 if (ifa->flags & (IFA_F_TENTATIVE |
7359                                                         IFA_F_DEPRECATED))
7360                                         continue;
7361                                 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7362                                 break;
7363                         }
7364                         sockaddr_storage->addr6.ScopeId = 0;
7365                         nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7366                 }
7367         }
7368         rtnl_unlock();
7369
7370         /* zero if this is last one */
7371         if (nii_rsp)
7372                 nii_rsp->Next = 0;
7373
7374         rsp->PersistentFileId = SMB2_NO_FID;
7375         rsp->VolatileFileId = SMB2_NO_FID;
7376         return nbytes;
7377 }
7378
7379 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7380                                          struct validate_negotiate_info_req *neg_req,
7381                                          struct validate_negotiate_info_rsp *neg_rsp,
7382                                          unsigned int in_buf_len)
7383 {
7384         int ret = 0;
7385         int dialect;
7386
7387         if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7388                         le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7389                 return -EINVAL;
7390
7391         dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7392                                              neg_req->DialectCount);
7393         if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7394                 ret = -EINVAL;
7395                 goto err_out;
7396         }
7397
7398         if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7399                 ret = -EINVAL;
7400                 goto err_out;
7401         }
7402
7403         if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7404                 ret = -EINVAL;
7405                 goto err_out;
7406         }
7407
7408         if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7409                 ret = -EINVAL;
7410                 goto err_out;
7411         }
7412
7413         neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7414         memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7415         neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7416         neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7417 err_out:
7418         return ret;
7419 }
7420
7421 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7422                                         struct file_allocated_range_buffer *qar_req,
7423                                         struct file_allocated_range_buffer *qar_rsp,
7424                                         unsigned int in_count, unsigned int *out_count)
7425 {
7426         struct ksmbd_file *fp;
7427         loff_t start, length;
7428         int ret = 0;
7429
7430         *out_count = 0;
7431         if (in_count == 0)
7432                 return -EINVAL;
7433
7434         fp = ksmbd_lookup_fd_fast(work, id);
7435         if (!fp)
7436                 return -ENOENT;
7437
7438         start = le64_to_cpu(qar_req->file_offset);
7439         length = le64_to_cpu(qar_req->length);
7440
7441         ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7442                                    qar_rsp, in_count, out_count);
7443         if (ret && ret != -E2BIG)
7444                 *out_count = 0;
7445
7446         ksmbd_fd_put(work, fp);
7447         return ret;
7448 }
7449
7450 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7451                                  unsigned int out_buf_len,
7452                                  struct smb2_ioctl_req *req,
7453                                  struct smb2_ioctl_rsp *rsp)
7454 {
7455         struct ksmbd_rpc_command *rpc_resp;
7456         char *data_buf = (char *)&req->Buffer[0];
7457         int nbytes = 0;
7458
7459         rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7460                                    le32_to_cpu(req->InputCount));
7461         if (rpc_resp) {
7462                 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7463                         /*
7464                          * set STATUS_SOME_NOT_MAPPED response
7465                          * for unknown domain sid.
7466                          */
7467                         rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7468                 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7469                         rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7470                         goto out;
7471                 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7472                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7473                         goto out;
7474                 }
7475
7476                 nbytes = rpc_resp->payload_sz;
7477                 if (rpc_resp->payload_sz > out_buf_len) {
7478                         rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7479                         nbytes = out_buf_len;
7480                 }
7481
7482                 if (!rpc_resp->payload_sz) {
7483                         rsp->hdr.Status =
7484                                 STATUS_UNEXPECTED_IO_ERROR;
7485                         goto out;
7486                 }
7487
7488                 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7489         }
7490 out:
7491         kvfree(rpc_resp);
7492         return nbytes;
7493 }
7494
7495 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7496                                    struct file_sparse *sparse)
7497 {
7498         struct ksmbd_file *fp;
7499         struct user_namespace *user_ns;
7500         int ret = 0;
7501         __le32 old_fattr;
7502
7503         fp = ksmbd_lookup_fd_fast(work, id);
7504         if (!fp)
7505                 return -ENOENT;
7506         user_ns = file_mnt_user_ns(fp->filp);
7507
7508         old_fattr = fp->f_ci->m_fattr;
7509         if (sparse->SetSparse)
7510                 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7511         else
7512                 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7513
7514         if (fp->f_ci->m_fattr != old_fattr &&
7515             test_share_config_flag(work->tcon->share_conf,
7516                                    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7517                 struct xattr_dos_attrib da;
7518
7519                 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7520                                                      fp->filp->f_path.dentry, &da);
7521                 if (ret <= 0)
7522                         goto out;
7523
7524                 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7525                 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7526                                                      fp->filp->f_path.dentry, &da);
7527                 if (ret)
7528                         fp->f_ci->m_fattr = old_fattr;
7529         }
7530
7531 out:
7532         ksmbd_fd_put(work, fp);
7533         return ret;
7534 }
7535
7536 static int fsctl_request_resume_key(struct ksmbd_work *work,
7537                                     struct smb2_ioctl_req *req,
7538                                     struct resume_key_ioctl_rsp *key_rsp)
7539 {
7540         struct ksmbd_file *fp;
7541
7542         fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7543         if (!fp)
7544                 return -ENOENT;
7545
7546         memset(key_rsp, 0, sizeof(*key_rsp));
7547         key_rsp->ResumeKey[0] = req->VolatileFileId;
7548         key_rsp->ResumeKey[1] = req->PersistentFileId;
7549         ksmbd_fd_put(work, fp);
7550
7551         return 0;
7552 }
7553
7554 /**
7555  * smb2_ioctl() - handler for smb2 ioctl command
7556  * @work:       smb work containing ioctl command buffer
7557  *
7558  * Return:      0 on success, otherwise error
7559  */
7560 int smb2_ioctl(struct ksmbd_work *work)
7561 {
7562         struct smb2_ioctl_req *req;
7563         struct smb2_ioctl_rsp *rsp;
7564         unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7565         u64 id = KSMBD_NO_FID;
7566         struct ksmbd_conn *conn = work->conn;
7567         int ret = 0;
7568
7569         if (work->next_smb2_rcv_hdr_off) {
7570                 req = ksmbd_req_buf_next(work);
7571                 rsp = ksmbd_resp_buf_next(work);
7572                 if (!has_file_id(req->VolatileFileId)) {
7573                         ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7574                                     work->compound_fid);
7575                         id = work->compound_fid;
7576                 }
7577         } else {
7578                 req = smb2_get_msg(work->request_buf);
7579                 rsp = smb2_get_msg(work->response_buf);
7580         }
7581
7582         if (!has_file_id(id))
7583                 id = req->VolatileFileId;
7584
7585         if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7586                 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7587                 goto out;
7588         }
7589
7590         cnt_code = le32_to_cpu(req->CtlCode);
7591         ret = smb2_calc_max_out_buf_len(work, 48,
7592                                         le32_to_cpu(req->MaxOutputResponse));
7593         if (ret < 0) {
7594                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7595                 goto out;
7596         }
7597         out_buf_len = (unsigned int)ret;
7598         in_buf_len = le32_to_cpu(req->InputCount);
7599
7600         switch (cnt_code) {
7601         case FSCTL_DFS_GET_REFERRALS:
7602         case FSCTL_DFS_GET_REFERRALS_EX:
7603                 /* Not support DFS yet */
7604                 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7605                 goto out;
7606         case FSCTL_CREATE_OR_GET_OBJECT_ID:
7607         {
7608                 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7609
7610                 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7611                 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7612                         &rsp->Buffer[0];
7613
7614                 /*
7615                  * TODO: This is dummy implementation to pass smbtorture
7616                  * Need to check correct response later
7617                  */
7618                 memset(obj_buf->ObjectId, 0x0, 16);
7619                 memset(obj_buf->BirthVolumeId, 0x0, 16);
7620                 memset(obj_buf->BirthObjectId, 0x0, 16);
7621                 memset(obj_buf->DomainId, 0x0, 16);
7622
7623                 break;
7624         }
7625         case FSCTL_PIPE_TRANSCEIVE:
7626                 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7627                 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7628                 break;
7629         case FSCTL_VALIDATE_NEGOTIATE_INFO:
7630                 if (conn->dialect < SMB30_PROT_ID) {
7631                         ret = -EOPNOTSUPP;
7632                         goto out;
7633                 }
7634
7635                 if (in_buf_len < sizeof(struct validate_negotiate_info_req))
7636                         return -EINVAL;
7637
7638                 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp))
7639                         return -EINVAL;
7640
7641                 ret = fsctl_validate_negotiate_info(conn,
7642                         (struct validate_negotiate_info_req *)&req->Buffer[0],
7643                         (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7644                         in_buf_len);
7645                 if (ret < 0)
7646                         goto out;
7647
7648                 nbytes = sizeof(struct validate_negotiate_info_rsp);
7649                 rsp->PersistentFileId = SMB2_NO_FID;
7650                 rsp->VolatileFileId = SMB2_NO_FID;
7651                 break;
7652         case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7653                 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7654                 if (ret < 0)
7655                         goto out;
7656                 nbytes = ret;
7657                 break;
7658         case FSCTL_REQUEST_RESUME_KEY:
7659                 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7660                         ret = -EINVAL;
7661                         goto out;
7662                 }
7663
7664                 ret = fsctl_request_resume_key(work, req,
7665                                                (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7666                 if (ret < 0)
7667                         goto out;
7668                 rsp->PersistentFileId = req->PersistentFileId;
7669                 rsp->VolatileFileId = req->VolatileFileId;
7670                 nbytes = sizeof(struct resume_key_ioctl_rsp);
7671                 break;
7672         case FSCTL_COPYCHUNK:
7673         case FSCTL_COPYCHUNK_WRITE:
7674                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7675                         ksmbd_debug(SMB,
7676                                     "User does not have write permission\n");
7677                         ret = -EACCES;
7678                         goto out;
7679                 }
7680
7681                 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7682                         ret = -EINVAL;
7683                         goto out;
7684                 }
7685
7686                 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7687                         ret = -EINVAL;
7688                         goto out;
7689                 }
7690
7691                 nbytes = sizeof(struct copychunk_ioctl_rsp);
7692                 rsp->VolatileFileId = req->VolatileFileId;
7693                 rsp->PersistentFileId = req->PersistentFileId;
7694                 fsctl_copychunk(work,
7695                                 (struct copychunk_ioctl_req *)&req->Buffer[0],
7696                                 le32_to_cpu(req->CtlCode),
7697                                 le32_to_cpu(req->InputCount),
7698                                 req->VolatileFileId,
7699                                 req->PersistentFileId,
7700                                 rsp);
7701                 break;
7702         case FSCTL_SET_SPARSE:
7703                 if (in_buf_len < sizeof(struct file_sparse)) {
7704                         ret = -EINVAL;
7705                         goto out;
7706                 }
7707
7708                 ret = fsctl_set_sparse(work, id,
7709                                        (struct file_sparse *)&req->Buffer[0]);
7710                 if (ret < 0)
7711                         goto out;
7712                 break;
7713         case FSCTL_SET_ZERO_DATA:
7714         {
7715                 struct file_zero_data_information *zero_data;
7716                 struct ksmbd_file *fp;
7717                 loff_t off, len, bfz;
7718
7719                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7720                         ksmbd_debug(SMB,
7721                                     "User does not have write permission\n");
7722                         ret = -EACCES;
7723                         goto out;
7724                 }
7725
7726                 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7727                         ret = -EINVAL;
7728                         goto out;
7729                 }
7730
7731                 zero_data =
7732                         (struct file_zero_data_information *)&req->Buffer[0];
7733
7734                 off = le64_to_cpu(zero_data->FileOffset);
7735                 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7736                 if (off > bfz) {
7737                         ret = -EINVAL;
7738                         goto out;
7739                 }
7740
7741                 len = bfz - off;
7742                 if (len) {
7743                         fp = ksmbd_lookup_fd_fast(work, id);
7744                         if (!fp) {
7745                                 ret = -ENOENT;
7746                                 goto out;
7747                         }
7748
7749                         ret = ksmbd_vfs_zero_data(work, fp, off, len);
7750                         ksmbd_fd_put(work, fp);
7751                         if (ret < 0)
7752                                 goto out;
7753                 }
7754                 break;
7755         }
7756         case FSCTL_QUERY_ALLOCATED_RANGES:
7757                 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7758                         ret = -EINVAL;
7759                         goto out;
7760                 }
7761
7762                 ret = fsctl_query_allocated_ranges(work, id,
7763                         (struct file_allocated_range_buffer *)&req->Buffer[0],
7764                         (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7765                         out_buf_len /
7766                         sizeof(struct file_allocated_range_buffer), &nbytes);
7767                 if (ret == -E2BIG) {
7768                         rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7769                 } else if (ret < 0) {
7770                         nbytes = 0;
7771                         goto out;
7772                 }
7773
7774                 nbytes *= sizeof(struct file_allocated_range_buffer);
7775                 break;
7776         case FSCTL_GET_REPARSE_POINT:
7777         {
7778                 struct reparse_data_buffer *reparse_ptr;
7779                 struct ksmbd_file *fp;
7780
7781                 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7782                 fp = ksmbd_lookup_fd_fast(work, id);
7783                 if (!fp) {
7784                         pr_err("not found fp!!\n");
7785                         ret = -ENOENT;
7786                         goto out;
7787                 }
7788
7789                 reparse_ptr->ReparseTag =
7790                         smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7791                 reparse_ptr->ReparseDataLength = 0;
7792                 ksmbd_fd_put(work, fp);
7793                 nbytes = sizeof(struct reparse_data_buffer);
7794                 break;
7795         }
7796         case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7797         {
7798                 struct ksmbd_file *fp_in, *fp_out = NULL;
7799                 struct duplicate_extents_to_file *dup_ext;
7800                 loff_t src_off, dst_off, length, cloned;
7801
7802                 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7803                         ret = -EINVAL;
7804                         goto out;
7805                 }
7806
7807                 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7808
7809                 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7810                                              dup_ext->PersistentFileHandle);
7811                 if (!fp_in) {
7812                         pr_err("not found file handle in duplicate extent to file\n");
7813                         ret = -ENOENT;
7814                         goto out;
7815                 }
7816
7817                 fp_out = ksmbd_lookup_fd_fast(work, id);
7818                 if (!fp_out) {
7819                         pr_err("not found fp\n");
7820                         ret = -ENOENT;
7821                         goto dup_ext_out;
7822                 }
7823
7824                 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7825                 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7826                 length = le64_to_cpu(dup_ext->ByteCount);
7827                 /*
7828                  * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7829                  * should fall back to vfs_copy_file_range().  This could be
7830                  * beneficial when re-exporting nfs/smb mount, but note that
7831                  * this can result in partial copy that returns an error status.
7832                  * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7833                  * fall back to vfs_copy_file_range(), should be avoided when
7834                  * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7835                  */
7836                 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7837                                               fp_out->filp, dst_off, length, 0);
7838                 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7839                         ret = -EOPNOTSUPP;
7840                         goto dup_ext_out;
7841                 } else if (cloned != length) {
7842                         cloned = vfs_copy_file_range(fp_in->filp, src_off,
7843                                                      fp_out->filp, dst_off,
7844                                                      length, 0);
7845                         if (cloned != length) {
7846                                 if (cloned < 0)
7847                                         ret = cloned;
7848                                 else
7849                                         ret = -EINVAL;
7850                         }
7851                 }
7852
7853 dup_ext_out:
7854                 ksmbd_fd_put(work, fp_in);
7855                 ksmbd_fd_put(work, fp_out);
7856                 if (ret < 0)
7857                         goto out;
7858                 break;
7859         }
7860         default:
7861                 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7862                             cnt_code);
7863                 ret = -EOPNOTSUPP;
7864                 goto out;
7865         }
7866
7867         rsp->CtlCode = cpu_to_le32(cnt_code);
7868         rsp->InputCount = cpu_to_le32(0);
7869         rsp->InputOffset = cpu_to_le32(112);
7870         rsp->OutputOffset = cpu_to_le32(112);
7871         rsp->OutputCount = cpu_to_le32(nbytes);
7872         rsp->StructureSize = cpu_to_le16(49);
7873         rsp->Reserved = cpu_to_le16(0);
7874         rsp->Flags = cpu_to_le32(0);
7875         rsp->Reserved2 = cpu_to_le32(0);
7876         inc_rfc1001_len(work->response_buf, 48 + nbytes);
7877
7878         return 0;
7879
7880 out:
7881         if (ret == -EACCES)
7882                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7883         else if (ret == -ENOENT)
7884                 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7885         else if (ret == -EOPNOTSUPP)
7886                 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7887         else if (ret == -ENOSPC)
7888                 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7889         else if (ret < 0 || rsp->hdr.Status == 0)
7890                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7891         smb2_set_err_rsp(work);
7892         return 0;
7893 }
7894
7895 /**
7896  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7897  * @work:       smb work containing oplock break command buffer
7898  *
7899  * Return:      0
7900  */
7901 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7902 {
7903         struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7904         struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7905         struct ksmbd_file *fp;
7906         struct oplock_info *opinfo = NULL;
7907         __le32 err = 0;
7908         int ret = 0;
7909         u64 volatile_id, persistent_id;
7910         char req_oplevel = 0, rsp_oplevel = 0;
7911         unsigned int oplock_change_type;
7912
7913         volatile_id = req->VolatileFid;
7914         persistent_id = req->PersistentFid;
7915         req_oplevel = req->OplockLevel;
7916         ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7917                     volatile_id, persistent_id, req_oplevel);
7918
7919         fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7920         if (!fp) {
7921                 rsp->hdr.Status = STATUS_FILE_CLOSED;
7922                 smb2_set_err_rsp(work);
7923                 return;
7924         }
7925
7926         opinfo = opinfo_get(fp);
7927         if (!opinfo) {
7928                 pr_err("unexpected null oplock_info\n");
7929                 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7930                 smb2_set_err_rsp(work);
7931                 ksmbd_fd_put(work, fp);
7932                 return;
7933         }
7934
7935         if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7936                 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7937                 goto err_out;
7938         }
7939
7940         if (opinfo->op_state == OPLOCK_STATE_NONE) {
7941                 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7942                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7943                 goto err_out;
7944         }
7945
7946         if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7947              opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7948             (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7949              req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7950                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7951                 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7952         } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7953                    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7954                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7955                 oplock_change_type = OPLOCK_READ_TO_NONE;
7956         } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7957                    req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7958                 err = STATUS_INVALID_DEVICE_STATE;
7959                 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7960                      opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7961                     req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7962                         oplock_change_type = OPLOCK_WRITE_TO_READ;
7963                 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7964                             opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7965                            req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7966                         oplock_change_type = OPLOCK_WRITE_TO_NONE;
7967                 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7968                            req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7969                         oplock_change_type = OPLOCK_READ_TO_NONE;
7970                 } else {
7971                         oplock_change_type = 0;
7972                 }
7973         } else {
7974                 oplock_change_type = 0;
7975         }
7976
7977         switch (oplock_change_type) {
7978         case OPLOCK_WRITE_TO_READ:
7979                 ret = opinfo_write_to_read(opinfo);
7980                 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7981                 break;
7982         case OPLOCK_WRITE_TO_NONE:
7983                 ret = opinfo_write_to_none(opinfo);
7984                 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7985                 break;
7986         case OPLOCK_READ_TO_NONE:
7987                 ret = opinfo_read_to_none(opinfo);
7988                 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7989                 break;
7990         default:
7991                 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7992                        opinfo->level, rsp_oplevel);
7993         }
7994
7995         if (ret < 0) {
7996                 rsp->hdr.Status = err;
7997                 goto err_out;
7998         }
7999
8000         opinfo_put(opinfo);
8001         ksmbd_fd_put(work, fp);
8002         opinfo->op_state = OPLOCK_STATE_NONE;
8003         wake_up_interruptible_all(&opinfo->oplock_q);
8004
8005         rsp->StructureSize = cpu_to_le16(24);
8006         rsp->OplockLevel = rsp_oplevel;
8007         rsp->Reserved = 0;
8008         rsp->Reserved2 = 0;
8009         rsp->VolatileFid = volatile_id;
8010         rsp->PersistentFid = persistent_id;
8011         inc_rfc1001_len(work->response_buf, 24);
8012         return;
8013
8014 err_out:
8015         opinfo->op_state = OPLOCK_STATE_NONE;
8016         wake_up_interruptible_all(&opinfo->oplock_q);
8017
8018         opinfo_put(opinfo);
8019         ksmbd_fd_put(work, fp);
8020         smb2_set_err_rsp(work);
8021 }
8022
8023 static int check_lease_state(struct lease *lease, __le32 req_state)
8024 {
8025         if ((lease->new_state ==
8026              (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8027             !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8028                 lease->new_state = req_state;
8029                 return 0;
8030         }
8031
8032         if (lease->new_state == req_state)
8033                 return 0;
8034
8035         return 1;
8036 }
8037
8038 /**
8039  * smb21_lease_break_ack() - handler for smb2.1 lease break command
8040  * @work:       smb work containing lease break command buffer
8041  *
8042  * Return:      0
8043  */
8044 static void smb21_lease_break_ack(struct ksmbd_work *work)
8045 {
8046         struct ksmbd_conn *conn = work->conn;
8047         struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8048         struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8049         struct oplock_info *opinfo;
8050         __le32 err = 0;
8051         int ret = 0;
8052         unsigned int lease_change_type;
8053         __le32 lease_state;
8054         struct lease *lease;
8055
8056         ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8057                     le32_to_cpu(req->LeaseState));
8058         opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8059         if (!opinfo) {
8060                 ksmbd_debug(OPLOCK, "file not opened\n");
8061                 smb2_set_err_rsp(work);
8062                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8063                 return;
8064         }
8065         lease = opinfo->o_lease;
8066
8067         if (opinfo->op_state == OPLOCK_STATE_NONE) {
8068                 pr_err("unexpected lease break state 0x%x\n",
8069                        opinfo->op_state);
8070                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8071                 goto err_out;
8072         }
8073
8074         if (check_lease_state(lease, req->LeaseState)) {
8075                 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8076                 ksmbd_debug(OPLOCK,
8077                             "req lease state: 0x%x, expected state: 0x%x\n",
8078                             req->LeaseState, lease->new_state);
8079                 goto err_out;
8080         }
8081
8082         if (!atomic_read(&opinfo->breaking_cnt)) {
8083                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8084                 goto err_out;
8085         }
8086
8087         /* check for bad lease state */
8088         if (req->LeaseState &
8089             (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8090                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8091                 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8092                         lease_change_type = OPLOCK_WRITE_TO_NONE;
8093                 else
8094                         lease_change_type = OPLOCK_READ_TO_NONE;
8095                 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8096                             le32_to_cpu(lease->state),
8097                             le32_to_cpu(req->LeaseState));
8098         } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8099                    req->LeaseState != SMB2_LEASE_NONE_LE) {
8100                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8101                 lease_change_type = OPLOCK_READ_TO_NONE;
8102                 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8103                             le32_to_cpu(lease->state),
8104                             le32_to_cpu(req->LeaseState));
8105         } else {
8106                 /* valid lease state changes */
8107                 err = STATUS_INVALID_DEVICE_STATE;
8108                 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8109                         if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8110                                 lease_change_type = OPLOCK_WRITE_TO_NONE;
8111                         else
8112                                 lease_change_type = OPLOCK_READ_TO_NONE;
8113                 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8114                         if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8115                                 lease_change_type = OPLOCK_WRITE_TO_READ;
8116                         else
8117                                 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8118                 } else {
8119                         lease_change_type = 0;
8120                 }
8121         }
8122
8123         switch (lease_change_type) {
8124         case OPLOCK_WRITE_TO_READ:
8125                 ret = opinfo_write_to_read(opinfo);
8126                 break;
8127         case OPLOCK_READ_HANDLE_TO_READ:
8128                 ret = opinfo_read_handle_to_read(opinfo);
8129                 break;
8130         case OPLOCK_WRITE_TO_NONE:
8131                 ret = opinfo_write_to_none(opinfo);
8132                 break;
8133         case OPLOCK_READ_TO_NONE:
8134                 ret = opinfo_read_to_none(opinfo);
8135                 break;
8136         default:
8137                 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8138                             le32_to_cpu(lease->state),
8139                             le32_to_cpu(req->LeaseState));
8140         }
8141
8142         lease_state = lease->state;
8143         opinfo->op_state = OPLOCK_STATE_NONE;
8144         wake_up_interruptible_all(&opinfo->oplock_q);
8145         atomic_dec(&opinfo->breaking_cnt);
8146         wake_up_interruptible_all(&opinfo->oplock_brk);
8147         opinfo_put(opinfo);
8148
8149         if (ret < 0) {
8150                 rsp->hdr.Status = err;
8151                 goto err_out;
8152         }
8153
8154         rsp->StructureSize = cpu_to_le16(36);
8155         rsp->Reserved = 0;
8156         rsp->Flags = 0;
8157         memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8158         rsp->LeaseState = lease_state;
8159         rsp->LeaseDuration = 0;
8160         inc_rfc1001_len(work->response_buf, 36);
8161         return;
8162
8163 err_out:
8164         opinfo->op_state = OPLOCK_STATE_NONE;
8165         wake_up_interruptible_all(&opinfo->oplock_q);
8166         atomic_dec(&opinfo->breaking_cnt);
8167         wake_up_interruptible_all(&opinfo->oplock_brk);
8168
8169         opinfo_put(opinfo);
8170         smb2_set_err_rsp(work);
8171 }
8172
8173 /**
8174  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8175  * @work:       smb work containing oplock/lease break command buffer
8176  *
8177  * Return:      0
8178  */
8179 int smb2_oplock_break(struct ksmbd_work *work)
8180 {
8181         struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8182         struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8183
8184         switch (le16_to_cpu(req->StructureSize)) {
8185         case OP_BREAK_STRUCT_SIZE_20:
8186                 smb20_oplock_break_ack(work);
8187                 break;
8188         case OP_BREAK_STRUCT_SIZE_21:
8189                 smb21_lease_break_ack(work);
8190                 break;
8191         default:
8192                 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8193                             le16_to_cpu(req->StructureSize));
8194                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8195                 smb2_set_err_rsp(work);
8196         }
8197
8198         return 0;
8199 }
8200
8201 /**
8202  * smb2_notify() - handler for smb2 notify request
8203  * @work:   smb work containing notify command buffer
8204  *
8205  * Return:      0
8206  */
8207 int smb2_notify(struct ksmbd_work *work)
8208 {
8209         struct smb2_change_notify_req *req;
8210         struct smb2_change_notify_rsp *rsp;
8211
8212         WORK_BUFFERS(work, req, rsp);
8213
8214         if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8215                 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8216                 smb2_set_err_rsp(work);
8217                 return 0;
8218         }
8219
8220         smb2_set_err_rsp(work);
8221         rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8222         return 0;
8223 }
8224
8225 /**
8226  * smb2_is_sign_req() - handler for checking packet signing status
8227  * @work:       smb work containing notify command buffer
8228  * @command:    SMB2 command id
8229  *
8230  * Return:      true if packed is signed, false otherwise
8231  */
8232 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8233 {
8234         struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8235
8236         if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8237             command != SMB2_NEGOTIATE_HE &&
8238             command != SMB2_SESSION_SETUP_HE &&
8239             command != SMB2_OPLOCK_BREAK_HE)
8240                 return true;
8241
8242         return false;
8243 }
8244
8245 /**
8246  * smb2_check_sign_req() - handler for req packet sign processing
8247  * @work:   smb work containing notify command buffer
8248  *
8249  * Return:      1 on success, 0 otherwise
8250  */
8251 int smb2_check_sign_req(struct ksmbd_work *work)
8252 {
8253         struct smb2_hdr *hdr;
8254         char signature_req[SMB2_SIGNATURE_SIZE];
8255         char signature[SMB2_HMACSHA256_SIZE];
8256         struct kvec iov[1];
8257         size_t len;
8258
8259         hdr = smb2_get_msg(work->request_buf);
8260         if (work->next_smb2_rcv_hdr_off)
8261                 hdr = ksmbd_req_buf_next(work);
8262
8263         if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8264                 len = get_rfc1002_len(work->request_buf);
8265         else if (hdr->NextCommand)
8266                 len = le32_to_cpu(hdr->NextCommand);
8267         else
8268                 len = get_rfc1002_len(work->request_buf) -
8269                         work->next_smb2_rcv_hdr_off;
8270
8271         memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8272         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8273
8274         iov[0].iov_base = (char *)&hdr->ProtocolId;
8275         iov[0].iov_len = len;
8276
8277         if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8278                                 signature))
8279                 return 0;
8280
8281         if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8282                 pr_err("bad smb2 signature\n");
8283                 return 0;
8284         }
8285
8286         return 1;
8287 }
8288
8289 /**
8290  * smb2_set_sign_rsp() - handler for rsp packet sign processing
8291  * @work:   smb work containing notify command buffer
8292  *
8293  */
8294 void smb2_set_sign_rsp(struct ksmbd_work *work)
8295 {
8296         struct smb2_hdr *hdr;
8297         struct smb2_hdr *req_hdr;
8298         char signature[SMB2_HMACSHA256_SIZE];
8299         struct kvec iov[2];
8300         size_t len;
8301         int n_vec = 1;
8302
8303         hdr = smb2_get_msg(work->response_buf);
8304         if (work->next_smb2_rsp_hdr_off)
8305                 hdr = ksmbd_resp_buf_next(work);
8306
8307         req_hdr = ksmbd_req_buf_next(work);
8308
8309         if (!work->next_smb2_rsp_hdr_off) {
8310                 len = get_rfc1002_len(work->response_buf);
8311                 if (req_hdr->NextCommand)
8312                         len = ALIGN(len, 8);
8313         } else {
8314                 len = get_rfc1002_len(work->response_buf) -
8315                         work->next_smb2_rsp_hdr_off;
8316                 len = ALIGN(len, 8);
8317         }
8318
8319         if (req_hdr->NextCommand)
8320                 hdr->NextCommand = cpu_to_le32(len);
8321
8322         hdr->Flags |= SMB2_FLAGS_SIGNED;
8323         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8324
8325         iov[0].iov_base = (char *)&hdr->ProtocolId;
8326         iov[0].iov_len = len;
8327
8328         if (work->aux_payload_sz) {
8329                 iov[0].iov_len -= work->aux_payload_sz;
8330
8331                 iov[1].iov_base = work->aux_payload_buf;
8332                 iov[1].iov_len = work->aux_payload_sz;
8333                 n_vec++;
8334         }
8335
8336         if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8337                                  signature))
8338                 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8339 }
8340
8341 /**
8342  * smb3_check_sign_req() - handler for req packet sign processing
8343  * @work:   smb work containing notify command buffer
8344  *
8345  * Return:      1 on success, 0 otherwise
8346  */
8347 int smb3_check_sign_req(struct ksmbd_work *work)
8348 {
8349         struct ksmbd_conn *conn = work->conn;
8350         char *signing_key;
8351         struct smb2_hdr *hdr;
8352         struct channel *chann;
8353         char signature_req[SMB2_SIGNATURE_SIZE];
8354         char signature[SMB2_CMACAES_SIZE];
8355         struct kvec iov[1];
8356         size_t len;
8357
8358         hdr = smb2_get_msg(work->request_buf);
8359         if (work->next_smb2_rcv_hdr_off)
8360                 hdr = ksmbd_req_buf_next(work);
8361
8362         if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8363                 len = get_rfc1002_len(work->request_buf);
8364         else if (hdr->NextCommand)
8365                 len = le32_to_cpu(hdr->NextCommand);
8366         else
8367                 len = get_rfc1002_len(work->request_buf) -
8368                         work->next_smb2_rcv_hdr_off;
8369
8370         if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8371                 signing_key = work->sess->smb3signingkey;
8372         } else {
8373                 read_lock(&work->sess->chann_lock);
8374                 chann = lookup_chann_list(work->sess, conn);
8375                 if (!chann) {
8376                         read_unlock(&work->sess->chann_lock);
8377                         return 0;
8378                 }
8379                 signing_key = chann->smb3signingkey;
8380                 read_unlock(&work->sess->chann_lock);
8381         }
8382
8383         if (!signing_key) {
8384                 pr_err("SMB3 signing key is not generated\n");
8385                 return 0;
8386         }
8387
8388         memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8389         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8390         iov[0].iov_base = (char *)&hdr->ProtocolId;
8391         iov[0].iov_len = len;
8392
8393         if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8394                 return 0;
8395
8396         if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8397                 pr_err("bad smb2 signature\n");
8398                 return 0;
8399         }
8400
8401         return 1;
8402 }
8403
8404 /**
8405  * smb3_set_sign_rsp() - handler for rsp packet sign processing
8406  * @work:   smb work containing notify command buffer
8407  *
8408  */
8409 void smb3_set_sign_rsp(struct ksmbd_work *work)
8410 {
8411         struct ksmbd_conn *conn = work->conn;
8412         struct smb2_hdr *req_hdr, *hdr;
8413         struct channel *chann;
8414         char signature[SMB2_CMACAES_SIZE];
8415         struct kvec iov[2];
8416         int n_vec = 1;
8417         size_t len;
8418         char *signing_key;
8419
8420         hdr = smb2_get_msg(work->response_buf);
8421         if (work->next_smb2_rsp_hdr_off)
8422                 hdr = ksmbd_resp_buf_next(work);
8423
8424         req_hdr = ksmbd_req_buf_next(work);
8425
8426         if (!work->next_smb2_rsp_hdr_off) {
8427                 len = get_rfc1002_len(work->response_buf);
8428                 if (req_hdr->NextCommand)
8429                         len = ALIGN(len, 8);
8430         } else {
8431                 len = get_rfc1002_len(work->response_buf) -
8432                         work->next_smb2_rsp_hdr_off;
8433                 len = ALIGN(len, 8);
8434         }
8435
8436         if (conn->binding == false &&
8437             le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8438                 signing_key = work->sess->smb3signingkey;
8439         } else {
8440                 read_lock(&work->sess->chann_lock);
8441                 chann = lookup_chann_list(work->sess, work->conn);
8442                 if (!chann) {
8443                         read_unlock(&work->sess->chann_lock);
8444                         return;
8445                 }
8446                 signing_key = chann->smb3signingkey;
8447                 read_unlock(&work->sess->chann_lock);
8448         }
8449
8450         if (!signing_key)
8451                 return;
8452
8453         if (req_hdr->NextCommand)
8454                 hdr->NextCommand = cpu_to_le32(len);
8455
8456         hdr->Flags |= SMB2_FLAGS_SIGNED;
8457         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8458         iov[0].iov_base = (char *)&hdr->ProtocolId;
8459         iov[0].iov_len = len;
8460         if (work->aux_payload_sz) {
8461                 iov[0].iov_len -= work->aux_payload_sz;
8462                 iov[1].iov_base = work->aux_payload_buf;
8463                 iov[1].iov_len = work->aux_payload_sz;
8464                 n_vec++;
8465         }
8466
8467         if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8468                 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8469 }
8470
8471 /**
8472  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8473  * @work:   smb work containing response buffer
8474  *
8475  */
8476 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8477 {
8478         struct ksmbd_conn *conn = work->conn;
8479         struct ksmbd_session *sess = work->sess;
8480         struct smb2_hdr *req, *rsp;
8481
8482         if (conn->dialect != SMB311_PROT_ID)
8483                 return;
8484
8485         WORK_BUFFERS(work, req, rsp);
8486
8487         if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8488             conn->preauth_info)
8489                 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8490                                                  conn->preauth_info->Preauth_HashValue);
8491
8492         if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8493                 __u8 *hash_value;
8494
8495                 if (conn->binding) {
8496                         struct preauth_session *preauth_sess;
8497
8498                         preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8499                         if (!preauth_sess)
8500                                 return;
8501                         hash_value = preauth_sess->Preauth_HashValue;
8502                 } else {
8503                         hash_value = sess->Preauth_HashValue;
8504                         if (!hash_value)
8505                                 return;
8506                 }
8507                 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8508                                                  hash_value);
8509         }
8510 }
8511
8512 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8513 {
8514         struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8515         struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8516         unsigned int orig_len = get_rfc1002_len(old_buf);
8517
8518         /* tr_buf must be cleared by the caller */
8519         tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8520         tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8521         tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8522         if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8523             cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8524                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8525         else
8526                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8527         memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8528         inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8529         inc_rfc1001_len(tr_buf, orig_len);
8530 }
8531
8532 int smb3_encrypt_resp(struct ksmbd_work *work)
8533 {
8534         char *buf = work->response_buf;
8535         struct kvec iov[3];
8536         int rc = -ENOMEM;
8537         int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8538
8539         if (ARRAY_SIZE(iov) < rq_nvec)
8540                 return -ENOMEM;
8541
8542         work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8543         if (!work->tr_buf)
8544                 return rc;
8545
8546         /* fill transform header */
8547         fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8548
8549         iov[0].iov_base = work->tr_buf;
8550         iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8551         buf_size += iov[0].iov_len - 4;
8552
8553         iov[1].iov_base = buf + 4;
8554         iov[1].iov_len = get_rfc1002_len(buf);
8555         if (work->aux_payload_sz) {
8556                 iov[1].iov_len = work->resp_hdr_sz - 4;
8557
8558                 iov[2].iov_base = work->aux_payload_buf;
8559                 iov[2].iov_len = work->aux_payload_sz;
8560                 buf_size += iov[2].iov_len;
8561         }
8562         buf_size += iov[1].iov_len;
8563         work->resp_hdr_sz = iov[1].iov_len;
8564
8565         rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8566         if (rc)
8567                 return rc;
8568
8569         memmove(buf, iov[1].iov_base, iov[1].iov_len);
8570         *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8571
8572         return rc;
8573 }
8574
8575 bool smb3_is_transform_hdr(void *buf)
8576 {
8577         struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8578
8579         return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8580 }
8581
8582 int smb3_decrypt_req(struct ksmbd_work *work)
8583 {
8584         struct ksmbd_conn *conn = work->conn;
8585         struct ksmbd_session *sess;
8586         char *buf = work->request_buf;
8587         unsigned int pdu_length = get_rfc1002_len(buf);
8588         struct kvec iov[2];
8589         int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8590         struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8591         int rc = 0;
8592
8593         if (buf_data_size < sizeof(struct smb2_hdr)) {
8594                 pr_err("Transform message is too small (%u)\n",
8595                        pdu_length);
8596                 return -ECONNABORTED;
8597         }
8598
8599         if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8600                 pr_err("Transform message is broken\n");
8601                 return -ECONNABORTED;
8602         }
8603
8604         sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8605         if (!sess) {
8606                 pr_err("invalid session id(%llx) in transform header\n",
8607                        le64_to_cpu(tr_hdr->SessionId));
8608                 return -ECONNABORTED;
8609         }
8610
8611         iov[0].iov_base = buf;
8612         iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8613         iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8614         iov[1].iov_len = buf_data_size;
8615         rc = ksmbd_crypt_message(conn, iov, 2, 0);
8616         if (rc)
8617                 return rc;
8618
8619         memmove(buf + 4, iov[1].iov_base, buf_data_size);
8620         *(__be32 *)buf = cpu_to_be32(buf_data_size);
8621
8622         return rc;
8623 }
8624
8625 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8626 {
8627         struct ksmbd_conn *conn = work->conn;
8628         struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8629
8630         if (conn->dialect < SMB30_PROT_ID)
8631                 return false;
8632
8633         if (work->next_smb2_rcv_hdr_off)
8634                 rsp = ksmbd_resp_buf_next(work);
8635
8636         if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8637             rsp->Status == STATUS_SUCCESS)
8638                 return true;
8639         return false;
8640 }