SMB 83.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright 1998 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
*
*  SMB.C  -- SMB Server routines
*
*  14-02-94 INH  Original
*                No WriteRaw
*  17-08-94      No 'drv' numbers passed
*  12-09-94      New NetBIOS interface
Ben Avison's avatar
Ben Avison committed
23
*  22-09-95      Tracks Uids & session keys. Uses "DOS LM1.2X002"
24 25
*                  protocol to keep Lan Manager happy.
*  26-03-97      SMB_GetAttribs call replaced for NT 4.0 bug workround
Ben Avison's avatar
Ben Avison committed
26
*  21-04-97      SMB_SetAttribs sets time/date using Open/Close on Windows95
Stewart Brodie's avatar
Stewart Brodie committed
27 28 29 30 31 32 33 34 35
*
*  04-12-98      sbrodie: started adding long filename support - controlled
*                  by LONGNAMES macro.
*  08-12-98      sbrodie: Added SMB_Transact2 with full support for setup
*                  words and the like (present only for LONGNAMES build)
*                  Several new functions added to support long filename
*                  compatible versions of some calls,  These functions have
*                  the same name as the function they upgrade with an X2 suffix
*                  added.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
*/

/* A word about 'drive letters':

   Each connection from us to a shared directory or printer on a server
   is given a drive letter (starting at 'A' and working up). This is
   essentially a handle to a (server_name, share_name) pair, but it
   is made a character to allow it to be passed as the first character
   in filename strings to the SMB_xxx functions.

   LanManFS itself will allow disk-type network connections to be
   given 'mount names' so RISCOS file names take the form
     LanMan::MountName.$.<filespec>

   We never see these mount names; they are handled in c.Omni. When
   a RISCOS filename is passed to Xlt_ConvertPath, it uses
   Omni_GetDrvLetter() to convert the mount name to an SMB drive letter.

   We could allow SMB to deal directly in mount names, but (i) we'd
   have to create nonconflicting names for all the anonymous mounts
   like printers and RPC connections, (ii) the Omni module has to
   deal with mount names anyway, & has a perfectly good set of list-
   management routines there already; we'd only have to duplicate
   them & write an interface (iii) legal characters & case
   sensitivity for mount names may be different to DOS filenames,
   making a composite name a pain in the bum to validate.

   SMB treats drives, printers and the IPC$ share used for remote
   procedure call as alike; a different set of operations
   is allowed on each one, but they are all connected with
   SMB_CreateShare() & SMB_DeleteShare(), and they all have a
   'drive letter'. Hence you will find references to
   drive letters in the printer and RPC code - panic not, they
   are just connection identifiers.
*/


/* Standard includes */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
Stewart Brodie's avatar
Stewart Brodie committed
79
#include <time.h>
80
#include "kernel.h"
Ben Avison's avatar
Ben Avison committed
81
#include "swis.h"
82 83 84 85 86 87 88

/* Our includes */

#include "stdtypes.h"
#include "buflib.h"
#include "netbios.h"
#include "smb.h"
Stewart Brodie's avatar
Stewart Brodie committed
89 90 91 92
#ifdef LONGNAMES
#include "Transact.h" /* for transaction structure building helpers */
#include "NameCache.h" /* for the directory entry cache */
#endif
93 94 95 96 97 98 99 100 101
#include "lmvars.h"
#include "attr.h"   /* For InvalidateDrive */
#include "xlate.h"  /* For string functions */


/* Definitions ===================================================== */

/* Timeouts * */

Ben Avison's avatar
Ben Avison committed
102
/* Reply timeout, in cs */
103

Stewart Brodie's avatar
Stewart Brodie committed
104 105 106
#ifdef LONGNAMES
#define REPLY_TIMEOUT 4000
#else
107
#define REPLY_TIMEOUT 1200
Stewart Brodie's avatar
Stewart Brodie committed
108
#endif
109 110 111 112

/* Timeout to put in 'Transact' params, in ms */

#define TRANSACT_TIMEOUT 5000
Stewart Brodie's avatar
Stewart Brodie committed
113 114 115
#ifdef LONGNAMES
#define TRANSACT2_TIMEOUT 10000
#endif
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

/* Our definitions */

#define MAX_SERVERS  (MAX_DRIVES + 4)
#define MAX_SHARES   (MAX_DRIVES + 4)

/* Tuning parameters */

#define FILE_BLOCK_SIZE 1024
#define RDRAW_BLOCK_SIZE 32768
#define WRRAW_BLOCK_SIZE 16384
#define PRN_BLOCK_SIZE  1024

/* This structure relies on Norcroft C packing the bytes & words
   properly!
 */
typedef struct
{
  BYTE id[4];
  BYTE command;
  BYTE errclass;
  BYTE reh;
  BYTE errlo;
  BYTE errhi;
  BYTE flg;
  WORD flg2;
  WORD rsvd[6];

  WORD tid;
  WORD pid;
  WORD uid;
  WORD mid;
  BYTE wct;  /* Word count */

} SMBHDR;

/* Size of above structure - sizeof() may round to word boundary! */
#define SMBHDR_SIZE 33

/* Maximum number of word params - 14 is used by Transact */
Stewart Brodie's avatar
Stewart Brodie committed
156 157 158 159 160 161
#ifdef LONGNAMES
/* Transact2 (LONGNAMES build only) requires 14 plus setup words
 * The NT LM 0.12 negprot response requires 17.
 */
#define MAX_WCT (17+(MAX_SETUPWORDS)+1)
#else
162
#define MAX_WCT 14
Stewart Brodie's avatar
Stewart Brodie committed
163
#endif
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

/* Max number of significant characters in a shared drive
   or printer name */
#define SHARENAME_LEN 16

#define DATA_BLOCK      1
#define DATA_DIALECT    2
#define DATA_PATHNAME   3
#define DATA_ASCII      4
#define DATA_VARBLK     5

#define ECLASS_DOS      1
#define ECLASS_SRV      2
#define ECLASS_HARD     3


#define SMBmkdir      0x00   /* create directory */
#define SMBrmdir      0x01   /* delete directory */
#define SMBopen       0x02   /* open file */
#define SMBcreate     0x03   /* create file */
#define SMBclose      0x04   /* close file */
#define SMBflush      0x05   /* flush file */
#define SMBunlink     0x06   /* delete file */
#define SMBmv         0x07   /* rename file */
#define SMBgetatr     0x08   /* get file attributes */
#define SMBsetatr     0x09   /* set file attributes */
#define SMBread       0x0A   /* read from file */
#define SMBwrite      0x0B   /* write to file */
#define SMBlock       0x0C   /* lock byte range */
#define SMBunlock     0x0D   /* unlock byte range */
#define SMBctemp      0x0E   /* create temporary file */
#define SMBmknew      0x0F   /* make new file */
#define SMBchkpth     0x10   /* check directory path */
#define SMBexit       0x11   /* process exit */
#define SMBlseek      0x12   /* seek */
#define SMBreadBraw   0x1A   /* Read block raw */
#define SMBwriteBraw  0x1D   /* Write block raw */
#define SMBtransact   0x25   /* RPC transaction */
#define SMBtcon       0x70   /* tree connect */
#define SMBtdis       0x71   /* tree disconnect */
#define SMBnegprot    0x72   /* negotiate protocol */
#define SMBsesssetup  0x73   /* Session setup and X */
#define SMBdskattr    0x80   /* get disk attributes */
#define SMBsearch     0x81   /* search directory */
#define SMBsplopen    0xC0   /* open print spool file */
#define SMBsplwr      0xC1   /* write to print spool file */
#define SMBsplclose   0xC2   /* close print spool file */
#define SMBsplretq    0xC3   /* return print queue */
#define SMBsends      0xD0   /* send single block message */
#define SMBsendb      0xD1   /* send broadcast message */
#define SMBfwdname    0xD2   /* forward user name */
#define SMBcancelf    0xD3   /* cancel forward */
#define SMBgetmac     0xD4   /* get machine name */
#define SMBsendstrt   0xD5   /* send start of multi-block message */
#define SMBsendend    0xD6   /* send end of multi-block message */
#define SMBsendtxt    0xD7   /* send text of multi-block message */

Stewart Brodie's avatar
Stewart Brodie committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
#ifdef LONGNAMES
/* The following are only available with LANMAN 2.0 Extended File Sharing
 * Protocol as defined in "SMB F. S. P. Extensions Version 3.0", document
 * version 1.11, June 19, 1990.
 */
#define SMBtrans2     0x32   /* transaction2 */
#define SMBtranss2    0x33   /* transaction2 (secondary request/response) */
#define SMBfindclose2 0x34   /* terminates a TRANSACT2_FIND_FIRST/NEXT */
#define SMBecho       0x2B

/* And now the sub-commands for SMBtrans2 */
#define TRANSACT2_FINDFIRST   0x01
#define TRANSACT2_FINDNEXT    0x02
#define TRANSACT2_QUERYFSINFORMATION 0x03
#define TRANSACT2_QUERYPATHINFORMATION 0x05
#endif

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
#define SUCCESS   0
#define ERRDOS 0x01
#define ERRSRV 0x02
#define ERRHRD 0x03
#define ERRCMD 0xFF


#define SEARCH_TOT_SIZE 43
#define SEARCH_COUNT 10

#define PROT_USERLOGON   1
#define PROT_ENCRYPT     2
#define PROT_READRAW     4
#define PROT_WRITERAW    8
#define PROT_RWMULTI     16
#define PROT_SETDATETIME 32
Stewart Brodie's avatar
Stewart Brodie committed
254
#define PROT_HAVE_GUID   64
255 256 257

#define SMB_CASELESS   8

Stewart Brodie's avatar
Stewart Brodie committed
258 259 260 261 262 263 264 265 266 267 268 269
#ifdef LONGNAMES
#define SMB_KNOWS_LONG_NAMES	(1)
#define SMB_IS_LONG_NAME	(0x40)
#define SMB_UNICODE		(0x8000)

#define T2FLAGS_LONGNAMES	(1)
#define T2FLAGS_SWAPDATETIME	(2)
#define T2FLAGS_TESTEDSWAP	(4)

#define CAP_EXTENDED_SECURITY	(0x80000000)
#endif

270 271 272 273 274 275 276 277 278 279 280 281
/* Private structures */

#define FREE         0   /* 'flags' values: */
#define ALLOCATED    1   /* True whenever this slot is allocated */
#define CONNECTED    2   /* True if share is connected, to the best of
                             our knowledge */

/* Password fields are strewn around here as mild hacker discouragement */

struct ActiveServer
{
  int      flags;
Stewart Brodie's avatar
Stewart Brodie committed
282
  time_t   last_xact;
283 284 285 286 287 288 289 290

  hSESSION hSession;    /* Only valid if status is IN_USE */
  char     password[NAME_LIMIT];

  int      Uid;        /* User identifier */
  int      Sesskey;    /* Session key */
  int      ProtFlags;  /* USERLOGON/ENCRYPT etc */
  int      SMB_flg;    /* Flags to pass in SMB_flg field */
Stewart Brodie's avatar
Stewart Brodie committed
291 292
#ifdef LONGNAMES
  int      SMB_flg2;   /* Flags to pass in SMB_flg2 field */
293
  int      t2flags;
Stewart Brodie's avatar
Stewart Brodie committed
294 295 296 297 298
#endif
  int      prot;       /* which protocol was nogitated */
  char     guid[16];   /* GUID returned from NT negprot commands */
  int      bloblen;
  BYTE     *blob;
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  char     servname[NAME_LIMIT]; /* upper case */
  char     username[NAME_LIMIT]; /* case preserved */
};

typedef struct ActiveServer *hSERVER;

struct ActiveShare
{
  int     flags;

  char    password[NAME_LIMIT];
  hSERVER hServer;  /* Only valid if status is IN_USE */
  int     sharetype;

  int     Tid;          /* Tree ID */
Stewart Brodie's avatar
Stewart Brodie committed
314
  int     Uid;          /* User ID */
315 316 317 318 319 320 321 322 323 324
  int     Datasize;
  int     FH_base;    /* Base number for file handles */
  char    drvletter;  /* Letter for identifying 'drive' */
  char    sharename[SHARENAME_LEN];  /* upper case */
};


#define GetFid(FH) ((FH) & 0xFFFF)
#define MakeFH(pS,FID) ((pS)->FH_base | (FID & 0xFFFF) )

Stewart Brodie's avatar
Stewart Brodie committed
325 326 327
#ifdef LONGNAMES
static err_t SMB_Transact2 ( hSHARE hS, struct TransactParms *pT );
#endif
328 329 330 331 332 333 334 335 336 337 338 339 340 341

/* SMB globals ======================================================== */

static SMBHDR SMB_TxHdr;
static WORD   SMB_TxWords [MAX_WCT+1];

static SMBHDR SMB_RxHdr;
static WORD   SMB_RxWords [MAX_WCT];
static WORD   SMB_RxByteCount;
static int    SMB_RxWordCount;

static struct ActiveServer SMB_Servers[MAX_SERVERS];
static struct ActiveShare  SMB_Shares[MAX_SHARES];

Ben Avison's avatar
Ben Avison committed
342
BYTE          SMB_WorkBuf[SMBWORKBUF_SIZE];
343 344 345 346 347 348 349 350

/* SMB routines ======================================================== */

static int DOS_Errs[] =
{
  18, ENOMOREFILES,
  2,  EFILENOTFOUND,
  12, ENOTPRESENT,  /* Returned by OS2-Connect from SetAttrib */
Stewart Brodie's avatar
Stewart Brodie committed
351
  50, ENOTPRESENT,  /* Return~ed by W4WG from SetAttrib call */
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  110, EFILENOTFOUND, /* Returned by OS2 servers for hidden files */
  3,  EPATHNOTFOUND,
  1,  EBADPARAM,
  5,  ENOACCESS,
  16, ESHARING,     /* Attempt to remove current dir on server */
  80, EFILEEXISTS,
  32, ESHARING,     /* Normal sharing violation */
  67, ENOSUCHSHARE, /* Returned by NT3.5 for bad share names */
  112, EDISKFULL,   /* Returned by NT3.5 when disk full */
  65, ENOACCESS,    /* Returned by W4WG on set-attribs on CDROM */
  145, EDIRNOTEMPTY, /* Attempt to remove non-empty directory */
  -1, EDOSERROR
};

/* --------------------------- */

static int SMB_Errs[] =
{
  2,  EBADPASSWD,
  4,  ENOACCESS,
  6,  ENOSUCHSHARE,
  5,  ENOACCESS,     /* Returned by W4WG when password changed */
  2239, EACCDISABLED,
  -1, ESERVERROR
};

/* --------------------------- */

