summaryrefslogtreecommitdiffhomepage
path: root/tunnel/tools/libwg-go/http-proxy.go
blob: 7e2bd32f7a6043aabf6c834bbc8827bf9556086f (plain)
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
package main

import (
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"

        "github.com/elazarl/goproxy"
	"github.com/inconshreveable/go-vhost"

	"golang.zx2c4.com/go118/netip"
	"golang.zx2c4.com/wireguard/device"

	"gopkg.in/olebedev/go-duktape.v3"
)

const (
        APIPA_PREFIX = "169.254.0.0/16"
//        ULA_PREFIX = "fdba:4b51:1606:a61d::/64"
        ULA_PREFIX = "fdba:4b51:1606:0000::/64"

	// Imported from Firefox' ProxyAutoConfig.cpp
	// https://searchfox.org/mozilla-central/source/netwerk/base/ProxyAutoConfig.cpp
	// This Source Code Form is subject to the terms of the Mozilla Public
	// License, v. 2.0. If a copy of the MPL was not distributed with this
	// file, You can obtain one at http://mozilla.org/MPL/2.0/.
	ASCII_PAC_UTILS = "function dnsDomainIs(host, domain) {\n" +
		"    return (host.length >= domain.length &&\n" +
		"            host.substring(host.length - domain.length) == domain);\n" +
		"}\n" +
		"" +
		"function dnsDomainLevels(host) {\n" +
		"    return host.split('.').length - 1;\n" +
		"}\n" +
		"" +
		"function isValidIpAddress(ipchars) {\n" +
		"    var matches = " +
		"/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(ipchars);\n" +
		"    if (matches == null) {\n" +
		"        return false;\n" +
		"    } else if (matches[1] > 255 || matches[2] > 255 || \n" +
		"               matches[3] > 255 || matches[4] > 255) {\n" +
		"        return false;\n" +
		"    }\n" +
		"    return true;\n" +
		"}\n" +
		"" +
		"function convert_addr(ipchars) {\n" +
		"    var bytes = ipchars.split('.');\n" +
		"    var result = ((bytes[0] & 0xff) << 24) |\n" +
		"                 ((bytes[1] & 0xff) << 16) |\n" +
		"                 ((bytes[2] & 0xff) <<  8) |\n" +
		"                  (bytes[3] & 0xff);\n" +
		"    return result;\n" +
		"}\n" +
		"" +
		"function isInNet(ipaddr, pattern, maskstr) {\n" +
		"    if (!isValidIpAddress(pattern) || !isValidIpAddress(maskstr)) {\n" +
		"        return false;\n" +
		"    }\n" +
		"    if (!isValidIpAddress(ipaddr)) {\n" +
		"        ipaddr = dnsResolve(ipaddr);\n" +
		"        if (ipaddr == null) {\n" +
		"            return false;\n" +
		"        }\n" +
		"    }\n" +
		"    var host = convert_addr(ipaddr);\n" +
		"    var pat  = convert_addr(pattern);\n" +
		"    var mask = convert_addr(maskstr);\n" +
		"    return ((host & mask) == (pat & mask));\n" +
		"    \n" +
		"}\n" +
		"" +
		"function isPlainHostName(host) {\n" +
		"    return (host.search('(\\\\.)|:') == -1);\n" +
		"}\n" +
		"" +
		"function isResolvable(host) {\n" +
		"    var ip = dnsResolve(host);\n" +
		"    return (ip != null);\n" +
		"}\n" +
		"" +
		"function localHostOrDomainIs(host, hostdom) {\n" +
		"    return (host == hostdom) ||\n" +
		"           (hostdom.lastIndexOf(host + '.', 0) == 0);\n" +
		"}\n" +
		"" +
		"function shExpMatch(url, pattern) {\n" +
		"   pattern = pattern.replace(/\\./g, '\\\\.');\n" +
		"   pattern = pattern.replace(/\\*/g, '.*');\n" +
		"   pattern = pattern.replace(/\\?/g, '.');\n" +
		"   var newRe = new RegExp('^'+pattern+'$');\n" +
		"   return newRe.test(url);\n" +
		"}\n" +
		"" +
		"var wdays = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6};\n" +
		"var months = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, " +
		"AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11};\n" +
		"" +
		"function weekdayRange() {\n" +
		"    function getDay(weekday) {\n" +
		"        if (weekday in wdays) {\n" +
		"            return wdays[weekday];\n" +
		"        }\n" +
		"        return -1;\n" +
		"    }\n" +
		"    var date = new Date();\n" +
		"    var argc = arguments.length;\n" +
		"    var wday;\n" +
		"    if (argc < 1)\n" +
		"        return false;\n" +
		"    if (arguments[argc - 1] == 'GMT') {\n" +
		"        argc--;\n" +
		"        wday = date.getUTCDay();\n" +
		"    } else {\n" +
		"        wday = date.getDay();\n" +
		"    }\n" +
		"    var wd1 = getDay(arguments[0]);\n" +
		"    var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" +
		"    return (wd1 == -1 || wd2 == -1) ? false\n" +
		"                                    : (wd1 <= wd2) ? (wd1 <= wday && wday " +
		"<= wd2)\n" +
		"                                                   : (wd2 >= wday || wday " +
		">= wd1);\n" +
		"}\n" +
		"" +
		"function dateRange() {\n" +
		"    function getMonth(name) {\n" +
		"        if (name in months) {\n" +
		"            return months[name];\n" +
		"        }\n" +
		"        return -1;\n" +
		"    }\n" +
		"    var date = new Date();\n" +
		"    var argc = arguments.length;\n" +
		"    if (argc < 1) {\n" +
		"        return false;\n" +
		"    }\n" +
		"    var isGMT = (arguments[argc - 1] == 'GMT');\n" +
		"\n" +
		"    if (isGMT) {\n" +
		"        argc--;\n" +
		"    }\n" +
		"    // function will work even without explict handling of this case\n" +
		"    if (argc == 1) {\n" +
		"        var tmp = parseInt(arguments[0]);\n" +
		"        if (isNaN(tmp)) {\n" +
		"            return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n" +
		"                     getMonth(arguments[0]));\n" +
		"        } else if (tmp < 32) {\n" +
		"            return ((isGMT ? date.getUTCDate() : date.getDate()) == " +
		"tmp);\n" +
		"        } else { \n" +
		"            return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) " +
		"==\n" +
		"                     tmp);\n" +
		"        }\n" +
		"    }\n" +
		"    var year = date.getFullYear();\n" +
		"    var date1, date2;\n" +
		"    date1 = new Date(year,  0,  1,  0,  0,  0);\n" +
		"    date2 = new Date(year, 11, 31, 23, 59, 59);\n" +
		"    var adjustMonth = false;\n" +
		"    for (var i = 0; i < (argc >> 1); i++) {\n" +
		"        var tmp = parseInt(arguments[i]);\n" +
		"        if (isNaN(tmp)) {\n" +
		"            var mon = getMonth(arguments[i]);\n" +
		"            date1.setMonth(mon);\n" +
		"        } else if (tmp < 32) {\n" +
		"            adjustMonth = (argc <= 2);\n" +
		"            date1.setDate(tmp);\n" +
		"        } else {\n" +
		"            date1.setFullYear(tmp);\n" +
		"        }\n" +
		"    }\n" +
		"    for (var i = (argc >> 1); i < argc; i++) {\n" +
		"        var tmp = parseInt(arguments[i]);\n" +
		"        if (isNaN(tmp)) {\n" +
		"            var mon = getMonth(arguments[i]);\n" +
		"            date2.setMonth(mon);\n" +
		"        } else if (tmp < 32) {\n" +
		"            date2.setDate(tmp);\n" +
		"        } else {\n" +
		"            date2.setFullYear(tmp);\n" +
		"        }\n" +
		"    }\n" +
		"    if (adjustMonth) {\n" +
		"        date1.setMonth(date.getMonth());\n" +
		"        date2.setMonth(date.getMonth());\n" +
		"    }\n" +
		"    if (isGMT) {\n" +
		"    var tmp = date;\n" +
		"        tmp.setFullYear(date.getUTCFullYear());\n" +
		"        tmp.setMonth(date.getUTCMonth());\n" +
		"        tmp.setDate(date.getUTCDate());\n" +
		"        tmp.setHours(date.getUTCHours());\n" +
		"        tmp.setMinutes(date.getUTCMinutes());\n" +
		"        tmp.setSeconds(date.getUTCSeconds());\n" +
		"        date = tmp;\n" +
		"    }\n" +
		"    return (date1 <= date2) ? (date1 <= date) && (date <= date2)\n" +
		"                            : (date2 >= date) || (date >= date1);\n" +
		"}\n" +
		"" +
		"function timeRange() {\n" +
		"    var argc = arguments.length;\n" +
		"    var date = new Date();\n" +
		"    var isGMT= false;\n" +
		"" +
		"    if (argc < 1) {\n" +
		"        return false;\n" +
		"    }\n" +
		"    if (arguments[argc - 1] == 'GMT') {\n" +
		"        isGMT = true;\n" +
		"        argc--;\n" +
		"    }\n" +
		"\n" +
		"    var hour = isGMT ? date.getUTCHours() : date.getHours();\n" +
		"    var date1, date2;\n" +
		"    date1 = new Date();\n" +
		"    date2 = new Date();\n" +
		"\n" +
		"    if (argc == 1) {\n" +
		"        return (hour == arguments[0]);\n" +
		"    } else if (argc == 2) {\n" +
		"        return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" +
		"    } else {\n" +
		"        switch (argc) {\n" +
		"        case 6:\n" +
		"            date1.setSeconds(arguments[2]);\n" +
		"            date2.setSeconds(arguments[5]);\n" +
		"        case 4:\n" +
		"            var middle = argc >> 1;\n" +
		"            date1.setHours(arguments[0]);\n" +
		"            date1.setMinutes(arguments[1]);\n" +
		"            date2.setHours(arguments[middle]);\n" +
		"            date2.setMinutes(arguments[middle + 1]);\n" +
		"            if (middle == 2) {\n" +
		"                date2.setSeconds(59);\n" +
		"            }\n" +
		"            break;\n" +
		"        default:\n" +
		"          throw 'timeRange: bad number of arguments'\n" +
		"        }\n" +
		"    }\n" +
		"\n" +
		"    if (isGMT) {\n" +
		"        date.setFullYear(date.getUTCFullYear());\n" +
		"        date.setMonth(date.getUTCMonth());\n" +
		"        date.setDate(date.getUTCDate());\n" +
		"        date.setHours(date.getUTCHours());\n" +
		"        date.setMinutes(date.getUTCMinutes());\n" +
		"        date.setSeconds(date.getUTCSeconds());\n" +
		"    }\n" +
		"    return (date1 <= date2) ? (date1 <= date) && (date <= date2)\n" +
		"                            : (date2 >= date) || (date >= date1);\n" +
		"\n" +
		"}\n"
)

