Annotation of libwww/Library/src/HTFile.c, revision 1.21

1.1       timbl       1: /*                     File Access                             HTFile.c
                      2: **                     ===========
                      3: **
                      4: **     This is unix-specific code in general, with some VMS bits.
1.8       timbl       5: **     These are routines for file access used by browsers.
1.1       timbl       6: **
                      7: ** History:
                      8: **        Feb 91       Written Tim Berners-Lee CERN/CN
                      9: **        Apr 91       vms-vms access included using DECnet syntax
                     10: **     26 Jun 92 (JFG) When running over DECnet, suppressed FTP.
                     11: **                     Fixed access bug for relative names on VMS.
                     12: **
                     13: ** Bugs:
1.2       timbl      14: **     FTP: Cannot access VMS files from a unix machine.
                     15: **      How can we know that the
1.1       timbl      16: **     target machine runs VMS?
                     17: */
                     18: 
1.2       timbl      19: #include "HTFile.h"            /* Implemented here */
                     20: 
                     21: 
1.1       timbl      22: #define INFINITY 512           /* file name length @@ FIXME */
1.2       timbl      23: #define MULTI_SUFFIX ".multi"   /* Extension for scanning formats */
1.1       timbl      24: 
                     25: #include "HTUtils.h"
                     26: 
                     27: #include "HTParse.h"
                     28: #include "tcp.h"
                     29: #include "HTTCP.h"
                     30: #ifndef DECNET
                     31: #include "HTFTP.h"
                     32: #endif
                     33: #include "HTAnchor.h"
1.2       timbl      34: #include "HTAtom.h"
                     35: #include "HTWriter.h"
                     36: #include "HTFWriter.h"
                     37: #include "HTInit.h"
1.7       secret     38: #include "HTBTree.h"
1.2       timbl      39: 
                     40: typedef struct _HTSuffix {
                     41:        char *          suffix;
                     42:        HTAtom *        rep;
1.19      timbl      43:        HTAtom *        encoding;
1.2       timbl      44:        float           quality;
                     45: } HTSuffix;
                     46: 
                     47: 
1.12      timbl      48: #ifdef USE_DIRENT              /* Set this for Sys V systems */
                     49: #define STRUCT_DIRENT struct dirent
                     50: #else
                     51: #define STRUCT_DIRENT struct direct
                     52: #endif
1.1       timbl      53: 
1.2       timbl      54: #include "HTML.h"              /* For directory object building */
                     55: 
1.10      secret     56: #define PUTC(c) (*target->isa->put_character)(target, c)
                     57: #define PUTS(s) (*target->isa->put_string)(target, s)
                     58: #define START(e) (*target->isa->start_element)(target, e, 0, 0)
                     59: #define END(e) (*target->isa->end_element)(target, e)
                     60: #define END_TARGET (*target->isa->end_document)(target)
                     61: #define FREE_TARGET (*target->isa->free)(target)
1.2       timbl      62: struct _HTStructured {
                     63:        CONST HTStructuredClass *       isa;
                     64:        /* ... */
                     65: };
                     66: 
                     67: 
                     68: /*                   Controlling globals
                     69: **
                     70: */
                     71: 
                     72: PUBLIC int HTDirAccess = HT_DIR_OK;
                     73: PUBLIC int HTDirReadme = HT_DIR_README_TOP;
1.1       timbl      74: 
                     75: PRIVATE char *HTMountRoot = "/Net/";           /* Where to find mounts */
                     76: #ifdef vms
                     77: PRIVATE char *HTCacheRoot = "/WWW$SCRATCH/";   /* Where to cache things */
                     78: #else
                     79: PRIVATE char *HTCacheRoot = "/tmp/W3_Cache_";   /* Where to cache things */
                     80: #endif
                     81: 
                     82: /* PRIVATE char *HTSaveRoot  = "$(HOME)/WWW/";*/    /* Where to save things */
                     83: 
1.2       timbl      84: 
                     85: /*     Suffix registration
                     86: */
                     87: 
                     88: PRIVATE HTList * HTSuffixes = 0;
1.19      timbl      89: PRIVATE HTSuffix no_suffix = { "*", NULL, NULL, 1.0 };
                     90: PRIVATE HTSuffix unknown_suffix = { "*.*", NULL, NULL, 1.0};
1.2       timbl      91: 
1.11      timbl      92: 
1.2       timbl      93: /*     Define the representation associated with a file suffix
                     94: **     -------------------------------------------------------
1.11      timbl      95: **
                     96: **     Calling this with suffix set to "*" will set the default
                     97: **     representation.
                     98: **     Calling this with suffix set to "*.*" will set the default
                     99: **     representation for unknown suffix files which contain a ".".
1.2       timbl     100: */
1.19      timbl     101: PUBLIC void HTSetSuffix ARGS4(
1.2       timbl     102:        CONST char *,   suffix,
                    103:        CONST char *,   representation,
1.19      timbl     104:        CONST char *,   encoding,
1.2       timbl     105:        float,          value)
                    106: {
                    107:     
1.11      timbl     108:     HTSuffix * suff;
                    109:     
1.19      timbl     110:     if (strcmp(suffix, "*")==0) suff = &no_suffix;
                    111:     else if (strcmp(suffix, "*.*")==0) suff = &unknown_suffix;
                    112:     else {
                    113:        suff = (HTSuffix*) calloc(1, sizeof(HTSuffix));
                    114:        if (suff == NULL) outofmem(__FILE__, "HTSetSuffix");
                    115:        
                    116:        if (!HTSuffixes) HTSuffixes = HTList_new();
                    117:        HTList_addObject(HTSuffixes, suff);
                    118:        
                    119:        StrAllocCopy(suff->suffix, suffix);
1.11      timbl     120:     }
1.19      timbl     121: 
                    122:     suff->rep = HTAtom_for(representation);
1.11      timbl     123:     
1.19      timbl     124:     {
                    125:        char * enc = NULL;
                    126:        char * p;
                    127:        StrAllocCopy(enc, encoding);
                    128:        for (p=enc; *p; p++) *p = TOLOWER(*p);
                    129:        suff->encoding = HTAtom_for(encoding);
1.11      timbl     130:     }
                    131:     
1.2       timbl     132:     suff->quality = value;
                    133: }
                    134: 
                    135: 
                    136: 
                    137: 