static err_t Err_Translate ( int class, int code )
{
  int *p1;

  debug2(" SMB-Err class %d number %d\n", class, code );

  if ( class == 0 )
    return OK;
  else if ( class == ECLASS_DOS )
    p1 = DOS_Errs;
  else if ( class == ECLASS_SRV )
    p1 = SMB_Errs;
  else if ( class == ECLASS_HARD )
    return EHARDERROR;
  else
    return EPROTOCOLERR;

  while ( *p1 >= 0 && *p1 != code )
    p1 += 2;

  debug1(" Unknown err code %d\n", code );
  return p1[1];
}


/* --------------------- */

static BUFCHAIN MkDataBlock ( BUFCHAIN pB, int type,
                                    BYTE *ptr, int len, bool indirect )
{
  BYTE   hdrblk[4];

  if ( len > 0 )
  {
    if ( indirect )
      pB = AddChainIndirect ( pB, ptr, len );
    else
      pB = AddChain ( pB, ptr, len );

    if ( pB == NULL ) return NULL;
  }

  hdrblk[0] = type;
  hdrblk[1] = len & 0xFF;
  hdrblk[2] = len >> 8;

  return AddChain ( pB, hdrblk, 3 );
}

/* --------------------- */

Stewart Brodie's avatar
Stewart Brodie committed
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
/* This routine takes an ASCII string and encodes it into Unicode by
 * inserting extra zero bytes between each character and at the end
 * It adds the resulting string to the given BUFCHAIN.  It optimises
 * for strings up to AUSTC_SKIP chars long.
 */
#if 0
static BUFCHAIN AddUnicodeStringToChain ( BUFCHAIN pB, char *str )
{
#define AUSTC_SKIP 18
        int len = strlen(str)+1, skiplen, cp;
        char ucbuf[AUSTC_SKIP*2];

	skiplen = len % AUSTC_SKIP;
	len -= skiplen;

        do {
                for (cp = skiplen - 1; cp>=0; --cp) {
                        ucbuf[cp*2] = str[len + cp];
                        ucbuf[cp*2+1] = '\0';
                }
                pB = AddChain(pB, ucbuf, skiplen * 2);
                skiplen = AUSTC_SKIP;
                len -= skiplen;
        } while (pB && len >= 0);

        return pB;
}
#endif

/* --------------------- */

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
static BUFCHAIN MkDataString ( BUFCHAIN pB, int type, char *ptr )
{
  BYTE   hdrblk[4];

  pB = AddChain ( pB, ptr, strlen(ptr)+1 );

  if ( pB == NULL ) return NULL;

  hdrblk[0] = type;

  return AddChain ( pB, hdrblk, 1 );
}


/* --------------------------- */

478
#define DumpBuffer(ptr, len) ddumpbuf("smb_1", ptr, len, 0)
Stewart Brodie's avatar
Stewart Brodie committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

#ifdef DEBUG
static BUFCHAIN DumpChain(BUFCHAIN pB)
{
        static char membuf[32768];
        int len = ChainLen(pB);

        GetData ( pB, membuf, len);
        FreeChain(pB);
        pB = AddChain ( NULL, membuf, len);
        if (pB == NULL)
                return NULL;
        DumpBuffer(membuf, len);
        return pB;
}
#else
#define DumpChain(pB) (pB)
#endif

#ifdef DEBUG
typedef struct {
        const char *name;
        int size;
} DumpVarStr;
#define DVS_MK(name,type) {name, sizeof(type)}
#define DVS_END {0,0}

DumpVarStr dvs_NTnegprot[] = {
	DVS_MK("dialect", WORD),
	DVS_MK("securitymode", BYTE),
	DVS_MK("maxmpx", WORD),
	DVS_MK("maxvcs", WORD),
	DVS_MK("maxbuffersize", DWORD),
	DVS_MK("maxrawsize", DWORD),
	DVS_MK("sessionkey", DWORD),
	DVS_MK("capabilities", DWORD),
	DVS_MK("systimelo", DWORD),
	DVS_MK("systimehi", DWORD),
	DVS_MK("servertimezone", WORD),
	DVS_MK("securitybloblen", BYTE),
	DVS_END
};

DumpVarStr dvs_negprot[] = {
	DVS_MK("dialect", WORD),
	DVS_MK("securitymode", WORD),
	DVS_MK("maxbuffersize", DWORD),
	DVS_MK("maxmpx", WORD),
	DVS_MK("maxvcs", WORD),
	DVS_MK("rawmode", WORD),
	DVS_MK("sessionkey", DWORD),
	DVS_MK("systime", WORD),
	DVS_MK("sysdate", WORD),
	DVS_MK("challengelen", WORD),
	DVS_MK("reserved (MBZ)", WORD),
	DVS_END
};

static void *DumpVar(void *ptr, const char *name, unsigned long sz)
{
        static const char *sizestr[] = { "<NULL>", "UCHAR", "USHORT", "????", "ULONG" };
	BYTE *bptr = ptr;
	unsigned long value = 0;
	unsigned long s;

	for (s=0; s<sz; ++s) {
	        value |= ((unsigned long)(*bptr++) << (s<<3UL));
	}
Stewart Brodie's avatar
Stewart Brodie committed
547
	dprintf(("%6s %s: %#lx (%ld)\n", sizestr[sz], name, value, value));
Stewart Brodie's avatar
Stewart Brodie committed
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
	return bptr;

}

static void DumpStruct(void *ptr, const DumpVarStr *dvs)
{
        while (dvs->size) {
                ptr = DumpVar(ptr, dvs->name, dvs->size);
                ++dvs;
        }
}
#else
#define DumpVar(ptr, name, sz) ((void *)(((char *)ptr)+sz))
#define DumpStruct(ptr, str) ((void)0)
#endif

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
/* Does one SMB command (send & reply).

   hS is the connection handle to do it on (MUST BE VALIDATED!)
   cmd is the command byte value
   wct_in is the number of Tx Words to be sent
   pB_in is any Tx Bytes to be sent afterwards, or NULL
   ppB_out is the address of a variable in which to store a pointer
        to any received bytes. If this is NULL, any received bytes
        will be discarded. If it isn't, either a pointer will be
        stored here (which MUST be freed after use), or NULL will
        be stored if there is any error.

   It will leave results in SMB_RxWords, SMB_RxWordCount and
    SMB_RxByteCount.
*/

Stewart Brodie's avatar
Stewart Brodie committed
580 581 582 583 584 585 586
/* sbrodie (15 Jan 1999)
 *
 * This function has been split into two parts so that SMB_Transact2 can share the
 * packet response code (now in Do_SMBResponse) with that used by Do_SMB.  SMB_Transact2
 * can have multiple response packets if the data is very large.
 */
static err_t Do_SMBResponse(hSHARE hS, int cmd, BUFCHAIN *ppB_out )
587
{
Stewart Brodie's avatar
Stewart Brodie committed
588
  int wct_rx;
589 590
  err_t res;
  BUFCHAIN pB_rx;
Stewart Brodie's avatar
Stewart Brodie committed
591

Stewart Brodie's avatar
Stewart Brodie committed
592 593 594 595 596 597
  if (cmd == SMBchkpth) {
    /* This was just the keep-alive message */
    debug0("Not waiting for response to SMBchkpth request\n");
    return OK;
  }

Stewart Brodie's avatar
Stewart Brodie committed
598
  /* Get reply */
Stewart Brodie's avatar
Stewart Brodie committed
599
  res = NB_GetData ( hS->hServer->hSession, &pB_rx, REPLY_TIMEOUT );
Stewart Brodie's avatar
Stewart Brodie committed
600 601 602 603
  if ( res != OK )
    return res;

  /* Extract received data */
604
  dprintf(("smb_2", "Do_SMB (cmd=0x%x) - NB_GetData => %d bytes\n", cmd, ChainLen(pB_rx)));
Stewart Brodie's avatar
Stewart Brodie committed
605 606 607 608 609 610 611 612 613 614 615 616

  SMB_RxHdr.wct = 0;
  SMB_RxByteCount = 0;
  SMB_RxWordCount = 0;

  pB_rx = GetData ( pB_rx, &SMB_RxHdr, SMBHDR_SIZE );
  wct_rx = SMB_RxHdr.wct;

/* sbrodie: moved this from just above "OK - all was well" comment */
  /* Process errors back from server */
  if ( SMB_RxHdr.errclass != 0 )
  {
617
    dprintf(("", "Do_SMB: errclass was %d\n", SMB_RxHdr.errclass));
Stewart Brodie's avatar
Stewart Brodie committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    FreeChain(pB_rx);
    return Err_Translate ( SMB_RxHdr.errclass,
        SMB_RxHdr.errlo + (SMB_RxHdr.errhi << 8) );
  }

  if ( wct_rx > MAX_WCT )  /* Dispose of extra word results */
  {
    pB_rx = GetData ( pB_rx, SMB_RxWords, MAX_WCT*2 );
    pB_rx = GetData ( pB_rx, NULL, (wct_rx-MAX_WCT)*2 );
  }
  else if ( wct_rx > 0 )
  {
    pB_rx = GetData ( pB_rx, SMB_RxWords, wct_rx*2 );
  }

  pB_rx = GetData(pB_rx, &SMB_RxByteCount, 2); /* Get byte count */

  if ( pB_rx == NULL ) /* It's all gone horribly wrong! */
    return EDATALEN;

  /* OK - all was well */
#ifdef DEBUG
  if (cmd == SMBnegprot) debug2("Protocol negotiation returned %d words and %d bytes\n",
          wct_rx, SMB_RxByteCount);
#endif

644 645 646 647 648 649
  if (SMB_RxHdr.command == SMBchkpth) {
    /* Discard the 'ping' response */
    dprintf(("smb_1", "This response was actually to the previous chkpth call\n"));
    ppB_out = NULL;
  }

Stewart Brodie's avatar
Stewart Brodie committed
650 651 652 653 654 655 656 657 658 659 660 661 662
  SMB_RxWordCount = wct_rx;

  if ( ppB_out != NULL )
    *ppB_out = pB_rx;     /* Hand over ownership */
  else
    FreeChain(pB_rx);
  return OK;
}

static err_t Do_SMB_threadsafe ( hSHARE hS, int cmd, int wct_in, BUFCHAIN pB_in,
                      BUFCHAIN *ppB_out )
{
  err_t res;
663 664
  hSESSION hSess;

Stewart Brodie's avatar
Stewart Brodie committed
665 666
  (void) time(&hS->hServer->last_xact);

667 668 669 670 671 672 673 674 675 676
  if ( ppB_out != NULL ) /* If early exit, leave NULL in result */
    *ppB_out = NULL;

  hSess = hS->hServer->hSession;

  /* Fill in parameters for this connection */

  SMB_TxHdr.tid = hS->Tid;
  SMB_TxHdr.uid = hS->hServer->Uid;
  SMB_TxHdr.flg = hS->hServer->SMB_flg;
Stewart Brodie's avatar
Stewart Brodie committed
677 678 679
#ifdef LONGNAMES
  SMB_TxHdr.flg2 = hS->hServer->SMB_flg2;
#endif
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

  /* Add byte count */

  SMB_TxWords[wct_in] = ChainLen(pB_in);

  /* Add parameter words */

  pB_in = AddChain ( pB_in, SMB_TxWords, (wct_in*2) + 2 );
  if ( pB_in == NULL )
    return EOUTOFMEM;

  /* Prepare & add header */

  SMB_TxHdr.command = cmd;
  SMB_TxHdr.wct     = wct_in;

  pB_in = AddChain ( pB_in, &SMB_TxHdr, SMBHDR_SIZE );
  if ( pB_in == NULL )
    return EOUTOFMEM;

Stewart Brodie's avatar
Stewart Brodie committed
700
  /* Send data */
701

Stewart Brodie's avatar
Stewart Brodie committed
702 703 704 705 706 707
  res = NB_ClearRxQueue ( hSess );
  if (res != OK) {
    debug0("****************** NB_ClearRxQueue says there was stuff pending!!!!!!!!\n");
  }

  res = NB_SendData ( hSess, pB_in );
708 709 710
  if ( res != OK )
    return res;

711 712 713 714 715 716
  do {
    /* MUST avoid recursive calls to Do_SMBResponse */
    res = Do_SMBResponse(hS, cmd, ppB_out);
  } while (res == OK && SMB_RxHdr.command == SMBchkpth);

  return res;
Stewart Brodie's avatar
Stewart Brodie committed
717
}
718

Stewart Brodie's avatar
Stewart Brodie committed
719 720 721 722
static err_t Do_SMB ( hSHARE hS, int cmd, int wct_in, BUFCHAIN pB_in,
                      BUFCHAIN *ppB_out )
{
  static volatile int threaded = 0;
723

Stewart Brodie's avatar
Stewart Brodie committed
724
  if (threaded) {
Stewart Brodie's avatar
Stewart Brodie committed
725
    return ELANMANFSINUSE;
726
  }
Stewart Brodie's avatar
Stewart Brodie committed
727
  else {
Ben Avison's avatar
Ben Avison committed
728 729 730 731 732
    err_t res;
    ++threaded;
    res = Do_SMB_threadsafe(hS, cmd, wct_in, pB_in, ppB_out);
    --threaded;
    return res;
733 734 735
  }
}

Stewart Brodie's avatar
Stewart Brodie committed
736

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
/* ---------------------------- */

/* This attempts to do a ReadRaw on a given file. If there are any errors,
   or we're at end of file, it returns 0. Assume 'hS' etc. has been
   validated.
*/


static int SMB_ReadRaw ( hSHARE hS,
                     int fid, int offset, int len, BYTE *where )
{
  err_t res;
  BUFCHAIN pB;
  hSESSION hSess = hS->hServer->hSession;;

  if (len>RDRAW_BLOCK_SIZE) len=RDRAW_BLOCK_SIZE;

  SMB_TxWords[0] = fid;
  SMB_TxWords[1] = (offset & 0xFFFF);
  SMB_TxWords[2] = (offset >> 16 );
  SMB_TxWords[3] = len;
  SMB_TxWords[4] = 0; /* Minimum returned byte count */

  SMB_TxWords[5] = 0xFFFF; /* Timeout */
  SMB_TxWords[6] = 0xFFFF;

  SMB_TxWords[7] = 0; /* Reserved */
  SMB_TxWords[8] = 0; /* Following byte count */

  pB = AddChain( NULL, SMB_TxWords, 18 );
  if ( pB == NULL )
    return 0;

  SMB_TxHdr.tid = hS->Tid;
  SMB_TxHdr.uid = hS->hServer->Uid;

  SMB_TxHdr.command = SMBreadBraw;
  SMB_TxHdr.wct     = 8; /* Word count */

  pB = AddChain ( pB, &SMB_TxHdr, SMBHDR_SIZE );
  if ( pB == NULL )
    return 0;

  /* Send data */

  NB_ClearRxQueue ( hSess ); /* Ensure reply is correct */

  res = NB_SendData ( hSess, pB );
  if ( res != OK )
  {
    debug1("Send data failed, %d\n", res);
    return 0;
  }

  /* Get reply (raw data block) */

  res = NB_GetBlockData ( hSess, where, &len, REPLY_TIMEOUT );
  if ( res != OK )
    return 0;

  return len;
}

