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

1.14      cvs         1: /*
                      2:  *
1.317   ! vatton      3:  *  (c) COPYRIGHT INRIA and W3C, 1996-2003
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)
1.316     vatton   1096:        {
1.315     vatton   1097:          /* @@@@ IV */
1.316     vatton   1098:          (*prompt) (request, HT_A_CONFIRM, status, NULL, NULL, NULL);
                   1099:          force_put = NO;
                   1100:        }
1.315     vatton   1101:       else
                   1102:        force_put = (*prompt) (request, HT_A_CONFIRM, HT_MSG_RULES,
                   1103:                               NULL, NULL, NULL);
                   1104:     }
1.168     cvs      1105:   else
                   1106:     force_put = NO;
                   1107:   
                   1108:   if (force_put)
                   1109:     {
1.297     kirschpi 1110: #ifdef DAV
                   1111:       BOOL noIf = NO;
                   1112: 
                   1113:       /* MKP: if the old request has preconditions, *
                   1114:        * then, we supose that these preconditions   *
                   1115:        * caused the 412 Precondition Failed status  *
                   1116:        * code, otherwise we supose that the cause   *
                   1117:        * was an eventual If header.                 */
1.315     vatton   1118:       if (HTRequest_preconditions(me->request) != HT_NO_MATCH)
1.297     kirschpi 1119:           noIf = NO;
                   1120:       else
                   1121:           noIf = YES;      
1.302     kirschpi 1122: #endif /* DAV */
1.297     kirschpi 1123:       
                   1124:       
1.168     cvs      1125:       /* start a new PUT request without preconditions */
                   1126:       /* @@ do we need to kill the request? */
                   1127:       if (me->output && me->output != stdout)
                   1128:        {
                   1129:          fclose (me->output);
                   1130:          me->output = NULL;
                   1131:        }
                   1132:       /*
                   1133:       ** reset the Amaya and libwww request status 
                   1134:       */
1.176     cvs      1135: 
                   1136:       /* start with a new, clean request structure */
                   1137:       HTRequest_delete (me->request);
                   1138:       me->request = HTRequest_new ();
                   1139:       /* clean the associated file structure) */
                   1140:       HTRequest_setOutputStream (me->request, NULL);
                   1141:       /* Initialize the other members of the structure */
1.171     cvs      1142:       HTRequest_setMethod (me->request, METHOD_GET);
1.176     cvs      1143:       HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                   1144:       HTRequest_setContext (me->request, me);
                   1145:       HTRequest_setPreemptive (me->request, NO);
                   1146:       /*
                   1147:       ** Make sure that the first request is flushed immediately and not
                   1148:       ** buffered in the output buffer
                   1149:       */
                   1150:       if (me->mode & AMAYA_FLUSH_REQUEST)
                   1151:        HTRequest_setFlush(me->request, YES);
                   1152: 
1.171     cvs      1153:       /* turn off preconditions */
                   1154:       HTRequest_setPreconditions(me->request, HT_NO_MATCH);
                   1155:       me->reqStatus = HT_NEW; 
1.297     kirschpi 1156: 
                   1157:       
                   1158: #ifdef DAV
1.302     kirschpi 1159:       /* MKP: add an If header (lock information) only 
                   1160:        * if there wasn't preconditions */
1.315     vatton   1161:       if (noIf != YES)
                   1162:        DAVAddIfHeader (me,HTAnchor_address(me->dest));
1.297     kirschpi 1163: #endif /* DAV */
                   1164:       
                   1165:       
1.171     cvs      1166:       /* make the request */      
1.176     cvs      1167:       status = HTPutDocumentAnchor (HTAnchor_parent (me->source), 
                   1168:                                    me->dest, me->request);
1.168     cvs      1169:       /* stop here */
                   1170:       return HT_ERROR;
                   1171:     }
                   1172:   else
                   1173:     {
                   1174:       /* abort the request */
                   1175:       /* @@ should we call StopRequest here? */
                   1176:       me->reqStatus = HT_ABORT;
                   1177:       /* stop here */
                   1178:       return HT_ERROR; 
                   1179:     }
                   1180: }
1.151     cvs      1181: 
1.168     cvs      1182: /*----------------------------------------------------------------------
                   1183:   check_handler
                   1184:   Request HEAD checker filter
                   1185:   ----------------------------------------------------------------------*/
                   1186: static int check_handler (HTRequest * request, HTResponse * response,
1.151     cvs      1187:                            void * param, int status)
                   1188: {
1.168     cvs      1189:   AHTReqContext  *me = (AHTReqContext *) HTRequest_context (request);
                   1190:   HTAlertCallback    *prompt = HTAlert_find (HT_A_CONFIRM);
1.191     cvs      1191:   ThotBool force_put;
1.168     cvs      1192: 
                   1193:   if (!me)
                   1194:     return HT_OK;              /* not an Amaya request */
                   1195: 
                   1196:   HTRequest_deleteAfter(me->request, check_handler);
                   1197:   /*
                   1198:   ** If head request showed that the document doesn't exist
                   1199:   ** then just go ahead and PUT it. Otherwise ask for help
                   1200:   */
                   1201:   if (status == HT_ERROR || status == HT_INTERRUPTED || status == HT_TIMEOUT)
                   1202:     {
                   1203:       /* we'd need to call terminate_handler, to free the resources */
                   1204:       /* abort the request */
                   1205:       /* @@ should we call StopRequest here? */
                   1206:       me->reqStatus = HT_ABORT;
                   1207:       /* stop here */
                   1208:       return HT_ERROR; 
                   1209:     } 
                   1210:   else if (status == HT_NO_ACCESS || status == HT_NO_PROXY_ACCESS) 
                   1211:     {
                   1212:       /* we'd need to call terminate_handler, to free the resources */
                   1213:       /* abort the request */
                   1214:       /* @@ should we call StopRequest here? */
                   1215:       me->reqStatus = HT_ABORT;
                   1216:       /* stop here */
                   1217:       return HT_ERROR; 
                   1218:     }
                   1219:   else if ( (abs(status)/100) != 2) 
                   1220:     {
1.176     cvs      1221:       /* start with a new, clean request structure */
                   1222:       HTRequest_delete (me->request);
                   1223:       me->request = HTRequest_new ();
1.208     cvs      1224:       /* add the default PUT name */
                   1225:       HTRequest_setDefaultPutName (me->request, me->default_put_name);
1.176     cvs      1226:       /* clean the associated file structure) */
                   1227:       HTRequest_setOutputStream (me->request, NULL);
                   1228:       /* Initialize the other members of the structure */
1.171     cvs      1229:       HTRequest_setMethod (me->request, METHOD_GET);
1.176     cvs      1230:       HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                   1231:       HTRequest_setContext (me->request, me);
                   1232:       HTRequest_setPreemptive (me->request, NO);
                   1233:       /*
                   1234:       ** Make sure that the first request is flushed immediately and not
                   1235:       ** buffered in the output buffer
                   1236:       */
                   1237:       if (me->mode & AMAYA_FLUSH_REQUEST)
                   1238:        HTRequest_setFlush(me->request, YES);
1.297     kirschpi 1239:    
                   1240: #ifdef DAV
1.302     kirschpi 1241:       /* MKP: try to add an "If" header (lock information) 
                   1242:        *      Such header will be added only if there is a
                   1243:        *      lock information in the local base. */
1.297     kirschpi 1244:       DAVAddIfHeader (me,me->urlName);   
1.302     kirschpi 1245: #endif /* DAV */
1.297     kirschpi 1246: 
1.176     cvs      1247: 
                   1248:       /* turn on the special preconditions, to avoid having this
                   1249:         ressource appear before we do the PUT */
1.168     cvs      1250:       HTRequest_setPreconditions(me->request, HT_DONT_MATCH_ANY);
1.171     cvs      1251:       me->reqStatus = HT_NEW;
1.168     cvs      1252:       status = HTPutDocumentAnchor (HTAnchor_parent (me->source), me->dest, me->request);
                   1253:       return HT_ERROR; /* stop here */
1.176     cvs      1254:     }
1.168     cvs      1255:   else 
                   1256:     {
                   1257:       if (prompt)
                   1258:          force_put = (*prompt) (request, HT_A_CONFIRM, HT_MSG_FILE_REPLACE,
                   1259:                                 NULL, NULL, NULL);
                   1260:       else
                   1261:        force_put = FALSE;
                   1262: 
                   1263:       if (force_put)
1.151     cvs      1264:        {
                   1265:          /* Start a new PUT request without preconditions */
1.176     cvs      1266: 
                   1267:          /* get a new, clean request structure */
                   1268:          HTRequest_delete (me->request);
                   1269:          me->request = HTRequest_new ();
1.208     cvs      1270:          /* add the default PUT name */
                   1271:          HTRequest_setDefaultPutName (me->request, me->default_put_name);
1.176     cvs      1272:          /* clean the associated file structure) */
                   1273:          HTRequest_setOutputStream (me->request, NULL);
                   1274:          /* Initialize the other members of the structure */
1.171     cvs      1275:          HTRequest_setMethod (me->request, METHOD_GET);
1.176     cvs      1276:          HTRequest_setOutputFormat (me->request, WWW_SOURCE);
                   1277:          HTRequest_setContext (me->request, me);
                   1278:          HTRequest_setPreemptive (me->request, NO);
1.297     kirschpi 1279:    
                   1280: #ifdef DAV
1.302     kirschpi 1281:          /* MKP: try to add an "If" header (lock information) 
                   1282:           *      Such header will be added only if there is a
                   1283:           *      lock information in the local base. */ 
1.297     kirschpi 1284:           DAVAddIfHeader (me,HTAnchor_address(me->dest));   
1.302     kirschpi 1285: #endif /* DAV */
                   1286: 
1.297     kirschpi 1287:          
1.176     cvs      1288:          /*
                   1289:          ** Make sure that the first request is flushed immediately and not
                   1290:          ** buffered in the output buffer
                   1291:          */
                   1292:          if (me->mode & AMAYA_FLUSH_REQUEST)
                   1293:            HTRequest_setFlush(me->request, YES);
                   1294:          /* remove the preconditions */
1.168     cvs      1295:          HTRequest_setPreconditions(me->request, HT_NO_MATCH);
1.171     cvs      1296:          me->reqStatus = HT_NEW; 
1.176     cvs      1297:          status = HTPutDocumentAnchor (HTAnchor_parent (me->source), 
                   1298:                                        me->dest, me->request);
1.168     cvs      1299:          return HT_ERROR; /* stop here */
1.151     cvs      1300:        } 
1.168     cvs      1301:       else
                   1302:        {
                   1303:          /* we'd need to call terminate_handler, to free the resources */
                   1304:          /* abort the request */
                   1305:          /* @@ should we call StopRequest here? */
                   1306:          me->reqStatus = HT_ABORT;
                   1307:          /* stop here */
                   1308:          return HT_ERROR; 
                   1309:        }
                   1310:     }
                   1311:   return HT_ERROR;
1.151     cvs      1312: }
                   1313: #endif /* AMAYA_LOST_UPDATE */
                   1314: 
1.5       cvs      1315: /*----------------------------------------------------------------------
1.17      cvs      1316:   terminate_handler
                   1317:   this function is registered to handle the result of the request
1.5       cvs      1318:   ----------------------------------------------------------------------*/
1.265     cvs      1319: static int terminate_handler (HTRequest *request, HTResponse *response,
                   1320:                              void *context, int status)
1.4       cvs      1321: {
1.116     cvs      1322:   AHTReqContext      *me = (AHTReqContext *) HTRequest_context (request);
1.191     cvs      1323:   ThotBool            error_flag;
1.116     cvs      1324: 
                   1325:   if (!me)
1.214     cvs      1326:      return HT_ERROR;          /* not an Amaya request */
1.116     cvs      1327: 
                   1328:   if (me->reqStatus == HT_END)
                   1329:     /* we have already processed this request! */
                   1330:     return HT_OK;
                   1331: 
                   1332:   /* if Amaya was killed, treat with this request as if it were
                   1333:      issued by a Stop button event */
                   1334: 
                   1335:    if (!AmayaIsAlive ())           
1.80      cvs      1336:       me->reqStatus = HT_ABORT; 
1.220     cvs      1337: 
                   1338:    /* trying to protect against this problem... hard to place
                   1339:       the detection elsewhere :-/ */
1.240     cvs      1340:    /* @@ JK: Is this still needed? */
1.220     cvs      1341:    if (IsHTTP09Error (request))
                   1342:      status = -1;
                   1343: 
1.238     cvs      1344:    if (status == HT_LOADED
                   1345:        || status == HT_CREATED
                   1346:        || status == HT_NO_DATA
1.249     kahan    1347:        /* JK: removed it as the kludge doesn't seem useful anymore */
1.160     cvs      1348:        /* kludge for work around libwww problem */
1.249     kahan    1349:        /* || (status == HT_INTERRUPTED && me->method == METHOD_PUT) */
1.116     cvs      1350: #ifdef AMAYA_WWW_CACHE
                   1351:        /* what status to use to know we're downloading from a cache? */
1.238     cvs      1352:        || status ==  HT_NOT_MODIFIED
                   1353:        || status == HT_PARTIAL_CONTENT
1.116     cvs      1354: #endif /* AMAYA_WWW_CACHE */
1.238     cvs      1355:        || me->reqStatus == HT_ABORT)
1.74      cvs      1356:      error_flag = FALSE;
1.297     kirschpi 1357: #ifdef DAV
                   1358:    else if (status == HT_LOCKED 
                   1359:            || status ==  HT_FAILED_DEPENDENCY 
1.302     kirschpi 1360:            || status == HT_MULTI_STATUS) 
                   1361:     {
1.297     kirschpi 1362:      /* WebDAV return codes - they are handled in
                   1363:       * specific filters. We don't need to deal
                   1364:       * with them anymore
                   1365:       */
                   1366:      error_flag = FALSE;          
1.302     kirschpi 1367:     }
                   1368: #endif   /* DAV */
1.256     kahan    1369:    else
1.74      cvs      1370:      error_flag = TRUE;
1.130     cvs      1371: 
1.285     kahan    1372:    /* If we did a PUT that was redirected, clean the original
                   1373:       cache entry */
                   1374:    if (status == 204 && me->method == METHOD_PUT && me->put_redirection)
                   1375:    {
                   1376:      HTCache * cache;
                   1377:      HTParentAnchor * anchor = HTAnchor_parent (me->dest);
                   1378:      cache = HTCache_find (anchor, NULL);
                   1379:      if (cache)
                   1380:        {
                   1381:         /* what a problem... we update the cache with the wrong data
                   1382:            from the response... after the redirection */
                   1383:         HTCache_resetMeta (cache, request, response);
                   1384:        }
                   1385:      else
                   1386:        /* If entry doesn't already exist then create a new entry */
                   1387:        HTCache_touch(request, response, HTAnchor_parent (me->dest));
                   1388:    }
                   1389: 
1.4       cvs      1390:    /* output any errors from the server */
1.130     cvs      1391: 
1.77      cvs      1392:    /*
1.74      cvs      1393:    ** me->output = output file which will receive an html file
                   1394:    ** me->error_html = yes, output HTML errors in the screen
                   1395:    ** request->error_stack == if there are any errors, they will be here
                   1396:    ** me->error_stream_size If it's != 0 means an error message has already
                   1397:    **                       been written to the stack
                   1398:    */
                   1399:    
1.4       cvs      1400:    /* First, we verify if there are any errors and if they are not
1.17      cvs      1401:    ** yet written to the error stack. If no, then let's try to write them
                   1402:    ** ourselves
                   1403:    */
1.74      cvs      1404:    
                   1405: #ifdef DEBUG_LIBWWW
                   1406:    fprintf (stderr, "terminate_handler: URL is "
                   1407:            "%s, closing FILE %p status is %d\n", me->urlName, me->output, 
                   1408:            status); 
1.69      cvs      1409: #endif
1.74      cvs      1410:    
1.69      cvs      1411:    if (me->output && me->output != stdout)
                   1412:      {
1.214     cvs      1413:        /* we are writing to a local file */
1.74      cvs      1414:        if (me->reqStatus != HT_ABORT)
                   1415:         {                      /* if the request was not aborted and */
1.80      cvs      1416:           if (error_flag &&
                   1417:               me->error_html == TRUE)
                   1418:               /* there were some errors and we want to print them */
                   1419:             {          
1.314     kahan    1420:               /* if the transfer was interrupted, the file may not be
                   1421:                  empty. So, we erase it */
                   1422:               fflush (me->output);
                   1423:               rewind (me->output);
                   1424: 
1.80      cvs      1425:               if (me->error_stream)
                   1426:                 {      /* if the stream is non-empty */
1.313     kahan    1427:                   fprintf (me->output, "%s", me->error_stream);/* output the errors */
1.85      cvs      1428:                   /* Clear the error context, so that we can deal with
                   1429:                      this answer as if it were a normal reply */
                   1430:                    HTError_deleteAll( HTRequest_error (request));
                   1431:                    HTRequest_setError (request, NULL);
                   1432:                    error_flag = 0;
1.74      cvs      1433:                 }
                   1434:             }                  /* if error_stack */
1.85      cvs      1435:         }
1.314     kahan    1436:        
1.85      cvs      1437:        /* if != HT_ABORT */
                   1438:        
                   1439: #ifdef DEBUG_LIBWWW       
                   1440:        fprintf (stderr, "terminate_handler: URL is  %s, closing "
                   1441:                "FILE %p\n", me->urlName, me->output); 
                   1442: #endif
1.74      cvs      1443:        fclose (me->output);
                   1444:        me->output = NULL;
1.69      cvs      1445:      }
1.80      cvs      1446: 
1.214     cvs      1447:    /* a very special handling so that we can put a message box
                   1448:       to tell the user WHAT he has just done... */
                   1449:    if (UserAborted_flag && me->method == METHOD_PUT)
                   1450:      {
                   1451:        HTRequest_addError (request, ERR_FATAL, NO, HTERR_INTERRUPTED,
                   1452:                           "Operation aborted by user", 0, NULL);
                   1453:      }
                   1454: 
1.80      cvs      1455:    if (error_flag)
                   1456:      me->reqStatus = HT_ERR;
1.214     cvs      1457:    else 
                   1458:      if (me->reqStatus != HT_ABORT)
                   1459:        me->reqStatus = HT_END;
1.154     cvs      1460: 
1.238     cvs      1461:    /* copy the headers in which the application is interested */
                   1462:    HTTP_headers_set (request, response, context, status);
1.114     cvs      1463: 
1.115     cvs      1464:    /* to avoid a hangup while downloading css files */
1.140     cvs      1465:    if (AmayaAlive_flag && (me->mode & AMAYA_LOAD_CSS))
1.265     cvs      1466:      TtaSetStatus (me->docid, 1,
                   1467:                   TtaGetMessage (AMAYA, AM_ELEMENT_LOADED),
                   1468:                   me->status_urlName);
1.116     cvs      1469:    
                   1470:   /* don't remove or Xt will hang up during the PUT */
                   1471:    if (AmayaIsAlive ()  && ((me->method == METHOD_POST) ||
                   1472:                            (me->method == METHOD_PUT)))
1.7       cvs      1473:      {
1.80      cvs      1474:        PrintTerminateStatus (me, status);
                   1475:      } 
1.114     cvs      1476: 
1.111     cvs      1477:    ProcessTerminateRequest (request, response, context, status);
1.116     cvs      1478:    
1.151     cvs      1479:    /* stop here */
1.150     cvs      1480:    return HT_ERROR;
1.4       cvs      1481: }
                   1482: 
