CoreFn 26.4 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 31 32 33 34 35 36
/* 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"

#include "lanman.h"
#include "Params.h"
#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 41 42 43 44 45 46 47


/* Some globals ================================== */

#define NAMEBUF_LEN (2*DOS_NAME_LEN)


static char DOSnamebuf  [NAMEBUF_LEN];
48 49
static err_t FileGetAttribs ( char *filename, DOS_ATTRIBS *pda,
    RISCOS_ATTRIBS *pra );
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

#define name_R(x) ((char *)R[x])



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

#define NAMES_ONLY 14
#define MOST_INFO  15
#define ALL_INFO   19

/* Read-directory subroutines --------- */

/* The directory entries can take one of three forms, taking up
   a variable degree of space

   NAMES_ONLY - 16 bytes (12 bytes of name, plus 0 terminator, plus
                          word rounding).
   MOST_INFO  - 36 bytes
   ALL_INFO   - 44 bytes

*/

static char  RD_CurrentPath[DOS_NAME_LEN];
static int   RD_Reason;
static char *RD_BufPtr;
Stewart Brodie's avatar
Stewart Brodie committed
76
static int   RD_BufLen;
77 78 79 80 81 82 83 84

static int   RD_ReqCount;  /* No. of entries required */
static int   RD_ReqOffset; /* Offset of currently required dir entry */
static int   RD_CurOffset; /* Offset of next entry to be given to
                                Dir_CallbackFn */

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

Stewart Brodie's avatar
Stewart Brodie committed
85 86 87 88 89 90
/* SNB: the blocks being written are those required by:
 *    NAMES_ONLY =>  OS_GBPB 9   =>  (FSEntry_Func 14)
 *    MOST_INFO  =>  OS_GBPB 10  =>  (FSEntry_Func 15)
 *    ALL_INFO   =>  OS_GBPB 11  =>  (FSEntry_Func 19)
 */
static char *WriteEntry ( int reason, char *ptr, BYTE *entry, int format )
91
{
Stewart Brodie's avatar
Stewart Brodie committed
92 93
  static char namebuf[DOS_NAME_LEN];
  int name_len;
94 95 96 97 98
  int rec_len;
  DOS_ATTRIBS    da;
  RISCOS_ATTRIBS ra;
  int *IntPtr;

Stewart Brodie's avatar
Stewart Brodie committed
99 100 101 102 103 104 105 106 107 108 109 110
#ifndef LONGNAMES
    (void) format;
#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;

111 112 113
  switch ( reason )
  {
    case NAMES_ONLY:
Stewart Brodie's avatar
Stewart Brodie committed
114 115 116 117
      rec_len = name_len;
      if (rec_len <= RD_BufLen) {
        memcpy(ptr, namebuf, name_len);
      }
118 119 120
      break;

    case MOST_INFO:
Stewart Brodie's avatar
Stewart Brodie committed
121 122 123 124 125 126 127 128 129 130
      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);
      }
131 132 133
      break;

    case ALL_INFO:
Stewart Brodie's avatar
Stewart Brodie committed
134 135 136 137 138 139 140 141 142 143 144 145 146
      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);
      }
147 148 149 150 151 152
      break;

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

Stewart Brodie's avatar
Stewart Brodie committed
153 154 155 156 157 158 159 160
  if (rec_len > RD_BufLen) {
          debug2("WriteEntry detects a buffer overflow (%d > %d)\n",
            rec_len, RD_BufLen);
          RD_BufLen = -1;
          return NULL;
  }

  RD_BufLen -= rec_len;
161 162 163 164 165
  return (ptr+rec_len);
}

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

