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