Annotation of Amaya/amaya/query.c, revision 1.315

1.14      cvs         1: /*
                      2:  *
1.265     cvs         3:  *  (c) COPYRIGHT MIT and INRIA, 1996-2001.
1.14      cvs         4:  *  Please first read the full copyright statement in file COPYRIGHT.
1.156     cvs         5:  * 
1.14      cvs         6:  */
1.243     cvs         7:  
1.19      cvs         8: /*
1.83      cvs         9:  * query.c : contains all the functions for requesting and publishing
1.19      cvs        10:  * URLs via libwww. It handles any eventual HTTP error code
                     11:  * (redirection, authentication needed, not found, etc.)
                     12:  *
1.69      cvs        13:  * Author: J. Kahan
1.92      cvs        14:  *         J. Kahan/R. Guetari Windows 95/NT routines
1.19      cvs        15:  */
1.17      cvs        16: 
1.116     cvs        17: /* defines to include elsewhere
                     18: *********************************/
                     19: 
1.185     cvs        20: #ifdef _WINDOWS
                     21: #include <string.h>
1.130     cvs        22: #endif /* !_WINDOWS */
1.116     cvs        23: #define AMAYA_WWW_CACHE
1.168     cvs        24: #define AMAYA_LOST_UPDATE
1.116     cvs        25: 
1.12      cvs        26: /* Amaya includes  */
1.25      cvs        27: #define THOT_EXPORT extern
1.4       cvs        28: #include "amaya.h"
1.214     cvs        29: #include "init_f.h"
1.130     cvs        30: #include <sys/types.h>
1.309     cvs        31: #ifndef _WINDOWS
1.308     kahan      32: #include <unistd.h>
1.309     cvs        33: #endif
1.70      cvs        34: #include <fcntl.h>
1.140     cvs        35: #include "HTEvtLst.h"
1.157     cvs        36: #include "HTAABrow.h"
1.272     cvs        37: #include "string.h"
1.279     cvs        38: #include "interface.h"
1.7       cvs        39: 
1.141     cvs        40: #if defined(__svr4__) || defined (_AIX)
1.4       cvs        41: #define CATCH_SIG
                     42: #endif
                     43: 
                     44: /* local structures coming from libwww and which are
1.17      cvs        45:    not found in any .h file
1.7       cvs        46:  */
1.68      cvs        47: 
1.7       cvs        48: struct _HTStream
                     49:   {
1.15      cvs        50:      const HTStreamClass *isa;
                     51:      FILE               *fp;
1.45      cvs        52:      BOOL                leave_open;   /* Close file when TtaFreeMemory? */
1.15      cvs        53:      char               *end_command;  /* Command to execute       */
                     54:      BOOL                remove_on_close;      /* Remove file?             */
                     55:      char               *filename;     /* Name of file             */
                     56:      HTRequest          *request;      /* saved for callback       */
                     57:      HTRequestCallback  *callback;
1.7       cvs        58:   };
                     59: 
1.15      cvs        60: 
1.7       cvs        61: struct _HTError
                     62:   {
                     63:      HTErrorElement      element;      /* Index number into HTError */
                     64:      HTSeverity          severity;     /* A la VMS */
                     65:      BOOL                ignore;       /* YES if msg should not go to user */
                     66:      void               *par;  /* Explanation, e.g. filename  */
                     67:      int                 length;       /* For copying by generic routine */
                     68:      char               *where;        /* Which function */
                     69:   };
                     70: 
1.4       cvs        71: /* Type definitions and global variables etc. local to this module */
                     72: 
1.17      cvs        73: /*----------------------------------------------------------------------*/
1.293     kahan      74: 
                     75: /* libwww default parameters */
                     76: #ifdef _WINDOWS
                     77: #define CACHE_DIR_NAME "\\libwww-cache\\"
                     78: #else
                     79: #define CACHE_DIR_NAME "/libwww-cache/"
                     80: #endif
                     81: 
                     82: #define DEFAULT_CACHE_SIZE 10
                     83: #define DEFAULT_MAX_CACHE_ENTRY_SIZE 3
                     84: #define DEFAULT_MAX_SOCKET 32
                     85: #define DEFAULT_DNS_TIMEOUT 1800L
                     86: #define DEFAULT_PERSIST_TIMEOUT 60L
                     87: #define DEFAULT_NET_EVENT_TIMEOUT 60000
1.294     kahan      88: /* defines the priority for general content negotiation */
                     89: #define GENERAL_ACCEPT_NEGOTIATION "*/*;q=0.1,"AM_SVG_MIME_TYPE","AM_MATHML_MIME_TYPE","AM_XHTML_MIME_TYPE
1.293     kahan      90: /* defines the priority for image content negotiation */
                     91: #define IMAGE_ACCEPT_NEGOTIATION "*/*;q=0.1,image/*,image/gif,image/jpeg,image/png,image/svg+xml,"AM_SVG_MIME_TYPE
                     92: 
1.4       cvs        93: /*** private variables ***/
1.17      cvs        94: 
1.4       cvs        95: static HTList      *converters = NULL; /* List of global converters */
1.27      cvs        96: static HTList      *acceptTypes = NULL; /* List of types for the Accept header */
1.193     cvs        97: static HTList      *acceptLanguages = NULL; /* List of language priorities for the Accept header */
1.151     cvs        98: static HTList      *transfer_encodings = NULL;
                     99: static HTList      *content_encodings = NULL;
1.207     cvs       100: /* List of domains where we can do a safe PUT redirect */
                    101: static HTList      *safeput_list = NULL;
                    102: 
1.16      cvs       103: static int          object_counter = 0;        /* loaded objects counter */
1.191     cvs       104: static  ThotBool    AmayaAlive_flag; /* set to 1 if the application is active;
1.140     cvs       105:                                        0 if we have killed */
1.191     cvs       106: static  ThotBool    CanDoStop_flag; /* set to 1 if we can do a stop, 0
1.140     cvs       107:                                       if we're inside a critical section */
1.214     cvs       108: static  ThotBool    UserAborted_flag; /* set to 1 if we're processing a user
                    109:                                         induced stop request operation */
1.128     cvs       110: #ifdef  AMAYA_WWW_CACHE
1.130     cvs       111: static int          fd_cachelock; /* open handle to the .lock cache file */
                    112: #endif /* AMAYA_WWW_CACHE */
1.4       cvs       113: 
1.246     kahan     114: static  ThotBool    FTPURL_flag; /* if set to true, we can browse FTP URLs */
                    115: 
1.248     kahan     116: static  FILE        *trace_fp = NULL;   /* file pointer to the trace logs */
                    117: 
1.15      cvs       118: #include "answer_f.h"
                    119: #include "query_f.h"
                    120: #include "AHTURLTools_f.h"
                    121: #include "AHTBridge_f.h"
                    122: #include "AHTMemConv_f.h"
                    123: #include "AHTFWrite_f.h"
1.4       cvs       124: 
1.298     cvs       125: #ifdef DAV
                    126: #include "davlib.h"
                    127: #include "davlib_f.h"
                    128: #include "davlibCommon_f.h"
1.302     kirschpi  129: #endif /* DAV */
1.298     cvs       130: 
1.116     cvs       131: /* prototypes */
                    132: 
1.123     cvs       133: #ifdef _WINDOWS
1.70      cvs       134: int WIN_Activate_Request (HTRequest* , HTAlertOpcode, int, const char*, void*, HTAlertPar*);
1.116     cvs       135: #endif /* _WINDOWS */
1.297     kirschpi  136: 
1.130     cvs       137: #ifdef AMAYA_WWW_CACHE
                    138: /***************************************************************
                    139:  lock functions, used to avoid concurrent use of the cache
                    140:  Mostly based on W. Richard Stevens' APUE book.
                    141:  ***************************************************************/
                    142: /*----------------------------------------------------------------------
                    143:   set_cachelock
                    144:   sets a write lock on filename. 
                    145:   Returns -1 in case of failure, otherwise, it'll open a handle on
                    146:   filename and fd_cachelock will take its value.
                    147:   ----------------------------------------------------------------------*/
1.265     cvs       148: static int set_cachelock (char *filename)
1.130     cvs       149: {
1.188     cvs       150:   int status;
1.130     cvs       151: #ifdef _WINDOWS
1.188     cvs       152: 
                    153:   status = TtaFileExist (filename);
                    154:   return ((status) ? 0 : -1);
1.130     cvs       155: #else
                    156:   struct flock lock;
                    157:  
                    158:   lock.l_type = F_WRLCK;
                    159:   lock.l_start = 0;
                    160:   lock.l_whence = SEEK_SET;
                    161:   lock.l_len = 0;
                    162:   
                    163:   fd_cachelock = open (filename, O_WRONLY);
                    164:   
                    165:   if (fd_cachelock == -1)
                    166:     status = -1;
                    167:   else
                    168:     status = fcntl(fd_cachelock, F_SETLK, &lock);
                    169:   
                    170:   if (status == -1)
1.190     cvs       171:     {
1.179     cvs       172:       if (fd_cachelock > 0)
1.190     cvs       173:          close (fd_cachelock);
1.179     cvs       174:       fd_cachelock = 0;
1.178     cvs       175:     }
1.130     cvs       176:   return (status);
                    177: #endif /* _WINDOWS */
                    178: }
                    179: 
                    180: /*----------------------------------------------------------------------
                    181:   clear_cachelock
                    182:   remove the write lock set on a filename.
                    183:   It'll close the fd handle on filename and reset *fd to 0.
                    184:   ----------------------------------------------------------------------*/
                    185: static int clear_cachelock (void)
                    186: {
                    187: #ifdef _WINDOWS
                    188:   return 0;
                    189: #else
                    190:   int status;
                    191: 
1.178     cvs       192:   if (!fd_cachelock)
1.130     cvs       193:     return (-1);
                    194:  
1.178     cvs       195:   status = close (fd_cachelock);
1.130     cvs       196:   fd_cachelock = 0;
                    197: 
                    198:   return (status);
                    199: #endif /* _WINDOWS */
                    200: }
                    201: 
                    202: /*----------------------------------------------------------------------
                    203:   test_cachelock
                    204:   returns 0 if a fd is not locked by other process, otherwise 
                    205:   returns the pid of the process who has the lock
                    206:   ----------------------------------------------------------------------*/
1.265     cvs       207: static int test_cachelock (char *filename)
1.130     cvs       208: {
                    209: #ifdef _WINDOWS
1.185     cvs       210:   /* if the lock is set, we can't unlink the file under Windows */
1.188     cvs       211:   if (!TtaFileUnlink (filename))
                    212:     return 0;
                    213:   else
1.185     cvs       214:     return -1;
1.130     cvs       215: #else
                    216:   struct flock lock;
                    217:   int fd, status;
                    218: 
                    219:   lock.l_type = F_WRLCK;
                    220:   lock.l_start = 0;
                    221:   lock.l_whence = SEEK_SET;
                    222:   lock.l_len = 0;
                    223: 
                    224:   fd = open (filename, O_WRONLY);
                    225: 
                    226:   if (fd < 0)
                    227:     return (-1);
                    228:   /* is this file locked ? */
                    229:   status = fcntl (fd,  F_GETLK, &lock);
                    230:   close (fd);
                    231: 
                    232:   if (status < 0)
                    233:     return (-1);
                    234: 
                    235:   if (lock.l_type == F_UNLCK)
                    236:     return (0); /* false, region is not locked by another proc */
                    237:   return (lock.l_pid); /* true, return pid of lock owner */
                    238: #endif /* _WINDOWS */
                    239: }
                    240: 
                    241: #endif /* AMAYA_WWW_CACHE */
                    242: 
1.15      cvs       243: /*----------------------------------------------------------------------
1.17      cvs       244:   GetDocIdStatus
                    245:   gets the status associated to a docid                         
1.15      cvs       246:   ----------------------------------------------------------------------*/
                    247: AHTDocId_Status    *GetDocIdStatus (int docid, HTList * documents)
                    248: {
                    249:    AHTDocId_Status    *me;
                    250:    HTList             *cur;
                    251: 
                    252:    if (documents)
                    253:      {
                    254:        cur = documents;
                    255: 
                    256:        while ((me = (AHTDocId_Status *) HTList_nextObject (cur)))
                    257:          {
                    258:             if (me->docid == docid)
                    259:                return (me);
1.18      cvs       260:          }
                    261:      }
1.15      cvs       262:    return (AHTDocId_Status *) NULL;
                    263: 
                    264: }
                    265: 
1.5       cvs       266: /*----------------------------------------------------------------------
1.27      cvs       267:   AHTGuessAtom_for
                    268:   Converts an Amaya type descriptor into the equivalent MIME type.
                    269:   ----------------------------------------------------------------------*/
1.276     kahan     270: static  HTAtom *AHTGuessAtom_for (char *urlName, char *contentType)
1.27      cvs       271: {
                    272:  HTAtom           *atom;
1.265     cvs       273:  char *          filename;
1.160     cvs       274:  HTEncoding        enc = NULL;
                    275:  HTEncoding        cte = NULL;
                    276:  HTLanguage        lang = NULL;
1.50      cvs       277:  double            quality = 1.0;
1.27      cvs       278: 
1.276     kahan     279:  /* we already have a MIME type, we jsut return the atom */
                    280:  if (contentType && *contentType)
                    281:    atom = HTAtom_for (contentType);
                    282:  else
1.27      cvs       283:    {
1.276     kahan     284:      /* we don't have the MIME type, so
                    285:        we try to use the filename's suffix to infer it */
1.265     cvs       286:      filename = AmayaParseUrl (urlName, "", 
                    287:                               AMAYA_PARSE_PATH | AMAYA_PARSE_PUNCTUATION);
                    288:      HTBind_getFormat (filename, &atom, &enc, &cte, &lang, &quality);
1.45      cvs       289:      TtaFreeMemory (filename);
1.27      cvs       290:      if (atom ==  WWW_UNKNOWN)
1.276     kahan     291:        {
1.27      cvs       292:         /*
1.276     kahan     293:         ** we could not identify the suffix, so we give it a default type.
                    294:         ** (we should ask the user, but we're not ready for that yet).
1.27      cvs       295:         */
                    296:         atom = HTAtom_for ("text/html");
1.276     kahan     297:        }
1.27      cvs       298:    }
                    299:  return atom;
                    300: }
                    301: 
                    302: /*----------------------------------------------------------------------
1.238     cvs       303:   HTTP_Headers_set
                    304:   Copies the headers in which the application is interested, doing
                    305:   any in-between conversions as needed.
                    306:   ----------------------------------------------------------------------*/
1.315   ! vatton    307: void HTTP_headers_set (HTRequest *request, HTResponse *response,
        !           308:                       void *context, int status)
1.238     cvs       309: {
1.267     kahan     310:   AHTReqContext  *me;
1.283     cvs       311:   HTAtom         *tmp_atom = NULL;
1.267     kahan     312:   char           *tmp_char;
1.285     kahan     313:   char           *tmp_char2;
1.284     kahan     314:   char           tmp_string[20];
1.267     kahan     315:   HTParentAnchor *anchor;
1.287     kahan     316:   ThotBool        use_anchor;
1.307     vatton    317:   HTError        *pres;
1.313     kahan     318:   HTList         *cur;
1.312     kahan     319:   int             index;
1.267     kahan     320: 
                    321:   me =  (AHTReqContext *) HTRequest_context (request);
1.282     kahan     322: 
1.267     kahan     323:   anchor = HTRequest_anchor (request);
1.238     cvs       324: 
1.287     kahan     325:   /* if we get a cached answer, we should get all the header information
                    326:      from the anchor, instead of from the response object */
                    327:   tmp_char = HTAnchor_physical (anchor);
                    328:   if (tmp_char && !strncmp (tmp_char, "cache:", sizeof ("cache:") - 1))
                    329:     use_anchor = TRUE;
                    330:   else
                    331:     use_anchor = FALSE;
                    332: 
1.263     kahan     333:   /* @@@ JK: we need a function here to specify which headers we
1.238     cvs       334:      want to copy */
                    335: 
1.267     kahan     336:   /* copy the content_type if we didn't force it before */
                    337:   if (me->http_headers.content_type == NULL)
1.260     kahan     338:     {
1.267     kahan     339:       /* trying to use the info in the anchor, rather than in the response.
                    340:         Seems it's more recent */
1.282     kahan     341: 
                    342:       /* @@ JK: trying to use the content type stored in the response object */
1.287     kahan     343:       if (!use_anchor && response)
1.282     kahan     344:        tmp_atom = HTResponse_format (response);
                    345:       if (!tmp_atom)
                    346:        tmp_atom = HTAnchor_format (anchor);
1.260     kahan     347: 
1.267     kahan     348:       if (tmp_atom)
                    349:        tmp_char = HTAtom_name (tmp_atom);
                    350:       else
                    351:        tmp_char = "www/unknown";
                    352:       
                    353:       if (tmp_char && tmp_char[0] != EOS)
1.238     cvs       354:        {
1.267     kahan     355:          /* libwww gives www/unknown when it gets an error. As this is 
                    356:             an HTML test, we force the type to text/html */
                    357:          if (!strcmp (tmp_char, "www/unknown"))
                    358:            {
                    359:              /* if it's not a file downloaded from FTP, initialize the
                    360:                 content type to text/html by default */
                    361:              me->http_headers.content_type = NULL;
                    362:            }
                    363:          else 
1.284     kahan     364:              me->http_headers.content_type = TtaStrdup (tmp_char);
1.267     kahan     365:          
1.238     cvs       366: #ifdef DEBUG_LIBWWW
1.267     kahan     367:          fprintf (stderr, "Set content type to: %s\n", 
                    368:                   me->http_headers.content_type);
1.238     cvs       369: #endif /* DEBUG_LIBWWW */
1.267     kahan     370:        }
1.238     cvs       371:     }
1.267     kahan     372: 
1.238     cvs       373:   /* copy the charset */
1.267     kahan     374: 
                    375:   /* @@ JK I think there was a problem when using info directly from
                    376:      the anchor... but what it was? The response object doesn't have
                    377:      it anyway */
                    378:   tmp_atom = HTAnchor_charset (anchor);
                    379: #if 0
1.260     kahan     380:   if (use_anchor)
                    381:     tmp_atom = HTAnchor_charset (anchor);
                    382:   else
                    383:     tmp_atom = HTResponse_charset (response);
1.267     kahan     384: #endif
                    385:   
1.238     cvs       386:   if (tmp_atom)
                    387:     {
1.284     kahan     388:       tmp_char = HTAtom_name (tmp_atom);
                    389:       if (tmp_char)
                    390:        me->http_headers.charset = TtaStrdup (tmp_char);
1.238     cvs       391:     }
1.256     kahan     392: 
1.268     kahan     393:   /* copy the content length */
1.284     kahan     394:   snprintf (tmp_string, sizeof (tmp_string), "%ld", HTAnchor_length (anchor));
                    395:   me->http_headers.content_length = TtaStrdup (tmp_string);
1.268     kahan     396: 
1.256     kahan     397:   /* copy the reason */
                    398:   tmp_char = HTResponse_reason (response);
                    399:   if (tmp_char)
1.284     kahan     400:       me->http_headers.reason = TtaStrdup (tmp_char);
                    401: 
                    402:   /* copy the content-location */
                    403:   tmp_char = HTAnchor_location (anchor);
1.285     kahan     404:   if (tmp_char && *tmp_char)
1.304     kahan     405:     {
                    406:       /* make a copy of the full location_header, for computing the base url */
1.305     kahan     407:       if (HTURL_isAbsolute (tmp_char))
                    408:        me->http_headers.full_content_location = TtaStrdup (tmp_char);
                    409:       else
                    410:        me->http_headers.full_content_location = AmayaParseUrl (me->urlName, tmp_char, 
                    411:                                                                AMAYA_PARSE_ALL);
                    412:       tmp_char = me->http_headers.full_content_location;
1.285     kahan     413:       /* only include the filename. We suppose we have either a 
                    414:        relative or an absolute URL and that everything after the last
1.304     kahan     415:       slash is the doc name + ext */
1.285     kahan     416:       if (HTURL_isAbsolute (tmp_char))
                    417:        {
                    418:          tmp_char2 = tmp_char + strlen (tmp_char) -1;
                    419:          while (*tmp_char2 != URL_SEP && tmp_char2 != tmp_char)
                    420:            tmp_char2--;
                    421:          if (tmp_char2 != tmp_char && *(tmp_char2 + 1))
                    422:            tmp_char = tmp_char2 + 1;
                    423:        }
                    424:       me->http_headers.content_location = TtaStrdup (tmp_char);
                    425:     }
1.307     vatton    426: 
                    427:   /* copy the status */
1.312     kahan     428:   me->http_headers.status = 0;
1.313     kahan     429: 
                    430:   cur = request->error_stack;
                    431:   while (me->http_headers.reason == NULL
                    432:         && (pres = (HTError *) HTList_nextObject (cur)))
1.312     kahan     433:     {
                    434:       index = HTError_index (pres);
                    435:       switch (index)
                    436:        {
                    437:        case HTERR_NO_REMOTE_HOST:
                    438:        case HTERR_SYSTEM:
                    439:        case HTERR_INTERNAL:
                    440:        case HTERR_TIME_OUT:
                    441:        case HTERR_CSO_SERVER:
1.313     kahan     442:          me->http_headers.status = index;
                    443:          me->http_headers.reason = TtaStrdup ("Cannot contact server");
                    444:          break;
1.312     kahan     445:        case HTERR_INTERRUPTED:
1.313     kahan     446:          me->http_headers.status = index;
                    447:          me->http_headers.reason = TtaStrdup ("Interrupted");
1.312     kahan     448:          break;
                    449:        }
                    450:     }
1.238     cvs       451: }
                    452: 
                    453: /*----------------------------------------------------------------------
                    454:   HTTP_headers_delete
                    455:   Deletes all the paramaters that were assigned to the response type
                    456:   ----------------------------------------------------------------------*/
                    457: static void HTTP_headers_delete (AHTHeaders me)
                    458: {
                    459:   if (me.content_type)
                    460:     TtaFreeMemory (me.content_type);
                    461: 
                    462:   if (me.charset)
                    463:     TtaFreeMemory (me.charset);
1.268     kahan     464: 
                    465:   if (me.content_length)
                    466:     TtaFreeMemory (me.content_length);
1.256     kahan     467:   
                    468:   if (me.reason)
                    469:     TtaFreeMemory (me.reason);
1.284     kahan     470: 
                    471:   if (me.content_location)
                    472:     TtaFreeMemory (me.content_location);
1.304     kahan     473: 
                    474:   if (me.full_content_location)
                    475:     TtaFreeMemory (me.full_content_location);
1.238     cvs       476: }
                    477: 
                    478: /*----------------------------------------------------------------------
                    479:   HTTP_headers
                    480:   Returns the value of a parameter in the HTTP response structure.
                    481:   Returns null if this structure is empty.
                    482:   ----------------------------------------------------------------------*/
1.265     cvs       483: char   *HTTP_headers (AHTHeaders *me, AHTHeaderName param)
1.238     cvs       484: {
1.265     cvs       485:   char   *result;
1.238     cvs       486: 
                    487:   if (!me)
                    488:     return NULL;
                    489:   
                    490:   switch (param)
                    491:     {
                    492:     case AM_HTTP_CONTENT_TYPE:
                    493:       result = me->content_type;
                    494:       break;
                    495:     case AM_HTTP_CHARSET:
                    496:       result = me->charset;
1.268     kahan     497:       break;
                    498:     case AM_HTTP_CONTENT_LENGTH:
                    499:       result = me->content_length;
1.238     cvs       500:       break;
1.256     kahan     501:     case AM_HTTP_REASON:
                    502:       result = me->reason;
1.284     kahan     503:       break;
                    504:     case AM_HTTP_CONTENT_LOCATION:
                    505:       result = me->content_location;
1.304     kahan     506:       break;
                    507:     case AM_HTTP_FULL_CONTENT_LOCATION:
                    508:       result = me->full_content_location;
1.256     kahan     509:       break;
1.238     cvs       510:     default:
                    511:       result = NULL;
                    512:     }
                    513:   
                    514:   return result;
                    515: }
                    516: 
                    517: /*----------------------------------------------------------------------
1.17      cvs       518:   AHTReqContext_new
                    519:   create a new Amaya Context Object and update the global Amaya
                    520:   request status.
1.297     kirschpi  521:   
                    522:   ----------------------------------------------------------------------
                    523:   MKP: this function is now used in davlib.c file for the WebDAV requests 
1.299     kirschpi  524: 
1.297     kirschpi  525:   ---------------------------------------------------------------------- */
                    526: AHTReqContext *AHTReqContext_new (int docid)
