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