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