summary refs log tree commit diff stats
path: root/compiler/lookups.nim
blob: 44a30eefa0d69bbba9bd037fb24dfa1dac9a326f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
#
#
#           The Nim Compiler
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# This module implements lookup helpers.
import std/[algorithm, strutils]
import
  intsets, ast, astalgo, idents, semdata, types, msgs, options,
  renderer, nimfix/prettybase, lineinfos, modulegraphs, astmsgs

proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope)

proc noidentError(conf: ConfigRef; n, origin: PNode) =
  var m = ""
  if origin != nil:
    m.add "in expression '" & origin.renderTree & "': "
  m.add "identifier expected, but found '" & n.renderTree & "'"
  localError(conf, n.info, m)

proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
  ## Retrieve a PIdent from a PNode, taking into account accent nodes.
  ## ``origin`` can be nil. If it is not nil, it is used for a better
  ## error message.
  template handleError(n, origin: PNode) =
    noidentError(c.config, n, origin)
    result = getIdent(c.cache, "<Error>")

  case n.kind
  of nkIdent: result = n.ident
  of nkSym: result = n.sym.name
  of nkAccQuoted:
    case n.len
    of 0: handleError(n, origin)
    of 1: result = considerQuotedIdent(c, n[0], origin)
    else:
      var id = ""
      for i in 0..<n.len:
        let x = n[i]
        case x.kind
        of nkIdent: id.add(x.ident.s)
        of nkSym: id.add(x.sym.name.s)
        of nkLiterals - nkFloatLiterals: id.add(x.renderTree)
        else: handleError(n, origin)
      result = getIdent(c.cache, id)
  of nkOpenSymChoice, nkClosedSymChoice:
    if n[0].kind == nkSym:
      result = n[0].sym.name
    else:
      handleError(n, origin)
  else:
    handleError(n, origin)

template addSym*(scope: PScope, s: PSym) =
  strTableAdd(scope.symbols, s)

proc addUniqueSym*(scope: PScope, s: PSym): PSym =
  result = strTableInclReportConflict(scope.symbols, s)

proc openScope*(c: PContext): PScope {.discardable.} =
  result = PScope(parent: c.currentScope,
                  symbols: newStrTable(),
                  depthLevel: c.scopeDepth + 1)
  c.currentScope = result

proc rawCloseScope*(c: PContext) =
  c.currentScope = c.currentScope.parent

proc closeScope*(c: PContext) =
  ensureNoMissingOrUnusedSymbols(c, c.currentScope)
  rawCloseScope(c)

iterator allScopes*(scope: PScope): PScope =
  var current = scope
  while current != nil:
    yield current
    current = current.parent

iterator localScopesFrom*(c: PContext; scope: PScope): PScope =
  for s in allScopes(scope):
    if s == c.topLevelScope: break
    yield s

proc skipAlias*(s: PSym; n: PNode; conf: ConfigRef): PSym =
  if s == nil or s.kind != skAlias:
    result = s
  else:
    result = s.owner
    if conf.cmd == cmdNimfix:
      prettybase.replaceDeprecated(conf, n.info, s, result)
    else:
      message(conf, n.info, warnDeprecated, "use " & result.name.s & " instead; " &
              s.name.s & " is deprecated")

proc isShadowScope*(s: PScope): bool {.inline.} =
  s.parent != nil and s.parent.depthLevel == s.depthLevel

proc localSearchInScope*(c: PContext, s: PIdent): PSym =
  var scope = c.currentScope
  result = strTableGet(scope.symbols, s)
  while result == nil and scope.isShadowScope:
    # We are in a shadow scope, check in the parent too
    scope = scope.parent
    result = strTableGet(scope.symbols, s)

proc initIdentIter(ti: var ModuleIter; marked: var IntSet; im: ImportedModule; name: PIdent;
                   g: ModuleGraph): PSym =
  result = initModuleIter(ti, g, im.m, name)
  while result != nil:
    let b =
      case im.mode
      of importAll: true
      of importSet: result.id in im.imported
      of importExcept: name.id notin im.exceptSet
    if b and not containsOrIncl(marked, result.id):
      return result
    result = nextModuleIter(ti, g)

proc nextIdentIter(ti: var ModuleIter; marked: var IntSet; im: ImportedModule;
                   g: ModuleGraph): PSym =
  while true:
    result = nextModuleIter(ti, g)
    if result == nil: return nil
    case im.mode
    of importAll:
      if not containsOrIncl(marked, result.id):
        return result
    of importSet:
      if result.id in im.imported and not containsOrIncl(marked, result.id):
        return result
    of importExcept:
      if result.name.id notin im.exceptSet and not containsOrIncl(marked, result.id):
        return result

iterator symbols(im: ImportedModule; marked: var IntSet; name: PIdent; g: ModuleGraph): PSym =
  var ti: ModuleIter
  var candidate = initIdentIter(ti, marked, im, name, g)
  while candidate != nil:
    yield candidate
    candidate = nextIdentIter(ti, marked, im, g)

iterator importedItems*(c: PContext; name: PIdent): PSym =
  var marked = initIntSet()
  for im in c.imports.mitems:
    for s in symbols(im, marked, name, c.graph):
      yield s

proc allPureEnumFields(c: PContext; name: PIdent): seq[PSym] =
  var ti: TIdentIter
  result = @[]
  var res = initIdentIter(ti, c.pureEnumFields, name)
  while res != nil:
    result.add res
    res = nextIdentIter(ti, c.pureEnumFields)

iterator allSyms*(c: PContext): (PSym, int, bool) =
  # really iterate over all symbols in all the scopes. This is expensive
  # and only used by suggest.nim.
  var isLocal = true
  var scopeN = 0
  for scope in allScopes(c.currentScope):
    if scope == c.topLevelScope: isLocal = false
    dec scopeN
    for item in scope.symbols:
      yield (item, scopeN, isLocal)

  dec scopeN
  isLocal = false
  for im in c.imports.mitems:
    for s in modulegraphs.allSyms(c.graph, im.m):
      assert s != nil
      yield (s, scopeN, isLocal)

proc someSymFromImportTable*(c: PContext; name: PIdent; ambiguous: var bool): PSym =
  var marked = initIntSet()
  result = nil
  for im in c.imports.mitems:
    for s in symbols(im, marked, name, c.graph):
      if result == nil:
        result = s
      else:
        if s.kind notin OverloadableSyms or result.kind notin OverloadableSyms:
          ambiguous = true

proc searchInScopes*(c: PContext, s: PIdent; ambiguous: var bool): PSym =
  for scope in allScopes(c.currentScope):
    result = strTableGet(scope.symbols, s)
    if result != nil: return result
  result = someSymFromImportTable(c, s, ambiguous)

proc debugScopes*(c: PContext; limit=0, max = int.high) {.deprecated.} =
  var i = 0
  var count = 0
  for scope in allScopes(c.currentScope):
    echo "scope ", i
    for h in 0..high(scope.symbols.data):
      if scope.symbols.data[h] != nil:
        if count >= max: return
        echo count, ": ", scope.symbols.data[h].name.s
        count.inc
    if i == limit: return
    inc i

proc searchInScopesFilterBy*(c: PContext, s: PIdent, filter: TSymKinds): seq[PSym] =
  result = @[]
  for scope in allScopes(c.currentScope):
    var ti: TIdentIter
    var candidate = initIdentIter(ti, scope.symbols, s)
    while candidate != nil:
      if candidate.kind in filter:
        if result.len == 0:
          result.add candidate
      candidate = nextIdentIter(ti, scope.symbols)

  if result.len == 0:
    var marked = initIntSet()
    for im in c.imports.mitems:
      for s in symbols(im, marked, s, c.graph):
        if s.kind in filter:
          result.add s

proc errorSym*(c: PContext, n: PNode): PSym =
  ## creates an error symbol to avoid cascading errors (for IDE support)
  var m = n
  # ensure that 'considerQuotedIdent' can't fail:
  if m.kind == nkDotExpr: m = m[1]
  let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
      considerQuotedIdent(c, m)
    else:
      getIdent(c.cache, "err:" & renderTree(m))
  result = newSym(skError, ident, nextSymId(c.idgen), getCurrOwner(c), n.info, {})
  result.typ = errorType(c)
  incl(result.flags, sfDiscardable)
  # pretend it's from the top level scope to prevent cascading errors:
  if c.config.cmd != cmdInteractive and c.compilesContextId == 0:
    c.moduleScope.addSym(result)

type
  TOverloadIterMode* = enum
    oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
    oimSymChoiceLocalLookup
  TOverloadIter* = object
    it*: TIdentIter
    mit*: ModuleIter
    m*: PSym
    mode*: TOverloadIterMode
    symChoiceIndex*: int
    currentScope: PScope
    importIdx: int
    marked: IntSet

proc getSymRepr*(conf: ConfigRef; s: PSym, getDeclarationPath = true): string =
  case s.kind
  of routineKinds, skType:
    result = getProcHeader(conf, s, getDeclarationPath = getDeclarationPath)
  else:
    result = "'$1'" % s.name.s
    if getDeclarationPath:
      result.addDeclaredLoc(conf, s)

proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope) =
  # check if all symbols have been used and defined:
  var it: TTabIter
  var s = initTabIter(it, scope.symbols)
  var missingImpls = 0
  var unusedSyms: seq[tuple[sym: PSym, key: string]]
  while s != nil:
    if sfForward in s.flags and s.kind notin {skType, skModule}:
      # too many 'implementation of X' errors are annoying
      # and slow 'suggest' down:
      if missingImpls == 0:
        localError(c.config, s.info, "implementation of '$1' expected" %
            getSymRepr(c.config, s, getDeclarationPath=false))
      inc missingImpls
    elif {sfUsed, sfExported} * s.flags == {}:
      if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam, skEnumField}:
        # XXX: implicit type params are currently skTypes
        # maybe they can be made skGenericParam as well.
        if s.typ != nil and tfImplicitTypeParam notin s.typ.flags and
           s.typ.kind != tyGenericParam:
          unusedSyms.add (s, toFileLineCol(c.config, s.info))
    s = nextIter(it, scope.symbols)
  for (s, _) in sortedByIt(unusedSyms, it.key):
    message(c.config, s.info, hintXDeclaredButNotUsed, s.name.s)

proc wrongRedefinition*(c: PContext; info: TLineInfo, s: string;
                        conflictsWith: TLineInfo, note = errGenerated) =
  ## Emit a redefinition error if in non-interactive mode
  if c.config.cmd != cmdInteractive:
    localError(c.config, info, note,
      "redefinition of '$1'; previous declaration here: $2" %
      [s, c.config $ conflictsWith])

# xxx pending bootstrap >= 1.4, replace all those overloads with a single one:
# proc addDecl*(c: PContext, sym: PSym, info = sym.info, scope = c.currentScope) {.inline.} =
proc addDeclAt*(c: PContext; scope: PScope, sym: PSym, info: TLineInfo) =
  let conflict = scope.addUniqueSym(sym)
  if conflict != nil:
    if sym.kind == skModule and conflict.kind == skModule and sym.owner == conflict.owner:
      # e.g.: import foo; import foo
      # xxx we could refine this by issuing a different hint for the case
      # where a duplicate import happens inside an include.
      localError(c.config, info, hintDuplicateModuleImport,
        "duplicate import of '$1'; previous import here: $2" %
        [sym.name.s, c.config $ conflict.info])
    else:
      wrongRedefinition(c, info, sym.name.s, conflict.info, errGenerated)

proc addDeclAt*(c: PContext; scope: PScope, sym: PSym) {.inline.} =
  addDeclAt(c, scope, sym, sym.info)

proc addDecl*(c: PContext, sym: PSym, info: TLineInfo) {.inline.} =
  addDeclAt(c, c.currentScope, sym, info)

proc addDecl*(c: PContext, sym: PSym) {.inline.} =
  addDeclAt(c, c.currentScope, sym)

proc addPrelimDecl*(c: PContext, sym: PSym) =
  discard c.currentScope.addUniqueSym(sym)

from ic / ic import addHidden

proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  ## adds symbol to the module for either private or public access.
  if sfExported in sym.flags:
    # add to interface:
    if c.module != nil: exportSym(c, sym)
    else: internalError(c.config, sym.info, "addInterfaceDeclAux")
  elif sym.kind in ExportableSymKinds and c.module != nil and isTopLevelInsideDeclaration(c, sym):
    strTableAdd(semtabAll(c.graph, c.module), sym)
    if c.config.symbolFiles != disabledSf:
      addHidden(c.encoder, c.packedRepr, sym)

proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  ## adds a symbol on the scope and the interface if appropriate
  addDeclAt(c, scope, sym)
  if not scope.isShadowScope:
    # adding into a non-shadow scope, we need to handle exports, etc
    addInterfaceDeclAux(c, sym)

proc addInterfaceDecl*(c: PContext, sym: PSym) {.inline.} =
  ## adds a decl and the interface if appropriate
  addInterfaceDeclAt(c, c.currentScope, sym)

proc addOverloadableSymAt*(c: PContext; scope: PScope, fn: PSym) =
  ## adds an symbol to the given scope, will check for and raise errors if it's
  ## a redefinition as opposed to an overload.
  if fn.kind notin OverloadableSyms:
    internalError(c.config, fn.info, "addOverloadableSymAt")
    return
  let check = strTableGet(scope.symbols, fn.name)
  if check != nil and check.kind notin OverloadableSyms:
    wrongRedefinition(c, fn.info, fn.name.s, check.info)
  else:
    scope.addSym(fn)

proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  ## adds an overloadable symbol on the scope and the interface if appropriate
  addOverloadableSymAt(c, scope, sym)
  if not scope.isShadowScope:
    # adding into a non-shadow scope, we need to handle exports, etc
    addInterfaceDeclAux(c, sym)

proc openShadowScope*(c: PContext) =
  ## opens a shadow scope, just like any other scope except the depth is the
  ## same as the parent -- see `isShadowScope`.
  c.currentScope = PScope(parent: c.currentScope,
                          symbols: newStrTable(),
                          depthLevel: c.scopeDepth)

proc closeShadowScope*(c: PContext) =
  ## closes the shadow scope, but doesn't merge any of the symbols
  ## Does not check for unused symbols or missing forward decls since a macro
  ## or template consumes this AST
  rawCloseScope(c)

proc mergeShadowScope*(c: PContext) =
  ## close the existing scope and merge in all defined symbols, this will also
  ## trigger any export related code if this is into a non-shadow scope.
  ##
  ## Merges:
  ## shadow -> shadow: add symbols to the parent but check for redefinitions etc
  ## shadow -> non-shadow: the above, but also handle exports and all that 
  let shadowScope = c.currentScope
  c.rawCloseScope
  for sym in shadowScope.symbols:
    if sym.kind in OverloadableSyms:
      c.addInterfaceOverloadableSymAt(c.currentScope, sym)
    else:
      c.addInterfaceDecl(sym)

when false:
  # `nimfix` used to call `altSpelling` and prettybase.replaceDeprecated(n.info, ident, alt)
  proc altSpelling(c: PContext, x: PIdent): PIdent =
    case x.s[0]
    of 'A'..'Z': result = getIdent(c.cache, toLowerAscii(x.s[0]) & x.s.substr(1))
    of 'a'..'z': result = getIdent(c.cache, toLowerAscii(x.s[0]) & x.s.substr(1))
    else: result = x

import std/editdistance, heapqueue

type SpellCandidate = object
  dist: int
  depth: int
  msg: string
  sym: PSym

template toOrderTup(a: SpellCandidate): auto =
  # `dist` is first, to favor nearby matches
  # `depth` is next, to favor nearby enclosing scopes among ties
  # `sym.name.s` is last, to make the list ordered and deterministic among ties
  (a.dist, a.depth, a.msg)

proc `<`(a, b: SpellCandidate): bool =
  a.toOrderTup < b.toOrderTup

proc mustFixSpelling(c: PContext): bool {.inline.} =
  result = c.config.spellSuggestMax != 0 and c.compilesContextId == 0
    # don't slowdown inside compiles()

proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) =
  ## when we cannot find the identifier, suggest nearby spellings
  var list = initHeapQueue[SpellCandidate]()
  let name0 = ident.s.nimIdentNormalize

  for (sym, depth, isLocal) in allSyms(c):
    let depth = -depth - 1
    let dist = editDistance(name0, sym.name.s.nimIdentNormalize)
    var msg: string
    msg.add "\n ($1, $2): '$3'" % [$dist, $depth, sym.name.s]
    addDeclaredLoc(msg, c.config, sym) # `msg` needed for deterministic ordering.
    list.push SpellCandidate(dist: dist, depth: depth, msg: msg, sym: sym)

  if list.len == 0: return
  let e0 = list[0]
  var count = 0
  while true:
    # pending https://github.com/timotheecour/Nim/issues/373 use more efficient `itemsSorted`.
    if list.len == 0: break
    let e = list.pop()
    if c.config.spellSuggestMax == spellSuggestSecretSauce:
      const
        smallThres = 2
        maxCountForSmall = 4
        # avoids ton of operator matches when mis-matching short symbols such as `i`
        # other heuristics could be devised, such as only suggesting operators if `name0`
        # is an operator (likewise with non-operators).
      if e.dist > e0.dist or (name0.len <= smallThres and count >= maxCountForSmall): break
    elif count >= c.config.spellSuggestMax: break
    if count == 0:
      result.add "\ncandidates (edit distance, scope distance); see '--spellSuggest': "
    result.add e.msg
    count.inc

proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym; amb: var bool): PSym =
  var err = "ambiguous identifier: '" & s.name.s & "'"
  var i = 0
  var ignoredModules = 0
  for candidate in importedItems(c, s.name):
    if i == 0: err.add " -- use one of the following:\n"
    else: err.add "\n"
    err.add "  " & candidate.owner.name.s & "." & candidate.name.s
    err.add ": " & typeToString(candidate.typ)
    if candidate.kind == skModule:
      inc ignoredModules
    else:
      result = candidate
    inc i
  if ignoredModules != i-1:
    localError(c.config, info, errGenerated, err)
    result = nil
  else:
    amb = false

proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
  var amb: bool
  discard errorUseQualifier(c, info, s, amb)

proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]) =
  var err = "ambiguous identifier: '" & candidates[0].name.s & "'"
  var i = 0
  for candidate in candidates:
    if i == 0: err.add " -- use one of the following:\n"
    else: err.add "\n"
    err.add "  " & candidate.owner.name.s & "." & candidate.name.s
    err.add ": " & typeToString(candidate.typ)
    inc i
  localError(c.config, info, errGenerated, err)

proc errorUndeclaredIdentifier*(c: PContext; info: TLineInfo; name: string, extra = "") =
  var err = "undeclared identifier: '" & name & "'" & extra
  if c.recursiveDep.len > 0:
    err.add "\nThis might be caused by a recursive module dependency:\n"
    err.add c.recursiveDep
    # prevent excessive errors for 'nim check'
    c.recursiveDep = ""
  localError(c.config, info, errGenerated, err)

proc errorUndeclaredIdentifierHint*(c: PContext; n: PNode, ident: PIdent): PSym =
  var extra = ""
  if c.mustFixSpelling: fixSpelling(c, n, ident, extra)
  errorUndeclaredIdentifier(c, n.info, ident.s, extra)
  result = errorSym(c, n)

proc lookUp*(c: PContext, n: PNode): PSym =
  # Looks up a symbol. Generates an error in case of nil.
  var amb = false
  case n.kind
  of nkIdent:
    result = searchInScopes(c, n.ident, amb).skipAlias(n, c.config)
    if result == nil: result = errorUndeclaredIdentifierHint(c, n, n.ident)
  of nkSym:
    result = n.sym
  of nkAccQuoted:
    var ident = considerQuotedIdent(c, n)
    result = searchInScopes(c, ident, amb).skipAlias(n, c.config)
    if result == nil: result = errorUndeclaredIdentifierHint(c, n, ident)
  else:
    internalError(c.config, n.info, "lookUp")
    return
  if amb:
    #contains(c.ambiguousSymbols, result.id):
    result = errorUseQualifier(c, n.info, result, amb)
  when false:
    if result.kind == skStub: loadStub(result)

type
  TLookupFlag* = enum
    checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields

proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  const allExceptModule = {low(TSymKind)..high(TSymKind)} - {skModule, skPackage}
  case n.kind
  of nkIdent, nkAccQuoted:
    var amb = false
    var ident = considerQuotedIdent(c, n)
    if checkModule in flags:
      result = searchInScopes(c, ident, amb).skipAlias(n, c.config)
    else:
      let candidates = searchInScopesFilterBy(c, ident, allExceptModule) #.skipAlias(n, c.config)
      if candidates.len > 0:
        result = candidates[0]
        amb = candidates.len > 1
        if amb and checkAmbiguity in flags:
          errorUseQualifier(c, n.info, candidates)
    if result == nil:
      let candidates = allPureEnumFields(c, ident)
      if candidates.len > 0:
        result = candidates[0]
        amb = candidates.len > 1
        if amb and checkAmbiguity in flags:
          errorUseQualifier(c, n.info, candidates)

    if result == nil and checkUndeclared in flags:
      result = errorUndeclaredIdentifierHint(c, n, ident)
    elif checkAmbiguity in flags and result != nil and amb:
      result = errorUseQualifier(c, n.info, result, amb)
    c.isAmbiguous = amb
  of nkSym:
    result = n.sym
  of nkDotExpr:
    result = nil
    var m = qualifiedLookUp(c, n[0], (flags * {checkUndeclared}) + {checkModule})
    if m != nil and m.kind == skModule:
      var ident: PIdent = nil
      if n[1].kind == nkIdent:
        ident = n[1].ident
      elif n[1].kind == nkAccQuoted:
        ident = considerQuotedIdent(c, n[1])
      if ident != nil:
        if m == c.module:
          result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n, c.config)
        else:
          result = someSym(c.graph, m, ident).skipAlias(n, c.config)
        if result == nil and checkUndeclared in flags:
          result = errorUndeclaredIdentifierHint(c, n[1], ident)
      elif n[1].kind == nkSym:
        result = n[1].sym
      elif checkUndeclared in flags and
           n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
        localError(c.config, n[1].info, "identifier expected, but got: " &
                   renderTree(n[1]))
        result = errorSym(c, n[1])
  else:
    result = nil
  when false:
    if result != nil and result.kind == skStub: loadStub(result)

proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  o.importIdx = -1
  o.marked = initIntSet()
  case n.kind
  of nkIdent, nkAccQuoted:
    var ident = considerQuotedIdent(c, n)
    var scope = c.currentScope
    o.mode = oimNoQualifier
    while true:
      result = initIdentIter(o.it, scope.symbols, ident).skipAlias(n, c.config)
      if result != nil:
        o.currentScope = scope
        break
      else:
        scope = scope.parent
        if scope == nil:
          for i in 0..c.imports.high:
            result = initIdentIter(o.mit, o.marked, c.imports[i], ident, c.graph).skipAlias(n, c.config)
            if result != nil:
              o.currentScope = nil
              o.importIdx = i
              return result
          return nil

  of nkSym:
    result = n.sym
    o.mode = oimDone
  of nkDotExpr:
    o.mode = oimOtherModule
    o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
    if o.m != nil and o.m.kind == skModule:
      var ident: PIdent = nil
      if n[1].kind == nkIdent:
        ident = n[1].ident
      elif n[1].kind == nkAccQuoted:
        ident = considerQuotedIdent(c, n[1], n)
      if ident != nil:
        if o.m == c.module:
          # a module may access its private members:
          result = initIdentIter(o.it, c.topLevelScope.symbols,
                                 ident).skipAlias(n, c.config)
          o.mode = oimSelfModule
        else:
          result = initModuleIter(o.mit, c.graph, o.m, ident).skipAlias(n, c.config)
      else:
        noidentError(c.config, n[1], n)
        result = errorSym(c, n[1])
  of nkClosedSymChoice, nkOpenSymChoice:
    o.mode = oimSymChoice
    if n[0].kind == nkSym:
      result = n[0].sym
    else:
      o.mode = oimDone
      return nil
    o.symChoiceIndex = 1
    o.marked = initIntSet()
    incl(o.marked, result.id)
  else: discard
  when false:
    if result != nil and result.kind == skStub: loadStub(result)

proc lastOverloadScope*(o: TOverloadIter): int =
  case o.mode
  of oimNoQualifier:
    result = if o.importIdx >= 0: 0
             elif o.currentScope.isNil: -1
             else: o.currentScope.depthLevel
  of oimSelfModule:  result = 1
  of oimOtherModule: result = 0
  else: result = -1

proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  assert o.currentScope == nil
  var idx = o.importIdx+1
  o.importIdx = c.imports.len # assume the other imported modules lack this symbol too
  while idx < c.imports.len:
    result = initIdentIter(o.mit, o.marked, c.imports[idx], o.it.name, c.graph).skipAlias(n, c.config)
    if result != nil:
      # oh, we were wrong, some other module had the symbol, so remember that:
      o.importIdx = idx
      break
    inc idx

proc symChoiceExtension(o: var TOverloadIter; c: PContext; n: PNode): PSym =
  assert o.currentScope == nil
  while o.importIdx < c.imports.len:
    result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph).skipAlias(n, c.config)
    #while result != nil and result.id in o.marked:
    #  result = nextIdentIter(o.it, o.marked, c.imports[o.importIdx])
    if result != nil:
      #assert result.id notin o.marked
      return result
    inc o.importIdx

proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  case o.mode
  of oimDone:
    result = nil
  of oimNoQualifier:
    if o.currentScope != nil:
      assert o.importIdx < 0
      result = nextIdentIter(o.it, o.currentScope.symbols).skipAlias(n, c.config)
      while result == nil:
        o.currentScope = o.currentScope.parent
        if o.currentScope != nil:
          result = initIdentIter(o.it, o.currentScope.symbols, o.it.name).skipAlias(n, c.config)
          # BUGFIX: o.it.name <-> n.ident
        else:
          o.importIdx = 0
          if c.imports.len > 0:
            result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph).skipAlias(n, c.config)
            if result == nil:
              result = nextOverloadIterImports(o, c, n)
          break
    elif o.importIdx < c.imports.len:
      result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph).skipAlias(n, c.config)
      if result == nil:
        result = nextOverloadIterImports(o, c, n)
    else:
      result = nil
  of oimSelfModule:
    result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n, c.config)
  of oimOtherModule:
    result = nextModuleIter(o.mit, c.graph).skipAlias(n, c.config)
  of oimSymChoice:
    if o.symChoiceIndex < n.len:
      result = n[o.symChoiceIndex].sym
      incl(o.marked, result.id)
      inc o.symChoiceIndex
    elif n.kind == nkOpenSymChoice:
      # try 'local' symbols too for Koenig's lookup:
      o.mode = oimSymChoiceLocalLookup
      o.currentScope = c.currentScope
      result = firstIdentExcluding(o.it, o.currentScope.symbols,
                                   n[0].sym.name, o.marked).skipAlias(n, c.config)
      while result == nil:
        o.currentScope = o.currentScope.parent
        if o.currentScope != nil:
          result = firstIdentExcluding(o.it, o.currentScope.symbols,
                                      n[0].sym.name, o.marked).skipAlias(n, c.config)
        else:
          o.importIdx = 0
          result = symChoiceExtension(o, c, n)
          break
      if result != nil:
        incl o.marked, result.id
  of oimSymChoiceLocalLookup:
    if o.currentScope != nil:
      result = nextIdentExcluding(o.it, o.currentScope.symbols, o.marked).skipAlias(n, c.config)
      while result == nil:
        o.currentScope = o.currentScope.parent
        if o.currentScope != nil:
          result = firstIdentExcluding(o.it, o.currentScope.symbols,
                                      n[0].sym.name, o.marked).skipAlias(n, c.config)
        else:
          o.importIdx = 0
          result = symChoiceExtension(o, c, n)
          break
      if result != nil:
        incl o.marked, result.id

    elif o.importIdx < c.imports.len:
      result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph).skipAlias(n, c.config)
      #assert result.id notin o.marked
      #while result != nil and result.id in o.marked:
      #  result = nextIdentIter(o.it, c.imports[o.importIdx]).skipAlias(n, c.config)
      if result == nil:
        inc o.importIdx
        result = symChoiceExtension(o, c, n)

  when false:
    if result != nil and result.kind == skStub: loadStub(result)

proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
              flags: TSymFlags = {}): PSym =
  var o: TOverloadIter
  var a = initOverloadIter(o, c, n)
  while a != nil:
    if a.kind in kinds and flags <= a.flags:
      if result == nil: result = a
      else: return nil # ambiguous
    a = nextOverloadIter(o, c, n)
30' href='/ingrix/lynx-snapshots/commit/WWW/Library/Implementation/HTTCP.c?id=6bd78b38830217fa268e678d9637116ec516bf0e'>6bd78b38 ^
86b4d41a ^
c3ec4181 ^
6bd78b38 ^
86b4d41a ^


6bd78b38 ^

43797ce7 ^


6bd78b38 ^
43797ce7 ^
6bd78b38 ^
86b4d41a ^

e087f6d4
6bd78b38 ^
86b4d41a ^

6bd78b38 ^
e087f6d4
86b4d41a ^
945e8eb6 ^

86b4d41a ^
945e8eb6 ^




86b4d41a ^


















e087f6d4
86b4d41a ^


e087f6d4
86b4d41a ^

6bd78b38 ^
86b4d41a ^





6bd78b38 ^
e087f6d4
86b4d41a ^
6bd78b38 ^
86b4d41a ^


e087f6d4
86b4d41a ^
6bd78b38 ^
86b4d41a ^

6bd78b38 ^
86b4d41a ^
6bd78b38 ^
86b4d41a ^
e087f6d4
6bd78b38 ^

86b4d41a ^
e087f6d4
86b4d41a ^
6bd78b38 ^
c3ec4181 ^










86b4d41a ^



e087f6d4
6bd78b38 ^
e087f6d4
6bd78b38 ^
86b4d41a ^



2a94396c ^
86b4d41a ^




e087f6d4
86b4d41a ^
6bd78b38 ^
86b4d41a ^




e087f6d4
e4409c40 ^
6bd78b38 ^

86b4d41a ^
c3ec4181 ^

6bd78b38 ^
86b4d41a ^



6bd78b38 ^
86b4d41a ^

6bd78b38 ^

86b4d41a ^
e087f6d4
6bd78b38 ^

e087f6d4

6bd78b38 ^


e087f6d4

86b4d41a ^
e087f6d4

6bd78b38 ^



e087f6d4
6bd78b38 ^
e087f6d4

6bd78b38 ^
86b4d41a ^
e087f6d4
6bd78b38 ^
86b4d41a ^

e087f6d4


6bd78b38 ^
e087f6d4
6bd78b38 ^
e087f6d4
6bd78b38 ^
e087f6d4
c3ec4181 ^

e087f6d4





945e8eb6 ^
86b4d41a ^
945e8eb6 ^

86b4d41a ^
945e8eb6 ^



e087f6d4
945e8eb6 ^
86b4d41a ^
945e8eb6 ^

e087f6d4
945e8eb6 ^



86b4d41a ^







e087f6d4


6bd78b38 ^


86b4d41a ^
c3ec4181 ^
6bd78b38 ^


86b4d41a ^
6bd78b38 ^
86b4d41a ^
6bd78b38 ^
86b4d41a ^
c3ec4181 ^
6bd78b38 ^
86b4d41a ^

6bd78b38 ^

e087f6d4




c3ec4181 ^













e087f6d4













6bd78b38 ^





e087f6d4
6bd78b38 ^

e087f6d4

6bd78b38 ^


e087f6d4
6bd78b38 ^




























e087f6d4


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157





                                                                       

                                                                            
                                                                         
                                                                         
                                        




                                                                          

  





                                                                      
                    
 


                     
                     
 

                                           

                                                   
                     
                             

                                 
                                  
                                   
                                   











                           
                    


                                        
                                        
                                        
                        






                                                                            
                       
 

                         
  

                                                                   

                    
  










                                                                               
             
                                                                    
                                                               
  
              
                                                          











                   
               

                       

                                                                       

                             
                     




                    









                                                                        

                                
                                                  

                                                                         



                                      
                         
                          


                                



                                

                    
                 
                


                           
                 

                                        

                      
     



                                          


                                 
            


                                 
     



                                                                    

                       
     
                          

                        
     
             


                       



                              
                              


               
                            



                     
                                                                             

                                                         
         
                                                                           




                        
                               
     

                                                                       



                        
                    
                                   
                        
                          

                        

                                                           




                              
                                                                   
                         
               
                                                            
                       



                     
      
                                                           
      









                         












                                                                               

                                     


                                  
                   
                                                                      
                                                          


                 

                                          
                                    
 
                        
                                                    





                 
                                                                  


                                                
            
                                                                    

                                 
                                       
                               


                                  



                                                            

                  
                    



                                             
             

                                                              
                                                                      
  
            
                                                                  
                                                   

                             
                               


                            
                                                                

                      
                                                                   
                         

               
                                                          


                                
                                                                  

                  


                                    
                                                                 
                          
      

                                     
                                             

                                                   
           
                                                 
                
             
                                                                              
     
                                                                                

                         
                                                                
                
                                                                  
                       
                                                

                                                               
             
                     
         
     

             
      

                                                                            
      

                                                                                
                                                                               
                                          
                                 
 


                                                                              
                                 
                              
                                           
                      
             

                     
                                                                           
                            
         

     
      

                                     
                                                         

            
                                                    
     
               
                                                                               
     
           
                                                                              
     
                                                                             
                 
                     
                  
                    
                   
                         
                                                         
                                                                         
                                                                      

                
               
          


                                                                     
         
              
                                                    
              

                                           



                                        
                  

                                              


                                            

                                            
                                     
                                                                  

                             
                                            

                                                          


              
                                                                  
              

                                
                  

                                        



                                                

                                         
                                                                    
                          
                 
                  

                                                   
                                            
                                                                             
                                         
                                           
                               

                                  


                                          

                                          

                         
                               
                                                        
             

                                                                                    
                                                

                                                                                        

                                                

                                                                                
                                              
                     
                      

                                                                                        
                                                
             
              
                                                               
              
                                            
                            
                                                                                   
                                   
                                                                            
                                                                 
                                      
                                                                                     
                                      
                                                                                   
                        
                                                     
                                                           
                 
                 
                                                                    
                       
                    
                                                                        
             
                          
                          
         
                                           
                                                                             
                              
                    
                       
                         
                      
         
                    
                   
                         
          
                                                                         


                         
            
                                                       
                   
                                           

                                                                                  

         





























                                                                                             
                                                         
                         
          
                                                                         
                
                     
                                                                             
                              
                    
                       
                         
                                   
         
                    
                   
                         




                                                                               
                                                                            
                                                                            
                                                    
          
                                                            
     
                                                                          
                           
                  
                     

     
                                                                                   




                                                                
                                 



                        





















                                                                          
                

                                                                            
                              
                                  
 
                 
                                                          



                                                            
      

                                                  
      





                                                                        



                                                          
                                                               

                                                                      
                          

                                                                                



                                                            

                                                              











                                     


                                                                     
  

                             

                                     

                          
                                   
                                              
               
                      


                         
 
      
                        
      

                                           
 
      
                                               
      


                                              

                                                                      


                                          
     

             
                                                                      



                                           
                                       







                                                                     
                      




                                                                  
 
      
                                                                    
      
                                                   
                   


                                  
     
 
               

                                            


                                                                     
      

                
                                                 
     

                                           
                      

                                                                   
     
                                   
                     
 
      


                                                                         
      
            
                     

                                                             


                           
                                                            
          
                  
                                                                              
             
      















                                                                       
      
                       



                                                                  
 


                            

              
                                                 
              
                                    


                                                                

             


                                 
                               
                         
                                     

                                  
            
                           

                                                                 
                
                  
                                                                              

             
                                                                     




                                                              


















                                                                               
            


                                 
                  

                                                                    
          





                                                                 
                                                                   
     
                                                              
                


                               
 
                                                                             
                                             

                          
            
                 
                  
             
            

                                 
                
                  
             
                  










                                                                             



                                                                           
          
                                              
                
                                                



                                        
                                                                       




                                        
     
                   
                     




                                                          
     
               

                                            
          

                                                           
                



                                           
                      

                                                                 

                                   
                     
 

                  

 


                                                              

                               
                            

                              



                           
          
           

                     
                    
                  
 
                                

                                


                      
              
     
              
                                
                    
          

                                             





                                                             
          
                                                                  

                                                           
            



                                     
            
                           
                                         

                                                                      
                  



                                                                     







                                           


                                   


                                            
                                  
      


                                          
                                                                          
                           
                                                            
      
                                                                         
      
                                        

                  

              




                     













                                                                             













                       





                                          
 

             

            


                                                                    
                  




























                                                                  


                           
/*			Generic Communication Code		HTTCP.c
**			==========================
**
**	This code is in common between client and server sides.
**
**	16 Jan 92  TBL	Fix strtol() undefined on CMU Mach.
**	25 Jun 92  JFG	Added DECNET option through TCP socket emulation.
**	13 Sep 93  MD	Added correct return of vmserrorno for HTInetStatus.
**			Added decoding of vms error message for MULTINET.
**	7-DEC-1993 Bjorn S. Nilsson, ALEPH, CERN, VMS UCX ioctl() changes
**			(done of Mosaic)
**	19 Feb 94  Danny Mayer	Added Bjorn Fixes to Lynx version
**	 7 Mar 94  Danny Mayer	Added Fix UCX version for full domain name
**	20 May 94  Andy Harper	Added support for CMU TCP/IP transport
**	17 Nov 94  Andy Harper	Added support for SOCKETSHR transport
**	16 Jul 95  S. Bjorndahl added kluge to deal with LIBCMU bug
*/

