Annotation of libwww/Library/src/HTTCP.c, revision 2.52

2.31      frystyk     1: /*                                                                     HTTCP.c
                      2: **     GENERIC COMMUNICATION CODE
                      3: **
2.42      frystyk     4: **     (c) COPYRIGHT MIT 1995.
2.31      frystyk     5: **     Please first read the full copyright statement in the file COPYRIGH.
1.1       timbl       6: **
                      7: **     This code is in common between client and server sides.
                      8: **
                      9: **     16 Jan 92  TBL  Fix strtol() undefined on CMU Mach.
                     10: **     25 Jun 92  JFG  Added DECNET option through TCP socket emulation.
2.7       duns       11: **     13 Sep 93  MD   Added correct return of vmserrorno for HTInetStatus.
                     12: **                     Added decoding of vms error message for MULTINET.
2.13      frystyk    13: **     31 May 94  HF   Added cache on host id's; now use inet_ntoa() to
                     14: **                     HTInetString and some other fixes. Added HTDoConnect
                     15: **                     and HTDoAccept
1.1       timbl      16: */
                     17: 
2.36      frystyk    18: /* Library include files */
                     19: #include "tcp.h"
2.13      frystyk    20: #include "HTUtils.h"
2.36      frystyk    21: #include "HTString.h"
2.13      frystyk    22: #include "HTAtom.h"
                     23: #include "HTList.h"
                     24: #include "HTParse.h"
2.50      frystyk    25: #include "HTAlert.h"
2.45      frystyk    26: #include "HTProt.h"
2.13      frystyk    27: #include "HTAccess.h"
                     28: #include "HTError.h"
2.27      frystyk    29: #include "HTThread.h"
2.36      frystyk    30: #include "HTTCP.h"                                      /* Implemented here */
2.29      frystyk    31: 
2.36      frystyk    32: #ifdef VMS 
                     33: #include "HTVMSUtils.h"
                     34: #endif /* VMS */
1.1       timbl      35: 
2.36      frystyk    36: /* VMS stuff */
                     37: #ifdef VMS
                     38: #ifndef MULTINET
                     39: #define FD_SETSIZE 32
                     40: #else /* Multinet */
                     41: #define FD_SETSIZE 256
                     42: #endif /* Multinet */
                     43: #endif /* VMS */
                     44: 
2.13      frystyk    45: /* Macros and other defines */
2.24      frystyk    46: /* x seconds penalty on a multi-homed host if IP-address is down */
                     47: #define TCP_PENALTY            1200
                     48: 
                     49: /* x seconds penalty on a multi-homed host if IP-address is timed out */
                     50: #define TCP_DELAY              600
                     51: 
                     52: /* Max number of non-blocking accepts */
2.13      frystyk    53: #define MAX_ACCEPT_POLL                30
                     54: 
2.36      frystyk    55: #ifndef RESOLV_CONF
                     56: #define RESOLV_CONF "/etc/resolv.conf"
                     57: #endif
                     58: 
2.13      frystyk    59: /* Globals */
                     60: PUBLIC unsigned int    HTConCacheSize = 512;    /* Number of cached servers */
                     61: 
                     62: /* Type definitions and global variables etc. local to this module */
                     63: 
                     64: /* This structure is a cache of hosts to whom we have connected over time.
                     65:    The structure contains the necessary parts from hostent. For Internet host
                     66:    hostent->h_addr_list is not an array of char pointers but an array of 
                     67:    pointers of type in_addr. */
                     68: typedef struct _host_info {
                     69:     HTAtom *           hostname;                   /* Official name of host */
                     70:     int                        hits;           /* Total number of hits on this host */
                     71:     int                        addrlength;            /* Length of address in bytes */
2.24      frystyk    72:     int                        homes;         /* Number of IP addresses on the host */
2.13      frystyk    73:     int                        offset;         /* Offset value of active IP address */
                     74:     char **            addrlist;      /* List of addresses from name server */
2.37      frystyk    75:     double *           weight;                    /* Weight on each address */
2.13      frystyk    76: } host_info;
                     77: 
                     78: PRIVATE char *hostname = NULL;                     /* The name of this host */
2.19      frystyk    79: PRIVATE char *mailaddress = NULL;                   /* Current mail address */
2.13      frystyk    80: PRIVATE HTList *hostcache = NULL;  /* List of servers that we have talked to */
                     81: PRIVATE unsigned int HTCacheSize = 0;              /* Current size of cache */
2.11      duns       82: 
2.13      frystyk    83: /* ------------------------------------------------------------------------- */
1.1       timbl      84: 
2.36      frystyk    85: /*
                     86: **     Returns the string equivalent to the errno passed in the argument.
2.37      frystyk    87: **     We can't use errno directly as we have both errno and socerrno. The
2.36      frystyk    88: **     result is a static buffer.
1.1       timbl      89: */
2.36      frystyk    90: PUBLIC CONST char * HTErrnoString ARGS1(int, errornumber)
1.1       timbl      91: {
2.41      frystyk    92: 
2.40      frystyk    93: #ifdef HAVE_STRERROR
2.36      frystyk    94:     return strerror(errornumber);
2.34      roeber     95: #else
2.36      frystyk    96: #ifdef VMS
2.12      luotonen   97:     static char buf[60];
2.36      frystyk    98:     sprintf(buf,"Unix errno = %ld dec, VMS error = %lx hex", errornumber,
                     99:            vaxc$errno);
2.12      luotonen  100:     return buf;
2.41      frystyk   101: #else 
2.40      frystyk   102: #ifdef _WINDOWS 
2.41      frystyk   103:        static char buf[60];
                    104:        sprintf(buf, "Unix errno = %ld dec, WinSock erro = %ld", errornumber, WSAGetLastError());
                    105:        return buf;
2.40      frystyk   106: #else
2.36      frystyk   107:     return (errornumber < sys_nerr ? sys_errlist[errornumber]:"Unknown error");
2.40      frystyk   108: #endif  /* WINDOWS */
                    109: #endif /* VMS */
2.51      frystyk   110: #endif /* HAVE_STRERROR */
2.12      luotonen  111: }
                    112: 
2.36      frystyk   113: 
                    114: /*     Debug error message
2.12      luotonen  115: */
2.39      frystyk   116: PUBLIC int HTInetStatus ARGS2(int, errnum, char *, where)
2.12      luotonen  117: {
2.40      frystyk   118: #if ! (defined(VMS) || defined(WINDOWS))
2.12      luotonen  119: 
2.27      frystyk   120:     if (PROT_TRACE)
2.41      frystyk   121:        fprintf(TDEST, "TCP errno... %d after call to %s() failed.\n............ %s\n", errno, where, HTErrnoString(errnum));
1.1       timbl     122: 
2.36      frystyk   123: #else /* VMS */
2.40      frystyk   124: #ifdef VMS 
2.36      frystyk   125:     if (PROT_TRACE) fprintf(TDEST, "         Unix error number          = %ld dec\n", errno);
                    126:     if (PROT_TRACE) fprintf(TDEST, "         VMS error                  = %lx hex\n", vaxc$errno);
2.40      frystyk   127: #endif
                    128: #ifdef WINDOWS 
                    129:     if (PROT_TRACE) fprintf(TDEST, "         Unix error number          = %ld dec\n", errno);
                    130:     if (PROT_TRACE) fprintf(TDEST, "         NT error                  = %lx hex\n", WSAGetLastError());
                    131: #endif 
2.12      luotonen  132: 
2.36      frystyk   133: #ifdef MULTINET
                    134:     if (PROT_TRACE) fprintf(TDEST, "         Multinet error             = %lx hex\n", socket_errno); 
                    135:     if (PROT_TRACE) fprintf(TDEST, "         Error String               = %s\n", vms_errno_string());
                    136: #endif /* MULTINET */
2.12      luotonen  137: 
2.36      frystyk   138: #endif /* VMS */
2.7       duns      139: 
2.36      frystyk   140: #ifdef VMS
2.11      duns      141:     /* errno happen to be zero if vaxc$errno <> 0 */
                    142:     return -vaxc$errno;
2.7       duns      143: #else
1.1       timbl     144:     return -errno;
2.7       duns      145: #endif
1.1       timbl     146: }
                    147: 
                    148: 
                    149: /*     Parse a cardinal value                                 parse_cardinal()
                    150: **     ----------------------
                    151: **
                    152: ** On entry,
                    153: **     *pp         points to first character to be interpreted, terminated by
                    154: **                 non 0:9 character.
                    155: **     *pstatus    points to status already valid
                    156: **     maxvalue    gives the largest allowable value.
                    157: **
                    158: ** On exit,
                    159: **     *pp         points to first unread character
                    160: **     *pstatus    points to status updated iff bad
                    161: */
                    162: 
                    163: PUBLIC unsigned int HTCardinal ARGS3
                    164:        (int *,         pstatus,
                    165:        char **,        pp,
                    166:        unsigned int,   max_value)
                    167: {
2.36      frystyk   168:     unsigned int n=0;
1.1       timbl     169:     if ( (**pp<'0') || (**pp>'9')) {       /* Null string is error */
                    170:        *pstatus = -3;  /* No number where one expeceted */
                    171:        return 0;
                    172:     }
                    173:     while ((**pp>='0') && (**pp<='9')) n = n*10 + *((*pp)++) - '0';
                    174: 
                    175:     if (n>max_value) {
                    176:        *pstatus = -4;  /* Cardinal outside range */
                    177:        return 0;
                    178:     }
                    179: 
                    180:     return n;
                    181: }
                    182: 