1.1       timbl     138: #ifdef vms
                    139: /*     Convert unix-style name into VMS name
                    140: **     -------------------------------------
                    141: **
                    142: ** Bug:        Returns pointer to static -- non-reentrant
                    143: */
                    144: PRIVATE char * vms_name(CONST char * nn, CONST char * fn)
                    145: {
                    146: 
                    147: /*     We try converting the filename into Files-11 syntax. That is, we assume
                    148: **     first that the file is, like us, on a VMS node. We try remote
                    149: **     (or local) DECnet access. Files-11, VMS, VAX and DECnet
                    150: **     are trademarks of Digital Equipment Corporation. 
                    151: **     The node is assumed to be local if the hostname WITHOUT DOMAIN
                    152: **     matches the local one. @@@
                    153: */
                    154:     static char vmsname[INFINITY];     /* returned */
                    155:     char * filename = (char*)malloc(strlen(fn)+1);
                    156:     char * nodename = (char*)malloc(strlen(nn)+2+1);   /* Copies to hack */
                    157:     char *second;              /* 2nd slash */
                    158:     char *last;                        /* last slash */
                    159:     
                    160:     char * hostname = HTHostName();
                    161: 
                    162:     if (!filename || !nodename) outofmem(__FILE__, "vms_name");
                    163:     strcpy(filename, fn);
                    164:     strcpy(nodename, "");      /* On same node? Yes if node names match */
                    165:     {
                    166:         char *p, *q;
                    167:         for (p=hostname, q=nn; *p && *p!='.' && *q && *q!='.'; p++, q++){
                    168:            if (TOUPPER(*p)!=TOUPPER(*q)) {
                    169:                strcpy(nodename, nn);
                    170:                q = strchr(nodename, '.');      /* Mismatch */
                    171:                if (q) *q=0;                    /* Chop domain */
                    172:                strcat(nodename, "::");         /* Try decnet anyway */
                    173:                break;
                    174:            }
                    175:        }
                    176:     }
                    177: 
                    178:     second = strchr(filename+1, '/');          /* 2nd slash */
                    179:     last = strrchr(filename, '/');     /* last slash */
                    180:         
                    181:     if (!second) {                             /* Only one slash */
                    182:        sprintf(vmsname, "%s%s", nodename, filename + 1);
                    183:     } else if(second==last) {          /* Exactly two slashes */
                    184:        *second = 0;            /* Split filename from disk */
                    185:        sprintf(vmsname, "%s%s:%s", nodename, filename+1, second+1);
                    186:        *second = '/';  /* restore */
                    187:     } else {                           /* More than two slashes */
                    188:        char * p;
                    189:        *second = 0;            /* Split disk from directories */
                    190:        *last = 0;              /* Split dir from filename */
                    191:        sprintf(vmsname, "%s%s:[%s]%s",
                    192:                nodename, filename+1, second+1, last+1);
                    193:        *second = *last = '/';  /* restore filename */
                    194:        for (p=strchr(vmsname, '['); *p!=']'; p++)
                    195:            if (*p=='/') *p='.';        /* Convert dir sep.  to dots */
                    196:     }
                    197:     free(nodename);
                    198:     free(filename);
                    199:     return vmsname;
                    200: }
                    201: 
                    202: 
                    203: #endif /* vms */
                    204: 
1.2       timbl     205: 
                    206: 
                    207: /*     Send README file
                    208: **
                    209: **  If a README file exists, then it is inserted into the document here.
                    210: */
                    211: 
1.12      timbl     212: #ifdef GOT_READ_DIR
1.2       timbl     213: PRIVATE void do_readme ARGS2(HTStructured *, target, CONST char *, localname)
                    214: { 
                    215:     FILE * fp;
                    216:     char * readme_file_name = 
                    217:        malloc(strlen(localname)+ 1 + strlen(HT_DIR_README_FILE) + 1);
                    218:     strcpy(readme_file_name, localname);
                    219:     strcat(readme_file_name, "/");
                    220:     strcat(readme_file_name, HT_DIR_README_FILE);
                    221:     
                    222:     fp = fopen(readme_file_name,  "r");
                    223:     
                    224:     if (fp) {
                    225:        HTStructuredClass targetClass;
                    226:        
                    227:        targetClass =  *target->isa;    /* (Can't init agregate in K&R) */
                    228:        START(HTML_PRE);
                    229:        for(;;){
                    230:            char c = fgetc(fp);
                    231:            if (c == (char)EOF) break;
                    232:            switch (c) {
                    233:                case '&':
                    234:                case '<':
                    235:                case '>':
                    236:                        PUTC('&');
                    237:                        PUTC('#');
                    238:                        PUTC((char)(c / 10));
                    239:                        PUTC((char) (c % 10));
                    240:                        PUTC(';');
                    241:                        break;
1.13      secret    242: /*             case '\n':
                    243:                        PUTC('\r');    
                    244: Bug removed thanks to joe@athena.mit.edu */                    
1.2       timbl     245:                default:
                    246:                        PUTC(c);
                    247:            }
                    248:        }
                    249:        END(HTML_PRE);
                    250:        fclose(fp);
                    251:     } 
                    252: }
1.3       timbl     253: #endif
1.2       timbl     254: 
                    255: 