1.5       cvs      1483: /*----------------------------------------------------------------------
1.17      cvs      1484:   AHTLoadTerminate_handler
1.74      cvs      1485:   this is an application "AFTER" Callback. It's called by the library
                   1486:   when a request has ended, so that we can setup the correct status.
1.5       cvs      1487:   ----------------------------------------------------------------------*/
1.265     cvs      1488: int AHTLoadTerminate_handler (HTRequest *request, HTResponse *response,
                   1489:                              void *param, int status)
1.4       cvs      1490: {
1.116     cvs      1491:   /** @@@@ use this with printstatus ?? */
1.4       cvs      1492:    AHTReqContext      *me = HTRequest_context (request);
                   1493:    HTAlertCallback    *cbf;
                   1494:    AHTDocId_Status    *docid_status;
                   1495: 
1.7       cvs      1496:    switch (status)
1.116     cvs      1497:      {
                   1498:         case HT_LOADED:
                   1499:           if (PROT_TRACE)
                   1500:             HTTrace ("Load End.... OK: `%s\' has been accessed\n",
                   1501:                      me->status_urlName);
1.4       cvs      1502: 
1.116     cvs      1503:           docid_status = GetDocIdStatus (me->docid,
                   1504:                                          Amaya->docid_status);
1.7       cvs      1505: 
1.116     cvs      1506:           if (docid_status != NULL && docid_status->counter > 1)
                   1507:             TtaSetStatus (me->docid, 1, 
                   1508:                           TtaGetMessage (AMAYA, AM_ELEMENT_LOADED),
1.233     cvs      1509:                           me->status_urlName);
1.7       cvs      1510:               break;
1.116     cvs      1511:               
                   1512:      case HT_NO_DATA:
                   1513:        if (PROT_TRACE)
                   1514:         HTTrace ("Load End.... OK BUT NO DATA: `%s\'\n", 
                   1515:                  me->status_urlName);
1.297     kirschpi 1516: #ifdef DAV      
1.302     kirschpi 1517:        if (me->method==METHOD_UNLOCK) 
                   1518:         {
                   1519:            /* MKP: set an appropriate status message */
1.297     kirschpi 1520:           TtaSetStatus (me->docid, 1, 
                   1521:                     TtaGetMessage (AMAYA, AM_UNLOCK_SUCCEED),
                   1522:                     NULL);
1.302     kirschpi 1523:         }
1.297     kirschpi 1524:        else
1.302     kirschpi 1525: #endif /* DAV */
1.297     kirschpi 1526:            TtaSetStatus (me->docid, 1, 
1.116     cvs      1527:                     TtaGetMessage (AMAYA, AM_LOADED_NO_DATA),
1.233     cvs      1528:                     me->status_urlName);
1.116     cvs      1529:        break;
                   1530:        
                   1531:      case HT_INTERRUPTED:
                   1532:        if (PROT_TRACE)
                   1533:         HTTrace ("Load End.... INTERRUPTED: `%s\'\n", 
                   1534:                  me->status_urlName);
                   1535:        TtaSetStatus (me->docid, 1, 
                   1536:                     TtaGetMessage (AMAYA, AM_LOAD_ABORT), 
                   1537:                     NULL);
                   1538:        break;
1.7       cvs      1539: 
1.116     cvs      1540:      case HT_RETRY:
                   1541:        if (PROT_TRACE)
                   1542:         HTTrace ("Load End.... NOT AVAILABLE, RETRY AT %ld\n",
                   1543:                  HTResponse_retryTime (response));
                   1544:        TtaSetStatus (me->docid, 1, 
                   1545:                     TtaGetMessage (AMAYA, AM_NOT_AVAILABLE_RETRY),
1.233     cvs      1546:                     me->status_urlName);
1.116     cvs      1547:        break;
1.7       cvs      1548: 
1.247     kahan    1549:      case HT_NOT_MODIFIED:
                   1550:        if (PROT_TRACE)
1.265     cvs      1551:         HTTrace ("Load End.... NOT MODIFIED (%s)",
                   1552:                  me->status_urlName ? me->status_urlName :" <UNKNOWN>");
1.247     kahan    1553:        break;
                   1554:        
1.116     cvs      1555:      case HT_ERROR:
                   1556:        cbf = HTAlert_find (HT_A_MESSAGE);
                   1557:        if (cbf)
                   1558:         (*cbf) (request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
                   1559:                 HTRequest_error (request), NULL);
1.247     kahan    1560:        if (PROT_TRACE)
1.265     cvs      1561:            HTTrace ("Load End.... ERROR: Can't access `%s\'\n",
                   1562:                    me->status_urlName ? me->status_urlName :"<UNKNOWN>"); 
                   1563:        TtaSetStatus (me->docid, 1,
                   1564:                     TtaGetMessage (AMAYA, AM_CANNOT_LOAD),
                   1565:                     me->status_urlName ? me->status_urlName : "<UNKNOWN>");
1.116     cvs      1566:        break;
1.247     kahan    1567: 
                   1568:      case HTERR_TIMEOUT:
                   1569:        cbf = HTAlert_find (HT_A_MESSAGE);
                   1570:        if (cbf)
                   1571:         (*cbf) (request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
                   1572:                 HTRequest_error (request), NULL);
1.116     cvs      1573:        if (PROT_TRACE)
1.265     cvs      1574:            HTTrace ("Load End.... REQUEST TIMEOUT: Can't access `%s\'\n",
                   1575:                    me->status_urlName ? me->status_urlName :"<UNKNOWN>"); 
                   1576:        TtaSetStatus (me->docid, 1, TtaGetMessage (AMAYA, AM_CANNOT_LOAD),
                   1577:                     me->status_urlName ? me->status_urlName : "<UNKNOWN>");
1.116     cvs      1578:        break;
1.247     kahan    1579: 
1.116     cvs      1580:      default:
                   1581:        if (PROT_TRACE)
                   1582:         HTTrace ("Load End.... UNKNOWN RETURN CODE %d\n", status);
                   1583:        break;
                   1584:      }
                   1585:    
                   1586:    return HT_OK;
                   1587: }
1.7       cvs      1588: 
1.248     kahan    1589: /*----------------------------------------------------------------------
                   1590:   LineTrace
                   1591:   Makes a file copy of libwww's traces
                   1592:   ----------------------------------------------------------------------*/
1.116     cvs      1593: static  int LineTrace (const char * fmt, va_list pArgs)
                   1594: {
1.248     kahan    1595:   vfprintf (trace_fp, fmt, pArgs);
                   1596:   return (fflush (trace_fp));
1.4       cvs      1597: }
                   1598: 
1.27      cvs      1599: /*----------------------------------------------------------------------
                   1600:   AHTAcceptTypesInit
1.74      cvs      1601:   This function prepares the Accept header used by Amaya during
                   1602:   the HTTP content negotiation phase
1.27      cvs      1603:   ----------------------------------------------------------------------*/
                   1604: static void           AHTAcceptTypesInit (HTList *c)
                   1605: {
1.223     cvs      1606:    if (c == (HTList *) NULL) 
1.27      cvs      1607:       return;
                   1608: 
1.223     cvs      1609:    /* define here all the mime types that Amaya can accept */
1.27      cvs      1610: 
1.223     cvs      1611:    HTConversion_add (c, "image/png",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1612:    HTConversion_add (c, "image/jpeg", "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1613:    HTConversion_add (c, "image/gif",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1614:    HTConversion_add (c, "image/xbm",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
                   1615:    HTConversion_add (c, "image/xpm",  "www/present", HTThroughLine, 1.0, 0.0, 0.0);
1.183     cvs      1616: 
1.27      cvs      1617:    /* Define here the equivalences between MIME types and file extensions for
1.223     cvs      1618:       the types that Amaya can display */
1.27      cvs      1619: 
1.176     cvs      1620:    /* Initialize suffix bindings for local files */
                   1621:    HTBind_init();
                   1622: 
1.27      cvs      1623:    /* Register the default set of file suffix bindings */
                   1624:    HTFileInit ();
                   1625: 
1.257     kahan    1626:    /* Register additional bindings */
1.276     kahan    1627:    HTBind_add("htm", "text/html",  NULL, "8bit", NULL, 1.0);
1.257     kahan    1628:    HTBind_add("tgz", "application/gnutar",  NULL, "binary", NULL, 1.0);
1.293     kahan    1629:    HTBind_add("mml", AM_MATHML_MIME_TYPE,  NULL, "8bit", NULL, 1.0);
                   1630:    HTBind_add("svg", AM_SVG_MIME_TYPE,  NULL, "8bit", NULL, 1.0);
1.260     kahan    1631:    HTBind_add("xsl", "text/xml",  NULL, "8bit", NULL, 1.0);
1.27      cvs      1632:    /* Don't do any case distinction */
                   1633:    HTBind_caseSensitive (FALSE);
                   1634: }
1.4       cvs      1635: 
1.5       cvs      1636: /*----------------------------------------------------------------------
1.193     cvs      1637:   AHTAcceptLanguagesInit
                   1638:   This function prepares the Accept header used by Amaya during
                   1639:   the HTTP content negotiation phase
                   1640:   ----------------------------------------------------------------------*/
1.196     cvs      1641: static void         AHTAcceptLanguagesInit (HTList *c)
1.193     cvs      1642: {
1.265     cvs      1643:   char             *ptr;
                   1644:   char             *lang_list;
1.223     cvs      1645:   char              s[3];
1.196     cvs      1646:   int               count, lg;
                   1647:   double            quality;
                   1648:   ThotBool          still;
1.193     cvs      1649: 
                   1650:   if (c == (HTList *) NULL) 
1.265     cvs      1651:     return;
1.193     cvs      1652:   
1.203     cvs      1653:   lang_list = TtaGetEnvString ("ACCEPT_LANGUAGES");
1.197     cvs      1654:   s[2] = EOS;
1.272     cvs      1655:   if (lang_list && *lang_list != EOS)
1.193     cvs      1656:     {
                   1657:       /* add the default language first  */
                   1658:       HTLanguage_add (c, "*", -1.0);
                   1659:       /* how many languages do we have? */
1.196     cvs      1660:       ptr = lang_list;
                   1661:       count = 0;
1.272     cvs      1662:       while (*ptr != EOS)
1.265     cvs      1663:        {
1.272     cvs      1664:          while (*ptr != EOS &&
1.265     cvs      1665:                 (*ptr < 'A' || (*ptr > 'Z' && *ptr < 'a') || *ptr > 'z'))
                   1666:            /* skip the whole separator */
                   1667:            ptr++;
                   1668:          lg = 0;
                   1669:          while ((*ptr >= 'A' &&
                   1670:                  *ptr <= 'Z') || (*ptr >= 'a' && *ptr <= 'z') || *ptr == '-')
                   1671:            {
                   1672:              /* it's a new language */
                   1673:              ptr++;
                   1674:              lg++;
                   1675:            }
                   1676:          if (lg >= 2)
                   1677:            count++;
1.272     cvs      1678:          if (*ptr != EOS)
1.265     cvs      1679:            ptr++;
                   1680:        }
1.193     cvs      1681: 
1.196     cvs      1682:       if (count > 0)
1.265     cvs      1683:        quality = 1.1 - (double) count/10.0;
1.193     cvs      1684:       else
1.265     cvs      1685:        quality = 1.0;
1.193     cvs      1686: 
1.265     cvs      1687:       /* Read the languages from the registry, then inject them one, by one.
                   1688:         The first one is the one with the highest priority.
                   1689:         The libwww ask for the lowest priority first.
1.196     cvs      1690:       */
                   1691:       ptr--;
                   1692:       still = TRUE;
1.265     cvs      1693:       while (count)
                   1694:        {
                   1695:          while (still && (*ptr < 'A' || (*ptr > 'Z' && *ptr < 'a') || *ptr > 'z'))
                   1696:            /* skip the whole separator */
                   1697:            if (ptr > lang_list)
                   1698:              ptr--;
                   1699:            else
                   1700:              still = FALSE;
                   1701:          lg = 0;
                   1702:          while (still &&
                   1703:                 ((*ptr >= 'A' &&
                   1704:                   *ptr <= 'Z') || (*ptr >= 'a' && *ptr <= 'z') || *ptr == '-'))
                   1705:            {
                   1706:              /* it's a new language */
                   1707:              if (ptr > lang_list)
                   1708:                ptr--;
                   1709:              else
                   1710:                still = FALSE;
                   1711:              lg++;
                   1712:            }
                   1713:          if (lg >= 2)
                   1714:            {
                   1715:              if (still)
                   1716:                strncpy  (s, &ptr[1], 2);
                   1717:              else
                   1718:                strncpy (s, lang_list, 2);
                   1719:              count--;
                   1720:              HTLanguage_add (c, s, quality);
                   1721:              quality += 0.1;
                   1722:            }
                   1723:          ptr--;
                   1724:        }
                   1725:     }
1.193     cvs      1726: }
                   1727: 
                   1728: /*----------------------------------------------------------------------
1.17      cvs      1729:   AHTConverterInit
                   1730:   Bindings between a source media type and a destination media type
                   1731:   (conversion).
1.5       cvs      1732:   ----------------------------------------------------------------------*/
1.15      cvs      1733: static void         AHTConverterInit (HTList *c)
1.4       cvs      1734: {
                   1735:    /* Handler for custom http error messages */
1.7       cvs      1736:    HTConversion_add (c, "*/*", "www/debug", AHTMemConverter, 1.0, 0.0, 0.0);
1.4       cvs      1737: 
                   1738:    /*
                   1739:     ** These are converters that converts to something other than www/present,
                   1740:     ** that is not directly outputting someting to the user on the screen
                   1741:     */
                   1742: 
1.223     cvs      1743:    HTConversion_add (c, "message/rfc822", "*/*", HTMIMEConvert, 1.0, 0.0, 0.0);
                   1744:    HTConversion_add (c, "message/x-rfc822-foot", "*/*", HTMIMEFooter, 1.0, 0.0, 0.0);
                   1745:    HTConversion_add (c, "message/x-rfc822-head", "*/*", HTMIMEHeader, 1.0, 0.0, 0.0);
                   1746:    HTConversion_add(c,"message/x-rfc822-cont", "*/*", HTMIMEContinue, 1.0, 0.0, 0.0);
                   1747:    HTConversion_add(c,"message/x-rfc822-partial","*/*",        HTMIMEPartial, 1.0, 0.0, 0.0);
                   1748:    HTConversion_add (c, "multipart/*", "*/*", HTBoundary, 1.0, 0.0, 0.0);
                   1749:    HTConversion_add (c, "text/plain", "text/html", HTPlainToHTML, 1.0, 0.0, 0.0);
1.4       cvs      1750: 
                   1751:    /*
1.116     cvs      1752:    ** The following conversions are converting ASCII output from various
                   1753:    ** protocols to HTML objects.
                   1754:    */
1.223     cvs      1755:    HTConversion_add (c, "text/x-http", "*/*", HTTPStatus_new, 1.0, 0.0, 0.0);
1.4       cvs      1756: 
                   1757:    /*
1.116     cvs      1758:    ** We also register a special content type guess stream that can figure out
                   1759:    ** the content type by reading the first bytes of the stream
                   1760:    */
1.223     cvs      1761:    HTConversion_add (c, "www/unknown", "*/*", HTGuess_new, 1.0, 0.0, 0.0);
1.4       cvs      1762: 
1.116     cvs      1763: #ifdef AMAYA_WWW_CACHE
1.4       cvs      1764:    /*
1.116     cvs      1765:    ** Register a persistent cache stream which can save an object to local
                   1766:    ** file
                   1767:    */
1.223     cvs      1768:    HTConversion_add (c, "www/cache", "*/*", HTCacheWriter, 1.0, 0.0, 0.0);
                   1769:    HTConversion_add(c,"www/cache-append", "*/*", HTCacheAppend, 1.0, 0.0, 0.0);
1.306     cheyroul 1770: #endif /*AMAYA_WWW_CACHE*/
1.4       cvs      1771: 
                   1772:    /*
1.116     cvs      1773:    ** This dumps all other formats to local disk without any further
                   1774:    ** action taken
                   1775:    */
1.223     cvs      1776:    HTConversion_add (c, "*/*", "www/present", HTSaveLocally, 0.3, 0.0, 0.0);  
1.4       cvs      1777: }
                   1778: 
1.27      cvs      1779: 
1.15      cvs      1780: /*----------------------------------------------------------------------
1.17      cvs      1781:   AHTProtocolInit
                   1782:   Registers all amaya supported protocols.
1.15      cvs      1783:   ----------------------------------------------------------------------*/
1.4       cvs      1784: static void         AHTProtocolInit (void)
                   1785: {
1.265     cvs      1786:   char *strptr;
1.4       cvs      1787: 
1.116     cvs      1788:   /* 
                   1789:      NB. Preemptive == YES means Blocking requests
                   1790:      Non-preemptive == NO means Non-blocking requests
                   1791:      */
                   1792:   HTTransport_add("tcp", HT_TP_SINGLE, HTReader_new, HTWriter_new);
                   1793:   HTTransport_add("buffered_tcp", HT_TP_SINGLE, HTReader_new, 
                   1794:                  HTBufferWriter_new);
                   1795:   HTProtocol_add ("http", "buffered_tcp", HTTP_PORT, NO, HTLoadHTTP, NULL);
1.136     cvs      1796: #ifdef _WINDOWS
                   1797:   HTProtocol_add ("file", "local", 0, YES, HTLoadFile, NULL);
                   1798: #else
1.116     cvs      1799:   HTProtocol_add ("file", "local", 0, NO, HTLoadFile, NULL);
1.198     cvs      1800: #endif /* _WINDOWS */
1.116     cvs      1801: #ifdef AMAYA_WWW_CACHE
                   1802:    HTProtocol_add("cache",  "local", 0, YES, HTLoadCache, NULL);
                   1803: #endif /* AMAYA_WWW_CACHE */
1.103     cvs      1804: #if 0 /* experimental code */
1.245     kahan    1805: #endif
1.116     cvs      1806:    HTProtocol_add ("ftp", "tcp", FTP_PORT, NO, HTLoadFTP, NULL);
1.245     kahan    1807: 
1.116     cvs      1808: 
                   1809:    /* initialize pipelining */
1.223     cvs      1810:   strptr = TtaGetEnvString ("ENABLE_PIPELINING");
1.265     cvs      1811:   if (strptr && *strptr && strcasecmp (strptr, "yes"))
1.116     cvs      1812:     HTTP_setConnectionMode (HTTP_11_NO_PIPELINING);
1.4       cvs      1813: }
                   1814: 
1.15      cvs      1815: /*----------------------------------------------------------------------
1.17      cvs      1816:   AHTNetInit
                   1817:   Reegisters "before" and "after" request filters.
1.15      cvs      1818:   ----------------------------------------------------------------------*/
1.4       cvs      1819: static void         AHTNetInit (void)
                   1820: {
                   1821: 
                   1822: /*      Register BEFORE filters
1.74      cvs      1823: **      The BEFORE filters handle proxies, caches, rule files etc.
                   1824: **      The filters are called in the order by which the are registered
                   1825: **      Not done automaticly - may be done by application!
                   1826: */
1.4       cvs      1827: 
1.116     cvs      1828:   HTNet_addBefore (HTCredentialsFilter, "http://*", NULL, HT_FILTER_LATE);
                   1829:   HTNet_addBefore (HTProxyFilter, NULL, NULL, HT_FILTER_LATE);
1.85      cvs      1830:   HTHost_setActivateRequestCallback (AHTOpen_file);
1.4       cvs      1831: 
                   1832: /*      register AFTER filters
1.74      cvs      1833: **      The AFTER filters handle error messages, logging, redirection,
                   1834: **      authentication etc.
                   1835: **      The filters are called in the order by which the are registered
                   1836: **      Not done automaticly - may be done by application!
                   1837: */
1.4       cvs      1838: 
1.223     cvs      1839:   HTNet_addAfter (HTAuthFilter, "http://*", NULL, HT_NO_ACCESS, HT_FILTER_MIDDLE);
                   1840:   HTNet_addAfter (HTAuthFilter, "http://*", NULL, HT_REAUTH, HT_FILTER_MIDDLE);
                   1841:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_PERM_REDIRECT, HT_FILTER_MIDDLE);
                   1842:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_FOUND, HT_FILTER_MIDDLE);
                   1843:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_SEE_OTHER, HT_FILTER_MIDDLE);
                   1844:   HTNet_addAfter (redirection_handler, "http://*", NULL, HT_TEMP_REDIRECT, HT_FILTER_MIDDLE);
                   1845:   HTNet_addAfter (HTAuthInfoFilter,    "http://*", NULL, HT_ALL, HT_FILTER_MIDDLE);
                   1846:   HTNet_addAfter (HTUseProxyFilter, "http://*", NULL, HT_USE_PROXY, HT_FILTER_MIDDLE);