#include <HTUtils.h>
#include <tcp.h>		/* Defines SHORT_NAMES if necessary */
#include <HTAccess.h>
#include <HTParse.h>
#include <HTAlert.h>
#include <HTTCP.h>
#include <LYUtils.h>

#ifdef NSL_FORK
#include <signal.h>
#include <sys/wait.h>
#endif /* NSL_FORK */

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

#define OK_HOST(p) ((p) != 0 && (p->h_length) != 0)

#ifdef SVR4_BSDSELECT
PUBLIC 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 */

#include <LYLeaks.h>

#ifdef SHORT_NAMES
#define HTInetStatus		HTInStat
#define HTInetString		HTInStri
#define HTParseInet		HTPaInet
#endif /* SHORT_NAMES */

#ifndef FD_SETSIZE
#if defined(UCX) || defined(SOCKETSHR_TCP) || defined(CMU_TCP)
#define FD_SETSIZE 32
#else
#define FD_SETSIZE 256
#endif /* Limit # sockets to 32 for UCX, BSN - also SOCKETSHR and CMU, AH */
#endif /* FD_SETSIZE */

/*
**  Module-Wide variables
*/
PRIVATE char *hostname = NULL;		/* The name of this host */

/*
**  PUBLIC VARIABLES
*/
#ifdef SOCKS
extern BOOLEAN socks_flag;
PUBLIC unsigned long socks_bind_remoteAddr; /* for long Rbind */
#endif /* SOCKS */

/* PUBLIC SockA HTHostAddress; */	/* The internet address of the host */
					/* Valid after call to HTHostName() */

/*	Encode INET status (as in sys/errno.h)			  inet_status()
**	------------------
**
**  On entry,
**	where		gives a description of what caused the error
**	global errno	gives the error number in the Unix way.
**
**  On return,
**	returns 	a negative status in the Unix way.
*/
#ifndef PCNFS

#ifdef VMS
#include <perror.h>
#ifndef errno
extern int errno;
#endif /* !errno */
#endif /* VMS */

#ifndef VM
#ifndef VMS
#ifndef THINK_C

#ifdef DECL_SYS_ERRLIST
extern char *sys_errlist[];		/* see man perror on cernvax */
extern int sys_nerr;
#endif /* DECL_SYS_ERRLIST */

#endif /* !THINK_C */
#endif /* !VMS */
#endif /* !VM */

#endif	/* !PCNFS */

#ifdef _WINDOWS_NSL
	 char host[512];
	 struct hostent  *phost;     /* Pointer to host - See netdb.h */

unsigned long _fork_func (void *arglist)
{
		  return (unsigned long)(phost = gethostbyname(host));
}
#endif /* _WINDOWS_NSL */

#if defined(VMS) && defined(UCX)
/*
**  A routine to mimic the ioctl function for UCX.
**  Bjorn S. Nilsson, 25-Nov-1993. Based on an example in the UCX manual.
*/
#include <iodef.h>
#define IOC_OUT (int)0x40000000
extern int vaxc$get_sdc(), sys$qiow();

PUBLIC int HTioctl ARGS3(
	int,		d,
	int,		request,
	int *,		argp)
{
    int sdc, status;
    unsigned short fun, iosb[4];
    char *p5, *p6;
    struct comm {
	int command;
	char *addr;
    } ioctl_comm;
    struct it2 {
	unsigned short len;
	unsigned short opt;
	struct comm *addr;
    } ioctl_desc;

    if ((sdc = vaxc$get_sdc (d)) == 0) {
	errno = EBADF;
	return -1;
    }
    ioctl_desc.opt  = UCX$C_IOCTL;
    ioctl_desc.len  = sizeof(struct comm);
    ioctl_desc.addr = &ioctl_comm;
    if (request & IOC_OUT) {
	fun = IO$_SENSEMODE;
	p5 = 0;
	p6 = (char *)&ioctl_desc;
    } else {
	fun = IO$_SETMODE;
	p5 = (char *)&ioctl_desc;
	p6 = 0;
    }
    ioctl_comm.command = request;
    ioctl_comm.addr = (char *)argp;
    status = sys$qiow (0, sdc, fun, iosb, 0, 0, 0, 0, 0, 0, p5, p6);
    if (!(status & 01)) {
	errno = status;
	return -1;
    }
    if (!(iosb[0] & 01)) {
	errno = iosb[0];
	return -1;
    }
    return 0;
}
#endif /* VMS && UCX */

/*	Report Internet Error
**	---------------------
*/
PUBLIC int HTInetStatus ARGS1(
	char *, 	where)
{
#ifdef VMS
#ifdef MULTINET
    SOCKET_ERRNO = vmserrno;
#endif /* MULTINET */
#endif /* VMS */

    CTRACE(tfp,
	"TCP: Error %d in `SOCKET_ERRNO' after call to %s() failed.\n\t%s\n",
	   SOCKET_ERRNO,  where,
	   /* third arg is transport/platform specific */
#ifdef VM
	   "(Error number not translated)");	/* What Is the VM equiv? */
#define ER_NO_TRANS_DONE
#endif /* VM */

#ifdef VMS
#ifdef MULTINET
	   vms_errno_string());
#else
	   ((SOCKET_ERRNO > 0 && SOCKET_ERRNO <= 65) ?
	    strerror(SOCKET_ERRNO) : "(Error number not translated)"));
#endif /* MULTINET */
#define ER_NO_TRANS_DONE
#endif /* VMS */

#ifdef HAVE_STRERROR
	   strerror(SOCKET_ERRNO));
#define ER_NO_TRANS_DONE
#endif /* HAVE_STRERROR */

#ifndef ER_NO_TRANS_DONE
	   (SOCKET_ERRNO < sys_nerr ?
	    sys_errlist[SOCKET_ERRNO] : "Unknown error" ));
#endif /* !ER_NO_TRANS_DONE */

#ifdef VMS
#ifndef MULTINET
    CTRACE(tfp,
	   "         Unix error number (SOCKET_ERRNO) = %ld dec\n",
	   SOCKET_ERRNO);
    CTRACE(tfp,
	   "         VMS error (vaxc$errno)    = %lx hex\n",
	   vaxc$errno);
#endif /* MULTINET */
#endif /* VMS */

#ifdef VMS
    /*
    **	uerrno and errno happen to be zero if vmserrno <> 0
    */
#ifdef MULTINET
    return -vmserrno;
#else
    return -vaxc$errno;
#endif /* MULTINET */
#else
    return -SOCKET_ERRNO;
#endif /* VMS */
}

/*	Parse a cardinal value				       parse_cardinal()
**	----------------------
**
** On entry,
**	*pp	    points to first character to be interpreted, terminated by
**		    non 0:9 character.
**	*pstatus    points to status already valid
**	maxvalue    gives the largest allowable value.
**
** On exit,
**	*pp	    points to first unread character
**	*pstatus    points to status updated iff bad
*/
PUBLIC unsigned int HTCardinal ARGS3(
	int *,		pstatus,
	char **,	pp,
	unsigned int,	max_value)
{
    unsigned int n;
    if ((**pp<'0') || (**pp>'9')) {	    /* Null string is error */
	*pstatus = -3;	/* No number where one expected */
	return 0;
    }

    n = 0;
    while ((**pp >= '0') && (**pp <= '9'))
	n = n*10 + *((*pp)++) - '0';

    if (n > max_value) {
	*pstatus = -4;	/* Cardinal outside range */
	return 0;
    }

    return n;
}

#ifndef DECNET	/* Function only used below for a trace message */
/*	Produce a string for an Internet address
**	----------------------------------------
**
**  On exit,
**	returns a pointer to a static string which must be copied if
**		it is to be kept.
*/
PUBLIC CONST char * HTInetString ARGS1(
	SockA*, 	soc_in)
{
    static char string[16];
    sprintf(string, "%d.%d.%d.%d",
	    (int)*((unsigned char *)(&soc_in->sin_addr)+0),
	    (int)*((unsigned char *)(&soc_in->sin_addr)+1),
	    (int)*((unsigned char *)(&soc_in->sin_addr)+2),
	    (int)*((unsigned char *)(&soc_in->sin_addr)+3));
    return string;
}
#endif /* !DECNET */

