1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3 *
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
6 *
7 */
8 #include <linux/fs.h>
9 #include <linux/net.h>
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
32 #include <net/ipv6.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
35 #include "cifspdu.h"
36 #include "cifsglob.h"
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
41 #include "ntlmssp.h"
42 #include "nterr.h"
43 #include "rfc1002pdu.h"
44 #include "fscache.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs_cache.h"
50 #endif
51 #include "fs_context.h"
52 #include "cifs_swn.h"
53
54 extern mempool_t *cifs_req_poolp;
55 extern bool disable_legacy_dialects;
56
57 /* FIXME: should these be tunable? */
58 #define TLINK_ERROR_EXPIRE (1 * HZ)
59 #define TLINK_IDLE_EXPIRE (600 * HZ)
60
61 /* Drop the connection to not overload the server */
62 #define NUM_STATUS_IO_TIMEOUT 5
63
64 struct mount_ctx {
65 struct cifs_sb_info *cifs_sb;
66 struct smb3_fs_context *fs_ctx;
67 unsigned int xid;
68 struct TCP_Server_Info *server;
69 struct cifs_ses *ses;
70 struct cifs_tcon *tcon;
71 #ifdef CONFIG_CIFS_DFS_UPCALL
72 struct cifs_ses *root_ses;
73 uuid_t mount_id;
74 char *origin_fullpath, *leaf_fullpath;
75 #endif
76 };
77
78 static int ip_connect(struct TCP_Server_Info *server);
79 static int generic_ip_connect(struct TCP_Server_Info *server);
80 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
81 static void cifs_prune_tlinks(struct work_struct *work);
82
83 /*
84 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
85 * get their ip addresses changed at some point.
86 *
87 * This should be called with server->srv_mutex held.
88 */
reconn_set_ipaddr_from_hostname(struct TCP_Server_Info * server)89 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
90 {
91 int rc;
92 int len;
93 char *unc, *ipaddr = NULL;
94 time64_t expiry, now;
95 unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
96
97 if (!server->hostname)
98 return -EINVAL;
99
100 len = strlen(server->hostname) + 3;
101
102 unc = kmalloc(len, GFP_KERNEL);
103 if (!unc) {
104 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
105 return -ENOMEM;
106 }
107 scnprintf(unc, len, "\\\\%s", server->hostname);
108
109 rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
110 kfree(unc);
111
112 if (rc < 0) {
113 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
114 __func__, server->hostname, rc);
115 goto requeue_resolve;
116 }
117
118 spin_lock(&cifs_tcp_ses_lock);
119 rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
120 strlen(ipaddr));
121 spin_unlock(&cifs_tcp_ses_lock);
122 kfree(ipaddr);
123
124 /* rc == 1 means success here */
125 if (rc) {
126 now = ktime_get_real_seconds();
127 if (expiry && expiry > now)
128 /*
129 * To make sure we don't use the cached entry, retry 1s
130 * after expiry.
131 */
132 ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
133 }
134 rc = !rc ? -1 : 0;
135
136 requeue_resolve:
137 cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
138 __func__, ttl);
139 mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
140
141 return rc;
142 }
143
144
cifs_resolve_server(struct work_struct * work)145 static void cifs_resolve_server(struct work_struct *work)
146 {
147 int rc;
148 struct TCP_Server_Info *server = container_of(work,
149 struct TCP_Server_Info, resolve.work);
150
151 mutex_lock(&server->srv_mutex);
152
153 /*
154 * Resolve the hostname again to make sure that IP address is up-to-date.
155 */
156 rc = reconn_set_ipaddr_from_hostname(server);
157 if (rc) {
158 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
159 __func__, rc);
160 }
161
162 mutex_unlock(&server->srv_mutex);
163 }
164
165 /**
166 * Mark all sessions and tcons for reconnect.
167 *
168 * @server needs to be previously set to CifsNeedReconnect.
169 */
cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info * server)170 static void cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server)
171 {
172 struct list_head *tmp, *tmp2;
173 struct cifs_ses *ses;
174 struct cifs_tcon *tcon;
175 struct mid_q_entry *mid_entry;
176 struct list_head retry_list;
177
178 server->maxBuf = 0;
179 server->max_read = 0;
180
181 cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
182 trace_smb3_reconnect(server->CurrentMid, server->conn_id, server->hostname);
183 /*
184 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
185 * are not used until reconnected.
186 */
187 cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n", __func__);
188 spin_lock(&cifs_tcp_ses_lock);
189 list_for_each(tmp, &server->smb_ses_list) {
190 ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
191 ses->need_reconnect = true;
192 list_for_each(tmp2, &ses->tcon_list) {
193 tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
194 tcon->need_reconnect = true;
195 }
196 if (ses->tcon_ipc)
197 ses->tcon_ipc->need_reconnect = true;
198 }
199 spin_unlock(&cifs_tcp_ses_lock);
200
201 /* do not want to be sending data on a socket we are freeing */
202 cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
203 mutex_lock(&server->srv_mutex);
204 if (server->ssocket) {
205 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
206 server->ssocket->flags);
207 kernel_sock_shutdown(server->ssocket, SHUT_WR);
208 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
209 server->ssocket->flags);
210 sock_release(server->ssocket);
211 server->ssocket = NULL;
212 }
213 server->sequence_number = 0;
214 server->session_estab = false;
215 kfree(server->session_key.response);
216 server->session_key.response = NULL;
217 server->session_key.len = 0;
218 server->lstrp = jiffies;
219
220 /* mark submitted MIDs for retry and issue callback */
221 INIT_LIST_HEAD(&retry_list);
222 cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
223 spin_lock(&GlobalMid_Lock);
224 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
225 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
226 kref_get(&mid_entry->refcount);
227 if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
228 mid_entry->mid_state = MID_RETRY_NEEDED;
229 list_move(&mid_entry->qhead, &retry_list);
230 mid_entry->mid_flags |= MID_DELETED;
231 }
232 spin_unlock(&GlobalMid_Lock);
233 mutex_unlock(&server->srv_mutex);
234
235 cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
236 list_for_each_safe(tmp, tmp2, &retry_list) {
237 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
238 list_del_init(&mid_entry->qhead);
239 mid_entry->callback(mid_entry);
240 cifs_mid_q_entry_release(mid_entry);
241 }
242
243 if (cifs_rdma_enabled(server)) {
244 mutex_lock(&server->srv_mutex);
245 smbd_destroy(server);
246 mutex_unlock(&server->srv_mutex);
247 }
248 }
249
cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info * server,int num_targets)250 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
251 {
252 spin_lock(&GlobalMid_Lock);
253 server->nr_targets = num_targets;
254 if (server->tcpStatus == CifsExiting) {
255 /* the demux thread will exit normally next time through the loop */
256 spin_unlock(&GlobalMid_Lock);
257 wake_up(&server->response_q);
258 return false;
259 }
260 server->tcpStatus = CifsNeedReconnect;
261 spin_unlock(&GlobalMid_Lock);
262 return true;
263 }
264
265 /*
266 * cifs tcp session reconnection
267 *
268 * mark tcp session as reconnecting so temporarily locked
269 * mark all smb sessions as reconnecting for tcp session
270 * reconnect tcp session
271 * wake up waiters on reconnection? - (not needed currently)
272 */
__cifs_reconnect(struct TCP_Server_Info * server)273 static int __cifs_reconnect(struct TCP_Server_Info *server)
274 {
275 int rc = 0;
276
277 if (!cifs_tcp_ses_needs_reconnect(server, 1))
278 return 0;
279
280 cifs_mark_tcp_ses_conns_for_reconnect(server);
281
282 do {
283 try_to_freeze();
284 mutex_lock(&server->srv_mutex);
285
286 if (!cifs_swn_set_server_dstaddr(server)) {
287 /* resolve the hostname again to make sure that IP address is up-to-date */
288 rc = reconn_set_ipaddr_from_hostname(server);
289 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
290 }
291
292 if (cifs_rdma_enabled(server))
293 rc = smbd_reconnect(server);
294 else
295 rc = generic_ip_connect(server);
296 if (rc) {
297 mutex_unlock(&server->srv_mutex);
298 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
299 msleep(3000);
300 } else {
301 atomic_inc(&tcpSesReconnectCount);
302 set_credits(server, 1);
303 spin_lock(&GlobalMid_Lock);
304 if (server->tcpStatus != CifsExiting)
305 server->tcpStatus = CifsNeedNegotiate;
306 spin_unlock(&GlobalMid_Lock);
307 cifs_swn_reset_server_dstaddr(server);
308 mutex_unlock(&server->srv_mutex);
309 }
310 } while (server->tcpStatus == CifsNeedReconnect);
311
312 if (server->tcpStatus == CifsNeedNegotiate)
313 mod_delayed_work(cifsiod_wq, &server->echo, 0);
314
315 wake_up(&server->response_q);
316 return rc;
317 }
318
319 #ifdef CONFIG_CIFS_DFS_UPCALL
__reconnect_target_unlocked(struct TCP_Server_Info * server,const char * target)320 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
321 {
322 int rc;
323 char *hostname;
324
325 if (!cifs_swn_set_server_dstaddr(server)) {
326 if (server->hostname != target) {
327 hostname = extract_hostname(target);
328 if (!IS_ERR(hostname)) {
329 kfree(server->hostname);
330 server->hostname = hostname;
331 } else {
332 cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
333 __func__, PTR_ERR(hostname));
334 cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
335 server->hostname);
336 }
337 }
338 /* resolve the hostname again to make sure that IP address is up-to-date. */
339 rc = reconn_set_ipaddr_from_hostname(server);
340 cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
341 }
342 /* Reconnect the socket */
343 if (cifs_rdma_enabled(server))
344 rc = smbd_reconnect(server);
345 else
346 rc = generic_ip_connect(server);
347
348 return rc;
349 }
350
reconnect_target_unlocked(struct TCP_Server_Info * server,struct dfs_cache_tgt_list * tl,struct dfs_cache_tgt_iterator ** target_hint)351 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
352 struct dfs_cache_tgt_iterator **target_hint)
353 {
354 int rc;
355 struct dfs_cache_tgt_iterator *tit;
356
357 *target_hint = NULL;
358
359 /* If dfs target list is empty, then reconnect to last server */
360 tit = dfs_cache_get_tgt_iterator(tl);
361 if (!tit)
362 return __reconnect_target_unlocked(server, server->hostname);
363
364 /* Otherwise, try every dfs target in @tl */
365 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
366 rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
367 if (!rc) {
368 *target_hint = tit;
369 break;
370 }
371 }
372 return rc;
373 }
374
reconnect_dfs_server(struct TCP_Server_Info * server)375 static int reconnect_dfs_server(struct TCP_Server_Info *server)
376 {
377 int rc = 0;
378 const char *refpath = server->current_fullpath + 1;
379 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
380 struct dfs_cache_tgt_iterator *target_hint = NULL;
381 int num_targets = 0;
382
383 /*
384 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
385 *
386 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
387 * targets (server->nr_targets). It's also possible that the cached referral was cleared
388 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
389 * refreshing the referral, so, in this case, default it to 1.
390 */
391 if (!dfs_cache_noreq_find(refpath, NULL, &tl))
392 num_targets = dfs_cache_get_nr_tgts(&tl);
393 if (!num_targets)
394 num_targets = 1;
395
396 if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
397 return 0;
398
399 cifs_mark_tcp_ses_conns_for_reconnect(server);
400
401 do {
402 try_to_freeze();
403 mutex_lock(&server->srv_mutex);
404
405 rc = reconnect_target_unlocked(server, &tl, &target_hint);
406 if (rc) {
407 /* Failed to reconnect socket */
408 mutex_unlock(&server->srv_mutex);
409 cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
410 msleep(3000);
411 continue;
412 }
413 /*
414 * Socket was created. Update tcp session status to CifsNeedNegotiate so that a
415 * process waiting for reconnect will know it needs to re-establish session and tcon
416 * through the reconnected target server.
417 */
418 atomic_inc(&tcpSesReconnectCount);
419 set_credits(server, 1);
420 spin_lock(&GlobalMid_Lock);
421 if (server->tcpStatus != CifsExiting)
422 server->tcpStatus = CifsNeedNegotiate;
423 spin_unlock(&GlobalMid_Lock);
424 cifs_swn_reset_server_dstaddr(server);
425 mutex_unlock(&server->srv_mutex);
426 } while (server->tcpStatus == CifsNeedReconnect);
427
428 if (target_hint)
429 dfs_cache_noreq_update_tgthint(refpath, target_hint);
430
431 dfs_cache_free_tgts(&tl);
432
433 /* Need to set up echo worker again once connection has been established */
434 if (server->tcpStatus == CifsNeedNegotiate)
435 mod_delayed_work(cifsiod_wq, &server->echo, 0);
436
437 wake_up(&server->response_q);
438 return rc;
439 }
440
cifs_reconnect(struct TCP_Server_Info * server)441 int cifs_reconnect(struct TCP_Server_Info *server)
442 {
443 /* If tcp session is not an dfs connection, then reconnect to last target server */
444 spin_lock(&cifs_tcp_ses_lock);
445 if (!server->is_dfs_conn || !server->origin_fullpath || !server->leaf_fullpath) {
446 spin_unlock(&cifs_tcp_ses_lock);
447 return __cifs_reconnect(server);
448 }
449 spin_unlock(&cifs_tcp_ses_lock);
450
451 return reconnect_dfs_server(server);
452 }
453 #else
cifs_reconnect(struct TCP_Server_Info * server)454 int cifs_reconnect(struct TCP_Server_Info *server)
455 {
456 return __cifs_reconnect(server);
457 }
458 #endif
459
460 static void
cifs_echo_request(struct work_struct * work)461 cifs_echo_request(struct work_struct *work)
462 {
463 int rc;
464 struct TCP_Server_Info *server = container_of(work,
465 struct TCP_Server_Info, echo.work);
466
467 /*
468 * We cannot send an echo if it is disabled.
469 * Also, no need to ping if we got a response recently.
470 */
471
472 if (server->tcpStatus == CifsNeedReconnect ||
473 server->tcpStatus == CifsExiting ||
474 server->tcpStatus == CifsNew ||
475 (server->ops->can_echo && !server->ops->can_echo(server)) ||
476 time_before(jiffies, server->lstrp + server->echo_interval - HZ))
477 goto requeue_echo;
478
479 rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
480 if (rc)
481 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
482 server->hostname);
483
484 /* Check witness registrations */
485 cifs_swn_check();
486
487 requeue_echo:
488 queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
489 }
490
491 static bool
allocate_buffers(struct TCP_Server_Info * server)492 allocate_buffers(struct TCP_Server_Info *server)
493 {
494 if (!server->bigbuf) {
495 server->bigbuf = (char *)cifs_buf_get();
496 if (!server->bigbuf) {
497 cifs_server_dbg(VFS, "No memory for large SMB response\n");
498 msleep(3000);
499 /* retry will check if exiting */
500 return false;
501 }
502 } else if (server->large_buf) {
503 /* we are reusing a dirty large buf, clear its start */
504 memset(server->bigbuf, 0, HEADER_SIZE(server));
505 }
506
507 if (!server->smallbuf) {
508 server->smallbuf = (char *)cifs_small_buf_get();
509 if (!server->smallbuf) {
510 cifs_server_dbg(VFS, "No memory for SMB response\n");
511 msleep(1000);
512 /* retry will check if exiting */
513 return false;
514 }
515 /* beginning of smb buffer is cleared in our buf_get */
516 } else {
517 /* if existing small buf clear beginning */
518 memset(server->smallbuf, 0, HEADER_SIZE(server));
519 }
520
521 return true;
522 }
523
524 static bool
server_unresponsive(struct TCP_Server_Info * server)525 server_unresponsive(struct TCP_Server_Info *server)
526 {
527 /*
528 * We need to wait 3 echo intervals to make sure we handle such
529 * situations right:
530 * 1s client sends a normal SMB request
531 * 2s client gets a response
532 * 30s echo workqueue job pops, and decides we got a response recently
533 * and don't need to send another
534 * ...
535 * 65s kernel_recvmsg times out, and we see that we haven't gotten
536 * a response in >60s.
537 */
538 if ((server->tcpStatus == CifsGood ||
539 server->tcpStatus == CifsNeedNegotiate) &&
540 (!server->ops->can_echo || server->ops->can_echo(server)) &&
541 time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
542 cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
543 (3 * server->echo_interval) / HZ);
544 cifs_reconnect(server);
545 return true;
546 }
547
548 return false;
549 }
550
551 static inline bool
zero_credits(struct TCP_Server_Info * server)552 zero_credits(struct TCP_Server_Info *server)
553 {
554 int val;
555
556 spin_lock(&server->req_lock);
557 val = server->credits + server->echo_credits + server->oplock_credits;
558 if (server->in_flight == 0 && val == 0) {
559 spin_unlock(&server->req_lock);
560 return true;
561 }
562 spin_unlock(&server->req_lock);
563 return false;
564 }
565
566 static int
cifs_readv_from_socket(struct TCP_Server_Info * server,struct msghdr * smb_msg)567 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
568 {
569 int length = 0;
570 int total_read;
571
572 for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
573 try_to_freeze();
574
575 /* reconnect if no credits and no requests in flight */
576 if (zero_credits(server)) {
577 cifs_reconnect(server);
578 return -ECONNABORTED;
579 }
580
581 if (server_unresponsive(server))
582 return -ECONNABORTED;
583 if (cifs_rdma_enabled(server) && server->smbd_conn)
584 length = smbd_recv(server->smbd_conn, smb_msg);
585 else
586 length = sock_recvmsg(server->ssocket, smb_msg, 0);
587
588 if (server->tcpStatus == CifsExiting)
589 return -ESHUTDOWN;
590
591 if (server->tcpStatus == CifsNeedReconnect) {
592 cifs_reconnect(server);
593 return -ECONNABORTED;
594 }
595
596 if (length == -ERESTARTSYS ||
597 length == -EAGAIN ||
598 length == -EINTR) {
599 /*
600 * Minimum sleep to prevent looping, allowing socket
601 * to clear and app threads to set tcpStatus
602 * CifsNeedReconnect if server hung.
603 */
604 usleep_range(1000, 2000);
605 length = 0;
606 continue;
607 }
608
609 if (length <= 0) {
610 cifs_dbg(FYI, "Received no data or error: %d\n", length);
611 cifs_reconnect(server);
612 return -ECONNABORTED;
613 }
614 }
615 return total_read;
616 }
617
618 int
cifs_read_from_socket(struct TCP_Server_Info * server,char * buf,unsigned int to_read)619 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
620 unsigned int to_read)
621 {
622 struct msghdr smb_msg = {};
623 struct kvec iov = {.iov_base = buf, .iov_len = to_read};
624 iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
625
626 return cifs_readv_from_socket(server, &smb_msg);
627 }
628
629 ssize_t
cifs_discard_from_socket(struct TCP_Server_Info * server,size_t to_read)630 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
631 {
632 struct msghdr smb_msg = {};
633
634 /*
635 * iov_iter_discard already sets smb_msg.type and count and iov_offset
636 * and cifs_readv_from_socket sets msg_control and msg_controllen
637 * so little to initialize in struct msghdr
638 */
639 iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
640
641 return cifs_readv_from_socket(server, &smb_msg);
642 }
643
644 int
cifs_read_page_from_socket(struct TCP_Server_Info * server,struct page * page,unsigned int page_offset,unsigned int to_read)645 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
646 unsigned int page_offset, unsigned int to_read)
647 {
648 struct msghdr smb_msg = {};
649 struct bio_vec bv = {
650 .bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
651 iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
652 return cifs_readv_from_socket(server, &smb_msg);
653 }
654
655 static bool
is_smb_response(struct TCP_Server_Info * server,unsigned char type)656 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
657 {
658 /*
659 * The first byte big endian of the length field,
660 * is actually not part of the length but the type
661 * with the most common, zero, as regular data.
662 */
663 switch (type) {
664 case RFC1002_SESSION_MESSAGE:
665 /* Regular SMB response */
666 return true;
667 case RFC1002_SESSION_KEEP_ALIVE:
668 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
669 break;
670 case RFC1002_POSITIVE_SESSION_RESPONSE:
671 cifs_dbg(FYI, "RFC 1002 positive session response\n");
672 break;
673 case RFC1002_NEGATIVE_SESSION_RESPONSE:
674 /*
675 * We get this from Windows 98 instead of an error on
676 * SMB negprot response.
677 */
678 cifs_dbg(FYI, "RFC 1002 negative session response\n");
679 /* give server a second to clean up */
680 msleep(1000);
681 /*
682 * Always try 445 first on reconnect since we get NACK
683 * on some if we ever connected to port 139 (the NACK
684 * is since we do not begin with RFC1001 session
685 * initialize frame).
686 */
687 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
688 cifs_reconnect(server);
689 break;
690 default:
691 cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
692 cifs_reconnect(server);
693 }
694
695 return false;
696 }
697
698 void
dequeue_mid(struct mid_q_entry * mid,bool malformed)699 dequeue_mid(struct mid_q_entry *mid, bool malformed)
700 {
701 #ifdef CONFIG_CIFS_STATS2
702 mid->when_received = jiffies;
703 #endif
704 spin_lock(&GlobalMid_Lock);
705 if (!malformed)
706 mid->mid_state = MID_RESPONSE_RECEIVED;
707 else
708 mid->mid_state = MID_RESPONSE_MALFORMED;
709 /*
710 * Trying to handle/dequeue a mid after the send_recv()
711 * function has finished processing it is a bug.
712 */
713 if (mid->mid_flags & MID_DELETED)
714 pr_warn_once("trying to dequeue a deleted mid\n");
715 else {
716 list_del_init(&mid->qhead);
717 mid->mid_flags |= MID_DELETED;
718 }
719 spin_unlock(&GlobalMid_Lock);
720 }
721
722 static unsigned int
smb2_get_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)723 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
724 {
725 struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buffer;
726
727 /*
728 * SMB1 does not use credits.
729 */
730 if (server->vals->header_preamble_size)
731 return 0;
732
733 return le16_to_cpu(shdr->CreditRequest);
734 }
735
736 static void
handle_mid(struct mid_q_entry * mid,struct TCP_Server_Info * server,char * buf,int malformed)737 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
738 char *buf, int malformed)
739 {
740 if (server->ops->check_trans2 &&
741 server->ops->check_trans2(mid, server, buf, malformed))
742 return;
743 mid->credits_received = smb2_get_credits_from_hdr(buf, server);
744 mid->resp_buf = buf;
745 mid->large_buf = server->large_buf;
746 /* Was previous buf put in mpx struct for multi-rsp? */
747 if (!mid->multiRsp) {
748 /* smb buffer will be freed by user thread */
749 if (server->large_buf)
750 server->bigbuf = NULL;
751 else
752 server->smallbuf = NULL;
753 }
754 dequeue_mid(mid, malformed);
755 }
756
clean_demultiplex_info(struct TCP_Server_Info * server)757 static void clean_demultiplex_info(struct TCP_Server_Info *server)
758 {
759 int length;
760
761 /* take it off the list, if it's not already */
762 spin_lock(&cifs_tcp_ses_lock);
763 list_del_init(&server->tcp_ses_list);
764 spin_unlock(&cifs_tcp_ses_lock);
765
766 cancel_delayed_work_sync(&server->echo);
767 cancel_delayed_work_sync(&server->resolve);
768
769 spin_lock(&GlobalMid_Lock);
770 server->tcpStatus = CifsExiting;
771 spin_unlock(&GlobalMid_Lock);
772 wake_up_all(&server->response_q);
773
774 /* check if we have blocked requests that need to free */
775 spin_lock(&server->req_lock);
776 if (server->credits <= 0)
777 server->credits = 1;
778 spin_unlock(&server->req_lock);
779 /*
780 * Although there should not be any requests blocked on this queue it
781 * can not hurt to be paranoid and try to wake up requests that may
782 * haven been blocked when more than 50 at time were on the wire to the
783 * same server - they now will see the session is in exit state and get
784 * out of SendReceive.
785 */
786 wake_up_all(&server->request_q);
787 /* give those requests time to exit */
788 msleep(125);
789 if (cifs_rdma_enabled(server))
790 smbd_destroy(server);
791 if (server->ssocket) {
792 sock_release(server->ssocket);
793 server->ssocket = NULL;
794 }
795
796 if (!list_empty(&server->pending_mid_q)) {
797 struct list_head dispose_list;
798 struct mid_q_entry *mid_entry;
799 struct list_head *tmp, *tmp2;
800
801 INIT_LIST_HEAD(&dispose_list);
802 spin_lock(&GlobalMid_Lock);
803 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
804 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
805 cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
806 kref_get(&mid_entry->refcount);
807 mid_entry->mid_state = MID_SHUTDOWN;
808 list_move(&mid_entry->qhead, &dispose_list);
809 mid_entry->mid_flags |= MID_DELETED;
810 }
811 spin_unlock(&GlobalMid_Lock);
812
813 /* now walk dispose list and issue callbacks */
814 list_for_each_safe(tmp, tmp2, &dispose_list) {
815 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
816 cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
817 list_del_init(&mid_entry->qhead);
818 mid_entry->callback(mid_entry);
819 cifs_mid_q_entry_release(mid_entry);
820 }
821 /* 1/8th of sec is more than enough time for them to exit */
822 msleep(125);
823 }
824
825 if (!list_empty(&server->pending_mid_q)) {
826 /*
827 * mpx threads have not exited yet give them at least the smb
828 * send timeout time for long ops.
829 *
830 * Due to delays on oplock break requests, we need to wait at
831 * least 45 seconds before giving up on a request getting a
832 * response and going ahead and killing cifsd.
833 */
834 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
835 msleep(46000);
836 /*
837 * If threads still have not exited they are probably never
838 * coming home not much else we can do but free the memory.
839 */
840 }
841
842 #ifdef CONFIG_CIFS_DFS_UPCALL
843 kfree(server->origin_fullpath);
844 kfree(server->leaf_fullpath);
845 #endif
846 kfree(server);
847
848 length = atomic_dec_return(&tcpSesAllocCount);
849 if (length > 0)
850 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
851 }
852
853 static int
standard_receive3(struct TCP_Server_Info * server,struct mid_q_entry * mid)854 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
855 {
856 int length;
857 char *buf = server->smallbuf;
858 unsigned int pdu_length = server->pdu_size;
859
860 /* make sure this will fit in a large buffer */
861 if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
862 server->vals->header_preamble_size) {
863 cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
864 cifs_reconnect(server);
865 return -ECONNABORTED;
866 }
867
868 /* switch to large buffer if too big for a small one */
869 if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
870 server->large_buf = true;
871 memcpy(server->bigbuf, buf, server->total_read);
872 buf = server->bigbuf;
873 }
874
875 /* now read the rest */
876 length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
877 pdu_length - HEADER_SIZE(server) + 1
878 + server->vals->header_preamble_size);
879
880 if (length < 0)
881 return length;
882 server->total_read += length;
883
884 dump_smb(buf, server->total_read);
885
886 return cifs_handle_standard(server, mid);
887 }
888
889 int
cifs_handle_standard(struct TCP_Server_Info * server,struct mid_q_entry * mid)890 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
891 {
892 char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
893 int length;
894
895 /*
896 * We know that we received enough to get to the MID as we
897 * checked the pdu_length earlier. Now check to see
898 * if the rest of the header is OK. We borrow the length
899 * var for the rest of the loop to avoid a new stack var.
900 *
901 * 48 bytes is enough to display the header and a little bit
902 * into the payload for debugging purposes.
903 */
904 length = server->ops->check_message(buf, server->total_read, server);
905 if (length != 0)
906 cifs_dump_mem("Bad SMB: ", buf,
907 min_t(unsigned int, server->total_read, 48));
908
909 if (server->ops->is_session_expired &&
910 server->ops->is_session_expired(buf)) {
911 cifs_reconnect(server);
912 return -1;
913 }
914
915 if (server->ops->is_status_pending &&
916 server->ops->is_status_pending(buf, server))
917 return -1;
918
919 if (!mid)
920 return length;
921
922 handle_mid(mid, server, buf, length);
923 return 0;
924 }
925
926 static void
smb2_add_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)927 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
928 {
929 struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)buffer;
930 int scredits, in_flight;
931
932 /*
933 * SMB1 does not use credits.
934 */
935 if (server->vals->header_preamble_size)
936 return;
937
938 if (shdr->CreditRequest) {
939 spin_lock(&server->req_lock);
940 server->credits += le16_to_cpu(shdr->CreditRequest);
941 scredits = server->credits;
942 in_flight = server->in_flight;
943 spin_unlock(&server->req_lock);
944 wake_up(&server->request_q);
945
946 trace_smb3_add_credits(server->CurrentMid,
947 server->conn_id, server->hostname, scredits,
948 le16_to_cpu(shdr->CreditRequest), in_flight);
949 cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
950 __func__, le16_to_cpu(shdr->CreditRequest),
951 scredits);
952 }
953 }
954
955
956 static int
cifs_demultiplex_thread(void * p)957 cifs_demultiplex_thread(void *p)
958 {
959 int i, num_mids, length;
960 struct TCP_Server_Info *server = p;
961 unsigned int pdu_length;
962 unsigned int next_offset;
963 char *buf = NULL;
964 struct task_struct *task_to_wake = NULL;
965 struct mid_q_entry *mids[MAX_COMPOUND];
966 char *bufs[MAX_COMPOUND];
967 unsigned int noreclaim_flag, num_io_timeout = 0;
968
969 noreclaim_flag = memalloc_noreclaim_save();
970 cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
971
972 length = atomic_inc_return(&tcpSesAllocCount);
973 if (length > 1)
974 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
975
976 set_freezable();
977 allow_kernel_signal(SIGKILL);
978 while (server->tcpStatus != CifsExiting) {
979 if (try_to_freeze())
980 continue;
981
982 if (!allocate_buffers(server))
983 continue;
984
985 server->large_buf = false;
986 buf = server->smallbuf;
987 pdu_length = 4; /* enough to get RFC1001 header */
988
989 length = cifs_read_from_socket(server, buf, pdu_length);
990 if (length < 0)
991 continue;
992
993 if (server->vals->header_preamble_size == 0)
994 server->total_read = 0;
995 else
996 server->total_read = length;
997
998 /*
999 * The right amount was read from socket - 4 bytes,
1000 * so we can now interpret the length field.
1001 */
1002 pdu_length = get_rfc1002_length(buf);
1003
1004 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1005 if (!is_smb_response(server, buf[0]))
1006 continue;
1007 next_pdu:
1008 server->pdu_size = pdu_length;
1009
1010 /* make sure we have enough to get to the MID */
1011 if (server->pdu_size < HEADER_SIZE(server) - 1 -
1012 server->vals->header_preamble_size) {
1013 cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1014 server->pdu_size);
1015 cifs_reconnect(server);
1016 continue;
1017 }
1018
1019 /* read down to the MID */
1020 length = cifs_read_from_socket(server,
1021 buf + server->vals->header_preamble_size,
1022 HEADER_SIZE(server) - 1
1023 - server->vals->header_preamble_size);
1024 if (length < 0)
1025 continue;
1026 server->total_read += length;
1027
1028 if (server->ops->next_header) {
1029 next_offset = server->ops->next_header(buf);
1030 if (next_offset)
1031 server->pdu_size = next_offset;
1032 }
1033
1034 memset(mids, 0, sizeof(mids));
1035 memset(bufs, 0, sizeof(bufs));
1036 num_mids = 0;
1037
1038 if (server->ops->is_transform_hdr &&
1039 server->ops->receive_transform &&
1040 server->ops->is_transform_hdr(buf)) {
1041 length = server->ops->receive_transform(server,
1042 mids,
1043 bufs,
1044 &num_mids);
1045 } else {
1046 mids[0] = server->ops->find_mid(server, buf);
1047 bufs[0] = buf;
1048 num_mids = 1;
1049
1050 if (!mids[0] || !mids[0]->receive)
1051 length = standard_receive3(server, mids[0]);
1052 else
1053 length = mids[0]->receive(server, mids[0]);
1054 }
1055
1056 if (length < 0) {
1057 for (i = 0; i < num_mids; i++)
1058 if (mids[i])
1059 cifs_mid_q_entry_release(mids[i]);
1060 continue;
1061 }
1062
1063 if (server->ops->is_status_io_timeout &&
1064 server->ops->is_status_io_timeout(buf)) {
1065 num_io_timeout++;
1066 if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1067 cifs_reconnect(server);
1068 num_io_timeout = 0;
1069 continue;
1070 }
1071 }
1072
1073 server->lstrp = jiffies;
1074
1075 for (i = 0; i < num_mids; i++) {
1076 if (mids[i] != NULL) {
1077 mids[i]->resp_buf_size = server->pdu_size;
1078
1079 if (bufs[i] && server->ops->is_network_name_deleted)
1080 server->ops->is_network_name_deleted(bufs[i],
1081 server);
1082
1083 if (!mids[i]->multiRsp || mids[i]->multiEnd)
1084 mids[i]->callback(mids[i]);
1085
1086 cifs_mid_q_entry_release(mids[i]);
1087 } else if (server->ops->is_oplock_break &&
1088 server->ops->is_oplock_break(bufs[i],
1089 server)) {
1090 smb2_add_credits_from_hdr(bufs[i], server);
1091 cifs_dbg(FYI, "Received oplock break\n");
1092 } else {
1093 cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1094 atomic_read(&midCount));
1095 cifs_dump_mem("Received Data is: ", bufs[i],
1096 HEADER_SIZE(server));
1097 smb2_add_credits_from_hdr(bufs[i], server);
1098 #ifdef CONFIG_CIFS_DEBUG2
1099 if (server->ops->dump_detail)
1100 server->ops->dump_detail(bufs[i],
1101 server);
1102 cifs_dump_mids(server);
1103 #endif /* CIFS_DEBUG2 */
1104 }
1105 }
1106
1107 if (pdu_length > server->pdu_size) {
1108 if (!allocate_buffers(server))
1109 continue;
1110 pdu_length -= server->pdu_size;
1111 server->total_read = 0;
1112 server->large_buf = false;
1113 buf = server->smallbuf;
1114 goto next_pdu;
1115 }
1116 } /* end while !EXITING */
1117
1118 /* buffer usually freed in free_mid - need to free it here on exit */
1119 cifs_buf_release(server->bigbuf);
1120 if (server->smallbuf) /* no sense logging a debug message if NULL */
1121 cifs_small_buf_release(server->smallbuf);
1122
1123 task_to_wake = xchg(&server->tsk, NULL);
1124 clean_demultiplex_info(server);
1125
1126 /* if server->tsk was NULL then wait for a signal before exiting */
1127 if (!task_to_wake) {
1128 set_current_state(TASK_INTERRUPTIBLE);
1129 while (!signal_pending(current)) {
1130 schedule();
1131 set_current_state(TASK_INTERRUPTIBLE);
1132 }
1133 set_current_state(TASK_RUNNING);
1134 }
1135
1136 memalloc_noreclaim_restore(noreclaim_flag);
1137 module_put_and_exit(0);
1138 }
1139
1140 /*
1141 * Returns true if srcaddr isn't specified and rhs isn't specified, or
1142 * if srcaddr is specified and matches the IP address of the rhs argument
1143 */
1144 bool
cifs_match_ipaddr(struct sockaddr * srcaddr,struct sockaddr * rhs)1145 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1146 {
1147 switch (srcaddr->sa_family) {
1148 case AF_UNSPEC:
1149 return (rhs->sa_family == AF_UNSPEC);
1150 case AF_INET: {
1151 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1152 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1153 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1154 }
1155 case AF_INET6: {
1156 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1157 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1158 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1159 }
1160 default:
1161 WARN_ON(1);
1162 return false; /* don't expect to be here */
1163 }
1164 }
1165
1166 /*
1167 * If no port is specified in addr structure, we try to match with 445 port
1168 * and if it fails - with 139 ports. It should be called only if address
1169 * families of server and addr are equal.
1170 */
1171 static bool
match_port(struct TCP_Server_Info * server,struct sockaddr * addr)1172 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1173 {
1174 __be16 port, *sport;
1175
1176 /* SMBDirect manages its own ports, don't match it here */
1177 if (server->rdma)
1178 return true;
1179
1180 switch (addr->sa_family) {
1181 case AF_INET:
1182 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1183 port = ((struct sockaddr_in *) addr)->sin_port;
1184 break;
1185 case AF_INET6:
1186 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1187 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1188 break;
1189 default:
1190 WARN_ON(1);
1191 return false;
1192 }
1193
1194 if (!port) {
1195 port = htons(CIFS_PORT);
1196 if (port == *sport)
1197 return true;
1198
1199 port = htons(RFC1001_PORT);
1200 }
1201
1202 return port == *sport;
1203 }
1204
1205 static bool
match_address(struct TCP_Server_Info * server,struct sockaddr * addr,struct sockaddr * srcaddr)1206 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1207 struct sockaddr *srcaddr)
1208 {
1209 switch (addr->sa_family) {
1210 case AF_INET: {
1211 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1212 struct sockaddr_in *srv_addr4 =
1213 (struct sockaddr_in *)&server->dstaddr;
1214
1215 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1216 return false;
1217 break;
1218 }
1219 case AF_INET6: {
1220 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1221 struct sockaddr_in6 *srv_addr6 =
1222 (struct sockaddr_in6 *)&server->dstaddr;
1223
1224 if (!ipv6_addr_equal(&addr6->sin6_addr,
1225 &srv_addr6->sin6_addr))
1226 return false;
1227 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1228 return false;
1229 break;
1230 }
1231 default:
1232 WARN_ON(1);
1233 return false; /* don't expect to be here */
1234 }
1235
1236 if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1237 return false;
1238
1239 return true;
1240 }
1241
1242 static bool
match_security(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1243 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1244 {
1245 /*
1246 * The select_sectype function should either return the ctx->sectype
1247 * that was specified, or "Unspecified" if that sectype was not
1248 * compatible with the given NEGOTIATE request.
1249 */
1250 if (server->ops->select_sectype(server, ctx->sectype)
1251 == Unspecified)
1252 return false;
1253
1254 /*
1255 * Now check if signing mode is acceptable. No need to check
1256 * global_secflags at this point since if MUST_SIGN is set then
1257 * the server->sign had better be too.
1258 */
1259 if (ctx->sign && !server->sign)
1260 return false;
1261
1262 return true;
1263 }
1264
match_server(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1265 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1266 {
1267 struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1268
1269 if (ctx->nosharesock)
1270 return 0;
1271
1272 /* this server does not share socket */
1273 if (server->nosharesock)
1274 return 0;
1275
1276 /* If multidialect negotiation see if existing sessions match one */
1277 if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1278 if (server->vals->protocol_id < SMB30_PROT_ID)
1279 return 0;
1280 } else if (strcmp(ctx->vals->version_string,
1281 SMBDEFAULT_VERSION_STRING) == 0) {
1282 if (server->vals->protocol_id < SMB21_PROT_ID)
1283 return 0;
1284 } else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1285 return 0;
1286
1287 if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1288 return 0;
1289
1290 if (strcasecmp(server->hostname, ctx->server_hostname))
1291 return 0;
1292
1293 if (!match_address(server, addr,
1294 (struct sockaddr *)&ctx->srcaddr))
1295 return 0;
1296
1297 if (!match_port(server, addr))
1298 return 0;
1299
1300 if (!match_security(server, ctx))
1301 return 0;
1302
1303 if (server->echo_interval != ctx->echo_interval * HZ)
1304 return 0;
1305
1306 if (server->rdma != ctx->rdma)
1307 return 0;
1308
1309 if (server->ignore_signature != ctx->ignore_signature)
1310 return 0;
1311
1312 if (server->min_offload != ctx->min_offload)
1313 return 0;
1314
1315 return 1;
1316 }
1317
1318 struct TCP_Server_Info *
cifs_find_tcp_session(struct smb3_fs_context * ctx)1319 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1320 {
1321 struct TCP_Server_Info *server;
1322
1323 spin_lock(&cifs_tcp_ses_lock);
1324 list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1325 #ifdef CONFIG_CIFS_DFS_UPCALL
1326 /*
1327 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1328 * DFS connections to do failover properly, so avoid sharing them with regular
1329 * shares or even links that may connect to same server but having completely
1330 * different failover targets.
1331 */
1332 if (server->is_dfs_conn)
1333 continue;
1334 #endif
1335 /*
1336 * Skip ses channels since they're only handled in lower layers
1337 * (e.g. cifs_send_recv).
1338 */
1339 if (server->is_channel || !match_server(server, ctx))
1340 continue;
1341
1342 ++server->srv_count;
1343 spin_unlock(&cifs_tcp_ses_lock);
1344 cifs_dbg(FYI, "Existing tcp session with server found\n");
1345 return server;
1346 }
1347 spin_unlock(&cifs_tcp_ses_lock);
1348 return NULL;
1349 }
1350
1351 void
cifs_put_tcp_session(struct TCP_Server_Info * server,int from_reconnect)1352 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1353 {
1354 struct task_struct *task;
1355
1356 spin_lock(&cifs_tcp_ses_lock);
1357 if (--server->srv_count > 0) {
1358 spin_unlock(&cifs_tcp_ses_lock);
1359 return;
1360 }
1361
1362 /* srv_count can never go negative */
1363 WARN_ON(server->srv_count < 0);
1364
1365 put_net(cifs_net_ns(server));
1366
1367 list_del_init(&server->tcp_ses_list);
1368 spin_unlock(&cifs_tcp_ses_lock);
1369
1370 cancel_delayed_work_sync(&server->echo);
1371 cancel_delayed_work_sync(&server->resolve);
1372
1373 if (from_reconnect)
1374 /*
1375 * Avoid deadlock here: reconnect work calls
1376 * cifs_put_tcp_session() at its end. Need to be sure
1377 * that reconnect work does nothing with server pointer after
1378 * that step.
1379 */
1380 cancel_delayed_work(&server->reconnect);
1381 else
1382 cancel_delayed_work_sync(&server->reconnect);
1383
1384 spin_lock(&GlobalMid_Lock);
1385 server->tcpStatus = CifsExiting;
1386 spin_unlock(&GlobalMid_Lock);
1387
1388 cifs_crypto_secmech_release(server);
1389 cifs_fscache_release_client_cookie(server);
1390
1391 kfree(server->session_key.response);
1392 server->session_key.response = NULL;
1393 server->session_key.len = 0;
1394 kfree(server->hostname);
1395 server->hostname = NULL;
1396
1397 task = xchg(&server->tsk, NULL);
1398 if (task)
1399 send_sig(SIGKILL, task, 1);
1400 }
1401
1402 struct TCP_Server_Info *
cifs_get_tcp_session(struct smb3_fs_context * ctx)1403 cifs_get_tcp_session(struct smb3_fs_context *ctx)
1404 {
1405 struct TCP_Server_Info *tcp_ses = NULL;
1406 int rc;
1407
1408 cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1409
1410 /* see if we already have a matching tcp_ses */
1411 tcp_ses = cifs_find_tcp_session(ctx);
1412 if (tcp_ses)
1413 return tcp_ses;
1414
1415 tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1416 if (!tcp_ses) {
1417 rc = -ENOMEM;
1418 goto out_err;
1419 }
1420
1421 tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1422 if (!tcp_ses->hostname) {
1423 rc = -ENOMEM;
1424 goto out_err;
1425 }
1426
1427 if (ctx->nosharesock)
1428 tcp_ses->nosharesock = true;
1429
1430 tcp_ses->ops = ctx->ops;
1431 tcp_ses->vals = ctx->vals;
1432 cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1433
1434 tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1435 tcp_ses->noblockcnt = ctx->rootfs;
1436 tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1437 tcp_ses->noautotune = ctx->noautotune;
1438 tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1439 tcp_ses->rdma = ctx->rdma;
1440 tcp_ses->in_flight = 0;
1441 tcp_ses->max_in_flight = 0;
1442 tcp_ses->credits = 1;
1443 init_waitqueue_head(&tcp_ses->response_q);
1444 init_waitqueue_head(&tcp_ses->request_q);
1445 INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1446 mutex_init(&tcp_ses->srv_mutex);
1447 memcpy(tcp_ses->workstation_RFC1001_name,
1448 ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1449 memcpy(tcp_ses->server_RFC1001_name,
1450 ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1451 tcp_ses->session_estab = false;
1452 tcp_ses->sequence_number = 0;
1453 tcp_ses->reconnect_instance = 1;
1454 tcp_ses->lstrp = jiffies;
1455 tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1456 spin_lock_init(&tcp_ses->req_lock);
1457 INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1458 INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1459 INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1460 INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1461 INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1462 mutex_init(&tcp_ses->reconnect_mutex);
1463 #ifdef CONFIG_CIFS_DFS_UPCALL
1464 mutex_init(&tcp_ses->refpath_lock);
1465 #endif
1466 memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1467 sizeof(tcp_ses->srcaddr));
1468 memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1469 sizeof(tcp_ses->dstaddr));
1470 if (ctx->use_client_guid)
1471 memcpy(tcp_ses->client_guid, ctx->client_guid,
1472 SMB2_CLIENT_GUID_SIZE);
1473 else
1474 generate_random_uuid(tcp_ses->client_guid);
1475 /*
1476 * at this point we are the only ones with the pointer
1477 * to the struct since the kernel thread not created yet
1478 * no need to spinlock this init of tcpStatus or srv_count
1479 */
1480 tcp_ses->tcpStatus = CifsNew;
1481 ++tcp_ses->srv_count;
1482
1483 if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1484 ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1485 tcp_ses->echo_interval = ctx->echo_interval * HZ;
1486 else
1487 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1488 if (tcp_ses->rdma) {
1489 #ifndef CONFIG_CIFS_SMB_DIRECT
1490 cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1491 rc = -ENOENT;
1492 goto out_err_crypto_release;
1493 #endif
1494 tcp_ses->smbd_conn = smbd_get_connection(
1495 tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1496 if (tcp_ses->smbd_conn) {
1497 cifs_dbg(VFS, "RDMA transport established\n");
1498 rc = 0;
1499 goto smbd_connected;
1500 } else {
1501 rc = -ENOENT;
1502 goto out_err_crypto_release;
1503 }
1504 }
1505 rc = ip_connect(tcp_ses);
1506 if (rc < 0) {
1507 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1508 goto out_err_crypto_release;
1509 }
1510 smbd_connected:
1511 /*
1512 * since we're in a cifs function already, we know that
1513 * this will succeed. No need for try_module_get().
1514 */
1515 __module_get(THIS_MODULE);
1516 tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1517 tcp_ses, "cifsd");
1518 if (IS_ERR(tcp_ses->tsk)) {
1519 rc = PTR_ERR(tcp_ses->tsk);
1520 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1521 module_put(THIS_MODULE);
1522 goto out_err_crypto_release;
1523 }
1524 tcp_ses->min_offload = ctx->min_offload;
1525 /*
1526 * at this point we are the only ones with the pointer
1527 * to the struct since the kernel thread not created yet
1528 * no need to spinlock this update of tcpStatus
1529 */
1530 tcp_ses->tcpStatus = CifsNeedNegotiate;
1531
1532 if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1533 tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1534 else
1535 tcp_ses->max_credits = ctx->max_credits;
1536
1537 tcp_ses->nr_targets = 1;
1538 tcp_ses->ignore_signature = ctx->ignore_signature;
1539 /* thread spawned, put it on the list */
1540 spin_lock(&cifs_tcp_ses_lock);
1541 list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1542 spin_unlock(&cifs_tcp_ses_lock);
1543
1544 cifs_fscache_get_client_cookie(tcp_ses);
1545
1546 /* queue echo request delayed work */
1547 queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1548
1549 /* queue dns resolution delayed work */
1550 cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1551 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1552
1553 queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1554
1555 return tcp_ses;
1556
1557 out_err_crypto_release:
1558 cifs_crypto_secmech_release(tcp_ses);
1559
1560 put_net(cifs_net_ns(tcp_ses));
1561
1562 out_err:
1563 if (tcp_ses) {
1564 kfree(tcp_ses->hostname);
1565 if (tcp_ses->ssocket)
1566 sock_release(tcp_ses->ssocket);
1567 kfree(tcp_ses);
1568 }
1569 return ERR_PTR(rc);
1570 }
1571
match_session(struct cifs_ses * ses,struct smb3_fs_context * ctx)1572 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1573 {
1574 if (ctx->sectype != Unspecified &&
1575 ctx->sectype != ses->sectype)
1576 return 0;
1577
1578 /*
1579 * If an existing session is limited to less channels than
1580 * requested, it should not be reused
1581 */
1582 spin_lock(&ses->chan_lock);
1583 if (ses->chan_max < ctx->max_channels) {
1584 spin_unlock(&ses->chan_lock);
1585 return 0;
1586 }
1587 spin_unlock(&ses->chan_lock);
1588
1589 switch (ses->sectype) {
1590 case Kerberos:
1591 if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1592 return 0;
1593 break;
1594 default:
1595 /* NULL username means anonymous session */
1596 if (ses->user_name == NULL) {
1597 if (!ctx->nullauth)
1598 return 0;
1599 break;
1600 }
1601
1602 /* anything else takes username/password */
1603 if (strncmp(ses->user_name,
1604 ctx->username ? ctx->username : "",
1605 CIFS_MAX_USERNAME_LEN))
1606 return 0;
1607 if ((ctx->username && strlen(ctx->username) != 0) &&
1608 ses->password != NULL &&
1609 strncmp(ses->password,
1610 ctx->password ? ctx->password : "",
1611 CIFS_MAX_PASSWORD_LEN))
1612 return 0;
1613 }
1614 return 1;
1615 }
1616
1617 /**
1618 * cifs_setup_ipc - helper to setup the IPC tcon for the session
1619 * @ses: smb session to issue the request on
1620 * @ctx: the superblock configuration context to use for building the
1621 * new tree connection for the IPC (interprocess communication RPC)
1622 *
1623 * A new IPC connection is made and stored in the session
1624 * tcon_ipc. The IPC tcon has the same lifetime as the session.
1625 */
1626 static int
cifs_setup_ipc(struct cifs_ses * ses,struct smb3_fs_context * ctx)1627 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1628 {
1629 int rc = 0, xid;
1630 struct cifs_tcon *tcon;
1631 char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1632 bool seal = false;
1633 struct TCP_Server_Info *server = ses->server;
1634
1635 /*
1636 * If the mount request that resulted in the creation of the
1637 * session requires encryption, force IPC to be encrypted too.
1638 */
1639 if (ctx->seal) {
1640 if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1641 seal = true;
1642 else {
1643 cifs_server_dbg(VFS,
1644 "IPC: server doesn't support encryption\n");
1645 return -EOPNOTSUPP;
1646 }
1647 }
1648
1649 tcon = tconInfoAlloc();
1650 if (tcon == NULL)
1651 return -ENOMEM;
1652
1653 scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1654
1655 xid = get_xid();
1656 tcon->ses = ses;
1657 tcon->ipc = true;
1658 tcon->seal = seal;
1659 rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1660 free_xid(xid);
1661
1662 if (rc) {
1663 cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1664 tconInfoFree(tcon);
1665 goto out;
1666 }
1667
1668 cifs_dbg(FYI, "IPC tcon rc = %d ipc tid = %d\n", rc, tcon->tid);
1669
1670 ses->tcon_ipc = tcon;
1671 out:
1672 return rc;
1673 }
1674
1675 /**
1676 * cifs_free_ipc - helper to release the session IPC tcon
1677 * @ses: smb session to unmount the IPC from
1678 *
1679 * Needs to be called everytime a session is destroyed.
1680 *
1681 * On session close, the IPC is closed and the server must release all tcons of the session.
1682 * No need to send a tree disconnect here.
1683 *
1684 * Besides, it will make the server to not close durable and resilient files on session close, as
1685 * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1686 */
1687 static int
cifs_free_ipc(struct cifs_ses * ses)1688 cifs_free_ipc(struct cifs_ses *ses)
1689 {
1690 struct cifs_tcon *tcon = ses->tcon_ipc;
1691
1692 if (tcon == NULL)
1693 return 0;
1694
1695 tconInfoFree(tcon);
1696 ses->tcon_ipc = NULL;
1697 return 0;
1698 }
1699
1700 static struct cifs_ses *
cifs_find_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1701 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1702 {
1703 struct cifs_ses *ses;
1704
1705 spin_lock(&cifs_tcp_ses_lock);
1706 list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1707 if (ses->status == CifsExiting)
1708 continue;
1709 if (!match_session(ses, ctx))
1710 continue;
1711 ++ses->ses_count;
1712 spin_unlock(&cifs_tcp_ses_lock);
1713 return ses;
1714 }
1715 spin_unlock(&cifs_tcp_ses_lock);
1716 return NULL;
1717 }
1718
cifs_put_smb_ses(struct cifs_ses * ses)1719 void cifs_put_smb_ses(struct cifs_ses *ses)
1720 {
1721 unsigned int rc, xid;
1722 unsigned int chan_count;
1723 struct TCP_Server_Info *server = ses->server;
1724 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1725
1726 spin_lock(&cifs_tcp_ses_lock);
1727 if (ses->status == CifsExiting) {
1728 spin_unlock(&cifs_tcp_ses_lock);
1729 return;
1730 }
1731
1732 cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1733 cifs_dbg(FYI, "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->treeName : "NONE");
1734
1735 if (--ses->ses_count > 0) {
1736 spin_unlock(&cifs_tcp_ses_lock);
1737 return;
1738 }
1739 spin_unlock(&cifs_tcp_ses_lock);
1740
1741 /* ses_count can never go negative */
1742 WARN_ON(ses->ses_count < 0);
1743
1744 spin_lock(&GlobalMid_Lock);
1745 if (ses->status == CifsGood)
1746 ses->status = CifsExiting;
1747 spin_unlock(&GlobalMid_Lock);
1748
1749 cifs_free_ipc(ses);
1750
1751 if (ses->status == CifsExiting && server->ops->logoff) {
1752 xid = get_xid();
1753 rc = server->ops->logoff(xid, ses);
1754 if (rc)
1755 cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1756 __func__, rc);
1757 _free_xid(xid);
1758 }
1759
1760 spin_lock(&cifs_tcp_ses_lock);
1761 list_del_init(&ses->smb_ses_list);
1762 spin_unlock(&cifs_tcp_ses_lock);
1763
1764 spin_lock(&ses->chan_lock);
1765 chan_count = ses->chan_count;
1766 spin_unlock(&ses->chan_lock);
1767
1768 /* close any extra channels */
1769 if (chan_count > 1) {
1770 int i;
1771
1772 for (i = 1; i < chan_count; i++) {
1773 /*
1774 * note: for now, we're okay accessing ses->chans
1775 * without chan_lock. But when chans can go away, we'll
1776 * need to introduce ref counting to make sure that chan
1777 * is not freed from under us.
1778 */
1779 cifs_put_tcp_session(ses->chans[i].server, 0);
1780 ses->chans[i].server = NULL;
1781 }
1782 }
1783
1784 sesInfoFree(ses);
1785 cifs_put_tcp_session(server, 0);
1786 }
1787
1788 #ifdef CONFIG_KEYS
1789
1790 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
1791 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
1792
1793 /* Populate username and pw fields from keyring if possible */
1794 static int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)1795 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
1796 {
1797 int rc = 0;
1798 int is_domain = 0;
1799 const char *delim, *payload;
1800 char *desc;
1801 ssize_t len;
1802 struct key *key;
1803 struct TCP_Server_Info *server = ses->server;
1804 struct sockaddr_in *sa;
1805 struct sockaddr_in6 *sa6;
1806 const struct user_key_payload *upayload;
1807
1808 desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
1809 if (!desc)
1810 return -ENOMEM;
1811
1812 /* try to find an address key first */
1813 switch (server->dstaddr.ss_family) {
1814 case AF_INET:
1815 sa = (struct sockaddr_in *)&server->dstaddr;
1816 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
1817 break;
1818 case AF_INET6:
1819 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
1820 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
1821 break;
1822 default:
1823 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
1824 server->dstaddr.ss_family);
1825 rc = -EINVAL;
1826 goto out_err;
1827 }
1828
1829 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1830 key = request_key(&key_type_logon, desc, "");
1831 if (IS_ERR(key)) {
1832 if (!ses->domainName) {
1833 cifs_dbg(FYI, "domainName is NULL\n");
1834 rc = PTR_ERR(key);
1835 goto out_err;
1836 }
1837
1838 /* didn't work, try to find a domain key */
1839 sprintf(desc, "cifs:d:%s", ses->domainName);
1840 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
1841 key = request_key(&key_type_logon, desc, "");
1842 if (IS_ERR(key)) {
1843 rc = PTR_ERR(key);
1844 goto out_err;
1845 }
1846 is_domain = 1;
1847 }
1848
1849 down_read(&key->sem);
1850 upayload = user_key_payload_locked(key);
1851 if (IS_ERR_OR_NULL(upayload)) {
1852 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
1853 goto out_key_put;
1854 }
1855
1856 /* find first : in payload */
1857 payload = upayload->data;
1858 delim = strnchr(payload, upayload->datalen, ':');
1859 cifs_dbg(FYI, "payload=%s\n", payload);
1860 if (!delim) {
1861 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
1862 upayload->datalen);
1863 rc = -EINVAL;
1864 goto out_key_put;
1865 }
1866
1867 len = delim - payload;
1868 if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
1869 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
1870 len);
1871 rc = -EINVAL;
1872 goto out_key_put;
1873 }
1874
1875 ctx->username = kstrndup(payload, len, GFP_KERNEL);
1876 if (!ctx->username) {
1877 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
1878 len);
1879 rc = -ENOMEM;
1880 goto out_key_put;
1881 }
1882 cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
1883
1884 len = key->datalen - (len + 1);
1885 if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
1886 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
1887 rc = -EINVAL;
1888 kfree(ctx->username);
1889 ctx->username = NULL;
1890 goto out_key_put;
1891 }
1892
1893 ++delim;
1894 ctx->password = kstrndup(delim, len, GFP_KERNEL);
1895 if (!ctx->password) {
1896 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
1897 len);
1898 rc = -ENOMEM;
1899 kfree(ctx->username);
1900 ctx->username = NULL;
1901 goto out_key_put;
1902 }
1903
1904 /*
1905 * If we have a domain key then we must set the domainName in the
1906 * for the request.
1907 */
1908 if (is_domain && ses->domainName) {
1909 ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
1910 if (!ctx->domainname) {
1911 cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
1912 len);
1913 rc = -ENOMEM;
1914 kfree(ctx->username);
1915 ctx->username = NULL;
1916 kfree_sensitive(ctx->password);
1917 ctx->password = NULL;
1918 goto out_key_put;
1919 }
1920 }
1921
1922 out_key_put:
1923 up_read(&key->sem);
1924 key_put(key);
1925 out_err:
1926 kfree(desc);
1927 cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
1928 return rc;
1929 }
1930 #else /* ! CONFIG_KEYS */
1931 static inline int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)1932 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
1933 struct cifs_ses *ses __attribute__((unused)))
1934 {
1935 return -ENOSYS;
1936 }
1937 #endif /* CONFIG_KEYS */
1938
1939 /**
1940 * cifs_get_smb_ses - get a session matching @ctx data from @server
1941 * @server: server to setup the session to
1942 * @ctx: superblock configuration context to use to setup the session
1943 *
1944 * This function assumes it is being called from cifs_mount() where we
1945 * already got a server reference (server refcount +1). See
1946 * cifs_get_tcon() for refcount explanations.
1947 */
1948 struct cifs_ses *
cifs_get_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1949 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1950 {
1951 int rc = 0;
1952 unsigned int xid;
1953 struct cifs_ses *ses;
1954 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
1955 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
1956
1957 xid = get_xid();
1958
1959 ses = cifs_find_smb_ses(server, ctx);
1960 if (ses) {
1961 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
1962 ses->status);
1963
1964 mutex_lock(&ses->session_mutex);
1965 rc = cifs_negotiate_protocol(xid, ses);
1966 if (rc) {
1967 mutex_unlock(&ses->session_mutex);
1968 /* problem -- put our ses reference */
1969 cifs_put_smb_ses(ses);
1970 free_xid(xid);
1971 return ERR_PTR(rc);
1972 }
1973 if (ses->need_reconnect) {
1974 cifs_dbg(FYI, "Session needs reconnect\n");
1975 rc = cifs_setup_session(xid, ses,
1976 ctx->local_nls);
1977 if (rc) {
1978 mutex_unlock(&ses->session_mutex);
1979 /* problem -- put our reference */
1980 cifs_put_smb_ses(ses);
1981 free_xid(xid);
1982 return ERR_PTR(rc);
1983 }
1984 }
1985 mutex_unlock(&ses->session_mutex);
1986
1987 /* existing SMB ses has a server reference already */
1988 cifs_put_tcp_session(server, 0);
1989 free_xid(xid);
1990 return ses;
1991 }
1992
1993 rc = -ENOMEM;
1994
1995 cifs_dbg(FYI, "Existing smb sess not found\n");
1996 ses = sesInfoAlloc();
1997 if (ses == NULL)
1998 goto get_ses_fail;
1999
2000 /* new SMB session uses our server ref */
2001 ses->server = server;
2002 if (server->dstaddr.ss_family == AF_INET6)
2003 sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2004 else
2005 sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2006
2007 if (ctx->username) {
2008 ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2009 if (!ses->user_name)
2010 goto get_ses_fail;
2011 }
2012
2013 /* ctx->password freed at unmount */
2014 if (ctx->password) {
2015 ses->password = kstrdup(ctx->password, GFP_KERNEL);
2016 if (!ses->password)
2017 goto get_ses_fail;
2018 }
2019 if (ctx->domainname) {
2020 ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2021 if (!ses->domainName)
2022 goto get_ses_fail;
2023 }
2024 if (ctx->domainauto)
2025 ses->domainAuto = ctx->domainauto;
2026 ses->cred_uid = ctx->cred_uid;
2027 ses->linux_uid = ctx->linux_uid;
2028
2029 ses->sectype = ctx->sectype;
2030 ses->sign = ctx->sign;
2031 mutex_lock(&ses->session_mutex);
2032
2033 /* add server as first channel */
2034 spin_lock(&ses->chan_lock);
2035 ses->chans[0].server = server;
2036 ses->chan_count = 1;
2037 ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2038 spin_unlock(&ses->chan_lock);
2039
2040 rc = cifs_negotiate_protocol(xid, ses);
2041 if (!rc)
2042 rc = cifs_setup_session(xid, ses, ctx->local_nls);
2043
2044 /* each channel uses a different signing key */
2045 memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2046 sizeof(ses->smb3signingkey));
2047
2048 mutex_unlock(&ses->session_mutex);
2049 if (rc)
2050 goto get_ses_fail;
2051
2052 /* success, put it on the list and add it as first channel */
2053 spin_lock(&cifs_tcp_ses_lock);
2054 list_add(&ses->smb_ses_list, &server->smb_ses_list);
2055 spin_unlock(&cifs_tcp_ses_lock);
2056
2057 free_xid(xid);
2058
2059 cifs_setup_ipc(ses, ctx);
2060
2061 return ses;
2062
2063 get_ses_fail:
2064 sesInfoFree(ses);
2065 free_xid(xid);
2066 return ERR_PTR(rc);
2067 }
2068
match_tcon(struct cifs_tcon * tcon,struct smb3_fs_context * ctx)2069 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2070 {
2071 if (tcon->tidStatus == CifsExiting)
2072 return 0;
2073 if (strncmp(tcon->treeName, ctx->UNC, MAX_TREE_SIZE))
2074 return 0;
2075 if (tcon->seal != ctx->seal)
2076 return 0;
2077 if (tcon->snapshot_time != ctx->snapshot_time)
2078 return 0;
2079 if (tcon->handle_timeout != ctx->handle_timeout)
2080 return 0;
2081 if (tcon->no_lease != ctx->no_lease)
2082 return 0;
2083 if (tcon->nodelete != ctx->nodelete)
2084 return 0;
2085 return 1;
2086 }
2087
2088 static struct cifs_tcon *
cifs_find_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2089 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2090 {
2091 struct list_head *tmp;
2092 struct cifs_tcon *tcon;
2093
2094 spin_lock(&cifs_tcp_ses_lock);
2095 list_for_each(tmp, &ses->tcon_list) {
2096 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2097
2098 if (!match_tcon(tcon, ctx))
2099 continue;
2100 ++tcon->tc_count;
2101 spin_unlock(&cifs_tcp_ses_lock);
2102 return tcon;
2103 }
2104 spin_unlock(&cifs_tcp_ses_lock);
2105 return NULL;
2106 }
2107
2108 void
cifs_put_tcon(struct cifs_tcon * tcon)2109 cifs_put_tcon(struct cifs_tcon *tcon)
2110 {
2111 unsigned int xid;
2112 struct cifs_ses *ses;
2113
2114 /*
2115 * IPC tcon share the lifetime of their session and are
2116 * destroyed in the session put function
2117 */
2118 if (tcon == NULL || tcon->ipc)
2119 return;
2120
2121 ses = tcon->ses;
2122 cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2123 spin_lock(&cifs_tcp_ses_lock);
2124 if (--tcon->tc_count > 0) {
2125 spin_unlock(&cifs_tcp_ses_lock);
2126 return;
2127 }
2128
2129 /* tc_count can never go negative */
2130 WARN_ON(tcon->tc_count < 0);
2131
2132 if (tcon->use_witness) {
2133 int rc;
2134
2135 rc = cifs_swn_unregister(tcon);
2136 if (rc < 0) {
2137 cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2138 __func__, rc);
2139 }
2140 }
2141
2142 list_del_init(&tcon->tcon_list);
2143 spin_unlock(&cifs_tcp_ses_lock);
2144
2145 xid = get_xid();
2146 if (ses->server->ops->tree_disconnect)
2147 ses->server->ops->tree_disconnect(xid, tcon);
2148 _free_xid(xid);
2149
2150 cifs_fscache_release_super_cookie(tcon);
2151 tconInfoFree(tcon);
2152 cifs_put_smb_ses(ses);
2153 }
2154
2155 /**
2156 * cifs_get_tcon - get a tcon matching @ctx data from @ses
2157 * @ses: smb session to issue the request on
2158 * @ctx: the superblock configuration context to use for building the
2159 *
2160 * - tcon refcount is the number of mount points using the tcon.
2161 * - ses refcount is the number of tcon using the session.
2162 *
2163 * 1. This function assumes it is being called from cifs_mount() where
2164 * we already got a session reference (ses refcount +1).
2165 *
2166 * 2. Since we're in the context of adding a mount point, the end
2167 * result should be either:
2168 *
2169 * a) a new tcon already allocated with refcount=1 (1 mount point) and
2170 * its session refcount incremented (1 new tcon). This +1 was
2171 * already done in (1).
2172 *
2173 * b) an existing tcon with refcount+1 (add a mount point to it) and
2174 * identical ses refcount (no new tcon). Because of (1) we need to
2175 * decrement the ses refcount.
2176 */
2177 static struct cifs_tcon *
cifs_get_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2178 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2179 {
2180 int rc, xid;
2181 struct cifs_tcon *tcon;
2182
2183 tcon = cifs_find_tcon(ses, ctx);
2184 if (tcon) {
2185 /*
2186 * tcon has refcount already incremented but we need to
2187 * decrement extra ses reference gotten by caller (case b)
2188 */
2189 cifs_dbg(FYI, "Found match on UNC path\n");
2190 cifs_put_smb_ses(ses);
2191 return tcon;
2192 }
2193
2194 if (!ses->server->ops->tree_connect) {
2195 rc = -ENOSYS;
2196 goto out_fail;
2197 }
2198
2199 tcon = tconInfoAlloc();
2200 if (tcon == NULL) {
2201 rc = -ENOMEM;
2202 goto out_fail;
2203 }
2204
2205 if (ctx->snapshot_time) {
2206 if (ses->server->vals->protocol_id == 0) {
2207 cifs_dbg(VFS,
2208 "Use SMB2 or later for snapshot mount option\n");
2209 rc = -EOPNOTSUPP;
2210 goto out_fail;
2211 } else
2212 tcon->snapshot_time = ctx->snapshot_time;
2213 }
2214
2215 if (ctx->handle_timeout) {
2216 if (ses->server->vals->protocol_id == 0) {
2217 cifs_dbg(VFS,
2218 "Use SMB2.1 or later for handle timeout option\n");
2219 rc = -EOPNOTSUPP;
2220 goto out_fail;
2221 } else
2222 tcon->handle_timeout = ctx->handle_timeout;
2223 }
2224
2225 tcon->ses = ses;
2226 if (ctx->password) {
2227 tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2228 if (!tcon->password) {
2229 rc = -ENOMEM;
2230 goto out_fail;
2231 }
2232 }
2233
2234 if (ctx->seal) {
2235 if (ses->server->vals->protocol_id == 0) {
2236 cifs_dbg(VFS,
2237 "SMB3 or later required for encryption\n");
2238 rc = -EOPNOTSUPP;
2239 goto out_fail;
2240 } else if (tcon->ses->server->capabilities &
2241 SMB2_GLOBAL_CAP_ENCRYPTION)
2242 tcon->seal = true;
2243 else {
2244 cifs_dbg(VFS, "Encryption is not supported on share\n");
2245 rc = -EOPNOTSUPP;
2246 goto out_fail;
2247 }
2248 }
2249
2250 if (ctx->linux_ext) {
2251 if (ses->server->posix_ext_supported) {
2252 tcon->posix_extensions = true;
2253 pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2254 } else {
2255 cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2256 rc = -EOPNOTSUPP;
2257 goto out_fail;
2258 }
2259 }
2260
2261 /*
2262 * BB Do we need to wrap session_mutex around this TCon call and Unix
2263 * SetFS as we do on SessSetup and reconnect?
2264 */
2265 xid = get_xid();
2266 rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2267 ctx->local_nls);
2268 free_xid(xid);
2269 cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2270 if (rc)
2271 goto out_fail;
2272
2273 tcon->use_persistent = false;
2274 /* check if SMB2 or later, CIFS does not support persistent handles */
2275 if (ctx->persistent) {
2276 if (ses->server->vals->protocol_id == 0) {
2277 cifs_dbg(VFS,
2278 "SMB3 or later required for persistent handles\n");
2279 rc = -EOPNOTSUPP;
2280 goto out_fail;
2281 } else if (ses->server->capabilities &
2282 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2283 tcon->use_persistent = true;
2284 else /* persistent handles requested but not supported */ {
2285 cifs_dbg(VFS,
2286 "Persistent handles not supported on share\n");
2287 rc = -EOPNOTSUPP;
2288 goto out_fail;
2289 }
2290 } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2291 && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2292 && (ctx->nopersistent == false)) {
2293 cifs_dbg(FYI, "enabling persistent handles\n");
2294 tcon->use_persistent = true;
2295 } else if (ctx->resilient) {
2296 if (ses->server->vals->protocol_id == 0) {
2297 cifs_dbg(VFS,
2298 "SMB2.1 or later required for resilient handles\n");
2299 rc = -EOPNOTSUPP;
2300 goto out_fail;
2301 }
2302 tcon->use_resilient = true;
2303 }
2304
2305 tcon->use_witness = false;
2306 if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2307 if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2308 if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2309 /*
2310 * Set witness in use flag in first place
2311 * to retry registration in the echo task
2312 */
2313 tcon->use_witness = true;
2314 /* And try to register immediately */
2315 rc = cifs_swn_register(tcon);
2316 if (rc < 0) {
2317 cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2318 goto out_fail;
2319 }
2320 } else {
2321 /* TODO: try to extend for non-cluster uses (eg multichannel) */
2322 cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2323 rc = -EOPNOTSUPP;
2324 goto out_fail;
2325 }
2326 } else {
2327 cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2328 rc = -EOPNOTSUPP;
2329 goto out_fail;
2330 }
2331 }
2332
2333 /* If the user really knows what they are doing they can override */
2334 if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2335 if (ctx->cache_ro)
2336 cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2337 else if (ctx->cache_rw)
2338 cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2339 }
2340
2341 if (ctx->no_lease) {
2342 if (ses->server->vals->protocol_id == 0) {
2343 cifs_dbg(VFS,
2344 "SMB2 or later required for nolease option\n");
2345 rc = -EOPNOTSUPP;
2346 goto out_fail;
2347 } else
2348 tcon->no_lease = ctx->no_lease;
2349 }
2350
2351 /*
2352 * We can have only one retry value for a connection to a share so for
2353 * resources mounted more than once to the same server share the last
2354 * value passed in for the retry flag is used.
2355 */
2356 tcon->retry = ctx->retry;
2357 tcon->nocase = ctx->nocase;
2358 if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2359 tcon->nohandlecache = ctx->nohandlecache;
2360 else
2361 tcon->nohandlecache = true;
2362 tcon->nodelete = ctx->nodelete;
2363 tcon->local_lease = ctx->local_lease;
2364 INIT_LIST_HEAD(&tcon->pending_opens);
2365
2366 spin_lock(&cifs_tcp_ses_lock);
2367 list_add(&tcon->tcon_list, &ses->tcon_list);
2368 spin_unlock(&cifs_tcp_ses_lock);
2369
2370 cifs_fscache_get_super_cookie(tcon);
2371
2372 return tcon;
2373
2374 out_fail:
2375 tconInfoFree(tcon);
2376 return ERR_PTR(rc);
2377 }
2378
2379 void
cifs_put_tlink(struct tcon_link * tlink)2380 cifs_put_tlink(struct tcon_link *tlink)
2381 {
2382 if (!tlink || IS_ERR(tlink))
2383 return;
2384
2385 if (!atomic_dec_and_test(&tlink->tl_count) ||
2386 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2387 tlink->tl_time = jiffies;
2388 return;
2389 }
2390
2391 if (!IS_ERR(tlink_tcon(tlink)))
2392 cifs_put_tcon(tlink_tcon(tlink));
2393 kfree(tlink);
2394 return;
2395 }
2396
2397 static int
compare_mount_options(struct super_block * sb,struct cifs_mnt_data * mnt_data)2398 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2399 {
2400 struct cifs_sb_info *old = CIFS_SB(sb);
2401 struct cifs_sb_info *new = mnt_data->cifs_sb;
2402 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2403 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2404
2405 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2406 return 0;
2407
2408 if (old->mnt_cifs_serverino_autodisabled)
2409 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2410
2411 if (oldflags != newflags)
2412 return 0;
2413
2414 /*
2415 * We want to share sb only if we don't specify an r/wsize or
2416 * specified r/wsize is greater than or equal to existing one.
2417 */
2418 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2419 return 0;
2420
2421 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2422 return 0;
2423
2424 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2425 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2426 return 0;
2427
2428 if (old->ctx->file_mode != new->ctx->file_mode ||
2429 old->ctx->dir_mode != new->ctx->dir_mode)
2430 return 0;
2431
2432 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2433 return 0;
2434
2435 if (old->ctx->acregmax != new->ctx->acregmax)
2436 return 0;
2437 if (old->ctx->acdirmax != new->ctx->acdirmax)
2438 return 0;
2439 if (old->ctx->closetimeo != new->ctx->closetimeo)
2440 return 0;
2441
2442 return 1;
2443 }
2444
2445 static int
match_prepath(struct super_block * sb,struct cifs_mnt_data * mnt_data)2446 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2447 {
2448 struct cifs_sb_info *old = CIFS_SB(sb);
2449 struct cifs_sb_info *new = mnt_data->cifs_sb;
2450 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2451 old->prepath;
2452 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2453 new->prepath;
2454
2455 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2456 return 1;
2457 else if (!old_set && !new_set)
2458 return 1;
2459
2460 return 0;
2461 }
2462
2463 int
cifs_match_super(struct super_block * sb,void * data)2464 cifs_match_super(struct super_block *sb, void *data)
2465 {
2466 struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
2467 struct smb3_fs_context *ctx;
2468 struct cifs_sb_info *cifs_sb;
2469 struct TCP_Server_Info *tcp_srv;
2470 struct cifs_ses *ses;
2471 struct cifs_tcon *tcon;
2472 struct tcon_link *tlink;
2473 int rc = 0;
2474
2475 spin_lock(&cifs_tcp_ses_lock);
2476 cifs_sb = CIFS_SB(sb);
2477
2478 /* We do not want to use a superblock that has been shutdown */
2479 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2480 spin_unlock(&cifs_tcp_ses_lock);
2481 return 0;
2482 }
2483
2484 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2485 if (tlink == NULL) {
2486 /* can not match superblock if tlink were ever null */
2487 spin_unlock(&cifs_tcp_ses_lock);
2488 return 0;
2489 }
2490 tcon = tlink_tcon(tlink);
2491 ses = tcon->ses;
2492 tcp_srv = ses->server;
2493
2494 ctx = mnt_data->ctx;
2495
2496 if (!match_server(tcp_srv, ctx) ||
2497 !match_session(ses, ctx) ||
2498 !match_tcon(tcon, ctx) ||
2499 !match_prepath(sb, mnt_data)) {
2500 rc = 0;
2501 goto out;
2502 }
2503
2504 rc = compare_mount_options(sb, mnt_data);
2505 out:
2506 spin_unlock(&cifs_tcp_ses_lock);
2507 cifs_put_tlink(tlink);
2508 return rc;
2509 }
2510
2511 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2512 static struct lock_class_key cifs_key[2];
2513 static struct lock_class_key cifs_slock_key[2];
2514
2515 static inline void
cifs_reclassify_socket4(struct socket * sock)2516 cifs_reclassify_socket4(struct socket *sock)
2517 {
2518 struct sock *sk = sock->sk;
2519 BUG_ON(!sock_allow_reclassification(sk));
2520 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2521 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2522 }
2523
2524 static inline void
cifs_reclassify_socket6(struct socket * sock)2525 cifs_reclassify_socket6(struct socket *sock)
2526 {
2527 struct sock *sk = sock->sk;
2528 BUG_ON(!sock_allow_reclassification(sk));
2529 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2530 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2531 }
2532 #else
2533 static inline void
cifs_reclassify_socket4(struct socket * sock)2534 cifs_reclassify_socket4(struct socket *sock)
2535 {
2536 }
2537
2538 static inline void
cifs_reclassify_socket6(struct socket * sock)2539 cifs_reclassify_socket6(struct socket *sock)
2540 {
2541 }
2542 #endif
2543
2544 /* See RFC1001 section 14 on representation of Netbios names */
rfc1002mangle(char * target,char * source,unsigned int length)2545 static void rfc1002mangle(char *target, char *source, unsigned int length)
2546 {
2547 unsigned int i, j;
2548
2549 for (i = 0, j = 0; i < (length); i++) {
2550 /* mask a nibble at a time and encode */
2551 target[j] = 'A' + (0x0F & (source[i] >> 4));
2552 target[j+1] = 'A' + (0x0F & source[i]);
2553 j += 2;
2554 }
2555
2556 }
2557
2558 static int
bind_socket(struct TCP_Server_Info * server)2559 bind_socket(struct TCP_Server_Info *server)
2560 {
2561 int rc = 0;
2562 if (server->srcaddr.ss_family != AF_UNSPEC) {
2563 /* Bind to the specified local IP address */
2564 struct socket *socket = server->ssocket;
2565 rc = socket->ops->bind(socket,
2566 (struct sockaddr *) &server->srcaddr,
2567 sizeof(server->srcaddr));
2568 if (rc < 0) {
2569 struct sockaddr_in *saddr4;
2570 struct sockaddr_in6 *saddr6;
2571 saddr4 = (struct sockaddr_in *)&server->srcaddr;
2572 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2573 if (saddr6->sin6_family == AF_INET6)
2574 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2575 &saddr6->sin6_addr, rc);
2576 else
2577 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2578 &saddr4->sin_addr.s_addr, rc);
2579 }
2580 }
2581 return rc;
2582 }
2583
2584 static int
ip_rfc1001_connect(struct TCP_Server_Info * server)2585 ip_rfc1001_connect(struct TCP_Server_Info *server)
2586 {
2587 int rc = 0;
2588 /*
2589 * some servers require RFC1001 sessinit before sending
2590 * negprot - BB check reconnection in case where second
2591 * sessinit is sent but no second negprot
2592 */
2593 struct rfc1002_session_packet *ses_init_buf;
2594 struct smb_hdr *smb_buf;
2595 ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2596 GFP_KERNEL);
2597 if (ses_init_buf) {
2598 ses_init_buf->trailer.session_req.called_len = 32;
2599
2600 if (server->server_RFC1001_name[0] != 0)
2601 rfc1002mangle(ses_init_buf->trailer.
2602 session_req.called_name,
2603 server->server_RFC1001_name,
2604 RFC1001_NAME_LEN_WITH_NULL);
2605 else
2606 rfc1002mangle(ses_init_buf->trailer.
2607 session_req.called_name,
2608 DEFAULT_CIFS_CALLED_NAME,
2609 RFC1001_NAME_LEN_WITH_NULL);
2610
2611 ses_init_buf->trailer.session_req.calling_len = 32;
2612
2613 /*
2614 * calling name ends in null (byte 16) from old smb
2615 * convention.
2616 */
2617 if (server->workstation_RFC1001_name[0] != 0)
2618 rfc1002mangle(ses_init_buf->trailer.
2619 session_req.calling_name,
2620 server->workstation_RFC1001_name,
2621 RFC1001_NAME_LEN_WITH_NULL);
2622 else
2623 rfc1002mangle(ses_init_buf->trailer.
2624 session_req.calling_name,
2625 "LINUX_CIFS_CLNT",
2626 RFC1001_NAME_LEN_WITH_NULL);
2627
2628 ses_init_buf->trailer.session_req.scope1 = 0;
2629 ses_init_buf->trailer.session_req.scope2 = 0;
2630 smb_buf = (struct smb_hdr *)ses_init_buf;
2631
2632 /* sizeof RFC1002_SESSION_REQUEST with no scope */
2633 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2634 rc = smb_send(server, smb_buf, 0x44);
2635 kfree(ses_init_buf);
2636 /*
2637 * RFC1001 layer in at least one server
2638 * requires very short break before negprot
2639 * presumably because not expecting negprot
2640 * to follow so fast. This is a simple
2641 * solution that works without
2642 * complicating the code and causes no
2643 * significant slowing down on mount
2644 * for everyone else
2645 */
2646 usleep_range(1000, 2000);
2647 }
2648 /*
2649 * else the negprot may still work without this
2650 * even though malloc failed
2651 */
2652
2653 return rc;
2654 }
2655
2656 static int
generic_ip_connect(struct TCP_Server_Info * server)2657 generic_ip_connect(struct TCP_Server_Info *server)
2658 {
2659 int rc = 0;
2660 __be16 sport;
2661 int slen, sfamily;
2662 struct socket *socket = server->ssocket;
2663 struct sockaddr *saddr;
2664
2665 saddr = (struct sockaddr *) &server->dstaddr;
2666
2667 if (server->dstaddr.ss_family == AF_INET6) {
2668 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2669
2670 sport = ipv6->sin6_port;
2671 slen = sizeof(struct sockaddr_in6);
2672 sfamily = AF_INET6;
2673 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2674 ntohs(sport));
2675 } else {
2676 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2677
2678 sport = ipv4->sin_port;
2679 slen = sizeof(struct sockaddr_in);
2680 sfamily = AF_INET;
2681 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2682 ntohs(sport));
2683 }
2684
2685 if (socket == NULL) {
2686 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2687 IPPROTO_TCP, &socket, 1);
2688 if (rc < 0) {
2689 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2690 server->ssocket = NULL;
2691 return rc;
2692 }
2693
2694 /* BB other socket options to set KEEPALIVE, NODELAY? */
2695 cifs_dbg(FYI, "Socket created\n");
2696 server->ssocket = socket;
2697 socket->sk->sk_allocation = GFP_NOFS;
2698 if (sfamily == AF_INET6)
2699 cifs_reclassify_socket6(socket);
2700 else
2701 cifs_reclassify_socket4(socket);
2702 }
2703
2704 rc = bind_socket(server);
2705 if (rc < 0)
2706 return rc;
2707
2708 /*
2709 * Eventually check for other socket options to change from
2710 * the default. sock_setsockopt not used because it expects
2711 * user space buffer
2712 */
2713 socket->sk->sk_rcvtimeo = 7 * HZ;
2714 socket->sk->sk_sndtimeo = 5 * HZ;
2715
2716 /* make the bufsizes depend on wsize/rsize and max requests */
2717 if (server->noautotune) {
2718 if (socket->sk->sk_sndbuf < (200 * 1024))
2719 socket->sk->sk_sndbuf = 200 * 1024;
2720 if (socket->sk->sk_rcvbuf < (140 * 1024))
2721 socket->sk->sk_rcvbuf = 140 * 1024;
2722 }
2723
2724 if (server->tcp_nodelay)
2725 tcp_sock_set_nodelay(socket->sk);
2726
2727 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2728 socket->sk->sk_sndbuf,
2729 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2730
2731 rc = socket->ops->connect(socket, saddr, slen,
2732 server->noblockcnt ? O_NONBLOCK : 0);
2733 /*
2734 * When mounting SMB root file systems, we do not want to block in
2735 * connect. Otherwise bail out and then let cifs_reconnect() perform
2736 * reconnect failover - if possible.
2737 */
2738 if (server->noblockcnt && rc == -EINPROGRESS)
2739 rc = 0;
2740 if (rc < 0) {
2741 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
2742 sock_release(socket);
2743 server->ssocket = NULL;
2744 return rc;
2745 }
2746
2747 if (sport == htons(RFC1001_PORT))
2748 rc = ip_rfc1001_connect(server);
2749
2750 return rc;
2751 }
2752
2753 static int
ip_connect(struct TCP_Server_Info * server)2754 ip_connect(struct TCP_Server_Info *server)
2755 {
2756 __be16 *sport;
2757 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2758 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2759
2760 if (server->dstaddr.ss_family == AF_INET6)
2761 sport = &addr6->sin6_port;
2762 else
2763 sport = &addr->sin_port;
2764
2765 if (*sport == 0) {
2766 int rc;
2767
2768 /* try with 445 port at first */
2769 *sport = htons(CIFS_PORT);
2770
2771 rc = generic_ip_connect(server);
2772 if (rc >= 0)
2773 return rc;
2774
2775 /* if it failed, try with 139 port */
2776 *sport = htons(RFC1001_PORT);
2777 }
2778
2779 return generic_ip_connect(server);
2780 }
2781
reset_cifs_unix_caps(unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)2782 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
2783 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
2784 {
2785 /*
2786 * If we are reconnecting then should we check to see if
2787 * any requested capabilities changed locally e.g. via
2788 * remount but we can not do much about it here
2789 * if they have (even if we could detect it by the following)
2790 * Perhaps we could add a backpointer to array of sb from tcon
2791 * or if we change to make all sb to same share the same
2792 * sb as NFS - then we only have one backpointer to sb.
2793 * What if we wanted to mount the server share twice once with
2794 * and once without posixacls or posix paths?
2795 */
2796 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2797
2798 if (ctx && ctx->no_linux_ext) {
2799 tcon->fsUnixInfo.Capability = 0;
2800 tcon->unix_ext = 0; /* Unix Extensions disabled */
2801 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
2802 return;
2803 } else if (ctx)
2804 tcon->unix_ext = 1; /* Unix Extensions supported */
2805
2806 if (!tcon->unix_ext) {
2807 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
2808 return;
2809 }
2810
2811 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
2812 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
2813 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
2814 /*
2815 * check for reconnect case in which we do not
2816 * want to change the mount behavior if we can avoid it
2817 */
2818 if (ctx == NULL) {
2819 /*
2820 * turn off POSIX ACL and PATHNAMES if not set
2821 * originally at mount time
2822 */
2823 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
2824 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2825 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2826 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2827 cifs_dbg(VFS, "POSIXPATH support change\n");
2828 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2829 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
2830 cifs_dbg(VFS, "possible reconnect error\n");
2831 cifs_dbg(VFS, "server disabled POSIX path support\n");
2832 }
2833 }
2834
2835 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2836 cifs_dbg(VFS, "per-share encryption not supported yet\n");
2837
2838 cap &= CIFS_UNIX_CAP_MASK;
2839 if (ctx && ctx->no_psx_acl)
2840 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
2841 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
2842 cifs_dbg(FYI, "negotiated posix acl support\n");
2843 if (cifs_sb)
2844 cifs_sb->mnt_cifs_flags |=
2845 CIFS_MOUNT_POSIXACL;
2846 }
2847
2848 if (ctx && ctx->posix_paths == 0)
2849 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
2850 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2851 cifs_dbg(FYI, "negotiate posix pathnames\n");
2852 if (cifs_sb)
2853 cifs_sb->mnt_cifs_flags |=
2854 CIFS_MOUNT_POSIX_PATHS;
2855 }
2856
2857 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
2858 #ifdef CONFIG_CIFS_DEBUG2
2859 if (cap & CIFS_UNIX_FCNTL_CAP)
2860 cifs_dbg(FYI, "FCNTL cap\n");
2861 if (cap & CIFS_UNIX_EXTATTR_CAP)
2862 cifs_dbg(FYI, "EXTATTR cap\n");
2863 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
2864 cifs_dbg(FYI, "POSIX path cap\n");
2865 if (cap & CIFS_UNIX_XATTR_CAP)
2866 cifs_dbg(FYI, "XATTR cap\n");
2867 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
2868 cifs_dbg(FYI, "POSIX ACL cap\n");
2869 if (cap & CIFS_UNIX_LARGE_READ_CAP)
2870 cifs_dbg(FYI, "very large read cap\n");
2871 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
2872 cifs_dbg(FYI, "very large write cap\n");
2873 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
2874 cifs_dbg(FYI, "transport encryption cap\n");
2875 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
2876 cifs_dbg(FYI, "mandatory transport encryption cap\n");
2877 #endif /* CIFS_DEBUG2 */
2878 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
2879 if (ctx == NULL)
2880 cifs_dbg(FYI, "resetting capabilities failed\n");
2881 else
2882 cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
2883
2884 }
2885 }
2886 }
2887
cifs_setup_cifs_sb(struct cifs_sb_info * cifs_sb)2888 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
2889 {
2890 struct smb3_fs_context *ctx = cifs_sb->ctx;
2891
2892 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
2893
2894 spin_lock_init(&cifs_sb->tlink_tree_lock);
2895 cifs_sb->tlink_tree = RB_ROOT;
2896
2897 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
2898 ctx->file_mode, ctx->dir_mode);
2899
2900 /* this is needed for ASCII cp to Unicode converts */
2901 if (ctx->iocharset == NULL) {
2902 /* load_nls_default cannot return null */
2903 cifs_sb->local_nls = load_nls_default();
2904 } else {
2905 cifs_sb->local_nls = load_nls(ctx->iocharset);
2906 if (cifs_sb->local_nls == NULL) {
2907 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
2908 ctx->iocharset);
2909 return -ELIBACC;
2910 }
2911 }
2912 ctx->local_nls = cifs_sb->local_nls;
2913
2914 smb3_update_mnt_flags(cifs_sb);
2915
2916 if (ctx->direct_io)
2917 cifs_dbg(FYI, "mounting share using direct i/o\n");
2918 if (ctx->cache_ro) {
2919 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
2920 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
2921 } else if (ctx->cache_rw) {
2922 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
2923 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
2924 CIFS_MOUNT_RW_CACHE);
2925 }
2926
2927 if ((ctx->cifs_acl) && (ctx->dynperm))
2928 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
2929
2930 if (ctx->prepath) {
2931 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
2932 if (cifs_sb->prepath == NULL)
2933 return -ENOMEM;
2934 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
2935 }
2936
2937 return 0;
2938 }
2939
2940 /* Release all succeed connections */
mount_put_conns(struct mount_ctx * mnt_ctx)2941 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
2942 {
2943 int rc = 0;
2944
2945 if (mnt_ctx->tcon)
2946 cifs_put_tcon(mnt_ctx->tcon);
2947 else if (mnt_ctx->ses)
2948 cifs_put_smb_ses(mnt_ctx->ses);
2949 else if (mnt_ctx->server)
2950 cifs_put_tcp_session(mnt_ctx->server, 0);
2951 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
2952 free_xid(mnt_ctx->xid);
2953 }
2954
2955 /* Get connections for tcp, ses and tcon */
mount_get_conns(struct mount_ctx * mnt_ctx)2956 static int mount_get_conns(struct mount_ctx *mnt_ctx)
2957 {
2958 int rc = 0;
2959 struct TCP_Server_Info *server = NULL;
2960 struct cifs_ses *ses = NULL;
2961 struct cifs_tcon *tcon = NULL;
2962 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
2963 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
2964 unsigned int xid;
2965
2966 xid = get_xid();
2967
2968 /* get a reference to a tcp session */
2969 server = cifs_get_tcp_session(ctx);
2970 if (IS_ERR(server)) {
2971 rc = PTR_ERR(server);
2972 server = NULL;
2973 goto out;
2974 }
2975
2976 /* get a reference to a SMB session */
2977 ses = cifs_get_smb_ses(server, ctx);
2978 if (IS_ERR(ses)) {
2979 rc = PTR_ERR(ses);
2980 ses = NULL;
2981 goto out;
2982 }
2983
2984 if ((ctx->persistent == true) && (!(ses->server->capabilities &
2985 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
2986 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
2987 rc = -EOPNOTSUPP;
2988 goto out;
2989 }
2990
2991 /* search for existing tcon to this server share */
2992 tcon = cifs_get_tcon(ses, ctx);
2993 if (IS_ERR(tcon)) {
2994 rc = PTR_ERR(tcon);
2995 tcon = NULL;
2996 goto out;
2997 }
2998
2999 /* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3000 if (tcon->posix_extensions)
3001 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3002
3003 /* tell server which Unix caps we support */
3004 if (cap_unix(tcon->ses)) {
3005 /*
3006 * reset of caps checks mount to see if unix extensions disabled
3007 * for just this mount.
3008 */
3009 reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3010 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3011 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3012 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3013 rc = -EACCES;
3014 goto out;
3015 }
3016 } else
3017 tcon->unix_ext = 0; /* server does not support them */
3018
3019 /* do not care if a following call succeed - informational */
3020 if (!tcon->pipe && server->ops->qfs_tcon) {
3021 server->ops->qfs_tcon(xid, tcon, cifs_sb);
3022 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3023 if (tcon->fsDevInfo.DeviceCharacteristics &
3024 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3025 cifs_dbg(VFS, "mounted to read only share\n");
3026 else if ((cifs_sb->mnt_cifs_flags &
3027 CIFS_MOUNT_RW_CACHE) == 0)
3028 cifs_dbg(VFS, "read only mount of RW share\n");
3029 /* no need to log a RW mount of a typical RW share */
3030 }
3031 }
3032
3033 /*
3034 * Clamp the rsize/wsize mount arguments if they are too big for the server
3035 * and set the rsize/wsize to the negotiated values if not passed in by
3036 * the user on mount
3037 */
3038 if ((cifs_sb->ctx->wsize == 0) ||
3039 (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3040 cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3041 if ((cifs_sb->ctx->rsize == 0) ||
3042 (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3043 cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3044
3045 out:
3046 mnt_ctx->server = server;
3047 mnt_ctx->ses = ses;
3048 mnt_ctx->tcon = tcon;
3049 mnt_ctx->xid = xid;
3050
3051 return rc;
3052 }
3053
mount_setup_tlink(struct cifs_sb_info * cifs_sb,struct cifs_ses * ses,struct cifs_tcon * tcon)3054 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3055 struct cifs_tcon *tcon)
3056 {
3057 struct tcon_link *tlink;
3058
3059 /* hang the tcon off of the superblock */
3060 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3061 if (tlink == NULL)
3062 return -ENOMEM;
3063
3064 tlink->tl_uid = ses->linux_uid;
3065 tlink->tl_tcon = tcon;
3066 tlink->tl_time = jiffies;
3067 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3068 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3069
3070 cifs_sb->master_tlink = tlink;
3071 spin_lock(&cifs_sb->tlink_tree_lock);
3072 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3073 spin_unlock(&cifs_sb->tlink_tree_lock);
3074
3075 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3076 TLINK_IDLE_EXPIRE);
3077 return 0;
3078 }
3079
3080 #ifdef CONFIG_CIFS_DFS_UPCALL
3081 /* Get unique dfs connections */
mount_get_dfs_conns(struct mount_ctx * mnt_ctx)3082 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3083 {
3084 int rc;
3085
3086 mnt_ctx->fs_ctx->nosharesock = true;
3087 rc = mount_get_conns(mnt_ctx);
3088 if (mnt_ctx->server) {
3089 cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3090 spin_lock(&cifs_tcp_ses_lock);
3091 mnt_ctx->server->is_dfs_conn = true;
3092 spin_unlock(&cifs_tcp_ses_lock);
3093 }
3094 return rc;
3095 }
3096
3097 /*
3098 * cifs_build_path_to_root returns full path to root when we do not have an
3099 * existing connection (tcon)
3100 */
3101 static char *
build_unc_path_to_root(const struct smb3_fs_context * ctx,const struct cifs_sb_info * cifs_sb,bool useppath)3102 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3103 const struct cifs_sb_info *cifs_sb, bool useppath)
3104 {
3105 char *full_path, *pos;
3106 unsigned int pplen = useppath && ctx->prepath ?
3107 strlen(ctx->prepath) + 1 : 0;
3108 unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3109
3110 if (unc_len > MAX_TREE_SIZE)
3111 return ERR_PTR(-EINVAL);
3112
3113 full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3114 if (full_path == NULL)
3115 return ERR_PTR(-ENOMEM);
3116
3117 memcpy(full_path, ctx->UNC, unc_len);
3118 pos = full_path + unc_len;
3119
3120 if (pplen) {
3121 *pos = CIFS_DIR_SEP(cifs_sb);
3122 memcpy(pos + 1, ctx->prepath, pplen);
3123 pos += pplen;
3124 }
3125
3126 *pos = '\0'; /* add trailing null */
3127 convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3128 cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3129 return full_path;
3130 }
3131
3132 /*
3133 * expand_dfs_referral - Update cifs_sb from dfs referral path
3134 *
3135 * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3136 * submount. Otherwise it will be left untouched.
3137 */
expand_dfs_referral(struct mount_ctx * mnt_ctx,const char * full_path,struct dfs_info3_param * referral)3138 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3139 struct dfs_info3_param *referral)
3140 {
3141 int rc;
3142 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3143 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3144 char *fake_devname = NULL, *mdata = NULL;
3145
3146 mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3147 &fake_devname);
3148 if (IS_ERR(mdata)) {
3149 rc = PTR_ERR(mdata);
3150 mdata = NULL;
3151 } else {
3152 /*
3153 * We can not clear out the whole structure since we no longer have an explicit
3154 * function to parse a mount-string. Instead we need to clear out the individual
3155 * fields that are no longer valid.
3156 */
3157 kfree(ctx->prepath);
3158 ctx->prepath = NULL;
3159 rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3160 }
3161 kfree(fake_devname);
3162 kfree(cifs_sb->ctx->mount_options);
3163 cifs_sb->ctx->mount_options = mdata;
3164
3165 return rc;
3166 }
3167 #endif
3168
3169 /* TODO: all callers to this are broken. We are not parsing mount_options here
3170 * we should pass a clone of the original context?
3171 */
3172 int
cifs_setup_volume_info(struct smb3_fs_context * ctx,const char * mntopts,const char * devname)3173 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3174 {
3175 int rc;
3176
3177 if (devname) {
3178 cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3179 rc = smb3_parse_devname(devname, ctx);
3180 if (rc) {
3181 cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3182 return rc;
3183 }
3184 }
3185
3186 if (mntopts) {
3187 char *ip;
3188
3189 rc = smb3_parse_opt(mntopts, "ip", &ip);
3190 if (rc) {
3191 cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3192 return rc;
3193 }
3194
3195 rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3196 kfree(ip);
3197 if (!rc) {
3198 cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3199 return -EINVAL;
3200 }
3201 }
3202
3203 if (ctx->nullauth) {
3204 cifs_dbg(FYI, "Anonymous login\n");
3205 kfree(ctx->username);
3206 ctx->username = NULL;
3207 } else if (ctx->username) {
3208 /* BB fixme parse for domain name here */
3209 cifs_dbg(FYI, "Username: %s\n", ctx->username);
3210 } else {
3211 cifs_dbg(VFS, "No username specified\n");
3212 /* In userspace mount helper we can get user name from alternate
3213 locations such as env variables and files on disk */
3214 return -EINVAL;
3215 }
3216
3217 return 0;
3218 }
3219
3220 static int
cifs_are_all_path_components_accessible(struct TCP_Server_Info * server,unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,char * full_path,int added_treename)3221 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3222 unsigned int xid,
3223 struct cifs_tcon *tcon,
3224 struct cifs_sb_info *cifs_sb,
3225 char *full_path,
3226 int added_treename)
3227 {
3228 int rc;
3229 char *s;
3230 char sep, tmp;
3231 int skip = added_treename ? 1 : 0;
3232
3233 sep = CIFS_DIR_SEP(cifs_sb);
3234 s = full_path;
3235
3236 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3237 while (rc == 0) {
3238 /* skip separators */
3239 while (*s == sep)
3240 s++;
3241 if (!*s)
3242 break;
3243 /* next separator */
3244 while (*s && *s != sep)
3245 s++;
3246 /*
3247 * if the treename is added, we then have to skip the first
3248 * part within the separators
3249 */
3250 if (skip) {
3251 skip = 0;
3252 continue;
3253 }
3254 /*
3255 * temporarily null-terminate the path at the end of
3256 * the current component
3257 */
3258 tmp = *s;
3259 *s = 0;
3260 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3261 full_path);
3262 *s = tmp;
3263 }
3264 return rc;
3265 }
3266
3267 /*
3268 * Check if path is remote (e.g. a DFS share). Return -EREMOTE if it is,
3269 * otherwise 0.
3270 */
is_path_remote(struct mount_ctx * mnt_ctx)3271 static int is_path_remote(struct mount_ctx *mnt_ctx)
3272 {
3273 int rc;
3274 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3275 struct TCP_Server_Info *server = mnt_ctx->server;
3276 unsigned int xid = mnt_ctx->xid;
3277 struct cifs_tcon *tcon = mnt_ctx->tcon;
3278 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3279 char *full_path;
3280
3281 if (!server->ops->is_path_accessible)
3282 return -EOPNOTSUPP;
3283
3284 /*
3285 * cifs_build_path_to_root works only when we have a valid tcon
3286 */
3287 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3288 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3289 if (full_path == NULL)
3290 return -ENOMEM;
3291
3292 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3293
3294 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3295 full_path);
3296 if (rc != 0 && rc != -EREMOTE) {
3297 kfree(full_path);
3298 return rc;
3299 }
3300
3301 if (rc != -EREMOTE) {
3302 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3303 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3304 if (rc != 0) {
3305 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3306 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3307 rc = 0;
3308 }
3309 }
3310
3311 kfree(full_path);
3312 return rc;
3313 }
3314
3315 #ifdef CONFIG_CIFS_DFS_UPCALL
set_root_ses(struct mount_ctx * mnt_ctx)3316 static void set_root_ses(struct mount_ctx *mnt_ctx)
3317 {
3318 if (mnt_ctx->ses) {
3319 spin_lock(&cifs_tcp_ses_lock);
3320 mnt_ctx->ses->ses_count++;
3321 spin_unlock(&cifs_tcp_ses_lock);
3322 dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3323 }
3324 mnt_ctx->root_ses = mnt_ctx->ses;
3325 }
3326
is_dfs_mount(struct mount_ctx * mnt_ctx,bool * isdfs,struct dfs_cache_tgt_list * root_tl)3327 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3328 {
3329 int rc;
3330 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3331 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3332
3333 *isdfs = true;
3334
3335 rc = mount_get_conns(mnt_ctx);
3336 /*
3337 * If called with 'nodfs' mount option, then skip DFS resolving. Otherwise unconditionally
3338 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3339 *
3340 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3341 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3342 */
3343 if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3344 dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3345 ctx->UNC + 1, NULL, root_tl)) {
3346 if (rc)
3347 return rc;
3348 /* Check if it is fully accessible and then mount it */
3349 rc = is_path_remote(mnt_ctx);
3350 if (!rc)
3351 *isdfs = false;
3352 else if (rc != -EREMOTE)
3353 return rc;
3354 }
3355 return 0;
3356 }
3357
connect_dfs_target(struct mount_ctx * mnt_ctx,const char * full_path,const char * ref_path,struct dfs_cache_tgt_iterator * tit)3358 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3359 const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3360 {
3361 int rc;
3362 struct dfs_info3_param ref = {};
3363 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3364 char *oldmnt = cifs_sb->ctx->mount_options;
3365
3366 rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3367 if (rc)
3368 goto out;
3369
3370 rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3371 if (rc)
3372 goto out;
3373
3374 /* Connect to new target only if we were redirected (e.g. mount options changed) */
3375 if (oldmnt != cifs_sb->ctx->mount_options) {
3376 mount_put_conns(mnt_ctx);
3377 rc = mount_get_dfs_conns(mnt_ctx);
3378 }
3379 if (!rc) {
3380 if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3381 set_root_ses(mnt_ctx);
3382 rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3383 cifs_remap(cifs_sb), ref_path, tit);
3384 }
3385
3386 out:
3387 free_dfs_info_param(&ref);
3388 return rc;
3389 }
3390
connect_dfs_root(struct mount_ctx * mnt_ctx,struct dfs_cache_tgt_list * root_tl)3391 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3392 {
3393 int rc;
3394 char *full_path;
3395 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3396 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3397 struct dfs_cache_tgt_iterator *tit;
3398
3399 /* Put initial connections as they might be shared with other mounts. We need unique dfs
3400 * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3401 * now on.
3402 */
3403 mount_put_conns(mnt_ctx);
3404 mount_get_dfs_conns(mnt_ctx);
3405 set_root_ses(mnt_ctx);
3406
3407 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3408 if (IS_ERR(full_path))
3409 return PTR_ERR(full_path);
3410
3411 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3412 cifs_remap(cifs_sb));
3413 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3414 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3415 mnt_ctx->origin_fullpath = NULL;
3416 goto out;
3417 }
3418
3419 /* Try all dfs root targets */
3420 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3421 tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3422 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3423 if (!rc) {
3424 mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3425 if (!mnt_ctx->leaf_fullpath)
3426 rc = -ENOMEM;
3427 break;
3428 }
3429 }
3430
3431 out:
3432 kfree(full_path);
3433 return rc;
3434 }
3435
__follow_dfs_link(struct mount_ctx * mnt_ctx)3436 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3437 {
3438 int rc;
3439 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3440 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3441 char *full_path;
3442 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3443 struct dfs_cache_tgt_iterator *tit;
3444
3445 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3446 if (IS_ERR(full_path))
3447 return PTR_ERR(full_path);
3448
3449 kfree(mnt_ctx->leaf_fullpath);
3450 mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3451 cifs_remap(cifs_sb));
3452 if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3453 rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3454 mnt_ctx->leaf_fullpath = NULL;
3455 goto out;
3456 }
3457
3458 /* Get referral from dfs link */
3459 rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3460 cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3461 if (rc)
3462 goto out;
3463
3464 /* Try all dfs link targets */
3465 for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3466 tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3467 rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3468 if (!rc) {
3469 rc = is_path_remote(mnt_ctx);
3470 break;
3471 }
3472 }
3473
3474 out:
3475 kfree(full_path);
3476 dfs_cache_free_tgts(&tl);
3477 return rc;
3478 }
3479
follow_dfs_link(struct mount_ctx * mnt_ctx)3480 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3481 {
3482 int rc;
3483 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3484 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3485 char *full_path;
3486 int num_links = 0;
3487
3488 full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3489 if (IS_ERR(full_path))
3490 return PTR_ERR(full_path);
3491
3492 kfree(mnt_ctx->origin_fullpath);
3493 mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3494 cifs_remap(cifs_sb));
3495 kfree(full_path);
3496
3497 if (IS_ERR(mnt_ctx->origin_fullpath)) {
3498 rc = PTR_ERR(mnt_ctx->origin_fullpath);
3499 mnt_ctx->origin_fullpath = NULL;
3500 return rc;
3501 }
3502
3503 do {
3504 rc = __follow_dfs_link(mnt_ctx);
3505 if (!rc || rc != -EREMOTE)
3506 break;
3507 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3508
3509 return rc;
3510 }
3511
3512 /* Set up DFS referral paths for failover */
setup_server_referral_paths(struct mount_ctx * mnt_ctx)3513 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3514 {
3515 struct TCP_Server_Info *server = mnt_ctx->server;
3516
3517 server->origin_fullpath = mnt_ctx->origin_fullpath;
3518 server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3519 server->current_fullpath = mnt_ctx->leaf_fullpath;
3520 mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3521 }
3522
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3523 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3524 {
3525 int rc;
3526 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3527 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3528 bool isdfs;
3529
3530 rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3531 if (rc)
3532 goto error;
3533 if (!isdfs)
3534 goto out;
3535
3536 uuid_gen(&mnt_ctx.mount_id);
3537 rc = connect_dfs_root(&mnt_ctx, &tl);
3538 dfs_cache_free_tgts(&tl);
3539
3540 if (rc)
3541 goto error;
3542
3543 rc = is_path_remote(&mnt_ctx);
3544 if (rc == -EREMOTE)
3545 rc = follow_dfs_link(&mnt_ctx);
3546 if (rc)
3547 goto error;
3548
3549 setup_server_referral_paths(&mnt_ctx);
3550 /*
3551 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3552 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3553 */
3554 cifs_autodisable_serverino(cifs_sb);
3555 /*
3556 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3557 * that have different prefix paths.
3558 */
3559 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3560 kfree(cifs_sb->prepath);
3561 cifs_sb->prepath = ctx->prepath;
3562 ctx->prepath = NULL;
3563 uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3564
3565 out:
3566 cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3567 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3568 if (rc)
3569 goto error;
3570
3571 free_xid(mnt_ctx.xid);
3572 return rc;
3573
3574 error:
3575 dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3576 kfree(mnt_ctx.origin_fullpath);
3577 kfree(mnt_ctx.leaf_fullpath);
3578 mount_put_conns(&mnt_ctx);
3579 return rc;
3580 }
3581 #else
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3582 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3583 {
3584 int rc = 0;
3585 struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3586
3587 rc = mount_get_conns(&mnt_ctx);
3588 if (rc)
3589 goto error;
3590
3591 if (mnt_ctx.tcon) {
3592 rc = is_path_remote(&mnt_ctx);
3593 if (rc == -EREMOTE)
3594 rc = -EOPNOTSUPP;
3595 if (rc)
3596 goto error;
3597 }
3598
3599 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3600 if (rc)
3601 goto error;
3602
3603 free_xid(mnt_ctx.xid);
3604 return rc;
3605
3606 error:
3607 mount_put_conns(&mnt_ctx);
3608 return rc;
3609 }
3610 #endif
3611
3612 /*
3613 * Issue a TREE_CONNECT request.
3614 */
3615 int
CIFSTCon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * nls_codepage)3616 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3617 const char *tree, struct cifs_tcon *tcon,
3618 const struct nls_table *nls_codepage)
3619 {
3620 struct smb_hdr *smb_buffer;
3621 struct smb_hdr *smb_buffer_response;
3622 TCONX_REQ *pSMB;
3623 TCONX_RSP *pSMBr;
3624 unsigned char *bcc_ptr;
3625 int rc = 0;
3626 int length;
3627 __u16 bytes_left, count;
3628
3629 if (ses == NULL)
3630 return -EIO;
3631
3632 smb_buffer = cifs_buf_get();
3633 if (smb_buffer == NULL)
3634 return -ENOMEM;
3635
3636 smb_buffer_response = smb_buffer;
3637
3638 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3639 NULL /*no tid */ , 4 /*wct */ );
3640
3641 smb_buffer->Mid = get_next_mid(ses->server);
3642 smb_buffer->Uid = ses->Suid;
3643 pSMB = (TCONX_REQ *) smb_buffer;
3644 pSMBr = (TCONX_RSP *) smb_buffer_response;
3645
3646 pSMB->AndXCommand = 0xFF;
3647 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3648 bcc_ptr = &pSMB->Password[0];
3649
3650 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
3651 *bcc_ptr = 0; /* password is null byte */
3652 bcc_ptr++; /* skip password */
3653 /* already aligned so no need to do it below */
3654
3655 if (ses->server->sign)
3656 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3657
3658 if (ses->capabilities & CAP_STATUS32) {
3659 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3660 }
3661 if (ses->capabilities & CAP_DFS) {
3662 smb_buffer->Flags2 |= SMBFLG2_DFS;
3663 }
3664 if (ses->capabilities & CAP_UNICODE) {
3665 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3666 length =
3667 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3668 6 /* max utf8 char length in bytes */ *
3669 (/* server len*/ + 256 /* share len */), nls_codepage);
3670 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
3671 bcc_ptr += 2; /* skip trailing null */
3672 } else { /* ASCII */
3673 strcpy(bcc_ptr, tree);
3674 bcc_ptr += strlen(tree) + 1;
3675 }
3676 strcpy(bcc_ptr, "?????");
3677 bcc_ptr += strlen("?????");
3678 bcc_ptr += 1;
3679 count = bcc_ptr - &pSMB->Password[0];
3680 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3681 pSMB->ByteCount = cpu_to_le16(count);
3682
3683 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3684 0);
3685
3686 /* above now done in SendReceive */
3687 if (rc == 0) {
3688 bool is_unicode;
3689
3690 tcon->tidStatus = CifsGood;
3691 tcon->need_reconnect = false;
3692 tcon->tid = smb_buffer_response->Tid;
3693 bcc_ptr = pByteArea(smb_buffer_response);
3694 bytes_left = get_bcc(smb_buffer_response);
3695 length = strnlen(bcc_ptr, bytes_left - 2);
3696 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3697 is_unicode = true;
3698 else
3699 is_unicode = false;
3700
3701
3702 /* skip service field (NB: this field is always ASCII) */
3703 if (length == 3) {
3704 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3705 (bcc_ptr[2] == 'C')) {
3706 cifs_dbg(FYI, "IPC connection\n");
3707 tcon->ipc = true;
3708 tcon->pipe = true;
3709 }
3710 } else if (length == 2) {
3711 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3712 /* the most common case */
3713 cifs_dbg(FYI, "disk share connection\n");
3714 }
3715 }
3716 bcc_ptr += length + 1;
3717 bytes_left -= (length + 1);
3718 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
3719
3720 /* mostly informational -- no need to fail on error here */
3721 kfree(tcon->nativeFileSystem);
3722 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3723 bytes_left, is_unicode,
3724 nls_codepage);
3725
3726 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3727
3728 if ((smb_buffer_response->WordCount == 3) ||
3729 (smb_buffer_response->WordCount == 7))
3730 /* field is in same location */
3731 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3732 else
3733 tcon->Flags = 0;
3734 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3735 }
3736
3737 cifs_buf_release(smb_buffer);
3738 return rc;
3739 }
3740
delayed_free(struct rcu_head * p)3741 static void delayed_free(struct rcu_head *p)
3742 {
3743 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3744
3745 unload_nls(cifs_sb->local_nls);
3746 smb3_cleanup_fs_context(cifs_sb->ctx);
3747 kfree(cifs_sb);
3748 }
3749
3750 void
cifs_umount(struct cifs_sb_info * cifs_sb)3751 cifs_umount(struct cifs_sb_info *cifs_sb)
3752 {
3753 struct rb_root *root = &cifs_sb->tlink_tree;
3754 struct rb_node *node;
3755 struct tcon_link *tlink;
3756
3757 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3758
3759 spin_lock(&cifs_sb->tlink_tree_lock);
3760 while ((node = rb_first(root))) {
3761 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3762 cifs_get_tlink(tlink);
3763 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3764 rb_erase(node, root);
3765
3766 spin_unlock(&cifs_sb->tlink_tree_lock);
3767 cifs_put_tlink(tlink);
3768 spin_lock(&cifs_sb->tlink_tree_lock);
3769 }
3770 spin_unlock(&cifs_sb->tlink_tree_lock);
3771
3772 kfree(cifs_sb->prepath);
3773 #ifdef CONFIG_CIFS_DFS_UPCALL
3774 dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
3775 #endif
3776 call_rcu(&cifs_sb->rcu, delayed_free);
3777 }
3778
3779 int
cifs_negotiate_protocol(const unsigned int xid,struct cifs_ses * ses)3780 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
3781 {
3782 int rc = 0;
3783 struct TCP_Server_Info *server = cifs_ses_server(ses);
3784
3785 if (!server->ops->need_neg || !server->ops->negotiate)
3786 return -ENOSYS;
3787
3788 /* only send once per connect */
3789 if (!server->ops->need_neg(server))
3790 return 0;
3791
3792 rc = server->ops->negotiate(xid, ses);
3793 if (rc == 0) {
3794 spin_lock(&GlobalMid_Lock);
3795 if (server->tcpStatus == CifsNeedNegotiate)
3796 server->tcpStatus = CifsGood;
3797 else
3798 rc = -EHOSTDOWN;
3799 spin_unlock(&GlobalMid_Lock);
3800 }
3801
3802 return rc;
3803 }
3804
3805 int
cifs_setup_session(const unsigned int xid,struct cifs_ses * ses,struct nls_table * nls_info)3806 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3807 struct nls_table *nls_info)
3808 {
3809 int rc = -ENOSYS;
3810 struct TCP_Server_Info *server = cifs_ses_server(ses);
3811
3812 if (!ses->binding) {
3813 ses->capabilities = server->capabilities;
3814 if (!linuxExtEnabled)
3815 ses->capabilities &= (~server->vals->cap_unix);
3816
3817 if (ses->auth_key.response) {
3818 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
3819 ses->auth_key.response);
3820 kfree(ses->auth_key.response);
3821 ses->auth_key.response = NULL;
3822 ses->auth_key.len = 0;
3823 }
3824 }
3825
3826 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3827 server->sec_mode, server->capabilities, server->timeAdj);
3828
3829 if (server->ops->sess_setup)
3830 rc = server->ops->sess_setup(xid, ses, nls_info);
3831
3832 if (rc)
3833 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3834
3835 return rc;
3836 }
3837
3838 static int
cifs_set_vol_auth(struct smb3_fs_context * ctx,struct cifs_ses * ses)3839 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
3840 {
3841 ctx->sectype = ses->sectype;
3842
3843 /* krb5 is special, since we don't need username or pw */
3844 if (ctx->sectype == Kerberos)
3845 return 0;
3846
3847 return cifs_set_cifscreds(ctx, ses);
3848 }
3849
3850 static struct cifs_tcon *
cifs_construct_tcon(struct cifs_sb_info * cifs_sb,kuid_t fsuid)3851 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3852 {
3853 int rc;
3854 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3855 struct cifs_ses *ses;
3856 struct cifs_tcon *tcon = NULL;
3857 struct smb3_fs_context *ctx;
3858
3859 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3860 if (ctx == NULL)
3861 return ERR_PTR(-ENOMEM);
3862
3863 ctx->local_nls = cifs_sb->local_nls;
3864 ctx->linux_uid = fsuid;
3865 ctx->cred_uid = fsuid;
3866 ctx->UNC = master_tcon->treeName;
3867 ctx->retry = master_tcon->retry;
3868 ctx->nocase = master_tcon->nocase;
3869 ctx->nohandlecache = master_tcon->nohandlecache;
3870 ctx->local_lease = master_tcon->local_lease;
3871 ctx->no_lease = master_tcon->no_lease;
3872 ctx->resilient = master_tcon->use_resilient;
3873 ctx->persistent = master_tcon->use_persistent;
3874 ctx->handle_timeout = master_tcon->handle_timeout;
3875 ctx->no_linux_ext = !master_tcon->unix_ext;
3876 ctx->linux_ext = master_tcon->posix_extensions;
3877 ctx->sectype = master_tcon->ses->sectype;
3878 ctx->sign = master_tcon->ses->sign;
3879 ctx->seal = master_tcon->seal;
3880 ctx->witness = master_tcon->use_witness;
3881
3882 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
3883 if (rc) {
3884 tcon = ERR_PTR(rc);
3885 goto out;
3886 }
3887
3888 /* get a reference for the same TCP session */
3889 spin_lock(&cifs_tcp_ses_lock);
3890 ++master_tcon->ses->server->srv_count;
3891 spin_unlock(&cifs_tcp_ses_lock);
3892
3893 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
3894 if (IS_ERR(ses)) {
3895 tcon = (struct cifs_tcon *)ses;
3896 cifs_put_tcp_session(master_tcon->ses->server, 0);
3897 goto out;
3898 }
3899
3900 tcon = cifs_get_tcon(ses, ctx);
3901 if (IS_ERR(tcon)) {
3902 cifs_put_smb_ses(ses);
3903 goto out;
3904 }
3905
3906 if (cap_unix(ses))
3907 reset_cifs_unix_caps(0, tcon, NULL, ctx);
3908
3909 out:
3910 kfree(ctx->username);
3911 kfree_sensitive(ctx->password);
3912 kfree(ctx);
3913
3914 return tcon;
3915 }
3916
3917 struct cifs_tcon *
cifs_sb_master_tcon(struct cifs_sb_info * cifs_sb)3918 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
3919 {
3920 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
3921 }
3922
3923 /* find and return a tlink with given uid */
3924 static struct tcon_link *
tlink_rb_search(struct rb_root * root,kuid_t uid)3925 tlink_rb_search(struct rb_root *root, kuid_t uid)
3926 {
3927 struct rb_node *node = root->rb_node;
3928 struct tcon_link *tlink;
3929
3930 while (node) {
3931 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3932
3933 if (uid_gt(tlink->tl_uid, uid))
3934 node = node->rb_left;
3935 else if (uid_lt(tlink->tl_uid, uid))
3936 node = node->rb_right;
3937 else
3938 return tlink;
3939 }
3940 return NULL;
3941 }
3942
3943 /* insert a tcon_link into the tree */
3944 static void
tlink_rb_insert(struct rb_root * root,struct tcon_link * new_tlink)3945 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
3946 {
3947 struct rb_node **new = &(root->rb_node), *parent = NULL;
3948 struct tcon_link *tlink;
3949
3950 while (*new) {
3951 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
3952 parent = *new;
3953
3954 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
3955 new = &((*new)->rb_left);
3956 else
3957 new = &((*new)->rb_right);
3958 }
3959
3960 rb_link_node(&new_tlink->tl_rbnode, parent, new);
3961 rb_insert_color(&new_tlink->tl_rbnode, root);
3962 }
3963
3964 /*
3965 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
3966 * current task.
3967 *
3968 * If the superblock doesn't refer to a multiuser mount, then just return
3969 * the master tcon for the mount.
3970 *
3971 * First, search the rbtree for an existing tcon for this fsuid. If one
3972 * exists, then check to see if it's pending construction. If it is then wait
3973 * for construction to complete. Once it's no longer pending, check to see if
3974 * it failed and either return an error or retry construction, depending on
3975 * the timeout.
3976 *
3977 * If one doesn't exist then insert a new tcon_link struct into the tree and
3978 * try to construct a new one.
3979 */
3980 struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info * cifs_sb)3981 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
3982 {
3983 int ret;
3984 kuid_t fsuid = current_fsuid();
3985 struct tcon_link *tlink, *newtlink;
3986
3987 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
3988 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
3989
3990 spin_lock(&cifs_sb->tlink_tree_lock);
3991 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
3992 if (tlink)
3993 cifs_get_tlink(tlink);
3994 spin_unlock(&cifs_sb->tlink_tree_lock);
3995
3996 if (tlink == NULL) {
3997 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3998 if (newtlink == NULL)
3999 return ERR_PTR(-ENOMEM);
4000 newtlink->tl_uid = fsuid;
4001 newtlink->tl_tcon = ERR_PTR(-EACCES);
4002 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4003 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4004 cifs_get_tlink(newtlink);
4005
4006 spin_lock(&cifs_sb->tlink_tree_lock);
4007 /* was one inserted after previous search? */
4008 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4009 if (tlink) {
4010 cifs_get_tlink(tlink);
4011 spin_unlock(&cifs_sb->tlink_tree_lock);
4012 kfree(newtlink);
4013 goto wait_for_construction;
4014 }
4015 tlink = newtlink;
4016 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4017 spin_unlock(&cifs_sb->tlink_tree_lock);
4018 } else {
4019 wait_for_construction:
4020 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4021 TASK_INTERRUPTIBLE);
4022 if (ret) {
4023 cifs_put_tlink(tlink);
4024 return ERR_PTR(-ERESTARTSYS);
4025 }
4026
4027 /* if it's good, return it */
4028 if (!IS_ERR(tlink->tl_tcon))
4029 return tlink;
4030
4031 /* return error if we tried this already recently */
4032 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4033 cifs_put_tlink(tlink);
4034 return ERR_PTR(-EACCES);
4035 }
4036
4037 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4038 goto wait_for_construction;
4039 }
4040
4041 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4042 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4043 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4044
4045 if (IS_ERR(tlink->tl_tcon)) {
4046 cifs_put_tlink(tlink);
4047 return ERR_PTR(-EACCES);
4048 }
4049
4050 return tlink;
4051 }
4052
4053 /*
4054 * periodic workqueue job that scans tcon_tree for a superblock and closes
4055 * out tcons.
4056 */
4057 static void
cifs_prune_tlinks(struct work_struct * work)4058 cifs_prune_tlinks(struct work_struct *work)
4059 {
4060 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4061 prune_tlinks.work);
4062 struct rb_root *root = &cifs_sb->tlink_tree;
4063 struct rb_node *node;
4064 struct rb_node *tmp;
4065 struct tcon_link *tlink;
4066
4067 /*
4068 * Because we drop the spinlock in the loop in order to put the tlink
4069 * it's not guarded against removal of links from the tree. The only
4070 * places that remove entries from the tree are this function and
4071 * umounts. Because this function is non-reentrant and is canceled
4072 * before umount can proceed, this is safe.
4073 */
4074 spin_lock(&cifs_sb->tlink_tree_lock);
4075 node = rb_first(root);
4076 while (node != NULL) {
4077 tmp = node;
4078 node = rb_next(tmp);
4079 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4080
4081 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4082 atomic_read(&tlink->tl_count) != 0 ||
4083 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4084 continue;
4085
4086 cifs_get_tlink(tlink);
4087 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4088 rb_erase(tmp, root);
4089
4090 spin_unlock(&cifs_sb->tlink_tree_lock);
4091 cifs_put_tlink(tlink);
4092 spin_lock(&cifs_sb->tlink_tree_lock);
4093 }
4094 spin_unlock(&cifs_sb->tlink_tree_lock);
4095
4096 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4097 TLINK_IDLE_EXPIRE);
4098 }
4099
4100 #ifdef CONFIG_CIFS_DFS_UPCALL
mark_tcon_tcp_ses_for_reconnect(struct cifs_tcon * tcon)4101 static void mark_tcon_tcp_ses_for_reconnect(struct cifs_tcon *tcon)
4102 {
4103 int i;
4104
4105 for (i = 0; i < tcon->ses->chan_count; i++) {
4106 spin_lock(&GlobalMid_Lock);
4107 if (tcon->ses->chans[i].server->tcpStatus != CifsExiting)
4108 tcon->ses->chans[i].server->tcpStatus = CifsNeedReconnect;
4109 spin_unlock(&GlobalMid_Lock);
4110 }
4111 }
4112
4113 /* Update dfs referral path of superblock */
update_server_fullpath(struct TCP_Server_Info * server,struct cifs_sb_info * cifs_sb,const char * target)4114 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4115 const char *target)
4116 {
4117 int rc = 0;
4118 size_t len = strlen(target);
4119 char *refpath, *npath;
4120
4121 if (unlikely(len < 2 || *target != '\\'))
4122 return -EINVAL;
4123
4124 if (target[1] == '\\') {
4125 len += 1;
4126 refpath = kmalloc(len, GFP_KERNEL);
4127 if (!refpath)
4128 return -ENOMEM;
4129
4130 scnprintf(refpath, len, "%s", target);
4131 } else {
4132 len += sizeof("\\");
4133 refpath = kmalloc(len, GFP_KERNEL);
4134 if (!refpath)
4135 return -ENOMEM;
4136
4137 scnprintf(refpath, len, "\\%s", target);
4138 }
4139
4140 npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4141 kfree(refpath);
4142
4143 if (IS_ERR(npath)) {
4144 rc = PTR_ERR(npath);
4145 } else {
4146 mutex_lock(&server->refpath_lock);
4147 kfree(server->leaf_fullpath);
4148 server->leaf_fullpath = npath;
4149 mutex_unlock(&server->refpath_lock);
4150 server->current_fullpath = server->leaf_fullpath;
4151 }
4152 return rc;
4153 }
4154
target_share_matches_server(struct TCP_Server_Info * server,const char * tcp_host,size_t tcp_host_len,char * share,bool * target_match)4155 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4156 size_t tcp_host_len, char *share, bool *target_match)
4157 {
4158 int rc = 0;
4159 const char *dfs_host;
4160 size_t dfs_host_len;
4161
4162 *target_match = true;
4163 extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4164
4165 /* Check if hostnames or addresses match */
4166 if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4167 cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4168 dfs_host, (int)tcp_host_len, tcp_host);
4169 rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4170 if (rc)
4171 cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4172 }
4173 return rc;
4174 }
4175
__tree_connect_dfs_target(const unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,char * tree,struct dfs_cache_tgt_list * tl,struct dfs_info3_param * ref)4176 int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4177 struct cifs_sb_info *cifs_sb, char *tree,
4178 struct dfs_cache_tgt_list *tl, struct dfs_info3_param *ref)
4179 {
4180 int rc;
4181 struct TCP_Server_Info *server = tcon->ses->server;
4182 const struct smb_version_operations *ops = server->ops;
4183 struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4184 bool islink;
4185 char *share = NULL, *prefix = NULL;
4186 const char *tcp_host;
4187 size_t tcp_host_len;
4188 struct dfs_cache_tgt_iterator *tit;
4189 bool target_match;
4190
4191 extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4192
4193 islink = ref->server_type == DFS_TYPE_LINK;
4194 free_dfs_info_param(ref);
4195
4196 tit = dfs_cache_get_tgt_iterator(tl);
4197 if (!tit) {
4198 rc = -ENOENT;
4199 goto out;
4200 }
4201
4202 /* Try to tree connect to all dfs targets */
4203 for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4204 const char *target = dfs_cache_get_tgt_name(tit);
4205 struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4206
4207 kfree(share);
4208 kfree(prefix);
4209
4210 /* Check if share matches with tcp ses */
4211 rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4212 if (rc) {
4213 cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4214 break;
4215 }
4216
4217 rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4218 &target_match);
4219 if (rc)
4220 break;
4221 if (!target_match) {
4222 rc = -EHOSTUNREACH;
4223 continue;
4224 }
4225
4226 if (ipc->need_reconnect) {
4227 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4228 rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4229 if (rc)
4230 break;
4231 }
4232
4233 scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4234 if (!islink) {
4235 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4236 break;
4237 }
4238 /*
4239 * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4240 * to it. Otherwise, cache the dfs referral and then mark current tcp ses for
4241 * reconnect so either the demultiplex thread or the echo worker will reconnect to
4242 * newly resolved target.
4243 */
4244 if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4245 ref, &ntl)) {
4246 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4247 if (rc)
4248 continue;
4249 rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4250 if (!rc)
4251 rc = cifs_update_super_prepath(cifs_sb, prefix);
4252 break;
4253 }
4254 /* Target is another dfs share */
4255 rc = update_server_fullpath(server, cifs_sb, target);
4256 dfs_cache_free_tgts(tl);
4257
4258 if (!rc) {
4259 rc = -EREMOTE;
4260 list_replace_init(&ntl.tl_list, &tl->tl_list);
4261 } else {
4262 dfs_cache_free_tgts(&ntl);
4263 free_dfs_info_param(ref);
4264 }
4265 break;
4266 }
4267
4268 out:
4269 kfree(share);
4270 kfree(prefix);
4271
4272 return rc;
4273 }
4274
tree_connect_dfs_target(const unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,char * tree,struct dfs_cache_tgt_list * tl,struct dfs_info3_param * ref)4275 int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4276 struct cifs_sb_info *cifs_sb, char *tree,
4277 struct dfs_cache_tgt_list *tl, struct dfs_info3_param *ref)
4278 {
4279 int rc;
4280 int num_links = 0;
4281 struct TCP_Server_Info *server = tcon->ses->server;
4282
4283 do {
4284 rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, tl, ref);
4285 if (!rc || rc != -EREMOTE)
4286 break;
4287 } while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4288 /*
4289 * If we couldn't tree connect to any targets from last referral path, then retry from
4290 * original referral path.
4291 */
4292 if (rc && server->current_fullpath != server->origin_fullpath) {
4293 server->current_fullpath = server->origin_fullpath;
4294 mark_tcon_tcp_ses_for_reconnect(tcon);
4295 }
4296
4297 dfs_cache_free_tgts(tl);
4298 return rc;
4299 }
4300
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon,const struct nls_table * nlsc)4301 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4302 {
4303 int rc;
4304 struct TCP_Server_Info *server = tcon->ses->server;
4305 const struct smb_version_operations *ops = server->ops;
4306 struct super_block *sb = NULL;
4307 struct cifs_sb_info *cifs_sb;
4308 struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4309 char *tree;
4310 struct dfs_info3_param ref = {0};
4311
4312 tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4313 if (!tree)
4314 return -ENOMEM;
4315
4316 if (tcon->ipc) {
4317 scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4318 rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4319 goto out;
4320 }
4321
4322 sb = cifs_get_tcp_super(server);
4323 if (IS_ERR(sb)) {
4324 rc = PTR_ERR(sb);
4325 cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4326 goto out;
4327 }
4328
4329 cifs_sb = CIFS_SB(sb);
4330
4331 /* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4332 if (!server->current_fullpath ||
4333 dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4334 rc = ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, cifs_sb->local_nls);
4335 goto out;
4336 }
4337
4338 rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, &tl, &ref);
4339
4340 out:
4341 kfree(tree);
4342 cifs_put_tcp_super(sb);
4343
4344 return rc;
4345 }
4346 #else
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon,const struct nls_table * nlsc)4347 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4348 {
4349 const struct smb_version_operations *ops = tcon->ses->server->ops;
4350
4351 return ops->tree_connect(xid, tcon->ses, tcon->treeName, tcon, nlsc);
4352 }
4353 #endif
4354