/* ---------------------------- */

static err_t SMB_WriteRaw ( hSHARE hS, int fid, int offset,
                    int len, BYTE *where )
{
  err_t res;

  SMB_TxWords[0] = fid;
  SMB_TxWords[1] = len;
  SMB_TxWords[2] = 0;
  SMB_TxWords[3] = (offset & 0xFFFF);
  SMB_TxWords[4] = (offset >> 16 );
  SMB_TxWords[5] = 0xFFFF; /* Timeout */
  SMB_TxWords[6] = 0xFFFF;

  SMB_TxWords[7] = 0; /* Write mode: write-through */
  SMB_TxWords[8] = 0; /* Reserved */
  SMB_TxWords[9] = 0; /* Reserved */
  SMB_TxWords[10] = 0; /* # of data bytes immediately following */
819
  SMB_TxWords[11] = 0; /* Offset to immediate data bytes */
820 821 822 823 824 825 826 827 828 829 830 831 832

  res = Do_SMB ( hS, SMBwriteBraw, 12, NULL, NULL );
  if ( res != OK )
    return res;

  /* If no error, just send the data in a large block. Any errors
     will be picked up on the next write or close operation. If
     we get to this stage, we can assume 'drv' is validated. */

  return NB_SendBlockData ( hS->hServer->hSession, where, len );

}

Stewart Brodie's avatar
Stewart Brodie committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
/* sbrodie: Abstract the dialect strings here - means debug version can
 * call this function to find out which protocol was accepted.  The
 * offsets within the array of each string are vital to SMB_Negotiate.
 */
static char *dialects[] = {
                "PC NETWORK PROGRAM 1.0",
                "DOS LM1.2X002",
                "LM1.2X002",
                "NT LM 0.12"
};
#define MAX_DIALECT ((sizeof(dialects)/sizeof(*dialects))-1)
#define DIALECT_BASIC 0
#define DIALECT_LM12X002 1
#define DIALECT_NT 3
static char *SMB_Dialect(unsigned int num)
{
        if (num <= MAX_DIALECT) return dialects[num];
        return "";
}

853 854 855 856 857
/* ---------------------------- */

static err_t SMB_Negotiate( hSHARE hS )
{
  err_t res;
Stewart Brodie's avatar
Stewart Brodie committed
858
  unsigned int dcount;
859 860
  BUFCHAIN pB;

Stewart Brodie's avatar
Stewart Brodie committed
861
  pB = NULL;
862

Stewart Brodie's avatar
Stewart Brodie committed
863 864 865 866 867
  /* Must be entered in reverse order */
  for (dcount = MAX_DIALECT; ; --dcount) {
    pB = MkDataString( pB, DATA_DIALECT, SMB_Dialect(dcount));
    if (pB == NULL || dcount == 0) break;
  }
868 869 870 871

  if ( pB == NULL )
    return EOUTOFMEM;

Stewart Brodie's avatar
Stewart Brodie committed
872
  res = Do_SMB ( hS, SMBnegprot, 0, pB, &pB );
873 874 875
  if ( res != OK )
    return res;

Stewart Brodie's avatar
Stewart Brodie committed
876 877
  #ifdef DEBUG
  debug1("Data length on negprot is %d\n", ChainLen(pB));
878
  {
Stewart Brodie's avatar
Stewart Brodie committed
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
          static char buf[4096];
          void *ptr = SMB_RxWords;
          int len = ChainLen(pB);
          GetData(pB, buf, len);
          DumpBuffer(buf, len);
          DumpStruct(ptr, (SMB_RxWords[0] >= DIALECT_NT) ? dvs_NTnegprot : dvs_negprot);
  }
  #endif
  FreeChain(pB);

  debug1("Negotiated protocol `%s'\n", SMB_Dialect(SMB_RxWords[0]));
  hS->hServer->prot = SMB_RxWords[0];
  if ( SMB_RxWords[0] >= DIALECT_LM12X002 )
  {
    if (SMB_RxWords[0] >= DIALECT_NT) {
      /* grr - different response format */
      hS->hServer->ProtFlags = PROT_RWMULTI + PROT_SETDATETIME +
         (SMB_RxWords[9] & 0x100 ? PROT_READRAW+PROT_WRITERAW : 0 ) +
         (SMB_RxWords[1] & 1 ? PROT_USERLOGON : 0 ) +
         (SMB_RxWords[1] & 2 ? PROT_ENCRYPT : 0 );
899
      if (SMB_RxWords[11] & 0x80) {
Stewart Brodie's avatar
Stewart Brodie committed
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
        /* CAP_EXTENDED_SECURITY */
        hS->hServer->ProtFlags |= PROT_HAVE_GUID;
        GetData(pB, hS->hServer->guid, 16);
        debug0("Found a GUID block in the data section\n");
      }
      else {
        /* No bit */
        debug0("No extended security - no GUID in the data block\n");
      }
      hS->hServer->bloblen = SMB_RxWords[16] >> 8;
    }
    else {
      hS->hServer->bloblen = SMB_RxWords[11];
      hS->hServer->ProtFlags = PROT_RWMULTI + PROT_SETDATETIME +
         (SMB_RxWords[1] & 1 ? PROT_USERLOGON : 0 ) +
         (SMB_RxWords[1] & 2 ? PROT_ENCRYPT : 0 ) +
         (SMB_RxWords[5] & 1 ? PROT_READRAW : 0 ) +
         (SMB_RxWords[5] & 2 ? PROT_WRITERAW : 0 );
    }
919
    hS->hServer->SMB_flg = SMB_CASELESS;
Stewart Brodie's avatar
Stewart Brodie committed
920 921 922
#ifdef LONGNAMES
    debug0("Enabling long filenames on this share\n");
    hS->hServer->SMB_flg2 = SMB_KNOWS_LONG_NAMES; /* | SMB_IS_LONG_NAME;*/
923
    hS->hServer->t2flags = T2FLAGS_LONGNAMES;
Stewart Brodie's avatar
Stewart Brodie committed
924
#endif
925
    hS->hServer->Sesskey = SMB_RxWords[6] | (SMB_RxWords[7] << 16);
Stewart Brodie's avatar
Stewart Brodie committed
926 927 928 929 930 931 932 933 934 935
    if (hS->hServer->bloblen > 0) {
      free(hS->hServer->blob);
      hS->hServer->blob = malloc(hS->hServer->bloblen);
      if (hS->hServer->blob != NULL) {
        GetData(pB, hS->hServer->blob, hS->hServer->bloblen);
      }
    }
    else {
      hS->hServer->blob = 0;
    }
936 937 938 939 940
  }
  else
  {
    hS->hServer->ProtFlags = PROT_SETDATETIME;
    hS->hServer->SMB_flg = 0;
Stewart Brodie's avatar
Stewart Brodie committed
941
#ifdef LONGNAMES
942
    hS->hServer->t2flags = 0;
Stewart Brodie's avatar
Stewart Brodie committed
943 944
    hS->hServer->SMB_flg2 = 0;
#endif
945
  }
Stewart Brodie's avatar
Stewart Brodie committed
946
  debug1("%s-level security\n", hS->hServer->ProtFlags & PROT_USERLOGON ? "User" : "Share");
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
  return OK;
}

/* ------------------------------- */

/* Session setup logs the user on with a given name and password */

static err_t SMB_SessSetup ( hSHARE hS, char *userid, char *passwd )
{
  BUFCHAIN pB;
  err_t res;

  SMB_TxWords[0] = 0x00FF; /* No additional command */
  SMB_TxWords[1] = 0;      /* Offset to next cmd */
  SMB_TxWords[2] = 4096;   /* Our buffer size */
  SMB_TxWords[3] = 0;      /* Max pending requests */
  SMB_TxWords[4] = 0;      /* First & only VC */
  SMB_TxWords[5] = hS->hServer->Sesskey & 0xFFFF;
  SMB_TxWords[6] = hS->hServer->Sesskey >> 16;

Stewart Brodie's avatar
Stewart Brodie committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
  if (hS->hServer->prot < DIALECT_NT) {
    pB = AddChain ( NULL, userid, strlen(userid)+1 );
    if ( pB != NULL ) pB = AddChain ( pB, passwd, strlen(passwd)+1 );
    if ( pB == NULL )
      return EOUTOFMEM;

    SMB_TxWords[7] = strlen ( passwd ) + 1;
    SMB_TxWords[8] = 0;
    SMB_TxWords[9] = 0;

    res = Do_SMB ( hS, SMBsesssetup, 10, pB, NULL );
  }
  else if (hS->hServer->ProtFlags & PROT_HAVE_GUID) {
    /* CAP_EXTENDED_SECURITY is supported by the server - setup session accordingly */
    SMB_TxWords[7] = hS->hServer->bloblen;
    SMB_TxWords[8] = SMB_TxWords[9] = 0; /* reserved */
    SMB_TxWords[10] = SMB_TxWords[11] = 0; /* client capabilities */
984 985 986
    pB = AddChain (NULL, "CIFS", sizeof("CIFS"));
    if (pB) pB = AddChain ( pB, "RISCOS", sizeof("RISCOS"));
    if (pB) pB = AddChain ( pB, hS->hServer->blob, hS->hServer->bloblen );
Stewart Brodie's avatar
Stewart Brodie committed
987 988 989 990 991 992 993 994 995 996
    if (pB == NULL )
      return EOUTOFMEM;
    res = Do_SMB ( hS, SMBsesssetup, 12, pB, NULL );
  }
  else {
    /* Server does not support extended security */
    SMB_TxWords[7] = strlen ( passwd );
    SMB_TxWords[8] = 0;
    SMB_TxWords[9] = SMB_TxWords[10] = 0; /* Reserved */
    SMB_TxWords[11] = SMB_TxWords[12] = 0; /* client capabilities */
997
    pB = AddChain(NULL, "CIFS", sizeof("CIFS"));
Stewart Brodie's avatar
Stewart Brodie committed
998 999 1000 1001 1002 1003 1004 1005
    if (pB) pB = AddChain(pB, "\0RISCOS", sizeof("\0RISCOS"));
    if (pB) pB = AddChain(pB, userid, strlen(userid) + 1);
    if (pB) pB = AddChain(pB, passwd, strlen(passwd));
    if (pB) pB = DumpChain(pB);
    if (pB == NULL)
      return EOUTOFMEM;
    res = Do_SMB ( hS, SMBsesssetup, 13, pB, NULL );
  }
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  if ( res != OK )
    return res;

  hS->hServer->Uid = SMB_RxHdr.uid;

  return OK;
}

/* ---------------------------- */

/* Keep in step with #defines in H.SMB ! */

static char *sharetype_str[4] =
{
  "A:", "LPT1:", "COMM", "IPC"
};

/* ConnectShare connects to a given share, with share name & type &
   password as given in the hSHARE structure. hS->hServer is
   assumed to be valid & connected
*/

static err_t ConnectShare ( hSHARE hS )
{
  BUFCHAIN pB;
  err_t res;

  /* Mild sanity check */

  if ( hS==NULL || hS->hServer==NULL ||
       hS->sharetype < 0 || hS->sharetype > 3 )
    return EBADPARAM;

  debug3("Connect share %c to \\\\%s\\%s\n", hS->drvletter,
            hS->hServer->servname, hS->sharename );

  pB = MkDataString( NULL, DATA_ASCII, sharetype_str[hS->sharetype] );

  if ( pB == NULL ) return EOUTOFMEM;

  /* For user-based logon schemes, there is not a password for
      tree connect */

  if ( hS->hServer->ProtFlags & PROT_USERLOGON )
    pB = MkDataString ( pB, DATA_ASCII, "" );
  else
  {
    Xlt_Unjumble ( hS->password );
    pB = MkDataString ( pB, DATA_ASCII, hS->password );
    Xlt_Jumble ( hS->password );
  }

  if ( pB == NULL ) return EOUTOFMEM;

  /* Path name is of the form \\SERVER\SHARENAME */

  sprintf( (char*)SMB_WorkBuf, "\\\\%s\\%s", hS->hServer->servname,
                                             hS->sharename );
  pB = MkDataString ( pB, DATA_ASCII, (char *)SMB_WorkBuf );

  if ( pB == NULL ) return EOUTOFMEM;

  /* Do connection */

  res = Do_SMB ( hS, SMBtcon, 0, pB, NULL );

  if ( res == OK )
  {
    hS->Tid      = SMB_RxWords[1];
    hS->Datasize = SMB_RxWords[0];
    hS->flags   |= CONNECTED;     /* Clear CONN_LOST flag */
  }

  return res;
}



/* ----------------------------- */

static err_t DisconnectShare ( hSHARE hS )
{
  if ( hS==NULL )       /* Shouldn't happen, but make sure */
    return EBADPARAM;

  debug3("Disconnect share %c from \\\\%s\\%s\n", hS->drvletter,
            hS->hServer->servname, hS->sharename );

  /* Say connection has been broken; if the operation fails it's
     probably been broken already */

  hS->flags &= ~CONNECTED;

  /* Do SMB Tree disconnect operation */
  return Do_SMB ( hS, SMBtdis, 0, NULL, NULL );
}

/* ------------------------------ */

/* ConnectServer attempts to connect to a given server. It is actually
   passed an hSHARE handle for internal reasons. It it assumed that
   hS->hServer has been set up to point to a valid server, and that
   the server name, user name & password are set up correctly.
*/

