URLutils 64.4 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   : URLutils.c                             */
17
/*                                                 */
18
/* Purpose: URL manipulation for the browser.      */
19
/*                                                 */
20 21
/* Author : Merlyn Kline for Customer browser     */
/*          This source adapted by A.D.Hodgkinson  */
22 23 24
/*          from various original functions        */
/*                                                 */
/* History: 06-Feb-97: Created.                    */
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/***************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "swis.h"

#include "URI.h" /* URI handler API, in URILib:h */

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

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

42
#include "Fetch.h" /* (Which itself includes URLstat.h) */
43
#include "Filetypes.h"
44
#include "MimeMap.h"
45
#include "URLveneer.h"
46 47 48

#include "URLutils.h"

49 50 51 52
/* Local definitions */

#define ExtensionMatches(url, len, ext) (len) > strlen(ext) && !strncmp((url) + (len) - strlen(ext), (ext), strlen(ext))

53 54 55 56 57 58 59
/* Local variables */

/* Pointer to first item in queue of URLs dispatched through */
/* the URI handler (structure defined in URLutils.h)         */

static uri_queue * uri_queue_base = NULL;

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 211 212 213 214 215
/*************************************************/
/* urlutils_urlsscmp()                           */
/*                                               */
/* Compares two URLs, returning 1 if they differ */
/* or 0 if they are the same. Both URLs are      */
/* converted internally to url_descriptions.     */
/*                                               */
/* Parameters: Pointer to a null terminated URL  */
/*             string;                           */
/*                                               */
/*             Pointer to a second null termina- */
/*             ted URL string.                   */
/*                                               */
/* Returns:    0 if the URLs match, else 1.      */
/*************************************************/

int urlutils_urlsscmp(const char * url_s1, const char * url_s2)
{
  url_description * url_d1;
  url_description * url_d2;
  int               result;

  /* Sanity check */

  if (!url_s1 && !url_s2) return 0;
  if (!url_s1 || !url_s2) return 1;

  // Awaiting URL module stuff

  url_d1 = urlutils_return_description(url_s1);
  url_d2 = urlutils_return_description(url_s2);

  if (url_d1 && url_d2)
  {
    result = !!strcmp(url_d1->full, url_d2->full);
  }

  /* No memory, no brain. Hey ho. */

  else result = !!strcmp(url_s1, url_s2);

  free(url_d1);
  free(url_d2);

  return result;
}

/*************************************************/
/* urlutils_urldscmp()                           */
/*                                               */
/* Compares two URLs, returning 1 if they differ */
/* or 0 if they are the same. The first URL is   */
/* specified as a url_description, the second    */
/* URL is converted internally.                  */
/*                                               */
/* Parameters: Pointer to a url_description      */
/*             filled in with the URL details;   */
/*                                               */
/*             Pointer to a second null termina- */
/*             ted URL string.                   */
/*                                               */
/* Returns:    0 if the URLs match, else 1.      */
/*************************************************/

int urlutils_urldscmp(const url_description * url_d, const char * url_s)
{
  url_description * url_d2;
  int               result;

  /* Sanity check */

  if (!url_d)                 return 1;
  if (!url_s && !url_d->full) return 0;
  if (!url_s || !url_d->full) return 1;

  // Awaiting URL module stuff

  url_d2 = urlutils_return_description(url_s);

  if (url_d && url_d2)
  {
    result = !!strcmp(url_d->full, url_d2->full);
  }
  else result = !!strcmp(url_d->full, url_s);

  free(url_d2);

  return result;
}

/*************************************************/
/* urlutils_urldscmp()                           */
/*                                               */
/* Compares two URLs, returning 1 if they differ */
/* or 0 if they are the same. Both URLs are      */
/* specified as url_description structures.      */
/*                                               */
/* Parameters: Pointer to a url_description      */
/*             filled in with the URL details;   */
/*                                               */
/*             Another url_description pointer,  */
/*             filled in with the details of a   */
/*             second URL.                       */
/*                                               */
/* Returns:    0 if the URLs match, else 1.      */
/*************************************************/

int urlutils_urlddcmp(const url_description * url_d1, const url_description * url_d2)
{
  /* Sanity check */

  if (!url_d1 && url_d2)  return 1;
  if (!url_d2 && url_d1)  return 1;
  if (!url_d1 && !url_d2) return 0;

  if (!url_d1->full && !url_d2->full) return 0;
  if (!url_d1->full || !url_d2->full) return 1;

  // Awaiting URL module stuff

  return !!strcmp(url_d1->full, url_d2->full);
}

/*************************************************/
/* urlutils_return_description()                 */
/*                                               */
/* Given a URL string, returns a url_description */
/* structure which contains more accessible      */
/* details on the URL contents.                  */
/*                                               */
/* The block itself and all filled in fields are */
/* allocated with malloc(), and any additions to */
/* the structure should be allocated in the same */
/* way.                                          */
/*                                               */
/* Parameters: Pointer to a null terminated URL  */
/*             string.                           */
/*                                               */
/* Returns:    Pointer to a url_description      */
/*             structure filled in with details  */
/*             of the string, or NULL if         */
/*             allocation failed.                */
/*************************************************/

url_description * urlutils_return_description(const char * url_s)
{
  url_description * new;

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

  /* Allocate the structure */

  new = calloc(1, sizeof(url_description));

  if (!new) return NULL;

216 217 218 219 220 221 222 223 224 225 226 227 228
  /* Find the item lengths */

  if (_swix(URL_ParseURL,
            _INR(0,5),

            0,
            URL_ParseURL_Reason_FindLengths,
            url_s,
            NULL,
            new,
            sizeof(url_description) / 4)) goto urlutils_return_description_free_and_exit;

  /* Expect the canonicalised form at the very least */
229 230

  if (!new->full) goto urlutils_return_description_free_and_exit;
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

  new->full = malloc((int) new->full);
  if (!new->full) goto urlutils_return_description_free_and_exit;

  new->protocol = malloc((int) new->protocol);
  new->host     = malloc((int) new->host);
  new->port     = malloc((int) new->port);

  new->user     = malloc((int) new->user);
  new->password = malloc((int) new->password);
  new->account  = malloc((int) new->account);

  new->path     = malloc((int) new->path);

  new->query    = malloc((int) new->query);
  new->fragment = malloc((int) new->fragment);

  /* Fill in the block */

  if (_swix(URL_ParseURL,
            _INR(0,5),

            0,
            URL_ParseURL_Reason_FillBuffers,
            url_s,
            NULL,
            new,
            sizeof(url_description) / 4)) goto urlutils_return_description_free_and_exit;
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 305 306 307

  /* Finished */

  return new;

  /* Error condition exit routine */

urlutils_return_description_free_and_exit:

  urlutils_free_description(new);

  return NULL;
}

/*************************************************/
/* urlutils_free_description()                   */
/*                                               */
/* Frees a url_description and all memory        */
/* associated with it.                           */
/*                                               */
/* The function expects all filled in fields in  */
/* the structure to point to malloced blocks, as */
/* this is the way that                          */
/* urlutils_return_description allocates it.     */
/*                                               */
/* Parameters: Pointer to a url_description      */
/*             structure.                        */
/*************************************************/

void urlutils_free_description(url_description * url_d)
{
  /* Not the most demanding code in the world, really */

  free(url_d->full);
  free(url_d->protocol);
  free(url_d->host);
  free(url_d->port);
  free(url_d->user);
  free(url_d->password);
  free(url_d->account);
  free(url_d->path);
  free(url_d->query);
  free(url_d->fragment);

  free(url_d);

  return;
}

308 309 310 311 312 313 314 315 316 317 318
/*************************************************/
/* urlutils_pathname_to_url()                    */
/*                                               */
/* Takes a pathname, and turns it into a File    */
/* URL, if it isn't one already. The pathname    */
/* that you give is altered directly, so if you  */
/* want to remember the path as well as the URL, */
/* ensure there is a second copy of it in        */
/* another buffer somewhere.                     */
/*                                               */
/* Parameters: Pointer to the pathname;          */
319
/*                                               */
320 321 322 323
/*             Size of the buffer the pathname   */
/*             is stored in.                     */
/*************************************************/

