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