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