/*	Parse a network node address and port
**	-------------------------------------
**
**  On entry,
**	str	points to a string with a node name or number,
**		with optional trailing colon and port number.
**	soc_in	points to the binary internet or decnet address field.
**
**  On exit,
**	*soc_in is filled in. If no port is specified in str, that
**		field is left unchanged in *soc_in.
*/
PUBLIC int HTParseInet ARGS2(
	SockA *,	soc_in,
	CONST char *,	str)
{
    char *port;
    int dotcount_ip = 0;	/* for dotted decimal IP addr */
#ifndef _WINDOWS_NSL
    char *host = NULL;
    struct hostent  *phost;	/* Pointer to host - See netdb.h */
#endif /* _WINDOWS_NSL */

    if (!str) {
	CTRACE(tfp, "HTParseInet: Can't parse `NULL'.\n");
	return -1;
    }
    if (HTCheckForInterrupt()) {
	CTRACE (tfp, "HTParseInet: INTERRUPTED for '%s'.\n", str);
	return -1;
    }
#ifdef _WINDOWS_NSL
    strncpy(host, str, (size_t)512);
#else
    StrAllocCopy(host, str);	/* Make a copy we can mutilate */
#endif /*  _WINDOWS_NSL */
    /*
    **	Parse port number if present.
    */
    if ((port = strchr(host, ':')) != NULL) {
	*port++ = 0;		/* Chop off port */
	if (port[0] >= '0' && port[0] <= '9') {
#ifdef unix
	    soc_in->sin_port = htons(atol(port));
#else /* VMS: */
#ifdef DECNET
	    soc_in->sdn_objnum = (unsigned char)(strtol(port, (char**)0, 10));
#else
	    soc_in->sin_port = htons((unsigned short)strtol(port,(char**)0,10));
#endif /* Decnet */
#endif /* Unix vs. VMS */
#ifdef SUPPRESS 	/* 1. crashes!?!.  2. Not recommended */
	} else {
	    struct servent * serv = getservbyname(port, (char*)0);
	    if (serv) {
		soc_in->sin_port = serv->s_port;
	    } else {
		CTRACE(tfp, "TCP: Unknown service %s\n", port);
	    }
#endif /* SUPPRESS */
	}
    }

#ifdef DECNET
    /*
    **	Read Decnet node name. @@ Should know about DECnet addresses, but
    **	it's probably worth waiting until the Phase transition from IV to V.
    */
    soc_in->sdn_nam.n_len = min(DN_MAXNAML, strlen(host));  /* <=6 in phase 4 */
    strncpy(soc_in->sdn_nam.n_name, host, soc_in->sdn_nam.n_len + 1);
    CTRACE(tfp, "DECnet: Parsed address as object number %d on host %.6s...\n",
		soc_in->sdn_objnum, host);
#else  /* parse Internet host: */

    if (*host >= '0' && *host <= '9') {   /* Test for numeric node address: */
	char *strptr = host;
	while (*strptr) {
	    if (*strptr == '.') {
		dotcount_ip++;
	    } else if (!isdigit(*strptr)) {
		break;
	    }
	    strptr++;
	}
	if (*strptr) {		/* found non-numeric, assume domain name */
	    dotcount_ip = 0;
	}
    }

    /*
    **	Parse host number if present.
    */
    if (dotcount_ip == 3) {   /* Numeric node address: */

#ifdef DJGPP
	soc_in->sin_addr.s_addr = htonl(aton(host));
#else
#ifdef DGUX_OLD
	soc_in->sin_addr.s_addr = inet_addr(host).s_addr; /* See arpa/inet.h */
#else
#ifdef GUSI
	soc_in->sin_addr = inet_addr(host);		/* See netinet/in.h */
#else
	soc_in->sin_addr.s_addr = inet_addr(host);	/* See arpa/inet.h */
#endif /* GUSI */
#endif /* DGUX_OLD */
#endif /* DJGPP */
#ifndef _WINDOWS_NSL
	FREE(host);
#endif /* _WINDOWS_NSL */
    } else {		    /* Alphanumeric node name: */
#ifdef MVS	/* Outstanding problem with crash in MVS gethostbyname */
	CTRACE(tfp, "HTParseInet: Calling gethostbyname(%s)\n", host);
#endif /* MVS */

#ifdef NSL_FORK
	/*
	**  Start block for fork-based gethostbyname() with
	**  checks for interrupts. - Tom Zerucha (tz@execpc.com) & FM
	*/
	{
	    /*
	    **	Pipe, child pid, and status buffers.
	    */
	    pid_t fpid, waitret = (pid_t)0;
	    int pfd[2], cstat, cst1 = 0;

	    pipe(pfd);

	    if ((fpid = fork()) == 0 ) {
		/*
		**  Child - for the long call.
		*/
		phost = gethostbyname(host);
		cst1 = 0;
		/*
		**  Return value (or nulls).
		*/
		if (OK_HOST(phost)) {
		    write(pfd[1], phost->h_addr, phost->h_length);
		    _exit(0);
		} else {
		    write(pfd[1], &cst1, 4);
		    _exit(1);	/* return an error code */
		}
	    }

	    /*
	    **	(parent) Wait until lookup finishes, or interrupt.
	    */
	    cstat = 0;
	    while (cstat <= 0) {
		/*
		**  Exit when data sent.
		*/
		IOCTL(pfd[0], FIONREAD, &cstat);
		if (cstat > 0)
		    break;
		/*
		**  Exit if child exited.
		*/
		if ((waitret = waitpid(fpid, &cst1, WNOHANG)) > 0) {
		    break;
		}
		/*
		**  Abort if interrupt key pressed.
		*/
		if (HTCheckForInterrupt()) {
		    CTRACE(tfp, "HTParseInet: INTERRUPTED gethostbyname.\n");
		    kill(fpid , SIGKILL);
		    waitpid(fpid, NULL, 0);
		    FREE(host);
		    close(pfd[0]);
		    close(pfd[1]);
		    return HT_INTERRUPTED;
		}
		/*
		**  Be nice to the system.
		*/
		sleep(1);
	    }
	    if (waitret <= 0) {
		waitret = waitpid(fpid, &cst1, WNOHANG);
	    }
	    if (WIFEXITED(cst1)) {
		CTRACE(tfp, "HTParseInet: NSL_FORK child %d exited, status 0x%x.\n",
			    (int)waitret, cst1);
	    } else if (WIFSIGNALED(cst1)) {
		CTRACE(tfp, "HTParseInet: NSL_FORK child %d got signal, status 0x%x!\n",
			    (int)waitret, cst1);
#ifdef WCOREDUMP
		if (WCOREDUMP(cst1)) {
		    CTRACE(tfp, "HTParseInet: NSL_FORK child %d dumped core!\n",
				(int)waitret);
		    }
#endif /* WCOREDUMP */
	    } else if (WIFSTOPPED(cst1)) {
		CTRACE(tfp, "HTParseInet: NSL_FORK child %d is stopped, status 0x%x!\n",
			    (int)waitret, cst1);
	    }
	    /*
	    **	Read as much as we can - should be the address.
	    */
	    IOCTL(pfd[0], FIONREAD, &cstat);
	    if (cstat < 4) {
		CTRACE(tfp, "HTParseInet: NSL_FORK child returns only %d bytes.\n",
			    cstat);
		CTRACE(tfp, "             Trying again without forking.\n");
		phost = gethostbyname(host);	/* See netdb.h */
		if (!OK_HOST(phost)) {
		    CTRACE(tfp, "HTParseInet: Can't find internet node name `%s'.\n",
				host);
		    memset((void *)&soc_in->sin_addr, 0, sizeof(soc_in->sin_addr));
		} else {
		    memcpy((void *)&soc_in->sin_addr,
			   phost->h_addr, phost->h_length);
		}
#ifdef NOTDEFINED
		cstat = read(pfd[0], (void *)&soc_in->sin_addr , 4);
#endif /* NOTDEFINED */
	    } else {
		cstat = read(pfd[0], (void *)&soc_in->sin_addr , cstat);
	    }
	    close(pfd[0]);
	    close(pfd[1]);
	}
	if (soc_in->sin_addr.s_addr == 0) {
	    CTRACE(tfp, "HTParseInet: Can't find internet node name `%s'.\n",
			host);
#ifndef _WINDOWS_NSL
	    FREE(host);
#endif /* _WINDOWS_NSL */
	    return -1;
	}
#ifndef _WINDOWS_NSL
	FREE(host);
#endif /* _WINDOWS_NSL */
#ifdef MVS
	CTRACE(tfp, "HTParseInet: gethostbyname() returned %d\n", phost);
#endif /* MVS */

#else /* Not NSL_FORK: */
#ifdef DJGPP
	soc_in->sin_addr.s_addr = htonl(resolve(host));
	FREE(host);
	if (soc_in->sin_addr.s_addr == 0) {
	    CTRACE(tfp, "HTTPAccess: Can't find internet node name `%s'.\n",host);
	    return -1;  /* Fail? */
	}
#else
#ifdef _WINDOWS_NSL
	{
#ifdef __BORLANDC__
		HANDLE hThread, dwThreadID;
#else
		unsigned long hThread, dwThreadID;
#endif /* __BORLANDC__ */
		phost = (struct hostent *) NULL;
		hThread = CreateThread((void *)NULL, 4096UL,
#ifdef __BORLANDC__
			 (LPTHREAD_START_ROUTINE)_fork_func,
#else
			 (unsigned long (*)())_fork_func,
#endif /* __BORLANDC__ */
			 (void *)NULL, 0UL, (unsigned long *)&dwThreadID);
		if (!hThread)
			 MessageBox((void *)NULL, "CreateThread",
				"CreateThread Failed", 0L);
		while (!phost)
			if (HTCheckForInterrupt())
			 {
			  /* Note that host is a character array and is not freed */
			  /* to avoid possible subthread problems: */
			  if (!CloseHandle(hThread))
				 MessageBox((void *)NULL, "CloseHandle","CloseHandle Failed",
						0L);
			  return HT_INTERRUPTED;
			};
	};
#else /* !_WINDOWS_NSL */
	phost = gethostbyname(host);	/* See netdb.h */
#endif /* _WINDOWS_NSL */
#ifdef MVS
	CTRACE(tfp, "HTParseInet: gethostbyname() returned %d\n", phost);
#endif /* MVS */
	if (!phost) {
	    CTRACE(tfp, "HTParseInet: Can't find internet node name `%s'.\n",
			host);
#ifndef _WINDOWS_NSL
	    FREE(host);
#endif /* _WINDOWS_NSL */
	    return -1;	/* Fail? */
	}
#ifndef _WINDOWS_NSL
	FREE(host);
#endif /* _WINDOWS_NSL */
#if defined(VMS) && defined(CMU_TCP)
	/*
	**  In LIBCMU, phost->h_length contains not the length of one address
	**  (four bytes) but the number of bytes in *h_addr, i.e. some multiple
	**  of four. Thus we need to hard code the value here, and remember to
	**  change it if/when IP addresses change in size. :-(	LIBCMU is no
	**  longer supported, and CMU users are encouraged to obtain and use
	**  SOCKETSHR/NETLIB instead. - S. Bjorndahl
	*/
	memcpy((void *)&soc_in->sin_addr, phost->h_addr, 4);
#else
	memcpy((void *)&soc_in->sin_addr, phost->h_addr, phost->h_length);
#endif /* VMS && CMU_TCP */
#endif /* DJGPP */
#endif /* NSL_FORK */
    }

    CTRACE(tfp, "HTParseInet: Parsed address as port %d, IP address %d.%d.%d.%d\n",
		(int)ntohs(soc_in->sin_port),
		(int)*((unsigned char *)(&soc_in->sin_addr)+0),
		(int)*((unsigned char *)(&soc_in->sin_addr)+1),
		(int)*((unsigned char *)(&soc_in->sin_addr)+2),
		(int)*((unsigned char *)(&soc_in->sin_addr)+3));
#endif	/* Internet vs. Decnet */

    return 0;	/* OK */
}