1.1       timbl     256: /*     Make the cache file name for a W3 document
                    257: **     ------------------------------------------
                    258: **     Make up a suitable name for saving the node in
                    259: **
                    260: **     E.g.    /tmp/WWW_Cache_news/1234@cernvax.cern.ch
                    261: **             /tmp/WWW_Cache_http/crnvmc/FIND/xx.xxx.xx
                    262: **
                    263: ** On exit,
                    264: **     returns a malloc'ed string which must be freed by the caller.
                    265: */
                    266: PUBLIC char * HTCacheFileName ARGS1(CONST char *,name)
                    267: {
                    268:     char * access = HTParse(name, "", PARSE_ACCESS);
                    269:     char * host = HTParse(name, "", PARSE_HOST);
                    270:     char * path = HTParse(name, "", PARSE_PATH+PARSE_PUNCTUATION);
                    271:     
                    272:     char * result;
                    273:     result = (char *)malloc(
                    274:            strlen(HTCacheRoot)+strlen(access)
                    275:            +strlen(host)+strlen(path)+6+1);
                    276:     if (result == NULL) outofmem(__FILE__, "HTCacheFileName");
                    277:     sprintf(result, "%s/WWW/%s/%s%s", HTCacheRoot, access, host, path);
                    278:     free(path);
                    279:     free(access);
                    280:     free(host);
                    281:     return result;
                    282: }
                    283: 
1.2       timbl     284: 
1.1       timbl     285: /*     Open a file for write, creating the path
                    286: **     ----------------------------------------
                    287: */
                    288: #ifdef NOT_IMPLEMENTED
                    289: PRIVATE int HTCreatePath ARGS1(CONST char *,path)
                    290: {
                    291:     return -1;
                    292: }
                    293: #endif
                    294: 
                    295: /*     Convert filenames between local and WWW formats
                    296: **     -----------------------------------------------
                    297: **     Make up a suitable name for saving the node in
                    298: **
                    299: **     E.g.    $(HOME)/WWW/news/1234@cernvax.cern.ch
                    300: **             $(HOME)/WWW/http/crnvmc/FIND/xx.xxx.xx
                    301: **
                    302: ** On exit,
                    303: **     returns a malloc'ed string which must be freed by the caller.
                    304: */
                    305: PUBLIC char * HTLocalName ARGS1(CONST char *,name)
                    306: {
                    307:     char * access = HTParse(name, "", PARSE_ACCESS);
                    308:     char * host = HTParse(name, "", PARSE_HOST);
                    309:     char * path = HTParse(name, "", PARSE_PATH+PARSE_PUNCTUATION);
                    310:     
1.6       timbl     311:     HTUnEscape(path);  /* Interpret % signs */
                    312:     
1.1       timbl     313:     if (0==strcmp(access, "file")) {
                    314:         free(access);  
1.9       timbl     315:        if ((0==strcasecomp(host, HTHostName())) ||
                    316:            (0==strcasecomp(host, "localhost")) || !*host) {
1.1       timbl     317:            free(host);
                    318:            if (TRACE) fprintf(stderr, "Node `%s' means path `%s'\n", name, path);
                    319:            return(path);
                    320:        } else {
                    321:            char * result = (char *)malloc(
                    322:                                strlen("/Net/")+strlen(host)+strlen(path)+1);
                    323:               if (result == NULL) outofmem(__FILE__, "HTLocalName");
                    324:            sprintf(result, "%s%s%s", "/Net/", host, path);
                    325:            free(host);
                    326:            free(path);
                    327:            if (TRACE) fprintf(stderr, "Node `%s' means file `%s'\n", name, result);
                    328:            return result;
                    329:        }
                    330:     } else {  /* other access */
                    331:        char * result;
                    332:         CONST char * home =  (CONST char*)getenv("HOME");
                    333:        if (!home) home = "/tmp"; 
                    334:        result = (char *)malloc(
                    335:                strlen(home)+strlen(access)+strlen(host)+strlen(path)+6+1);
                    336:       if (result == NULL) outofmem(__FILE__, "HTLocalName");
                    337:        sprintf(result, "%s/WWW/%s/%s%s", home, access, host, path);
                    338:        free(path);
                    339:        free(access);
                    340:        free(host);
                    341:        return result;
                    342:     }
                    343: }
                    344: 
                    345: 
                    346: /*     Make a WWW name from a full local path name
                    347: **
                    348: ** Bugs:
                    349: **     At present, only the names of two network root nodes are hand-coded
                    350: **     in and valid for the NeXT only. This should be configurable in
                    351: **     the general case.
                    352: */
                    353: 
                    354: PUBLIC char * WWW_nameOfFile ARGS1 (CONST char *,name)
                    355: {
                    356:     char * result;
                    357: #ifdef NeXT
                    358:     if (0==strncmp("/private/Net/", name, 13)) {
                    359:        result = (char *)malloc(7+strlen(name+13)+1);
                    360:        if (result == NULL) outofmem(__FILE__, "WWW_nameOfFile");
                    361:        sprintf(result, "file://%s", name+13);
                    362:     } else
                    363: #endif
                    364:     if (0==strncmp(HTMountRoot, name, 5)) {
                    365:        result = (char *)malloc(7+strlen(name+5)+1);
                    366:        if (result == NULL) outofmem(__FILE__, "WWW_nameOfFile");
                    367:        sprintf(result, "file://%s", name+5);
                    368:     } else {
                    369:         result = (char *)malloc(7+strlen(HTHostName())+strlen(name)+1);
                    370:        if (result == NULL) outofmem(__FILE__, "WWW_nameOfFile");
                    371:        sprintf(result, "file://%s%s", HTHostName(), name);
                    372:     }
                    373:     if (TRACE) fprintf(stderr, "File `%s'\n\tmeans node `%s'\n", name, result);
                    374:     return result;
                    375: }
                    376: 
                    377: 
1.2       timbl     378: /*     Determine a suitable suffix, given the representation
                    379: **     -----------------------------------------------------
                    380: **
                    381: ** On entry,
                    382: **     rep     is the atomized MIME style representation
                    383: **
                    384: ** On exit,
                    385: **     returns a pointer to a suitable suffix string if one has been
                    386: **             found, else "".
                    387: */
                    388: PUBLIC CONST char * HTFileSuffix ARGS1(HTAtom*, rep)
                    389: {
                    390:     HTSuffix * suff;
                    391:     int n;
                    392:     int i;
                    393: 
                    394: #ifndef NO_INIT    
                    395:     if (!HTSuffixes) HTFileInit();
                    396: #endif
                    397:     n = HTList_count(HTSuffixes);
                    398:     for(i=0; i<n; i++) {
                    399:        suff = HTList_objectAt(HTSuffixes, i);
                    400:        if (suff->rep == rep) {
                    401:            return suff->suffix;                /* OK -- found */
                    402:        }
                    403:     }
                    404:     return "";         /* Dunno */
                    405: }
                    406: 
                    407: 
