CoreFn 26.9 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
#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;

192 193 194 195 196 197 198 199
  if (n_names == 0 || dir_offset == -1 || buffer == NULL || buflen <= 0)
  {
    *pOutNread = 0;
    *pOutNextOffset = -1;
    return OK;
  }
  if ((unsigned int) n_names > 0xfffd) n_names = 0xfffd;   /* limit large n_names to unsigned short - ensure adding 2 doesn't overflow */

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 232 233 234 235 236 237 238 239
  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
240 241 242 243 244 245 246
/* 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.
 */
247 248 249 250
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
251 252 253
  static Transact_SearchContext con;
  int    one_name;
  err_t  res;
254

Stewart Brodie's avatar
Stewart Brodie committed
255
  debug2 ( "\n\n>> ReadDir reason %d path %s", reason, path_name );
Ben Avison's avatar
Ben Avison committed
256 257
  debug2 ( " offset %d count %d", dir_offset, n_names );
  debug1 ( " buflen %d\n", buflen);
258

Ben Avison's avatar
Ben Avison committed
259 260 261
  /* 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;
262

Stewart Brodie's avatar
Stewart Brodie committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
#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
279
  if ( (n_names * one_name) > buflen ) n_names = buflen/one_name;
280
  if ( n_names <= 0 ) return EBADPARAM;
Ben Avison's avatar
Ben Avison committed
281
  debug1( "Adjusted count=%d\n", n_names );
282 283
  RD_Reason = reason;
  RD_BufPtr = buffer;
Stewart Brodie's avatar
Stewart Brodie committed
284
  RD_BufLen = buflen;
Ben Avison's avatar
Ben Avison committed
285
  RD_CurCount = 0;
286 287 288 289 290
  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
291 292
  if ( DOSnamebuf[strlen( DOSnamebuf ) - 1] != '\\' )
    strcat( DOSnamebuf, "\\");
Stewart Brodie's avatar
Stewart Brodie committed
293
#ifdef LONGNAMES
Ben Avison's avatar
Ben Avison committed
294
  strcat( DOSnamebuf, "*" );
Stewart Brodie's avatar
Stewart Brodie committed
295
#else
Ben Avison's avatar
Ben Avison committed
296
  strcat( DOSnamebuf, "????????.???" );
Stewart Brodie's avatar
Stewart Brodie committed
297
#endif
298

Ben Avison's avatar
Ben Avison committed
299 300
  /* Start a new search? */
  if (dir_offset == 0)
301
  {
Ben Avison's avatar
Ben Avison committed
302 303 304 305
    debug2( ">> Start search (%s) count %d\n", DOSnamebuf, RD_ReqCount);
    con.resume_key = 0;
    res = SMB_ReadDirEntries ( DOSnamebuf, RD_ReqCount,
                               Dir_CallbackFn, NULL, &con );
306
  }
Ben Avison's avatar
Ben Avison committed
307 308
  else {
    con.resume_key = dir_offset;
309
    res = OK;
Ben Avison's avatar
Ben Avison committed
310
  }
311 312 313 314 315

  /* Continue search, if needs be */
  while ( res == OK  &&     /* More names available */
          RD_ReqCount > 0 ) /* More names wanted */
  {
Ben Avison's avatar
Ben Avison committed
316 317 318
    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 );
319 320 321
  }

  /* Process results */
Stewart Brodie's avatar
Stewart Brodie committed
322 323 324 325 326 327
  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);
328

Ben Avison's avatar
Ben Avison committed
329
  if ( res != OK ) {  /* Ran out of files, or error */
330 331 332
    *pOutNextOffset = -1;
  }
  else
Ben Avison's avatar
Ben Avison committed
333
    *pOutNextOffset = con.resume_key;
334

Ben Avison's avatar
Ben Avison committed
335
  *pOutNread = RD_CurCount;
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 368 369 370 371 372 373 374 375
  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);
376
      if ( err == OK ) err = Xlt_ConvertPath( name_R(2), DOSnamebuf+DOS_NAME_LEN );