1.151     cvs      1847: #ifdef AMAYA_LOST_UPDATE
1.223     cvs      1848:   HTNet_addAfter (precondition_handler, NULL, NULL, HT_PRECONDITION_FAILED, HT_FILTER_MIDDLE);
1.151     cvs      1849: #endif /* AMAYA_LOST_UPDATE */
1.111     cvs      1850: #ifndef _WINDOWS
1.223     cvs      1851:   HTNet_addAfter (AHTLoadTerminate_handler, NULL, NULL, HT_ALL, HT_FILTER_LAST);       
1.111     cvs      1852: #endif /* !_WINDOWS */
1.116     cvs      1853:    /**** for later ?? ****/
                   1854:    /*  HTNet_addAfter(HTInfoFilter,    NULL,           NULL, HT_ALL,           HT_FILTER_LATE); */
1.245     kahan    1855:   /* @@ JK: Filters for doing ftp authentication */
                   1856:   HTNet_addAfter (HTAuthFilter, "ftp://*", NULL, HT_NO_ACCESS, HT_FILTER_MIDDLE);
                   1857:   HTNet_addAfter (HTAuthFilter, "ftp://*", NULL, HT_REAUTH, HT_FILTER_MIDDLE);
1.51      cvs      1858:    /* handles all errors */
1.116     cvs      1859:   HTNet_addAfter (terminate_handler, NULL, NULL, HT_ALL, HT_FILTER_LAST);
1.4       cvs      1860: }
                   1861: 
1.15      cvs      1862: /*----------------------------------------------------------------------
1.17      cvs      1863:   AHTAlertInit
                   1864:   Register alert messages and their callbacks.
1.15      cvs      1865:   ----------------------------------------------------------------------*/
                   1866: static void         AHTAlertInit (void)
                   1867: {
                   1868:    HTAlert_add (AHTProgress, HT_A_PROGRESS);
1.120     cvs      1869: #ifdef __WINDOWS
1.70      cvs      1870:    HTAlert_add ((HTAlertCallback *) WIN_Activate_Request, HT_PROG_CONNECT);
1.116     cvs      1871: #endif /* _WINDOWS */
1.15      cvs      1872:    HTAlert_add (AHTError_print, HT_A_MESSAGE);
1.48      cvs      1873:    HTError_setShow (~((unsigned int) 0 ) & ~((unsigned int) HT_ERR_SHOW_DEBUG));       /* process all messages except debug ones*/
1.15      cvs      1874:    HTAlert_add (AHTConfirm, HT_A_CONFIRM);
                   1875:    HTAlert_add (AHTPrompt, HT_A_PROMPT);
                   1876:    HTAlert_add (AHTPromptUsernameAndPassword, HT_A_USER_PW);
1.116     cvs      1877: }
                   1878: 
1.118     cvs      1879: #ifdef AMAYA_WWW_CACHE
                   1880: /*----------------------------------------------------------------------
1.128     cvs      1881:   RecCleanCache
1.118     cvs      1882:   Clears an existing cache directory
                   1883:   ----------------------------------------------------------------------*/
1.265     cvs      1884: static void RecCleanCache (char *dirname)
                   1885: {
1.128     cvs      1886: #ifdef _WINDOWS
1.223     cvs      1887:   HANDLE          hFindFile;
                   1888:   ThotBool        status;
1.128     cvs      1889:   WIN32_FIND_DATA ffd;
1.290     vatton   1890:   char            t_dir [MAX_LENGTH];
                   1891:   char           *ptr;
1.128     cvs      1892: 
1.130     cvs      1893:   /* create a t_dir name to start searching for files */
1.265     cvs      1894:   if ((strlen (dirname) + 10) > MAX_LENGTH)
1.128     cvs      1895:     /* ERROR: directory name is too big */
                   1896:     return;
                   1897: 
1.265     cvs      1898:   strcpy (t_dir, dirname);
1.130     cvs      1899:   /* save the end of the dirname. We'll use it to make
                   1900:      a complete pathname when erasing files */
1.265     cvs      1901:   ptr = &t_dir[strlen (t_dir)];
                   1902:   strcat (t_dir, "*");
1.128     cvs      1903: 
1.130     cvs      1904:   hFindFile = FindFirstFile (t_dir, &ffd);
1.128     cvs      1905:     
                   1906:   if (hFindFile == INVALID_HANDLE_VALUE)
                   1907:     /* nothing to erase? */
                   1908:     return;
                   1909: 
                   1910:   status = TRUE;
1.130     cvs      1911:   while (status) 
                   1912:     {
                   1913:       if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1.133     cvs      1914:        {
                   1915:          /* it's a directory, erase it recursively */
1.265     cvs      1916:          if (strcmp (ffd.cFileName, "..") && strcmp (ffd.cFileName, "."))
1.133     cvs      1917:            {
1.265     cvs      1918:              strcpy (ptr, ffd.cFileName);
1.272     cvs      1919:              strcat (ptr, DIR_STR);
1.133     cvs      1920:              RecCleanCache (t_dir);
1.274     cvs      1921:              rmdir (t_dir);
1.133     cvs      1922:            }
                   1923:        }
                   1924:        else
1.130     cvs      1925:          {
1.133     cvs      1926:            /* it's a file, erase it */
1.265     cvs      1927:            strcpy (ptr, ffd.cFileName);
1.133     cvs      1928:            TtaFileUnlink (t_dir);
1.130     cvs      1929:          }
                   1930:       status = FindNextFile (hFindFile, &ffd);
                   1931:     }
1.128     cvs      1932:   FindClose (hFindFile);
                   1933: 
                   1934: #else /* _WINDOWS */
1.118     cvs      1935:   DIR *dp;
                   1936:   struct stat st;
                   1937: #ifdef HAVE_DIRENT_H
                   1938:   struct dirent *d;
                   1939: #else
                   1940:   struct direct *d;
                   1941: #endif /* HAVE_DIRENT_H */
1.128     cvs      1942:   char filename[BUFSIZ+1];
1.118     cvs      1943: 
                   1944:   if ((dp = opendir (dirname)) == NULL) 
                   1945:     {
                   1946:       /* @@@ we couldn't open the directory ... we need some msg */
                   1947:       perror (dirname);
1.176     cvs      1948:       return;
1.118     cvs      1949:     }
                   1950:   
                   1951:   while ((d = readdir (dp)) != NULL)
                   1952:     {
                   1953:       /* skip the UNIX . and .. links */
                   1954:       if (!strcmp (d->d_name, "..")
                   1955:          || !strcmp (d->d_name, "."))
                   1956:        continue;
                   1957: 
1.188     cvs      1958:       sprintf (filename, "%s%c%s", dirname, DIR_SEP, d->d_name);
1.118     cvs      1959:       if  (lstat (filename, &st) < 0 ) 
                   1960:        {
                   1961:          /* @@2 need some error message */
                   1962:          perror (filename);
                   1963:          continue;
                   1964:        }
                   1965:       
                   1966:       switch (st.st_mode & S_IFMT)
                   1967:        {
                   1968:        case S_IFDIR:
                   1969:          /* if we find a directory, we erase it, recursively */
1.128     cvs      1970:          strcat (filename, DIR_STR);
                   1971:          RecCleanCache (filename);
                   1972:          rmdir (filename);
1.118     cvs      1973:          break;
                   1974:        case S_IFLNK:
                   1975:          /* skip any links we find */
                   1976:          continue;
                   1977:          break;
                   1978:        default:
                   1979:          /* erase the filename */
                   1980:          TtaFileUnlink (filename);
                   1981:          break;
                   1982:        }
                   1983:     }
                   1984:   closedir (dp);
1.265     cvs      1985: #endif /* _WINDOWS */
1.118     cvs      1986: }
                   1987: #endif /* AMAYA_WWW_CACHE */
                   1988: 
