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