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