type HttpProxy struct {
        conntrack *Conntrack
	listener net.Listener
	tlsListener net.Listener
	logger *device.Logger
	addrPort netip.AddrPort
        tlsAddrPort netip.AddrPort
	pacFileUrl *url.URL
	ctx *duktape.Context
        defaultProxy *goproxy.ProxyHttpServer
	uidRequest chan AddrPortPair
	uidResponse chan string
}

func NewHttpProxy(uidRequest chan AddrPortPair, uidResponse chan string, logger *device.Logger, pacFileUrl *url.URL) *HttpProxy {
	logger.Verbosef("NewHttpProxy")
	return &HttpProxy{
		listener: nil,
		logger: logger,
		pacFileUrl: pacFileUrl,
		uidRequest: uidRequest,
		uidResponse: uidResponse,
	}
}

var (
	ASCII_PAC_UTILS_NAMES = []string{"dnsDomainIs", "dnsDomainLevels", "isValidIpAddress", "convert_addr", "isInNet", "isPlainHostName", "isResolvable", "localHostOrDomainIs", "shExpMatch", "weekdayRange", "dateRange", "timeRange"}
)

func (p *HttpProxy) SetConntrack(ct *Conntrack) {
        p.conntrack = ct
}

func (p *HttpProxy) GetAddrPort() netip.AddrPort {
	return p.addrPort
}

