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