/*	Free our name for the host on which we are - FM
**	-------------------------------------------
**
*/
PRIVATE void free_HTTCP_hostname NOARGS
{
    FREE(hostname);
}

/*	Derive the name of the host on which we are
**	-------------------------------------------
**
*/
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64		/* Arbitrary limit */
#endif /* MAXHOSTNAMELEN */

PRIVATE void get_host_details NOARGS
{
    char name[MAXHOSTNAMELEN+1];	/* The name of this host */
#ifdef UCX
    char *domain_name;			/* The name of this host domain */
#endif /* UCX */
#ifdef NEED_HOST_ADDRESS		/* no -- needs name server! */
    struct hostent * phost;		/* Pointer to host -- See netdb.h */
#endif /* NEED_HOST_ADDRESS */
    int namelength = sizeof(name);

    if (hostname)
	return; 			/* Already done */
    gethostname(name, namelength);	/* Without domain */
    StrAllocCopy(hostname, name);
    atexit(free_HTTCP_hostname);
#ifdef UCX
    /*
    **	UCX doesn't give the complete domain name.
    **	Get rest from UCX$BIND_DOM logical.
    */
    if (strchr(hostname,'.') == NULL) { 	  /* Not full address */
	domain_name = getenv("UCX$BIND_DOMAIN");
	if (domain_name != NULL) {
	    StrAllocCat(hostname, ".");
	    StrAllocCat(hostname, domain_name);
	}
     }
#endif /* UCX */
    CTRACE(tfp, "TCP: Local host name is %s\n", hostname);

#ifndef DECNET	/* Decnet ain't got no damn name server 8#OO */
#ifdef NEED_HOST_ADDRESS		/* no -- needs name server! */
    phost = gethostbyname(name);	/* See netdb.h */
    if (!OK_HOST(phost)) {
	CTRACE(tfp, "TCP: Can't find my own internet node address for `%s'!!\n",
		    name);
	return;  /* Fail! */
    }
    StrAllocCopy(hostname, phost->h_name);
    memcpy(&HTHostAddress, &phost->h_addr, phost->h_length);
    CTRACE(tfp, "     Name server says that I am `%s' = %s\n",
		hostname, HTInetString(&HTHostAddress));
#endif /* NEED_HOST_ADDRESS */

#endif /* !DECNET */
}

PUBLIC CONST char * HTHostName NOARGS
{
    get_host_details();
    return hostname;
}

