~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/cifs/connect.c

Version: ~ [ linux-5.8-rc4 ] ~ [ linux-5.7.7 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.50 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.131 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.187 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.229 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.229 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  *   fs/cifs/connect.c
  3  *
  4  *   Copyright (C) International Business Machines  Corp., 2002,2011
  5  *   Author(s): Steve French (sfrench@us.ibm.com)
  6  *
  7  *   This library is free software; you can redistribute it and/or modify
  8  *   it under the terms of the GNU Lesser General Public License as published
  9  *   by the Free Software Foundation; either version 2.1 of the License, or
 10  *   (at your option) any later version.
 11  *
 12  *   This library is distributed in the hope that it will be useful,
 13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
 15  *   the GNU Lesser General Public License for more details.
 16  *
 17  *   You should have received a copy of the GNU Lesser General Public License
 18  *   along with this library; if not, write to the Free Software
 19  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 20  */
 21 #include <linux/fs.h>
 22 #include <linux/net.h>
 23 #include <linux/string.h>
 24 #include <linux/list.h>
 25 #include <linux/wait.h>
 26 #include <linux/slab.h>
 27 #include <linux/pagemap.h>
 28 #include <linux/ctype.h>
 29 #include <linux/utsname.h>
 30 #include <linux/mempool.h>
 31 #include <linux/delay.h>
 32 #include <linux/completion.h>
 33 #include <linux/kthread.h>
 34 #include <linux/pagevec.h>
 35 #include <linux/freezer.h>
 36 #include <linux/namei.h>
 37 #include <asm/uaccess.h>
 38 #include <asm/processor.h>
 39 #include <linux/inet.h>
 40 #include <linux/module.h>
 41 #include <keys/user-type.h>
 42 #include <net/ipv6.h>
 43 #include <linux/parser.h>
 44 
 45 #include "cifspdu.h"
 46 #include "cifsglob.h"
 47 #include "cifsproto.h"
 48 #include "cifs_unicode.h"
 49 #include "cifs_debug.h"
 50 #include "cifs_fs_sb.h"
 51 #include "ntlmssp.h"
 52 #include "nterr.h"
 53 #include "rfc1002pdu.h"
 54 #include "fscache.h"
 55 #ifdef CONFIG_CIFS_SMB2
 56 #include "smb2proto.h"
 57 #endif
 58 
 59 #define CIFS_PORT 445
 60 #define RFC1001_PORT 139
 61 
 62 extern mempool_t *cifs_req_poolp;
 63 
 64 /* FIXME: should these be tunable? */
 65 #define TLINK_ERROR_EXPIRE      (1 * HZ)
 66 #define TLINK_IDLE_EXPIRE       (600 * HZ)
 67 
 68 enum {
 69 
 70         /* Mount options that take no arguments */
 71         Opt_user_xattr, Opt_nouser_xattr,
 72         Opt_forceuid, Opt_noforceuid,
 73         Opt_forcegid, Opt_noforcegid,
 74         Opt_noblocksend, Opt_noautotune,
 75         Opt_hard, Opt_soft, Opt_perm, Opt_noperm,
 76         Opt_mapchars, Opt_nomapchars, Opt_sfu,
 77         Opt_nosfu, Opt_nodfs, Opt_posixpaths,
 78         Opt_noposixpaths, Opt_nounix,
 79         Opt_nocase,
 80         Opt_brl, Opt_nobrl,
 81         Opt_forcemandatorylock, Opt_setuids,
 82         Opt_nosetuids, Opt_dynperm, Opt_nodynperm,
 83         Opt_nohard, Opt_nosoft,
 84         Opt_nointr, Opt_intr,
 85         Opt_nostrictsync, Opt_strictsync,
 86         Opt_serverino, Opt_noserverino,
 87         Opt_rwpidforward, Opt_cifsacl, Opt_nocifsacl,
 88         Opt_acl, Opt_noacl, Opt_locallease,
 89         Opt_sign, Opt_seal, Opt_noac,
 90         Opt_fsc, Opt_mfsymlinks,
 91         Opt_multiuser, Opt_sloppy, Opt_nosharesock,
 92 
 93         /* Mount options which take numeric value */
 94         Opt_backupuid, Opt_backupgid, Opt_uid,
 95         Opt_cruid, Opt_gid, Opt_file_mode,
 96         Opt_dirmode, Opt_port,
 97         Opt_rsize, Opt_wsize, Opt_actimeo,
 98 
 99         /* Mount options which take string value */
100         Opt_user, Opt_pass, Opt_ip,
101         Opt_domain, Opt_srcaddr, Opt_iocharset,
102         Opt_netbiosname, Opt_servern,
103         Opt_ver, Opt_vers, Opt_sec, Opt_cache,
104 
105         /* Mount options to be ignored */
106         Opt_ignore,
107 
108         /* Options which could be blank */
109         Opt_blank_pass,
110         Opt_blank_user,
111         Opt_blank_ip,
112 
113         Opt_err
114 };
115 
116 static const match_table_t cifs_mount_option_tokens = {
117 
118         { Opt_user_xattr, "user_xattr" },
119         { Opt_nouser_xattr, "nouser_xattr" },
120         { Opt_forceuid, "forceuid" },
121         { Opt_noforceuid, "noforceuid" },
122         { Opt_forcegid, "forcegid" },
123         { Opt_noforcegid, "noforcegid" },
124         { Opt_noblocksend, "noblocksend" },
125         { Opt_noautotune, "noautotune" },
126         { Opt_hard, "hard" },
127         { Opt_soft, "soft" },
128         { Opt_perm, "perm" },
129         { Opt_noperm, "noperm" },
130         { Opt_mapchars, "mapchars" },
131         { Opt_nomapchars, "nomapchars" },
132         { Opt_sfu, "sfu" },
133         { Opt_nosfu, "nosfu" },
134         { Opt_nodfs, "nodfs" },
135         { Opt_posixpaths, "posixpaths" },
136         { Opt_noposixpaths, "noposixpaths" },
137         { Opt_nounix, "nounix" },
138         { Opt_nounix, "nolinux" },
139         { Opt_nocase, "nocase" },
140         { Opt_nocase, "ignorecase" },
141         { Opt_brl, "brl" },
142         { Opt_nobrl, "nobrl" },
143         { Opt_nobrl, "nolock" },
144         { Opt_forcemandatorylock, "forcemandatorylock" },
145         { Opt_forcemandatorylock, "forcemand" },
146         { Opt_setuids, "setuids" },
147         { Opt_nosetuids, "nosetuids" },
148         { Opt_dynperm, "dynperm" },
149         { Opt_nodynperm, "nodynperm" },
150         { Opt_nohard, "nohard" },
151         { Opt_nosoft, "nosoft" },
152         { Opt_nointr, "nointr" },
153         { Opt_intr, "intr" },
154         { Opt_nostrictsync, "nostrictsync" },
155         { Opt_strictsync, "strictsync" },
156         { Opt_serverino, "serverino" },
157         { Opt_noserverino, "noserverino" },
158         { Opt_rwpidforward, "rwpidforward" },
159         { Opt_cifsacl, "cifsacl" },
160         { Opt_nocifsacl, "nocifsacl" },
161         { Opt_acl, "acl" },
162         { Opt_noacl, "noacl" },
163         { Opt_locallease, "locallease" },
164         { Opt_sign, "sign" },
165         { Opt_seal, "seal" },
166         { Opt_noac, "noac" },
167         { Opt_fsc, "fsc" },
168         { Opt_mfsymlinks, "mfsymlinks" },
169         { Opt_multiuser, "multiuser" },
170         { Opt_sloppy, "sloppy" },
171         { Opt_nosharesock, "nosharesock" },
172 
173         { Opt_backupuid, "backupuid=%s" },
174         { Opt_backupgid, "backupgid=%s" },
175         { Opt_uid, "uid=%s" },
176         { Opt_cruid, "cruid=%s" },
177         { Opt_gid, "gid=%s" },
178         { Opt_file_mode, "file_mode=%s" },
179         { Opt_dirmode, "dirmode=%s" },
180         { Opt_dirmode, "dir_mode=%s" },
181         { Opt_port, "port=%s" },
182         { Opt_rsize, "rsize=%s" },
183         { Opt_wsize, "wsize=%s" },
184         { Opt_actimeo, "actimeo=%s" },
185 
186         { Opt_blank_user, "user=" },
187         { Opt_blank_user, "username=" },
188         { Opt_user, "user=%s" },
189         { Opt_user, "username=%s" },
190         { Opt_blank_pass, "pass=" },
191         { Opt_blank_pass, "password=" },
192         { Opt_pass, "pass=%s" },
193         { Opt_pass, "password=%s" },
194         { Opt_blank_ip, "ip=" },
195         { Opt_blank_ip, "addr=" },
196         { Opt_ip, "ip=%s" },
197         { Opt_ip, "addr=%s" },
198         { Opt_ignore, "unc=%s" },
199         { Opt_ignore, "target=%s" },
200         { Opt_ignore, "path=%s" },
201         { Opt_domain, "dom=%s" },
202         { Opt_domain, "domain=%s" },
203         { Opt_domain, "workgroup=%s" },
204         { Opt_srcaddr, "srcaddr=%s" },
205         { Opt_ignore, "prefixpath=%s" },
206         { Opt_iocharset, "iocharset=%s" },
207         { Opt_netbiosname, "netbiosname=%s" },
208         { Opt_servern, "servern=%s" },
209         { Opt_ver, "ver=%s" },
210         { Opt_vers, "vers=%s" },
211         { Opt_sec, "sec=%s" },
212         { Opt_cache, "cache=%s" },
213 
214         { Opt_ignore, "cred" },
215         { Opt_ignore, "credentials" },
216         { Opt_ignore, "cred=%s" },
217         { Opt_ignore, "credentials=%s" },
218         { Opt_ignore, "guest" },
219         { Opt_ignore, "rw" },
220         { Opt_ignore, "ro" },
221         { Opt_ignore, "suid" },
222         { Opt_ignore, "nosuid" },
223         { Opt_ignore, "exec" },
224         { Opt_ignore, "noexec" },
225         { Opt_ignore, "nodev" },
226         { Opt_ignore, "noauto" },
227         { Opt_ignore, "dev" },
228         { Opt_ignore, "mand" },
229         { Opt_ignore, "nomand" },
230         { Opt_ignore, "_netdev" },
231 
232         { Opt_err, NULL }
233 };
234 
235 enum {
236         Opt_sec_krb5, Opt_sec_krb5i, Opt_sec_krb5p,
237         Opt_sec_ntlmsspi, Opt_sec_ntlmssp,
238         Opt_ntlm, Opt_sec_ntlmi, Opt_sec_ntlmv2,
239         Opt_sec_ntlmv2i, Opt_sec_lanman,
240         Opt_sec_none,
241 
242         Opt_sec_err
243 };
244 
245 static const match_table_t cifs_secflavor_tokens = {
246         { Opt_sec_krb5, "krb5" },
247         { Opt_sec_krb5i, "krb5i" },
248         { Opt_sec_krb5p, "krb5p" },
249         { Opt_sec_ntlmsspi, "ntlmsspi" },
250         { Opt_sec_ntlmssp, "ntlmssp" },
251         { Opt_ntlm, "ntlm" },
252         { Opt_sec_ntlmi, "ntlmi" },
253         { Opt_sec_ntlmv2, "nontlm" },
254         { Opt_sec_ntlmv2, "ntlmv2" },
255         { Opt_sec_ntlmv2i, "ntlmv2i" },
256         { Opt_sec_lanman, "lanman" },
257         { Opt_sec_none, "none" },
258 
259         { Opt_sec_err, NULL }
260 };
261 
262 /* cache flavors */
263 enum {
264         Opt_cache_loose,
265         Opt_cache_strict,
266         Opt_cache_none,
267         Opt_cache_err
268 };
269 
270 static const match_table_t cifs_cacheflavor_tokens = {
271         { Opt_cache_loose, "loose" },
272         { Opt_cache_strict, "strict" },
273         { Opt_cache_none, "none" },
274         { Opt_cache_err, NULL }
275 };
276 
277 static const match_table_t cifs_smb_version_tokens = {
278         { Smb_1, SMB1_VERSION_STRING },
279         { Smb_20, SMB20_VERSION_STRING},
280         { Smb_21, SMB21_VERSION_STRING },
281         { Smb_30, SMB30_VERSION_STRING },
282         { Smb_302, SMB302_VERSION_STRING },
283 };
284 
285 static int ip_connect(struct TCP_Server_Info *server);
286 static int generic_ip_connect(struct TCP_Server_Info *server);
287 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
288 static void cifs_prune_tlinks(struct work_struct *work);
289 static int cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
290                                         const char *devname);
291 
292 /*
293  * cifs tcp session reconnection
294  *
295  * mark tcp session as reconnecting so temporarily locked
296  * mark all smb sessions as reconnecting for tcp session
297  * reconnect tcp session
298  * wake up waiters on reconnection? - (not needed currently)
299  */
300 int
301 cifs_reconnect(struct TCP_Server_Info *server)
302 {
303         int rc = 0;
304         struct list_head *tmp, *tmp2;
305         struct cifs_ses *ses;
306         struct cifs_tcon *tcon;
307         struct mid_q_entry *mid_entry;
308         struct list_head retry_list;
309 
310         spin_lock(&GlobalMid_Lock);
311         if (server->tcpStatus == CifsExiting) {
312                 /* the demux thread will exit normally
313                 next time through the loop */
314                 spin_unlock(&GlobalMid_Lock);
315                 return rc;
316         } else
317                 server->tcpStatus = CifsNeedReconnect;
318         spin_unlock(&GlobalMid_Lock);
319         server->maxBuf = 0;
320 #ifdef CONFIG_CIFS_SMB2
321         server->max_read = 0;
322 #endif
323 
324         cifs_dbg(FYI, "Reconnecting tcp session\n");
325 
326         /* before reconnecting the tcp session, mark the smb session (uid)
327                 and the tid bad so they are not used until reconnected */
328         cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n",
329                  __func__);
330         spin_lock(&cifs_tcp_ses_lock);
331         list_for_each(tmp, &server->smb_ses_list) {
332                 ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
333                 ses->need_reconnect = true;
334                 ses->ipc_tid = 0;
335                 list_for_each(tmp2, &ses->tcon_list) {
336                         tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
337                         tcon->need_reconnect = true;
338                 }
339         }
340         spin_unlock(&cifs_tcp_ses_lock);
341 
342         /* do not want to be sending data on a socket we are freeing */
343         cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
344         mutex_lock(&server->srv_mutex);
345         if (server->ssocket) {
346                 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n",
347                          server->ssocket->state, server->ssocket->flags);
348                 kernel_sock_shutdown(server->ssocket, SHUT_WR);
349                 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n",
350                          server->ssocket->state, server->ssocket->flags);
351                 sock_release(server->ssocket);
352                 server->ssocket = NULL;
353         }
354         server->sequence_number = 0;
355         server->session_estab = false;
356         kfree(server->session_key.response);
357         server->session_key.response = NULL;
358         server->session_key.len = 0;
359         server->lstrp = jiffies;
360         mutex_unlock(&server->srv_mutex);
361 
362         /* mark submitted MIDs for retry and issue callback */
363         INIT_LIST_HEAD(&retry_list);
364         cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
365         spin_lock(&GlobalMid_Lock);
366         list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
367                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
368                 if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
369                         mid_entry->mid_state = MID_RETRY_NEEDED;
370                 list_move(&mid_entry->qhead, &retry_list);
371         }
372         spin_unlock(&GlobalMid_Lock);
373 
374         cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
375         list_for_each_safe(tmp, tmp2, &retry_list) {
376                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
377                 list_del_init(&mid_entry->qhead);
378                 mid_entry->callback(mid_entry);
379         }
380 
381         do {
382                 try_to_freeze();
383 
384                 /* we should try only the port we connected to before */
385                 mutex_lock(&server->srv_mutex);
386                 rc = generic_ip_connect(server);
387                 if (rc) {
388                         cifs_dbg(FYI, "reconnect error %d\n", rc);
389                         msleep(3000);
390                 } else {
391                         atomic_inc(&tcpSesReconnectCount);
392                         spin_lock(&GlobalMid_Lock);
393                         if (server->tcpStatus != CifsExiting)
394                                 server->tcpStatus = CifsNeedNegotiate;
395                         spin_unlock(&GlobalMid_Lock);
396                 }
397                 mutex_unlock(&server->srv_mutex);
398         } while (server->tcpStatus == CifsNeedReconnect);
399 
400         return rc;
401 }
402 
403 static void
404 cifs_echo_request(struct work_struct *work)
405 {
406         int rc;
407         struct TCP_Server_Info *server = container_of(work,
408                                         struct TCP_Server_Info, echo.work);
409 
410         /*
411          * We cannot send an echo if it is disabled or until the
412          * NEGOTIATE_PROTOCOL request is done, which is indicated by
413          * server->ops->need_neg() == true. Also, no need to ping if
414          * we got a response recently.
415          */
416 
417         if (server->tcpStatus == CifsNeedReconnect ||
418             server->tcpStatus == CifsExiting || server->tcpStatus == CifsNew ||
419             (server->ops->can_echo && !server->ops->can_echo(server)) ||
420             time_before(jiffies, server->lstrp + SMB_ECHO_INTERVAL - HZ))
421                 goto requeue_echo;
422 
423         rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
424         if (rc)
425                 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
426                          server->hostname);
427 
428 requeue_echo:
429         queue_delayed_work(cifsiod_wq, &server->echo, SMB_ECHO_INTERVAL);
430 }
431 
432 static bool
433 allocate_buffers(struct TCP_Server_Info *server)
434 {
435         if (!server->bigbuf) {
436                 server->bigbuf = (char *)cifs_buf_get();
437                 if (!server->bigbuf) {
438                         cifs_dbg(VFS, "No memory for large SMB response\n");
439                         msleep(3000);
440                         /* retry will check if exiting */
441                         return false;
442                 }
443         } else if (server->large_buf) {
444                 /* we are reusing a dirty large buf, clear its start */
445                 memset(server->bigbuf, 0, HEADER_SIZE(server));
446         }
447 
448         if (!server->smallbuf) {
449                 server->smallbuf = (char *)cifs_small_buf_get();
450                 if (!server->smallbuf) {
451                         cifs_dbg(VFS, "No memory for SMB response\n");
452                         msleep(1000);
453                         /* retry will check if exiting */
454                         return false;
455                 }
456                 /* beginning of smb buffer is cleared in our buf_get */
457         } else {
458                 /* if existing small buf clear beginning */
459                 memset(server->smallbuf, 0, HEADER_SIZE(server));
460         }
461 
462         return true;
463 }
464 
465 static bool
466 server_unresponsive(struct TCP_Server_Info *server)
467 {
468         /*
469          * We need to wait 2 echo intervals to make sure we handle such
470          * situations right:
471          * 1s  client sends a normal SMB request
472          * 2s  client gets a response
473          * 30s echo workqueue job pops, and decides we got a response recently
474          *     and don't need to send another
475          * ...
476          * 65s kernel_recvmsg times out, and we see that we haven't gotten
477          *     a response in >60s.
478          */
479         if (server->tcpStatus == CifsGood &&
480             time_after(jiffies, server->lstrp + 2 * SMB_ECHO_INTERVAL)) {
481                 cifs_dbg(VFS, "Server %s has not responded in %d seconds. Reconnecting...\n",
482                          server->hostname, (2 * SMB_ECHO_INTERVAL) / HZ);
483                 cifs_reconnect(server);
484                 wake_up(&server->response_q);
485                 return true;
486         }
487 
488         return false;
489 }
490 
491 /*
492  * kvec_array_init - clone a kvec array, and advance into it
493  * @new:        pointer to memory for cloned array
494  * @iov:        pointer to original array
495  * @nr_segs:    number of members in original array
496  * @bytes:      number of bytes to advance into the cloned array
497  *
498  * This function will copy the array provided in iov to a section of memory
499  * and advance the specified number of bytes into the new array. It returns
500  * the number of segments in the new array. "new" must be at least as big as
501  * the original iov array.
502  */
503 static unsigned int
504 kvec_array_init(struct kvec *new, struct kvec *iov, unsigned int nr_segs,
505                 size_t bytes)
506 {
507         size_t base = 0;
508 
509         while (bytes || !iov->iov_len) {
510                 int copy = min(bytes, iov->iov_len);
511 
512                 bytes -= copy;
513                 base += copy;
514                 if (iov->iov_len == base) {
515                         iov++;
516                         nr_segs--;
517                         base = 0;
518                 }
519         }
520         memcpy(new, iov, sizeof(*iov) * nr_segs);
521         new->iov_base += base;
522         new->iov_len -= base;
523         return nr_segs;
524 }
525 
526 static struct kvec *
527 get_server_iovec(struct TCP_Server_Info *server, unsigned int nr_segs)
528 {
529         struct kvec *new_iov;
530 
531         if (server->iov && nr_segs <= server->nr_iov)
532                 return server->iov;
533 
534         /* not big enough -- allocate a new one and release the old */
535         new_iov = kmalloc(sizeof(*new_iov) * nr_segs, GFP_NOFS);
536         if (new_iov) {
537                 kfree(server->iov);
538                 server->iov = new_iov;
539                 server->nr_iov = nr_segs;
540         }
541         return new_iov;
542 }
543 
544 int
545 cifs_readv_from_socket(struct TCP_Server_Info *server, struct kvec *iov_orig,
546                        unsigned int nr_segs, unsigned int to_read)
547 {
548         int length = 0;
549         int total_read;
550         unsigned int segs;
551         struct msghdr smb_msg;
552         struct kvec *iov;
553 
554         iov = get_server_iovec(server, nr_segs);
555         if (!iov)
556                 return -ENOMEM;
557 
558         smb_msg.msg_control = NULL;
559         smb_msg.msg_controllen = 0;
560 
561         for (total_read = 0; to_read; total_read += length, to_read -= length) {
562                 try_to_freeze();
563 
564                 if (server_unresponsive(server)) {
565                         total_read = -EAGAIN;
566                         break;
567                 }
568 
569                 segs = kvec_array_init(iov, iov_orig, nr_segs, total_read);
570 
571                 length = kernel_recvmsg(server->ssocket, &smb_msg,
572                                         iov, segs, to_read, 0);
573 
574                 if (server->tcpStatus == CifsExiting) {
575                         total_read = -ESHUTDOWN;
576                         break;
577                 } else if (server->tcpStatus == CifsNeedReconnect) {
578                         cifs_reconnect(server);
579                         total_read = -EAGAIN;
580                         break;
581                 } else if (length == -ERESTARTSYS ||
582                            length == -EAGAIN ||
583                            length == -EINTR) {
584                         /*
585                          * Minimum sleep to prevent looping, allowing socket
586                          * to clear and app threads to set tcpStatus
587                          * CifsNeedReconnect if server hung.
588                          */
589                         usleep_range(1000, 2000);
590                         length = 0;
591                         continue;
592                 } else if (length <= 0) {
593                         cifs_dbg(FYI, "Received no data or error: expecting %d\n"
594                                  "got %d", to_read, length);
595                         cifs_reconnect(server);
596                         total_read = -EAGAIN;
597                         break;
598                 }
599         }
600         return total_read;
601 }
602 
603 int
604 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
605                       unsigned int to_read)
606 {
607         struct kvec iov;
608 
609         iov.iov_base = buf;
610         iov.iov_len = to_read;
611 
612         return cifs_readv_from_socket(server, &iov, 1, to_read);
613 }
614 
615 static bool
616 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
617 {
618         /*
619          * The first byte big endian of the length field,
620          * is actually not part of the length but the type
621          * with the most common, zero, as regular data.
622          */
623         switch (type) {
624         case RFC1002_SESSION_MESSAGE:
625                 /* Regular SMB response */
626                 return true;
627         case RFC1002_SESSION_KEEP_ALIVE:
628                 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
629                 break;
630         case RFC1002_POSITIVE_SESSION_RESPONSE:
631                 cifs_dbg(FYI, "RFC 1002 positive session response\n");
632                 break;
633         case RFC1002_NEGATIVE_SESSION_RESPONSE:
634                 /*
635                  * We get this from Windows 98 instead of an error on
636                  * SMB negprot response.
637                  */
638                 cifs_dbg(FYI, "RFC 1002 negative session response\n");
639                 /* give server a second to clean up */
640                 msleep(1000);
641                 /*
642                  * Always try 445 first on reconnect since we get NACK
643                  * on some if we ever connected to port 139 (the NACK
644                  * is since we do not begin with RFC1001 session
645                  * initialize frame).
646                  */
647                 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
648                 cifs_reconnect(server);
649                 wake_up(&server->response_q);
650                 break;
651         default:
652                 cifs_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
653                 cifs_reconnect(server);
654         }
655 
656         return false;
657 }
658 
659 void
660 dequeue_mid(struct mid_q_entry *mid, bool malformed)
661 {
662 #ifdef CONFIG_CIFS_STATS2
663         mid->when_received = jiffies;
664 #endif
665         spin_lock(&GlobalMid_Lock);
666         if (!malformed)
667                 mid->mid_state = MID_RESPONSE_RECEIVED;
668         else
669                 mid->mid_state = MID_RESPONSE_MALFORMED;
670         list_del_init(&mid->qhead);
671         spin_unlock(&GlobalMid_Lock);
672 }
673 
674 static void
675 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
676            char *buf, int malformed)
677 {
678         if (server->ops->check_trans2 &&
679             server->ops->check_trans2(mid, server, buf, malformed))
680                 return;
681         mid->resp_buf = buf;
682         mid->large_buf = server->large_buf;
683         /* Was previous buf put in mpx struct for multi-rsp? */
684         if (!mid->multiRsp) {
685                 /* smb buffer will be freed by user thread */
686                 if (server->large_buf)
687                         server->bigbuf = NULL;
688                 else
689                         server->smallbuf = NULL;
690         }
691         dequeue_mid(mid, malformed);
692 }
693 
694 static void clean_demultiplex_info(struct TCP_Server_Info *server)
695 {
696         int length;
697 
698         /* take it off the list, if it's not already */
699         spin_lock(&cifs_tcp_ses_lock);
700         list_del_init(&server->tcp_ses_list);
701         spin_unlock(&cifs_tcp_ses_lock);
702 
703         spin_lock(&GlobalMid_Lock);
704         server->tcpStatus = CifsExiting;
705         spin_unlock(&GlobalMid_Lock);
706         wake_up_all(&server->response_q);
707 
708         /* check if we have blocked requests that need to free */
709         spin_lock(&server->req_lock);
710         if (server->credits <= 0)
711                 server->credits = 1;
712         spin_unlock(&server->req_lock);
713         /*
714          * Although there should not be any requests blocked on this queue it
715          * can not hurt to be paranoid and try to wake up requests that may
716          * haven been blocked when more than 50 at time were on the wire to the
717          * same server - they now will see the session is in exit state and get
718          * out of SendReceive.
719          */
720         wake_up_all(&server->request_q);
721         /* give those requests time to exit */
722         msleep(125);
723 
724         if (server->ssocket) {
725                 sock_release(server->ssocket);
726                 server->ssocket = NULL;
727         }
728 
729         if (!list_empty(&server->pending_mid_q)) {
730                 struct list_head dispose_list;
731                 struct mid_q_entry *mid_entry;
732                 struct list_head *tmp, *tmp2;
733 
734                 INIT_LIST_HEAD(&dispose_list);
735                 spin_lock(&GlobalMid_Lock);
736                 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
737                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
738                         cifs_dbg(FYI, "Clearing mid 0x%llx\n", mid_entry->mid);
739                         mid_entry->mid_state = MID_SHUTDOWN;
740                         list_move(&mid_entry->qhead, &dispose_list);
741                 }
742                 spin_unlock(&GlobalMid_Lock);
743 
744                 /* now walk dispose list and issue callbacks */
745                 list_for_each_safe(tmp, tmp2, &dispose_list) {
746                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
747                         cifs_dbg(FYI, "Callback mid 0x%llx\n", mid_entry->mid);
748                         list_del_init(&mid_entry->qhead);
749                         mid_entry->callback(mid_entry);
750                 }
751                 /* 1/8th of sec is more than enough time for them to exit */
752                 msleep(125);
753         }
754 
755         if (!list_empty(&server->pending_mid_q)) {
756                 /*
757                  * mpx threads have not exited yet give them at least the smb
758                  * send timeout time for long ops.
759                  *
760                  * Due to delays on oplock break requests, we need to wait at
761                  * least 45 seconds before giving up on a request getting a
762                  * response and going ahead and killing cifsd.
763                  */
764                 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
765                 msleep(46000);
766                 /*
767                  * If threads still have not exited they are probably never
768                  * coming home not much else we can do but free the memory.
769                  */
770         }
771 
772         kfree(server->hostname);
773         kfree(server->iov);
774         kfree(server);
775 
776         length = atomic_dec_return(&tcpSesAllocCount);
777         if (length > 0)
778                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv,
779                                 GFP_KERNEL);
780 }
781 
782 static int
783 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
784 {
785         int length;
786         char *buf = server->smallbuf;
787         unsigned int pdu_length = get_rfc1002_length(buf);
788 
789         /* make sure this will fit in a large buffer */
790         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) - 4) {
791                 cifs_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
792                 cifs_reconnect(server);
793                 wake_up(&server->response_q);
794                 return -EAGAIN;
795         }
796 
797         /* switch to large buffer if too big for a small one */
798         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
799                 server->large_buf = true;
800                 memcpy(server->bigbuf, buf, server->total_read);
801                 buf = server->bigbuf;
802         }
803 
804         /* now read the rest */
805         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
806                                 pdu_length - HEADER_SIZE(server) + 1 + 4);
807         if (length < 0)
808                 return length;
809         server->total_read += length;
810 
811         dump_smb(buf, server->total_read);
812 
813         /*
814          * We know that we received enough to get to the MID as we
815          * checked the pdu_length earlier. Now check to see
816          * if the rest of the header is OK. We borrow the length
817          * var for the rest of the loop to avoid a new stack var.
818          *
819          * 48 bytes is enough to display the header and a little bit
820          * into the payload for debugging purposes.
821          */
822         length = server->ops->check_message(buf, server->total_read);
823         if (length != 0)
824                 cifs_dump_mem("Bad SMB: ", buf,
825                         min_t(unsigned int, server->total_read, 48));
826 
827         if (server->ops->is_status_pending &&
828             server->ops->is_status_pending(buf, server, length))
829                 return -1;
830 
831         if (!mid)
832                 return length;
833 
834         handle_mid(mid, server, buf, length);
835         return 0;
836 }
837 
838 static int
839 cifs_demultiplex_thread(void *p)
840 {
841         int length;
842         struct TCP_Server_Info *server = p;
843         unsigned int pdu_length;
844         char *buf = NULL;
845         struct task_struct *task_to_wake = NULL;
846         struct mid_q_entry *mid_entry;
847 
848         current->flags |= PF_MEMALLOC;
849         cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
850 
851         length = atomic_inc_return(&tcpSesAllocCount);
852         if (length > 1)
853                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv,
854                                 GFP_KERNEL);
855 
856         set_freezable();
857         while (server->tcpStatus != CifsExiting) {
858                 if (try_to_freeze())
859                         continue;
860 
861                 if (!allocate_buffers(server))
862                         continue;
863 
864                 server->large_buf = false;
865                 buf = server->smallbuf;
866                 pdu_length = 4; /* enough to get RFC1001 header */
867 
868                 length = cifs_read_from_socket(server, buf, pdu_length);
869                 if (length < 0)
870                         continue;
871                 server->total_read = length;
872 
873                 /*
874                  * The right amount was read from socket - 4 bytes,
875                  * so we can now interpret the length field.
876                  */
877                 pdu_length = get_rfc1002_length(buf);
878 
879                 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
880                 if (!is_smb_response(server, buf[0]))
881                         continue;
882 
883                 /* make sure we have enough to get to the MID */
884                 if (pdu_length < HEADER_SIZE(server) - 1 - 4) {
885                         cifs_dbg(VFS, "SMB response too short (%u bytes)\n",
886                                  pdu_length);
887                         cifs_reconnect(server);
888                         wake_up(&server->response_q);
889                         continue;
890                 }
891 
892                 /* read down to the MID */
893                 length = cifs_read_from_socket(server, buf + 4,
894                                                HEADER_SIZE(server) - 1 - 4);
895                 if (length < 0)
896                         continue;
897                 server->total_read += length;
898 
899                 mid_entry = server->ops->find_mid(server, buf);
900 
901                 if (!mid_entry || !mid_entry->receive)
902                         length = standard_receive3(server, mid_entry);
903                 else
904                         length = mid_entry->receive(server, mid_entry);
905 
906                 if (length < 0)
907                         continue;
908 
909                 if (server->large_buf)
910                         buf = server->bigbuf;
911 
912                 server->lstrp = jiffies;
913                 if (mid_entry != NULL) {
914                         if (!mid_entry->multiRsp || mid_entry->multiEnd)
915                                 mid_entry->callback(mid_entry);
916                 } else if (!server->ops->is_oplock_break ||
917                            !server->ops->is_oplock_break(buf, server)) {
918                         cifs_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
919                                  atomic_read(&midCount));
920                         cifs_dump_mem("Received Data is: ", buf,
921                                       HEADER_SIZE(server));
922 #ifdef CONFIG_CIFS_DEBUG2
923                         if (server->ops->dump_detail)
924                                 server->ops->dump_detail(buf);
925                         cifs_dump_mids(server);
926 #endif /* CIFS_DEBUG2 */
927 
928                 }
929         } /* end while !EXITING */
930 
931         /* buffer usually freed in free_mid - need to free it here on exit */
932         cifs_buf_release(server->bigbuf);
933         if (server->smallbuf) /* no sense logging a debug message if NULL */
934                 cifs_small_buf_release(server->smallbuf);
935 
936         task_to_wake = xchg(&server->tsk, NULL);
937         clean_demultiplex_info(server);
938 
939         /* if server->tsk was NULL then wait for a signal before exiting */
940         if (!task_to_wake) {
941                 set_current_state(TASK_INTERRUPTIBLE);
942                 while (!signal_pending(current)) {
943                         schedule();
944                         set_current_state(TASK_INTERRUPTIBLE);
945                 }
946                 set_current_state(TASK_RUNNING);
947         }
948 
949         module_put_and_exit(0);
950 }
951 
952 /* extract the host portion of the UNC string */
953 static char *
954 extract_hostname(const char *unc)
955 {
956         const char *src;
957         char *dst, *delim;
958         unsigned int len;
959 
960         /* skip double chars at beginning of string */
961         /* BB: check validity of these bytes? */
962         src = unc + 2;
963 
964         /* delimiter between hostname and sharename is always '\\' now */
965         delim = strchr(src, '\\');
966         if (!delim)
967                 return ERR_PTR(-EINVAL);
968 
969         len = delim - src;
970         dst = kmalloc((len + 1), GFP_KERNEL);
971         if (dst == NULL)
972                 return ERR_PTR(-ENOMEM);
973 
974         memcpy(dst, src, len);
975         dst[len] = '\0';
976 
977         return dst;
978 }
979 
980 static int get_option_ul(substring_t args[], unsigned long *option)
981 {
982         int rc;
983         char *string;
984 
985         string = match_strdup(args);
986         if (string == NULL)
987                 return -ENOMEM;
988         rc = kstrtoul(string, 0, option);
989         kfree(string);
990 
991         return rc;
992 }
993 
994 static int get_option_uid(substring_t args[], kuid_t *result)
995 {
996         unsigned long value;
997         kuid_t uid;
998         int rc;
999 
1000         rc = get_option_ul(args, &value);
1001         if (rc)
1002                 return rc;
1003 
1004         uid = make_kuid(current_user_ns(), value);
1005         if (!uid_valid(uid))
1006                 return -EINVAL;
1007 
1008         *result = uid;
1009         return 0;
1010 }
1011 
1012 static int get_option_gid(substring_t args[], kgid_t *result)
1013 {
1014         unsigned long value;
1015         kgid_t gid;
1016         int rc;
1017 
1018         rc = get_option_ul(args, &value);
1019         if (rc)
1020                 return rc;
1021 
1022         gid = make_kgid(current_user_ns(), value);
1023         if (!gid_valid(gid))
1024                 return -EINVAL;
1025 
1026         *result = gid;
1027         return 0;
1028 }
1029 
1030 static int cifs_parse_security_flavors(char *value,
1031                                        struct smb_vol *vol)
1032 {
1033 
1034         substring_t args[MAX_OPT_ARGS];
1035 
1036         /*
1037          * With mount options, the last one should win. Reset any existing
1038          * settings back to default.
1039          */
1040         vol->sectype = Unspecified;
1041         vol->sign = false;
1042 
1043         switch (match_token(value, cifs_secflavor_tokens, args)) {
1044         case Opt_sec_krb5p:
1045                 cifs_dbg(VFS, "sec=krb5p is not supported!\n");
1046                 return 1;
1047         case Opt_sec_krb5i:
1048                 vol->sign = true;
1049                 /* Fallthrough */
1050         case Opt_sec_krb5:
1051                 vol->sectype = Kerberos;
1052                 break;
1053         case Opt_sec_ntlmsspi:
1054                 vol->sign = true;
1055                 /* Fallthrough */
1056         case Opt_sec_ntlmssp:
1057                 vol->sectype = RawNTLMSSP;
1058                 break;
1059         case Opt_sec_ntlmi:
1060                 vol->sign = true;
1061                 /* Fallthrough */
1062         case Opt_ntlm:
1063                 vol->sectype = NTLM;
1064                 break;
1065         case Opt_sec_ntlmv2i:
1066                 vol->sign = true;
1067                 /* Fallthrough */
1068         case Opt_sec_ntlmv2:
1069                 vol->sectype = NTLMv2;
1070                 break;
1071 #ifdef CONFIG_CIFS_WEAK_PW_HASH
1072         case Opt_sec_lanman:
1073                 vol->sectype = LANMAN;
1074                 break;
1075 #endif
1076         case Opt_sec_none:
1077                 vol->nullauth = 1;
1078                 break;
1079         default:
1080                 cifs_dbg(VFS, "bad security option: %s\n", value);
1081                 return 1;
1082         }
1083 
1084         return 0;
1085 }
1086 
1087 static int
1088 cifs_parse_cache_flavor(char *value, struct smb_vol *vol)
1089 {
1090         substring_t args[MAX_OPT_ARGS];
1091 
1092         switch (match_token(value, cifs_cacheflavor_tokens, args)) {
1093         case Opt_cache_loose:
1094                 vol->direct_io = false;
1095                 vol->strict_io = false;
1096                 break;
1097         case Opt_cache_strict:
1098                 vol->direct_io = false;
1099                 vol->strict_io = true;
1100                 break;
1101         case Opt_cache_none:
1102                 vol->direct_io = true;
1103                 vol->strict_io = false;
1104                 break;
1105         default:
1106                 cifs_dbg(VFS, "bad cache= option: %s\n", value);
1107                 return 1;
1108         }
1109         return 0;
1110 }
1111 
1112 static int
1113 cifs_parse_smb_version(char *value, struct smb_vol *vol)
1114 {
1115         substring_t args[MAX_OPT_ARGS];
1116 
1117         switch (match_token(value, cifs_smb_version_tokens, args)) {
1118         case Smb_1:
1119                 vol->ops = &smb1_operations;
1120                 vol->vals = &smb1_values;
1121                 break;
1122 #ifdef CONFIG_CIFS_SMB2
1123         case Smb_20:
1124                 vol->ops = &smb20_operations;
1125                 vol->vals = &smb20_values;
1126                 break;
1127         case Smb_21:
1128                 vol->ops = &smb21_operations;
1129                 vol->vals = &smb21_values;
1130                 break;
1131         case Smb_30:
1132                 vol->ops = &smb30_operations;
1133                 vol->vals = &smb30_values;
1134                 break;
1135         case Smb_302:
1136                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1137                 vol->vals = &smb302_values;
1138                 break;
1139 #endif
1140         default:
1141                 cifs_dbg(VFS, "Unknown vers= option specified: %s\n", value);
1142                 return 1;
1143         }
1144         return 0;
1145 }
1146 
1147 /*
1148  * Parse a devname into substrings and populate the vol->UNC and vol->prepath
1149  * fields with the result. Returns 0 on success and an error otherwise.
1150  */
1151 static int
1152 cifs_parse_devname(const char *devname, struct smb_vol *vol)
1153 {
1154         char *pos;
1155         const char *delims = "/\\";
1156         size_t len;
1157 
1158         /* make sure we have a valid UNC double delimiter prefix */
1159         len = strspn(devname, delims);
1160         if (len != 2)
1161                 return -EINVAL;
1162 
1163         /* find delimiter between host and sharename */
1164         pos = strpbrk(devname + 2, delims);
1165         if (!pos)
1166                 return -EINVAL;
1167 
1168         /* skip past delimiter */
1169         ++pos;
1170 
1171         /* now go until next delimiter or end of string */
1172         len = strcspn(pos, delims);
1173 
1174         /* move "pos" up to delimiter or NULL */
1175         pos += len;
1176         vol->UNC = kstrndup(devname, pos - devname, GFP_KERNEL);
1177         if (!vol->UNC)
1178                 return -ENOMEM;
1179 
1180         convert_delimiter(vol->UNC, '\\');
1181 
1182         /* If pos is NULL, or is a bogus trailing delimiter then no prepath */
1183         if (!*pos++ || !*pos)
1184                 return 0;
1185 
1186         vol->prepath = kstrdup(pos, GFP_KERNEL);
1187         if (!vol->prepath)
1188                 return -ENOMEM;
1189 
1190         return 0;
1191 }
1192 
1193 static int
1194 cifs_parse_mount_options(const char *mountdata, const char *devname,
1195                          struct smb_vol *vol)
1196 {
1197         char *data, *end;
1198         char *mountdata_copy = NULL, *options;
1199         unsigned int  temp_len, i, j;
1200         char separator[2];
1201         short int override_uid = -1;
1202         short int override_gid = -1;
1203         bool uid_specified = false;
1204         bool gid_specified = false;
1205         bool sloppy = false;
1206         char *invalid = NULL;
1207         char *nodename = utsname()->nodename;
1208         char *string = NULL;
1209         char *tmp_end, *value;
1210         char delim;
1211         bool got_ip = false;
1212         unsigned short port = 0;
1213         struct sockaddr *dstaddr = (struct sockaddr *)&vol->dstaddr;
1214 
1215         separator[0] = ',';
1216         separator[1] = 0;
1217         delim = separator[0];
1218 
1219         /* ensure we always start with zeroed-out smb_vol */
1220         memset(vol, 0, sizeof(*vol));
1221 
1222         /*
1223          * does not have to be perfect mapping since field is
1224          * informational, only used for servers that do not support
1225          * port 445 and it can be overridden at mount time
1226          */
1227         memset(vol->source_rfc1001_name, 0x20, RFC1001_NAME_LEN);
1228         for (i = 0; i < strnlen(nodename, RFC1001_NAME_LEN); i++)
1229                 vol->source_rfc1001_name[i] = toupper(nodename[i]);
1230 
1231         vol->source_rfc1001_name[RFC1001_NAME_LEN] = 0;
1232         /* null target name indicates to use *SMBSERVR default called name
1233            if we end up sending RFC1001 session initialize */
1234         vol->target_rfc1001_name[0] = 0;
1235         vol->cred_uid = current_uid();
1236         vol->linux_uid = current_uid();
1237         vol->linux_gid = current_gid();
1238 
1239         /* default to only allowing write access to owner of the mount */
1240         vol->dir_mode = vol->file_mode = S_IRUGO | S_IXUGO | S_IWUSR;
1241 
1242         /* vol->retry default is 0 (i.e. "soft" limited retry not hard retry) */
1243         /* default is always to request posix paths. */
1244         vol->posix_paths = 1;
1245         /* default to using server inode numbers where available */
1246         vol->server_ino = 1;
1247 
1248         /* default is to use strict cifs caching semantics */
1249         vol->strict_io = true;
1250 
1251         vol->actimeo = CIFS_DEF_ACTIMEO;
1252 
1253         /* FIXME: add autonegotiation -- for now, SMB1 is default */
1254         vol->ops = &smb1_operations;
1255         vol->vals = &smb1_values;
1256 
1257         if (!mountdata)
1258                 goto cifs_parse_mount_err;
1259 
1260         mountdata_copy = kstrndup(mountdata, PAGE_SIZE, GFP_KERNEL);
1261         if (!mountdata_copy)
1262                 goto cifs_parse_mount_err;
1263 
1264         options = mountdata_copy;
1265         end = options + strlen(options);
1266 
1267         if (strncmp(options, "sep=", 4) == 0) {
1268                 if (options[4] != 0) {
1269                         separator[0] = options[4];
1270                         options += 5;
1271                 } else {
1272                         cifs_dbg(FYI, "Null separator not allowed\n");
1273                 }
1274         }
1275         vol->backupuid_specified = false; /* no backup intent for a user */
1276         vol->backupgid_specified = false; /* no backup intent for a group */
1277 
1278         switch (cifs_parse_devname(devname, vol)) {
1279         case 0:
1280                 break;
1281         case -ENOMEM:
1282                 cifs_dbg(VFS, "Unable to allocate memory for devname.\n");
1283                 goto cifs_parse_mount_err;
1284         case -EINVAL:
1285                 cifs_dbg(VFS, "Malformed UNC in devname.\n");
1286                 goto cifs_parse_mount_err;
1287         default:
1288                 cifs_dbg(VFS, "Unknown error parsing devname.\n");
1289                 goto cifs_parse_mount_err;
1290         }
1291 
1292         while ((data = strsep(&options, separator)) != NULL) {
1293                 substring_t args[MAX_OPT_ARGS];
1294                 unsigned long option;
1295                 int token;
1296 
1297                 if (!*data)
1298                         continue;
1299 
1300                 token = match_token(data, cifs_mount_option_tokens, args);
1301 
1302                 switch (token) {
1303 
1304                 /* Ingnore the following */
1305                 case Opt_ignore:
1306                         break;
1307 
1308                 /* Boolean values */
1309                 case Opt_user_xattr:
1310                         vol->no_xattr = 0;
1311                         break;
1312                 case Opt_nouser_xattr:
1313                         vol->no_xattr = 1;
1314                         break;
1315                 case Opt_forceuid:
1316                         override_uid = 1;
1317                         break;
1318                 case Opt_noforceuid:
1319                         override_uid = 0;
1320                         break;
1321                 case Opt_forcegid:
1322                         override_gid = 1;
1323                         break;
1324                 case Opt_noforcegid:
1325                         override_gid = 0;
1326                         break;
1327                 case Opt_noblocksend:
1328                         vol->noblocksnd = 1;
1329                         break;
1330                 case Opt_noautotune:
1331                         vol->noautotune = 1;
1332                         break;
1333                 case Opt_hard:
1334                         vol->retry = 1;
1335                         break;
1336                 case Opt_soft:
1337                         vol->retry = 0;
1338                         break;
1339                 case Opt_perm:
1340                         vol->noperm = 0;
1341                         break;
1342                 case Opt_noperm:
1343                         vol->noperm = 1;
1344                         break;
1345                 case Opt_mapchars:
1346                         vol->remap = 1;
1347                         break;
1348                 case Opt_nomapchars:
1349                         vol->remap = 0;
1350                         break;
1351                 case Opt_sfu:
1352                         vol->sfu_emul = 1;
1353                         break;
1354                 case Opt_nosfu:
1355                         vol->sfu_emul = 0;
1356                         break;
1357                 case Opt_nodfs:
1358                         vol->nodfs = 1;
1359                         break;
1360                 case Opt_posixpaths:
1361                         vol->posix_paths = 1;
1362                         break;
1363                 case Opt_noposixpaths:
1364                         vol->posix_paths = 0;
1365                         break;
1366                 case Opt_nounix:
1367                         vol->no_linux_ext = 1;
1368                         break;
1369                 case Opt_nocase:
1370                         vol->nocase = 1;
1371                         break;
1372                 case Opt_brl:
1373                         vol->nobrl =  0;
1374                         break;
1375                 case Opt_nobrl:
1376                         vol->nobrl =  1;
1377                         /*
1378                          * turn off mandatory locking in mode
1379                          * if remote locking is turned off since the
1380                          * local vfs will do advisory
1381                          */
1382                         if (vol->file_mode ==
1383                                 (S_IALLUGO & ~(S_ISUID | S_IXGRP)))
1384                                 vol->file_mode = S_IALLUGO;
1385                         break;
1386                 case Opt_forcemandatorylock:
1387                         vol->mand_lock = 1;
1388                         break;
1389                 case Opt_setuids:
1390                         vol->setuids = 1;
1391                         break;
1392                 case Opt_nosetuids:
1393                         vol->setuids = 0;
1394                         break;
1395                 case Opt_dynperm:
1396                         vol->dynperm = true;
1397                         break;
1398                 case Opt_nodynperm:
1399                         vol->dynperm = false;
1400                         break;
1401                 case Opt_nohard:
1402                         vol->retry = 0;
1403                         break;
1404                 case Opt_nosoft:
1405                         vol->retry = 1;
1406                         break;
1407                 case Opt_nointr:
1408                         vol->intr = 0;
1409                         break;
1410                 case Opt_intr:
1411                         vol->intr = 1;
1412                         break;
1413                 case Opt_nostrictsync:
1414                         vol->nostrictsync = 1;
1415                         break;
1416                 case Opt_strictsync:
1417                         vol->nostrictsync = 0;
1418                         break;
1419                 case Opt_serverino:
1420                         vol->server_ino = 1;
1421                         break;
1422                 case Opt_noserverino:
1423                         vol->server_ino = 0;
1424                         break;
1425                 case Opt_rwpidforward:
1426                         vol->rwpidforward = 1;
1427                         break;
1428                 case Opt_cifsacl:
1429                         vol->cifs_acl = 1;
1430                         break;
1431                 case Opt_nocifsacl:
1432                         vol->cifs_acl = 0;
1433                         break;
1434                 case Opt_acl:
1435                         vol->no_psx_acl = 0;
1436                         break;
1437                 case Opt_noacl:
1438                         vol->no_psx_acl = 1;
1439                         break;
1440                 case Opt_locallease:
1441                         vol->local_lease = 1;
1442                         break;
1443                 case Opt_sign:
1444                         vol->sign = true;
1445                         break;
1446                 case Opt_seal:
1447                         /* we do not do the following in secFlags because seal
1448                          * is a per tree connection (mount) not a per socket
1449                          * or per-smb connection option in the protocol
1450                          * vol->secFlg |= CIFSSEC_MUST_SEAL;
1451                          */
1452                         vol->seal = 1;
1453                         break;
1454                 case Opt_noac:
1455                         printk(KERN_WARNING "CIFS: Mount option noac not "
1456                                 "supported. Instead set "
1457                                 "/proc/fs/cifs/LookupCacheEnabled to 0\n");
1458                         break;
1459                 case Opt_fsc:
1460 #ifndef CONFIG_CIFS_FSCACHE
1461                         cifs_dbg(VFS, "FS-Cache support needs CONFIG_CIFS_FSCACHE kernel config option set\n");
1462                         goto cifs_parse_mount_err;
1463 #endif
1464                         vol->fsc = true;
1465                         break;
1466                 case Opt_mfsymlinks:
1467                         vol->mfsymlinks = true;
1468                         break;
1469                 case Opt_multiuser:
1470                         vol->multiuser = true;
1471                         break;
1472                 case Opt_sloppy:
1473                         sloppy = true;
1474                         break;
1475                 case Opt_nosharesock:
1476                         vol->nosharesock = true;
1477                         break;
1478 
1479                 /* Numeric Values */
1480                 case Opt_backupuid:
1481                         if (get_option_uid(args, &vol->backupuid)) {
1482                                 cifs_dbg(VFS, "%s: Invalid backupuid value\n",
1483                                          __func__);
1484                                 goto cifs_parse_mount_err;
1485                         }
1486                         vol->backupuid_specified = true;
1487                         break;
1488                 case Opt_backupgid:
1489                         if (get_option_gid(args, &vol->backupgid)) {
1490                                 cifs_dbg(VFS, "%s: Invalid backupgid value\n",
1491                                          __func__);
1492                                 goto cifs_parse_mount_err;
1493                         }
1494                         vol->backupgid_specified = true;
1495                         break;
1496                 case Opt_uid:
1497                         if (get_option_uid(args, &vol->linux_uid)) {
1498                                 cifs_dbg(VFS, "%s: Invalid uid value\n",
1499                                          __func__);
1500                                 goto cifs_parse_mount_err;
1501                         }
1502                         uid_specified = true;
1503                         break;
1504                 case Opt_cruid:
1505                         if (get_option_uid(args, &vol->cred_uid)) {
1506                                 cifs_dbg(VFS, "%s: Invalid cruid value\n",
1507                                          __func__);
1508                                 goto cifs_parse_mount_err;
1509                         }
1510                         break;
1511                 case Opt_gid:
1512                         if (get_option_gid(args, &vol->linux_gid)) {
1513                                 cifs_dbg(VFS, "%s: Invalid gid value\n",
1514                                          __func__);
1515                                 goto cifs_parse_mount_err;
1516                         }
1517                         gid_specified = true;
1518                         break;
1519                 case Opt_file_mode:
1520                         if (get_option_ul(args, &option)) {
1521                                 cifs_dbg(VFS, "%s: Invalid file_mode value\n",
1522                                          __func__);
1523                                 goto cifs_parse_mount_err;
1524                         }
1525                         vol->file_mode = option;
1526                         break;
1527                 case Opt_dirmode:
1528                         if (get_option_ul(args, &option)) {
1529                                 cifs_dbg(VFS, "%s: Invalid dir_mode value\n",
1530                                          __func__);
1531                                 goto cifs_parse_mount_err;
1532                         }
1533                         vol->dir_mode = option;
1534                         break;
1535                 case Opt_port:
1536                         if (get_option_ul(args, &option) ||
1537                             option > USHRT_MAX) {
1538                                 cifs_dbg(VFS, "%s: Invalid port value\n",
1539                                          __func__);
1540                                 goto cifs_parse_mount_err;
1541                         }
1542                         port = (unsigned short)option;
1543                         break;
1544                 case Opt_rsize:
1545                         if (get_option_ul(args, &option)) {
1546                                 cifs_dbg(VFS, "%s: Invalid rsize value\n",
1547                                          __func__);
1548                                 goto cifs_parse_mount_err;
1549                         }
1550                         vol->rsize = option;
1551                         break;
1552                 case Opt_wsize:
1553                         if (get_option_ul(args, &option)) {
1554                                 cifs_dbg(VFS, "%s: Invalid wsize value\n",
1555                                          __func__);
1556                                 goto cifs_parse_mount_err;
1557                         }
1558                         vol->wsize = option;
1559                         break;
1560                 case Opt_actimeo:
1561                         if (get_option_ul(args, &option)) {
1562                                 cifs_dbg(VFS, "%s: Invalid actimeo value\n",
1563                                          __func__);
1564                                 goto cifs_parse_mount_err;
1565                         }
1566                         vol->actimeo = HZ * option;
1567                         if (vol->actimeo > CIFS_MAX_ACTIMEO) {
1568                                 cifs_dbg(VFS, "attribute cache timeout too large\n");
1569                                 goto cifs_parse_mount_err;
1570                         }
1571                         break;
1572 
1573                 /* String Arguments */
1574 
1575                 case Opt_blank_user:
1576                         /* null user, ie. anonymous authentication */
1577                         vol->nullauth = 1;
1578                         vol->username = NULL;
1579                         break;
1580                 case Opt_user:
1581                         string = match_strdup(args);
1582                         if (string == NULL)
1583                                 goto out_nomem;
1584 
1585                         if (strnlen(string, CIFS_MAX_USERNAME_LEN) >
1586                                                         CIFS_MAX_USERNAME_LEN) {
1587                                 printk(KERN_WARNING "CIFS: username too long\n");
1588                                 goto cifs_parse_mount_err;
1589                         }
1590                         vol->username = kstrdup(string, GFP_KERNEL);
1591                         if (!vol->username)
1592                                 goto cifs_parse_mount_err;
1593                         break;
1594                 case Opt_blank_pass:
1595                         /* passwords have to be handled differently
1596                          * to allow the character used for deliminator
1597                          * to be passed within them
1598                          */
1599 
1600                         /*
1601                          * Check if this is a case where the  password
1602                          * starts with a delimiter
1603                          */
1604                         tmp_end = strchr(data, '=');
1605                         tmp_end++;
1606                         if (!(tmp_end < end && tmp_end[1] == delim)) {
1607                                 /* No it is not. Set the password to NULL */
1608                                 vol->password = NULL;
1609                                 break;
1610                         }
1611                         /* Yes it is. Drop down to Opt_pass below.*/
1612                 case Opt_pass:
1613                         /* Obtain the value string */
1614                         value = strchr(data, '=');
1615                         value++;
1616 
1617                         /* Set tmp_end to end of the string */
1618                         tmp_end = (char *) value + strlen(value);
1619 
1620                         /* Check if following character is the deliminator
1621                          * If yes, we have encountered a double deliminator
1622                          * reset the NULL character to the deliminator
1623                          */
1624                         if (tmp_end < end && tmp_end[1] == delim) {
1625                                 tmp_end[0] = delim;
1626 
1627                                 /* Keep iterating until we get to a single
1628                                  * deliminator OR the end
1629                                  */
1630                                 while ((tmp_end = strchr(tmp_end, delim))
1631                                         != NULL && (tmp_end[1] == delim)) {
1632                                                 tmp_end = (char *) &tmp_end[2];
1633                                 }
1634 
1635                                 /* Reset var options to point to next element */
1636                                 if (tmp_end) {
1637                                         tmp_end[0] = '\0';
1638                                         options = (char *) &tmp_end[1];
1639                                 } else
1640                                         /* Reached the end of the mount option
1641                                          * string */
1642                                         options = end;
1643                         }
1644 
1645                         /* Now build new password string */
1646                         temp_len = strlen(value);
1647                         vol->password = kzalloc(temp_len+1, GFP_KERNEL);
1648                         if (vol->password == NULL) {
1649                                 printk(KERN_WARNING "CIFS: no memory "
1650                                                     "for password\n");
1651                                 goto cifs_parse_mount_err;
1652                         }
1653 
1654                         for (i = 0, j = 0; i < temp_len; i++, j++) {
1655                                 vol->password[j] = value[i];
1656                                 if ((value[i] == delim) &&
1657                                      value[i+1] == delim)
1658                                         /* skip the second deliminator */
1659                                         i++;
1660                         }
1661                         vol->password[j] = '\0';
1662                         break;
1663                 case Opt_blank_ip:
1664                         /* FIXME: should this be an error instead? */
1665                         got_ip = false;
1666                         break;
1667                 case Opt_ip:
1668                         string = match_strdup(args);
1669                         if (string == NULL)
1670                                 goto out_nomem;
1671 
1672                         if (!cifs_convert_address(dstaddr, string,
1673                                         strlen(string))) {
1674                                 printk(KERN_ERR "CIFS: bad ip= option (%s).\n",
1675                                         string);
1676                                 goto cifs_parse_mount_err;
1677                         }
1678                         got_ip = true;
1679                         break;
1680                 case Opt_domain:
1681                         string = match_strdup(args);
1682                         if (string == NULL)
1683                                 goto out_nomem;
1684 
1685                         if (strnlen(string, CIFS_MAX_DOMAINNAME_LEN)
1686                                         == CIFS_MAX_DOMAINNAME_LEN) {
1687                                 printk(KERN_WARNING "CIFS: domain name too"
1688                                                     " long\n");
1689                                 goto cifs_parse_mount_err;
1690                         }
1691 
1692                         vol->domainname = kstrdup(string, GFP_KERNEL);
1693                         if (!vol->domainname) {
1694                                 printk(KERN_WARNING "CIFS: no memory "
1695                                                     "for domainname\n");
1696                                 goto cifs_parse_mount_err;
1697                         }
1698                         cifs_dbg(FYI, "Domain name set\n");
1699                         break;
1700                 case Opt_srcaddr:
1701                         string = match_strdup(args);
1702                         if (string == NULL)
1703                                 goto out_nomem;
1704 
1705                         if (!cifs_convert_address(
1706                                         (struct sockaddr *)&vol->srcaddr,
1707                                         string, strlen(string))) {
1708                                 printk(KERN_WARNING "CIFS:  Could not parse"
1709                                                     " srcaddr: %s\n", string);
1710                                 goto cifs_parse_mount_err;
1711                         }
1712                         break;
1713                 case Opt_iocharset:
1714                         string = match_strdup(args);
1715                         if (string == NULL)
1716                                 goto out_nomem;
1717 
1718                         if (strnlen(string, 1024) >= 65) {
1719                                 printk(KERN_WARNING "CIFS: iocharset name "
1720                                                     "too long.\n");
1721                                 goto cifs_parse_mount_err;
1722                         }
1723 
1724                          if (strnicmp(string, "default", 7) != 0) {
1725                                 vol->iocharset = kstrdup(string,
1726                                                          GFP_KERNEL);
1727                                 if (!vol->iocharset) {
1728                                         printk(KERN_WARNING "CIFS: no memory"
1729                                                             "for charset\n");
1730                                         goto cifs_parse_mount_err;
1731                                 }
1732                         }
1733                         /* if iocharset not set then load_nls_default
1734                          * is used by caller
1735                          */
1736                          cifs_dbg(FYI, "iocharset set to %s\n", string);
1737                         break;
1738                 case Opt_netbiosname:
1739                         string = match_strdup(args);
1740                         if (string == NULL)
1741                                 goto out_nomem;
1742 
1743                         memset(vol->source_rfc1001_name, 0x20,
1744                                 RFC1001_NAME_LEN);
1745                         /*
1746                          * FIXME: are there cases in which a comma can
1747                          * be valid in workstation netbios name (and
1748                          * need special handling)?
1749                          */
1750                         for (i = 0; i < RFC1001_NAME_LEN; i++) {
1751                                 /* don't ucase netbiosname for user */
1752                                 if (string[i] == 0)
1753                                         break;
1754                                 vol->source_rfc1001_name[i] = string[i];
1755                         }
1756                         /* The string has 16th byte zero still from
1757                          * set at top of the function
1758                          */
1759                         if (i == RFC1001_NAME_LEN && string[i] != 0)
1760                                 printk(KERN_WARNING "CIFS: netbiosname"
1761                                        " longer than 15 truncated.\n");
1762 
1763                         break;
1764                 case Opt_servern:
1765                         /* servernetbiosname specified override *SMBSERVER */
1766                         string = match_strdup(args);
1767                         if (string == NULL)
1768                                 goto out_nomem;
1769 
1770                         /* last byte, type, is 0x20 for servr type */
1771                         memset(vol->target_rfc1001_name, 0x20,
1772                                 RFC1001_NAME_LEN_WITH_NULL);
1773 
1774                         /* BB are there cases in which a comma can be
1775                            valid in this workstation netbios name
1776                            (and need special handling)? */
1777 
1778                         /* user or mount helper must uppercase the
1779                            netbios name */
1780                         for (i = 0; i < 15; i++) {
1781                                 if (string[i] == 0)
1782                                         break;
1783                                 vol->target_rfc1001_name[i] = string[i];
1784                         }
1785                         /* The string has 16th byte zero still from
1786                            set at top of the function  */
1787                         if (i == RFC1001_NAME_LEN && string[i] != 0)
1788                                 printk(KERN_WARNING "CIFS: server net"
1789                                        "biosname longer than 15 truncated.\n");
1790                         break;
1791                 case Opt_ver:
1792                         string = match_strdup(args);
1793                         if (string == NULL)
1794                                 goto out_nomem;
1795 
1796                         if (strnicmp(string, "1", 1) == 0) {
1797                                 /* This is the default */
1798                                 break;
1799                         }
1800                         /* For all other value, error */
1801                         printk(KERN_WARNING "CIFS: Invalid version"
1802                                             " specified\n");
1803                         goto cifs_parse_mount_err;
1804                 case Opt_vers:
1805                         string = match_strdup(args);
1806                         if (string == NULL)
1807                                 goto out_nomem;
1808 
1809                         if (cifs_parse_smb_version(string, vol) != 0)
1810                                 goto cifs_parse_mount_err;
1811                         break;
1812                 case Opt_sec:
1813                         string = match_strdup(args);
1814                         if (string == NULL)
1815                                 goto out_nomem;
1816 
1817                         if (cifs_parse_security_flavors(string, vol) != 0)
1818                                 goto cifs_parse_mount_err;
1819                         break;
1820                 case Opt_cache:
1821                         string = match_strdup(args);
1822                         if (string == NULL)
1823                                 goto out_nomem;
1824 
1825                         if (cifs_parse_cache_flavor(string, vol) != 0)
1826                                 goto cifs_parse_mount_err;
1827                         break;
1828                 default:
1829                         /*
1830                          * An option we don't recognize. Save it off for later
1831                          * if we haven't already found one
1832                          */
1833                         if (!invalid)
1834                                 invalid = data;
1835                         break;
1836                 }
1837                 /* Free up any allocated string */
1838                 kfree(string);
1839                 string = NULL;
1840         }
1841 
1842         if (!sloppy && invalid) {
1843                 printk(KERN_ERR "CIFS: Unknown mount option \"%s\"\n", invalid);
1844                 goto cifs_parse_mount_err;
1845         }
1846 
1847 #ifndef CONFIG_KEYS
1848         /* Muliuser mounts require CONFIG_KEYS support */
1849         if (vol->multiuser) {
1850                 cifs_dbg(VFS, "Multiuser mounts require kernels with CONFIG_KEYS enabled\n");
1851                 goto cifs_parse_mount_err;
1852         }
1853 #endif
1854         if (!vol->UNC) {
1855                 cifs_dbg(VFS, "CIFS mount error: No usable UNC path provided in device string!\n");
1856                 goto cifs_parse_mount_err;
1857         }
1858 
1859         /* make sure UNC has a share name */
1860         if (!strchr(vol->UNC + 3, '\\')) {
1861                 cifs_dbg(VFS, "Malformed UNC. Unable to find share name.\n");
1862                 goto cifs_parse_mount_err;
1863         }
1864 
1865         if (!got_ip) {
1866                 /* No ip= option specified? Try to get it from UNC */
1867                 if (!cifs_convert_address(dstaddr, &vol->UNC[2],
1868                                                 strlen(&vol->UNC[2]))) {
1869                         printk(KERN_ERR "Unable to determine destination "
1870                                         "address.\n");
1871                         goto cifs_parse_mount_err;
1872                 }
1873         }
1874 
1875         /* set the port that we got earlier */
1876         cifs_set_port(dstaddr, port);
1877 
1878         if (uid_specified)
1879                 vol->override_uid = override_uid;
1880         else if (override_uid == 1)
1881                 printk(KERN_NOTICE "CIFS: ignoring forceuid mount option "
1882                                    "specified with no uid= option.\n");
1883 
1884         if (gid_specified)
1885                 vol->override_gid = override_gid;
1886         else if (override_gid == 1)
1887                 printk(KERN_NOTICE "CIFS: ignoring forcegid mount option "
1888                                    "specified with no gid= option.\n");
1889 
1890         kfree(mountdata_copy);
1891         return 0;
1892 
1893 out_nomem:
1894         printk(KERN_WARNING "Could not allocate temporary buffer\n");
1895 cifs_parse_mount_err:
1896         kfree(string);
1897         kfree(mountdata_copy);
1898         return 1;
1899 }
1900 
1901 /** Returns true if srcaddr isn't specified and rhs isn't
1902  * specified, or if srcaddr is specified and
1903  * matches the IP address of the rhs argument.
1904  */
1905 static bool
1906 srcip_matches(struct sockaddr *srcaddr, struct sockaddr *rhs)
1907 {
1908         switch (srcaddr->sa_family) {
1909         case AF_UNSPEC:
1910                 return (rhs->sa_family == AF_UNSPEC);
1911         case AF_INET: {
1912                 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1913                 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1914                 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1915         }
1916         case AF_INET6: {
1917                 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1918                 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1919                 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1920         }
1921         default:
1922                 WARN_ON(1);
1923                 return false; /* don't expect to be here */
1924         }
1925 }
1926 
1927 /*
1928  * If no port is specified in addr structure, we try to match with 445 port
1929  * and if it fails - with 139 ports. It should be called only if address
1930  * families of server and addr are equal.
1931  */
1932 static bool
1933 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1934 {
1935         __be16 port, *sport;
1936 
1937         switch (addr->sa_family) {
1938         case AF_INET:
1939                 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1940                 port = ((struct sockaddr_in *) addr)->sin_port;
1941                 break;
1942         case AF_INET6:
1943                 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1944                 port = ((struct sockaddr_in6 *) addr)->sin6_port;
1945                 break;
1946         default:
1947                 WARN_ON(1);
1948                 return false;
1949         }
1950 
1951         if (!port) {
1952                 port = htons(CIFS_PORT);
1953                 if (port == *sport)
1954                         return true;
1955 
1956                 port = htons(RFC1001_PORT);
1957         }
1958 
1959         return port == *sport;
1960 }
1961 
1962 static bool
1963 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1964               struct sockaddr *srcaddr)
1965 {
1966         switch (addr->sa_family) {
1967         case AF_INET: {
1968                 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1969                 struct sockaddr_in *srv_addr4 =
1970                                         (struct sockaddr_in *)&server->dstaddr;
1971 
1972                 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1973                         return false;
1974                 break;
1975         }
1976         case AF_INET6: {
1977                 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1978                 struct sockaddr_in6 *srv_addr6 =
1979                                         (struct sockaddr_in6 *)&server->dstaddr;
1980 
1981                 if (!ipv6_addr_equal(&addr6->sin6_addr,
1982                                      &srv_addr6->sin6_addr))
1983                         return false;
1984                 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1985                         return false;
1986                 break;
1987         }
1988         default:
1989                 WARN_ON(1);
1990                 return false; /* don't expect to be here */
1991         }
1992 
1993         if (!srcip_matches(srcaddr, (struct sockaddr *)&server->srcaddr))
1994                 return false;
1995 
1996         return true;
1997 }
1998 
1999 static bool
2000 match_security(struct TCP_Server_Info *server, struct smb_vol *vol)
2001 {
2002         /*
2003          * The select_sectype function should either return the vol->sectype
2004          * that was specified, or "Unspecified" if that sectype was not
2005          * compatible with the given NEGOTIATE request.
2006          */
2007         if (select_sectype(server, vol->sectype) == Unspecified)
2008                 return false;
2009 
2010         /*
2011          * Now check if signing mode is acceptable. No need to check
2012          * global_secflags at this point since if MUST_SIGN is set then
2013          * the server->sign had better be too.
2014          */
2015         if (vol->sign && !server->sign)
2016                 return false;
2017 
2018         return true;
2019 }
2020 
2021 static int match_server(struct TCP_Server_Info *server, struct smb_vol *vol)
2022 {
2023         struct sockaddr *addr = (struct sockaddr *)&vol->dstaddr;
2024 
2025         if (vol->nosharesock)
2026                 return 0;
2027 
2028         if ((server->vals != vol->vals) || (server->ops != vol->ops))
2029                 return 0;
2030 
2031         if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
2032                 return 0;
2033 
2034         if (!match_address(server, addr,
2035                            (struct sockaddr *)&vol->srcaddr))
2036                 return 0;
2037 
2038         if (!match_port(server, addr))
2039                 return 0;
2040 
2041         if (!match_security(server, vol))
2042                 return 0;
2043 
2044         return 1;
2045 }
2046 
2047 static struct TCP_Server_Info *
2048 cifs_find_tcp_session(struct smb_vol *vol)
2049 {
2050         struct TCP_Server_Info *server;
2051 
2052         spin_lock(&cifs_tcp_ses_lock);
2053         list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
2054                 if (!match_server(server, vol))
2055                         continue;
2056 
2057                 ++server->srv_count;
2058                 spin_unlock(&cifs_tcp_ses_lock);
2059                 cifs_dbg(FYI, "Existing tcp session with server found\n");
2060                 return server;
2061         }
2062         spin_unlock(&cifs_tcp_ses_lock);
2063         return NULL;
2064 }
2065 
2066 void
2067 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
2068 {
2069         struct task_struct *task;
2070 
2071         spin_lock(&cifs_tcp_ses_lock);
2072         if (--server->srv_count > 0) {
2073                 spin_unlock(&cifs_tcp_ses_lock);
2074                 return;
2075         }
2076 
2077         put_net(cifs_net_ns(server));
2078 
2079         list_del_init(&server->tcp_ses_list);
2080         spin_unlock(&cifs_tcp_ses_lock);
2081 
2082         cancel_delayed_work_sync(&server->echo);
2083 
2084 #ifdef CONFIG_CIFS_SMB2
2085         if (from_reconnect)
2086                 /*
2087                  * Avoid deadlock here: reconnect work calls
2088                  * cifs_put_tcp_session() at its end. Need to be sure
2089                  * that reconnect work does nothing with server pointer after
2090                  * that step.
2091                  */
2092                 cancel_delayed_work(&server->reconnect);
2093         else
2094                 cancel_delayed_work_sync(&server->reconnect);
2095 #endif
2096 
2097         spin_lock(&GlobalMid_Lock);
2098         server->tcpStatus = CifsExiting;
2099         spin_unlock(&GlobalMid_Lock);
2100 
2101         cifs_crypto_shash_release(server);
2102         cifs_fscache_release_client_cookie(server);
2103 
2104         kfree(server->session_key.response);
2105         server->session_key.response = NULL;
2106         server->session_key.len = 0;
2107 
2108         task = xchg(&server->tsk, NULL);
2109         if (task)
2110                 force_sig(SIGKILL, task);
2111 }
2112 
2113 static struct TCP_Server_Info *
2114 cifs_get_tcp_session(struct smb_vol *volume_info)
2115 {
2116         struct TCP_Server_Info *tcp_ses = NULL;
2117         int rc;
2118 
2119         cifs_dbg(FYI, "UNC: %s\n", volume_info->UNC);
2120 
2121         /* see if we already have a matching tcp_ses */
2122         tcp_ses = cifs_find_tcp_session(volume_info);
2123         if (tcp_ses)
2124                 return tcp_ses;
2125 
2126         tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
2127         if (!tcp_ses) {
2128                 rc = -ENOMEM;
2129                 goto out_err;
2130         }
2131 
2132         tcp_ses->ops = volume_info->ops;
2133         tcp_ses->vals = volume_info->vals;
2134         cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
2135         tcp_ses->hostname = extract_hostname(volume_info->UNC);
2136         if (IS_ERR(tcp_ses->hostname)) {
2137                 rc = PTR_ERR(tcp_ses->hostname);
2138                 goto out_err_crypto_release;
2139         }
2140 
2141         tcp_ses->noblocksnd = volume_info->noblocksnd;
2142         tcp_ses->noautotune = volume_info->noautotune;
2143         tcp_ses->tcp_nodelay = volume_info->sockopt_tcp_nodelay;
2144         tcp_ses->in_flight = 0;
2145         tcp_ses->credits = 1;
2146         init_waitqueue_head(&tcp_ses->response_q);
2147         init_waitqueue_head(&tcp_ses->request_q);
2148         INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
2149         mutex_init(&tcp_ses->srv_mutex);
2150         memcpy(tcp_ses->workstation_RFC1001_name,
2151                 volume_info->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
2152         memcpy(tcp_ses->server_RFC1001_name,
2153                 volume_info->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
2154         tcp_ses->session_estab = false;
2155         tcp_ses->sequence_number = 0;
2156         tcp_ses->lstrp = jiffies;
2157         spin_lock_init(&tcp_ses->req_lock);
2158         INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
2159         INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
2160         INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
2161 #ifdef CONFIG_CIFS_SMB2
2162         INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
2163         mutex_init(&tcp_ses->reconnect_mutex);
2164 #endif
2165         memcpy(&tcp_ses->srcaddr, &volume_info->srcaddr,
2166                sizeof(tcp_ses->srcaddr));
2167         memcpy(&tcp_ses->dstaddr, &volume_info->dstaddr,
2168                 sizeof(tcp_ses->dstaddr));
2169 #ifdef CONFIG_CIFS_SMB2
2170         generate_random_uuid(tcp_ses->client_guid);
2171 #endif
2172         /*
2173          * at this point we are the only ones with the pointer
2174          * to the struct since the kernel thread not created yet
2175          * no need to spinlock this init of tcpStatus or srv_count
2176          */
2177         tcp_ses->tcpStatus = CifsNew;
2178         ++tcp_ses->srv_count;
2179 
2180         rc = ip_connect(tcp_ses);
2181         if (rc < 0) {
2182                 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
2183                 goto out_err_crypto_release;
2184         }
2185 
2186         /*
2187          * since we're in a cifs function already, we know that
2188          * this will succeed. No need for try_module_get().
2189          */
2190         __module_get(THIS_MODULE);
2191         tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
2192                                   tcp_ses, "cifsd");
2193         if (IS_ERR(tcp_ses->tsk)) {
2194                 rc = PTR_ERR(tcp_ses->tsk);
2195                 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
2196                 module_put(THIS_MODULE);
2197                 goto out_err_crypto_release;
2198         }
2199         tcp_ses->tcpStatus = CifsNeedNegotiate;
2200 
2201         /* thread spawned, put it on the list */
2202         spin_lock(&cifs_tcp_ses_lock);
2203         list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
2204         spin_unlock(&cifs_tcp_ses_lock);
2205 
2206         cifs_fscache_get_client_cookie(tcp_ses);
2207 
2208         /* queue echo request delayed work */
2209         queue_delayed_work(cifsiod_wq, &tcp_ses->echo, SMB_ECHO_INTERVAL);
2210 
2211         return tcp_ses;
2212 
2213 out_err_crypto_release:
2214         cifs_crypto_shash_release(tcp_ses);
2215 
2216         put_net(cifs_net_ns(tcp_ses));
2217 
2218 out_err:
2219         if (tcp_ses) {
2220                 if (!IS_ERR(tcp_ses->hostname))
2221                         kfree(tcp_ses->hostname);
2222                 if (tcp_ses->ssocket)
2223                         sock_release(tcp_ses->ssocket);
2224                 kfree(tcp_ses);
2225         }
2226         return ERR_PTR(rc);
2227 }
2228 
2229 static int match_session(struct cifs_ses *ses, struct smb_vol *vol)
2230 {
2231         if (vol->sectype != Unspecified &&
2232             vol->sectype != ses->sectype)
2233                 return 0;
2234 
2235         switch (ses->sectype) {
2236         case Kerberos:
2237                 if (!uid_eq(vol->cred_uid, ses->cred_uid))
2238                         return 0;
2239                 break;
2240         default:
2241                 /* NULL username means anonymous session */
2242                 if (ses->user_name == NULL) {
2243                         if (!vol->nullauth)
2244                                 return 0;
2245                         break;
2246                 }
2247 
2248                 /* anything else takes username/password */
2249                 if (strncmp(ses->user_name,
2250                             vol->username ? vol->username : "",
2251                             CIFS_MAX_USERNAME_LEN))
2252                         return 0;
2253                 if (strlen(vol->username) != 0 &&
2254                     ses->password != NULL &&
2255                     strncmp(ses->password,
2256                             vol->password ? vol->password : "",
2257                             CIFS_MAX_PASSWORD_LEN))
2258                         return 0;
2259         }
2260         return 1;
2261 }
2262 
2263 static struct cifs_ses *
2264 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol)
2265 {
2266         struct cifs_ses *ses;
2267 
2268         spin_lock(&cifs_tcp_ses_lock);
2269         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2270                 if (ses->status == CifsExiting)
2271                         continue;
2272                 if (!match_session(ses, vol))
2273                         continue;
2274                 ++ses->ses_count;
2275                 spin_unlock(&cifs_tcp_ses_lock);
2276                 return ses;
2277         }
2278         spin_unlock(&cifs_tcp_ses_lock);
2279         return NULL;
2280 }
2281 
2282 static void
2283 cifs_put_smb_ses(struct cifs_ses *ses)
2284 {
2285         unsigned int rc, xid;
2286         struct TCP_Server_Info *server = ses->server;
2287 
2288         cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2289 
2290         spin_lock(&cifs_tcp_ses_lock);
2291         if (ses->status == CifsExiting) {
2292                 spin_unlock(&cifs_tcp_ses_lock);
2293                 return;
2294         }
2295         if (--ses->ses_count > 0) {
2296                 spin_unlock(&cifs_tcp_ses_lock);
2297                 return;
2298         }
2299         if (ses->status == CifsGood)
2300                 ses->status = CifsExiting;
2301         spin_unlock(&cifs_tcp_ses_lock);
2302 
2303         if (ses->status == CifsExiting && server->ops->logoff) {
2304                 xid = get_xid();
2305                 rc = server->ops->logoff(xid, ses);
2306                 if (rc)
2307                         cifs_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2308                                 __func__, rc);
2309                 _free_xid(xid);
2310         }
2311 
2312         spin_lock(&cifs_tcp_ses_lock);
2313         list_del_init(&ses->smb_ses_list);
2314         spin_unlock(&cifs_tcp_ses_lock);
2315 
2316         sesInfoFree(ses);
2317         cifs_put_tcp_session(server, 0);
2318 }
2319 
2320 #ifdef CONFIG_KEYS
2321 
2322 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2323 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2324 
2325 /* Populate username and pw fields from keyring if possible */
2326 static int
2327 cifs_set_cifscreds(struct smb_vol *vol, struct cifs_ses *ses)
2328 {
2329         int rc = 0;
2330         char *desc, *delim, *payload;
2331         ssize_t len;
2332         struct key *key;
2333         struct TCP_Server_Info *server = ses->server;
2334         struct sockaddr_in *sa;
2335         struct sockaddr_in6 *sa6;
2336         struct user_key_payload *upayload;
2337 
2338         desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2339         if (!desc)
2340                 return -ENOMEM;
2341 
2342         /* try to find an address key first */
2343         switch (server->dstaddr.ss_family) {
2344         case AF_INET:
2345                 sa = (struct sockaddr_in *)&server->dstaddr;
2346                 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2347                 break;
2348         case AF_INET6:
2349                 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2350                 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2351                 break;
2352         default:
2353                 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2354                          server->dstaddr.ss_family);
2355                 rc = -EINVAL;
2356                 goto out_err;
2357         }
2358 
2359         cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2360         key = request_key(&key_type_logon, desc, "");
2361         if (IS_ERR(key)) {
2362                 if (!ses->domainName) {
2363                         cifs_dbg(FYI, "domainName is NULL\n");
2364                         rc = PTR_ERR(key);
2365                         goto out_err;
2366                 }
2367 
2368                 /* didn't work, try to find a domain key */
2369                 sprintf(desc, "cifs:d:%s", ses->domainName);
2370                 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2371                 key = request_key(&key_type_logon, desc, "");
2372                 if (IS_ERR(key)) {
2373                         rc = PTR_ERR(key);
2374                         goto out_err;
2375                 }
2376         }
2377 
2378         down_read(&key->sem);
2379         upayload = key->payload.data;
2380         if (IS_ERR_OR_NULL(upayload)) {
2381                 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2382                 goto out_key_put;
2383         }
2384 
2385         /* find first : in payload */
2386         payload = (char *)upayload->data;
2387         delim = strnchr(payload, upayload->datalen, ':');
2388         cifs_dbg(FYI, "payload=%s\n", payload);
2389         if (!delim) {
2390                 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2391                          upayload->datalen);
2392                 rc = -EINVAL;
2393                 goto out_key_put;
2394         }
2395 
2396         len = delim - payload;
2397         if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2398                 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2399                          len);
2400                 rc = -EINVAL;
2401                 goto out_key_put;
2402         }
2403 
2404         vol->username = kstrndup(payload, len, GFP_KERNEL);
2405         if (!vol->username) {
2406                 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2407                          len);
2408                 rc = -ENOMEM;
2409                 goto out_key_put;
2410         }
2411         cifs_dbg(FYI, "%s: username=%s\n", __func__, vol->username);
2412 
2413         len = key->datalen - (len + 1);
2414         if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2415                 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2416                 rc = -EINVAL;
2417                 kfree(vol->username);
2418                 vol->username = NULL;
2419                 goto out_key_put;
2420         }
2421 
2422         ++delim;
2423         vol->password = kstrndup(delim, len, GFP_KERNEL);
2424         if (!vol->password) {
2425                 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2426                          len);
2427                 rc = -ENOMEM;
2428                 kfree(vol->username);
2429                 vol->username = NULL;
2430                 goto out_key_put;
2431         }
2432 
2433 out_key_put:
2434         up_read(&key->sem);
2435         key_put(key);
2436 out_err:
2437         kfree(desc);
2438         cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2439         return rc;
2440 }
2441 #else /* ! CONFIG_KEYS */
2442 static inline int
2443 cifs_set_cifscreds(struct smb_vol *vol __attribute__((unused)),
2444                    struct cifs_ses *ses __attribute__((unused)))
2445 {
2446         return -ENOSYS;
2447 }
2448 #endif /* CONFIG_KEYS */
2449 
2450 static struct cifs_ses *
2451 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
2452 {
2453         int rc = -ENOMEM;
2454         unsigned int xid;
2455         struct cifs_ses *ses;
2456         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2457         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2458 
2459         xid = get_xid();
2460 
2461         ses = cifs_find_smb_ses(server, volume_info);
2462         if (ses) {
2463                 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2464                          ses->status);
2465 
2466                 mutex_lock(&ses->session_mutex);
2467                 rc = cifs_negotiate_protocol(xid, ses);
2468                 if (rc) {
2469                         mutex_unlock(&ses->session_mutex);
2470                         /* problem -- put our ses reference */
2471                         cifs_put_smb_ses(ses);
2472                         free_xid(xid);
2473                         return ERR_PTR(rc);
2474                 }
2475                 if (ses->need_reconnect) {
2476                         cifs_dbg(FYI, "Session needs reconnect\n");
2477                         rc = cifs_setup_session(xid, ses,
2478                                                 volume_info->local_nls);
2479                         if (rc) {
2480                                 mutex_unlock(&ses->session_mutex);
2481                                 /* problem -- put our reference */
2482                                 cifs_put_smb_ses(ses);
2483                                 free_xid(xid);
2484                                 return ERR_PTR(rc);
2485                         }
2486                 }
2487                 mutex_unlock(&ses->session_mutex);
2488 
2489                 /* existing SMB ses has a server reference already */
2490                 cifs_put_tcp_session(server, 0);
2491                 free_xid(xid);
2492                 return ses;
2493         }
2494 
2495         cifs_dbg(FYI, "Existing smb sess not found\n");
2496         ses = sesInfoAlloc();
2497         if (ses == NULL)
2498                 goto get_ses_fail;
2499 
2500         /* new SMB session uses our server ref */
2501         ses->server = server;
2502         if (server->dstaddr.ss_family == AF_INET6)
2503                 sprintf(ses->serverName, "%pI6", &addr6->sin6_addr);
2504         else
2505                 sprintf(ses->serverName, "%pI4", &addr->sin_addr);
2506 
2507         if (volume_info->username) {
2508                 ses->user_name = kstrdup(volume_info->username, GFP_KERNEL);
2509                 if (!ses->user_name)
2510                         goto get_ses_fail;
2511         }
2512 
2513         /* volume_info->password freed at unmount */
2514         if (volume_info->password) {
2515                 ses->password = kstrdup(volume_info->password, GFP_KERNEL);
2516                 if (!ses->password)
2517                         goto get_ses_fail;
2518         }
2519         if (volume_info->domainname) {
2520                 ses->domainName = kstrdup(volume_info->domainname, GFP_KERNEL);
2521                 if (!ses->domainName)
2522                         goto get_ses_fail;
2523         }
2524         ses->cred_uid = volume_info->cred_uid;
2525         ses->linux_uid = volume_info->linux_uid;
2526 
2527         ses->sectype = volume_info->sectype;
2528         ses->sign = volume_info->sign;
2529 
2530         mutex_lock(&ses->session_mutex);
2531         rc = cifs_negotiate_protocol(xid, ses);
2532         if (!rc)
2533                 rc = cifs_setup_session(xid, ses, volume_info->local_nls);
2534         mutex_unlock(&ses->session_mutex);
2535         if (rc)
2536                 goto get_ses_fail;
2537 
2538         /* success, put it on the list */
2539         spin_lock(&cifs_tcp_ses_lock);
2540         list_add(&ses->smb_ses_list, &server->smb_ses_list);
2541         spin_unlock(&cifs_tcp_ses_lock);
2542 
2543         free_xid(xid);
2544         return ses;
2545 
2546 get_ses_fail:
2547         sesInfoFree(ses);
2548         free_xid(xid);
2549         return ERR_PTR(rc);
2550 }
2551 
2552 static int match_tcon(struct cifs_tcon *tcon, const char *unc)
2553 {
2554         if (tcon->tidStatus == CifsExiting)
2555                 return 0;
2556         if (strncmp(tcon->treeName, unc, MAX_TREE_SIZE))
2557                 return 0;
2558         return 1;
2559 }
2560 
2561 static struct cifs_tcon *
2562 cifs_find_tcon(struct cifs_ses *ses, const char *unc)
2563 {
2564         struct list_head *tmp;
2565         struct cifs_tcon *tcon;
2566 
2567         spin_lock(&cifs_tcp_ses_lock);
2568         list_for_each(tmp, &ses->tcon_list) {
2569                 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2570                 if (!match_tcon(tcon, unc))
2571                         continue;
2572                 ++tcon->tc_count;
2573                 spin_unlock(&cifs_tcp_ses_lock);
2574                 return tcon;
2575         }
2576         spin_unlock(&cifs_tcp_ses_lock);
2577         return NULL;
2578 }
2579 
2580 void
2581 cifs_put_tcon(struct cifs_tcon *tcon)
2582 {
2583         unsigned int xid;
2584         struct cifs_ses *ses = tcon->ses;
2585 
2586         cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2587         spin_lock(&cifs_tcp_ses_lock);
2588         if (--tcon->tc_count > 0) {
2589                 spin_unlock(&cifs_tcp_ses_lock);
2590                 return;
2591         }
2592 
2593         list_del_init(&tcon->tcon_list);
2594         spin_unlock(&cifs_tcp_ses_lock);
2595 
2596         xid = get_xid();
2597         if (ses->server->ops->tree_disconnect)
2598                 ses->server->ops->tree_disconnect(xid, tcon);
2599         _free_xid(xid);
2600 
2601         cifs_fscache_release_super_cookie(tcon);
2602         tconInfoFree(tcon);
2603         cifs_put_smb_ses(ses);
2604 }
2605 
2606 static struct cifs_tcon *
2607 cifs_get_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
2608 {
2609         int rc, xid;
2610         struct cifs_tcon *tcon;
2611 
2612         tcon = cifs_find_tcon(ses, volume_info->UNC);
2613         if (tcon) {
2614                 cifs_dbg(FYI, "Found match on UNC path\n");
2615                 /* existing tcon already has a reference */
2616                 cifs_put_smb_ses(ses);
2617                 if (tcon->seal != volume_info->seal)
2618                         cifs_dbg(VFS, "transport encryption setting conflicts with existing tid\n");
2619                 return tcon;
2620         }
2621 
2622         if (!ses->server->ops->tree_connect) {
2623                 rc = -ENOSYS;
2624                 goto out_fail;
2625         }
2626 
2627         tcon = tconInfoAlloc();
2628         if (tcon == NULL) {
2629                 rc = -ENOMEM;
2630                 goto out_fail;
2631         }
2632 
2633         tcon->ses = ses;
2634         if (volume_info->password) {
2635                 tcon->password = kstrdup(volume_info->password, GFP_KERNEL);
2636                 if (!tcon->password) {
2637                         rc = -ENOMEM;
2638                         goto out_fail;
2639                 }
2640         }
2641 
2642         /*
2643          * BB Do we need to wrap session_mutex around this TCon call and Unix
2644          * SetFS as we do on SessSetup and reconnect?
2645          */
2646         xid = get_xid();
2647         rc = ses->server->ops->tree_connect(xid, ses, volume_info->UNC, tcon,
2648                                             volume_info->local_nls);
2649         free_xid(xid);
2650         cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2651         if (rc)
2652                 goto out_fail;
2653 
2654         if (volume_info->nodfs) {
2655                 tcon->Flags &= ~SMB_SHARE_IS_IN_DFS;
2656                 cifs_dbg(FYI, "DFS disabled (%d)\n", tcon->Flags);
2657         }
2658         tcon->seal = volume_info->seal;
2659         /*
2660          * We can have only one retry value for a connection to a share so for
2661          * resources mounted more than once to the same server share the last
2662          * value passed in for the retry flag is used.
2663          */
2664         tcon->retry = volume_info->retry;
2665         tcon->nocase = volume_info->nocase;
2666         tcon->local_lease = volume_info->local_lease;
2667         INIT_LIST_HEAD(&tcon->pending_opens);
2668 
2669         spin_lock(&cifs_tcp_ses_lock);
2670         list_add(&tcon->tcon_list, &ses->tcon_list);
2671         spin_unlock(&cifs_tcp_ses_lock);
2672 
2673         cifs_fscache_get_super_cookie(tcon);
2674 
2675         return tcon;
2676 
2677 out_fail:
2678         tconInfoFree(tcon);
2679         return ERR_PTR(rc);
2680 }
2681 
2682 void
2683 cifs_put_tlink(struct tcon_link *tlink)
2684 {
2685         if (!tlink || IS_ERR(tlink))
2686                 return;
2687 
2688         if (!atomic_dec_and_test(&tlink->tl_count) ||
2689             test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2690                 tlink->tl_time = jiffies;
2691                 return;
2692         }
2693 
2694         if (!IS_ERR(tlink_tcon(tlink)))
2695                 cifs_put_tcon(tlink_tcon(tlink));
2696         kfree(tlink);
2697         return;
2698 }
2699 
2700 static inline struct tcon_link *
2701 cifs_sb_master_tlink(struct cifs_sb_info *cifs_sb)
2702 {
2703         return cifs_sb->master_tlink;
2704 }
2705 
2706 static int
2707 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2708 {
2709         struct cifs_sb_info *old = CIFS_SB(sb);
2710         struct cifs_sb_info *new = mnt_data->cifs_sb;
2711 
2712         if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2713                 return 0;
2714 
2715         if ((old->mnt_cifs_flags & CIFS_MOUNT_MASK) !=
2716             (new->mnt_cifs_flags & CIFS_MOUNT_MASK))
2717                 return 0;
2718 
2719         /*
2720          * We want to share sb only if we don't specify an r/wsize or
2721          * specified r/wsize is greater than or equal to existing one.
2722          */
2723         if (new->wsize && new->wsize < old->wsize)
2724                 return 0;
2725 
2726         if (new->rsize && new->rsize < old->rsize)
2727                 return 0;
2728 
2729         if (!uid_eq(old->mnt_uid, new->mnt_uid) || !gid_eq(old->mnt_gid, new->mnt_gid))
2730                 return 0;
2731 
2732         if (old->mnt_file_mode != new->mnt_file_mode ||
2733             old->mnt_dir_mode != new->mnt_dir_mode)
2734                 return 0;
2735 
2736         if (strcmp(old->local_nls->charset, new->local_nls->charset))
2737                 return 0;
2738 
2739         if (old->actimeo != new->actimeo)
2740                 return 0;
2741 
2742         return 1;
2743 }
2744 
2745 static int
2746 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2747 {
2748         struct cifs_sb_info *old = CIFS_SB(sb);
2749         struct cifs_sb_info *new = mnt_data->cifs_sb;
2750 
2751         if (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) {
2752                 if (!(new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH))
2753                         return 0;
2754                 /* The prepath should be null terminated strings */
2755                 if (strcmp(new->prepath, old->prepath))
2756                         return 0;
2757 
2758                 return 1;
2759         }
2760         return 0;
2761 }
2762 
2763 int
2764 cifs_match_super(struct super_block *sb, void *data)
2765 {
2766         struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
2767         struct smb_vol *volume_info;
2768         struct cifs_sb_info *cifs_sb;
2769         struct TCP_Server_Info *tcp_srv;
2770         struct cifs_ses *ses;
2771         struct cifs_tcon *tcon;
2772         struct tcon_link *tlink;
2773         int rc = 0;
2774 
2775         spin_lock(&cifs_tcp_ses_lock);
2776         cifs_sb = CIFS_SB(sb);
2777         tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2778         if (IS_ERR(tlink)) {
2779                 spin_unlock(&cifs_tcp_ses_lock);
2780                 return rc;
2781         }
2782         tcon = tlink_tcon(tlink);
2783         ses = tcon->ses;
2784         tcp_srv = ses->server;
2785 
2786         volume_info = mnt_data->vol;
2787 
2788         if (!match_server(tcp_srv, volume_info) ||
2789             !match_session(ses, volume_info) ||
2790             !match_tcon(tcon, volume_info->UNC) ||
2791             !match_prepath(sb, mnt_data)) {
2792                 rc = 0;
2793                 goto out;
2794         }
2795 
2796         rc = compare_mount_options(sb, mnt_data);
2797 out:
2798         spin_unlock(&cifs_tcp_ses_lock);
2799         cifs_put_tlink(tlink);
2800         return rc;
2801 }
2802 
2803 int
2804 get_dfs_path(const unsigned int xid, struct cifs_ses *ses, const char *old_path,
2805              const struct nls_table *nls_codepage, unsigned int *num_referrals,
2806              struct dfs_info3_param **referrals, int remap)
2807 {
2808         char *temp_unc;
2809         int rc = 0;
2810 
2811         if (!ses->server->ops->tree_connect || !ses->server->ops->get_dfs_refer)
2812                 return -ENOSYS;
2813 
2814         *num_referrals = 0;
2815         *referrals = NULL;
2816 
2817         if (ses->ipc_tid == 0) {
2818                 temp_unc = kmalloc(2 /* for slashes */ +
2819                         strnlen(ses->serverName, SERVER_NAME_LEN_WITH_NULL * 2)
2820                                 + 1 + 4 /* slash IPC$ */ + 2, GFP_KERNEL);
2821                 if (temp_unc == NULL)
2822                         return -ENOMEM;
2823                 temp_unc[0] = '\\';
2824                 temp_unc[1] = '\\';
2825                 strcpy(temp_unc + 2, ses->serverName);
2826                 strcpy(temp_unc + 2 + strlen(ses->serverName), "\\IPC$");
2827                 rc = ses->server->ops->tree_connect(xid, ses, temp_unc, NULL,
2828                                                     nls_codepage);
2829                 cifs_dbg(FYI, "Tcon rc = %d ipc_tid = %d\n", rc, ses->ipc_tid);
2830                 kfree(temp_unc);
2831         }
2832         if (rc == 0)
2833                 rc = ses->server->ops->get_dfs_refer(xid, ses, old_path,
2834                                                      referrals, num_referrals,
2835                                                      nls_codepage, remap);
2836         /*
2837          * BB - map targetUNCs to dfs_info3 structures, here or in
2838          * ses->server->ops->get_dfs_refer.
2839          */
2840 
2841         return rc;
2842 }
2843 
2844 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2845 static struct lock_class_key cifs_key[2];
2846 static struct lock_class_key cifs_slock_key[2];
2847 
2848 static inline void
2849 cifs_reclassify_socket4(struct socket *sock)
2850 {
2851         struct sock *sk = sock->sk;
2852         BUG_ON(sock_owned_by_user(sk));
2853         sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2854                 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2855 }
2856 
2857 static inline void
2858 cifs_reclassify_socket6(struct socket *sock)
2859 {
2860         struct sock *sk = sock->sk;
2861         BUG_ON(sock_owned_by_user(sk));
2862         sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2863                 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2864 }
2865 #else
2866 static inline void
2867 cifs_reclassify_socket4(struct socket *sock)
2868 {
2869 }
2870 
2871 static inline void
2872 cifs_reclassify_socket6(struct socket *sock)
2873 {
2874 }
2875 #endif
2876 
2877 /* See RFC1001 section 14 on representation of Netbios names */
2878 static void rfc1002mangle(char *target, char *source, unsigned int length)
2879 {
2880         unsigned int i, j;
2881 
2882         for (i = 0, j = 0; i < (length); i++) {
2883                 /* mask a nibble at a time and encode */
2884                 target[j] = 'A' + (0x0F & (source[i] >> 4));
2885                 target[j+1] = 'A' + (0x0F & source[i]);
2886                 j += 2;
2887         }
2888 
2889 }
2890 
2891 static int
2892 bind_socket(struct TCP_Server_Info *server)
2893 {
2894         int rc = 0;
2895         if (server->srcaddr.ss_family != AF_UNSPEC) {
2896                 /* Bind to the specified local IP address */
2897                 struct socket *socket = server->ssocket;
2898                 rc = socket->ops->bind(socket,
2899                                        (struct sockaddr *) &server->srcaddr,
2900                                        sizeof(server->srcaddr));
2901                 if (rc < 0) {
2902                         struct sockaddr_in *saddr4;
2903                         struct sockaddr_in6 *saddr6;
2904                         saddr4 = (struct sockaddr_in *)&server->srcaddr;
2905                         saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2906                         if (saddr6->sin6_family == AF_INET6)
2907                                 cifs_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2908                                          &saddr6->sin6_addr, rc);
2909                         else
2910                                 cifs_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2911                                          &saddr4->sin_addr.s_addr, rc);
2912                 }
2913         }
2914         return rc;
2915 }
2916 
2917 static int
2918 ip_rfc1001_connect(struct TCP_Server_Info *server)
2919 {
2920         int rc = 0;
2921         /*
2922          * some servers require RFC1001 sessinit before sending
2923          * negprot - BB check reconnection in case where second
2924          * sessinit is sent but no second negprot
2925          */
2926         struct rfc1002_session_packet *ses_init_buf;
2927         struct smb_hdr *smb_buf;
2928         ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2929                                GFP_KERNEL);
2930         if (ses_init_buf) {
2931                 ses_init_buf->trailer.session_req.called_len = 32;
2932 
2933                 if (server->server_RFC1001_name &&
2934                     server->server_RFC1001_name[0] != 0)
2935                         rfc1002mangle(ses_init_buf->trailer.
2936                                       session_req.called_name,
2937                                       server->server_RFC1001_name,
2938                                       RFC1001_NAME_LEN_WITH_NULL);
2939                 else
2940                         rfc1002mangle(ses_init_buf->trailer.
2941                                       session_req.called_name,
2942                                       DEFAULT_CIFS_CALLED_NAME,
2943                                       RFC1001_NAME_LEN_WITH_NULL);
2944 
2945                 ses_init_buf->trailer.session_req.calling_len = 32;
2946 
2947                 /*
2948                  * calling name ends in null (byte 16) from old smb
2949                  * convention.
2950                  */
2951                 if (server->workstation_RFC1001_name &&
2952                     server->workstation_RFC1001_name[0] != 0)
2953                         rfc1002mangle(ses_init_buf->trailer.
2954                                       session_req.calling_name,
2955                                       server->workstation_RFC1001_name,
2956                                       RFC1001_NAME_LEN_WITH_NULL);
2957                 else
2958                         rfc1002mangle(ses_init_buf->trailer.
2959                                       session_req.calling_name,
2960                                       "LINUX_CIFS_CLNT",
2961                                       RFC1001_NAME_LEN_WITH_NULL);
2962 
2963                 ses_init_buf->trailer.session_req.scope1 = 0;
2964                 ses_init_buf->trailer.session_req.scope2 = 0;
2965                 smb_buf = (struct smb_hdr *)ses_init_buf;
2966 
2967                 /* sizeof RFC1002_SESSION_REQUEST with no scope */
2968                 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
2969                 rc = smb_send(server, smb_buf, 0x44);
2970                 kfree(ses_init_buf);
2971                 /*
2972                  * RFC1001 layer in at least one server
2973                  * requires very short break before negprot
2974                  * presumably because not expecting negprot
2975                  * to follow so fast.  This is a simple
2976                  * solution that works without
2977                  * complicating the code and causes no
2978                  * significant slowing down on mount
2979                  * for everyone else
2980                  */
2981                 usleep_range(1000, 2000);
2982         }
2983         /*
2984          * else the negprot may still work without this
2985          * even though malloc failed
2986          */
2987 
2988         return rc;
2989 }
2990 
2991 static int
2992 generic_ip_connect(struct TCP_Server_Info *server)
2993 {
2994         int rc = 0;
2995         __be16 sport;
2996         int slen, sfamily;
2997         struct socket *socket = server->ssocket;
2998         struct sockaddr *saddr;
2999 
3000         saddr = (struct sockaddr *) &server->dstaddr;
3001 
3002         if (server->dstaddr.ss_family == AF_INET6) {
3003                 sport = ((struct sockaddr_in6 *) saddr)->sin6_port;
3004                 slen = sizeof(struct sockaddr_in6);
3005                 sfamily = AF_INET6;
3006         } else {
3007                 sport = ((struct sockaddr_in *) saddr)->sin_port;
3008                 slen = sizeof(struct sockaddr_in);
3009                 sfamily = AF_INET;
3010         }
3011 
3012         if (socket == NULL) {
3013                 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3014                                    IPPROTO_TCP, &socket, 1);
3015                 if (rc < 0) {
3016                         cifs_dbg(VFS, "Error %d creating socket\n", rc);
3017                         server->ssocket = NULL;
3018                         return rc;
3019                 }
3020 
3021                 /* BB other socket options to set KEEPALIVE, NODELAY? */
3022                 cifs_dbg(FYI, "Socket created\n");
3023                 server->ssocket = socket;
3024                 socket->sk->sk_allocation = GFP_NOFS;
3025                 if (sfamily == AF_INET6)
3026                         cifs_reclassify_socket6(socket);
3027                 else
3028                         cifs_reclassify_socket4(socket);
3029         }
3030 
3031         rc = bind_socket(server);
3032         if (rc < 0)
3033                 return rc;
3034 
3035         /*
3036          * Eventually check for other socket options to change from
3037          * the default. sock_setsockopt not used because it expects
3038          * user space buffer
3039          */
3040         socket->sk->sk_rcvtimeo = 7 * HZ;
3041         socket->sk->sk_sndtimeo = 5 * HZ;
3042 
3043         /* make the bufsizes depend on wsize/rsize and max requests */
3044         if (server->noautotune) {
3045                 if (socket->sk->sk_sndbuf < (200 * 1024))
3046                         socket->sk->sk_sndbuf = 200 * 1024;
3047                 if (socket->sk->sk_rcvbuf < (140 * 1024))
3048                         socket->sk->sk_rcvbuf = 140 * 1024;
3049         }
3050 
3051         if (server->tcp_nodelay) {
3052                 int val = 1;
3053                 rc = kernel_setsockopt(socket, SOL_TCP, TCP_NODELAY,
3054                                 (char *)&val, sizeof(val));
3055                 if (rc)
3056                         cifs_dbg(FYI, "set TCP_NODELAY socket option error %d\n",
3057                                  rc);
3058         }
3059 
3060         cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3061                  socket->sk->sk_sndbuf,
3062                  socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3063 
3064         rc = socket->ops->connect(socket, saddr, slen, 0);
3065         if (rc < 0) {
3066                 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3067                 sock_release(socket);
3068                 server->ssocket = NULL;
3069                 return rc;
3070         }
3071 
3072         if (sport == htons(RFC1001_PORT))
3073                 rc = ip_rfc1001_connect(server);
3074 
3075         return rc;
3076 }
3077 
3078 static int
3079 ip_connect(struct TCP_Server_Info *server)
3080 {
3081         __be16 *sport;
3082         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3083         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3084 
3085         if (server->dstaddr.ss_family == AF_INET6)
3086                 sport = &addr6->sin6_port;
3087         else
3088                 sport = &addr->sin_port;
3089 
3090         if (*sport == 0) {
3091                 int rc;
3092 
3093                 /* try with 445 port at first */
3094                 *sport = htons(CIFS_PORT);
3095 
3096                 rc = generic_ip_connect(server);
3097                 if (rc >= 0)
3098                         return rc;
3099 
3100                 /* if it failed, try with 139 port */
3101                 *sport = htons(RFC1001_PORT);
3102         }
3103 
3104         return generic_ip_connect(server);
3105 }
3106 
3107 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3108                           struct cifs_sb_info *cifs_sb, struct smb_vol *vol_info)
3109 {
3110         /* if we are reconnecting then should we check to see if
3111          * any requested capabilities changed locally e.g. via
3112          * remount but we can not do much about it here
3113          * if they have (even if we could detect it by the following)
3114          * Perhaps we could add a backpointer to array of sb from tcon
3115          * or if we change to make all sb to same share the same
3116          * sb as NFS - then we only have one backpointer to sb.
3117          * What if we wanted to mount the server share twice once with
3118          * and once without posixacls or posix paths? */
3119         __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3120 
3121         if (vol_info && vol_info->no_linux_ext) {
3122                 tcon->fsUnixInfo.Capability = 0;
3123                 tcon->unix_ext = 0; /* Unix Extensions disabled */
3124                 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3125                 return;
3126         } else if (vol_info)
3127                 tcon->unix_ext = 1; /* Unix Extensions supported */
3128 
3129         if (tcon->unix_ext == 0) {
3130                 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3131                 return;
3132         }
3133 
3134         if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3135                 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3136                 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3137                 /* check for reconnect case in which we do not
3138                    want to change the mount behavior if we can avoid it */
3139                 if (vol_info == NULL) {
3140                         /* turn off POSIX ACL and PATHNAMES if not set
3141                            originally at mount time */
3142                         if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3143                                 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3144                         if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3145                                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3146                                         cifs_dbg(VFS, "POSIXPATH support change\n");
3147                                 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3148                         } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3149                                 cifs_dbg(VFS, "possible reconnect error\n");
3150                                 cifs_dbg(VFS, "server disabled POSIX path support\n");
3151                         }
3152                 }
3153 
3154                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3155                         cifs_dbg(VFS, "per-share encryption not supported yet\n");
3156 
3157                 cap &= CIFS_UNIX_CAP_MASK;
3158                 if (vol_info && vol_info->no_psx_acl)
3159                         cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3160                 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3161                         cifs_dbg(FYI, "negotiated posix acl support\n");
3162                         if (cifs_sb)
3163                                 cifs_sb->mnt_cifs_flags |=
3164                                         CIFS_MOUNT_POSIXACL;
3165                 }
3166 
3167                 if (vol_info && vol_info->posix_paths == 0)
3168                         cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3169                 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3170                         cifs_dbg(FYI, "negotiate posix pathnames\n");
3171                         if (cifs_sb)
3172                                 cifs_sb->mnt_cifs_flags |=
3173                                         CIFS_MOUNT_POSIX_PATHS;
3174                 }
3175 
3176                 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3177 #ifdef CONFIG_CIFS_DEBUG2
3178                 if (cap & CIFS_UNIX_FCNTL_CAP)
3179                         cifs_dbg(FYI, "FCNTL cap\n");
3180                 if (cap & CIFS_UNIX_EXTATTR_CAP)
3181                         cifs_dbg(FYI, "EXTATTR cap\n");
3182                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3183                         cifs_dbg(FYI, "POSIX path cap\n");
3184                 if (cap & CIFS_UNIX_XATTR_CAP)
3185                         cifs_dbg(FYI, "XATTR cap\n");
3186                 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3187                         cifs_dbg(FYI, "POSIX ACL cap\n");
3188                 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3189                         cifs_dbg(FYI, "very large read cap\n");
3190                 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3191                         cifs_dbg(FYI, "very large write cap\n");
3192                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3193                         cifs_dbg(FYI, "transport encryption cap\n");
3194                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3195                         cifs_dbg(FYI, "mandatory transport encryption cap\n");
3196 #endif /* CIFS_DEBUG2 */
3197                 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3198                         if (vol_info == NULL) {
3199                                 cifs_dbg(FYI, "resetting capabilities failed\n");
3200                         } else
3201                                 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");
3202 
3203                 }
3204         }
3205 }
3206 
3207 int cifs_setup_cifs_sb(struct smb_vol *pvolume_info,
3208                         struct cifs_sb_info *cifs_sb)
3209 {
3210         INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3211 
3212         spin_lock_init(&cifs_sb->tlink_tree_lock);
3213         cifs_sb->tlink_tree = RB_ROOT;
3214 
3215         /*
3216          * Temporarily set r/wsize for matching superblock. If we end up using
3217          * new sb then client will later negotiate it downward if needed.
3218          */
3219         cifs_sb->rsize = pvolume_info->rsize;
3220         cifs_sb->wsize = pvolume_info->wsize;
3221 
3222         cifs_sb->mnt_uid = pvolume_info->linux_uid;
3223         cifs_sb->mnt_gid = pvolume_info->linux_gid;
3224         cifs_sb->mnt_file_mode = pvolume_info->file_mode;
3225         cifs_sb->mnt_dir_mode = pvolume_info->dir_mode;
3226         cifs_dbg(FYI, "file mode: 0x%hx  dir mode: 0x%hx\n",
3227                  cifs_sb->mnt_file_mode, cifs_sb->mnt_dir_mode);
3228 
3229         cifs_sb->actimeo = pvolume_info->actimeo;
3230         cifs_sb->local_nls = pvolume_info->local_nls;
3231 
3232         if (pvolume_info->noperm)
3233                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM;
3234         if (pvolume_info->setuids)
3235                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID;
3236         if (pvolume_info->server_ino)
3237                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM;
3238         if (pvolume_info->remap)
3239                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR;
3240         if (pvolume_info->no_xattr)
3241                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR;
3242         if (pvolume_info->sfu_emul)
3243                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UNX_EMUL;
3244         if (pvolume_info->nobrl)
3245                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_BRL;
3246         if (pvolume_info->nostrictsync)
3247                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOSSYNC;
3248         if (pvolume_info->mand_lock)
3249                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOPOSIXBRL;
3250         if (pvolume_info->rwpidforward)
3251                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RWPIDFORWARD;
3252         if (pvolume_info->cifs_acl)
3253                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_ACL;
3254         if (pvolume_info->backupuid_specified) {
3255                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPUID;
3256                 cifs_sb->mnt_backupuid = pvolume_info->backupuid;
3257         }
3258         if (pvolume_info->backupgid_specified) {
3259                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPGID;
3260                 cifs_sb->mnt_backupgid = pvolume_info->backupgid;
3261         }
3262         if (pvolume_info->override_uid)
3263                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_UID;
3264         if (pvolume_info->override_gid)
3265                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_GID;
3266         if (pvolume_info->dynperm)
3267                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DYNPERM;
3268         if (pvolume_info->fsc)
3269                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_FSCACHE;
3270         if (pvolume_info->multiuser)
3271                 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_MULTIUSER |
3272                                             CIFS_MOUNT_NO_PERM);
3273         if (pvolume_info->strict_io)
3274                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_STRICT_IO;
3275         if (pvolume_info->direct_io) {
3276                 cifs_dbg(FYI, "mounting share using direct i/o\n");
3277                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO;
3278         }
3279         if (pvolume_info->mfsymlinks) {
3280                 if (pvolume_info->sfu_emul) {
3281                         cifs_dbg(VFS, "mount option mfsymlinks ignored if sfu mount option is used\n");
3282                 } else {
3283                         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MF_SYMLINKS;
3284                 }
3285         }
3286 
3287         if ((pvolume_info->cifs_acl) && (pvolume_info->dynperm))
3288                 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3289 
3290 
3291         if (pvolume_info->prepath) {
3292                 cifs_sb->prepath = kstrdup(pvolume_info->prepath, GFP_KERNEL);
3293                 if (cifs_sb->prepath == NULL)
3294                         return -ENOMEM;
3295         }
3296 
3297         return 0;
3298 }
3299 
3300 static void
3301 cleanup_volume_info_contents(struct smb_vol *volume_info)
3302 {
3303         kfree(volume_info->username);
3304         kzfree(volume_info->password);
3305         kfree(volume_info->UNC);
3306         kfree(volume_info->domainname);
3307         kfree(volume_info->iocharset);
3308         kfree(volume_info->prepath);
3309 }
3310 
3311 void
3312 cifs_cleanup_volume_info(struct smb_vol *volume_info)
3313 {
3314         if (!volume_info)
3315                 return;
3316         cleanup_volume_info_contents(volume_info);
3317         kfree(volume_info);
3318 }
3319 
3320 
3321 #ifdef CONFIG_CIFS_DFS_UPCALL
3322 /*
3323  * cifs_build_path_to_root returns full path to root when we do not have an
3324  * exiting connection (tcon)
3325  */
3326 static char *
3327 build_unc_path_to_root(const struct smb_vol *vol,
3328                 const struct cifs_sb_info *cifs_sb)
3329 {
3330         char *full_path, *pos;
3331         unsigned int pplen = vol->prepath ? strlen(vol->prepath) + 1 : 0;
3332         unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1);
3333 
3334         full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3335         if (full_path == NULL)
3336                 return ERR_PTR(-ENOMEM);
3337 
3338         strncpy(full_path, vol->UNC, unc_len);
3339         pos = full_path + unc_len;
3340 
3341         if (pplen) {
3342                 *pos = CIFS_DIR_SEP(cifs_sb);
3343                 strncpy(pos + 1, vol->prepath, pplen);
3344                 pos += pplen;
3345         }
3346 
3347         *pos = '\0'; /* add trailing null */
3348         convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3349         cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3350         return full_path;
3351 }
3352 
3353 /*
3354  * Perform a dfs referral query for a share and (optionally) prefix
3355  *
3356  * If a referral is found, cifs_sb->mountdata will be (re-)allocated
3357  * to a string containing updated options for the submount.  Otherwise it
3358  * will be left untouched.
3359  *
3360  * Returns the rc from get_dfs_path to the caller, which can be used to
3361  * determine whether there were referrals.
3362  */
3363 static int
3364 expand_dfs_referral(const unsigned int xid, struct cifs_ses *ses,
3365                     struct smb_vol *volume_info, struct cifs_sb_info *cifs_sb,
3366                     int check_prefix)
3367 {
3368         int rc;
3369         unsigned int num_referrals = 0;
3370         struct dfs_info3_param *referrals = NULL;
3371         char *full_path = NULL, *ref_path = NULL, *mdata = NULL;
3372 
3373         full_path = build_unc_path_to_root(volume_info, cifs_sb);
3374         if (IS_ERR(full_path))
3375                 return PTR_ERR(full_path);
3376 
3377         /* For DFS paths, skip the first '\' of the UNC */
3378         ref_path = check_prefix ? full_path + 1 : volume_info->UNC + 1;
3379 
3380         rc = get_dfs_path(xid, ses, ref_path, cifs_sb->local_nls,
3381                           &num_referrals, &referrals,
3382                           cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR);
3383 
3384         if (!rc && num_referrals > 0) {
3385                 char *fake_devname = NULL;
3386 
3387                 mdata = cifs_compose_mount_options(cifs_sb->mountdata,
3388                                                    full_path + 1, referrals,
3389                                                    &fake_devname);
3390 
3391                 free_dfs_info_array(referrals, num_referrals);
3392 
3393                 if (IS_ERR(mdata)) {
3394                         rc = PTR_ERR(mdata);
3395                         mdata = NULL;
3396                 } else {
3397                         cleanup_volume_info_contents(volume_info);
3398                         rc = cifs_setup_volume_info(volume_info, mdata,
3399                                                         fake_devname);
3400                 }
3401                 kfree(fake_devname);
3402                 kfree(cifs_sb->mountdata);
3403                 cifs_sb->mountdata = mdata;
3404         }
3405         kfree(full_path);
3406         return rc;
3407 }
3408 #endif
3409 
3410 static int
3411 cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
3412                         const char *devname)
3413 {
3414         int rc = 0;
3415 
3416         if (cifs_parse_mount_options(mount_data, devname, volume_info))
3417                 return -EINVAL;
3418 
3419         if (volume_info->nullauth) {
3420                 cifs_dbg(FYI, "Anonymous login\n");
3421                 kfree(volume_info->username);
3422                 volume_info->username = NULL;
3423         } else if (volume_info->username) {
3424                 /* BB fixme parse for domain name here */
3425                 cifs_dbg(FYI, "Username: %s\n", volume_info->username);
3426         } else {
3427                 cifs_dbg(VFS, "No username specified\n");
3428         /* In userspace mount helper we can get user name from alternate
3429            locations such as env variables and files on disk */
3430                 return -EINVAL;
3431         }
3432 
3433         /* this is needed for ASCII cp to Unicode converts */
3434         if (volume_info->iocharset == NULL) {
3435                 /* load_nls_default cannot return null */
3436                 volume_info->local_nls = load_nls_default();
3437         } else {
3438                 volume_info->local_nls = load_nls(volume_info->iocharset);
3439                 if (volume_info->local_nls == NULL) {
3440                         cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3441                                  volume_info->iocharset);
3442                         return -ELIBACC;
3443                 }
3444         }
3445 
3446         return rc;
3447 }
3448 
3449 struct smb_vol *
3450 cifs_get_volume_info(char *mount_data, const char *devname)
3451 {
3452         int rc;
3453         struct smb_vol *volume_info;
3454 
3455         volume_info = kmalloc(sizeof(struct smb_vol), GFP_KERNEL);
3456         if (!volume_info)
3457                 return ERR_PTR(-ENOMEM);
3458 
3459         rc = cifs_setup_volume_info(volume_info, mount_data, devname);
3460         if (rc) {
3461                 cifs_cleanup_volume_info(volume_info);
3462                 volume_info = ERR_PTR(rc);
3463         }
3464 
3465         return volume_info;
3466 }
3467 
3468 static int
3469 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3470                                         unsigned int xid,
3471                                         struct cifs_tcon *tcon,
3472                                         struct cifs_sb_info *cifs_sb,
3473                                         char *full_path)
3474 {
3475         int rc;
3476         char *s;
3477         char sep, tmp;
3478 
3479         sep = CIFS_DIR_SEP(cifs_sb);
3480         s = full_path;
3481 
3482         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3483         while (rc == 0) {
3484                 /* skip separators */
3485                 while (*s == sep)
3486                         s++;
3487                 if (!*s)
3488                         break;
3489                 /* next separator */
3490                 while (*s && *s != sep)
3491                         s++;
3492 
3493                 /*
3494                  * temporarily null-terminate the path at the end of
3495                  * the current component
3496                  */
3497                 tmp = *s;
3498                 *s = 0;
3499                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3500                                                      full_path);
3501                 *s = tmp;
3502         }
3503         return rc;
3504 }
3505 
3506 int
3507 cifs_mount(struct cifs_sb_info *cifs_sb, struct smb_vol *volume_info)
3508 {
3509         int rc;
3510         unsigned int xid;
3511         struct cifs_ses *ses;
3512         struct cifs_tcon *tcon;
3513         struct TCP_Server_Info *server;
3514         char   *full_path;
3515         struct tcon_link *tlink;
3516 #ifdef CONFIG_CIFS_DFS_UPCALL
3517         int referral_walks_count = 0;
3518 #endif
3519 
3520         rc = bdi_setup_and_register(&cifs_sb->bdi, "cifs", BDI_CAP_MAP_COPY);
3521         if (rc)
3522                 return rc;
3523 
3524 #ifdef CONFIG_CIFS_DFS_UPCALL
3525 try_mount_again:
3526         /* cleanup activities if we're chasing a referral */
3527         if (referral_walks_count) {
3528                 if (tcon)
3529                         cifs_put_tcon(tcon);
3530                 else if (ses)
3531                         cifs_put_smb_ses(ses);
3532 
3533                 free_xid(xid);
3534         }
3535 #endif
3536         rc = 0;
3537         tcon = NULL;
3538         ses = NULL;
3539         server = NULL;
3540         full_path = NULL;
3541         tlink = NULL;
3542 
3543         xid = get_xid();
3544 
3545         /* get a reference to a tcp session */
3546         server = cifs_get_tcp_session(volume_info);
3547         if (IS_ERR(server)) {
3548                 rc = PTR_ERR(server);
3549                 bdi_destroy(&cifs_sb->bdi);
3550                 goto out;
3551         }
3552 
3553         /* get a reference to a SMB session */
3554         ses = cifs_get_smb_ses(server, volume_info);
3555         if (IS_ERR(ses)) {
3556                 rc = PTR_ERR(ses);
3557                 ses = NULL;
3558                 goto mount_fail_check;
3559         }
3560 
3561         /* search for existing tcon to this server share */
3562         tcon = cifs_get_tcon(ses, volume_info);
3563         if (IS_ERR(tcon)) {
3564                 rc = PTR_ERR(tcon);
3565                 tcon = NULL;
3566                 goto remote_path_check;
3567         }
3568 
3569         /* tell server which Unix caps we support */
3570         if (cap_unix(tcon->ses)) {
3571                 /* reset of caps checks mount to see if unix extensions
3572                    disabled for just this mount */
3573                 reset_cifs_unix_caps(xid, tcon, cifs_sb, volume_info);
3574                 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3575                     (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3576                      CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3577                         rc = -EACCES;
3578                         goto mount_fail_check;
3579                 }
3580         } else
3581                 tcon->unix_ext = 0; /* server does not support them */
3582 
3583         /* do not care if a following call succeed - informational */
3584         if (!tcon->ipc && server->ops->qfs_tcon)
3585                 server->ops->qfs_tcon(xid, tcon);
3586 
3587         cifs_sb->wsize = server->ops->negotiate_wsize(tcon, volume_info);
3588         cifs_sb->rsize = server->ops->negotiate_rsize(tcon, volume_info);
3589 
3590         /* tune readahead according to rsize */
3591         cifs_sb->bdi.ra_pages = cifs_sb->rsize / PAGE_CACHE_SIZE;
3592 
3593 remote_path_check:
3594 #ifdef CONFIG_CIFS_DFS_UPCALL
3595         /*
3596          * Perform an unconditional check for whether there are DFS
3597          * referrals for this path without prefix, to provide support
3598          * for DFS referrals from w2k8 servers which don't seem to respond
3599          * with PATH_NOT_COVERED to requests that include the prefix.
3600          * Chase the referral if found, otherwise continue normally.
3601          */
3602         if (referral_walks_count == 0) {
3603                 int refrc = expand_dfs_referral(xid, ses, volume_info, cifs_sb,
3604                                                 false);
3605                 if (!refrc) {
3606                         referral_walks_count++;
3607                         goto try_mount_again;
3608                 }
3609         }
3610 #endif
3611 
3612         /* check if a whole path is not remote */
3613         if (!rc && tcon) {
3614                 if (!server->ops->is_path_accessible) {
3615                         rc = -ENOSYS;
3616                         goto mount_fail_check;
3617                 }
3618                 /*
3619                  * cifs_build_path_to_root works only when we have a valid tcon
3620                  */
3621                 full_path = cifs_build_path_to_root(volume_info, cifs_sb, tcon);
3622                 if (full_path == NULL) {
3623                         rc = -ENOMEM;
3624                         goto mount_fail_check;
3625                 }
3626                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3627                                                      full_path);
3628                 if (rc != 0 && rc != -EREMOTE) {
3629                         kfree(full_path);
3630                         goto mount_fail_check;
3631                 }
3632                 if (rc != -EREMOTE) {
3633                         rc = cifs_are_all_path_components_accessible(server,
3634                                                                      xid, tcon, cifs_sb,
3635                                                                      full_path);
3636                         if (rc != 0) {
3637                                 cifs_dbg(VFS, "cannot query dirs between root and final path, "
3638                                          "enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3639                                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3640                                 rc = 0;
3641                         }
3642                 }
3643                 kfree(full_path);
3644         }
3645 
3646         /* get referral if needed */
3647         if (rc == -EREMOTE) {
3648 #ifdef CONFIG_CIFS_DFS_UPCALL
3649                 if (referral_walks_count > MAX_NESTED_LINKS) {
3650                         /*
3651                          * BB: when we implement proper loop detection,
3652                          *     we will remove this check. But now we need it
3653                          *     to prevent an indefinite loop if 'DFS tree' is
3654                          *     misconfigured (i.e. has loops).
3655                          */
3656                         rc = -ELOOP;
3657                         goto mount_fail_check;
3658                 }
3659 
3660                 rc = expand_dfs_referral(xid, ses, volume_info, cifs_sb, true);
3661 
3662                 if (!rc) {
3663                         referral_walks_count++;
3664                         goto try_mount_again;
3665                 }
3666                 goto mount_fail_check;
3667 #else /* No DFS support, return error on mount */
3668                 rc = -EOPNOTSUPP;
3669 #endif
3670         }
3671 
3672         if (rc)
3673                 goto mount_fail_check;
3674 
3675         /* now, hang the tcon off of the superblock */
3676         tlink = kzalloc(sizeof *tlink, GFP_KERNEL);
3677         if (tlink == NULL) {
3678                 rc = -ENOMEM;
3679                 goto mount_fail_check;
3680         }
3681 
3682         tlink->tl_uid = ses->linux_uid;
3683         tlink->tl_tcon = tcon;
3684         tlink->tl_time = jiffies;
3685         set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3686         set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3687 
3688         cifs_sb->master_tlink = tlink;
3689         spin_lock(&cifs_sb->tlink_tree_lock);
3690         tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3691         spin_unlock(&cifs_sb->tlink_tree_lock);
3692 
3693         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3694                                 TLINK_IDLE_EXPIRE);
3695 
3696 mount_fail_check:
3697         /* on error free sesinfo and tcon struct if needed */
3698         if (rc) {
3699                 /* If find_unc succeeded then rc == 0 so we can not end */
3700                 /* up accidentally freeing someone elses tcon struct */
3701                 if (tcon)
3702                         cifs_put_tcon(tcon);
3703                 else if (ses)
3704                         cifs_put_smb_ses(ses);
3705                 else
3706                         cifs_put_tcp_session(server, 0);
3707                 bdi_destroy(&cifs_sb->bdi);
3708         }
3709 
3710 out:
3711         free_xid(xid);
3712         return rc;
3713 }
3714 
3715 /*
3716  * Issue a TREE_CONNECT request. Note that for IPC$ shares, that the tcon
3717  * pointer may be NULL.
3718  */
3719 int
3720 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3721          const char *tree, struct cifs_tcon *tcon,
3722          const struct nls_table *nls_codepage)
3723 {
3724         struct smb_hdr *smb_buffer;
3725         struct smb_hdr *smb_buffer_response;
3726         TCONX_REQ *pSMB;
3727         TCONX_RSP *pSMBr;
3728         unsigned char *bcc_ptr;
3729         int rc = 0;
3730         int length;
3731         __u16 bytes_left, count;
3732 
3733         if (ses == NULL)
3734                 return -EIO;
3735 
3736         smb_buffer = cifs_buf_get();
3737         if (smb_buffer == NULL)
3738                 return -ENOMEM;
3739 
3740         smb_buffer_response = smb_buffer;
3741 
3742         header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3743                         NULL /*no tid */ , 4 /*wct */ );
3744 
3745         smb_buffer->Mid = get_next_mid(ses->server);
3746         smb_buffer->Uid = ses->Suid;
3747         pSMB = (TCONX_REQ *) smb_buffer;
3748         pSMBr = (TCONX_RSP *) smb_buffer_response;
3749 
3750         pSMB->AndXCommand = 0xFF;
3751         pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3752         bcc_ptr = &pSMB->Password[0];
3753         if (!tcon || (ses->server->sec_mode & SECMODE_USER)) {
3754                 pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
3755                 *bcc_ptr = 0; /* password is null byte */
3756                 bcc_ptr++;              /* skip password */
3757                 /* already aligned so no need to do it below */
3758         } else {
3759                 pSMB->PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE);
3760                 /* BB FIXME add code to fail this if NTLMv2 or Kerberos
3761                    specified as required (when that support is added to
3762                    the vfs in the future) as only NTLM or the much
3763                    weaker LANMAN (which we do not send by default) is accepted
3764                    by Samba (not sure whether other servers allow
3765                    NTLMv2 password here) */
3766 #ifdef CONFIG_CIFS_WEAK_PW_HASH
3767                 if ((global_secflags & CIFSSEC_MAY_LANMAN) &&
3768                     (ses->sectype == LANMAN))
3769                         calc_lanman_hash(tcon->password, ses->server->cryptkey,
3770                                          ses->server->sec_mode &
3771                                             SECMODE_PW_ENCRYPT ? true : false,
3772                                          bcc_ptr);
3773                 else
3774 #endif /* CIFS_WEAK_PW_HASH */
3775                 rc = SMBNTencrypt(tcon->password, ses->server->cryptkey,
3776                                         bcc_ptr, nls_codepage);
3777 
3778                 bcc_ptr += CIFS_AUTH_RESP_SIZE;
3779                 if (ses->capabilities & CAP_UNICODE) {
3780                         /* must align unicode strings */
3781                         *bcc_ptr = 0; /* null byte password */
3782                         bcc_ptr++;
3783                 }
3784         }
3785 
3786         if (ses->server->sign)
3787                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3788 
3789         if (ses->capabilities & CAP_STATUS32) {
3790                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3791         }
3792         if (ses->capabilities & CAP_DFS) {
3793                 smb_buffer->Flags2 |= SMBFLG2_DFS;
3794         }
3795         if (ses->capabilities & CAP_UNICODE) {
3796                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3797                 length =
3798                     cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3799                         6 /* max utf8 char length in bytes */ *
3800                         (/* server len*/ + 256 /* share len */), nls_codepage);
3801                 bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
3802                 bcc_ptr += 2;   /* skip trailing null */
3803         } else {                /* ASCII */
3804                 strcpy(bcc_ptr, tree);
3805                 bcc_ptr += strlen(tree) + 1;
3806         }
3807         strcpy(bcc_ptr, "?????");
3808         bcc_ptr += strlen("?????");
3809         bcc_ptr += 1;
3810         count = bcc_ptr - &pSMB->Password[0];
3811         pSMB->hdr.smb_buf_length = cpu_to_be32(be32_to_cpu(
3812                                         pSMB->hdr.smb_buf_length) + count);
3813         pSMB->ByteCount = cpu_to_le16(count);
3814 
3815         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3816                          0);
3817 
3818         /* above now done in SendReceive */
3819         if ((rc == 0) && (tcon != NULL)) {
3820                 bool is_unicode;
3821 
3822                 tcon->tidStatus = CifsGood;
3823                 tcon->need_reconnect = false;
3824                 tcon->tid = smb_buffer_response->Tid;
3825                 bcc_ptr = pByteArea(smb_buffer_response);
3826                 bytes_left = get_bcc(smb_buffer_response);
3827                 length = strnlen(bcc_ptr, bytes_left - 2);
3828                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3829                         is_unicode = true;
3830                 else
3831                         is_unicode = false;
3832 
3833 
3834                 /* skip service field (NB: this field is always ASCII) */
3835                 if (length == 3) {
3836                         if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3837                             (bcc_ptr[2] == 'C')) {
3838                                 cifs_dbg(FYI, "IPC connection\n");
3839                                 tcon->ipc = 1;
3840                         }
3841                 } else if (length == 2) {
3842                         if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3843                                 /* the most common case */
3844                                 cifs_dbg(FYI, "disk share connection\n");
3845                         }
3846                 }
3847                 bcc_ptr += length + 1;
3848                 bytes_left -= (length + 1);
3849                 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
3850 
3851                 /* mostly informational -- no need to fail on error here */
3852                 kfree(tcon->nativeFileSystem);
3853                 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3854                                                       bytes_left, is_unicode,
3855                                                       nls_codepage);
3856 
3857                 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3858 
3859                 if ((smb_buffer_response->WordCount == 3) ||
3860                          (smb_buffer_response->WordCount == 7))
3861                         /* field is in same location */
3862                         tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3863                 else
3864                         tcon->Flags = 0;
3865                 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3866         } else if ((rc == 0) && tcon == NULL) {
3867                 /* all we need to save for IPC$ connection */
3868                 ses->ipc_tid = smb_buffer_response->Tid;
3869         }
3870 
3871         cifs_buf_release(smb_buffer);
3872         return rc;
3873 }
3874 
3875 void
3876 cifs_umount(struct cifs_sb_info *cifs_sb)
3877 {
3878         struct rb_root *root = &cifs_sb->tlink_tree;
3879         struct rb_node *node;
3880         struct tcon_link *tlink;
3881 
3882         cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3883 
3884         spin_lock(&cifs_sb->tlink_tree_lock);
3885         while ((node = rb_first(root))) {
3886                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3887                 cifs_get_tlink(tlink);
3888                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3889                 rb_erase(node, root);
3890 
3891                 spin_unlock(&cifs_sb->tlink_tree_lock);
3892                 cifs_put_tlink(tlink);
3893                 spin_lock(&cifs_sb->tlink_tree_lock);
3894         }
3895         spin_unlock(&cifs_sb->tlink_tree_lock);
3896 
3897         bdi_destroy(&cifs_sb->bdi);
3898         kfree(cifs_sb->mountdata);
3899         kfree(cifs_sb->prepath);
3900         unload_nls(cifs_sb->local_nls);
3901         kfree(cifs_sb);
3902 }
3903 
3904 int
3905 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
3906 {
3907         int rc = 0;
3908         struct TCP_Server_Info *server = ses->server;
3909 
3910         if (!server->ops->need_neg || !server->ops->negotiate)
3911                 return -ENOSYS;
3912 
3913         /* only send once per connect */
3914         if (!server->ops->need_neg(server))
3915                 return 0;
3916 
3917         set_credits(server, 1);
3918 
3919         rc = server->ops->negotiate(xid, ses);
3920         if (rc == 0) {
3921                 spin_lock(&GlobalMid_Lock);
3922                 if (server->tcpStatus == CifsNeedNegotiate)
3923                         server->tcpStatus = CifsGood;
3924                 else
3925                         rc = -EHOSTDOWN;
3926                 spin_unlock(&GlobalMid_Lock);
3927         }
3928 
3929         return rc;
3930 }
3931 
3932 int
3933 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
3934                    struct nls_table *nls_info)
3935 {
3936         int rc = -ENOSYS;
3937         struct TCP_Server_Info *server = ses->server;
3938 
3939         ses->capabilities = server->capabilities;
3940         if (linuxExtEnabled == 0)
3941                 ses->capabilities &= (~server->vals->cap_unix);
3942 
3943         cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
3944                  server->sec_mode, server->capabilities, server->timeAdj);
3945 
3946         if (server->ops->sess_setup)
3947                 rc = server->ops->sess_setup(xid, ses, nls_info);
3948 
3949         if (rc)
3950                 cifs_dbg(VFS, "Send error in SessSetup = %d\n", rc);
3951 
3952         return rc;
3953 }
3954 
3955 static int
3956 cifs_set_vol_auth(struct smb_vol *vol, struct cifs_ses *ses)
3957 {
3958         vol->sectype = ses->sectype;
3959 
3960         /* krb5 is special, since we don't need username or pw */
3961         if (vol->sectype == Kerberos)
3962                 return 0;
3963 
3964         return cifs_set_cifscreds(vol, ses);
3965 }
3966 
3967 static struct cifs_tcon *
3968 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
3969 {
3970         int rc;
3971         struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
3972         struct cifs_ses *ses;
3973         struct cifs_tcon *tcon = NULL;
3974         struct smb_vol *vol_info;
3975 
3976         vol_info = kzalloc(sizeof(*vol_info), GFP_KERNEL);
3977         if (vol_info == NULL)
3978                 return ERR_PTR(-ENOMEM);
3979 
3980         vol_info->local_nls = cifs_sb->local_nls;
3981         vol_info->linux_uid = fsuid;
3982         vol_info->cred_uid = fsuid;
3983         vol_info->UNC = master_tcon->treeName;
3984         vol_info->retry = master_tcon->retry;
3985         vol_info->nocase = master_tcon->nocase;
3986         vol_info->local_lease = master_tcon->local_lease;
3987         vol_info->no_linux_ext = !master_tcon->unix_ext;
3988         vol_info->sectype = master_tcon->ses->sectype;
3989         vol_info->sign = master_tcon->ses->sign;
3990 
3991         rc = cifs_set_vol_auth(vol_info, master_tcon->ses);
3992         if (rc) {
3993                 tcon = ERR_PTR(rc);
3994                 goto out;
3995         }
3996 
3997         /* get a reference for the same TCP session */
3998         spin_lock(&cifs_tcp_ses_lock);
3999         ++master_tcon->ses->server->srv_count;
4000         spin_unlock(&cifs_tcp_ses_lock);
4001 
4002         ses = cifs_get_smb_ses(master_tcon->ses->server, vol_info);
4003         if (IS_ERR(ses)) {
4004                 tcon = (struct cifs_tcon *)ses;
4005                 cifs_put_tcp_session(master_tcon->ses->server, 0);
4006                 goto out;
4007         }
4008 
4009         tcon = cifs_get_tcon(ses, vol_info);
4010         if (IS_ERR(tcon)) {
4011                 cifs_put_smb_ses(ses);
4012                 goto out;
4013         }
4014 
4015         if (cap_unix(ses))
4016                 reset_cifs_unix_caps(0, tcon, NULL, vol_info);
4017 out:
4018         kfree(vol_info->username);
4019         kfree(vol_info->password);
4020         kfree(vol_info);
4021 
4022         return tcon;
4023 }
4024 
4025 struct cifs_tcon *
4026 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4027 {
4028         return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4029 }
4030 
4031 static int
4032 cifs_sb_tcon_pending_wait(void *unused)
4033 {
4034         schedule();
4035         return signal_pending(current) ? -ERESTARTSYS : 0;
4036 }
4037 
4038 /* find and return a tlink with given uid */
4039 static struct tcon_link *
4040 tlink_rb_search(struct rb_root *root, kuid_t uid)
4041 {
4042         struct rb_node *node = root->rb_node;
4043         struct tcon_link *tlink;
4044 
4045         while (node) {
4046                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4047 
4048                 if (uid_gt(tlink->tl_uid, uid))
4049                         node = node->rb_left;
4050                 else if (uid_lt(tlink->tl_uid, uid))
4051                         node = node->rb_right;
4052                 else
4053                         return tlink;
4054         }
4055         return NULL;
4056 }
4057 
4058 /* insert a tcon_link into the tree */
4059 static void
4060 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4061 {
4062         struct rb_node **new = &(root->rb_node), *parent = NULL;
4063         struct tcon_link *tlink;
4064 
4065         while (*new) {
4066                 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4067                 parent = *new;
4068 
4069                 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4070                         new = &((*new)->rb_left);
4071                 else
4072                         new = &((*new)->rb_right);
4073         }
4074 
4075         rb_link_node(&new_tlink->tl_rbnode, parent, new);
4076         rb_insert_color(&new_tlink->tl_rbnode, root);
4077 }
4078 
4079 /*
4080  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4081  * current task.
4082  *
4083  * If the superblock doesn't refer to a multiuser mount, then just return
4084  * the master tcon for the mount.
4085  *
4086  * First, search the rbtree for an existing tcon for this fsuid. If one
4087  * exists, then check to see if it's pending construction. If it is then wait
4088  * for construction to complete. Once it's no longer pending, check to see if
4089  * it failed and either return an error or retry construction, depending on
4090  * the timeout.
4091  *
4092  * If one doesn't exist then insert a new tcon_link struct into the tree and
4093  * try to construct a new one.
4094  */
4095 struct tcon_link *
4096 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4097 {
4098         int ret;
4099         kuid_t fsuid = current_fsuid();
4100         struct tcon_link *tlink, *newtlink;
4101 
4102         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4103                 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4104 
4105         spin_lock(&cifs_sb->tlink_tree_lock);
4106         tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4107         if (tlink)
4108                 cifs_get_tlink(tlink);
4109         spin_unlock(&cifs_sb->tlink_tree_lock);
4110 
4111         if (tlink == NULL) {
4112                 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4113                 if (newtlink == NULL)
4114                         return ERR_PTR(-ENOMEM);
4115                 newtlink->tl_uid = fsuid;
4116                 newtlink->tl_tcon = ERR_PTR(-EACCES);
4117                 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4118                 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4119                 cifs_get_tlink(newtlink);
4120 
4121                 spin_lock(&cifs_sb->tlink_tree_lock);
4122                 /* was one inserted after previous search? */
4123                 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4124                 if (tlink) {
4125                         cifs_get_tlink(tlink);
4126                         spin_unlock(&cifs_sb->tlink_tree_lock);
4127                         kfree(newtlink);
4128                         goto wait_for_construction;
4129                 }
4130                 tlink = newtlink;
4131                 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4132                 spin_unlock(&cifs_sb->tlink_tree_lock);
4133         } else {
4134 wait_for_construction:
4135                 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4136                                   cifs_sb_tcon_pending_wait,
4137                                   TASK_INTERRUPTIBLE);
4138                 if (ret) {
4139                         cifs_put_tlink(tlink);
4140                         return ERR_PTR(ret);
4141                 }
4142 
4143                 /* if it's good, return it */
4144                 if (!IS_ERR(tlink->tl_tcon))
4145                         return tlink;
4146 
4147                 /* return error if we tried this already recently */
4148                 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4149                         cifs_put_tlink(tlink);
4150                         return ERR_PTR(-EACCES);
4151                 }
4152 
4153                 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4154                         goto wait_for_construction;
4155         }
4156 
4157         tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4158         clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4159         wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4160 
4161         if (IS_ERR(tlink->tl_tcon)) {
4162                 cifs_put_tlink(tlink);
4163                 return ERR_PTR(-EACCES);
4164         }
4165 
4166         return tlink;
4167 }
4168 
4169 /*
4170  * periodic workqueue job that scans tcon_tree for a superblock and closes
4171  * out tcons.
4172  */
4173 static void
4174 cifs_prune_tlinks(struct work_struct *work)
4175 {
4176         struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4177                                                     prune_tlinks.work);
4178         struct rb_root *root = &cifs_sb->tlink_tree;
4179         struct rb_node *node = rb_first(root);
4180         struct rb_node *tmp;
4181         struct tcon_link *tlink;
4182 
4183         /*
4184          * Because we drop the spinlock in the loop in order to put the tlink
4185          * it's not guarded against removal of links from the tree. The only
4186          * places that remove entries from the tree are this function and
4187          * umounts. Because this function is non-reentrant and is canceled
4188          * before umount can proceed, this is safe.
4189          */
4190         spin_lock(&cifs_sb->tlink_tree_lock);
4191         node = rb_first(root);
4192         while (node != NULL) {
4193                 tmp = node;
4194                 node = rb_next(tmp);
4195                 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4196 
4197                 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4198                     atomic_read(&tlink->tl_count) != 0 ||
4199                     time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4200                         continue;
4201 
4202                 cifs_get_tlink(tlink);
4203                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4204                 rb_erase(tmp, root);
4205 
4206                 spin_unlock(&cifs_sb->tlink_tree_lock);
4207                 cifs_put_tlink(tlink);
4208                 spin_lock(&cifs_sb->tlink_tree_lock);
4209         }
4210         spin_unlock(&cifs_sb->tlink_tree_lock);
4211 
4212         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4213                                 TLINK_IDLE_EXPIRE);
4214 }
4215 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp