Fetch 76.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright 1997 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/***************************************************/
/* File   : Fetch.c                                */
17 18 19 20 21 22 23
/*                                                 */
/* Purpose: Mid-level fetch functions, concerned   */
/*          mostly with HStreams but not low level */
/*          HTMLLib interfacing. Compare with      */
/*          FetchPage.c, which provides a much     */
/*          higher level interface.                */
/*                                                 */
24
/* Author : A.D.Hodgkinson                         */
25 26 27 28 29
/*                                                 */
/* History: 25-Nov-96: Created.                    */
/*          17-Aug-97: Split up to form the        */
/*                     URLveneer.c and FetchHTML.c */
/*                     sources.                    */
30 31 32 33 34
/***************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
35
#include <ctype.h>
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

#include "swis.h"
#include "flex.h"

#include "HTMLLib.h" /* HTML library API, Which will include html2_ext.h, tags.h and struct.h */

#include "wimp.h"
#include "wimplib.h"
#include "event.h"

#include "svcprint.h"
#include "Global.h"
#include "MiscDefs.h"
#include "Utils.h"

#include "Authorise.h"
#include "Browser.h"
53
#include "Filetypes.h"
54 55
#include "FontManage.h"
#include "Forms.h"
56
#include "FetchHTML.h"
57 58 59 60
#include "Frames.h"
#include "History.h"
#include "Images.h"
#include "Memory.h"
61
#include "Meta.h"
62
#include "PlugIn.h"
63
#include "Protocols.h"
64
#include "Object.h"
65 66
#include "Redraw.h"
#include "Reformat.h"
67
#include "RMA.h"
68
#include "Save.h"
69 70
#include "SaveFile.h"
#include "SaveObject.h"
71 72
#include "Toolbars.h"
#include "URLutils.h"
73
#include "URLveneer.h"
74 75
#include "Windows.h"

76
#include "Fetch.h" /* (Which itself includes URLstat.h) */
77 78 79 80 81 82 83 84

/* Local definitons */

#define AuthorisationStr "Authorization: Basic "

/* Static function prototypes */

static HStream * fetch_find_anchor_token_r (browser_data * b, HStream * streambase, char * anchor);
85
static HStream * fetch_find_text_token_r   (browser_data * b, char * text, HStream ** last_t, int * last_o, int * offset, int cs, HStream * streambase, int * enabled);
86 87 88 89

/*************************************************/
/* fetch_start()                                 */
/*                                               */
90
/* Initiate a fetch for some URL.                */
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             for the browser window that the   */
/*             fetch relates to; the URL is      */
/*             pointed to in that structure, as  */
/*             the last item in the history.     */
/*                                               */
/* Returns:    A pointer to a _kernel_oserror    */
/*             structure if an error occured, or */
/*             NULL if there was no error.       */
/*************************************************/

_kernel_oserror * fetch_start(browser_data * b)
{
  _kernel_oserror * e;
106
  int               handle, method;
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

  #ifdef TRACE
    if (tl & (1u<<6)) Printf("\nfetch_start: Called\n");
  #endif

  /* (Order of evaluation ensures the check for the contents of */
  /* the memory pointed to by browser_fetch_url only occurs if  */
  /* the pointer isn't null)                                    */

  if (!browser_fetch_url(b) || !*browser_fetch_url(b))
  {
    b->fetch_status = BS_IDLE;
    toolbars_cancel_status(b, Toolbars_Status_Fetching);
    return NULL;
  }

  /* URL method is set to POST if there is forms data, or GET */
  /* if not (see Fetch.c for the definitions)                 */

126
  method = b->post_data ? URL_Method_http_POST : URL_Method_http_GET;
127

128 129 130 131
  /* Reset the encoding priority to default, awaiting any  */
  /* information in the HTTP header. Don't actually change */
  /* the encoding yet as we don't want the menu to change  */
  /* at this point.                                        */
132 133 134 135 136 137

  if (
       b->encoding_priority > priority_link &&
       b->encoding_priority < priority_user
     )
     b->encoding_priority = priority_default;
138

139 140 141
  /* Find out if this is an internal URL, and if so, */
  /* set the 'displayed' field in the browser_data   */
  /* struct appropriately.                           */
142 143 144 145
  /*                                                 */
  /* If we're saving out data in a link, then don't  */
  /* do this, as the page contents aren't actually   */
  /* changing (so leave the flag alone).             */
146

147 148 149 150 151
  if (!b->save_link) urlutils_set_displayed(b, b->urlfdata);

  /* Reset the data size counter */

  b->data_size = 0;
152 153 154

  /* Get, and start parsing the document */

155 156 157 158 159 160 161
  e = html_get(b->urlfdata,               /* Required document */
               (char **) (&b->post_data), /* Extra bits to append for POST etc */
               &handle,                   /* The library's handle for request */
               method,                    /* See above - POST or GET at this point */
               NULL,                      /* User name for Mailserv */
               1,                         /* Allow HTML parsing, 1 = yes, 0 = no */
               !b->reloading);            /* If 0, don't go through a proxy - e.g. for a reload */
162 163

  #ifdef TRACE
164
    if (b->post_data)
165
    {
166
      flexcount -= flex_size((flex_ptr) &b->post_data);
167 168 169 170
      if (tl & (1u<<13)) Printf("**   flexcount: %d\n",flexcount);
    }
  #endif

171
  if (b->post_data) flex_free((flex_ptr) &b->post_data);
172 173 174 175 176

  if (e)
  {
    b->fetch_status = BS_IDLE;
    toolbars_cancel_status(b, Toolbars_Status_Fetching);
177 178

    RetWarnE(e);
179 180 181 182 183 184
  }

  /* No error, so signal that the fetch has started. */

  b->fetch_handle = handle;
  b->fetch_status = BS_STARTED;
185
  toolbars_update_status(b, Toolbars_Status_Connecting);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

  /* At this point e will always be NULL but that might change, */
  /* so the full trace code is being left in for now            */

  #ifdef TRACE
    if (tl & (1u<<6))
    {
      if (e) Printf("fetch_start: Exiting with error\n");
      else Printf("fetch_start: Successful\n");
    }
  #endif

  return e;
}

/*************************************************/
/* fetch_fetching()                              */
/*                                               */
/* Returns 1 if there is a fetch in progress     */
/* according to the contents of the data that    */
/* was pointed to (see Parameters), else 0.      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the inquiry.          */
/*                                               */
211
/* Returns:    1 if a fetch is in progress, or   */
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
/*             0 if a fetch is not in progress.  */
/*************************************************/

int fetch_fetching(browser_data * b)
{
  /* This is currently very simple - a fetch is considered to be in */
  /* progress so long as the fetch_status doesn't indicate BS_IDLE. */

  return (b->fetch_status != BS_IDLE);
}

/*************************************************/
/* fetch_find_name_tag()                         */
/*                                               */
/* Finds the # separating an anchor name in a    */
/* URL.                                          */
/*                                               */
/* Parameters: A pointer to the URL string.      */
/*                                               */
/* Returns:    A pointer to the anchor string,   */
/*             including the leading #           */
/*************************************************/

char * fetch_find_name_tag(char * url)
{
  char * p;

239
  p = strrchr(url, '#');
240

241 242 243 244 245
//  p = strchr(url,'/'); /* Get past the first /, as in http:/ */
//
//  if (p) p = strchr(p + 1, '/'); /* Get past second /, as in http://                     */
//  if (p) p = strchr(p + 1, '/'); /* Get past site specifier, as in http://www.this.that/ */
//  if (p) p = strchr(p + 1, '#'); /* Find # in the document path                          */
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

  return p;
}

/*************************************************/
/* fetch_find_anchor_token()                     */
/*                                               */
/* Returns the address of the first token in the */
/* token list which has the given anchor name    */
/* associated with it, or NULL if none can be    */
/* found.                                        */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the token list;       */
/*                                               */
/*             Pointer to the anchor name.       */
/*                                               */
/* Returns:    Pointer to the token associated   */
/*             with the given anchor name, or    */
/*             NULL if none is found.            */
/*************************************************/

HStream * fetch_find_anchor_token(browser_data * b, char * anchor)
{
  return fetch_find_anchor_token_r(b, b->stream, anchor);
}

/*************************************************/
/* fetch_find_anchor_token_r()                   */
/*                                               */
/* Recursive back-end to fetch_find_anchor_token */
/* - takes an extra parameter giving the top of  */
/* the HStream list to scan.                     */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the token list;       */
/*                                               */
/*             Pointer to first item in HStream  */
/*             list to scan;                     */
/*                                               */
/*             Pointer to the anchor name.       */
/*                                               */
/* Returns:    As fetch_find_anchor_token.       */
/*************************************************/

static HStream * fetch_find_anchor_token_r(browser_data * b, HStream * streambase, char * anchor)
{
  HStream * tp;

  tp = streambase;

  /* Go down the token list, checking if a token represents an   */
  /* anchor, has a name, and that name matches the given one. If */
  /* so, return the token address, else go onto the next token.  */

  while (tp && (tp->flags & HFlags_DealtWithToken))
  {
    /* A table token? */

305
    if (tp->tagno == TAG_TABLE)
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    {
      table_stream   * table      = (table_stream *) tp;
      table_row      * row        = NULL;
      table_headdata * head       = NULL;
      HStream        * tf;
      int              cellcount  = 0;
      int              cellmax    = table->ColSpan * table->RowSpan;

      /* Scan the table for the token, using a recursive */
      /* call to this function for each cell.            */

      if (table->cells)
      {
        row = table->List;

        while (row && cellcount < cellmax)
        {
          head = row->List;

          while (head && cellcount < cellmax)
          {
            switch (head->Tag)
            {
              case TagTableData:
              case TagTableHead:
              {
                tf = fetch_find_anchor_token_r(b, (HStream *) head->List, anchor);
                if (tf) return tf;
              }
              break;
            }

            cellcount ++;

            head = head->Next;

          /* Closure of 'while (head && ...)' */
          }

          row = row->Next;

        /* Closure of 'while (row && ...)' */
        }

      /* Closure of 'if (table->cells)' */
      }

    /* Closure of check to see if token represents a table */
    }
    else if (
              (tp->style & A) &&
              tp->name        &&
358
              !utils_strcasecmp(tp->name, anchor)
359 360 361 362 363 364 365 366 367 368 369
            )
            return tp;

    tp = tp->next;
  }

  /* No match found - return NULL. */

  return NULL;
}

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
/*************************************************/
/* fetch_find_text_token()                       */
/*                                               */
/* Returns the address of the first token in the */
/* token list after a given one (or NULL for the */
/* very first) which points to a string holding  */
/* the given text, or NULL if none can be found. */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the token list;       */
/*                                               */
/*             Pointer to a fragment of text to  */
/*             find;                             */
/*                                               */
/*             Pointer to the HStream where text */
/*             was last found (the function will */
/*             find the next), or NULL for the   */
/*             first call;                       */
/*                                               */
/*             The offset into that token the    */
/*             string was found at, or 0;        */
/*                                               */
/*             Pointer to an int, into which, if */
/*             text is found in a token, the     */
/*             offset into that text at which    */
/*             the search string was found;      */
/*                                               */
/*             1 for case sensitive comparison,  */
/*             else 0;                           */
/*                                               */
/*             1 to find the next item, else     */
/*             find the previous one.            */
/*                                               */
/* Returns:    Pointer to the token associated   */
/*             with the given anchor name, or    */
/*             NULL if none is found.            */
/*                                               */
/* Assumes:    The int pointer may NOT be NULL.  */
/*************************************************/

HStream * fetch_find_text_token(browser_data * b, char * text, HStream * last_t,
                                int last_o, int * offset, int cs, int forwards)
{
  int flags;

  if (!text || !*text) return NULL;

  /* Searching forwards is easy... */

  if (forwards)
  {
    flags = 0;

    return fetch_find_text_token_r(b,
                                   text,
                                   &last_t,
                                   &last_o,
                                   offset,
                                   cs,
                                   b->stream,
                                   &flags);
  }

  /* Going backwards is a bit trickier. Start from the top */
  /* of the page; remember if anything is found, and keep  */
  /* going until the last_t and last_o passed in here are  */
  /* matched. Return the previously found item (which may  */
  /* be NULL if you're already on the first).              */

  else
  {
    HStream * local_last_t  = NULL;
    int       local_last_o  = 0;

    HStream * local_start_t = NULL;
    int       local_start_o = 0;

    HStream * local_pass_t  = NULL;
    int       local_pass_o  = 0;

    for (;;)
    {
      /* The call may corrupt flags, local_start_t and */
      /* local_start_o, so reset flags before entry,   */
      /* and use a second copy of the other two.       */

      flags = 0;

      local_pass_t = local_start_t;
      local_pass_o = local_start_o;

      local_last_t = fetch_find_text_token_r(b,
                                             text,
                                             &local_pass_t,
                                             &local_pass_o,
                                             &local_last_o,
                                             cs,
                                             b->stream,
                                             &flags);

      if (local_last_t == last_t && local_last_o == last_o) break;
      if (!local_last_t) break;

      local_start_t = local_last_t;
      local_start_o = local_last_o;
    }

    *offset = local_start_o;

    return local_start_t;
  }
}

/*************************************************/
/* fetch_find_text_token_r()                     */
/*                                               */
/* Recursive back-end to fetch_find_text_token.  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the token list;       */
/*                                               */
/*             Pointer to a fragment of text to  */
/*             find;                             */
/*                                               */
/*             Pointer to a pointer to the       */
/*             HStream where text was last found */
/*             (the function will find the       */
/*             next), or pointer to NULL for the */
/*             first call (contents may be       */
/*             updated);                         */
/*                                               */
/*             Pointer to an int holding the     */
/*             offset into that token the string */
/*             was found at, or pointer to 0     */
/*             (again, contents may be updated); */
/*                                               */
/*             Pointer to an int, into which, if */
/*             text is found in a token, the     */
/*             offset into that text at which    */
/*             the search string was found;      */
/*                                               */
/*             1 for case sensitive comparison,  */
/*             else 0;                           */
/*                                               */
/*             Pointer to the first HStream in   */
/*             the list to search;               */
/*                                               */
/*             Pointer to an int, which contains */
/*             1 if string comparisons are to be */
/*             done yet, else 0 - this is so the */
/*             'find next' functionality can     */
/*             deal with recursion correctly.    */
/*             The int contents may be updated.  */
/*                                               */
/* Returns:    As fetch_find_text_token.         */
/*                                               */
/* Assumes:    As fetch_find_text_token, and     */
/*             that no other pointers are NULL   */
/*             unless stated (remember, there    */
/*             is a difference between being a   */
/*             NULL pointer and pointing to a    */
/*             NULL value!).                     */
/*************************************************/

static HStream * fetch_find_text_token_r(browser_data * b, char * text, HStream ** last_t, int * last_o,
                                         int * offset, int cs, HStream * streambase, int * enabled)
{
  HStream * tp;

  tp = streambase;

  /* Go down the token list, checking if a token has text. */
  /* If so, and comparisons are enabled, see if the given  */
  /* string lies in the token.                             */

  while (tp && (tp->flags & HFlags_DealtWithToken))
  {
    if (!(*last_t) || (*last_t) == tp) *enabled = 1;

    /* A table token? */

    if (tp->tagno == TAG_TABLE)
    {
      table_stream   * table      = (table_stream *) tp;
      table_row      * row        = NULL;
      table_headdata * head       = NULL;
      HStream        * tf;
      int              cellcount  = 0;
      int              cellmax    = table->ColSpan * table->RowSpan;

      /* Scan the table for the token, using a recursive */
      /* call to this function for each cell.            */

      if (table->cells)
      {
        row = table->List;

        while (row && cellcount < cellmax)
        {
          head = row->List;

          while (head && cellcount < cellmax)
          {
            switch (head->Tag)
            {
              case TagTableData:
              case TagTableHead:
              {
                tf = fetch_find_text_token_r(b,
                                             text,
                                             last_t,
                                             last_o,
                                             offset,
                                             cs,
                                             (HStream *) head->List,
                                             enabled);
                if (tf) return tf;
              }
              break;
            }

            cellcount ++;

            head = head->Next;

          /* Closure of 'while (head && ...)' */
          }

          row = row->Next;

        /* Closure of 'while (row && ...)' */
        }

      /* Closure of 'if (table->cells)' */
      }

    /* Closure of check to see if token represents a table */
    }
    else if (
              tp->text             &&
              (tp->style & PCDATA) &&
              *enabled
            )
    {
      const char * find = tp->text;

      /* If we're on the last found token, must make */
      /* sure we start looking just past the given   */
      /* offset.                                     */

      if (tp == (*last_t))
      {
        (*last_o) ++;

        /* If last_o is still within range of the token's */
        /* attached text, advance the pointer into that   */
        /* text past the start of the found offset.       */
        /* Otherwise, set last_o to -1 to signal that we  */
        /* have, in fact, finished with this token and    */
        /* should move onto the next one.                 */

        if ((*last_o) < strlen(find)) find += (*last_o), (*last_o) = 0;
        else (*last_o) = -1;
      }

      if ((*last_o) == 0)
      {
        const char * start_p   = find;
        const char * current_p = start_p;

        HStream    * current_t;

        const char * search_p  = text;

        char         search_b;
        char         current_b;

find_first_char:

        /* Get the byte of search string to look for, converting  */
        /* to lower case if this is a case insensitive comparison */

        current_t = tp;

        search_b = *search_p;
        if (!cs) search_b = tolower(search_b);

        do
        {
          /* Similarly, get a byte of the comparison string, possibly */
          /* converting to lower case.                                */

          current_b = *start_p;
          if (!cs) current_b = tolower(current_b);

          /* Keep looking as long as the strings don't run out and we */
          /* don't have a match. If we do find a match, we still want */
          /* to have start_p point past it in case the rest of the    */
          /* search string doesn't match and we need to jump back     */
          /* into this 'find the first character' routine.            */

          start_p++;
        }
        while (search_b && current_b && search_b != current_b);

        /* If we've still got a non-zero search string and comparison */
        /* string byte, they matched (otherwise, there's nothing      */
        /* else to do).                                               */

        if (search_b && current_b)
        {
          /* Now we step through both strings, not just the comparison */
          /* string, to make sure that all of the search string is     */
          /* contained within the comparison string.                   */

          current_p = start_p - 1;

check_rest_matches:

          do
          {
            search_p++;
            current_p++;

            search_b  = *search_p;
            current_b = *current_p;

            if (!cs) search_b = tolower(search_b), current_b = tolower(current_b);
          }
          while (search_b && current_b && search_b == current_b);

          /* If we've run out of search string, we have a match. If we've */
          /* run out of neither, the match failed; jump back to finding   */
          /* the first character in the rest of the comparison string.    */

          if (!search_b)
          {
            /* Found it - return the token pointer and offset */

            *offset = start_p - tp->text - 1; /* (-1 as start_p was advanced past the start point by 1) */
            return tp;
          }

          /* Mismatch - start looking again */

          if (search_b && current_b)
          {
            search_p = text;

            goto find_first_char;
          }

          /* If we've run out of *comparison* string, it might continue */
          /* in the next token (and the next, and the next, etc.)       */

          if (
               current_t->next                   &&
               current_t->next->text             &&
               (current_t->next->style & PCDATA)
             )
          {
            current_t = current_t->next;

            current_p = current_t->text - 1;
            search_p--;

            goto check_rest_matches;
          }
        }
      }
      else (*last_o) = 0;
    }

    tp = tp->next;
  }

  /* No match found - return NULL. */

  return NULL;
}

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
/*************************************************/
/* fetch_preprocess_token()                      */
/*                                               */
/* Takes a token for a given browser_data struct */
/* and preprocesses it - e.g. tells the image    */
/* library about image tokens so fetches can     */
/* start for those images.                       */
/*                                               */
/* Parameters: A pointer to a browser_data       */
/*             structure relevant to the token;  */
/*                                               */
/*             Pointer to the token.             */
/*************************************************/

void fetch_preprocess_token(browser_data * b, HStream * tptr)
{
767 768
  /* final_token keeps track of the last token dealt with by this */
  /* routine, in the main token stream.                           */
769

770
  if (!tptr->parent) b->final_token = tptr;
771

772 773
  /* Deal with smart quotes etc. */

774
  // This could have side effects placed here...! Sort it out! - the function just returns at present.
775 776 777 778 779 780
  reformat_change_text(b, tptr);

  /* Deal with document body tags (not within HEAD, FRAMESET etc. containers) */

  if (ISBODY(tptr))
  {
781 782 783
    /* First, anything which isn't a table tag */

    if (tptr->tagno != TAG_TABLE)
784
    {
785 786 787
      /* If the 'style' entry has the image (IMG) bit set, ask */
      /* the image library to handle a new image. tptr->src    */
      /* will be a char * to the URL of the image.             */
788

789
      if (tptr->style & IMG)
790
      {
791 792
        if (fetch_chkerror(b,
                           image_new_image(b,
793
                                           tptr->src,
794 795
                                           tptr,
                                           0))) return;
796 797
      }

798 799
      /* Ask the Object library to handle a new OBJECT, EMBED or APPLET tag */

800
      if (ISOBJECT(tptr))
801 802 803 804 805 806
      {
        if (fetch_chkerror(b,
                           object_new_object(b,
                                             tptr))) return;
      }

807
      /* Handle some form tags */
808

809
      if (tptr->style & FORM)
810
      {
811
        switch (tptr->tagno)
812
        {
813 814 815 816 817 818 819 820 821 822 823 824 825
          /* If this is a FORM tag, create a new form. Otherwise, */
          /* any following form-related elements will be added to */
          /* the current form. We want to force a new header if   */
          /* the form ends - if another form starts, the dummy    */
          /* header is skipped (not a big problem), else any new  */
          /* forms elements without a FORM tag don't get          */
          /* accidentally associated with the earlier FORM.       */

          case TAG_FORM:
          {
            if (fetch_chkerror(b, form_new_form(b, tptr))) return;
          }
          break;
826

827 828 829 830 831
          case TAG_FORM_END:
          {
            if (fetch_chkerror(b, form_new_form(b, NULL))) return;
          }
          break;
832

833 834 835
          /* Deal with creating a new field as appropriate */

          case TAG_INPUT:
836
          {
837 838 839 840 841 842 843 844 845 846 847 848
            switch(HtmlINPUTtype(tptr))
            {
              case inputtype_TEXT:    if (fetch_chkerror(b, form_new_field(b, tptr, form_text,     tptr->text                     ))) return; break;
              case inputtype_PASSWORD:if (fetch_chkerror(b, form_new_field(b, tptr, form_password, tptr->text                     ))) return; break;
              case inputtype_CHECKBOX:if (fetch_chkerror(b, form_new_field(b, tptr, form_checkbox, (char *) HtmlINPUTchecked(tptr)))) return; break;
              case inputtype_RADIO:   if (fetch_chkerror(b, form_new_field(b, tptr, form_radio,    (char *) HtmlINPUTchecked(tptr)))) return; break;
              case inputtype_IMAGE:   if (fetch_chkerror(b, form_new_field(b, tptr, form_image,    NULL                           ))) return; break;
              case inputtype_HIDDEN:  if (fetch_chkerror(b, form_new_field(b, tptr, form_hidden,   NULL                           ))) return; break;
              case inputtype_SUBMIT:  if (fetch_chkerror(b, form_new_field(b, tptr, form_submit,   NULL                           ))) return; break;
              case inputtype_BUTTON:  if (fetch_chkerror(b, form_new_field(b, tptr, form_button,   NULL                           ))) return; break;
              case inputtype_RESET:   if (fetch_chkerror(b, form_new_field(b, tptr, form_reset,    NULL                           ))) return; break;
            }
849
          }
850
          break;
851

852
          /* Handle text areas */
853

854 855 856 857 858
          case TAG_TEXTAREA:
          {
            if (fetch_chkerror(b, form_new_field(b, tptr, form_textarea, tptr->text))) return;
          }
          break;
859

860
          /* Handle selection buttons */
861

862 863 864 865 866
          case TAG_SELECT:
          {
            if (fetch_chkerror(b, form_new_field(b, tptr, form_select, (char *) HtmlSELECToptions(tptr)))) return;
          }
          break;
867 868
        }
      }
869 870
    }

871 872 873 874 875 876 877 878
    /* Tables - need to preprocess any HStreams attached as part of a table */
    /* tag. Because any one token is only run through this preprocessor     */
    /* once, and because when this table tag is run through it all of the   */
    /* HStreams within may not have arrived yet (the page is only partially */
    /* fetched), it is still necessary to rescan the attached HStreams at a */
    /* later date (e.g. as part of the reformatting process) to ensure they */
    /* are all preprocessed correctly.                                      */

879
    else
880 881 882 883
    {
      table_stream   * table = (table_stream *) tptr;
      table_row      * R;
      table_headdata * D;
884
      HStream        * attached;
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904

      R = table->List;

      /* Scan the rows and cells */

      while (R)
      {
        D = R->List;

        while (D)
        {
          if (D->Tag)
          {
            switch (D->Tag)
            {
              case TagTableData:
              case TagTableHead:
              {
                attached = (HStream *) D->List;

905 906 907 908
                /* Preprocess any attached HStream list - must */
                /* check table tags even if they've been done  */
                /* before to look for new HStreams, otherwise  */
                /* avoid preprocessing the same thing twice.   */
909 910 911

                while (attached)
                {
912
                  if (
913 914
                       attached->tagno == TAG_TABLE ||
                       !(attached->flags & HFlags_DealtWithToken)
915 916
                     )
                     fetch_preprocess_token(b, attached);
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934

                  attached = attached->next;
                }
              }
              break;
            }
          }

          D = D->Next;
        }

        R = R->Next;
      }
    }

    /* Closure of long 'if' to see if the HStream structure represented */
    /* a body tag or header information - the code is run if it's a     */
    /* body tag.                                                        */
935
  }
936 937 938 939
  else if ISFRAMESET(tptr)
  {
    browser_data * parent;
    browser_data * child = b;
940

941 942
    parent = b->parent;
    if (!parent) parent = b;
943

944
    if (tptr->size)
945
    {
946
      int level = tptr->size;
947

948 949
      /* If filling_frame is equal to the number of children, then */
      /* they've all been filled - the frameset must be broken.    */
950

951
      if (
952
           !b->nchildren ||
953
           (
954 955
             b->nchildren                    &&
             b->filling_frame < b->nchildren
956 957
           )
         )
958
      {
959 960 961 962 963
        while (level > 1)
        {
          /* If in a nested frameset, find out what browser_data struct  */
          /* to put the frames in. This should go in the next frame that */
          /* is to be filled in according to the parent.                 */
964

965 966 967 968 969 970 971 972 973 974
          if (child->nchildren && child->filling_frame < child->nchildren)
          {
            child = (browser_data *) child->children[child->filling_frame];
            level--;
          }
          else
          {
            child = NULL;
            break;
          }
975
        }
976 977
      }
      else child = NULL;
978

979 980
      if (child)
      {
981 982 983 984 985 986 987 988 989
        /* If stepping down a level, i.e. after a /frameset tag, */
        /* will want to increment the filling_frame field for    */
        /* this browser to say that the child we just stepped    */
        /* down for has been filled with a frameset. There's the */
        /* complication of a /frameset being followed by another */
        /* frameset and the level therefore staying the same;    */
        /* this is dealt with in the frameset section below.     */

        if (tptr->size < parent->nesting_level)
990
        {
991 992
          child->filling_frame++;
        }
993

994
        /* The aforementioned frameset section... */
995

996 997 998
        if (!(tptr->style & FRAME))
        {
          /* Define a new frameset. */
999

1000
          if (tptr->size <= parent->nesting_level && child->parent)
1001
          {
1002
            /* If at the same level as before on receiving a frameset  */
1003 1004
            /* tag, must be doing nested frames and just had some      */
            /* /framesets before this tag came along. So need to       */
1005 1006 1007
            /* increment the filling_frame counter of the *parent*     */
            /* (remember, we're at the level of the frame to fill in,  */
            /* not in the level below as with the code above that      */
1008
            /* checked the level has stepped down). Therefore, need    */
1009 1010 1011 1012 1013
            /* to find out again what browser_data struct is to be     */
            /* given the frameset based on the new filled_frame value. */

            child->parent->filling_frame++;
            child = (browser_data *) child->parent->children[child->parent->filling_frame];
1014 1015
          }

1016 1017
          /* Must force scrollbars off in this current view, */
          /* as a frameset is about to appear over it.       */
1018

1019
          windows_check_tools(child, NULL);
1020

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
          if (tptr->size > 1 && parent->frameset)
          {
            /* This is a nested frameset, so we must inherit some aspects */
            /* of the parent's frameset token to tptr.                    */

            if (parent->frameset)
            {
              /* Border colour */

              tptr->maxlen = parent->frameset->maxlen;

              /* Border width / frame spacing */

              tptr->indent = parent->frameset->indent;
            }
          }

1038
          /* Finally, define the frameset at the required depth. */
1039

1040
          frames_define_frameset(child, tptr);
1041
        }
1042 1043 1044
        else
        {
          /* Fill in details of a frame. */
1045

1046 1047
          frames_define_frame(child, tptr);
        }
1048

1049 1050
        parent->nesting_level = tptr->size;
      }
1051

1052
      #ifdef STRICT_PARSER
1053

1054 1055
        else
        {
1056

1057
          erb.errnum = Utils_Error_Custom_Message;
1058

1059 1060 1061
          StrNCpy0(erb.errmess,
                   lookup_token("FramNest:Frames definition is badly nested; could not complete the frames layout.",
                                0,0));
1062

1063 1064
          show_error_ret(&erb);
        }
1065

1066 1067 1068
      #endif
    }
  }
1069 1070 1071 1072
  else if ISHEAD(tptr)
  {
    /* Deal with header (HEAD) tags */

1073
    if (tptr->tagno == TAG_TITLE && tptr->text)
1074 1075 1076
    {
      /* The tag is TITLE, and there is title text. */

1077
      char   title[Limits_Title];
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
      char * p = title;
      char * end;

      /* Can't overflow maximum length so just crop the string to fit */

      StrNCpy0(title, tptr->text);

      /* Strip any spaces at the start */

      while (*p == ' ') p++;

      /* Strip any spaces at the end */

      end = (char *) ((int) p + strlen(p) - 1);
      if (end > p) while (*end == ' ') *end-- = 0;

      /* If there's anything left now... */

      if (*p != 0)
      {
        /* Set the title */

        if (!b->ancestor && fetch_chkerror(b, window_set_title(0, b->self_id, p))) return;

        /* Try adding this title to the history, ignoring any errors */

1104
        history_add_title(browser_fetch_url(b), p);
1105 1106 1107
      }
    }

1108
    if (tptr->tag == BODY)
1109
    {
1110
      /* The BODY tag. All sorts of exciting stuff in here... */
1111

1112
      if (HtmlBODYbgcolour(tptr) != NULL_COLOUR)
1113
      {
1114 1115 1116 1117
        /* Get the 24-bit background colour, if any. Do this before */
        /* starting a fetch for any background image as it will     */
        /* affect whether cross referencing can occur or not.       */

1118
        b->background_colour = HtmlBODYbgcolour(tptr);
1119 1120

        #ifdef TRACE
1121
          if (tl & (1u<<6)) Printf("fetch_preprocess_token: Background colour set to %d\n", b->background_colour);
1122 1123 1124 1125 1126
        #endif

        /* If there's no actual background image, set the anti-alias */
        /* colour to be the same as the background colour.           */

1127
        if (b->background_image < 0) b->antialias_colour = b->background_colour;
1128 1129 1130 1131

        browser_update_bottom(b, 0);
      }

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
      /* Background images */

      if (HtmlBODYbackground(tptr))
      {
        /* If there's a URL for the image, ask the image library for it */
        /* and remember the image number in the browser_data structure  */

        image_new_image(b, HtmlBODYbackground(tptr), tptr, 2);
      }

      /* Get the rest of the colour info out */
1143

1144 1145 1146 1147
      if (HtmlBODYtext (tptr) != NULL_COLOUR) b->text_colour     = HtmlBODYtext (tptr);
      if (HtmlBODYlink (tptr) != NULL_COLOUR) b->link_colour     = HtmlBODYlink (tptr);
      if (HtmlBODYvlink(tptr) != NULL_COLOUR) b->used_colour     = HtmlBODYvlink(tptr);
      if (HtmlBODYalink(tptr) != NULL_COLOUR) b->followed_colour = HtmlBODYalink(tptr);
1148

1149
      /* Pull out the onload and onunload scripts */
1150 1151

      if (HtmlBODYonload  (tptr)) b->onload   = HtmlBODYonload  (tptr);
1152
      if (HtmlBODYonunload(tptr)) b->onunload = HtmlBODYonunload(tptr);
1153 1154
    }

1155 1156 1157 1158 1159 1160 1161
    /* Deal with META... tags */

    if (tptr->tag == META)
    {
      meta_process_tag(b, tptr);
    }

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    /* Closure of long else to see if the HStream structure represented */
    /* a body tag or header information - the code is run if it's a     */
    /* head tag.                                                        */
  }

  /* If we've reached here, the token has been dealt with */
  /* successfully - so mark this in its flags word.       */

  tptr->flags |= HFlags_DealtWithToken;

  return;
}

/*************************************************/
/* fetch_fetcher()                               */
/*                                               */
/* The main part of the fetch routine. Handles   */
/* the processing of data from the URL module,   */
1180
/* after fetch_start has asked it to start       */
1181 1182 1183 1184 1185 1186 1187 1188 1189
/* getting data from a server.                   */
/*                                               */
/* Parameters: A pointer to a browser_data       */
/*             structure, to which the fetch     */
/*             relates.                          */
/*************************************************/

void fetch_fetcher(browser_data * b)
{
1190 1191 1192
  HStream * tptr;
  int       start = -1;
  int       i, remain, sofar, waiting;
1193

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
  /* It really helps to understand this function if you realise that */
  /* it's coded more or less backwards (Merlyn was weird...). For    */
  /* example, the BS_DATAFETCH code below isn't executed unless the  */
  /* fetch state reaches BS_DATAFETCH, but it can't do that unless   */
  /* fetcher code much further down is run. So you really need to    */
  /* read this all in one go before trying to piece it together, or  */
  /* maybe even read it from the bottom up...                        */
  /*                                                                 */
  /* BS stands for Browser Status, by the way, and nothing else ;-)  */

1204
  for (i = 0; i < 10; i ++) /* Get several tokens on each null event */
1205
  {
1206
    /* For BS_DATAFETCH, save the file */
1207 1208 1209 1210

    if (b->fetch_status == BS_DATAFETCH)
    {
      #ifdef TRACE
1211
        if (tl & (1u<<6)) Printf("fetch_fetcher: fetch_status = BS_DATAFETCH / BS_DATAWHERE.\n");
1212 1213 1214 1215
      #endif

      /* This code gets called by the stuff further down advancing */
      /* the status to BS_DATAFETCH.                               */
1216 1217 1218 1219
      /*                                                           */
      /* If the save_file field is NULL, we're still waiting for   */
      /* the user to pull their finger out and say where to save   */
      /* the object.                                               */
1220

1221
      if (b->save_file) /* Proceed if there's a file to save to */
1222
      {
1223 1224
        char              buffer[2048];
        int               success, bytes = -1, done = 0;
1225 1226 1227 1228
        _kernel_oserror * e;

        /* Get a chunk of data */

1229 1230 1231 1232 1233 1234 1235
        e = fetch_get_raw_data(NULL,
                               b->fetch_handle,
                               buffer,
                               sizeof(buffer),
                               &done,
                               &bytes);

1236 1237
        /* If there's an error, show it but continue */

1238 1239 1240
        if (e) show_error_ret(e);

        success = !e;
1241 1242 1243

        /* If there was not an error, write a chunk of file */

1244
        if (success && bytes) success = fwrite(buffer, 1, bytes, b->save_file);
1245 1246 1247 1248 1249 1250 1251

        /* If the expected number of bytes was not written, */
        /* show whatever error fwrite generated             */

        if (success != bytes && bytes)
        {
          success = 0;
1252 1253
          erb     = *_kernel_last_oserror();
          show_error_ret(&erb);
1254 1255 1256 1257 1258 1259 1260 1261
        }

        /* If apparently successful and finished, read the pathname */
        /* of the file so the filetype can be set.                  */

        if (success && done)
        {
          _swix(OS_Args,
1262
                _INR(0,2) | _IN(5),
1263 1264

                7, /* Read pathname of open file */
1265
                b->save_file->__file,
1266 1267 1268 1269 1270 1271
                buffer,
                sizeof(buffer));
        }

        /* If finished or there was some error above, stop the fetch */

1272
        if (!success || done) fetch_stop(b, 0); /* This closes the output file, too */
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

        /* If successful and finished, set the filetype */

        if (success && done)
        {
          _swix(OS_File,
                _INR(0,2),

                18,
                buffer,
1283
                b->save_type);
1284 1285 1286 1287 1288 1289
        }

        /* Finally, ensure toolbars are up to date. */

        toolbars_update_progress(b);
      }
1290 1291

      return;
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    }

    #ifdef TRACE
      if (tl & (1u<<6)) Printf("fetch_fetcher: Get next token\n");
    #endif

    /* Get the next token, with fetch_chkerror allowing us to exit */
    /* relatively cleanly should an error occur.                   */

    if (
         fetch_chkerror(
                         b, html_get_next_token(
                                                 b,
                                                 b->fetch_handle,
                                                 &remain,
                                                 &sofar,
                                                 &tptr,
                                                 &waiting,
                                                 (flex_ptr) &b->source,
                                                 browser_fetch_url(b),
                                                 0
                                               )
                       )
       )
       return;

    /* Show the fetch's progress */

    toolbars_update_progress(b);

1322 1323
    /* If waiting = 3 the data being fetched isn't parseable, or has */
    /* been marked as not for parsing so that it may be saved.       */
1324

1325
    if (waiting == 3)
1326
    {
1327
      /* Full screen browsers can't save objects out */
1328

1329 1330
      if (choices.full_screen && b->full_screen)
      {
1331
        erb.errnum = Utils_Error_Custom_Message;
1332

1333 1334 1335 1336 1337
        StrNCpy0(erb.errmess,
                 lookup_token("NotInternal:Can't save objects when running in full screen mode.",
                              0,
                              0));

1338 1339 1340
        fetch_chkerror(b, &erb);

        return;
1341 1342 1343
      }
      else
      {
1344 1345 1346 1347
        #ifdef TRACE
          if (tl & (1u<<6)) Printf("fetch_fetcher: fetch_status moved to BS_DATAFETCH\n");
        #endif

1348
        b->fetch_status = BS_DATAFETCH;
1349

1350
        b->save_type    = remain;
1351
        b->save_link    = 1;
1352

1353 1354 1355 1356 1357
        /* Flag that we're now fetching */

        toolbars_cancel_status(b, Toolbars_Status_Connecting);
        toolbars_update_status(b, Toolbars_Status_Fetching);

1358 1359 1360 1361 1362 1363 1364
        if (b->save_type == FileType_DATA || b->save_type == 0x000)
        {
          /* If we've been given data or unknown, see if we can have a better guess! */

          b->save_type = urlutils_filetype_from_url(browser_fetch_url(b));
        }

1365 1366
        /* We may already have a save file if something knew the path before */
        /* the fetch started...                                              */
1367

1368
        if (!b->save_file)
1369
        {
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
          /* Open a save dialogue for the object if we're not */
          /* spooling data for a Plug-In, else go straight to */
          /* a temporary file.                                */

          if (!b->pstream)
          {
            if (fetch_chkerror(b, saveobject_open_for(b))) return;
          }
          else
          {
            char unique[Limits_OS_Pathname];
1381

1382
            protocols_util_make_unique_name(unique, sizeof(unique));
1383

1384
            if (fetch_chkerror(b, save_save_object(unique, b))) return;
1385

1386 1387 1388
            /* If we haven't got an active stream, should now send a  */
            /* message to the Plug-In to tell it that we want to open */
            /* this stream. We need to record the filename, too.      */
1389

1390 1391 1392 1393
            if (fetch_chkerror(b,
                               rma_claim(b,
                                         strlen(unique) + 1,
                                         (void **) &b->pstream->filename.ptr))) return;
1394

1395
            strcpy(b->pstream->filename.ptr, unique);
1396

1397 1398 1399
            if (fetch_chkerror(b,
                               plugin_send_original_stream_new(b))) return;
          }
1400
        }
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
      }

      return;
    }

    /* If waiting = 2, a redirect has occurred */

    else if (waiting == 2)
    {
      char * url;
      int    internal = 0;

      #ifdef TRACE
        if (tl & (1u<<6)) Printf("fetch_fetcher: Redirect to %s\n",(char *) remain);
      #endif

      /* Get the new URL pointed to by 'url' */

      url = (char *) remain;

      if (b->displayed != Display_Fetched_Page) internal = 1;

      if (!internal)
      {
        /* Allocate space for new URL and copy it into that space */

        #ifdef TRACE
          if (tl & (1u<<12)) Printf("fetch_fetcher: Chunk CK_FURL set to %d\n",strlen(url) + 1);
        #endif

        if (fetch_chkerror(b, memory_set_chunk_size(b, NULL, CK_FURL, strlen(url) + 1))) return;
        strcpy(b->urlfdata, url);
      }
      else
      {
1436
        char furl[Limits_URL];
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

        /* Allocate space for new URL plus old URL and separator, */
        /* and copy them into that space                          */

        #ifdef TRACE
          if (tl & (1u<<12)) Printf("fetch_fetcher: Chunk CK_FURL set to %d\n",strlen(url) + strlen(furl) + 2);
        #endif

        StrNCpy0(furl, browser_fetch_url(b));

        if (fetch_chkerror(b, memory_set_chunk_size(b, NULL, CK_FURL, strlen(url) + strlen(furl) + 2))) return;

        strcpy(b->urlfdata, url);
        strcat(b->urlfdata, ":");
        strcat(b->urlfdata, furl);
      }

      /* Reflect the new URL in the status and URL bars */

1456
      toolbars_update_status(b, Toolbars_Status_Redirected);
1457 1458 1459
      toolbars_update_url(b);
    }

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
    /* If we're waiting for new tokens, don't sit here in a loop   */
    /* single tasking - break out, allowing more external polling. */

    else if (waiting)
    {
      break;
    }

    /* We're not waiting for data. */

    else
1471 1472
    {
      /* If it isn't already non-zero, set 'start' to the number of */
1473
      /* the last line in the line list (i.e. nlines - 1).          */
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500

      if (start < 0) start = b->cell->nlines - 1;

      /* We're not waiting, have we got a token? */

      if (b->fetch_status == BS_STARTED)
      {
        /* Yes - this is the first token on this page. Get the window */
        /* ready for the new page - this includes ditching old data.  */

        int l;

        /* Make the current display URL = current fetch URL... */

        l = strlen(browser_fetch_url(b)); /* Get the fetching URL string length */

        /* Allocate memory for it, and copy the string across */

        #ifdef TRACE
          if (tl & (1u<<12)) Printf("fetch_fetcher: Chunk CK_DURL set to %d\n",l + 1);
        #endif

        if (fetch_chkerror(b, memory_set_chunk_size(b, NULL, CK_DURL, l + 1))) return;

        strcpy(b->urlddata, browser_fetch_url(b));
        toolbars_hide_internal(b->urlddata);

1501 1502
        /* Write to the global history */

1503 1504 1505 1506 1507
        if (
             b->displayed == Display_Fetched_Page ||
             b->displayed == Display_External_Image
           )
           history_record(b, b->urlddata);
1508

1509 1510 1511 1512
        /* Update the title bar */

        if (!b->ancestor) /* Child windows don't have title bars... */
        {
1513
          char title[Limits_Title];
1514

1515
          StrNCpy0(title, b->urlddata);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531

          if (fetch_chkerror(b, window_set_title(0, b->self_id, title))) return;
        }

        /* Set status to FETCHING instead of STARTED */

        b->fetch_status = BS_FETCHING;

        /* If there was previous display data present, get rid of it */

        if ((b->display_handle) && (b->display_handle != b->fetch_handle))
        {
          html_close(b->display_handle);
          b->display_handle = 0;
        }

1532 1533
        b->save_oldstore = 0;

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
        /* Signal that the display data is coming from the fetch data, */
        /* so that the fetch data doesn't get accidentally ditched     */
        /* until it's finished with                                    */

        b->display_handle = b->fetch_handle;

        /* Initialise various things inside the browser_data structure */
        /* to do with colours and so-forth                             */

        #ifdef TRACE
          if (tl & (1u<<18)) Printf("New fetch for %p, stream %p\n",b,tptr);
        #endif

1547 1548 1549
        b->stream            = tptr;                     /* Pointer to list of HStream structures */
        b->final_token       = NULL;                     /* Last HStream structure dealt with     */
        b->last_char         = ' ';                      /* Last character dealt with             */
1550

1551
        b->background_colour = -1;                       /* Background colour, or -1 for default  */
1552

1553 1554 1555 1556 1557 1558 1559
        b->background_image  = -1;                       /* Image no. of background image, 0=none */
        b->text_colour       = choices.text_colour;      /* Body text default colour              */
        b->link_colour       = choices.link_colour;      /* Link text default colour              */
        b->used_colour       = choices.used_colour;      /* Followed link default colour          */
        b->antialias_colour  = redraw_backcol(b);        /* Colour to anti-alias to, or -1=none   */
        b->followed_colour   = choices.followed_colour;  /* Following link default colour         */
        b->selected_colour   = choices.selected_colour;  /* Selected (highlighted) link colour    */
1560

1561 1562
        b->onload            = NULL;                     /* <BODY onload> attribute               */
        b->onunload          = NULL;                     /* <BODY onunload> attribute             */
1563

1564 1565 1566 1567
        /* If this was a History-based fetch, clear the flag */

        b->from_history      = 0;

1568 1569
        /* Ensure the nesting level and filling frame counters are reset */

1570 1571
        b->nesting_level     = 0;
        b->filling_frame     = 0;
1572

1573 1574 1575 1576 1577 1578
        /* Cancel any pending automatic fetches */

        if (b->meta_refresh_at) deregister_null_claimant(Wimp_ENull, (WimpEventHandler *) meta_check_refresh, b);
        b->meta_refresh_at  = 0;
        b->meta_refresh_url = NULL;

1579 1580
        /* Cancel pending reformats */

1581
        reformat_stop_pending(b);
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669

        /* Hideously long comment alert...                                  */
        /*                                                                  */
        /* Although if a frame loads a document containing another frameset */
        /* this is in one sense a nested frame defintion, in another the    */
        /* second document is independent of the first; certainly as far as */
        /* incrementing the filling_frame field of the parent goes, the     */
        /* <frame> tag that loaded this document into the frame in the      */
        /* first place will already have done that.                         */
        /*                                                                  */
        /* Consequently, whilst all child frames have an ancestor - the     */
        /* original, base browser that defined the first of possibly many   */
        /* framesets - only genuinely nested frameset arrays have parents.  */
        /* That is, a parent can only have children; it may not also be a   */
        /* child (i.e. have a parent), it may only have an ancestor.        */
        /*                                                                  */
        /* Genuinely nested frames consist of one document with more than   */
        /* one set of <frameset> tags. Here, filling_frame considerations   */
        /* demand the use of a nested_level count and a parent as well as   */
        /* an ancestor. For those single documents, we won't be running     */
        /* this code when second or further framesets come in, so the       */
        /* parent field will get estabilshed and remain as long as needed   */
        /* by the frames routines.                                          */

        b->parent = NULL;

        /* Yup - that whole comment for one tiny line of code. Woo...       */
        /*                                                                  */
        /* 'Course, that said, it's useful for every child to know who its  */
        /* parent is. That's what the real_parent field is for.             */

//        {
//          WimpGetWindowStateBlock state;
//
//          state.window_handle = b->window_handle;
//
//          if (!wimp_get_window_state(&state))
//          {
//            b->display_width = b->display_extent = state.visible_area.xmax - state.visible_area.xmin;
//          }
//        }

        /* Don't want to set the pointer_over field, as then it may not seem to */
        /* have changed from one fetch to another; the pointer can get 'stuck'  */
        /* in the 'link' shape.                                                 */

        b->highlight      = NULL; /* No tokens are highlighted */
        b->selected       = NULL; /* No tokens are selected    */
        b->selected_owner = NULL;

        #ifdef TRACE
          if (tl & (1u<<6)) Printf("\nfetch_fetcher: Document colours etc. set to default values\n");
        #endif

        /* Clear the status bar contents block for an ancestor */
        /* window beginning a new fetch.                       */

        if (!b->ancestor && b->nstatus)
        {
          #ifdef TRACE

            if (
                 (tl & (1u<<1)) ||
                 (tl & (1u<<6))
               )
               Printf("fetch_fetcher: Freeing status_contents array\n");

          #endif

          b->nstatus = 0;
          memory_set_chunk_size(b, NULL, CK_STAT, 0);
        }

        /* Clear allocated memory for the forms, and tell */
        /* the font library that the fonts aren't needed  */
//        /* anymore. Images are cleared after the fetch,   */
//        /* so that any images common between the two can  */
//        /* be preserved.                                  */

        form_discard(b);
        fm_lose_fonts(b);

        /* Flag that images need to be garbage collected later */

// Um... ToDo list time...
        image_discard(b);
//        b->clear_images = 1;

1670 1671 1672 1673
        /* Similarly, get rid of Objects */

        object_discard(b);

1674 1675 1676 1677 1678 1679 1680 1681
        /* IMPORTANT, must call the reformatter here to ensure that all various   */
        /* line list data is invalidated, discarded, and any new stuff is valid.  */
        /* Otherwise, could have bits of the application subsequently using old   */
        /* line data and things will go very wrong very quickly.                  */
        /*                                                                        */
        /* DON'T put anything that might try and read line data before this call! */

        b->display_extent = b->display_width; /* Ensure a new fetch starts with the horizontal extent matching the visible area */
1682

1683
        start = -1;
1684 1685 1686
        reformat_format_from(b, -1, 1, -1);
        reformat_check_extent(b);

1687 1688 1689 1690
        /* If there's a save dialogue open for this frame, get rid of it */

        savefile_close(b->self_id, 0);

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
        /* Collapse any frames within this browser */

        frames_collapse_set(b);

        /* Ensure window tools are up to date */

        if (b->ancestor || b->full_screen) windows_set_tools(b, NULL, !b->ancestor, 0, 0, 0);

        /* If there's a # inside the URL (i.e. we're supposed to jump to an */
        /* anchor) then set the token to display first to be DISPLAY_NAMED, */
        /* a large number which acts as a flag to say 'jump to anchor'. The */
        /* fetch polling routine (see FetchPage.c) should notice this and   */
        /* start looking for a token with the appropriate name, and if it   */
        /* finds it, display that token.                                    */

        if (fetch_find_name_tag(browser_current_url(b))) b->display_request = DISPLAY_NAMED;

        /* Ensure the pointer shape is correct */

        browser_pointer_check(0, NULL, NULL, b);

        /* Reflect the new browser status */

1714
        toolbars_cancel_status(b, Toolbars_Status_Connecting);
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
        toolbars_update_status(b, Toolbars_Status_Fetching);

        /* Since the new fetch is now official, update the current and previous */
        /* page variables                                                       */

        if (!b->ancestor)
        {
          /* Not speed critical, so avoid lots of nasty C-isms with malloc */
          /* and so-on, by running through OS_CLI.                         */

          _swix(OS_CLI,
                _IN(0),

                "Set Browse$PreviousPage <Browse$CurrentPage>");

          _swix(OS_SetVarVal,
                _INR(0,4),

                "Browse$CurrentPage",
                b->urlfdata,
                strlen(b->urlfdata),
                0,
                4);
        }

        /* (Initialisation to an empty state is now complete, so we're */
        /* ready to fetch a new page).                                 */
      }

      /* We're not waiting, but if there's also no data left to fetch, */
      /* then we're just chugging through the list of tokens that the  */
1746
      /* library has generated, telling various bits of the code about */
1747 1748 1749 1750 1751 1752 1753
      /* their contents (e.g. a new image, a new form). In this case,  */
      /* change the fetch status so the status bar can reflect the new */
      /* situation.                                                    */

      if (!remain)
      {
        b->fetch_status = BS_PROCESS;
1754

1755
        toolbars_update_status(b, Toolbars_Status_Processing);
1756
        toolbars_update_progress(b);
1757 1758 1759 1760 1761 1762 1763 1764
      }

      /* If tptr is null, there are no HStream structures (see the */
      /* html_get_next_token call). But we're not waiting either,  */
      /* so must be at the end of the file - stop the fetch.       */

      if (!tptr)
      {
1765
        if (b->last_token->tagno == TAG_TABLE)
1766 1767 1768
        {
          /* If the last thing the reformatter dealt with was a table, */
          /* then extra table structures could have been added by      */
1769
          /* HTMLLib. It is important to ensure that any tokens that   */
1770 1771
          /* were added to the token stream are preprocessed before    */
          /* starting a reformat.                                      */
1772

1773
          fetch_preprocess_token(b, b->last_token);
1774 1775 1776 1777

          /* Make sure the page is fully reformatted */

          start = -1;
1778 1779 1780 1781 1782 1783 1784 1785
          reformat_format_from(b, b->cell->nlines - 2, 1, -1);
        }

        #ifdef TRACE
          if (tl & (1u<<6)) Printf("\nfetch_fetcher: Finished, so stopping and exiting.\n");
        #endif

        fetch_stop(b, 1);
1786 1787

        break;
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
      }
      else fetch_preprocess_token(b, tptr);

    /* Closure of series of ifs that checked the state of 'waiting' */
    /* amongst other things, to handle redirections etc. The bulk   */
    /* of the code deals with a conventional fetch.                 */
    }

  /* Closure of for loop that deals with several fetches per null */
  }

  /* If start is >= 0, there is data that can be used for     */
  /* displaying the page; so start a reformat based on that   */
  /* data. Start from 'one line up' as the last line may have */
  /* been only partially finished when it was last redrawn.   */
1803 1804 1805 1806 1807
  /* The reformat session can be deferred if the reformatter  */
  /* is not running, but if the reformatter is still going,   */
  /* push this request through immediately. Otherwise         */
  /* problems with long-delayed reformats way after the page  */
  /* has been more or less completely formatted can occur.    */
1808

1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
  if (start >= 0)// && !reformat_formatting(b))
  {
    reformat_format_from(b,
                         start - 1, /* '-1' as this parameter is the *last valid* line number */
                                    /* we want to keep, and 'start' holds the first line to   */
                                    /* start the reformat at.                                 */

                         reformat_formatting(b),
                         -1);
  }
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
}

/*************************************************/
/* fetch_chkerror()                              */
/*                                               */
/* Called by low level fetch routines instead of */
/* the ChkError macro, as it stops the current   */
/* fetch correctly before reporting the error.   */
/*                                               */
/* Parameters: Pointer to a browser_data         */
/*             structure relevant to the fetch;  */
1830
/*                                               */
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
/*             Pointer to a _kernel_oserror      */
/*             structure, which contains the     */
/*             error to report (or NULL).        */
/*                                               */
/* Returns:    0 if there was no error, else 1.  */
/*************************************************/

int fetch_chkerror(browser_data * b, _kernel_oserror * e)
{
  if (e)
  {
    /* There is an error - cancel the fetch */

    fetch_cancel(b);

1846 1847 1848
    /* Copy it locally if need be */

    if (&erb != e) erb = *e;
1849

1850 1851 1852 1853 1854
    /* Report the error, as a warning message only */

    erb.errnum = Utils_Error_Custom_Message;

    show_error_ret(&erb);
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885

    /* Flag the error in the returned value */

    return 1;
  }

  return 0;
}

/*************************************************/
/* fetch_cancel()                                */
/*                                               */
/* Aborts a fetch, closing any relevant streams, */
/* freeing up any claimed memory that was only   */
/* relevant to the fetch, but leaves the page    */
/* fetched so far visible.                       */
/*                                               */
/* Parameters: A pointer to the browser_data     */
/*             structure relevant to the fetch   */
/*             to be cancelled.                  */
/*************************************************/

_kernel_oserror * fetch_cancel(browser_data * b)
{
  /* If there is a fetch, and the HTML data isn't being used by the  */
  /* display routines, close the fetch handle and free up any memory */
  /* associated with it.                                             */

  if ((b->fetch_handle) && ((b->fetch_handle) != (b->display_handle))) html_close(b->fetch_handle);
  b->fetch_handle = 0;

1886 1887 1888 1889 1890
  /* If a META tag is about to do a reload, cancel this */

  if (b->meta_refresh_at) deregister_null_claimant(Wimp_ENull, (WimpEventHandler *) meta_check_refresh, b);
  b->meta_refresh_at = 0;

1891 1892 1893 1894
  /* If not fetching, exit here */

  if (!fetch_fetching(b)) return NULL;

1895 1896 1897 1898
  /* If we have a Plug-In stream, mark it as abandoned */

  if (b->pstream) b->pstream->abandoned = 1;

1899 1900 1901 1902 1903 1904
  /* Stop everything else */

  fetch_stop(b, 1);

  /* Ensure the page is correctly formatted */

1905
  if (b->cell->nlines) reformat_format_from(b, b->cell->nlines - 1, 1, -1);
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

  return(NULL);
}

/*************************************************/
/* fetch_stop()                                  */
/*                                               */
/* Stops a fetch, optionally discarding the      */
/* HTML source, making sure the browser window   */
/* state (buttons, status bar animation etc.) is */
/* correct, any open files are closed, and so    */
/* forth. In the UI sense this is higher level   */
/* than fetch_cancel, though fetch_cancel calls  */
/* this as part of doing other cancel actions,   */
/* and is therefore the higher level function.   */
/*                                               */
/* Parameters: A pointer to the browser_data     */
/*             structure relevant to the fetch   */
/*             to be stopped;                    */
1925
/*                                               */
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
/*             1 to keep the HTML source, 0 to   */
/*             destroy it.                       */
/*************************************************/

void fetch_stop(browser_data * b, int keep_source)
{
  /* Destroy the source, provided the browser was fetching any */

  if (fetch_fetching(b) && !keep_source) browser_destroy_source(b);

  /* Set the fetch status to idle */

  b->fetch_status = BS_IDLE;

1940 1941 1942
  /* The save_link flag tells the browser to save the next fetch as data, */
  /* even if it is parsable. Want to make sure that flag is clear now to  */
  /* avoid complications later on.                                        */
1943

1944
  b->save_link = 0;
1945

1946 1947 1948 1949
  /* If data was being saved to a file, close that file */

  if (b->save_file)
  {
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
    char buffer[Limits_OS_Pathname];

    /* Leave the file intact, but set it to a Data filetype */

    if (
         !_swix(OS_Args,
                _INR(0,2) | _IN(5),

                7, /* Read pathname of open file */
                b->save_file->__file,
                buffer,
                sizeof(buffer))
       )
    {
      _swix(OS_File,
            _INR(0,2),

            18,
            buffer,
            FileType_DATA);
    }

1972 1973 1974 1975
    fclose(b->save_file);
    b->save_file = NULL;
  }

1976
  if (b->save_dbox) saveobject_close(b);
1977

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
  if (b->fetch_handle)
  {
    /* If there is a fetch, and the associated HTML document isn't being */
    /* used by the display routines, close that fetch handle and free    */
    /* any memory associated with it.                                    */

    if (b->fetch_handle != b->display_handle) html_close(b->fetch_handle);

    /* Otherwise, still have to call EndParse (which html_close would */
    /* do, if it were called).                                        */

    else
    {
      urlstat * up = urlstat_find_entry(b->fetch_handle);

      if (up && up->context)
      {
        HtmlEndParse(up->context);
        up->context = NULL;
      }
    }
  }
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010

  b->fetch_handle = 0;

  /* Discard the URL being fetched */

  #ifdef TRACE
    if (tl & (1u<<12)) Printf("fetch_stop: Chunk CK_FURL set to 0\n");
  #endif

  memory_set_chunk_size(b, NULL, CK_FURL, 0);

2011 2012
  /* Update the status bar */

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
  toolbars_cancel_status(b, Toolbars_Status_Fetching);

  /* Check that the window extent is large enough to fit the whole page in */

  reformat_check_extent(b);

  /* Set up the window buttons */

  toolbars_set_button_states(b);
}

/*************************************************/
/* fetch_authorisation_proceed()                 */
/*                                               */
/* Given a browser_data structure with a URL     */
/* containing a host and a pointer to a realm    */
/* string, proceed with an authorisation         */
/* request based on the data in the global       */
/* 'authorise' flex block (handled by the        */
/* functions in Authorise.c).                    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the authorisation     */
/*             request;                          */
/*                                               */
/*             Pointer to a urlstat structure    */
/*             giving the fetch context, or NULL */
/*             to get it from the browser_data   */
/*             structure's fetch_handle field    */
/*             (no good for images, obviously);  */
/*                                               */
/*             Pointer to a string containing    */
/*             the realm for the request;        */
/*                                               */
/*             Pointer to the request URL.       */
/*************************************************/

void fetch_authorisation_proceed(browser_data * b, urlstat * context, char * realm, char * url)
{
2052 2053 2054 2055 2056
  int       ok, l, s, offset;
  char      host    [Limits_HostName];
  char      base64  [(Limits_AuthUserWrit + Limits_AuthPassWrit + 2) * 4 / 3];
  char      authcode[(Limits_AuthUserWrit + Limits_AuthPassWrit + 2)];
  urlstat * up;
2057 2058 2059 2060 2061

  /* Clear the 'authorising' flag */

  authorising = 0;

2062 2063
  /* If required, find out the session handle */

2064 2065
  if (!context)
  {
2066
    up = urlstat_find_entry(b->fetch_handle);
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076

    if (!up)
    {
      fetch_cancel(b);

      erb.errnum = Utils_Error_Custom_Normal; /* Nasty error but can recover from it here */

      StrNCpy0(erb.errmess,
               lookup_token("StrNotFd:Internal error: Can't find structure in %0.",
                            0,
2077
                            "fetch_authorisation_proceed"));
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139

      show_error_ret(&erb);

      return;
    }
  }
  else up = context;

  /* Mark this fetch as authorised once already - if the server */
  /* resends an authorisation request the fetcher will know     */
  /* that the authorisation failed (see html_get_next_token).   */

  up->authorised = 2;

  if (up->extradata) s = flex_size((flex_ptr) &up->extradata);
  else               s = 0;

  /* Work out the host name */

  urlutils_host_name_from_url(url, host, sizeof(host));

  /* Store the details in the authcode block */

  offset = authorise_find_user_name(host, realm);
  if (offset < 0)
  {
    fetch_authorisation_fail(b);
    return;
  }

  strcpy(authcode, authorise + offset);

  strcat(authcode, ":");

  offset = authorise_find_password(host, realm);
  if (offset < 0)
  {
    fetch_authorisation_fail(b);
    return;
  }

  strcat(authcode, authorise + offset);

  /* Encode the block */

  l = encode_base64(authcode, strlen(authcode), base64);
  base64[l] = 0;

  /* Allocate memory for the encoded data as a */
  /* header entry.                             */
  /*                                           */
  /* +2 accounts for CR + LF termination.      */

  l += strlen(AuthorisationStr) + 2;

  if (s) ok = flex_extend((flex_ptr) &up->extradata, s + l);
  else   ok = flex_alloc((flex_ptr) &up->extradata, l + 1);

  if (!ok)
  {
    fetch_cancel(b);

2140
    show_error_ret(make_no_fetch_memory_error(12));
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157

    return;
  }

  if (s) memmove(up->extradata + l, up->extradata, s);

  /* Copy the data in */

  strcpy(up->extradata, AuthorisationStr);
  strncpy(up->extradata + strlen(AuthorisationStr), base64, l - 23);
  up->extradata[l - 2] = '\r';
  up->extradata[l - 1] = '\n';

  if (!s) up->extradata[l] = 0;

  /* Restart the fetch with authentication */

2158 2159 2160 2161 2162 2163 2164
  fetch_chkerror(b, url_get_url(URL_GetURL_AgentGiven,
                    up->session,
                    up->method,
                    url,
                    &up->extradata,
                    NULL,
                    2));
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199

  return;
}

/*************************************************/
/* fetch_authorisation_fail()                    */
/*                                               */
/* Called when authorisation for a URL fails in  */
/* some way. Reports an appropriate error and    */
/* stops the fetch.                              */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the fetch.            */
/*************************************************/

void fetch_authorisation_fail(browser_data * b)
{
  /* Cancel the fetch */

  authorising = 0;
  fetch_cancel(b);

  /* Give the error */

  erb.errnum = Utils_Error_Custom_Message;

  StrNCpy0(erb.errmess,
           lookup_token("BadAuthor:Authorisation failed; you must use a valid user name and password.",
                        0,
                        0));

  show_error_ret(&erb);
}

/*************************************************/
2200
/* fetch_get_raw_data()                          */
2201
/*                                               */
2202 2203
/* Gets a chunk of data from a stream, assuming  */
/* that it is *not* HTML.                        */
2204
/*                                               */
2205 2206
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the fetch;            */
2207
/*                                               */
2208
/*             The fetch handle;                 */
2209
/*                                               */
2210 2211 2212
/*             Pointer to buffer into which the  */
/*             fetched data will be placed (as   */
/*             a char *);                        */
2213
/*                                               */
2214
/*             Size of the buffer;               */
2215
/*                                               */
2216 2217 2218 2219 2220 2221 2222 2223
/*             Pointer to an int into which 1 is */
/*             placed if the fetch is complete,  */
/*             else 0 is returned (this pointer  */
/*             may be NULL);                     */
/*                                               */
/*             Pointer to an int into which the  */
/*             number of bytes fetched is placed */
/*             (which may also be NULL).         */
2224
/*                                               */
2225 2226 2227
/* Assumes:    That if the browser_data struct   */
/*             pointer is NULL, the fetch is not */
/*             for an internal URL;              */
2228
/*                                               */
2229 2230 2231
/*             The int pointer to take the       */
/*             number of bytes fetched may not   */
/*             be NULL.                          */
2232 2233
/*************************************************/

2234 2235
_kernel_oserror * fetch_get_raw_data(browser_data * b, unsigned int handle, char * buffer,
                                     int size, int * done, int * bytes)
2236
{
2237 2238 2239
  _kernel_oserror * e;
  urlstat         * up;
  int               s, t;
2240

2241 2242 2243 2244 2245
//
// This function does not know about internal URLs yet (so parameter 'b' is currently unused)...
// BEWARE when using this, as of course this URL fetch may not be for page data under an
// internal URL.
//
2246

2247
  /* Find the urlstat structure for the fetch handle */
2248

2249
  up = urlstat_find_entry(handle);
2250 2251 2252 2253 2254 2255 2256 2257

  if (!up)
  {
    erb.errnum = Utils_Error_Custom_Fatal;

    StrNCpy0(erb.errmess,
             lookup_token("StrNotFd:Internal error: Can't find structure in %0.",
                          0,
2258
                          "fetch_get_raw_data"));
2259 2260 2261
    return &erb;
  }

2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
  /* If we're not fetching, some earlier fetch process must have */
  /* shut things down; so say that we're finished and exit.      */

  if (!up->fetching)
  {
    if (done) *done = 1;
    *bytes = 0;

    return NULL;
  }

2273
  /* Read some data */
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300

  e = url_read_data(0,
                    handle,
                    buffer,
                    size,
                    NULL,
                    bytes,
                    &t);

  if (e) return e;

  /* Get the fetch status */

  e = url_status(0,
                 handle,
                 &s,
                 NULL,
                 NULL);

  if (e) return e;

  /* Fill in 'done' as appropriate to the fetch status and exit */

  if (done) *done = (s & URL_Status_Done) ? 1 : 0;

  return NULL;
}