324
void urlutils_pathname_to_url(char * path, int buffersize)
325
{
326 327
  int    len;
  char * pathdup;
328

329 330
  /* Try to expand the path - if this fails, carry on */
  /* without the expansion.                           */
331

332
  pathdup = malloc(strlen(path) + 1);
333

334 335 336
  if (pathdup)
  {
    unsigned int flags;
337

338
    strcpy(pathdup, path);
339

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    /* Expand the path */

    if (
         _swix(OS_GSTrans,
               _INR(0,2) | _OUT(_FLAGS),

               pathdup,
               path,
               buffersize,

               &flags)

         || (flags & _C)
       )
    {
      strcpy(path, pathdup);
    }
    else
358
    {
359 360 361 362 363 364 365 366 367 368
      /* Terminate the string at any control code */

      for (len = 0; len < buffersize; len++)
      {
        if (path[len] < 32)
        {
          path[len] = 0;
          break;
        }
      }
369
    }
370 371

    free(pathdup);
372 373
  }

374 375
  /* Find the length of the File module protocol specifier */

376
  len = strlen(FileMethod ProtocolSepShort); /* (urlutils.h) */
377

378 379 380
  /* If the first part of the string doesn't match the FileMethod */
  /* specifier (see URLutils.h) then insert this text and convert */
  /* the rest of the path to a URL.                               */
381

382
  if (strncmp(path, FileMethod ProtocolSepShort, len))
383 384
  {
    memmove(path + len, path, buffersize - len);
385
    strncpy(path, FileMethod ProtocolSepShort, len);
386 387 388 389 390 391 392 393 394 395 396

    /* Ensure the string is terminated */

    path[buffersize - 1] = 0;

    /* Now translate the pathname part of the URL to a Unix-style */
    /* path scheme.                                               */

    urlutils_translate_pathname(path + len);
  }

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
  return;
}

/*************************************************/
/* urlutils_url_to_pathname()                    */
/*                                               */
/* Takes a file:// URL, and turns it into a RISC */
/* OS pathname, if it isn't one already. The URL */
/* that you give is altered directly, so if you  */
/* want to remember the URL as well as the new   */
/* path, ensure there is a second copy of it in  */
/* another buffer somewhere.                     */
/*                                               */
/* Parameters: Pointer to the URL;               */
/*                                               */
/*             Size of the buffer the URL is     */
/*             stored in.                        */
/*************************************************/

void urlutils_url_to_pathname(char * url, int buffersize)
{
418
  url_description * url_d;
419

420
  url_d = urlutils_return_description(url);
421

422
  /* If this fails, try a more basic approach... */
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  if (!url_d)
  {
    int    len;
    char * hash;

    /* Find the length of the File module protocol specifier */

    len = strlen(FileMethod); /* (urlutils.h) */

    /* If the first part of the string doesn't match the FileMethod */
    /* specifier (see URLutils.h) then we can't do anything.        */

    if (!url || strncmp(url, FileMethod, len)) return;

    /* Copy over the file: specifier and any '/'s */

    while (url[len] == '/') len++;
441

442
    memmove(url, url + len, buffersize - len);
443

444 445 446 447
    /* Strip off any fragment (this bit could fail badly for file */
    /* system specifiers, but in the absence of URL_ParseURL      */
    /* working - 'url_d' is NULL if we reach here - there's not a */
    /* lot of point working very hard to pull out.                */
448

449 450 451 452 453 454 455 456
    hash = strrchr(url, '#');
    if (hash) *hash = 0;
  }

  else
  {
    /* We managed to get a full URL description, so take the */
    /* path component of this.                               */
457

458 459 460 461 462
    strncpy(url, url_d->path, buffersize - 1);
    url[buffersize - 1] = 0;

    urlutils_free_description(url_d);
  }
463 464 465 466 467 468

  /* Convert the path component of the URL back to RISC OS style */

  urlutils_translate_pathname(url);

  return;
469 470 471 472 473 474
}

/*************************************************/
/* urlutils_translate_pathname()                 */
/*                                               */
/* Takes a RISC OS-style pathname and turns it   */
475
/* into a Unix-style pathname, or vice versa.    */
476
/*                                               */
477 478 479 480
/* The pathname you give is altered directly, so */
/* if you want to remember the path before       */
/* translation, ensure there is a second copy of */
/* in another buffer somewhere.                  */
481
/*                                               */
482
/* Parameters: Pointer to the pathname.          */
483 484
/*************************************************/

485
void urlutils_translate_pathname(char * path)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
{
  char * p;

  p = path;

  /* Skip past any filing system separators (e.g. as in the */
  /* colons in 'ADFS::<disc>.<path>').                      */

  while (*p && *p != ':') p++;

  /* Swap '/' for '.' */

  while (*p)
  {
    if      (*p == '/') *p = '.';
    else if (*p == '.') *p = '/';

    p++;
  }

506
  return;
507 508 509 510 511 512 513 514 515 516
}

/*************************************************/
/* urlutils_leafname_from_url()                  */
/*                                               */
/* Returns a pointer to a string containing a    */
/* possible leafname, based upon the URL passed  */
/* into the function.                            */
/*                                               */
/* Parameters: Pointer to a URL string;          */
517
/*                                               */
518 519 520
/*             Pointer to a buffer into which to */
/*             place the leafname (not the same  */
/*             as the URL string);               */
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
/*             Size of the buffer.               */
/*                                               */
/* Returns:    Will fill the buffer in with some */
/*             leafname, even if one could not   */
/*             be worked out from the URL.       */
/*             Returns the buffer pointer for    */
/*             convenience (even though the      */
/*             caller will almost certainly know */
/*             this).                            */
/*                                               */
/* Assumes:    Neither pointer may be NULL. The  */
/*             buffer must be at least 2 bytes   */
/*             in size. If either condition is   */
/*             not met, NULL is returned and the */
/*             buffer is left untouched.         */
/*************************************************/

