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