1.116     cvs      1989: /*----------------------------------------------------------------------
1.265     cvs      1990:   libwww_CleanCache
                   1991:   frontend to the recursive cache cleaning function
                   1992:   ----------------------------------------------------------------------*/
                   1993: void libwww_CleanCache (void)
                   1994: {
                   1995: #ifdef AMAYA_WWW_CACHE
                   1996:   char * real_dir;
                   1997:   char*    cache_dir;
                   1998:   char*    tmp;
                   1999:   int      cache_size;
                   2000:   int      cache_expire;
                   2001:   int      cache_disconnect;
                   2002:   ThotBool error;
                   2003:   char * ptr;
                   2004: 
                   2005:   if (!HTCacheMode_enabled ())
                   2006:     /* don't do anything if we're not using a cache */
                   2007:     return;
                   2008:   /* temporarily close down the cache, purge it, then restart */
                   2009:   tmp = HTCacheMode_getRoot ();
                   2010:   /* don't do anything if we don't have a valid cache dir */
                   2011:   if (!tmp || *tmp == EOS)
                   2012:          return;
                   2013:   cache_dir = TtaStrdup (tmp);
                   2014:   HT_FREE (tmp);
                   2015:   cache_size = HTCacheMode_maxSize ();
                   2016:   cache_expire = HTCacheMode_expires ();
                   2017:   cache_disconnect = HTCacheMode_disconnected ();
                   2018: 
                   2019:   /* get something we can work on :) */
                   2020:   tmp = HTWWWToLocal (cache_dir, "file:", NULL);
                   2021:   real_dir = TtaGetMemory (strlen (tmp) + 20);
1.273     cvs      2022:   strcpy (real_dir, tmp);
1.265     cvs      2023:   HT_FREE (tmp);
                   2024: 
                   2025:   /* safeguard... abort the operation if cache_dir doesn't end with
                   2026:      CACHE_DIR_NAME */
                   2027:   error = TRUE;
                   2028:   ptr = strstr (real_dir, CACHE_DIR_NAME);  
                   2029:     if (ptr && *ptr && !strcasecmp (ptr, CACHE_DIR_NAME))
                   2030:       error = FALSE;
                   2031:   if (error)
                   2032:     return;  
                   2033:   
                   2034:   /* remove the concurrent cache lock */
                   2035: #ifdef DEBUG_LIBWWW
                   2036:   fprintf (stderr, "Clearing the cache lock\n");
                   2037: #endif /* DEBUG_LIBWWW */
                   2038:   clear_cachelock ();
                   2039:   HTCacheTerminate ();
                   2040:   HTCacheMode_setEnabled (FALSE);
                   2041:   
                   2042:   RecCleanCache (real_dir);
                   2043: 
                   2044:   HTCacheMode_setExpires (cache_expire);
                   2045:   HTCacheMode_setDisconnected (cache_disconnect);
                   2046:   HTCacheInit (cache_dir, cache_size);
                   2047:   /* set a new concurrent cache lock */
                   2048:   strcat (real_dir, ".lock");
                   2049:   if (set_cachelock (real_dir) == -1)
                   2050:     /* couldn't open the .lock file, so, we close the cache to
                   2051:        be in the safe side */
                   2052:     {
                   2053: #ifdef DEBUG_LIBWWW
                   2054:       fprintf (stderr, "couldnt set the cache lock\n");
                   2055: #endif /* DEBUG_LIBWWW */
                   2056:       HTCacheTerminate ();
                   2057:       HTCacheMode_setEnabled (FALSE);
                   2058:     }
                   2059: #ifdef DEBUG_LIBWWW
                   2060:   fprintf (stderr, "set a cache lock\n");
                   2061: #endif /* DEBUG_LIBWWW */
                   2062:   TtaFreeMemory (real_dir);
                   2063:   TtaFreeMemory (cache_dir);
                   2064: #endif /* AMAYA_WWW_CACHE */
                   2065: }
                   2066: 
                   2067: /*----------------------------------------------------------------------
1.116     cvs      2068:   CacheInit
                   2069:   Reads the cache settings from the thot.ini file.
                   2070:   ----------------------------------------------------------------------*/
                   2071: static void CacheInit (void)
                   2072: {
                   2073: #ifndef AMAYA_WWW_CACHE
                   2074:    HTCacheMode_setEnabled (NO);
                   2075: 
                   2076: #else /* AMAYA_WWW_CACHE */
1.265     cvs      2077:   char     *strptr;
                   2078:   char     *real_dir = NULL;
                   2079:   char     *cache_lockfile;
                   2080:   char     *cache_dir = NULL;
1.223     cvs      2081:   int       cache_size;
                   2082:   int       cache_entry_size;
                   2083:   ThotBool  cache_enabled;
                   2084:   ThotBool  cache_locked;
                   2085:   ThotBool  tmp_bool;
1.130     cvs      2086: 
1.185     cvs      2087: int i;
                   2088: 
1.116     cvs      2089:   /* activate cache? */
1.203     cvs      2090:   strptr = TtaGetEnvString ("ENABLE_CACHE");
1.265     cvs      2091:   if (strptr && *strptr && strcasecmp (strptr, "yes"))
1.130     cvs      2092:     cache_enabled = NO;
1.116     cvs      2093:   else
1.130     cvs      2094:     cache_enabled = YES;
1.116     cvs      2095: 
1.151     cvs      2096:   /* cache protected documents? */
1.203     cvs      2097:   strptr = TtaGetEnvString ("CACHE_PROTECTED_DOCS");
1.265     cvs      2098:   if (strptr && *strptr && !strcasecmp (strptr, "yes"))
1.151     cvs      2099:     HTCacheMode_setProtected (YES);
                   2100:   else
                   2101:     HTCacheMode_setProtected (NO);
                   2102: 
1.116     cvs      2103:   /* get the cache dir (or use a default one) */
1.203     cvs      2104:   strptr = TtaGetEnvString ("CACHE_DIR");
1.116     cvs      2105:   if (strptr && *strptr) 
                   2106:     {
1.265     cvs      2107:       real_dir = TtaGetMemory (strlen (strptr) + strlen (CACHE_DIR_NAME) + 20);
                   2108:       strcpy (real_dir, strptr);
1.272     cvs      2109:       if (*(real_dir + strlen (real_dir) - 1) != DIR_SEP)
                   2110:        strcat (real_dir, DIR_STR);
1.116     cvs      2111:     }
                   2112:   else
                   2113:     {
1.265     cvs      2114:       real_dir = TtaGetMemory (strlen (TempFileDirectory) + strlen (CACHE_DIR_NAME) + 20);
1.272     cvs      2115:       sprintf (real_dir, "%s%s", TempFileDirectory, CACHE_DIR_NAME);
1.185     cvs      2116:     }
                   2117: 
                   2118:   /* compatiblity with previous versions of Amaya: does real_dir
                   2119:      include CACHE_DIR_NAME? If not, add it */
1.265     cvs      2120:   strptr = strstr (real_dir, CACHE_DIR_NAME);
1.185     cvs      2121:   if (!strptr)
1.265     cvs      2122:     strcat (real_dir, CACHE_DIR_NAME);
1.185     cvs      2123:   else
                   2124:     {
1.265     cvs      2125:       i = strlen (CACHE_DIR_NAME);
1.272     cvs      2126:          if (strptr[i] != EOS)
1.265     cvs      2127:           strcat (real_dir, CACHE_DIR_NAME);
1.116     cvs      2128:     }
1.185     cvs      2129: 
1.211     cvs      2130:   /* convert the local cache dir into a file URL, as expected by
                   2131:      libwww */
1.265     cvs      2132:   cache_dir = HTLocalToWWW (real_dir, "file:");
1.116     cvs      2133:   /* get the cache size (or use a default one) */
1.203     cvs      2134:   strptr = TtaGetEnvString ("CACHE_SIZE");
1.116     cvs      2135:   if (strptr && *strptr) 
1.288     vatton   2136:     cache_size = atoi (strptr);
1.116     cvs      2137:   else
                   2138:     cache_size = DEFAULT_CACHE_SIZE;
1.176     cvs      2139:   /* get the max cached file size (or use a default one) */
1.223     cvs      2140:   if (!TtaGetEnvInt ("MAX_CACHE_ENTRY_SIZE", &cache_entry_size))
1.176     cvs      2141:     cache_entry_size = DEFAULT_MAX_CACHE_ENTRY_SIZE;
1.130     cvs      2142:   if (cache_enabled) 
1.116     cvs      2143:     {
                   2144:       /* how to remove the lock? force remove it? */
1.265     cvs      2145:       cache_lockfile = TtaGetMemory (strlen (real_dir) + 20);
                   2146:       strcpy (cache_lockfile, real_dir);
                   2147:       strcat (cache_lockfile, ".lock");
1.130     cvs      2148:       cache_locked = FALSE;
1.223     cvs      2149:       if (TtaFileExist (cache_lockfile) && !(cache_locked = test_cachelock (cache_lockfile)))
1.116     cvs      2150:        {
1.130     cvs      2151: #ifdef DEBUG_LIBWWW
                   2152:          fprintf (stderr, "found a stale cache, removing it\n");
                   2153: #endif /* DEBUG_LIBWWW */
                   2154:          /* remove the lock and clean the cache (the clean cache 
                   2155:             will remove all, making the following call unnecessary */
                   2156:          /* little trick to win some memory */
1.265     cvs      2157:          strptr = strrchr (cache_lockfile, '.');
1.272     cvs      2158:          *strptr = EOS;
1.130     cvs      2159:          RecCleanCache (cache_lockfile);
1.265     cvs      2160:          *strptr = '.';
1.116     cvs      2161:        }
                   2162: 
1.130     cvs      2163:       if (!cache_locked) 
                   2164:        {
                   2165:          /* initialize the cache if there's no other amaya
                   2166:             instance running */
1.177     cvs      2167:          HTCacheMode_setMaxCacheEntrySize (cache_entry_size);
1.223     cvs      2168:          if (TtaGetEnvBoolean ("CACHE_EXPIRE_IGNORE", &tmp_bool) && tmp_bool)
1.177     cvs      2169:            HTCacheMode_setExpires (HT_EXPIRES_IGNORE);
                   2170:          else
                   2171:            HTCacheMode_setExpires (HT_EXPIRES_AUTO);
1.223     cvs      2172:          TtaGetEnvBoolean ("CACHE_DISCONNECTED_MODE", &tmp_bool);
1.177     cvs      2173:          if (tmp_bool)
                   2174:            HTCacheMode_setDisconnected (HT_DISCONNECT_NORMAL);
                   2175:          else
                   2176:            HTCacheMode_setDisconnected (HT_DISCONNECT_NONE);
1.211     cvs      2177:          if (HTCacheInit (cache_dir, cache_size))
1.130     cvs      2178:            {
1.188     cvs      2179:              if (set_cachelock (cache_lockfile) == -1)
                   2180:                /* couldn't open the .lock file, so, we close the cache to
                   2181:                   be in the safe side */
                   2182:                {
                   2183:                  HTCacheTerminate ();
                   2184:                  HTCacheMode_setEnabled (FALSE);
                   2185: #ifdef DEBUG_LIBWWW
                   2186:                  fprintf (stderr, "couldnt set the cache lock\n");
                   2187: #endif /* DEBUG_LIBWWW */
                   2188:                }
1.130     cvs      2189: #ifdef DEBUG_LIBWWW
1.188     cvs      2190:              else
                   2191:                fprintf (stderr, "created the cache lock\n");
1.130     cvs      2192: #endif /* DEBUG_LIBWWW */
                   2193:            }
1.188     cvs      2194:          else
                   2195:            {
1.130     cvs      2196: #ifdef DEBUG_LIBWWW
1.188     cvs      2197:              fprintf (stderr, "couldn't create the cache\n");
                   2198: #endif /* DEBUG_LIBWWW */            
                   2199:              HTCacheTerminate ();
                   2200:            }
1.130     cvs      2201:        }
                   2202:       else 
                   2203:        {
1.185     cvs      2204:          HTCacheMode_setEnabled (FALSE);
1.130     cvs      2205: #ifdef DEBUG_LIBWWW
                   2206:          fprintf (stderr, "lock detected, starting libwww without a cache/n");
                   2207: #endif /* DEBUG_LIBWWW */
                   2208:        }
                   2209:       TtaFreeMemory (cache_lockfile);
1.116     cvs      2210:     }
                   2211:   else
1.185     cvs      2212:     {
                   2213:       HTCacheMode_setEnabled (FALSE);
                   2214:     }
1.116     cvs      2215:   if (cache_dir)
1.211     cvs      2216:     HT_FREE (cache_dir);
1.189     cvs      2217:   if (real_dir)
                   2218:     TtaFreeMemory (real_dir);
1.185     cvs      2219:   /* warn the user if the cache isn't active */
                   2220:   if (cache_enabled && !HTCacheMode_enabled ())
1.291     kahan    2221:     {
                   2222:       ThotBool warn_user;
                   2223: 
                   2224:       TtaGetEnvBoolean ("WARN_NO_CACHE", &warn_user);
                   2225:       if (warn_user)
                   2226:        InitInfo ("Cache", TtaGetMessage (AMAYA, AM_CANT_CREATE_CACHE));
                   2227:     }
1.116     cvs      2228: #endif /* AMAYA_WWW_CACHE */
1.15      cvs      2229: }
                   2230: 
                   2231: /*----------------------------------------------------------------------
1.97      cvs      2232:   ProxyInit
                   2233:   Reads any proxies settings which may be declared as environmental
                   2234:   variables or in the thot.ini file. The former overrides the latter.
                   2235:   ----------------------------------------------------------------------*/
                   2236: static void ProxyInit (void)
                   2237: {
1.265     cvs      2238:   char     *strptr;
                   2239:   char     *name;
                   2240:   char     *tmp = NULL;
                   2241:   char     *strptrA;
1.223     cvs      2242:   ThotBool  proxy_is_onlyproxy;
1.97      cvs      2243: 
                   2244:   /* get the proxy settings from the thot.ini file */
1.203     cvs      2245:   strptr = TtaGetEnvString ("HTTP_PROXY");
1.228     cvs      2246:   if (strptr && *strptr)
                   2247:     {
1.265     cvs      2248:       tmp = (char *) TtaGetMemory (strlen (strptr) + 1);
                   2249:       strcpy (tmp, strptr);
1.223     cvs      2250: 
1.228     cvs      2251:       /* does the proxy env string has an "http://" prefix? */
1.265     cvs      2252:       if (!strncasecmp (strptr, "http://", 7)) 
1.223     cvs      2253:         HTProxy_add ("http", tmp);
1.228     cvs      2254:       else 
                   2255:        {
1.265     cvs      2256:          strptrA = (char *) TtaGetMemory (strlen (strptr) + 9);
1.228     cvs      2257:          strcpy (strptrA, "http://");
                   2258:          strcat (strptrA, tmp);
                   2259:          HTProxy_add ("http", strptrA);
                   2260:          TtaFreeMemory (strptrA);
                   2261:        }
                   2262:       TtaFreeMemory (tmp);
                   2263:     }
1.216     cvs      2264: 
1.97      cvs      2265:   /* get the no_proxy settings from the thot.ini file */
1.212     cvs      2266:   strptr = TtaGetEnvString ("PROXYDOMAIN");
1.228     cvs      2267:   if (strptr && *strptr) 
                   2268:     {
1.265     cvs      2269:       strptrA = (char *) TtaGetMemory (strlen (strptr) + 1);
                   2270:       tmp = strptrA;
                   2271:       strcpy (tmp, strptr);
1.228     cvs      2272:       /* as HTNextField changes the ptr we pass as an argument, we'll
1.265     cvs      2273:         work with another variable, so that we can free the tmp
1.228     cvs      2274:         block later on */
                   2275:       while ((name = HTNextField (&tmp)) != NULL) 
                   2276:        {
                   2277:          char* portstr = strchr (name, ':');
                   2278:          unsigned port=0;
1.265     cvs      2279:          if (portstr)
                   2280:            { 
                   2281:              *portstr++ = EOS;
                   2282:              if (*portstr) 
                   2283:                port = (unsigned) atoi (portstr);
                   2284:            }
1.228     cvs      2285:          /* Register it for all access methods */
                   2286:          HTNoProxy_add (name, NULL, port);
                   2287:        }
                   2288:       TtaFreeMemory (strptrA);
                   2289:     }
                   2290:   
1.212     cvs      2291:   /* how should we interpret the proxy domain list? */
1.291     kahan    2292: 
1.212     cvs      2293:   TtaGetEnvBoolean ("PROXYDOMAIN_IS_ONLYPROXY", &proxy_is_onlyproxy);
                   2294:   HTProxy_setNoProxyIsOnlyProxy (proxy_is_onlyproxy);
                   2295: 
                   2296:   /* use libwww's routine to get all proxy settings from the environment */
1.97      cvs      2297:    HTProxy_getEnvVar ();
                   2298: }
                   2299: 
1.207     cvs      2300: /*----------------------------------------------------------------------
1.17      cvs      2301:   AHTProfile_newAmaya
                   2302:   creates the Amaya client profile for libwww.
1.15      cvs      2303:   ----------------------------------------------------------------------*/
1.265     cvs      2304: static void AHTProfile_newAmaya (char *AppName, char *AppVersion)
1.4       cvs      2305: {
1.265     cvs      2306:    char *strptr;
1.158     cvs      2307: 
1.4       cvs      2308:    /* If the Library is not already initialized then do it */
1.257     kahan    2309:    if (!HTLib_isInitialized ()) 
1.273     cvs      2310:        HTLibInit (AppName, AppVersion);
1.4       cvs      2311: 
                   2312:    if (!converters)
                   2313:       converters = HTList_new ();
1.27      cvs      2314:    if (!acceptTypes)
                   2315:       acceptTypes = HTList_new ();
1.193     cvs      2316:    if (!acceptLanguages)
                   2317:       acceptLanguages = HTList_new ();
1.151     cvs      2318:    if (!transfer_encodings)
                   2319:       transfer_encodings = HTList_new ();
                   2320:    if (!content_encodings)
                   2321:       content_encodings = HTList_new ();
1.4       cvs      2322: 
1.169     cvs      2323:    /* inhibits libwww's automatic file_suffix_binding */
                   2324:    HTFile_doFileSuffixBinding (FALSE);
                   2325: 
1.4       cvs      2326:    /* Register the default set of transport protocols */
                   2327:    HTTransportInit ();
                   2328: 
                   2329:    /* Register the default set of application protocol modules */
                   2330:    AHTProtocolInit ();
                   2331: 
1.116     cvs      2332:    /* Register the default set of messages and dialog functions */
                   2333:    AHTAlertInit ();
                   2334:    HTAlert_setInteractive (YES);
                   2335: 
                   2336: #ifdef AMAYA_WWW_CACHE
                   2337:    /* Enable the persistent cache  */
                   2338:    CacheInit ();
                   2339: #else
                   2340:    HTCacheMode_setEnabled (NO);
                   2341: #endif /* AMAYA_WWW_CACHE */
1.4       cvs      2342: 
                   2343:    /* Register the default set of BEFORE and AFTER filters */
                   2344:    AHTNetInit ();
                   2345: 
                   2346:    /* Set up the default set of Authentication schemes */
1.223     cvs      2347:    HTAA_newModule ("basic", HTBasic_generate, HTBasic_parse, NULL, HTBasic_delete);
1.158     cvs      2348:    /* activate MDA by defaul */
1.203     cvs      2349:    strptr = TtaGetEnvString ("ENABLE_MDA");
1.265     cvs      2350:    if (!strptr || (strptr && *strptr && strcasecmp (strptr, "no")))
1.223     cvs      2351:      HTAA_newModule ("digest", HTDigest_generate, HTDigest_parse, HTDigest_updateInfo, HTDigest_delete);
1.257     kahan    2352:    
1.97      cvs      2353:    /* Get any proxy settings */
                   2354:    ProxyInit ();
1.4       cvs      2355: 
1.207     cvs      2356:    /* Set up the domains where we accept a redirect on PUT */
                   2357:    SafePut_init ();
                   2358: 
1.4       cvs      2359:    /* Register the default set of converters */
                   2360:    AHTConverterInit (converters);
1.151     cvs      2361:    HTFormat_setConversion (converters);
1.27      cvs      2362:    AHTAcceptTypesInit (acceptTypes);
1.193     cvs      2363:    AHTAcceptLanguagesInit (acceptLanguages);
1.4       cvs      2364: 
                   2365:    /* Register the default set of transfer encoders and decoders */
1.151     cvs      2366:    HTTransferEncoderInit (transfer_encodings);
1.190     cvs      2367:    HTFormat_setTransferCoding (transfer_encodings);
                   2368:    /* Register the default set of content encoders and decoders */
1.296     kahan    2369:    /* commented because we don't know yet how to handle deflate in the content enconding */
                   2370:    /* HTContentEncoderInit (content_encodings); */
                   2371:    HTCoding_add (content_encodings, "gzip", NULL, HTIdentityCoding, 1.0);
1.190     cvs      2372:    /* ignore all other encoding formats (or libwww will send them 
1.181     cvs      2373:       thru a blackhole otherwise */
                   2374:    HTCoding_add (content_encodings, "*", NULL, HTIdentityCoding, 1.0);
1.151     cvs      2375:    if (HTList_count(content_encodings) > 0)
                   2376:      HTFormat_setContentCoding(content_encodings);
                   2377:    else 
                   2378:      {
                   2379:        HTList_delete(content_encodings);
                   2380:        content_encodings = NULL;
                   2381:      }
1.4       cvs      2382: 
                   2383:    /* Register the default set of MIME header parsers */
1.74      cvs      2384:    HTMIMEInit ();   /* must be called again for language selector */
1.4       cvs      2385: 
                   2386:    /* Register the default set of Icons for directory listings */
1.27      cvs      2387:    /*HTIconInit(NULL); *//* experimental */
1.4       cvs      2388: }
                   2389: 
1.5       cvs      2390: /*----------------------------------------------------------------------
1.17      cvs      2391:   AHTProfile_delete
                   2392:   deletes the Amaya client profile.
1.5       cvs      2393:   ----------------------------------------------------------------------*/
1.4       cvs      2394: static void         AHTProfile_delete (void)
                   2395: {
1.22      cvs      2396:   /* free the Amaya global context */
1.151     cvs      2397:   /* Clean up all the registred converters */
                   2398:   HTFormat_deleteAll ();
                   2399:   if (acceptTypes)
1.74      cvs      2400:     HTConversion_deleteAll (acceptTypes);
1.193     cvs      2401:   if (acceptLanguages)
                   2402:     HTLanguage_deleteAll (acceptLanguages);
1.151     cvs      2403: 
1.209     cvs      2404:   StopAllRequests (1);
1.74      cvs      2405:   HTList_delete (Amaya->docid_status);
                   2406:   HTList_delete (Amaya->reqlist);
                   2407:   TtaFreeMemory (Amaya);
1.61      cvs      2408: 
1.120     cvs      2409: #ifdef _WINDOWS
1.209     cvs      2410:   if (HTLib_isInitialized ())      
1.151     cvs      2411:     HTEventTerminate ();
1.198     cvs      2412: #endif /* _WINDOWS; */         
1.74      cvs      2413:     
1.151     cvs      2414:   /* Clean up the persistent cache (if any) */
1.116     cvs      2415: #ifdef AMAYA_WWW_CACHE
1.151     cvs      2416:   clear_cachelock ();
                   2417:   HTCacheTerminate ();
1.116     cvs      2418: #endif /* AMAYA_WWW_CACHE */
1.217     cvs      2419:   
1.218     cvs      2420:   /* call remove functions that are not called automatically by libwww */
                   2421:   HTNetCall_deleteBeforeAll (HTNet_before ());
                   2422:   HTNetCall_deleteAfterAll (HTNet_after ());
                   2423:   HTAA_deleteAllModules ();
                   2424:   HTAlertCall_deleteAll (HTAlert_global () );
                   2425:   HTAlert_setGlobal ((HTList *) NULL);
1.259     cvs      2426:   HTTimer_deleteAll ();
1.249     kahan    2427:   HTEventList_unregisterAll ();
1.218     cvs      2428:   /* these two functions are broken, so we can't call them right now 
                   2429:   HTHeader_deleteAll ();
                   2430:   HTTimer_deleteAll ();
                   2431:   */
                   2432:   HTTransport_deleteAll ();
1.217     cvs      2433:   /* remove bindings between suffixes, media types*/
                   2434:   HTBind_deleteAll ();
1.151     cvs      2435:   /* Terminate libwww */
                   2436:   HTLibTerminate ();
1.4       cvs      2437: }
                   2438: 
1.5       cvs      2439: /*----------------------------------------------------------------------
1.116     cvs      2440:   AmayacontextInit
                   2441:   initializes an internal Amaya context for our libwww interface 
                   2442:   ----------------------------------------------------------------------*/