1.4       cvs       527: {
                    528:    AHTReqContext      *me;
                    529:    AHTDocId_Status    *docid_status;
                    530: 
                    531:    if ((me = (AHTReqContext *) TtaGetMemory (sizeof (AHTReqContext))) == NULL)
1.116     cvs       532:      outofmem (__FILE__, "AHTReqContext_new");
                    533: 
                    534:    /* clear the structure */
                    535:    memset ((void *) me, 0, sizeof (AHTReqContext));
1.4       cvs       536: 
1.81      cvs       537:    /* Bind the Context object together with the Request Object */
                    538:    me->request = HTRequest_new ();
                    539:   
1.80      cvs       540:    /* clean the associated file structure) */
1.79      cvs       541:    HTRequest_setOutputStream (me->request, NULL);
1.81      cvs       542:  
1.4       cvs       543:    /* Initialize the other members of the structure */
1.17      cvs       544:    me->reqStatus = HT_NEW; /* initial status of a request */
1.4       cvs       545:    me->docid = docid;
                    546:    HTRequest_setMethod (me->request, METHOD_GET);
                    547:    HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                    548:    HTRequest_setContext (me->request, me);
1.116     cvs       549: 
1.36      cvs       550:    /* experimental */
                    551:    me->read_sock = INVSOC;
                    552:    me->write_sock = INVSOC;
                    553:    me->except_sock = INVSOC;
1.4       cvs       554: 
                    555:    /* Update the global context */
                    556:    HTList_appendObject (Amaya->reqlist, (void *) me);
                    557: 
                    558:    docid_status = GetDocIdStatus (docid, Amaya->docid_status);
                    559: 
1.7       cvs       560:    if (docid_status == NULL)
                    561:      {
1.116     cvs       562:        docid_status = (AHTDocId_Status *) 
                    563:          TtaGetMemory (sizeof (AHTDocId_Status));
1.7       cvs       564:        docid_status->docid = docid;
                    565:        docid_status->counter = 1;
                    566:        HTList_addObject (Amaya->docid_status, (void *) docid_status);
                    567:      }
                    568:    else
1.4       cvs       569:       docid_status->counter++;
                    570: 
1.297     kirschpi  571: #ifdef DAV                /* clean the DAV request context */
                    572:    me->dav_context = NULL; /* it should be create only when doing a DAV request */
1.302     kirschpi  573: #endif /* DAV */  
1.297     kirschpi  574: 
1.4       cvs       575:    Amaya->open_requests++;
                    576: 
1.74      cvs       577: #ifdef DEBUG_LIBWWW
                    578:    fprintf (stderr, "AHTReqContext_new: Created object %p\n", me);
                    579: #endif   
1.116     cvs       580: 
1.4       cvs       581:    return me;
                    582: }
                    583: 
1.5       cvs       584: /*----------------------------------------------------------------------
1.17      cvs       585:   AHTReqContext_delete
                    586:   Delete an Amaya Context Object and update the global Amaya request
                    587:   status.
1.5       cvs       588:   ----------------------------------------------------------------------*/
1.191     cvs       589: ThotBool  AHTReqContext_delete (AHTReqContext * me)
1.4       cvs       590: {
                    591:    AHTDocId_Status    *docid_status;
                    592: 
1.7       cvs       593:    if (me)
                    594:      {
1.74      cvs       595: #ifdef DEBUG_LIBWWW
1.138     cvs       596:        fprintf (stderr, "AHTReqContext_delete: Deleting object %p\n", me);
1.74      cvs       597: #endif   
1.297     kirschpi  598: 
                    599: #ifdef DAV /* if there is a DAV context object, delete it */
1.303     kirschpi  600:        if (me->dav_context) AHTDAVContext_delete (me->dav_context);
1.297     kirschpi  601: #endif /* DAV */
                    602: 
1.138     cvs       603:        if (Amaya->reqlist)
                    604:         HTList_removeObject (Amaya->reqlist, (void *) me);
                    605:        
                    606:        docid_status = GetDocIdStatus (me->docid, Amaya->docid_status);
                    607:        if (docid_status)
                    608:         {
                    609:           docid_status->counter--;
                    610:           
                    611:           if (docid_status->counter == 0)
                    612:             {
                    613:               HTList_removeObject (Amaya->docid_status, (void *) docid_status);
                    614:               TtaFreeMemory ((void *) docid_status);
                    615:             }
                    616:         }
1.215     cvs       617: 
                    618:        HTNoFreeStream_delete (HTRequest_outputStream (me->request));
                    619:        HTRequest_setOutputStream (me->request, NULL); 
1.190     cvs       620:        /* JK: no longer needed in libwww 5.2.3
                    621:          if (me->method != METHOD_PUT && HTRequest_outputStream (me->request))
                    622:          AHTFWriter_FREE (HTRequest_outputStream (me->request));
                    623:        */
1.138     cvs       624:        HTRequest_delete (me->request);
                    625:        
                    626:        if (me->output && me->output != stdout)
                    627:         {      
1.85      cvs       628: #ifdef DEBUG_LIBWWW       
1.138     cvs       629:           fprintf (stderr, "AHTReqContext_delete: URL is  %s, closing "
                    630:                    "FILE %p\n", me->urlName, me->output); 
1.85      cvs       631: #endif
1.138     cvs       632:           fclose (me->output);
                    633:           me->output = NULL;
                    634:         }
1.79      cvs       635:          
1.138     cvs       636:        if (me->error_stream != (char *) NULL)
                    637:         HT_FREE (me->error_stream);
                    638: #ifndef _WINDOWS
                    639: #ifdef WWW_XWINDOWS    
                    640:        if (me->read_xtinput_id || me->write_xtinput_id ||
                    641:           me->except_xtinput_id)
                    642:         RequestKillAllXtevents(me);
                    643: #endif /* WWW_XWINDOWS */
                    644: #endif /* !_WINDOWS */
                    645:        
                    646:        if (me->reqStatus == HT_ABORT)
                    647:         {
                    648:           if (me->outputfile && me->outputfile[0] != EOS)
                    649:             {
1.233     cvs       650:               TtaFileUnlink (me->outputfile);
1.138     cvs       651:               me->outputfile[0] = EOS;
                    652:             }
                    653:         }
                    654:        
                    655:        if ((me->mode & AMAYA_ASYNC) || (me->mode & AMAYA_IASYNC))
                    656:         /* for the ASYNC mode, free the memory we allocated in GetObjectWWW
                    657:            or in PutObjectWWW */
                    658:         {
                    659:           if (me->urlName)
                    660:             TtaFreeMemory (me->urlName);
                    661:           if (me->outputfile)
                    662:             TtaFreeMemory (me->outputfile);
                    663:         }
1.206     cvs       664: 
1.208     cvs       665:        /* the real name to which we are publishing */
                    666:        if (me->default_put_name)
                    667:         TtaFreeMemory (me->default_put_name);
                    668: 
1.206     cvs       669:        /* @@ temp change for the %esc conversion */
                    670:        if (me->method == METHOD_PUT && me->urlName)
                    671:         TtaFreeMemory (me->urlName);
                    672: 
1.138     cvs       673:        if (me->formdata)
                    674:         HTAssocList_delete (me->formdata);
1.238     cvs       675: 
                    676:        /* erase the response headers */
                    677:        HTTP_headers_delete (me->http_headers);
1.138     cvs       678:        
1.228     cvs       679: #ifdef ANNOTATIONS
                    680:        if (me->document)
                    681:         TtaFreeMemory (me->document);
                    682: #endif /* ANNOTATIONS */
                    683: 
1.138     cvs       684:        /* to trace bugs */
                    685:        memset ((void *) me, 0, sizeof (AHTReqContext));
                    686:        
                    687:        TtaFreeMemory ((void *) me);
                    688:        
                    689:        Amaya->open_requests--;
                    690:        
                    691:        return TRUE;
1.7       cvs       692:      }
1.15      cvs       693:    return FALSE;
1.4       cvs       694: }
                    695: 
                    696: 
1.15      cvs       697: /*----------------------------------------------------------------------
1.17      cvs       698:   Thread_deleteAll
                    699:   this function deletes the whole list of active threads.           
1.5       cvs       700:   ----------------------------------------------------------------------*/
1.4       cvs       701: static void         Thread_deleteAll (void)
                    702: {
1.21      cvs       703:   HTList             *cur;
                    704:   AHTReqContext      *me;
                    705:   AHTDocId_Status    *docid_status;
                    706: 
1.74      cvs       707:   if (Amaya && Amaya->reqlist)
                    708:     {
                    709:       if (Amaya->open_requests > 0)
                    710: #ifdef DEBUG_LIBWWW
                    711:       fprintf (stderr, "Thread_deleteAll: Killing %d outstanding "
                    712:                       "requests\n", Amaya->open_requests);
                    713: #endif   
                    714:        {
                    715:          cur = Amaya->reqlist;
                    716:          
                    717:          /* erase the requests */
                    718:          while ((me = (AHTReqContext *) HTList_removeLastObject (cur)))
                    719:            {
                    720:              if (me->request)
                    721:                {
1.142     cvs       722: #ifndef _WINDOWS
                    723: #ifdef WWW_XWINDOWS 
1.74      cvs       724:                  RequestKillAllXtevents (me);
1.142     cvs       725: #endif /* WWW_XWINDOWS */
1.138     cvs       726: #endif /* !_WINDOWS */
1.140     cvs       727:                  if (!HTRequest_kill (me->request))
                    728:                    AHTReqContext_delete (me);
1.74      cvs       729:                }
                    730:            }           /* while */
                    731:          
                    732:          /* erase the docid_status entities */
                    733:          while ((docid_status = (AHTDocId_Status *) HTList_removeLastObject ((void *) Amaya->docid_status)))
                    734:            TtaFreeMemory ((void *) docid_status);
                    735:          
                    736:        }                       /* if */
1.84      cvs       737:        
1.74      cvs       738:     }
1.4       cvs       739: }
1.198     cvs       740:  
1.5       cvs       741: /*----------------------------------------------------------------------
1.83      cvs       742:   AHTOpen_file
                    743:   ----------------------------------------------------------------------*/
1.85      cvs       744: int                 AHTOpen_file (HTRequest * request)
1.83      cvs       745: {
                    746:   AHTReqContext      *me;      /* current request */
                    747: 
                    748:   me = HTRequest_context (request);
1.93      cvs       749:   if (!me)
                    750:       return HT_ERROR;
1.83      cvs       751: #ifdef DEBUG_LIBWWW
1.116     cvs       752:   fprintf(stderr, "AHTOpen_file: start for object : %p\n", me);
1.85      cvs       753: #endif /* DEBUG_LIBWWW */
                    754:   if (me->reqStatus == HT_ABORT) 
                    755:     {
                    756: #ifdef DEBUG_LIBWWW
                    757:       fprintf(stderr, "AHTOpen_file: caught an abort request, skipping it\n");
1.83      cvs       758: #endif /* DEBUG_LIBWWW */
1.85      cvs       759:       return HT_OK;
                    760:     }
                    761: 
1.136     cvs       762:   if (me->method == METHOD_PUT)
                    763:     {
                    764:       me->reqStatus = HT_WAITING;
                    765:       return HT_OK;
                    766:     }
                    767: 
1.85      cvs       768:   if (HTRequest_outputStream (me->request)) 
                    769:     {
                    770: #ifdef DEBUG_LIBWWW
                    771:       fprintf(stderr, "AHTOpen_file: output stream already existed for url %s\n", me->urlName);
                    772: #endif /* DEBUG_LIBWWW */      
                    773:       return HT_OK;
                    774:     }
                    775: 
                    776: #ifdef DEBUG_LIBWWW
1.265     cvs       777:   fprintf(stderr, "AHTOpen_file: opening output stream for url %s\n", me->urlName);
1.85      cvs       778: #endif /* DEBUG_LIBWWW */      
                    779: 
1.83      cvs       780:   if (!(me->output) && 
                    781:       (me->output != stdout) && 
                    782: #ifndef _WINDOWS
1.265     cvs       783:       (me->output = fopen (me->outputfile, "w")) == NULL)
1.116     cvs       784: #else /* !_WINDOWS */
1.265     cvs       785:       (me->output = fopen (me->outputfile, "wb")) == NULL)  
                    786: #endif /* !_WINDOWS */
1.83      cvs       787:     {
1.131     cvs       788:       me->outputfile[0] = EOS; /* file could not be opened */
1.85      cvs       789: #ifdef DEBUG_LIBWWW
                    790:       fprintf(stderr, "AHTOpen_file: couldn't open output stream for url %s\n", me->urlName);
                    791: #endif
1.265     cvs       792:       TtaSetStatus (me->docid, 1,
                    793:                    TtaGetMessage (AMAYA, AM_CANNOT_CREATE_FILE),
                    794:                    me->outputfile);
1.83      cvs       795:       me->reqStatus = HT_ERR;
                    796:       return (HT_ERROR);
                    797:     }
                    798:          
                    799:   HTRequest_setOutputStream (me->request,
1.265     cvs       800:                             AHTFWriter_new (me->request, me->output, YES));
1.83      cvs       801:   me->reqStatus = HT_WAITING;
                    802:   return HT_OK;
                    803: }
                    804: 
                    805: /*----------------------------------------------------------------------
1.265     cvs       806:   SafePut_init
                    807:   Sets up the domains which are authorized to make a redirect on 
                    808:   a PUT.
                    809:   ----------------------------------------------------------------------*/
                    810: static void SafePut_init (void)
                    811: {
                    812:   char     *strptr;
1.266     cvs       813:   char     *ptr, *ptr2;
                    814:   char     *domain;
1.265     cvs       815: 
                    816:   /* get the proxy settings from the thot.ini file */
                    817:   strptr = TtaGetEnvString ("SAFE_PUT_REDIRECT");
                    818:   if (strptr && *strptr)
                    819:     {
                    820:       /* Get copy we can mutilate */
1.266     cvs       821:       ptr2 = TtaStrdup (strptr);
1.265     cvs       822:       /* convert to lowercase */
1.266     cvs       823:       ptr = ptr2;
1.265     cvs       824:       while (*ptr) 
                    825:        {
                    826:          *ptr = tolower (*ptr);
                    827:          ptr++;
                    828:        }
                    829:       
                    830:       /* create the list container */
1.266     cvs       831:       safeput_list = HTList_new ();
                    832:  
1.265     cvs       833:       /* store the domain list */
1.266     cvs       834:       ptr = ptr2;
                    835:       while ((domain = HTNextField (&ptr)) != NULL)
1.265     cvs       836:          HTList_addObject (safeput_list, TtaStrdup (domain)); 
                    837: 
                    838:       TtaFreeMemory (ptr2);
                    839:     }
                    840: }
                    841: 
                    842: /*----------------------------------------------------------------------
                    843:   SafePut_delete
                    844:   Deletes the safeput_list variable
                    845:   ----------------------------------------------------------------------*/
                    846: static void SafePut_delete (void)
                    847: {
                    848:   HTList *cur = safeput_list;
                    849:   char *domain;
                    850: 
                    851:   if (!safeput_list) 
                    852:     return;
                    853: 
                    854:   while ((domain = (char *) HTList_nextObject (cur))) 
                    855:       TtaFreeMemory (domain);
                    856:    HTList_delete (safeput_list);
                    857:    safeput_list = NULL;
                    858: }
                    859: 
                    860: /*----------------------------------------------------------------------
                    861:   SafePut_query
                    862:   returns true if the domain to which belongs the URL accepts an automatic
                    863:   PUT redirect.
                    864:   ----------------------------------------------------------------------*/
                    865: static ThotBool SafePut_query (char *url)
                    866: {
1.266     cvs       867:   HTList   *cur;
                    868:   char     *me;
                    869:   ThotBool  found;
                    870:   char      tmp[MAX_LENGTH];
1.265     cvs       871: 
                    872:   /* extract the domain path of the url and normalize it */
                    873:   /* domain = url; */
                    874:   cur = safeput_list;
                    875:   found = FALSE;
                    876: 
1.266     cvs       877:   while ((me = (char *) HTList_nextObject (cur)))
                    878:     {
1.273     cvs       879:       strcpy (tmp, me);
1.266     cvs       880:       if (strstr (url, tmp))
                    881:        {
                    882:          found = TRUE;
                    883:          break;
                    884:        } 
                    885:     } 
1.265     cvs       886: 
                    887:   return (found);
                    888: }
                    889: 
                    890: /*----------------------------------------------------------------------
1.17      cvs       891:   redirection_handler
                    892:   this function is registered to handle permanent and temporary
                    893:   redirections.
                    894:   ----------------------------------------------------------------------*/
1.265     cvs       895: static int redirection_handler (HTRequest *request, HTResponse *response,
                    896:                                void *param, int status)
1.4       cvs       897: {
1.265     cvs       898:   HTAnchor           *new_anchor = HTResponse_redirection (response);
                    899:   AHTReqContext      *me = HTRequest_context (request);
                    900:   HTMethod            method = HTRequest_method (request);
                    901:   char               *ref;
                    902:   char               *escape_src, *dst;
                    903:   char                urlAdr[MAX_LENGTH];
                    904: 
                    905:    if (!me)
                    906:      /* if the redirect doesn't come from Amaya, we call libwww's standard redirect filter */
                    907:      return (HTRedirectFilter (request, response, param, status));
                    908:    
                    909:    if (!new_anchor)
                    910:      {
                    911:        if (PROT_TRACE)
1.235     cvs       912:          HTTrace ("Redirection. No destination\n");
1.265     cvs       913:        return HT_OK;
                    914:      }
1.4       cvs       915: 
                    916:    /*
1.207     cvs       917:    ** Only do redirect on GET, HEAD, and authorized domains for PUT
1.265     cvs       918:    */
                    919:    if ((me->method == METHOD_PUT && !SafePut_query (me->urlName)) ||
                    920:        (me->method != METHOD_PUT && !HTMethod_isSafe (method)))
                    921:      {
                    922:      /*
                    923:      ** If we got a 303 See Other then change the method to GET.
                    924:      ** Otherwise ask the user whether we should continue.
                    925:      */
                    926:      if (status == HT_SEE_OTHER)
                    927:        {
1.235     cvs       928:          if (PROT_TRACE)
1.265     cvs       929:           HTTrace("Redirection. Changing method from %s to GET\n", HTMethod_name(method));
                    930:         HTRequest_setMethod(request, METHOD_GET);
                    931:        }
                    932:      else
                    933:        {
                    934:         HTAlertCallback    *prompt = HTAlert_find (HT_A_CONFIRM);
                    935:         if (prompt)
                    936:           {
                    937:             if ((*prompt) (request, HT_A_CONFIRM, HT_MSG_REDIRECTION, NULL, NULL, NULL) != YES)
                    938:               {
                    939:                 /* the user didn't agree on the redirection, so
                    940:                    we consider it's an abort */
                    941:                 me->reqStatus = HT_ABORT;
                    942:                 /* and we return HT_OK so that the terminate_handler
                    943:                    will be called */
                    944:                 return HT_OK;
                    945:               }
                    946:           }
                    947:        }
                    948:    }
                    949: 
1.4       cvs       950:    /*
1.265     cvs       951:    **  Start new request with the redirect anchor found in the headers.
                    952:    **  Note that we reuse the same request object which means that we must
                    953:    **  keep this around until the redirected request has terminated. It also
                    954:    **  allows us in an easy way to keep track of the number of redirections
                    955:    **  so that we can detect endless loops.
                    956:    */
                    957:    if (HTRequest_doRetry (request))
                    958:      {
                    959:        /*
                    960:        ** Start request with new credentials 
                    961:        */
                    962:        /* only do a redirect using a network protocol understood by Amaya */
1.273     cvs       963:        strcpy (urlAdr, new_anchor->parent->address);
1.265     cvs       964:        if (IsValidProtocol (urlAdr))
                    965:         {
                    966:           /* if it's a valid URL, we try to normalize it */
                    967:           /* We use the pre-redirection anchor as a base name */
                    968:           /* @@ how to obtain this address here? */
                    969:           dst = urlAdr;
                    970:           escape_src = EscapeURL (me->urlName);
                    971:           if (escape_src)
                    972:             {
                    973:               ref = AmayaParseUrl (dst, escape_src, AMAYA_PARSE_ALL);
                    974:               TtaFreeMemory (escape_src);
                    975:             }
                    976:           else
                    977:             ref = NULL;
                    978:           
                    979:           if (ref)
                    980:             {
                    981:               HTAnchor_setPhysical (HTAnchor_parent (new_anchor), ref);
                    982:               TtaFreeMemory (ref);
                    983:             }
                    984:           else
                    985:             return HT_OK; /* We can't redirect anymore */
                    986:         }
                    987:        else
                    988:         return HT_OK; /* We can't redirect anymore */
                    989:        
                    990:        /* update the current file name */
                    991:        if ((me->mode & AMAYA_ASYNC) || (me->mode & AMAYA_IASYNC) ||
                    992:           (me->method == METHOD_PUT))
                    993:         {
                    994:           TtaFreeMemory (me->urlName);
1.272     cvs       995:           me->urlName = TtaStrdup (urlAdr);
1.265     cvs       996:         }
                    997:        else
                    998:         {
                    999:           /* it's a SYNC mode, so we should keep the urlName */
                   1000:           strncpy (me->urlName, urlAdr, MAX_LENGTH - 1);
                   1001:           me->urlName[MAX_LENGTH - 1] = EOS;
                   1002:         }
                   1003:        ChopURL (me->status_urlName, me->urlName);
1.166     cvs      1004: 
1.265     cvs      1005:        /* @@ verify if this is important */
                   1006:        /* @@@ new libwww doesn't need this free stream while making
                   1007:          a PUT. Is it the case everywhere or just for PUT? */
                   1008:        if (me->method != METHOD_PUT &&
                   1009:           me->request->orig_output_stream != NULL)
                   1010:         {
                   1011:           AHTFWriter_FREE (me->request->orig_output_stream);
                   1012:           me->request->orig_output_stream = NULL;
                   1013:           if (me->output != stdout)
                   1014:             {
                   1015:               /* Are we writing to a file? */
1.257     kahan    1016: #ifdef DEBUG_LIBWWW
1.265     cvs      1017:               fprintf (stderr, "redirection_handler: New URL is  %s, closing FILE %p\n", me->urlName, me->output); 
1.257     kahan    1018: #endif 
1.265     cvs      1019:               fclose (me->output);
                   1020:               me->output = NULL;
                   1021:             }
                   1022:         }
                   1023:        
                   1024:        /* tell the user what we're doing */
                   1025:        TtaSetStatus (me->docid, 1,
                   1026:                     TtaGetMessage (AMAYA, AM_RED_FETCHING), me->status_urlName); 
                   1027:        /*
                   1028:        ** launch the request
                   1029:        */
                   1030:        /* add a link relationship? */
                   1031:        /* reset the request status */
                   1032:        me->reqStatus = HT_NEW; 
                   1033:        /* clear the errors */
                   1034:        HTError_deleteAll (HTRequest_error (request));
                   1035:        HTRequest_setError (request, NULL);
                   1036:        /* clear the authentication credentials, as they get regenerated  */
                   1037:        HTRequest_deleteCredentialsAll (request);
1.297     kirschpi 1038: 
                   1039: #ifdef DAV
1.299     kirschpi 1040:        /* remove the old header "If" (WebDAV lock information) */
1.297     kirschpi 1041:        DAVRemoveIfHeader (me);
                   1042:        
                   1043:        /* search lock information for the new url */
                   1044:        if (me->method == METHOD_POST || me->method == METHOD_PUT) 
                   1045:            DAVAddIfHeader (me,me->urlName);
1.302     kirschpi 1046: #endif /* DAV */      
1.265     cvs      1047:        
                   1048:        if (me->method == METHOD_POST || me->method == METHOD_PUT)
1.285     kahan    1049:         {
                   1050:           /* PUT, POST etc. */
                   1051:           /* for PUT, we memorize there was a redirection, so that we 
                   1052:              can clear the original cache entry in the terminate_handler */
                   1053:           if (me->method == METHOD_PUT)
                   1054:             me->put_redirection = TRUE;
                   1055:           status = HTLoadAbsolute (me->urlName, request);
                   1056:         }
1.265     cvs      1057:        else
                   1058:         HTLoadAnchor (new_anchor, request);
                   1059:      }
                   1060:    else
                   1061:      {
                   1062:        HTRequest_addError (request, ERR_FATAL, NO, HTERR_MAX_REDIRECT, NULL, 0, "HTRedirectFilter");
                   1063:        /* so that we can show the error message */
                   1064:        if (me->error_html)
                   1065:         DocNetworkStatus[me->docid] |= AMAYA_NET_ERROR;
                   1066:        me->reqStatus = HT_ERR;
                   1067:        TtaSetStatus (me->docid, 1, TtaGetMessage (AMAYA, AM_REDIRECTIONS_LIMIT), NULL);
                   1068:      }
                   1069:    
1.4       cvs      1070:    /*
1.74      cvs      1071:    **  By returning HT_ERROR we make sure that this is the last handler to be
                   1072:    **  called. We do this as we don't want any other filter to delete the 
                   1073:    **  request object now when we have just started a new one ourselves
                   1074:    */
1.4       cvs      1075:    return HT_ERROR;
                   1076: }
                   1077: 
