Annotation of libwww/Library/src/HTEvtLst.c, revision 2.16

2.4       eric        1: /*                                                                  HTEvtLst.c
2.1       frystyk     2: **     EVENT MANAGER
                      3: **
                      4: **     (c) COPYRIGHT MIT 1995.
                      5: **     Please first read the full copyright statement in the file COPYRIGH.
2.16    ! frystyk     6: **     @(#) $Id: HTEvtLst.c,v 2.15 1997/01/31 22:55:21 frystyk Exp $
2.1       frystyk     7: **
                      8: **     Updated HTEvent module 
                      9: **     This new module combines the functions of the old HTEvent module and 
                     10: **     the HTThread module. We retain the old HTThread module, but it
                     11: **     consists of calls to the HTEvent interfaces
                     12: **
                     13: ** Authors:
                     14: **     HFN     Henrik Frystyk <frystyk@w3.org>
                     15: **     CLB     Charlie Brooks <cbrooks@osf.org>
                     16: ** Bugs
                     17: **
                     18: */
                     19: 
                     20: /*   WSAAsyncSelect and windows app stuff need the following definitions:
                     21:  *   WWW_WIN_ASYNC - enable WSAAsyncSelect instead of select
                     22:  *   _WIN23 - win32 libararies - may be window or console app
                     23:  *   _WINSOCKAPI_ - using WINSOCK.DLL - not necessarily the async routines.
                     24:  *   _CONSOLE - the console app for NT
                     25:  *
                     26:  * first pass: EGP - 10/26/95
                     27:  */
                     28: 
                     29: /* Implementation dependent include files */
                     30: #include "sysdep.h"
                     31: #include "WWWUtil.h"
                     32: #include "WWWCore.h"
                     33: #include "HTReqMan.h"
                     34: #include "HTTimer.h"
2.5       eric       35: #include "HTEvent.h"
2.1       frystyk    36: #include "HTEvtLst.h"                                   /* Implemented here */
                     37: 
                     38: /* Type definitions and global variables etc. local to this module */
                     39: #define PRIME_TABLE_SIZE       67
                     40: #define MILLI_PER_SECOND       1000
                     41: #define HASH(s)                        ((s) % PRIME_TABLE_SIZE) 
2.2       eric       42: #define HT_EVENT_ORDER                           /* use event ordering code */
                     43: #define EVENTS_TO_EXECUTE      5  /* how many to execute in one select loop */
2.1       frystyk    44: 
2.3       eric       45: #ifdef WWW_WIN_ASYNC
                     46: #define TIMEOUT        1 /* WM_TIMER id */
                     47: PRIVATE HWND HTSocketWin;
                     48: PRIVATE unsigned long HTwinMsg;
                     49: #else /* WWW_WIN_ASYNC */
                     50: PRIVATE fd_set FdArray[HTEvent_TYPES];
2.15      frystyk    51: PRIVATE SOCKET MaxSock = 0;                      /* max socket value in use */
2.3       eric       52: #endif /* !WWW_WIN_ASYNC */
2.1       frystyk    53: 
2.15      frystyk    54: #define HT_FD_BYTES(a) ((a/16)+1)*4
                     55: 
2.3       eric       56: typedef struct {
                     57:     SOCKET     s ;                     /* our socket */
                     58:     HTEvent *  events[HTEvent_TYPES];  /* event parameters for read, write, oob */
2.5       eric       59: #ifndef IN_EVENT
                     60:     HTTimer *  timeouts[HTEvent_TYPES];
                     61: #endif
2.3       eric       62: } SockEvents;
                     63: 
                     64: typedef enum {
                     65:     SockEvents_mayCreate,
                     66:     SockEvents_find
                     67: } SockEvents_action;
2.1       frystyk    68: 
2.2       eric       69: HTList * HashTable[PRIME_TABLE_SIZE]; 
2.1       frystyk    70: PRIVATE int HTEndLoop = 0;                    /* If !0 then exit event loop */
                     71: 
                     72: /* ------------------------------------------------------------------------- */
                     73: 
2.8       frystyk    74: #ifdef WWW_WIN_ASYNC
                     75: PRIVATE BOOL Timer_setWindowsTimer (HTTimer * timer)
                     76: {
                     77:     HWND hwnd;
                     78:     UINT id;
                     79:     hwnd = HTEventList_getWinHandle(&id);
2.9       eric       80:     return SetTimer(hwnd, (UINT)timer, (UINT)HTTimer_getTime(timer), NULL) != 0;
2.8       frystyk    81: }
                     82: 
                     83: PRIVATE BOOL Timer_deleteWindowsTimer (HTTimer * timer)
                     84: {
                     85:     HWND hwnd;
                     86:     UINT id;
                     87:     hwnd = HTEventList_getWinHandle(&id);
                     88:     return KillTimer(hwnd, (UINT)timer) != 0;
                     89: }
                     90: #endif /* WWW_WIN_ASYNC */
                     91: 
2.3       eric       92: PRIVATE SockEvents * SockEvents_get (SOCKET s, SockEvents_action action)
2.1       frystyk    93: {
                     94:     long v = HASH(s);
2.2       eric       95:     HTList* cur;
2.3       eric       96:     SockEvents * pres;
2.2       eric       97: 
                     98:     if (HashTable[v] == NULL)
                     99:        HashTable[v] = HTList_new();
                    100:     cur = HashTable[v];
2.3       eric      101:     while ((pres = (SockEvents *) HTList_nextObject(cur)))
2.2       eric      102:        if (pres->s == s)
                    103:            return pres;
                    104: 
2.3       eric      105:     if (action == SockEvents_mayCreate) {
                    106:         if ((pres = (SockEvents *) HT_CALLOC(1, sizeof(SockEvents))) == NULL)
2.1       frystyk   107:            HT_OUTOFMEM("HTEventList_register");
2.2       eric      108:        pres->s = s;
                    109:        HTList_addObject(HashTable[v], (void *)pres);
                    110:        return pres;
2.1       frystyk   111:     }
                    112:     return NULL;
                    113: }
                    114: 