1.265     cvs      2443: static void    AmayaContextInit ()
1.116     cvs      2444: {
1.140     cvs      2445:   AmayaAlive_flag = TRUE;
1.116     cvs      2446:   /* Initialization of the global context */
                   2447:   Amaya = (AmayaContext *) TtaGetMemory (sizeof (AmayaContext));
                   2448:   Amaya->reqlist = HTList_new ();
                   2449:   Amaya->docid_status = HTList_new ();
                   2450:   Amaya->open_requests = 0;
                   2451: }
                   2452: 
                   2453: /*----------------------------------------------------------------------
1.17      cvs      2454:   QueryInit
                   2455:   initializes the libwww interface 
1.5       cvs      2456:   ----------------------------------------------------------------------*/
1.265     cvs      2457: void         QueryInit ()
1.4       cvs      2458: {
1.265     cvs      2459:   char   *strptr;
                   2460:   int     tmp_i;
                   2461:   long    tmp_l;
1.4       cvs      2462: 
1.116     cvs      2463:    AmayaContextInit ();
1.4       cvs      2464:    AHTProfile_newAmaya (HTAppName, HTAppVersion);
1.140     cvs      2465:    CanDoStop_set (TRUE);
1.214     cvs      2466:    UserAborted_flag = FALSE;
1.4       cvs      2467: 
1.116     cvs      2468: #ifdef _WINDOWS
1.125     cvs      2469:    HTEventInit ();
1.116     cvs      2470: #endif /* _WINDOWS */
1.72      cvs      2471: 
1.123     cvs      2472: #ifndef _WINDOWS
1.116     cvs      2473:    HTEvent_setRegisterCallback ((void *) AHTEvent_register);
                   2474:    HTEvent_setUnregisterCallback ((void *) AHTEvent_unregister);
1.120     cvs      2475:    HTTimer_registerSetTimerCallback ((void *) AMAYA_SetTimer);
                   2476:    HTTimer_registerDeleteTimerCallback ((void *) AMAYA_DeleteTimer);
1.116     cvs      2477: #endif /* !_WINDOWS */
1.190     cvs      2478: 
1.213     cvs      2479: #ifdef HTDEBUG
1.247     kahan    2480:    /* an undocumented option for being able to generate an HTTP protocol
                   2481:       trace.  The flag can take values from 1-10, which are interpreted as
                   2482:       different kinds of debug traces. Value 99 means a complete trace.
                   2483:       0 or other values means No Debug.1 No Debug (default), up to Full debug, respectively. */
1.238     cvs      2484:    if (TtaGetEnvInt ("ENABLE_LIBWWW_DEBUG", &tmp_i))
1.247     kahan    2485:      {
                   2486:        switch (tmp_i)
                   2487:         {
                   2488:         case 1:
                   2489:           WWW_TraceFlag = SHOW_URI_TRACE;
                   2490:           break;
                   2491:         case 2:
                   2492:           WWW_TraceFlag = SHOW_BIND_TRACE;
                   2493:           break;
                   2494:         case 3:
                   2495:           WWW_TraceFlag = SHOW_THREAD_TRACE;
                   2496:           break;
                   2497:         case 4:
                   2498:           WWW_TraceFlag = SHOW_STREAM_TRACE;
                   2499:           break;
                   2500:         case 5:
                   2501:           WWW_TraceFlag = SHOW_PROTOCOL_TRACE;
                   2502:           break;
                   2503:         case 6:
                   2504:           WWW_TraceFlag = SHOW_MEM_TRACE;
                   2505:           break;
                   2506:         case 7:
                   2507:           WWW_TraceFlag = SHOW_URI_TRACE;
                   2508:           break;
                   2509:         case 8:
                   2510:           WWW_TraceFlag = SHOW_AUTH_TRACE;
                   2511:           break;
                   2512:         case 9:
                   2513:           WWW_TraceFlag = SHOW_ANCHOR_TRACE;
                   2514:           break;
                   2515:         case 10 :
                   2516:           WWW_TraceFlag = SHOW_CORE_TRACE; 
                   2517:           break;
1.251     kahan    2518:         case 11 :
                   2519:           WWW_TraceFlag = SHOW_CORE_TRACE | SHOW_ANCHOR_TRACE | SHOW_AUTH_TRACE | SHOW_URI_TRACE | SHOW_THREAD_TRACE | SHOW_STREAM_TRACE;
                   2520:           break;
1.247     kahan    2521:         case 99 :
                   2522:           WWW_TraceFlag = SHOW_ALL_TRACE;
                   2523:           break;
                   2524:         default:
                   2525:           WWW_TraceFlag = 0;
                   2526:           break;
                   2527:         }
1.248     kahan    2528:        if (WWW_TraceFlag)
                   2529:         {
                   2530:           /* Trace activation (for debugging) */
1.265     cvs      2531:           char   *s, *tmp;
1.248     kahan    2532:           s = TtaGetEnvString ("APP_TMPDIR");
1.265     cvs      2533:           tmp = TtaGetMemory (strlen (s) + sizeof ("/libwww.log") + 1);
                   2534:           strcpy (tmp, s);
                   2535:           strcat (tmp, "/libwww.log");
                   2536:           trace_fp = fopen (tmp, "ab");
1.248     kahan    2537:           TtaFreeMemory (tmp);
                   2538:           if (trace_fp)
                   2539:             HTTrace_setCallback(LineTrace);
                   2540:         }
1.247     kahan    2541:      }
1.208     cvs      2542:    else
                   2543:      WWW_TraceFlag = 0;
1.213     cvs      2544: #endif /* HTDEBUG */
1.208     cvs      2545: 
1.74      cvs      2546: #ifdef DEBUG_LIBWWW
1.116     cvs      2547:   /* forwards error messages to our own function */
                   2548:    WWW_TraceFlag = THD_TRACE;
1.138     cvs      2549:    HTTrace_setCallback(LineTrace);
1.248     kahan    2550: 
1.148     cvs      2551:    /***
1.138     cvs      2552:     WWW_TraceFlag = SHOW_CORE_TRACE | SHOW_THREAD_TRACE | SHOW_PROTOCOL_TRACE;
                   2553:     ***/
1.152     cvs      2554: #endif
1.247     kahan    2555: 
                   2556:    TtaGetEnvBoolean ("ENABLE_FTP", &FTPURL_flag);
1.152     cvs      2557: 
1.148     cvs      2558:    /* Setting up different network parameters */
1.151     cvs      2559: 
1.148     cvs      2560:    /* Maximum number of simultaneous open sockets */
1.203     cvs      2561:    strptr = TtaGetEnvString ("MAX_SOCKET");
1.151     cvs      2562:    if (strptr && *strptr) 
1.288     vatton   2563:      tmp_i = atoi (strptr);
1.151     cvs      2564:    else
                   2565:      tmp_i = DEFAULT_MAX_SOCKET;
                   2566:    HTNet_setMaxSocket (tmp_i);
                   2567: 
1.148     cvs      2568:    /* different network services timeouts */
1.151     cvs      2569:    /* dns timeout */
1.203     cvs      2570:    strptr = TtaGetEnvString ("DNS_TIMEOUT");
1.151     cvs      2571:    if (strptr && *strptr) 
1.288     vatton   2572:      tmp_i = atoi (strptr);
1.151     cvs      2573:    else
                   2574:      tmp_i = DEFAULT_DNS_TIMEOUT;
                   2575:    HTDNS_setTimeout (tmp_i);
                   2576: 
                   2577:    /* persistent connections timeout */
1.203     cvs      2578:    strptr = TtaGetEnvString ("PERSIST_CX_TIMEOUT");
1.151     cvs      2579:    if (strptr && *strptr) 
1.288     vatton   2580:      tmp_l = atol (strptr); 
1.151     cvs      2581:    else
                   2582:      tmp_l = DEFAULT_PERSIST_TIMEOUT;
                   2583:    HTHost_setPersistTimeout (tmp_l);
                   2584: 
1.148     cvs      2585:    /* default timeout in ms */
1.203     cvs      2586:    strptr = TtaGetEnvString ("NET_EVENT_TIMEOUT");
1.151     cvs      2587:    if (strptr && *strptr) 
1.288     vatton   2588:      tmp_i = atoi (strptr);
1.151     cvs      2589:    else
                   2590:      tmp_i = DEFAULT_NET_EVENT_TIMEOUT;
                   2591:    HTHost_setEventTimeout (tmp_i);
                   2592: 
1.173     cvs      2593:    HTRequest_setMaxRetry (8);
1.4       cvs      2594: #ifdef CATCH_SIG
1.148     cvs      2595:    signal (SIGPIPE, SIG_IGN);
1.4       cvs      2596: #endif
1.15      cvs      2597: }
                   2598: 
                   2599: /*----------------------------------------------------------------------
1.17      cvs      2600:   LoopForStop
1.136     cvs      2601:   a copy of the Thop event loop so we can handle the stop button in Unix
                   2602:   and preemptive requests under Windows
1.15      cvs      2603:   ----------------------------------------------------------------------*/
                   2604: static int          LoopForStop (AHTReqContext * me)
                   2605: {
1.136     cvs      2606: #ifdef _WINDOWS
                   2607:   MSG msg;
                   2608:   unsigned long libwww_msg;
                   2609:   HWND old_active_window, libwww_window;
                   2610:   int  status_req = HT_OK;
                   2611: 
                   2612:   old_active_window = GetActiveWindow ();
                   2613:   libwww_window = HTEventList_getWinHandle (&libwww_msg);
1.137     cvs      2614:  
1.149     cvs      2615:   while (me->reqStatus != HT_END && me->reqStatus != HT_ERR
1.253     cvs      2616:         && me->reqStatus != HT_ABORT && AmayaIsAlive () &&
                   2617:         GetMessage (&msg, NULL, 0, 0))
                   2618:     {
                   2619:       if (msg.message != WM_QUIT)
                   2620:        TtaHandleOneEvent (&msg);
                   2621:       else
                   2622:        break;      
                   2623:     }
1.136     cvs      2624:   if (!AmayaIsAlive ())
                   2625:     /* Amaya was killed by one of the callback handlers */
                   2626:     exit (0);
                   2627: #else /* _WINDOWS */
1.277     kahan    2628:    ThotEvent                ev;
1.17      cvs      2629:    int                 status_req = HT_OK;
1.15      cvs      2630: 
                   2631:    /* to test the async calls  */
1.17      cvs      2632:    /* Loop while waiting for new events, exists when the request is over */
1.15      cvs      2633:    while (me->reqStatus != HT_ABORT &&
                   2634:          me->reqStatus != HT_END &&
1.69      cvs      2635:          me->reqStatus != HT_ERR) {
1.116     cvs      2636:         if (!AmayaIsAlive ())
1.69      cvs      2637:            /* Amaya was killed by one of the callback handlers */
                   2638:            exit (0);
1.277     kahan    2639:         
                   2640:          if (TtaFetchOneAvailableEvent (&ev))
                   2641:           TtaHandleOneEvent (&ev);
1.69      cvs      2642:    }
1.136     cvs      2643: #endif /* _WINDOWS */
1.69      cvs      2644:    switch (me->reqStatus) {
                   2645:          case HT_ERR:
                   2646:           case HT_ABORT:
1.130     cvs      2647:               status_req = NO;
1.15      cvs      2648:               break;
                   2649: 
1.69      cvs      2650:          case HT_END:
1.130     cvs      2651:               status_req = YES;
1.15      cvs      2652:               break;
                   2653: 
1.69      cvs      2654:          default:
1.15      cvs      2655:               break;
1.69      cvs      2656:    }
1.15      cvs      2657:    return (status_req);
1.4       cvs      2658: }
                   2659: 
1.5       cvs      2660: /*----------------------------------------------------------------------
1.15      cvs      2661:   QueryClose
1.21      cvs      2662:   closes all existing threads, frees all non-automatically deallocated
                   2663:   memory and then ends libwww.
1.5       cvs      2664:   ----------------------------------------------------------------------*/
1.116     cvs      2665: void QueryClose ()
1.4       cvs      2666: {
1.24      cvs      2667: 
1.140     cvs      2668:   AmayaAlive_flag = FALSE;
1.24      cvs      2669: 
1.116     cvs      2670:   /* remove all the handlers and callbacks that may output a message to
                   2671:      a non-existent Amaya window */
                   2672:   HTEvent_setRegisterCallback ((HTEvent_registerCallback *) NULL);
                   2673:   HTEvent_setUnregisterCallback ((HTEvent_unregisterCallback *) NULL);
                   2674: #ifndef _WINDOWS
                   2675:   /** need to erase all existing timers too **/
                   2676:    HTTimer_registerSetTimerCallback (NULL);
                   2677:    HTTimer_registerDeleteTimerCallback (NULL);
                   2678: #endif /* !_WINDOWS */
                   2679:   HTHost_setActivateRequestCallback (NULL);
                   2680:   Thread_deleteAll ();
1.21      cvs      2681:  
1.116     cvs      2682:   HTProxy_deleteAll ();
                   2683:   HTNoProxy_deleteAll ();
1.207     cvs      2684:   SafePut_delete ();
1.116     cvs      2685:   HTGateway_deleteAll ();
                   2686:   AHTProfile_delete ();
1.248     kahan    2687: 
                   2688:   /* close the trace file (if it exists) */
                   2689:   if (trace_fp)
                   2690:     fclose (trace_fp);
                   2691: 
1.116     cvs      2692: }
                   2693: 
                   2694: /*----------------------------------------------------------------------
                   2695:   NextNameValue
                   2696:   ---------------------------------------------------------------------*/
1.265     cvs      2697: static char * NextNameValue (char **pstr, char **name, char **value)
1.116     cvs      2698: {
                   2699:   char * p = *pstr;
                   2700:   char * start = NULL;
                   2701:   if (!pstr || !*pstr) return NULL;
                   2702:   
                   2703:     if (!*p) {
                   2704:       *pstr = p;
                   2705:       *name = NULL;
                   2706:       *value = NULL;
                   2707:       return NULL;                                      /* No field */
                   2708:     }
                   2709:     
                   2710:     /* Now search for the next '&' and ';' delimitators */
                   2711:     start = p;
                   2712:     while (*p && *p != '&' && *p != ';') p++;
                   2713:     if (*p) 
                   2714:       *p++ = '\0';
                   2715:     *pstr = p;
                   2716: 
                   2717:     /* Search for the name and value */
                   2718:     *name = start;
                   2719:     p = start;
                   2720:     
                   2721:     while(*p && *p != '=') 
                   2722:       p++;
                   2723:     if (*p) 
                   2724:       *p++ = '\0';
                   2725:     *value = p;
                   2726: 
                   2727:     return start;
                   2728: }
                   2729: 
                   2730: /*----------------------------------------------------------------------
                   2731:   PrepareFormdata
                   2732:   ---------------------------------------------------------------------*/
1.265     cvs      2733: static   HTAssocList * PrepareFormdata (char *string)
1.116     cvs      2734: {
1.266     cvs      2735:   char          *tmp_string, *tmp_string_ptr;
                   2736:   char          *name;
                   2737:   char          *value;
                   2738:   HTAssocList   *formdata;
1.116     cvs      2739: 
                   2740:   if (!string)
                   2741:     return NULL;
                   2742: 
                   2743:   /* store the ptr in another variable, as the original address will
                   2744:      change
                   2745:      */
1.236     cvs      2746:   
1.265     cvs      2747:   tmp_string_ptr = TtaGetMemory (strlen (string) + 1);
1.236     cvs      2748:   tmp_string = tmp_string_ptr;
1.273     cvs      2749:   strcpy (tmp_string_ptr, string);
1.116     cvs      2750:   formdata = HTAssocList_new();
                   2751:   
                   2752:   while (*tmp_string)
                   2753:     {
                   2754:       NextNameValue (&tmp_string, &name, &value);
                   2755:       HTAssocList_addObject(formdata,
                   2756:                            name, value);
                   2757:     }
                   2758: 
                   2759:   TtaFreeMemory (tmp_string_ptr);
                   2760:   return formdata;
1.4       cvs      2761: }
                   2762: 
1.236     cvs      2763: /*----------------------------------------------------------------------
                   2764:   ---------------------------------------------------------------------*/
1.216     cvs      2765: void AHTRequest_setCustomAcceptHeader (HTRequest *request, char *value)
                   2766: {                              
                   2767:   HTRqHd rqhd = HTRequest_rqHd (request);
                   2768:   rqhd = rqhd & (~HT_C_ACCEPT_TYPE);
                   2769:   HTRequest_setRqHd (request, rqhd);
1.221     cvs      2770:   HTRequest_addExtraHeader (request, "Accept", value);
1.216     cvs      2771: }
                   2772: 
1.228     cvs      2773: /*----------------------------------------------------------------------
1.99      cvs      2774:   InvokeGetObjectWWW_callback
                   2775:   A simple function to invoke a callback function whenever there's an error
                   2776:   in GetObjectWWW
                   2777:   ---------------------------------------------------------------------*/
1.265     cvs      2778: void InvokeGetObjectWWW_callback (int docid, char *urlName,
                   2779:                                  char *outputfile, TTcbf *terminate_cbf,
                   2780:                                  void *context_tcbf, int status)
1.99      cvs      2781: {
                   2782:   if (!terminate_cbf)
                   2783:     return;
                   2784:   
1.116     cvs      2785:   (*terminate_cbf) (docid, status, urlName, outputfile,
1.99      cvs      2786:                    NULL, context_tcbf);  
                   2787: }
                   2788: 
                   2789: 
                   2790: 