1.151     cvs      1078: #ifdef AMAYA_LOST_UPDATE
                   1079: /*----------------------------------------------------------------------
                   1080:   precondition_handler
                   1081:   412 "Precondition failed" handler
                   1082:   ----------------------------------------------------------------------*/
1.265     cvs      1083: static int precondition_handler (HTRequest *request, HTResponse *response,
                   1084:                                 void *context, int status)
1.151     cvs      1085: {
1.315   ! vatton   1086:   AHTReqContext      *me = (AHTReqContext *) HTRequest_context (request);
1.168     cvs      1087:   HTAlertCallback    *prompt = HTAlert_find (HT_A_CONFIRM);
1.315   ! vatton   1088:   ThotBool            force_put;
1.151     cvs      1089: 
                   1090:   if (!me)
                   1091:     return HT_OK;              /* not an Amaya request */
                   1092: 
1.168     cvs      1093:   if (prompt)
1.315   ! vatton   1094:     {
        !          1095:       if (me->method == METHOD_GET)
        !          1096:          /* @@@@ IV */
        !          1097:        force_put = (*prompt) (request, HT_A_CONFIRM, status,
        !          1098:                               NULL, NULL, NULL);
        !          1099:       else
        !          1100:        force_put = (*prompt) (request, HT_A_CONFIRM, HT_MSG_RULES,
        !          1101:                               NULL, NULL, NULL);
        !          1102:     }
1.168     cvs      1103:   else
                   1104:     force_put = NO;
                   1105:   
                   1106:   if (force_put)
                   1107:     {
1.297     kirschpi 1108: #ifdef DAV
                   1109:       BOOL noIf = NO;
                   1110: 
                   1111:       /* MKP: if the old request has preconditions, *
                   1112:        * then, we supose that these preconditions   *
                   1113:        * caused the 412 Precondition Failed status  *
                   1114:        * code, otherwise we supose that the cause   *
                   1115:        * was an eventual If header.                 */
1.315   ! vatton   1116:       if (HTRequest_preconditions(me->request) != HT_NO_MATCH)
1.297     kirschpi 1117:           noIf = NO;
                   1118:       else
                   1119:           noIf = YES;      
1.302     kirschpi 1120: #endif /* DAV */
1.297     kirschpi 1121:       
                   1122:       
1.168     cvs      1123:       /* start a new PUT request without preconditions */
                   1124:       /* @@ do we need to kill the request? */
                   1125:       if (me->output && me->output != stdout)
                   1126:        {
                   1127:          fclose (me->output);
                   1128:          me->output = NULL;
                   1129:        }
                   1130:       /*
                   1131:       ** reset the Amaya and libwww request status 
                   1132:       */
1.176     cvs      1133: 
                   1134:       /* start with a new, clean request structure */
                   1135:       HTRequest_delete (me->request);
                   1136:       me->request = HTRequest_new ();
                   1137:       /* clean the associated file structure) */
                   1138:       HTRequest_setOutputStream (me->request, NULL);
                   1139:       /* Initialize the other members of the structure */
1.171     cvs      1140:       HTRequest_setMethod (me->request, METHOD_GET);
1.176     cvs      1141:       HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                   1142:       HTRequest_setContext (me->request, me);
                   1143:       HTRequest_setPreemptive (me->request, NO);
                   1144:       /*
                   1145:       ** Make sure that the first request is flushed immediately and not
                   1146:       ** buffered in the output buffer
                   1147:       */
                   1148:       if (me->mode & AMAYA_FLUSH_REQUEST)
                   1149:        HTRequest_setFlush(me->request, YES);
                   1150: 
1.171     cvs      1151:       /* turn off preconditions */
                   1152:       HTRequest_setPreconditions(me->request, HT_NO_MATCH);
                   1153:       me->reqStatus = HT_NEW; 
1.297     kirschpi 1154: 
                   1155:       
                   1156: #ifdef DAV
1.302     kirschpi 1157:       /* MKP: add an If header (lock information) only 
                   1158:        * if there wasn't preconditions */
1.315   ! vatton   1159:       if (noIf != YES)
        !          1160:        DAVAddIfHeader (me,HTAnchor_address(me->dest));
1.297     kirschpi 1161: #endif /* DAV */
                   1162:       
                   1163:       
1.171     cvs      1164:       /* make the request */      
1.176     cvs      1165:       status = HTPutDocumentAnchor (HTAnchor_parent (me->source), 
                   1166:                                    me->dest, me->request);
1.168     cvs      1167:       /* stop here */
                   1168:       return HT_ERROR;
                   1169:     }
                   1170:   else
                   1171:     {
                   1172:       /* abort the request */
                   1173:       /* @@ should we call StopRequest here? */
                   1174:       me->reqStatus = HT_ABORT;
                   1175:       /* stop here */
                   1176:       return HT_ERROR; 
                   1177:     }
                   1178: }
1.151     cvs      1179: 
1.168     cvs      1180: /*----------------------------------------------------------------------
                   1181:   check_handler
                   1182:   Request HEAD checker filter
                   1183:   ----------------------------------------------------------------------*/
                   1184: static int check_handler (HTRequest * request, HTResponse * response,
1.151     cvs      1185:                            void * param, int status)
                   1186: {
1.168     cvs      1187:   AHTReqContext  *me = (AHTReqContext *) HTRequest_context (request);
                   1188:   HTAlertCallback    *prompt = HTAlert_find (HT_A_CONFIRM);
1.191     cvs      1189:   ThotBool force_put;
1.168     cvs      1190: 
                   1191:   if (!me)
                   1192:     return HT_OK;              /* not an Amaya request */
                   1193: 
                   1194:   HTRequest_deleteAfter(me->request, check_handler);
                   1195:   /*
                   1196:   ** If head request showed that the document doesn't exist
                   1197:   ** then just go ahead and PUT it. Otherwise ask for help
                   1198:   */
                   1199:   if (status == HT_ERROR || status == HT_INTERRUPTED || status == HT_TIMEOUT)
                   1200:     {
                   1201:       /* we'd need to call terminate_handler, to free the resources */
                   1202:       /* abort the request */
                   1203:       /* @@ should we call StopRequest here? */
                   1204:       me->reqStatus = HT_ABORT;
                   1205:       /* stop here */
                   1206:       return HT_ERROR; 
                   1207:     } 
                   1208:   else if (status == HT_NO_ACCESS || status == HT_NO_PROXY_ACCESS) 
                   1209:     {
                   1210:       /* we'd need to call terminate_handler, to free the resources */
                   1211:       /* abort the request */
                   1212:       /* @@ should we call StopRequest here? */
                   1213:       me->reqStatus = HT_ABORT;
                   1214:       /* stop here */
                   1215:       return HT_ERROR; 
                   1216:     }
                   1217:   else if ( (abs(status)/100) != 2) 
                   1218:     {
1.176     cvs      1219:       /* start with a new, clean request structure */
                   1220:       HTRequest_delete (me->request);
                   1221:       me->request = HTRequest_new ();
1.208     cvs      1222:       /* add the default PUT name */
                   1223:       HTRequest_setDefaultPutName (me->request, me->default_put_name);
1.176     cvs      1224:       /* clean the associated file structure) */
                   1225:       HTRequest_setOutputStream (me->request, NULL);
                   1226:       /* Initialize the other members of the structure */
1.171     cvs      1227:       HTRequest_setMethod (me->request, METHOD_GET);
1.176     cvs      1228:       HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                   1229:       HTRequest_setContext (me->request, me);
                   1230:       HTRequest_setPreemptive (me->request, NO);
                   1231:       /*
                   1232:       ** Make sure that the first request is flushed immediately and not
                   1233:       ** buffered in the output buffer
                   1234:       */
                   1235:       if (me->mode & AMAYA_FLUSH_REQUEST)
                   1236:        HTRequest_setFlush(me->request, YES);
1.297     kirschpi 1237:    
                   1238: #ifdef DAV
1.302     kirschpi 1239:       /* MKP: try to add an "If" header (lock information) 
                   1240:        *      Such header will be added only if there is a
                   1241:        *      lock information in the local base. */
1.297     kirschpi 1242:       DAVAddIfHeader (me,me->urlName);   
1.302     kirschpi 1243: #endif /* DAV */
1.297     kirschpi 1244: 
1.176     cvs      1245: 
                   1246:       /* turn on the special preconditions, to avoid having this
                   1247:         ressource appear before we do the PUT */
1.168     cvs      1248:       HTRequest_setPreconditions(me->request, HT_DONT_MATCH_ANY);
1.171     cvs      1249:       me->reqStatus = HT_NEW;
1.168     cvs      1250:       status = HTPutDocumentAnchor (HTAnchor_parent (me->source), me->dest, me->request);
                   1251:       return HT_ERROR; /* stop here */
1.176     cvs      1252:     }
1.168     cvs      1253:   else 
                   1254:     {
                   1255:       if (prompt)
                   1256:          force_put = (*prompt) (request, HT_A_CONFIRM, HT_MSG_FILE_REPLACE,
                   1257:                                 NULL, NULL, NULL);
                   1258:       else
                   1259:        force_put = FALSE;
                   1260: 
                   1261:       if (force_put)
1.151     cvs      1262:        {
                   1263:          /* Start a new PUT request without preconditions */
1.176     cvs      1264: 
                   1265:          /* get a new, clean request structure */
                   1266:          HTRequest_delete (me->request);
                   1267:          me->request = HTRequest_new ();
1.208     cvs      1268:          /* add the default PUT name */
                   1269:          HTRequest_setDefaultPutName (me->request, me->default_put_name);
1.176     cvs      1270:          /* clean the associated file structure) */
                   1271:          HTRequest_setOutputStream (me->request, NULL);
                   1272:          /* Initialize the other members of the structure */
1.171     cvs      1273:          HTRequest_setMethod (me->request, METHOD_GET);
1.176     cvs      1274:          HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                   1275:          HTRequest_setContext (me->request, me);
                   1276:          HTRequest_setPreemptive (me->request, NO);
1.297     kirschpi 1277:    
                   1278: #ifdef DAV
1.302     kirschpi 1279:          /* MKP: try to add an "If" header (lock information) 
                   1280:           *      Such header will be added only if there is a
                   1281:           *      lock information in the local base. */ 
1.297     kirschpi 1282:           DAVAddIfHeader (me,HTAnchor_address(me->dest));   
1.302     kirschpi 1283: #endif /* DAV */
                   1284: 
1.297     kirschpi 1285:          
1.176     cvs      1286:          /*
                   1287:          ** Make sure that the first request is flushed immediately and not
                   1288:          ** buffered in the output buffer
                   1289:          */
                   1290:          if (me->mode & AMAYA_FLUSH_REQUEST)
                   1291:            HTRequest_setFlush(me->request, YES);
                   1292:          /* remove the preconditions */
1.168     cvs      1293:          HTRequest_setPreconditions(me->request, HT_NO_MATCH);
1.171     cvs      1294:          me->reqStatus = HT_NEW; 
1.176     cvs      1295:          status = HTPutDocumentAnchor (HTAnchor_parent (me->source), 
                   1296:                                        me->dest, me->request);
1.168     cvs      1297:          return HT_ERROR; /* stop here */
1.151     cvs      1298:        } 
1.168     cvs      1299:       else
                   1300:        {
                   1301:          /* we'd need to call terminate_handler, to free the resources */
                   1302:          /* abort the request */
                   1303:          /* @@ should we call StopRequest here? */
                   1304:          me->reqStatus = HT_ABORT;
                   1305:          /* stop here */
                   1306:          return HT_ERROR; 
                   1307:        }
                   1308:     }
                   1309:   return HT_ERROR;
1.151     cvs      1310: }
                   1311: #endif /* AMAYA_LOST_UPDATE */
                   1312: 
1.5       cvs      1313: /*----------------------------------------------------------------------
1.17      cvs      1314:   terminate_handler
                   1315:   this function is registered to handle the result of the request
1.5       cvs      1316:   ----------------------------------------------------------------------*/
1.265     cvs      1317: static int terminate_handler (HTRequest *request, HTResponse *response,
                   1318:                              void *context, int status)
1.4       cvs      1319: {
1.116     cvs      1320:   AHTReqContext      *me = (AHTReqContext *) HTRequest_context (request);
1.191     cvs      1321:   ThotBool            error_flag;
1.116     cvs      1322: 
                   1323:   if (!me)
1.214     cvs      1324:      return HT_ERROR;          /* not an Amaya request */
1.116     cvs      1325: 
                   1326:   if (me->reqStatus == HT_END)
                   1327:     /* we have already processed this request! */
                   1328:     return HT_OK;
                   1329: 
                   1330:   /* if Amaya was killed, treat with this request as if it were
                   1331:      issued by a Stop button event */
                   1332: 
                   1333:    if (!AmayaIsAlive ())           
1.80      cvs      1334:       me->reqStatus = HT_ABORT; 
1.220     cvs      1335: 
                   1336:    /* trying to protect against this problem... hard to place
                   1337:       the detection elsewhere :-/ */
1.240     cvs      1338:    /* @@ JK: Is this still needed? */
1.220     cvs      1339:    if (IsHTTP09Error (request))
                   1340:      status = -1;
                   1341: 
1.238     cvs      1342:    if (status == HT_LOADED
                   1343:        || status == HT_CREATED
                   1344:        || status == HT_NO_DATA
1.249     kahan    1345:        /* JK: removed it as the kludge doesn't seem useful anymore */
1.160     cvs      1346:        /* kludge for work around libwww problem */
1.249     kahan    1347:        /* || (status == HT_INTERRUPTED && me->method == METHOD_PUT) */
1.116     cvs      1348: #ifdef AMAYA_WWW_CACHE
                   1349:        /* what status to use to know we're downloading from a cache? */
1.238     cvs      1350:        || status ==  HT_NOT_MODIFIED
                   1351:        || status == HT_PARTIAL_CONTENT
1.116     cvs      1352: #endif /* AMAYA_WWW_CACHE */
1.238     cvs      1353:        || me->reqStatus == HT_ABORT)
1.74      cvs      1354:      error_flag = FALSE;
1.297     kirschpi 1355: #ifdef DAV
                   1356:    else if (status == HT_LOCKED 
                   1357:            || status ==  HT_FAILED_DEPENDENCY 
1.302     kirschpi 1358:            || status == HT_MULTI_STATUS) 
                   1359:     {
1.297     kirschpi 1360:      /* WebDAV return codes - they are handled in
                   1361:       * specific filters. We don't need to deal
                   1362:       * with them anymore
                   1363:       */
                   1364:      error_flag = FALSE;          
1.302     kirschpi 1365:     }
                   1366: #endif   /* DAV */
1.256     kahan    1367:    else
1.74      cvs      1368:      error_flag = TRUE;
1.130     cvs      1369: 
1.285     kahan    1370:    /* If we did a PUT that was redirected, clean the original
                   1371:       cache entry */
                   1372:    if (status == 204 && me->method == METHOD_PUT && me->put_redirection)
                   1373:    {
                   1374:      HTCache * cache;
                   1375:      HTParentAnchor * anchor = HTAnchor_parent (me->dest);
                   1376:      cache = HTCache_find (anchor, NULL);
                   1377:      if (cache)
                   1378:        {
                   1379:         /* what a problem... we update the cache with the wrong data
                   1380:            from the response... after the redirection */
                   1381:         HTCache_resetMeta (cache, request, response);
                   1382:        }
                   1383:      else
                   1384:        /* If entry doesn't already exist then create a new entry */
                   1385:        HTCache_touch(request, response, HTAnchor_parent (me->dest));
                   1386:    }
                   1387: 
1.4       cvs      1388:    /* output any errors from the server */
1.130     cvs      1389: 
1.77      cvs      1390:    /*
1.74      cvs      1391:    ** me->output = output file which will receive an html file
                   1392:    ** me->error_html = yes, output HTML errors in the screen
                   1393:    ** request->error_stack == if there are any errors, they will be here
                   1394:    ** me->error_stream_size If it's != 0 means an error message has already
                   1395:    **                       been written to the stack
                   1396:    */
                   1397:    
1.4       cvs      1398:    /* First, we verify if there are any errors and if they are not
1.17      cvs      1399:    ** yet written to the error stack. If no, then let's try to write them
                   1400:    ** ourselves
                   1401:    */
1.74      cvs      1402:    
                   1403: #ifdef DEBUG_LIBWWW
                   1404:    fprintf (stderr, "terminate_handler: URL is "
                   1405:            "%s, closing FILE %p status is %d\n", me->urlName, me->output, 
                   1406:            status); 
1.69      cvs      1407: #endif
1.74      cvs      1408:    
1.69      cvs      1409:    if (me->output && me->output != stdout)
                   1410:      {
1.214     cvs      1411:        /* we are writing to a local file */
1.74      cvs      1412:        if (me->reqStatus != HT_ABORT)
                   1413:         {                      /* if the request was not aborted and */
1.80      cvs      1414:           if (error_flag &&
                   1415:               me->error_html == TRUE)
                   1416:               /* there were some errors and we want to print them */
                   1417:             {          
1.314     kahan    1418:               /* if the transfer was interrupted, the file may not be
                   1419:                  empty. So, we erase it */
                   1420:               fflush (me->output);
                   1421:               rewind (me->output);
                   1422: 
1.80      cvs      1423:               if (me->error_stream)
                   1424:                 {      /* if the stream is non-empty */
1.313     kahan    1425:                   fprintf (me->output, "%s", me->error_stream);/* output the errors */
1.85      cvs      1426:                   /* Clear the error context, so that we can deal with
                   1427:                      this answer as if it were a normal reply */
                   1428:                    HTError_deleteAll( HTRequest_error (request));
                   1429:                    HTRequest_setError (request, NULL);
                   1430:                    error_flag = 0;
1.74      cvs      1431:                 }
                   1432:             }                  /* if error_stack */
1.85      cvs      1433:         }
1.314     kahan    1434:        
1.85      cvs      1435:        /* if != HT_ABORT */
                   1436:        
                   1437: #ifdef DEBUG_LIBWWW       
                   1438:        fprintf (stderr, "terminate_handler: URL is  %s, closing "
                   1439:                "FILE %p\n", me->urlName, me->output); 
                   1440: #endif
1.74      cvs      1441:        fclose (me->output);
                   1442:        me->output = NULL;
1.69      cvs      1443:      }
1.80      cvs      1444: 
1.214     cvs      1445:    /* a very special handling so that we can put a message box
                   1446:       to tell the user WHAT he has just done... */
                   1447:    if (UserAborted_flag && me->method == METHOD_PUT)
                   1448:      {
                   1449:        HTRequest_addError (request, ERR_FATAL, NO, HTERR_INTERRUPTED,
                   1450:                           "Operation aborted by user", 0, NULL);
                   1451:      }
                   1452: 
1.80      cvs      1453:    if (error_flag)
                   1454:      me->reqStatus = HT_ERR;
1.214     cvs      1455:    else 
                   1456:      if (me->reqStatus != HT_ABORT)
                   1457:        me->reqStatus = HT_END;
1.154     cvs      1458: 
1.238     cvs      1459:    /* copy the headers in which the application is interested */
                   1460:    HTTP_headers_set (request, response, context, status);
1.114     cvs      1461: 
1.115     cvs      1462:    /* to avoid a hangup while downloading css files */
1.140     cvs      1463:    if (AmayaAlive_flag && (me->mode & AMAYA_LOAD_CSS))
1.265     cvs      1464:      TtaSetStatus (me->docid, 1,
                   1465:                   TtaGetMessage (AMAYA, AM_ELEMENT_LOADED),
                   1466:                   me->status_urlName);
1.116     cvs      1467:    
                   1468:   /* don't remove or Xt will hang up during the PUT */
                   1469:    if (AmayaIsAlive ()  && ((me->method == METHOD_POST) ||
                   1470:                            (me->method == METHOD_PUT)))
1.7       cvs      1471:      {
1.80      cvs      1472:        PrintTerminateStatus (me, status);
                   1473:      } 
1.114     cvs      1474: 
1.111     cvs      1475:    ProcessTerminateRequest (request, response, context, status);
1.116     cvs      1476:    
1.151     cvs      1477:    /* stop here */
1.150     cvs      1478:    return HT_ERROR;
1.4       cvs      1479: }
                   1480: 
1.5       cvs      1481: /*----------------------------------------------------------------------
1.17      cvs      1482:   AHTLoadTerminate_handler
1.74      cvs      1483:   this is an application "AFTER" Callback. It's called by the library
                   1484:   when a request has ended, so that we can setup the correct status.
1.5       cvs      1485:   ----------------------------------------------------------------------*/
1.265     cvs      1486: int AHTLoadTerminate_handler (HTRequest *request, HTResponse *response,
                   1487:                              void *param, int status)
1.4       cvs      1488: {
1.116     cvs      1489:   /** @@@@ use this with printstatus ?? */
1.4       cvs      1490:    AHTReqContext      *me = HTRequest_context (request);
                   1491:    HTAlertCallback    *cbf;
                   1492:    AHTDocId_Status    *docid_status;
                   1493: 
1.7       cvs      1494:    switch (status)
1.116     cvs      1495:      {
                   1496:         case HT_LOADED:
                   1497:           if (PROT_TRACE)
                   1498:             HTTrace ("Load End.... OK: `%s\' has been accessed\n",
                   1499:                      me->status_urlName);
1.4       cvs      1500: 
1.116     cvs      1501:           docid_status = GetDocIdStatus (me->docid,
                   1502:                                          Amaya->docid_status);
1.7       cvs      1503: 
1.116     cvs      1504:           if (docid_status != NULL && docid_status->counter > 1)
                   1505:             TtaSetStatus (me->docid, 1, 
                   1506:                           TtaGetMessage (AMAYA, AM_ELEMENT_LOADED),
1.233     cvs      1507:                           me->status_urlName);
1.7       cvs      1508:               break;
1.116     cvs      1509:               
                   1510:      case HT_NO_DATA:
                   1511:        if (PROT_TRACE)
                   1512:         HTTrace ("Load End.... OK BUT NO DATA: `%s\'\n", 
                   1513:                  me->status_urlName);
1.297     kirschpi 1514: #ifdef DAV      
1.302     kirschpi 1515:        if (me->method==METHOD_UNLOCK) 
                   1516:         {
                   1517:            /* MKP: set an appropriate status message */
1.297     kirschpi 1518:           TtaSetStatus (me->docid, 1, 
                   1519:                     TtaGetMessage (AMAYA, AM_UNLOCK_SUCCEED),
                   1520:                     NULL);
1.302     kirschpi 1521:         }
1.297     kirschpi 1522:        else
1.302     kirschpi 1523: #endif /* DAV */
1.297     kirschpi 1524:            TtaSetStatus (me->docid, 1, 
1.116     cvs      1525:                     TtaGetMessage (AMAYA, AM_LOADED_NO_DATA),
1.233     cvs      1526:                     me->status_urlName);
1.116     cvs      1527:        break;
                   1528:        
                   1529:      case HT_INTERRUPTED:
                   1530:        if (PROT_TRACE)
                   1531:         HTTrace ("Load End.... INTERRUPTED: `%s\'\n", 
                   1532:                  me->status_urlName);
                   1533:        TtaSetStatus (me->docid, 1, 
                   1534:                     TtaGetMessage (AMAYA, AM_LOAD_ABORT), 
                   1535:                     NULL);
                   1536:        break;
1.7       cvs      1537: 
1.116     cvs      1538:      case HT_RETRY:
                   1539:        if (PROT_TRACE)
                   1540:         HTTrace ("Load End.... NOT AVAILABLE, RETRY AT %ld\n",
                   1541:                  HTResponse_retryTime (response));
                   1542:        TtaSetStatus (me->docid, 1, 
                   1543:                     TtaGetMessage (AMAYA, AM_NOT_AVAILABLE_RETRY),
1.233     cvs      1544:                     me->status_urlName);
1.116     cvs      1545:        break;
1.7       cvs      1546: 
1.247     kahan    1547:      case HT_NOT_MODIFIED:
                   1548:        if (PROT_TRACE)
1.265     cvs      1549:         HTTrace ("Load End.... NOT MODIFIED (%s)",
                   1550:                  me->status_urlName ? me->status_urlName :" <UNKNOWN>");
1.247     kahan    1551:        break;
                   1552:        
1.116     cvs      1553:      case HT_ERROR:
                   1554:        cbf = HTAlert_find (HT_A_MESSAGE);
                   1555:        if (cbf)
                   1556:         (*cbf) (request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
                   1557:                 HTRequest_error (request), NULL);
1.247     kahan    1558:        if (PROT_TRACE)
1.265     cvs      1559:            HTTrace ("Load End.... ERROR: Can't access `%s\'\n",
                   1560:                    me->status_urlName ? me->status_urlName :"<UNKNOWN>"); 
                   1561:        TtaSetStatus (me->docid, 1,
                   1562:                     TtaGetMessage (AMAYA, AM_CANNOT_LOAD),
                   1563:                     me->status_urlName ? me->status_urlName : "<UNKNOWN>");
1.116     cvs      1564:        break;
1.247     kahan    1565: 
                   1566:      case HTERR_TIMEOUT:
                   1567:        cbf = HTAlert_find (HT_A_MESSAGE);
                   1568:        if (cbf)
                   1569:         (*cbf) (request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
                   1570:                 HTRequest_error (request), NULL);
1.116     cvs      1571:        if (PROT_TRACE)
1.265     cvs      1572:            HTTrace ("Load End.... REQUEST TIMEOUT: Can't access `%s\'\n",
                   1573:                    me->status_urlName ? me->status_urlName :"<UNKNOWN>"); 
                   1574:        TtaSetStatus (me->docid, 1, TtaGetMessage (AMAYA, AM_CANNOT_LOAD),
                   1575:                     me->status_urlName ? me->status_urlName : "<UNKNOWN>");
1.116     cvs      1576:        break;
1.247     kahan    1577: 
1.116     cvs      1578:      default:
                   1579:        if (PROT_TRACE)
                   1580:         HTTrace ("Load End.... UNKNOWN RETURN CODE %d\n", status);
                   1581:        break;
                   1582:      }
                   1583:    
                   1584:    return HT_OK;
                   1585: }