2.3       eric      115: PUBLIC void HTEvent_traceHead(void)
                    116: {
                    117:     HTTrace("     event: pri millis  callback   param    request  ");
                    118: }
                    119: PUBLIC void HTEvent_trace(HTEvent * event)
                    120: {
                    121:     if (event == NULL)
                    122:        return;
                    123:     HTTrace("%8p: %3d %6d %8p %8p %8p", event, event->priority, event->millis, event->cbf, event->param, event->request);
                    124: }
                    125: PUBLIC void HTTimer_traceHead(void)
                    126: {
                    127:     HTTrace("     timer: millis expires ?   param   callback  ");
                    128: }
                    129: PRIVATE char * MyTime(unsigned long int time, int len)
                    130: {
                    131: static char space[100];
                    132:     sprintf(space, "1234567");
                    133:     return space;
                    134: }
                    135: struct _HTTimer {
                    136:     HTTimer *  next;           /* The next guy in line */
                    137:     ms_t       millis;         /* Relative value in millis */
                    138:     ms_t       expires;        /* Absolute value in millis */
                    139:     BOOL       relative;
                    140:     void *     param;          /* Client supplied context */
                    141:     HTTimerCallback * cbf;
                    142: };
                    143: 
                    144: PUBLIC void HTTimer_trace(HTTimer * timer)
                    145: {
                    146:     if (timer == NULL)
                    147:        return;
                    148:     HTTrace("%8p: %6d %7s %c %8p %8p", timer, timer->millis, MyTime(timer->expires, 7), 
                    149:            timer->relative == YES ? 'R' : 'A', timer->param, timer->cbf);
                    150: }
2.1       frystyk   151: /*
                    152: **  A simple debug function that dumps all the socket arrays
                    153: **  as trace messages
                    154: */
2.3       eric      155: PRIVATE void EventList_dump (void)
2.1       frystyk   156: {
2.3       eric      157:     long v;
                    158:     HTList* cur;
                    159:     SockEvents * pres;
                    160: 
                    161:     if (HashTable[v] == NULL) {
                    162:        HTTrace("Event....... No sockets registered\n");
                    163:        return;
                    164:     }
                    165:     HTTrace("Event....... Dumping socket events\n");
                    166:     HTTrace("soc ");
                    167:     HTEvent_traceHead();
                    168:     HTTrace(" ");
                    169:     HTTimer_traceHead();
                    170:     HTTrace("\n");
                    171:     for (v = 0; v < PRIME_TABLE_SIZE; v++) {
                    172:        cur = HashTable[v];
                    173:        while ((pres = (SockEvents *) HTList_nextObject(cur))) {
                    174:            int i;
                    175:            HTTrace("%3d \n", pres->s);
                    176:            for (i = 0; i < HTEvent_TYPES; i++)
                    177:                if (pres->events[i]) {
                    178:                    static char * names[HTEvent_TYPES] = {"read", "writ", "xcpt"};
                    179:                    HTTrace("%s", names[i]);
                    180:                    HTEvent_trace(pres->events[i]);
                    181:                    HTTrace(" ");
2.5       eric      182: #ifndef IN_EVENT
2.3       eric      183:                    HTTimer_trace(pres->timeouts[i]);
                    184:                    HTTrace(" ");
2.5       eric      185: #endif
2.3       eric      186:                }
                    187:            HTTrace("\n");
                    188:        }
                    189:     }
2.1       frystyk   190: }
                    191: 
                    192: /* ------------------------------------------------------------------------- */
2.5       eric      193: /*             T I M E O U T   H A N D L E R                                */
                    194: PRIVATE int EventListTimerHandler (HTTimer * timer, void * param, HTEventType type)
                    195: {
2.11      frystyk   196:     SockEvents * sockp = (SockEvents *) param;
                    197:     HTEvent * event = NULL;
2.9       eric      198:     /* HTMemLog_flush(); keep around - very useful for debugging crashes - EGP */
2.5       eric      199: #ifdef IN_EVENT
                    200:     if (sockp->events[HTEvent_INDEX(HTEvent_READ)]->timer == timer)
                    201: #else /* IN_EVENT */
                    202:     if (sockp->timeouts[HTEvent_INDEX(HTEvent_READ)] == timer)
                    203: #endif /* !IN_EVENT */
                    204:     {
                    205:        event = sockp->events[HTEvent_INDEX(HTEvent_READ)];
                    206:        if (THD_TRACE) HTTrace("Event....... READ timed out on %d.\n", sockp->s);
                    207:        return (*event->cbf) (sockp->s, event->param, HTEvent_TIMEOUT);
                    208:     }
                    209: #ifdef IN_EVENT
                    210:     if (sockp->events[HTEvent_INDEX(HTEvent_WRITE)]->timer == timer)
                    211: #else /* IN_EVENT */
                    212:     if (sockp->timeouts[HTEvent_INDEX(HTEvent_WRITE)] == timer)
                    213: #endif /* !IN_EVENT */
                    214:     {
                    215:        event = sockp->events[HTEvent_INDEX(HTEvent_WRITE)];
                    216:        if (THD_TRACE) HTTrace("Event....... WRITE timed out on %d.\n", sockp->s);
                    217:        return (*event->cbf) (sockp->s, event->param, HTEvent_TIMEOUT);
                    218:     }
                    219: #ifdef IN_EVENT
                    220:     if (sockp->events[HTEvent_INDEX(HTEvent_OOB)]->timer == timer)
                    221: #else /* IN_EVENT */
                    222:     if (sockp->timeouts[HTEvent_INDEX(HTEvent_OOB)] == timer)
                    223: #endif /* !IN_EVENT */
                    224:     {
                    225:        event = sockp->events[HTEvent_INDEX(HTEvent_OOB)];
                    226:        if (THD_TRACE) HTTrace("Event....... OOB timed out on %d.\n", sockp->s);
                    227:        return (*event->cbf) (sockp->s, event->param, HTEvent_TIMEOUT);
                    228:     }
2.11      frystyk   229:     if (THD_TRACE)
                    230:        HTTrace("Event....... Can't find event for timer %p with context %p\n",
                    231:                timer, param);
2.5       eric      232:     return HT_ERROR;
                    233: }
                    234: 
                    235: /* ------------------------------------------------------------------------- */