1.1       timbl     408: /*     Determine file format from file name
                    409: **     ------------------------------------
                    410: **
1.19      timbl     411: **     This version will return the representation and also set
                    412: **     a variable for the encoding.
                    413: **
                    414: **     It will handle for example  x.txt, x.txt,Z, x.Z
1.2       timbl     415: */
                    416: 
1.19      timbl     417: PUBLIC HTFormat HTFileFormat ARGS2 (
                    418:                        CONST char *,   filename,
                    419:                        HTAtom **,      pencoding)
1.2       timbl     420: 
                    421: {
                    422:     HTSuffix * suff;
                    423:     int n;
                    424:     int i;
                    425:     int lf = strlen(filename);
                    426: 
                    427: #ifndef NO_INIT    
                    428:     if (!HTSuffixes) HTFileInit();
                    429: #endif
1.19      timbl     430:     *pencoding = NULL;
1.2       timbl     431:     n = HTList_count(HTSuffixes);
                    432:     for(i=0; i<n; i++) {
                    433:         int ls;
                    434:        suff = HTList_objectAt(HTSuffixes, i);
                    435:        ls = strlen(suff->suffix);
                    436:        if ((ls <= lf) && 0==strcmp(suff->suffix, filename + lf - ls)) {
1.19      timbl     437:            int j;
                    438:            *pencoding = suff->encoding;
                    439:            if (suff->rep) return suff->rep;            /* OK -- found */
                    440:            
                    441:            for(j=0; j<n; j++) {  /* Got encoding, need representation */
                    442:                int ls2;
                    443:                suff = HTList_objectAt(HTSuffixes, j);
                    444:                ls2 = strlen(suff->suffix);
                    445:                if ((ls <= lf) && 0==strncmp(
                    446:                        suff->suffix, filename + lf - ls -ls2, ls2)) {
                    447:                    if (suff->rep) return suff->rep;
                    448:                }
                    449:            }
                    450:            
1.2       timbl     451:        }
                    452:     }
1.11      timbl     453:     
1.19      timbl     454:     /* defaults tree */
1.11      timbl     455:     
1.19      timbl     456:     suff = strchr(filename, '.') ?     /* Unknown suffix */
                    457:         ( unknown_suffix.rep ? &unknown_suffix : &no_suffix)
                    458:         : &no_suffix;
                    459:         
                    460:     /* set default encoding unless found with suffix already */
                    461:     if (!*pencoding) *pencoding = suff->encoding ? suff->encoding
                    462:                                    : HTAtom_for("binary");
                    463:     return suff->rep ? suff->rep : WWW_BINARY;
1.2       timbl     464: }
                    465: 
                    466: 
                    467: /*     Determine value from file name
                    468: **     ------------------------------
1.1       timbl     469: **
                    470: */
                    471: 
1.2       timbl     472: PUBLIC float HTFileValue ARGS1 (CONST char *,filename)
                    473: 
1.1       timbl     474: {
1.2       timbl     475:     HTSuffix * suff;
                    476:     int n;
                    477:     int i;
                    478:     int lf = strlen(filename);
                    479: 
                    480: #ifndef NO_INIT    
                    481:     if (!HTSuffixes) HTFileInit();
                    482: #endif
                    483:     n = HTList_count(HTSuffixes);
                    484:     for(i=0; i<n; i++) {
                    485:         int ls;
                    486:        suff = HTList_objectAt(HTSuffixes, i);
                    487:        ls = strlen(suff->suffix);
                    488:        if ((ls <= lf) && 0==strcmp(suff->suffix, filename + lf - ls)) {
                    489:            if (TRACE) fprintf(stderr, "File: Value of %s is %.3f\n",
                    490:                               filename, suff->quality);
                    491:            return suff->quality;               /* OK -- found */
                    492:        }
                    493:     }
                    494:     return 0.3;                /* Dunno! */
1.1       timbl     495: }
                    496: 
                    497: 
                    498: /*     Determine write access to a file
1.2       timbl     499: **     --------------------------------
                    500: **
                    501: ** On exit,
                    502: **     return value    YES if file can be accessed and can be written to.
                    503: **
                    504: ** Bugs:
                    505: **     1.      No code for non-unix systems.
                    506: **     2.      Isn't there a quicker way?
1.1       timbl     507: */
                    508: 
                    509: #ifdef vms
                    510: #define NO_GROUPS
                    511: #endif
                    512: #ifdef NO_UNIX_IO
                    513: #define NO_GROUPS
                    514: #endif
                    515: #ifdef PCNFS
                    516: #define NO_GROUPS
                    517: #endif
                    518: 
                    519: PUBLIC BOOL HTEditable ARGS1 (CONST char *,filename)
                    520: {
                    521: #ifdef NO_GROUPS
                    522:     return NO;         /* Safe answer till we find the correct algorithm */
                    523: #else
                    524:     int        groups[NGROUPS];        
                    525:     uid_t      myUid;
                    526:     int                ngroups;                        /* The number of groups  */
                    527:     struct stat        fileStatus;
                    528:     int                i;
                    529:         
                    530:     if (stat(filename, &fileStatus))           /* Get details of filename */
                    531:        return NO;                              /* Can't even access file! */
                    532: 
                    533:     ngroups = getgroups(NGROUPS, groups);      /* Groups to which I belong  */
                    534:     myUid = geteuid();                         /* Get my user identifier */
                    535: 
                    536:     if (TRACE) {
                    537:         int i;
1.19      timbl     538:        fprintf(stderr, 
                    539:            "File mode is 0%o, uid=%d, gid=%d. My uid=%d, %d groups (",
1.5       timbl     540:            (unsigned int) fileStatus.st_mode, fileStatus.st_uid,
                    541:            fileStatus.st_gid,
1.1       timbl     542:            myUid, ngroups);
1.19      timbl     543:        for (i=0; i<ngroups; i++) fprintf(stderr, " %d", groups[i]);
                    544:        fprintf(stderr, ")\n");
1.1       timbl     545:     }
                    546:     
                    547:     if (fileStatus.st_mode & 0002)             /* I can write anyway? */
                    548:        return YES;
                    549:        
                    550:     if ((fileStatus.st_mode & 0200)            /* I can write my own file? */
                    551:      && (fileStatus.st_uid == myUid))
                    552:        return YES;
                    553: 
                    554:     if (fileStatus.st_mode & 0020)             /* Group I am in can write? */
                    555:     {
                    556:        for (i=0; i<ngroups; i++) {
                    557:             if (groups[i] == fileStatus.st_gid)
                    558:                return YES;
                    559:        }
                    560:     }
                    561:     if (TRACE) fprintf(stderr, "\tFile is not editable.\n");
                    562:     return NO;                                 /* If no excuse, can't do */
                    563: #endif
                    564: }
                    565: 
                    566: 