1.5       cvs      2791: /*----------------------------------------------------------------------
1.15      cvs      2792:    GetObjectWWW
1.17      cvs      2793:    this function requests a resource designated by a URLname into a
                   2794:    temporary filename. The download can come from a simple GET operation,
                   2795:    or can come from POSTING/GETTING a form. In the latter
                   2796:    case, the function receives a query string to send to the server.
                   2797: 
1.5       cvs      2798:    4  file retrieval modes are proposed:                              
                   2799:    AMAYA_SYNC : blocking mode                            
                   2800:    AMAYA_ISYNC : incremental, blocking mode              
                   2801:    AMAYA_ASYNC : non-blocking mode                       
                   2802:    AMAYA_IASYNC : incremental, non-blocking mode         
                   2803:    
                   2804:    In the incremental mode, each time a package arrives, it will be   
                   2805:    stored in the temporary file. In addition, if an                   
                   2806:    incremental_callback function is defined, this function will be    
                   2807:    called and handled a copy of the newly received data package.      
                   2808:    Finally, if a terminate_callback function is defined, it will be   
                   2809:    invoked when the request terminates. The caller of this function
1.4       cvs      2810:    can define two different contexts to be passed to the callback
                   2811:    functions.
                   2812: 
                   2813:    When the function is called with the SYNC mode, the function will
                   2814:    return only when the requested file has been loaded.
                   2815:    The ASYNC mode will immediately return after setting up the
                   2816:    call.
                   2817: 
                   2818:    Notes:
                   2819:    At the end of a succesful request, the urlName string contains the
                   2820:    name of the actually retrieved URL. As a URL can change over the time,
                   2821:    (e.g., be redirected elsewhere), it is advised that the function
1.17      cvs      2822:    caller verify the value of the urlName variable at the end of
1.4       cvs      2823:    a request.
                   2824: 
                   2825:    Inputs:
                   2826:    - docid  Document identifier for the set of objects being
                   2827:    retrieved.
                   2828:    - urlName The URL to be retrieved (MAX_URL_LENGTH chars length)
                   2829:    - outputfile A pointer to an empty string of MAX_URL_LENGTH.
                   2830:    - mode The retrieval mode.
                   2831:    - incremental_cbf 
                   2832:    - context_icbf
                   2833:    Callback and context for the incremental modes
                   2834:    - terminate_cbf 
                   2835:    - context_icbf
                   2836:    Callback and context for a terminate handler
1.17      cvs      2837:    -error_html if TRUE, then display any server error message as an
                   2838:    HTML document.
1.88      cvs      2839:    - content_type a string
                   2840:  
1.4       cvs      2841:    Outputs:
                   2842:    - urlName The URL that was retrieved
                   2843:    - outputfile The name of the temporary file which holds the
                   2844:    retrieved data. (Only in case of success)
1.88      cvs      2845:    - if content_type wasn't NULL, it will contain a copy of the parameter
                   2846:      sent in the HTTP answer
1.4       cvs      2847:    Returns:
                   2848:    HT_ERROR
                   2849:    HT_OK
1.5       cvs      2850:   ----------------------------------------------------------------------*/
1.265     cvs      2851: int GetObjectWWW (int docid, char *urlName, char *formdata,
                   2852:                  char *outputfile, int mode, TIcbf *incremental_cbf, 
                   2853:                  void *context_icbf, TTcbf *terminate_cbf, 
                   2854:                  void *context_tcbf, ThotBool error_html, char *content_type)
1.4       cvs      2855: {
                   2856:    AHTReqContext      *me;
1.301     vatton   2857:    char               *ref;
                   2858:    char               *esc_url;
1.107     cvs      2859:    int                 status, l;
1.114     cvs      2860:    int                 tempsubdir;
1.191     cvs      2861:    ThotBool            bool_tmp;
1.7       cvs      2862: 
1.116     cvs      2863:    if (urlName == NULL || docid == 0 || outputfile == NULL) 
                   2864:      {
                   2865:        /* no file to be loaded */
                   2866:        TtaSetStatus (docid, 1, TtaGetMessage (AMAYA, AM_BAD_URL), urlName);
1.69      cvs      2867:        
1.116     cvs      2868:        if (error_html)
1.69      cvs      2869:         /* so we can show the error message */
                   2870:         DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
1.116     cvs      2871:        InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
                   2872:                                    context_tcbf, HT_ERROR);
                   2873:        return HT_ERROR;
                   2874:      }
1.7       cvs      2875: 
1.159     cvs      2876:    /* if it's a 'docImage', we have already downloaded it */
1.265     cvs      2877:    if (!strncmp ("internal:", urlName, 9)) 
1.159     cvs      2878:      {
1.265     cvs      2879:        strcpy (outputfile, urlName);
1.159     cvs      2880:        InvokeGetObjectWWW_callback (docid, urlName, outputfile,
                   2881:                                    terminate_cbf, context_tcbf, HT_OK);
                   2882:        return HT_OK;
                   2883:      }
                   2884: 
1.4       cvs      2885:    /* do we support this protocol? */
1.116     cvs      2886:    if (IsValidProtocol (urlName) == NO) 
                   2887:      {
                   2888:        /* return error */
                   2889:        outputfile[0] = EOS;    /* file could not be opened */
                   2890:        TtaSetStatus (docid, 1, 
                   2891:                     TtaGetMessage (AMAYA, AM_GET_UNSUPPORTED_PROTOCOL),
                   2892:                     urlName);
                   2893: 
                   2894:        if (error_html)
1.69      cvs      2895:         /* so we can show the error message */
                   2896:         DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
1.116     cvs      2897:        InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
                   2898:                                    context_tcbf, HT_ERROR);
                   2899:        return HT_ERROR;
                   2900:      }
1.4       cvs      2901: 
1.114     cvs      2902:    /* we store CSS in subdir named 0; all the other files go to a subidr
                   2903:       named after their own docid */
                   2904:    tempsubdir = (mode & AMAYA_LOAD_CSS) ? 0 : docid;
1.116     cvs      2905:    /* create a tempfilename */
1.272     cvs      2906:    sprintf (outputfile, "%s%c%d%c%04dAM", TempFileDirectory, DIR_SEP, tempsubdir, DIR_SEP, object_counter);
1.116     cvs      2907:    /* update the object_counter (used for the tempfilename) */
1.4       cvs      2908:    object_counter++;
                   2909:    /* normalize the URL */
1.300     kahan    2910:    esc_url = EscapeURL (urlName);
1.206     cvs      2911:    if (esc_url) 
                   2912:      {
1.265     cvs      2913:        ref = AmayaParseUrl (esc_url, "", AMAYA_PARSE_ALL);
1.206     cvs      2914:        TtaFreeMemory (esc_url);
                   2915:      }
                   2916:    else
                   2917:      ref = NULL;
                   2918: 
1.4       cvs      2919:    /* should we abort the request if we could not normalize the url? */
1.198     cvs      2920:    if (ref == NULL || ref[0] == EOS) {
1.69      cvs      2921:       /*error */
                   2922:       outputfile[0] = EOS;
                   2923:       TtaSetStatus (docid, 1, TtaGetMessage (AMAYA, AM_BAD_URL), urlName);
1.214     cvs      2924:       if (ref)
                   2925:        TtaFreeMemory (ref); 
1.69      cvs      2926:       if (error_html)
1.116     cvs      2927:        /* so we can show the error message */
                   2928:        DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
1.99      cvs      2929:       InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
1.116     cvs      2930:                                   context_tcbf, HT_ERROR);
1.69      cvs      2931:       return HT_ERROR;
                   2932:    }
1.116     cvs      2933: 
1.4       cvs      2934:    /* verify if that file name existed */
1.9       cvs      2935:    if (TtaFileExist (outputfile))
1.77      cvs      2936:      TtaFileUnlink (outputfile);
1.116     cvs      2937:    
1.4       cvs      2938:    /* Initialize the request structure */
                   2939:    me = AHTReqContext_new (docid);
1.116     cvs      2940:    if (me == NULL) 
                   2941:      {
                   2942:        outputfile[0] = EOS;
                   2943:        /* need an error message here */
                   2944:        TtaFreeMemory (ref);
                   2945:        InvokeGetObjectWWW_callback (docid, urlName, outputfile, terminate_cbf,
                   2946:                                   context_tcbf, HT_ERROR);
                   2947:        return HT_ERROR;
                   2948:      }
                   2949: 
1.4       cvs      2950:    /* Specific initializations for POST and GET */
1.222     cvs      2951:    if (mode & AMAYA_FORM_POST
1.228     cvs      2952:        || mode & AMAYA_FILE_POST)
1.116     cvs      2953:      {
                   2954:        me->method = METHOD_POST;
                   2955:        HTRequest_setMethod (me->request, METHOD_POST);
                   2956:      }
                   2957:    else 
                   2958:      {
1.254     kahan    2959: #ifdef ANNOTATIONS
                   2960:        /* we support the DELETE method for deleting annotations.
                   2961:          the rest of the request is similar to the GET */
                   2962:        if (mode & AMAYA_DELETE)
                   2963:         {
                   2964:           me->method = METHOD_GET;
                   2965:           HTRequest_setMethod (me->request, METHOD_DELETE);
                   2966:         }
                   2967:         else
                   2968: #endif /* ANNOTATIONS */
                   2969:           me->method = METHOD_GET;
1.295     kahan    2970: #ifdef ANNOTATIONS
                   2971:        /* use the custom sent content_type */
                   2972:        if (content_type && content_type[0] != EOS)
                   2973:         AHTRequest_setCustomAcceptHeader (me->request, content_type);
                   2974:        else
                   2975: #endif /* ANNOTATIONS */
                   2976:         if (!HasKnownFileSuffix (ref))
1.216     cvs      2977:         {
                   2978:           /* try to adjust the Accept header in an netwise economical way */
                   2979:           if (mode & AMAYA_LOAD_IMAGE)
                   2980:             AHTRequest_setCustomAcceptHeader (me->request, IMAGE_ACCEPT_NEGOTIATION);
                   2981:           else if (mode & AMAYA_LOAD_CSS)
                   2982:             AHTRequest_setCustomAcceptHeader (me->request, "*/*;q=0.1,css/*");
1.294     kahan    2983:           else
                   2984:             AHTRequest_setCustomAcceptHeader (me->request, GENERAL_ACCEPT_NEGOTIATION);
1.216     cvs      2985:           /*
                   2986:           HTRequest_setConversion(me->request, acceptTypes, TRUE);
                   2987:           */
                   2988:         }
1.295     kahan    2989:         else
                   2990:           AHTRequest_setCustomAcceptHeader (me->request, GENERAL_ACCEPT_NEGOTIATION);
                   2991:        /* language negotiation */
                   2992:        HTRequest_setLanguage (me->request, acceptLanguages, TRUE);
1.116     cvs      2993:      }
1.93      cvs      2994: 
1.116     cvs      2995:    /* Common initialization for all HTML methods */
1.4       cvs      2996:    me->mode = mode;
                   2997:    me->error_html = error_html;
                   2998:    me->incremental_cbf = incremental_cbf;
                   2999:    me->context_icbf = context_icbf;
                   3000:    me->terminate_cbf = terminate_cbf;
                   3001:    me->context_tcbf = context_tcbf;
1.64      cvs      3002: 
1.69      cvs      3003:    /* for the async. request modes, we need to have our
1.4       cvs      3004:       own copy of outputfile and urlname
1.116     cvs      3005:       */
1.4       cvs      3006: 
1.116     cvs      3007:    if ((mode & AMAYA_ASYNC) || (mode & AMAYA_IASYNC)) 
                   3008:      {
1.265     cvs      3009:        l = strlen (outputfile);
1.116     cvs      3010:        if (l > MAX_LENGTH)
1.265     cvs      3011:         me->outputfile = TtaGetMemory (l + 2);
1.116     cvs      3012:        else
1.265     cvs      3013:         me->outputfile = TtaGetMemory (MAX_LENGTH + 2);
                   3014:        strcpy (me->outputfile, outputfile);
                   3015:        l = strlen (urlName);
1.116     cvs      3016:        if (l > MAX_LENGTH)
1.265     cvs      3017:         me->urlName = TtaGetMemory (l + 2);
1.116     cvs      3018:        else
1.265     cvs      3019:         me->urlName = TtaGetMemory (MAX_LENGTH + 2);
                   3020:        strcpy (me->urlName, urlName);
1.116     cvs      3021: #ifdef _WINDOWS
                   3022:      /* force windows ASYNC requests to always be non preemptive */
                   3023:      HTRequest_setPreemptive (me->request, NO);
                   3024: #endif /*_WINDOWS */
                   3025:      } /* AMAYA_ASYNC mode */ 
                   3026:    else 
                   3027: #ifdef _WINDOWS
                   3028:      {
1.233     cvs      3029:        me->outputfile = outputfile;
                   3030:        me->urlName = urlName;
1.116     cvs      3031:        /* force windows SYNC requests to always be non preemptive */
                   3032:        HTRequest_setPreemptive (me->request, YES);
                   3033:      }
                   3034: #else /* !_WINDOWS */
                   3035:      {
                   3036:        me->outputfile = outputfile;
                   3037:        me->urlName = urlName;
                   3038:      }
                   3039:    /***
1.136     cvs      3040:      In order to take into account the stop button, 
                   3041:      the requests will be always asynchronous, however, if mode=AMAYA_SYNC,
1.57      cvs      3042:      we will loop until the document has been received or a stop signal
                   3043:      generated
1.77      cvs      3044:      ****/
1.116     cvs      3045:    HTRequest_setPreemptive (me->request, NO);
                   3046: #endif /* _WINDOWS */
1.61      cvs      3047: 
1.151     cvs      3048:    /*
                   3049:    ** Make sure that the first request is flushed immediately and not
                   3050:    ** buffered in the output buffer
                   3051:    */
                   3052:    if (mode & AMAYA_FLUSH_REQUEST)
                   3053:      HTRequest_setFlush(me->request, YES);
                   3054:    HTRequest_setFlush(me->request, YES);
                   3055: 
1.61      cvs      3056:    /* prepare the URLname that will be displayed in teh status bar */
                   3057:    ChopURL (me->status_urlName, me->urlName);
1.77      cvs      3058:    TtaSetStatus (me->docid, 1, 
                   3059:                 TtaGetMessage (AMAYA, AM_FETCHING),
1.233     cvs      3060:                 me->status_urlName);
1.4       cvs      3061: 
1.265     cvs      3062:    me->anchor = (HTParentAnchor *) HTAnchor_findAddress (ref);
1.45      cvs      3063:    TtaFreeMemory (ref);
1.177     cvs      3064:    
1.223     cvs      3065:    TtaGetEnvBoolean ("CACHE_DISCONNECTED_MODE", &bool_tmp);
1.177     cvs      3066:    if (!bool_tmp && (mode & AMAYA_NOCACHE))
1.116     cvs      3067:       HTRequest_setReloadMode (me->request, HT_CACHE_FLUSH);
                   3068: 
                   3069:    /* prepare the query string and format for POST */
                   3070:    if (mode & AMAYA_FORM_POST)
1.114     cvs      3071:      {
1.116     cvs      3072:        HTAnchor_setFormat ((HTParentAnchor *) me->anchor, 
                   3073:                           HTAtom_for ("application/x-www-form-urlencoded"));
                   3074:        HTAnchor_setLength ((HTParentAnchor *) me->anchor, me->block_size);
                   3075:        HTRequest_setEntityAnchor (me->request, me->anchor);
                   3076:      } 
1.114     cvs      3077: 
1.127     cvs      3078:    /* create the formdata element for libwww */
1.236     cvs      3079:    if (formdata && ! (mode & AMAYA_FILE_POST))
                   3080:       me->formdata = PrepareFormdata (formdata);
1.127     cvs      3081: 
1.297     kirschpi 3082:        
                   3083: #ifdef DAV 
1.302     kirschpi 3084:    /* try to add an "If" header (lock information) also for POST 
                   3085:     * requests and for GET forms */
1.297     kirschpi 3086:    if (HTRequest_method(me->request) == METHOD_POST ||
                   3087:           (HTRequest_method(me->request) == METHOD_GET && me->formdata))          
                   3088:        DAVAddIfHeader (me,HTAnchor_address((HTAnchor*)me->anchor));
1.302     kirschpi 3089: #endif /* DAV */
1.297     kirschpi 3090:        
                   3091:    
1.116     cvs      3092:    /* do the request */
                   3093:    if (mode & AMAYA_FORM_POST)
1.119     cvs      3094:      {
1.191     cvs      3095:        /* this call doesn't give back a ThotBool */
1.119     cvs      3096:        HTParentAnchor * posted = NULL;
                   3097: 
                   3098:        posted = HTPostFormAnchor (me->formdata, (HTAnchor *) me->anchor, 
                   3099:                                    me->request);
                   3100:        status = posted ? YES : NO; 
                   3101:      }
1.222     cvs      3102: #ifdef ANNOTATIONS
1.251     kahan    3103:    else if (mode & AMAYA_FILE_POST)
1.222     cvs      3104:      {
1.228     cvs      3105:        unsigned long filesize;
                   3106:        char *fileURL;
                   3107: 
                   3108:        /* @@@ a very ugly patch :)))
                   3109:        I'm copying here some of the functionality I use in the PUT
                   3110:        I need to put the common parts in another module */
1.252     kahan    3111:        AM_GetFileSize (formdata, &filesize);
1.228     cvs      3112:        me->block_size = filesize;
                   3113: 
1.233     cvs      3114:        fileURL = HTParse (formdata, "file:/", PARSE_ALL);
1.228     cvs      3115:        me->source = HTAnchor_findAddress (fileURL);
                   3116:        HT_FREE (fileURL);
1.222     cvs      3117: 
1.228     cvs      3118:        /* hardcoded ... */
                   3119:        AHTRequest_setCustomAcceptHeader (me->request, "application/xml");
1.222     cvs      3120:        HTAnchor_setFormat (HTAnchor_parent (me->source),
                   3121:                           HTAtom_for ("application/xml"));
1.228     cvs      3122:        HTAnchor_setFormat (me->anchor,
                   3123:                           HTAtom_for ("application/xml"));
                   3124:        HTAnchor_setLength ((HTParentAnchor *) me->source, me->block_size);
                   3125:        /* @@ here I need to actually read the file and put it in document,
                   3126:          then, when I kill the request, I need to kill it */
                   3127:        {
                   3128:         FILE *fp;
                   3129:         int i;
                   3130:         char c;
                   3131: 
1.255     swick    3132:         me->document = TtaGetMemory (me->block_size + 1);
1.233     cvs      3133:         fp = fopen (formdata, "r");
1.244     kahan    3134:         i = 0; 
1.228     cvs      3135:         c = getc (fp);
                   3136:         while (!feof (fp))
                   3137:           {
                   3138:             me->document[i++] = c;
                   3139:             c = getc (fp);
                   3140:           }
                   3141:         me->document[i] = '\0';
                   3142:         fclose (fp);
                   3143:        }
                   3144:        HTAnchor_setDocument ( (HTParentAnchor *) me->source,
                   3145:                              (void * ) me->document);
                   3146:        HTRequest_setEntityAnchor (me->request, HTAnchor_parent (me->source));
                   3147:  
                   3148:        status = HTPostAnchor (HTAnchor_parent (me->source), 
1.222     cvs      3149:                              (HTAnchor *) me->anchor, 
                   3150:                              me->request);
                   3151:      }
                   3152: #endif /* ANNOTATIONS */
1.127     cvs      3153:    else if (formdata)
                   3154:      status = HTGetFormAnchor(me->formdata, (HTAnchor *) me->anchor,
                   3155:                              me->request);