2.2       eric      236: /*             E V E N T   O R D E R I N G   S T U F F                      */
                    237: #ifdef HT_EVENT_ORDER
                    238: typedef struct {
                    239:     HTEvent *  event;
                    240:     SOCKET     s;
                    241:     HTEventType        type;
                    242:     HTPriority skipped;
                    243: } EventOrder;
2.1       frystyk   244: 
2.2       eric      245: HTList * EventOrderList = NULL;
                    246: #if 0
                    247: /*
                    248: **     return -1 if a should be after b
                    249:  */
                    250: int EventOrderComparer (const void * a, const void * b)
                    251: {
                    252:     EventOrder * placeMe = (EventOrder *)a;
                    253:     EventOrder * maybeHere = (EventOrder *)b;
                    254:     if (placeMe->event->priority+placeMe->skipped >= maybeHere->event->priority+maybeHere->skipped)
                    255:        return 1;
                    256:     return -1;
                    257: }
                    258: #endif
                    259: 
2.5       eric      260: int EventOrder_add (SOCKET s, HTEventType type, ms_t now)
2.2       eric      261: {
                    262:     EventOrder * pres;
                    263:     HTList * cur = EventOrderList;
                    264:     HTList * insertAfter = cur;
2.5       eric      265:     SockEvents * sockp = SockEvents_get(s, SockEvents_find);
                    266:     HTEvent * event;
2.2       eric      267: 
2.5       eric      268:     if (sockp == NULL || (event = sockp->events[HTEvent_INDEX(type)]) == NULL) {
                    269:        HTTrace("EventOrder.. no event found for socket %d, type %s.\n", s, HTEvent_type2str(type));
2.2       eric      270:        return HT_ERROR;
                    271:     }
                    272: 
2.5       eric      273:     /* Fixup the timeout
                    274:     */
                    275: #ifdef IN_EVENT
                    276:     if (event->timer)
                    277:        HTTimer_refresh(event->timer, now);
                    278: #else
                    279:     if (sockp->timeouts[HTEvent_INDEX(type)])
                    280:        HTTimer_refresh(sockp->timeouts[HTEvent_INDEX(type)], now);
                    281: #endif
                    282: 
2.2       eric      283:     /*
                    284:     ** Look to see if it's already here from before
                    285:     */
                    286:     while ((pres = (EventOrder *) HTList_nextObject(cur))) {
                    287:        if (pres->s == s && pres->event == event && pres->type == type) {
                    288:            pres->skipped++;
                    289:            return HT_OK;
                    290:        }
                    291:        if (pres->event->priority+pres->skipped > event->priority)
                    292:            insertAfter = cur;
                    293:     }
                    294: 
                    295:     /*
                    296:     ** No, so create a new element
                    297:     */
                    298:     if ((pres = (EventOrder *) HT_CALLOC(1, sizeof(EventOrder))) == NULL)
                    299:        HT_OUTOFMEM("EventOrder_add");
                    300:     pres->event = event;
                    301:     pres->s = s;
                    302:     pres->type = type;
                    303:     HTList_addObject(insertAfter, (void *)pres);
                    304:     return HT_OK;
                    305: }
                    306: 
                    307: PUBLIC int EventOrder_executeAndDelete (void) 
                    308: {
2.4       eric      309:     HTList * cur = EventOrderList;
2.2       eric      310:     EventOrder * pres;
                    311:     int i = 0;
                    312:     if (THD_TRACE) HTTrace("EventOrder.. execute ordered events\n");
2.4       eric      313:     if (cur == NULL) return NO;
2.2       eric      314:     while ((pres = (EventOrder *) HTList_removeLastObject(cur)) && i < EVENTS_TO_EXECUTE) {
2.5       eric      315:        HTEvent * event = pres->event;
                    316:        int ret;
2.7       frystyk   317:        if (THD_TRACE)
2.5       eric      318:        HTTrace("EventList... calling socket %d, request %p handler %p type %s\n",
                    319:                pres->s, (void *) event->request,
                    320:                (void *) event->cbf, HTEvent_type2str(pres->type));
                    321:        ret = (*pres->event->cbf)(pres->s, pres->event->param, pres->type);
2.2       eric      322:        HT_FREE(pres);
                    323:        if (ret != HT_OK)
                    324:            return ret;
                    325:        i++;
                    326:     }
                    327:     return HT_OK;
                    328: }
                    329: 
                    330: PUBLIC BOOL EventOrder_deleteAll (void) 
                    331: {
                    332:     HTList * cur = EventOrderList;
                    333:     EventOrder * pres;
                    334:     if (THD_TRACE) HTTrace("EventOrder.. all ordered events\n");
2.4       eric      335:     if (cur == NULL) return NO;
2.2       eric      336:     while ((pres = (EventOrder *) HTList_nextObject(cur)))
                    337:        HT_FREE(pres);
                    338:     HTList_delete(EventOrderList);
                    339:     EventOrderList = NULL;
                    340:     return YES;
                    341: }
                    342: #endif /* HT_EVENT_ORDER */
                    343: 
                    344: /* ------------------------------------------------------------------------- */