1.7       cvs      1586: 
1.248     kahan    1587: /*----------------------------------------------------------------------
                   1588:   LineTrace
                   1589:   Makes a file copy of libwww's traces
                   1590:   ----------------------------------------------------------------------*/
1.116     cvs      1591: static  int LineTrace (const char * fmt, va_list pArgs)
                   1592: {
1.248     kahan    1593:   vfprintf (trace_fp, fmt, pArgs);
                   1594:   return (fflush (trace_fp));
1.4       cvs      1595: }
                   1596: 
1.27      cvs      1597: /*----------------------------------------------------------------------
                   1598:   AHTAcceptTypesInit
1.74      cvs      1599:   This function prepares the Accept header used by Amaya during
                   1600:   the HTTP content negotiation phase
1.27      cvs      1601:   ----------------------------------------------------------------------*/
                   1602: static void           AHTAcceptTypesInit (HTList *c)
                   1603: {
1.223     cvs      1604:    if (c == (HTList *) NULL) 
1.27      cvs      1605:       return;
                   1606: 
1.223     cvs      1607:    /* define here all the mime types that Amaya can accept */
1.27      cvs      1608: 
1.223     cvs      1609:    HTConversion_add (c, "image/png",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1610:    HTConversion_add (c, "image/jpeg", "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1611:    HTConversion_add (c, "image/gif",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1612:    HTConversion_add (c, "image/xbm",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1613:    HTConversion_add (c, "image/xpm",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
1.183     cvs      1614: 
1.27      cvs      1615:    /* Define here the equivalences between MIME types and file extensions for
1.223     cvs      1616:       the types that Amaya can display */
1.27      cvs      1617: 
1.176     cvs      1618:    /* Initialize suffix bindings for local files */
                   1619:    HTBind_init();
                   1620: 
1.27      cvs      1621:    /* Register the default set of file suffix bindings */
                   1622:    HTFileInit ();
                   1623: 
1.257     kahan    1624:    /* Register additional bindings */
1.276     kahan    1625:    HTBind_add("htm", "text/html",  NULL, "8bit", NULL, 1.0);
1.257     kahan    1626:    HTBind_add("tgz", "application/gnutar",  NULL, "binary", NULL, 1.0);
1.293     kahan    1627:    HTBind_add("mml", AM_MATHML_MIME_TYPE,  NULL, "8bit", NULL, 1.0);
                   1628:    HTBind_add("svg", AM_SVG_MIME_TYPE,  NULL, "8bit", NULL, 1.0);
1.260     kahan    1629:    HTBind_add("xsl", "text/xml",  NULL, "8bit", NULL, 1.0);
1.27      cvs      1630:    /* Don't do any case distinction */
                   1631:    HTBind_caseSensitive (FALSE);
                   1632: }
1.4       cvs      1633: 
1.5       cvs      1634: /*----------------------------------------------------------------------
1.193     cvs      1635:   AHTAcceptLanguagesInit
                   1636:   This function prepares the Accept header used by Amaya during
                   1637:   the HTTP content negotiation phase
                   1638:   ----------------------------------------------------------------------*/
1.196     cvs      1639: static void         AHTAcceptLanguagesInit (HTList *c)
1.193     cvs      1640: {
1.265     cvs      1641:   char             *ptr;
                   1642:   char             *lang_list;
1.223     cvs      1643:   char              s[3];
1.196     cvs      1644:   int               count, lg;
                   1645:   double            quality;
                   1646:   ThotBool          still;
1.193     cvs      1647: 
                   1648:   if (c == (HTList *) NULL) 
1.265     cvs      1649:     return;
1.193     cvs      1650:   
1.203     cvs      1651:   lang_list = TtaGetEnvString ("ACCEPT_LANGUAGES");
1.197     cvs      1652:   s[2] = EOS;
1.272     cvs      1653:   if (lang_list && *lang_list != EOS)
1.193     cvs      1654:     {
                   1655:       /* add the default language first  */
                   1656:       HTLanguage_add (c, "*", -1.0);
                   1657:       /* how many languages do we have? */
1.196     cvs      1658:       ptr = lang_list;
                   1659:       count = 0;
1.272     cvs      1660:       while (*ptr != EOS)
1.265     cvs      1661:        {
1.272     cvs      1662:          while (*ptr != EOS &&
1.265     cvs      1663:                 (*ptr < 'A' || (*ptr > 'Z' && *ptr < 'a') || *ptr > 'z'))
                   1664:            /* skip the whole separator */
                   1665:            ptr++;
                   1666:          lg = 0;
                   1667:          while ((*ptr >= 'A' &&
                   1668:                  *ptr <= 'Z') || (*ptr >= 'a' && *ptr <= 'z') || *ptr == '-')
                   1669:            {
                   1670:              /* it's a new language */
                   1671:              ptr++;
                   1672:              lg++;
                   1673:            }
                   1674:          if (lg >= 2)
                   1675:            count++;
1.272     cvs      1676:          if (*ptr != EOS)
1.265     cvs      1677:            ptr++;
                   1678:        }
1.193     cvs      1679: 
1.196     cvs      1680:       if (count > 0)
1.265     cvs      1681:        quality = 1.1 - (double) count/10.0;
1.193     cvs      1682:       else
1.265     cvs      1683:        quality = 1.0;
1.193     cvs      1684: 
1.265     cvs      1685:       /* Read the languages from the registry, then inject them one, by one.
                   1686:         The first one is the one with the highest priority.
                   1687:         The libwww ask for the lowest priority first.
1.196     cvs      1688:       */
                   1689:       ptr--;
                   1690:       still = TRUE;
1.265     cvs      1691:       while (count)
                   1692:        {
                   1693:          while (still && (*ptr < 'A' || (*ptr > 'Z' && *ptr < 'a') || *ptr > 'z'))
                   1694:            /* skip the whole separator */
                   1695:            if (ptr > lang_list)
                   1696:              ptr--;
                   1697:            else
                   1698:              still = FALSE;
                   1699:          lg = 0;
                   1700:          while (still &&
                   1701:                 ((*ptr >= 'A' &&
                   1702:                   *ptr <= 'Z') || (*ptr >= 'a' && *ptr <= 'z') || *ptr == '-'))
                   1703:            {
                   1704:              /* it's a new language */
                   1705:              if (ptr > lang_list)
                   1706:                ptr--;
                   1707:              else
                   1708:                still = FALSE;
                   1709:              lg++;
                   1710:            }
                   1711:          if (lg >= 2)
                   1712:            {
                   1713:              if (still)
                   1714:                strncpy  (s, &ptr[1], 2);
                   1715:              else
                   1716:                strncpy (s, lang_list, 2);
                   1717:              count--;
                   1718:              HTLanguage_add (c, s, quality);
                   1719:              quality += 0.1;
                   1720:            }
                   1721:          ptr--;
                   1722:        }
                   1723:     }
1.193     cvs      1724: }
                   1725: 
                   1726: /*----------------------------------------------------------------------
1.17      cvs      1727:   AHTConverterInit
                   1728:   Bindings between a source media type and a destination media type
                   1729:   (conversion).
1.5       cvs      1730:   ----------------------------------------------------------------------*/
1.15      cvs      1731: static void         AHTConverterInit (HTList *c)
1.4       cvs      1732: {
                   1733:    /* Handler for custom http error messages */
1.7       cvs      1734:    HTConversion_add (c, "*/*", "www/debug", AHTMemConverter, 1.0, 0.0, 0.0);
1.4       cvs      1735: 
                   1736:    /*
                   1737:     ** These are converters that converts to something other than www/present,
                   1738:     ** that is not directly outputting someting to the user on the screen
                   1739:     */
                   1740: 
1.223     cvs      1741:    HTConversion_add (c, "message/rfc822", "*/*", HTMIMEConvert, 1.0, 0.0, 0.0);
                   1742:    HTConversion_add (c, "message/x-rfc822-foot", "*/*", HTMIMEFooter, 1.0, 0.0, 0.0);
                   1743:    HTConversion_add (c, "message/x-rfc822-head", "*/*", HTMIMEHeader, 1.0, 0.0, 0.0);
                   1744:    HTConversion_add(c,"message/x-rfc822-cont", "*/*", HTMIMEContinue, 1.0, 0.0, 0.0);
                   1745:    HTConversion_add(c,"message/x-rfc822-partial","*/*",        HTMIMEPartial, 1.0, 0.0, 0.0);
                   1746:    HTConversion_add (c, "multipart/*", "*/*", HTBoundary, 1.0, 0.0, 0.0);
                   1747:    HTConversion_add (c, "text/plain", "text/html", HTPlainToHTML, 1.0, 0.0, 0.0);
1.4       cvs      1748: 
                   1749:    /*
1.116     cvs      1750:    ** The following conversions are converting ASCII output from various
                   1751:    ** protocols to HTML objects.
                   1752:    */
1.223     cvs      1753:    HTConversion_add (c, "text/x-http", "*/*", HTTPStatus_new, 1.0, 0.0, 0.0);
1.4       cvs      1754: 
                   1755:    /*
1.116     cvs      1756:    ** We also register a special content type guess stream that can figure out
                   1757:    ** the content type by reading the first bytes of the stream
                   1758:    */
1.223     cvs      1759:    HTConversion_add (c, "www/unknown", "*/*", HTGuess_new, 1.0, 0.0, 0.0);
1.4       cvs      1760: 
1.116     cvs      1761: #ifdef AMAYA_WWW_CACHE
1.4       cvs      1762:    /*
1.116     cvs      1763:    ** Register a persistent cache stream which can save an object to local
                   1764:    ** file
                   1765:    */
1.223     cvs      1766:    HTConversion_add (c, "www/cache", "*/*", HTCacheWriter, 1.0, 0.0, 0.0);
                   1767:    HTConversion_add(c,"www/cache-append", "*/*", HTCacheAppend, 1.0, 0.0, 0.0);
1.306     cheyroul 1768: #endif /*AMAYA_WWW_CACHE*/
1.4       cvs      1769: 
                   1770:    /*
1.116     cvs      1771:    ** This dumps all other formats to local disk without any further
                   1772:    ** action taken
                   1773:    */
1.223     cvs      1774:    HTConversion_add (c, "*/*", "www/present", HTSaveLocally, 0.3, 0.0, 0.0);  
1.4       cvs      1775: }
                   1776: 
1.27      cvs      1777: 
1.15      cvs      1778: /*----------------------------------------------------------------------
1.17      cvs      1779:   AHTProtocolInit
                   1780:   Registers all amaya supported protocols.
1.15      cvs      1781:   ----------------------------------------------------------------------*/
1.4       cvs      1782: static void         AHTProtocolInit (void)
                   1783: {
1.265     cvs      1784:   char *strptr;
1.4       cvs      1785: 
1.116     cvs      1786:   /* 
                   1787:      NB. Preemptive == YES means Blocking requests
                   1788:      Non-preemptive == NO means Non-blocking requests
                   1789:      */
                   1790:   HTTransport_add("tcp", HT_TP_SINGLE, HTReader_new, HTWriter_new);
                   1791:   HTTransport_add("buffered_tcp", HT_TP_SINGLE, HTReader_new, 
                   1792:                  HTBufferWriter_new);
                   1793:   HTProtocol_add ("http", "buffered_tcp", HTTP_PORT, NO, HTLoadHTTP, NULL);
1.136     cvs      1794: #ifdef _WINDOWS
                   1795:   HTProtocol_add ("file", "local", 0, YES, HTLoadFile, NULL);
                   1796: #else
1.116     cvs      1797:   HTProtocol_add ("file", "local", 0, NO, HTLoadFile, NULL);
1.198     cvs      1798: #endif /* _WINDOWS */
1.116     cvs      1799: #ifdef AMAYA_WWW_CACHE
                   1800:    HTProtocol_add("cache",  "local", 0, YES, HTLoadCache, NULL);
                   1801: #endif /* AMAYA_WWW_CACHE */
1.103     cvs      1802: #if 0 /* experimental code */
1.245     kahan    1803: #endif
1.116     cvs      1804:    HTProtocol_add ("ftp", "tcp", FTP_PORT, NO, HTLoadFTP, NULL);
1.245     kahan    1805: 
1.116     cvs      1806: 
                   1807:    /* initialize pipelining */
1.223     cvs      1808:   strptr = TtaGetEnvString ("ENABLE_PIPELINING");
1.265     cvs      1809:   if (strptr && *strptr && strcasecmp (strptr, "yes"))
1.116     cvs      1810:     HTTP_setConnectionMode (HTTP_11_NO_PIPELINING);
1.4       cvs      1811: }
                   1812: 
1.15      cvs      1813: /*----------------------------------------------------------------------
1.17      cvs      1814:   AHTNetInit
                   1815:   Reegisters "before" and "after" request filters.
1.15      cvs      1816:   ----------------------------------------------------------------------*/
1.4       cvs      1817: static void         AHTNetInit (void)
                   1818: {
                   1819: 
                   1820: /*      Register BEFORE filters
1.74      cvs      1821: **      The BEFORE filters handle proxies, caches, rule files etc.
                   1822: **      The filters are called in the order by which the are registered
                   1823: **      Not done automaticly - may be done by application!
                   1824: */
1.4       cvs      1825: 
1.116     cvs      1826:   HTNet_addBefore (HTCredentialsFilter, "http://*", NULL, HT_FILTER_LATE);
                   1827:   HTNet_addBefore (HTProxyFilter, NULL, NULL, HT_FILTER_LATE);
1.85      cvs      1828:   HTHost_setActivateRequestCallback (AHTOpen_file);
1.4       cvs      1829: 
                   1830: /*      register AFTER filters
1.74      cvs      1831: **      The AFTER filters handle error messages, logging, redirection,
                   1832: **      authentication etc.
                   1833: **      The filters are called in the order by which the are registered
                   1834: **      Not done automaticly - may be done by application!
                   1835: */
1.4       cvs      1836: 
1.223     cvs      1837:   HTNet_addAfter (HTAuthFilter, "http://*", NULL, HT_NO_ACCESS, HT_FILTER_MIDDLE);
                   1838:   HTNet_addAfter (HTAuthFilter, "http://*", NULL, HT_REAUTH, HT_FILTER_MIDDLE);
                   1839:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_PERM_REDIRECT, HT_FILTER_MIDDLE);
                   1840:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_FOUND, HT_FILTER_MIDDLE);
                   1841:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_SEE_OTHER, HT_FILTER_MIDDLE);
                   1842:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_TEMP_REDIRECT, HT_FILTER_MIDDLE);
                   1843:   HTNet_addAfter (HTAuthInfoFilter,    "http://*", NULL, HT_ALL, HT_FILTER_MIDDLE);
                   1844:   HTNet_addAfter (HTUseProxyFilter, "http://*", NULL, HT_USE_PROXY, HT_FILTER_MIDDLE);
1.151     cvs      1845: #ifdef AMAYA_LOST_UPDATE
1.223     cvs      1846:   HTNet_addAfter (precondition_handler, NULL, NULL, HT_PRECONDITION_FAILED, HT_FILTER_MIDDLE);
1.151     cvs      1847: #endif /* AMAYA_LOST_UPDATE */
1.111     cvs      1848: #ifndef _WINDOWS
1.223     cvs      1849:   HTNet_addAfter (AHTLoadTerminate_handler, NULL, NULL, HT_ALL, HT_FILTER_LAST);       
1.111     cvs      1850: #endif /* !_WINDOWS */
1.116     cvs      1851:    /**** for later ?? ****/
                   1852:    /*  HTNet_addAfter(HTInfoFilter,    NULL,           NULL, HT_ALL,           HT_FILTER_LATE); */
1.245     kahan    1853:   /* @@ JK: Filters for doing ftp authentication */
                   1854:   HTNet_addAfter (HTAuthFilter, "ftp://*", NULL, HT_NO_ACCESS, HT_FILTER_MIDDLE);
                   1855:   HTNet_addAfter (HTAuthFilter, "ftp://*", NULL, HT_REAUTH, HT_FILTER_MIDDLE);
1.51      cvs      1856:    /* handles all errors */
1.116     cvs      1857:   HTNet_addAfter (terminate_handler, NULL, NULL, HT_ALL, HT_FILTER_LAST);
1.4       cvs      1858: }
                   1859: 
1.15      cvs      1860: /*----------------------------------------------------------------------
1.17      cvs      1861:   AHTAlertInit
                   1862:   Register alert messages and their callbacks.
1.15      cvs      1863:   ----------------------------------------------------------------------*/
                   1864: static void         AHTAlertInit (void)
                   1865: {
                   1866:    HTAlert_add (AHTProgress, HT_A_PROGRESS);
1.120     cvs      1867: #ifdef __WINDOWS
1.70      cvs      1868:    HTAlert_add ((HTAlertCallback *) WIN_Activate_Request, HT_PROG_CONNECT);
1.116     cvs      1869: #endif /* _WINDOWS */
1.15      cvs      1870:    HTAlert_add (AHTError_print, HT_A_MESSAGE);
1.48      cvs      1871:    HTError_setShow (~((unsigned int) 0 ) & ~((unsigned int) HT_ERR_SHOW_DEBUG));       /* process all messages except debug ones*/
1.15      cvs      1872:    HTAlert_add (AHTConfirm, HT_A_CONFIRM);
                   1873:    HTAlert_add (AHTPrompt, HT_A_PROMPT);
                   1874:    HTAlert_add (AHTPromptUsernameAndPassword, HT_A_USER_PW);
1.116     cvs      1875: }
                   1876: 
1.118     cvs      1877: #ifdef AMAYA_WWW_CACHE
                   1878: /*----------------------------------------------------------------------
1.128     cvs      1879:   RecCleanCache
1.118     cvs      1880:   Clears an existing cache directory
                   1881:   ----------------------------------------------------------------------*/
1.265     cvs      1882: static void RecCleanCache (char *dirname)
                   1883: {
1.128     cvs      1884: #ifdef _WINDOWS
1.223     cvs      1885:   HANDLE          hFindFile;
                   1886:   ThotBool        status;
1.128     cvs      1887:   WIN32_FIND_DATA ffd;
1.290     vatton   1888:   char            t_dir [MAX_LENGTH];
                   1889:   char           *ptr;
1.128     cvs      1890: 
1.130     cvs      1891:   /* create a t_dir name to start searching for files */
1.265     cvs      1892:   if ((strlen (dirname) + 10) > MAX_LENGTH)
1.128     cvs      1893:     /* ERROR: directory name is too big */
                   1894:     return;
                   1895: 
1.265     cvs      1896:   strcpy (t_dir, dirname);
1.130     cvs      1897:   /* save the end of the dirname. We'll use it to make
                   1898:      a complete pathname when erasing files */
1.265     cvs      1899:   ptr = &t_dir[strlen (t_dir)];
                   1900:   strcat (t_dir, "*");
1.128     cvs      1901: 
1.130     cvs      1902:   hFindFile = FindFirstFile (t_dir, &ffd);
1.128     cvs      1903:     
                   1904:   if (hFindFile == INVALID_HANDLE_VALUE)
                   1905:     /* nothing to erase? */
                   1906:     return;
                   1907: 
                   1908:   status = TRUE;
1.130     cvs      1909:   while (status) 
                   1910:     {
                   1911:       if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1.133     cvs      1912:        {
                   1913:          /* it's a directory, erase it recursively */
1.265     cvs      1914:          if (strcmp (ffd.cFileName, "..") && strcmp (ffd.cFileName, "."))
1.133     cvs      1915:            {
1.265     cvs      1916:              strcpy (ptr, ffd.cFileName);
1.272     cvs      1917:              strcat (ptr, DIR_STR);
1.133     cvs      1918:              RecCleanCache (t_dir);
1.274     cvs      1919:              rmdir (t_dir);
1.133     cvs      1920:            }
                   1921:        }
                   1922:        else
1.130     cvs      1923:          {
1.133     cvs      1924:            /* it's a file, erase it */
1.265     cvs      1925:            strcpy (ptr, ffd.cFileName);
1.133     cvs      1926:            TtaFileUnlink (t_dir);
1.130     cvs      1927:          }
                   1928:       status = FindNextFile (hFindFile, &ffd);
                   1929:     }
1.128     cvs      1930:   FindClose (hFindFile);
                   1931: 
                   1932: #else /* _WINDOWS */
1.118     cvs      1933:   DIR *dp;
                   1934:   struct stat st;
                   1935: #ifdef HAVE_DIRENT_H
                   1936:   struct dirent *d;
                   1937: #else
                   1938:   struct direct *d;
                   1939: #endif /* HAVE_DIRENT_H */
1.128     cvs      1940:   char filename[BUFSIZ+1];
1.118     cvs      1941: 
                   1942:   if ((dp = opendir (dirname)) == NULL) 
                   1943:     {
                   1944:       /* @@@ we couldn't open the directory ... we need some msg */
                   1945:       perror (dirname);
1.176     cvs      1946:       return;
1.118     cvs      1947:     }
                   1948:   
                   1949:   while ((d = readdir (dp)) != NULL)
                   1950:     {
                   1951:       /* skip the UNIX . and .. links */
                   1952:       if (!strcmp (d->d_name, "..")
                   1953:          || !strcmp (d->d_name, "."))
                   1954:        continue;
                   1955: 
1.188     cvs      1956:       sprintf (filename, "%s%c%s", dirname, DIR_SEP, d->d_name);
1.118     cvs      1957:       if  (lstat (filename, &st) < 0 ) 
                   1958:        {
                   1959:          /* @@2 need some error message */
                   1960:          perror (filename);
                   1961:          continue;
                   1962:        }
                   1963:       
                   1964:       switch (st.st_mode & S_IFMT)
                   1965:        {
                   1966:        case S_IFDIR:
                   1967:          /* if we find a directory, we erase it, recursively */
1.128     cvs      1968:          strcat (filename, DIR_STR);
                   1969:          RecCleanCache (filename);
                   1970:          rmdir (filename);
1.118     cvs      1971:          break;
                   1972:        case S_IFLNK:
                   1973:          /* skip any links we find */
                   1974:          continue;
                   1975:          break;
                   1976:        default:
                   1977:          /* erase the filename */
                   1978:          TtaFileUnlink (filename);
                   1979:          break;
                   1980:        }
                   1981:     }
                   1982:   closedir (dp);
1.265     cvs      1983: #endif /* _WINDOWS */
1.118     cvs      1984: }
                   1985: #endif /* AMAYA_WWW_CACHE */
                   1986: 
