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