1.116     cvs      3156:    else
1.77      cvs      3157:      status = HTLoadAnchor ((HTAnchor *) me->anchor, me->request);
1.69      cvs      3158: 
1.123     cvs      3159:    /* @@@ may need some special windows error msg here */
1.116     cvs      3160:    /* control the errors */
1.4       cvs      3161: 
1.130     cvs      3162:     if (status == NO)
1.116     cvs      3163:      /* the request invocation failed */
                   3164:      {
                   3165:        /* show an error message on the status bar */
                   3166:        DocNetworkStatus[docid] |= AMAYA_NET_ERROR;
                   3167:        TtaSetStatus (docid, 1, 
                   3168:                     TtaGetMessage (AMAYA, AM_CANNOT_LOAD),
                   3169:                     urlName);
                   3170:        if (me->reqStatus == HT_NEW)
                   3171:         /* manually invoke the last processing that usually gets done
                   3172:            in a succesful request */
                   3173:         InvokeGetObjectWWW_callback (docid, urlName, outputfile, 
                   3174:                                      terminate_cbf, context_tcbf, HT_ERROR);
                   3175:        /* terminate_handler wasn't called */
1.136     cvs      3176:        AHTReqContext_delete (me);
1.116     cvs      3177:      }
                   3178:    else
1.136     cvs      3179:      /* end treatment for SYNC requests */
1.120     cvs      3180:      if ((mode & AMAYA_SYNC) || (mode & AMAYA_ISYNC))
                   3181:        {
1.136     cvs      3182:         /* wait here untilt the asynchronous request finishes */
1.130     cvs      3183:         status = LoopForStop (me);
1.136     cvs      3184:         /* if status returns HT_ERROR, should we invoke the callback? */
1.120     cvs      3185:         if (!HTRequest_kill (me->request))
                   3186:           AHTReqContext_delete (me);
                   3187:        }
1.130     cvs      3188: 
1.136     cvs      3189:     /* an interface problem!!! */
                   3190:     return (status == YES ? 0 : -1);
1.4       cvs      3191: }
                   3192: 
1.5       cvs      3193: /*----------------------------------------------------------------------
1.17      cvs      3194:    PutObjectWWW
                   3195:    frontend for uploading a resource to a URL. This function downloads
                   3196:    a file to be uploaded into memory, it then calls UploadMemWWW to
                   3197:    finish the job.
                   3198: 
1.5       cvs      3199:    2 upload modes are proposed:                                       
                   3200:    AMAYA_SYNC : blocking mode                            
                   3201:    AMAYA_ASYNC : non-blocking mode                       
                   3202:    
1.4       cvs      3203:    When the function is called with the SYNC mode, the function will
                   3204:    return only when the file has been uploaded.
                   3205:    The ASYNC mode will immediately return after setting up the
                   3206:    call. Furthermore, at the end of an upload, the ASYNC mode will 
                   3207:    call back terminate_cbf, handling it the context defined in
                   3208:    context_tcbf.
                   3209: 
                   3210:    Notes:
                   3211:    At the end of a succesful request, the urlName string contains the
                   3212:    name of the actually uploaded URL. As a URL can change over the time,
                   3213:    (e.g., be redirected elsewhere), it is advised that the function
                   3214:    caller verifies the value of the urlName variable at the end of
                   3215:    a request.
                   3216: 
                   3217:    Inputs:
                   3218:    - docid  Document identifier for the set of objects being
                   3219:    retrieved.
                   3220:    - fileName A pointer to the local file to upload
                   3221:    - urlName The URL to be uploaded (MAX_URL_LENGTH chars length)
                   3222:    - mode The retrieval mode.
                   3223:    - terminate_cbf 
                   3224:    - context_icbf
                   3225:    Callback and context for a terminate handler
                   3226: 
                   3227:    Outputs:
                   3228:    - urlName The URL that was uploaded
                   3229: 
                   3230:    Returns:
                   3231:    HT_ERROR
                   3232:    HT_OK
1.5       cvs      3233:   ----------------------------------------------------------------------*/
1.276     kahan    3234: int PutObjectWWW (int docid, char *fileName, char *urlName, 
                   3235:                  char *contentType, int mode,
1.265     cvs      3236:                  TTcbf *terminate_cbf, void *context_tcbf)
1.4       cvs      3237: {
1.116     cvs      3238:    AHTReqContext      *me;
1.250     cvs      3239:    CHARSET             charset;
1.4       cvs      3240:    int                 status;
1.250     cvs      3241:    unsigned long       file_size;
1.116     cvs      3242:    char               *fileURL;
1.168     cvs      3243:    char               *etag = NULL;
1.169     cvs      3244:    HTParentAnchor     *dest_anc_parent;
1.265     cvs      3245:    char               *tmp;
                   3246:    char               *esc_url;
1.168     cvs      3247:    int                 UsePreconditions;
1.191     cvs      3248:    ThotBool            lost_update_check = TRUE;
1.235     cvs      3249:    char                url_name[MAX_LENGTH];
1.285     kahan    3250:    char               *resource_name;
1.265     cvs      3251:    char               *tmp2;
1.239     cvs      3252: #ifdef _WINDOWS
                   3253:    char                file_name[MAX_LENGTH];
                   3254: #endif /* _WINDOWS */
1.172     cvs      3255: 
                   3256:    /* should we protect the PUT against lost updates? */
1.203     cvs      3257:    tmp = TtaGetEnvString ("ENABLE_LOST_UPDATE_CHECK");
1.265     cvs      3258:    if (tmp && *tmp && strcasecmp (tmp, "yes"))
1.172     cvs      3259:      lost_update_check = FALSE;
1.168     cvs      3260: 
                   3261:    UsePreconditions = mode & AMAYA_USE_PRECONDITIONS;
1.4       cvs      3262: 
1.33      cvs      3263:    AmayaLastHTTPErrorMsg [0] = EOS;
1.256     kahan    3264:    AmayaLastHTTPErrorMsgR [0] = EOS;
                   3265: 
1.33      cvs      3266:    
1.116     cvs      3267:    if (urlName == NULL || docid == 0 || fileName == NULL 
                   3268:        || !TtaFileExist (fileName))
1.4       cvs      3269:       /* no file to be uploaded */
                   3270:       return HT_ERROR;
                   3271: 
                   3272:    /* do we support this protocol? */
1.7       cvs      3273:    if (IsValidProtocol (urlName) == NO)
                   3274:      {
                   3275:        /* return error */
1.198     cvs      3276:        TtaSetStatus (docid, 1, TtaGetMessage (AMAYA, AM_PUT_UNSUPPORTED_PROTOCOL), urlName);
1.7       cvs      3277:        return HT_ERROR;
                   3278:      }
1.116     cvs      3279: 
1.228     cvs      3280:    /* get the size of the file */
1.252     kahan    3281:    if (!AM_GetFileSize (fileName, &file_size) || file_size == 0L)
1.7       cvs      3282:      {
                   3283:        /* file was empty */
                   3284:        /*errmsg here */
                   3285:        return (HT_ERROR);
                   3286:      }
1.116     cvs      3287: 
                   3288:    /* prepare the request context */
1.4       cvs      3289:    if (THD_TRACE)
1.228     cvs      3290:       fprintf (stderr, "file size == %u\n", (unsigned) file_size);
1.4       cvs      3291: 
                   3292:    me = AHTReqContext_new (docid);
1.7       cvs      3293:    if (me == NULL)
                   3294:      {
1.168     cvs      3295:        /* @@ need an error message here */
1.151     cvs      3296:        TtaHandlePendingEvents (); 
1.7       cvs      3297:        return (HT_ERROR);
1.208     cvs      3298:      }
                   3299: 
                   3300:    /*
                   3301:    ** Set up the original URL name
                   3302:    */
1.285     kahan    3303: 
                   3304:    /* are we using content-location? */
                   3305:    if (DocumentMeta[docid]->content_location)
                   3306:      resource_name = DocumentMeta[docid]->content_location;
                   3307:    else
                   3308:      resource_name = NULL;
                   3309: 
                   3310:    /* prepare the target URL */
                   3311:    if (resource_name)
1.208     cvs      3312:      {
1.285     kahan    3313:        tmp = strstr (urlName, resource_name);     
                   3314:        if (!tmp)
1.208     cvs      3315:         {
1.285     kahan    3316:           /* urlName does not include the resource name */
                   3317:           me->default_put_name = TtaGetMemory (strlen (urlName)
                   3318:                                                + strlen (resource_name)
                   3319:                                                + sizeof (URL_SEP)
                   3320:                                                + 1);
                   3321:           strcpy (me->default_put_name, urlName);
                   3322:           tmp = strrchr (me->default_put_name, URL_SEP);
                   3323:           if (tmp)
1.208     cvs      3324:             {
1.285     kahan    3325:               /* it is a URL finishing in /. Only add the resrouce name */
                   3326:               tmp++;
                   3327:               strcpy (tmp, resource_name);
                   3328:             }
                   3329:           else
                   3330:             {
                   3331:               strcat (me->default_put_name, URL_STR);
                   3332:               strcat (me->default_put_name, resource_name);
1.208     cvs      3333:             }
                   3334:         }
1.7       cvs      3335:      }
1.285     kahan    3336:    
                   3337:    if (!me->default_put_name)
1.271     kahan    3338:      me->default_put_name = TtaStrdup (urlName);
                   3339:    
1.285     kahan    3340:    HTRequest_setDefaultPutName (me->request, me->default_put_name);
1.116     cvs      3341: 
1.4       cvs      3342:    me->mode = mode;
                   3343:    me->incremental_cbf = (TIcbf *) NULL;
                   3344:    me->context_icbf = (void *) NULL;
                   3345:    me->terminate_cbf = terminate_cbf;
                   3346:    me->context_tcbf = context_tcbf;
1.286     kahan    3347: 
                   3348:    /* normalize the URL */
1.300     kahan    3349:    esc_url = EscapeURL (urlName);
1.272     cvs      3350:    me->urlName = TtaStrdup (esc_url);
1.206     cvs      3351:    TtaFreeMemory (esc_url);
1.300     kahan    3352: 
1.228     cvs      3353:    me->block_size =  file_size;
1.17      cvs      3354:    /* select the parameters that distinguish a PUT from a GET/POST */
1.4       cvs      3355:    me->method = METHOD_PUT;
                   3356:    me->output = stdout;
1.17      cvs      3357:    /* we are not expecting to receive any input from the server */
1.265     cvs      3358:    me->outputfile = (char  *) NULL; 
1.4       cvs      3359: 
1.134     cvs      3360: #ifdef _WINDOWS
                   3361:    /* libwww's HTParse function doesn't take into account the drive name;
1.168     cvs      3362:       so we sidestep it */
1.238     cvs      3363: 
1.134     cvs      3364:    fileURL = NULL;
                   3365:    StrAllocCopy (fileURL, "file:");
1.273     cvs      3366:    strcpy (file_name, fileName);
1.235     cvs      3367:    StrAllocCat (fileURL, file_name);
1.134     cvs      3368: #else
1.116     cvs      3369:    fileURL = HTParse (fileName, "file:/", PARSE_ALL);
1.134     cvs      3370: #endif /* _WINDOWS */
1.168     cvs      3371:    me->source = HTAnchor_findAddress (fileURL);
1.116     cvs      3372:    HT_FREE (fileURL);
1.273     cvs      3373:    strcpy (url_name, me->urlName);
1.235     cvs      3374:    me->dest = HTAnchor_findAddress (url_name);
1.169     cvs      3375:    /* we memorize the anchor's parent @ as we use it a number of times
                   3376:       in the following lines */
                   3377:    dest_anc_parent = HTAnchor_parent (me->dest);
1.168     cvs      3378: 
1.169     cvs      3379:    /*
                   3380:    **  Set the Content-Type of the file we are uploading 
                   3381:    */
                   3382:    /* we try to use any content-type previosuly associated
                   3383:       with the parent. If it doesn't exist, we try to guess it
                   3384:       from the URL */
1.276     kahan    3385:    /* @@ JK: trying to use the content type we stored */
                   3386:    /*
1.235     cvs      3387:    tmp2 = HTAtom_name (HTAnchor_format (dest_anc_parent));
1.276     kahan    3388:    */
                   3389:    tmp2 = NULL;
1.235     cvs      3390:    if (!tmp2 || !strcmp (tmp2, "www/unknown"))
1.169     cvs      3391:      {
1.260     kahan    3392:        HTAtom *tmp_atom;
1.276     kahan    3393:        
1.260     kahan    3394:        tmp_atom = AHTGuessAtom_for (me->urlName, contentType);
1.276     kahan    3395:        if (!tmp_atom || !strcmp (HTAtom_name (tmp_atom), "www/unknown"))
                   3396:         {
                   3397:           /* ask the user for a MIME type */
                   3398:         }
1.260     kahan    3399:        HTAnchor_setFormat (dest_anc_parent, tmp_atom);
1.235     cvs      3400:        tmp2 = HTAtom_name (HTAnchor_format (dest_anc_parent));
1.169     cvs      3401:      }
                   3402:    /* .. and we give the same type to the source anchor */
                   3403:    /* we go thru setOutputFormat, rather than change the parent's
                   3404:       anchor, as that's the place that libwww expects it to be */
1.235     cvs      3405:    HTAnchor_setFormat (HTAnchor_parent (me->source), HTAtom_for (tmp2));
1.219     cvs      3406: 
1.235     cvs      3407:    HTRequest_setOutputFormat (me->request, HTAtom_for (tmp2));
1.219     cvs      3408: 
                   3409:    /*
                   3410:    **  Set the Charset of the file we are uploading 
                   3411:    */
1.240     cvs      3412:    /* we set the charset as indicated in the document's metadata
                   3413:       structure (and only if it exists) */
1.250     cvs      3414:    charset = TtaGetDocumentCharset (docid);
                   3415:    if (charset != UNDEFINED_CHARSET)
1.240     cvs      3416:      {
1.250     cvs      3417:        tmp =  TtaGetCharsetName (charset);
1.272     cvs      3418:        if (tmp && *tmp != EOS)
1.250     cvs      3419:         {
1.273     cvs      3420:           tmp2 = TtaStrdup (tmp);
1.250     cvs      3421:           HTAnchor_setCharset (dest_anc_parent, HTAtom_for (tmp2));
                   3422:           TtaFreeMemory (tmp2);
                   3423:           tmp2 = HTAtom_name (HTAnchor_charset (dest_anc_parent));
                   3424:           /* .. and we give the same charset to the source anchor */
                   3425:           /* we go thru setCharSet, rather than change the parent's
                   3426:              anchor, as that's the place that libwww expects it to be */
                   3427:           HTAnchor_setCharset (HTAnchor_parent (me->source),
                   3428:                                HTAtom_for (tmp2));
                   3429:         }
1.219     cvs      3430:      }
                   3431: 
                   3432:    /*
                   3433:    ** define other request characteristics
                   3434:    */
1.116     cvs      3435: #ifdef _WINDOWS
1.136     cvs      3436:    HTRequest_setPreemptive (me->request, NO);
1.116     cvs      3437: #else
1.134     cvs      3438:    HTRequest_setPreemptive (me->request, NO);
1.116     cvs      3439: #endif /* _WINDOWS */
                   3440: 
1.151     cvs      3441:    /*
                   3442:    ** Make sure that the first request is flushed immediately and not
                   3443:    ** buffered in the output buffer
                   3444:    */
                   3445:    if (mode & AMAYA_FLUSH_REQUEST)
                   3446:      HTRequest_setFlush(me->request, YES);
1.168     cvs      3447:    
                   3448:    /* Should we use preconditions? */
1.172     cvs      3449:    if (lost_update_check)
1.168     cvs      3450:      {
1.172     cvs      3451:        if (UsePreconditions) 
                   3452:         etag = HTAnchor_etag (HTAnchor_parent (me->dest));
                   3453:        
                   3454:        if (etag) 
                   3455:         {
                   3456:           HTRequest_setPreconditions(me->request, HT_MATCH_THIS);
                   3457:         }
                   3458:        else
                   3459:         {
                   3460:           HTRequest_setPreconditions(me->request, HT_NO_MATCH);
                   3461:           HTRequest_addAfter(me->request, check_handler, NULL, NULL, HT_ALL,
                   3462:                              HT_FILTER_MIDDLE, YES);
1.175     cvs      3463:           HTRequest_addAfter (me->request, HTAuthFilter, "http://*", NULL, 
                   3464:                               HT_NO_ACCESS, HT_FILTER_MIDDLE, YES);
                   3465:           HTRequest_addAfter (me->request, HTAuthFilter, "http://*", NULL,
                   3466:                               HT_REAUTH, HT_FILTER_MIDDLE, YES);
                   3467:           HTRequest_addAfter (me->request, HTAuthInfoFilter, "http://*", NULL,
                   3468:                               HT_ALL, HT_FILTER_MIDDLE, YES);
                   3469:           HTRequest_addAfter (me->request, HTUseProxyFilter, "http://*", NULL,
                   3470:                               HT_USE_PROXY, HT_FILTER_MIDDLE, YES);
1.172     cvs      3471:         }
1.168     cvs      3472:      }
                   3473:    else
                   3474:      {
1.172     cvs      3475:        /* don't use preconditions */
1.168     cvs      3476:        HTRequest_setPreconditions(me->request, HT_NO_MATCH);
                   3477:      }
1.151     cvs      3478:    
1.136     cvs      3479:    /* don't use the cache while saving a document */
                   3480:    HTRequest_setReloadMode (me->request, HT_CACHE_FLUSH);
1.116     cvs      3481: 
1.164     cvs      3482:    /* Throw away any reponse body */
                   3483:    /*
                   3484:    HTRequest_setOutputStream (me->request, HTBlackHole());        
                   3485:    */
                   3486: 
1.168     cvs      3487:    /* prepare the URLname that will be displayed in the status bar */
1.74      cvs      3488:    ChopURL (me->status_urlName, me->urlName);
1.233     cvs      3489:    TtaSetStatus (me->docid, 1, TtaGetMessage (AMAYA, AM_REMOTE_SAVING), me->status_urlName);
1.114     cvs      3490: 
1.297     kirschpi 3491:    
                   3492: #ifdef DAV
1.302     kirschpi 3493:    /* MKP: for a PUT request, try to add an "If" header (lock information)
1.297     kirschpi 3494:     * for a HEAD request, leave this for check_handler */
                   3495:    if ( !(lost_update_check && (!UsePreconditions || !etag)) )
                   3496:        DAVAddIfHeader (me,HTAnchor_address(me->dest));   
1.302     kirschpi 3497: #endif /* DAV */
1.297     kirschpi 3498: 
                   3499:    
1.164     cvs      3500:    /* make the request */
1.172     cvs      3501:    if (lost_update_check && (!UsePreconditions || !etag))
1.168     cvs      3502:      status = HTHeadAnchor (me->dest, me->request);
                   3503:    else
                   3504:      status = HTPutDocumentAnchor (HTAnchor_parent (me->source), me->dest, me->request);
1.4       cvs      3505: 
1.130     cvs      3506:    if (status == YES && me->reqStatus != HT_ERR)
1.7       cvs      3507:      {
1.168     cvs      3508:        /* part of the stop button handler */
                   3509:        if ((mode & AMAYA_SYNC) || (mode & AMAYA_ISYNC))
                   3510:         status = LoopForStop (me);
1.15      cvs      3511:      }
1.136     cvs      3512:    if (!HTRequest_kill (me->request))
                   3513:      AHTReqContext_delete (me);
1.168     cvs      3514:    
1.116     cvs      3515:    TtaHandlePendingEvents ();
1.90      cvs      3516: 
1.130     cvs      3517:    return (status == YES ? 0 : -1);
1.28      cvs      3518: }
1.4       cvs      3519: 
1.5       cvs      3520: /*----------------------------------------------------------------------
1.138     cvs      3521:   StopRequest
1.17      cvs      3522:   stops (kills) all active requests associated with a docid 
1.5       cvs      3523:   ----------------------------------------------------------------------*/
1.4       cvs      3524: void                StopRequest (int docid)
                   3525: {
1.140     cvs      3526:    if (Amaya && CanDoStop ())
1.138     cvs      3527:      { 
1.139     cvs      3528: #if 0 /* for later */
1.140     cvs      3529:        AHTDocId_Status    *docid_status;
                   3530:         /* verify if there are any requests at all associated with docid */
1.138     cvs      3531:        docid_status = (AHTDocId_Status *) GetDocIdStatus (docid,
                   3532:                                                          Amaya->docid_status);
                   3533:        if (docid_status == (AHTDocId_Status *) NULL)
                   3534:         return;
1.139     cvs      3535: #endif /* 0 */
1.138     cvs      3536:        /* temporary call to stop all requests, as libwww changed its API */
                   3537:        StopAllRequests (docid);
                   3538:      }
                   3539: }
                   3540: 
