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