static err_t ConnectServer ( hSHARE hS )
{
  NETNAME nnserver;
  hSERVER hSrv;
  err_t res;

  if ( hS == NULL || (hSrv=hS->hServer, hSrv == NULL) )
    return EBADPARAM;

  debug1("Connect server %s\n", hSrv->servname);

  /* Set initial values */

  hSrv->ProtFlags = 0;
  hSrv->SMB_flg = 0;
  hSrv->Uid = 0;
  hSrv->Sesskey = 0;
  hSrv->hSession = NULL;

  /* Try to contact server */

Stewart Brodie's avatar
Stewart Brodie committed
1132
  debug0("NB_FormatName..\n");
1133 1134 1135 1136 1137 1138
  res = NB_FormatName ( ntSERVER, hSrv->servname, &nnserver );
  if ( res != OK )
    return res;

  /* Try to contact server */

Stewart Brodie's avatar
Stewart Brodie committed
1139
  debug0("NB_OpenSession..\n");
1140 1141 1142 1143 1144 1145
  res = NB_OpenSession( NB_MachineName, &nnserver, &(hSrv->hSession) );
  if ( res != OK )
    return res;

  /* Establish protocol */

Stewart Brodie's avatar
Stewart Brodie committed
1146
  debug0("SMB_Negotiate..\n");
1147 1148 1149 1150 1151 1152 1153 1154 1155
  res = SMB_Negotiate ( hS );
  if ( res != OK )
    goto abort_server;

  /* Logon user, if it's that sort of server */

  if (hSrv->ProtFlags & PROT_USERLOGON)
  {
    Xlt_Unjumble(hSrv->password);
Stewart Brodie's avatar
Stewart Brodie committed
1156
  debug0("SMB_SessSetup..\n");
1157 1158 1159 1160 1161 1162
    res = SMB_SessSetup ( hS, hSrv->username, hSrv->password );
    Xlt_Jumble(hSrv->password);

    if ( res != OK ) goto abort_server;
  }

Stewart Brodie's avatar
Stewart Brodie committed
1163 1164
  debug0("ConnectServer succeeds\n");

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
  return OK;

abort_server:
  NB_CloseSession(hSrv->hSession);
  hSrv->hSession = NULL;
  return res;
}

/* ------------------------------ */

static err_t DisconnectServer ( hSERVER hSrv )
{
  int i;
  hSHARE hS;

  if ( hSrv == NULL )
    return EBADPARAM;

  debug1("Disconnect server %s\n", hSrv->servname);

  /* Disconnect Server implicity closes all shares using it;
     fortunately, the server will do all this if we drop the
     link. All we have to do is mark the relevant shares as being
     disconnected.
  */

  hS = SMB_Shares;
  for ( i=0; i < MAX_SHARES; i++ )
  {
    if ( (hS->flags & ALLOCATED) &&
         (hS->hServer == hSrv )     )
      hS->flags &= ~CONNECTED;

    hS++;
  }

  /* Close NetBIOS session */
  if ( hSrv->hSession != NULL )
  {
    NB_CloseSession(hSrv->hSession);
    hSrv->hSession = NULL;
  }
  return OK;
}

/* As a general rule, the routines above don't perform
   any allocation/deallocation functions, only the network
   transactions themselves. These are dealt with in the following
   bits.
*/

/* ==========================================  */

static hSERVER AllocServer ( void )
{
  hSERVER hS;
  int i;

  for ( hS = SMB_Servers, i=0; i < MAX_SERVERS; hS++, i++ )
    if ( (hS->flags & ALLOCATED)==0 )
    {
      hS->flags = ALLOCATED;
      hS->hSession = 0;
Stewart Brodie's avatar
Stewart Brodie committed
1228
      hS->blob = 0;
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
      return hS;
    }

  return NULL;
}

/* ----------------------------------- */

static hSHARE AllocShare ( void )
{
  hSHARE hS;
  int i;

  for ( hS = SMB_Shares, i=0; i < MAX_SHARES; hS++, i++ )
    if ( (hS->flags & ALLOCATED)== 0 )
    {
      hS->flags = ALLOCATED;
      hS->hServer = NULL;
      hS->Tid=0;
      hS->Datasize=0;
Stewart Brodie's avatar
Stewart Brodie committed
1249
#ifdef LONGNAMES
1250
      hS->hServer->t2flags = 0;
Stewart Brodie's avatar
Stewart Brodie committed
1251
#endif
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
      return hS;
    }

  return NULL;
}

/* ----------------------------------- */

static bool ServerInUse ( hSERVER hServ )
{
  int i;
  hSHARE hS;

  for ( hS=SMB_Shares, i=0; i<MAX_SHARES; hS++, i++ )
  {
    if ( hS->hServer == hServ && (hS->flags & ALLOCATED)  )
      return true;
  }

  return false;
}

/* ----------------------------------- */

static hSERVER FindServer ( char *serv_name )
{
  hSERVER hS;
  int i;

  for ( hS = SMB_Servers, i=0; i < MAX_SERVERS; hS++, i++ )
  {
    if ( (hS->flags & ALLOCATED) &&
         stricmp ( hS->servname, serv_name ) == 0
       )
      return hS;
  }

  return NULL;
}

/* ----------------------------------- */

static hSHARE FindShare ( hSERVER hServ, char *share_name )
{
  hSHARE hS;
  int i;

  for ( hS = SMB_Shares, i=0; i < MAX_SHARES; hS++, i++ )
  {
    if ( hS->hServer == hServ && (hS->flags & ALLOCATED) &&
         stricmp ( hS->sharename, share_name ) == 0
       )
      return hS;
  }

  return NULL;
}


/* ----------------------------------- */

static void FreeServer ( hSERVER hS )
{
Stewart Brodie's avatar
Stewart Brodie committed
1315 1316 1317 1318
  if (hS->flags != FREE) {
    free(hS->blob);
    hS->blob = NULL;
  }
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  hS->flags = FREE;
}

/* ----------------------------------- */

static void FreeShare ( hSHARE hS )
{
  hS->flags = FREE;
}

/* =======================================  */

/* Validates a share, given a filename (the first character being the
   drive letter). If the link to the server has failed, it will
   attempt to reconnect it before returning.

   Unlike most routines, it returns an hSHARE as a result and an error
   via a pointer. The hSHARE will be non-Null if & only if the result is
   OK; it is acceptable to test either.
*/

Stewart Brodie's avatar
Stewart Brodie committed
1340
static hSHARE GetShare ( const char *filename, err_t *pRes )
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
{
  uint tmp;
  hSHARE hS;
  err_t res;

  /* Is drive letter in range & in use? */

  tmp = filename[0] - 'A';
  if ( tmp >= MAX_SHARES ||
        (hS=&SMB_Shares[tmp], (hS->flags & ALLOCATED)==0) )
  {
    *pRes = EBADDRV;
    return NULL;
  }

  /* Can we still talk to the server */

  if ( !NB_LinkOK ( hS->hServer->hSession ) )
  {
    DisconnectServer(hS->hServer);      /* Drop links, deallocate stuff */

    res = ConnectServer(hS);   /* Try to reconnect to server */
    if ( res != OK )
    {
      *pRes = res;
      return NULL;
    }
  }

  /* Server works, now see if we need reconnecting */

  if ( (hS->flags & CONNECTED) == 0 )
  {
    res = ConnectShare(hS);
    if ( res != OK )
    {
      *pRes = res;
      return NULL;
    }
  }

  *pRes = OK;
  return hS;
}

Stewart Brodie's avatar
Stewart Brodie committed
1386

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
/* ---------------------------- */

/* GetShareNoConn() is used to validate a drive letter when
    we aren't bothered if the connection is lost (e.g. for
    the GetConnInfo or DisconnectShare calls)
*/
static hSHARE GetShareNoConn ( uint letter )
{
  letter -= 'A';
  if ( (letter < MAX_SHARES) &&
       (SMB_Shares[letter].flags & ALLOCATED) )
    return &SMB_Shares[letter];

  return NULL;
}

Stewart Brodie's avatar
Stewart Brodie committed
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

/* ---------------------------- */

/* SMB_IsLongNameFS() returns true if the path refers to a share which is using long
    filenames.  Xlate.c needs to know this in order to determine which set of file
    mappings is to be used.
 */
bool SMB_IsLongNameFS( const char * path)
{
  hSHARE hS;

  hS = GetShareNoConn(*path);
1415
  if (hS != NULL && (hS->hServer->t2flags & T2FLAGS_LONGNAMES)) return true;
Stewart Brodie's avatar
Stewart Brodie committed
1416 1417 1418 1419
  return false;
}


1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
/* --------------------- */

/* When trying to get a share ID from a file handle, there's
   no point reconnecting, because the handle wouldn't be valid
   anyway.
*/

static hSHARE GetShareFromFH ( uint FH, err_t *pRes )
{
  FH = (FH >> 16);  /* Get share identifier from file handle */
  if ( FH < MAX_SHARES )
  {
    hSHARE hS=&SMB_Shares[FH];

    if ( (hS->flags & (ALLOCATED|CONNECTED))  == (ALLOCATED|CONNECTED) )
      return hS;
  }

  *pRes = EFILEHANDLE;
  return NULL;
}

/* ----------------------------- */