char * urlutils_leafname_from_url(char * url, char * leaf, int size)
{
  int l = 0;

  if (!url || !leaf || size < 2) return NULL;

  memset(leaf, 0, size);

  /* l holds the string length if b->urlfdata exists */

  l = (int) strlen(url);

  /* If the string exists and is not null, try to extract */
  /* a leafname from it.                                  */

  if (l)
  {
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    /* Set 'e' to point at the last character in the string, */
    /* and we will use 's' to point to the first character   */
    /* after the host name.                                  */

    int e     = l - 1;
    int s     = 0;
    int found = 0;

    /* We want to do the following, bearing in mind that whilst */
    /* a protocol at the start of the URL is assumed, it may be */
    /* separated by nothing more than a colon (not even ':/' or */
    /* '://'). The use of square brackets implies one or more   */
    /* analogous optional terms.                                */
    /*                                                          */
    /* a.b.c/[dir/]name.html  ->  name                          */
    /* a.b.c/dir[/]           ->  dir                           */
    /* a.b.c[/]               ->  Generic                       */
    /* a.b.c/name.txt         ->  name                          */
    /* a.b.c/name.tar.gz      ->  name/tar (as a consequence)   */
    /* a.b.c/name_1.2.1.gz    ->  name/1/2/1 (as a consequence) */
    /* a.b.c/name.html#anc    ->  anc                           */
    /*                                                          */
578 579 580 581 582 583 584 585 586
    /* A slight change to the above behaviour is to only strip  */
    /* filename extensions if there is a defined filetype for   */
    /* that extension. Then, for example, we get the following. */
    /*                                                          */
    /* a.b.c/dir/name.txt     ->  name                          */
    /* a.b.c/dir/name.zip     ->  name                          */
    /* a.b.c/dir/name.01      ->  name/01                       */
    /* a.b.c/dir/name.02      ->  name/02                       */
    /*                                                          */
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    /* The tricky part is determining what bit is host name and */
    /* what bit is path; it gets easier after that. First, look */
    /* for a ':'. This will either be a protocol separator, or  */
    /* a port number separator. Trouble is, you need to skip    */
    /* any '/'s after the ':' if it's the first case, so check  */
    /* if any '.'s are passed when looking for the ':'. If so,  */
    /* we're on a port number. The only possible failure case   */
    /* is a URL with no protocol specified and a single word    */
    /* host name with a port number; but then, just about every */
    /* other system will fail as the host name will be taken to */
    /* be the protocol (e.g. 'dylan:8080'). So this isn't a     */
    /* problem, really - we'd return a generic response.        */

    while (s < l && url[s] != ':')
    {
      if (url[s] == '.') found = 1;
      s++;
    }
605

606 607
    /* Did we run out of string? If so, go back to the start; */
    /* we may just have no protocol or port specified.        */
608

609
    if (s == l) s = 0;
610

611 612 613
    /* If we've not found any dots, may need to skip a few slashes;  */
    /* but not more than two, as three slashes (for example) implies */
    /* that no host name is present.                                 */
614

615 616 617
    if (!found)
    {
      s++; /* Skip past the ':' */
618

619 620
      if (url[s] == '/') s++;
      if (url[s] == '/') s++;
621

622
      /* If we ran out of string, must use a generic response */
623

624
      if (s == l) goto return_generic;
625
    }
626 627 628 629 630 631 632 633 634

    /* We're either now on the ':' separating the host name */
    /* and port number, or on the first character after any */
    /* '/'s or the ':' separating the protocol from the     */
    /* host name. In either case, we now search forward for */
    /* a single slash - the separator between host name and */
    /* path.                                                */

    while (s < l && url[s] != '/')
635
    {
636 637
      s++;
    }
638

639
    /* Skip past the '/' */
640

641
    if (url[s] == '/') s++;
642

643 644
    /* If we're run out string, go for a generic response - */
    /* e.g. 'http://www/' or just 'http://www'.             */
645

646
    if (s >= l) goto return_generic;
647

648 649 650
    /* Otherwise, we can now start searching backwards for a */
    /* usable leafname, knowing that reaching 's' is the     */
    /* exit condition. First, look for anchor names.         */
651

652 653 654 655 656
    if (strrchr(url, '#') > strrchr(url, '/')) /* Want 'a/b#c' -> 'c', but not 'a#b/c' -> 'b/c' */
    {
      while (e > s && url[e] != '#')
      {
        e--;
657 658
      }

659
      /* Step forward past the '#' */
660

661
      e++;
662

663 664 665 666 667 668
      /* If it turns out that the '#' is all that there is after */
      /* the host name, it may be possible to step back and get  */
      /* whatever comes before it; or if we hit 's' in trying,   */
      /* we'll have to return a generic response.                */

      if (e == l)
669
      {
670
        e --;
671

672 673
        if (e <= s) goto return_generic;
        else        goto get_directory_name;
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

      /* Right, copy the string from this point forwards */

      strncpy(leaf, url + e, size - 1);

      /* Finished, so jump to the final stripping routine */

      goto strip_illegal_chars;
    }

    /* Right, if we have a trailing '/' or '#' (from the above code), */
    /* following a directory name, then get that directory name.      */

get_directory_name:

    if (url[e] == '/' || url[e] == '#')
    {
      int chars;

      found = e--;

      /* Find the start point of the name */

      while (e > s && url[e] != '/') e--;

      /* If e is greater than s, we're sitting on the '/' */
      /* found above, so advance past it.                 */

      if (e > s) e++;

      /* Copy the name in */

      chars = found - e;
      if (chars > size - 1) chars = size - 1;
      strncpy(leaf, url + e, chars);

      /* Finished - just need to take care of any illegal characters */

      goto strip_illegal_chars;
    }

    /* Otherwise, continue, looking for a '/'. If a '.' is found on the */
    /* way, remember the offset for the first time it is encountered.   */

    found = 0;

    while (e > s && url[e] != '/')
    {
      if (url[e] == '.' && !found) found = e;
      e--;
    }

    if (url[e] == '/')
    {
      e++;
      if (e >= l) goto return_generic;
    }

    /* We now have 'e' pointing to the start of a leafname */
    /* and possibly 'found' pointing to the start of a     */
    /* filename extension. If the latter is true, check    */
    /* that there is something between the two...          */

    if (found && found - 1 == e) goto return_generic;

740 741
    /* OK, we have a string. If found is NULL, then we don't have a */
    /* filename extension to strip                                  */
742 743 744 745 746

    if (!found)
    {
      strncpy(leaf, url + e, size - 1);
    }
747 748 749

    /* Otherwise, strip the extension if a filetype is found for it */

750 751 752
    else
    {
      int chars = found - e;
753
      int filetype;
754

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
      /* Is there a filetype for this extension? */

      if (
           (
             mimemap_extension_to_riscos(url + found, &filetype) ||
             filetype == FileType_DATA
           )
           && utils_strcasecmp(url + found, ".cgi") /* Special case '.cgi' - always strip it */
         )
      {
        /* Don't strip it */

        strncpy(leaf, url + e, size - 1);
      }
      else
      {
        /* Strip the extension */

        if (chars > size - 1) chars = size - 1;
        strncpy(leaf, url + e, chars);
      }
776
    }
777

778 779
    /* Right, that's the worst of it over...! The strip routine will */
    /* take care of converting '.'s to '/'s, etc., if there are any. */
780 781 782 783 784 785 786

    goto strip_illegal_chars;

return_generic:

    lookup_token("NoURLleaf:Index",0,0);
    strncpy(leaf, tokens, size - 1);
787 788 789 790 791 792 793 794 795 796 797
  }

  /* There was apparently no URL in the buffer, so offer a */
  /* neutral filename of HTMLfile.                         */

  else
  {
    lookup_token("NoURLdata:HTMLfile",0,0); /* Will put the string in the 'tokens' global buffer */
    strncpy(leaf, tokens, size - 1);
  }

798 799
strip_illegal_chars:

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
  /* Scan the leaf for illegal characters */

  l = 0;

  while (leaf[l])
  {
    /* A few we can replace with meaningful alternatives */

    if (leaf[l] == '.')  leaf[l] = '/';
    if (leaf[l] == '\\') leaf[l] = '/';
    if (leaf[l] == '&')  leaf[l] = '+';
    if (leaf[l] == '"')  leaf[l] = '\'';

    /* And the rest, replace with underscores */

    if (
         leaf[l] == '$' ||
         leaf[l] == '%' ||
         leaf[l] == '@' ||
         leaf[l] == '^' ||
         leaf[l] == ':' ||
         leaf[l] == '#' ||
         leaf[l] == '*' ||
         leaf[l] == '"' ||
         leaf[l] == '|'
       )
       leaf[l] = '_';

    l++;
  }

  /* Finished. */

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
  return leaf;
}

/*************************************************/
/* urlutils_host_name_from_url()                 */
/*                                               */
/* Extracts the host name from a given URL.      */
/*                                               */
/* Parameters: Pointer to the URL string;        */
/*                                               */
/*             Pointer to a buffer to write the  */
/*             host name into;                   */
/*                                               */
/*             Size of the buffer.               */
/*************************************************/

void urlutils_host_name_from_url(char * url, char * host, int size)
{
  char * p;

  host[0] = 0;

  /* First look for '//', as in 'http://' */

857
  p = strstr(url, ProtocolSeparator);
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

  if (p)
  {
    /* If found, copy everything after that into 'host' */

    p += 2;
    strncpy(host, p, size - 1);
    host[size - 1] = 0;

    /* Now search for a '/', as in 'http://www.acorn/', */
    /* and if found force a terminator there.           */

    p = strchr(host, '/');
    if (p) *p = 0;
  }
}

875 876 877 878 879 880 881 882 883 884 885 886 887 888
/*************************************************/
/* urlutils_filetype_from_url()                  */
/*                                               */
/* Examines a URL and returns a RISC OS filetype */
/* based on the filename extension in the URL.   */
/*                                               */
/* Parameters: Pointer to a null-terminated URL  */
/*             string.                           */
/*                                               */
/* Returns:    A RISC OS filetype.               */
/*************************************************/

int urlutils_filetype_from_url(const char * url)
{
889 890
  const char * dot;
  int          filetype;
891 892

  if (!url || !*url) return NULL;
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

  dot = strrchr(url, '.');

  if (!dot) return FileType_TEXT;

  if (mimemap_extension_to_riscos(dot, &filetype)) return FileType_TEXT;

  return filetype;

//  /* For now, hard code it. In future, use a mime mapper module. */
//
//  int len;
//
//  if (!url || !*url) return NULL;
//  else len = strlen(url);
//
//  /* Document types */
//
//  if (ExtensionMatches(url, len, ".html"))  return FileType_HTML;
//  if (ExtensionMatches(url, len, ".htm"))   return FileType_HTML;
//  if (ExtensionMatches(url, len, ".txt"))   return FileType_TEXT;
//  if (ExtensionMatches(url, len, ".shtml")) return FileType_HTML;
//  if (ExtensionMatches(url, len, ".shtm"))  return FileType_HTML;
//  if (ExtensionMatches(url, len, ".pdf"))   return FileType_PDF;
//  if (ExtensionMatches(url, len, ".doc"))   return FileType_WORD;
//  if (ExtensionMatches(url, len, ".ps"))    return FileType_PS;
//  if (ExtensionMatches(url, len, ".eps"))   return FileType_PS;
//  if (ExtensionMatches(url, len, ".wri"))   return FileType_DOS;
//  if (ExtensionMatches(url, len, ".xls"))   return FileType_XLS;
//
//  /* Images */
//
//  if (ExtensionMatches(url, len, ".gif"))   return FileType_GIF;
//  if (ExtensionMatches(url, len, ".jpg"))   return FileType_JPEG;
//  if (ExtensionMatches(url, len, ".jpeg"))  return FileType_JPEG;
//  if (ExtensionMatches(url, len, ".tiff"))  return FileType_TIFF;
//  if (ExtensionMatches(url, len, ".tif"))   return FileType_TIFF;
//  if (ExtensionMatches(url, len, ".png"))   return FileType_PNG;
//
//  /* Archives */
//
//  if (ExtensionMatches(url, len, ".zip"))   return FileType_ARC;
//  if (ExtensionMatches(url, len, ".arc"))   return FileType_ARC;
//  if (ExtensionMatches(url, len, ".spk"))   return FileType_ARC;
//  if (ExtensionMatches(url, len, ".arj"))   return FileType_ARC;
//  if (ExtensionMatches(url, len, ".gz"))    return FileType_GZ;
//  if (ExtensionMatches(url, len, ".tar"))   return FileType_ARC;
//  if (ExtensionMatches(url, len, ".zoo"))   return FileType_ARC;
//
//  /* Sounds */
//
//  if (ExtensionMatches(url, len, ".wav"))   return FileType_WAVE;
//  if (ExtensionMatches(url, len, ".arm"))   return FileType_ARMA;
//  if (ExtensionMatches(url, len, ".mod"))   return FileType_MOD;
//
//  /* Movies */
//
//  if (ExtensionMatches(url, len, ".mov"))   return FileType_AVI;
//  if (ExtensionMatches(url, len, ".avi"))   return FileType_AVI;
//  if (ExtensionMatches(url, len, ".qt"))    return FileType_AVI;
//  if (ExtensionMatches(url, len, ".qtvr"))  return FileType_AVI;
//  if (ExtensionMatches(url, len, ".rpl"))   return FileType_ARMO;
//  if (ExtensionMatches(url, len, ".rep"))   return FileType_ARMO;
//
//  /* Miscellaneous */
//
//  if (ExtensionMatches(url, len, ".bin"))   return FileType_DATA;
//  if (ExtensionMatches(url, len, ".dat"))   return FileType_DATA;
//  if (ExtensionMatches(url, len, ".data"))  return FileType_DATA;
//  if (ExtensionMatches(url, len, ".exe"))   return FileType_DOS;
//  if (ExtensionMatches(url, len, ".com"))   return FileType_DOS;
//
//  /* Otherwise, return text */
//
//  return FileType_TEXT;
968 969
}

970 971 972 973 974
/*************************************************/
/* urlutils_create_hotlist_url()                 */
/*                                               */
/* Creates a URL though which a hotlist file may */
/* be fetched. This is done by looking at a      */
975 976
/* system variable '<App>$HotlistURL'. If that   */
/* isn't set it looks at '<App>$HotlistURIFile'  */
977 978 979 980 981 982 983 984 985
/* which can hold the path of a URI file to      */
/* load. Lastly, it looks at the Choices file    */
/* token 'HotlistPath', where a RISC OS pathname */
/* pointing to the file should be placed. This   */
/* will be turned into a URL for fetching, so    */
/* care must be taken over the path used.        */
/*                                               */
/* Parameters: Pointer to a buffer to place the  */
/*             URL in (not in a flex block!);    */
986
/*                                               */
987 988 989 990 991 992
/*             Size of the buffer.               */
/*************************************************/

void urlutils_create_hotlist_url(char * buffer, int size)
{
  _kernel_oserror * e;
993
  char            * varname;
994

995 996
  /* See if the variable exists. */

997 998
  memset(buffer, 0, size);

999 1000 1001
  /* Equivalent to getenv, but the RISC OS implementation evaluates  */
  /* the system variable as an expression which we don't want; hence */
  /* the direct use of the SWI.                                      */
1002

1003 1004 1005
  varname = lookup_token("_TaskName",1,0);
  strcat(varname, "$HotlistURL");

1006 1007 1008
  e = _swix(OS_ReadVarVal,
            _INR(0,4),

1009 1010 1011 1012 1013
            varname, /* Variable name                      */
            buffer,  /* Buffer                             */
            size,    /* Buffer size, -1 to check it exists */
            0,       /* Name pointer (0 for 1st call)      */
            4);      /* Variable type (4 = literal string) */
1014 1015 1016 1017 1018

  /* First lookup failed, so try the URI file. */

  if (e)
  {
1019 1020 1021
    varname = lookup_token("_TaskName",1,0);
    strcat(varname, "$HotlistURIFile");

1022 1023 1024
    e = _swix(OS_ReadVarVal,
              _INR(0,4),

1025
              varname,
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
              buffer,
              size,
              0,
              4);

    if (e)
    {
      /* If the above gives an error, the variable doesn't exist; get */
      /* the HotlistPath string from the Messages file instead.       */

      strncpy(buffer, lookup_choice("HotlistPath",1,0), size - 1);
      urlutils_pathname_to_url(buffer, size);
    }
    else
    {
1041
      char path[Limits_OS_Pathname];
1042 1043

      StrNCpy0(path, buffer);
1044
      urlutils_load_uri_file(buffer, size, NULL, 0, path);
1045 1046 1047 1048 1049 1050 1051 1052 1053
    }
  }
}

/*************************************************/
/* urlutils_create_home_url()                    */
/*                                               */
/* Creates a URL though which a home page may be */
/* fetched. This is done by looking at a system  */
1054 1055
/* variable '<App>$HomeURL'. If that isn't set,  */
/* it looks at '<App>$HomeURIFile', which can   */
1056 1057 1058 1059 1060 1061
/* hold the path of a URI file to load. Lastly,  */
/* it looks at the Choices file token            */
/* 'HomePage'.                                   */
/*                                               */
/* Parameters: Pointer to a buffer to place the  */
/*             URL in (not in a flex block!);    */
1062
/*                                               */
1063 1064 1065 1066 1067 1068
/*             Size of the buffer.               */
/*************************************************/

void urlutils_create_home_url(char * buffer, int size)
{
  _kernel_oserror * e;
1069
  char            * varname;
1070

1071 1072
  /* See if the variable exists */

1073 1074
  memset(buffer, 0, size);

1075 1076 1077
  /* Equivalent to getenv, but the RISC OS implementation evaluates  */
  /* the system variable as an expression which we don't want; hence */
  /* the direct use of the SWI.                                      */
1078

1079 1080 1081
  varname = lookup_token("_TaskName",1,0);
  strcat(varname, "$HomeURL");

1082 1083 1084
  e = _swix(OS_ReadVarVal,
            _INR(0,4),

1085 1086 1087 1088 1089
            varname, /* Variable name                      */
            buffer,  /* Buffer                             */
            size,    /* Buffer size, -1 to check it exists */
            0,       /* Name pointer (0 for 1st call)      */
            4);      /* Variable type (4 = literal string) */
1090 1091 1092 1093 1094

  /* First lookup failed, so try the URI file. */

  if (e)
  {
1095 1096 1097
    varname = lookup_token("_TaskName",1,0);
    strcat(varname, "$HomeURIFile");

1098 1099 1100
    e = _swix(OS_ReadVarVal,
              _INR(0,4),

1101
              varname,
1102 1103 1104 1105 1106 1107 1108 1109
              buffer,
              size,
              0,
              4);

    if (e)
    {
      /* If the above gives an error, the variable doesn't exist; get */
1110 1111
      /* the HotlistPath string from the global choices structure     */
      /* instead.                                                     */
1112

1113
      strncpy(buffer, choices.home_page, size - 1);
1114 1115 1116
    }
    else
    {
1117
      char path[Limits_OS_Pathname];
1118 1119

      StrNCpy0(path, buffer);
1120
      urlutils_load_uri_file(buffer, size, NULL, 0, path);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    }
  }
}

/*************************************************/
/* urlutils_fix_url()                            */
/*                                               */
/* Takes a URL and 'fixes' it, e.g. appends a    */
/* '/' character to a URL which is missing one.  */
/* The contents of the buffer you give with the  */
/* URL inside are altered directly, so if you    */
/* want to remember the old URL, ensure there is */
/* a second copy of it in another buffer         */
/* somewhere.                                    */
/*                                               */
/* Parameters: Pointer to the URL;               */
1137
/*                                               */
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
/*             Size of the buffer the URL is     */
/*             stored in.                        */
/*                                               */
/* Returns:    Pointer to the fixed URL (which   */
/*             at the moment is the buffer that  */
/*             you passed in).                   */
/*************************************************/

char * urlutils_fix_url(char * buffer, int buffersize)
{
1148 1149 1150 1151 1152 1153
  int len,  shl;
  int flen, fshl;
  int glen, gshl;
  int blen, plen;

  plen = strlen(ProtocolSeparator);
1154

1155
  shl  = strlen(HTTPmethod);
1156
  len  = shl + plen;
1157

1158
  fshl = strlen(FTPmethod);
1159 1160 1161 1162
  flen = fshl + plen;

  gshl = strlen(GopherMethod);
  glen = gshl + plen;
1163

1164 1165 1166 1167 1168 1169 1170 1171 1172
  blen = strlen(buffer);

  /* If there's no ':' in the string, insert a protocol type */

  if (
       !strchr(buffer, ':')     &&
       blen + len  < buffersize &&
       blen + flen < buffersize
     )
1173
  {
1174
    /* If the site appears to be an FTP site, insert the FTP protocol */
1175
    /* at the start. Similarly for Gopher; else insert HTTP.          */
1176

1177
    if (!strncmp(buffer, FTPmethod, fshl - 1)) /* -1 as we don't want to compare the ':' */
1178 1179 1180 1181
    {
      memmove(buffer + flen, buffer, buffersize - flen);
      strncpy(buffer, FTPmethod ProtocolSeparator, flen);
    }
1182 1183 1184 1185 1186
    else if (!strncmp(buffer, GopherMethod, gshl - 1))
    {
      memmove(buffer + glen, buffer, buffersize - glen);
      strncpy(buffer, GopherMethod ProtocolSeparator, glen);
    }
1187 1188 1189 1190 1191
    else
    {
      memmove(buffer + len, buffer, buffersize - len);
      strncpy(buffer, HTTPmethod ProtocolSeparator, len);
    }
1192 1193 1194 1195 1196

    buffer[buffersize - 1] = 0;
  }

  /* If there are at least 2 unused bytes in the buffer, and the */
1197
  /* front of the string matches the HTTPMethod specifier (again */
1198 1199 1200 1201 1202
  /* this is defined at the top of this file) then search for a  */
  /* '/' character which isn't part of a '//' sequence. If none  */
  /* is found, append a '/'. This is why 2 bytes free are needed */
  /* - one for the '/', one for the string terminator.           */

1203
  if (strlen(buffer) < buffersize - 2 && !strncmp(buffer, HTTPmethod, shl))
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  {
    int i, s = 0;

    for (i = 0;
         !s && buffer[i] && (i < (buffersize - 1));
         i ++)
    {
      /* If we have a '/' but not a '//' sequence, mark this with s = 1 */

      if (buffer[i] == '/' && buffer[i + 1] != '/') s = 1;

      /* If at start of a '//' sequence, skip past it */

      else if (buffer[i] == '/') i++;
    }

    if (!s) strcat(buffer,"/");
  }

  return buffer;
}

/*************************************************/
/* urlutils_load_uri_file()                      */
/*                                               */
1229
/* Loads a URI file. Will take ANT URL files     */
1230 1231
/* too. The given buffer will be filled with a   */
/* null-terminated URI from the file.            */
1232
/*                                               */
1233
/* The load terminates when the buffer is full   */
1234 1235 1236 1237 1238 1239
/* except for the last byte (to allow for a      */
/* forced terminator), or a control code is met  */
/* in the URI file. Note that the buffer is      */
/* initialised to hold null bytes before the URI */
/* file is opened.                               */
/*                                               */
1240 1241 1242
/* For URI files, you may also try to read a     */
/* title string.                                 */
/*                                               */
1243
/* If there is an error opening the file or the  */
1244 1245
/* file is empty, the contents of the buffer are */
/* undefined.                                    */
1246
/*                                               */
1247 1248
/* Parameters: Pointer to the buffer for the     */
/*             URL;                              */
1249
/*                                               */
1250
/*             Size of the buffer;               */
1251
/*                                               */
1252 1253 1254 1255 1256
/*             Pointer to the buffer for the     */
/*             title (if any), or NULL;          */
/*                                               */
/*             Size of the buffer (or zero);     */
/*                                               */
1257 1258 1259
/*             Pointer to the pathname of the    */
/*             URI file.                         */
/*                                               */
1260
/* Assumes:    The buffers and path must NOT be  */
1261 1262 1263
/*             the same area in memory.          */
/*************************************************/

1264
void urlutils_load_uri_file(char * buffer, size_t size, char * tbuffer, size_t tsize, char * path)
1265 1266
{
  FILE * fp;
1267
  int    byte, counter;
1268
  int    type, found;
1269

1270 1271 1272
  /* Warning - heavy use of 'goto's coming up shortly...! */

  if (!size) return;
1273 1274
  memset(buffer, 0, size);

1275 1276 1277
  if (tbuffer && tsize) memset(tbuffer, 0, tsize);

  /* Does the file exist? */
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296

  if (
       _swix(OS_File,
             _INR(0,1) | _OUT(0) | _OUT(6),

             23, /* Read catalogue info for named, stamped object */
             path,

             &found,
             &type)
     )
     return;

  /* 'found' should be 1 (a file, rather than not found, a directory, etc.). */

  if (found != 1) return;

  /* Open the file */

1297 1298 1299 1300
  fp = fopen(path, "rb");

  if (fp)
  {
1301 1302 1303 1304 1305
    byte = getc(fp);

    /* For URL files, go straight to URL reading - they're just */
    /* a terminated, or unterminated URL in a file.             */

1306
    if (type != FileType_URI) goto urlutils_load_uri_file_read_uri;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331

    /* If it is a URI file, it must start with 'URI'. */

    if (byte != 'U') goto urlutils_load_uri_file_not_a_uri_file;

    byte = getc(fp);
    if (byte != 'R') goto urlutils_load_uri_file_not_a_uri_file;

    byte = getc(fp);
    if (byte != 'I') goto urlutils_load_uri_file_not_a_uri_file;

    /* Get to first character after the 'I' */

    byte = getc(fp);

    /* Now find the version number - skip white space */

urlutils_load_uri_file_skip_white_space_1:

    while (byte != EOF && byte < ' ') byte = getc(fp);

    /* If we've hit a hash, this is a comment line - terminated by white */
    /* space or end of file.                                             */

    if (byte == '#')
1332
    {
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
      /* Now want to *find* the white space to skip the comment */

      while (byte != EOF && byte >= ' ') byte = getc(fp);

      /* If we're not at the end of the file, loop back and continue */
      /* skipping white space.                                       */

      if (byte != EOF) goto urlutils_load_uri_file_skip_white_space_1;
    }

    /* By now, we're either at EOF or the start of the first real entry */
    /* after 'URL', which will be the file version. URI file versions   */
    /* are guaranteed backwards compatible, so we can skip this bit.    */

    while (byte != EOF && byte >= ' ') byte = getc(fp);

    /* Now we want to get to the URI, so again, skip white space */
    /* and comment lines. After that, we'll be on the first byte */
    /* of the URI (or end of file, if it's broken).              */

urlutils_load_uri_file_skip_white_space_2:

    while (byte != EOF && byte < ' ') byte = getc(fp);

    if (byte == '#')
    {
      while (byte != EOF && byte >= ' ') byte = getc(fp);

      if (byte != EOF) goto urlutils_load_uri_file_skip_white_space_2;
    }

    /* Load the URI component - assume everything from here up */
    /* to any control chracter or EOF is part of the URI. Note */
    /* that 'byte' already contains the first character.       */

urlutils_load_uri_file_read_uri:

1370 1371
    counter = 0;

1372 1373 1374 1375
    while (byte != EOF && byte >= ' ' && counter < size - 1)
    {
      buffer[counter++] = byte;
      byte              = getc(fp);
1376 1377
    }

1378 1379 1380
    /* If it's a single '*', the URI is not present */

    if (!strcmp(buffer, "*")) *buffer = 0;
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

    /* We may still have a title to read... */

    if (type == FileType_URI && tbuffer && tsize)
    {
      /* Once more, skip any white space or comments */

urlutils_load_uri_file_skip_white_space_3:

      while (byte != EOF && byte < ' ') byte = getc(fp);

      if (byte == '#')
      {
        while (byte != EOF && byte >= ' ') byte = getc(fp);

        if (byte != EOF) goto urlutils_load_uri_file_skip_white_space_3;
      }

      /* Now read the title */

      counter = 0;

      while (byte != EOF && byte >= ' ' && counter < size - 1)
      {
        tbuffer[counter++] = byte;
        byte               = getc(fp);
      }

      /* If it's a single '*', the URI is not present */

      if (!strcmp(tbuffer, "*")) *tbuffer = 0;
    }

    fclose(fp);
1415
  }
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454

  return;

  /* Error condition exits */

urlutils_load_uri_file_not_a_uri_file:

  /* Not a URI / URL file */

  if (fp) fclose(fp);

  erb.errnum = Utils_Error_Custom_Message;

  StrNCpy0(erb.errmess,
           lookup_token("NotAURI:This is not a valid URI file.",
                        0,
                        0));

  show_error_ret(&erb);

  return;
}

/*************************************************/
/* urlutils_extract_uri()                        */
/*                                               */
/* Looks at a URI file loaded into a buffer, and */
/* overwrites it with the URL contents extracted */
/* from the body.                                */
/*                                               */
/* Parameters: Pointer to the buffer holding the */
/*             URI file;                         */
/*                                               */
/*             Size of the file (the buffer is   */
/*             assumed to be at least this size  */
/*             but not assumed to be larger).    */
/*                                               */
/* Returns:    Contents of the buffer are        */
/*             updated to hold a null terminated */
1455 1456
/*             URI followed by a null terminated */
/*             title string, if there is one.    */
1457 1458 1459 1460
/*************************************************/

void urlutils_extract_uri(char * buffer, size_t file_size)
{
1461 1462 1463
  int copy    = 0;
  int counter = 0;
  int is_uri  = 1;
1464 1465 1466

  if (!buffer || !file_size) return;

1467 1468 1469 1470 1471 1472
  /* Ensure it starts with 'URI' - if not, jump straight to */
  /* URI extraction (assume it's a URL file).               */

  if (strncmp(buffer, "URI", 3))
  {
    is_uri = 0;
1473

1474 1475
    goto urlutils_extract_uri_read_uri;
  }
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 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540

  /* Point to the first byte after the 'URI' indentifier */

  counter = 3;

  /* Skip white space to find the version number */

urlutils_extract_uri_skip_white_space_1:

  while (
          counter < file_size   &&
          buffer[counter]       &&
          buffer[counter] < ' '
        )
        counter++;

  /* If we find a comment, skip the comment body */

  if (buffer[counter] == '#')
  {
    while (
            counter < file_size    &&
            buffer[counter]        &&
            buffer[counter] >= ' '
          )
          counter++;

    /* Now go back to skip the white space after the comment, and */
    /* thus any other comments that follow.                       */

    if (buffer[counter]) goto urlutils_extract_uri_skip_white_space_1;
  }

  /* Skip the file version */

  while (
          counter < file_size    &&
          buffer[counter]        &&
          buffer[counter] >= ' '
        )
        counter++;

  /* Again, skip white space and comments */

urlutils_extract_uri_skip_white_space_2:

  while (
          counter < file_size   &&
          buffer[counter]       &&
          buffer[counter] < ' '
        )
        counter++;

  if (buffer[counter] == '#')
  {
    while (
            counter < file_size    &&
            buffer[counter]        &&
            buffer[counter] >= ' '
          )
          counter++;

    if (buffer[counter]) goto urlutils_extract_uri_skip_white_space_2;
  }

1541
urlutils_extract_uri_read_uri:
1542

1543
  /* Now we're at the URI. Copy it to the start of the buffer. */
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556

  while (
          counter < file_size    &&
          buffer[counter]        &&
          buffer[counter] >= ' '
        )
        buffer[copy++] = buffer[counter++];

  /* Need to make sure that the string is terminated - if we're */
  /* likely to overflow the buffer, we must overwrite the last  */
  /* char with a terminator. You never know, it could be a non- */
  /* essential last character (e.g. trailing '/').              */

1557
  if (copy && copy < file_size) buffer[copy] = 0, copy++;
1558 1559
  else buffer[copy - 1] = 0;

1560
  /* May have a title to read, too. */
1561

1562 1563 1564
  if (is_uri)
  {
    /* Skip white space and comments once more */
1565

1566
urlutils_extract_uri_skip_white_space_3:
1567

1568 1569 1570 1571 1572 1573
    while (
            counter < file_size   &&
            buffer[counter]       &&
            buffer[counter] < ' '
          )
          counter++;
1574

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    if (buffer[counter] == '#')
    {
      while (
              counter < file_size    &&
              buffer[counter]        &&
              buffer[counter] >= ' '
            )
            counter++;

      if (buffer[counter]) goto urlutils_extract_uri_skip_white_space_3;
    }
1586

1587
    /* Now read the title */
1588

1589 1590 1591 1592 1593 1594
    while (
            counter < file_size    &&
            buffer[counter]        &&
            buffer[counter] >= ' '
          )
          buffer[copy++] = buffer[counter++];
1595

1596 1597 1598 1599 1600 1601 1602 1603 1604
    /* Again, ensure things are correctly terminated */

    if (copy && copy < file_size) buffer[copy] = 0;
    else buffer[copy - 1] = 0;
  }

  /* If we've ended up with just a single star, the field is blank */

  if (!strcmp(buffer, "*")) *buffer = 0;
1605 1606

  return;
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 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
}

/*************************************************/
/* urlutils_internal_extra()                     */
/*                                               */
/* Returns an offset into a given string at      */
/* which extra data in an internal URL may be    */
/* found.                                        */
/*                                               */
/* Parameters: Pointer to the URL string.        */
/*                                               */
/* Returns:    Offset for the extra data, or 0   */
/*             if none is found.                 */
/*************************************************/

int urlutils_internal_extra(char * iurl)
{
  char * extra;

  if (strncmp(iurl, Internal_URL, Int_URL_Len)) return 0;

  extra = strchr(iurl, ':');

  if (!extra) return 0;
  else extra ++;

  return (int) (extra - iurl);
}

/*************************************************/
/* urlutils_internal_tail()                      */
/*                                               */
/* Returns an offset into a given string at      */
/* which tail data (typically a URL leafname)    */
/* may be found.                                 */
/*                                               */
/* Parameters: Pointer to the URL string.        */
/*                                               */
/* Returns:    Offset for the tail data, or 0 if */
/*             none is found.                    */
/*************************************************/

int urlutils_internal_tail(char * iurl)
{
  char * tail, * extra;
  int    exoff, found = 0;

  exoff = urlutils_internal_extra(iurl);

  if (!exoff) return 0;

  extra = iurl + exoff;
  tail  = iurl + strlen(iurl); /* No '-1' here as tail is decremented early in the while loop below */

  while (tail > extra && !found)
  {
    tail--;
    if (*tail == '/') found = 1;
  }

  if (!found) return 0;
  else tail ++;

  return (int) (tail - iurl);
}

/*************************************************/
/* urlutils_set_displayed()                      */
/*                                               */
/* On the basis of a given internal URL, sets    */
/* the 'displayed' field of a given browser_data */
/* structure.                                    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             that is to be altered;            */
1682
/*                                               */
1683 1684 1685 1686 1687 1688 1689
/*             Pointer to the internal URL.      */
/*************************************************/

void urlutils_set_displayed(browser_data * b, char * iurl)
{
  if (!strncmp(iurl, Internal_URL, Int_URL_Len))
  {
1690 1691 1692 1693
    if      (!strncmp(iurl + Int_URL_Len, ForExternalHImage, strlen(ForExternalHImage))) b->displayed = Display_External_Image;
    else if (!strncmp(iurl + Int_URL_Len, ForExternalNImage, strlen(ForExternalNImage))) b->displayed = Display_External_Image;
    else if (!strncmp(iurl + Int_URL_Len, ForScrapFile,      strlen(ForScrapFile)))      b->displayed = Display_Scrap_File;
    else if (!strncmp(iurl + Int_URL_Len, ForGoBack,         strlen(ForGoBack)))         b->displayed = Display_Previous_Page;
1694
    else if (!strncmp(iurl + Int_URL_Len, ForGoForward,      strlen(ForGoForward)))      b->displayed = Display_Next_Page;
1695
    else if (!strncmp(iurl + Int_URL_Len, ForGoRecover,      strlen(ForGoRecover)))      b->displayed = Display_Recovered_Page;
1696
    else if (!strncmp(iurl + Int_URL_Len, ForGoReload,       strlen(ForGoReload)))       b->displayed = Display_Reloaded_Page;
1697
    else if (!strncmp(iurl + Int_URL_Len, ForGoHome,         strlen(ForGoHome)))         b->displayed = Display_Home_Page;
1698
    else if (!strncmp(iurl + Int_URL_Len, ForAbout,          strlen(ForAbout)))          b->displayed = Display_About_Page;
1699 1700
    else if (!strncmp(iurl + Int_URL_Len, ForGoToURL,        strlen(ForGoToURL)))        b->displayed = Display_Embedded_URL;
    else if (!strncmp(iurl + Int_URL_Len, ForAnError,        strlen(ForAnError)))        b->displayed = Display_Embedded_Error;
1701 1702

    else b->displayed = Display_Fetched_Page;
1703 1704 1705 1706 1707
  }
  else b->displayed = Display_Fetched_Page;
}

/*************************************************/
1708
/* urlutils_check_protocols()                    */
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
/*                                               */
/* Checks a given URL to see if the fetch        */
/* protocol it specifies can be handled.         */
/*                                               */
/* Parameters: Pointer to the URL string.        */
/*                                               */
/* Returns:    1 if the URL can be handled (i.e. */
/*             the protocol at the start of the  */
/*             URL matches one that the Messages */
/*             file says a module which is       */
/*             currently running copes with),    */
/*             else 0.                           */
/*************************************************/

int urlutils_check_protocols(char * url)
{
  int  protocols = 0;
  int  i;
1727
  char p[24];
1728 1729 1730 1731 1732

  if (!url || (url && !*url)) return 0;

  /* Find the number of possible protocols */

1733
  protocols = atoi(lookup_control("ProtocolMax", 1, NULL));
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753

  /* Exit if not found / not a sensible number */

  if (protocols <= 0) return 0;

  /* Loop round all protocols */

  for (i = 1; i <= protocols; i++)
  {
    /* Look up the module name by building a MessageTrans  */
    /* token of the appropriate format, and call OS_Module */
    /* 18 (lookup module) for it; if the SWI doesn't       */
    /* raise an error, the module was found.               */

    sprintf(p, "ProtocolM%d", i);

    if (!_swix(OS_Module,
               _INR(0,1),

               18,
1754
               lookup_control(p, 1, NULL)))
1755 1756 1757 1758 1759
    {
      /* Module is present, so check the protocol */

      sprintf(p, "ProtocolU%d", i);

1760
      lookup_control(p, 1, NULL);
1761 1762 1763 1764 1765 1766 1767 1768 1769

      /* If the protocol identifier can be found... */

      if (tokens[0] != '!')
      {
        /* Compare it to the same number of characters in */
        /* the given URL. If it matches, we can deal with */
        /* the URL.                                       */

1770
        if (!utils_strncasecmp(tokens, url, strlen(tokens))) return 1;
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781

        /* Otherwise, loop on to the next protocol... */
      }
    }
  }

  /* If we reach here, no protocol was found. */

  return 0;
}

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 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 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
/*************************************************/
/* urlutils_cycle_protocol()                     */
/*                                               */
/* Given a URL, add in the HTTP protocol         */
/* specifier if none is already present, or      */
/* cycle through those in order of appearance in */
/* the protocols list in Controls.               */
/*                                               */
/* Parameters: Pointer to the URL string;        */
/*                                               */
/*             Size of the buffer the URL string */
/*             lies in (the string will be       */
/*             updated).                         */
/*                                               */
/* Returns:    1 if the URL was changed, else 0. */
/*************************************************/

int urlutils_cycle_protocol(char * url, int size)
{
  int  protocols = 0;
  int  in_use    = 0;
  int  have_any  = 0;
  int  have_one  = 0;
  int  i, ulen, plen;
  char p[24];

  if (!url || !size) return 0;

  /* Find the number of possible protocols */

  protocols = atoi(lookup_control("ProtocolMax", 1, NULL));

  /* Exit if not found / not a sensible number */

  if (protocols <= 0) return 0;

  /* Loop round all protocols */

  for (i = 1; i <= protocols; i++)
  {
    /* Look up the module name by building a MessageTrans  */
    /* token of the appropriate format, and call OS_Module */
    /* 18 (lookup module) for it; if the SWI doesn't       */
    /* raise an error, the module was found.               */

    sprintf(p, "ProtocolM%d", i);

    if (!_swix(OS_Module,
               _INR(0,1),

               18,
               lookup_control(p, 1, NULL)))
    {
      /* Module is present, so check the protocol */

      sprintf(p, "ProtocolU%d", i);

      lookup_control(p, 1, NULL);

      /* If the protocol identifier can be found... */

      if (tokens[0] != '!')
      {
        have_any = 1;

        /* Compare it to the same number of characters in */
        /* the given URL. If it matches, flag this.       */

        if (!strncmp(tokens, url, strlen(tokens)))
        {
          in_use = i, have_one = 1;

          break;
        }

        /* Otherwise, loop on to the next protocol... */
      }
    }
  }

  /* If we haven't got any available protocols (!) exit */

  if (!have_any) return 0;

  /* Get rid of any existing protocol... */

  if (have_one)
  {
    char * separator = (char *) (((int) url) + strlen(tokens));

    memmove(url, separator, strlen(url) - (((int) separator) - ((int) url)) + 1);
  }

  /* Find the first/next protocol */

  have_any = 0;

  while (!have_any)
  {
    /* If nothing was found in the first loop (the URL doesn't  */
    /* specify a protocol, or it wasn't recognised) then in_use */
    /* starts at 0; we thus increment to 1, which is what we    */
    /* want. So there's no special casing needed here.          */

    in_use ++;

    if (in_use > protocols) in_use = 1;

    /* Again, see if the protocol is available */

    sprintf(p, "ProtocolM%d", in_use);

    if (!_swix(OS_Module,
               _INR(0,1),

               18,
               lookup_control(p, 1, NULL)))
    {
      /* Module is present, so check the protocol */

      sprintf(p, "ProtocolU%d", in_use);

      lookup_control(p, 1, NULL);

      /* If the protocol identifier can be found, flag it */

      if (tokens[0] != '!') have_any = 1;
    }
  }

  /* Insert the new protocol */

  ulen = strlen(url);
  plen = strlen(tokens); /* (The protocol) */

  if (ulen + plen + 1 > size) return have_one; /* Yikes, if it won't fit we may have thrown out an existing protocol... */

  memmove(url + plen, url, ulen + 1);

  strncpy(url, tokens, plen);

  /* Finished */

  return 1;
}

1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
/*************************************************/
/* urlutils_dispatch()                           */
/*                                               */
/* Puts a given URI into the URI queue and sends */
/* it out to the URI handler.                    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             for which the URI relates;        */
/*                                               */
/*             Pointer to null-terminated URI    */
/*             string (not in a movable block,   */
/*             so not, e.g., in a flex block);   */
/*                                               */
/*             URI queue flags (see URIutils.h). */
/*                                               */
/* Assumes:    That the caller has already made  */
/*             sure the URI handler is present.  */
/*************************************************/

_kernel_oserror * urlutils_dispatch(browser_data * b, char * uri, unsigned int flags)
{
  _kernel_oserror * e;
  unsigned int      return_code;
  uri_queue       * entry;

  #ifdef TRACE
    if (tl & (1u<<21)) Printf("urlutils_dispatch: Called for %p with '%s'\n",b,uri);
  #endif

  /* Claim memory for the new entry */

  entry = malloc(sizeof(uri_queue));

  /* Moan if the claim failed */

  if (!entry)
  {
    #ifdef TRACE
      if (tl & (1u<<21)) Printf("urlutils_dispatch: Memory claim for queue entry failed\n",b,uri);
    #endif

1969
    return make_no_fetch_memory_error(15);
1970 1971 1972 1973
  }

  #ifdef TRACE
    malloccount += sizeof(uri_queue);
1974
    if (tl & (1u<<13)) Printf("** malloccount (urlutils_dispatch): \0211%d\0217\n",malloccount);
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 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 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096

    if (tl & (1u<<21)) Printf("urlutils_dispatch: Claimed queue entry %p\n",entry);
  #endif

  /* Fill in part of the entry */

  entry->flags = flags;
  entry->b     = b;

  /* If there are no entries, set uri_queue_base to the */
  /* address of this one. Otherwise, point this entry's */
  /* 'next' to the current base item, and point that    */
  /* item's 'prev' back to this entry. Then replace the */
  /* current base entry with this new one.              */

  entry->prev = NULL;

  if (!uri_queue_base) entry->next = NULL;
  else
  {
    entry->next          = uri_queue_base;
    uri_queue_base->prev = entry;
  }

  uri_queue_base = entry;

  /* Now call the URI handler and get a handle to fill in */
  /* the last uri_queue field.                            */

  e = uri_dispatch(URI_Dispatch_Inform,
                   uri,
                   task_handle,

                   &return_code,
                   NULL,
                   &entry->uri_handle);

  if (e)
  {
    #ifdef TRACE
      if (tl & (1u<<21)) Printf("urlutils_dispatch: Exitting with error\n");
    #endif

    return e;
  }

  /* If the request was refused complain */

  if (return_code != URI_Dispatch_RequestAccepted)
  {
    erb.errnum = Utils_Error_Custom_Message;
    StrNCpy0(erb.errmess,
             lookup_token("Refused:Cannot fetch this address as the fetch request was refused by the internal handler.",
                          0,0));

    #ifdef TRACE
      if (tl & (1u<<21)) Printf("urlutils_dispatch: Exitting with error\n");
    #endif

    return &erb;
  }

  /* Otherwise exit successfully */

  #ifdef TRACE
    if (tl & (1u<<21)) Printf("urlutils_dispatch: Successful\n");
  #endif

  return NULL;
}

/*************************************************/
/* urlutils_remove_from_queue()                  */
/*                                               */
/* Removes a specified entry from the list of    */
/* uri_queue structures, freeing the memory      */
/* allocated for it.                             */
/*                                               */
/* Parameters: The URI handle of the entry.      */
/*************************************************/

_kernel_oserror * urlutils_remove_from_queue(URI_handle_t uri_handle)
{
  uri_queue * entry = uri_queue_base;

  #ifdef TRACE
    if (tl & (1u<<21)) Printf("urlutils_remove_from_queue: Called with handle %p\n", uri_handle);
  #endif

  /* Try to find the entry */

  while (entry && entry->uri_handle != uri_handle) entry = entry->next;

  #ifdef TRACE

    /* Complain if not found */

    if (!entry)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess, "Can't find URI handle %p in URI queue", uri_handle);

      if (tl & (1u<<21)) Printf("urlutils_remove_from_queue: Exitting with error\n");

      return &erb;
    }

  #else

    /* Fail silently */

    if (!entry) return NULL;

  #endif

  if (entry->prev) entry->prev->next = entry->next;
  if (entry->next) entry->next->prev = entry->prev;

  if (entry == uri_queue_base) uri_queue_base = entry->next;

  #ifdef TRACE
    malloccount -= sizeof(uri_queue);