1.2       timbl     567: /*     Make a save stream
                    568: **     ------------------
                    569: **
                    570: **     The stream must be used for writing back the file.
                    571: **     @@@ no backup done
                    572: */
                    573: PUBLIC HTStream * HTFileSaveStream ARGS1(HTParentAnchor *, anchor)
                    574: {
                    575: 
                    576:     CONST char * addr = HTAnchor_address((HTAnchor*)anchor);
                    577:     char *  localname = HTLocalName(addr);
                    578:     
                    579:     FILE* fp = fopen(localname, "w");
                    580:     if (!fp) return NULL;
                    581:     
                    582:     return HTFWriter_new(fp);
                    583:     
                    584: }
                    585: 
1.10      secret    586: /*      Output one directory entry
                    587: **
                    588: */
                    589: PUBLIC void HTDirEntry ARGS3(HTStructured *, target,
                    590:                 CONST char * , tail,
                    591:                 CONST char *,  entry)
                    592: {
                    593:     char * relative;
                    594:     char * escaped = HTEscape(entry, URL_XPALPHAS);
                    595: 
                    596:     /* If empty tail, gives absolute ref below */
                    597:     relative = (char*) malloc(
                    598:                              strlen(tail) + strlen(escaped)+2);
                    599:     if (relative == NULL) outofmem(__FILE__, "DirRead");
                    600:     sprintf(relative, "%s/%s", tail, escaped);
                    601:     HTStartAnchor(target, "", relative);
                    602:     free(escaped);
                    603:     free(relative);
                    604:     PUTS(entry);
                    605:     END(HTML_A);
                    606: }
                    607:  
                    608: /*      Output parent directory entry
                    609: **
                    610: **    This gives the TITLE and H1 header, and also a link
                    611: **    to the parent directory if appropriate.
                    612: */
                    613: PUBLIC void HTDirTitles ARGS2(HTStructured *, target,
                    614:                 HTAnchor * , anchor)
                    615: 
                    616: {
                    617:     char * logical = HTAnchor_address(anchor);
                    618:     char * path = HTParse(logical, "", PARSE_PATH + PARSE_PUNCTUATION);
                    619:     char * current;
                    620: 
                    621:     current = strrchr(path, '/');      /* last part or "" */
                    622:     free(logical);
                    623: 
                    624:     {
                    625:       char * printable = NULL;
                    626:       StrAllocCopy(printable, (current + 1));
                    627:       HTUnEscape(printable);
                    628:       START(HTML_TITLE);
                    629:       PUTS(*printable ? printable : "Welcome ");
                    630:       PUTS(" directory");
                    631:       END(HTML_TITLE);    
                    632:     
                    633:       START(HTML_H1);
                    634:       PUTS(*printable ? printable : "Welcome");
                    635:       END(HTML_H1);
                    636:       free(printable);
                    637:     }
                    638: 
                    639:     /*  Make link back to parent directory
                    640:      */
                    641: 
                    642:     if (current && current[1]) {   /* was a slash AND something else too */
                    643:         char * parent;
                    644:        char * relative;
                    645:        *current++ = 0;
                    646:       parent = strrchr(path, '/');  /* penultimate slash */
                    647: 
                    648:        relative = (char*) malloc(strlen(current) + 4);
                    649:        if (relative == NULL) outofmem(__FILE__, "DirRead");
                    650:        sprintf(relative, "%s/..", current);
                    651:        HTStartAnchor(target, "", relative);
                    652:        free(relative);
                    653: 
                    654:        PUTS("Up to ");
                    655:        if (parent) {
                    656:          char * printable = NULL;
                    657:          StrAllocCopy(printable, parent + 1);
                    658:          HTUnEscape(printable);
                    659:          PUTS(printable);
                    660:          free(printable);
                    661:        } else {
                    662:          PUTS("/");
                    663:        }
                    664: 
                    665:        END(HTML_A);
                    666: 
                    667:     }
                    668:     free(path);
                    669: }
                    670:                
1.2       timbl     671: 
1.10      secret    672: 
1.1       timbl     673: /*     Load a document
                    674: **     ---------------
                    675: **
                    676: ** On entry,
                    677: **     addr            must point to the fully qualified hypertext reference.
                    678: **                     This is the physsical address of the file
                    679: **
                    680: ** On exit,
1.2       timbl     681: **     returns         <0              Error has occured.
                    682: **                     HTLOADED        OK 
1.1       timbl     683: **
                    684: */