2.1       frystyk   345: 
                    346: /*
2.15      frystyk   347: ** ResetMaxSock - reset the value of the maximum socket in use 
                    348: */
                    349: PRIVATE void __ResetMaxSock (void)
                    350: {
                    351:     SOCKET cnt;
                    352:     SOCKET t_max = 0;
                    353:     SOCKET old_max = MaxSock;
                    354:     for (cnt = 0 ; cnt <= MaxSock; cnt++) { 
                    355:        if (FD_ISSET(cnt, (FdArray + HTEvent_INDEX(HTEvent_READ))) ||
                    356:            FD_ISSET(cnt, (FdArray + HTEvent_INDEX(HTEvent_WRITE))) ||
                    357:            FD_ISSET(cnt, (FdArray + HTEvent_INDEX(HTEvent_OOB))))
                    358:            if (cnt > t_max) t_max = cnt;
                    359:     }
                    360:     MaxSock = t_max+1;
                    361:     if (THD_TRACE)
                    362:        HTTrace("Event....... Reset MaxSock from %u to %u\n", old_max, MaxSock);
                    363:     return;
                    364: }  
                    365: 
                    366: /*
2.1       frystyk   367: **  For a given socket, reqister a request structure, a set of operations, 
                    368: **  a HTEventCallback function, and a priority. For this implementation, 
                    369: **  we allow only a single HTEventCallback function for all operations.
                    370: **  and the priority field is ignored.
                    371: */
                    372: PUBLIC int HTEventList_register (SOCKET s, HTEventType type, HTEvent * event)
                    373: {
2.3       eric      374:     SockEvents * sockp;
2.1       frystyk   375:     if (THD_TRACE) 
2.5       eric      376:        HTTrace("Event....... Register socket %d, request %p handler %p type %s at priority %d\n",
2.1       frystyk   377:                s, (void *) event->request,
2.5       eric      378:                (void *) event->cbf, HTEvent_type2str(type),
2.1       frystyk   379:                (unsigned) event->priority);
2.4       eric      380:     if (s==INVSOC || HTEvent_INDEX(type) >= HTEvent_TYPES)
2.1       frystyk   381:        return 0;
                    382: 
                    383:     /*
                    384:     ** Insert socket into appropriate file descriptor set. We also make sure
                    385:     ** that it is registered in the global set.
                    386:     */
2.5       eric      387:     if (THD_TRACE) HTTrace("Event....... Registering socket for %s\n", HTEvent_type2str(type));
2.3       eric      388:     sockp = SockEvents_get(s, SockEvents_mayCreate);
                    389:     sockp->s = s;
                    390:     sockp->events[HTEvent_INDEX(type)] = event;
                    391: #ifdef WWW_WIN_ASYNC
2.4       eric      392:     if (WSAAsyncSelect(s, HTSocketWin, HTwinMsg, HTEvent_BITS(type)) < 0)
2.3       eric      393:        return HT_ERROR;
                    394: #else /* WWW_WIN_ASYNC */
2.1       frystyk   395:     FD_SET(s, FdArray+HTEvent_INDEX(type));
2.15      frystyk   396:     if (s > MaxSock) {
                    397:        MaxSock = s ;
                    398:        if (THD_TRACE) HTTrace("Event....... New value for MaxSock is %d\n", MaxSock);
                    399:     }
2.3       eric      400: #endif /* !WWW_WIN_ASYNC */
2.11      frystyk   401: 
2.1       frystyk   402:     /*
2.11      frystyk   403:     **  If the timeout has been set (relative in millis) then we register 
                    404:     **  a new timeout for this event unless we already have a timer.
2.1       frystyk   405:     */
                    406:     if (event->millis >= 0) {
2.5       eric      407: #ifdef IN_EVENT
2.11      frystyk   408:        event->timer = HTTimer_new(event->timer, EventListTimerHandler,
                    409:                                   sockp, event->millis, YES);
2.5       eric      410: #else
2.11      frystyk   411:        sockp->timeouts[HTEvent_INDEX(type)] =
                    412:            HTTimer_new(sockp->timeouts[HTEvent_INDEX(type)],
                    413:                        EventListTimerHandler, sockp, event->millis, YES);
2.5       eric      414: #endif
2.1       frystyk   415:     }
                    416: 
                    417:     return HT_OK;
                    418: }
                    419: 
2.3       eric      420: PRIVATE int EventList_remaining(SockEvents * pres)
                    421: {
                    422:     int ret = 0;
                    423:     int i;
                    424:     for (i = 0; i < HTEvent_TYPES; i++)
                    425:        if (pres->events[i] != NULL)
                    426:            ret |= 1<<i;
                    427:     return ret;
                    428: }
                    429: 
