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