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