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