2.1       frystyk   430: /*
                    431: ** Remove the registered information for the specified socket for the actions 
                    432: ** specified in ops. if no actions remain after the unregister, the registered
                    433: ** info is deleted, and, if the socket has been registered for notification, 
                    434: ** the HTEventCallback will be invoked.
                    435: */
                    436: PUBLIC int HTEventList_unregister(SOCKET s, HTEventType type) 
                    437: {
2.3       eric      438:     long               v = HASH(s);
                    439:     HTList *           cur = HashTable[v];
                    440:     HTList *           last = cur;
                    441:     SockEvents *       pres;
2.9       eric      442:     int                        ret = HT_ERROR;
2.2       eric      443: 
2.9       eric      444:     while (cur && (pres = (SockEvents *) HTList_nextObject(cur))) {
2.2       eric      445:         if (pres->s == s) {
2.3       eric      446:            int         remaining;
2.1       frystyk   447: 
                    448:            /*
                    449:            **  Unregister the event from this action
                    450:            */
2.2       eric      451:            pres->events[HTEvent_INDEX(type)] = NULL;
2.1       frystyk   452: 
                    453:            /*
                    454:            **  Check to see of there was a timeout connected with the event.
                    455:            **  If so then delete the timeout as well.
                    456:            */
                    457:            {
2.5       eric      458: #ifdef IN_EVENT
                    459:                HTTimer * timer = pres->events[HTEvent_INDEX(type)]->timer;
                    460: #else
2.2       eric      461:                HTTimer * timer = pres->timeouts[HTEvent_INDEX(type)];
2.5       eric      462: #endif
2.1       frystyk   463:                if (timer) HTTimer_delete(timer);
                    464:            }
                    465:            
                    466:            /*
                    467:            **  Check to see if we can delete the action completely. We do this
                    468:            **  if there are no more events registered.
                    469:            */
2.3       eric      470:            if ((remaining = EventList_remaining(pres)) == 0) {
2.9       eric      471:                HTList * doomed = cur;
2.1       frystyk   472:                if (THD_TRACE)
                    473:                    HTTrace("Event....... No more events registered for socket %d\n", s);
2.15      frystyk   474: 
                    475: 
                    476: #ifndef WWW_WIN_ASYNC
                    477:                /* Check to see if we have to update MaxSock */
                    478:                if(pres->s > MaxSock) __ResetMaxSock();
                    479: #endif /* !WWW_WIN_ASYNC */
                    480: 
2.2       eric      481:                HT_FREE(pres);
2.9       eric      482:                pres = (SockEvents *) HTList_nextObject(cur);
                    483:                HTList_quickRemoveElement(doomed, last);
                    484:            }
                    485:            ret = HT_OK;
2.15      frystyk   486: 
2.3       eric      487: #ifdef WWW_WIN_ASYNC
                    488:            if (WSAAsyncSelect(s, HTSocketWin, HTwinMsg, remaining) < 0)
2.9       eric      489:                ret = HT_ERROR;
2.3       eric      490: #else /* WWW_WIN_ASYNC */
                    491:            FD_CLR(s, FdArray+HTEvent_INDEX(type));
2.14      frystyk   492:            HTTraceData((char*)FdArray+HTEvent_INDEX(type), 8, "HTEventList_unregister: (s:%d)", s);
2.3       eric      493: #endif /* !WWW_WIN_ASYNC */
                    494:            if (THD_TRACE)
2.15      frystyk   495:                HTTrace("Event....... Socket %d unregistered for %s\n", s, HTEvent_type2str(type));
                    496: 
2.6       eric      497:            /*
2.15      frystyk   498:            **  We found the socket and can break
2.6       eric      499:            */
2.15      frystyk   500:            break;
2.9       eric      501:        }
                    502:        last = cur;
2.1       frystyk   503:     }
2.9       eric      504:     if (ret == HT_ERROR && THD_TRACE) HTTrace("Event....... Couldn't find socket %d.\n", s);
                    505:     return ret;
2.1       frystyk   506: }
                    507: 
                    508: /*
                    509: ** Unregister all sockets 
                    510: ** N.B. we just remove them for our internal data structures: it is up to the 
                    511: ** application to actually close the socket. 
                    512: */
2.2       eric      513: PUBLIC int HTEventList_unregisterAll (void) 
2.1       frystyk   514: {
                    515:     int i;
                    516:     if (THD_TRACE) HTTrace("Unregister.. all sockets\n");
                    517:     for (i = 0 ; i < PRIME_TABLE_SIZE; i++) {
2.2       eric      518:        HTList * cur = HashTable[i];
2.3       eric      519:        SockEvents * pres;
                    520:        while ((pres = (SockEvents *) HTList_nextObject(cur))) {
                    521: #ifdef WWW_WIN_ASYNC
                    522:            WSAAsyncSelect(pres->s, HTSocketWin, HTwinMsg, 0);
                    523: #endif /* WWW_WIN_ASYNC */
2.2       eric      524:            HT_FREE(pres);
2.3       eric      525:        }
2.2       eric      526:        HTList_delete(HashTable[i]);
                    527:        HashTable[i] = NULL;
2.1       frystyk   528:     }
2.3       eric      529: #ifndef WWW_WIN_ASYNC
                    530:     MaxSock = 0 ;
2.15      frystyk   531:     if (THD_TRACE) HTTrace("Event....... New value for MaxSock is %d\n", MaxSock);
2.1       frystyk   532:     FD_ZERO(FdArray+HTEvent_INDEX(HTEvent_READ));
                    533:     FD_ZERO(FdArray+HTEvent_INDEX(HTEvent_WRITE));
                    534:     FD_ZERO(FdArray+HTEvent_INDEX(HTEvent_OOB));
2.3       eric      535: #endif /* !WWW_WIN_ASYNC */
2.2       eric      536: #ifdef HT_EVENT_ORDER
                    537:     EventOrder_deleteAll();
                    538: #endif /* HT_EVENT_ORDER */
2.1       frystyk   539:     return 0;
                    540: }
                    541: 
                    542: /*
                    543: **  Dispatch the event to the appropriate event handler.
                    544: **  If no event handler is found then just return.
                    545: */
