CoreFn 26.6 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 23 24 25 26 27 28 29 30
/* 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.
 */
/*
*   C.CoreFn -- C core functions for new filing system
*
*
*   28-02-94 INH Original, derived from FSinC
*   1997.04.21 INH  Don't pass time of 0 to SMB_Close, fixes W95 bug
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "kernel.h"
#include "swis.h"
#include "stdtypes.h"

31
#include "LanMan.h"
32
#include "Params.h"
33 34 35 36
#include "CoreFn.h"
#include "Xlate.h"
#include "Attr.h"
#include "SMB.h"
Stewart Brodie's avatar
Stewart Brodie committed
37 38 39
#include "Omni.h"
#include "Transact.h"
#include "NameCache.h"
40
#include "SMBFind.h"
41 42 43


#define NAMEBUF_LEN (2*DOS_NAME_LEN)
Ben Avison's avatar
Ben Avison committed
44
#define name_R(x) ((char *)R[x])
45

Ben Avison's avatar
Ben Avison committed
46
static char DOSnamebuf[NAMEBUF_LEN];
47 48
static err_t FileGetAttribs ( char *filename, DOS_ATTRIBS *pda,
    RISCOS_ATTRIBS *pra );
49

Ben Avison's avatar
Ben Avison committed
50
/* Read-directory subroutines ======================================= */
51 52
static int   RD_Reason;
static char *RD_BufPtr;
Stewart Brodie's avatar
Stewart Brodie committed
53
static int   RD_BufLen;
54
static int   RD_ReqCount;  /* No. of entries required */
Ben Avison's avatar
Ben Avison committed
55
static int   RD_CurCount;  /* No. of entries given */
56

Ben Avison's avatar
Ben Avison committed
57 58 59
/* Write one directory entry to the supplied buffer
 * The directory entries can take one of three forms, taking up
 * a variable degree of space
Stewart Brodie's avatar
Stewart Brodie committed
60 61
 */
static char *WriteEntry ( int reason, char *ptr, BYTE *entry, int format )
62
{
Stewart Brodie's avatar
Stewart Brodie committed
63 64
  static char namebuf[DOS_NAME_LEN];
  int name_len;
65 66 67 68 69
  int rec_len;
  DOS_ATTRIBS    da;
  RISCOS_ATTRIBS ra;
  int *IntPtr;

Stewart Brodie's avatar
Stewart Brodie committed
70
#ifndef LONGNAMES
Ben Avison's avatar
Ben Avison committed
71
  (void) format;
Stewart Brodie's avatar
Stewart Brodie committed
72 73 74 75 76 77 78 79 80
#else
  if (format == 1) {
    Xlt_ExpandSearchEntryX2(entry, DOSnamebuf, namebuf, &da, &ra);
  }
  else
#endif
    Xlt_ExpandSearchEntry(entry, DOSnamebuf, namebuf, &da, &ra);

  name_len = strlen(namebuf) + 1;
Ben Avison's avatar
Ben Avison committed
81
  debug1("WriteEntry (%s)\n", namebuf);
Stewart Brodie's avatar
Stewart Brodie committed
82

83 84
  switch ( reason )
  {
Ben Avison's avatar
Ben Avison committed
85
    case FSEntry_Func_Reason_ReadDirectoryEntries:
Stewart Brodie's avatar
Stewart Brodie committed
86 87 88 89
      rec_len = name_len;
      if (rec_len <= RD_BufLen) {
        memcpy(ptr, namebuf, name_len);
      }
90 91
      break;

Ben Avison's avatar
Ben Avison committed
92
    case FSEntry_Func_Reason_ReadDirectoriesAndInformation:
Stewart Brodie's avatar
Stewart Brodie committed
93 94 95 96 97 98 99 100 101 102
      rec_len = (20+name_len+3) & ~3;  /* Round up to whole word */
      if (rec_len <= RD_BufLen) {
        IntPtr = (int *)ptr;
        IntPtr[0] = ra.loadaddr;
        IntPtr[1] = ra.execaddr;
        IntPtr[2] = da.length;
        IntPtr[3] = ra.flags;
        IntPtr[4] = (da.attr & ATTR_DIR) ? 2 : 1;
        memcpy(ptr+20, namebuf, name_len);
      }
103 104
      break;

Ben Avison's avatar
Ben Avison committed
105
    case FSEntry_Func_Reason_ReadDirectoryEntriesAndInformation:
Stewart Brodie's avatar
Stewart Brodie committed
106 107 108 109 110 111 112 113 114 115 116 117 118
      rec_len = (29+name_len)+3 & ~3; /* Round up to whole word */
      if (rec_len <= RD_BufLen) {
        IntPtr = (int *)ptr;
        IntPtr[0] = ra.loadaddr;
        IntPtr[1] = ra.execaddr;
        IntPtr[2] = da.length;
        IntPtr[3] = ra.flags;
        IntPtr[4] = (da.attr & ATTR_DIR) ? 2 : 1;
        IntPtr[5] = 0;
        IntPtr[6] = ra.execaddr;
        ptr[28] = ra.loadaddr & 0xFF;
        memcpy(ptr+29, namebuf, name_len);
      }
119 120 121 122 123 124
      break;

    default:      /* Shouldn't get here */
      return ptr;
  }

Stewart Brodie's avatar
Stewart Brodie committed
125
  if (rec_len > RD_BufLen) {
Ben Avison's avatar
Ben Avison committed
126
    debug2("WriteEntry detects a buffer overflow (%d > %d)\n",
Stewart Brodie's avatar
Stewart Brodie committed
127
            rec_len, RD_BufLen);
Ben Avison's avatar
Ben Avison committed
128 129
    RD_BufLen = -1;
    return NULL;
Stewart Brodie's avatar
Stewart Brodie committed
130 131 132
  }

  RD_BufLen -= rec_len;
133 134 135 136 137
  return (ptr+rec_len);
}

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

