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