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