Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/protocols/utils/fields.go
2842 views
1
package utils
2
3
import (
4
"net"
5
"strings"
6
7
"github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs"
8
iputil "github.com/projectdiscovery/utils/ip"
9
urlutil "github.com/projectdiscovery/utils/url"
10
)
11
12
// JsonFields contains additional metadata fields for JSON output
13
type JsonFields struct {
14
Host string `json:"host,omitempty"`
15
Path string `json:"path,omitempty"`
16
Port string `json:"port,omitempty"`
17
Ip string `json:"ip,omitempty"`
18
Scheme string `json:"scheme,omitempty"`
19
URL string `json:"url,omitempty"`
20
}
21
22
// GetJsonFields returns the json fields for the request
23
func GetJsonFieldsFromURL(URL string) JsonFields {
24
parsed, err := urlutil.Parse(URL)
25
if err != nil {
26
return JsonFields{}
27
}
28
fields := JsonFields{
29
Port: parsed.Port(),
30
Scheme: parsed.Scheme,
31
URL: parsed.String(),
32
Path: parsed.Path,
33
}
34
35
host := parsed.Host
36
host, fields.Port = extractHostPort(host, fields.Port)
37
38
if fields.Port == "" {
39
fields.Port = "80"
40
if fields.Scheme == "https" {
41
fields.Port = "443"
42
}
43
}
44
if iputil.IsIP(host) {
45
fields.Ip = host
46
}
47
48
fields.Host = host
49
return fields
50
}
51
52
// GetJsonFieldsFromMetaInput returns the json fields for the request
53
func GetJsonFieldsFromMetaInput(ctx *contextargs.MetaInput) JsonFields {
54
input := ctx.Input
55
fields := JsonFields{
56
Ip: ctx.CustomIP,
57
}
58
parsed, err := urlutil.Parse(input)
59
if err != nil {
60
return fields
61
}
62
fields.Port = parsed.Port()
63
fields.Scheme = parsed.Scheme
64
fields.URL = parsed.String()
65
fields.Path = parsed.Path
66
67
host := parsed.Host
68
host, fields.Port = extractHostPort(host, fields.Port)
69
70
if fields.Port == "" {
71
fields.Port = "80"
72
if fields.Scheme == "https" {
73
fields.Port = "443"
74
}
75
}
76
if iputil.IsIP(host) {
77
fields.Ip = host
78
}
79
80
fields.Host = host
81
return fields
82
}
83
84
func extractHostPort(host, port string) (string, string) {
85
if !strings.Contains(host, ":") {
86
return host, port
87
}
88
if strings.HasPrefix(host, "[") {
89
if idx := strings.Index(host, "]:"); idx != -1 {
90
if port == "" {
91
port = host[idx+2:]
92
}
93
return host[1:idx], port
94
}
95
if strings.HasSuffix(host, "]") {
96
return host[1 : len(host)-1], port
97
}
98
return host, port
99
}
100
if h, p, err := net.SplitHostPort(host); err == nil {
101
if port == "" {
102
port = p
103
}
104
return h, port
105
}
106
return host, port
107
}
108
109