Stewart Brodie's avatar
Stewart Brodie committed
166
static err_t Dir_CallbackFn ( BYTE *entry, int format, void *pw )
167 168
{
  (void) pw;
Stewart Brodie's avatar
Stewart Brodie committed
169 170 171
#ifdef LONGNAMES
  /* Insert check for . and .. here */
  if (format == 1) {
Stewart Brodie's avatar
Stewart Brodie committed
172 173 174 175 176 177 178 179
    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
180 181 182
  }
  else
#endif
Stewart Brodie's avatar
Stewart Brodie committed
183 184
  if ( entry[9] == '.' ) {
    /* Ignore '.' and '..' directories */
Stewart Brodie's avatar
Stewart Brodie committed
185
    if (entry[10] == '.' && entry[11] == '\0' || entry[10] == '\0') {
Stewart Brodie's avatar
Stewart Brodie committed
186 187 188
      return OK;
    }
  }
189

Stewart Brodie's avatar
Stewart Brodie committed
190 191
//  debug3 ("Entry: current %d req %d count %d\n",
//            RD_CurOffset, RD_ReqOffset, RD_ReqCount );
192 193 194 195 196

  if ( RD_ReqOffset == RD_CurOffset )
  {
    if ( RD_ReqCount > 0 )
    {
Stewart Brodie's avatar
Stewart Brodie committed
197 198 199 200 201 202 203 204 205 206 207
      char *w_result = WriteEntry ( RD_Reason, RD_BufPtr, entry, format );
      if (w_result != NULL) {
        RD_BufPtr = w_result;
        RD_ReqCount--;
        RD_ReqOffset++;
      }
      else {
        debug0("Oh dear - client ran out of buffer space!\n");
        RD_CurOffset++;
        return EOUTOFMEM;
      }
208 209 210 211
    }
  }

  RD_CurOffset++;
Stewart Brodie's avatar
Stewart Brodie committed
212
  return OK;
213 214 215 216 217 218 219 220
}

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

static err_t Func_ReadDir ( int reason, char *path_name, char *buffer,
       int n_names, int dir_offset, int buflen, int *pOutNread,
       int *pOutNextOffset )
{
Stewart Brodie's avatar
Stewart Brodie committed
221
  static Transact_SearchContext scon;
222 223 224
  int tmp;
  err_t res;

Stewart Brodie's avatar
Stewart Brodie committed
225
  debug2 ( "\n\n>> ReadDir reason %d path %s", reason, path_name );
226 227 228 229 230 231 232
  debug2 ( " offset %d count %d\n", dir_offset, n_names );

  /* Make sure the number of names we read will fit into buffer ---- */

  tmp = (reason == NAMES_ONLY) ? 16 :
        (reason == MOST_INFO) ? 36 : 44;

Stewart Brodie's avatar
Stewart Brodie committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
#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.
   */

  /* There is no code inside this #ifdef - it just marks my comment. */
#endif
251 252 253 254 255
  if ( n_names*tmp > buflen ) n_names = buflen/tmp;
  if ( n_names <= 0 ) return EBADPARAM;

  RD_Reason = reason;
  RD_BufPtr = buffer;
Stewart Brodie's avatar
Stewart Brodie committed
256
  RD_BufLen = buflen;
257 258 259
  RD_ReqCount = n_names;
  RD_ReqOffset = dir_offset;

Stewart Brodie's avatar
Stewart Brodie committed
260
  debug1("Actual count=%d\n", n_names );
261 262 263 264 265 266 267

  /* Convert path adding wildcard search spec */

  res = Xlt_ConvertPath( path_name, DOSnamebuf );
  if ( res != OK ) return res;

  tmp = strlen(DOSnamebuf);
Stewart Brodie's avatar
Stewart Brodie committed
268 269 270 271 272 273
#ifdef LONGNAMES
  if ( DOSnamebuf[tmp-1] == '\\' )
    strcpy( DOSnamebuf+tmp, "*" );
  else
    strcpy( DOSnamebuf+tmp, "\\*" );
#else
274 275 276 277
  if ( DOSnamebuf[tmp-1] == '\\' )
    strcpy( DOSnamebuf+tmp, "????????.???" );
  else
    strcpy( DOSnamebuf+tmp, "\\????????.???" );
Stewart Brodie's avatar
Stewart Brodie committed
278
#endif
279 280 281 282 283 284 285 286

  /* Start a new search? ----------------------------------- */


  if ( RD_ReqOffset == 0 || /* New start */
       RD_ReqOffset < RD_CurOffset || /* Going back in search */
       strcmp(DOSnamebuf, RD_CurrentPath) != 0 ) /* New directory */
  {
Stewart Brodie's avatar
Stewart Brodie committed
287
    debug1("\n>> Start search (%s)\n", DOSnamebuf);
288 289 290
    strcpy ( RD_CurrentPath, DOSnamebuf);
    RD_CurOffset = 0;
    res = SMB_ReadDirEntries ( DOSnamebuf, RD_ReqCount+RD_ReqOffset,
Stewart Brodie's avatar
Stewart Brodie committed
291
                                      Dir_CallbackFn, NULL, &scon );
292 293 294 295 296 297 298 299 300
  }
  else
    res = OK;

  /* Continue search, if needs be */

  while ( res == OK  &&     /* More names available */
          RD_ReqCount > 0 ) /* More names wanted */
  {
Stewart Brodie's avatar
Stewart Brodie committed
301
    debug0("\n>> Continue search\n");
302
    res = SMB_ReadDirEntries ( NULL, RD_ReqCount+RD_ReqOffset-RD_CurOffset,
Stewart Brodie's avatar
Stewart Brodie committed
303
                                      Dir_CallbackFn, NULL, &scon );
304 305 306 307
  }

  /* Process results */

Stewart Brodie's avatar
Stewart Brodie committed
308 309 310 311 312 313 314
  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);
