rmtaccessserver.c 15.7 KB
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 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 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 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 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
/*
 * Copyright (C) 1996-1998 by the Board of Trustees
 *    of Leland Stanford Junior University.
 * 
 * This file is part of the SimOS distribution. 
 * See LICENSE file for terms of the license. 
 *
 */

/* 
 * rmtacessserver.c
 *
 *   Support remote access to Simos files.
 * 
 */
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <signal.h>
#include <pwd.h>
#include <setjmp.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
#include <strings.h>
#include <varargs.h>
#include <stropts.h>
#include <poll.h>
#include <search.h>
#include <memory.h>
#include <stdlib.h>
#include <unistd.h>

/* machine specific includes */
#ifdef sgi
#include <bstring.h>
#else
#include <sys/resource.h>
#endif

#include "simtypes.h"

#if 0
#include "syslimits.h"
#endif

/*
 * "obvious" defines needed for correct inclusion
 */

#include "devices/controllers/rmtaccess.h"
#include "devices/controllers/hd.h"


#define MAX_PATH_LENGTH 128

static int readforsure(int fd, char *buf, int size);

void ERRCmd(int fd, int err);
void ACKCmd (int fd);
int CopyFile(int infd, int outfd);
int CopySizedFile(int infd, int outfd, int size);
int DiskInit(char *args);

/*
 * Buffer to hold the current disk request 
 */
char curPacket[sizeof(NetDiskHdr) + NETDISK_MAX_REQUEST_SIZE];
char argbuf[16*1024];

int verbose = 0;
static char *source = "Unknown";


#ifndef  SIM_DISK_DEV_MAX_UNIT
/*
 * gross hack. bugnion
 */
#define SIM_DISK_DEV_MAX_UNIT 128
#define SIM_DISK_DEV_MAX_CTRL 128
#endif


static DiskFileInfo diskInfo[NETDISK_MAX_DISKS];
#define CU2DISK(c,u) (c*SIM_DISK_DEV_MAX_UNIT + u)

char hostname[MAX_PATH_LENGTH];
char cwd[MAX_PATH_LENGTH];

/*
 * Forward routine declartions.
 */
int serviceRequest(int, char *);
int ProcessDiskRequest(int fd);
int64 DoDiskRequest(int op, int ctrl, int unit, 
                  int64 sectorNum, int64 sizeInBytes, char *buffer);
static void childdone(int sig);