1.116     cvs      1987: /*----------------------------------------------------------------------
1.265     cvs      1988:   libwww_CleanCache
                   1989:   frontend to the recursive cache cleaning function
                   1990:   ----------------------------------------------------------------------*/
                   1991: void libwww_CleanCache (void)
                   1992: {
                   1993: #ifdef AMAYA_WWW_CACHE
                   1994:   char * real_dir;
                   1995:   char*    cache_dir;
                   1996:   char*    tmp;
                   1997:   int      cache_size;
                   1998:   int      cache_expire;
                   1999:   int      cache_disconnect;
                   2000:   ThotBool error;
                   2001:   char * ptr;
                   2002: 
                   2003:   if (!HTCacheMode_enabled ())
                   2004:     /* don't do anything if we're not using a cache */
                   2005:     return;
                   2006:   /* temporarily close down the cache, purge it, then restart */
                   2007:   tmp = HTCacheMode_getRoot ();
                   2008:   /* don't do anything if we don't have a valid cache dir */
                   2009:   if (!tmp || *tmp == EOS)
                   2010:          return;
                   2011:   cache_dir = TtaStrdup (tmp);
                   2012:   HT_FREE (tmp);
                   2013:   cache_size = HTCacheMode_maxSize ();
                   2014:   cache_expire = HTCacheMode_expires ();
                   2015:   cache_disconnect = HTCacheMode_disconnected ();
                   2016: 
                   2017:   /* get something we can work on :) */
                   2018:   tmp = HTWWWToLocal (cache_dir, "file:", NULL);
                   2019:   real_dir = TtaGetMemory (strlen (tmp) + 20);
1.273     cvs      2020:   strcpy (real_dir, tmp);
1.265     cvs      2021:   HT_FREE (tmp);
                   2022: 
                   2023:   /* safeguard... abort the operation if cache_dir doesn't end with
                   2024:      CACHE_DIR_NAME */
                   2025:   error = TRUE;
                   2026:   ptr = strstr (real_dir, CACHE_DIR_NAME);  
                   2027:     if (ptr && *ptr && !strcasecmp (ptr, CACHE_DIR_NAME))
                   2028:       error = FALSE;
                   2029:   if (error)
                   2030:     return;  
                   2031:   
                   2032:   /* remove the concurrent cache lock */
                   2033: #ifdef DEBUG_LIBWWW
                   2034:   fprintf (stderr, "Clearing the cache lock\n");
                   2035: #endif /* DEBUG_LIBWWW */
                   2036:   clear_cachelock ();
                   2037:   HTCacheTerminate ();
                   2038:   HTCacheMode_setEnabled (FALSE);
                   2039:   
                   2040:   RecCleanCache (real_dir);
                   2041: 
                   2042:   HTCacheMode_setExpires (cache_expire);
                   2043:   HTCacheMode_setDisconnected (cache_disconnect);
                   2044:   HTCacheInit (cache_dir, cache_size);
                   2045:   /* set a new concurrent cache lock */
                   2046:   strcat (real_dir, ".lock");
                   2047:   if (set_cachelock (real_dir) == -1)
                   2048:     /* couldn't open the .lock file, so, we close the cache to
                   2049:        be in the safe side */
                   2050:     {
                   2051: #ifdef DEBUG_LIBWWW
                   2052:       fprintf (stderr, "couldnt set the cache lock\n");
                   2053: #endif /* DEBUG_LIBWWW */
                   2054:       HTCacheTerminate ();
                   2055:       HTCacheMode_setEnabled (FALSE);
                   2056:     }
                   2057: #ifdef DEBUG_LIBWWW
                   2058:   fprintf (stderr, "set a cache lock\n");
                   2059: #endif /* DEBUG_LIBWWW */
                   2060:   TtaFreeMemory (real_dir);
                   2061:   TtaFreeMemory (cache_dir);
                   2062: #endif /* AMAYA_WWW_CACHE */
                   2063: }
                   2064: 
                   2065: /*----------------------------------------------------------------------
1.116     cvs      2066:   CacheInit
                   2067:   Reads the cache settings from the thot.ini file.
                   2068:   ----------------------------------------------------------------------*/
                   2069: static void CacheInit (void)
                   2070: {
                   2071: #ifndef AMAYA_WWW_CACHE
                   2072:    HTCacheMode_setEnabled (NO);
                   2073: 
                   2074: #else /* AMAYA_WWW_CACHE */
1.265     cvs      2075:   char     *strptr;
                   2076:   char     *real_dir = NULL;
                   2077:   char     *cache_lockfile;
                   2078:   char     *cache_dir = NULL;
1.223     cvs      2079:   int       cache_size;
                   2080:   int       cache_entry_size;
                   2081:   ThotBool  cache_enabled;
                   2082:   ThotBool  cache_locked;
                   2083:   ThotBool  tmp_bool;
1.130     cvs      2084: 
1.185     cvs      2085: int i;
                   2086: 
1.116     cvs      2087:   /* activate cache? */
1.203     cvs      2088:   strptr = TtaGetEnvString ("ENABLE_CACHE");
1.265     cvs      2089:   if (strptr && *strptr && strcasecmp (strptr, "yes"))
1.130     cvs      2090:     cache_enabled = NO;
1.116     cvs      2091:   else
1.130     cvs      2092:     cache_enabled = YES;
1.116     cvs      2093: 
1.151     cvs      2094:   /* cache protected documents? */
1.203     cvs      2095:   strptr = TtaGetEnvString ("CACHE_PROTECTED_DOCS");
1.265     cvs      2096:   if (strptr && *strptr && !strcasecmp (strptr, "yes"))
1.151     cvs      2097:     HTCacheMode_setProtected (YES);
                   2098:   else
                   2099:     HTCacheMode_setProtected (NO);
                   2100: 
1.116     cvs      2101:   /* get the cache dir (or use a default one) */
1.203     cvs      2102:   strptr = TtaGetEnvString ("CACHE_DIR");
1.116     cvs      2103:   if (strptr && *strptr) 
                   2104:     {
1.265     cvs      2105:       real_dir = TtaGetMemory (strlen (strptr) + strlen (CACHE_DIR_NAME) + 20);
                   2106:       strcpy (real_dir, strptr);
1.272     cvs      2107:       if (*(real_dir + strlen (real_dir) - 1) != DIR_SEP)
                   2108:        strcat (real_dir, DIR_STR);
1.116     cvs      2109:     }
                   2110:   else
                   2111:     {
1.265     cvs      2112:       real_dir = TtaGetMemory (strlen (TempFileDirectory) + strlen (CACHE_DIR_NAME) + 20);
1.272     cvs      2113:       sprintf (real_dir, "%s%s", TempFileDirectory, CACHE_DIR_NAME);
1.185     cvs      2114:     }
                   2115: 
                   2116:   /* compatiblity with previous versions of Amaya: does real_dir
                   2117:      include CACHE_DIR_NAME? If not, add it */
1.265     cvs      2118:   strptr = strstr (real_dir, CACHE_DIR_NAME);
1.185     cvs      2119:   if (!strptr)
1.265     cvs      2120:     strcat (real_dir, CACHE_DIR_NAME);
1.185     cvs      2121:   else
                   2122:     {
1.265     cvs      2123:       i = strlen (CACHE_DIR_NAME);
1.272     cvs      2124:          if (strptr[i] != EOS)
1.265     cvs      2125:           strcat (real_dir, CACHE_DIR_NAME);
1.116     cvs      2126:     }
1.185     cvs      2127: 
1.211     cvs      2128:   /* convert the local cache dir into a file URL, as expected by
                   2129:      libwww */
1.265     cvs      2130:   cache_dir = HTLocalToWWW (real_dir, "file:");
1.116     cvs      2131:   /* get the cache size (or use a default one) */
1.203     cvs      2132:   strptr = TtaGetEnvString ("CACHE_SIZE");
1.116     cvs      2133:   if (strptr && *strptr) 
1.288     vatton   2134:     cache_size = atoi (strptr);
1.116     cvs      2135:   else
                   2136:     cache_size = DEFAULT_CACHE_SIZE;
1.176     cvs      2137:   /* get the max cached file size (or use a default one) */
1.223     cvs      2138:   if (!TtaGetEnvInt ("MAX_CACHE_ENTRY_SIZE", &cache_entry_size))
1.176     cvs      2139:     cache_entry_size = DEFAULT_MAX_CACHE_ENTRY_SIZE;
1.130     cvs      2140:   if (cache_enabled) 
1.116     cvs      2141:     {
                   2142:       /* how to remove the lock? force remove it? */
1.265     cvs      2143:       cache_lockfile = TtaGetMemory (strlen (real_dir) + 20);
                   2144:       strcpy (cache_lockfile, real_dir);
                   2145:       strcat (cache_lockfile, ".lock");
1.130     cvs      2146:       cache_locked = FALSE;
1.223     cvs      2147:       if (TtaFileExist (cache_lockfile) && !(cache_locked = test_cachelock (cache_lockfile)))
1.116     cvs      2148:        {
1.130     cvs      2149: #ifdef DEBUG_LIBWWW
                   2150:          fprintf (stderr, "found a stale cache, removing it\n");
                   2151: #endif /* DEBUG_LIBWWW */
                   2152:          /* remove the lock and clean the cache (the clean cache 
                   2153:             will remove all, making the following call unnecessary */
                   2154:          /* little trick to win some memory */
1.265     cvs      2155:          strptr = strrchr (cache_lockfile, '.');
1.272     cvs      2156:          *strptr = EOS;
1.130     cvs      2157:          RecCleanCache (cache_lockfile);
1.265     cvs      2158:          *strptr = '.';
1.116     cvs      2159:        }
                   2160: 
1.130     cvs      2161:       if (!cache_locked) 
                   2162:        {
                   2163:          /* initialize the cache if there's no other amaya
                   2164:             instance running */
1.177     cvs      2165:          HTCacheMode_setMaxCacheEntrySize (cache_entry_size);
1.223     cvs      2166:          if (TtaGetEnvBoolean ("CACHE_EXPIRE_IGNORE", &tmp_bool) && tmp_bool)
1.177     cvs      2167:            HTCacheMode_setExpires (HT_EXPIRES_IGNORE);
                   2168:          else
                   2169:            HTCacheMode_setExpires (HT_EXPIRES_AUTO);
1.223     cvs      2170:          TtaGetEnvBoolean ("CACHE_DISCONNECTED_MODE", &tmp_bool);
1.177     cvs      2171:          if (tmp_bool)
                   2172:            HTCacheMode_setDisconnected (HT_DISCONNECT_NORMAL);
                   2173:          else
                   2174:            HTCacheMode_setDisconnected (HT_DISCONNECT_NONE);
1.211     cvs      2175:          if (HTCacheInit (cache_dir, cache_size))
1.130     cvs      2176:            {
1.188     cvs      2177:              if (set_cachelock (cache_lockfile) == -1)
                   2178:                /* couldn't open the .lock file, so, we close the cache to
                   2179:                   be in the safe side */
                   2180:                {
                   2181:                  HTCacheTerminate ();
                   2182:                  HTCacheMode_setEnabled (FALSE);
                   2183: #ifdef DEBUG_LIBWWW
                   2184:                  fprintf (stderr, "couldnt set the cache lock\n");
                   2185: #endif /* DEBUG_LIBWWW */
                   2186:                }
1.130     cvs      2187: #ifdef DEBUG_LIBWWW
1.188     cvs      2188:              else
                   2189:                fprintf (stderr, "created the cache lock\n");
1.130     cvs      2190: #endif /* DEBUG_LIBWWW */
                   2191:            }
1.188     cvs      2192:          else
                   2193:            {
1.130     cvs      2194: #ifdef DEBUG_LIBWWW
1.188     cvs      2195:              fprintf (stderr, "couldn't create the cache\n");
                   2196: #endif /* DEBUG_LIBWWW */            
                   2197:              HTCacheTerminate ();
                   2198:            }
1.130     cvs      2199:        }
                   2200:       else 
                   2201:        {
1.185     cvs      2202:          HTCacheMode_setEnabled (FALSE);
1.130     cvs      2203: #ifdef DEBUG_LIBWWW
                   2204:          fprintf (stderr, "lock detected, starting libwww without a cache/n");
                   2205: #endif /* DEBUG_LIBWWW */
                   2206:        }
                   2207:       TtaFreeMemory (cache_lockfile);
1.116     cvs      2208:     }
                   2209:   else
1.185     cvs      2210:     {
                   2211:       HTCacheMode_setEnabled (FALSE);
                   2212:     }
1.116     cvs      2213:   if (cache_dir)
1.211     cvs      2214:     HT_FREE (cache_dir);
1.189     cvs      2215:   if (real_dir)
                   2216:     TtaFreeMemory (real_dir);
1.185     cvs      2217:   /* warn the user if the cache isn't active */
                   2218:   if (cache_enabled && !HTCacheMode_enabled ())
1.291     kahan    2219:     {
                   2220:       ThotBool warn_user;
                   2221: 
                   2222:       TtaGetEnvBoolean ("WARN_NO_CACHE", &warn_user);
                   2223:       if (warn_user)
                   2224:        InitInfo ("Cache", TtaGetMessage (AMAYA, AM_CANT_CREATE_CACHE));
                   2225:     }
1.116     cvs      2226: #endif /* AMAYA_WWW_CACHE */
1.15      cvs      2227: }
                   2228: 
                   2229: /*----------------------------------------------------------------------
1.97      cvs      2230:   ProxyInit
                   2231:   Reads any proxies settings which may be declared as environmental
                   2232:   variables or in the thot.ini file. The former overrides the latter.
                   2233:   ----------------------------------------------------------------------*/
                   2234: static void ProxyInit (void)
                   2235: {
1.265     cvs      2236:   char     *strptr;
                   2237:   char     *name;
                   2238:   char     *tmp = NULL;
                   2239:   char     *strptrA;
1.223     cvs      2240:   ThotBool  proxy_is_onlyproxy;
1.97      cvs      2241: 
                   2242:   /* get the proxy settings from the thot.ini file */
1.203     cvs      2243:   strptr = TtaGetEnvString ("HTTP_PROXY");
1.228     cvs      2244:   if (strptr && *strptr)
                   2245:     {
1.265     cvs      2246:       tmp = (char *) TtaGetMemory (strlen (strptr) + 1);
                   2247:       strcpy (tmp, strptr);
1.223     cvs      2248: 
1.228     cvs      2249:       /* does the proxy env string has an "http://" prefix? */
1.265     cvs      2250:       if (!strncasecmp (strptr, "http://", 7)) 
1.223     cvs      2251:         HTProxy_add ("http", tmp);
1.228     cvs      2252:       else 
                   2253:        {
1.265     cvs      2254:          strptrA = (char *) TtaGetMemory (strlen (strptr) + 9);
1.228     cvs      2255:          strcpy (strptrA, "http://");
                   2256:          strcat (strptrA, tmp);
                   2257:          HTProxy_add ("http", strptrA);
                   2258:          TtaFreeMemory (strptrA);
                   2259:        }
                   2260:       TtaFreeMemory (tmp);
                   2261:     }
1.216     cvs      2262: 
1.97      cvs      2263:   /* get the no_proxy settings from the thot.ini file */
1.212     cvs      2264:   strptr = TtaGetEnvString ("PROXYDOMAIN");
1.228     cvs      2265:   if (strptr && *strptr) 
                   2266:     {
1.265     cvs      2267:       strptrA = (char *) TtaGetMemory (strlen (strptr) + 1);
                   2268:       tmp = strptrA;
                   2269:       strcpy (tmp, strptr);
1.228     cvs      2270:       /* as HTNextField changes the ptr we pass as an argument, we'll
1.265     cvs      2271:         work with another variable, so that we can free the tmp
1.228     cvs      2272:         block later on */
                   2273:       while ((name = HTNextField (&tmp)) != NULL) 
                   2274:        {
                   2275:          char* portstr = strchr (name, ':');
                   2276:          unsigned port=0;
1.265     cvs      2277:          if (portstr)
                   2278:            { 
                   2279:              *portstr++ = EOS;
                   2280:              if (*portstr) 
                   2281:                port = (unsigned) atoi (portstr);
                   2282:            }
1.228     cvs      2283:          /* Register it for all access methods */
                   2284:          HTNoProxy_add (name, NULL, port);
                   2285:        }
                   2286:       TtaFreeMemory (strptrA);
                   2287:     }
                   2288:   
1.212     cvs      2289:   /* how should we interpret the proxy domain list? */
1.291     kahan    2290: 
1.212     cvs      2291:   TtaGetEnvBoolean ("PROXYDOMAIN_IS_ONLYPROXY", &proxy_is_onlyproxy);
                   2292:   HTProxy_setNoProxyIsOnlyProxy (proxy_is_onlyproxy);
                   2293: 
                   2294:   /* use libwww's routine to get all proxy settings from the environment */
1.97      cvs      2295:    HTProxy_getEnvVar ();
                   2296: }
                   2297: 
1.207     cvs      2298: /*----------------------------------------------------------------------
1.17      cvs      2299:   AHTProfile_newAmaya
                   2300:   creates the Amaya client profile for libwww.
1.15      cvs      2301:   ----------------------------------------------------------------------*/
1.265     cvs      2302: static void AHTProfile_newAmaya (char *AppName, char *AppVersion)
1.4       cvs      2303: {
1.265     cvs      2304:    char *strptr;
1.158     cvs      2305: 
1.4       cvs      2306:    /* If the Library is not already initialized then do it */
1.257     kahan    2307:    if (!HTLib_isInitialized ()) 
1.273     cvs      2308:        HTLibInit (AppName, AppVersion);
1.4       cvs      2309: 
                   2310:    if (!converters)
                   2311:       converters = HTList_new ();
1.27      cvs      2312:    if (!acceptTypes)
                   2313:       acceptTypes = HTList_new ();
1.193     cvs      2314:    if (!acceptLanguages)
                   2315:       acceptLanguages = HTList_new ();
1.151     cvs      2316:    if (!transfer_encodings)
                   2317:       transfer_encodings = HTList_new ();
                   2318:    if (!content_encodings)
                   2319:       content_encodings = HTList_new ();
1.4       cvs      2320: 
1.169     cvs      2321:    /* inhibits libwww's automatic file_suffix_binding */
                   2322:    HTFile_doFileSuffixBinding (FALSE);
                   2323: 
1.4       cvs      2324:    /* Register the default set of transport protocols */
                   2325:    HTTransportInit ();
                   2326: 
                   2327:    /* Register the default set of application protocol modules */
                   2328:    AHTProtocolInit ();
                   2329: 
1.116     cvs      2330:    /* Register the default set of messages and dialog functions */
                   2331:    AHTAlertInit ();
                   2332:    HTAlert_setInteractive (YES);
                   2333: 
                   2334: #ifdef AMAYA_WWW_CACHE
                   2335:    /* Enable the persistent cache  */
                   2336:    CacheInit ();
                   2337: #else
                   2338:    HTCacheMode_setEnabled (NO);
                   2339: #endif /* AMAYA_WWW_CACHE */
1.4       cvs      2340: 
                   2341:    /* Register the default set of BEFORE and AFTER filters */
                   2342:    AHTNetInit ();
                   2343: 
                   2344:    /* Set up the default set of Authentication schemes */
1.223     cvs      2345:    HTAA_newModule ("basic", HTBasic_generate, HTBasic_parse, NULL, HTBasic_delete);
1.158     cvs      2346:    /* activate MDA by defaul */
1.203     cvs      2347:    strptr = TtaGetEnvString ("ENABLE_MDA");
1.265     cvs      2348:    if (!strptr || (strptr && *strptr && strcasecmp (strptr, "no")))
1.223     cvs      2349:      HTAA_newModule ("digest", HTDigest_generate, HTDigest_parse, HTDigest_updateInfo, HTDigest_delete);
1.257     kahan    2350:    
1.97      cvs      2351:    /* Get any proxy settings */
                   2352:    ProxyInit ();
1.4       cvs      2353: 
1.207     cvs      2354:    /* Set up the domains where we accept a redirect on PUT */
                   2355:    SafePut_init ();
                   2356: 
1.4       cvs      2357:    /* Register the default set of converters */
                   2358:    AHTConverterInit (converters);
1.151     cvs      2359:    HTFormat_setConversion (converters);
1.27      cvs      2360:    AHTAcceptTypesInit (acceptTypes);
1.193     cvs      2361:    AHTAcceptLanguagesInit (acceptLanguages);
1.4       cvs      2362: 
                   2363:    /* Register the default set of transfer encoders and decoders */
1.151     cvs      2364:    HTTransferEncoderInit (transfer_encodings);
1.190     cvs      2365:    HTFormat_setTransferCoding (transfer_encodings);
                   2366:    /* Register the default set of content encoders and decoders */
1.296     kahan    2367:    /* commented because we don't know yet how to handle deflate in the content enconding */
                   2368:    /* HTContentEncoderInit (content_encodings); */
                   2369:    HTCoding_add (content_encodings, "gzip", NULL, HTIdentityCoding, 1.0);
1.190     cvs      2370:    /* ignore all other encoding formats (or libwww will send them 
1.181     cvs      2371:       thru a blackhole otherwise */
                   2372:    HTCoding_add (content_encodings, "*", NULL, HTIdentityCoding, 1.0);
1.151     cvs      2373:    if (HTList_count(content_encodings) > 0)
                   2374:      HTFormat_setContentCoding(content_encodings);
                   2375:    else 
                   2376:      {
                   2377:        HTList_delete(content_encodings);
                   2378:        content_encodings = NULL;
                   2379:      }
1.4       cvs      2380: 
                   2381:    /* Register the default set of MIME header parsers */
1.74      cvs      2382:    HTMIMEInit ();   /* must be called again for language selector */
1.4       cvs      2383: 
                   2384:    /* Register the default set of Icons for directory listings */
1.27      cvs      2385:    /*HTIconInit(NULL); *//* experimental */
1.4       cvs      2386: }
                   2387: 
1.5       cvs      2388: /*----------------------------------------------------------------------
1.17      cvs      2389:   AHTProfile_delete
                   2390:   deletes the Amaya client profile.
1.5       cvs      2391:   ----------------------------------------------------------------------*/
1.4       cvs      2392: static void         AHTProfile_delete (void)
                   2393: {
1.22      cvs      2394:   /* free the Amaya global context */
1.151     cvs      2395:   /* Clean up all the registred converters */
                   2396:   HTFormat_deleteAll ();
                   2397:   if (acceptTypes)
1.74      cvs      2398:     HTConversion_deleteAll (acceptTypes);
1.193     cvs      2399:   if (acceptLanguages)
                   2400:     HTLanguage_deleteAll (acceptLanguages);
1.151     cvs      2401: 
1.209     cvs      2402:   StopAllRequests (1);
1.74      cvs      2403:   HTList_delete (Amaya->docid_status);
                   2404:   HTList_delete (Amaya->reqlist);
                   2405:   TtaFreeMemory (Amaya);
1.61      cvs      2406: 
1.120     cvs      2407: #ifdef _WINDOWS
1.209     cvs      2408:   if (HTLib_isInitialized ())      
1.151     cvs      2409:     HTEventTerminate ();
1.198     cvs      2410: #endif /* _WINDOWS; */         
1.74      cvs      2411:     
1.151     cvs      2412:   /* Clean up the persistent cache (if any) */
1.116     cvs      2413: #ifdef AMAYA_WWW_CACHE
1.151     cvs      2414:   clear_cachelock ();
                   2415:   HTCacheTerminate ();
1.116     cvs      2416: #endif /* AMAYA_WWW_CACHE */
1.217     cvs      2417:   
1.218     cvs      2418:   /* call remove functions that are not called automatically by libwww */
                   2419:   HTNetCall_deleteBeforeAll (HTNet_before ());
                   2420:   HTNetCall_deleteAfterAll (HTNet_after ());
                   2421:   HTAA_deleteAllModules ();
                   2422:   HTAlertCall_deleteAll (HTAlert_global () );
                   2423:   HTAlert_setGlobal ((HTList *) NULL);
1.259     cvs      2424:   HTTimer_deleteAll ();
1.249     kahan    2425:   HTEventList_unregisterAll ();
1.218     cvs      2426:   /* these two functions are broken, so we can't call them right now 
                   2427:   HTHeader_deleteAll ();
                   2428:   HTTimer_deleteAll ();
                   2429:   */
                   2430:   HTTransport_deleteAll ();
1.217     cvs      2431:   /* remove bindings between suffixes, media types*/
                   2432:   HTBind_deleteAll ();
1.151     cvs      2433:   /* Terminate libwww */
                   2434:   HTLibTerminate ();
1.4       cvs      2435: }
                   2436: 
1.5       cvs      2437: /*----------------------------------------------------------------------
1.116     cvs      2438:   AmayacontextInit
                   2439:   initializes an internal Amaya context for our libwww interface 
                   2440:   ----------------------------------------------------------------------*/
