1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3 *
4 * Copyright (C) International Business Machines Corp., 2002,2011
5 * Author(s): Steve French (sfrench@us.ibm.com)
6 *
7 */
8 #include <linux/fs.h>
9 #include <linux/net.h>
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
32 #include <net/ipv6.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
35 #include "cifspdu.h"
36 #include "cifsglob.h"
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
41 #include "ntlmssp.h"
42 #include "nterr.h"
43 #include "rfc1002pdu.h"
44 #include "fscache.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs.h"
50 #include "dfs_cache.h"
51 #endif
52 #include "fs_context.h"
53 #include "cifs_swn.h"
54
55 /* FIXME: should these be tunable? */
56 #define TLINK_ERROR_EXPIRE (1 * HZ)
57 #define TLINK_IDLE_EXPIRE (600 * HZ)
58
59 /* Drop the connection to not overload the server */
60 #define MAX_STATUS_IO_TIMEOUT 5
61
62 static int ip_connect(struct TCP_Server_Info *server);
63 static int generic_ip_connect(struct TCP_Server_Info *server);
64 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
65 static void cifs_prune_tlinks(struct work_struct *work);
66
67 /*
68 * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
69 * get their ip addresses changed at some point.
70 *
71 * This should be called with server->srv_mutex held.
72 */
reconn_set_ipaddr_from_hostname(struct TCP_Server_Info * server)73 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
74 {
75 struct sockaddr_storage ss;
76 int rc;
77
78 if (!server->hostname)
79 return -EINVAL;
80
81 /* if server hostname isn't populated, there's nothing to do here */
82 if (server->hostname[0] == '\0')
83 return 0;
84
85 spin_lock(&server->srv_lock);
86 ss = server->dstaddr;
87 spin_unlock(&server->srv_lock);
88
89 rc = dns_resolve_name(server->dns_dom, server->hostname,
90 strlen(server->hostname),
91 (struct sockaddr *)&ss);
92 if (!rc) {
93 spin_lock(&server->srv_lock);
94 memcpy(&server->dstaddr, &ss, sizeof(server->dstaddr));
95 spin_unlock(&server->srv_lock);
96 }
97 return rc;
98 }
99
smb2_query_server_interfaces(struct work_struct * work)100 static void smb2_query_server_interfaces(struct work_struct *work)
101 {
102 int rc;
103 int xid;
104 struct cifs_tcon *tcon = container_of(work,
105 struct cifs_tcon,
106 query_interfaces.work);
107 struct TCP_Server_Info *server = tcon->ses->server;
108
109 /*
110 * query server network interfaces, in case they change
111 */
112 if (!server->ops->query_server_interfaces)
113 return;
114
115 xid = get_xid();
116 rc = server->ops->query_server_interfaces(xid, tcon, false);
117 free_xid(xid);
118
119 if (rc)
120 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 to
683 * negotiate protocol.
684 */
685 spin_lock(&server->srv_lock);
686 if (server->tcpStatus == CifsInNegotiate &&
687 time_after(jiffies, server->lstrp + 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 INIT_LIST_HEAD(&tcon->pending_opens);
2884 tcon->status = TID_GOOD;
2885
2886 INIT_DELAYED_WORK(&tcon->query_interfaces,
2887 smb2_query_server_interfaces);
2888 if (ses->server->dialect >= SMB30_PROT_ID &&
2889 (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2890 /* schedule query interfaces poll */
2891 queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2892 (SMB_INTERFACE_POLL_INTERVAL * HZ));
2893 }
2894 #ifdef CONFIG_CIFS_DFS_UPCALL
2895 INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2896 #endif
2897 spin_lock(&cifs_tcp_ses_lock);
2898 list_add(&tcon->tcon_list, &ses->tcon_list);
2899 spin_unlock(&cifs_tcp_ses_lock);
2900
2901 return tcon;
2902
2903 out_fail:
2904 tconInfoFree(tcon, netfs_trace_tcon_ref_free_fail);
2905 return ERR_PTR(rc);
2906 }
2907
2908 void
cifs_put_tlink(struct tcon_link * tlink)2909 cifs_put_tlink(struct tcon_link *tlink)
2910 {
2911 if (!tlink || IS_ERR(tlink))
2912 return;
2913
2914 if (!atomic_dec_and_test(&tlink->tl_count) ||
2915 test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2916 tlink->tl_time = jiffies;
2917 return;
2918 }
2919
2920 if (!IS_ERR(tlink_tcon(tlink)))
2921 cifs_put_tcon(tlink_tcon(tlink), netfs_trace_tcon_ref_put_tlink);
2922 kfree(tlink);
2923 }
2924
2925 static int
compare_mount_options(struct super_block * sb,struct cifs_mnt_data * mnt_data)2926 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2927 {
2928 struct cifs_sb_info *old = CIFS_SB(sb);
2929 struct cifs_sb_info *new = mnt_data->cifs_sb;
2930 unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2931 unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2932
2933 if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2934 return 0;
2935
2936 if (old->mnt_cifs_serverino_autodisabled)
2937 newflags &= ~CIFS_MOUNT_SERVER_INUM;
2938
2939 if (oldflags != newflags)
2940 return 0;
2941
2942 /*
2943 * We want to share sb only if we don't specify an r/wsize or
2944 * specified r/wsize is greater than or equal to existing one.
2945 */
2946 if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2947 return 0;
2948
2949 if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2950 return 0;
2951
2952 if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2953 !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2954 return 0;
2955
2956 if (old->ctx->file_mode != new->ctx->file_mode ||
2957 old->ctx->dir_mode != new->ctx->dir_mode)
2958 return 0;
2959
2960 if (strcmp(old->local_nls->charset, new->local_nls->charset))
2961 return 0;
2962
2963 if (old->ctx->acregmax != new->ctx->acregmax)
2964 return 0;
2965 if (old->ctx->acdirmax != new->ctx->acdirmax)
2966 return 0;
2967 if (old->ctx->closetimeo != new->ctx->closetimeo)
2968 return 0;
2969 if (old->ctx->reparse_type != new->ctx->reparse_type)
2970 return 0;
2971 if (old->ctx->nonativesocket != new->ctx->nonativesocket)
2972 return 0;
2973 if (old->ctx->symlink_type != new->ctx->symlink_type)
2974 return 0;
2975
2976 return 1;
2977 }
2978
match_prepath(struct super_block * sb,struct cifs_tcon * tcon,struct cifs_mnt_data * mnt_data)2979 static int match_prepath(struct super_block *sb,
2980 struct cifs_tcon *tcon,
2981 struct cifs_mnt_data *mnt_data)
2982 {
2983 struct smb3_fs_context *ctx = mnt_data->ctx;
2984 struct cifs_sb_info *old = CIFS_SB(sb);
2985 struct cifs_sb_info *new = mnt_data->cifs_sb;
2986 bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2987 old->prepath;
2988 bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2989 new->prepath;
2990
2991 if (tcon->origin_fullpath &&
2992 dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2993 return 1;
2994
2995 if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2996 return 1;
2997 else if (!old_set && !new_set)
2998 return 1;
2999
3000 return 0;
3001 }
3002
3003 int
cifs_match_super(struct super_block * sb,void * data)3004 cifs_match_super(struct super_block *sb, void *data)
3005 {
3006 struct cifs_mnt_data *mnt_data = data;
3007 struct smb3_fs_context *ctx;
3008 struct cifs_sb_info *cifs_sb;
3009 struct TCP_Server_Info *tcp_srv;
3010 struct cifs_ses *ses;
3011 struct cifs_tcon *tcon;
3012 struct tcon_link *tlink;
3013 int rc = 0;
3014
3015 spin_lock(&cifs_tcp_ses_lock);
3016 cifs_sb = CIFS_SB(sb);
3017
3018 /* We do not want to use a superblock that has been shutdown */
3019 if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
3020 spin_unlock(&cifs_tcp_ses_lock);
3021 return 0;
3022 }
3023
3024 tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
3025 if (IS_ERR_OR_NULL(tlink)) {
3026 pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
3027 __func__, tlink);
3028 spin_unlock(&cifs_tcp_ses_lock);
3029 return 0;
3030 }
3031 tcon = tlink_tcon(tlink);
3032 ses = tcon->ses;
3033 tcp_srv = ses->server;
3034
3035 ctx = mnt_data->ctx;
3036
3037 spin_lock(&tcp_srv->srv_lock);
3038 spin_lock(&ses->ses_lock);
3039 spin_lock(&ses->chan_lock);
3040 spin_lock(&tcon->tc_lock);
3041 if (!match_server(tcp_srv, ctx, true) ||
3042 !match_session(ses, ctx, true) ||
3043 !match_tcon(tcon, ctx) ||
3044 !match_prepath(sb, tcon, mnt_data)) {
3045 rc = 0;
3046 goto out;
3047 }
3048
3049 rc = compare_mount_options(sb, mnt_data);
3050 out:
3051 spin_unlock(&tcon->tc_lock);
3052 spin_unlock(&ses->chan_lock);
3053 spin_unlock(&ses->ses_lock);
3054 spin_unlock(&tcp_srv->srv_lock);
3055
3056 spin_unlock(&cifs_tcp_ses_lock);
3057 cifs_put_tlink(tlink);
3058 return rc;
3059 }
3060
3061 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3062 static struct lock_class_key cifs_key[2];
3063 static struct lock_class_key cifs_slock_key[2];
3064
3065 static inline void
cifs_reclassify_socket4(struct socket * sock)3066 cifs_reclassify_socket4(struct socket *sock)
3067 {
3068 struct sock *sk = sock->sk;
3069
3070 BUG_ON(!sock_allow_reclassification(sk));
3071 sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
3072 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
3073 }
3074
3075 static inline void
cifs_reclassify_socket6(struct socket * sock)3076 cifs_reclassify_socket6(struct socket *sock)
3077 {
3078 struct sock *sk = sock->sk;
3079
3080 BUG_ON(!sock_allow_reclassification(sk));
3081 sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
3082 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
3083 }
3084 #else
3085 static inline void
cifs_reclassify_socket4(struct socket * sock)3086 cifs_reclassify_socket4(struct socket *sock)
3087 {
3088 }
3089
3090 static inline void
cifs_reclassify_socket6(struct socket * sock)3091 cifs_reclassify_socket6(struct socket *sock)
3092 {
3093 }
3094 #endif
3095
3096 /* See RFC1001 section 14 on representation of Netbios names */
rfc1002mangle(char * target,char * source,unsigned int length)3097 static void rfc1002mangle(char *target, char *source, unsigned int length)
3098 {
3099 unsigned int i, j;
3100
3101 for (i = 0, j = 0; i < (length); i++) {
3102 /* mask a nibble at a time and encode */
3103 target[j] = 'A' + (0x0F & (source[i] >> 4));
3104 target[j+1] = 'A' + (0x0F & source[i]);
3105 j += 2;
3106 }
3107
3108 }
3109
3110 static int
bind_socket(struct TCP_Server_Info * server)3111 bind_socket(struct TCP_Server_Info *server)
3112 {
3113 int rc = 0;
3114
3115 if (server->srcaddr.ss_family != AF_UNSPEC) {
3116 /* Bind to the specified local IP address */
3117 struct socket *socket = server->ssocket;
3118
3119 rc = kernel_bind(socket,
3120 (struct sockaddr *) &server->srcaddr,
3121 sizeof(server->srcaddr));
3122 if (rc < 0) {
3123 struct sockaddr_in *saddr4;
3124 struct sockaddr_in6 *saddr6;
3125
3126 saddr4 = (struct sockaddr_in *)&server->srcaddr;
3127 saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3128 if (saddr6->sin6_family == AF_INET6)
3129 cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3130 &saddr6->sin6_addr, rc);
3131 else
3132 cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3133 &saddr4->sin_addr.s_addr, rc);
3134 }
3135 }
3136 return rc;
3137 }
3138
3139 static int
smb_recv_kvec(struct TCP_Server_Info * server,struct msghdr * msg,size_t * recv)3140 smb_recv_kvec(struct TCP_Server_Info *server, struct msghdr *msg, size_t *recv)
3141 {
3142 int rc = 0;
3143 int retries = 0;
3144 int msg_flags = server->noblocksnd ? MSG_DONTWAIT : 0;
3145
3146 *recv = 0;
3147
3148 while (msg_data_left(msg)) {
3149 rc = sock_recvmsg(server->ssocket, msg, msg_flags);
3150 if (rc == -EAGAIN) {
3151 retries++;
3152 if (retries >= 14 ||
3153 (!server->noblocksnd && (retries > 2))) {
3154 cifs_server_dbg(VFS, "sends on sock %p stuck for 15 seconds\n",
3155 server->ssocket);
3156 return -EAGAIN;
3157 }
3158 msleep(1 << retries);
3159 continue;
3160 }
3161
3162 if (rc < 0)
3163 return rc;
3164
3165 if (rc == 0) {
3166 cifs_dbg(FYI, "Received no data (TCP RST)\n");
3167 return -ECONNABORTED;
3168 }
3169
3170 /* recv was at least partially successful */
3171 *recv += rc;
3172 retries = 0; /* in case we get ENOSPC on the next send */
3173 }
3174 return 0;
3175 }
3176
3177 static int
ip_rfc1001_connect(struct TCP_Server_Info * server)3178 ip_rfc1001_connect(struct TCP_Server_Info *server)
3179 {
3180 int rc = 0;
3181 /*
3182 * some servers require RFC1001 sessinit before sending
3183 * negprot - BB check reconnection in case where second
3184 * sessinit is sent but no second negprot
3185 */
3186 struct rfc1002_session_packet req = {};
3187 struct rfc1002_session_packet resp = {};
3188 struct msghdr msg = {};
3189 struct kvec iov = {};
3190 unsigned int len;
3191 size_t sent;
3192 size_t recv;
3193
3194 req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
3195
3196 if (server->server_RFC1001_name[0] != 0)
3197 rfc1002mangle(req.trailer.session_req.called_name,
3198 server->server_RFC1001_name,
3199 RFC1001_NAME_LEN_WITH_NULL);
3200 else
3201 rfc1002mangle(req.trailer.session_req.called_name,
3202 DEFAULT_CIFS_CALLED_NAME,
3203 RFC1001_NAME_LEN_WITH_NULL);
3204
3205 req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
3206
3207 /* calling name ends in null (byte 16) from old smb convention */
3208 if (server->workstation_RFC1001_name[0] != 0)
3209 rfc1002mangle(req.trailer.session_req.calling_name,
3210 server->workstation_RFC1001_name,
3211 RFC1001_NAME_LEN_WITH_NULL);
3212 else
3213 rfc1002mangle(req.trailer.session_req.calling_name,
3214 "LINUX_CIFS_CLNT",
3215 RFC1001_NAME_LEN_WITH_NULL);
3216
3217 /*
3218 * As per rfc1002, @len must be the number of bytes that follows the
3219 * length field of a rfc1002 session request payload.
3220 */
3221 len = sizeof(req.trailer.session_req);
3222 req.type = RFC1002_SESSION_REQUEST;
3223 req.flags = 0;
3224 req.length = cpu_to_be16(len);
3225 len += offsetof(typeof(req), trailer.session_req);
3226 iov.iov_base = &req;
3227 iov.iov_len = len;
3228 iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &iov, 1, len);
3229 rc = smb_send_kvec(server, &msg, &sent);
3230 if (rc < 0 || len != sent)
3231 return (rc == -EINTR || rc == -EAGAIN) ? rc : -ECONNABORTED;
3232
3233 /*
3234 * RFC1001 layer in at least one server requires very short break before
3235 * negprot presumably because not expecting negprot to follow so fast.
3236 * For example DOS SMB servers cannot process negprot if it was received
3237 * before the server sent response for SESSION_REQUEST packet. So, wait
3238 * for the response, read it and parse it as it can contain useful error
3239 * information (e.g. specified server name was incorrect). For example
3240 * even the latest Windows Server 2022 SMB1 server over port 139 send
3241 * error if its server name was in SESSION_REQUEST packet incorrect.
3242 * Nowadays usage of port 139 is not common, so waiting for reply here
3243 * does not slowing down mounting of common case (over port 445).
3244 */
3245 len = offsetof(typeof(resp), trailer);
3246 iov.iov_base = &resp;
3247 iov.iov_len = len;
3248 iov_iter_kvec(&msg.msg_iter, ITER_DEST, &iov, 1, len);
3249 rc = smb_recv_kvec(server, &msg, &recv);
3250 if (rc < 0 || recv != len)
3251 return (rc == -EINTR || rc == -EAGAIN) ? rc : -ECONNABORTED;
3252
3253 switch (resp.type) {
3254 case RFC1002_POSITIVE_SESSION_RESPONSE:
3255 if (be16_to_cpu(resp.length) != 0) {
3256 cifs_dbg(VFS, "RFC 1002 positive session response but with invalid non-zero length %u\n",
3257 be16_to_cpu(resp.length));
3258 return -EIO;
3259 }
3260 cifs_dbg(FYI, "RFC 1002 positive session response");
3261 break;
3262 case RFC1002_NEGATIVE_SESSION_RESPONSE:
3263 /* Read RFC1002 response error code and convert it to errno in rc */
3264 len = sizeof(resp.trailer.neg_ses_resp_error_code);
3265 iov.iov_base = &resp.trailer.neg_ses_resp_error_code;
3266 iov.iov_len = len;
3267 iov_iter_kvec(&msg.msg_iter, ITER_DEST, &iov, 1, len);
3268 if (be16_to_cpu(resp.length) == len &&
3269 smb_recv_kvec(server, &msg, &recv) == 0 &&
3270 recv == len) {
3271 cifs_dbg(VFS, "RFC 1002 negative session response with error 0x%x\n",
3272 resp.trailer.neg_ses_resp_error_code);
3273 switch (resp.trailer.neg_ses_resp_error_code) {
3274 case RFC1002_NOT_LISTENING_CALLED:
3275 /* server does not listen for specified server name */
3276 fallthrough;
3277 case RFC1002_NOT_PRESENT:
3278 /* server name is incorrect */
3279 rc = -ENOENT;
3280 cifs_dbg(VFS, "Server rejected NetBIOS servername %.15s\n",
3281 server->server_RFC1001_name[0] ?
3282 server->server_RFC1001_name :
3283 DEFAULT_CIFS_CALLED_NAME);
3284 cifs_dbg(VFS, "Specify correct NetBIOS servername in source path or with -o servern= option\n");
3285 break;
3286 case RFC1002_NOT_LISTENING_CALLING:
3287 /* client name was not accepted by server */
3288 rc = -EACCES;
3289 cifs_dbg(VFS, "Server rejected NetBIOS clientname %.15s\n",
3290 server->workstation_RFC1001_name[0] ?
3291 server->workstation_RFC1001_name :
3292 "LINUX_CIFS_CLNT");
3293 cifs_dbg(VFS, "Specify correct NetBIOS clientname with -o netbiosname= option\n");
3294 break;
3295 case RFC1002_INSUFFICIENT_RESOURCE:
3296 /* remote server resource error */
3297 rc = -EREMOTEIO;
3298 break;
3299 case RFC1002_UNSPECIFIED_ERROR:
3300 default:
3301 /* other/unknown error */
3302 rc = -EIO;
3303 break;
3304 }
3305 } else {
3306 cifs_dbg(VFS, "RFC 1002 negative session response\n");
3307 rc = -EIO;
3308 }
3309 return rc;
3310 case RFC1002_RETARGET_SESSION_RESPONSE:
3311 cifs_dbg(VFS, "RFC 1002 retarget session response\n");
3312 if (be16_to_cpu(resp.length) == sizeof(resp.trailer.retarget_resp)) {
3313 len = sizeof(resp.trailer.retarget_resp);
3314 iov.iov_base = &resp.trailer.retarget_resp;
3315 iov.iov_len = len;
3316 iov_iter_kvec(&msg.msg_iter, ITER_DEST, &iov, 1, len);
3317 if (smb_recv_kvec(server, &msg, &recv) == 0 && recv == len) {
3318 cifs_dbg(VFS, "Server wants to redirect connection\n");
3319 cifs_dbg(VFS, "Remount with options -o ip=%pI4,port=%u\n",
3320 &resp.trailer.retarget_resp.retarget_ip_addr,
3321 be16_to_cpu(resp.trailer.retarget_resp.port));
3322 }
3323 }
3324 cifs_dbg(VFS, "Closing connection\n");
3325 /* FIXME: Should we automatically redirect to new retarget_resp server? */
3326 return -EMULTIHOP;
3327 default:
3328 cifs_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", resp.type);
3329 return -EIO;
3330 }
3331
3332 server->with_rfc1001 = true;
3333 return 0;
3334 }
3335
3336 static int
generic_ip_connect(struct TCP_Server_Info * server)3337 generic_ip_connect(struct TCP_Server_Info *server)
3338 {
3339 struct sockaddr *saddr;
3340 struct socket *socket;
3341 int slen, sfamily;
3342 __be16 sport;
3343 int rc = 0;
3344
3345 saddr = (struct sockaddr *) &server->dstaddr;
3346
3347 if (server->dstaddr.ss_family == AF_INET6) {
3348 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3349
3350 sport = ipv6->sin6_port;
3351 slen = sizeof(struct sockaddr_in6);
3352 sfamily = AF_INET6;
3353 cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3354 ntohs(sport));
3355 } else {
3356 struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3357
3358 sport = ipv4->sin_port;
3359 slen = sizeof(struct sockaddr_in);
3360 sfamily = AF_INET;
3361 cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3362 ntohs(sport));
3363 }
3364
3365 if (server->ssocket) {
3366 socket = server->ssocket;
3367 } else {
3368 struct net *net = cifs_net_ns(server);
3369 struct sock *sk;
3370
3371 rc = __sock_create(net, sfamily, SOCK_STREAM,
3372 IPPROTO_TCP, &server->ssocket, 1);
3373 if (rc < 0) {
3374 cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3375 return rc;
3376 }
3377
3378 sk = server->ssocket->sk;
3379 __netns_tracker_free(net, &sk->ns_tracker, false);
3380 sk->sk_net_refcnt = 1;
3381 get_net_track(net, &sk->ns_tracker, GFP_KERNEL);
3382 sock_inuse_add(net, 1);
3383
3384 /* BB other socket options to set KEEPALIVE, NODELAY? */
3385 cifs_dbg(FYI, "Socket created\n");
3386 socket = server->ssocket;
3387 socket->sk->sk_allocation = GFP_NOFS;
3388 socket->sk->sk_use_task_frag = false;
3389 if (sfamily == AF_INET6)
3390 cifs_reclassify_socket6(socket);
3391 else
3392 cifs_reclassify_socket4(socket);
3393 }
3394
3395 rc = bind_socket(server);
3396 if (rc < 0)
3397 return rc;
3398
3399 /*
3400 * Eventually check for other socket options to change from
3401 * the default. sock_setsockopt not used because it expects
3402 * user space buffer
3403 */
3404 socket->sk->sk_rcvtimeo = 7 * HZ;
3405 socket->sk->sk_sndtimeo = 5 * HZ;
3406
3407 /* make the bufsizes depend on wsize/rsize and max requests */
3408 if (server->noautotune) {
3409 if (socket->sk->sk_sndbuf < (200 * 1024))
3410 socket->sk->sk_sndbuf = 200 * 1024;
3411 if (socket->sk->sk_rcvbuf < (140 * 1024))
3412 socket->sk->sk_rcvbuf = 140 * 1024;
3413 }
3414
3415 if (server->tcp_nodelay)
3416 tcp_sock_set_nodelay(socket->sk);
3417
3418 cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3419 socket->sk->sk_sndbuf,
3420 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3421
3422 rc = kernel_connect(socket, saddr, slen,
3423 server->noblockcnt ? O_NONBLOCK : 0);
3424 /*
3425 * When mounting SMB root file systems, we do not want to block in
3426 * connect. Otherwise bail out and then let cifs_reconnect() perform
3427 * reconnect failover - if possible.
3428 */
3429 if (server->noblockcnt && rc == -EINPROGRESS)
3430 rc = 0;
3431 if (rc < 0) {
3432 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3433 trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3434 sock_release(socket);
3435 server->ssocket = NULL;
3436 return rc;
3437 }
3438 trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3439
3440 /*
3441 * Establish RFC1001 NetBIOS session when it was explicitly requested
3442 * by mount option -o nbsessinit, or when connecting to default RFC1001
3443 * server port (139) and it was not explicitly disabled by mount option
3444 * -o nonbsessinit.
3445 */
3446 if (server->with_rfc1001 ||
3447 server->rfc1001_sessinit == 1 ||
3448 (server->rfc1001_sessinit == -1 && sport == htons(RFC1001_PORT)))
3449 rc = ip_rfc1001_connect(server);
3450
3451 return rc;
3452 }
3453
3454 static int
ip_connect(struct TCP_Server_Info * server)3455 ip_connect(struct TCP_Server_Info *server)
3456 {
3457 __be16 *sport;
3458 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3459 struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3460
3461 if (server->dstaddr.ss_family == AF_INET6)
3462 sport = &addr6->sin6_port;
3463 else
3464 sport = &addr->sin_port;
3465
3466 if (*sport == 0) {
3467 int rc;
3468
3469 /* try with 445 port at first */
3470 *sport = htons(CIFS_PORT);
3471
3472 rc = generic_ip_connect(server);
3473 if (rc >= 0)
3474 return rc;
3475
3476 /* if it failed, try with 139 port */
3477 *sport = htons(RFC1001_PORT);
3478 }
3479
3480 return generic_ip_connect(server);
3481 }
3482
3483 #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)3484 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3485 struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3486 {
3487 /*
3488 * If we are reconnecting then should we check to see if
3489 * any requested capabilities changed locally e.g. via
3490 * remount but we can not do much about it here
3491 * if they have (even if we could detect it by the following)
3492 * Perhaps we could add a backpointer to array of sb from tcon
3493 * or if we change to make all sb to same share the same
3494 * sb as NFS - then we only have one backpointer to sb.
3495 * What if we wanted to mount the server share twice once with
3496 * and once without posixacls or posix paths?
3497 */
3498 __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3499
3500 if (ctx && ctx->no_linux_ext) {
3501 tcon->fsUnixInfo.Capability = 0;
3502 tcon->unix_ext = 0; /* Unix Extensions disabled */
3503 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3504 return;
3505 } else if (ctx)
3506 tcon->unix_ext = 1; /* Unix Extensions supported */
3507
3508 if (!tcon->unix_ext) {
3509 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3510 return;
3511 }
3512
3513 if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3514 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3515
3516 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3517 /*
3518 * check for reconnect case in which we do not
3519 * want to change the mount behavior if we can avoid it
3520 */
3521 if (ctx == NULL) {
3522 /*
3523 * turn off POSIX ACL and PATHNAMES if not set
3524 * originally at mount time
3525 */
3526 if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3527 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3528 if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3529 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3530 cifs_dbg(VFS, "POSIXPATH support change\n");
3531 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3532 } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3533 cifs_dbg(VFS, "possible reconnect error\n");
3534 cifs_dbg(VFS, "server disabled POSIX path support\n");
3535 }
3536 }
3537
3538 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3539 cifs_dbg(VFS, "per-share encryption not supported yet\n");
3540
3541 cap &= CIFS_UNIX_CAP_MASK;
3542 if (ctx && ctx->no_psx_acl)
3543 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3544 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3545 cifs_dbg(FYI, "negotiated posix acl support\n");
3546 if (cifs_sb)
3547 cifs_sb->mnt_cifs_flags |=
3548 CIFS_MOUNT_POSIXACL;
3549 }
3550
3551 if (ctx && ctx->posix_paths == 0)
3552 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3553 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3554 cifs_dbg(FYI, "negotiate posix pathnames\n");
3555 if (cifs_sb)
3556 cifs_sb->mnt_cifs_flags |=
3557 CIFS_MOUNT_POSIX_PATHS;
3558 }
3559
3560 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3561 #ifdef CONFIG_CIFS_DEBUG2
3562 if (cap & CIFS_UNIX_FCNTL_CAP)
3563 cifs_dbg(FYI, "FCNTL cap\n");
3564 if (cap & CIFS_UNIX_EXTATTR_CAP)
3565 cifs_dbg(FYI, "EXTATTR cap\n");
3566 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3567 cifs_dbg(FYI, "POSIX path cap\n");
3568 if (cap & CIFS_UNIX_XATTR_CAP)
3569 cifs_dbg(FYI, "XATTR cap\n");
3570 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3571 cifs_dbg(FYI, "POSIX ACL cap\n");
3572 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3573 cifs_dbg(FYI, "very large read cap\n");
3574 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3575 cifs_dbg(FYI, "very large write cap\n");
3576 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3577 cifs_dbg(FYI, "transport encryption cap\n");
3578 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3579 cifs_dbg(FYI, "mandatory transport encryption cap\n");
3580 #endif /* CIFS_DEBUG2 */
3581 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3582 if (ctx == NULL)
3583 cifs_dbg(FYI, "resetting capabilities failed\n");
3584 else
3585 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");
3586
3587 }
3588 }
3589 }
3590 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3591
cifs_setup_cifs_sb(struct cifs_sb_info * cifs_sb)3592 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3593 {
3594 struct smb3_fs_context *ctx = cifs_sb->ctx;
3595
3596 INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3597 INIT_LIST_HEAD(&cifs_sb->tcon_sb_link);
3598
3599 spin_lock_init(&cifs_sb->tlink_tree_lock);
3600 cifs_sb->tlink_tree = RB_ROOT;
3601
3602 cifs_dbg(FYI, "file mode: %04ho dir mode: %04ho\n",
3603 ctx->file_mode, ctx->dir_mode);
3604
3605 /* this is needed for ASCII cp to Unicode converts */
3606 if (ctx->iocharset == NULL) {
3607 /* load_nls_default cannot return null */
3608 cifs_sb->local_nls = load_nls_default();
3609 } else {
3610 cifs_sb->local_nls = load_nls(ctx->iocharset);
3611 if (cifs_sb->local_nls == NULL) {
3612 cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3613 ctx->iocharset);
3614 return -ELIBACC;
3615 }
3616 }
3617 ctx->local_nls = cifs_sb->local_nls;
3618
3619 smb3_update_mnt_flags(cifs_sb);
3620
3621 if (ctx->direct_io)
3622 cifs_dbg(FYI, "mounting share using direct i/o\n");
3623 if (ctx->cache_ro) {
3624 cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3625 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3626 } else if (ctx->cache_rw) {
3627 cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3628 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3629 CIFS_MOUNT_RW_CACHE);
3630 }
3631
3632 if ((ctx->cifs_acl) && (ctx->dynperm))
3633 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3634
3635 if (ctx->prepath) {
3636 cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3637 if (cifs_sb->prepath == NULL)
3638 return -ENOMEM;
3639 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3640 }
3641
3642 return 0;
3643 }
3644
3645 /* Release all succeed connections */
cifs_mount_put_conns(struct cifs_mount_ctx * mnt_ctx)3646 void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3647 {
3648 int rc = 0;
3649
3650 if (mnt_ctx->tcon)
3651 cifs_put_tcon(mnt_ctx->tcon, netfs_trace_tcon_ref_put_mnt_ctx);
3652 else if (mnt_ctx->ses)
3653 cifs_put_smb_ses(mnt_ctx->ses);
3654 else if (mnt_ctx->server)
3655 cifs_put_tcp_session(mnt_ctx->server, 0);
3656 mnt_ctx->ses = NULL;
3657 mnt_ctx->tcon = NULL;
3658 mnt_ctx->server = NULL;
3659 mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3660 free_xid(mnt_ctx->xid);
3661 }
3662
cifs_mount_get_session(struct cifs_mount_ctx * mnt_ctx)3663 int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3664 {
3665 struct TCP_Server_Info *server = NULL;
3666 struct smb3_fs_context *ctx;
3667 struct cifs_ses *ses = NULL;
3668 unsigned int xid;
3669 int rc = 0;
3670
3671 xid = get_xid();
3672
3673 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3674 rc = -EINVAL;
3675 goto out;
3676 }
3677 ctx = mnt_ctx->fs_ctx;
3678
3679 /* get a reference to a tcp session */
3680 server = cifs_get_tcp_session(ctx, NULL);
3681 if (IS_ERR(server)) {
3682 rc = PTR_ERR(server);
3683 server = NULL;
3684 goto out;
3685 }
3686
3687 /* get a reference to a SMB session */
3688 ses = cifs_get_smb_ses(server, ctx);
3689 if (IS_ERR(ses)) {
3690 rc = PTR_ERR(ses);
3691 ses = NULL;
3692 goto out;
3693 }
3694
3695 if ((ctx->persistent == true) && (!(ses->server->capabilities &
3696 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3697 cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3698 rc = -EOPNOTSUPP;
3699 }
3700
3701 out:
3702 mnt_ctx->xid = xid;
3703 mnt_ctx->server = server;
3704 mnt_ctx->ses = ses;
3705 mnt_ctx->tcon = NULL;
3706
3707 return rc;
3708 }
3709
cifs_mount_get_tcon(struct cifs_mount_ctx * mnt_ctx)3710 int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3711 {
3712 struct TCP_Server_Info *server;
3713 struct cifs_sb_info *cifs_sb;
3714 struct smb3_fs_context *ctx;
3715 struct cifs_tcon *tcon = NULL;
3716 int rc = 0;
3717
3718 if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3719 !mnt_ctx->cifs_sb)) {
3720 rc = -EINVAL;
3721 goto out;
3722 }
3723 server = mnt_ctx->server;
3724 ctx = mnt_ctx->fs_ctx;
3725 cifs_sb = mnt_ctx->cifs_sb;
3726
3727 /* search for existing tcon to this server share */
3728 tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3729 if (IS_ERR(tcon)) {
3730 rc = PTR_ERR(tcon);
3731 tcon = NULL;
3732 goto out;
3733 }
3734
3735 /*
3736 * if new SMB3.11 POSIX extensions are supported, do not change anything in the
3737 * path (i.e., do not remap / and \ and do not map any special characters)
3738 */
3739 if (tcon->posix_extensions) {
3740 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3741 cifs_sb->mnt_cifs_flags &= ~(CIFS_MOUNT_MAP_SFM_CHR |
3742 CIFS_MOUNT_MAP_SPECIAL_CHR);
3743 }
3744
3745 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3746 /* tell server which Unix caps we support */
3747 if (cap_unix(tcon->ses)) {
3748 /*
3749 * reset of caps checks mount to see if unix extensions disabled
3750 * for just this mount.
3751 */
3752 reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3753 spin_lock(&tcon->ses->server->srv_lock);
3754 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3755 (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3756 CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3757 spin_unlock(&tcon->ses->server->srv_lock);
3758 rc = -EACCES;
3759 goto out;
3760 }
3761 spin_unlock(&tcon->ses->server->srv_lock);
3762 } else
3763 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3764 tcon->unix_ext = 0; /* server does not support them */
3765
3766 /* do not care if a following call succeed - informational */
3767 if (!tcon->pipe && server->ops->qfs_tcon) {
3768 server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3769 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3770 if (tcon->fsDevInfo.DeviceCharacteristics &
3771 cpu_to_le32(FILE_READ_ONLY_DEVICE))
3772 cifs_dbg(VFS, "mounted to read only share\n");
3773 else if ((cifs_sb->mnt_cifs_flags &
3774 CIFS_MOUNT_RW_CACHE) == 0)
3775 cifs_dbg(VFS, "read only mount of RW share\n");
3776 /* no need to log a RW mount of a typical RW share */
3777 }
3778 }
3779
3780 cifs_negotiate_iosize(server, cifs_sb->ctx, tcon);
3781 /*
3782 * The cookie is initialized from volume info returned above.
3783 * Inside cifs_fscache_get_super_cookie it checks
3784 * that we do not get super cookie twice.
3785 */
3786 if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3787 cifs_fscache_get_super_cookie(tcon);
3788
3789 out:
3790 mnt_ctx->tcon = tcon;
3791 return rc;
3792 }
3793
mount_setup_tlink(struct cifs_sb_info * cifs_sb,struct cifs_ses * ses,struct cifs_tcon * tcon)3794 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3795 struct cifs_tcon *tcon)
3796 {
3797 struct tcon_link *tlink;
3798
3799 /* hang the tcon off of the superblock */
3800 tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3801 if (tlink == NULL)
3802 return -ENOMEM;
3803
3804 tlink->tl_uid = ses->linux_uid;
3805 tlink->tl_tcon = tcon;
3806 tlink->tl_time = jiffies;
3807 set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3808 set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3809
3810 cifs_sb->master_tlink = tlink;
3811 spin_lock(&cifs_sb->tlink_tree_lock);
3812 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3813 spin_unlock(&cifs_sb->tlink_tree_lock);
3814
3815 spin_lock(&tcon->sb_list_lock);
3816 list_add(&cifs_sb->tcon_sb_link, &tcon->cifs_sb_list);
3817 spin_unlock(&tcon->sb_list_lock);
3818
3819 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3820 TLINK_IDLE_EXPIRE);
3821 return 0;
3822 }
3823
3824 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)3825 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3826 unsigned int xid,
3827 struct cifs_tcon *tcon,
3828 struct cifs_sb_info *cifs_sb,
3829 char *full_path,
3830 int added_treename)
3831 {
3832 int rc;
3833 char *s;
3834 char sep, tmp;
3835 int skip = added_treename ? 1 : 0;
3836
3837 sep = CIFS_DIR_SEP(cifs_sb);
3838 s = full_path;
3839
3840 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3841 while (rc == 0) {
3842 /* skip separators */
3843 while (*s == sep)
3844 s++;
3845 if (!*s)
3846 break;
3847 /* next separator */
3848 while (*s && *s != sep)
3849 s++;
3850 /*
3851 * if the treename is added, we then have to skip the first
3852 * part within the separators
3853 */
3854 if (skip) {
3855 skip = 0;
3856 continue;
3857 }
3858 /*
3859 * temporarily null-terminate the path at the end of
3860 * the current component
3861 */
3862 tmp = *s;
3863 *s = 0;
3864 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3865 full_path);
3866 *s = tmp;
3867 }
3868 return rc;
3869 }
3870
3871 /*
3872 * Check if path is remote (i.e. a DFS share).
3873 *
3874 * Return -EREMOTE if it is, otherwise 0 or -errno.
3875 */
cifs_is_path_remote(struct cifs_mount_ctx * mnt_ctx)3876 int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3877 {
3878 int rc;
3879 struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3880 struct TCP_Server_Info *server = mnt_ctx->server;
3881 unsigned int xid = mnt_ctx->xid;
3882 struct cifs_tcon *tcon = mnt_ctx->tcon;
3883 struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3884 char *full_path;
3885
3886 if (!server->ops->is_path_accessible)
3887 return -EOPNOTSUPP;
3888
3889 /*
3890 * cifs_build_path_to_root works only when we have a valid tcon
3891 */
3892 full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3893 tcon->Flags & SMB_SHARE_IS_IN_DFS);
3894 if (full_path == NULL)
3895 return -ENOMEM;
3896
3897 cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3898
3899 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3900 full_path);
3901 if (rc != 0 && rc != -EREMOTE)
3902 goto out;
3903
3904 if (rc != -EREMOTE) {
3905 rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3906 cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3907 if (rc != 0) {
3908 cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3909 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3910 rc = 0;
3911 }
3912 }
3913
3914 out:
3915 kfree(full_path);
3916 return rc;
3917 }
3918
3919 #ifdef CONFIG_CIFS_DFS_UPCALL
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3920 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3921 {
3922 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3923 int rc;
3924
3925 rc = dfs_mount_share(&mnt_ctx);
3926 if (rc)
3927 goto error;
3928 if (!ctx->dfs_conn)
3929 goto out;
3930
3931 /*
3932 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3933 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3934 */
3935 cifs_autodisable_serverino(cifs_sb);
3936 /*
3937 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3938 * that have different prefix paths.
3939 */
3940 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3941 kfree(cifs_sb->prepath);
3942 cifs_sb->prepath = ctx->prepath;
3943 ctx->prepath = NULL;
3944
3945 out:
3946 cifs_try_adding_channels(mnt_ctx.ses);
3947 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3948 if (rc)
3949 goto error;
3950
3951 free_xid(mnt_ctx.xid);
3952 return rc;
3953
3954 error:
3955 cifs_mount_put_conns(&mnt_ctx);
3956 return rc;
3957 }
3958 #else
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3959 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3960 {
3961 int rc = 0;
3962 struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3963
3964 rc = cifs_mount_get_session(&mnt_ctx);
3965 if (rc)
3966 goto error;
3967
3968 rc = cifs_mount_get_tcon(&mnt_ctx);
3969 if (!rc) {
3970 /*
3971 * Prevent superblock from being created with any missing
3972 * connections.
3973 */
3974 if (WARN_ON(!mnt_ctx.server))
3975 rc = -EHOSTDOWN;
3976 else if (WARN_ON(!mnt_ctx.ses))
3977 rc = -EACCES;
3978 else if (WARN_ON(!mnt_ctx.tcon))
3979 rc = -ENOENT;
3980 }
3981 if (rc)
3982 goto error;
3983
3984 rc = cifs_is_path_remote(&mnt_ctx);
3985 if (rc == -EREMOTE)
3986 rc = -EOPNOTSUPP;
3987 if (rc)
3988 goto error;
3989
3990 rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3991 if (rc)
3992 goto error;
3993
3994 free_xid(mnt_ctx.xid);
3995 return rc;
3996
3997 error:
3998 cifs_mount_put_conns(&mnt_ctx);
3999 return rc;
4000 }
4001 #endif
4002
4003 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4004 /*
4005 * Issue a TREE_CONNECT request.
4006 */
4007 int
CIFSTCon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * nls_codepage)4008 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
4009 const char *tree, struct cifs_tcon *tcon,
4010 const struct nls_table *nls_codepage)
4011 {
4012 struct smb_hdr *smb_buffer;
4013 struct smb_hdr *smb_buffer_response;
4014 TCONX_REQ *pSMB;
4015 TCONX_RSP *pSMBr;
4016 unsigned char *bcc_ptr;
4017 int rc = 0;
4018 int length;
4019 __u16 bytes_left, count;
4020
4021 if (ses == NULL)
4022 return -EIO;
4023
4024 smb_buffer = cifs_buf_get();
4025 if (smb_buffer == NULL)
4026 return -ENOMEM;
4027
4028 smb_buffer_response = smb_buffer;
4029
4030 header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
4031 NULL /*no tid */, 4 /*wct */);
4032
4033 smb_buffer->Mid = get_next_mid(ses->server);
4034 smb_buffer->Uid = ses->Suid;
4035 pSMB = (TCONX_REQ *) smb_buffer;
4036 pSMBr = (TCONX_RSP *) smb_buffer_response;
4037
4038 pSMB->AndXCommand = 0xFF;
4039 pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
4040 bcc_ptr = &pSMB->Password[0];
4041
4042 pSMB->PasswordLength = cpu_to_le16(1); /* minimum */
4043 *bcc_ptr = 0; /* password is null byte */
4044 bcc_ptr++; /* skip password */
4045 /* already aligned so no need to do it below */
4046
4047 if (ses->server->sign)
4048 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
4049
4050 if (ses->capabilities & CAP_STATUS32)
4051 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
4052
4053 if (ses->capabilities & CAP_DFS)
4054 smb_buffer->Flags2 |= SMBFLG2_DFS;
4055
4056 if (ses->capabilities & CAP_UNICODE) {
4057 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
4058 length =
4059 cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
4060 6 /* max utf8 char length in bytes */ *
4061 (/* server len*/ + 256 /* share len */), nls_codepage);
4062 bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */
4063 bcc_ptr += 2; /* skip trailing null */
4064 } else { /* ASCII */
4065 strcpy(bcc_ptr, tree);
4066 bcc_ptr += strlen(tree) + 1;
4067 }
4068 strcpy(bcc_ptr, "?????");
4069 bcc_ptr += strlen("?????");
4070 bcc_ptr += 1;
4071 count = bcc_ptr - &pSMB->Password[0];
4072 be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
4073 pSMB->ByteCount = cpu_to_le16(count);
4074
4075 rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
4076 0);
4077
4078 /* above now done in SendReceive */
4079 if (rc == 0) {
4080 bool is_unicode;
4081
4082 tcon->tid = smb_buffer_response->Tid;
4083 bcc_ptr = pByteArea(smb_buffer_response);
4084 bytes_left = get_bcc(smb_buffer_response);
4085 length = strnlen(bcc_ptr, bytes_left - 2);
4086 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
4087 is_unicode = true;
4088 else
4089 is_unicode = false;
4090
4091
4092 /* skip service field (NB: this field is always ASCII) */
4093 if (length == 3) {
4094 if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
4095 (bcc_ptr[2] == 'C')) {
4096 cifs_dbg(FYI, "IPC connection\n");
4097 tcon->ipc = true;
4098 tcon->pipe = true;
4099 }
4100 } else if (length == 2) {
4101 if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
4102 /* the most common case */
4103 cifs_dbg(FYI, "disk share connection\n");
4104 }
4105 }
4106 bcc_ptr += length + 1;
4107 bytes_left -= (length + 1);
4108 strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
4109
4110 /* mostly informational -- no need to fail on error here */
4111 kfree(tcon->nativeFileSystem);
4112 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
4113 bytes_left, is_unicode,
4114 nls_codepage);
4115
4116 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
4117
4118 if ((smb_buffer_response->WordCount == 3) ||
4119 (smb_buffer_response->WordCount == 7))
4120 /* field is in same location */
4121 tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
4122 else
4123 tcon->Flags = 0;
4124 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
4125
4126 /*
4127 * reset_cifs_unix_caps calls QFSInfo which requires
4128 * need_reconnect to be false, but we would not need to call
4129 * reset_caps if this were not a reconnect case so must check
4130 * need_reconnect flag here. The caller will also clear
4131 * need_reconnect when tcon was successful but needed to be
4132 * cleared earlier in the case of unix extensions reconnect
4133 */
4134 if (tcon->need_reconnect && tcon->unix_ext) {
4135 cifs_dbg(FYI, "resetting caps for %s\n", tcon->tree_name);
4136 tcon->need_reconnect = false;
4137 reset_cifs_unix_caps(xid, tcon, NULL, NULL);
4138 }
4139 }
4140 cifs_buf_release(smb_buffer);
4141 return rc;
4142 }
4143 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4144
delayed_free(struct rcu_head * p)4145 static void delayed_free(struct rcu_head *p)
4146 {
4147 struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
4148
4149 unload_nls(cifs_sb->local_nls);
4150 smb3_cleanup_fs_context(cifs_sb->ctx);
4151 kfree(cifs_sb);
4152 }
4153
4154 void
cifs_umount(struct cifs_sb_info * cifs_sb)4155 cifs_umount(struct cifs_sb_info *cifs_sb)
4156 {
4157 struct rb_root *root = &cifs_sb->tlink_tree;
4158 struct rb_node *node;
4159 struct tcon_link *tlink;
4160 struct cifs_tcon *tcon = NULL;
4161
4162 cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
4163
4164 if (cifs_sb->master_tlink) {
4165 tcon = cifs_sb->master_tlink->tl_tcon;
4166 if (tcon) {
4167 spin_lock(&tcon->sb_list_lock);
4168 list_del_init(&cifs_sb->tcon_sb_link);
4169 spin_unlock(&tcon->sb_list_lock);
4170 }
4171 }
4172
4173 spin_lock(&cifs_sb->tlink_tree_lock);
4174 while ((node = rb_first(root))) {
4175 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4176 cifs_get_tlink(tlink);
4177 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4178 rb_erase(node, root);
4179
4180 spin_unlock(&cifs_sb->tlink_tree_lock);
4181 cifs_put_tlink(tlink);
4182 spin_lock(&cifs_sb->tlink_tree_lock);
4183 }
4184 spin_unlock(&cifs_sb->tlink_tree_lock);
4185
4186 kfree(cifs_sb->prepath);
4187 call_rcu(&cifs_sb->rcu, delayed_free);
4188 }
4189
4190 int
cifs_negotiate_protocol(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server)4191 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
4192 struct TCP_Server_Info *server)
4193 {
4194 bool in_retry = false;
4195 int rc = 0;
4196
4197 if (!server->ops->need_neg || !server->ops->negotiate)
4198 return -ENOSYS;
4199
4200 retry:
4201 /* only send once per connect */
4202 spin_lock(&server->srv_lock);
4203 if (server->tcpStatus != CifsGood &&
4204 server->tcpStatus != CifsNew &&
4205 server->tcpStatus != CifsNeedNegotiate) {
4206 spin_unlock(&server->srv_lock);
4207 return -EHOSTDOWN;
4208 }
4209
4210 if (!server->ops->need_neg(server) &&
4211 server->tcpStatus == CifsGood) {
4212 spin_unlock(&server->srv_lock);
4213 return 0;
4214 }
4215
4216 server->lstrp = jiffies;
4217 server->tcpStatus = CifsInNegotiate;
4218 spin_unlock(&server->srv_lock);
4219
4220 rc = server->ops->negotiate(xid, ses, server);
4221 if (rc == -EAGAIN) {
4222 /* Allow one retry attempt */
4223 if (!in_retry) {
4224 in_retry = true;
4225 goto retry;
4226 }
4227 rc = -EHOSTDOWN;
4228 }
4229 if (rc == 0) {
4230 spin_lock(&server->srv_lock);
4231 if (server->tcpStatus == CifsInNegotiate)
4232 server->tcpStatus = CifsGood;
4233 else
4234 rc = -EHOSTDOWN;
4235 spin_unlock(&server->srv_lock);
4236 } else {
4237 spin_lock(&server->srv_lock);
4238 if (server->tcpStatus == CifsInNegotiate)
4239 server->tcpStatus = CifsNeedNegotiate;
4240 spin_unlock(&server->srv_lock);
4241 }
4242
4243 return rc;
4244 }
4245
4246 int
cifs_setup_session(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,struct nls_table * nls_info)4247 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4248 struct TCP_Server_Info *server,
4249 struct nls_table *nls_info)
4250 {
4251 int rc = 0;
4252 struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4253 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
4254 struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
4255 bool is_binding = false;
4256
4257 spin_lock(&ses->ses_lock);
4258 cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
4259 __func__, ses->chans_need_reconnect);
4260
4261 if (ses->ses_status != SES_GOOD &&
4262 ses->ses_status != SES_NEW &&
4263 ses->ses_status != SES_NEED_RECON) {
4264 spin_unlock(&ses->ses_lock);
4265 return -EHOSTDOWN;
4266 }
4267
4268 /* only send once per connect */
4269 spin_lock(&ses->chan_lock);
4270 if (CIFS_ALL_CHANS_GOOD(ses)) {
4271 if (ses->ses_status == SES_NEED_RECON)
4272 ses->ses_status = SES_GOOD;
4273 spin_unlock(&ses->chan_lock);
4274 spin_unlock(&ses->ses_lock);
4275 return 0;
4276 }
4277
4278 cifs_chan_set_in_reconnect(ses, server);
4279 is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4280 spin_unlock(&ses->chan_lock);
4281
4282 if (!is_binding) {
4283 ses->ses_status = SES_IN_SETUP;
4284
4285 /* force iface_list refresh */
4286 ses->iface_last_update = 0;
4287 }
4288 spin_unlock(&ses->ses_lock);
4289
4290 /* update ses ip_addr only for primary chan */
4291 if (server == pserver) {
4292 if (server->dstaddr.ss_family == AF_INET6)
4293 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4294 else
4295 scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4296 }
4297
4298 if (!is_binding) {
4299 ses->capabilities = server->capabilities;
4300 if (!linuxExtEnabled)
4301 ses->capabilities &= (~server->vals->cap_unix);
4302
4303 /*
4304 * Check if the server supports specified encoding mode.
4305 * Zero value in vals->cap_unicode indidcates that chosen
4306 * protocol dialect does not support non-UNICODE mode.
4307 */
4308 if (ses->unicode == 1 && server->vals->cap_unicode != 0 &&
4309 !(server->capabilities & server->vals->cap_unicode)) {
4310 cifs_dbg(VFS, "Server does not support mounting in UNICODE mode\n");
4311 rc = -EOPNOTSUPP;
4312 } else if (ses->unicode == 0 && server->vals->cap_unicode == 0) {
4313 cifs_dbg(VFS, "Server does not support mounting in non-UNICODE mode\n");
4314 rc = -EOPNOTSUPP;
4315 } else if (ses->unicode == 0) {
4316 /*
4317 * When UNICODE mode was explicitly disabled then
4318 * do not announce client UNICODE capability.
4319 */
4320 ses->capabilities &= (~server->vals->cap_unicode);
4321 }
4322
4323 if (ses->auth_key.response) {
4324 cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4325 ses->auth_key.response);
4326 kfree_sensitive(ses->auth_key.response);
4327 ses->auth_key.response = NULL;
4328 ses->auth_key.len = 0;
4329 }
4330 }
4331
4332 cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4333 server->sec_mode, server->capabilities, server->timeAdj);
4334
4335 if (!rc) {
4336 if (server->ops->sess_setup)
4337 rc = server->ops->sess_setup(xid, ses, server, nls_info);
4338 else
4339 rc = -ENOSYS;
4340 }
4341
4342 if (rc) {
4343 cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4344 spin_lock(&ses->ses_lock);
4345 if (ses->ses_status == SES_IN_SETUP)
4346 ses->ses_status = SES_NEED_RECON;
4347 spin_lock(&ses->chan_lock);
4348 cifs_chan_clear_in_reconnect(ses, server);
4349 spin_unlock(&ses->chan_lock);
4350 spin_unlock(&ses->ses_lock);
4351 } else {
4352 spin_lock(&ses->ses_lock);
4353 if (ses->ses_status == SES_IN_SETUP)
4354 ses->ses_status = SES_GOOD;
4355 spin_lock(&ses->chan_lock);
4356 cifs_chan_clear_in_reconnect(ses, server);
4357 cifs_chan_clear_need_reconnect(ses, server);
4358 spin_unlock(&ses->chan_lock);
4359 spin_unlock(&ses->ses_lock);
4360 }
4361
4362 return rc;
4363 }
4364
4365 static int
cifs_set_vol_auth(struct smb3_fs_context * ctx,struct cifs_ses * ses)4366 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4367 {
4368 ctx->sectype = ses->sectype;
4369
4370 /* krb5 is special, since we don't need username or pw */
4371 if (ctx->sectype == Kerberos)
4372 return 0;
4373
4374 return cifs_set_cifscreds(ctx, ses);
4375 }
4376
4377 static struct cifs_tcon *
cifs_construct_tcon(struct cifs_sb_info * cifs_sb,kuid_t fsuid)4378 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4379 {
4380 int rc;
4381 struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4382 struct cifs_ses *ses;
4383 struct cifs_tcon *tcon = NULL;
4384 struct smb3_fs_context *ctx;
4385 char *origin_fullpath = NULL;
4386
4387 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4388 if (ctx == NULL)
4389 return ERR_PTR(-ENOMEM);
4390
4391 ctx->local_nls = cifs_sb->local_nls;
4392 ctx->linux_uid = fsuid;
4393 ctx->cred_uid = fsuid;
4394 ctx->UNC = master_tcon->tree_name;
4395 ctx->retry = master_tcon->retry;
4396 ctx->nocase = master_tcon->nocase;
4397 ctx->nohandlecache = master_tcon->nohandlecache;
4398 ctx->local_lease = master_tcon->local_lease;
4399 ctx->no_lease = master_tcon->no_lease;
4400 ctx->resilient = master_tcon->use_resilient;
4401 ctx->persistent = master_tcon->use_persistent;
4402 ctx->handle_timeout = master_tcon->handle_timeout;
4403 ctx->no_linux_ext = !master_tcon->unix_ext;
4404 ctx->linux_ext = master_tcon->posix_extensions;
4405 ctx->sectype = master_tcon->ses->sectype;
4406 ctx->sign = master_tcon->ses->sign;
4407 ctx->seal = master_tcon->seal;
4408 ctx->witness = master_tcon->use_witness;
4409 ctx->dfs_root_ses = master_tcon->ses->dfs_root_ses;
4410 ctx->unicode = master_tcon->ses->unicode;
4411
4412 rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4413 if (rc) {
4414 tcon = ERR_PTR(rc);
4415 goto out;
4416 }
4417
4418 /* get a reference for the same TCP session */
4419 spin_lock(&cifs_tcp_ses_lock);
4420 ++master_tcon->ses->server->srv_count;
4421 spin_unlock(&cifs_tcp_ses_lock);
4422
4423 ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4424 if (IS_ERR(ses)) {
4425 tcon = ERR_CAST(ses);
4426 cifs_put_tcp_session(master_tcon->ses->server, 0);
4427 goto out;
4428 }
4429
4430 #ifdef CONFIG_CIFS_DFS_UPCALL
4431 spin_lock(&master_tcon->tc_lock);
4432 if (master_tcon->origin_fullpath) {
4433 spin_unlock(&master_tcon->tc_lock);
4434 origin_fullpath = dfs_get_path(cifs_sb, cifs_sb->ctx->source);
4435 if (IS_ERR(origin_fullpath)) {
4436 tcon = ERR_CAST(origin_fullpath);
4437 origin_fullpath = NULL;
4438 cifs_put_smb_ses(ses);
4439 goto out;
4440 }
4441 } else {
4442 spin_unlock(&master_tcon->tc_lock);
4443 }
4444 #endif
4445
4446 tcon = cifs_get_tcon(ses, ctx);
4447 if (IS_ERR(tcon)) {
4448 cifs_put_smb_ses(ses);
4449 goto out;
4450 }
4451
4452 #ifdef CONFIG_CIFS_DFS_UPCALL
4453 if (origin_fullpath) {
4454 spin_lock(&tcon->tc_lock);
4455 tcon->origin_fullpath = origin_fullpath;
4456 spin_unlock(&tcon->tc_lock);
4457 origin_fullpath = NULL;
4458 queue_delayed_work(dfscache_wq, &tcon->dfs_cache_work,
4459 dfs_cache_get_ttl() * HZ);
4460 }
4461 #endif
4462
4463 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4464 if (cap_unix(ses))
4465 reset_cifs_unix_caps(0, tcon, NULL, ctx);
4466 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4467
4468 out:
4469 kfree(ctx->username);
4470 kfree_sensitive(ctx->password);
4471 kfree(origin_fullpath);
4472 kfree(ctx);
4473
4474 return tcon;
4475 }
4476
4477 struct cifs_tcon *
cifs_sb_master_tcon(struct cifs_sb_info * cifs_sb)4478 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4479 {
4480 return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4481 }
4482
4483 /* find and return a tlink with given uid */
4484 static struct tcon_link *
tlink_rb_search(struct rb_root * root,kuid_t uid)4485 tlink_rb_search(struct rb_root *root, kuid_t uid)
4486 {
4487 struct rb_node *node = root->rb_node;
4488 struct tcon_link *tlink;
4489
4490 while (node) {
4491 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4492
4493 if (uid_gt(tlink->tl_uid, uid))
4494 node = node->rb_left;
4495 else if (uid_lt(tlink->tl_uid, uid))
4496 node = node->rb_right;
4497 else
4498 return tlink;
4499 }
4500 return NULL;
4501 }
4502
4503 /* insert a tcon_link into the tree */
4504 static void
tlink_rb_insert(struct rb_root * root,struct tcon_link * new_tlink)4505 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4506 {
4507 struct rb_node **new = &(root->rb_node), *parent = NULL;
4508 struct tcon_link *tlink;
4509
4510 while (*new) {
4511 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4512 parent = *new;
4513
4514 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4515 new = &((*new)->rb_left);
4516 else
4517 new = &((*new)->rb_right);
4518 }
4519
4520 rb_link_node(&new_tlink->tl_rbnode, parent, new);
4521 rb_insert_color(&new_tlink->tl_rbnode, root);
4522 }
4523
4524 /*
4525 * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4526 * current task.
4527 *
4528 * If the superblock doesn't refer to a multiuser mount, then just return
4529 * the master tcon for the mount.
4530 *
4531 * First, search the rbtree for an existing tcon for this fsuid. If one
4532 * exists, then check to see if it's pending construction. If it is then wait
4533 * for construction to complete. Once it's no longer pending, check to see if
4534 * it failed and either return an error or retry construction, depending on
4535 * the timeout.
4536 *
4537 * If one doesn't exist then insert a new tcon_link struct into the tree and
4538 * try to construct a new one.
4539 *
4540 * REMEMBER to call cifs_put_tlink() after successful calls to cifs_sb_tlink,
4541 * to avoid refcount issues
4542 */
4543 struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info * cifs_sb)4544 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4545 {
4546 struct tcon_link *tlink, *newtlink;
4547 kuid_t fsuid = current_fsuid();
4548 int err;
4549
4550 if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4551 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4552
4553 spin_lock(&cifs_sb->tlink_tree_lock);
4554 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4555 if (tlink)
4556 cifs_get_tlink(tlink);
4557 spin_unlock(&cifs_sb->tlink_tree_lock);
4558
4559 if (tlink == NULL) {
4560 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4561 if (newtlink == NULL)
4562 return ERR_PTR(-ENOMEM);
4563 newtlink->tl_uid = fsuid;
4564 newtlink->tl_tcon = ERR_PTR(-EACCES);
4565 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4566 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4567 cifs_get_tlink(newtlink);
4568
4569 spin_lock(&cifs_sb->tlink_tree_lock);
4570 /* was one inserted after previous search? */
4571 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4572 if (tlink) {
4573 cifs_get_tlink(tlink);
4574 spin_unlock(&cifs_sb->tlink_tree_lock);
4575 kfree(newtlink);
4576 goto wait_for_construction;
4577 }
4578 tlink = newtlink;
4579 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4580 spin_unlock(&cifs_sb->tlink_tree_lock);
4581 } else {
4582 wait_for_construction:
4583 err = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4584 TASK_INTERRUPTIBLE);
4585 if (err) {
4586 cifs_put_tlink(tlink);
4587 return ERR_PTR(-ERESTARTSYS);
4588 }
4589
4590 /* if it's good, return it */
4591 if (!IS_ERR(tlink->tl_tcon))
4592 return tlink;
4593
4594 /* return error if we tried this already recently */
4595 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4596 err = PTR_ERR(tlink->tl_tcon);
4597 cifs_put_tlink(tlink);
4598 return ERR_PTR(err);
4599 }
4600
4601 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4602 goto wait_for_construction;
4603 }
4604
4605 tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4606 clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4607 wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4608
4609 if (IS_ERR(tlink->tl_tcon)) {
4610 err = PTR_ERR(tlink->tl_tcon);
4611 if (err == -ENOKEY)
4612 err = -EACCES;
4613 cifs_put_tlink(tlink);
4614 return ERR_PTR(err);
4615 }
4616
4617 return tlink;
4618 }
4619
4620 /*
4621 * periodic workqueue job that scans tcon_tree for a superblock and closes
4622 * out tcons.
4623 */
4624 static void
cifs_prune_tlinks(struct work_struct * work)4625 cifs_prune_tlinks(struct work_struct *work)
4626 {
4627 struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4628 prune_tlinks.work);
4629 struct rb_root *root = &cifs_sb->tlink_tree;
4630 struct rb_node *node;
4631 struct rb_node *tmp;
4632 struct tcon_link *tlink;
4633
4634 /*
4635 * Because we drop the spinlock in the loop in order to put the tlink
4636 * it's not guarded against removal of links from the tree. The only
4637 * places that remove entries from the tree are this function and
4638 * umounts. Because this function is non-reentrant and is canceled
4639 * before umount can proceed, this is safe.
4640 */
4641 spin_lock(&cifs_sb->tlink_tree_lock);
4642 node = rb_first(root);
4643 while (node != NULL) {
4644 tmp = node;
4645 node = rb_next(tmp);
4646 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4647
4648 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4649 atomic_read(&tlink->tl_count) != 0 ||
4650 time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4651 continue;
4652
4653 cifs_get_tlink(tlink);
4654 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4655 rb_erase(tmp, root);
4656
4657 spin_unlock(&cifs_sb->tlink_tree_lock);
4658 cifs_put_tlink(tlink);
4659 spin_lock(&cifs_sb->tlink_tree_lock);
4660 }
4661 spin_unlock(&cifs_sb->tlink_tree_lock);
4662
4663 queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4664 TLINK_IDLE_EXPIRE);
4665 }
4666
4667 #ifndef CONFIG_CIFS_DFS_UPCALL
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon)4668 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon)
4669 {
4670 const struct smb_version_operations *ops = tcon->ses->server->ops;
4671 int rc;
4672
4673 /* only send once per connect */
4674 spin_lock(&tcon->tc_lock);
4675
4676 /* if tcon is marked for needing reconnect, update state */
4677 if (tcon->need_reconnect)
4678 tcon->status = TID_NEED_TCON;
4679
4680 if (tcon->status == TID_GOOD) {
4681 spin_unlock(&tcon->tc_lock);
4682 return 0;
4683 }
4684
4685 if (tcon->status != TID_NEW &&
4686 tcon->status != TID_NEED_TCON) {
4687 spin_unlock(&tcon->tc_lock);
4688 return -EHOSTDOWN;
4689 }
4690
4691 tcon->status = TID_IN_TCON;
4692 spin_unlock(&tcon->tc_lock);
4693
4694 rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name,
4695 tcon, tcon->ses->local_nls);
4696 if (rc) {
4697 spin_lock(&tcon->tc_lock);
4698 if (tcon->status == TID_IN_TCON)
4699 tcon->status = TID_NEED_TCON;
4700 spin_unlock(&tcon->tc_lock);
4701 } else {
4702 spin_lock(&tcon->tc_lock);
4703 if (tcon->status == TID_IN_TCON)
4704 tcon->status = TID_GOOD;
4705 tcon->need_reconnect = false;
4706 spin_unlock(&tcon->tc_lock);
4707 }
4708
4709 return rc;
4710 }
4711 #endif
4712