func newGoProxy(proxyUrl string) *goproxy.ProxyHttpServer {
	proxy := goproxy.NewProxyHttpServer()
	proxy.Verbose = true
	proxy.Tr.Proxy = func(req *http.Request) (*url.URL, error) {
		return url.Parse(proxyUrl)
	}
	proxy.ConnectDial = proxy.NewConnectDialToProxy(proxyUrl)
        proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.Host == "" {
			fmt.Fprintln(w, "Cannot handle requests without Host header, e.g., HTTP 1.0")
			return
		}
		req.URL.Scheme = "http"
		req.URL.Host = req.Host
		proxy.ServeHTTP(w, req)
        })

	return proxy
}

func FindProxyForURL(ctx *duktape.Context, url, host string, logger *device.Logger) (res string, err error) {
	if !ctx.GetGlobalString("FindProxyForURL") {
		ctx.Pop()
		return "", fmt.Errorf("FindProxyForURL not found")
	}

	ctx.PushString(url)
	ctx.PushString(host)

	res = "DIRECT"
	logger.Verbosef("Before pcall")
	r := ctx.Pcall(2)
	logger.Verbosef("After pcall")
	if r == 0 {
		res = ctx.GetString(-1)
	} else if ctx.IsError(-1) {
		ctx.GetPropString(-1, "stack")
		err = fmt.Errorf("Error: %v", ctx.SafeToString(-1))
	} else {
		err = fmt.Errorf("Error: %v", ctx.SafeToString(-1))
	}
	ctx.Pop()
	return
}