1.190     cvs      3541: /* @@@ the docid parameter isn't used... clean it up */
1.138     cvs      3542: /*----------------------------------------------------------------------
                   3543:   StopAllRequests
                   3544:   stops (kills) all active requests. We use the docid 
                   3545:   ----------------------------------------------------------------------*/
                   3546: void                StopAllRequests (int docid)
                   3547: {
1.4       cvs      3548:    HTList             *cur;
                   3549:    AHTReqContext      *me;
1.191     cvs      3550:    static ThotBool     lock_stop = 0;
                   3551:    ThotBool            async_flag;
1.232     cvs      3552:    AHTReqStatus        old_reqStatus;
1.116     cvs      3553: 
1.138     cvs      3554:    /* only do the stop if we're not being called while processing a 
1.146     cvs      3555:       request, and if we're not already dealing with a stop */
                   3556:    if (Amaya && CanDoStop () && !lock_stop)
1.7       cvs      3557:      {
1.100     cvs      3558: #ifdef DEBUG_LIBWWW
1.138     cvs      3559:        fprintf (stderr, "StopRequest: number of Amaya requests "
                   3560:                "before kill: %d\n", Amaya->open_requests);
1.100     cvs      3561: #endif /* DEBUG_LIBWWW */
1.150     cvs      3562:        /* enter the critical section */
1.146     cvs      3563:        lock_stop = TRUE; 
1.214     cvs      3564:        /* set a module global variable so that we can do special
                   3565:          processing easier */
                   3566:        UserAborted_flag = TRUE;
1.232     cvs      3567:        /* abort all outstanding libwww UI dialogues */
1.265     cvs      3568:        CallbackDialogue (BaseDialog + FormAnswer,  STRING_DATA, NULL);
                   3569:        CallbackDialogue (BaseDialog + ConfirmForm, INTEGER_DATA, NULL);
1.164     cvs      3570:        /* expire all outstanding timers */
                   3571:        HTTimer_expireAll ();
1.160     cvs      3572:        /* HTNet_killAll (); */
1.245     kahan    3573:        if (Amaya->open_requests)
1.116     cvs      3574:         {
1.245     kahan    3575:           cur = Amaya->reqlist;
                   3576:           while ((me = (AHTReqContext *) HTList_nextObject (cur))) 
1.160     cvs      3577:             {
1.245     kahan    3578:               if (AmayaIsAlive ())
                   3579:                 {
1.161     cvs      3580: #ifdef DEBUG_LIBWWW
1.245     kahan    3581:                   fprintf (stderr,"StopRequest: killing req %p, url %s, status %d\n", me, me->urlName, me->reqStatus);
1.161     cvs      3582: #endif /* DEBUG_LIBWWW */
1.245     kahan    3583:                   
                   3584:                   if (me->reqStatus != HT_END && me->reqStatus != HT_ABORT)
1.163     cvs      3585:                     {
1.245     kahan    3586:                       if ((me->mode & AMAYA_ASYNC)
                   3587:                           || (me->mode & AMAYA_IASYNC))
                   3588:                         async_flag = TRUE;
                   3589:                       else
                   3590:                         async_flag = FALSE;
                   3591:                       
                   3592:                       /* change the status to say that the request aborted */
                   3593:                       /* if the request was "busy", we just change a flag to say so and
                   3594:                          let the handler finish the processing itself */
                   3595:                       old_reqStatus = me->reqStatus;
                   3596:                       me->reqStatus = HT_ABORT;
                   3597:                       if (old_reqStatus == HT_BUSY)
                   3598:                         continue;
                   3599:                       
                   3600:                       /* kill the request, using the appropriate function */
                   3601:                       if (me->request->net)
                   3602:                         HTNet_killPipe (me->request->net);
                   3603:                       else
                   3604:                         {
                   3605:                           if (me->terminate_cbf)
                   3606:                             (*me->terminate_cbf) (me->docid, -1, me->urlName,
                   3607:                                                   me->outputfile,
                   3608:                                                   NULL,
                   3609:                                                   me->context_tcbf);
                   3610:                           
                   3611:                           if (async_flag) 
                   3612:                             /* explicitly free the request context for async
                   3613:                                requests. The sync requests context is freed
                   3614:                                by LoopForStop */
                   3615:                             AHTReqContext_delete (me);
                   3616:                         }
                   3617:                       cur = Amaya->reqlist;
1.160     cvs      3618:                     }
1.142     cvs      3619: #ifndef _WINDOWS
                   3620: #ifdef WWW_XWINDOWS
1.245     kahan    3621:                   /* to be on the safe side, remove all outstanding 
                   3622:                      X events */
1.160     cvs      3623:                   else 
                   3624:                     RequestKillAllXtevents (me);
1.142     cvs      3625: #endif /* WWW_XWINDOWS */
                   3626: #endif /* !_WINDOWS */
1.245     kahan    3627:                 }
1.160     cvs      3628:             }
1.245     kahan    3629:           /* Delete remaining channels */
                   3630:           HTChannel_safeDeleteAll ();
1.116     cvs      3631:         }
1.214     cvs      3632:        /* reset the stop status */
                   3633:        UserAborted_flag = FALSE;
1.150     cvs      3634:        /* exit the critical section */
1.148     cvs      3635:        lock_stop = FALSE; 
1.100     cvs      3636: #ifdef DEBUG_LIBWWW
1.138     cvs      3637:        fprintf (stderr, "StopRequest: number of Amaya requests "
                   3638:                "after kill: %d\n", Amaya->open_requests);
1.100     cvs      3639: #endif /* DEBUG_LIBWWW */
1.138     cvs      3640:      }
                   3641: } /* StopAllRequests */
1.17      cvs      3642: 
                   3643: 
1.105     cvs      3644: /*----------------------------------------------------------------------
                   3645:   AmayaIsAlive
1.140     cvs      3646:   returns the value of the AmayaAlive_flag
1.105     cvs      3647:   ----------------------------------------------------------------------*/
1.191     cvs      3648: ThotBool AmayaIsAlive (void)
1.105     cvs      3649: {
1.140     cvs      3650:   return AmayaAlive_flag;
                   3651: }
                   3652: 
                   3653: /*----------------------------------------------------------------------
                   3654:   CanDoStop
                   3655:   returns the value of the CanDoStop flag
                   3656:   ----------------------------------------------------------------------*/
1.191     cvs      3657: ThotBool CanDoStop (void)
1.140     cvs      3658: {
                   3659:   return CanDoStop_flag;
                   3660: }
                   3661: 
                   3662: /*----------------------------------------------------------------------
                   3663:   CanDoStop_set
                   3664:   sets the value of the CanDoStop flag
                   3665:   ----------------------------------------------------------------------*/
1.191     cvs      3666: void CanDoStop_set (ThotBool value)
1.140     cvs      3667: {
                   3668:   CanDoStop_flag = value;
1.176     cvs      3669: }
                   3670: 
1.265     cvs      3671: /*----------------------------------------------------------------------
                   3672:   ----------------------------------------------------------------------*/
1.176     cvs      3673: void libwww_updateNetworkConf (int status)
                   3674: {
                   3675:   /* @@@ the docid parameter isn't used... clean it up */
                   3676:   int docid = 1;
                   3677: 
                   3678:   /* first, stop all current requests, as the network
                   3679:    may make some changes */
                   3680:   StopAllRequests (docid);
1.207     cvs      3681: 
                   3682:   if (status & AMAYA_SAFEPUT_RESTART)
                   3683:     { 
                   3684:       SafePut_delete ();
                   3685:       SafePut_init ();
                   3686:     }
1.176     cvs      3687: 
                   3688:   if (status & AMAYA_PROXY_RESTART)
                   3689:     {
                   3690:       HTProxy_deleteAll ();
                   3691:       ProxyInit ();
                   3692:     }
                   3693: 
                   3694:   if (status & AMAYA_CACHE_RESTART)
                   3695:     {
                   3696:       clear_cachelock ();
                   3697:       HTCacheTerminate ();
                   3698:       HTCacheMode_setEnabled (NO);
                   3699:       CacheInit ();
                   3700:     }
1.193     cvs      3701: 
                   3702:   if (status & AMAYA_LANNEG_RESTART)
                   3703:     {
                   3704:       /* clear the current values */
                   3705:       if (acceptLanguages)
                   3706:        HTLanguage_deleteAll (acceptLanguages);
                   3707:       /* read in the new ones */
                   3708:       acceptLanguages = HTList_new ();
                   3709:       AHTAcceptLanguagesInit (acceptLanguages);
                   3710:     }
1.105     cvs      3711: }
1.246     kahan    3712: 
                   3713: /****************************************************************************
                   3714:  ** The following two functions allow to set and read the value of          *
                   3715:  ** the  FTPURL_flag. If this flag is true, it means we can browse FTP URLs *
                   3716:  ***************************************************************************/
                   3717: 
                   3718: /*----------------------------------------------------------------------
                   3719:   AHT_FTPURL_flag_set
                   3720:   ----------------------------------------------------------------------*/
                   3721: void AHTFTPURL_flag_set (ThotBool value)
                   3722: {
                   3723:   FTPURL_flag = value;
                   3724: }
                   3725: 
                   3726: /*----------------------------------------------------------------------
                   3727:   AHT_FTPURL_flag
                   3728:   ----------------------------------------------------------------------*/
                   3729: ThotBool AHTFTPURL_flag (void)
                   3730: {
                   3731:   return (FTPURL_flag);
                   3732: }
1.308     kahan    3733: 
                   3734: 
                   3735: /*----------------------------------------------------------------------
                   3736:   CheckSingleInstance
                   3737:   Returns TRUE if this is the single instance of Amaya in the system,
                   3738:   FALSE otherwise. 
                   3739:   N.B. : This implementation is naif.
                   3740:   ----------------------------------------------------------------------*/
                   3741: ThotBool CheckSingleInstance (char *pid_dir)
                   3742: {
                   3743: #ifdef _WINDOWS
                   3744:   HWND hwnd;
                   3745: 
1.310     cvs      3746:   hwnd = FindWindow ("Amaya", NULL);
1.308     kahan    3747: 
                   3748:   if (!hwnd)
                   3749:     return TRUE;
                   3750:   else
                   3751:     return FALSE;
                   3752: 
                   3753: #else /* _WINDOWS */
                   3754: 
                   3755:   int instances;
                   3756:   char *ptr;
                   3757:   pid_t pid;
                   3758: 
                   3759:   DIR *dp;
                   3760:   struct stat st;
                   3761: #ifdef HAVE_DIRENT_H
                   3762:   struct dirent *d;
                   3763: #else
                   3764:   struct direct *d;
                   3765: #endif /* HAVE_DIRENT_H */
                   3766:   char filename[BUFSIZ+1];
                   3767: 
                   3768:   if ((dp = opendir (pid_dir)) == NULL) 
                   3769:     {
                   3770:       /* @@@ we couldn't open the directory ... we need some msg */
                   3771:       perror (pid_dir);
                   3772:       return FALSE;
                   3773:     }
                   3774: 
                   3775:   instances = 0;
                   3776: 
                   3777:   while ((d = readdir (dp)) != NULL)
                   3778:     {
                   3779:       /* skip the UNIX . and .. links */
                   3780:       if (!strcmp (d->d_name, "..")
                   3781:          || !strcmp (d->d_name, "."))
                   3782:        continue;
                   3783: 
                   3784:       sprintf (filename, "%s%c%s", pid_dir, DIR_SEP, d->d_name);
                   3785:       if  (lstat (filename, &st) < 0 ) 
                   3786:        {
                   3787:          /* @@2 need some error message */
                   3788:          perror (filename);
                   3789:          continue;
                   3790:        }
                   3791:       
                   3792:       switch (st.st_mode & S_IFMT)
                   3793:        {
                   3794:        case S_IFDIR:
                   3795:        case S_IFLNK:
                   3796:          /* skip any links and directories that we find */
                   3797:          continue;
                   3798:          break;
                   3799:        default:
                   3800:          /* check if this pid exists. If not, erase it */
                   3801:          ptr = strrchr (filename, DIR_SEP);
                   3802:          if (!ptr) 
                   3803:            continue;
                   3804:          sscanf (ptr, DIR_STR"%d", &pid);
                   3805:          if (kill (pid, 0) == -1)
                   3806:            {
                   3807:              /* erase the stale pid file */
                   3808:              TtaFileUnlink (filename);
                   3809:            }
                   3810:          else /* we found one live instance */
                   3811:            {
                   3812:              instances++;
                   3813:            }
                   3814:          break;
                   3815:        }
                   3816:     }
                   3817:   closedir (dp);
                   3818:   return (instances == 0);
                   3819: #endif /* !_WINDOWS */
                   3820: }
                   3821: 
                   3822: /*----------------------------------------------------------------------
                   3823:   FreeAmayaCache 
                   3824:   ----------------------------------------------------------------------*/
                   3825: void FreeAmayaCache (void)
                   3826: {
                   3827: #ifndef _WINDOWS
                   3828:   char str[MAX_LENGTH];
                   3829:   pid_t pid;
                   3830: 
                   3831:   /* unregister this instance of Amaya */
                   3832:   pid = getpid ();
                   3833:   sprintf (str, "%s/pid/%d", TempFileDirectory, pid);
                   3834:   if (TtaFileExist (str))
                   3835:     TtaFileUnlink (str);
                   3836: #endif /* _WINDOWS */
                   3837: }
                   3838: 
                   3839: /*----------------------------------------------------------------------
                   3840:   InitAmayaCache 
                   3841:   Create the temporary sub-directories for storing the HTML and
                   3842:   other downloaded files.
                   3843:   ----------------------------------------------------------------------*/
                   3844: void InitAmayaCache (void)
                   3845: {
                   3846:   ThotBool can_erase;
                   3847:   int i;
                   3848:   char str[MAX_LENGTH];
                   3849:   char *ptr;
1.309     cvs      3850: #ifndef _WINDOWS
1.308     kahan    3851:   pid_t pid;
                   3852:   int fd_pid;
1.309     cvs      3853: #endif /* _WINDOWS */
1.308     kahan    3854: 
                   3855: #ifndef _WINDOWS
                   3856:   /* create the temp dir for the Amaya pid */
                   3857:   sprintf (str, "%s%cpid", TempFileDirectory, DIR_SEP);
                   3858:   TtaMakeDirectory (str);
                   3859: #endif
                   3860: 
                   3861:   /* protection against dir names that have . in them to avoid
                   3862:      erasing everything  by accident */
                   3863:   ptr = TempFileDirectory;
                   3864:   can_erase = TRUE;
                   3865:   while (*ptr && can_erase)
                   3866:     {
                   3867:       if (*ptr == '.')
                   3868:        {
                   3869:          if (*(ptr + 1) == '.')
                   3870:            can_erase = FALSE;
                   3871:          else
                   3872:            ptr++;
                   3873:          continue;
                   3874:        }
                   3875:       else if (*ptr == '~')
                   3876:        can_erase = FALSE;
                   3877:       else if (!isalnum (*ptr) && *ptr != DIR_SEP && *ptr != ':')
                   3878:        can_erase = FALSE;
                   3879:       ptr++;
                   3880:     }
                   3881: 
                   3882:   if (can_erase && CheckSingleInstance (str))
                   3883:     {
                   3884:       /* Erase the previous directories */
                   3885:       for (i = 0; i < DocumentTableLength; i++)
                   3886:        {      
                   3887:          sprintf (str, "%s%c%d%c", TempFileDirectory, DIR_SEP, i, DIR_SEP);
                   3888:          RecCleanCache (str);
                   3889:        }
                   3890:     }
                   3891: 
                   3892:   /* create the temporary cache directories if they don't exit*/
                   3893:   for (i = 0; i < DocumentTableLength; i++)
                   3894:     {      
                   3895:       sprintf (str, "%s%c%d", TempFileDirectory, DIR_SEP, i);
                   3896:       TtaMakeDirectory (str);
                   3897:     }
                   3898: 
                   3899: #ifndef _WINDOWS
                   3900:   /* register this instance of Amaya */
                   3901:   pid = getpid ();
                   3902:   sprintf (str, "%s/pid/%d", TempFileDirectory, pid);
                   3903:   fd_pid = open (str, O_CREAT, S_IRUSR | S_IWUSR );
                   3904:   if (fd_pid != -1)
                   3905:     close (fd_pid);
                   3906:   else
                   3907:     printf ("Couldn't create fd_pid %s\n", str);
                   3908: #endif /* _WINDOWS */
                   3909: }

Webmaster