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