2.5       eric      546: PUBLIC int HTEventList_dispatch (SOCKET s, HTEventType type, ms_t now)
2.1       frystyk   547: {
2.3       eric      548:     SockEvents * sockp = SockEvents_get(s, SockEvents_find);
                    549:     if (sockp) {
                    550:        HTEvent * event = sockp->events[HTEvent_INDEX(type)];
2.1       frystyk   551: 
2.5       eric      552:        /*      Fixup the timeout
                    553:        */
                    554: #ifdef IN_EVENT
                    555:        if (event->timer)
                    556:            HTTimer_refresh(event->timer, now);
                    557: #else
                    558:        if (sockp->timeouts[HTEvent_INDEX(type)])
                    559:            HTTimer_refresh(sockp->timeouts[HTEvent_INDEX(type)], now);
                    560: #endif
2.1       frystyk   561:        /*
                    562:        **  If we have found an event object for this event then see
                    563:        **  is we should call it.
                    564:        */
                    565:        if (event && event->priority!=HT_PRIORITY_OFF)
                    566:            return (*event->cbf) (s, event->param, type);
2.3       eric      567:        if (THD_TRACE) HTTrace("Dispatch.... Handler %p NOT called\n", sockp);
2.1       frystyk   568:        return HT_OK;
                    569:     }
                    570:     if (THD_TRACE) HTTrace("Dispatch.... Bad socket %d\n", s);
                    571:     return NO;
                    572: }
                    573: 
                    574: /*
                    575: **  Stops the (select based) event loop. The function does not guarantee
                    576: **  that all requests have terminated. This is for the app to do
                    577: */
                    578: PUBLIC void HTEventList_stopLoop (void)
                    579: {
                    580:     HTEndLoop = 1;
                    581: }
                    582: 