2.19      frystyk   183: /* ------------------------------------------------------------------------- */
2.27      frystyk   184: /*                             SIGNAL HANDLING                              */
                    185: /* ------------------------------------------------------------------------- */
                    186: 
                    187: #ifdef WWWLIB_SIG
                    188: /*                                                                 HTSetSignal
                    189: **  This function sets up signal handlers. This might not be necessary to
                    190: **  call if the application has its own handlers.
                    191: */
                    192: #include <signal.h>
                    193: PUBLIC void HTSetSignal NOARGS
                    194: {
                    195:     /* On some systems (SYSV) it is necessary to catch the SIGPIPE signal
                    196:     ** when attemting to connect to a remote host where you normally should
                    197:     ** get `connection refused' back
                    198:     */
                    199:     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
2.36      frystyk   200:        if (PROT_TRACE) fprintf(TDEST, "HTSignal.... Can't catch SIGPIPE\n");
2.27      frystyk   201:     } else {
2.36      frystyk   202:        if (PROT_TRACE) fprintf(TDEST, "HTSignal.... Ignoring SIGPIPE\n");
2.27      frystyk   203:     }
                    204: }
                    205: #endif /* WWWLIB_SIG */
                    206: 
                    207: /* ------------------------------------------------------------------------- */
2.19      frystyk   208: /*                          HOST CACHE MANAGEMENT                           */
                    209: /* ------------------------------------------------------------------------- */
1.1       timbl     210: 
2.27      frystyk   211: /*                                                             HTTCPCacheRemoveElement
2.13      frystyk   212: **
                    213: **     Remove the element specified from the cache
                    214: */
                    215: PRIVATE void HTTCPCacheRemoveElement ARGS1(host_info *, element)
                    216: {
                    217:     if (!hostcache) {
2.27      frystyk   218:         if (PROT_TRACE)
2.36      frystyk   219:             fprintf(TDEST, "HostCache... Remove not done, no cache\n");
2.13      frystyk   220:         return;
                    221:     }
2.36      frystyk   222:     if (PROT_TRACE) fprintf(TDEST, "HostCache... Remove `%s' from cache\n",
2.27      frystyk   223:                            HTAtom_name(element->hostname));
                    224:     HTList_removeObject(hostcache, (void *) element);
2.22      frystyk   225:     if (*element->addrlist)
                    226:        free(*element->addrlist);
2.13      frystyk   227:     if (element->addrlist)
                    228:        free(element->addrlist);
                    229:     if (element->weight)
                    230:        free(element->weight);
                    231:     free(element);
                    232: }
                    233: 
                    234: 
2.32      frystyk   235: /*                                                             HTTCPCacheRemoveAll
                    236: **
                    237: **     Cleans up the memory. Called by HTLibTerminate
                    238: */
                    239: PUBLIC void HTTCPCacheRemoveAll NOARGS
                    240: {
                    241:     if (hostcache) {
                    242:        HTList *cur = hostcache;
                    243:        host_info *pres;
                    244:        while ((pres = (host_info *) HTList_nextObject(cur))) {
                    245:            if (*pres->addrlist)
                    246:                free(*pres->addrlist);
                    247:            if (pres->addrlist)
                    248:                free(pres->addrlist);
                    249:            if (pres->weight)
                    250:                free(pres->weight);
                    251:            free(pres);
                    252:        }
                    253:        HTList_delete(hostcache);
                    254:        hostcache = NULL;
                    255:     }
                    256: }
                    257: 
                    258: 
