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