/*
**  Interruptable connect as implemented for Mosaic by Marc Andreesen
**  and hacked in for Lynx years ago by Lou Montulli, and further
**  modified over the years by numerous Lynx lovers. - FM
*/
PUBLIC int HTDoConnect ARGS4(
	CONST char *,	url,
	char *, 	protocol,
	int,		default_port,
	int *,		s)
{
    struct sockaddr_in soc_address;
    struct sockaddr_in *soc_in = &soc_address;
    int status;
    char *line = NULL;
    char *p1 = NULL;
    char *at_sign = NULL;
    char *host = NULL;

    /*
    **	Set up defaults.
    */
    soc_in->sin_family = AF_INET;
    soc_in->sin_port = htons(default_port);

    /*
    **	Get node name and optional port number.
    */
    p1 = HTParse(url, "", PARSE_HOST);
    if ((at_sign = strchr(p1, '@')) != NULL) {
	/*
	**  If there's an @ then use the stuff after it as a hostname.
	*/
	StrAllocCopy(host, (at_sign + 1));
    } else {
	StrAllocCopy(host, p1);
    }
    FREE(p1);

    line = (char *)calloc(1, (strlen(host) + strlen(protocol) + 128));
    if (line == NULL)
	outofmem(__FILE__, "HTDoConnect");
    sprintf (line, "Looking up %s.", host);
    _HTProgress (line);
    status = HTParseInet(soc_in, host);
    if (status) {
	if (status != HT_INTERRUPTED) {
	    sprintf (line, "Unable to locate remote host %s.", host);
	    _HTProgress(line);
	    status = HT_NO_DATA;
	}
	FREE(host);
	FREE(line);
	return status;
    }

    sprintf (line, "Making %s connection to %s.", protocol, host);
    _HTProgress (line);
    FREE(host);

    /*
    **	Now, let's get a socket set up from the server for the data.
    */
    *s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (*s == -1) {
	HTAlert("socket failed.");
	FREE(line);
	return HT_NO_DATA;
    }

#ifndef DOSPATH
#if !defined(NO_IOCTL) || defined(USE_FCNTL)
    /*
    **	Make the socket non-blocking, so the connect can be canceled.
    **	This means that when we issue the connect we should NOT
    **	have to wait for the accept on the other end.
    */
    {
#ifdef USE_FCNTL
	int ret = fcntl(*s, F_SETFL, O_NONBLOCK);
#else
	int val = 1;
	int ret = IOCTL(*s, FIONBIO, &val);
#endif /* USE_FCNTL */
	if (ret == -1)
	    _HTProgress("Could not make connection non-blocking.");
    }
#endif /* !NO_IOCTL || USE_FCNTL */
#endif /* !DOSPATH */

    /*
    **	Issue the connect.  Since the server can't do an instantaneous
    **	accept and we are non-blocking, this will almost certainly return
    **	a negative status.
    */
#ifdef SOCKS
    if (socks_flag) {
	status = Rconnect(*s, (struct sockaddr*)&soc_address,
			  sizeof(soc_address));
	/*
	**  For long Rbind.
	*/
	socks_bind_remoteAddr = soc_address.sin_addr.s_addr;
    } else
#endif /* SOCKS */
    status = connect(*s, (struct sockaddr*)&soc_address, sizeof(soc_address));
#ifndef DJGPP
    /*
    **	According to the Sun man page for connect:
    **	   EINPROGRESS	       The socket is non-blocking and the  con-
    **			       nection cannot be completed immediately.
    **			       It is possible to select(2) for	comple-
    **			       tion  by  selecting the socket for writ-
    **			       ing.
    **	According to the Motorola SVR4 man page for connect:
    **	   EAGAIN	       The socket is non-blocking and the  con-
    **			       nection cannot be completed immediately.
    **			       It is possible to select for  completion
    **			       by  selecting  the  socket  for writing.
    **			       However, this is only  possible	if  the
    **			       socket  STREAMS	module	is  the topmost
    **			       module on  the  protocol  stack	with  a
    **			       write  service  procedure.  This will be
    **			       the normal case.
    */
    if ((status < 0) &&
	(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EAGAIN)) {
	struct timeval timeout;
	int ret;
	int tries=0;

	ret = 0;
	while (ret <= 0) {
	    fd_set writefds;

	    /*
	    **	Protect against an infinite loop.
	    */
	    if (tries++ >= 180000) {
		HTAlert("Connection failed for 180,000 tries.");
		FREE(line);
		return HT_NO_DATA;
	    }

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

	   /*
	   **  If we suspend, then it is possible that select will be
	   **  interrupted.  Allow for this possibility. - JED
	   */
	   if ((ret == -1) && (errno == EINTR))
	     continue;

	    /*
	    **	Again according to the Sun and Motorola man pages for connect:
	    **	   EALREADY	       The socket is non-blocking and a  previ-
	    **			       ous  connection attempt has not yet been
	    **			       completed.
	    **	Thus if the SOCKET_ERRNO is NOT EALREADY we have a real error,
	    **	and should break out here and return that error.
	    **	Otherwise if it is EALREADY keep on trying to complete the
	    **	connection.
	    */
	    if ((ret < 0) && (SOCKET_ERRNO != EALREADY)) {
		status = ret;
		break;
	    } else if (ret > 0) {
		/*
		**  Extra check here for connection success, if we try to
		**  connect again, and get EISCONN, it means we have a
		**  successful connection.  But don't check with SOCKS.
		*/
#ifdef SOCKS
		if (socks_flag) {
		    status = 0;
		} else {
#endif /* SOCKS */
		status = connect(*s, (struct sockaddr*)&soc_address,
				 sizeof(soc_address));
#ifdef UCX
		/*
		**  A UCX feature: Instead of returning EISCONN
		**		 UCX returns EADDRINUSE.
		**  Test for this status also.
		*/
		if ((status < 0) && ((SOCKET_ERRNO == EISCONN) ||
				     (SOCKET_ERRNO == EADDRINUSE)))
#else
		if ((status < 0) && (SOCKET_ERRNO == EISCONN))
#endif /* UCX */
		{
		    status = 0;
		}

		if (status && (SOCKET_ERRNO == EALREADY)) /* new stuff LJM */
		    ret = 0; /* keep going */
		else
		    break;
#ifdef SOCKS
		}
#endif /* SOCKS */
	    }
#ifdef SOCKS
	    else if (!socks_flag)
#else
	    else
#endif /* SOCKS */
	    {
		/*
		**  The select says we aren't ready yet.  Try to connect
		**  again to make sure.  If we don't get EALREADY or EISCONN,
		**  something has gone wrong.  Break out and report it.
		**
		**  For some reason, SVR4 returns EAGAIN here instead of
		**  EALREADY, even though the man page says it should be
		**  EALREADY.
		**
		**  For some reason, UCX pre 3 apparently returns
		**  errno = 18242 instead the EALREADY or EISCONN.
		*/
		status = connect(*s, (struct sockaddr*)&soc_address,
				 sizeof(soc_address));
		if ((status < 0) &&
		    (SOCKET_ERRNO != EALREADY && SOCKET_ERRNO != EAGAIN) &&
#ifdef UCX
		    (SOCKET_ERRNO != 18242) &&
#endif /* UCX */
		    (SOCKET_ERRNO != EISCONN)) {
		    break;
		}
	    }
	    if (HTCheckForInterrupt()) {
		CTRACE(tfp, "*** INTERRUPTED in middle of connect.\n");
		status = HT_INTERRUPTED;
		SOCKET_ERRNO = EINTR;
		break;
	    }
	}
    }
#endif /* !DJGPP */
    if (status < 0) {
	/*
	**  The connect attempt failed or was interrupted,
	**  so close up the socket.
	*/
	NETCLOSE(*s);
    }
#ifndef DOSPATH
#if !defined(NO_IOCTL) || defined(USE_FCNTL)
    else {
	/*
	**  Make the socket blocking again on good connect.
	*/
#ifdef USE_FCNTL
	int ret = fcntl(*s, F_SETFL, 0);
#else
	int val = 0;
	int ret = IOCTL(*s, FIONBIO, &val);
#endif /* USE_FCNTL */
	if (ret == -1)
	    _HTProgress("Could not restore socket to blocking.");
    }
#endif /* !NO_IOCTL || USE_FCNTL */
#endif /* !DOSPATH */

    FREE(line);
    return status;
}

/*
**  This is so interruptible reads can be implemented cleanly.
*/
PUBLIC int HTDoRead ARGS3(
	int,		fildes,
	void *, 	buf,
	unsigned,	nbyte)
{
    int ready, ret;
    fd_set readfds;
    struct timeval timeout;
    int tries=0;
#ifdef UCX
    int nb;
#endif /* UCX, BSN */

    if (fildes <= 0)
	return -1;

    if (HTCheckForInterrupt()) {
	SOCKET_ERRNO = EINTR;
	return (HT_INTERRUPTED);
    }

#if !defined(NO_IOCTL)
    ready = 0;
#else
    ready = 1;
#endif /* bypass for NO_IOCTL */
    while (!ready) {
	/*
	**  Protect against an infinite loop.
	*/
	if (tries++ >= 180000) {
	    HTAlert("Socket read failed for 180,000 tries.");
	    SOCKET_ERRNO = EINTR;
	    return HT_INTERRUPTED;
	}

	/*
	**  If we suspend, then it is possible that select will be
	**  interrupted.  Allow for this possibility. - JED
	*/
	do {
	    timeout.tv_sec = 0;
	    timeout.tv_usec = 100000;
	    FD_ZERO(&readfds);
	    FD_SET(fildes, &readfds);
#ifdef SOCKS
	    if (socks_flag)
		ret = Rselect(FD_SETSIZE,
			      (void *)&readfds, NULL, NULL, &timeout);
	    else
#endif /* SOCKS */
		ret = select(FD_SETSIZE,
			     (void *)&readfds, NULL, NULL, &timeout);
	} while ((ret == -1) && (errno == EINTR));

	if (ret < 0) {
	    return -1;
	} else if (ret > 0) {
	    ready = 1;
	} else if (HTCheckForInterrupt()) {
	    SOCKET_ERRNO = EINTR;
	    return HT_INTERRUPTED;
	}
    }

#if !defined(UCX) || !defined(VAXC)
    return SOCKET_READ (fildes, buf, nbyte);
#else
    /*
    **	VAXC and UCX problem only.
    */
    errno = vaxc$errno = 0;
    nb = SOCKET_READ (fildes, buf, nbyte);
    CTRACE(tfp,
	   "Read - nb,errno,vaxc$errno: %d %d %d\n", nb,errno,vaxc$errno);
    if ((nb <= 0) && TRACE)
	perror ("HTTCP.C:HTDoRead:read");	   /* RJF */
    /*
    **	An errno value of EPIPE and nb < 0 indicates end-of-file on VAXC.
    */
    if ((nb <= 0) && (errno == EPIPE)) {
	nb = 0;
	errno = 0;
    }
    return nb;
#endif /* UCX, BSN */
}

#ifdef SVR4_BSDSELECT
/*
**  This is a fix for the difference between BSD's select() and
**  SVR4's select().  SVR4's select() can never return a value larger
**  than the total number of file descriptors being checked.  So, if
**  you select for read and write on one file descriptor, and both
**  are true, SVR4 select() will only return 1.  BSD select in the
**  same situation will return 2.
**
**	Additionally, BSD select() on timing out, will zero the masks,
**	while SVR4 does not.  This is fixed here as well.
**
**	Set your tabstops to 4 characters to have this code nicely formatted.
**
**	Jerry Whelan, guru@bradley.edu, June 12th, 1993
*/
#ifdef select
#undef select
#endif /* select */

#ifdef SOCKS
#ifdef Rselect
#undef Rselect
#endif /* Rselect */
#endif /* SOCKS */

#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>

PUBLIC int BSDselect ARGS5(
	int,			nfds,
	fd_set *,		readfds,
	fd_set *,		writefds,
	fd_set *,		exceptfds,
	struct timeval *,	timeout)
{
    int rval,
    i;

#ifdef SOCKS
    if (socks_flag)
	rval = Rselect(nfds, readfds, writefds, exceptfds, timeout);
    else
#endif /* SOCKS */
    rval = select(nfds, readfds, writefds, exceptfds, timeout);

    switch (rval) {
	case -1:
	    return(rval);
	    break;

	case 0:
	    if (readfds != NULL)
		FD_ZERO(readfds);
	    if (writefds != NULL)
		FD_ZERO(writefds);
	    if (exceptfds != NULL)
		FD_ZERO(exceptfds);
	    return(rval);
	    break;

	default:
	    for (i = 0, rval = 0; i < nfds; i++) {
		if ((readfds != NULL) && FD_ISSET(i, readfds))
		    rval++;
		if ((writefds != NULL) && FD_ISSET(i, writefds))
		    rval++;
		if ((exceptfds != NULL) && FD_ISSET(i, exceptfds))
		    rval++;

	    }
	    return(rval);
    }
/* Should never get here */
}
#endif /* SVR4_BSDSELECT */