Stewart Brodie's avatar
Stewart Brodie committed
377 378
#ifdef LONGNAMES
      {
379 380 381 382 383 384 385 386 387 388 389
        DOS_ATTRIBS    da;
        RISCOS_ATTRIBS ra;

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

        if ( err == OK )
        {
390 391 392 393
          /* Trim any RO extension and append the ones from the source instead */
          Xlt_RemoveROType ( DOSnamebuf + DOS_NAME_LEN );
          if ((da.attr & ATTR_DIR) == 0)
          {
394
            Xlt_AddROType ( DOSnamebuf + DOS_NAME_LEN, ra.loadaddr, ra.execaddr );
395
          }
396
        }
Stewart Brodie's avatar
Stewart Brodie committed
397 398
      }
#endif
399 400
      if ( err == OK )
      {
401
        err = SMB_Rename ( DOSnamebuf, DOSnamebuf+DOS_NAME_LEN );
402
      }
403

Stewart Brodie's avatar
Stewart Brodie committed
404
#ifdef LONGNAMES
405 406
      if (SMB_IsLongNameFS(DOSnamebuf + DOS_NAME_LEN))
      {
Stewart Brodie's avatar
Stewart Brodie committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420
         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

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 450 451 452 453 454 455 456 457
      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
458 459 460
      /* On shutdown, disconnect all drives */
      err = SMB_Shutdown();
      break;
461 462 463 464

    case FSEntry_Func_Reason_ReadDirectoryEntries:
    case FSEntry_Func_Reason_ReadDirectoriesAndInformation:
    case FSEntry_Func_Reason_ReadDirectoryEntriesAndInformation:
465 466 467 468
#ifdef LONGNAMES
      err = Func_ReadDir1 ( R[0], name_R(1), name_R(2),
               R[3], R[4], R[5], &R[3], &R[4] );
#else
469 470
      err = Func_ReadDir ( R[0], name_R(1), name_R(2),
               R[3], R[4], R[5], &R[3], &R[4] );
471
#endif
Stewart Brodie's avatar
Stewart Brodie committed
472 473
      break;

474 475 476 477 478
    default:
      err = EBADPARAM;
      break;
  }

Stewart Brodie's avatar
Stewart Brodie committed
479
#ifdef LONGNAMES
480
  NameCache_Flush(ncf_FSFUNC_EXIT);
Stewart Brodie's avatar
Stewart Brodie committed
481 482
#endif

Robert Sprowson's avatar
Robert Sprowson committed
483
  return MsgError(err);
484 485 486 487 488 489 490 491 492 493
}


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

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

Stewart Brodie's avatar
Stewart Brodie committed
494
  debug1("FileGetAttribs(%s) ... \n", filename);
495 496 497 498
  err = SMB_GetAttribs ( filename, pda );
  if ( err == OK )
  {
    Xlt_CnvDOStoRO ( pda, pra, CNV_DATETIME | CNV_ATTRIBS );
Stewart Brodie's avatar
Stewart Brodie committed
499
    Attr_GetInfo ( filename, NULL, pra );
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
  }
  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
527
    return MsgError(OK);
528 529 530
  }

  if ( err != OK )
Robert Sprowson's avatar
Robert Sprowson committed
531
    return MsgError(err);
532 533 534 535 536 537 538 539 540

  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
541 542
#ifdef LONGNAMES
      strncpy(DOSnamebuf + DOS_NAME_LEN, DOSnamebuf, DOS_NAME_LEN);
