about summary refs log blame commit diff stats
path: root/AUTHORS
blob: 62387efe41c335f2ae2b5129a6ca7a6f416f9c4d (plain) (tree)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
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
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
358
359
360
361
362
363
364
365
366
367
368
369
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




















                                                              
                                                 

                                                                 
                                                                               
















                                                                             

































































































































































































































































































































































































































































































































































































































































































                                                                              
Copyright 2009-2015  Roman Zimbelmann <hut@hut.pm>
Copyright 2010  David Barnett <davidbarnett2@gmail.com>
Copyright 2010  Lucas de Vries <lucas@glacicle.org>
Copyright 2010  Sitaram Chamarty <sitaram@atc.tcs.com>
Copyright 2011-2012  Abdó Roig-Maranges <abdo.roig@gmail.com>
Copyright 2011-2012  M Rawash <mrawash@gmail.com>
Copyright 2011  David Pugnasse <david.pugnasse@gmail.com>
Copyright 2011  ornicar <thibault.duplessis@gmail.com>
Copyright 2012  joe <joebodo@gmail.com>
Copyright 2012  Serge Broslavsky <serge.broslavsky@gmail.com>
Copyright 2013-2014  GermainZ <germanosz@gmail.com>
Copyright 2013  Emanuel Guevel
Copyright 2013  Joseph Tannhuber <sepp.tannhuber@yahoo.de>
Copyright 2014  Célestin Matte <celestin.matte@gmail.com>
Copyright 2014  Milan Svoboda <milan.svoboda@centrum.cz>
Copyright 2014  rukai <rubickent@gmail.com>
Copyright 2015  Alexander Buddenbrock <a.buddenbrock@ish.de>
Copyright 2015  anekos <anekos@snca.net>
Copyright 2015  bastorran
Copyright 2015  Delisa Mason <iskanamagus@gmail.com>
Copyright 2015  No Suck <admin@nosuck.org>
Copyright 2015  Randy Nance <randynobx@gmail.com>
Copyright 2015  Wojciech Siewierski <wojciech.siewierski@onet.pl>

Ideally, all contributors of non-trivial code are named here to the extent that
a name and e-mail address is available.  Please write a mail to hut@hut.pm if
your name is missing, or in case of any other issues.

The authorship and modification date of the individual lines of code can be
determined through querying the version control management software:

    git blame <filename>

Explicitly named authors in a source file are there to help you find a
competent person in case of questions, not necessarily because they are
the exclusive authors of a source file.

This software is distributed under the terms of the GNU General Public
License version 3.  Copyright terms follow.

=======================================================================

                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
' href='#n2043'>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 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 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 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 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 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 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
#include "HTUtils.h"
#include "tcp.h"
#include "HTParse.h"
#include "HTAccess.h"
#include "HTCJK.h"
#include "HTAlert.h"
#include "LYCurses.h"
#include "LYUtils.h"
#include "LYStrings.h"
#include "LYGlobalDefs.h"
#include "LYSignal.h"
#include "GridText.h"

#ifdef VMS
#include <descrip.h>
#include <libclidef.h>
#include <lib$routines.h>
#include "HTVMSUtils.h"
#endif /* VMS */

#ifdef UNIX
#include <pwd.h>
#ifdef UTMPX_FOR_UTMP
#include <utmpx.h>
#define utmp utmpx
#ifdef UTMP_FILE
#undef UTMP_FILE
#endif /* UTMP_FILE */
#define UTMP_FILE UTMPX_FILE
#else
#include <utmp.h>
#endif /* UTMPX_FOR_UTMP */
#endif /* UNIX */

#include "LYLeaks.h"

#ifdef SVR4_BSDSELECT
extern int BSDselect PARAMS((int nfds, fd_set * readfds, fd_set * writefds,
	 		     fd_set * exceptfds, struct timeval * timeout));
#ifdef select
#undef select
#endif /* select */
#define select BSDselect
#ifdef SOCKS
#ifdef Rselect
#undef Rselect
#endif /* Rselect */
#define Rselect BSDselect
#endif /* SOCKS */
#endif /* SVR4_BSDSELECT */

#ifndef FD_SETSIZE
#define FD_SETSIZE 256
#endif /* !FD_SETSIZE */

#ifndef UTMP_FILE
#if defined(__FreeBSD__) || defined(__bsdi__)
#define UTMP_FILE _PATH_UTMP
#else
#define UTMP_FILE "/etc/utmp"
#endif /* __FreeBSD__ || __bsdi__ */
#endif /* !UTMP_FILE */

#define FREE(x) if (x) {free(x); x = NULL;}

extern HTkcode kanji_code;
extern BOOLEAN LYHaveCJKCharacterSet;
extern HTCJKlang HTCJK;

PRIVATE HTList * localhost_aliases = NULL;	/* Hosts to treat as local */
PUBLIC  HTList * sug_filenames = NULL;		/* Suggested filenames   */

/*
 * highlight (or unhighlight) a given link
 */
PUBLIC void highlight ARGS2(int,flag, int,cur)
{
    char buffer[200];
    int i;
    char tmp[3];

    tmp[0] = tmp[1] = tmp[2] = '\0';

    /* Bug in history code can cause -1 to be sent, which will yield
    ** an ACCVIO when LYstrncpy() is called with a nonsense pointer.
    ** This works around the bug, for now. -- FM
    */
    if (cur < 0)
        cur = 0;

    if (nlinks > 0) {
	move(links[cur].ly, links[cur].lx);
	if (flag == ON) { 
	    /* makes some terminals work wrong because
	     * they can't handle two attributes at the 
	     * same time
	     */
	    /* start_bold();  */
	    start_reverse();
#ifdef USE_SLANG
	    start_underline ();
#endif /* USE_SLANG */
	} else {
	    start_bold();
	}

	if (links[cur].type == WWW_FORM_LINK_TYPE) {
	    int len;
	    int avail_space = (LYcols-links[cur].lx)-1;

	    LYstrncpy(buffer,
	    	      links[cur].hightext, 
		      (avail_space > links[cur].form->size ? 
				      links[cur].form->size : avail_space));
	    addstr(buffer);  

	    len = strlen(buffer);
	    for (; len < links[cur].form->size && len < avail_space; len++)
	        addch('_');

	} else {

	    /* copy into the buffer only what will fit within the
	     * width of the screen
	     */
	    LYstrncpy(buffer,links[cur].hightext, LYcols-links[cur].lx-1);
	    addstr(buffer);  
	}

	/* display a second line as well */
	if (links[cur].hightext2 && links[cur].ly < display_lines) {
	    if (flag == ON) {
	        stop_reverse();
#ifdef USE_SLANG
		stop_underline ();
#endif /* USE_SLANG */
	    } else {
	        stop_bold();
	    }

	    addch('\n');
	    for (i=0; i < links[cur].hightext2_offset; i++)
	        addch(' ');

	    if (flag == ON) {
	        start_reverse();
#ifdef USE_SLANG
		start_underline ();
#endif /* USE_SLANG */
	    } else {
	        start_bold();
	    }

	    for (i=0; (tmp[0] = links[cur].hightext2[i]) != '\0' &&
	    	      i+links[cur].hightext2_offset < LYcols; i++) {
		if (!IsSpecialAttrChar(links[cur].hightext2[i])) {
		    /* For CJK strings, by Masanobu Kimura */
		    if (HTCJK != NOCJK && !isascii(tmp[0])) {
		        tmp[1] = links[cur].hightext2[++i];
			addstr(tmp);
			tmp[1] = '\0';
		    } else {
		        addstr(tmp);
		    }
		 }
	    }
	}

	if (flag == ON) {
	    stop_reverse();
#ifdef USE_SLANG
	    stop_underline ();
#endif /* USE_SLANG */
	} else {
	    stop_bold();
	}

#if defined(FANCY_CURSES) || defined(USE_SLANG)
	if (!LYShowCursor)
	    move(LYlines-1, LYcols-1);  /* get cursor out of the way */
	else
#endif /* FANCY CURSES || USE_SLANG */
	    /* never hide the cursor if there's no FANCY CURSES or SLANG */
	    move(links[cur].ly, links[cur].lx - 1);

	if (flag)
	    refresh();
    }
    return;
}

/*
 * free_and_clear will free a pointer if it is non-zero and
 * then set it to zero
 */
PUBLIC void free_and_clear ARGS1(char **,pointer)
{
    if (*pointer) {
	free(*pointer);
        *pointer = 0;
    }
    return;
}

/*
 * Collapse (REMOVE) all spaces in the string. 
 */
PUBLIC void collapse_spaces ARGS1(char *,string)
{
    int i=0;
    int j=0;

    if (!string)
        return;

    for (; string[i] != '\0'; i++) 
	if (!isspace(string[i])) 
	    string[j++] = string[i];

    string[j] = '\0';  /* terminate */
    return;
}

/*
 * Convert single or serial newlines to single spaces throughout a string
 * (ignore newlines if the preceding character is a space) and convert
 * tabs to single spaces (but don't ignore any explicit tabs or spaces).
 */
PUBLIC void convert_to_spaces ARGS1(char *,string)
{
    char *s = string;
    char *ns = string;
    BOOL last_is_space = FALSE;

    if (!string)
        return;

    while (*s) {
	switch (*s) {
	    case ' ':
	    case '\t':
		*(ns++) = ' ';
		last_is_space = TRUE;
		break;

	    case '\r':
	    case '\n':
	        if (!last_is_space) {
		    *(ns++) = ' ';
		    last_is_space = TRUE;
		}
		break;

	    default:
		*(ns++) = *s;
		last_is_space = FALSE;
		break;
	}
	s++;
    }
    *ns = '\0';
    return;
}

/*
 * display (or hide) the status line
 */
BOOLEAN mustshow = FALSE;