static err_t SMB_SingleOp ( int op, char *path )
{
  BUFCHAIN pB;
  hSHARE hS;
  err_t res;

  hS = GetShare (path, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString( NULL, DATA_ASCII, path+2 );
  if ( pB == NULL )
    return EOUTOFMEM;

  return Do_SMB ( hS, op, 0, pB, NULL );
}

/* Public Connect/disconnect operations ====================== */

/* CreateShare can do about five different things, depending on
    the current state of the system. See SMB.H for full
    description of the parameters. Scenarios include
    - connection to a new share on a new server
    - if we're already connected to the given server and the
        given user name is blank or the same, connect to a new
        share on the same server.
    - if we're already connected to the given server and the
        given user name is different, reconnect to the server;
        the share name may be the same as an existing name (in
        which case we're just changing user ID) or it may be
        a new one (in which case it needs adding)
    - if all of (server name, user name, share name) are the
        same, return the drive letter corresponding to this
        connection.

    This is all a bit of a logical nightmare, especially as we
    have to back out gracefully if any bit fails, so I've written
    it out using flags which get set as each thing needs to be
    done.

*/

static bool IsBlank ( char *str )
{
  while ( isspace(*str) ) str++;  /* Skip leading spaces */

  if ( iscntrl(*str) )            /* If it's the end, it's blank */
    return true;

  return false;
}

#define ALLOC_SERVER   1
#define ALLOC_SHARE    2
#define DISCONN_SERVER 4
#define CONN_SERVER    8

err_t SMB_CreateShare (  int sharetype_in,
                         int style,
                         char *servname_in, char *sharename_in,
                         char *username_in, char *password_in,
                         char *drv_letter_out )
{
  hSHARE hShare;
  hSERVER hServ;
  char uc_sharename[SHARENAME_LEN];
  char uc_servname [NAME_LIMIT];
  char plain_password[NAME_LIMIT];
  int to_do, done;
  err_t res;

  /* Validate & format parameters */
Stewart Brodie's avatar
Stewart Brodie committed
1516 1517 1518 1519
#ifdef TRACE
  debug2("Server name %p; share name %p\n", servname_in, sharename_in);
  debug2("Server name `%s'; share name `%s'\n", servname_in, sharename_in);
#endif
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

  if ( servname_in == NULL || sharename_in==NULL )
    return EBADPARAM;

  strcpyn_upper ( uc_sharename, sharename_in, SHARENAME_LEN);
  strcpyn_upper ( uc_servname,  servname_in, NAME_LIMIT);

  if ( username_in == NULL ) username_in = "";
  if ( password_in == NULL ) password_in = "";

  /* Work out a list of what we have to do ------------ */

  to_do = 0;

  hServ = FindServer ( uc_servname );

  if ( hServ == NULL )  /* New server */
  {
    hShare = NULL;
    to_do |= (ALLOC_SERVER | ALLOC_SHARE | CONN_SERVER);

    /* If both names are blank, use logon names */
    if ( IsBlank(username_in) && IsBlank(password_in) )
    {
      username_in = LM_Vars.username;
      Xlt_Unjumble ( LM_Vars.password_ptr );
      strcpyn ( plain_password, LM_Vars.password_ptr, NAME_LIMIT );
      Xlt_Jumble ( LM_Vars.password_ptr );
      password_in = plain_password;
    }
  }
  else
  {
    /* Already have connection to server */
    hShare = FindShare(hServ, uc_sharename);

    if ( hShare == NULL ) /* New share on existing server */
      to_do |= (ALLOC_SHARE);

    /* Check if user name is being given. If not,
       disconnect and reconnect to force name change */

    if ( (style & CREATE_NEW_USER) && !IsBlank (username_in)  )
      to_do |= (DISCONN_SERVER | CONN_SERVER);
  }

  /* Check that's OK with the given style ----- */

  if ( (style & CREATE_NEW_SHARE) && !(to_do & ALLOC_SHARE) )
  {
    /* If the share already exists, and the 'insist it's something
       new' bit is set,  we fail the call and say  which drive letter
       it is. Otherwise, we drop through the rest of the code - the
       only thing that might happen is a disconnect/reconnect to
       change user ID */
    *drv_letter_out = hShare->drvletter;
    return ECONNEXISTS;
  }

  /* Now do each bit ----------------------- */

  done = 0;

  /* Ensure hServ is allocated */
  if ( to_do & ALLOC_SERVER )
  {
    hServ = AllocServer();
    if ( hServ == NULL )
    {
      res = ECONNLIMIT;
      goto fail;
    }
    strcpy  ( hServ->servname, uc_servname );
    done |= ALLOC_SERVER;
  }

  /* Ensure hShare is allocated & set up */
  if ( to_do & ALLOC_SHARE )
  {
    hShare = AllocShare();
    if ( hShare == NULL )
    {
      res = ECONNLIMIT;
      goto fail;
    }

    /* Assume flags don't have CONNECTED set */
    hShare->hServer = hServ;
    hShare->sharetype = sharetype_in;
    strcpy  ( hShare->sharename, uc_sharename );
    strcpyn_upper ( hShare->password, password_in, NAME_LIMIT );
    Xlt_Jumble(hShare->password);
    done |= ALLOC_SHARE;
  }

  /* Clear attribute-file cache for the drive */

  Attr_InvalidateDrive ( hShare->drvletter );

  /* Disconnect server if new user */

  if ( to_do & DISCONN_SERVER )
  {
    /* For a change of user, disconnect the server. It will mark
       all attached shares as being disconnected */
    DisconnectServer ( hServ );
    done |= DISCONN_SERVER;
  }

  /* (re)connect to server */

  if ( to_do & CONN_SERVER )
  {
    /* Set up new server details */
    strcpyn_upper ( hServ->username, username_in, NAME_LIMIT );
    strcpyn_upper ( hServ->password, password_in, NAME_LIMIT );
    Xlt_Jumble(hServ->password);

    res = ConnectServer ( hShare );
    if ( res != OK )
      goto fail;

    done |= CONN_SERVER;
  }

  /* Connect to share ------------------- */

  /* Reconnect share, & reconnect link if it's down */
  if ( GetShare ( &(hShare->drvletter), &res ) == NULL )
    goto fail;

  *drv_letter_out = hShare->drvletter;
  return OK;

  /* Back out if something goes wrong */

fail:
  if ( done & ALLOC_SHARE )   /* If it was a new share */
    FreeShare(hShare);        /*   free it */

  if ( done & ALLOC_SERVER )  /* If it was a new server... */
  {
    if ( done & CONN_SERVER )  /* Disconnect it if it was */
      DisconnectServer(hServ); /* connected */

    FreeServer(hServ);
  }

  return res;
}

/* --------------------------- */

err_t SMB_DeleteShare ( char drvlettr )
{
  hSHARE  hShare;
  hSERVER hSrv;

  hShare = GetShareNoConn(drvlettr);
  if ( hShare == NULL )
    return EBADDRV;

  hSrv = hShare->hServer;

  /* Do Tree disconnect */

  DisconnectShare(hShare);
  FreeShare(hShare);

  /* If there are no shares left on this server, drop link */

  if ( !ServerInUse(hSrv) )
  {
    DisconnectServer(hSrv);
    FreeServer(hSrv);
  }

  return OK;
}

/* Public file/directory routines ================================ */

Stewart Brodie's avatar
Stewart Brodie committed
1702
static err_t SMB_ChkPath ( char *path )
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
{
  return SMB_SingleOp( SMBchkpth, path );
}

/* ----------------------------- */

err_t SMB_MkDir ( char *path )
{
  return SMB_SingleOp( SMBmkdir, path );
}

/* ----------------------------- */

err_t SMB_RmDir ( char *path )
{
  return SMB_SingleOp( SMBrmdir, path );
}

/* ----------------------------- */

err_t SMB_Delete ( char *path )
{
  BUFCHAIN pB;
  hSHARE hS;
  err_t res;

  hS = GetShare (path, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString( NULL, DATA_ASCII, path+2 );
  if ( pB == NULL )
    return EOUTOFMEM;

  SMB_TxWords[0] = ATTR_NORM;

  return Do_SMB ( hS, SMBunlink, 1, pB, NULL );
}


/* ----------------------------- */

err_t SMB_Rename ( char *oldpath, char *newpath )
{
  BUFCHAIN pB;
  hSHARE hS;
  err_t res;

  if ( oldpath[0] != newpath[0] )  /* Different drives! */
    return EBADRENAME;

1754 1755 1756 1757
  debug2("SMB_Rename: %s %s\n", oldpath+1, newpath+1);
  if (strcmp(oldpath+1, newpath+1) == 0)
    return OK;

1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
  hS = GetShare (oldpath, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString( NULL, DATA_ASCII, newpath+2 );
  if ( pB != NULL ) pB = MkDataString ( pB, DATA_ASCII, oldpath+2 );

  if ( pB == NULL )
    return EOUTOFMEM;

1768
  SMB_TxWords[0] = ATTR_NORM | ATTR_DIR; /* Permit both file and dir renaming */
1769 1770 1771 1772 1773 1774

  return Do_SMB ( hS, SMBmv, 1, pB, NULL );
}

/* --------------------------- */

Stewart Brodie's avatar
Stewart Brodie committed
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
#ifdef LONGNAMES

/* Some Microsoft servers not sending them in the documented order */
static void swap_time_date(BYTE *p)
{
        BYTE swp;

        swp = p[0];
        p[0] = p[2];
        p[2] = swp;

        swp = p[1];
        p[1] = p[3];
        p[3] = swp;
}

static err_t SMB_GetAttribsX2 (hSHARE hS, char *filename, DOS_ATTRIBS *pAttr )
{
  err_t res;
  BYTE *resb;
  static struct TransactParms tp;

1797
  debug1("SMB_GetAttribs: %s\n", filename);
Stewart Brodie's avatar
Stewart Brodie committed
1798 1799
  resb = NameCache_Locate(filename);
  if (resb != NULL) {
1800
    Transact_init(&tp, 1 * 2);           /* need to initialise tp.data_out_buf!! */
Stewart Brodie's avatar
Stewart Brodie committed
1801 1802 1803 1804 1805
    memcpy( tp.data_out_buf, resb, 23);
    strcpy( (char *) tp.data_out_buf + 23, (char *) resb + 23);
    return Xlt_ExpandSearchEntryX2 ( tp.data_out_buf, NULL, NULL, pAttr, NULL);
  }

1806
  if (!(hS->hServer->t2flags & T2FLAGS_TESTEDSWAP)) {
Stewart Brodie's avatar
Stewart Brodie committed
1807 1808 1809
    /* Need to test whether we have to swap the date/time fields */
    char fnbuffer[8];
    DOS_ATTRIBS aattrbuf;
1810
    hS->hServer->t2flags |= T2FLAGS_TESTEDSWAP;
Stewart Brodie's avatar
Stewart Brodie committed
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
    fnbuffer[0] = *filename;
    fnbuffer[1] = ':';
    fnbuffer[2] = '\\';
    fnbuffer[3] = '\0';
    debug1("Looking up `%s' to test buffer format\n", fnbuffer);
    if (SMB_GetAttribsX2 ( hS, fnbuffer, &aattrbuf ) == OK) {
      fnbuffer[3] = '\0';
      fnbuffer[4] = '\0';
      Transact_init(&tp, 6 * 2);           /* will accept 6 WORD return params */
      Transact_addsetupword(&tp, TRANSACT2_FINDFIRST);
Ben Avison's avatar
Ben Avison committed
1821 1822 1823 1824 1825 1826
      if (LM_Vars.namemode & NM_INTERNAL) {
        Transact_addword(&tp, ATTR_DIR | ATTR_SYS | ATTR_HID);     /* findfirst_Attribute */
      }
      else {
        Transact_addword(&tp, ATTR_DIR);     /* findfirst_Attribute */
      }
Stewart Brodie's avatar
Stewart Brodie committed
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
      Transact_addword(&tp, 1);            /* findfirst_SearchCount */
      Transact_addword(&tp, 0);            /* findfirst_flags */
      Transact_addword(&tp, 1);            /* Search level  */
      Transact_addlong(&tp, 0L);           /* reserved, MBZ */
      Transact_addstring(&tp, fnbuffer+2); /* findfirst_FileName[] */
      debug1("Looking for `%s'\n", fnbuffer+2);
      res = SMB_Transact2(hS, &tp);
      if (res == OK) {
        debug0("SMB_Transact2 worked\n");
        SMB_TxWords[0] = Transact_getword(tp.parms_out_buf);
        if (Transact_getword(tp.parms_out_buf + 2) == 1) {
          DOS_ATTRIBS sattrbuf;
          debug1("Filename was `%s'\n", tp.data_out_buf + 23);
          res = Xlt_ExpandSearchEntryX2 ( tp.data_out_buf, NULL, NULL, &sattrbuf, NULL);
          if (res == OK) {
            if (sattrbuf.utime != aattrbuf.utime) {
               debug0("Need to swap date/time!\n");
1844
               hS->hServer->t2flags |= T2FLAGS_SWAPDATETIME;
Stewart Brodie's avatar
Stewart Brodie committed
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
               swap_time_date(tp.data_out_buf);
               swap_time_date(tp.data_out_buf+4);
               swap_time_date(tp.data_out_buf+8);
               Xlt_ExpandSearchEntryX2 ( tp.data_out_buf, NULL, NULL, &sattrbuf, NULL);
               if (sattrbuf.utime != aattrbuf.utime) {
                 debug0("Didnt get the right thing anyway\n");
               }
               else {
                 debug0("Tested and verified!\n");
               }
            }
            else {
               debug0("Don't need to swap date/time!\n");
            }
          }
        }
      	(void) Do_SMB(hS, SMBfindclose2, 1, NULL, NULL);
      }
      else {
        debug0("SMB_Transact2 failed\n");
      }
    }
  }

  Transact_init(&tp, 1 * 2);
  Transact_addsetupword(&tp, TRANSACT2_QUERYPATHINFORMATION);
  Transact_addword(&tp, 1);  /* information level */
  Transact_addlong(&tp, 0L); /* Reserved */
  Transact_addstring(&tp, filename+2);
  res = SMB_Transact2(hS, &tp);
  if (res != OK)
    return res;
  /*
   * OK.  Who decided that this call should return data in a different
   * format than the FindFirst/FindNext calls.  Need to reverse the times
   * and dates of the file before calling Xlt to expand them ... but only
   * if the remote server has this bug.
   */
1883
  if (hS->hServer->t2flags & T2FLAGS_SWAPDATETIME) {
Stewart Brodie's avatar
Stewart Brodie committed
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
    swap_time_date(tp.data_out_buf);
    swap_time_date(tp.data_out_buf+4);
    swap_time_date(tp.data_out_buf+8);
  }
  /* end workaround */
  strcpy((char *)tp.data_out_buf+23, filename); /* Xlt_ExpandSearchEntryX2 relies on this */
  return Xlt_ExpandSearchEntryX2 ( tp.data_out_buf, NULL, NULL, pAttr, NULL);
}
#endif /* LONGNAMES */

/* --------------------------- */

1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
#if 0
err_t SMB_GetAttribs ( char *filename, DOS_ATTRIBS *pAttr )
{
  err_t res;
  BUFCHAIN pB;
  hSHARE hS;

  hS = GetShare (filename, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString ( NULL, DATA_ASCII, filename+2 );
  if ( pB == NULL )
    return EOUTOFMEM;

  res = Do_SMB ( hS, SMBgetatr, 0, pB, NULL );

  if ( res == OK )
  {
    pAttr->attr  = SMB_RxWords[0];
    pAttr->utime = SMB_RxWords[1] + (SMB_RxWords[2] << 16);
    pAttr->length = SMB_RxWords[3] + (SMB_RxWords[4] << 16);
  }

  return res;
}
#else
/* THIS IS A BODGE!!
   The SMB_GetAtr command in NT4.0 returns rubbish the file time;
     it renders this command basically unusable. We have to get the
     same information out via a directory search command instead.
*/

err_t SMB_GetAttribs ( char *filename, DOS_ATTRIBS *pAttr )
{
  err_t res;
  BUFCHAIN pB, pBres;
  hSHARE hS;

  hS = GetShare (filename, &res);
  if ( hS == NULL )
    return res;

Stewart Brodie's avatar
Stewart Brodie committed
1939
#ifdef LONGNAMES
1940
  if (hS->hServer->t2flags & T2FLAGS_LONGNAMES)
Stewart Brodie's avatar
Stewart Brodie committed
1941 1942 1943
    return SMB_GetAttribsX2 (hS, filename, pAttr );
#endif

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
  pB = MkDataBlock ( NULL, DATA_VARBLK, NULL, 0, false );
  if ( pB != NULL )
    pB = MkDataString ( pB, DATA_ASCII, filename+2 );

  if ( pB == NULL )
    return EOUTOFMEM;

  SMB_TxWords[0] = 1; /* Count of entries to return */
  SMB_TxWords[1] = ATTR_DIR; /* Return files & directories info */

  res = Do_SMB ( hS, SMBsearch, 2, pB, &pBres );

  if ( res == ENOMOREFILES )
    return EFILENOTFOUND;

  if ( res != OK )
    return res;

  /* Extract all data  */

  FreeChain( GetData ( pBres, SMB_WorkBuf, SMB_RxByteCount ) );

  if ( SMB_RxWords[0] < 1 ) /* No files read */
    return EFILENOTFOUND;

  return Xlt_ExpandSearchEntry ( SMB_WorkBuf+3+SEARCH_ST_SIZE,
               NULL, NULL, pAttr, NULL );

}
#endif

/* --------------------------- */

static err_t SMB_SetDateTimeAttr ( char *filename, DOS_ATTRIBS *pAttr,
                                         int flags )
{
  BUFCHAIN pB;
  hSHARE hS;
  err_t res;

  hS = GetShare (filename, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString ( NULL, DATA_ASCII, "" );
  if ( pB != NULL )
    pB = MkDataString ( pB, DATA_ASCII, filename+2 );
  if ( pB == NULL )
    return EOUTOFMEM;

  SMB_TxWords[0] = pAttr->attr;
  if ( flags & PROT_SETDATETIME )
  {
    SMB_TxWords[1] = pAttr->utime & 0xFFFF;
    SMB_TxWords[2] = pAttr->utime >> 16;
  }
  else
  {
    SMB_TxWords[1] = 0;
    SMB_TxWords[2] = 0;
  }
  SMB_TxWords[3] = 0;
  SMB_TxWords[4] = 0;
  SMB_TxWords[5] = 0;
  SMB_TxWords[6] = 0;
  SMB_TxWords[7] = 0;

  return Do_SMB ( hS, SMBsetatr, 8, pB, NULL );
}

/* ------------------------------------------ */

err_t SMB_SetAttribs ( char *filename, DOS_ATTRIBS *pAttr )
{
  err_t res;

  /* W4WG / Windows 95 barfs if we try to set a file time with this call */
  /* but they can set other attributes, so we have to retry */

  res = SMB_SetDateTimeAttr ( filename, pAttr, PROT_SETDATETIME );
  if ( res != ENOTPRESENT )
    return res;

  /* 1997.04.21 - try really hard to set file attributes first, then
                  date & time by opening and closing the file */

  res = SMB_SetDateTimeAttr ( filename, pAttr, 0 );
  if ( res != OK )
    return res;

  if ( pAttr->utime != 0 && (pAttr->attr & ATTR_DIR) == 0 )
  {
    int FH, tmp;
    DOS_ATTRIBS da;

    res = SMB_Open ( MODE_RD, filename, &da, &FH, &tmp );
    if ( res == OK )
    {
      da.utime = pAttr->utime;
      SMB_Close( FH, &da );
    }
    /* Swallow errors, as this is a bit of a bodge! */
  }

  return OK;
}

/* --------------------------- */

Stewart Brodie's avatar
Stewart Brodie committed
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
#ifdef LONGNAMES
static err_t SMB_GetFreeSpaceX2 ( hSHARE hS, struct disk_size_response *pDSR  )
{
  err_t res;
  static struct TransactParms tp;
  BYTE *p;
  DWORD sectors_per_alloc, total_allocs, total_avail_allocs;
  WORD bytes_per_sector;

  Transact_init(&tp, 1 * 2);
  Transact_addsetupword(&tp, TRANSACT2_QUERYFSINFORMATION);
  Transact_addword(&tp, 1);  /* information level */
  res = SMB_Transact2(hS, &tp);
  if (res != OK)
    return res;
  p = tp.data_out_buf + 4;
  sectors_per_alloc = Transact_getlong(p), p += 4;
  total_allocs = Transact_getlong(p), p += 4;
  total_avail_allocs = Transact_getlong(p), p += 4;
  bytes_per_sector = Transact_getword(p);

  pDSR->blksize = bytes_per_sector * sectors_per_alloc;
  pDSR->freeblks =  total_avail_allocs;
  pDSR->totalblks = total_allocs;

  return OK;
}
#endif

2082 2083 2084 2085 2086 2087 2088 2089 2090
err_t SMB_GetFreeSpace ( char lettr, struct disk_size_response *pDSR  )
{
  err_t res;
  hSHARE hS;

  hS = GetShare (&lettr, &res);
  if ( hS == NULL )
    return res;

Stewart Brodie's avatar
Stewart Brodie committed
2091
#ifdef LONGNAMES
2092
  if (hS->hServer->t2flags & T2FLAGS_LONGNAMES)
Stewart Brodie's avatar
Stewart Brodie committed
2093 2094 2095 2096 2097
  {
    return SMB_GetFreeSpaceX2(hS, pDSR);
  }
#endif

2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
  res = Do_SMB ( hS, SMBdskattr, 0, NULL, NULL );

  if ( res == OK )
  {
    pDSR->blksize = SMB_RxWords[1] * SMB_RxWords[2];
    pDSR->freeblks = SMB_RxWords[3];
    pDSR->totalblks = SMB_RxWords[0];
  }

  return res;
}


/* ------------------------------- */

Stewart Brodie's avatar
Stewart Brodie committed
2113 2114 2115 2116 2117 2118 2119 2120
#ifdef LONGNAMES

/* Note.
 *
 * Requesting close_if_done doesn't seem to work (at least on NT 4.0 SP3)
 *
 */
enum {
Ben Avison's avatar
Ben Avison committed
2121 2122 2123 2124 2125
  ffirst_FORCE_CLOSE = 1,
  ffirst_CLOSE_IF_DONE = 2,
  ffirst_RETURN_KEYS = 4,
  fnext_CONTINUE = 8, /* This bit allows continuation without the need to use resume keys */
  ffirst_BACKUP_INTENT = 16
Stewart Brodie's avatar
Stewart Brodie committed
2126 2127 2128 2129
};

static err_t SMB_AbandonFind2( hSHARE hS, WORD dir_handle )
{
Ben Avison's avatar
Ben Avison committed
2130 2131 2132
  debug1("Terminating search op (dir_handle = %x)\n", dir_handle);
  SMB_TxWords[0] = dir_handle;
  return Do_SMB(hS, SMBfindclose2, 1, NULL, NULL);
Stewart Brodie's avatar
Stewart Brodie committed
2133
}
2134

Ben Avison's avatar
Ben Avison committed
2135
/* Implement directory searching via TRANSACT2/FINDFIRST/FINDNEXT */
Stewart Brodie's avatar
Stewart Brodie committed
2136
static err_t SMB_ReadDirEntriesX2 ( hSHARE hS, char *path, int count,
Ben Avison's avatar
Ben Avison committed
2137 2138
                                    ENUM_DIR_FN dirfn, void *private,
                                    Transact_SearchContext *con )
Stewart Brodie's avatar
Stewart Brodie committed
2139 2140 2141 2142 2143 2144 2145
{
  err_t res;
  BYTE *p;
  int n_read = 0;
  int eos;
  int i;
  int flags;
Ben Avison's avatar
Ben Avison committed
2146 2147 2148 2149
  const int first_flags = ffirst_RETURN_KEYS;
  const int next_flags  = ffirst_RETURN_KEYS;
  bool path_changed = false;
  bool taken;
Stewart Brodie's avatar
Stewart Brodie committed
2150

Ben Avison's avatar
Ben Avison committed
2151 2152 2153
  /* Despite having a resume key it may be necessary to restart */
  if ( (path != NULL) && (strcmp( path, con->dir_path ) != 0) )
    path_changed = true;
Stewart Brodie's avatar
Stewart Brodie committed
2154

Ben Avison's avatar
Ben Avison committed
2155 2156 2157 2158 2159 2160 2161 2162 2163
  if ( path_changed || (con->resume_key == 0) ) {
    /* Path changed due to recursion or new search */
    if (con->dir_handle_valid) {
      debug1("SMB_ReadDirEntriesX2 -> abandon old search of dir handle %x\n", con->dir_handle);
      (void) SMB_AbandonFind2( hS, con->dir_handle );
      con->dir_handle_valid = false;
    }
    strcpy( con->dir_path, path );
    con->resume_key_encountered = (con->resume_key == 0) ? true : false;
Stewart Brodie's avatar
Stewart Brodie committed
2164

Ben Avison's avatar
Ben Avison committed
2165 2166 2167 2168 2169
    /* For a new search, ensure the request allows for "." and ".." which are
     * always given and would therefore end up oscillating with 0 useful files
     * found and a resume key of 0 again
     */
    count = max( count, 3 );
Stewart Brodie's avatar
Stewart Brodie committed
2170 2171 2172 2173 2174 2175 2176

    /* Initial search - note we accept SIX return parameters - contrary to
     * Microsoft's own document - because it doesn't work if you only pass 5. Grr.
     */
    flags = first_flags;
    Transact_init(&con->tp, 6 * 2);           /* will accept 6 WORD return params */
    Transact_addsetupword(&con->tp, TRANSACT2_FINDFIRST);
Ben Avison's avatar
Ben Avison committed
2177
    if (LM_Vars.namemode & NM_INTERNAL) {
Stewart Brodie's avatar
Stewart Brodie committed
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
      Transact_addword(&con->tp, ATTR_DIR | ATTR_SYS | ATTR_HID);     /* findfirst_Attribute */
    }
    else {
      Transact_addword(&con->tp, ATTR_DIR);   /* findfirst_Attribute */
    }
    Transact_addword(&con->tp, count);        /* findfirst_SearchCount */
    Transact_addword(&con->tp, first_flags);  /* findfirst_flags */
    Transact_addword(&con->tp, 1);            /* Search level  */
    Transact_addlong(&con->tp, 0L);           /* reserved, MBZ */
    Transact_addstring(&con->tp, path+2);     /* findfirst_FileName[] */
    res = SMB_Transact2(hS, &con->tp);
    if (res != OK)
      return res;
    p = con->tp.parms_out_buf;
    con->dir_handle = Transact_getword(p); p += 2;
Stewart Brodie's avatar
Stewart Brodie committed
2193
    con->dir_handle_valid = true;
Ben Avison's avatar
Ben Avison committed
2194
    debug1("SMB_ReadDirEntriesX2 -> new dir handle %x\n", con->dir_handle);
Stewart Brodie's avatar
Stewart Brodie committed
2195 2196
  }
  else {
Ben Avison's avatar
Ben Avison committed
2197 2198
    /* Continuation */
    con->resume_key_encountered = true;
Stewart Brodie's avatar
Stewart Brodie committed
2199
    flags = next_flags;
Ben Avison's avatar
Ben Avison committed
2200
    Transact_init(&con->tp, 4 * 2);                /* will accept 4 WORD return params */
Stewart Brodie's avatar
Stewart Brodie committed
2201 2202
    Transact_addsetupword(&con->tp, TRANSACT2_FINDNEXT);
    Transact_addword(&con->tp, con->dir_handle);   /* findnext_DirHandle */
Ben Avison's avatar
Ben Avison committed
2203 2204
    Transact_addword(&con->tp, count);             /* findnext_SearchCount */
    Transact_addword(&con->tp, 1);                 /* Search level  */
Stewart Brodie's avatar
Stewart Brodie committed
2205
    Transact_addlong(&con->tp, con->resume_key);   /* Resume key from previous */
Ben Avison's avatar
Ben Avison committed
2206 2207 2208
    Transact_addword(&con->tp, next_flags);        /* findnext_flags */
    Transact_addstring(&con->tp, "");              /* no name needed */
    debug1("SMB_ReadDirEntriesX2 -> continue with key %08x\n", con->resume_key);
Stewart Brodie's avatar
Stewart Brodie committed
2209 2210 2211 2212 2213 2214 2215 2216
    res = SMB_Transact2(hS, &con->tp);
    if (res != OK)
      return res;
    p = con->tp.parms_out_buf;
  }
  /* Remainder of response handling is common to both sub-commands */
  n_read = Transact_getword(p); p += 2;
  eos = Transact_getword(p); p += 2;
Ben Avison's avatar
Ben Avison committed
2217 2218
  if (eos)
    debug0(">> Server said it was the end of the search operation\n");
Stewart Brodie's avatar
Stewart Brodie committed
2219 2220 2221 2222 2223 2224 2225 2226 2227

  p = con->tp.data_out_buf;
  /* At this point, p is pointing to the start of the returned data
   * buffer, n_read contains the number of files known to be in the
   * return buffer, eos is non-zero if the search is completed.
   */
  if (n_read == 0)
    return ENOMOREFILES;

Ben Avison's avatar
Ben Avison committed
2228
  for (i = 1; i <= n_read; i++) {
Stewart Brodie's avatar
Stewart Brodie committed
2229 2230
    int length;
    DWORD next_resume_key;
Ben Avison's avatar
Ben Avison committed
2231 2232 2233

    /* Get next resume key */
    next_resume_key = Transact_getlong(p); p += 4;
Stewart Brodie's avatar
Stewart Brodie committed
2234
    length = p[22];
Ben Avison's avatar
Ben Avison committed
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244

    if ( con->resume_key_encountered ) {
      debug1("SMB_ReadDirEntriesX2 -> call back with key %08x\n", next_resume_key);
      res = dirfn(p, 1, &taken, private);
      if (taken) con->resume_key = next_resume_key;
      if (res != OK) {
        /* Entry expander must have run out of space! */
        debug0("SMB_ReadDirEntriesX2 -> caller ran out of space (or could be name xlate code)\n");
        return EOUTOFMEM;
      }
Stewart Brodie's avatar
Stewart Brodie committed
2245 2246
    }
    else {
Ben Avison's avatar
Ben Avison committed
2247 2248 2249
      debug2("SMB_ReadDirEntriesX2 -> awaiting key %08x (got %08x)\n", con->resume_key, next_resume_key);
      if ( next_resume_key == con->resume_key )
        con->resume_key_encountered = true;
Stewart Brodie's avatar
Stewart Brodie committed
2250 2251 2252 2253
    }
    p += 23 + length + 1;
  }

Ben Avison's avatar
Ben Avison committed
2254 2255
  if (eos)
    debug0(">> Server said it was the end of the search operation\n");
Stewart Brodie's avatar
Stewart Brodie committed
2256

Ben Avison's avatar
Ben Avison committed
2257
  return eos ? ENOMOREFILES : OK;
Stewart Brodie's avatar
Stewart Brodie committed
2258 2259
}
#endif
2260 2261

err_t SMB_ReadDirEntries ( char *path, int count,
Ben Avison's avatar
Ben Avison committed
2262
                           ENUM_DIR_FN dirfn, void *private, void *context )
2263 2264
{
  err_t res;
Ben Avison's avatar
Ben Avison committed
2265 2266
  int i, n_read, eos;
  BYTE *p;
2267
  BUFCHAIN pB, pBres;
Ben Avison's avatar
Ben Avison committed
2268 2269 2270
  Transact_SearchContext *con;
  bool path_changed = false;
  bool taken;
Stewart Brodie's avatar
Stewart Brodie committed
2271

Ben Avison's avatar
Ben Avison committed
2272 2273
  /* Don't be silly */
  if (count < 0) return ENOMOREFILES;
Stewart Brodie's avatar
Stewart Brodie committed
2274

Ben Avison's avatar
Ben Avison committed
2275 2276 2277 2278 2279
  con = (Transact_SearchContext *)context;
  if (con->resume_key == 0) {
    /* Start search */
    con->search_drive = GetShare(path, &res);
    if ( con->search_drive == NULL )
Stewart Brodie's avatar
Stewart Brodie committed
2280 2281
      return res;
  }
Ben Avison's avatar
Ben Avison committed
2282 2283 2284
  else {
    /* Continue search */
    if ( con->search_drive == NULL )
Stewart Brodie's avatar
Stewart Brodie committed
2285 2286 2287 2288
      return ENOMOREFILES;
  }

#ifdef LONGNAMES
Ben Avison's avatar
Ben Avison committed
2289 2290 2291
  if ( con->search_drive->hServer->t2flags & T2FLAGS_LONGNAMES ) {
    /* Long names enabled */
    return SMB_ReadDirEntriesX2(con->search_drive, path, count, dirfn, private, con);
Stewart Brodie's avatar
Stewart Brodie committed
2292 2293
  }
#endif
2294

Ben Avison's avatar
Ben Avison committed
2295 2296 2297
  /* Despite having a resume key it may be necessary to restart */
  if ( (path != NULL) && (strcmp( path, con->dir_path ) != 0) )
    path_changed = true;
2298

Ben Avison's avatar
Ben Avison committed
2299 2300 2301 2302 2303
  if (con->resume_key == 0) {
    /* New search */
    strcpy( con->dir_path, path );
    con->resume_key_encountered = true;
    con->dir_handle_valid = false;
2304

Ben Avison's avatar
Ben Avison committed
2305 2306 2307 2308 2309
    /* For a new search, ensure the request allows for "." and ".." which are
     * always given and would therefore end up oscillating with 0 useful files
     * found and a resume key of 0 again
     */
    count = max( count, 3 );
2310

Ben Avison's avatar
Ben Avison committed
2311
    /* Initial search */
2312 2313 2314
    pB = MkDataBlock ( NULL, DATA_VARBLK, NULL, 0, false );
    if ( pB != NULL )
      pB = MkDataString( pB, DATA_ASCII, path+2 );
Ben Avison's avatar
Ben Avison committed
2315
    debug1("SMB_ReadDirEntries -> new search of %s\n", path);
2316
  }
Ben Avison's avatar
Ben Avison committed
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
  else {
    /* Continuation */
    debug1("SMB_ReadDirEntries -> continue with key %08x\n", con->resume_key);

    if (!path_changed && con->dir_handle_valid &&
       ((WORD)con->resume_key == con->dir_handle)) {
      /* Path is the same, search key non zero, state valid */
      debug0("SMB_ReadDirEntries -> hyperspace\n");
      con->resume_key_encountered = true;
      pB = MkDataBlock (NULL, DATA_VARBLK, con->resume_state,
                        SEARCH_ST_SIZE, false);
      if ( pB != NULL)
        pB = MkDataString( pB, DATA_ASCII, "" );
    }
    else {
      /* Emulate the state resumption, slow but infrequent */
      debug0("SMB_ReadDirEntries -> emulation\n");

      con->resume_key_encountered = false;
      pB = MkDataBlock ( NULL, DATA_VARBLK, NULL, 0, false );
      if ( pB != NULL )
        pB = MkDataString( pB, DATA_ASCII, path+2 );

      while (!con->resume_key_encountered) {
        /* Do search */
        if ( pB == NULL )
          return EOUTOFMEM;
        SMB_TxWords[0] = max( count, SEARCH_COUNT );
        SMB_TxWords[1] = ATTR_DIR /* | ATTR_SYS | ATTR_HID */;
        res = Do_SMB( con->search_drive, SMBsearch, 2, pB, &pBres );
        if ( res != OK )
          return res;
        FreeChain( GetData( pBres, SMB_WorkBuf, SMB_RxByteCount ) );

        /* Scan for a match */
        n_read = SMB_RxWords[0];
        eos = (n_read < count);
        if (eos)
          debug0(">> Server said it was the end of the search operation\n");

        p = SMB_WorkBuf+3;
        /* At this point, p is pointing to the start of the returned data
         * buffer, n_read contains the number of files known to be in the
         * return buffer, eos is non-zero if the search is completed.
         */
        if (n_read == 0)
          return ENOMOREFILES;

        for (i = 1; i <= n_read; i++) {
          DWORD next_resume_key;

          /* Prep resumption */
          memcpy( con->resume_state, p, SEARCH_ST_SIZE );

          /* Get next resume key */
          _swix(OS_CRC, _INR(0,3)|_OUT(0), 0, p+30, p+SEARCH_TOT_SIZE, 1, &next_resume_key);
          if (next_resume_key == con->resume_key) {
            strcpy( con->dir_path, path );
            con->resume_key_encountered = true;
            break;
          }

          p += SEARCH_TOT_SIZE;
        }

        /* Again again... */
        pB = MkDataBlock (NULL, DATA_VARBLK, con->resume_state,
                          SEARCH_ST_SIZE, false);
        if ( pB != NULL)
          pB = MkDataString( pB, DATA_ASCII, "" );
      }
    }
2389 2390
  }

Ben Avison's avatar
Ben Avison committed
2391
  /* Do search */
2392 2393
  if ( pB == NULL )
    return EOUTOFMEM;
Ben Avison's avatar
Ben Avison committed
2394
  count = min( count, SEARCH_COUNT );
2395 2396
  SMB_TxWords[0] = count;
  SMB_TxWords[1] = ATTR_DIR /* | ATTR_SYS | ATTR_HID */;
Ben Avison's avatar
Ben Avison committed
2397
  res = Do_SMB( con->search_drive, SMBsearch, 2, pB, &pBres );
2398 2399
  if ( res != OK )
    return res;
Ben Avison's avatar
Ben Avison committed
2400
  FreeChain( GetData( pBres, SMB_WorkBuf, SMB_RxByteCount ) );
2401

Ben Avison's avatar
Ben Avison committed
2402 2403 2404 2405 2406
  /* Remainder of response handling is common to both sub-commands */
  n_read = SMB_RxWords[0];
  eos = (n_read < count);
  if (eos)
    debug0(">> Server said it was the end of the search operation\n");
2407

Ben Avison's avatar
Ben Avison committed
2408 2409 2410 2411 2412 2413 2414
  p = SMB_WorkBuf+3;
  /* At this point, p is pointing to the start of the returned data
   * buffer, n_read contains the number of files known to be in the
   * return buffer, eos is non-zero if the search is completed.
   */
  if (n_read == 0)
    return ENOMOREFILES;
2415

Ben Avison's avatar
Ben Avison committed
2416 2417
  for (i = 1; i <= n_read; i++) {
    DWORD next_resume_key;
2418

Ben Avison's avatar
Ben Avison committed
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
    /* Get next resume key */
    _swix(OS_CRC, _INR(0,3)|_OUT(0), 0, p+30, p+SEARCH_TOT_SIZE, 1, &next_resume_key);
    p[SEARCH_TOT_SIZE - 1] = 0;

    debug1("SMB_ReadDirEntries -> call back with key %08x\n", next_resume_key);
    res = dirfn(p+SEARCH_ST_SIZE, 0, &taken, private);
    if (taken) {
      con->resume_key = next_resume_key;
      memcpy( con->resume_state, p, SEARCH_ST_SIZE );
      con->dir_handle = (WORD)next_resume_key;
      con->dir_handle_valid = true;
    }
    if (res != OK) {
      /* Entry expander must have run out of space! */
      debug0("SMB_ReadDirEntries -> caller ran out of space (or could be name xlate code)\n");
      return EOUTOFMEM;
2435
    }
Ben Avison's avatar
Ben Avison committed
2436 2437

    p += SEARCH_TOT_SIZE;
2438 2439
  }

Ben Avison's avatar
Ben Avison committed
2440 2441 2442 2443
  if (eos)
    debug0(">> Server said it was the end of the search operation\n");

  return eos ? ENOMOREFILES : OK;
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
}

/* Public file read/write operations ============================= */


err_t SMB_Create ( char *filename, DOS_ATTRIBS *pInAttr,
                   int *pOutFH )
{
  err_t res;
  BUFCHAIN pB;
  hSHARE hS;

  hS = GetShare(filename, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString ( NULL, DATA_ASCII, filename+2 );
  if ( pB == NULL )
    return EOUTOFMEM;

  SMB_TxWords[0] = (pInAttr->attr) & (ATTR_RO|ATTR_SYS|ATTR_HID);
  SMB_TxWords[1] = (pInAttr->utime) & 0xFFFF;
  SMB_TxWords[2] = (pInAttr->utime) >> 16;

  res = Do_SMB ( hS, SMBcreate, 3, pB, NULL );
  if ( res == OK )
    *pOutFH = MakeFH(hS, SMB_RxWords[0]);

  return res;
}

/* ---------------- */

static int ModeXlate[4] = { MODE_RD, MODE_WR, MODE_RDWR, 0 };

err_t SMB_Open ( int mode, char *filename,
      DOS_ATTRIBS *pOutAttr, int *pOutFH, int *pOutModes )
{
  err_t res;
  BUFCHAIN pB;
  hSHARE hS;

  hS = GetShare(filename, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString ( NULL, DATA_ASCII, filename+2 );
  if ( pB == NULL )
    return EOUTOFMEM;

  SMB_TxWords[0] = mode;  /* Exclusive access */
  SMB_TxWords[1] = ATTR_RO | ATTR_HID | ATTR_SYS; /* Attribute */

  res = Do_SMB ( hS, SMBopen, 2, pB, NULL );
  if ( res == OK )
  {
    *pOutFH = MakeFH(hS, SMB_RxWords[0]);

    if ( pOutAttr != NULL )
    {
      pOutAttr->attr    = SMB_RxWords[1];
      pOutAttr->utime   = SMB_RxWords[2] + (SMB_RxWords[3] << 16);
      pOutAttr->length  = SMB_RxWords[4] + (SMB_RxWords[5] << 16);
    }

    if ( pOutModes != NULL )
      *pOutModes = ModeXlate[SMB_RxWords[6] & 3];
  }
  return res;
}

/* ---------------- */

err_t SMB_GetLength ( int FH, int *pOutLen )
{
  err_t res;
  hSHARE hS = GetShareFromFH(FH, &res);
  if ( hS == NULL )
    return res;

  SMB_TxWords[0] = GetFid(FH);
  SMB_TxWords[1] = 2;  /* SEEK from end */
  SMB_TxWords[2] = 0;  /* Offset 0: Relative to end */
  SMB_TxWords[3] = 0;

  res = Do_SMB ( hS, SMBlseek, 4, NULL, NULL );
  if ( res == OK )
  {
    *pOutLen = SMB_RxWords[0] + (SMB_RxWords[1] << 16);
  }

  return res;
}

/* ---------------- */


err_t SMB_Read ( int FH, int offset, int len, BYTE *where,
    int *pOutLen )
{
  int len_left, n_read, fid;
  hSHARE hS;
  BUFCHAIN pB_res;
  err_t res = OK;

  len_left = len;
  hS = GetShareFromFH(FH, &res);
  if ( hS == NULL )
    return res;

  fid = GetFid(FH);

  /* Can a raw block read help us ? */

  if ( hS->hServer->ProtFlags & PROT_READRAW )
  {
    while ( len_left > FILE_BLOCK_SIZE )
    {
      n_read = SMB_ReadRaw ( hS, fid, offset, len_left, where );
      if ( n_read <= 0 )  /* Didn't work? Find out why */
        break;

      len_left -= n_read;
      where    += n_read;
      offset   += n_read;
    }
  }

  /* Conventional read command */

  while ( len_left > 0 )
  {
    SMB_TxWords[0] = fid;
    SMB_TxWords[1] = min(len_left,FILE_BLOCK_SIZE);
    SMB_TxWords[2] = offset & 0xFFFF;
    SMB_TxWords[3] = (offset >> 16 );
    SMB_TxWords[4] = (len_left);

    res = Do_SMB ( hS, SMBread, 5, NULL, &pB_res );
    if ( res != OK )
      break;

    n_read = SMB_RxWords[0];

    if ( n_read > 0 )
    {
      pB_res = GetData(pB_res, NULL, 3 ); /* Data header */
      pB_res = GetData(pB_res, where, n_read );

      if ( pB_res == NULL )  /* Read failed */
      {
        res = EDATALEN;
        break;
      }

      len_left -= n_read;
      where    += n_read;
      offset   += n_read;
    }

    FreeChain(pB_res);

    if ( n_read < FILE_BLOCK_SIZE )  /* Reached end of file */
      break;
  }

  if ( pOutLen != NULL ) *pOutLen = len-len_left;
  return res;
}

/* ---------------- */

err_t SMB_Truncate ( int FH, int length )
{
  BUFCHAIN pB;
  err_t res;
  hSHARE hS;

  hS = GetShareFromFH(FH, &res);
  if ( hS == NULL )
    return res;

  /* Do a truncate with a write of length zero */
  SMB_TxWords[0] = GetFid(FH);
  SMB_TxWords[1] = 0 /* Byte count to write */;
  SMB_TxWords[2] = length & 0xFFFF;
  SMB_TxWords[3] = (length >> 16 );
  SMB_TxWords[4] = 0;

  pB = MkDataBlock ( NULL, DATA_BLOCK, NULL, 0, false );
  if ( pB == NULL )
    return EOUTOFMEM;

  return Do_SMB ( hS, SMBwrite, 5, pB, NULL );
}

/* ---------------- */

err_t SMB_Write ( int FH, int offset, int len, BYTE *where,
    int *pOutLen )
{
  BUFCHAIN pB;
  int len_left, n_written, fid;
  hSHARE hS;

  err_t res=OK;

  hS = GetShareFromFH(FH, &res);
  if ( hS == NULL )
    return res;

  fid = GetFid(FH);
  len_left = len;

  /* Can we do it with raw writes? */

  if ( hS->hServer->ProtFlags & PROT_WRITERAW )
  {
    while ( len_left > FILE_BLOCK_SIZE )
    {
      n_written = min(len_left,WRRAW_BLOCK_SIZE);
      res = SMB_WriteRaw ( hS, fid, offset, n_written, where );
      if ( res != OK )
        goto finish;

      len_left -= n_written;
      where    += n_written;
      offset   += n_written;
    }
  }

  while ( len_left > 0 )
  {
    n_written = min(len_left,FILE_BLOCK_SIZE);
    SMB_TxWords[0] = fid;
    SMB_TxWords[1] = n_written;
    SMB_TxWords[2] = offset & 0xFFFF;
    SMB_TxWords[3] = (offset >> 16 );
    SMB_TxWords[4] = (len_left);

    pB = MkDataBlock ( NULL, DATA_BLOCK, where, n_written, true );
    if ( pB == NULL )
    {
      res = EOUTOFMEM;
      break;
    }

    res = Do_SMB ( hS, SMBwrite, 5, pB, NULL );
    if ( res != OK )
      break;

    n_written = SMB_RxWords[0];
    len_left -= n_written;
    where    += n_written;
    offset   += n_written;

    if ( n_written < FILE_BLOCK_SIZE )  /* End of data */
      break;
  }

finish:
  if ( pOutLen != NULL ) *pOutLen = len-len_left;
  return res;

}

/* ---------------- */

err_t SMB_Flush ( int FH )
{
  err_t res;
  hSHARE hS;

  hS = GetShareFromFH(FH, &res);
  if ( hS == NULL )
    return res;

  SMB_TxWords[0] = GetFid(FH);
  return Do_SMB ( hS, SMBflush, 1, NULL, NULL );
}

/* ---------------- */

err_t SMB_Close ( int FH, DOS_ATTRIBS *pAttr )
{
  err_t res;
  hSHARE hS;

  hS = GetShareFromFH(FH, &res);
  if ( hS == NULL )
    return res;

  SMB_TxWords[0] = GetFid(FH);
  SMB_TxWords[1] = pAttr->utime & 0xFFFF;
  SMB_TxWords[2] = pAttr->utime >> 16;

  return Do_SMB ( hS, SMBclose, 3, NULL, NULL );
}


/* Printing routines ================================== */

err_t SMB_OpenPrinter ( char drvlettr, char *idstring, int *ph_out )
{
  err_t res;
  BUFCHAIN pB;
  hSHARE hS;

  hS = GetShare(&drvlettr, &res);
  if ( hS == NULL )
    return res;

  pB = MkDataString ( NULL, DATA_ASCII, idstring );
  if ( pB == NULL )
    return EOUTOFMEM;

  SMB_TxWords[0] = 0;  /* Length of printer setup data */
  SMB_TxWords[1] = 1;  /* Graphics mode */

  res = Do_SMB ( hS, SMBsplopen, 2, pB, NULL );

  if ( res == OK )
    *ph_out = MakeFH(hS, SMB_RxWords[0]);

  return res;
}

/* -------------- */

err_t SMB_WritePrinter ( int PH, BYTE *data, int datalen )
{
  BUFCHAIN pB;
  hSHARE hS;
  int len;
  err_t res=OK;

  hS = GetShareFromFH(PH, &res);
  if ( hS == NULL )
    return res;

  while ( datalen > 0 )
  {
    len = ( datalen > PRN_BLOCK_SIZE ) ? PRN_BLOCK_SIZE : datalen;
    SMB_TxWords[0] = GetFid(PH);

    pB = MkDataBlock ( NULL, DATA_BLOCK, data, len, true );
    if ( pB == NULL )
    {
      res = EOUTOFMEM;
      break;
    }

    res = Do_SMB ( hS, SMBsplwr, 1, pB, NULL );
    if ( res != OK )
      break;

    datalen -= len;
    data += len;
  }

  return res;
}

/* ---------------- */

err_t SMB_ClosePrinter ( int PH )
{
  err_t res;
  hSHARE hS;

  hS = GetShareFromFH(PH, &res);
  if ( hS == NULL )
    return res;

  SMB_TxWords[0] = GetFid(PH);
  return Do_SMB ( hS, SMBsplclose, 1, NULL, NULL );
}

/* "Transact" (Remote-procedure-call) operations =========== */

/* For the time being, we limit each transmission to one
   packet's worth (1500 bytes). This might cause Tx failures
   if we exceed it.

   Also, we don't allow any 'setup words' (cos I've never seen them
   used & don't know what they do!).

*/

err_t SMB_Transact ( char drvlettr, char *name, struct TransactParms *pT )
{
  BUFCHAIN pB, pBres;
  err_t res;
  int   a, padbytes;    /* Temp variable */
  hSHARE hS;

  hS = GetShare(&drvlettr, &res);
  if ( hS == NULL )
    return res;

  a = SMBHDR_SIZE + (14*2) + 2 + strlen(name) + 1;
      /* Size of SMB header, 14 word params, 2 byte data length,
            plus the transaction name inc. zero terminator */

  SMB_TxWords[0]  = pT->parms_in_len; /* Total length */
  SMB_TxWords[1]  = pT->data_in_len; /* Total length */
  SMB_TxWords[2]  = pT->parms_out_maxlen;
  SMB_TxWords[3]  = pT->data_out_maxlen;
  SMB_TxWords[4]  = 0; /* Setup words to return */
  SMB_TxWords[5]  = 0; /* Flags - normal */
  SMB_TxWords[6]  = TRANSACT_TIMEOUT; /* Timeout LSW */
  SMB_TxWords[7]  = 0; /* Timeout MSW */
  SMB_TxWords[8]  = 0; /* Reserved */
  SMB_TxWords[9]  = pT->parms_in_len; /* Length this buffer */
  SMB_TxWords[10] = a;  /* Offset from SMB header to parm bytes */
  SMB_TxWords[11] = pT->data_in_len; /* Length this buffer */
  SMB_TxWords[12] = a + pT->parms_in_len;  /* Offset to data bytes */
  SMB_TxWords[13] = 0; /* Setup words being sent */

  pB = NULL;

  /* Make up data chain */

  if ( pT->data_in_len != 0 )
  {
    pB = AddChain ( pB, pT->data_in, pT->data_in_len );
    if ( pB == NULL )
      return EOUTOFMEM;
  }

  if ( pT->parms_in_len != 0 )
  {
    pB = AddChain ( pB, pT->parms_in, pT->parms_in_len );
    if ( pB == NULL )
      return EOUTOFMEM;
  }

  pB = AddChain ( pB, name, strlen(name)+1 );

  res = Do_SMB ( hS, SMBtransact, 14, pB, &pBres );

  if ( res != OK )
    return res;

  /* Now extract results */

  if ( SMB_RxWordCount < 10 )
  {
    FreeChain(pBres);
    return EDATALEN;
  }

  a = SMBHDR_SIZE + (SMB_RxWordCount)*2 + 2;
  /* Size of SMBHDR plus returned rx words plus byte count
     = offset of data in pBres from start of header */

  pT->parms_out_len = min(SMB_RxWords[3], pT->parms_out_maxlen);
                          /* Parm bytes being returned */
  pT->data_out_len  = min(SMB_RxWords[6], pT->data_out_maxlen);
                          /* Data bytes being returned */

  if ( pT->parms_out_len > 0 )         /* Get parms_out */
  {
    padbytes = SMB_RxWords[4] - a;     /* RxWords[4] is offset;
                                          Get number of pad bytes */

    if ( padbytes > 0 )
      pBres = GetData(pBres, NULL, padbytes);
    pBres = GetData(pBres, pT->parms_out_buf, pT->parms_out_len);
    a += padbytes + pT->parms_out_len; /* New offset value */
  }

  if ( pT->data_out_len > 0 )        /* Get parms_out */
  {
    padbytes = SMB_RxWords[7] - a;     /* Number of pad bytes */

    if ( padbytes > 0 )
      pBres = GetData(pBres, NULL, padbytes);
    pBres = GetData(pBres, pT->data_out_buf, pT->data_out_len);
  }

  if ( pBres == NULL )  /* Oh no! Techo fear! */
    return EDATALEN;

  FreeChain(pBres);
  return OK;
}

Stewart Brodie's avatar
Stewart Brodie committed
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
#ifdef LONGNAMES
/* 14 is the number of words common to all Transact2 commands.  The
 * number of setup words is then added to that value.  The 14 passed
 * to Do_SMB has the number of setup words added to it as this doubles
 * as the header length limiter and the pointer to where to write the
 * total data+param size field (what the Microsoft docs call smb_bcc).
 * This is why you cannot just AddChain the setup word blocks like the
 * data and parameters are handled.
 */
static err_t SMB_Transact2 ( hSHARE hS, struct TransactParms *pT )
{
  BUFCHAIN pB, pBres;
  err_t res;
  int iter = 0; /* Response iteration number */
  int a = SMBHDR_SIZE + ((14 + pT->setup_in_len)*2) + 2;
  int pda = ((a + 3) & ~3);
      /* SMB header size, 14 params + setup words + 2 byte data length
       */
  int   padbytes;    /* Temp variable */
  int   sc;
  int   retry = 3;
  int   tot_data_rcvd = 0, tot_param_rcvd = 0;

retry_transact2:
  debug2("SMB_Transact2: processing (Tid = %#04x, sub-cmd=%#04x)...\n", hS->Tid,
    pT->setup_in[0]);

  SMB_TxWords[0]  = pT->parms_in_len; /* Total length */
  SMB_TxWords[1]  = pT->data_in_len; /* Total length */
  SMB_TxWords[2]  = pT->parms_out_maxlen;
  SMB_TxWords[3]  = pT->data_out_maxlen;
  SMB_TxWords[4]  = 0; /* Setup words to return */
  SMB_TxWords[5]  = 0; /* Flags - normal */
  SMB_TxWords[6]  = TRANSACT2_TIMEOUT; /* Timeout LSW */
  SMB_TxWords[7]  = 0; /* Timeout MSW */
  SMB_TxWords[8]  = 0; /* Reserved */
  SMB_TxWords[9]  = pT->parms_in_len; /* Length this buffer */
  SMB_TxWords[10] = pda;  /* Offset from SMB header to parm bytes */
  SMB_TxWords[11] = pT->data_in_len; /* Length this buffer */
  SMB_TxWords[12] = pda + pT->parms_in_len;  /* Offset to data bytes */
  SMB_TxWords[13] = pT->setup_in_len; /* Setup words being sent */

  debug2("%d bytes of parameters at offset %#x\n", pT->parms_in_len, pda);
  debug2("%d bytes of data at offset %#x\n", pT->data_in_len, SMB_TxWords[12]);

  for (sc = 0; sc < pT->setup_in_len; ++sc)
    SMB_TxWords[14 + sc] = pT->setup_in[sc];

  pB = NULL;

  /* Make up data chain */

  if ( pT->data_in_len != 0 )
  {
    pB = AddChain ( pB, pT->data_in, pT->data_in_len );
    if ( pB == NULL )
      return EOUTOFMEM;
  }

  if ( pT->parms_in_len != 0 )
  {
    pB = AddChain ( pB, pT->parms_in, pT->parms_in_len );
    if ( pB == NULL )
      return EOUTOFMEM;
  }

  /* Add the null string - pda-a must be 1 or 3.  "D " added because
   * that's what SAMBA does (because that's what OS/2 does) */
  pB = AddChain ( pB, "\0D ", pda - a );
  if (pB == NULL )
    return EOUTOFMEM;

  res = Do_SMB ( hS, SMBtrans2, 14 + pT->setup_in_len, pB, &pBres );

  if ( res != OK ) {
    if (SMB_RxHdr.errclass == ERRSRV && SMB_RxHdr.errlo == 1 && SMB_RxHdr.errhi == 0 && retry)
    {
       --retry;
       debug0("SMB_Transact2: retrying request\n");
       goto retry_transact2;
    }
    debug0("SMB_Transact2: Do_SMB failed\n");
    DumpBuffer(&SMB_RxHdr, SMBHDR_SIZE);
    return res;
  }

  /* Now extract results - note that there may be 1 of these.  OTOH, there may be several
   * if the data didn't fit into the negotiated buffer sizes ... */
  for (iter = 0; ; ++iter) {

    if ( SMB_RxWordCount < 10 )
    {
      FreeChain(pBres);
      return EDATALEN;
    }

    a = SMBHDR_SIZE + (SMB_RxWordCount)*2 + 2;
    /* Size of SMBHDR plus returned rx words plus byte count
       = offset of data in pBres from start of header */

    if (iter == 0) {
      /* First response will tell us how much is coming */
      pT->parms_out_len = min(SMB_RxWords[0], pT->parms_out_maxlen);
                              /* Parm bytes being returned */
      pT->data_out_len  = min(SMB_RxWords[1], pT->data_out_maxlen);
                              /* Data bytes being returned */
      pT->setup_out_len = min(SMB_RxWords[9] & 0xFF, pT->setup_out_maxlen);

      /* setup words must come in the first packet */
      if (pT->setup_out_len > 0 )          /* Get setup_out */
      {
        memcpy(pT->setup_out, &SMB_RxWords[14], 2 * pT->setup_out_len);
      }
    }

    if ( pT->parms_out_len > 0 && SMB_RxWords[3])         /* Get parms_out */
    {
      padbytes = SMB_RxWords[4] - a;     /* RxWords[4] is offset;
                                            Get number of pad bytes */

      if ( padbytes > 0 )
        pBres = GetData(pBres, NULL, padbytes);
      pBres = GetData(pBres, pT->parms_out_buf + SMB_RxWords[5], SMB_RxWords[3]);
      a += padbytes + pT->parms_out_len; /* New offset value */
      tot_param_rcvd += SMB_RxWords[3];
    }

    if ( pT->data_out_len > 0 && SMB_RxWords[6] > 0)        /* Get data_out */
    {
      padbytes = SMB_RxWords[7] - a;     /* Number of pad bytes */
      if ( padbytes > 0 )
        pBres = GetData(pBres, NULL, padbytes);
      pBres = GetData(pBres, pT->data_out_buf + SMB_RxWords[8], SMB_RxWords[6]);
      tot_data_rcvd += SMB_RxWords[6];
      if (pT->setup_in[0] == TRANSACT2_QUERYPATHINFORMATION)
        DumpBuffer(pT->data_out_buf, pT->data_out_len);
    }

    if ( pBres == NULL ) {  /* Oh no! Techo fear! */
      debug0("SMB_Transact2: pBres was NULL\n");
      return EDATALEN;
    }

    FreeChain(pBres);

    if (tot_data_rcvd < pT->data_out_len || tot_param_rcvd < pT->parms_out_len) {
3078 3079 3080 3081 3082 3083

      do {
        /* MUST avoid recursive calls to Do_SMBResponse */
        res = Do_SMBResponse(hS, SMBtrans2, &pBres);
      } while (res == OK && SMB_RxHdr.command == SMBchkpth);

Stewart Brodie's avatar
Stewart Brodie committed
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
      if (res != OK)
        return res;
      /* Extract received data */
      debug1("Transact2 (2ndary response) - returned %d bytes\n", ChainLen(pBres));
    }
    else break;
  }

  return OK;
}
#endif

3096 3097
/* Utility routines ============================================ */

Ben Avison's avatar
Ben Avison committed
3098
static char *sharetype_name[4] = { "Disc", "Printer", "Comms", "IPC" };
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162

char *SMB_GetConnInfo ( char drvletter, int infotype )
{
  hSHARE hS = GetShareNoConn(drvletter);

  if ( hS == NULL )
    return NULL;

  switch ( infotype )
  {
    case GCI_SERVER:
      return hS->hServer->servname;

    case GCI_USER:
      if ( hS->hServer->ProtFlags & PROT_USERLOGON )
        return hS->hServer->username;
      else
        return "(none)";

    case GCI_SHARE:
      return hS->sharename;

    case GCI_LOGONTYPE:
      if ( hS->hServer->ProtFlags & PROT_USERLOGON )
        return "User";
      else
        return "Share";

    case GCI_SHARETYPE:
      return sharetype_name[ hS->sharetype ];

    case GCI_SERVERINFO:
      return NB_DescribeLink( hS->hServer->hSession );
  }

  return "";
}

/* Init routines ================================================ */

bool SMB_Init( void )
{
  int i;

  for ( i=0; i<MAX_SHARES; i++ )
  {
    SMB_Servers[i].flags = FREE;
  }

  for ( i=0; i<MAX_SHARES; i++ )
  {
    SMB_Shares[i].flags = FREE;
    SMB_Shares[i].drvletter = 'A' + i;
    SMB_Shares[i].FH_base = (i << 16);
  }

  SMB_TxHdr.id[0] = 0xFF;
  SMB_TxHdr.id[1] = 'S';
  SMB_TxHdr.id[2] = 'M';
  SMB_TxHdr.id[3] = 'B';

  SMB_TxHdr.mid = 0;  /* Multiplex ID: not used */
  SMB_TxHdr.pid = 1;  /* Process ID: dummy value */
  SMB_TxHdr.tid = 0;  /* Tree ID: set later */
Stewart Brodie's avatar
Stewart Brodie committed
3163 3164 3165 3166 3167 3168 3169 3170
#ifdef LONGNAMES
  SMB_TxHdr.flg2 = SMB_KNOWS_LONG_NAMES; /*| SMB_IS_LONG_NAME;*/
#else
  SMB_TxHdr.flg2 = 0;
#endif
#ifdef LONGNAMES
  NameCache_Init();
#endif
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
  return true;
}


/* ----------------------------------------- */

/* Shutdown will disconnect all logged-on drives */

err_t SMB_Shutdown ( void )
{
  int i;
  for ( i=0; i < MAX_SHARES; i++ )
    SMB_DeleteShare ( 'A'+i );

  return OK;
}

Stewart Brodie's avatar
Stewart Brodie committed
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205
/* ---------------------------- */

/* SMB_AntiIdle() is used to stop idle-outs on shares.
 * Each call, it moves onto the next share in order to
 * "ping" the server to keep it awake.
 */
void SMB_AntiIdle ( void )
{
  static uint letter = -1;
  hSHARE hS;

  ++letter;
  if (letter >= MAX_SHARES) letter = 0;
  hS = GetShareNoConn('A' + letter);
  if (hS == NULL) {
    return;
  }
  else {
Stewart Brodie's avatar
Stewart Brodie committed
3206 3207 3208 3209 3210
    time_t t;
    (void) time(&t);
    if (t > (hS->hServer->last_xact + 60 * 10)) {
      char echodat[sizeof("A:\\")];
      (void) sprintf(echodat, "%c:\\", 'A' + letter);
3211
      dprintf(("idle_1", "Anti idle-out measure: %s\n", echodat));
Stewart Brodie's avatar
Stewart Brodie committed
3212
      if (ELANMANFSINUSE == SMB_ChkPath(echodat)) {
3213
        dprintf(("idle_1", "Re-entrancy due to idle-out check prevented\n"));
Stewart Brodie's avatar
Stewart Brodie committed
3214 3215
      }
    }
Stewart Brodie's avatar
Stewart Brodie committed
3216 3217
  }
}