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