PUBLIC void statusline ARGS1(char *,text)
{
    char buffer[256];
    unsigned char *temp = NULL;
    extern BOOLEAN no_statusline;
    int max_length, len, i, j;
    unsigned char k;

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

    /*
     *  Don't print statusline messages if dumping to stdout.
     */
    if (dump_output_immediately)
	return;

    /*
     *  Don't print statusline message if turned off.
     */
    if (mustshow != TRUE) {
	if (no_statusline == TRUE) {
	    return;
	}
    }
    mustshow = FALSE;

    /*
     *  Deal with any CJK escape sequences and Kanji if we have a CJK
     *  character set selected, otherwise, strip any escapes.  Also,
     *  make sure text is not longer than the statusline window. - FM
     */
    max_length = ((LYcols - 2) < 256) ? (LYcols - 2) : 255;
    if ((buffer[0] != '\0') &&
        (LYHaveCJKCharacterSet)) {
        /*
	 *  Translate or filter any escape sequences.
	 */
	if ((temp = (unsigned char *)calloc(1, strlen(text) + 1)) == NULL)
	    outofmem(__FILE__, "statusline");
	if (kanji_code == EUC) {
	    TO_EUC((unsigned char *)text, temp);
	} else if (kanji_code == SJIS) {
	    TO_SJIS((unsigned char *)text, temp);
	} else {
	    for (i = 0, j = 0; text[i]; i++) {
		if (text[i] != '\033') {
		    temp[j++] = text[i];
		}
	    }
	    temp[j] = '\0';
	}

        /*
	 *  Deal with any newlines or tabs in the string.
	 */
	convert_to_spaces((char *)temp);

	/*
	 *  Handle the Kanji, making sure the text is not
	 *  longer than the statusline window. - FM
	 */
	for (i = 0, j = 0, len = 0, k = '\0';
	     temp[i] != '\0' && len < max_length; i++) {
	    if (k != '\0') {
	        buffer[j++] = k;
		buffer[j++] = temp[i];
		k = '\0';
		len += 2;
	    } else if ((temp[i] & 0200) != 0) {
	        k = temp[i];
	    } else {
	        buffer[j++] = temp[i];
		len++;
	    }
	}
	buffer[j] = '\0';
	FREE(temp);
    } else {
        /*
	 *  Strip any escapes, and shorten text if necessary. - FM
	 */
	for (i = 0, len = 0; text[i] != '\0' && len < max_length; i++) {
	    if (text[i] != '\033') {
	        buffer[len++] = text[i];
	    }
	}
	buffer[len] = '\0';
        /*
	 *  Deal with any newlines or tabs in the string.
	 */
	convert_to_spaces(buffer);
    }

    /*
     *  Move to the statusline window and output the text highlighted.
     */
    if (user_mode == NOVICE_MODE)
        move(LYlines-3,0);
    else
        move(LYlines-1,0);
    clrtoeol();
    if (text != NULL) {
	start_reverse();
	addstr(buffer);
	stop_reverse();
    }

    refresh();
    return;
}

static char *novice_lines[] = {
#ifndef	NOVICE_LINE_TWO_A
#define	NOVICE_LINE_TWO_A	NOVICE_LINE_TWO
#define	NOVICE_LINE_TWO_B	""
#define	NOVICE_LINE_TWO_C	""
#endif /* !NOVICE_LINE_TWO_A */
  NOVICE_LINE_TWO_A,
  NOVICE_LINE_TWO_B,
  NOVICE_LINE_TWO_C,
  ""
};
static int lineno = 0;

PUBLIC void toggle_novice_line NOARGS
{
	lineno++;
	if (*novice_lines[lineno] == '\0')
		lineno = 0;
	return;
}

PUBLIC void noviceline ARGS1(int,more)
{

    if (dump_output_immediately)
	return;

    move(LYlines-2,0);
    stop_reverse();
    clrtoeol();
    addstr(NOVICE_LINE_ONE);
    clrtoeol();

#if defined(DIRED_SUPPORT ) && defined(OK_OVERRIDE)
    if (lynx_edit_mode && !no_dired_support) 
       addstr(DIRED_NOVICELINE);
    else
#endif /* DIRED_SUPPORT && OK_OVERRIDE */

    if (LYUseNoviceLineTwo)
        addstr(NOVICE_LINE_TWO);
    else
        addstr(novice_lines[lineno]);

#ifdef NOTDEFINED
    if (is_www_index && more) {
        addstr("This is a searchable index.  Use ");
	addstr(key_for_func(LYK_INDEX_SEARCH));
	addstr(" to search:");
	stop_reverse();
	addstr("                ");
	start_reverse();
        addstr("space for more");

    } else if (is_www_index) {
        addstr("This is a searchable index.  Use ");
	addstr(key_for_func(LYK_INDEX_SEARCH));
	addstr(" to search:");
    } else {
        addstr("Type a command or ? for help:");                   

        if (more) {
	    stop_reverse();
	    addstr("                       ");
	    start_reverse();
            addstr("Press space for next page");
	}
    }

#endif /* NOTDEFINED */

    refresh();
    return;
}

PUBLIC int HTCheckForInterrupt NOARGS
{
#ifndef VMS /* UNIX stuff: */
    int c;
#ifndef USE_SLANG
    struct timeval socket_timeout;
    int ret = 0;
    fd_set readfds;
#endif /* !USE_SLANG */

    /** Curses or slang setup was not invoked **/
    if (dump_output_immediately)
	return((int)FALSE);

#ifdef USE_SLANG
    /** No keystroke was entered
        Note that this isn't taking possible SOCKSification
	and the socks_flag into account, and may fail on the
	slang library's select() when SOCKSified. - FM **/
    if (0 == SLang_input_pending(0))
        return(FALSE);

#else /* Unix curses: */

    socket_timeout.tv_sec = 0;
    socket_timeout.tv_usec = 100;
    FD_ZERO(&readfds);
    FD_SET(0, &readfds);
#ifdef SOCKS
    if (socks_flag)
        ret = Rselect(FD_SETSIZE, (void *)&readfds, NULL, NULL,
	  	      &socket_timeout);
    else
#endif /* SOCKS */
        ret = select(FD_SETSIZE, (void *)&readfds, NULL, NULL,
	  	     &socket_timeout);

    /** No keystroke was entered **/
    if (!FD_ISSET(0,&readfds))
	 return((int)FALSE); 
#endif /* USE_SLANG */

    /** Keyboard 'Z' or 'z', or Control-G or Control-C **/
    c = LYgetch();
    if (TOUPPER(c) == 'Z' || c == 7 || c == 3)
	return((int)TRUE);

    /** Other keystrokes **/
    return((int)FALSE);

#else /* VMS: */

    int c;
    extern BOOLEAN HadVMSInterrupt;
    extern int typeahead();

    /** Curses or slang setup was not invoked **/
    if (dump_output_immediately)
	  return((int)FALSE);

    /** Control-C or Control-Y and a 'N'o reply to exit query **/
    if (HadVMSInterrupt) {
        HadVMSInterrupt = FALSE;
        return((int)TRUE);
    }

    /** Keyboard 'Z' or 'z', or Control-G or Control-C **/
    c = typeahead();
    if (TOUPPER(c) == 'Z' || c == 7 || c == 3)
        return((int)TRUE);

    /** Other or no keystrokes **/
    return((int)FALSE);
#endif /* !VMS */
}

/*
 * A file URL for a remote host is an obsolete ftp URL.
 * Return YES only if we're certain it's a local file. - FM
 */
PUBLIC BOOLEAN LYisLocalFile ARGS1(char *,filename)
{
    char *host=NULL;
    char *access=NULL;
    char *cp;

    if (!filename)
        return NO;
    if (!(host = HTParse(filename, "", PARSE_HOST)))
        return NO;
    if (!*host) {
        FREE(host);
	return NO;
    }

    if ((cp=strchr(host, ':')) != NULL)
        *cp = '\0';

    if ((access = HTParse(filename, "", PARSE_ACCESS))) {
        if (0==strcmp("file", access) &&
	    (0==strcmp(host, "localhost") ||
#ifdef VMS
             0==strcasecomp(host, HTHostName())))
#else
             0==strcmp(host, HTHostName())))
#endif /* VMS */
        {
	    FREE(host);
	    FREE(access);
	    return YES;
	}
    }

    FREE(host);
    FREE(access);
    return NO;
}

/*
 * Utility for checking URLs with a host field.
 * Return YES only if we're certain it's the local host. - FM
 */
