-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebServer.go
736 lines (671 loc) · 23 KB
/
webServer.go
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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
cache "github.com/ahmetozer/net-tools-service/cache"
"github.com/ahmetozer/net-tools-service/functions"
)
// pass CMD output to HTTP
func writeCmdOutput(res http.ResponseWriter, pipeReader *io.PipeReader) {
BUFLEN := 1024 // for
buffer := make([]byte, BUFLEN)
defer functions.Recover("Http Flush Panic")
for {
n, err := pipeReader.Read(buffer)
if err != nil {
pipeReader.Close()
break
}
data := buffer[0:n]
res.Write(data)
f, ok := res.(http.Flusher)
if ok {
f.Flush()
}
//reset buffer
for i := 0; i < n; i++ {
buffer[i] = 0
}
}
}
var (
/*
Regexs for checking input
*/
ipv6Regex = `^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$`
ipv4Regex = `^(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4})`
domainRegex = `^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z]$`
portRegex = "^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([1-9][0-9]{3})|([1-9][0-9]{2})|([1-9][0-9])|([1-9]))$"
asnRegex = `^(AS|as)?([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])(\.([1-5]\d{4}|[1-9]\d{0,3}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]|0))?$`
//iframeStyle = "<pre style='white-space: pre-line; text-shadow: 3px 3px 4px #000; font-size: 20px; font-family: Arial, Helvetica, sans-serif; color: #000'>"
iframeStyle = "<pre style='white-space: pre-line; font-size: 20px; font-family: Arial, Helvetica, sans-serif; color: #000'>"
limiter *IPRateLimiter
)
func init() {
if isPortValid(os.Getenv("rate")) {
i, err := strconv.Atoi(os.Getenv("rate"))
if err == nil {
log.Println("Rate limit is setted to " + fmt.Sprint(i))
limiter = newIPRateLimiter(1, i)
} else {
log.Fatalf("\033[1;31mCannot assing your rate limit. Please write number between 1 - 65535\033[0m")
}
} else {
limiter = newIPRateLimiter(1, 1)
}
}
func webServer(logger *log.Logger, lAdr string) *http.Server {
// Crearte New HTTP Router
router := http.NewServeMux()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Server conf checker
if !isFunctionEnabled["IPv4"] && !isFunctionEnabled["IPv6"] {
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code":"NotAcceptable","err":This server does not have a IPv4 and IPv6 connection, so this server is disabled or in maintance"`)
return
}
// All functions to be check connecting IP version except time,whois,nslookup
switch r.URL.Query().Get("funcType") {
case // IPversion control not required services
"time",
"whois",
"",
"nslookup":
default:
if isFunctionEnabled["IPv4"] && !isFunctionEnabled["IPv6"] {
if r.URL.Query().Get("IPVersion") != "IPv4" {
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code":"NotAcceptable","err":"This server only allow IPv4 requests"}`)
return
}
}
if isFunctionEnabled["IPv6"] && !isFunctionEnabled["IPv4"] {
if r.URL.Query().Get("IPVersion") != "IPv6" {
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code":"NotAcceptable","err":"This server only allow IPv6 requests"}`)
return
}
}
if !contains([]string{"IPv4", "IPv6", "IPvDefault"}, r.URL.Query().Get("IPVersion")) {
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongIPVersion"}`)
return
}
}
if !isFunctionEnabled[r.URL.Query().Get("funcType")] {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, `{"code":"Forbidden", "err":"This function is disabled or not found"}`)
return
}
var host = "EMPTY"
switch r.URL.Query().Get("funcType") {
case "client":
mapB, err := json.Marshal(r.Header)
if err != nil {
fmt.Fprintf(w, "{ \"err\": \"%s\"", err)
}
clientIP, clientPort, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
fmt.Fprintf(w, "userip: %q is not IP:port", r.RemoteAddr)
}
fmt.Fprintf(w, "{ \"ip\": \"%s\", \"port\":\"%s\", \"headers\": %s}", net.ParseIP(clientIP), clientPort, mapB)
return
case "svinfo":
default:
// functions require host variable by default
host = r.URL.Query().Get("host")
functions.SetLiveOutputHeaders(w)
/*
Check host input
*/
if host == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest","err":"You have to define host."}`)
return
}
match, _ := regexp.MatchString(ipv4Regex+`|`+ipv6Regex+`|`+domainRegex+`|`+asnRegex, host)
if !match {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest","err":"Host is not IPv4, IPv6, domain or ASN"}`)
return
}
}
storageHash := r.URL.Query().Get("funcType") + " - " + host + " - " + r.URL.Query().Get("IPVersion") // r.RequestURI
/*
Server functions
*/
switch r.URL.Query().Get("funcType") {
// case "svinfo":
// args := []string{"-q"}
// switch r.URL.Query().Get("IPVersion") {
// case "IPv4":
// args = append(args, "-4")
// case "IPv6":
// args = append(args, "-6")
// case "IPvDefault":
// default:
// w.WriteHeader(http.StatusBadRequest)
// fmt.Fprintf(w, `{"code":"BadRequest", "err":"WrongIPVersion"}`)
// return
// }
// if cache.IsCached(storageHash) {
// fmt.Fprint(w, cache.Get(storageHash))
// } else {
// host := "https://ahmetozer.org/cdn-cgi/tracert"
// args = append(args, host)
// cmd := exec.Command("curl", args...)
// //err := cmd.Run()
// out, err := cmd.CombinedOutput()
// if err != nil { // If error occur on ping command.
// // If given input type wich is IPv4 or IPv6 and run type is not match this error will be occur
// if fmt.Sprint(err) == "exit status 2" {
// fmt.Fprintf(w, cache.Set(storageHash, `{"code":"BadRequest", "err":"funcTypeMissMatchExecuted"}`))
// return
// }
// // When the ping command cannot access the server, this error will be occur
// if fmt.Sprint(err) == "exit status 1" {
// fmt.Fprintf(w, cache.Set(storageHash, `{"code":"Down", "err":"BadRequest"}`))
// return
// }
// // If Any un expected occur, this will be shown
// fmt.Fprintf(w, cache.Set(storageHash, `{"code":"InternalServerError","err":"UnknownExit","exitCode":`+fmt.Sprint(err)+`","execOut:`+string(out)+`"}`))
// } else {
// fmt.Fprint(w, cache.Set(storageHash, `{"ip":"`+functions.GetINI(string(out), "ip")+`", "loc":"`+functions.GetINI(string(out), "loc")+`"}`))
// }
// }
// return
case "icmp":
//cmd.Dir = "/empty/"
args := []string{"-l 3", "-c 5", "-i 0.3", "-s 64", "-t 64", "-W 1", "-q"}
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
if !isMayIPv4(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-4")
case "IPv6":
if !isMayIPv6(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-6")
case "IPvDefault":
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"WrongIPVersion"}`)
return
}
if cache.IsCached(storageHash) {
fmt.Fprint(w, cache.Get(storageHash))
} else {
args = append(args, host)
cmd := exec.Command("ping", args...)
//err := cmd.Run()
out, err := cmd.CombinedOutput()
if err != nil { // If error occur on ping command.
// If given input type wich is IPv4 or IPv6 and run type is not match this error will be occur
if fmt.Sprint(err) == "exit status 2" {
fmt.Fprintf(w, cache.Set(storageHash, `{"code":"BadRequest", "err":"funcTypeMissMatchExecuted", "host":"`+host+`"}`))
return
}
// When the ping command cannot access the server, this error will be occur
if fmt.Sprint(err) == "exit status 1" {
fmt.Fprintf(w, cache.Set(storageHash, `{"code":"RemoteHostDown"}`))
return
}
// If Any un expected occur, this will be shown
fmt.Fprintf(w, cache.Set(storageHash, `{"code":"InternalServerError","err":"UnknownExit","exitCode":`+fmt.Sprint(err)+`","execOut:`+string(out)+`"}`))
} else {
// Execute output to convert string
outString := string(out)
// Get only rtt status
mdevLoc := strings.Index(outString, "/mdev =")
rttOut := outString[mdevLoc+8 : mdevLoc+strings.Index(outString[mdevLoc+1:], "ms")]
// parse rtt status
rttOutParsed := strings.Split(rttOut, "/") // [0] rtt min , [1] avg, [2] max, [3] mdev
// Get other data from program output.
transmittedPacketCount := outString[strings.Index(outString, "ping statistics ---")+20 : strings.Index(outString, " packets transmitted,")]
receivedPacketCount := outString[strings.Index(outString, " packets transmitted,")+22 : strings.Index(outString, " received,")]
packetLoss := outString[strings.Index(outString, " received,")+11 : strings.Index(outString, " packet loss,")]
//fmt.Fprint(w)
//fmt.Fprint(w, rttOutParsed[0]+"\n"+transmittedPacketCount+"\n"+recivedPacketCount+"\n"+packetLoss)
fmt.Fprint(w, cache.Set(storageHash, `{"code":"OK", "rttmin":"`+rttOutParsed[0]+`", "rttavg":"`+rttOutParsed[1]+`", "rttmax":"`+rttOutParsed[2]+`", "mdev":"`+
rttOutParsed[3]+`", "packetloss":"`+packetLoss+`", "recivedPacketCount": "`+receivedPacketCount+`", "transmittedPacketCount":"`+transmittedPacketCount+`"}`))
// To debug output
//fmt.Fprint(w, "\n=====================================================\n\n\n"+outString)
}
}
return
case "tcp":
port := r.URL.Query().Get("port")
if port == "" {
port = "443"
}
if !isPortValid(port) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"InvalidPort"}`)
return
}
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
if !isMayIPv4(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
case "IPv6":
if !isMayIPv6(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
case "IPvDefault":
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"WrongIPVersion"}`)
return
}
//Check if it's a domain
if isMayDomain(host) {
// resolve domain, Pre resolvin important for net.Dialer. If its not pre resolved, Resolving time will be add to latency.
ips, err := net.LookupIP(host)
if err != nil {
fmt.Fprintf(w, `{ "code":"DomainResolveErr", "err":"%s" }`, err)
return
}
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
for _, ip := range ips {
host = ip.String()
if isMayOnlyIPv4(host) {
break
}
}
if !isMayOnlyIPv4(host) {
fmt.Fprintf(w, `{"code":"DomainResolveErr", "err":"DomainDoesNotHaveAIPv4"}`)
return
}
case "IPv6":
for _, ip := range ips {
host = ip.String()
if isMayOnlyIPv6(host) {
break
}
}
if !isMayOnlyIPv6(host) {
fmt.Fprintf(w, `{"code":"DomainResolveErr", "err":"DomainDoesNotHaveAIPv6"}`)
return
}
case "IPvDefault":
for _, ip := range ips {
host = ip.String()
if isMayOnlyIPv6(host) {
break
}
}
if !isMayOnlyIPv6(host) {
for _, ip := range ips {
host = ip.String()
if isMayOnlyIPv6(host) {
break
}
}
if !isMayOnlyIPv4(host) {
fmt.Fprintf(w, `{"code":"DomainResolveErr", "err":"DomainDoesNotHaveAIPv4andIPv6"}`)
return
}
}
default:
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongIPVersion"}`)
return
}
}
if isMayIPv6(host) { // Add brackets if IPv6
host = "[" + host + "]"
}
host = host + ":" + port
if cache.IsCached(storageHash) {
fmt.Fprint(w, cache.Get(storageHash))
} else {
d := net.Dialer{Timeout: 5 * time.Second}
dialStartTime := time.Now()
conn, err := d.Dial("tcp", host)
if err != nil {
fmt.Fprintf(w, cache.Set(storageHash, `{ "code"="Down","err":"`+fmt.Sprint(err)+`" }`))
return
}
elapsedTime := time.Since(dialStartTime)
fmt.Fprintf(w, cache.Set(storageHash, `{ "code"="ok","latency":"`+fmt.Sprint(elapsedTime.Milliseconds())+` ms" }`))
defer conn.Close()
}
return
case "webcontrol":
scheme := r.URL.Query().Get("scheme")
if r.URL.Query().Get("scheme") == "" { // If scheme is not given, set to https
scheme = "https"
}
port := r.URL.Query().Get("port")
if port != "" {
if isPortValid(port) {
host = host + ":" + port
} else {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"InvalidPort"}`)
return
}
}
if isHTTPURLScheme(scheme) {
if cache.IsCached(storageHash) {
fmt.Fprint(w, cache.Get(storageHash))
} else {
resp, err := http.Get(scheme + "://" + host)
if err != nil {
fmt.Fprintf(w, cache.Set(storageHash, `{ "code"="Down","err":"`+fmt.Sprint(err)+`" }`))
} else { // Print the HTTP Status Code and Status Name
fmt.Fprintf(w, cache.Set(storageHash, `{ "code":"`+http.StatusText(resp.StatusCode)+`" }`))
}
}
} else {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"SchemeDoesNotMatchHTTPorHTTPS"}`)
}
return
case "time":
date := time.Now()
fmt.Fprintf(w, `{ "time":"`+date.Format("15:04:05")+`","date":"`+date.Format("01/02/2006")+`" }`)
return
case "whois":
args := []string{host}
if r.URL.Query().Get("term") == "" {
w.Header().Set("content-type", "text/html; charset=utf-8")
fmt.Fprintf(w, iframeStyle)
}
cmd := exec.Command("whois", args...)
// Organize pipelines
out, err := cmd.CombinedOutput()
if err != nil {
// If error occur on ping command.
if fmt.Sprint(err) == "exit status 1" {
fmt.Fprintf(w, string(out))
return
}
fmt.Fprintf(w, "{\"code\":\"UnknownExit\",\"exitCode\":\""+fmt.Sprint(err)+"\",\"execOut:\""+string(out)+"\"}")
} else {
// Execute output to convert string
fmt.Fprintf(w, string(out))
}
return
case "nslookup":
args := []string{host}
if r.URL.Query().Get("nameserver") != "" {
nameserver := r.URL.Query().Get("nameserver")
match, _ := regexp.MatchString(ipv4Regex+`|`+ipv6Regex+`|`+domainRegex, nameserver)
if !match {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"Host is not IPv4, IPv6 or domain"}`)
return
}
args = append(args, nameserver)
}
if r.URL.Query().Get("term") == "" {
w.Header().Set("content-type", "text/html; charset=utf-8")
fmt.Fprintf(w, iframeStyle)
}
cmd := exec.Command("nslookup", args...)
out, err := cmd.CombinedOutput()
if err != nil {
// If error occur on command.
if fmt.Sprint(err) == "exit status 1" {
fmt.Fprintf(w, string(out))
return
}
fmt.Fprintf(w, "{\"code\":\"UnknownExit\",\"exitCode\":\""+fmt.Sprint(err)+"\",\"execOut:\""+string(out)+"\"}")
} else {
// Execute output to convert string and send to web.
fmt.Fprintf(w, string(out))
}
return
/*************************
Live output for ping frame
**************************/
case "ping":
args := []string{"-c 10", "-i 0.2"}
if r.URL.Query().Get("isMobile") == "1" { // No resolve domain names to reduce widht of ping output to shown in mobile in better
args = append(args, "-n")
}
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
if !isMayIPv4(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-4")
case "IPv6":
if !isMayIPv6(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-6")
case "IPvDefault":
default:
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongIPVersion"}`)
return
}
// If requests comes from iframe (not term), add style to iframe
if r.URL.Query().Get("term") == "" {
w.Header().Set("content-type", "text/html; charset=utf-8")
fmt.Fprintf(w, iframeStyle)
}
args = append(args, host) // add host to arguments
cmd := exec.Command("ping", args...)
// Organize pipelines
pipeIn, pipeWriter := io.Pipe()
cmd.Stdout = pipeWriter
cmd.Stderr = pipeWriter
// Pass to web output
go functions.HttpExecPipe(w, pipeIn)
// Run commands
cmd.Run()
pipeWriter.Close()
return
/****************************
Live output for tracert frame
*****************************/
case "tracert":
args := []string{}
if r.URL.Query().Get("isMobile") == "1" {
args = append(args, "-n", "-q 1")
} else {
args = append(args, "-q 3")
args = append(args, "-e")
}
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
if !isMayIPv4(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-4")
case "IPv6":
if !isMayIPv6(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-6")
case "IPvDefault":
default:
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongIPVersion"}`)
return
}
if r.URL.Query().Get("term") == "" {
w.Header().Set("content-type", "text/html; charset=utf-8")
fmt.Fprintf(w, iframeStyle)
}
args = append(args, host) // add host to arguments
cmd := exec.Command("traceroute", args...)
// Organize pipelines
pipeIn, pipeWriter := io.Pipe()
cmd.Stdout = pipeWriter
cmd.Stderr = pipeWriter
// Pass to web output
go functions.HttpExecPipe(w, pipeIn) // live output
// Run command
cmd.Run()
pipeWriter.Close()
return
case "mtr":
args := []string{}
if r.URL.Query().Get("isMobile") == "1" {
args = append(args, "-n")
args = append(args, "-r")
} else {
args = append(args, "-e")
args = append(args, "-w")
}
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
if !isMayIPv4(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-4")
case "IPv6":
if !isMayIPv6(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-6")
case "IPvDefault":
default:
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongIPVersion"}`)
return
}
if r.URL.Query().Get("term") == "" {
w.Header().Set("content-type", "text/html; charset=utf-8")
fmt.Fprintf(w, iframeStyle)
}
args = append(args, "-i 1")
args = append(args, "-c 5")
args = append(args, host) // add host to arguments
cmd := exec.Command("mtr", args...)
// Organize pipelines
pipeIn, pipeWriter := io.Pipe()
cmd.Stdout = pipeWriter
cmd.Stderr = pipeWriter
// Pass to web output
go functions.HttpExecPipe(w, pipeIn) // live output
// Run command
cmd.Run()
pipeWriter.Close()
return
case "curl":
args := []string{"-I", "--max-time", "45", "--limit-rate", "5K"} //{"-iH","'Accept: text/plain'", "--max-time", "45", "--limit-rate", "5K"} // Webserver already time out in 60 second. So max time cant be bigger than 60
switch r.URL.Query().Get("IPVersion") {
case "IPv4":
if !isMayIPv4(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-4")
case "IPv6":
if !isMayIPv6(host) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"code":"BadRequest", "err":"IPVersionMissMatch"}`)
return
}
args = append(args, "-6")
case "IPvDefault":
default:
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongIPVersion"}`)
return
}
if isMayOnlyIPv6(host) { // Add brackets if IPv6
host = "[" + host + "]"
}
switch r.URL.Query().Get("reqScheme") {
case "https":
host = "https://" + host
case "http":
host = "http://" + host
default:
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"WrongreqSchemeVersion"}`)
return
}
// If requests comes from iframe (not term), add style to iframe
if r.URL.Query().Get("term") == "" {
w.Header().Set("content-type", "text/html; charset=utf-8")
fmt.Fprintf(w, iframeStyle)
}
args = append(args, host) // add host to arguments
cmd := exec.Command("curl", args...)
// Organize pipelines
pipeIn, pipeWriter := io.Pipe()
cmd.Stdout = pipeWriter
cmd.Stderr = pipeWriter
// Pass to web output
go functions.HttpExecPipe(w, pipeIn)
// Run commands
cmd.Run()
pipeWriter.Close()
return
default:
// if any unknown function name given.
// requestDump, err := httputil.DumpRequest(r, true)
// if err != nil {
// fmt.Println(err)
// }
// fmt.Fprintf(w, string(requestDump))
w.WriteHeader(http.StatusNotAcceptable)
fmt.Fprintf(w, `{"code:"NotAcceptable", err":"FunctionIsNotFound"}`)
return
}
})
router.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, `<title="Net Tools Service"/><h1>Net Tools Service</h1></br><p>For more information, visit <a href="https://ahmetozer.org/">ahmetozer.org</a></br><a href="https://github.com/ahmetozer/net-tools-service/">github.com/ahmetozer/net-tools-service/</a></p>`)
})
router.HandleFunc("/svcheck", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
})
// return as a webServer
return &http.Server{
Addr: lAdr,
Handler: middlewareHTTPHandler(router),
ErrorLog: logger,
/* Close sockets */
ReadTimeout: 5 * time.Second, // Input Time Out
WriteTimeout: 60 * time.Second, // Output Time Out
//IdleTimeout: 15 * time.Second,
}
}
/*
Set HTTP headers to show live output on browser
*/