1.265     cvs      2441: static void    AmayaContextInit ()
1.116     cvs      2442: {
1.140     cvs      2443:   AmayaAlive_flag = TRUE;
1.116     cvs      2444:   /* Initialization of the global context */
                   2445:   Amaya = (AmayaContext *) TtaGetMemory (sizeof (AmayaContext));
                   2446:   Amaya->reqlist = HTList_new ();
                   2447:   Amaya->docid_status = HTList_new ();
                   2448:   Amaya->open_requests = 0;
                   2449: }
                   2450: 
                   2451: /*----------------------------------------------------------------------
1.17      cvs      2452:   QueryInit
                   2453:   initializes the libwww interface 
1.5       cvs      2454:   ----------------------------------------------------------------------*/
1.265     cvs      2455: void         QueryInit ()
1.4       cvs      2456: {
1.265     cvs      2457:   char   *strptr;
                   2458:   int     tmp_i;
                   2459:   long    tmp_l;
1.4       cvs      2460: 
1.116     cvs      2461:    AmayaContextInit ();
1.4       cvs      2462:    AHTProfile_newAmaya (HTAppName, HTAppVersion);
1.140     cvs      2463:    CanDoStop_set (TRUE);
1.214     cvs      2464:    UserAborted_flag = FALSE;
1.4       cvs      2465: 
1.116     cvs      2466: #ifdef _WINDOWS
1.125     cvs      2467:    HTEventInit ();
1.116     cvs      2468: #endif /* _WINDOWS */
1.72      cvs      2469: 
1.123     cvs      2470: #ifndef _WINDOWS
1.116     cvs      2471:    HTEvent_setRegisterCallback ((void *) AHTEvent_register);
                   2472:    HTEvent_setUnregisterCallback ((void *) AHTEvent_unregister);
1.120     cvs      2473:    HTTimer_registerSetTimerCallback ((void *) AMAYA_SetTimer);
                   2474:    HTTimer_registerDeleteTimerCallback ((void *) AMAYA_DeleteTimer);
1.116     cvs      2475: #endif /* !_WINDOWS */
1.190     cvs      2476: 
1.213     cvs      2477: #ifdef HTDEBUG
1.247     kahan    2478:    /* an undocumented option for being able to generate an HTTP protocol
                   2479:       trace.  The flag can take values from 1-10, which are interpreted as
                   2480:       different kinds of debug traces. Value 99 means a complete trace.
                   2481:       0 or other values means No Debug.1 No Debug (default), up to Full debug, respectively. */
1.238     cvs      2482:    if (TtaGetEnvInt ("ENABLE_LIBWWW_DEBUG", &tmp_i))
1.247     kahan    2483:      {
                   2484:        switch (tmp_i)
                   2485:         {
                   2486:         case 1:
                   2487:           WWW_TraceFlag = SHOW_URI_TRACE;
                   2488:           break;
                   2489:         case 2:
                   2490:           WWW_TraceFlag = SHOW_BIND_TRACE;
                   2491:           break;
                   2492:         case 3:
                   2493:           WWW_TraceFlag = SHOW_THREAD_TRACE;
                   2494:           break;
                   2495:         case 4:
                   2496:           WWW_TraceFlag = SHOW_STREAM_TRACE;
                   2497:           break;
                   2498:         case 5:
                   2499:           WWW_TraceFlag = SHOW_PROTOCOL_TRACE;
                   2500:           break;
                   2501:         case 6:
                   2502:           WWW_TraceFlag = SHOW_MEM_TRACE;
                   2503:           break;
                   2504:         case 7:
                   2505:           WWW_TraceFlag = SHOW_URI_TRACE;
                   2506:           break;
                   2507:         case 8:
                   2508:           WWW_TraceFlag = SHOW_AUTH_TRACE;
                   2509:           break;
                   2510:         case 9:
                   2511:           WWW_TraceFlag = SHOW_ANCHOR_TRACE;
                   2512:           break;
                   2513:         case 10 :
                   2514:           WWW_TraceFlag = SHOW_CORE_TRACE; 
                   2515:           break;
1.251     kahan    2516:         case 11 :
                   2517:           WWW_TraceFlag = SHOW_CORE_TRACE | SHOW_ANCHOR_TRACE | SHOW_AUTH_TRACE | SHOW_URI_TRACE | SHOW_THREAD_TRACE | SHOW_STREAM_TRACE;
                   2518:           break;
1.247     kahan    2519:         case 99 :
                   2520:           WWW_TraceFlag = SHOW_ALL_TRACE;
                   2521:           break;
                   2522:         default:
                   2523:           WWW_TraceFlag = 0;
                   2524:           break;
                   2525:         }
1.248     kahan    2526:        if (WWW_TraceFlag)
                   2527:         {
                   2528:           /* Trace activation (for debugging) */
1.265     cvs      2529:           char   *s, *tmp;
1.248     kahan    2530:           s = TtaGetEnvString ("APP_TMPDIR");
1.265     cvs      2531:           tmp = TtaGetMemory (strlen (s) + sizeof ("/libwww.log") + 1);
                   2532:           strcpy (tmp, s);
                   2533:           strcat (tmp, "/libwww.log");
                   2534:           trace_fp = fopen (tmp, "ab");
1.248     kahan    2535:           TtaFreeMemory (tmp);
                   2536:           if (trace_fp)
                   2537:             HTTrace_setCallback(LineTrace);
                   2538:         }
1.247     kahan    2539:      }
1.208     cvs      2540:    else
                   2541:      WWW_TraceFlag = 0;
1.213     cvs      2542: #endif /* HTDEBUG */
1.208     cvs      2543: 
1.74      cvs      2544: #ifdef DEBUG_LIBWWW
1.116     cvs      2545:   /* forwards error messages to our own function */
                   2546:    WWW_TraceFlag = THD_TRACE;
1.138     cvs      2547:    HTTrace_setCallback(LineTrace);
1.248     kahan    2548: 
1.148     cvs      2549:    /***
1.138     cvs      2550:     WWW_TraceFlag = SHOW_CORE_TRACE | SHOW_THREAD_TRACE | SHOW_PROTOCOL_TRACE;
                   2551:     ***/
1.152     cvs      2552: #endif
1.247     kahan    2553: 
                   2554:    TtaGetEnvBoolean ("ENABLE_FTP", &FTPURL_flag);
1.152     cvs      2555: 
1.148     cvs      2556:    /* Setting up different network parameters */
1.151     cvs      2557: 
1.148     cvs      2558:    /* Maximum number of simultaneous open sockets */
1.203     cvs      2559:    strptr = TtaGetEnvString ("MAX_SOCKET");
1.151     cvs      2560:    if (strptr && *strptr) 
1.288     vatton   2561:      tmp_i = atoi (strptr);
1.151     cvs      2562:    else
                   2563:      tmp_i = DEFAULT_MAX_SOCKET;
                   2564:    HTNet_setMaxSocket (tmp_i);
                   2565: 
1.148     cvs      2566:    /* different network services timeouts */
1.151     cvs      2567:    /* dns timeout */
1.203     cvs      2568:    strptr = TtaGetEnvString ("DNS_TIMEOUT");
1.151     cvs      2569:    if (strptr && *strptr) 
1.288     vatton   2570:      tmp_i = atoi (strptr);
1.151     cvs      2571:    else
                   2572:      tmp_i = DEFAULT_DNS_TIMEOUT;
                   2573:    HTDNS_setTimeout (tmp_i);
                   2574: 
                   2575:    /* persistent connections timeout */
1.203     cvs      2576:    strptr = TtaGetEnvString ("PERSIST_CX_TIMEOUT");
1.151     cvs      2577:    if (strptr && *strptr) 
1.288     vatton   2578:      tmp_l = atol (strptr); 
1.151     cvs      2579:    else
                   2580:      tmp_l = DEFAULT_PERSIST_TIMEOUT;
                   2581:    HTHost_setPersistTimeout (tmp_l);
                   2582: 
1.148     cvs      2583:    /* default timeout in ms */
1.203     cvs      2584:    strptr = TtaGetEnvString ("NET_EVENT_TIMEOUT");
1.151     cvs      2585:    if (strptr && *strptr) 
1.288     vatton   2586:      tmp_i = atoi (strptr);
1.151     cvs      2587:    else
                   2588:      tmp_i = DEFAULT_NET_EVENT_TIMEOUT;
                   2589:    HTHost_setEventTimeout (tmp_i);
                   2590: 
1.173     cvs      2591:    HTRequest_setMaxRetry (8);
1.4       cvs      2592: #ifdef CATCH_SIG
1.148     cvs      2593:    signal (SIGPIPE, SIG_IGN);
1.4       cvs      2594: #endif
1.15      cvs      2595: }
                   2596: 
                   2597: /*----------------------------------------------------------------------
1.17      cvs      2598:   LoopForStop
1.136     cvs      2599:   a copy of the Thop event loop so we can handle the stop button in Unix
                   2600:   and preemptive requests under Windows
1.15      cvs      2601:   ----------------------------------------------------------------------*/
                   2602: static int          LoopForStop (AHTReqContext * me)
                   2603: {
1.136     cvs      2604: #ifdef _WINDOWS
                   2605:   MSG msg;
                   2606:   unsigned long libwww_msg;
                   2607:   HWND old_active_window, libwww_window;
                   2608:   int  status_req = HT_OK;
                   2609: 
                   2610:   old_active_window = GetActiveWindow ();
                   2611:   libwww_window = HTEventList_getWinHandle (&libwww_msg);
1.137     cvs      2612:  
1.149     cvs      2613:   while (me->reqStatus != HT_END && me->reqStatus != HT_ERR
1.253     cvs      2614:         && me->reqStatus != HT_ABORT && AmayaIsAlive () &&
                   2615:         GetMessage (&msg, NULL, 0, 0))
                   2616:     {
                   2617:       if (msg.message != WM_QUIT)
                   2618:        TtaHandleOneEvent (&msg);
                   2619:       else
                   2620:        break;      
                   2621:     }
1.136     cvs      2622:   if (!AmayaIsAlive ())
                   2623:     /* Amaya was killed by one of the callback handlers */
                   2624:     exit (0);
                   2625: #else /* _WINDOWS */
1.277     kahan    2626:    ThotEvent                ev;
1.17      cvs      2627:    int                 status_req = HT_OK;
1.15      cvs      2628: 
                   2629:    /* to test the async calls  */
1.17      cvs      2630:    /* Loop while waiting for new events, exists when the request is over */
1.15      cvs      2631:    while (me->reqStatus != HT_ABORT &&
                   2632:          me->reqStatus != HT_END &&
1.69      cvs      2633:          me->reqStatus != HT_ERR) {
1.116     cvs      2634:         if (!AmayaIsAlive ())
1.69      cvs      2635:            /* Amaya was killed by one of the callback handlers */
                   2636:            exit (0);
1.277     kahan    2637:         
                   2638:          if (TtaFetchOneAvailableEvent (&ev))
                   2639:           TtaHandleOneEvent (&ev);
1.69      cvs      2640:    }
1.136     cvs      2641: #endif /* _WINDOWS */
1.69      cvs      2642:    switch (me->reqStatus) {
                   2643:          case HT_ERR:
                   2644:           case HT_ABORT:
1.130     cvs      2645:               status_req = NO;
1.15      cvs      2646:               break;
                   2647: 
1.69      cvs      2648:          case HT_END:
1.130     cvs      2649:               status_req = YES;
1.15      cvs      2650:               break;
                   2651: 
1.69      cvs      2652:          default:
1.15      cvs      2653:               break;
1.69      cvs      2654:    }
1.15      cvs      2655:    return (status_req);
1.4       cvs      2656: }
                   2657: 
1.5       cvs      2658: /*----------------------------------------------------------------------
1.15      cvs      2659:   QueryClose
1.21      cvs      2660:   closes all existing threads, frees all non-automatically deallocated
                   2661:   memory and then ends libwww.
1.5       cvs      2662:   ----------------------------------------------------------------------*/
1.116     cvs      2663: void QueryClose ()
1.4       cvs      2664: {
1.24      cvs      2665: 
1.140     cvs      2666:   AmayaAlive_flag = FALSE;
1.24      cvs      2667: 
1.116     cvs      2668:   /* remove all the handlers and callbacks that may output a message to
                   2669:      a non-existent Amaya window */
                   2670:   HTEvent_setRegisterCallback ((HTEvent_registerCallback *) NULL);
                   2671:   HTEvent_setUnregisterCallback ((HTEvent_unregisterCallback *) NULL);
                   2672: #ifndef _WINDOWS
                   2673:   /** need to erase all existing timers too **/
                   2674:    HTTimer_registerSetTimerCallback (NULL);
                   2675:    HTTimer_registerDeleteTimerCallback (NULL);
                   2676: #endif /* !_WINDOWS */
                   2677:   HTHost_setActivateRequestCallback (NULL);
                   2678:   Thread_deleteAll ();
1.21      cvs      2679:  
1.116     cvs      2680:   HTProxy_deleteAll ();
                   2681:   HTNoProxy_deleteAll ();
1.207     cvs      2682:   SafePut_delete ();
1.116     cvs      2683:   HTGateway_deleteAll ();
                   2684:   AHTProfile_delete ();
1.248     kahan    2685: 
                   2686:   /* close the trace file (if it exists) */
                   2687:   if (trace_fp)
                   2688:     fclose (trace_fp);
                   2689: 
1.116     cvs      2690: }
                   2691: 
                   2692: /*----------------------------------------------------------------------
                   2693:   NextNameValue
                   2694:   ---------------------------------------------------------------------*/
1.265     cvs      2695: static char * NextNameValue (char **pstr, char **name, char **value)
1.116     cvs      2696: {
                   2697:   char * p = *pstr;
                   2698:   char * start = NULL;
                   2699:   if (!pstr || !*pstr) return NULL;
                   2700:   
                   2701:     if (!*p) {
                   2702:       *pstr = p;
                   2703:       *name = NULL;
                   2704:       *value = NULL;
                   2705:       return NULL;                                      /* No field */
                   2706:     }
                   2707:     
                   2708:     /* Now search for the next '&' and ';' delimitators */
                   2709:     start = p;
                   2710:     while (*p && *p != '&' && *p != ';') p++;
                   2711:     if (*p) 
                   2712:       *p++ = '\0';
                   2713:     *pstr = p;
                   2714: 
                   2715:     /* Search for the name and value */
                   2716:     *name = start;
                   2717:     p = start;
                   2718:     
                   2719:     while(*p && *p != '=') 
                   2720:       p++;
                   2721:     if (*p) 
                   2722:       *p++ = '\0';
                   2723:     *value = p;
                   2724: 
                   2725:     return start;
                   2726: }
                   2727: 
                   2728: /*----------------------------------------------------------------------
                   2729:   PrepareFormdata
                   2730:   ---------------------------------------------------------------------*/
1.265     cvs      2731: static   HTAssocList * PrepareFormdata (char *string)
1.116     cvs      2732: {
1.266     cvs      2733:   char          *tmp_string, *tmp_string_ptr;
                   2734:   char          *name;
                   2735:   char          *value;
                   2736:   HTAssocList   *formdata;
1.116     cvs      2737: 
                   2738:   if (!string)
                   2739:     return NULL;
                   2740: 
                   2741:   /* store the ptr in another variable, as the original address will
                   2742:      change
                   2743:      */
1.236     cvs      2744:   
1.265     cvs      2745:   tmp_string_ptr = TtaGetMemory (strlen (string) + 1);
1.236     cvs      2746:   tmp_string = tmp_string_ptr;
1.273     cvs      2747:   strcpy (tmp_string_ptr, string);
1.116     cvs      2748:   formdata = HTAssocList_new();
                   2749:   
                   2750:   while (*tmp_string)
                   2751:     {
                   2752:       NextNameValue (&tmp_string, &name, &value);
                   2753:       HTAssocList_addObject(formdata,
                   2754:                            name, value);
                   2755:     }
                   2756: 
                   2757:   TtaFreeMemory (tmp_string_ptr);
                   2758:   return formdata;
1.4       cvs      2759: }
                   2760: 
1.236     cvs      2761: /*----------------------------------------------------------------------
                   2762:   ---------------------------------------------------------------------*/
1.216     cvs      2763: void AHTRequest_setCustomAcceptHeader (HTRequest *request, char *value)
                   2764: {                              
                   2765:   HTRqHd rqhd = HTRequest_rqHd (request);
                   2766:   rqhd = rqhd & (~HT_C_ACCEPT_TYPE);
                   2767:   HTRequest_setRqHd (request, rqhd);
1.221     cvs      2768:   HTRequest_addExtraHeader (request, "Accept", value);
1.216     cvs      2769: }
                   2770: 
1.228     cvs      2771: /*----------------------------------------------------------------------
1.99      cvs      2772:   InvokeGetObjectWWW_callback
                   2773:   A simple function to invoke a callback function whenever there's an error
                   2774:   in GetObjectWWW
                   2775:   ---------------------------------------------------------------------*/
1.265     cvs      2776: void InvokeGetObjectWWW_callback (int docid, char *urlName,
                   2777:                                  char *outputfile, TTcbf *terminate_cbf,
                   2778:                                  void *context_tcbf, int status)
1.99      cvs      2779: {
                   2780:   if (!terminate_cbf)
                   2781:     return;
                   2782:   
1.116     cvs      2783:   (*terminate_cbf) (docid, status, urlName, outputfile,
1.99      cvs      2784:                    NULL, context_tcbf);  
                   2785: }
                   2786: 
                   2787: 
                   2788: 
1.5       cvs      2789: /*----------------------------------------------------------------------
1.15      cvs      2790:    GetObjectWWW
1.17      cvs      2791:    this function requests a resource designated by a URLname into a
                   2792:    temporary filename. The download can come from a simple GET operation,
                   2793:    or can come from POSTING/GETTING a form. In the latter
                   2794:    case, the function receives a query string to send to the server.
                   2795: 
1.5       cvs      2796:    4  file retrieval modes are proposed:                              
                   2797:    AMAYA_SYNC : blocking mode                            
                   2798:    AMAYA_ISYNC : incremental, blocking mode              
                   2799:    AMAYA_ASYNC : non-blocking mode                       
                   2800:    AMAYA_IASYNC : incremental, non-blocking mode         
                   2801:    
                   2802:    In the incremental mode, each time a package arrives, it will be   
                   2803:    stored in the temporary file. In addition, if an                   
                   2804:    incremental_callback function is defined, this function will be    
                   2805:    called and handled a copy of the newly received data package.      
                   2806:    Finally, if a terminate_callback function is defined, it will be   
                   2807:    invoked when the request terminates. The caller of this function
1.4       cvs      2808:    can define two different contexts to be passed to the callback
                   2809:    functions.
                   2810: 
                   2811:    When the function is called with the SYNC mode, the function will
                   2812:    return only when the requested file has been loaded.
                   2813:    The ASYNC mode will immediately return after setting up the
                   2814:    call.
                   2815: 
                   2816:    Notes:
                   2817:    At the end of a succesful request, the urlName string contains the
                   2818:    name of the actually retrieved URL. As a URL can change over the time,
                   2819:    (e.g., be redirected elsewhere), it is advised that the function
1.17      cvs      2820:    caller verify the value of the urlName variable at the end of
1.4       cvs      2821:    a request.
                   2822: 
                   2823:    Inputs:
                   2824:    - docid  Document identifier for the set of objects being
                   2825:    retrieved.
                   2826:    - urlName The URL to be retrieved (MAX_URL_LENGTH chars length)
                   2827:    - outputfile A pointer to an empty string of MAX_URL_LENGTH.
                   2828:    - mode The retrieval mode.
                   2829:    - incremental_cbf 
                   2830:    - context_icbf
                   2831:    Callback and context for the incremental modes
                   2832:    - terminate_cbf 
                   2833:    - context_icbf
                   2834:    Callback and context for a terminate handler
1.17      cvs      2835:    -error_html if TRUE, then display any server error message as an
                   2836:    HTML document.
1.88      cvs      2837:    - content_type a string
                   2838:  
1.4       cvs      2839:    Outputs:
                   2840:    - urlName The URL that was retrieved
                   2841:    - outputfile The name of the temporary file which holds the
                   2842:    retrieved data. (Only in case of success)
1.88      cvs      2843:    - if content_type wasn't NULL, it will contain a copy of the parameter
                   2844:      sent in the HTTP answer
1.4       cvs      2845:    Returns:
                   2846:    HT_ERROR
                   2847:    HT_OK
1.5       cvs      2848:   ----------------------------------------------------------------------*/
1.265     cvs      2849: int GetObjectWWW (int docid, char *urlName, char *formdata,
                   2850:                  char *outputfile, int mode, TIcbf *incremental_cbf, 
                   2851:                  void *context_icbf, TTcbf *terminate_cbf, 
                   2852:                  void *context_tcbf, ThotBool error_html, char *content_type)
1.4       cvs      2853: {
                   2854:    AHTReqContext      *me;
1.301     vatton   2855:    char               *ref;
                   2856:    char               *esc_url;
1.107     cvs      2857:    int                 status, l;
1.114     cvs      2858:    int                 tempsubdir;
1.191     cvs      2859:    ThotBool            bool_tmp;
1.7       cvs      2860: 
1.116     cvs      2861:    if (urlName == NULL || docid == 0 || outputfile == NULL) 
                   2862:      {
                   2863:        /* no file to be loaded */
                   2864:        TtaSetStatus (docid, 1, TtaGetMessage (AMAYA, AM_BAD_URL), urlName);
1.69      cvs      2865:        
1.116     cvs      2866:        if (error_html)
1.69      cvs      2867:         /* so we can show the error message */
                   2868:         DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
1.116     cvs      2869:        InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
                   2870:                                    context_tcbf, HT_ERROR);
                   2871:        return HT_ERROR;
                   2872:      }
1.7       cvs      2873: 
1.159     cvs      2874:    /* if it's a 'docImage', we have already downloaded it */
1.265     cvs      2875:    if (!strncmp ("internal:", urlName, 9)) 
1.159     cvs      2876:      {
1.265     cvs      2877:        strcpy (outputfile, urlName);
1.159     cvs      2878:        InvokeGetObjectWWW_callback (docid, urlName, outputfile,
                   2879:                                    terminate_cbf, context_tcbf, HT_OK);
                   2880:        return HT_OK;
                   2881:      }
                   2882: 
1.4       cvs      2883:    /* do we support this protocol? */
1.116     cvs      2884:    if (IsValidProtocol (urlName) == NO) 
                   2885:      {
                   2886:        /* return error */
                   2887:        outputfile[0] = EOS;    /* file could not be opened */
                   2888:        TtaSetStatus (docid, 1, 
                   2889:                     TtaGetMessage (AMAYA, AM_GET_UNSUPPORTED_PROTOCOL),
                   2890:                     urlName);
                   2891: 
                   2892:        if (error_html)
1.69      cvs      2893:         /* so we can show the error message */
                   2894:         DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
1.116     cvs      2895:        InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
                   2896:                                    context_tcbf, HT_ERROR);
                   2897:        return HT_ERROR;
                   2898:      }
1.4       cvs      2899: 
1.114     cvs      2900:    /* we store CSS in subdir named 0; all the other files go to a subidr
                   2901:       named after their own docid */
                   2902:    tempsubdir = (mode & AMAYA_LOAD_CSS) ? 0 : docid;
1.116     cvs      2903:    /* create a tempfilename */
1.272     cvs      2904:    sprintf (outputfile, "%s%c%d%c%04dAM", TempFileDirectory, DIR_SEP, tempsubdir, DIR_SEP, object_counter);
1.116     cvs      2905:    /* update the object_counter (used for the tempfilename) */
1.4       cvs      2906:    object_counter++;
                   2907:    /* normalize the URL */
1.300     kahan    2908:    esc_url = EscapeURL (urlName);
1.206     cvs      2909:    if (esc_url) 
                   2910:      {
1.265     cvs      2911:        ref = AmayaParseUrl (esc_url, "", AMAYA_PARSE_ALL);
1.206     cvs      2912:        TtaFreeMemory (esc_url);
                   2913:      }
                   2914:    else
                   2915:      ref = NULL;
                   2916: 
1.4       cvs      2917:    /* should we abort the request if we could not normalize the url? */
1.198     cvs      2918:    if (ref == NULL || ref[0] == EOS) {
1.69      cvs      2919:       /*error */
                   2920:       outputfile[0] = EOS;
                   2921:       TtaSetStatus (docid, 1, TtaGetMessage (AMAYA, AM_BAD_URL), urlName);
1.214     cvs      2922:       if (ref)
                   2923:        TtaFreeMemory (ref); 
1.69      cvs      2924:       if (error_html)
1.116     cvs      2925:        /* so we can show the error message */
                   2926:        DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
1.99      cvs      2927:       InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
1.116     cvs      2928:                                   context_tcbf, HT_ERROR);
1.69      cvs      2929:       return HT_ERROR;
                   2930:    }