2097
    if (tl & (1u<<13)) Printf("** malloccount (uriutils_remove_from_queue): \0212%d\0217\n",malloccount);
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

    if (tl & (1u<<21)) Printf("urlutils_remove_from_queue: Freeing entry %p\n",entry);
  #endif

  free (entry);

  #ifdef TRACE
    if (tl & (1u<<21)) Printf("urlutils_remove_from_queue: Successful\n");
  #endif

  return NULL;
}

/*************************************************/
/* urlutils_find_queue_entry()                   */
/*                                               */
/* Finds an entry in the list of uri_queue       */
/* structures.                                   */
/*                                               */
/* Parameters: The URI handle of the entry.      */
/*                                               */
/* Returns:    Pointer to the entry, or NULL if  */
/*             no entry with that handle could   */
/*             be found.                         */
/*************************************************/

uri_queue * urlutils_find_queue_entry(URI_handle_t uri_handle)
{
  uri_queue * entry = uri_queue_base;

  #ifdef TRACE
    if (tl & (1u<<21)) Printf("urlutils_find_queue_entry: Called with handle %p\n", uri_handle);
  #endif

  while (entry && entry->uri_handle != uri_handle) entry = entry->next;

  #ifdef TRACE
    if (tl & (1u<<21)) Printf("urlutils_find_queue_entry: Returning with entry %p\n", entry);
  #endif

  return entry;
}