PUBLIC BOOLEAN LYisLocalHost ARGS1(char *,filename)
{
    char *host=NULL;
    char *cp;

    if (!filename)
        return NO;
    if (!(host = HTParse(filename, "", PARSE_HOST)))
        return NO;
    if (!*host) {
        FREE(host);
	return NO;
    }

    if ((cp=strchr(host, ':')) != NULL)
        *cp = '\0';

#ifdef VMS
    if ((0==strcasecomp(host, "localhost") ||
	 0==strcasecomp(host, LYHostName) ||
         0==strcasecomp(host, HTHostName()))) {
#else
    if ((0==strcmp(host, "localhost") ||
	 0==strcmp(host, LYHostName) ||
         0==strcmp(host, HTHostName()))) {
#endif /* VMS */
	    FREE(host);
	    return YES;
    }

    FREE(host);
    return NO;
}

/* 
 * Utility for freeing the list of local host aliases. - FM
 */
PUBLIC void LYLocalhostAliases_free NOARGS
{
    char *alias;
    HTList *cur = localhost_aliases;

    if (!cur)
        return;

    while (NULL != (alias = (char *)HTList_nextObject(cur))) {
	FREE(alias);
    }
    HTList_delete(localhost_aliases);
    localhost_aliases = NULL;
    return;
}

/* 
 * Utility for listing hosts to be treated as local aliases. - FM
 */
PUBLIC void LYAddLocalhostAlias ARGS1(char *, alias)
{
    char *LocalAlias;

    if (!(alias && *alias))
        return;

    if (!localhost_aliases) {
        localhost_aliases = HTList_new();
	atexit(LYLocalhostAliases_free);
    }

    if ((LocalAlias = (char *)calloc(1, (strlen(alias) + 1))) == NULL)
    	outofmem(__FILE__, "HTAddLocalhosAlias");
    strcpy(LocalAlias, alias);
    HTList_addObject(localhost_aliases, LocalAlias);

    return;
}

/*
 * Utility for checking URLs with a host field.
 * Return YES only if we've listed the host as a local alias. - FM
 */
PUBLIC BOOLEAN LYisLocalAlias ARGS1(char *,filename)
{
    char *host=NULL;
    char *alias;
    char *cp;
    HTList *cur = localhost_aliases;

    if (!cur || !filename)
        return NO;
    if (!(host = HTParse(filename, "", PARSE_HOST)))
        return NO;
    if (!(*host)) {
        FREE(host);
	return NO;
    }

    if ((cp=strchr(host, ':')) != NULL)
        *cp = '\0';

    while (NULL != (alias = (char *)HTList_nextObject(cur))) {
#ifdef VMS
        if (0==strcasecomp(host, alias)) {
#else
        if (0==strcmp(host, alias)) {
#endif /* VMS */
	    FREE(host);
	    return YES;
	}
    }

    FREE(host);
    return NO;
}

/*
**  This function checks for a URL with an unknown scheme,
**  but for which proxying has been set up, and if so,
**  returns PROXY_URL_TYPE. - FM
**
**  If a colon is present but the string segment which
**  precedes it is not being proxied, and we can rule
**  out that what follows the colon is not a port field,
**  it returns UNKNOWN_URL_TYPE.  Otherwise, it returns
**  0 (not a URL). - FM
*/
PUBLIC int LYCheckForProxyURL ARGS1(char *, filename) {
    char *cp=filename;
    char *cp1;
    char *cp2 = NULL;

    /*
     *  Don't crash on an empty argument.
     */
    if (cp == NULL || *cp == '\0')
        return(0);

    /* kill beginning spaces */
    while (isspace(*cp))
        cp++;

    /*
     * Check for a colon, and if present,
     * see if we have proxying set up.
     */
    if ((cp1=strchr((cp+1), ':')) != NULL) {
	*cp1 = '\0';
	StrAllocCopy(cp2, cp);
	*cp1 = ':';
	StrAllocCat(cp2, "_proxy");
	if (getenv(cp2) != NULL) {
	    FREE(cp2);
	    return(PROXY_URL_TYPE);
	}
	FREE(cp2);
	cp1++;
	if (isdigit(*cp1)) {
	    while (*cp1 && isdigit(*cp1))
	        cp1++;
	    if (*cp1 && *cp1 != '/')
	        return(UNKNOWN_URL_TYPE);
	}
    }

    return(0);
}

/*
**  Must recognize a URL and return the type.
**  If recognized, based on a case-insensitive
**  analyis of the scheme field, ensures that
**  the scheme field has the expected case.
**
**  Returns 0 (not a URL) for a NULL argument,
**  one which lacks a colon.
**
**  Chains to LYCheckForProxyURL() if a colon
**  is present but the type is not recognized.
*/
PUBLIC int is_url ARGS1(char *,filename)
{
    char *cp = filename;
    char *cp1;
    int i;

    /*
     *  Don't crash on an empty argument.
     */
    if (cp == NULL || *cp == '\0')
        return(0);

    /*
     *  Can't be a URL if it lacks a colon.
     */
    if (NULL == strchr(cp, ':'))
        return(0);

    /*
     *  Kill beginning spaces.
     */
    while (isspace(*cp))
        cp++;

    if (!strncasecomp(cp, "news:", 5)) {
        if (strncmp(cp, "news", 4)) {
	    for (i = 0; i < 4; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(NEWS_URL_TYPE);

    } else if (!strncasecomp(cp, "snews:", 6)) {
        if (strncmp(cp, "snews", 5)) {
	    for (i = 0; i < 5; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(SNEWS_URL_TYPE);

    } else if (!strncasecomp(cp, "mailto:", 7)) {
        if (strncmp(cp, "mailto", 6)) {
	    for (i = 0; i < 6; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(MAILTO_URL_TYPE);

    } else if (!strncasecomp(cp, "data:", 5)) {
        if (strncmp(cp, "data", 4)) {
	    for (i = 0; i < 4; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(DATA_URL_TYPE);

    } else if (!strncasecomp(cp, "lynxexec:", 9)) {
	/*
	 *  Special External Lynx type to handle execution
	 *  of commands or scripts which require a pause to
	 *  read the screen upon completion.
	 */
        if (strncmp(cp, "lynxexec", 8)) {
	    for (i = 0; i < 8; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(LYNXEXEC_URL_TYPE);

    } else if (!strncasecomp(cp, "lynxprog:", 9)) {
	/*
	 *  Special External Lynx type to handle execution
	 *  of commans, sriptis or programs with do not
	 *  require a pause to read screen upon completion.
	 */
        if (strncmp(cp, "lynxprog", 8)) {
	    for (i = 0; i < 8; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(LYNXPROG_URL_TYPE);

    } else if (!strncasecomp(cp, "lynxcgi:", 8)) {
	/*
	 *  Special External Lynx type to handle cgi scripts.
	 */
        if (strncmp(cp, "lynxcgi", 7)) {
	    for (i = 0; i < 7; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(LYNXCGI_URL_TYPE);

    } else if (!strncasecomp(cp, "newspost:", 9)) {
	/*
	 *  Special Internal Lynx type to handle news posts.
	 */
        if (strncmp(cp, "newspost", 8)) {
	    for (i = 0; i < 8; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(NEWSPOST_URL_TYPE);

    } else if (!strncasecomp(cp, "newsreply:", 10)) {
	/*
	 *  Special Internal Lynx type to handle news replies (followups).
	 */
        if (strncmp(cp, "newsreply", 9)) {
	    for (i = 0; i < 9; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(NEWSREPLY_URL_TYPE);

    } else if (!strncasecomp(cp, "LYNXPRINT:", 10)) {
	/*
	 *  Special Internal Lynx type.
	 */
        if (strncmp(cp, "LYNXPRINT", 9)) {
	    for (i = 0; i < 9; i++)
	        cp[i] = TOUPPER(cp[i]);
	}
	return(LYNXPRINT_URL_TYPE);

    } else if (!strncasecomp(cp, "LYNXDOWNLOAD:", 13)) {
	/*
	 *  Special Internal Lynx type.
	 */
        if (strncmp(cp, "LYDOWNLOAD", 12)) {
	    for (i = 0; i < 12; i++)
	        cp[i] = TOUPPER(cp[i]);
	}
	return(LYNXDOWNLOAD_URL_TYPE);

    } else if (!strncasecomp(cp, "LYNXDIRED:", 10)) {
	/*
	 *  Special Internal Lynx type.
	 */
        if (strncmp(cp, "LYNXDIRED", 9)) {
	    for (i = 0; i < 9; i++)
	        cp[i] = TOUPPER(cp[i]);
	}
	return(LYNXDIRED_URL_TYPE);

    } else if (!strncasecomp(cp, "LYNXHIST:", 9)) {
	/*
	 *  Special Internal Lynx type.
	 */
        if (strncmp(cp, "LYNXHIST", 8)) {
	    for (i = 0; i < 8; i++)
	        cp[i] = TOUPPER(cp[i]);
	}
	return(LYNXHIST_URL_TYPE);

    } else if (!strncasecomp(cp, "LYNXKEYMAP:", 11)) {
	/*
	 *  Special Internal Lynx type.
	 */
        if (strncmp(cp, "LYNXKEYMAP", 10)) {
	    for (i = 0; i < 10; i++)
	        cp[i] = TOUPPER(cp[i]);
	}
	return(LYNXKEYMAP_URL_TYPE);

    } else if (!strncasecomp(cp, "LYNXIMGMAP:", 11)) {
	/*
	 *  Special Internal Lynx type.
	 */
        if (strncmp(cp, "LYNXIMGMAP", 10)) {
	    for (i = 0; i < 10; i++)
	        cp[i] = TOUPPER(cp[i]);
	}
	return(LYNXIMGMAP_URL_TYPE);

    } else if (strstr((cp+3), ":/") == NULL) {  
	/*
	 *  If it doesn't contain ":/", and it's not one of the
	 *  the above, it can't be a URL with a scheme we know,
	 *  so check if it's an unknown scheme for which proxying
	 *  has been set up. - FM
	 */
	return(LYCheckForProxyURL(filename));

    } else if (!strncasecomp(cp, "https:", 6)) {
        if (strncmp(cp, "https", 5)) {
	    for (i = 0; i < 5; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(HTTPS_URL_TYPE);

    } else if (!strncasecomp(cp, "http:", 5)) {
        if (strncmp(cp, "http", 4)) {
	    for (i = 0; i < 4; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(HTTP_URL_TYPE);

    } else if (!strncasecomp(cp, "file:", 5)) {
        if (strncmp(cp, "file", 4)) {
	    for (i = 0; i < 4; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
        /*
	 *  We won't expend the overhead here of
	 *  determining whether it's really an
	 *  ftp URL unless we are restricting
	 *  ftp access, in which case getfile()
	 *  needs to know in order to issue an
	 *  appropriate statusline message and
	 *  and return NULLFILE.
	 */
        if ((ftp_ok) || LYisLocalFile(cp))
	    return(FILE_URL_TYPE);
	else
	    return(FTP_URL_TYPE);

    } else if (!strncasecomp(cp, "gopher:", 7)) {
        if (strncmp(cp, "gopher", 6)) {
	    for (i = 0; i < 6; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	if ((cp1 = strchr(cp+11,'/')) != NULL) {

	    if (TOUPPER(*(cp1+1)) == 'H' || *(cp1+1) == 'w')
		/* if this is a gopher html type */
	        return(HTML_GOPHER_URL_TYPE);
	    else if (*(cp1+1) == 'T' || *(cp1+1) == '8')
	        return(TELNET_GOPHER_URL_TYPE);
	    else if (*(cp1+1) == '7')
	        return(INDEX_GOPHER_URL_TYPE);
	    else
	        return(GOPHER_URL_TYPE);
	} else {
	    return(GOPHER_URL_TYPE);
	}

    } else if (!strncasecomp(cp, "ftp:", 4)) {
        if (strncmp(cp, "ftp", 3)) {
	    for (i = 0; i < 3; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(FTP_URL_TYPE);

    } else if (!strncasecomp(cp, "wais:", 5)) {
        if (strncmp(cp, "wais", 4)) {
	    for (i = 0; i < 4; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(WAIS_URL_TYPE);

    } else if (!strncasecomp(cp, "telnet:", 7)) {
        if (strncmp(cp, "telnet", 6)) {
	    for (i = 0; i < 6; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(TELNET_URL_TYPE);

    } else if (!strncasecomp(cp, "tn3270:", 7)) {
        if (strncmp(cp, "tn", 2)) {
	    for (i = 0; i < 2; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(TN3270_URL_TYPE);

    } else if (!strncasecomp(cp, "rlogin:", 7)) {
        if (strncmp(cp, "rlogin", 6)) {
	    for (i = 0; i < 6; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(RLOGIN_URL_TYPE);

    } else if (!strncasecomp(cp, "nntp:", 5)) {
        if (strncmp(cp, "nntp", 4)) {
	    for (i = 0; i < 4; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(NNTP_URL_TYPE);

    } else if (!strncasecomp(cp, "cso:", 4)) {
        if (strncmp(cp, "cso", 3)) {
	    for (i = 0; i < 3; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(CSO_URL_TYPE);

    } else if (!strncasecomp(cp, "finger:", 7)) {
        if (strncmp(cp, "finger", 6)) {
	    for (i = 0; i < 6; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(FINGER_URL_TYPE);

    } else if (!strncasecomp(cp, "afs:", 4)) {
        if (strncmp(cp, "afs", 3)) {
	    for (i = 0; i < 3; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(AFS_URL_TYPE);

    } else if (!strncasecomp(cp, "prospero:", 9)) {
        if (strncmp(cp, "prospero", 8)) {
	    for (i = 0; i < 8; i++)
	        cp[i] = TOLOWER(cp[i]);
	}
	return(PROSPERO_URL_TYPE);

    } else {
        /*
	 *  Check if it's an unknown scheme for which
	 *  proxying has been set up. - FM
	 */
	return(LYCheckForProxyURL(filename));
    }
}

/*
 *  Remove backslashes from any string.
 */
PUBLIC void remove_backslashes ARGS1(char *,buf)
{
    char *cp;

    for (cp = buf; *cp != '\0' ; cp++) {

	if (*cp != '\\') { /* don't print slashes */
	    *buf = *cp;
	    buf++;
	} else if (*cp == '\\' &&      /* print one slash if there */
		   *(cp+1) == '\\') {  /* are two in a row         */
	    *buf = *cp;
	    buf++;
	}
    }
    *buf = '\0';
    return;
}

/*
 *  Quote the path to make it safe for shell command processing.
 *
 *  We use a simple technique which involves quoting the entire
 *  string using single quotes, escaping the real single quotes
 *  with double quotes. This may be gross but it seems to work.
 */
PUBLIC char * quote_pathname ARGS1(char *, pathname)
{
    int i, n = 0;
    char * result;

    for (i=0; i < strlen(pathname); ++i)
        if (pathname[i] == '\'') ++n;

    result = (char *)malloc(strlen(pathname) + 5*n + 3);
    if (result == NULL)
        outofmem(__FILE__, "quote_pathname");

    result[0] = '\'';
    for (i = 0, n = 1; i < strlen(pathname); i++)
        if (pathname[i] == '\'') {
            result[n++] = '\'';
            result[n++] = '"';
            result[n++] = '\'';
            result[n++] = '"';
            result[n++] = '\'';
        } else {
            result[n++] = pathname[i];
	}
    result[n++] = '\'';
    result[n] = '\0';
    return result;
}

/*
 * checks to see if the current process is attached via a terminal in the
 * local domain
 *
 */
#ifdef VMS
#ifndef NO_UTMP
#define NO_UTMP
#endif /* NO_UTMP */
#endif /* VMS */

PUBLIC BOOLEAN inlocaldomain NOARGS
{
#ifdef NO_UTMP
    return(TRUE);
#else
    int n;
    FILE *fp;
    struct utmp me;
    char *cp, *mytty=NULL;
    char *ttyname();

    if ((cp=ttyname(0)))
	mytty = strrchr(cp, '/');

    if (mytty && (fp=fopen(UTMP_FILE, "r")) != NULL) {
	    mytty++;
	    do {
		n = fread((char *) &me, sizeof(struct utmp), 1, fp);
	    } while (n>0 && !STREQ(me.ut_line,mytty));
	    (void) fclose(fp);

	    if (n > 0 &&
	        strlen(me.ut_host) > strlen(LYLocalDomain) &&
	        STREQ(LYLocalDomain,
		  me.ut_host+strlen(me.ut_host)-strlen(LYLocalDomain)) )
		return(TRUE);
#ifdef LINUX
/* Linux fix to check for local user. J.Cullen 11Jul94          */
		if ((n > 0) && (strlen(me.ut_host) == 0))
			return(TRUE);
#endif /* LINUX */

    } else {
	if (TRACE)
	   fprintf(stderr,"Could not get ttyname or open UTMP file");
    }

    return(FALSE);
#endif /* NO_UTMP */
}

/**************
** This bit of code catches window size change signals
**/

#if defined(VMS) || defined(SNAKE)
#define NO_SIZECHANGE
#endif /* VMS || SNAKE */

#if !defined(VMS) && !defined(ISC)
#include <sys/ioctl.h>
#endif /* !VMS && !ISC */

#ifdef HAVE_TERMIOS_H
#include <termios.h>
#else
#ifdef HAVE_TERMIO_H
#include <termio.h>
#endif /* HAVE_TERMIO_H */
#endif /* HAVE_TERMIOS_H */

PUBLIC void size_change ARGS1(int,sig)
{
#ifndef NO_SIZECHANGE
#ifdef TIOCGSIZE
    struct ttysize win;
#else
#ifdef TIOCGWINSZ
    struct winsize win;
#endif /* TIOCGWINSZ */
#endif /* TIOCGSIZE */

#ifdef TIOCGSIZE
    if (ioctl(0, TIOCGSIZE, &win) == 0) {
        if (win.ts_lines != 0) {
#ifdef USE_SLANG
	    LYlines = win.ts_lines;
#else
	    LYlines = win.ts_lines - 1;
#endif /* USE_SLANG */
	}
	if (win.ts_cols != 0) {
	    LYcols = win.ts_cols;
	}
    }
#else
#ifdef TIOCGWINSZ
    if (ioctl(0, TIOCGWINSZ, &win) == 0) {
        if (win.ws_row != 0) {
#ifdef USE_SLANG
	    LYlines = win.ws_row;
#else
	    LYlines = win.ws_row - 1;
#endif /* USE_SLANG */
	}
	if (win.ws_col != 0) {
	    LYcols = win.ws_col;
	}
    }
#endif /* TIOCGWINSZ */
#endif /* TIOCGSIZE */
#endif /* !NO_SIZECHANGE */

    if (LYlines <= 0)
        LYlines = 24;
    if (LYcols <= 0)
        LYcols = 80;

#ifdef USE_SLANG
    SLtt_Screen_Rows = LYlines; 
    SLtt_Screen_Cols = LYcols;
    if (sig == 0)
        return;	/* called from start_curses */
#endif /* USE_SLANG */

    recent_sizechange = TRUE; 
#ifdef SIGWINCH
    (void)signal (SIGWINCH, size_change);
#endif /* SIGWINCH */

    return;
}

/* 
 * Utility for freeing the list of previous suggested filenames. - FM
 */
PUBLIC void HTSugFilenames_free NOARGS
{
    char *fname;
    HTList *cur = sug_filenames;

    if (!cur)
        return;

    while (NULL != (fname = (char *)HTList_nextObject(cur))) {
	FREE(fname);
    }
    HTList_delete(sug_filenames);
    sug_filenames = NULL;
    return;
}

/* 
 *  Utility for listing suggested filenames, making any
 *  repeated filenanmes the most current in the list. - FM
 */
PUBLIC void HTAddSugFilename ARGS1(char *, fname)
{
    char *new;
    char *old;
    HTList *cur;

    if (!(fname && *fname))
        return;

    if ((new = (char *)calloc(1, (strlen(fname) + 1))) == NULL)
    	outofmem(__FILE__, "HTAddSugFilename");
    strcpy(new, fname);

    if (!sug_filenames) {
        sug_filenames = HTList_new();
	atexit(HTSugFilenames_free);
	HTList_addObject(sug_filenames, new);
	return;
    }

    cur = sug_filenames;
    while (NULL != (old = (char *)HTList_nextObject(cur))) {
	if (!strcmp(old, new)) {
	    HTList_removeObject(sug_filenames, old);
	    FREE(old);
	    break;
	}
    }
    HTList_addObject(sug_filenames, new);

    return;
}

/*
 *  CHANGE_SUG_FILENAME -- Foteos Macrides 29-Dec-1993
 *	Upgraded for use with Lynx2.2 - FM 17-Jan-1994
 */
PUBLIC void change_sug_filename ARGS1(char *,fname)
{
     char *temp, *cp, *cp1, *end;
     int len;
#ifdef VMS
     char *dot;
     int j,k;
#endif /* VMS */

     /*** establish the current end of fname ***/
     end = fname + strlen(fname);

     /*** unescape fname ***/
     HTUnEscape(fname);

     /*** rename any temporary files ***/
     temp = (char *)calloc(1, (strlen(lynx_temp_space) + 60));
     if (*lynx_temp_space == '/')
         sprintf(temp, "file://localhost%sL%d", lynx_temp_space, getpid());
     else
         sprintf(temp, "file://localhost/%sL%d", lynx_temp_space, getpid());
     len = strlen(temp);
     if (0==strncmp(fname, temp, len)) {
         cp = strrchr(fname, '.');
	 if (strlen(cp) > (len - 4))
	     cp = NULL;
	 strcpy(temp, (cp ? cp : ""));
	 strcpy(fname, "temp");
	 strcat(fname, temp);
     }
     FREE(temp);

     /*** remove everything up the the last_slash if there is one ***/
     if ((cp = strrchr(fname,'/')) != NULL && strlen(cp) > 1) {
	 cp1=fname;
	 cp++; /* go past the slash */
	 for (; *cp != '\0'; cp++, cp1++)
	    *cp1 = *cp;

	 *cp1 = '\0'; /* terminate */
     }

     /*** Trim off date-size suffix, if present ***/
     if ((*(end - 1) == ']') && ((cp = strrchr(fname, '[')) != NULL) &&
         (cp > fname) && *(--cp) == ' ')
	  while (*cp == ' ')
	       *(cp--) = '\0';

     /*** Trim off VMS device and/or directory specs, if present ***/
     if ((cp=strchr(fname,'[')) != NULL &&
         (cp1=strrchr(cp,']')) != NULL && strlen(cp1) > 1) {
	  cp1++;
	  for (cp=fname; *cp1 != '\0'; cp1++)
	       *(cp++) = *cp1;
	  *cp = '\0';
     }

#ifdef VMS
     /*** Replace illegal or problem characters ***/
     dot = fname + strlen(fname);
     for (cp = fname; cp < dot; cp++) {

	  /** Replace with underscores **/
	  if (*cp == ' ' || *cp == '/' || *cp == ':' ||
	      *cp == '[' || *cp == ']' || *cp == '&')
	       *cp = '_';

	  /** Replace with dashes **/
	  else if (*cp == '!' || *cp == '?' || *cp == '\'' || 
	           *cp == ',' || *cp == ':' || *cp == '\"' ||
	           *cp == '+' || *cp == '@' || *cp == '\\' ||
	           *cp == '(' || *cp == ')' || *cp == '=' ||
	           *cp == '<' || *cp == '>' || *cp == '#' ||
	           *cp == '%' || *cp == '*' || *cp == '`' ||
	           *cp == '~' || *cp == '^' || *cp == '|' ||
		   *cp <  ' ' || ((unsigned char)*cp) > 126)
	       *cp = '-';
     }

     /** Collapse any serial underscores **/
     cp = fname + 1;
     j = 0;
     while (cp < dot) {
	  if (fname[j] == '_' && *cp == '_')
	       cp++;
	  else
	       fname[++j] = *cp++;
     }
     fname[++j] = '\0';

     /** Collapse any serial dashes **/
     dot = fname + (strlen(fname));
     cp = fname + 1;
     j = 0;
     while (cp < dot) {
          if (fname[j] == '-' && *cp == '-')
	       cp++;
	  else
	       fname[++j] = *cp++;
     }
     fname[++j] = '\0';

     /** Trim any trailing or leading **/
     /** underscrores or dashes       **/
     cp = fname + (strlen(fname)) - 1;
     while (*cp == '_' || *cp == '-')
          *cp-- = '\0';
     if (fname[0] == '_' || fname[0] == '-') {
          dot = fname + (strlen(fname));
          cp = fname;
          while ((*cp == '_' || *cp == '-') && cp < dot)
	       cp++;
	  j = 0;
          while (cp < dot)
	       fname[j++] = *cp++;
	  fname[j] = '\0';
     }

     /** Replace all but the last period with _'s, or second **/
     /** to last if last is followed by a terminal Z or z,   **/
     /** or GZ or gz,					     **/
     /** e.g., convert foo.tar.Z to                          **/
     /**               foo.tar_Z                             **/
     /**   or, convert foo.tar.gz to                         **/
     /**               foo.tar-gz                            **/
     j = strlen(fname) - 1;
     if ((dot = strrchr(fname, '.')) != NULL) {
	  if (TOUPPER(fname[j]) == 'Z') {
	      if ((fname[j-1] == '.') &&
	          (((cp = strchr(fname, '.')) != NULL) && cp < dot)) {
		  *dot = '_';
		  dot = strrchr(fname, '.');
	      } else if (((TOUPPER(fname[j-1]) == 'G') &&
	      		  fname[j-2] == '.') &&
			 (((cp = strchr(fname, '.')) != NULL) && cp < dot)) {
		  *dot = '-';
		  dot = strrchr(fname, '.');
	      }
	  }
	  cp = fname;
	  while ((cp = strchr(cp, '.')) != NULL && cp < dot)
	       *cp = '_';

          /** But if the root is > 39 characters, move **/
          /** the period appropriately to the left     **/
	  while (dot - fname > 39) {
	       *dot = '\0';
	       if ((cp = strrchr(fname, '_')) != NULL) {
		    *cp  = '.';
		    *dot = '_';
	       } 
	       else if ((cp = strrchr(fname, '-')) != NULL) {
		    *cp  = '.';
		    *dot = '_';
	       }
	       else {
		    *dot = '_';
		    j = strlen(fname);
		    fname[j+1] = '\0';
		    while (j > 39)
			 fname[j--] = fname[j];
		    fname[j] = '.';
	       }
               dot = strrchr(fname, '.');
	  }

          /** Make sure the extension is < 40 characters **/
          if ((fname + strlen(fname) - dot) > 39)
	       *(dot+40) = '\0';

	  /** Trim trailing dashes or underscores **/
	  j = strlen(fname) - 1;
	  while (fname[j] == '_' || fname[j] == '-')
	       fname[j--] = '\0';
     }
     else {
	  /** No period, so put one on the end, or after   **/
	  /** the 39th character, trimming trailing dashes **/
	  /** or underscrores                              **/
	  if (strlen(fname) > 39)
	       fname[39] = '\0';
	  j = strlen(fname) - 1;
	  while ((fname[j] == '_') || (fname[j] == '-'))
	       j--;
	  fname[++j] = '.';
	  fname[++j] = '\0';
     }

#else /* Not VMS (UNIX): */

     /*** Replace problem characters ***/
     for (cp = fname; *cp != '\0'; cp++) {
	  switch (*cp) {
	  case '\'':
	  case '\"':
	  case '/':
	  case ' ':
	       *cp = '-';
	  }
     }
#endif /* VMS (UNIX) */

     /** Make sure the rest of the original string in nulled. **/
     cp = fname + strlen(fname);
     while (cp < end)
          *cp++ = '\0';

    return;
}

/*
 *	To create standard temporary file names
 */
PUBLIC void tempname ARGS2(char *,namebuffer, int,action)
{
	static int counter = 0;


	if (action == REMOVE_FILES) { /* REMOVE ALL FILES */ 
	    for (; counter > 0; counter--) {
	        sprintf(namebuffer, "%sL%d%uTMP.txt", lynx_temp_space,
						      getpid(), counter-1);
		remove(namebuffer);
	        sprintf(namebuffer, "%sL%d%uTMP.html", lynx_temp_space,
						       getpid(), counter-1);
		remove(namebuffer);
	    }
	} else /* add a file */ {
	/*
	 * 	Create name
	 */
	    sprintf(namebuffer, "%sL%d%uTMP.html", lynx_temp_space,
	    					   getpid(), counter++);
	}
	return;
}

/*
 *  Convert 4, 6, 2, 8 to left, right, down, up, etc.
 */
PUBLIC int number2arrows ARGS1(int,number)
{
      switch(number) {
            case '1':
                number=END;
                  break;
            case '2':
                number=DNARROW;
                  break;
            case '3':
                number=PGDOWN;
                  break;
            case '4':
                number=LTARROW;
                  break;
	    case '5':
		number=DO_NOTHING;
		break;
            case '6':
                number=RTARROW;
                  break;
            case '7':
                number=HOME;
                  break;
 	    case '8':
                number=UPARROW;
                  break;
            case '9':
                number=PGUP;
                  break;
      }

      return(number);
}

/*
 * parse_restrictions takes a string of comma-separated restrictions
 * and sets the corresponding flags to restrict the facilities available
 */
PRIVATE char *restrict_name[] = {
       "inside_telnet" ,
       "outside_telnet",
       "telnet_port"   ,
       "inside_ftp"    ,
       "outside_ftp"   ,
       "inside_rlogin" ,
       "outside_rlogin",
       "suspend"       ,
       "editor"        ,
       "shell"         ,
       "bookmark"      ,
       "multibook"     ,
       "bookmark_exec" ,
       "option_save"   ,
       "print"         ,
       "download"      ,
       "disk_save"     ,
       "exec"          ,
       "lynxcgi"       ,
       "exec_frozen"   ,
       "goto"          ,
       "jump"          ,
       "file_url"      ,
       "news_post"     ,
       "inside_news"   ,
       "outside_news"  ,
       "mail"          ,
       "dotfiles"      ,
       "useragent"     ,
#ifdef DIRED_SUPPORT
       "dired_support" ,
#ifdef OK_PERMIT
       "change_exec_perms",
#endif /* OK_PERMIT */
#endif /* DIRED_SUPPORT */
       (char *) 0     };

	/* restrict_name and restrict_flag structure order
	 * must be maintained exactly!
	 */

PRIVATE BOOLEAN *restrict_flag[] = {
       &no_inside_telnet,
       &no_outside_telnet,
       &no_telnet_port,
       &no_inside_ftp,
       &no_outside_ftp,
       &no_inside_rlogin,
       &no_outside_rlogin,
       &no_suspend  ,
       &no_editor   ,
       &no_shell    ,
       &no_bookmark ,
       &no_multibook ,
       &no_bookmark_exec,
       &no_option_save,
       &no_print    ,
       &no_download ,
       &no_disk_save,
       &no_exec     ,
       &no_lynxcgi  ,
       &exec_frozen ,
       &no_goto     ,
       &no_jump     ,
       &no_file_url ,
       &no_newspost ,
       &no_inside_news,
       &no_outside_news,
       &no_mail     ,
       &no_dotfiles ,
       &no_useragent ,
#ifdef DIRED_SUPPORT
       &no_dired_support,
#ifdef OK_PERMIT
       &no_change_exec_perms,
#endif /* OK_PERMIT */
#endif /* DIRED_SUPPORT */
       (BOOLEAN *) 0  };

PUBLIC void parse_restrictions ARGS1(char *,s)
{
      char *p;
      char *word;
      int i;

      if (STREQ("all", s)) {
	   /* set all restrictions */
          for (i=0; restrict_flag[i]; i++) 
              *restrict_flag[i] = TRUE;
          return;
      }

      if (STREQ("default", s)) {
	   /* set all restrictions */
          for (i=0; restrict_flag[i]; i++) 
              *restrict_flag[i] = TRUE;

	     /* reset these to defaults */
             no_inside_telnet = !(CAN_ANONYMOUS_INSIDE_DOMAIN_TELNET);
            no_outside_telnet = !(CAN_ANONYMOUS_OUTSIDE_DOMAIN_TELNET);
	       no_inside_news = !(CAN_ANONYMOUS_INSIDE_DOMAIN_READ_NEWS);
	      no_outside_news = !(CAN_ANONYMOUS_OUTSIDE_DOMAIN_READ_NEWS);
                no_inside_ftp = !(CAN_ANONYMOUS_INSIDE_DOMAIN_FTP);
               no_outside_ftp = !(CAN_ANONYMOUS_OUTSIDE_DOMAIN_FTP);
             no_inside_rlogin = !(CAN_ANONYMOUS_INSIDE_DOMAIN_RLOGIN);
            no_outside_rlogin = !(CAN_ANONYMOUS_OUTSIDE_DOMAIN_RLOGIN);
		      no_goto = !(CAN_ANONYMOUS_GOTO);
		  no_goto_cso = !(CAN_ANONYMOUS_GOTO_CSO);
		 no_goto_file = !(CAN_ANONYMOUS_GOTO_FILE);
	       no_goto_finger = !(CAN_ANONYMOUS_GOTO_FINGER);
		  no_goto_ftp = !(CAN_ANONYMOUS_GOTO_FTP);
	       no_goto_gopher = !(CAN_ANONYMOUS_GOTO_GOPHER);
		 no_goto_http = !(CAN_ANONYMOUS_GOTO_HTTP);
		no_goto_https = !(CAN_ANONYMOUS_GOTO_HTTPS);
	      no_goto_lynxcgi = !(CAN_ANONYMOUS_GOTO_LYNXCGI);
	     no_goto_lynxexec = !(CAN_ANONYMOUS_GOTO_LYNXEXEC);
	     no_goto_lynxprog = !(CAN_ANONYMOUS_GOTO_LYNXPROG);
	       no_goto_mailto = !(CAN_ANONYMOUS_GOTO_MAILTO);
		 no_goto_news = !(CAN_ANONYMOUS_GOTO_NEWS);
		 no_goto_nntp = !(CAN_ANONYMOUS_GOTO_NNTP);
	       no_goto_rlogin = !(CAN_ANONYMOUS_GOTO_RLOGIN);
		no_goto_snews = !(CAN_ANONYMOUS_GOTO_SNEWS);
	       no_goto_telnet = !(CAN_ANONYMOUS_GOTO_TELNET);
	       no_goto_tn3270 = !(CAN_ANONYMOUS_GOTO_TN3270);
		 no_goto_wais = !(CAN_ANONYMOUS_GOTO_WAIS);
	       no_telnet_port = !(CAN_ANONYMOUS_GOTO_TELNET_PORT);
		      no_jump = !(CAN_ANONYMOUS_JUMP);
                      no_mail = !(CAN_ANONYMOUS_MAIL);
                     no_print = !(CAN_ANONYMOUS_PRINT);
#if defined(EXEC_LINKS) || defined(EXEC_SCRIPTS)
		      no_exec = LOCAL_EXECUTION_LINKS_ALWAYS_OFF_FOR_ANONYMOUS;
#endif /* EXEC_LINKS || EXEC_SCRIPTS */
          return;
      }

      p = s;
      while (*p) {
          while (isspace(*p))
              p++;
          if (*p == '\0')
              break;
          word = p;
          while (*p != ',' && *p != '\0')
              p++;
          if (*p)
              *p++ = '\0';

	  for (i=0; restrict_name[i]; i++) 
             if (STREQ(word, restrict_name[i])) {
                 *restrict_flag[i] = TRUE;
		 break;
	     }
      }
      return;
}

#ifdef VMS
#include <jpidef.h>
#include <maildef.h>
#include <starlet.h>

typedef struct _VMSMailItemList
{
  short buffer_length;
  short item_code;
  void *buffer_address;
  long *return_length_address;
} VMSMailItemList;

PUBLIC int LYCheckMail NOARGS
{
    static BOOL firsttime = TRUE, failure = FALSE;
    static char user[13], dir[252];
    static long userlen = 0, dirlen;
    static time_t lastcheck = 0;
    time_t now;
    static short new, lastcount;
    long ucontext = 0, status;
    short flags = MAIL$M_NEWMSG;
    VMSMailItemList
      null_list[] = {{0,0,0,0}},
      jpi_list[]  = {{sizeof(user) - 1,JPI$_USERNAME,(void *)user,&userlen},
		     {0,0,0,0}},
      uilist[]    = {{0,MAIL$_USER_USERNAME,0,0},
    		     {0,0,0,0}},
      uolist[]    = {{sizeof(new),MAIL$_USER_NEW_MESSAGES,&new,0},
                     {sizeof(dir),MAIL$_USER_FULL_DIRECTORY,dir,&dirlen},
                     {0,0,0,0}};
    extern long mail$user_begin();
    extern long mail$user_get_info(); 
    extern long mail$user_end();

    if (failure)
        return 0;

    if (firsttime) {
        firsttime = FALSE;
        /* Get the username. */
        status = sys$getjpiw(0,0,0,jpi_list,0,0,0);
        if (!(status & 1)) {
            failure = TRUE;
            return 0;
        }
        user[userlen] = '\0';
        while (user[0] &&
	       isspace(user[--userlen])) /* suck up trailing spaces */
            user[userlen] = '\0';
    }

    /* Minimum report interval is 60 sec. */
    time(&now);
    if (now - lastcheck < 60)
	return 0;
    lastcheck = now;

    /* Get the current newmail count. */
    status = mail$user_begin(&ucontext,null_list,null_list);
    if (!(status & 1)) {
        failure = TRUE;
        return 0;
    }
    uilist[0].buffer_length = strlen(user);
    uilist[0].buffer_address = user;
    status = mail$user_get_info(&ucontext,uilist,uolist);
    if (!(status & 1)) {
        failure = TRUE;
        return 0;
    }

    /* Should we report anything to the user? */
    if (new > 0) {
	if (lastcount == 0)
	    /* Have newmail at startup of Lynx. */
	    _statusline(HAVE_UNREAD_MAIL_MSG);
	else if (new > lastcount)
	    /* Have additional mail since last report. */
	    _statusline(HAVE_NEW_MAIL_MSG);
        lastcount = new;
	return 1;
    }
    lastcount = new;

    /* Clear the context */
    mail$user_end((long *)&ucontext,null_list,null_list);
    return 0;
}
#else
PUBLIC int LYCheckMail NOARGS
{
    static BOOL firsttime = TRUE;
    static char *mf;
    static time_t lastcheck;
    static long lastsize;
    time_t now;
    struct stat st;

    if (firsttime) {
	mf = getenv("MAIL");
	firsttime = FALSE;
    }

    if (mf == NULL)
	return 0;

    time(&now);
    if (now - lastcheck < 60)
	return 0;
    lastcheck = now;

    if (stat(mf,&st) < 0) {
	mf = NULL;
	return 0;
    }

    if (st.st_size > 0) {
	if (st.st_mtime > st.st_atime ||
	    (lastsize && st.st_size > lastsize))
	    _statusline(HAVE_NEW_MAIL_MSG);
	else if (lastsize == 0)
	    _statusline(HAVE_MAIL_MSG);
        lastsize = st.st_size;
	return 1;
    }
    lastsize = st.st_size;
    return 0;
}
#endif /* VMS */

/*
 *  Rewrite and reallocate a previously allocated string
 *  as a file URL if the string resolves to a file or
 *  directory on the local system, otherwise as an
 *  http URL. - FM
 */
PUBLIC void LYConvertToURL ARGS1(char **, AllocatedString)
{
    char *old_string = *AllocatedString;

    if (!old_string || *old_string == '\0')
        return;

    *AllocatedString = NULL;  /* so StrAllocCopy doesn't free it */
    StrAllocCopy(*AllocatedString,"file://localhost");

    if (*old_string != '/') {
#ifdef VMS
	/*
	 *  Not a SHELL pathspec.  Get the full VMS spec and convert it.
	 */
	char *cp, *cur_dir=NULL;
	static char url_file[256], file_name[256], dir_name[256];
	unsigned long context = 0;
	$DESCRIPTOR(url_file_dsc, url_file);
	$DESCRIPTOR(file_name_dsc, file_name);
	if (*old_string == '~') {
	    /*
	     *  On VMS, we'll accept '~' on the command line as
	     *  $HOME, and assume the rest of the path, if any,
	     *  has SHELL syntax.
	     */
	    StrAllocCat(*AllocatedString, HTVMS_wwwName(getenv("HOME")));
	    if (old_string[1])
		StrAllocCat(*AllocatedString, (old_string+1));
	    goto have_VMS_URL;
	} else {
	    strcpy(url_file, old_string);
	}
	url_file_dsc.dsc$w_length = (short) strlen(url_file);
	if (1&lib$find_file(&url_file_dsc, &file_name_dsc, &context,
    			    0, 0, 0, 0)) {
	    /*
	     *  We found the file.  Convert to a URL pathspec.
	     */
	    if ((cp=strchr(file_name, ';')) != NULL) {
		*cp = '\0';
	    }
	    for (cp = file_name; *cp; cp++) {
		*cp = TOLOWER(*cp);
	    }
	    StrAllocCat(*AllocatedString, HTVMS_wwwName(file_name));
	    if ((cp=strchr(old_string, ';')) != NULL) {
		StrAllocCat(*AllocatedString, cp);
	    }
	} else if ((NULL != getcwd(dir_name, 255, 0)) &&
		   0 == chdir(old_string)) {
	    /*
	     * Probably a directory.  Try converting that.
	     */
	    StrAllocCopy(cur_dir, dir_name);
	    if (NULL != getcwd(dir_name, 255, 0)) {
		/*
		 * Yup, we got it!
		 */
		StrAllocCat(*AllocatedString, dir_name);
	    } else {
		/*
		 *  Nope.  Assume it's an http URL with
		 *  the "http://" defaulted, if we can't
		 *  rule out a bad VMS path.
		 */
		if (strchr(old_string, '[') ||
		    ((cp=strchr(old_string, ':')) != NULL &&
		     !isdigit(cp[1])) ||
		    !LYExpandHostForURL((char **)&old_string,
		    			URLDomainPrefixes,
					URLDomainSuffixes)) {
		    /*
		     *  Probably a bad VMS path (but can't be
		     *  sure).  Use original pathspec for the
		     *  error message that will result.
		     */
		    strcpy(url_file, "/");
		    strcat(url_file, old_string);
		    if (TRACE) {
			fprintf(stderr,
			    "Can't find '%s'  Will assume it's a bad path.\n",
			        old_string);
		    }
		    StrAllocCat(*AllocatedString, url_file);
		} else {
		    /*
		     *  Assume a URL is wanted, so guess the
		     *  scheme with "http://" as the default. - FM
		     */
		    if (!LYAddSchemeForURL((char **)&old_string, "http://")) {
		        StrAllocCopy(*AllocatedString, "http://");
			StrAllocCat(*AllocatedString, old_string);
		    } else {
		        StrAllocCopy(*AllocatedString, old_string);
		    }
		}
	    }
	} else {
	    /*
	     *  Nothing found.  Assume it's an http URL
	     *  with the "http://" defaulted, if we can't
	     *  rule out a bad VMS path.
	     */
	    if (strchr(old_string, '[') ||
		((cp=strchr(old_string, ':')) != NULL &&
		 !isdigit(cp[1])) ||
		!LYExpandHostForURL((char **)&old_string,
		    		    URLDomainPrefixes,
				    URLDomainSuffixes)) {
		/*
		 *  Probably a bad VMS path (but can't be
		 *  sure).  Use original pathspec for the
		 *  error message that will result.
		 */
		strcpy(url_file, "/");
		strcat(url_file, old_string);
		if (TRACE) {
		    fprintf(stderr,
			    "Can't find '%s'  Will assume it's a bad path.\n",
			        old_string);
		}
		StrAllocCat(*AllocatedString, url_file);
	    } else {
		/*
		 *  Assume a URL is wanted, so guess the
		 *  scheme with "http://" as the default. - FM
		 */
		if (!LYAddSchemeForURL((char **)&old_string, "http://")) {
		    StrAllocCopy(*AllocatedString, "http://");
		    StrAllocCat(*AllocatedString, old_string);
		} else {
		    StrAllocCopy(*AllocatedString, old_string);
		}
	    }
	}
	lib$find_file_end(&context);
	FREE(cur_dir);
have_VMS_URL:
	if (TRACE) {
	    fprintf(stderr, "Trying: '%s'\n", *AllocatedString);
	}
#else /* Unix: */
	if (*old_string == '~') {
	    /*
	     * On Unix, covert '~' to $HOME.
	     */
	    StrAllocCat(*AllocatedString, getenv("HOME"));
	    if (old_string[1]) {
		StrAllocCat(*AllocatedString, (old_string+1));
	    }
	    if (TRACE) {
		fprintf(stderr, "Converted '%s' to '%s'\n",
		    		old_string, *AllocatedString);
	    }
	} else {
	    /*
	     *  Create a full path to the current default directory.
	     */
	    char curdir[DIRNAMESIZE];
	    char *temp=NULL;
	    struct stat st;
	    FILE *fptemp=NULL;
#ifdef NO_GETCWD
	    getwd (curdir);
#else
	    getcwd (curdir, DIRNAMESIZE);
#endif /* NO_GETCWD */
	    StrAllocCopy(temp, curdir);
	    StrAllocCat(temp, "/");
	    StrAllocCat(temp, old_string);
	    if (TRACE) {
		fprintf(stderr, "Converted '%s' to '%s'\n", old_string, temp);
	    }
	    if ((stat(temp, &st) < 0) &&
		!(fptemp=fopen(temp, "r"))) {
		/*
		 *  It's not an accessible subdirectory or file on the
		 *  local system, so assume it's a URL request and guess
		 *  the scheme with "http://" as the default.
		 */
		if (TRACE) {
		    fprintf(stderr, "Can't stat() or fopen() '%s'\n", temp);
		}
		if (LYExpandHostForURL((char **)&old_string,
		    		       URLDomainPrefixes,
				       URLDomainSuffixes)) {
		    if (!LYAddSchemeForURL((char **)&old_string, "http://")) {
		        StrAllocCopy(*AllocatedString, "http://");
			StrAllocCat(*AllocatedString, old_string);
		    } else {
		        StrAllocCopy(*AllocatedString, old_string);
		    }
		} else {
		    StrAllocCat(*AllocatedString, temp);
		}
		if (TRACE) {
		    fprintf(stderr, "Trying: '%s'\n", *AllocatedString);
		}
	    } else {
		/*
		 *  It is a subdirectory or file on the local system.
		 */
		StrAllocCat(*AllocatedString, temp);
		if (TRACE) {
		    fprintf(stderr, "Converted '%s' to '%s'\n",
				    old_string, *AllocatedString);
		}
	    }
	    FREE(temp);
	    if (fptemp) {
		fclose(fptemp);
	    }
	}
#endif /* VMS */
    } else { 
	/*
	 *  Path begins with a slash.  Use it as is.
	 */
	StrAllocCat(*AllocatedString, old_string);
	if (TRACE) {
	    fprintf(stderr, "Converted '%s' to '%s'\n",
			    old_string, *AllocatedString);
	}
    }
    if (old_string) {
	FREE(old_string);
    }
    if (TRACE) {
	/* Pause so we can read the messages before invoking curses */
	sleep(AlertSecs);
    }
}

/*
 *  This function rewrites and reallocates a previously allocated
 *  string so that the first element is a confirmed Internet host,
 *  and returns TRUE, otherwise it does not modify the string and
 *  returns FALSE.  It first tries the element as is, then, if the
 *  element does not end with a dot, it adds prefixes from the
 *  (comma separated) prefix list arguement, and, if the element
 *  does not begin with a dot, suffixes from the (comma separated)
 *  suffix list arguments (e.g., www.host.com, then www.host,edu,
 *  then www.host.net, then www.host.org).  The remaining path, if
 *  one is present, will be appended to the expanded host.  It also
 *  takes into account whether a colon is in the element or suffix,
 *  and includes that and what follows as a port field for the
 *  expanded host field (e.g, wfbr:8002/dir/lynx should yield
 *  www.wfbr.edu:8002/dir/lynx).  The calling function should
 *  prepend the scheme field (e.g., http://), or pass the string
 *  to LYAddSchemeForURL(), if this function returns TRUE. - FM
 */
PUBLIC BOOLEAN LYExpandHostForURL ARGS3(
	char **,	AllocatedString,
	char *,		prefix_list,
	char *,		suffix_list)
{
    char DomainPrefix[80], *StartP, *EndP;
    char DomainSuffix[80], *StartS, *EndS;
    char *Str = NULL, *StrColon = NULL, *MsgStr = NULL;
    char *Host = NULL, *HostColon = NULL;
    char *Path = NULL;
    struct hostent  *phost;
    BOOLEAN GotHost = FALSE;

    /*
     *  If we were passed a NULL or zero-length string, or if it
     *  begins with a slash, don't continue pointlessly. - FM
     */
    if (!(*AllocatedString) ||
        *AllocatedString[0] == '\0' || *AllocatedString[0] == '/') {
        return GotHost;
    }

    /*
     *  Make a clean copy of the string, and trim off the
     *  path if one is present, but save the information
     *  so we can restore the path after filling in the
     *  Host[:port] field. - FM
     */
    StrAllocCopy(Str, *AllocatedString);
    if ((Path = strchr(Str, '/')) != NULL) {
        *Path = '\0';
    }

    /*
     *  If the potential host string has a colon, assume it
     *  begins a port field, and trim it off, but save the
     *  information so we can restore the port field after
     *  filling in the host field. - FM
     */
    if ((StrColon = strrchr(Str, ':')) != NULL && isdigit(StrColon[1])) {
        if (StrColon == Str) {
	    FREE(Str);
	    return GotHost;
	}
	*StrColon = '\0';
    }

    /*
     *  Do a DNS test on the potential host field
     *  as presently trimmed. - FM
     */
    if (LYCursesON) {
        StrAllocCopy(MsgStr, "Looking up ");
	StrAllocCat(MsgStr, Str);
	StrAllocCat(MsgStr, " first.");
	HTProgress(MsgStr);
    }
    if ((phost = gethostbyname(Str)) != NULL) {
        GotHost = TRUE;
        FREE(Str);
        FREE(MsgStr);
	return GotHost;
    }

    /*
    **  Set the first prefix, making it a zero-length string
    **  if the list is NULL or if the potential host field
    **  ends with a dot. - FM
    */
    StartP = ((prefix_list && Str[strlen(Str)-1] != '.') ?
    					     prefix_list : "");
    while ((*StartP) && (WHITE(*StartP) || *StartP == ',')) {
        StartP++;	/* Skip whitespace and separators */
    }
    EndP = StartP;
    while (*EndP && !WHITE(*EndP) && *EndP != ',') {
	EndP++;		/* Find separator */
    }
    LYstrncpy(DomainPrefix, StartP, (EndP - StartP));

    /*
    **  Test each prefix with each suffix. - FM
    */
    do {
        /*
	**  Set the first suffix, making it a zero-length string
	**  if the list is NULL or if the potential host field
	**  begins with a dot. - FM
	*/
	StartS = ((suffix_list && *Str != '.') ?
				   suffix_list : "");
	while ((*StartS) && (WHITE(*StartS) || *StartS == ',')) {
	    StartS++;	/* Skip whitespace and separators */
	}
	EndS = StartS;
	while (*EndS && !WHITE(*EndS) && *EndS != ',') {
	    EndS++;	/* Find separator */
	}
	LYstrncpy(DomainSuffix, StartS, (EndS - StartS));

	/*
	**  Create domain names and do DNS tests. - FM
	*/
	do {
	    StrAllocCopy(Host, DomainPrefix);
	    StrAllocCat(Host, ((*Str == '.') ? (Str + 1) : Str));
	    if (Host[strlen(Host)-1] == '.') {
	        Host[strlen(Host)-1] = '\0';
	    }
	    StrAllocCat(Host, DomainSuffix);
	    if ((HostColon = strrchr(Host, ':')) != NULL &&
	        isdigit(HostColon[1])) {
		*HostColon = '\0';
	    }
	    if (LYCursesON) {
 	        StrAllocCopy(MsgStr, "Looking up ");
 		StrAllocCat(MsgStr, Host);
 		StrAllocCat(MsgStr, ", guessing...");
 		HTProgress(MsgStr);
	    }
	    GotHost = ((phost = gethostbyname(Host)) != NULL);
	    if (HostColon != NULL) {
	        *HostColon = ':';
	    }
	    if (GotHost == FALSE) {
		/*
		 *  Give the user chance to interrupt lookup cycles. - KW
		 */
		if (LYCursesON && HTCheckForInterrupt()) {
		    if (TRACE) {
			fprintf(stderr,
	 "*** LYExpandHostForURL interrupted while %s failed to resolve\n",
				Host);
			    }
		    FREE(Str);
		    FREE(MsgStr);
		    FREE(Host);
		    return FALSE; /* We didn't find a valid name. */
		}

	        /*
		**  Advance to the next suffix, or end of suffix list. - FM
		*/
		StartS = ((*EndS == '\0') ? EndS : (EndS + 1));
		while ((*StartS) && (WHITE(*StartS) || *StartS == ',')) {
		    StartS++;	/* Skip whitespace and separators */
		}
		EndS = StartS;
		while (*EndS && !WHITE(*EndS) && *EndS != ',') {
		    EndS++;	/* Find separator */
		}
		LYstrncpy(DomainSuffix, StartS, (EndS - StartS));
	    }
	}  while ((GotHost == FALSE) && (*DomainSuffix != '\0'));

	if (GotHost == FALSE) {
	   /*
	   **  Advance to the next prefix, or end of prefix list. - FM
	   */
	   StartP = ((*EndP == '\0') ? EndP : (EndP + 1));
	   while ((*StartP) && (WHITE(*StartP) || *StartP == ',')) {
	       StartP++;	/* Skip whitespace and separators */
	   }
	   EndP = StartP;
	   while (*EndP && !WHITE(*EndP) && *EndP != ',') {
	       EndP++;		/* Find separator */
	   }
	   LYstrncpy(DomainPrefix, StartP, (EndP - StartP));
     	}
    } while ((GotHost == FALSE) && (*DomainPrefix != '\0'));

    /*
     *  If a test passed, restore the port field if we had one
     *  and there is no colon in the expanded host, and the path
     *  if we had one, and reallocate the original string with
     *  the expanded Host[:port] field included. - FM
     */
    if (GotHost) {
        if (StrColon && strchr(Host, ':') == NULL) {
	    *StrColon = ':';
	    StrAllocCat(Host, StrColon);
	}
        if (Path) {
	    *Path = '/';
	    StrAllocCat(Host, Path);
	}
	StrAllocCopy(*AllocatedString, Host);
    }

    /*
     *  Clean up and return the last test result. - FM
     */
    FREE(Str);
    FREE(MsgStr);
    FREE(Host);
    return GotHost;
}

/*
 *  This function rewrites and reallocates a previously allocated
 *  string that begins with an Internet host name so that the string
 *  begins with its guess of the scheme based on the first field of
 *  the host name, or the default scheme if no guess was made, and
 *  returns TRUE, otherwise it does not modify the string and returns
 *  FALSE.  It also returns FALSE without modifying the string if the
 *  default_scheme argument was NULL or zero-length and no guess was
 *  made. - FM
  */
PUBLIC BOOLEAN LYAddSchemeForURL ARGS2(
	char **,	AllocatedString,
	char *,		default_scheme)
{
    char *Str = NULL;
    BOOLEAN GotScheme = FALSE;

    /*
     *  If we were passed a NULL or zero-length string,
     *  don't continue pointlessly. - FM
     */
    if (!(*AllocatedString) || *AllocatedString[0] == '\0') {
        return GotScheme;
    }

    /*
     * Try to guess the appropriate scheme. - FM
     */
    if (0 == strncasecomp(*AllocatedString, "www", 3)) {
        /*
	 *  This could be either http or https, so check
	 *  the default and otherwise use "http". - FM
	 */
        if (default_scheme != NULL && 
	    NULL != strstr(default_scheme, "http")) {
            StrAllocCopy(Str, default_scheme);
	} else {
            StrAllocCopy(Str, "http://");
	}
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "ftp", 3)) {
        StrAllocCopy(Str, "ftp://");
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "gopher", 6)) {
        StrAllocCopy(Str, "gopher://");
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "wais", 4)) {
        StrAllocCopy(Str, "wais://");
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "cso", 3) ||
    	       0 == strncasecomp(*AllocatedString, "ns.", 3) ||
	       0 == strncasecomp(*AllocatedString, "ph.", 3)) {
        StrAllocCopy(Str, "cso://");
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "finger", 6)) {
        StrAllocCopy(Str, "finger://");
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "news", 4)) {
        /*
	 *  This could be either news, snews, or nntp, so
	 *  check the default, and otherwise use news. - FM
	 */
        if ((default_scheme != NULL) && 
	    (NULL != strstr(default_scheme, "news") ||
	     NULL != strstr(default_scheme, "nntp"))) {
            StrAllocCopy(Str, default_scheme);
	} else {
            StrAllocCopy(Str, "news://");
	}
	GotScheme = TRUE;

    } else if (0 == strncasecomp(*AllocatedString, "nntp", 4)) {
        StrAllocCopy(Str, "nntp://");
	GotScheme = TRUE;

    }

    /*
     *  If we've make a guess, use it.  Otherwise, if we
     *  were passed a default scheme prefix, use that. - FM
     */
    if (GotScheme == TRUE) {
        StrAllocCat(Str, *AllocatedString);
        StrAllocCopy(*AllocatedString, Str);
	FREE(Str);
	return GotScheme;

    } else if (default_scheme != NULL && *default_scheme != '\0') {
        StrAllocCopy(Str, default_scheme);
	GotScheme = TRUE;
        StrAllocCat(Str, *AllocatedString);
        StrAllocCopy(*AllocatedString, Str);
	FREE(Str);
	return GotScheme;
    }

    return GotScheme;
}

/*
 *  Example Client-Side Include interface.
 *
 *  This is called from SGML.c and simply returns markup for reporting
 *  the URL of the document being loaded if a comment begins with
 *  "<!--#lynxCSI".  The markup will be included as if it were in the
 *  document.  Move this function to a separate module for doing this
 *  kind of thing seriously, someday. - FM
 */
PUBLIC void LYDoCSI ARGS3(
	char *,		url,
	CONST char *,	comment,
	char **,	csi)
{
    char *cp = (char *)comment;

    if (cp == NULL)
        return;

    if (strncmp(cp, "!--#", 4))
        return;

    cp += 4;
    if (!strncasecomp(cp, "lynxCSI", 7)) {
        StrAllocCat(*csi, "\n<p align=\"center\">URL: ");
        StrAllocCat(*csi, url);
	StrAllocCat(*csi, "</p>\n\n");
    }

    return;
}

#ifdef VMS
/*
 *  Define_VMSLogical -- Fote Macrides 04-Apr-1995
 *	Define VMS logicals in the process table.
 */
PUBLIC void Define_VMSLogical ARGS2(char *, LogicalName, char *, LogicalValue)
{
    $DESCRIPTOR(lname, "");
    $DESCRIPTOR(lvalue, "");
    $DESCRIPTOR(ltable, "LNM$PROCESS");

    if (!LogicalName || *LogicalName == '\0')
        return;

    lname.dsc$w_length = strlen(LogicalName);
    lname.dsc$a_pointer = LogicalName;

    if (!LogicalValue || *LogicalValue == '\0') {
        lib$delete_logical(&lname, &ltable);
	return;
    }

    lvalue.dsc$w_length = strlen(LogicalValue);
    lvalue.dsc$a_pointer = LogicalValue;
    lib$set_logical(&lname, &lvalue, &ltable, 0, 0);
    return;
}
#endif /* VMS */

PUBLIC CONST char * Home_Dir NOARGS
{
    static CONST char *homedir;

    if (!homedir) {
	if ((homedir = getenv("HOME")) == NULL) {
#ifdef VMS
	    if ((homedir = getenv("SYS$LOGIN")) == NULL) {
	        if ((homedir = getenv("SYS$SCRATCH")) == NULL)
		    homedir = "sys$scratch:";
	    }
#else
	    /* One could use getlogin() and getpwnam() here instead */
	    struct passwd *pw = getpwuid(geteuid());
	    if (pw && pw->pw_dir) {
		homedir = (CONST char *)malloc(1+strlen(pw->pw_dir));
		if (homedir == NULL)
		    outofmem(__FILE__, "Home_Dir");
		strcpy((char *)homedir, pw->pw_dir);
	    }
	    else {
		/* Use /tmp; it should be writable. */
		homedir = "/tmp";
	    }
#endif /* VMS */
	}
    }
    return homedir;
}

#ifdef NO_PUTENV
/* no putenv on the next so we use this code instead!
 */

/* Copyright (C) 1991 Free Software Foundation, Inc.
This file is part of the GNU C Library.

The GNU C Library is free software; you can  redistribute it and/or
modify it under the terms of the GNU Library General  Public License as
published by the Free Software Foundation; either  version 2 of the
License, or (at your option) any later version.

The GNU C Library is distributed in the hope that it  will be useful,
but WITHOUT ANY WARRANTY; without even the implied  warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library  General Public
License along with the GNU C Library; see the file  COPYING.LIB.  If
not, write to the Free Software Foundation, Inc., 675  Mass Ave,
Cambridge, MA 02139, USA.  */

#include <sys/types.h>
#include <errno.h>
#ifdef STDC_HEADERS
#include <stdlib.h>
#else
extern int errno;
#endif /* STDC_HEADERS */

#if defined(STDC_HEADERS) || defined(USG)
#include <string.h>
#define index strchr
#define bcopy(s, d, n) memcpy((d), (s), (n))
#else /* Not (STDC_HEADERS or USG): */
#include <strings.h>
#endif /* STDC_HEADERS or USG */

#ifndef NULL
#define NULL 0
#endif /* !NULL */

#if !__STDC__
#define const
#endif /* !__STDC__ */

extern char **environ;

/* Put STRING, which is of the form "NAME=VALUE", in  the environment.  */
int
putenv (string)
     const char *string;
{
  char *name_end = index (string, '=');
  register size_t size;
  register char **ep;

  if (name_end == NULL)
    {
      /* Remove the variable from the environment.  */
      size = strlen (string);
      for (ep = environ; *ep != NULL; ++ep)
	if (!strncmp (*ep, string, size) && (*ep)[size]  == '=')
	  {
	    while (ep[1] != NULL)
	      {
		ep[0] = ep[1];
		++ep;
	      }
	    *ep = NULL;
	    return 0;
	  }
    }

  size = 0;
  for (ep = environ; *ep != NULL; ++ep)
    if (!strncmp (*ep, string, name_end - string) && (*ep)[name_end - string] == '=')
      break;
    else
      ++size;

  if (*ep == NULL)
    {
      static char **last_environ = NULL;
      char **new_environ = (char **) malloc ((size + 2)  * sizeof (char *));
      if (new_environ == NULL)
	return -1;
      (void) bcopy ((char *) environ, (char *)  new_environ, size * sizeof (char *));
      new_environ[size] = (char *) string;
      new_environ[size + 1] = NULL;
      if (last_environ != NULL)
	free ((char *) last_environ);
      last_environ = new_environ;
      environ = new_environ;
    }
  else
    *ep = (char *) string;

  return 0;
}
#endif /* NO_PUTENV */

#ifdef VMS
/*
 *  This function appends fname to the home path and returns
 *  the full path and filename in VMS syntax.  The fname
 *  string can be just a filename, or include a subirectory
 *  off the home directory, in which chase fname should
 *  with "./" (e.g., ./BM/lynx_bookmarks.html). - FM
 */
PUBLIC void LYVMS_HomePathAndFilename ARGS3(
	char *,		fbuffer,
	int,		fbuffer_size,
	char *,		fname)
{
    char *home = NULL;
    char *temp = NULL;
    int len;

    /*
     *  Make sure we have a buffer and string. - FM
     */
    if (!fbuffer)
        return;
    if (!(fname && *fname) || fbuffer_size < 1) {
        fbuffer[0] = '\0';
	return;
    }

    /*
     *  Set up home string and length. - FM
     */
    StrAllocCopy(home, Home_Dir());
    if (!(home && *home))
        StrAllocCopy(home, "Error:");
    len = fbuffer_size - strlen(home) - 1;
    if (len < 0) {
        len = 0;
	home[fbuffer_size] = '\0';
    }

    /*
     *  Check whether we have a subdirectory path or just a filename. - FM
     */
    if (!strncmp(fname, "./", 2)) {
        /*
	 *  We have a subdirectory path. - FM
	 */
	if (home[strlen(home)-1] == ']') {
	    /*
	     *  We got the home directory, so convert it to
	     *  SHELL syntax and append subdirectory path,
	     *  then convert that to VMS syntax. - FM
	     */
	    temp = (char *)calloc(1, (strlen(home) + strlen(fname) + 10));
	    sprintf(temp, "%s%s", HTVMS_wwwName(home), (fname + 1));
	    sprintf(fbuffer, "%.*s",
	    	    (fbuffer_size - 1), HTVMS_name("", temp));
	    FREE(temp);
	} else {
	    /*
	     *  This will fail, but we need something in the buffer. - FM
	     */
	    sprintf(fbuffer,"%s%.*s", home, len, fname);
	}
    } else {
        /*
	 *  We have a file in the home directory. - FM
	 */
	sprintf(fbuffer,"%s%.*s", home, len, fname);
    }
    FREE(home);
}
#endif /* VMS */