/*
 *----------------------------------------------------------------------
 *
 * main -- 
 *
 *    Main routine and loop for remote checkpoint access
 *
 * Results:
 *   Only returns if an error occurs.
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
    int	new_s, errflg;
    struct sockaddr_in addr;
    int	simfd;	
    int port, num;
    extern char *optarg;
    extern int optind;


    while ((num = getopt(argc, argv, "vs:")) != EOF) {
        switch (num) {
        case 'v': {
            verbose++;
            break;

        }
        default:
            goto usage;
        }
    }
    num = argc - optind;
    if ((num < 1) || (num > 2)) {
      usage:
        fprintf(stderr, "usage: %s [-v] Port [CheckPointDir]\n", argv[0]);
        exit(1);
    }
    port = atoi(argv[optind]);
    if ((port < 1000) || (port > 0xffff)) {
        fprintf(stderr, "Bad port number %s\n", argv[optind]);
        goto usage;
    }

    if (num == 2) {
        if (chdir(argv[optind+1]) < 0) { 
            perror(argv[optind+1]);
            goto usage;
        }
    } 
    if (verbose) {
        getwd(argbuf);
        printf("Remote access enabled\nDirectory: %s\nPort: %d\n",
               argbuf, port);
        fflush(stdout);
    }
    simfd = -1;
    errflg = 0;

    /*
     * Create the socket that recieves requests. 
     * The mostly likely
     * cause of failure is another netdisk running causing the bind
     * to fail with address in use.
     */

    simfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (simfd < 0) {
        perror("main: socket");
        exit(1);
    }

    bzero((char *)&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons((short)port);
    if (bind(simfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        perror("main: bind");
        exit(2);
    }

    if (listen(simfd, 4) < 0) {
        perror("main:listen");
        exit(2);
    } 

    if (sigset(SIGCLD, childdone) == (void(*)())-1) {
       perror("sigset");
       exit(1);
    }

    /*
     * Loop waiting for packets to arrive.
     */
    while(1) { 
        struct sockaddr from;
        int pid;
        int fromlen = sizeof (from);

        /* must accept connection from TCP */
        fromlen = sizeof(from);
        if((new_s = accept(simfd, &from, &fromlen)) < 0) {
            if (errno == EINTR)
                continue;
            perror("main:accept");
            exit(1);
        }
        pid = fork();
        if (pid < 0) {
            perror("main:fork");
            exit(1);
        }
        if (pid == 0) {
            close(simfd);
            if (verbose) {
                static char buf[256];
                struct sockaddr_in *inet_from = (struct sockaddr_in *) &from;
                sprintf(buf, "%s:%d", inet_ntoa(inet_from->sin_addr), 
                        inet_from->sin_port);
                source = buf;
            }
            serviceRequest(new_s, source);
            exit(1);
        }
        close(new_s);
    }

    exit(0);
}


/*
 *----------------------------------------------------------------------
 *
 * serviceRequest -- 
 *
 * Service a request that arrives at the simulated ethernet port.
 *
 * Results:
 *   -1 if problem occur with
 *
 * Side effects:
 *
 *----------------------------------------------------------------------
 */
int
serviceRequest(int fd, char *from)
{
    int	  n;
    RmtAccessStartRequest  req;

    if (verbose) {
       printf("Processing request from %s...\n", from);
    }
    n = readforsure(fd, (char *) &req, sizeof(req));
    if (n != sizeof(req)) { 
        perror("serviceRequest -- read");
        if (verbose) printf("  Request from %s exiting\n", from);
        exit(1);
    }
    if (req.magic != RMTACCESS_MAGIC) {
        fprintf(stderr, "  Bad magic number in req\n");
        if (verbose) printf("  Request from %s exiting\n", from);
        exit(1);
    }
    if ((unsigned)req.arglen > sizeof(argbuf)-1) {
        fprintf(stderr, "  Arg buffer too large %d\n", req.arglen);
        req.arglen = sizeof(argbuf);
    }
    if (req.arglen > 0) { 
        n = readforsure(fd, argbuf, req.arglen);
        if (n != req.arglen) {
            fprintf(stderr, "  Can't read arg buffer\n");
            if (verbose) printf("  Request from %s exiting\n", from);
            exit(1);
        }
    }  

    switch (req.cmd) {
    case SIMRMT_ACCESS: {
      argbuf[req.arglen] = 0;  /* Null terminate */
     
      if (argbuf[0] == '/' || (argbuf[0] =='.' && argbuf[1] =='.')) { 
        fprintf(stderr, "  Security error. Can't open %s\n", argbuf);
        if (verbose) printf("  Request from %s exiting\n", from);
        ERRCmd(fd, errno);
        exit(1);
      }
      if (verbose) printf("  access(%s, R_OK) = %d\n", argbuf, access(argbuf, R_OK));
      if (access(argbuf, R_OK) == 0)
        ACKCmd(fd);
      else
        ERRCmd(fd, errno);
      if (verbose) printf("  Request from %s exiting\n", from);
      exit(1);
    }
    case SIMRMT_OPEN: {
        int file_fd;
        argbuf[req.arglen] = 0;  /* Null terminate */
        if (argbuf[0] == '/' || (argbuf[0] =='.' && argbuf[1] =='.')) { 
            fprintf(stderr, "  Security error. Can't open %s\n", argbuf);
            if (verbose) printf("  Request from %s exiting\n", from);
            ERRCmd(fd, errno);
            exit(1);
        }
        file_fd = open(argbuf, O_RDONLY);
        if (file_fd < 0) {
            perror("serviceRequest -- open");
            fprintf(stderr, "  Can't open file %s\n", argbuf);
            if (verbose) printf("  Request from %s exiting\n", from);
            ERRCmd(fd,errno);
            exit(1);
        }
        if (verbose) 
            printf("  OPEN(%s)\n", argbuf);
        ACKCmd(fd);
        if (verbose) printf("  Sending file %s....", argbuf);
        fflush(stdout);
        (void) CopyFile(file_fd,fd);
        if (verbose) printf("Done.\n");
        if (verbose) printf("  Request from %s exiting\n", from);
        exit(0);
    }
    case SIMRMT_DISKINIT: {
        argbuf[req.arglen] = 0;  /* Null terminate */
        if (DiskInit(argbuf) < 0) {
            if (verbose) printf("  DiskInit failed. Request from %s exiting\n", from);
            ERRCmd(fd, 1);
            exit(1);
        }
        ACKCmd(fd);
        if (verbose) printf("  DiskInit from %s successful -- processing requests.\n", from);
        ProcessDiskRequest(fd);
        break;
    }
    default:
        fprintf(stderr, "  Unknown command %d\n", req.cmd);
        if (verbose) printf("  Request from %s exiting\n", from);
        exit(1);
    }
    exit(0);
}	
void
ACKCmd(int fd) 
{
    if (write(fd, "OK\n", 3) != 3) {
        perror("ACKCmd -- write");
        exit(1);
    } 
}

void
ERRCmd(int fd, int err) 
{
    char str[8];
    sprintf(str, "E%02d", err);
    if (write(fd, str, 3) != 3) {
        perror("ERRCmd -- write");
        exit(1);
    } 
}

int
CopyFile(int infd, int outfd)
{
    char buf[8192];
    int cnt, cnt2;
    while(1) {
        cnt = read(infd, buf, sizeof(buf));
        if (cnt == 0) 
            break;
        if (cnt < 0) {
            perror("CopyFile -- read");
            exit(1);
        }
        cnt2 = write(outfd, buf, cnt);
        if (cnt2 != cnt) {
            perror("CopyFile -- write");
            exit(1);
        }
    }
    return 0;
}

int
CopySizedFile(int infd, int outfd, int size)
{
  char buf[8192];
  int cnt, cnt2;
  while(size > 0) {
    int getsize = (size < sizeof(buf) ? size : sizeof(buf));
    cnt = readforsure(infd, buf, getsize);
    if (cnt != getsize) {
      perror("CopySizedFile -- read");
      exit(1);
    }
    cnt2 = write(outfd, buf, cnt);
    if (cnt2 != cnt) {
      perror("CopySizedFile -- write");
      exit(1);
    }
    size -= cnt;
  }
  return 0;
}


int
DiskInit(char *arg)
{
    int i;
    for (i = 0; i < NETDISK_MAX_DISKS; i++) { 
        diskInfo[i].fd = -1;
    }

    if (getwd(cwd) == 0) return -1;
    if (gethostname(hostname, MAX_PATH_LENGTH) != 0) return -1;
    else {
      char *c = strchr(hostname, '.');
      if (c != NULL) *c = 0;
    }
    return 0;
}

int
ProcessDiskRequest(int fd)
{
    int   n;
    int xfersize;
    NetDiskHdr *hdrPtr;
 
    while(1) {
        n = readforsure(fd, curPacket, sizeof(NetDiskHdr));
        if (n != sizeof(NetDiskHdr)) {
            if (n == 0) exit(0);
            perror("ProcessDiskRequest -- read");
            exit(1);
        }
        hdrPtr = (NetDiskHdr *) curPacket;
 
        if ((hdrPtr->op == NETDISK_WRITE) || (hdrPtr->op == NETDISK_ATTACH)) {
            xfersize =  hdrPtr->sizeInBytes;
            n = readforsure(fd, curPacket + sizeof(NetDiskHdr), xfersize);
            if (n != xfersize) {
                if (n == 0) exit(0);
                perror("ProcessDiskRequest -- read");
                exit(1);
            }
        }
 
        hdrPtr = (NetDiskHdr *) curPacket;

        if ((hdrPtr->retVal = DoDiskRequest(hdrPtr->op,
					    hdrPtr->ctrl, hdrPtr->unit,
                                            hdrPtr->sectorNum, hdrPtr->sizeInBytes,
                                            (char *) (hdrPtr+1))) == -1 ) {
           /* Exiting here leaves SimOS hanging for a response header --
            Instead return a header with size -1 and let SimOS deal */
#ifdef notdef
           exit(1);
#endif
        }
        
        if ((hdrPtr->op == NETDISK_READ) || (hdrPtr->op == NETDISK_ATTACH)) {
           n = hdrPtr->retVal;
           if (n < 0) n = 0;
        } else {
           n = 0;
        }
        xfersize = write(fd, curPacket, n + sizeof(*hdrPtr));
        if (xfersize !=  n + sizeof(*hdrPtr)) {
            perror("ProcessDiskRequest -- write");
            exit(1);
        }

    }
    return 0;
}


int64
DoDiskRequest(int op, int ctrl, int unit, int64 sectorNum, int64 sizeInBytes, char *buffer)
{ 	
   DiskFileInfo *hd;
   DiskFileInfo *df = (DiskFileInfo *) buffer;

   unsigned long transferSize, bytesRemaining;
  
   if ((ctrl < 0) || (ctrl >= SIM_DISK_DEV_MAX_CTRL)) {
     if (verbose) printf("  Bad controller number %d in request from %s\n",
			 ctrl, source);
     return -1;
   }
   if ((unit < 0) || (unit >= SIM_DISK_DEV_MAX_UNIT)) {
     if (verbose) printf("  Bad unit number %d in request from %s\n",
			 unit, source);
     return -1;
   }
   hd = &(diskInfo[CU2DISK(ctrl,unit)]);
   
   if (op == NETDISK_ATTACH) {
      if (hd->fd > 0) {
         if (verbose) printf("  Trying to reattach disk %d.%d in request from %s\n",
                             ctrl, unit, source);
         return -1;
      }
      /* If we're restoring from a checkpoint, then SimOS will provide
         the full pathname of the disk file in the buffer; if not, then
         SimOS simply provides the disk number and we use the devices in 
         the CWD of the rmtaccess process. */
      /* In any case, we return to SimOS the relevant file info for the 
         disk file: filename, size, and last modified time -- these are 
         needed by SimOS to take a checkpoint */
      if (sizeInBytes > 0) {
         strcpy(hd->filename, df->filename);
      }
      else {
         sprintf(hd->filename, "%s/DISK%d.%d", cwd, ctrl, unit);
         strcpy(df->filename, hd->filename);
      }

      hd->fd = open(hd->filename, O_RDONLY , 0);
      if (hd->fd > 0) { 
         long size;
         struct stat filestats;
         
         if (verbose) printf("  Attach disk %s for %s\n", hd->filename,
                             source);
         
         if ((size = lseek(hd->fd, 0, SEEK_END)) < 0 ) {
            perror("Lseeking disk in netdiskserver");
         }
         if (fstat(hd->fd, &filestats) < 0) {
            perror("stat");
         }
         df->fileSize = hd->fileSize = size;
         size = (SIM_DISK_SHADOW_BLKSIZE)
            *((size+(SIM_DISK_SHADOW_BLKSIZE))/(SIM_DISK_SHADOW_BLKSIZE));
         df->modifyTime = hd->modifyTime = filestats.st_mtime;
      } else { 
         perror(hd->filename);
         return -1;
      }
      return sizeof(DiskFileInfo);
   }
   
   if (hd->fd <= 0) {
      if (verbose) printf("  Failed request for DISK%d.%d for %s\n",
			  ctrl, unit, source);
      return -1;
   }
   if (op == NETDISK_PROBE) { 
      return hd->fileSize;
   }
   if (sectorNum*SectorSize + sizeInBytes > hd->fileSize) {
      sizeInBytes = hd->fileSize - sectorNum*SectorSize;
      if (verbose) printf("  Out of range request for DISK%d.%d for %s\n",
			  ctrl, unit, source);
       
   }
   if (sizeInBytes < 0) 
      sizeInBytes = 0;	

   bytesRemaining = sizeInBytes;
   while(bytesRemaining) {
      transferSize = bytesRemaining > SectorSize ? SectorSize : bytesRemaining;
      lseek (hd->fd, sectorNum*SectorSize, SEEK_SET);
      if (op == NETDISK_READ) {
         if (read (hd->fd, (void *)buffer, transferSize ) != transferSize) {
            if (verbose) printf("Can't read from file for DISK%d.%d\n",
				ctrl, unit);
            return -1;
         }
      } else {
         if (verbose) printf("Can't write to rmtaccess disk for DISK%d.%d\n",
			     ctrl, unit);
         return -1;
      }
      buffer += transferSize;
      sectorNum++;
      bytesRemaining -= transferSize;
   }

   return sizeInBytes;
}


static int
readforsure(int fd, char *buf, int size)
{
    int a;
    for(a = 0; a < size;) {
        int ret = read(fd, buf + a, size-a);
        if (ret <= 0)
            return ret;
        a += ret;
    }
    return size;
}


static void
childdone(int sig)
{
   int pid, status;

   pid = wait(&status);
   /*
    * Now reinstall handler & cause SIGCLD to be re-raised
    * if any more children exited while we were in here.
    */
   sigset(SIGCLD, childdone);
}