1.2       timbl     685: PUBLIC int HTLoadFile ARGS4 (
1.1       timbl     686:        CONST char *,           addr,
                    687:        HTParentAnchor *,       anchor,
1.2       timbl     688:        HTFormat,               format_out,
                    689:        HTStream *,             sink
1.1       timbl     690: )
                    691: {
                    692:     char * filename;
                    693:     HTFormat format;
                    694:     char * nodename = 0;
                    695:     char * newname=0;  /* Simplified name of file */
1.19      timbl     696:     HTAtom * encoding; /* @@ not used yet */
                    697:     
1.1       timbl     698: /*     Reduce the filename to a basic form (hopefully unique!)
                    699: */
                    700:     StrAllocCopy(newname, addr);
                    701:     filename=HTParse(newname, "", PARSE_PATH|PARSE_PUNCTUATION);
                    702:     nodename=HTParse(newname, "", PARSE_HOST);
                    703:     free(newname);
                    704:     
1.19      timbl     705:     format = HTFileFormat(filename, &encoding);
1.1       timbl     706: 
1.16      secret    707: 
1.1       timbl     708: #ifdef vms
                    709: /* Assume that the file is in Unix-style syntax if it contains a '/'
                    710:    after the leading one @@ */
                    711:     {
                    712:        char * vmsname = strchr(filename + 1, '/') ?
                    713:          vms_name(nodename, filename) : filename + 1;
                    714:        fd = open(vmsname, O_RDONLY, 0);
                    715:        
                    716: /*     If the file wasn't VMS syntax, then perhaps it is ultrix
                    717: */
                    718:        if (fd<0) {
                    719:            char ultrixname[INFINITY];
                    720:            if (TRACE) fprintf(stderr, "HTFile: Can't open as %s\n", vmsname);
                    721:            sprintf(ultrixname, "%s::\"%s\"", nodename, filename);
                    722:            fd = open(ultrixname, O_RDONLY, 0);
                    723:            if (fd<0) {
                    724:                if (TRACE) fprintf(stderr, 
                    725:                                   "HTFile: Can't open as %s\n", ultrixname);
                    726:            }
                    727:        }
                    728:     }
                    729: #else
                    730: 
1.6       timbl     731:     free(filename);
                    732:     
1.1       timbl     733: /*     For unix, we try to translate the name into the name of a transparently
                    734: **     mounted file.
                    735: **
                    736: **     Not allowed in secure (HTClienntHost) situations TBL 921019
                    737: */
                    738: #ifndef NO_UNIX_IO
1.17      timbl     739:     /*  Need protection here for telnet server but not httpd server */
1.2       timbl     740:         
1.17      timbl     741:     if (!HTSecure) {           /* try local file system */
1.1       timbl     742:        char * localname = HTLocalName(addr);
1.2       timbl     743:        struct stat dir_info;
1.1       timbl     744:        
                    745: #ifdef GOT_READ_DIR
1.2       timbl     746: 
                    747: /*                       Multiformat handling
                    748: **
                    749: **     If needed, scan directory to find a good file.
                    750: **  Bug:  we don't stat the file to find the length
                    751: */
                    752:        if ( (strlen(localname) > strlen(MULTI_SUFFIX))
                    753:           && (0==strcmp(localname + strlen(localname) - strlen(MULTI_SUFFIX),
                    754:                          MULTI_SUFFIX))) {
                    755:            DIR *dp;
                    756: 
1.12      timbl     757:            STRUCT_DIRENT * dirbuf;
1.2       timbl     758:            float best = NO_VALUE_FOUND;        /* So far best is bad */
                    759:            HTFormat best_rep = NULL;   /* Set when rep found */
1.12      timbl     760:            STRUCT_DIRENT best_dirbuf;  /* Best dir entry so far */
1.2       timbl     761: 
                    762:            char * base = strrchr(localname, '/');
                    763:            int baselen;
                    764: 
                    765:            if (!base || base == localname) goto forget_multi;
                    766:            *base++ = 0;                /* Just got directory name */
                    767:            baselen = strlen(base)- strlen(MULTI_SUFFIX);
                    768:            base[baselen] = 0;  /* Chop off suffix */
                    769: 
                    770:            dp = opendir(localname);
                    771:            if (!dp) {
                    772: forget_multi:
                    773:                free(localname);
                    774:                return HTLoadError(sink, 500,
                    775:                        "Multiformat: directory scan failed.");
                    776:            }
                    777:            
1.21    ! timbl     778:            while ((dirbuf = readdir(dp))!=0) {
1.2       timbl     779:                        /* while there are directory entries to be read */
                    780:                if (dirbuf->d_ino == 0) continue;
                    781:                                /* if the entry is not being used, skip it */
                    782:                
                    783:                if (dirbuf->d_namlen > baselen &&      /* Match? */
                    784:                    !strncmp(dirbuf->d_name, base, baselen)) {  
1.19      timbl     785:                    HTFormat rep = HTFileFormat(dirbuf->d_name, &encoding);
1.2       timbl     786:                    float value = HTStackValue(rep, format_out,
                    787:                                                HTFileValue(dirbuf->d_name),
                    788:                                                0.0  /* @@@@@@ */);
                    789:                    if (value != NO_VALUE_FOUND) {
                    790:                        if (TRACE) fprintf(stderr,
                    791:                                "HTFile: value of presenting %s is %f\n",
                    792:                                HTAtom_name(rep), value);
                    793:                        if  (value > best) {
                    794:                            best_rep = rep;
                    795:                            best = value;
                    796:                            best_dirbuf = *dirbuf;
                    797:                       }
                    798:                    }   /* if best so far */                
                    799:                 } /* if match */  
                    800:                    
                    801:            } /* end while directory entries left to read */
                    802:            closedir(dp);
                    803:            
                    804:            if (best_rep) {
                    805:                format = best_rep;
                    806:                base[-1] = '/';         /* Restore directory name */
                    807:                base[0] = 0;
                    808:                StrAllocCat(localname, best_dirbuf.d_name);
                    809:                goto open_file;
                    810:                
                    811:            } else {                    /* If not found suitable file */
                    812:                free(localname);
                    813:                return HTLoadError(sink, 403,   /* List formats? */
                    814:                   "Could not find suitable representation for transmission.");
                    815:            }
                    816:            /*NOTREACHED*/
                    817:        } /* if multi suffix */
1.1       timbl     818: /*
                    819: **     Check to see if the 'localname' is in fact a directory.  If it is
                    820: **     create a new hypertext object containing a list of files and 
                    821: **     subdirectories contained in the directory.  All of these are links
                    822: **      to the directories or files listed.
1.12      timbl     823: **      NB This assumes the existance of a type 'STRUCT_DIRENT', which will
1.1       timbl     824: **      hold the directory entry, and a type 'DIR' which is used to point to
                    825: **      the current directory being read.
                    826: */
                    827:        
                    828:        
                    829:        if (stat(localname,&dir_info) == -1) {     /* get file information */
                    830:                                       /* if can't read file information */
                    831:            if (TRACE) fprintf(stderr, "HTFile: can't stat %s\n", localname);
                    832: 
                    833:        }  else {               /* Stat was OK */
                    834:                
                    835: 
                    836:            if (((dir_info.st_mode) & S_IFMT) == S_IFDIR) {
                    837:                /* if localname is a directory */       
1.2       timbl     838: 
                    839:                HTStructured* target;           /* HTML object */
                    840:                HTStructuredClass targetClass;
                    841: 
1.1       timbl     842:                DIR *dp;
1.12      timbl     843:                STRUCT_DIRENT * dirbuf;
1.2       timbl     844:                
1.6       timbl     845:                char * logical;
                    846:                char * tail;
                    847:                
1.2       timbl     848:                BOOL present[HTML_A_ATTRIBUTES];
                    849:                
1.1       timbl     850:                char * tmpfilename = NULL;
1.2       timbl     851:                struct stat file_info;
1.1       timbl     852:                
                    853:                if (TRACE)
                    854:                    fprintf(stderr,"%s is a directory\n",localname);
                    855:                        
1.2       timbl     856: /*     Check directory access.
                    857: **     Selective access means only those directories containing a
                    858: **     marker file can be browsed
                    859: */
                    860:                if (HTDirAccess == HT_DIR_FORBID) {
1.6       timbl     861:                    free(localname);
1.2       timbl     862:                    return HTLoadError(sink, 403,
                    863:                    "Directory browsing is not allowed.");
                    864:                }
                    865: 
                    866: 
                    867:                if (HTDirAccess == HT_DIR_SELECTIVE) {
                    868:                    char * enable_file_name = 
                    869:                        malloc(strlen(localname)+ 1 +
                    870:                         strlen(HT_DIR_ENABLE_FILE) + 1);
                    871:                    strcpy(enable_file_name, localname);
                    872:                    strcat(enable_file_name, "/");
                    873:                    strcat(enable_file_name, HT_DIR_ENABLE_FILE);
                    874:                    if (stat(enable_file_name, &file_info) != 0) {
                    875:                        free(localname);
                    876:                        return HTLoadError(sink, 403,
                    877:                        "Selective access is not enabled for this directory");
                    878:                    }
                    879:                }
                    880: 
                    881:  
                    882:                dp = opendir(localname);
                    883:                if (!dp) {
                    884:                    free(localname);
                    885:                    return HTLoadError(sink, 403, "This directory is not readable.");
                    886:                }
                    887: 
                    888: 
                    889:  /*    Directory access is allowed and possible
                    890:  */
1.6       timbl     891:                logical = HTAnchor_address((HTAnchor*)anchor);
                    892:                tail = strrchr(logical, '/') +1;        /* last part or "" */
                    893:                
1.4       timbl     894:                target = HTML_new(anchor, format_out, sink);
1.2       timbl     895:                targetClass = *target->isa;     /* Copy routine entry points */
                    896:                    
                    897:                { int i;
                    898:                        for(i=0; i<HTML_A_ATTRIBUTES; i++)
                    899:                                present[i] = (i==HTML_A_HREF);
                    900:                }
1.1       timbl     901:                
1.10      secret    902:                 HTDirTitles(target, (HTAnchor *)anchor);
                    903: 
1.2       timbl     904:                 if (HTDirReadme == HT_DIR_README_TOP)
                    905:                    do_readme(target, localname);
1.7       secret    906:                {
1.9       timbl     907:                    HTBTree * bt = HTBTree_new((HTComparer)strcasecomp);
1.2       timbl     908: 
1.21    ! timbl     909:                    while ((dirbuf = readdir(dp))!=0)
1.7       secret    910:                    {
                    911:                        HTBTElement * dirname = NULL;
1.2       timbl     912: 
                    913:                            /* while there are directory entries to be read */
1.7       secret    914:                        if (dirbuf->d_ino == 0)
                    915:                                  /* if the entry is not being used, skip it */
                    916:                            continue;
1.1       timbl     917:                    
1.10      secret    918: 
1.2       timbl     919:                                /* if the current entry is parent directory */
1.10      secret    920:                        if ((*(dirbuf->d_name)=='.') ||
1.7       secret    921:                                (*(dirbuf->d_name)==','))
1.2       timbl     922:                            continue;    /* skip those files whose name begins
                    923:                                            with '.' or ',' */
1.10      secret    924: 
1.14      timbl     925:                        dirname = (HTBTElement *)malloc(
                    926:                                        strlen(dirbuf->d_name) + 2);
1.7       secret    927:                        if (dirname == NULL) outofmem(__FILE__,"DirRead");
                    928:                        StrAllocCopy(tmpfilename,localname);
                    929:                        if (strcmp(localname,"/")) 
                    930: 
                    931:                                        /* if filename is not root directory */
                    932:                            StrAllocCat(tmpfilename,"/"); 
1.10      secret    933: 
1.7       secret    934: 
                    935:                        StrAllocCat(tmpfilename,dirbuf->d_name);
                    936:                        stat(tmpfilename, &file_info);
                    937:                        if (((file_info.st_mode) & S_IFMT) == S_IFDIR)
                    938:                                sprintf((char *)dirname,"D%s",dirbuf->d_name);
                    939:                        else sprintf((char *)dirname,"F%s",dirbuf->d_name);
                    940:                            /* D & F to have first directories, then files */
                    941:                        HTBTree_add(bt,dirname); /* Sort dirname in the tree bt */
1.6       timbl     942:                    }
1.7       secret    943: 
                    944:                    /*    Run through tree printing out in order
                    945:                     */
                    946:                    {
                    947:                        HTBTElement * next_element = HTBTree_next(bt,NULL);
                    948:                            /* pick up the first element of the list */
1.15      secret    949:                        char state;
                    950:                            /* I for initial (.. file),
                    951:                               D for directory file,
                    952:                               F for file */
                    953:                        
                    954:                        state = 'I';
1.7       secret    955: 
                    956:                        while (next_element != NULL)
                    957:                        {
                    958:                            StrAllocCopy(tmpfilename,localname);
                    959:                            if (strcmp(localname,"/")) 
                    960: 
1.2       timbl     961:                                        /* if filename is not root directory */
1.7       secret    962:                                StrAllocCat(tmpfilename,"/"); 
                    963: 
1.15      secret    964:                            StrAllocCat(tmpfilename,
                    965:                                        (char *)HTBTree_object(next_element)+1);
1.7       secret    966:                            /* append the current entry's filename to the path */
                    967:                            HTSimplify(tmpfilename);
                    968:                            /* Output the directory entry */
1.15      secret    969:                            if (strcmp((char *)
                    970:                                             (HTBTree_object(next_element)),"D.."))
                    971:                            {                       
                    972:                                if (state != *(char *)(HTBTree_object(next_element))) 
1.7       secret    973:                                {
1.15      secret    974:                                    if (state == 'D')
                    975:                                        END(HTML_DIR);
                    976:                                    state = *(char *)
                    977:                                        (HTBTree_object(next_element))=='D'?'D':'F';
1.7       secret    978:                                    START(HTML_H2);
1.15      secret    979:                                    PUTS(state == 'D'?"Subdirectories:":"Files");
1.7       secret    980:                                    END(HTML_H2);
                    981:                                    START(HTML_DIR);
                    982:                                }
1.15      secret    983:                                START(HTML_LI);
1.7       secret    984:                            }
1.10      secret    985:                            HTDirEntry(target, tail,
                    986:                                       (char*)HTBTree_object(next_element) +1);
1.7       secret    987: 
                    988:                            next_element = HTBTree_next(bt,next_element);
                    989:                                /* pick up the next element of the list; 
                    990:                                 if none, return NULL*/
                    991:                        }
1.15      secret    992:                        if (state == 'I')
                    993:                        {
                    994:                            START(HTML_P);
                    995:                            PUTS("Empty Directory");
                    996:                        }
                    997:                        else
1.7       secret    998:                            END(HTML_DIR);
1.2       timbl     999:                    }
1.16      secret   1000: 
1.7       secret   1001:                        /* end while directory entries left to read */
                   1002:                    closedir(dp);
                   1003:                    free(logical);
                   1004:                    free(tmpfilename);
                   1005:                    HTBTreeAndObject_free(bt);
                   1006: 
                   1007:                    if (HTDirReadme == HT_DIR_README_BOTTOM)
                   1008:                          do_readme(target, localname);
                   1009:                    END_TARGET;
                   1010:                    FREE_TARGET;
                   1011:                    free(localname);
                   1012:                    return HT_LOADED;   /* document loaded */
1.2       timbl    1013:                }
                   1014: 
1.1       timbl    1015:            } /* end if localname is directory */
                   1016:        
                   1017:        } /* end if file stat worked */
                   1018:        
                   1019: /* End of directory reading section
                   1020: */
                   1021: #endif
1.2       timbl    1022: open_file:
1.16      secret   1023:        {
                   1024:            FILE * fp = fopen(localname,"r");
1.19      timbl    1025:            if(TRACE) fprintf (stderr, "HTFile: Opening `%s' gives %p\n",
                   1026:                                localname, (void*)fp);
1.16      secret   1027:            if (fp) {           /* Good! */
                   1028:                if (HTEditable(localname)) {
                   1029:                    HTAtom * put = HTAtom_for("PUT");
                   1030:                    HTList * methods = HTAnchor_methods(anchor);
                   1031:                    if (HTList_indexOf(methods, put) == (-1)) {
                   1032:                        HTList_addObject(methods, put);
                   1033:                    }
1.2       timbl    1034:                }
1.16      secret   1035:                free(localname);
                   1036:                HTParseFile(format, format_out, anchor, fp, sink);
                   1037:                fclose(fp);
                   1038:                return HT_LOADED;
                   1039:            }  /* If succesfull open */
                   1040:        }    /* scope of fp */
                   1041:     }  /* local unix file system */    
1.1       timbl    1042: #endif
                   1043: #endif
                   1044: 
                   1045: #ifndef DECNET
                   1046: /*     Now, as transparently mounted access has failed, we try FTP.
                   1047: */
1.16      secret   1048:     {
                   1049:        if (strcmp(nodename, HTHostName())!=0)
                   1050:            return HTFTPLoad(addr, anchor, format_out, sink);
1.1       timbl    1051:     }
                   1052: #endif
                   1053: 
1.16      secret   1054: /*     All attempts have failed.
1.1       timbl    1055: */
1.16      secret   1056:     {
1.2       timbl    1057:        if (TRACE)
1.6       timbl    1058:        printf("Can't open `%s', errno=%d\n", addr, errno);
1.2       timbl    1059:        return HTLoadError(sink, 403, "Can't access requested file.");
                   1060:     }
1.1       timbl    1061:     
1.16      secret   1062:  
1.1       timbl    1063: }
                   1064: 
                   1065: /*             Protocol descriptors
                   1066: */
                   1067: PUBLIC HTProtocol HTFTP  = { "ftp", HTLoadFile, 0 };
1.2       timbl    1068: PUBLIC HTProtocol HTFile = { "file", HTLoadFile, HTFileSaveStream };

Webmaster