2.13      frystyk   259: /*                                                     HTTCPCacheRemoveHost
                    260: **
                    261: **     Removes the corresponding entrance in the cache
                    262: */
                    263: PRIVATE void HTTCPCacheRemoveHost ARGS1(char *, host)
                    264: {
                    265:     HTAtom *hostatom = HTAtom_for(host);
                    266:     HTList *cur = hostcache;
                    267:     host_info *pres = NULL;
                    268:     if (!hostcache) {
2.36      frystyk   269:        if (PROT_TRACE)
                    270:            fprintf(TDEST, "HostCache... Remove host not done, no cache\n");
2.13      frystyk   271:        return;
                    272:     }
                    273:     while ((pres = (host_info *) HTList_nextObject(cur)) != NULL) {
                    274:        if (pres->hostname == hostatom) {
                    275:            break;
                    276:        }
                    277:     }
                    278:     if (pres)
                    279:        HTTCPCacheRemoveElement(pres);
                    280: }
                    281: 
                    282: 
                    283: /*                                                     HTTCPCacheGarbage
                    284: **
                    285: **     Remove the element with the lowest hit rate
                    286: */
                    287: PRIVATE void HTTCPCacheGarbage NOARGS
                    288: {
                    289:     HTList *cur = hostcache;
                    290:     host_info *pres, *worst_match = NULL;
                    291:     unsigned int worst_hits = 30000;             /* Should use UINT_MAX :-( */
                    292:     if (!hostcache) {
2.27      frystyk   293:        if (PROT_TRACE)
2.36      frystyk   294:            fprintf(TDEST, "HostCache... Garbage collection not done, no cache\n");
2.13      frystyk   295:        return;
                    296:     }
                    297: 
                    298:     /* Seek for worst element */
                    299:     while ((pres = (host_info *) HTList_nextObject(cur))) {
                    300:        if (!worst_match || pres->hits <= worst_hits) {
                    301:            worst_match = pres;
                    302:            worst_hits = pres->hits;
                    303:        }
                    304:     }
                    305:     if (worst_match)
                    306:        HTTCPCacheRemoveElement(worst_match);
                    307: }
                    308: 
                    309: 
                    310: /*                                                     HTTCPCacheAddElement
                    311: **
                    312: **     Add an element to the cache of visited hosts. Note that this function
                    313: **     requires the system implemented structure hostent and not our own
2.24      frystyk   314: **     host_info. The homes variable indicates the number of
                    315: **     IP addresses found.
2.13      frystyk   316: **
                    317: **      Returns new element if OK NULL if error
                    318: */
                    319: PRIVATE host_info *HTTCPCacheAddElement ARGS2(HTAtom *, host,
                    320:                                              struct hostent *, element)
                    321: {
2.25      frystyk   322:     host_info *newhost;
2.22      frystyk   323:     char *addr;
                    324:     char **index = element->h_addr_list;
                    325:     int cnt = 1;
2.13      frystyk   326:     if (!host || !element) {
2.27      frystyk   327:        if (PROT_TRACE)
2.36      frystyk   328:            fprintf(TDEST, "HostCache... Bad argument to add to cache\n");
2.13      frystyk   329:        return NULL;
                    330:     }
2.22      frystyk   331:     while(*index++)
                    332:        cnt++;
2.25      frystyk   333:     if ((newhost = (host_info *) calloc(1, sizeof(host_info))) == NULL ||
                    334:        (newhost->addrlist = (char **) calloc(1, cnt*sizeof(char*))) == NULL ||
2.22      frystyk   335:        (addr = (char *) calloc(1, cnt*element->h_length)) == NULL)
2.18      frystyk   336:        outofmem(__FILE__, "HTTCPCacheAddElement");
2.25      frystyk   337:     newhost->hostname = host;
2.22      frystyk   338:     index = element->h_addr_list;
                    339:     cnt = 0;
                    340:     while (*index) {
2.25      frystyk   341:        *(newhost->addrlist+cnt) = addr+cnt*element->h_length;
                    342:        memcpy((void *) *(newhost->addrlist+cnt++), *index++,
                    343:               element->h_length);
2.22      frystyk   344:     }
2.25      frystyk   345:     newhost->homes = cnt;
2.37      frystyk   346:     if ((newhost->weight = (double *) calloc(newhost->homes,
                    347:                                            sizeof(double))) == NULL)
2.24      frystyk   348:        outofmem(__FILE__, "HTTCPCacheAddElement");
                    349: 
2.25      frystyk   350:     newhost->addrlength = element->h_length;
2.13      frystyk   351:     if (!hostcache)
                    352:        hostcache = HTList_new();
                    353: 
2.27      frystyk   354:     if (PROT_TRACE) {
2.25      frystyk   355:        if (newhost->homes == 1)
2.36      frystyk   356:            fprintf(TDEST, "HostCache... Adding single-homed host `%s'\n",
2.24      frystyk   357:                    HTAtom_name(host));
2.13      frystyk   358:        else
2.36      frystyk   359:            fprintf(TDEST, "HostCache... Adding host `%s' with %d homes\n",
2.25      frystyk   360:                    HTAtom_name(host), newhost->homes);
2.13      frystyk   361:     }
2.25      frystyk   362:     HTList_addObject(hostcache, (void *) newhost);
2.13      frystyk   363:     HTCacheSize++;                             /* Update number of elements */
2.25      frystyk   364:     return newhost;
2.13      frystyk   365: }
                    366: 
                    367: 
                    368: /*                                                                   HTTCPAddrWeights
                    369: **
                    370: **     This function calculates the weights of the different IP addresses
                    371: **     on a multi homed host. Each weight is calculated as
                    372: **
                    373: **             w(n+1) = w(n)*a + (1-a) * deltatime
                    374: **             a = exp(-1/Neff)
                    375: **             Neff is the effective number of samples used
                    376: **             deltatime is time spend on making a connection
                    377: **
                    378: **     A short window (low Neff) gives a high sensibility, but this is
                    379: **     required as we can't expect a lot of data to test on.
                    380: **
                    381: */
                    382: PUBLIC void HTTCPAddrWeights ARGS2(char *, host, time_t, deltatime)
                    383: {
                    384:     HTAtom *hostatom = HTAtom_for(host);
                    385:     HTList *cur = hostcache;
                    386:     host_info *pres = NULL;
                    387:     if (!hostcache) {
2.36      frystyk   388:        fprintf(TDEST, "HostCache... Weights not calculated, no cache\n");
2.13      frystyk   389:        return;
                    390:     }
2.24      frystyk   391:     /* Skip any port number from host name */
                    392:     if (strchr(host, ':')) {
                    393:        char *newhost = NULL;
                    394:        char *strptr;
                    395:        StrAllocCopy(newhost, host);
                    396:        strptr = strchr(newhost, ':');
                    397:        *strptr = '\0';
                    398:        hostatom = HTAtom_for(newhost);
                    399:        free(newhost);
                    400:     } else
                    401:        hostatom = HTAtom_for(host);
                    402:     
2.13      frystyk   403:     while ((pres = (host_info *) HTList_nextObject(cur)) != NULL) {
                    404:        if (pres->hostname == hostatom) {
                    405:            break;
                    406:        }
                    407:     }
2.24      frystyk   408:     if (pres) {
2.13      frystyk   409:        int cnt;
2.37      frystyk   410:        CONST double passive = 0.9;       /* Factor for all passive IP_addrs */
2.13      frystyk   411: #if 0
2.14      frystyk   412:        CONST int Neff = 3;
2.37      frystyk   413:        CONST double alpha = exp(-1.0/Neff);
2.13      frystyk   414: #else
2.37      frystyk   415:        CONST double alpha = 0.716531310574;    /* Doesn't need the math lib */
2.13      frystyk   416: #endif
2.24      frystyk   417:        for (cnt=0; cnt<pres->homes; cnt++) {
2.13      frystyk   418:            if (cnt == pres->offset) {
                    419:                *(pres->weight+pres->offset) = *(pres->weight+pres->offset)*alpha + (1.0-alpha)*deltatime;
                    420:            } else {
                    421:                *(pres->weight+cnt) = *(pres->weight+cnt) * passive;
                    422:            }
2.24      frystyk   423:            if (PROT_TRACE)
2.36      frystyk   424:                fprintf(TDEST, "AddrWeights. Home %d has weight %4.2f\n", cnt,
2.24      frystyk   425:                        *(pres->weight+cnt));
2.13      frystyk   426:        }
2.27      frystyk   427:     } else if (PROT_TRACE) {
2.36      frystyk   428:        fprintf(TDEST, "HostCache... Weights not calculated, host not found in cache: `%s\'\n", host);
2.13      frystyk   429:     }
                    430: }
                    431: 
2.19      frystyk   432: /* ------------------------------------------------------------------------- */
                    433: /*                          HOST NAME FUNCTIONS                             */
                    434: /* ------------------------------------------------------------------------- */
                    435: 
                    436: #ifndef DECNET  /* Function only used below for a trace message */
                    437: 
                    438: /*     Produce a string for an Internet address
                    439: **     ----------------------------------------
                    440: **
                    441: ** On exit,
                    442: **     returns a pointer to a static string which must be copied if
2.41      frystyk   443: **             it is to be kept.
2.19      frystyk   444: */
2.41      frystyk   445: 
2.19      frystyk   446: PUBLIC CONST char * HTInetString ARGS1(SockA *, sin)
                    447: {
2.41      frystyk   448: #if 0
                    449:     /* This dumps core on some Sun systems :-(. The problem is now, that 
                    450:        the current implememtation only works for IP-addresses and not in
                    451:        other address spaces. */
                    452:     return inet_ntoa(sin->sin_addr);
                    453: #endif
2.19      frystyk   454:     static char string[16];
                    455:     sprintf(string, "%d.%d.%d.%d",
                    456:            (int)*((unsigned char *)(&sin->sin_addr)+0),
                    457:            (int)*((unsigned char *)(&sin->sin_addr)+1),
                    458:            (int)*((unsigned char *)(&sin->sin_addr)+2),
                    459:            (int)*((unsigned char *)(&sin->sin_addr)+3));
                    460:     return string;
                    461: }
                    462: #endif /* Decnet */
                    463: 
2.13      frystyk   464: 
                    465: /*                                                          HTGetHostByName
                    466: **
                    467: **     Searched first the local cache then asks the DNS for an address of
                    468: **     the host specified.
                    469: **
2.24      frystyk   470: **      Returns:       >0 if OK the number of homes are returned
                    471: **                     -1 if error
2.13      frystyk   472: */
2.50      frystyk   473: PUBLIC int HTGetHostByName ARGS4(HTRequest *, request,
                    474:                                 char *, host, SockA *, sin, BOOL, use_cur)