Ben Avison's avatar
Ben Avison committed
138
static err_t Dir_CallbackFn ( BYTE *entry, int format, bool *taken, void *pw )
139 140
{
  (void) pw;
141 142 143

  *taken = false;

Stewart Brodie's avatar
Stewart Brodie committed
144 145 146
#ifdef LONGNAMES
  /* Insert check for . and .. here */
  if (format == 1) {
Stewart Brodie's avatar
Stewart Brodie committed
147 148 149 150 151 152 153 154
    if (entry[23] == '.') {
      if (entry[22] == 1 || entry[24] == '\0') {
        return OK;
      }
      if (entry[24] == '.' && (entry[22] == 2 || entry[25] == '\0')) {
        return OK;
      }
    }
Stewart Brodie's avatar
Stewart Brodie committed
155 156 157
  }
  else
#endif
Stewart Brodie's avatar
Stewart Brodie committed
158 159
  if ( entry[9] == '.' ) {
    /* Ignore '.' and '..' directories */
Stewart Brodie's avatar
Stewart Brodie committed
160
    if (entry[10] == '.' && entry[11] == '\0' || entry[10] == '\0') {
Stewart Brodie's avatar
Stewart Brodie committed
161 162 163
      return OK;
    }
  }
164

165
  if ( RD_ReqCount > 0 ) {
Ben Avison's avatar
Ben Avison committed
166 167 168 169 170 171 172 173 174 175
    char *w_result = WriteEntry ( RD_Reason, RD_BufPtr, entry, format );
    if (w_result != NULL) {
      RD_BufPtr = w_result;
      RD_ReqCount--;
      RD_CurCount++;
      *taken = true;
    }
    else {
      debug0("Oh dear - client ran out of buffer space!\n");
      return EOUTOFMEM;
176 177 178
    }
  }

Stewart Brodie's avatar
Stewart Brodie committed
179
  return OK;
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 221 222 223 224 225 226 227 228 229 230 231
#ifdef LONGNAMES
static err_t Func_ReadDir1 ( int reason, char *path_name, char *buffer,
       int n_names, int dir_offset, int buflen, int *pOutNread,
       int *pOutNextOffset )
{
  static SMBFind_t smbfind;
  err_t  res;

  RD_Reason = reason;
  RD_BufPtr = buffer;
  RD_BufLen = buflen;
  RD_CurCount = 0;
  RD_ReqCount = n_names;

  res = OK;
  while ( dir_offset != -1 &&
          res == OK  &&     /* More names available */
          RD_ReqCount > 0 ) /* More names wanted */
  {
    res = SMBFind_EnumDir(&smbfind, dir_offset, path_name, RD_ReqCount, Dir_CallbackFn, NULL, &dir_offset);
  }

  /* Process results */
  if (res == EOUTOFMEM && RD_BufLen == -1 && RD_CurCount > 0)
  {
    /* Special result when client buffer space exhausted */
    res = OK;
  }

  if ( res != OK )
  {
    /* Ran out of files, or error */
    *pOutNextOffset = -1;
  }
  else
    *pOutNextOffset = dir_offset;

  *pOutNread = RD_CurCount;

  if ( res == ENOMOREFILES )
    return OK;

  return res;
}
#endif

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

Ben Avison's avatar
Ben Avison committed
232 233 234 235 236 237 238
/* Called in 2 situations
 *   - starting a search from scratch (dir_offset = 0)
 *   - continuing a search (dir_offset != 0)
 * The underlying SMB routine must track whether it has been called
 * recursively or from within Xlt_NameROtoDOSX2_sub and deal with
 * abandoning searches appropriately.
 */
239 240 241 242
static err_t Func_ReadDir ( int reason, char *path_name, char *buffer,
       int n_names, int dir_offset, int buflen, int *pOutNread,
       int *pOutNextOffset )
{
Ben Avison's avatar
Ben Avison committed
243 244 245
  static Transact_SearchContext con;
  int    one_name;
  err_t  res;
246

Stewart Brodie's avatar
Stewart Brodie committed
247
  debug2 ( "\n\n>> ReadDir reason %d path %s", reason, path_name );
Ben Avison's avatar
Ben Avison committed
248 249
  debug2 ( " offset %d count %d", dir_offset, n_names );
  debug1 ( " buflen %d\n", buflen);
250

Ben Avison's avatar
Ben Avison committed
251 252 253
  /* Make sure the number of names we read will fit into buffer */
  one_name = (reason == FSEntry_Func_Reason_ReadDirectoryEntries) ? 16 :
             (reason == FSEntry_Func_Reason_ReadDirectoriesAndInformation) ? 36 : 44;
254

Stewart Brodie's avatar
Stewart Brodie committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
#ifdef LONGNAMES
  /* Of course, the above calculation assumes that the filename is at most
   * 16 characters long (8 + '.' + 3 + \0 + 3 bytes pad).  This is
   * useless for long filename shares and so the n_names parameter is
   * accepted in place, and the buffer writer updated to be able to
   * avoid and flag buffer overflow.  In the worst case, this may mean
   * multiple searches are required, however, as long as the directory
   * reading function SMB_ReadDirEntriesX2 is intelligent, it can remember
   * the resume keys and last successful filename data for the search and
   * attempt to keep our caller in step with the remote server.
   *
   * The limit is still performed as it is still useful for avoiding
   * unnecessary buffer overruns - especially when there are not very
   * many files with long names or even no files with long names.
   */
#endif
Ben Avison's avatar
Ben Avison committed
271
  if ( (n_names * one_name) > buflen ) n_names = buflen/one_name;
272
  if ( n_names <= 0 ) return EBADPARAM;
Ben Avison's avatar
Ben Avison committed
273
  debug1( "Adjusted count=%d\n", n_names );
274 275
  RD_Reason = reason;
  RD_BufPtr = buffer;
Stewart Brodie's avatar
Stewart Brodie committed
276
  RD_BufLen = buflen;
Ben Avison's avatar
Ben Avison committed
277
  RD_CurCount = 0;
278 279 280 281 282
  RD_ReqCount = n_names;

  /* Convert path adding wildcard search spec */
  res = Xlt_ConvertPath( path_name, DOSnamebuf );
  if ( res != OK ) return res;
Ben Avison's avatar
Ben Avison committed
283 284
  if ( DOSnamebuf[strlen( DOSnamebuf ) - 1] != '\\' )
    strcat( DOSnamebuf, "\\");
Stewart Brodie's avatar
Stewart Brodie committed
285
#ifdef LONGNAMES
Ben Avison's avatar
Ben Avison committed
286
  strcat( DOSnamebuf, "*" );
Stewart Brodie's avatar
Stewart Brodie committed
287
#else
Ben Avison's avatar
Ben Avison committed
288
  strcat( DOSnamebuf, "????????.???" );
Stewart Brodie's avatar
Stewart Brodie committed
289
#endif
290

Ben Avison's avatar
Ben Avison committed
291 292
  /* Start a new search? */
  if (dir_offset == 0)
293
  {
Ben Avison's avatar
Ben Avison committed
294 295 296 297
    debug2( ">> Start search (%s) count %d\n", DOSnamebuf, RD_ReqCount);
    con.resume_key = 0;
    res = SMB_ReadDirEntries ( DOSnamebuf, RD_ReqCount,
                               Dir_CallbackFn, NULL, &con );
298
  }
Ben Avison's avatar
Ben Avison committed
299 300
  else {
    con.resume_key = dir_offset;
301
    res = OK;
Ben Avison's avatar
Ben Avison committed
302
  }
303 304 305 306 307

  /* Continue search, if needs be */
  while ( res == OK  &&     /* More names available */
          RD_ReqCount > 0 ) /* More names wanted */
  {
Ben Avison's avatar
Ben Avison committed
308 309 310
    debug3( ">> Continue search (%s) count %d resume %08x\n", DOSnamebuf, RD_ReqCount, con.resume_key);
    res = SMB_ReadDirEntries ( DOSnamebuf, RD_ReqCount,
                               Dir_CallbackFn, NULL, &con );
311 312 313
  }

  /* Process results */
Stewart Brodie's avatar
Stewart Brodie committed
314 315 316 317 318 319
  if (res == EOUTOFMEM && RD_BufLen == -1) {
    /* Special result when client buffer space exhausted */
    debug0("Client buffer space was exhausted\n");
    res = OK;
  }
  debug2("End search, res=%d RD_ReqCount=%d\n", res, RD_ReqCount);
320

Ben Avison's avatar
Ben Avison committed
321
  if ( res != OK ) {  /* Ran out of files, or error */
322 323 324
    *pOutNextOffset = -1;
  }
  else
Ben Avison's avatar
Ben Avison committed
325
    *pOutNextOffset = con.resume_key;
326

Ben Avison's avatar
Ben Avison committed
327
  *pOutNread = RD_CurCount;
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
  if ( res == ENOMOREFILES )
    return OK;

  return res;
}

/* Func ============================================================= */

_kernel_oserror *fsentry_func ( int *R )
{
  err_t err;

  debug1("FS_func(%d)", R[0] );

  switch ( R[0] )
  {
    case FSEntry_Func_Reason_SetCurrentDirectory:
      /* Although we don't maintain a current directory,
         we use this to keep track of the current drive */

      err = Xlt_ConvertPath( name_R(1), DOSnamebuf);
      if ( err == OK ) Xlt_SetDefaultDrv ( DOSnamebuf );
      break;

    case FSEntry_Func_Reason_SetLibraryDirectory:
    case FSEntry_Func_Reason_CatalogueDirectory:
    case FSEntry_Func_Reason_ExamineCurrentDirectory:
    case FSEntry_Func_Reason_CatalogueLibraryDirectory:
    case FSEntry_Func_Reason_ExamineLibraryDirectory:
    case FSEntry_Func_Reason_ExamineObjects:
    case FSEntry_Func_Reason_ReadCurrentDirectoryNameAndPrivilegeByte:
    case FSEntry_Func_Reason_ReadLibraryDirectoryNameAndPrivilegeByte:
    case FSEntry_Func_Reason_SetDirectoryContexts:
    case FSEntry_Func_Reason_AccessObjects:
    case FSEntry_Func_Reason_OutputFullInformationOnObjects:
      err = ENORISCOS2;
      break;

    case FSEntry_Func_Reason_RenameObject:
      err = Xlt_ConvertPath( name_R(1), DOSnamebuf);
368
      if ( err == OK ) err = Xlt_ConvertPath( name_R(2), DOSnamebuf+DOS_NAME_LEN );
Stewart Brodie's avatar
Stewart Brodie committed
369 370
#ifdef LONGNAMES
      {
371 372 373 374 375 376 377 378 379 380 381
        DOS_ATTRIBS    da;
        RISCOS_ATTRIBS ra;

        err = FileGetAttribs ( DOSnamebuf, &da, &ra );
        if ( err == EFILENOTFOUND || err == EPATHNOTFOUND )
        {
          err = OK;
        }

        if ( err == OK )
        {
382 383 384 385 386 387
          /* Trim any RO extension and append the ones from the source instead */
          Xlt_RemoveROType ( DOSnamebuf + DOS_NAME_LEN );
          if ((da.attr & ATTR_DIR) == 0)
          {
            Xlt_AddROType ( DOSnamebuf + DOS_NAME_LEN, ra.loadaddr );
          }
388
        }
Stewart Brodie's avatar
Stewart Brodie committed
389 390
      }
#endif
391 392
      if ( err == OK )
      {
393
        err = SMB_Rename ( DOSnamebuf, DOSnamebuf+DOS_NAME_LEN );
394
      }
395

Stewart Brodie's avatar
Stewart Brodie committed
396
#ifdef LONGNAMES
397 398
      if (SMB_IsLongNameFS(DOSnamebuf + DOS_NAME_LEN))
      {
Stewart Brodie's avatar
Stewart Brodie committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412
         if ( err == EBADRENAME )
         {
           R[1] = 1;
           err = OK;
         }
         else
         {
           R[1] = 0;
         }
         break;
      }
      /* Don't bother with any of this rubbish for long filename discs */
#endif

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
      if ( err == OK )  /* If rename worked, swap attribs */
      {
        RISCOS_ATTRIBS ra;
        ra.loadaddr = 0xFFF00000;
        ra.execaddr = 0;
        ra.flags = ROA_READ | ROA_WRITE;
        if ( Attr_GetInfo ( DOSnamebuf, NULL, &ra ) == OK )
        {
          Attr_DeleteInfo ( DOSnamebuf );
          Attr_SetInfo ( DOSnamebuf + DOS_NAME_LEN, &ra );
        }
        R[1] = 0;
      }
      else if ( err == EBADRENAME )
      {
        R[1] = 1; /* Indicate failure */
        err = OK;
      }
      break;

    case FSEntry_Func_Reason_SetFilingSystemOptions:
    case FSEntry_Func_Reason_ReadNameAndBootOptionOfDisc:
      err = ENOTPRESENT;
      break;

    /* SNB 980225.  Must identify and boot on request from OS! */
    case FSEntry_Func_Reason_PrintStartUpBanner:
      (void) _swix(OS_Write0, _IN(0), "Acorn LanManFS\n\r");
      err = OK;
      break;

    case FSEntry_Func_Reason_BootFilingSystem:
      LM_Boot();
      err = OK;
      break;

    case FSEntry_Func_Reason_ShutDown:
Ben Avison's avatar
Ben Avison committed
450 451 452
      /* On shutdown, disconnect all drives */
      err = SMB_Shutdown();
      break;
453 454 455 456

    case FSEntry_Func_Reason_ReadDirectoryEntries:
    case FSEntry_Func_Reason_ReadDirectoriesAndInformation:
    case FSEntry_Func_Reason_ReadDirectoryEntriesAndInformation:
457 458 459 460
#ifdef LONGNAMES
      err = Func_ReadDir1 ( R[0], name_R(1), name_R(2),
               R[3], R[4], R[5], &R[3], &R[4] );
#else
461 462
      err = Func_ReadDir ( R[0], name_R(1), name_R(2),
               R[3], R[4], R[5], &R[3], &R[4] );
463
#endif
Stewart Brodie's avatar
Stewart Brodie committed
464 465
      break;

466 467 468 469 470
    default:
      err = EBADPARAM;
      break;
  }

Stewart Brodie's avatar
Stewart Brodie committed
471
#ifdef LONGNAMES
472
  NameCache_Flush(ncf_FSFUNC_EXIT);
Stewart Brodie's avatar
Stewart Brodie committed
473 474
#endif

Robert Sprowson's avatar
Robert Sprowson committed
475
  return MsgError(err);
476 477 478 479 480 481 482 483 484 485
}


/* File  =================================================== */

static err_t FileGetAttribs ( char *filename, DOS_ATTRIBS *pda,
    RISCOS_ATTRIBS *pra )
{
  err_t err;

Stewart Brodie's avatar
Stewart Brodie committed
486
  debug1("FileGetAttribs(%s) ... \n", filename);
487 488 489 490
  err = SMB_GetAttribs ( filename, pda );
  if ( err == OK )
  {
    Xlt_CnvDOStoRO ( pda, pra, CNV_DATETIME | CNV_ATTRIBS );
Stewart Brodie's avatar
Stewart Brodie committed
491
    Attr_GetInfo ( filename, NULL, pra );
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
  }
  return err;
}

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

_kernel_oserror *fsentry_file( int *R )
{
  err_t err;
  int FH;
  int tmp;
  DOS_ATTRIBS    da;
  RISCOS_ATTRIBS ra;

  debug1("FS_file(%d)", R[0] );

  err = Xlt_ConvertPath ( name_R(1), DOSnamebuf );

  /* This is a bodge to stop cmd-line 'copies' with wildcards
     not working! */

  if ( err == ENOWILDCARD  &&
       (R[0] == FSEntry_File_Reason_ReadCatalogueInformationNoLength ||
        R[0] == FSEntry_File_Reason_ReadCatalogueInformation )
     )
  {
    R[0] = 0;
Robert Sprowson's avatar
Robert Sprowson committed
519
    return MsgError(OK);
520 521 522
  }

  if ( err != OK )
Robert Sprowson's avatar
Robert Sprowson committed
523
    return MsgError(err);
524 525 526 527 528 529 530 531 532

  switch ( R[0] )
  {
    case FSEntry_File_Reason_CreateFile:
    case FSEntry_File_Reason_SaveFile:
      ra.loadaddr = R[2];
      ra.execaddr = R[3];
      ra.flags    = ROA_READ | ROA_WRITE;
      Xlt_CnvROtoDOS(&ra, &da, CNV_DATETIME | CNV_ATTRIBS );
Stewart Brodie's avatar
Stewart Brodie committed
533 534 535 536 537 538 539 540 541 542 543
#ifdef LONGNAMES
      strncpy(DOSnamebuf + DOS_NAME_LEN, DOSnamebuf, DOS_NAME_LEN);
      if (Xlt_AddROType(DOSnamebuf, ra.loadaddr)) {
        /* We changed the filetype - therefore delete old file */
        err = SMB_Delete(DOSnamebuf + DOS_NAME_LEN);
        if (err != OK && err != EFILENOTFOUND) {
           /* Oh dear - looks likely the create would fail anyway! */
           break;
        }
      }
#endif
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

      err = SMB_Create ( DOSnamebuf, &da, &FH );
      if ( err == OK )
      {
        if ( R[0] == FSEntry_File_Reason_SaveFile )
        {
          err = SMB_Write ( FH, 0, /* Offset */
                            R[5]-R[4], /* Len */
                   (BYTE *)(R[4]),     /* Where */
                            NULL );
        }
        else if ( R[0] == FSEntry_File_Reason_CreateFile )
        {
          err = SMB_Truncate ( FH, R[5]-R[4] );
        }
        SMB_Close ( FH, &da );

        Attr_SetInfo ( DOSnamebuf, &ra );
      }

      R[6] = (int) Xlt_GetRISCOSLeafName(name_R(1));
      break;

    case FSEntry_File_Reason_LoadFile:
      err = SMB_Open ( MODE_RD, DOSnamebuf, &da, &FH, &tmp );

      if ( err == OK )
      {
        err = SMB_Read ( FH, 0, da.length, (BYTE *)(R[2]), NULL );
        SMB_Close ( FH, &da);

        Xlt_CnvDOStoRO( &da, &ra, CNV_DATETIME | CNV_ATTRIBS );
        Attr_GetInfo ( DOSnamebuf, NULL, &ra );
        R[2] = ra.loadaddr;
        R[3] = ra.execaddr;
        R[4] = da.length;
        R[5] = ra.flags;
      }

      R[6] = (int) Xlt_GetRISCOSLeafName(name_R(1));
      break;


    /* Read/write file attribute calls ------------------- */

    case FSEntry_File_Reason_WriteLoadAddress:
    case FSEntry_File_Reason_WriteExecutionAddress:
    case FSEntry_File_Reason_WriteAttributes:
      /* Get current attributes */
      err = FileGetAttribs ( DOSnamebuf, &da, &ra );
      if ( err == EFILENOTFOUND || err == EPATHNOTFOUND )
      {
        err = OK;
        break;
      }

      if ( R[0] == FSEntry_File_Reason_WriteLoadAddress )
      {
        ra.loadaddr = R[2];
        Xlt_CnvROtoDOS ( &ra, &da, CNV_DATETIME );
Stewart Brodie's avatar
Stewart Brodie committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617
#ifdef LONGNAMES
      {
        if (da.attr & ATTR_DIR)
                ;
        else {
          strncpy(DOSnamebuf + DOS_NAME_LEN, DOSnamebuf, DOS_NAME_LEN);
          if (Xlt_AddROType(DOSnamebuf + DOS_NAME_LEN, ra.loadaddr)) {
            err = SMB_Rename(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
            if (err != OK) break;
            strcpy(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
          }
        }
      }
#endif
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
      }
      else if ( R[0] == FSEntry_File_Reason_WriteExecutionAddress )
      {
        ra.execaddr = R[3];
        Xlt_CnvROtoDOS ( &ra, &da, CNV_DATETIME );
      }
      else if ( R[0] == FSEntry_File_Reason_WriteAttributes )
      {
        ra.flags = R[5];
        Xlt_CnvROtoDOS ( &ra, &da, CNV_ATTRIBS );
      }

      Attr_SetInfo ( DOSnamebuf, &ra );
      err = SMB_SetAttribs ( DOSnamebuf, &da );
      break;

    case FSEntry_File_Reason_WriteCatalogueInformation:
      ra.loadaddr = R[2];
      ra.execaddr = R[3];
      ra.flags = R[5];

Stewart Brodie's avatar
Stewart Brodie committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
#ifdef LONGNAMES
      {
        RISCOS_ATTRIBS test_ra;
        err = FileGetAttribs ( DOSnamebuf, &da, &test_ra );
        if (err == OK && (da.attr & ATTR_DIR))
                ;
        else {
          strncpy(DOSnamebuf + DOS_NAME_LEN, DOSnamebuf, DOS_NAME_LEN);
          if (Xlt_AddROType(DOSnamebuf + DOS_NAME_LEN, ra.loadaddr)) {
            err = SMB_Rename(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
            if (err != OK) break;
            strcpy(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
          }
        }
      }
#endif

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
      Xlt_CnvROtoDOS ( &ra, &da, CNV_ATTRIBS | CNV_DATETIME );
      Attr_SetInfo ( DOSnamebuf, &ra );
      err = SMB_SetAttribs ( DOSnamebuf, &da );
      break;

    case FSEntry_File_Reason_DeleteObject:
      err = FileGetAttribs ( DOSnamebuf, &da, &ra );
      if ( err == OK )
      {
        R[2] = ra.loadaddr;
        R[3] = ra.execaddr;
        R[4] = da.length;
        R[5] = ra.flags;

        if ( da.attr & ATTR_DIR )
        {
          R[0] = 2;
          Attr_CheckEmptyDir ( DOSnamebuf );
          err = SMB_RmDir ( DOSnamebuf );
        }
        else
        {
          R[0] = 1;
          err = SMB_Delete ( DOSnamebuf );
        }

        if ( err==OK )
          Attr_DeleteInfo ( DOSnamebuf );
      }
      break;

    case FSEntry_File_Reason_CreateDirectory:
688 689 690
#ifdef LONGNAMES
      Xlt_RemoveROType ( DOSnamebuf );
#endif
Ben Avison's avatar
Ben Avison committed
691
      err = SMB_MkDir ( DOSnamebuf );
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
      break;

    /* Read information calls ---------------------------- */

    case FSEntry_File_Reason_ReadCatalogueInformationNoLength:
    case FSEntry_File_Reason_ReadCatalogueInformation:
      err = FileGetAttribs ( DOSnamebuf, &da, &ra );
      if ( err == OK )
      {
        if ( da.attr & ATTR_DIR )
          R[0] = 2;
        else
          R[0] = 1;

        R[2] = ra.loadaddr;
        R[3] = ra.execaddr;
        R[4] = da.length;
        R[5] = ra.flags;
      }
      else if ( err == EFILENOTFOUND || err == EPATHNOTFOUND )
      {
        R[0] = 0;
        err = OK;
      }
      break;

    default:
      err = EBADPARAM;
      break;
  }

Stewart Brodie's avatar
Stewart Brodie committed
723
#ifdef LONGNAMES
724
  NameCache_Flush(ncf_FSFILE_EXIT);
Stewart Brodie's avatar
Stewart Brodie committed
725 726
#endif

Robert Sprowson's avatar
Robert Sprowson committed
727
  return MsgError(err);
728 729 730 731 732 733 734 735 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
}

/* Open/Close subroutines --------------------------------------- */

#define MAXFILES 30

static struct FileInfo
{
  bool Free;        /* -1 indicates this file not in use */
  int SMB_FH;       /* File handle for SMB use */

  DOS_ATTRIBS da;
  int filesw_id;    /* Fileswitch handle for the file */

}
  FileTbl[MAXFILES];

static int NextHandle;

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

static int NewHandle(void)
{
  int i;

  if ( NextHandle >= MAXFILES ) NextHandle = 0;

  if ( FileTbl[NextHandle].Free )
    return NextHandle++;

  for ( i=0; i<MAXFILES; i++)
  {
    if (FileTbl[i].Free)
    {
      NextHandle=i+1;
      return i;
    }
  }

  return -1;
}


/* Open  =================================================== */

_kernel_oserror *fsentry_open( int *R )
{
  err_t err;
  int fid;
  int modes=0;
  struct FileInfo *pFI;
  RISCOS_ATTRIBS ra;

  debug1("FS_open(%d)", R[0]);

  /* Convert to DOS name & allocate handle */

  err = Xlt_ConvertPath ( name_R(1), DOSnamebuf );

  if ( err != OK )
Robert Sprowson's avatar
Robert Sprowson committed
788
    return MsgError(err);
789 790 791

  fid = NewHandle();
  if ( fid < 0 )
Robert Sprowson's avatar
Robert Sprowson committed
792
    return MsgError(ENOHANDLES);
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 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

  pFI = &FileTbl[fid];
  pFI->filesw_id = R[3];

  switch ( R[0]  )
  {
    case FSEntry_Open_Reason_OpenRead:
      err = SMB_Open ( MODE_RD, DOSnamebuf,
            &pFI->da, &pFI->SMB_FH, &modes );
      break;

    case FSEntry_Open_Reason_Update:
      err = SMB_Open ( MODE_RDWR, DOSnamebuf,
              &pFI->da, &pFI->SMB_FH, &modes );

      if ( err == ENOACCESS )
      {
        err = SMB_Open ( MODE_RD, DOSnamebuf,
                &pFI->da, &pFI->SMB_FH, &modes );
      }

      break;

    case FSEntry_Open_Reason_CreateUpdate:
      ra.execaddr = 0;  /* Not called by RISCOS 3?? */
      ra.loadaddr = 0;  /* If so, should be the current time */
      ra.flags  = ROA_READ | ROA_WRITE;
      Xlt_CnvROtoDOS ( &ra, &pFI->da, CNV_DATETIME | CNV_ATTRIBS );
      err = SMB_Create ( DOSnamebuf, &pFI->da, &pFI->SMB_FH );
      pFI->da.length = 0;
      modes = MODE_RDWR;
      break;

    default:
      err = EBADPARAM;
      break;

  }

  if ( err == OK )
  {
    pFI -> Free = false;
    R[0] = (modes == MODE_RD ) ? OPEN_Readable :
           (modes == MODE_RDWR ) ? OPEN_Readable | OPEN_Writable :
           (modes == MODE_WR ) ? OPEN_Writable : 0;

    R[1] = fid+1;
    R[2] = 512; /* Buffer size - doesn't really matter */
    R[3] = pFI->da.length;
    R[4] = (R[3] + 511) & ~511;

  }
  else
Stewart Brodie's avatar
Stewart Brodie committed
846
  {
847
    R[1] = 0;
Stewart Brodie's avatar
Stewart Brodie committed
848 849 850 851 852
#ifdef LONGNAMES
    /* Take a risk to enhance cacheing :-) */
    NameCache_Flush(ncf_FSOPEN_EXIT);
#endif
  }
Robert Sprowson's avatar
Robert Sprowson committed
853
  return MsgError(err);
854 855 856 857 858 859 860 861 862
}

/* GetBytes  =================================================== */

_kernel_oserror *fsentry_getbytes( int *R )
{
  int fid = R[1]-1;

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
Robert Sprowson's avatar
Robert Sprowson committed
863
    return MsgError(EBADPARAM);
864

Robert Sprowson's avatar
Robert Sprowson committed
865
  return MsgError( SMB_Read (FileTbl[fid].SMB_FH,
866 867 868 869 870 871 872 873 874 875 876 877 878 879
                      R[4],      /* Offset */
                      R[3],      /* Length */
             (BYTE *)(R[2]),     /* Where */
                      NULL ) );

}

/* PutBytes  =================================================== */

_kernel_oserror *fsentry_putbytes( int *R )
{
  int fid = R[1]-1;

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
Robert Sprowson's avatar
Robert Sprowson committed
880
    return MsgError(EBADPARAM);
881

Robert Sprowson's avatar
Robert Sprowson committed
882
  return MsgError ( SMB_Write (FileTbl[fid].SMB_FH,
883 884 885 886 887 888 889 890 891 892 893
                      R[4],      /* Offset */
                      R[3],      /* Length */
             (BYTE *)(R[2]),     /* Where */
                      NULL ) );
}

/* GBPB  =================================================== */

_kernel_oserror *fsentry_gbpb( int *R )
{
  (void)R;
Robert Sprowson's avatar
Robert Sprowson committed
894
  return MsgError(ENOGBPB);
895 896 897 898 899 900 901 902 903 904 905 906
}

/* Close  =================================================== */

_kernel_oserror *fsentry_close( int *R )
{
  err_t err;
  RISCOS_ATTRIBS ra;

  int fid = R[1]-1;

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
Robert Sprowson's avatar
Robert Sprowson committed
907
    return MsgError(EBADPARAM);
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922

  /* On entry, R2/R3 contain new timestamp for file.
     This call will be unable to alter the file-type as
     recorded by Attr_SetInfo: we don't know the file name */

  if ( R[2] != 0 || R[3] != 0 )
  {
    /* IH: Windows 95 doesn't recognise a NULL timestamp field. */
    ra.loadaddr = R[2];
    ra.execaddr = R[3];
    Xlt_CnvROtoDOS ( &ra, &FileTbl[fid].da, CNV_DATETIME );
  }

  err=SMB_Close( FileTbl[fid].SMB_FH, &FileTbl[fid].da);
  FileTbl[fid].Free = true;
Robert Sprowson's avatar
Robert Sprowson committed
923
  return MsgError(err);
924 925 926 927
}

/* Args ========================================== */

928
static err_t WriteZeros ( int FH, uint offset, uint len )
929
{
930
  uint  tmp;
931 932 933 934 935 936
  err_t res=OK;

  memset ( DOSnamebuf, 0, NAMEBUF_LEN );

  while ( len > 0 )
  {
937 938
#if 0
    tmp = min(NAMEBUF_LEN, len);
939
    res = SMB_Write ( FH, offset, tmp, (BYTE *)DOSnamebuf, NULL );
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
#else
    /* SMB_Write uses the write bytes command (v1-spec-02 section 5.22)
     * which states that any bytes between the previous EOF and the new
     * one are filled to zero by the server - so don't waste time
     * sending them over the network. However, very large extends can
     * end up with a timeout, so the extend is chopped up a bit assuming
     * the server can write at least 1MB/s to the disc.
     * SMB_Truncate pends all the zero filling which leads to a timeout
     * when closing the file, so we just write 1 byte of 0 each jump.
     */
    tmp = min(1024 * 1024 * (REPLY_TIMEOUT / 100), len);
    if ( offset == 0 )
      res = SMB_Write ( FH, 0, 1, (BYTE *)DOSnamebuf, NULL );
    else
      res = SMB_Write ( FH, offset - 1, 1, (BYTE *)DOSnamebuf, NULL );
#endif
956 957 958 959 960 961 962 963 964 965 966 967 968
    if ( res != OK ) break;
    offset += tmp;
    len -= tmp;
  }
  return res;
}

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

_kernel_oserror *fsentry_args( int *R )
{
  err_t err=OK;
  int fid = R[1]-1;
969
  uint tmp;
970 971 972 973

  debug1("FS_args(%d)\n", R[0]);

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
Robert Sprowson's avatar
Robert Sprowson committed
974
    return MsgError(EBADPARAM);
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006

  switch( R[0] )
  {
    case FSEntry_Args_Reason_ReadSequentialFilePointer:
    case FSEntry_Args_Reason_WriteSequentialFilePointer:
    case FSEntry_Args_Reason_ReadFileExtent:
    case FSEntry_Args_Reason_EOFCheck:
      err = ENOUNBUFF;
      break;

    case FSEntry_Args_Reason_WriteFileExtent:
      err = SMB_Truncate ( FileTbl[fid].SMB_FH, R[2] );
      break;

    /* We ignore this call - WriteFileExtent is used to truncate */

    case FSEntry_Args_Reason_EnsureFileSize:
      err = OK;
      break;

    case FSEntry_Args_Reason_ReadSizeAllocatedToFile:
      err = SMB_GetLength ( FileTbl[fid].SMB_FH, &tmp );
      if ( err == OK )
        R[2] = tmp;
      break;

    case FSEntry_Args_Reason_FlushFileBuffer:
      err = SMB_Flush ( FileTbl[fid].SMB_FH );
      break;

    case FSEntry_Args_Reason_WriteZerosToFile:
      err = WriteZeros ( FileTbl[fid].SMB_FH,
1007 1008
                         (uint)R[2], /* Offset */
                         (uint)R[3]  /* Length */  );
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
      break;

    case FSEntry_Args_Reason_ReadFileDateStamp:
      {
        /* This call will be unable to correctly get the file type */
        /* If this is needed, it must be done when the file is opened */
        RISCOS_ATTRIBS ra;
        Xlt_CnvDOStoRO ( &FileTbl[fid].da, &ra, CNV_DATETIME );

        R[2] = ra.loadaddr;
        R[3] = ra.execaddr;
      }
      err = OK;
      break;

    default:
      err = EBADPARAM;
      break;
  }

Robert Sprowson's avatar
Robert Sprowson committed
1029
  return MsgError(err);
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
}

/* Init --------------------------------- */

bool FS_Init(void)
{
  int i;
  for ( i=0; i<MAXFILES; i++ )
    FileTbl[i].Free = true;
  NextHandle = 0;
Ben Avison's avatar
Ben Avison committed
1040

1041 1042 1043
  return true;
}