1.116     cvs      2931: 
1.4       cvs      2932:    /* verify if that file name existed */
1.9       cvs      2933:    if (TtaFileExist (outputfile))
1.77      cvs      2934:      TtaFileUnlink (outputfile);
1.116     cvs      2935:    
1.4       cvs      2936:    /* Initialize the request structure */
                   2937:    me = AHTReqContext_new (docid);
1.116     cvs      2938:    if (me == NULL) 
                   2939:      {
                   2940:        outputfile[0] = EOS;
                   2941:        /* need an error message here */
                   2942:        TtaFreeMemory (ref);
                   2943:        InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
                   2944:                                   context_tcbf, HT_ERROR);
                   2945:        return HT_ERROR;
                   2946:      }
                   2947: 
1.4       cvs      2948:    /* Specific initializations for POST and GET */
1.222     cvs      2949:    if (mode & AMAYA_FORM_POST
1.228     cvs      2950:        || mode & AMAYA_FILE_POST)
1.116     cvs      2951:      {
                   2952:        me->method = METHOD_POST;
                   2953:        HTRequest_setMethod (me->request, METHOD_POST);
                   2954:      }
                   2955:    else 
                   2956:      {
1.254     kahan    2957: #ifdef ANNOTATIONS
                   2958:        /* we support the DELETE method for deleting annotations.
                   2959:          the rest of the request is similar to the GET */
                   2960:        if (mode & AMAYA_DELETE)
                   2961:         {
                   2962:           me->method = METHOD_GET;
                   2963:           HTRequest_setMethod (me->request, METHOD_DELETE);
                   2964:         }
                   2965:         else
                   2966: #endif /* ANNOTATIONS */
                   2967:           me->method = METHOD_GET;
1.295     kahan    2968: #ifdef ANNOTATIONS
                   2969:        /* use the custom sent content_type */
                   2970:        if (content_type && content_type[0] != EOS)
                   2971:         AHTRequest_setCustomAcceptHeader (me->request, content_type);
                   2972:        else
                   2973: #endif /* ANNOTATIONS */
                   2974:         if (!HasKnownFileSuffix (ref))
1.216     cvs      2975:         {
                   2976:           /* try to adjust the Accept header in an netwise economical way */
                   2977:           if (mode & AMAYA_LOAD_IMAGE)
                   2978:             AHTRequest_setCustomAcceptHeader (me->request, IMAGE_ACCEPT_NEGOTIATION);
                   2979:           else if (mode & AMAYA_LOAD_CSS)
                   2980:             AHTRequest_setCustomAcceptHeader (me->request, "*/*;q=0.1,css/*");
1.294     kahan    2981:           else
                   2982:             AHTRequest_setCustomAcceptHeader (me->request, GENERAL_ACCEPT_NEGOTIATION);
1.216     cvs      2983:           /*
                   2984:           HTRequest_setConversion(me->request, acceptTypes, TRUE);
                   2985:           */
                   2986:         }
1.295     kahan    2987:         else
                   2988:           AHTRequest_setCustomAcceptHeader (me->request, GENERAL_ACCEPT_NEGOTIATION);
                   2989:        /* language negotiation */
                   2990:        HTRequest_setLanguage (me->request, acceptLanguages, TRUE);
1.116     cvs      2991:      }
1.93      cvs      2992: 
1.116     cvs      2993:    /* Common initialization for all HTML methods */
1.4       cvs      2994:    me->mode = mode;
                   2995:    me->error_html = error_html;
                   2996:    me->incremental_cbf = incremental_cbf;
                   2997:    me->context_icbf = context_icbf;
                   2998:    me->terminate_cbf = terminate_cbf;
                   2999:    me->context_tcbf = context_tcbf;
1.64      cvs      3000: 
1.69      cvs      3001:    /* for the async. request modes, we need to have our
1.4       cvs      3002:       own copy of outputfile and urlname
1.116     cvs      3003:       */
1.4       cvs      3004: 
1.116     cvs      3005:    if ((mode & AMAYA_ASYNC) || (mode & AMAYA_IASYNC)) 
                   3006:      {
1.265     cvs      3007:        l = strlen (outputfile);
1.116     cvs      3008:        if (l > MAX_LENGTH)
1.265     cvs      3009:         me->outputfile = TtaGetMemory (l + 2);
1.116     cvs      3010:        else
1.265     cvs      3011:         me->outputfile = TtaGetMemory (MAX_LENGTH + 2);
                   3012:        strcpy (me->outputfile, outputfile);
                   3013:        l = strlen (urlName);
1.116     cvs      3014:        if (l > MAX_LENGTH)
1.265     cvs      3015:         me->urlName = TtaGetMemory (l + 2);
1.116     cvs      3016:        else
1.265     cvs      3017:         me->urlName = TtaGetMemory (MAX_LENGTH + 2);
                   3018:        strcpy (me->urlName, urlName);
1.116     cvs      3019: #ifdef _WINDOWS
                   3020:      /* force windows ASYNC requests to always be non preemptive */
                   3021:      HTRequest_setPreemptive (me->request, NO);
                   3022: #endif /*_WINDOWS */
                   3023:      } /* AMAYA_ASYNC mode */ 
                   3024:    else 
                   3025: #ifdef _WINDOWS
                   3026:      {
1.233     cvs      3027:        me->outputfile = outputfile;
                   3028:        me->urlName = urlName;
1.116     cvs      3029:        /* force windows SYNC requests to always be non preemptive */
                   3030:        HTRequest_setPreemptive (me->request, YES);
                   3031:      }
                   3032: #else /* !_WINDOWS */
                   3033:      {
                   3034:        me->outputfile = outputfile;
                   3035:        me->urlName = urlName;
                   3036:      }
                   3037:    /***
1.136     cvs      3038:      In order to take into account the stop button, 
                   3039:      the requests will be always asynchronous, however, if mode=AMAYA_SYNC,
1.57      cvs      3040:      we will loop until the document has been received or a stop signal
                   3041:      generated
1.77      cvs      3042:      ****/
1.116     cvs      3043:    HTRequest_setPreemptive (me->request, NO);
                   3044: #endif /* _WINDOWS */
1.61      cvs      3045: 
1.151     cvs      3046:    /*
                   3047:    ** Make sure that the first request is flushed immediately and not
                   3048:    ** buffered in the output buffer
                   3049:    */
                   3050:    if (mode & AMAYA_FLUSH_REQUEST)
                   3051:      HTRequest_setFlush(me->request, YES);
                   3052:    HTRequest_setFlush(me->request, YES);
                   3053: 
1.61      cvs      3054:    /* prepare the URLname that will be displayed in teh status bar */
                   3055:    ChopURL (me->status_urlName, me->urlName);
1.77      cvs      3056:    TtaSetStatus (me->docid, 1, 
                   3057:                 TtaGetMessage (AMAYA, AM_FETCHING),
1.233     cvs      3058:                 me->status_urlName);
1.4       cvs      3059: 
1.265     cvs      3060:    me->anchor = (HTParentAnchor *) HTAnchor_findAddress (ref);
1.45      cvs      3061:    TtaFreeMemory (ref);
1.177     cvs      3062:    
1.223     cvs      3063:    TtaGetEnvBoolean ("CACHE_DISCONNECTED_MODE", &bool_tmp);
1.177     cvs      3064:    if (!bool_tmp && (mode & AMAYA_NOCACHE))
1.116     cvs      3065:       HTRequest_setReloadMode (me->request, HT_CACHE_FLUSH);
                   3066: 
                   3067:    /* prepare the query string and format for POST */
                   3068:    if (mode & AMAYA_FORM_POST)
1.114     cvs      3069:      {
1.116     cvs      3070:        HTAnchor_setFormat ((HTParentAnchor *) me->anchor, 
                   3071:                           HTAtom_for ("application/x-www-form-urlencoded"));
                   3072:        HTAnchor_setLength ((HTParentAnchor *) me->anchor, me->block_size);
                   3073:        HTRequest_setEntityAnchor (me->request, me->anchor);
                   3074:      } 
1.114     cvs      3075: 
1.127     cvs      3076:    /* create the formdata element for libwww */
1.236     cvs      3077:    if (formdata && ! (mode & AMAYA_FILE_POST))
                   3078:       me->formdata = PrepareFormdata (formdata);
1.127     cvs      3079: 
1.297     kirschpi 3080:        
                   3081: #ifdef DAV 
1.302     kirschpi 3082:    /* try to add an "If" header (lock information) also for POST 
                   3083:     * requests and for GET forms */
1.297     kirschpi 3084:    if (HTRequest_method(me->request) == METHOD_POST ||
                   3085:           (HTRequest_method(me->request) == METHOD_GET && me->formdata))          
                   3086:        DAVAddIfHeader (me,HTAnchor_address((HTAnchor*)me->anchor));
1.302     kirschpi 3087: #endif /* DAV */
1.297     kirschpi 3088:        
                   3089:    
1.116     cvs      3090:    /* do the request */
                   3091:    if (mode & AMAYA_FORM_POST)
1.119     cvs      3092:      {
1.191     cvs      3093:        /* this call doesn't give back a ThotBool */
1.119     cvs      3094:        HTParentAnchor * posted = NULL;
                   3095: 
                   3096:        posted = HTPostFormAnchor (me->formdata, (HTAnchor *) me->anchor, 
                   3097:                                    me->request);
                   3098:        status = posted ? YES : NO; 
                   3099:      }
1.222     cvs      3100: #ifdef ANNOTATIONS
1.251     kahan    3101:    else if (mode & AMAYA_FILE_POST)
1.222     cvs      3102:      {
1.228     cvs      3103:        unsigned long filesize;
                   3104:        char *fileURL;
                   3105: 
                   3106:        /* @@@ a very ugly patch :)))
                   3107:        I'm copying here some of the functionality I use in the PUT
                   3108:        I need to put the common parts in another module */
1.252     kahan    3109:        AM_GetFileSize (formdata, &filesize);
1.228     cvs      3110:        me->block_size = filesize;
                   3111: 
1.233     cvs      3112:        fileURL = HTParse (formdata, "file:/", PARSE_ALL);
1.228     cvs      3113:        me->source = HTAnchor_findAddress (fileURL);
                   3114:        HT_FREE (fileURL);
1.222     cvs      3115: 
1.228     cvs      3116:        /* hardcoded ... */
                   3117:        AHTRequest_setCustomAcceptHeader (me->request, "application/xml");
1.222     cvs      3118:        HTAnchor_setFormat (HTAnchor_parent (me->source),
                   3119:                           HTAtom_for ("application/xml"));
1.228     cvs      3120:        HTAnchor_setFormat (me->anchor,
                   3121:                           HTAtom_for ("application/xml"));
                   3122:        HTAnchor_setLength ((HTParentAnchor *) me->source, me->block_size);
                   3123:        /* @@ here I need to actually read the file and put it in document,
                   3124:          then, when I kill the request, I need to kill it */
                   3125:        {
                   3126:         FILE *fp;
                   3127:         int i;
                   3128:         char c;
                   3129: 
1.255     swick    3130:         me->document = TtaGetMemory (me->block_size + 1);
1.233     cvs      3131:         fp = fopen (formdata, "r");
1.244     kahan    3132:         i = 0; 
1.228     cvs      3133:         c = getc (fp);
                   3134:         while (!feof (fp))
                   3135:           {
                   3136:             me->document[i++] = c;
                   3137:             c = getc (fp);
                   3138:           }
                   3139:         me->document[i] = '\0';
                   3140:         fclose (fp);
                   3141:        }
                   3142:        HTAnchor_setDocument ( (HTParentAnchor *) me->source,
                   3143:                              (void * ) me->document);
                   3144:        HTRequest_setEntityAnchor (me->request, HTAnchor_parent (me->source));
                   3145:  
                   3146:        status = HTPostAnchor (HTAnchor_parent (me->source), 
1.222     cvs      3147:                              (HTAnchor *) me->anchor, 
                   3148:                              me->request);
                   3149:      }
                   3150: #endif /* ANNOTATIONS */
1.127     cvs      3151:    else if (formdata)
                   3152:      status = HTGetFormAnchor(me->formdata, (HTAnchor *) me->anchor,
                   3153:                              me->request);
1.116     cvs      3154:    else
1.77      cvs      3155:      status = HTLoadAnchor ((HTAnchor *) me->anchor, me->request);
1.69      cvs      3156: 
1.123     cvs      3157:    /* @@@ may need some special windows error msg here */
1.116     cvs      3158:    /* control the errors */
1.4       cvs      3159: 
1.130     cvs      3160:     if (status == NO)
1.116     cvs      3161:      /* the request invocation failed */
                   3162:      {
                   3163:        /* show an error message on the status bar */
                   3164:        DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
                   3165:        TtaSetStatus (docid, 1, 
                   3166:                     TtaGetMessage (AMAYA, AM_CANNOT_LOAD),
                   3167:                     urlName);
                   3168:        if (me->reqStatus == HT_NEW)
                   3169:         /* manually invoke the last processing that usually gets done
                   3170:            in a succesful request */
                   3171:         InvokeGetObjectWWW_callback (docid, urlName, outputfile, 
                   3172:                                      terminate_cbf, context_tcbf, HT_ERROR);
                   3173:        /* terminate_handler wasn't called */
1.136     cvs      3174:        AHTReqContext_delete (me);
1.116     cvs      3175:      }
                   3176:    else
1.136     cvs      3177:      /* end treatment for SYNC requests */
1.120     cvs      3178:      if ((mode & AMAYA_SYNC) || (mode & AMAYA_ISYNC))
                   3179:        {
1.136     cvs      3180:         /* wait here untilt the asynchronous request finishes */
1.130     cvs      3181:         status = LoopForStop (me);
1.136     cvs      3182:         /* if status returns HT_ERROR, should we invoke the callback? */
1.120     cvs      3183:         if (!HTRequest_kill (me->request))
                   3184:           AHTReqContext_delete (me);
                   3185:        }
1.130     cvs      3186: 
1.136     cvs      3187:     /* an interface problem!!! */
                   3188:     return (status == YES ? 0 : -1);
1.4       cvs      3189: }
                   3190: 
1.5       cvs      3191: /*----------------------------------------------------------------------
1.17      cvs      3192:    PutObjectWWW
                   3193:    frontend for uploading a resource to a URL. This function downloads
                   3194:    a file to be uploaded into memory, it then calls UploadMemWWW to
                   3195:    finish the job.
                   3196: 
1.5       cvs      3197:    2 upload modes are proposed:                                       
                   3198:    AMAYA_SYNC : blocking mode                            
                   3199:    AMAYA_ASYNC : non-blocking mode                       
                   3200:    
1.4       cvs      3201:    When the function is called with the SYNC mode, the function will
                   3202:    return only when the file has been uploaded.
                   3203:    The ASYNC mode will immediately return after setting up the
                   3204:    call. Furthermore, at the end of an upload, the ASYNC mode will 
                   3205:    call back terminate_cbf, handling it the context defined in
                   3206:    context_tcbf.
                   3207: 
                   3208:    Notes:
                   3209:    At the end of a succesful request, the urlName string contains the
                   3210:    name of the actually uploaded URL. As a URL can change over the time,
                   3211:    (e.g., be redirected elsewhere), it is advised that the function
                   3212:    caller verifies the value of the urlName variable at the end of
                   3213:    a request.
                   3214: 
                   3215:    Inputs:
                   3216:    - docid  Document identifier for the set of objects being
                   3217:    retrieved.
                   3218:    - fileName A pointer to the local file to upload
                   3219:    - urlName The URL to be uploaded (MAX_URL_LENGTH chars length)
                   3220:    - mode The retrieval mode.
                   3221:    - terminate_cbf 
                   3222:    - context_icbf
                   3223:    Callback and context for a terminate handler
                   3224: 
                   3225:    Outputs:
                   3226:    - urlName The URL that was uploaded
                   3227: 
                   3228:    Returns:
                   3229:    HT_ERROR
                   3230:    HT_OK
1.5       cvs      3231:   ----------------------------------------------------------------------*/
1.276     kahan    3232: int PutObjectWWW (int docid, char *fileName, char *urlName, 
                   3233:                  char *contentType, int mode,
1.265     cvs      3234:                  TTcbf *terminate_cbf, void *context_tcbf)
1.4       cvs      3235: {
1.116     cvs      3236:    AHTReqContext      *me;
1.250     cvs      3237:    CHARSET             charset;
1.4       cvs      3238:    int                 status;
1.250     cvs      3239:    unsigned long       file_size;
1.116     cvs      3240:    char               *fileURL;
1.168     cvs      3241:    char               *etag = NULL;
1.169     cvs      3242:    HTParentAnchor     *dest_anc_parent;
1.265     cvs      3243:    char               *tmp;
                   3244:    char               *esc_url;
1.168     cvs      3245:    int                 UsePreconditions;
1.191     cvs      3246:    ThotBool            lost_update_check = TRUE;
1.235     cvs      3247:    char                url_name[MAX_LENGTH];
1.285     kahan    3248:    char               *resource_name;
1.265     cvs      3249:    char               *tmp2;
1.239     cvs      3250: #ifdef _WINDOWS
                   3251:    char                file_name[MAX_LENGTH];
                   3252: #endif /* _WINDOWS */
1.172     cvs      3253: 
                   3254:    /* should we protect the PUT against lost updates? */
1.203     cvs      3255:    tmp = TtaGetEnvString ("ENABLE_LOST_UPDATE_CHECK");
1.265     cvs      3256:    if (tmp && *tmp && strcasecmp (tmp, "yes"))
1.172     cvs      3257:      lost_update_check = FALSE;
1.168     cvs      3258: 
                   3259:    UsePreconditions = mode & AMAYA_USE_PRECONDITIONS;
1.4       cvs      3260: 
1.33      cvs      3261:    AmayaLastHTTPErrorMsg [0] = EOS;
1.256     kahan    3262:    AmayaLastHTTPErrorMsgR [0] = EOS;
                   3263: 
1.33      cvs      3264:    
1.116     cvs      3265:    if (urlName == NULL || docid == 0 || fileName == NULL 
                   3266:        || !TtaFileExist (fileName))
1.4       cvs      3267:       /* no file to be uploaded */
                   3268:       return HT_ERROR;
                   3269: 
                   3270:    /* do we support this protocol? */
1.7       cvs      3271:    if (IsValidProtocol (urlName) == NO)
                   3272:      {
                   3273:        /* return error */
1.198     cvs      3274:        TtaSetStatus (docid, 1, TtaGetMessage (AMAYA, AM_PUT_UNSUPPORTED_PROTOCOL), urlName);
1.7       cvs      3275:        return HT_ERROR;
                   3276:      }
1.116     cvs      3277: 
1.228     cvs      3278:    /* get the size of the file */
1.252     kahan    3279:    if (!AM_GetFileSize (fileName, &file_size) || file_size == 0L)
1.7       cvs      3280:      {
                   3281:        /* file was empty */
                   3282:        /*errmsg here */
                   3283:        return (HT_ERROR);
                   3284:      }
1.116     cvs      3285: 
                   3286:    /* prepare the request context */
1.4       cvs      3287:    if (THD_TRACE)
1.228     cvs      3288:       fprintf (stderr, "file size == %u\n", (unsigned) file_size);
1.4       cvs      3289: 
                   3290:    me = AHTReqContext_new (docid);
1.7       cvs      3291:    if (me == NULL)
                   3292:      {
1.168     cvs      3293:        /* @@ need an error message here */
1.151     cvs      3294:        TtaHandlePendingEvents (); 
1.7       cvs      3295:        return (HT_ERROR);
1.208     cvs      3296:      }
                   3297: 
                   3298:    /*
                   3299:    ** Set up the original URL name
                   3300:    */
1.285     kahan    3301: 
                   3302:    /* are we using content-location? */
                   3303:    if (DocumentMeta[docid]->content_location)
                   3304:      resource_name = DocumentMeta[docid]->content_location;
                   3305:    else
                   3306:      resource_name = NULL;
                   3307: 
                   3308:    /* prepare the target URL */
                   3309:    if (resource_name)
1.208     cvs      3310:      {
1.285     kahan    3311:        tmp = strstr (urlName, resource_name);     
                   3312:        if (!tmp)
1.208     cvs      3313:         {
1.285     kahan    3314:           /* urlName does not include the resource name */
                   3315:           me->default_put_name = TtaGetMemory (strlen (urlName)
                   3316:                                                + strlen (resource_name)
                   3317:                                                + sizeof (URL_SEP)
                   3318:                                                + 1);
                   3319:           strcpy (me->default_put_name, urlName);
                   3320:           tmp = strrchr (me->default_put_name, URL_SEP);
                   3321:           if (tmp)
1.208     cvs      3322:             {
1.285     kahan    3323:               /* it is a URL finishing in /. Only add the resrouce name */
                   3324:               tmp++;
                   3325:               strcpy (tmp, resource_name);
                   3326:             }
                   3327:           else
                   3328:             {
                   3329:               strcat (me->default_put_name, URL_STR);
                   3330:               strcat (me->default_put_name, resource_name);
1.208     cvs      3331:             }
                   3332:         }
1.7       cvs      3333:      }
1.285     kahan    3334:    
                   3335:    if (!me->default_put_name)
1.271     kahan    3336:      me->default_put_name = TtaStrdup (urlName);
                   3337:    
1.285     kahan    3338:    HTRequest_setDefaultPutName (me->request, me->default_put_name);
1.116     cvs      3339: 
1.4       cvs      3340:    me->mode = mode;
                   3341:    me->incremental_cbf = (TIcbf *) NULL;
                   3342:    me->context_icbf = (void *) NULL;
                   3343:    me->terminate_cbf = terminate_cbf;
                   3344:    me->context_tcbf = context_tcbf;
1.286     kahan    3345: 
                   3346:    /* normalize the URL */
1.300     kahan    3347:    esc_url = EscapeURL (urlName);
1.272     cvs      3348:    me->urlName = TtaStrdup (esc_url);
1.206     cvs      3349:    TtaFreeMemory (esc_url);
1.300     kahan    3350: 
1.228     cvs      3351:    me->block_size =  file_size;
1.17      cvs      3352:    /* select the parameters that distinguish a PUT from a GET/POST */
1.4       cvs      3353:    me->method = METHOD_PUT;
                   3354:    me->output = stdout;
1.17      cvs      3355:    /* we are not expecting to receive any input from the server */
1.265     cvs      3356:    me->outputfile = (char  *) NULL; 
1.4       cvs      3357: 
1.134     cvs      3358: #ifdef _WINDOWS
                   3359:    /* libwww's HTParse function doesn't take into account the drive name;
1.168     cvs      3360:       so we sidestep it */
1.238     cvs      3361: 
1.134     cvs      3362:    fileURL = NULL;
                   3363:    StrAllocCopy (fileURL, "file:");
1.273     cvs      3364:    strcpy (file_name, fileName);
1.235     cvs      3365:    StrAllocCat (fileURL, file_name);
1.134     cvs      3366: #else
1.116     cvs      3367:    fileURL = HTParse (fileName, "file:/", PARSE_ALL);
1.134     cvs      3368: #endif /* _WINDOWS */
1.168     cvs      3369:    me->source = HTAnchor_findAddress (fileURL);
1.116     cvs      3370:    HT_FREE (fileURL);
1.273     cvs      3371:    strcpy (url_name, me->urlName);
1.235     cvs      3372:    me->dest = HTAnchor_findAddress (url_name);
1.169     cvs      3373:    /* we memorize the anchor's parent @ as we use it a number of times
                   3374:       in the following lines */
                   3375:    dest_anc_parent = HTAnchor_parent (me->dest);
1.168     cvs      3376: 
1.169     cvs      3377:    /*
                   3378:    **  Set the Content-Type of the file we are uploading 
                   3379:    */
                   3380:    /* we try to use any content-type previosuly associated
                   3381:       with the parent. If it doesn't exist, we try to guess it
                   3382:       from the URL */
1.276     kahan    3383:    /* @@ JK: trying to use the content type we stored */
                   3384:    /*
1.235     cvs      3385:    tmp2 = HTAtom_name (HTAnchor_format (dest_anc_parent));
1.276     kahan    3386:    */
                   3387:    tmp2 = NULL;
1.235     cvs      3388:    if (!tmp2 || !strcmp (tmp2, "www/unknown"))
1.169     cvs      3389:      {
1.260     kahan    3390:        HTAtom *tmp_atom;
1.276     kahan    3391:        
1.260     kahan    3392:        tmp_atom = AHTGuessAtom_for (me->urlName, contentType);
1.276     kahan    3393:        if (!tmp_atom || !strcmp (HTAtom_name (tmp_atom), "www/unknown"))
                   3394:         {
                   3395:           /* ask the user for a MIME type */
                   3396:         }
1.260     kahan    3397:        HTAnchor_setFormat (dest_anc_parent, tmp_atom);
1.235     cvs      3398:        tmp2 = HTAtom_name (HTAnchor_format (dest_anc_parent));
1.169     cvs      3399:      }
                   3400:    /* .. and we give the same type to the source anchor */
                   3401:    /* we go thru setOutputFormat, rather than change the parent's
                   3402:       anchor, as that's the place that libwww expects it to be */
1.235     cvs      3403:    HTAnchor_setFormat (HTAnchor_parent (me->source), HTAtom_for (tmp2));
1.219     cvs      3404: 
1.235     cvs      3405:    HTRequest_setOutputFormat (me->request, HTAtom_for (tmp2));
1.219     cvs      3406: 
                   3407:    /*
                   3408:    **  Set the Charset of the file we are uploading 
                   3409:    */
1.240     cvs      3410:    /* we set the charset as indicated in the document's metadata
                   3411:       structure (and only if it exists) */
1.250     cvs      3412:    charset = TtaGetDocumentCharset (docid);
                   3413:    if (charset != UNDEFINED_CHARSET)
1.240     cvs      3414:      {
1.250     cvs      3415:        tmp =  TtaGetCharsetName (charset);
1.272     cvs      3416:        if (tmp && *tmp != EOS)
1.250     cvs      3417:         {
1.273     cvs      3418:           tmp2 = TtaStrdup (tmp);
1.250     cvs      3419:           HTAnchor_setCharset (dest_anc_parent, HTAtom_for (tmp2));
                   3420:           TtaFreeMemory (tmp2);
                   3421:           tmp2 = HTAtom_name (HTAnchor_charset (dest_anc_parent));
                   3422:           /* .. and we give the same charset to the source anchor */
                   3423:           /* we go thru setCharSet, rather than change the parent's
                   3424:              anchor, as that's the place that libwww expects it to be */
                   3425:           HTAnchor_setCharset (HTAnchor_parent (me->source),
                   3426:                                HTAtom_for (tmp2));
                   3427:         }
1.219     cvs      3428:      }
                   3429: 
                   3430:    /*
                   3431:    ** define other request characteristics
                   3432:    */
1.116     cvs      3433: #ifdef _WINDOWS
1.136     cvs      3434:    HTRequest_setPreemptive (me->request, NO);
1.116     cvs      3435: #else
1.134     cvs      3436:    HTRequest_setPreemptive (me->request, NO);
1.116     cvs      3437: #endif /* _WINDOWS */
                   3438: 
1.151     cvs      3439:    /*
                   3440:    ** Make sure that the first request is flushed immediately and not
                   3441:    ** buffered in the output buffer
                   3442:    */
                   3443:    if (mode & AMAYA_FLUSH_REQUEST)
                   3444:      HTRequest_setFlush(me->request, YES);
1.168     cvs      3445:    
                   3446:    /* Should we use preconditions? */
1.172     cvs      3447:    if (lost_update_check)
1.168     cvs      3448:      {
1.172     cvs      3449:        if (UsePreconditions) 
                   3450:         etag = HTAnchor_etag (HTAnchor_parent (me->dest));
                   3451:        
                   3452:        if (etag) 
                   3453:         {
                   3454:           HTRequest_setPreconditions(me->request, HT_MATCH_THIS);
                   3455:         }
                   3456:        else
                   3457:         {
                   3458:           HTRequest_setPreconditions(me->request, HT_NO_MATCH);
                   3459:           HTRequest_addAfter(me->request, check_handler, NULL, NULL, HT_ALL,
                   3460:                              HT_FILTER_MIDDLE, YES);
1.175     cvs      3461:           HTRequest_addAfter (me->request, HTAuthFilter, "http://*", NULL, 
                   3462:                               HT_NO_ACCESS, HT_FILTER_MIDDLE, YES);
                   3463:           HTRequest_addAfter (me->request, HTAuthFilter, "http://*", NULL,
                   3464:                               HT_REAUTH, HT_FILTER_MIDDLE, YES);
                   3465:           HTRequest_addAfter (me->request, HTAuthInfoFilter, "http://*", NULL,
                   3466:                               HT_ALL, HT_FILTER_MIDDLE, YES);
                   3467:           HTRequest_addAfter (me->request, HTUseProxyFilter, "http://*", NULL,
                   3468:                               HT_USE_PROXY, HT_FILTER_MIDDLE, YES);
1.172     cvs      3469:         }
1.168     cvs      3470:      }
                   3471:    else
                   3472:      {
1.172     cvs      3473:        /* don't use preconditions */
1.168     cvs      3474:        HTRequest_setPreconditions(me->request, HT_NO_MATCH);
                   3475:      }
1.151     cvs      3476:    
1.136     cvs      3477:    /* don't use the cache while saving a document */
                   3478:    HTRequest_setReloadMode (me->request, HT_CACHE_FLUSH);
1.116     cvs      3479: 
1.164     cvs      3480:    /* Throw away any reponse body */
                   3481:    /*
                   3482:    HTRequest_setOutputStream (me->request, HTBlackHole());        
                   3483:    */
                   3484: 
1.168     cvs      3485:    /* prepare the URLname that will be displayed in the status bar */
1.74      cvs      3486:    ChopURL (me->status_urlName, me->urlName);
1.233     cvs      3487:    TtaSetStatus (me->docid, 1, TtaGetMessage (AMAYA, AM_REMOTE_SAVING), me->status_urlName);
1.114     cvs      3488: 
1.297     kirschpi 3489:    
                   3490: #ifdef DAV
1.302     kirschpi 3491:    /* MKP: for a PUT request, try to add an "If" header (lock information)
1.297     kirschpi 3492:     * for a HEAD request, leave this for check_handler */
                   3493:    if ( !(lost_update_check && (!UsePreconditions || !etag)) )
                   3494:        DAVAddIfHeader (me,HTAnchor_address(me->dest));   
1.302     kirschpi 3495: #endif /* DAV */
1.297     kirschpi 3496: 
                   3497:    
1.164     cvs      3498:    /* make the request */
1.172     cvs      3499:    if (lost_update_check && (!UsePreconditions || !etag))
1.168     cvs      3500:      status = HTHeadAnchor (me->dest, me->request);
                   3501:    else
                   3502:      status = HTPutDocumentAnchor (HTAnchor_parent (me->source), me->dest, me->request);
1.4       cvs      3503: 
1.130     cvs      3504:    if (status == YES && me->reqStatus != HT_ERR)
1.7       cvs      3505:      {
1.168     cvs      3506:        /* part of the stop button handler */
                   3507:        if ((mode & AMAYA_SYNC) || (mode & AMAYA_ISYNC))
                   3508:         status = LoopForStop (me);
1.15      cvs      3509:      }
1.136     cvs      3510:    if (!HTRequest_kill (me->request))
                   3511:      AHTReqContext_delete (me);
1.168     cvs      3512:    
1.116     cvs      3513:    TtaHandlePendingEvents ();
1.90      cvs      3514: 
1.130     cvs      3515:    return (status == YES ? 0 : -1);
1.28      cvs      3516: }
1.4       cvs      3517: 
1.5       cvs      3518: /*----------------------------------------------------------------------
1.138     cvs      3519:   StopRequest
1.17      cvs      3520:   stops (kills) all active requests associated with a docid 
1.5       cvs      3521:   ----------------------------------------------------------------------*/
1.4       cvs      3522: void                StopRequest (int docid)
                   3523: {
1.140     cvs      3524:    if (Amaya && CanDoStop ())
1.138     cvs      3525:      { 
1.139     cvs      3526: #if 0 /* for later */
1.140     cvs      3527:        AHTDocId_Status    *docid_status;
                   3528:         /* verify if there are any requests at all associated with docid */
1.138     cvs      3529:        docid_status = (AHTDocId_Status *) GetDocIdStatus (docid,
                   3530:                                                          Amaya->docid_status);
                   3531:        if (docid_status == (AHTDocId_Status *) NULL)
                   3532:         return;
1.139     cvs      3533: #endif /* 0 */
1.138     cvs      3534:        /* temporary call to stop all requests, as libwww changed its API */
                   3535:        StopAllRequests (docid);
                   3536:      }
                   3537: }
                   3538: 