2.13      frystyk   475: {
                    476:     HTAtom *hostatom = HTAtom_for(host);
                    477:     host_info *pres = NULL;
                    478:     if (!hostcache)
                    479:        hostcache = HTList_new();                      /* First time through */
                    480:     else {
                    481:        HTList *cur = hostcache;                             /* Search cache */
                    482:        while ((pres = (host_info *) HTList_nextObject(cur)) != NULL) {
                    483:            if (pres->hostname == hostatom) {
2.27      frystyk   484:                if (PROT_TRACE)
2.36      frystyk   485:                    fprintf(TDEST, "HostByName.. Host `%s\' found in cache.\n", host);
2.13      frystyk   486:                break;
                    487:            }
                    488:        }
                    489:     }
                    490:     
                    491:     /* If the host was not found in the cache, then do gethostbyname.
2.24      frystyk   492:        If we are talking to a multi homed host then take the IP address with
                    493:        the lowest weight. If `use_cur'=YES then use current IP-address */
2.13      frystyk   494:     if (pres) {
2.24      frystyk   495:        if (pres->homes > 1 && !use_cur) {
2.13      frystyk   496:            int cnt;
2.37      frystyk   497:            double best_weight = 1e30;              /* Should be FLT_MAX :-( */
2.24      frystyk   498:            for (cnt=0; cnt<pres->homes; cnt++) {
2.13      frystyk   499:                if (*(pres->weight+cnt) < best_weight) {
                    500:                    best_weight = *(pres->weight+cnt);
                    501:                    pres->offset = cnt;
                    502:                }
                    503:            }
2.24      frystyk   504:        }
                    505:        pres->hits++;            /* Update total number of hits on this host */
2.13      frystyk   506:     } else {                                           /* Go and ask for it */
                    507:        struct hostent *hostelement;                          /* see netdb.h */
2.47      frystyk   508: #ifdef HT_REENTRANT
                    509:        int thd_errno;
                    510:        char buffer[HOSTENT_MAX];
                    511:        struct hostent result;                        /* For gethostbyname_r */
2.50      frystyk   512:        HTProgress(request, HT_PROG_DNS, host);
2.47      frystyk   513:        if ((hostelement = gethostbyname_r(host, &result, buffer,
                    514:                                           HOSTENT_MAX, &thd_errno)) == NULL) {
                    515: #else
2.50      frystyk   516:        HTProgress(request, HT_PROG_DNS, host);
2.13      frystyk   517:        if ((hostelement = gethostbyname(host)) == NULL) {
2.47      frystyk   518: #endif
2.27      frystyk   519:            if (PROT_TRACE)
2.36      frystyk   520:                fprintf(TDEST, "HostByName.. Can't find internet node name `%s'.\n", host);
2.13      frystyk   521:            return -1;
                    522:        }
                    523:        
                    524:        /* Add element to the cache and maybe do garbage collection */
                    525:        if (HTCacheSize >= HTConCacheSize)
                    526:            HTTCPCacheGarbage();
                    527:        if ((pres = HTTCPCacheAddElement(hostatom, hostelement)) == NULL) {
                    528:            return -1;
                    529:        }
                    530:     }
                    531:     
                    532:     /* Update socket structure using the element with the lowest weight. On
                    533:        single homed hosts it means the first value */
                    534:     memcpy(&sin->sin_addr, *(pres->addrlist+pres->offset), pres->addrlength);
2.24      frystyk   535:     return pres->homes;
2.13      frystyk   536: }
                    537: 
                    538: 
2.19      frystyk   539: /*
                    540: **     Get host name of the machine on the other end of a socket.
                    541: **
                    542: */
                    543: PUBLIC char * HTGetHostBySock ARGS1(int, soc)
                    544: {
                    545:     struct sockaddr addr;
                    546:     int len = sizeof(struct sockaddr);
                    547:     struct in_addr *iaddr;
2.47      frystyk   548:     char *name = NULL;
2.19      frystyk   549:     struct hostent * phost;            /* Pointer to host -- See netdb.h */
2.47      frystyk   550: #ifdef HT_REENTRANT
                    551:     int thd_errno;
                    552:     char buffer[HOSTENT_MAX];
                    553:     struct hostent result;                           /* For gethostbyaddr_r */
                    554: #endif
2.19      frystyk   555: 
                    556: #ifdef DECNET  /* Decnet ain't got no damn name server 8#OO */
                    557:     return NULL;
                    558: #else
                    559:     if (getpeername(soc, &addr, &len) < 0)
                    560:        return NULL;
2.47      frystyk   561:     iaddr = &(((struct sockaddr_in *)&addr)->sin_addr);
2.19      frystyk   562: 
2.47      frystyk   563: #ifdef HT_REENTRANT
                    564:     phost = gethostbyaddr_r((char *) iaddr, sizeof(struct in_addr), AF_INET,
                    565:                            &result, buffer, HOSTENT_MAX, &thd_errno);
                    566: #else
                    567:     phost = gethostbyaddr((char *) iaddr, sizeof(struct in_addr), AF_INET);
                    568: #endif
2.19      frystyk   569:     if (!phost) {
2.27      frystyk   570:        if (PROT_TRACE)
2.36      frystyk   571:            fprintf(TDEST, "TCP......... Can't find internet node name for peer!!\n");
2.19      frystyk   572:        return NULL;
                    573:     }
                    574:     StrAllocCopy(name, phost->h_name);
2.36      frystyk   575:     if (PROT_TRACE) fprintf(TDEST, "TCP......... Peer name is `%s'\n", name);
2.19      frystyk   576:     return name;
                    577: 
                    578: #endif /* not DECNET */
                    579: }
                    580: 
                    581: 
1.1       timbl     582: /*     Parse a network node address and port
                    583: **     -------------------------------------
                    584: **
                    585: ** On entry,
                    586: **     str     points to a string with a node name or number,
                    587: **             with optional trailing colon and port number.
                    588: **     sin     points to the binary internet or decnet address field.
                    589: **
2.24      frystyk   590: ** On exit,    -1      If error
                    591: **             >0      If OK the number of homes on the host
1.1       timbl     592: **     *sin    is filled in. If no port is specified in str, that
                    593: **             field is left unchanged in *sin.
2.13      frystyk   594: **
                    595: ** NOTE:       It is assumed that any portnumber and numeric host address
                    596: **             is given in decimal notation. Separation character is '.'
1.1       timbl     597: */
2.50      frystyk   598: PUBLIC int HTParseInet ARGS4(HTRequest *, request,
                    599:                             SockA *, sin, CONST char *, str, BOOL, use_cur)
1.1       timbl     600: {
2.13      frystyk   601:     char *host = NULL;
2.24      frystyk   602:     int status = 0;
2.13      frystyk   603:     StrAllocCopy(host, str);                 /* Take a copy we can mutilate */
1.1       timbl     604: 
2.13      frystyk   605:     /* Parse port number if present. */    
                    606:     {
                    607:        char *port;
                    608:        if ((port=strchr(host, ':'))) {
                    609:            *port++ = 0;                                    /* Chop off port */
                    610:            if (isdigit(*port)) {
2.27      frystyk   611: 
1.1       timbl     612: #ifdef DECNET
2.13      frystyk   613:                sin->sdn_objnum = (unsigned char)(strtol(port, (char**)0, 10));
                    614: #else /* Internet */
                    615:                sin->sin_port = htons(atol(port));
1.1       timbl     616: #endif
2.13      frystyk   617:            } else {
2.24      frystyk   618:                if (PROT_TRACE)
2.36      frystyk   619:                    fprintf(TDEST, "ParseInet... No port indicated\n");
2.24      frystyk   620:                free(host);
                    621:                return -1;
2.13      frystyk   622:            }
1.1       timbl     623:        }
2.13      frystyk   624:     }
1.1       timbl     625: 
2.13      frystyk   626:     /* Parse Internet host */
1.1       timbl     627: #ifdef DECNET
                    628:     /* read Decnet node name. @@ Should know about DECnet addresses, but it's
                    629:        probably worth waiting until the Phase transition from IV to V. */
                    630: 
                    631:     sin->sdn_nam.n_len = min(DN_MAXNAML, strlen(host));  /* <=6 in phase 4 */
                    632:     strncpy (sin->sdn_nam.n_name, host, sin->sdn_nam.n_len + 1);
                    633: 
2.36      frystyk   634:     if (PROT_TRACE) fprintf(TDEST,  
1.1       timbl     635:        "DECnet: Parsed address as object number %d on host %.6s...\n",
                    636:                      sin->sdn_objnum, host);
                    637: 
2.13      frystyk   638: #else /* Internet */
1.1       timbl     639: 
2.13      frystyk   640:     /* Parse host number if present */
                    641:     {
                    642:        BOOL numeric = YES;
                    643:        char *strptr = host;
                    644:        while (*strptr) {
                    645:            if (!isdigit(*strptr) && *strptr != '.') {
                    646:                numeric = NO;
                    647:                break;
                    648:            }
                    649:            ++strptr;
                    650:        }
                    651:        if (numeric) {
2.51      frystyk   652: #ifdef GUSI
                    653:            sin->sin_addr = inet_addr(host);             /* See netinet/in.h */
                    654: #else
2.13      frystyk   655:            sin->sin_addr.s_addr = inet_addr(host);       /* See arpa/inet.h */
2.51      frystyk   656: #endif
2.13      frystyk   657:        } else {
2.50      frystyk   658:            if ((status = HTGetHostByName(request, host, sin, use_cur)) < 0) {
2.13      frystyk   659:                free(host);
                    660:                return -1;
                    661:            }
                    662:        }
2.27      frystyk   663:        if (PROT_TRACE) {
2.36      frystyk   664:            fprintf(TDEST, "ParseInet... Parsed address as port %d on %s\n",
2.13      frystyk   665:                    (int) ntohs(sin->sin_port),
                    666:                    HTInetString(sin));
1.1       timbl     667:        }
                    668:     }
                    669: #endif  /* Internet vs. Decnet */
2.13      frystyk   670:     free(host);
2.24      frystyk   671:     return status;
1.1       timbl     672: }
                    673: 
                    674: 
2.24      frystyk   675: /*                                                             HTGetDomainName
                    676: **     Returns the current domain name without the local host name.
                    677: **     The response is pointing to a static area that might be changed
2.36      frystyk   678: **     using HTSetHostName().
                    679: **
                    680: **     Returns NULL on error, "" if domain name is not found
2.24      frystyk   681: */
                    682: PUBLIC CONST char *HTGetDomainName NOARGS
                    683: {
                    684:     CONST char *host = HTGetHostName();
                    685:     char *domain;
                    686:     if (host && *host) {
                    687:        if ((domain = strchr(host, '.')) != NULL)
                    688:            return ++domain;
                    689:        else
2.36      frystyk   690:            return "";
2.24      frystyk   691:     } else
                    692:        return NULL;
                    693: }
                    694: 
                    695: 
2.19      frystyk   696: /*                                                             HTSetHostName
                    697: **     Sets the current hostname inclusive domain name.
                    698: **     If this is not set then the default approach is used using
                    699: **     HTGetHostname().
                    700: */
                    701: PUBLIC void HTSetHostName ARGS1(char *, host)
                    702: {
2.24      frystyk   703:     if (host && *host) {
                    704:        char *strptr;
2.19      frystyk   705:        StrAllocCopy(hostname, host);
2.24      frystyk   706:        strptr = hostname;
                    707:        while (*strptr) {
                    708:            *strptr = TOLOWER(*strptr);
                    709:            strptr++;
                    710:        }
                    711:        if (*(hostname+strlen(hostname)-1) == '.')    /* Remove trailing dot */
                    712:            *(hostname+strlen(hostname)-1) = '\0';
                    713:     } else {
2.36      frystyk   714:        if (PROT_TRACE) fprintf(TDEST, "SetHostName. Bad argument ignored\n");
2.19      frystyk   715:     }
                    716: }
                    717: 
                    718: 
                    719: /*                                                             HTGetHostName
2.18      frystyk   720: **     Returns the name of this host. It uses the following algoritm:
                    721: **
                    722: **     1) gethostname()
                    723: **     2) if the hostname doesn't contain any '.' try to read
                    724: **        /etc/resolv.conf. If there is no domain line in this file then
                    725: **     3) Try getdomainname and do as the man pages say for resolv.conf (sun)
2.49      frystyk   726: **        If there is no domain line in this file, then it is derived
                    727: **        from the domain name set by the domainname(1) command, usually
                    728: **        by removing the first component. For example, if the domain-
                    729: **        name is set to ``foo.podunk.edu'' then the default domain name
                    730: **        used will be ``pudunk.edu''.
2.18      frystyk   731: **
                    732: **     This is the same procedure as used by res_init() and sendmail.
2.16      frystyk   733: **
                    734: **     Return: hostname on success else NULL
                    735: */
2.19      frystyk   736: PUBLIC CONST char * HTGetHostName NOARGS
1.1       timbl     737: {
2.18      frystyk   738:     BOOL got_it = NO;
                    739:     FILE *fp;
2.16      frystyk   740:     char name[MAXHOSTNAMELEN+1];
2.18      frystyk   741:     if (hostname) {                                      /* If already done */
                    742:        if (*hostname)
                    743:            return hostname;
                    744:        else
                    745:            return NULL;                    /* We couldn't get the last time */
                    746:     }
2.16      frystyk   747:     *(name+MAXHOSTNAMELEN) = '\0';
2.52    ! frystyk   748: 
        !           749: #ifndef NO_GETHOSTNAME
2.16      frystyk   750:     if (gethostname(name, MAXHOSTNAMELEN)) {        /* Maybe without domain */
2.27      frystyk   751:        if (PROT_TRACE)
2.36      frystyk   752:            fprintf(TDEST, "HostName.... Can't get host name\n");
2.16      frystyk   753:        return NULL;
                    754:     }
2.27      frystyk   755:     if (PROT_TRACE)
2.36      frystyk   756:        fprintf(TDEST, "HostName.... Local host name is  `%s\'\n", name);
2.16      frystyk   757:     StrAllocCopy(hostname, name);
2.24      frystyk   758:     {
                    759:        char *strptr = strchr(hostname, '.');
                    760:        if (strptr != NULL)                                /* We have it all */
                    761:            got_it = YES;
                    762:     }
2.16      frystyk   763: 
2.52    ! frystyk   764: #ifndef NO_RESOLV_CONF
2.18      frystyk   765:     /* Now try the resolver config file */
2.24      frystyk   766:     if (!got_it && (fp = fopen(RESOLV_CONF, "r")) != NULL) {
2.18      frystyk   767:        char buffer[80];
                    768:        *(buffer+79) = '\0';
                    769:        while (fgets(buffer, 79, fp)) {
                    770:            if (!strncasecomp(buffer, "domain", 6)) {   
                    771:                char *domainstr = buffer+6;
                    772:                char *end;
                    773:                while (*domainstr == ' ' || *domainstr == '\t')
                    774:                    domainstr++;
                    775:                end = domainstr;
                    776:                while (*end && !isspace(*end))
                    777:                    end++;
                    778:                *end = '\0';
                    779:                if (*domainstr) {
                    780:                    StrAllocCat(hostname, ".");
                    781:                    StrAllocCat(hostname, domainstr);
                    782:                    got_it = YES;
                    783:                    break;
                    784:                }
                    785:            }
                    786:        }
                    787:        fclose(fp);
2.16      frystyk   788:     }
2.52    ! frystyk   789: #endif /* NO_RESOLV_CONF */
2.16      frystyk   790: 
2.52    ! frystyk   791: #ifndef NO_GETDOMAINNAME
2.18      frystyk   792:     /* If everything else has failed then try getdomainname */
                    793:     if (!got_it) {
                    794:        if (getdomainname(name, MAXHOSTNAMELEN)) {
2.27      frystyk   795:            if (PROT_TRACE)
2.36      frystyk   796:                fprintf(TDEST, "HostName.... Can't get domain name\n");
2.24      frystyk   797:            StrAllocCopy(hostname, "");
2.18      frystyk   798:            return NULL;
                    799:        }
                    800: 
                    801:        /* If the host name and the first part of the domain name are different
                    802:           then use the former as it is more exact (I guess) */
                    803:        if (strncmp(name, hostname, (int) strlen(hostname))) {
                    804:            char *domain = strchr(name, '.');
2.50      frystyk   805:            if (!domain)
                    806:                domain = name;
                    807:            StrAllocCat(hostname, domain);
2.18      frystyk   808:        }
2.16      frystyk   809:     }
2.36      frystyk   810: #endif /* NO_GETDOMAINNAME */
2.23      duns      811: 
2.24      frystyk   812:     {
                    813:        char *strptr = hostname;
                    814:        while (*strptr) {           
                    815:            *strptr = TOLOWER(*strptr);
                    816:            strptr++;
                    817:        }
                    818:        if (*(hostname+strlen(hostname)-1) == '.')    /* Remove trailing dot */
                    819:            *(hostname+strlen(hostname)-1) = '\0';
                    820:     }
2.52    ! frystyk   821: #endif /* NO_GETHOSTNAME */
        !           822: 
2.27      frystyk   823:     if (PROT_TRACE)
2.36      frystyk   824:        fprintf(TDEST, "HostName.... Full host name is `%s\'\n", hostname);
2.18      frystyk   825:     return hostname;
2.13      frystyk   826: }
                    827: 
2.19      frystyk   828: 
2.32      frystyk   829: /*
                    830: **     Free the host name. Called from HTLibTerminate
                    831: */
                    832: PUBLIC void HTFreeHostName NOARGS
                    833: {
                    834:     FREE(hostname);
                    835: }
                    836: 
                    837: 
2.19      frystyk   838: /*                                                            HTSetMailAddress
                    839: **     Sets the current mail address plus host name and domain name.
                    840: **     If this is not set then the default approach is used using
2.27      frystyk   841: **     HTGetMailAddress(). If the argument is NULL or "" then HTGetMailAddress
                    842: **     returns NULL on a succeding request.
2.19      frystyk   843: */
                    844: PUBLIC void HTSetMailAddress ARGS1(char *, address)
                    845: {
2.27      frystyk   846:     if (!address || !*address)
                    847:        StrAllocCopy(mailaddress, "");
                    848:     else
2.19      frystyk   849:        StrAllocCopy(mailaddress, address);
2.27      frystyk   850:     if (TRACE)
2.36      frystyk   851:        fprintf(TDEST, "SetMailAdr.. Set mail address to `%s\'\n",
2.27      frystyk   852:                mailaddress);
2.19      frystyk   853: }
                    854: 
                    855: 
                    856: /*                                                            HTGetMailAddress
                    857: **
                    858: **     Get the mail address of the current user on the current host. The
                    859: **     domain name used is the one initialized in HTSetHostName or
                    860: **     HTGetHostName. The login name is determined using (ordered):
                    861: **
                    862: **             getlogin
                    863: **             getpwuid(getuid())
                    864: **
                    865: **     The weakness about the last attempt is if the user has multiple
                    866: **     login names each with the same user ID. If this fails as well then:
                    867: **
                    868: **             LOGNAME environment variable
                    869: **             USER environment variable
                    870: **
                    871: **     Returns NULL if error else pointer to static string
                    872: */
                    873: PUBLIC CONST char * HTGetMailAddress NOARGS
                    874: {
2.47      frystyk   875: #ifdef HT_REENTRANT
                    876:     char name[LOGNAME_MAX+1];                             /* For getlogin_r */
                    877: #endif
2.19      frystyk   878:     char *login;
                    879:     CONST char *domain;
                    880:     struct passwd *pw_info;
2.21      frystyk   881:     if (mailaddress) {
                    882:        if (*mailaddress)
                    883:            return mailaddress;
                    884:        else
                    885:            return NULL;       /* No luck the last time so we wont try again */
                    886:     }
2.23      duns      887: 
2.36      frystyk   888: #ifdef VMS
2.23      duns      889:     if ((login = (char *) cuserid(NULL)) == NULL) {
2.36      frystyk   890:         if (PROT_TRACE) fprintf(TDEST, "MailAddress. cuserid returns NULL\n");
                    891:     }
                    892: #else
2.40      frystyk   893: #ifdef WIN32 
2.41      frystyk   894:     login = getenv("USERNAME") ;
2.40      frystyk   895: #else 
2.41      frystyk   896: #ifdef _WINDOWS
2.36      frystyk   897:     login = "PCUSER";                            /* @@@ COULD BE BETTER @@@ */
2.51      frystyk   898: #else
                    899: #ifdef GUSI
                    900:     if ((login = getenv("LOGNAME")) == NULL) 
                    901:        login = "MACUSER";
2.36      frystyk   902: #else /* Unix like... */
2.47      frystyk   903: #ifdef HT_REENTRANT
                    904:     if ((login = (char *) getlogin_r(name, LOGNAME_MAX)) == NULL) {
                    905: #else
2.34      roeber    906:     if ((login = (char *) getlogin()) == NULL) {
2.47      frystyk   907: #endif
2.36      frystyk   908:        if (PROT_TRACE)
                    909:            fprintf(TDEST, "MailAddress. getlogin returns NULL\n");
                    910:        if ((pw_info = getpwuid(getuid())) == NULL) {
                    911:            if (PROT_TRACE)
                    912:                fprintf(TDEST, "MailAddress. getpwid returns NULL\n");
                    913:            if ((login = getenv("LOGNAME")) == NULL) {
                    914:                if (PROT_TRACE)
                    915:                    fprintf(TDEST, "MailAddress. LOGNAME not found\n");
                    916:                if ((login = getenv("USER")) == NULL) {
                    917:                    if (PROT_TRACE)
                    918:                        fprintf(TDEST,"MailAddress. USER not found\n");
                    919:                    return NULL;                /* I GIVE UP */
                    920:                }
                    921:            }
                    922:        } else
                    923:            login = pw_info->pw_name;
                    924:     }
2.51      frystyk   925: #endif /* GUSI */
                    926: #endif /* _WINDOWS */
                    927: #endif /* WIN32 */
                    928: #endif /* VMS */
2.34      roeber    929: 
2.19      frystyk   930:     if (login) {
                    931:        StrAllocCopy(mailaddress, login);
                    932:        StrAllocCat(mailaddress, "@");
                    933:        if ((domain = HTGetHostName()) != NULL)
                    934:            StrAllocCat(mailaddress, domain);
2.21      frystyk   935:        else {
                    936:            *mailaddress = '\0';
                    937:            return NULL;                        /* Domain name not available */
                    938:        }
2.19      frystyk   939:        return mailaddress;
                    940:     }
                    941:     return NULL;
                    942: }
2.32      frystyk   943: 
                    944: 
                    945: /*
                    946: **     Free the mail address. Called from HTLibTerminate
                    947: */
                    948: PUBLIC void HTFreeMailAddress NOARGS
                    949: {
                    950:     FREE(mailaddress);
                    951: }
                    952: 
2.19      frystyk   953: 
                    954: /* ------------------------------------------------------------------------- */
                    955: /*                   CONNECTION ESTABLISHMENT MANAGEMENT                    */
                    956: /* ------------------------------------------------------------------------- */
2.13      frystyk   957: 
                    958: /*                                                             HTDoConnect()
                    959: **
                    960: **     Note: Any port indication in URL, e.g., as `host:port' overwrites
                    961: **     the default_port value.
                    962: **
2.40      frystyk   963: **     returns         HT_ERROR        Error has occured or interrupted
                    964: **                     HT_OK           if connected
                    965: **                     HT_WOULD_BLOCK  if operation would have blocked
                    966: **                     HT_INTERRUPTED  if interrupted
2.13      frystyk   967: */
2.24      frystyk   968: PUBLIC int HTDoConnect ARGS5(HTNetInfo *, net, char *, url,
                    969:                             u_short, default_port, u_long *, addr,
                    970:                             BOOL, use_cur)
2.13      frystyk   971: {
                    972:     int status;
                    973:     char *p1 = HTParse(url, "", PARSE_HOST);
                    974:     char *at_sign;
                    975:     char *host;
                    976: 
                    977:     /* if theres an @ then use the stuff after it as a hostname */
2.27      frystyk   978:     if((at_sign = strchr(p1, '@')) != NULL)
2.13      frystyk   979:        host = at_sign+1;
                    980:     else
                    981:        host = p1;
2.24      frystyk   982:     if (!*host) {
                    983:        HTErrorAdd(net->request, ERR_FATAL, NO, HTERR_NO_HOST,
                    984:                   NULL, 0, "HTDoConnect");
                    985:        free(p1);
2.40      frystyk   986:        return HT_ERROR;
2.27      frystyk   987:     }
2.13      frystyk   988: 
2.44      frystyk   989:     /* Set up defaults */
2.36      frystyk   990:     if (net->sockfd==INVSOC) {
2.27      frystyk   991:        memset((void *) &net->sock_addr, '\0', sizeof(net->sock_addr));
2.13      frystyk   992: #ifdef DECNET
2.27      frystyk   993:        net->sock_addr.sdn_family = AF_DECnet;/* Family = DECnet, host order */
                    994:        net->sock_addr.sdn_objnum = DNP_OBJ;  /* Default: http object number */
2.13      frystyk   995: #else  /* Internet */
2.27      frystyk   996:        net->sock_addr.sin_family = AF_INET;
                    997:        net->sock_addr.sin_port = htons(default_port);
2.13      frystyk   998: #endif
2.27      frystyk   999:     }
2.41      frystyk  1000:                                       
2.24      frystyk  1001:     /* If we are trying to connect to a multi-homed host then loop here until
                   1002:        success or we have tried all IP-addresses */
                   1003:     do {
2.36      frystyk  1004:        if (net->sockfd==INVSOC) {
2.27      frystyk  1005:            int hosts;
2.44      frystyk  1006:            if (PROT_TRACE)
                   1007:                fprintf(TDEST, "HTDoConnect. Looking up `%s\'\n", host);
2.50      frystyk  1008:            if ((hosts = HTParseInet(net->request, &net->sock_addr,
                   1009:                                     host, use_cur)) < 0) {
2.27      frystyk  1010:                if (PROT_TRACE)
2.36      frystyk  1011:                    fprintf(TDEST, "HTDoConnect. Can't locate remote host `%s\'\n", host);
2.27      frystyk  1012:                HTErrorAdd(net->request, ERR_FATAL, NO, HTERR_NO_REMOTE_HOST,
                   1013:                           (void *) host, strlen(host), "HTDoConnect");
                   1014:                break;
2.41      frystyk  1015:            }
2.27      frystyk  1016:            if (!net->addressCount && hosts > 1)
                   1017:                net->addressCount = hosts;
                   1018: #ifdef DECNET
2.36      frystyk  1019:            if ((net->sockfd=socket(AF_DECnet, SOCK_STREAM, 0))==INVSOC)
2.27      frystyk  1020: #else
2.36      frystyk  1021:            if ((net->sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVSOC)
2.27      frystyk  1022: #endif
                   1023:            {
2.36      frystyk  1024:                HTErrorSysAdd(net->request, ERR_FATAL, socerrno, NO, "socket");
2.27      frystyk  1025:                break;
                   1026:            }
                   1027:            if (addr)
                   1028:                *addr = ntohl(net->sock_addr.sin_addr.s_addr);
                   1029:            if (PROT_TRACE)
2.36      frystyk  1030:                fprintf(TDEST, "HTDoConnect. Created socket number %d\n",
2.27      frystyk  1031:                        net->sockfd);
                   1032: 
2.28      frystyk  1033:            /* If non-blocking protocol then change socket status
2.50      frystyk  1034:            ** I use FCNTL so that I can ask the status before I set it.
                   1035:            ** See W. Richard Stevens (Advan. Prog. in UNIX environment, p.364)
                   1036:            ** Be CAREFULL with the old `O_NDELAY' - it will not work as read()
                   1037:            ** returns 0 when blocking and NOT -1. FNDELAY is ONLY for BSD and
                   1038:            ** does NOT work on SVR4 systems. O_NONBLOCK is POSIX.
                   1039:            */
2.45      frystyk  1040:            if (!HTProtocol_isBlocking(net->request)) {
2.41      frystyk  1041: #ifdef _WINDOWS 
                   1042:                {               /* begin windows scope  */
                   1043:                    HTRequest * rq = net->request;
                   1044:                    long levents = FD_READ | FD_WRITE | FD_ACCEPT | 
                   1045:                        FD_CONNECT | FD_CLOSE ;
                   1046:                    int rv = 0 ;
                   1047:                                    
                   1048: #ifndef _WIN32                 
                   1049:                    if (net->request->hwnd == 0) {
                   1050:                                        
                   1051:                    }
                   1052: #endif 
                   1053:                    /* N.B WSAAsyncSelect() turns on non-blocking I/O */
                   1054: 
                   1055:                    if (net->request->hwnd != 0) {
                   1056:                        rv = WSAAsyncSelect( net->sockfd, rq->hwnd, 
                   1057:                                            rq->winMsg, levents);
                   1058:                        if (rv == SOCKET_ERROR) {
                   1059:                            status = -1 ;
                   1060:                            if (PROT_TRACE) 
                   1061:                                fprintf(TDEST, 
                   1062:                                        "HTDoConnect: WSAAsyncSelect() fails: %d\n", 
                   1063:                                        WSAGetLastError());
                   1064:                        } /* error returns */
                   1065:                    } else {
                   1066:                        int enable = 1 ;
                   1067:                        status = IOCTL(net->sockfd, FIONBIO, &enable);
                   1068:                    }
                   1069:                } /* end scope */
                   1070: #else 
                   1071: #if defined(VMS)
2.36      frystyk  1072:                {
                   1073:                    int enable = 1;
                   1074:                    status = IOCTL(net->sockfd, FIONBIO, &enable);
                   1075:                }
                   1076: #else
2.27      frystyk  1077:                if((status = FCNTL(net->sockfd, F_GETFL, 0)) != -1) {
2.41      frystyk  1078:                    status |= O_NONBLOCK; /* POSIX */
2.27      frystyk  1079:                    status = FCNTL(net->sockfd, F_SETFL, status);
                   1080:                }
2.41      frystyk  1081: #endif /* VMS */
                   1082: #endif /* WINDOW */
2.43      frystyk  1083:                if (PROT_TRACE) {
                   1084:                    if (status == -1)
                   1085:                        fprintf(TDEST, "HTDoConnect. Can't make socket non-blocking\n");
                   1086:                    else
                   1087:                        fprintf(TDEST, "HTDoConnect. Using NON_BLOCKING I/O\n");
                   1088:                }
2.27      frystyk  1089:            }
                   1090:            
                   1091:            /* If multi-homed host then start timer on connection */
                   1092:            if (net->addressCount >= 1)
                   1093:                net->connecttime = time(NULL);
2.50      frystyk  1094: 
                   1095:            /* Update progress state */
                   1096:            HTProgress(net->request, HT_PROG_CONNECT, NULL);
2.41      frystyk  1097:        } /* IF socket is invalid */
                   1098:        
2.27      frystyk  1099:        /* Check for interrupt */
2.41      frystyk  1100:        if (HTThreadIntr(net->sockfd)) {
2.27      frystyk  1101:            if (NETCLOSE(net->sockfd) < 0)
2.36      frystyk  1102:                HTErrorSysAdd(net->request, ERR_FATAL, socerrno,NO,"NETCLOSE");
2.27      frystyk  1103:            HTThreadState(net->sockfd, THD_CLOSE);
2.36      frystyk  1104:            net->sockfd = INVSOC;
2.27      frystyk  1105:            free(p1);
                   1106:            return HT_INTERRUPTED;
                   1107:        }
2.41      frystyk  1108:        
2.27      frystyk  1109:        /* Do a connect */
                   1110:        status = connect(net->sockfd, (struct sockaddr *) &net->sock_addr,
                   1111:                         sizeof(net->sock_addr));
                   1112:        /*
                   1113:         * According to the Sun man page for connect:
                   1114:         *     EINPROGRESS         The socket is non-blocking and the  con-
                   1115:         *                         nection cannot be completed immediately.
                   1116:         *                         It is possible to select(2) for  comple-
                   1117:         *                         tion  by  selecting the socket for writ-
                   1118:         *                         ing.
                   1119:         * According to the Motorola SVR4 man page for connect:
                   1120:         *     EAGAIN              The socket is non-blocking and the  con-
                   1121:         *                         nection cannot be completed immediately.
                   1122:         *                         It is possible to select for  completion
                   1123:         *                         by  selecting  the  socket  for writing.
                   1124:         *                         However, this is only  possible  if  the
                   1125:         *                         socket  STREAMS  module  is  the topmost
                   1126:         *                         module on  the  protocol  stack  with  a
                   1127:         *                         write  service  procedure.  This will be
                   1128:         *                         the normal case.
                   1129:         */
2.41      frystyk  1130:        
2.27      frystyk  1131: #ifdef EAGAIN
2.36      frystyk  1132:        if ((status < 0) && ((socerrno==EINPROGRESS) || (socerrno==EAGAIN)))
2.41      frystyk  1133: #else 
2.40      frystyk  1134: #ifdef WSAEWOULDBLOCK     /* WinSock API */
                   1135:        if ((status == SOCKET_ERROR) && (socerrno == WSAEWOULDBLOCK))
                   1136: #else
2.41      frystyk  1137:        if ((status < 0) && (socerrno == EINPROGRESS))
                   1138: #endif /* WSAEWOULDBLOCK */
2.27      frystyk  1139: #endif /* EAGAIN */
2.24      frystyk  1140:        {
2.27      frystyk  1141:            if (PROT_TRACE)
2.36      frystyk  1142:                fprintf(TDEST, "HTDoConnect. WOULD BLOCK `%s'\n", host);
2.46      frystyk  1143:            HTThreadState(net->sockfd, THD_SET_CONNECT);
2.27      frystyk  1144:            free(p1);
                   1145:            return HT_WOULD_BLOCK;
2.24      frystyk  1146:        }
2.41      frystyk  1147:        
                   1148:        /* We have 4 situations: single OK, Pb and multi OK, pb */
2.27      frystyk  1149:        if (net->addressCount >= 1) {
2.48      frystyk  1150:            net->connecttime = time(NULL) - net->connecttime;
2.41      frystyk  1151:            if (status < 0) {                                    /* multi PB */
                   1152:                if (socerrno == EISCONN) { /* connect multi after would block*/
2.46      frystyk  1153:                    HTThreadState(net->sockfd, THD_CLR_CONNECT);
2.27      frystyk  1154:                    HTTCPAddrWeights(host, net->connecttime);
                   1155:                    free(p1);
                   1156:                    net->addressCount = 0;
2.41      frystyk  1157:                    if (PROT_TRACE)
                   1158:                        fprintf(TDEST, "HTDoConnect: Socket %ld already connected\n", net->sockfd) ;
2.40      frystyk  1159:                    return HT_OK;
2.27      frystyk  1160:                }
2.41      frystyk  1161: 
2.36      frystyk  1162:                HTErrorSysAdd(net->request, ERR_NON_FATAL, socerrno, NO,
                   1163:                              "connect");
2.27      frystyk  1164: 
                   1165:                /* I have added EINVAL `invalid argument' as this is what I 
                   1166:                   get back from a non-blocking connect where I should 
2.36      frystyk  1167:                   get `connection refused' on SVR4 */
2.41      frystyk  1168: 
2.36      frystyk  1169:                if (socerrno==ECONNREFUSED || socerrno==ETIMEDOUT ||
                   1170:                    socerrno==ENETUNREACH || socerrno==EHOSTUNREACH ||
                   1171: #ifdef __srv4__
                   1172:                    socerrno==EHOSTDOWN || socerrno==EINVAL)
                   1173: #else
                   1174:                    socerrno==EHOSTDOWN)
2.35      roeber   1175: #endif
2.27      frystyk  1176:                    net->connecttime += TCP_DELAY;
2.41      frystyk  1177:                else
2.27      frystyk  1178:                    net->connecttime += TCP_PENALTY;
2.40      frystyk  1179: 
2.41      frystyk  1180:                if (NETCLOSE(net->sockfd) < 0)
                   1181:                        HTErrorSysAdd(net->request, ERR_FATAL, socerrno, NO, 
                   1182:                                      "NETCLOSE");
                   1183:                HTThreadState(net->sockfd, THD_CLOSE);
                   1184:                net->sockfd = INVSOC;
                   1185:                HTTCPAddrWeights(host, net->connecttime);
                   1186:            } else {                                             /* multi OK */
2.27      frystyk  1187:                HTTCPAddrWeights(host, net->connecttime);
                   1188:                free(p1);
                   1189:                net->addressCount = 0;
2.40      frystyk  1190:                return HT_OK;
2.27      frystyk  1191:            }
2.41      frystyk  1192:         } else if (status < 0) {                               /* single PB */
                   1193:            if (socerrno==EISCONN) {     /* Connect single after would block */
2.46      frystyk  1194:                HTThreadState(net->sockfd, THD_CLR_CONNECT);
2.27      frystyk  1195:                net->addressCount = 0;
                   1196:                free(p1);
2.40      frystyk  1197:                return HT_OK;
2.24      frystyk  1198:            } else {
2.36      frystyk  1199:                HTErrorSysAdd(net->request, ERR_FATAL, socerrno, NO,
2.41      frystyk  1200:                          "connect");
2.27      frystyk  1201:                HTTCPCacheRemoveHost(host);
                   1202:                if (NETCLOSE(net->sockfd) < 0)
2.36      frystyk  1203:                    HTErrorSysAdd(net->request, ERR_FATAL, socerrno, NO,
                   1204:                                  "NETCLOSE");
2.27      frystyk  1205:                HTThreadState(net->sockfd, THD_CLOSE);
2.24      frystyk  1206:                break;
                   1207:            }
2.41      frystyk  1208:        } else {                                                /* single OK */
2.27      frystyk  1209:            free(p1);
                   1210:            net->addressCount = 0;
2.40      frystyk  1211:            return HT_OK;
2.24      frystyk  1212:        }
2.41      frystyk  1213:     } while (--net->addressCount);                      /* End of mega loop */
2.13      frystyk  1214: 
2.27      frystyk  1215:     if (PROT_TRACE)
2.41      frystyk  1216:         fprintf(TDEST, "HTDoConnect. Connect failed\n");
2.24      frystyk  1217:     free (p1);
                   1218:     net->addressCount = 0;
2.36      frystyk  1219:     net->sockfd = INVSOC;
2.40      frystyk  1220:     return HT_ERROR;
2.13      frystyk  1221: }
                   1222: 
                   1223: 
                   1224: /*                                                             HTDoAccept()
                   1225: **
                   1226: **     This function makes a non-blocking accept on a port and polls every
                   1227: **     second until MAX_ACCEPT_POLL or interrupted by user.
                   1228: **
                   1229: **     BUGS Interrupted is not yet implemented!!!
                   1230: **
2.27      frystyk  1231: **     Returns  HT_WOULD_BLOCK         if waiting
                   1232: **              0              if OK,
                   1233: **              -1             on error
2.13      frystyk  1234: */
2.15      frystyk  1235: PUBLIC int HTDoAccept ARGS1(HTNetInfo *, net)
2.13      frystyk  1236: {
                   1237:     SockA soc_address;                         /* SockA is defined in tcp.h */
                   1238:     int status;
                   1239:     int cnt;
                   1240:     int soc_addrlen = sizeof(soc_address);
2.36      frystyk  1241:     if (net->sockfd==INVSOC) {
                   1242:        if (PROT_TRACE) fprintf(TDEST, "HTDoAccept.. Bad socket number\n");
2.13      frystyk  1243:        return -1;
                   1244:     }
2.27      frystyk  1245: 
2.13      frystyk  1246:     /* First make the socket non-blocking */
2.36      frystyk  1247: #if defined(_WINDOWS) || defined(VMS)
2.23      duns     1248:     {
2.36      frystyk  1249:        int enable = 1;         /* Need the variable! */
                   1250:        status = IOCTL(net->sockfd, FIONBIO, enable);
2.23      duns     1251:     }
2.36      frystyk  1252: #else
2.15      frystyk  1253:     if((status = FCNTL(net->sockfd, F_GETFL, 0)) != -1) {
2.36      frystyk  1254:        status |= O_NONBLOCK;   /* POSIX */
2.15      frystyk  1255:        status = FCNTL(net->sockfd, F_SETFL, status);
2.13      frystyk  1256:     }
2.36      frystyk  1257: #endif
2.13      frystyk  1258:     if (status == -1) {
2.36      frystyk  1259:        HTErrorSysAdd(net->request, ERR_FATAL, socerrno, NO, "IOCTL");
2.13      frystyk  1260:        return -1;
                   1261:     }
                   1262: 
                   1263:     /* Now poll every sekund */
                   1264:     for(cnt=0; cnt<MAX_ACCEPT_POLL; cnt++) {
2.15      frystyk  1265:        if ((status = accept(net->sockfd, (struct sockaddr*) &soc_address,
2.36      frystyk  1266:                             &soc_addrlen)) != INVSOC) {
                   1267:            if (PROT_TRACE) fprintf(TDEST,
2.13      frystyk  1268:                               "HTDoAccept.. Accepted new socket %d\n", 
                   1269:                               status);
                   1270:            return status;
                   1271:        } else
2.36      frystyk  1272:            HTErrorSysAdd(net->request, ERR_WARN, socerrno, YES, "accept");
2.38      frystyk  1273:        SLEEP(1);
                   1274:     }
2.13      frystyk  1275:     
                   1276:     /* If nothing has happened */    
2.27      frystyk  1277:     if (PROT_TRACE)
2.36      frystyk  1278:        fprintf(TDEST, "HTDoAccept.. Timed out, no connection!\n");
2.15      frystyk  1279:     HTErrorAdd(net->request, ERR_FATAL, NO, HTERR_TIME_OUT, NULL, 0,
                   1280:               "HTDoAccept");
2.13      frystyk  1281:     return -1;
1.1       timbl    1282: }
2.27      frystyk  1283: 
1.1       timbl    1284: 

Webmaster