315 316 317 318 319 320 321 322

  if ( res != OK )   /* Ran out of files, or error */
  {
    RD_CurrentPath[0] = 0;  /* Stop any repeat searches */
    *pOutNextOffset = -1;
  }
  else
  {
Stewart Brodie's avatar
Stewart Brodie committed
323 324 325 326 327 328 329 330 331
    if (RD_BufLen < 0) {
      /* OK - was out of buffer space, force restart */
      *pOutNextOffset = RD_ReqOffset;
      //RD_CurOffset = 0;
      //RD_CurrentPath[0] = 0;
    }
    else {
      *pOutNextOffset = RD_ReqOffset;
    }
332 333 334 335 336 337 338 339 340 341
  }

  *pOutNread = RD_ReqOffset-dir_offset;

  if ( res == ENOMOREFILES )
    return OK;

  return res;
}

Stewart Brodie's avatar
Stewart Brodie committed
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
static err_t Func_ReadFreeSpace ( int sixtyfourbit, char *name, int *R )
{
  _kernel_swi_regs r;
  _kernel_oserror *err;
  struct disk_size_response dsr;

  r.r[0] = 2;
  r.r[2] = (int) &dsr;
  r.r[3] = (int) name;
  err = Omni_FreeOp_SWI(&r);
  if (err != NULL)
    return ENOTPRESENT;

  R[0] = dsr.freeblks;
  if (sixtyfourbit) {
    R[1] = R[4] = 0;
    R[2] = 0x7FFFFFFF;
    R[3] = dsr.totalblks;
  }
  else {
    R[1] = 0x7FFFFFFF;
    R[2] = dsr.totalblks;
  }

  return OK;
}

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
/* 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);
      if ( err == OK )
        err = Xlt_ConvertPath( name_R(2), DOSnamebuf+DOS_NAME_LEN );
Stewart Brodie's avatar
Stewart Brodie committed
405 406
#ifdef LONGNAMES
      {
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
        DOS_ATTRIBS    da;
        RISCOS_ATTRIBS ra;

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

        if ( err == OK )
        {
          (void) Xlt_CnvRenameX2 ( DOSnamebuf, DOSnamebuf + DOS_NAME_LEN );
        }
        if (da.attr & ATTR_DIR)     // force strip RO extent from dir name
        {
          Xlt_CnvRenameX2 ( DOSnamebuf+DOS_NAME_LEN,DOSnamebuf+DOS_NAME_LEN);
        }
Stewart Brodie's avatar
Stewart Brodie committed
424 425
      }
#endif
426 427 428
      if ( err == OK )
        err = SMB_Rename ( DOSnamebuf, DOSnamebuf+DOS_NAME_LEN );

Stewart Brodie's avatar
Stewart Brodie committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
#ifdef LONGNAMES
      if (SMB_IsLongNameFS(DOSnamebuf + DOS_NAME_LEN)) {
         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

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
      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:
       /* On shutdown, disconnect all drives */
       err = SMB_Shutdown();
       break;

    case FSEntry_Func_Reason_ReadDirectoryEntries:
    case FSEntry_Func_Reason_ReadDirectoriesAndInformation:
    case FSEntry_Func_Reason_ReadDirectoryEntriesAndInformation:
      err = Func_ReadDir ( R[0], name_R(1), name_R(2),
               R[3], R[4], R[5], &R[3], &R[4] );
        break;