func FindProxyForPkg(ctx *duktape.Context, pkg string, logger *device.Logger) (res string, err error) {
	if !ctx.GetGlobalString("FindProxyForPkg") {
		ctx.Pop()
		return "", fmt.Errorf("FindProxyForPkg not found")
	}

	ctx.PushString(pkg)

	res = "DIRECT"
	logger.Verbosef("Before pcall")
	r := ctx.Pcall(1)
	logger.Verbosef("After pcall")
	if r == 0 {
		res = ctx.GetString(-1)
	} else if ctx.IsError(-1) {
		ctx.GetPropString(-1, "stack")
		err = fmt.Errorf("Error: %v", ctx.SafeToString(-1))
	} else {
		err = fmt.Errorf("Error: %v", ctx.SafeToString(-1))
	}
	ctx.Pop()
	return
}

func newPacFileCtx(body string, logger *device.Logger) *duktape.Context {
	ctx := duktape.New()

	ctx.PushGlobalGoFunction("dnsResolve",
		func(ctx *duktape.Context) int {
			// Check stack
			host := ctx.GetString(-1)
			ctx.Pop()
			ips, err := net.LookupIP(host)
			if err != nil {
				return 0
			}

			for _, ip := range(ips) {
				ipStr := string(ip)
				if strings.Contains(ipStr, ".") {
					// Found IPv4
					ctx.PushString(ipStr)
					return 1
				}
			}
			// No IPv4
			return 0
		})

	ctx.PevalString(ASCII_PAC_UTILS)
	// ctx.PushString("ascii_pac_utils.js")
	// ctx.CompileStringFilename(0, ASCII_PAC_UTILS)
	logger.Verbosef("ASCII_PAC_UTILS result is: %v stack:%v", ctx.GetType(-1), ctx.GetTop())
	ctx.Pop()

	// for _, f := range ASCII_PAC_UTILS_NAMES {
	// ctx.GetGlobalString("dnsDomainIs")
	// ctx.PushString("proxy.pac")
				// if err = ctx.Pcompile(0); err != nil {
	// 	logger.Verbosef("Compile failed: %v, %v", err, ctx.SafeToString(-1))
	// } else {
	// 	ctx.PutGlobalString("dnsDomainIs")
	// }

	ctx.PevalString(string(body))
	logger.Verbosef("result is: %v stack:%v", ctx.GetType(-1), ctx.GetTop())
	ctx.Pop()
	FindProxyForURL(ctx, "http://www.jabra.se/", "www.jabra.se", logger)
	return ctx
}


func (p *HttpProxy) Start() (listen_port uint16, err error) {
	p.logger.Verbosef("HttpProxy.Start()")
	listen_port = 0

	var pacFileBody = ""
	if p.pacFileUrl != nil {
		resp, err := http.Get(p.pacFileUrl.String())
		p.logger.Verbosef("pacFile: %v, %v", resp, err)

		if err == nil {
			defer resp.Body.Close()
			ct, ok := resp.Header["Content-Type"]
			if ok && len(ct) == 1 && ct[0] == "application/x-ns-proxy-autoconfig" {
				body, err := io.ReadAll(resp.Body)
				if err == nil {
					pacFileBody = string(body)
				}
			}
		}
	}

	proxyMap := make(map[string]*goproxy.ProxyHttpServer)
	proxyMap["bbc.iplayer.android"] = newGoProxy("http://10.49.124.111:8888")
	proxyMap["no.nrk.tv"] = newGoProxy("http://10.49.124.115:8888")

        // TODO: Debugging NATed tls proxy
	// defaultProxy := goproxy.NewProxyHttpServer()
	// defaultProxy.Verbose = true
        p.defaultProxy = newGoProxy("http://10.49.32.1:8888")
        proxyMap[""] = p.defaultProxy
        
        listen_port, err = p.startRegularProxy(pacFileBody, proxyMap)
        if err != nil {
                return
        }

        err = p.startTlsProxy(pacFileBody, proxyMap)
        if err != nil {
                p.Stop()
        }
        return
}