2.3       eric      583: PUBLIC HTEvent * HTEventList_lookup (SOCKET s, HTEventType type)
                    584: {
                    585:     SockEvents * sockp = NULL;
                    586:     if ((sockp = SockEvents_get(s, SockEvents_find)) == NULL)
                    587:        return NULL;
                    588:     return sockp->events[HTEvent_INDEX(type)];
                    589: }
                    590: 
                    591: /*     REGISTER DEFULT EVENT MANAGER
                    592: **     -----------------------------
                    593: **     Not done automaticly - may be done by application!
                    594: */
                    595: PUBLIC BOOL HTEventInit (void)
                    596: {
2.4       eric      597: #ifdef WWW_WIN_ASYNC
                    598:     /*
                    599:     ** We are here starting a hidden window to take care of events from
                    600:     **  the async select() call in the async version of the event loop in
                    601:     ** the Internal event manager (HTEvtLst.c)
                    602:     */
                    603:     static char className[] = "AsyncWindowClass";
                    604:     WNDCLASS wc;
                    605:     OSVERSIONINFO osInfo;
                    606:     
                    607:     wc.style=0;
                    608:     wc.lpfnWndProc=(WNDPROC)AsyncWindowProc;
                    609:     wc.cbClsExtra=0;
                    610:     wc.cbWndExtra=0;
                    611:     wc.hIcon=0;
                    612:     wc.hCursor=0;
                    613:     wc.hbrBackground=0;
                    614:     wc.lpszMenuName=(LPSTR)0;
                    615:     wc.lpszClassName=className;
                    616: 
                    617:     osInfo.dwOSVersionInfoSize = sizeof(osInfo);
                    618:     GetVersionEx(&osInfo);
                    619:     if (osInfo.dwPlatformId == VER_PLATFORM_WIN32s || osInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
                    620:        wc.hInstance=GetModuleHandle(NULL); /* 95 and non threaded platforms */
                    621:     else
                    622:        wc.hInstance=GetCurrentProcess(); /* NT and hopefully everything following */
                    623:     if (!RegisterClass(&wc)) {
                    624:        HTTrace("HTLibInit.. Can't RegisterClass \"%s\"\n", className);
                    625:            return NO;
                    626:     }
                    627:     if (!(HTSocketWin = CreateWindow(className, "WWW_WIN_ASYNC", WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT, 
                    628:                                      CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, wc.hInstance,0))) {
                    629:        char space[50];
                    630:                HTTrace("HTLibInit.. Can't CreateWindow \"WWW_WIN_ASYNC\" - error:");
                    631:        sprintf(space, "%ld\n", GetLastError());
                    632:        HTTrace(space);
                    633:        return NO;
                    634:     }
                    635:     HTwinMsg = WM_USER;  /* use first available message since app uses none */
2.8       frystyk   636: 
                    637:     /*
                    638:     **  Register platform specific timer handlers for windows
                    639:     */
                    640:     HTTimer_registerSetTimerCallback(Timer_setWindowsTimer);
                    641:     HTTimer_registerDeleteTimerCallback(Timer_deleteWindowsTimer);
                    642: 
2.4       eric      643: #endif /* WWW_WIN_ASYNC */
                    644: 
                    645: #ifdef _WINSOCKAPI_
                    646:     /*
                    647:     ** Initialise WinSock DLL. This must also be shut down! PMH
                    648:     */
                    649:     {
                    650:         WSADATA            wsadata;
                    651:        if (WSAStartup(DESIRED_WINSOCK_VERSION, &wsadata)) {
                    652:            if (WWWTRACE)
                    653:                HTTrace("HTEventInit. Can't initialize WinSoc\n");
                    654:             WSACleanup();
                    655:             return NO;
                    656:         }
                    657:         if (wsadata.wVersion < MINIMUM_WINSOCK_VERSION) {
                    658:             if (WWWTRACE)
                    659:                HTTrace("HTEventInit. Bad version of WinSoc\n");
                    660:             WSACleanup();
                    661:             return NO;
                    662:         }
                    663:        if (APP_TRACE)
                    664:            HTTrace("HTEventInit. Using WinSoc version \"%s\".\n", 
                    665:                    wsadata.szDescription);
                    666:     }
                    667: #endif /* _WINSOCKAPI_ */
                    668: 
2.3       eric      669:     HTEvent_setRegisterCallback(HTEventList_register);
                    670:     HTEvent_setUnregisterCallback(HTEventList_unregister);
                    671:     return YES;
                    672: }
                    673: 
                    674: PUBLIC BOOL HTEventTerminate (void)
                    675: {
                    676:     return YES;
                    677: }
                    678: 
                    679: #ifdef WWW_WIN_ASYNC
                    680: 
2.4       eric      681: /*     HTEventList_get/setWinHandle
2.3       eric      682: **     --------------------------
                    683: **     Managing the windows handle on Windows
                    684: */
                    685: PUBLIC BOOL HTEventList_setWinHandle (HWND window, unsigned long message)
                    686: {
                    687:     HTSocketWin = window;
                    688:     HTwinMsg = message;
                    689:     return YES;
                    690: }
                    691: 
                    692: PUBLIC HWND HTEventList_getWinHandle (unsigned long * pMessage)
                    693: {
                    694:     if (pMessage)
                    695:         *pMessage = HTwinMsg;
                    696:     return (HTSocketWin);
                    697: }
                    698: 
                    699: /* only responsible for WM_TIMER and WSA_AsyncSelect */        
                    700: PUBLIC LRESULT CALLBACK AsyncWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
                    701: {
                    702:     WORD event;
                    703:     SOCKET sock;
2.4       eric      704:     HTEventType type;
2.5       eric      705:     ms_t now = HTGetTimeInMillis();
2.3       eric      706: 
                    707:     /* timeout stuff */
                    708:     if (uMsg == WM_TIMER) {
2.4       eric      709:        HTTimer_dispatch((HTTimer *)wParam);
2.3       eric      710:        return (0);
                    711:     }
                    712: 
                    713:     if (uMsg != HTwinMsg)      /* not our async message */
                    714:        return (DefWindowProc(hwnd, uMsg, wParam, lParam));
                    715: 
                    716:     event = LOWORD(lParam);
                    717:     sock = (SOCKET)wParam;
2.4       eric      718:     switch (event) {
                    719:     case FD_READ: type = HTEvent_READ; break;
                    720:     case FD_WRITE: type = HTEvent_WRITE; break;
                    721:     case FD_ACCEPT: type = HTEvent_ACCEPT; break;
                    722:     case FD_CONNECT: type = HTEvent_CONNECT; break;
                    723:     case FD_OOB: type = HTEvent_OOB; break;
                    724:     case FD_CLOSE: type = HTEvent_CLOSE; break;
                    725:     default: HTDebugBreak();
                    726:     }
2.5       eric      727:     if (HTEventList_dispatch((int)sock, type, now) != HT_OK)
2.4       eric      728:        HTEndLoop = -1;
2.3       eric      729:     return (0);
                    730: }
                    731: 
2.4       eric      732: PUBLIC int HTEventList_loop (HTRequest * theRequest )
2.3       eric      733: {
                    734:     MSG msg;
                    735:     while (GetMessage(&msg,0,0,0)) {
                    736:            TranslateMessage(&msg);
                    737:            DispatchMessage(&msg);
                    738:     }
                    739:     return (HTEndLoop == 1 ? HT_OK : HT_ERROR);
                    740: }
                    741: 
                    742: #else /* WWW_WIN_ASYNC */
                    743: 
2.1       frystyk   744: /*
                    745: **  We wait for activity from one of our registered 
                    746: **  channels, and dispatch on that.
                    747: **
                    748: **  There are now two versions of the event loop. The first is if you want
                    749: **  to use async I/O on windows, and the other is if you want to use normal
                    750: **  Unix setup with sockets
                    751: */
                    752: PUBLIC int HTEventList_loop (HTRequest * theRequest) 
                    753: {
                    754:     fd_set treadset, twriteset, texceptset;
                    755:     struct timeval waittime, * wt;
                    756:     int active_sockets;
                    757:     int maxfds;
2.5       eric      758:     ms_t timeout;
                    759:     ms_t now;
2.1       frystyk   760:     SOCKET s;
2.5       eric      761:     int status = HT_OK;
2.1       frystyk   762:     HTEndLoop = 0;
                    763: 
2.2       eric      764:     EventOrderList = HTList_new();     /* is kept around until EventOrder_deleteAll */
                    765: 
2.1       frystyk   766:     /* Don't leave this loop until we leave the application */
                    767:     do {
                    768:         treadset = FdArray[HTEvent_INDEX(HTEvent_READ)];
                    769:         twriteset = FdArray[HTEvent_INDEX(HTEvent_WRITE)];
                    770:         texceptset = FdArray[HTEvent_INDEX(HTEvent_OOB)];
2.3       eric      771:         maxfds = MaxSock; 
2.1       frystyk   772: 
                    773:        if (THD_TRACE) HTTrace("Event Loop.. calling select: maxfds is %d\n", maxfds);
                    774: 
                    775:         /*
                    776:        **  Timeval struct copy needed for linux, as it set the value to the
                    777:        **  remaining timeout while exiting the select. (and perhaps for
                    778:        **  other OS). Code borrowed from X server.
                    779:        */
                    780:        wt = NULL;
2.5       eric      781:        if ((status = HTTimer_next(&timeout)))
                    782:            return status;
                    783:        if (timeout != 0) {
2.1       frystyk   784:            waittime.tv_sec = timeout / MILLI_PER_SECOND;
                    785:            waittime.tv_usec = (timeout % MILLI_PER_SECOND) *
                    786:                (1000000 / MILLI_PER_SECOND);
                    787:            wt = &waittime;
                    788:        }
                    789: 
2.15      frystyk   790:        /* WHAT THE HECK??? */
                    791: #define HT_FS_BYTES(a)  ((((a)/16)+1) * 4)
2.2       eric      792: 
2.15      frystyk   793:        HTTraceData((char*)&treadset, HT_FS_BYTES(maxfds), "HTEventList_loop pre treadset: (maxfd:%d)", maxfds);
                    794:        HTTraceData((char*)&twriteset, HT_FS_BYTES(maxfds), "HTEventList_loop pre twriteset:");
                    795:        HTTraceData((char*)&texceptset, HT_FS_BYTES(maxfds), "HTEventList_loop pre texceptset:");
                    796: 
2.1       frystyk   797: #ifdef __hpux 
                    798:         active_sockets = select(maxfds+1, (int *)&treadset, (int *)&twriteset,
                    799:                                (int *)&texceptset, wt);
                    800: #else
                    801:         active_sockets = select(maxfds+1, &treadset, &twriteset, &texceptset, wt);
                    802: #endif
2.2       eric      803: 
2.5       eric      804:        now = HTGetTimeInMillis();
2.15      frystyk   805:        HTTraceData((char*)&treadset, HT_FS_BYTES(maxfds), "HTEventList_loop post treadset: (active_sockets:%d)", active_sockets);
                    806:        HTTraceData((char*)&twriteset, HT_FS_BYTES(maxfds), "HTEventList_loop post twriteset: (errno:%d)", errno);
                    807:        HTTraceData((char*)&texceptset, HT_FS_BYTES(maxfds), "HTEventList_loop post texceptset:");
2.2       eric      808: 
2.1       frystyk   809:        if (THD_TRACE) HTTrace("Event Loop.. select returns %d\n", active_sockets);
                    810: 
                    811:         if (active_sockets == -1) {
                    812:            HTRequest_addSystemError( theRequest, ERR_FATAL, socerrno, NO, "select");
2.3       eric      813:            EventList_dump();
2.1       frystyk   814:            return HT_ERROR;
                    815:         }
                    816: 
                    817:        /*
                    818:        **  We had a timeout so now we check and see if we have a timeout
2.5       eric      819:        **  handler to call. Let HTTimer_next get it.
2.1       frystyk   820:        */ 
2.5       eric      821:        if (active_sockets == 0)
2.1       frystyk   822:            continue;
                    823: 
                    824:        /*
                    825:        **  There were active sockets. Determine which fd sets they were in
                    826:        */
2.2       eric      827: #ifdef HT_EVENT_ORDER
2.5       eric      828: #define DISPATCH(socket, type, now) EventOrder_add(socket, type, now)
2.2       eric      829: #else /* HT_EVENT_ORDER */
2.5       eric      830: #define DISPATCH(socket, type, now) HTEventList_dispatch(socket, type, now)
2.2       eric      831: #endif /* !HT_EVENT_ORDER */
2.1       frystyk   832:        for (s = 0 ; s <= maxfds ; s++) { 
                    833:            if (FD_ISSET(s, &texceptset))
2.5       eric      834:                if ((status = DISPATCH(s, HTEvent_OOB, now)) != HT_OK)
2.1       frystyk   835:                    return status;
                    836:            if (FD_ISSET(s, &twriteset))
2.5       eric      837:                if ((status = DISPATCH(s, HTEvent_WRITE, now)) != HT_OK)
2.1       frystyk   838:                    return status;
                    839:            if (FD_ISSET(s, &treadset))
2.5       eric      840:                if ((status = DISPATCH(s, HTEvent_READ, now)) != HT_OK)
2.1       frystyk   841:                    return status;
                    842:        }
2.2       eric      843: #ifdef HT_EVENT_ORDER
                    844:        if ((status = EventOrder_executeAndDelete()) != HT_OK)
                    845:            return status;
                    846: #endif /* HT_EVENT_ORDER */
2.1       frystyk   847:     } while (!HTEndLoop);
                    848: 
                    849:     return HT_OK;
                    850: }
                    851: 
2.3       eric      852: #endif /* !WWW_WIN_ASYNC */
2.12      eric      853: 
                    854: PUBLIC void CheckSockEvent(HTTimer * timer, HTTimerCallback * cbf, void * param)
                    855: {
                    856:     SockEvents * sockp = (SockEvents *)param;
                    857:     if (cbf == EventListTimerHandler && 
                    858:        sockp->timeouts[0] != timer && 
                    859:        sockp->timeouts[1] != timer && 
                    860:        sockp->timeouts[2] != timer) {
2.13      frystyk   861:        if (THD_TRACE) HTTrace("Timer....... bad timer %p.\n", timer);
2.12      eric      862:        HTDebugBreak();
                    863:     }
                    864: }
                    865: 

Webmaster