-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo-trace.go
633 lines (531 loc) · 15.4 KB
/
go-trace.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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/pelletier/go-toml/v2"
)
const (
bold = "\033[1m"
boldBlue = "\033[1;34m"
brightCyan = "\033[38;5;14m"
green = "\033[32m"
reset = "\033[0m"
underline = "\033[4m"
)
var (
client = createHTTPClient()
outputWidth = 120
outputDividerWidth = 135
)
// Config struct to hold configuration values
type Config struct {
UseJSON bool `toml:"use_json"`
AlwaysTerse bool `toml:"always_terse"`
AlwaysVerbose bool `toml:"always_verbose"`
Width int `toml:"width"`
}
type Hop struct {
Number int
URL string
StatusCode int
}
type TraceResult struct {
Hops []Hop `json:"hops"`
FinalURL string `json:"finalURL"`
CleanURL string `json:"cleanURL"`
}
// Utility Functions
func ClearTerminal() {
// For Unix-like systems, use ANSI escape codes
fmt.Print("\033[2J\033[H")
// For Windows, use the "cls" command
if runtime.GOOS == "windows" {
cmd := exec.Command("cmd", "/c", "cls")
cmd.Stdout = os.Stdout
cmd.Run()
}
}
func createHTTPClient() *http.Client {
return &http.Client{
Timeout: 8 * time.Second,
Transport: &http.Transport{
ResponseHeaderTimeout: 5 * time.Second,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// Stop following redirects after the first hop
if len(via) >= 1 {
return http.ErrUseLastResponse
}
return nil
},
}
}
// formatURL formats the URL for better presentation
func formatURL(url string) string {
if len(url) <= outputWidth {
return url
}
var formattedURL strings.Builder
lineStart := 0
for i := 0; i < len(url); i += outputWidth {
end := i + outputWidth
if end > len(url) {
end = len(url)
}
if i > 0 {
// Insert additional indentation for the URL continuation
formattedURL.WriteString("\n" + strings.Repeat(" ", 23))
}
formattedURL.WriteString(url[lineStart:end])
lineStart = end
}
return formattedURL.String()
}
// loadConfig reads the configuration file and returns a Config struct
// If the file doesn't exist or some values are missing, default values are used
func loadConfig() (*Config, error) {
// Check if XDG_CONFIG_HOME is set
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
var configDir string
if xdgConfigHome != "" {
configDir = filepath.Join(xdgConfigHome, "go-trace")
} else {
// Get user's home directory
usr, err := user.Current()
if err != nil {
return nil, err
}
configDir = filepath.Join(usr.HomeDir, ".config", "go-trace")
}
// Define config file path in the selected directory
configFilePath := filepath.Join(configDir, "go-trace.toml")
// Read the config file
file, err := os.ReadFile(configFilePath)
if os.IsNotExist(err) {
// go-trace.toml does not exist, return nil config (no error)
return nil, nil
} else if err != nil {
return nil, err
}
// Unmarshal TOML content into Config struct
var config Config
err = toml.Unmarshal(file, &config)
if err != nil {
return nil, err
}
// Set default values if not present
if !config.UseJSON {
config.UseJSON = false // Set the default value
}
if !config.AlwaysTerse {
config.AlwaysTerse = false // Set the default value
}
if !config.AlwaysVerbose {
config.AlwaysVerbose = false // Set the default value
}
if config.Width == 0 {
config.Width = 120 // Set the default value
}
return &config, nil
}
// Try to make a clean URL
func makeCleanURL(url string) string {
return extractParameters(url)
}
func extractParameters(inputURL string) string {
var goodParams string
var additionalText string
// Parse the URL
parsedURL, err := url.Parse(inputURL)
if err != nil {
fmt.Println("Error parsing URL:", err)
return ""
}
// Add scheme and host
additionalText += parsedURL.Scheme + "://" + parsedURL.Host
// Add a trailing slash if there's a non-empty path
if parsedURL.Path != "" {
additionalText += "/"
}
// Extract query parameters
queryParams := parsedURL.Query()
// Iterate over the query parameters
for key, values := range queryParams {
if filterTheParams(key) {
// Add only good parameters and their values
for _, value := range values {
goodParams += "&" + key + "=" + value
}
}
}
// Add path segments
pathSegments := strings.Split(parsedURL.Path, "/")
for _, segment := range pathSegments {
if segment != "" && !strings.HasPrefix(segment, "#") {
// Check if the path already ends with a slash
if !strings.HasSuffix(additionalText, "/") {
additionalText += "/"
}
additionalText += segment
}
}
// Add query parameters if present
if len(goodParams) > 1 {
additionalText += "?" + goodParams[1:]
}
// Add anchor if present
if parsedURL.Fragment != "" {
additionalText += "#" + parsedURL.Fragment
}
return additionalText
}
func filterTheParams(param string) bool {
// List of known bad parts to discard
badParts := []string{
"_kx",
"bbeml",
"cid",
"ck_subscriber_id",
"cmpid",
"dm_i",
"dm_t",
"ea.tracking.id",
"EMLCID",
"EMLDTL",
"fbclid",
"gbraid",
"gclid",
"linkID",
"mailId",
"msclkid",
"mc_cid",
"mcID",
"mc_eid",
"mgparam",
"rfrr",
"ser",
"snr",
"wbraid",
}
isBadPart := false
for _, part := range badParts {
if part == param || strings.HasPrefix(param, "cm_") || strings.HasPrefix(param, "pk_") || strings.HasPrefix(param, "utm_") {
isBadPart = true
break
}
}
return !isBadPart
}
// Output as JSON
func outputAsJSON(traceResult TraceResult) error {
// Marshal the TraceResult struct into a formatted JSON string
jsonString, err := json.MarshalIndent(traceResult, "", " ")
if err != nil {
return err
}
// Print the JSON string
fmt.Println(string(jsonString))
return nil
}
func printUsageMessage() {
fmt.Printf("\n%sUsage%s: go-trace [options] <URL>\n\n\t%sOptions%s:\n\t-h: prints this help message\n\t-j: outputs as JSON\n\t-s: prints only the final/clean URL\n\t-v: shows all hops\n\t-w: sets the width of the URL tab (line wraps here)\n\n\t%sDefaults%s:\n\t-j: Off\n\t-v: Off (Final/Clean URL only)\n\t-w: 120\n\n", underline, reset, underline, reset, underline, reset)
}
func printTraceResult(redirectURL string, hops []Hop, cloudflareStatus bool, viewOption string) {
cleanedURL := makeCleanURL(redirectURL)
if cloudflareStatus {
doCloudFlareError()
}
switch {
case viewOption == "terse":
if cleanedURL != redirectURL {
fmt.Println(cleanedURL)
} else {
fmt.Println(redirectURL)
}
case viewOption == "short":
// Print additional information
fmt.Fprintf(os.Stdout, "\n%sFinal URL%s: %s\n", boldBlue, reset, formatURL(redirectURL))
if cleanedURL != redirectURL {
fmt.Fprintf(os.Stdout, "\n%sClean URL%s: %s\n\n", green, reset, cleanedURL)
}
case viewOption == "verbose":
if len(redirectURL) <= outputWidth {
outputDividerWidth = len(redirectURL) + 15
}
fmt.Printf("\n\t%sHop%s | %sStatus%s | %sURL%s\n", boldBlue, reset, boldBlue, reset, boldBlue, reset)
fmt.Printf("\t%s", strings.Repeat("-", outputDividerWidth))
// Print each hop
for _, hop := range hops {
fmt.Fprintf(
os.Stdout,
"\n\t%s%-3d%s | %-6d | %s\n\t%s\n",
brightCyan,
hop.Number,
reset,
hop.StatusCode,
formatURL(hop.URL),
strings.Repeat("-", outputDividerWidth),
)
}
// Print additional information
fmt.Fprintf(os.Stdout, "\n\t%sFinal URL%s: %s\n", boldBlue, reset, formatURL(redirectURL))
if cleanedURL != redirectURL {
fmt.Fprintf(os.Stdout, "\n\t%sClean URL%s: %s\n", green, reset, cleanedURL)
}
fmt.Printf("\t%s\n", strings.Repeat("-", outputDividerWidth))
}
}
// Tracer Functions
func doCloudFlareError() {
fmt.Println("\nCloudflare protection prevents tracing. Sorry!")
os.Exit(0)
}
func doConnectionRefusedError() {
fmt.Println("\nThe connection was refused (possibly because of DNS). Sorry!")
os.Exit(0)
}
func doTimeout() {
fmt.Println("\nThe request timed out. Sorry!")
os.Exit(0)
}
func doValidationError() {
fmt.Println("\nThere was a certification validation error. Sorry!")
os.Exit(0)
}
func followRedirects(urlStr string) (string, []Hop, bool, error) {
// CF didn't break anything yet.
cloudflareStatus := false // Defaults to false
hops := []Hop{}
number := 1
var previousURL *url.URL
// Use a set to keep track of visited URLs
visitedURLs := make(map[string]int)
// Ensure the initial URL is marked as visited
visitedURLs[urlStr] = 1
for {
// Check if the URL has been visited before
if visitedURLs[urlStr] > 1 {
// Redirect loop detected
hops = append(hops, Hop{
Number: number,
URL: urlStr,
StatusCode: http.StatusLoopDetected,
})
return urlStr, hops, cloudflareStatus, nil
} else {
visitedURLs[urlStr]++
}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return "", nil, cloudflareStatus, fmt.Errorf("error creating request: %s", err)
}
// Set the user agent header
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
resp, err := client.Do(req)
if err != nil {
if strings.Contains(err.Error(), "connection refused") {
doConnectionRefusedError()
return "", nil, cloudflareStatus, nil
}
if err, ok := err.(*url.Error); ok && err.Timeout() {
doTimeout()
return "", nil, cloudflareStatus, nil
}
if strings.Contains(err.Error(), "x509: certificate signed by unknown authority") {
// Handle certificate verification error
doValidationError()
return "", nil, cloudflareStatus, nil
}
// Close response body in case of error
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return "", nil, cloudflareStatus, fmt.Errorf("error accessing URL: %s", err)
}
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
hop := Hop{
Number: number,
URL: urlStr,
StatusCode: resp.StatusCode,
}
hops = append(hops, hop)
if resp.StatusCode >= 300 && resp.StatusCode <= 399 {
location := resp.Header.Get("Location")
if location == "" {
if strings.Contains(resp.Header.Get("Server"), "cloudflare") {
cloudflareStatus = true
}
return "", []Hop{}, cloudflareStatus, nil // Return empty slice of Hop when redirect location is not found
}
if strings.HasPrefix(location, "https://outlook.office365.com") {
// Only include the final request as the last hop
finalHop := Hop{
Number: number + 2, // Increment the hop number for the final request
URL: location,
StatusCode: http.StatusOK, // Set the status code to 200 for the final request
}
hops = append(hops, finalHop)
return location, hops, cloudflareStatus, nil
}
redirectURL, err := handleRelativeRedirect(previousURL, location, req.URL)
if err != nil {
return "", nil, cloudflareStatus, fmt.Errorf("error handling relative redirect: %s", err)
}
// Convert redirectURL to a string
redirectURLString := redirectURL.String()
// Check if the "returnUri" query parameter is present
u, err := url.Parse(redirectURLString)
if err != nil {
return "", nil, cloudflareStatus, fmt.Errorf("error parsing URL: %s", err)
}
queryParams := u.Query()
if returnURI := queryParams.Get("returnUri"); returnURI != "" {
decodedReturnURI, err := url.PathUnescape(returnURI)
if err != nil {
return "", nil, cloudflareStatus, fmt.Errorf("error decoding returnUri: %s", err)
}
decodedReturnURI = strings.ReplaceAll(decodedReturnURI, "%3A", ":")
decodedReturnURI = strings.ReplaceAll(decodedReturnURI, "%2F", "/")
redirectURLString = u.Scheme + "://" + u.Host + u.Path + "?returnUri=" + decodedReturnURI
}
if redirURI := queryParams.Get("redir"); redirURI != "" {
decodedRedirURI, err := url.PathUnescape(redirURI)
if err != nil {
return "", nil, cloudflareStatus, fmt.Errorf("error decoding redir param: %s", err)
}
decodedRedirURI = strings.ReplaceAll(decodedRedirURI, "%3A", ":")
decodedRedirURI = strings.ReplaceAll(decodedRedirURI, "%2F", "/")
redirectURLString = u.Scheme + "://" + u.Host + u.Path + "?redir=" + decodedRedirURI
}
urlStr = redirectURLString
number++
previousURL, err = url.Parse(urlStr)
if err != nil {
return "", nil, cloudflareStatus, fmt.Errorf("error parsing URL: %s", err)
}
continue
}
return urlStr, hops, cloudflareStatus, nil
}
}
func handleRelativeRedirect(previousURL *url.URL, location string, requestURL *url.URL) (*url.URL, error) {
redirectURL, err := url.Parse(location)
if err != nil {
log.Printf("Error parsing redirect URL: %v", err)
return nil, err
}
if redirectURL.Scheme == "" {
// If the scheme is missing, set it to the scheme of the previous URL or the request URL
if previousURL != nil {
redirectURL.Scheme = previousURL.Scheme
} else if requestURL != nil {
redirectURL.Scheme = requestURL.Scheme
} else {
return nil, errors.New("missing scheme for relative redirect")
}
}
if redirectURL.Host == "" {
// If the host is missing, set it to the host of the previous URL or the request URL
if previousURL != nil {
redirectURL.Host = previousURL.Host
} else if requestURL != nil {
redirectURL.Host = requestURL.Host
} else {
return nil, errors.New("missing host for relative redirect")
}
}
return redirectURL, nil
}
func main() {
// Parse command-line arguments
var (
flagHelp bool
flagOutputJSON bool
flagTerse bool
flagVerbose bool
flagWidth int
)
flag.BoolVar(&flagHelp, "h", false, "Show help message")
flag.BoolVar(&flagHelp, "help", false, "Show help message")
flag.BoolVar(&flagOutputJSON, "j", false, "Output results as JSON")
flag.BoolVar(&flagTerse, "s", false, "Output only the final/clean url")
flag.BoolVar(&flagVerbose, "v", false, "Show verbose trace results")
flag.IntVar(&flagWidth, "w", 120, "Width of the URL tab")
// Load configuration from file, if exists
config, err := loadConfig()
if err != nil {
fmt.Printf("Error loading configuration: %s\n", err)
os.Exit(1)
}
// Set flag values based on config, or use default values if config is nil
if config != nil {
flagOutputJSON = config.UseJSON
flagTerse = config.AlwaysTerse
flagVerbose = config.AlwaysVerbose
flagWidth = config.Width
}
flag.Parse()
args := flag.Args()
// Check if there are additional arguments after the URL
if len(args) < 1 {
printUsageMessage()
os.Exit(1)
}
// Get the URL from the command-line arguments
url := args[0]
// Check if there are flags after the URL
if len(args) > 1 {
printUsageMessage()
os.Exit(1)
}
// If help requested, print message and exit
if flagHelp {
printUsageMessage()
os.Exit(0)
}
// Perform the trace
redirectURL, hops, cloudflareStatus, err := followRedirects(url)
if err != nil {
fmt.Printf("Error tracing URL: %s\n", err)
os.Exit(1)
}
traceResult := TraceResult{
Hops: hops,
FinalURL: redirectURL,
CleanURL: makeCleanURL(redirectURL),
}
// Change URL tab width, if required.
if flagWidth != 120 {
outputWidth = flagWidth
outputDividerWidth = flagWidth + 15
}
// Save to JSON if requested
if flagOutputJSON {
outputAsJSON(traceResult)
os.Exit(0)
}
// Print the trace result in terse or tabular format
if flagTerse {
printTraceResult(redirectURL, nil, cloudflareStatus, "terse")
} else if flagVerbose {
ClearTerminal()
printTraceResult(redirectURL, hops, cloudflareStatus, "verbose")
} else {
ClearTerminal()
printTraceResult(redirectURL, nil, cloudflareStatus, "short")
}
}