543
      if (Xlt_AddROType(DOSnamebuf, ra.loadaddr, ra.execaddr)) {
Stewart Brodie's avatar
Stewart Brodie committed
544 545 546 547 548 549 550 551
        /* 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
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 604 605 606 607 608 609 610 611

      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
612 613 614 615 616 617
#ifdef LONGNAMES
      {
        if (da.attr & ATTR_DIR)
                ;
        else {
          strncpy(DOSnamebuf + DOS_NAME_LEN, DOSnamebuf, DOS_NAME_LEN);
618
          if (Xlt_AddROType(DOSnamebuf + DOS_NAME_LEN, ra.loadaddr, ra.execaddr)) {
Stewart Brodie's avatar
Stewart Brodie committed
619 620 621 622 623 624 625
            err = SMB_Rename(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
            if (err != OK) break;
            strcpy(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
          }
        }
      }
#endif
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
      }
      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
647 648 649 650 651 652 653 654
#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);
655
          if (Xlt_AddROType(DOSnamebuf + DOS_NAME_LEN, ra.loadaddr, ra.execaddr)) {
Stewart Brodie's avatar
Stewart Brodie committed
656 657 658 659 660 661 662 663
            err = SMB_Rename(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
            if (err != OK) break;
            strcpy(DOSnamebuf, DOSnamebuf + DOS_NAME_LEN);
          }
        }
      }
#endif

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
      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:
696 697 698
#ifdef LONGNAMES
      Xlt_RemoveROType ( DOSnamebuf );
#endif
Ben Avison's avatar
Ben Avison committed
699
      err = SMB_MkDir ( DOSnamebuf );
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
      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
731
#ifdef LONGNAMES
732
  NameCache_Flush(ncf_FSFILE_EXIT);
Stewart Brodie's avatar
Stewart Brodie committed
733 734
#endif

Robert Sprowson's avatar
Robert Sprowson committed
735
  return MsgError(err);
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
}

/* 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
796
    return MsgError(err);
797 798 799

  fid = NewHandle();
  if ( fid < 0 )
Robert Sprowson's avatar
Robert Sprowson committed
800
    return MsgError(ENOHANDLES);
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 846 847 848 849 850 851 852 853

  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
854
  {
855
    R[1] = 0;
Stewart Brodie's avatar
Stewart Brodie committed
856 857 858 859 860
#ifdef LONGNAMES
    /* Take a risk to enhance cacheing :-) */
    NameCache_Flush(ncf_FSOPEN_EXIT);
#endif
  }
Robert Sprowson's avatar
Robert Sprowson committed
861
  return MsgError(err);
862 863 864 865 866 867 868 869 870
}

/* 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
871
    return MsgError(EBADPARAM);
872

Robert Sprowson's avatar
Robert Sprowson committed
873
  return MsgError( SMB_Read (FileTbl[fid].SMB_FH,
874 875 876 877 878 879 880 881 882 883 884 885 886 887
                      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
888
    return MsgError(EBADPARAM);
889

Robert Sprowson's avatar
Robert Sprowson committed
890
  return MsgError ( SMB_Write (FileTbl[fid].SMB_FH,
891 892 893 894 895 896 897 898 899 900 901
                      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
902
  return MsgError(ENOGBPB);
903 904 905 906 907 908 909 910 911 912 913 914
}

/* 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
915
    return MsgError(EBADPARAM);
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

  /* 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
931
  return MsgError(err);
932 933 934 935
}

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

936
static err_t WriteZeros ( int FH, uint offset, uint len )
937
{
938
  uint  tmp;
939 940 941 942 943 944
  err_t res=OK;

  memset ( DOSnamebuf, 0, NAMEBUF_LEN );

  while ( len > 0 )
  {
945 946
#if 0
    tmp = min(NAMEBUF_LEN, len);
947
    res = SMB_Write ( FH, offset, tmp, (BYTE *)DOSnamebuf, NULL );
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
#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
964 965 966 967 968 969 970 971 972 973 974 975 976
    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;
977
  uint tmp;
978 979 980 981

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

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
Robert Sprowson's avatar
Robert Sprowson committed
982
    return MsgError(EBADPARAM);
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

  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,
1015 1016
                         (uint)R[2], /* Offset */
                         (uint)R[3]  /* Length */  );
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
      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
1037
  return MsgError(err);
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
}

/* 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
1048

1049 1050 1051
  return true;
}