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