func (p *HttpProxy) startRegularProxy(pacFileBody string, proxyMap map[string]*goproxy.ProxyHttpServer) (listen_port uint16, err error) {
	p.listener, err = net.Listen("tcp", "[::]:")
	if err != nil {
		return
	}

	p.addrPort, err = netip.ParseAddrPort(p.listener.Addr().String())
	if err != nil {
		return
	}

	listen_port = p.addrPort.Port()

	handler := NewHttpHandler(p, p.defaultProxy, pacFileBody, proxyMap, p.logger)

	go http.Serve(NewUidListener(p, p.listener, handler, p.logger), handler)
        return
}

func (p *HttpProxy) startTlsProxy(pacFileBody string, proxyMap map[string]*goproxy.ProxyHttpServer) (err error) {
        p.tlsListener, err = net.Listen("tcp", "[::]:")
        if err != nil {
                return
        }

	p.tlsAddrPort, err = netip.ParseAddrPort(p.tlsListener.Addr().String())
	if err != nil {
		return
	}

        handler := NewHttpHandler(p, p.defaultProxy, pacFileBody, proxyMap, p.logger)

        go func () {
                for {
                        conn, err := p.tlsListener.Accept()
                
                        if err != nil {
                                p.logger.Verbosef("Error accepting new connection - %v", err)
                                return
                        }

                        go func(conn net.Conn) {
                                if !handler.addConnToProxyMap(conn) {
                                        p.logger.Verbosef("Reject connection: %v", conn)
                                        conn.Close()
                                        return
                                }

                                tlsConn, err := vhost.TLS(conn)
                                if err != nil {
                                        p.logger.Verbosef("Error TLS connection - %v", err)
                                }
                                if tlsConn.Host() == "" {
                                        p.logger.Verbosef("Cannot support non-SNI enabled clients")
                                        return
                                }

                                connectReq := &http.Request{
                                        Method: "CONNECT",
                                        URL: &url.URL{
                                                Opaque: tlsConn.Host(),
                                                Host:   net.JoinHostPort(tlsConn.Host(), "443"),
                                        },
                                        Host:       tlsConn.Host(),
                                        Header:     make(http.Header),
                                        // TODO fetch remote addr from NAT map
                                        RemoteAddr: conn.RemoteAddr().String(),
                                }
                                resp := dumbResponseWriter{tlsConn}
                                handler.ServeHTTP(resp, connectReq)
                        }(conn)
                }
        }()
        return
}

func (p *HttpProxy) Stop() {
	if p.listener != nil {
		p.logger.Verbosef("Close: %v", p.listener)
		p.listener.Close()
//		p.listener = nil
	}
	if p.tlsListener != nil {
		p.logger.Verbosef("Close: %v", p.tlsListener)
		p.tlsListener.Close()
//		p.tlsListener = nil
	}
	if p.ctx != nil {
		p.ctx.DestroyHeap()
		p.ctx = nil
	}
}

type HttpHandler struct {
        p *HttpProxy
	defaultProxy *goproxy.ProxyHttpServer
	logger *device.Logger
	remoteAddrPkgMap map[string]*goproxy.ProxyHttpServer
        apipaPrefix netip.Prefix
        ulaPrefix netip.Prefix
	uidRequest chan AddrPortPair
	uidResponse chan string
	ctx *duktape.Context
	proxyMap map[string]*goproxy.ProxyHttpServer
}

func NewHttpHandler(p *HttpProxy, defaultProxy *goproxy.ProxyHttpServer, pacFileBody string, proxyMap map[string]*goproxy.ProxyHttpServer, logger *device.Logger) *HttpHandler{
        apipa, _ := netip.ParsePrefix(APIPA_PREFIX)
        ula, _ := netip.ParsePrefix(ULA_PREFIX)

	h := &HttpHandler{
                p: p,
		defaultProxy: defaultProxy,
		logger: logger,
		remoteAddrPkgMap: make(map[string]*goproxy.ProxyHttpServer),
                apipaPrefix: apipa,
                ulaPrefix: ula,
		uidRequest: p.uidRequest,
		uidResponse: p.uidResponse,        
		proxyMap: proxyMap,
	}

	if pacFileBody != "" {
		h.ctx = newPacFileCtx(pacFileBody, logger)
	}

        return h
}