Stewart Brodie's avatar
Stewart Brodie committed
493 494 495 496 497 498 499 500 501 502 503 504 505
    case FSEntry_Func_Reason_ResolveWildcard:
      /* Tell FileSwitch to do it itself */
      R[4] = -1;
      err = OK;
      break;

    case FSEntry_Func_Reason_ReadFreeSpace:
      err = Func_ReadFreeSpace ( 0, name_R(1), R );
        break;
    case FSEntry_Func_Reason_ReadFreeSpace64:
      err = Func_ReadFreeSpace ( 1, name_R(1), R );
        break;

506 507 508 509 510
    default:
      err = EBADPARAM;
      break;
  }

Stewart Brodie's avatar
Stewart Brodie committed
511 512 513 514
#ifdef LONGNAMES
  NameCache_Flush(ncf_FSFUNC_EXIT);
#endif

515 516 517 518 519 520 521 522 523 524 525
  return Xlt_Error(err);
}


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

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

Stewart Brodie's avatar
Stewart Brodie committed
526
  debug1("FileGetAttribs(%s) ... \n", filename);
527 528 529 530
  err = SMB_GetAttribs ( filename, pda );
  if ( err == OK )
  {
    Xlt_CnvDOStoRO ( pda, pra, CNV_DATETIME | CNV_ATTRIBS );
Stewart Brodie's avatar
Stewart Brodie committed
531
    Attr_GetInfo ( filename, NULL, pra );
532 533 534 535 536 537 538 539 540 541 542 543 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
  }
  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;
    return Xlt_Error(OK);
  }

  if ( err != OK )
    return Xlt_Error(err);

  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
573 574 575 576 577 578 579 580 581 582 583
#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
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 612 613 614 615 616 617 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

      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
644 645 646 647 648 649 650 651 652 653 654 655 656 657
#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
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
      }
      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
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
#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

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 723 724 725 726 727
      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:
Ben Avison's avatar
Ben Avison committed
728 729
     Xlt_CnvRenameX2 ( DOSnamebuf, DOSnamebuf );
     err = SMB_MkDir ( DOSnamebuf );
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
      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
761 762 763 764
#ifdef LONGNAMES
  NameCache_Flush(ncf_FSFILE_EXIT);
#endif

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 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 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
  return Xlt_Error(err);
}

/* 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 )
    return Xlt_Error(err);

  fid = NewHandle();
  if ( fid < 0 )
    return Xlt_Error(ENOHANDLES);

  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
884
  {
885
    R[1] = 0;
Stewart Brodie's avatar
Stewart Brodie committed
886 887 888 889 890
#ifdef LONGNAMES
    /* Take a risk to enhance cacheing :-) */
    NameCache_Flush(ncf_FSOPEN_EXIT);
#endif
  }
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 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 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
  return Xlt_Error(err);
}

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

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

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
    return Xlt_Error(EBADPARAM);

  return Xlt_Error( SMB_Read (FileTbl[fid].SMB_FH,
                      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 )
    return Xlt_Error(EBADPARAM);

  return Xlt_Error ( SMB_Write (FileTbl[fid].SMB_FH,
                      R[4],      /* Offset */
                      R[3],      /* Length */
             (BYTE *)(R[2]),     /* Where */
                      NULL ) );
}

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

_kernel_oserror *fsentry_gbpb( int *R )
{
  (void)R;
  return Xlt_Error(ENOGBPB);
}

/* 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 )
    return Xlt_Error(EBADPARAM);

  /* 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;
  return Xlt_Error(err);
}

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

static err_t WriteZeros ( int FH, int offset, int len )
{
  int tmp;
  err_t res=OK;

  memset ( DOSnamebuf, 0, NAMEBUF_LEN );

  while ( len > 0 )
  {
    tmp = (len > NAMEBUF_LEN) ? NAMEBUF_LEN : len;
    res = SMB_Write ( FH, offset, tmp, (BYTE *)DOSnamebuf, NULL );
    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;
  int tmp;

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

  if ( fid < 0 || fid >= MAXFILES || FileTbl[fid].Free )
    return Xlt_Error(EBADPARAM);

  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,
                          R[2], /* Offset */
                          R[3]  /* Length */  );
      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;
  }

  return Xlt_Error(err);
}

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

bool FS_Init(void)
{
  int i;
  for ( i=0; i<MAXFILES; i++ )
    FileTbl[i].Free = true;
  NextHandle = 0;
  return true;
}