1.190     cvs      3539: /* @@@ the docid parameter isn't used... clean it up */
1.138     cvs      3540: /*----------------------------------------------------------------------
                   3541:   StopAllRequests
                   3542:   stops (kills) all active requests. We use the docid 
                   3543:   ----------------------------------------------------------------------*/
                   3544: void                StopAllRequests (int docid)
                   3545: {
1.4       cvs      3546:    HTList             *cur;
                   3547:    AHTReqContext      *me;
1.191     cvs      3548:    static ThotBool     lock_stop = 0;
                   3549:    ThotBool            async_flag;
1.232     cvs      3550:    AHTReqStatus        old_reqStatus;
1.116     cvs      3551: 
1.138     cvs      3552:    /* only do the stop if we're not being called while processing a 
1.146     cvs      3553:       request, and if we're not already dealing with a stop */
                   3554:    if (Amaya && CanDoStop () && !lock_stop)
1.7       cvs      3555:      {
1.100     cvs      3556: #ifdef DEBUG_LIBWWW
1.138     cvs      3557:        fprintf (stderr, "StopRequest: number of Amaya requests "
                   3558:                "before kill: %d\n", Amaya->open_requests);
1.100     cvs      3559: #endif /* DEBUG_LIBWWW */
1.150     cvs      3560:        /* enter the critical section */
1.146     cvs      3561:        lock_stop = TRUE; 
1.214     cvs      3562:        /* set a module global variable so that we can do special
                   3563:          processing easier */
                   3564:        UserAborted_flag = TRUE;
1.232     cvs      3565:        /* abort all outstanding libwww UI dialogues */
1.265     cvs      3566:        CallbackDialogue (BaseDialog + FormAnswer,  STRING_DATA, NULL);
                   3567:        CallbackDialogue (BaseDialog + ConfirmForm, INTEGER_DATA, NULL);
1.164     cvs      3568:        /* expire all outstanding timers */
                   3569:        HTTimer_expireAll ();
1.160     cvs      3570:        /* HTNet_killAll (); */
1.245     kahan    3571:        if (Amaya->open_requests)
1.116     cvs      3572:         {
1.245     kahan    3573:           cur = Amaya->reqlist;
                   3574:           while ((me = (AHTReqContext *) HTList_nextObject (cur))) 
1.160     cvs      3575:             {
1.245     kahan    3576:               if (AmayaIsAlive ())
                   3577:                 {
1.161     cvs      3578: #ifdef DEBUG_LIBWWW
1.245     kahan    3579:                   fprintf (stderr,"StopRequest: killing req %p, url %s, status %d\n", me, me->urlName, me->reqStatus);
1.161     cvs      3580: #endif /* DEBUG_LIBWWW */
1.245     kahan    3581:                   
                   3582:                   if (me->reqStatus != HT_END && me->reqStatus != HT_ABORT)
1.163     cvs      3583:                     {
1.245     kahan    3584:                       if ((me->mode & AMAYA_ASYNC)
                   3585:                           || (me->mode & AMAYA_IASYNC))
                   3586:                         async_flag = TRUE;
                   3587:                       else
                   3588:                         async_flag = FALSE;
                   3589:                       
                   3590:                       /* change the status to say that the request aborted */
                   3591:                       /* if the request was "busy", we just change a flag to say so and
                   3592:                          let the handler finish the processing itself */
                   3593:                       old_reqStatus = me->reqStatus;
                   3594:                       me->reqStatus = HT_ABORT;
                   3595:                       if (old_reqStatus == HT_BUSY)
                   3596:                         continue;
                   3597:                       
                   3598:                       /* kill the request, using the appropriate function */
                   3599:                       if (me->request->net)
                   3600:                         HTNet_killPipe (me->request->net);
                   3601:                       else
                   3602:                         {
                   3603:                           if (me->terminate_cbf)
                   3604:                             (*me->terminate_cbf) (me->docid, -1, me->urlName,
                   3605:                                                   me->outputfile,
                   3606:                                                   NULL,
                   3607:                                                   me->context_tcbf);
                   3608:                           
                   3609:                           if (async_flag) 
                   3610:                             /* explicitly free the request context for async
                   3611:                                requests. The sync requests context is freed
                   3612:                                by LoopForStop */
                   3613:                             AHTReqContext_delete (me);
                   3614:                         }
                   3615:                       cur = Amaya->reqlist;
1.160     cvs      3616:                     }
1.142     cvs      3617: #ifndef _WINDOWS
                   3618: #ifdef WWW_XWINDOWS
1.245     kahan    3619:                   /* to be on the safe side, remove all outstanding 
                   3620:                      X events */
1.160     cvs      3621:                   else 
                   3622:                     RequestKillAllXtevents (me);
1.142     cvs      3623: #endif /* WWW_XWINDOWS */
                   3624: #endif /* !_WINDOWS */
1.245     kahan    3625:                 }
1.160     cvs      3626:             }
1.245     kahan    3627:           /* Delete remaining channels */
                   3628:           HTChannel_safeDeleteAll ();
1.116     cvs      3629:         }
1.214     cvs      3630:        /* reset the stop status */
                   3631:        UserAborted_flag = FALSE;
1.150     cvs      3632:        /* exit the critical section */
1.148     cvs      3633:        lock_stop = FALSE; 
1.100     cvs      3634: #ifdef DEBUG_LIBWWW
1.138     cvs      3635:        fprintf (stderr, "StopRequest: number of Amaya requests "
                   3636:                "after kill: %d\n", Amaya->open_requests);
1.100     cvs      3637: #endif /* DEBUG_LIBWWW */
1.138     cvs      3638:      }
                   3639: } /* StopAllRequests */
1.17      cvs      3640: 
                   3641: 
1.105     cvs      3642: /*----------------------------------------------------------------------
                   3643:   AmayaIsAlive
1.140     cvs      3644:   returns the value of the AmayaAlive_flag
1.105     cvs      3645:   ----------------------------------------------------------------------*/
1.191     cvs      3646: ThotBool AmayaIsAlive (void)
1.105     cvs      3647: {
1.140     cvs      3648:   return AmayaAlive_flag;
                   3649: }
                   3650: 
                   3651: /*----------------------------------------------------------------------
                   3652:   CanDoStop
                   3653:   returns the value of the CanDoStop flag
                   3654:   ----------------------------------------------------------------------*/
1.191     cvs      3655: ThotBool CanDoStop (void)
1.140     cvs      3656: {
                   3657:   return CanDoStop_flag;
                   3658: }
                   3659: 
                   3660: /*----------------------------------------------------------------------
                   3661:   CanDoStop_set
                   3662:   sets the value of the CanDoStop flag
                   3663:   ----------------------------------------------------------------------*/
1.191     cvs      3664: void CanDoStop_set (ThotBool value)
1.140     cvs      3665: {
                   3666:   CanDoStop_flag = value;
1.176     cvs      3667: }
                   3668: 
1.265     cvs      3669: /*----------------------------------------------------------------------
                   3670:   ----------------------------------------------------------------------*/
1.176     cvs      3671: void libwww_updateNetworkConf (int status)
                   3672: {
                   3673:   /* @@@ the docid parameter isn't used... clean it up */
                   3674:   int docid = 1;
                   3675: 
                   3676:   /* first, stop all current requests, as the network
                   3677:    may make some changes */
                   3678:   StopAllRequests (docid);
1.207     cvs      3679: 
                   3680:   if (status & AMAYA_SAFEPUT_RESTART)
                   3681:     { 
                   3682:       SafePut_delete ();
                   3683:       SafePut_init ();
                   3684:     }
1.176     cvs      3685: 
                   3686:   if (status & AMAYA_PROXY_RESTART)
                   3687:     {
                   3688:       HTProxy_deleteAll ();
                   3689:       ProxyInit ();
                   3690:     }
                   3691: 
                   3692:   if (status & AMAYA_CACHE_RESTART)
                   3693:     {
                   3694:       clear_cachelock ();
                   3695:       HTCacheTerminate ();
                   3696:       HTCacheMode_setEnabled (NO);
                   3697:       CacheInit ();
                   3698:     }
1.193     cvs      3699: 
                   3700:   if (status & AMAYA_LANNEG_RESTART)
                   3701:     {
                   3702:       /* clear the current values */
                   3703:       if (acceptLanguages)
                   3704:        HTLanguage_deleteAll (acceptLanguages);
                   3705:       /* read in the new ones */
                   3706:       acceptLanguages = HTList_new ();
                   3707:       AHTAcceptLanguagesInit (acceptLanguages);
                   3708:     }
1.105     cvs      3709: }
1.246     kahan    3710: 
                   3711: /****************************************************************************
                   3712:  ** The following two functions allow to set and read the value of          *
                   3713:  ** the  FTPURL_flag. If this flag is true, it means we can browse FTP URLs *
                   3714:  ***************************************************************************/
                   3715: 
                   3716: /*----------------------------------------------------------------------
                   3717:   AHT_FTPURL_flag_set
                   3718:   ----------------------------------------------------------------------*/
                   3719: void AHTFTPURL_flag_set (ThotBool value)
                   3720: {
                   3721:   FTPURL_flag = value;
                   3722: }
                   3723: 
                   3724: /*----------------------------------------------------------------------
                   3725:   AHT_FTPURL_flag
                   3726:   ----------------------------------------------------------------------*/
                   3727: ThotBool AHTFTPURL_flag (void)
                   3728: {
                   3729:   return (FTPURL_flag);
                   3730: }
1.308     kahan    3731: 
                   3732: 
                   3733: /*----------------------------------------------------------------------
                   3734:   CheckSingleInstance
                   3735:   Returns TRUE if this is the single instance of Amaya in the system,
                   3736:   FALSE otherwise. 
                   3737:   N.B. : This implementation is naif.
                   3738:   ----------------------------------------------------------------------*/
                   3739: ThotBool CheckSingleInstance (char *pid_dir)
                   3740: {
                   3741: #ifdef _WINDOWS
                   3742:   HWND hwnd;
                   3743: 
1.310     cvs      3744:   hwnd = FindWindow ("Amaya", NULL);
1.308     kahan    3745: 
                   3746:   if (!hwnd)
                   3747:     return TRUE;
                   3748:   else
                   3749:     return FALSE;
                   3750: 
                   3751: #else /* _WINDOWS */
                   3752: 
                   3753:   int instances;
                   3754:   char *ptr;
                   3755:   pid_t pid;
                   3756: 
                   3757:   DIR *dp;
                   3758:   struct stat st;
                   3759: #ifdef HAVE_DIRENT_H
                   3760:   struct dirent *d;
                   3761: #else
                   3762:   struct direct *d;
                   3763: #endif /* HAVE_DIRENT_H */
                   3764:   char filename[BUFSIZ+1];
                   3765: 
                   3766:   if ((dp = opendir (pid_dir)) == NULL) 
                   3767:     {
                   3768:       /* @@@ we couldn't open the directory ... we need some msg */
                   3769:       perror (pid_dir);
                   3770:       return FALSE;
                   3771:     }
                   3772: 
                   3773:   instances = 0;
                   3774: 
                   3775:   while ((d = readdir (dp)) != NULL)
                   3776:     {
                   3777:       /* skip the UNIX . and .. links */
                   3778:       if (!strcmp (d->d_name, "..")
                   3779:          || !strcmp (d->d_name, "."))
                   3780:        continue;
                   3781: 
                   3782:       sprintf (filename, "%s%c%s", pid_dir, DIR_SEP, d->d_name);
                   3783:       if  (lstat (filename, &st) < 0 ) 
                   3784:        {
                   3785:          /* @@2 need some error message */
                   3786:          perror (filename);
                   3787:          continue;
                   3788:        }
                   3789:       
                   3790:       switch (st.st_mode & S_IFMT)
                   3791:        {
                   3792:        case S_IFDIR:
                   3793:        case S_IFLNK:
                   3794:          /* skip any links and directories that we find */
                   3795:          continue;
                   3796:          break;
                   3797:        default:
                   3798:          /* check if this pid exists. If not, erase it */
                   3799:          ptr = strrchr (filename, DIR_SEP);
                   3800:          if (!ptr) 
                   3801:            continue;
                   3802:          sscanf (ptr, DIR_STR"%d", &pid);
                   3803:          if (kill (pid, 0) == -1)
                   3804:            {
                   3805:              /* erase the stale pid file */
                   3806:              TtaFileUnlink (filename);
                   3807:            }
                   3808:          else /* we found one live instance */
                   3809:            {
                   3810:              instances++;
                   3811:            }
                   3812:          break;
                   3813:        }
                   3814:     }
                   3815:   closedir (dp);
                   3816:   return (instances == 0);
                   3817: #endif /* !_WINDOWS */
                   3818: }
                   3819: 
                   3820: /*----------------------------------------------------------------------
                   3821:   FreeAmayaCache 
                   3822:   ----------------------------------------------------------------------*/
                   3823: void FreeAmayaCache (void)
                   3824: {
                   3825: #ifndef _WINDOWS
                   3826:   char str[MAX_LENGTH];
                   3827:   pid_t pid;
                   3828: 
                   3829:   /* unregister this instance of Amaya */
                   3830:   pid = getpid ();
                   3831:   sprintf (str, "%s/pid/%d", TempFileDirectory, pid);
                   3832:   if (TtaFileExist (str))
                   3833:     TtaFileUnlink (str);
                   3834: #endif /* _WINDOWS */
                   3835: }
                   3836: 
                   3837: /*----------------------------------------------------------------------
                   3838:   InitAmayaCache 
                   3839:   Create the temporary sub-directories for storing the HTML and
                   3840:   other downloaded files.
                   3841:   ----------------------------------------------------------------------*/
                   3842: void InitAmayaCache (void)
                   3843: {
                   3844:   ThotBool can_erase;
                   3845:   int i;
                   3846:   char str[MAX_LENGTH];
                   3847:   char *ptr;
1.309     cvs      3848: #ifndef _WINDOWS
1.308     kahan    3849:   pid_t pid;
                   3850:   int fd_pid;
1.309     cvs      3851: #endif /* _WINDOWS */
1.308     kahan    3852: 
                   3853: #ifndef _WINDOWS
                   3854:   /* create the temp dir for the Amaya pid */
                   3855:   sprintf (str, "%s%cpid", TempFileDirectory, DIR_SEP);
                   3856:   TtaMakeDirectory (str);
                   3857: #endif
                   3858: 
                   3859:   /* protection against dir names that have . in them to avoid
                   3860:      erasing everything  by accident */
                   3861:   ptr = TempFileDirectory;
                   3862:   can_erase = TRUE;
                   3863:   while (*ptr && can_erase)
                   3864:     {
                   3865:       if (*ptr == '.')
                   3866:        {
                   3867:          if (*(ptr + 1) == '.')
                   3868:            can_erase = FALSE;
                   3869:          else
                   3870:            ptr++;
                   3871:          continue;
                   3872:        }
                   3873:       else if (*ptr == '~')
                   3874:        can_erase = FALSE;
                   3875:       else if (!isalnum (*ptr) && *ptr != DIR_SEP && *ptr != ':')
                   3876:        can_erase = FALSE;
                   3877:       ptr++;
                   3878:     }
                   3879: 
                   3880:   if (can_erase && CheckSingleInstance (str))
                   3881:     {
                   3882:       /* Erase the previous directories */
                   3883:       for (i = 0; i < DocumentTableLength; i++)
                   3884:        {      
                   3885:          sprintf (str, "%s%c%d%c", TempFileDirectory, DIR_SEP, i, DIR_SEP);
                   3886:          RecCleanCache (str);
                   3887:        }
                   3888:     }
                   3889: 
                   3890:   /* create the temporary cache directories if they don't exit*/
                   3891:   for (i = 0; i < DocumentTableLength; i++)
                   3892:     {      
                   3893:       sprintf (str, "%s%c%d", TempFileDirectory, DIR_SEP, i);
                   3894:       TtaMakeDirectory (str);
                   3895:     }
                   3896: 
                   3897: #ifndef _WINDOWS
                   3898:   /* register this instance of Amaya */
                   3899:   pid = getpid ();
                   3900:   sprintf (str, "%s/pid/%d", TempFileDirectory, pid);
                   3901:   fd_pid = open (str, O_CREAT, S_IRUSR | S_IWUSR );
                   3902:   if (fd_pid != -1)
                   3903:     close (fd_pid);
                   3904:   else
                   3905:     printf ("Couldn't create fd_pid %s\n", str);
                   3906: #endif /* _WINDOWS */
                   3907: }

Webmaster