func (h *HttpHandler) addConnToProxyMap(c net.Conn) bool {
	h.logger.Verbosef("Accept: %v -> %v", c.RemoteAddr().String(), c.LocalAddr().String())
	local, err := netip.ParseAddrPort(c.RemoteAddr().String())
        if err != nil {
                h.logger.Verbosef("Bad local address: %c", c.RemoteAddr())
                return false
        }

	remote, err := netip.ParseAddrPort(c.LocalAddr().String())
	if err != nil {
                h.logger.Verbosef("Bad remote address: %c", c.LocalAddr())
                return false
        }

        newConn := connection{src: local, dst: remote}
        oldConn, ok := h.p.conntrack.lookupConnection(newConn)
                
        if ok {
                local = oldConn.src
                remote = oldConn.dst
                h.logger.Verbosef("Before NAT: %v -> %v", local, remote)
        } else if remote.Addr().IsLoopback() {
                h.logger.Verbosef("Loopback request")
        } else {
                h.logger.Verbosef("Reject non-NAT, non-loopback request: %v -> %v", local, remote)
                return false
        }
                
        h.logger.Verbosef("uidRequest")
        h.uidRequest <- AddrPortPair{local: local, remote: remote}

        // TODO add timeout?
        select {
        case pkg := <-h.uidResponse:
                h.logger.Verbosef("uidResponse: '%v'", pkg)

                proxy, ok := h.proxyMap[pkg]
                if !ok {
                        proxy = h.findProxyForPkg(pkg)
                }

                if proxy != nil {
                        h.remoteAddrPkgMap[c.RemoteAddr().String()] = proxy
                }
        }

        return true
}
                
func (h *HttpHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	proxy, ok := h.remoteAddrPkgMap[req.RemoteAddr]
	if ok && proxy != nil {
		proxyStr := "Error"
		proxyUrl, err := proxy.Tr.Proxy(nil)
		if err == nil {
			proxyStr = proxyUrl.String()
		}
		h.logger.Verbosef("ServeHTTP remote:%s proxy:%v", req.RemoteAddr, proxyStr)
		delete(h.remoteAddrPkgMap, req.RemoteAddr)

		proxy.ServeHTTP(rw, req)
	} else {
                h.defaultProxy.ServeHTTP(rw, req)
	}
}

func (h *HttpHandler) findProxyForPkg(pkg string) *goproxy.ProxyHttpServer {
	if h.ctx == nil {
		return nil
	}

	find := func() (res string, err error) {
		h.logger.Verbosef("Call FindProxyForPkg %v %v", pkg)
		res, err = FindProxyForPkg(h.ctx, pkg, h.logger)
		h.logger.Verbosef("FindProxyForPkg res %v %v", res, err)
		if err != nil {
			h.logger.Verbosef("FindProxyForPkg result is: %v stack:%v", res, h.ctx.GetTop())
				return "", err
		} else {
			values := strings.Split(strings.Trim(res, " "), ";")
			for _, v := range values {
				value := strings.Trim(v, " ")
				parts := strings.SplitN(value, " ", 2)
				if parts[0] == "PROXY" {
					return parts[1], nil
				}
			}
			}
		return "", fmt.Errorf("No result")
	}
	res, err := find()
	if err != nil {
		return nil
	}

	proxy := newGoProxy("http://" + res)
	h.proxyMap[res] = proxy

	return proxy
}

type AddrPortPair struct {
        local netip.AddrPort
        remote netip.AddrPort
}

// UidListener
type UidListener struct {
        p *HttpProxy
	l net.Listener
	handler *HttpHandler
	logger *device.Logger
}

func NewUidListener(httpProxy *HttpProxy, listener net.Listener, handler *HttpHandler, logger *device.Logger) *UidListener{
	l := &UidListener{
                p: httpProxy,
		l: listener,
		handler: handler,
		logger: logger,
	}

	return l
}

func (l *UidListener) Accept() (net.Conn, error) {
	c, err := l.l.Accept()
	if err != nil {	
                l.logger.Verbosef("Accept failed: %v", err)
                return c, err
	}

        if !l.handler.addConnToProxyMap(c) {
                err = fmt.Errorf("Reject connection: %v", c)
                c.Close()
                return nil, err
        }

	return c, nil
}

func (l *UidListener) Close() error {
	return l.l.Close()
}

func (l *UidListener) Addr() net.Addr {
	return l.l.Addr()
}