_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q30300 | NewStaticUpstreams | train | func NewStaticUpstreams(c caddyfile.Dispenser) ([]Upstream, error) {
var upstreams []Upstream
for c.Next() {
upstream := &staticUpstream{
from: "",
upstreamHeaders: make(http.Header),
downstreamHeaders: make(http.Header),
Hosts: nil,
Policy: &Random{},
MaxFail... | go | {
"resource": ""
} |
q30301 | WebservicesInit | train | func (pf *pfdns) WebservicesInit() error {
var ctx = context.Background()
var webservices pfconfigdriver.PfConfWebservices
webservices.PfconfigNS = "config::Pf"
webservices.PfconfigMethod = "hash_element"
webservices.PfconfigHashNS = "webservices"
pfconfigdriver.FetchDecodeSocket(ctx, &webservices)
pf.Webservic... | go | {
"resource": ""
} |
q30302 | addDetectionMechanismsToList | train | func (pf *pfdns) addDetectionMechanismsToList(ctx context.Context, r string) error {
rgx, err := regexp.Compile(r)
if err == nil {
pf.mutex.Lock()
pf.detectionMechanisms = append(pf.detectionMechanisms, rgx)
pf.mutex.Unlock()
} else {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to compile the regexp ... | go | {
"resource": ""
} |
q30303 | newUser | train | func newUser(email string) (User, error) {
user := User{Email: email}
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return user, errors.New("error generating private key: " + err.Error())
}
user.key = privateKey
return user, nil
} | go | {
"resource": ""
} |
q30304 | getUser | train | func getUser(storage Storage, email string) (User, error) {
var user User
// open user reg
userData, err := storage.LoadUser(email)
if err != nil {
if _, ok := err.(ErrNotExist); ok {
// create a new user
return newUser(email)
}
return user, err
}
// load user information
err = json.Unmarshal(userD... | go | {
"resource": ""
} |
q30305 | saveUser | train | func saveUser(storage Storage, user User) error {
// Save the private key and registration
userData := new(UserData)
var err error
userData.Key, err = savePrivateKey(user.key)
if err == nil {
userData.Reg, err = json.MarshalIndent(&user, "", "\t")
}
if err == nil {
err = storage.StoreUser(user.Email, userDat... | go | {
"resource": ""
} |
q30306 | promptUserAgreement | train | func promptUserAgreement(agreementURL string, changed bool) bool {
if changed {
fmt.Printf("The Let's Encrypt Subscriber Agreement has changed:\n %s\n", agreementURL)
fmt.Print("Do you agree to the new terms? (y/n): ")
} else {
fmt.Printf("To continue, you must agree to the Let's Encrypt Subscriber Agreement:\... | go | {
"resource": ""
} |
q30307 | NewSocket | train | func NewSocket(path string) (s *Socket, err error) {
s = &Socket{path: path}
if err = openSocket(s); err != nil {
err = fmt.Errorf("open socket: %s", err)
s.err = err
return
}
return
} | go | {
"resource": ""
} |
q30308 | Close | train | func (s *Socket) Close() error {
if s.err != nil {
// nothing to close
return nil
}
defer s.conn.Close()
if err := s.enc.Flush(); err != nil {
return fmt.Errorf("flush: %s", err)
}
return s.enc.Close()
} | go | {
"resource": ""
} |
q30309 | DialTimeout | train | func DialTimeout(network string, address string, timeout time.Duration) (fcgi *FCGIClient, err error) {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return
}
fcgi = &FCGIClient{conn: conn, keepAlive: false, reqID: 1}
return fcgi, nil
} | go | {
"resource": ""
} |
q30310 | UuidIndex | train | func (rh *RequestHistory) UuidIndex(uuid string) int {
rh.lock.RLock()
defer rh.lock.RUnlock()
return rh.uuidIndexNoLock(uuid)
} | go | {
"resource": ""
} |
q30311 | connectDB | train | func connectDB(configDatabase pfconfigdriver.PfConfDatabase) {
db, err := db.DbFromConfig(ctx)
sharedutils.CheckError(err)
MySQLdatabase = db
} | go | {
"resource": ""
} |
q30312 | initiaLease | train | func initiaLease(dhcpHandler *DHCPHandler, ConfNet pfconfigdriver.RessourseNetworkConf) {
// Need to calculate the end ip because of the ip per role feature
now := time.Now()
endip := binary.BigEndian.Uint32(dhcpHandler.start.To4()) + uint32(dhcpHandler.leaseRange) - uint32(1)
a := make([]byte, 4)
binary.BigEndian... | go | {
"resource": ""
} |
q30313 | ExcludeIP | train | func ExcludeIP(dhcpHandler *DHCPHandler, ipRange string) []net.IP {
excludeIPs, _ := IPsFromRange(ipRange)
for _, excludeIP := range excludeIPs {
if excludeIP != nil {
// Calculate the position for the dhcp pool
position := uint32(binary.BigEndian.Uint32(excludeIP.To4())) - uint32(binary.BigEndian.Uint32(dhc... | go | {
"resource": ""
} |
q30314 | AssignIP | train | func AssignIP(dhcpHandler *DHCPHandler, ipRange string) (map[string]uint32, []net.IP) {
couple := make(map[string]uint32)
var iplist []net.IP
if ipRange != "" {
rgx, _ := regexp.Compile("((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}):((?:[0-9]{1,3}.){3}(?:[0-9]{1,3}))")
ipRangeArray := strings.Split(ipRange, ",")
if l... | go | {
"resource": ""
} |
q30315 | GetCertificate | train | func (cg configGroup) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
cert, err := cg.getCertDuringHandshake(strings.ToLower(clientHello.ServerName), true, true)
return &cert.Certificate, err
} | go | {
"resource": ""
} |
q30316 | checkLimitsForObtainingNewCerts | train | func (cg configGroup) checkLimitsForObtainingNewCerts(name string, cfg *Config) error {
// User can set hard limit for number of certs for the process to issue
if cfg.OnDemandState.MaxObtain > 0 &&
atomic.LoadInt32(&cfg.OnDemandState.ObtainedCount) >= cfg.OnDemandState.MaxObtain {
return fmt.Errorf("%s: maximum c... | go | {
"resource": ""
} |
q30317 | obtainOnDemandCertificate | train | func (cg configGroup) obtainOnDemandCertificate(name string, cfg *Config) (Certificate, error) {
// We must protect this process from happening concurrently, so synchronize.
obtainCertWaitChansMu.Lock()
wait, ok := obtainCertWaitChans[name]
if ok {
// lucky us -- another goroutine is already obtaining the certifi... | go | {
"resource": ""
} |
q30318 | handshakeMaintenance | train | func (cg configGroup) handshakeMaintenance(name string, cert Certificate) (Certificate, error) {
// Check cert expiration
timeLeft := cert.NotAfter.Sub(time.Now().UTC())
if timeLeft < RenewDurationBefore {
log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft)
return cg.r... | go | {
"resource": ""
} |
q30319 | renewDynamicCertificate | train | func (cg configGroup) renewDynamicCertificate(name string, cfg *Config) (Certificate, error) {
obtainCertWaitChansMu.Lock()
wait, ok := obtainCertWaitChans[name]
if ok {
// lucky us -- another goroutine is already renewing the certificate.
// wait for it to finish, then we'll use the new one.
obtainCertWaitCha... | go | {
"resource": ""
} |
q30320 | NewRawClient | train | func NewRawClient(ifi *net.Interface) (*RawClient, error) {
// Open raw socket to send Wake-on-LAN magic packets
var cfg raw.Config
p, err := raw.ListenPacket(ifi, 0x0806, &cfg)
if err != nil {
return nil, err
}
return &RawClient{
ifi: ifi,
p: p,
}, nil
} | go | {
"resource": ""
} |
q30321 | sendDHCP | train | func (c *RawClient) sendDHCP(target net.HardwareAddr, dhcp []byte, dstIP net.IP, srcIP net.IP) error {
proto := 17
udpsrc := uint(67)
udpdst := uint(68)
udp := udphdr{
src: uint16(udpsrc),
dst: uint16(udpdst),
}
udplen := 8 + len(dhcp)
ip := iphdr{
vhl: 0x45,
tos: 0,
id: 0x0000, // the kern... | go | {
"resource": ""
} |
q30322 | setupEdns0Opt | train | func setupEdns0Opt(r *dns.Msg) *dns.OPT {
o := r.IsEdns0()
if o == nil {
r.SetEdns0(4096, true)
o = r.IsEdns0()
}
return o
} | go | {
"resource": ""
} |
q30323 | Rewrite | train | func (rule *edns0LocalRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option {
switch e := s.(type) {
case *dns.EDNS0_LOCAL:
if rule.code == e.Code {
if rule.action == Replace || rule.action == Set {
e.Data = ... | go | {
"resource": ""
} |
q30324 | newEdns0Rule | train | func newEdns0Rule(mode string, args ...string) (Rule, error) {
if len(args) < 2 {
return nil, fmt.Errorf("too few arguments for an EDNS0 rule")
}
ruleType := strings.ToLower(args[0])
action := strings.ToLower(args[1])
switch action {
case Append:
case Replace:
case Set:
default:
return nil, fmt.Errorf("in... | go | {
"resource": ""
} |
q30325 | newEdns0VariableRule | train | func newEdns0VariableRule(mode, action, code, variable string) (*edns0VariableRule, error) {
c, err := strconv.ParseUint(code, 0, 16)
if err != nil {
return nil, err
}
//Validate
if !isValidVariable(variable) {
return nil, fmt.Errorf("unsupported variable name %q", variable)
}
return &edns0VariableRule{mode:... | go | {
"resource": ""
} |
q30326 | ruleData | train | func (rule *edns0VariableRule) ruleData(w dns.ResponseWriter, r *dns.Msg) ([]byte, error) {
req := request.Request{W: w, Req: r}
switch rule.variable {
case queryName:
//Query name is written as ascii string
return []byte(req.QName()), nil
case queryType:
return rule.uint16ToWire(req.QType()), nil
case cl... | go | {
"resource": ""
} |
q30327 | fillEcsData | train | func (rule *edns0SubnetRule) fillEcsData(w dns.ResponseWriter, r *dns.Msg,
ecs *dns.EDNS0_SUBNET) error {
req := request.Request{W: w, Req: r}
family := req.Family()
if (family != 1) && (family != 2) {
return fmt.Errorf("unable to fill data for EDNS0 subnet due to invalid IP family")
}
ecs.Family = uint16(fam... | go | {
"resource": ""
} |
q30328 | Rewrite | train | func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
result := RewriteIgnored
o := setupEdns0Opt(r)
found := false
for _, s := range o.Option {
switch e := s.(type) {
case *dns.EDNS0_SUBNET:
if rule.action == Replace || rule.action == Set {
if rule.fillEcsData(w, r, e) == nil {... | go | {
"resource": ""
} |
q30329 | setup | train | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
pfsso, err := buildPfssoHandler(ctx)
if err != nil {
return err
}
// Declare all pfconfig resources that will be necessary
pfconfigdriver.PfconfigPool.AddRefreshable(ctx, &firewallsso.Firewalls)
pfconfigdriver.Pfconfig... | go | {
"resource": ""
} |
q30330 | buildPfssoHandler | train | func buildPfssoHandler(ctx context.Context) (PfssoHandler, error) {
pfsso := PfssoHandler{}
pfsso.updateCache = cache.New(1*time.Hour, 30*time.Second)
router := httprouter.New()
router.POST("/api/v1/firewall_sso/update", pfsso.handleUpdate)
router.POST("/api/v1/firewall_sso/start", pfsso.handleStart)
router.PO... | go | {
"resource": ""
} |
q30331 | validateInfo | train | func (h PfssoHandler) validateInfo(ctx context.Context, info map[string]string) error {
required := []string{"ip", "mac", "username", "role"}
for _, k := range required {
if _, ok := info[k]; !ok {
return errors.New(fmt.Sprintf("Missing %s in request", k))
}
}
return nil
} | go | {
"resource": ""
} |
q30332 | spawnSso | train | func (h PfssoHandler) spawnSso(ctx context.Context, firewall firewallsso.FirewallSSOInt, info map[string]string, f func(info map[string]string) (bool, error)) {
// Perform a copy of the information hash before spawning the goroutine
infoCopy := map[string]string{}
for k, v := range info {
infoCopy[k] = v
}
go f... | go | {
"resource": ""
} |
q30333 | addInfoToContext | train | func (h PfssoHandler) addInfoToContext(ctx context.Context, info map[string]string) context.Context {
return log.AddToLogContext(ctx, "username", info["username"], "ip", info["ip"], "mac", info["mac"], "role", info["role"])
} | go | {
"resource": ""
} |
q30334 | handleUpdate | train | func (h PfssoHandler) handleUpdate(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleUpdate")
info, timeout, err := h.parseSsoRequest(ctx, r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
ret... | go | {
"resource": ""
} |
q30335 | handleStop | train | func (h PfssoHandler) handleStop(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := r.Context()
defer statsd.NewStatsDTiming(ctx).Send("PfssoHandler.handleStop")
info, _, err := h.parseSsoRequest(ctx, r.Body)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
return
}
c... | go | {
"resource": ""
} |
q30336 | a | train | func a(zone string, ips []net.IP) []dns.RR {
answers := []dns.RR{}
for _, ip := range ips {
r := new(dns.A)
r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeA,
Class: dns.ClassINET, Ttl: 3600}
r.A = ip
answers = append(answers, r)
}
return answers
} | go | {
"resource": ""
} |
q30337 | NewFileStorage | train | func NewFileStorage(caURL *url.URL) (Storage, error) {
return &FileStorage{
Path: filepath.Join(storageBasePath, caURL.Host),
nameLocks: make(map[string]*sync.WaitGroup),
}, nil
} | go | {
"resource": ""
} |
q30338 | site | train | func (s *FileStorage) site(domain string) string {
domain = strings.ToLower(domain)
return filepath.Join(s.sites(), domain)
} | go | {
"resource": ""
} |
q30339 | user | train | func (s *FileStorage) user(email string) string {
if email == "" {
email = emptyEmail
}
email = strings.ToLower(email)
return filepath.Join(s.users(), email)
} | go | {
"resource": ""
} |
q30340 | emailUsername | train | func emailUsername(email string) string {
at := strings.Index(email, "@")
if at == -1 {
return email
} else if at == 0 {
return email[1:]
}
return email[:at]
} | go | {
"resource": ""
} |
q30341 | userRegFile | train | func (s *FileStorage) userRegFile(email string) string {
if email == "" {
email = emptyEmail
}
email = strings.ToLower(email)
fileName := emailUsername(email)
if fileName == "" {
fileName = "registration"
}
return filepath.Join(s.user(email), fileName+".json")
} | go | {
"resource": ""
} |
q30342 | readFile | train | func (s *FileStorage) readFile(file string) ([]byte, error) {
b, err := ioutil.ReadFile(file)
if os.IsNotExist(err) {
return nil, ErrNotExist(err)
}
return b, err
} | go | {
"resource": ""
} |
q30343 | SiteExists | train | func (s *FileStorage) SiteExists(domain string) (bool, error) {
_, err := os.Stat(s.siteCertFile(domain))
if os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
_, err = os.Stat(s.siteKeyFile(domain))
if err != nil {
return false, err
}
return true, nil
} | go | {
"resource": ""
} |
q30344 | LoadSite | train | func (s *FileStorage) LoadSite(domain string) (*SiteData, error) {
var err error
siteData := new(SiteData)
siteData.Cert, err = s.readFile(s.siteCertFile(domain))
if err != nil {
return nil, err
}
siteData.Key, err = s.readFile(s.siteKeyFile(domain))
if err != nil {
return nil, err
}
siteData.Meta, err = s... | go | {
"resource": ""
} |
q30345 | StoreSite | train | func (s *FileStorage) StoreSite(domain string, data *SiteData) error {
err := os.MkdirAll(s.site(domain), 0700)
if err != nil {
return fmt.Errorf("making site directory: %v", err)
}
err = ioutil.WriteFile(s.siteCertFile(domain), data.Cert, 0600)
if err != nil {
return fmt.Errorf("writing certificate file: %v",... | go | {
"resource": ""
} |
q30346 | DeleteSite | train | func (s *FileStorage) DeleteSite(domain string) error {
err := os.Remove(s.siteCertFile(domain))
if err != nil {
if os.IsNotExist(err) {
return ErrNotExist(err)
}
return err
}
return nil
} | go | {
"resource": ""
} |
q30347 | LoadUser | train | func (s *FileStorage) LoadUser(email string) (*UserData, error) {
var err error
userData := new(UserData)
userData.Reg, err = s.readFile(s.userRegFile(email))
if err != nil {
return nil, err
}
userData.Key, err = s.readFile(s.userKeyFile(email))
if err != nil {
return nil, err
}
return userData, nil
} | go | {
"resource": ""
} |
q30348 | StoreUser | train | func (s *FileStorage) StoreUser(email string, data *UserData) error {
err := os.MkdirAll(s.user(email), 0700)
if err != nil {
return fmt.Errorf("making user directory: %v", err)
}
err = ioutil.WriteFile(s.userRegFile(email), data.Reg, 0600)
if err != nil {
return fmt.Errorf("writing user registration file: %v"... | go | {
"resource": ""
} |
q30349 | TryLock | train | func (s *FileStorage) TryLock(name string) (Waiter, error) {
s.nameLocksMu.Lock()
defer s.nameLocksMu.Unlock()
wg, ok := s.nameLocks[name]
if ok {
// lock already obtained, let caller wait on it
return wg, nil
}
// caller gets lock
wg = new(sync.WaitGroup)
wg.Add(1)
s.nameLocks[name] = wg
return nil, nil
... | go | {
"resource": ""
} |
q30350 | Unlock | train | func (s *FileStorage) Unlock(name string) error {
s.nameLocksMu.Lock()
defer s.nameLocksMu.Unlock()
wg, ok := s.nameLocks[name]
if !ok {
return fmt.Errorf("FileStorage: no lock to release for %s", name)
}
wg.Done()
delete(s.nameLocks, name)
return nil
} | go | {
"resource": ""
} |
q30351 | MostRecentUserEmail | train | func (s *FileStorage) MostRecentUserEmail() string {
userDirs, err := ioutil.ReadDir(s.users())
if err != nil {
return ""
}
var mostRecent os.FileInfo
for _, dir := range userDirs {
if !dir.IsDir() {
continue
}
if mostRecent == nil || dir.ModTime().After(mostRecent.ModTime()) {
mostRecent = dir
}
... | go | {
"resource": ""
} |
q30352 | setup | train | func setup(c *caddy.Controller) error {
ctx := log.LoggerNewContext(context.Background())
pfconfigdriver.PfconfigPool.AddStruct(ctx, &pfconfigdriver.Config.Cluster.HostsIp)
pfipset, err := buildPfipsetHandler(ctx)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handle... | go | {
"resource": ""
} |
q30353 | resourceExists | train | func resourceExists(root, path string) bool {
_, err := os.Stat(root + path)
// technically we should use os.IsNotExist(err)
// but we don't handle any other kinds of errors anyway
return err == nil
} | go | {
"resource": ""
} |
q30354 | Refresh | train | func (f *FirewallsContainer) Refresh(ctx context.Context) {
reload := false
f.ids.PfconfigNS = "config::Firewall_SSO"
// If ids changed, we want to reload
if !pfconfigdriver.IsValid(ctx, &f.ids) {
reload = true
}
pfconfigdriver.FetchDecodeSocketCache(ctx, &f.ids)
fssoFactory := NewFactory(ctx)
if f.Struc... | go | {
"resource": ""
} |
q30355 | getPfconfigSocketPath | train | func getPfconfigSocketPath() string {
if pfconfigSocketPathCache != "" {
// Do nothing, cache is populated, will be returned below
} else if sharedutils.EnvOrDefault("PFCONFIG_TESTING", "") == "" {
pfconfigSocketPathCache = pfconfigSocketPath
} else {
fmt.Println("Test flag is on. Using pfconfig test socket pa... | go | {
"resource": ""
} |
q30356 | GetPayload | train | func (q *Query) GetPayload() string {
j, err := json.Marshal(struct {
Encoding string `json:"encoding"`
Method string `json:"method"`
NS string `json:"key"`
}{
Encoding: q.encoding,
Method: q.method,
NS: q.ns,
})
sharedutils.CheckError(err)
return string(j) + "\n"
} | go | {
"resource": ""
} |
q30357 | GetIdentifier | train | func (q *Query) GetIdentifier() string {
return fmt.Sprintf("%s|%s", q.method, q.ns)
} | go | {
"resource": ""
} |
q30358 | connectSocket | train | func connectSocket(ctx context.Context) net.Conn {
timeoutChan := time.After(SocketTimeout)
var c net.Conn
err := errors.New("Not yet connected")
for err != nil {
select {
case <-timeoutChan:
panic("Can't connect to pfconfig socket")
default:
// We try to connect to the pfconfig socket
// If we fai... | go | {
"resource": ""
} |
q30359 | FetchSocket | train | func FetchSocket(ctx context.Context, payload string) []byte {
c := connectSocket(ctx)
// Send our query in the socket
fmt.Fprintf(c, payload)
var buf bytes.Buffer
buf.ReadFrom(c)
// First 4 bytes are a little-endian representing the length of the payload
var length uint32
binary.Read(&buf, binary.LittleEndi... | go | {
"resource": ""
} |
q30360 | metadataFromField | train | func metadataFromField(ctx context.Context, param interface{}, fieldName string) string {
var ov reflect.Value
ov = reflect.ValueOf(param)
for ov.Kind() == reflect.Ptr || ov.Kind() == reflect.Interface {
ov = ov.Elem()
}
// We check if the field was set to a value as this will overide the value in the tag
// ... | go | {
"resource": ""
} |
q30361 | decodeInterface | train | func decodeInterface(ctx context.Context, encoding string, b []byte, o interface{}) {
switch encoding {
case "json":
decodeJsonInterface(ctx, b, o)
default:
panic(fmt.Sprintf("Unknown encoding %s", encoding))
}
} | go | {
"resource": ""
} |
q30362 | decodeJsonInterface | train | func decodeJsonInterface(ctx context.Context, b []byte, o interface{}) {
decoder := json.NewDecoder(bytes.NewReader(b))
for {
if err := decoder.Decode(&o); err == io.EOF {
break
} else if err != nil {
panic(err)
}
}
} | go | {
"resource": ""
} |
q30363 | FetchDecodeSocketCache | train | func FetchDecodeSocketCache(ctx context.Context, o PfconfigObject) (bool, error) {
query := createQuery(ctx, o)
ctx = log.AddToLogContext(ctx, "PfconfigObject", query.GetIdentifier())
// If the resource is still valid and is already loaded
if IsValid(ctx, o) {
return false, nil
}
err := FetchDecodeSocket(ctx,... | go | {
"resource": ""
} |
q30364 | FetchKeys | train | func FetchKeys(ctx context.Context, name string) ([]string, error) {
keys := PfconfigKeys{PfconfigNS: name}
err := FetchDecodeSocket(ctx, &keys)
if err != nil {
return nil, err
}
return keys.Keys, nil
} | go | {
"resource": ""
} |
q30365 | FetchDecodeSocket | train | func FetchDecodeSocket(ctx context.Context, o PfconfigObject) error {
ptrT := reflect.TypeOf(o)
new := reflect.New(ptrT.Elem())
newo := new.Interface().(PfconfigObject)
transferMetadata(ctx, &o, &newo)
reflect.ValueOf(o).Elem().Set(reflect.ValueOf(newo).Elem())
query := createQuery(ctx, o)
jsonResponse := Fe... | go | {
"resource": ""
} |
q30366 | AAAA | train | func AAAA(b ServiceBackend, zone string, state request.Request, previousRecords []dns.RR, opt Options) (records []dns.RR, err error) {
services, err := b.Services(state, false, opt)
if err != nil {
return nil, err
}
for _, serv := range services {
what, ip := serv.HostType()
switch what {
case dns.TypeCN... | go | {
"resource": ""
} |
q30367 | MX | train | func MX(b ServiceBackend, zone string, state request.Request, opt Options) (records, extra []dns.RR, err error) {
services, err := b.Services(state, false, opt)
if err != nil {
return nil, nil, err
}
lookup := make(map[string]bool)
for _, serv := range services {
if !serv.Mail {
continue
}
what, ip := ... | go | {
"resource": ""
} |
q30368 | CNAME | train | func CNAME(b ServiceBackend, zone string, state request.Request, opt Options) (records []dns.RR, err error) {
services, err := b.Services(state, true, opt)
if err != nil {
return nil, err
}
if len(services) > 0 {
serv := services[0]
if ip := net.ParseIP(serv.Host); ip == nil {
records = append(records, se... | go | {
"resource": ""
} |
q30369 | BackendError | train | func BackendError(b ServiceBackend, zone string, rcode int, state request.Request, err error, opt Options) (int, error) {
m := new(dns.Msg)
m.SetRcode(state.Req, rcode)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Ns, _ = SOA(b, zone, state, opt)
state.SizeAndDo(m)
state.W.WriteMsg(m)
... | go | {
"resource": ""
} |
q30370 | hostnameToIP | train | func (network *network) hostnameToIP(rname string) net.IP {
var matchedIP net.IP
match := network.RegexMatchIP.FindStringSubmatch(rname)
if len(match) != 2 {
return nil
}
if network.IPnet.IP.To4() != nil {
matchedIP = net.ParseIP(match[1])
} else {
// TODO: can probably just allocate a []byte and use that... | go | {
"resource": ""
} |
q30371 | ipToHostname | train | func (network *network) ipToHostname(ip net.IP) (name string) {
if ipv4 := ip.To4(); ipv4 != nil {
// replace . to -
name = ipv4.String()
} else {
// assume v6
// ensure zeros are present in string
buf := make([]byte, 0, len(ip)*4)
for i := 0; i < len(ip); i++ {
v := ip[i]
buf = append(buf, hexDigit... | go | {
"resource": ""
} |
q30372 | Ok | train | func (h *health) Ok() bool {
h.RLock()
defer h.RUnlock()
return h.ok
} | go | {
"resource": ""
} |
q30373 | SetOk | train | func (h *health) SetOk(ok bool) {
h.Lock()
defer h.Unlock()
h.ok = ok
} | go | {
"resource": ""
} |
q30374 | poll | train | func (h *health) poll() {
for _, m := range h.h {
if !m.Health() {
h.SetOk(false)
return
}
}
h.SetOk(true)
} | go | {
"resource": ""
} |
q30375 | NewLookupWithOption | train | func NewLookupWithOption(hosts []string, opts Options) Proxy {
p := Proxy{Next: nil}
// TODO(miek): this needs to be unified with upstream.go's NewStaticUpstreams, caddy uses NewHost
// we should copy/make something similar.
upstream := &staticUpstream{
from: ".",
HealthCheck: healthcheck.HealthCheck{
FailT... | go | {
"resource": ""
} |
q30376 | Lookup | train | func (p Proxy) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) {
req := new(dns.Msg)
req.SetQuestion(name, typ)
state.SizeAndDo(req)
state2 := request.Request{W: state.W, Req: req}
return p.lookup(state2)
} | go | {
"resource": ""
} |
q30377 | Forward | train | func (p Proxy) Forward(state request.Request) (*dns.Msg, error) {
return p.lookup(state)
} | go | {
"resource": ""
} |
q30378 | Write | train | func (w internalResponseWriter) Write(b []byte) (int, error) {
if isInternalRedirect(w) {
return 0, nil
}
return w.ResponseWriter.Write(b)
} | go | {
"resource": ""
} |
q30379 | Set | train | func (r replacer) Set(key, value string) {
r.replacements["{"+key+"}"] = value
} | go | {
"resource": ""
} |
q30380 | NewPool | train | func NewPool() Pool {
p := Pool{}
p.lock = timedlock.NewRWLock()
p.lock.Timeout = 1 * time.Second
p.lock.RTimeout = 3 * time.Second
p.lock.PrintErrors = false
p.lock.Panic = false
p.structs = make(map[string]interface{})
return p
} | go | {
"resource": ""
} |
q30381 | ReadLock | train | func (p *Pool) ReadLock(ctx context.Context) (uint64, error) {
return p.lock.RLock()
} | go | {
"resource": ""
} |
q30382 | ReadUnlock | train | func (p *Pool) ReadUnlock(ctx context.Context, id uint64) {
p.lock.RUnlock(id)
} | go | {
"resource": ""
} |
q30383 | AddRefreshable | train | func (p *Pool) AddRefreshable(ctx context.Context, r Refreshable) {
id, err := p.lock.Lock()
if err == nil {
defer p.lock.Unlock(id)
p.refreshables = append(p.refreshables, r)
r.Refresh(ctx)
}
} | go | {
"resource": ""
} |
q30384 | AddStruct | train | func (p *Pool) AddStruct(ctx context.Context, s interface{}) {
id, err := p.lock.Lock()
if err == nil {
defer p.lock.Unlock(id)
addr := fmt.Sprintf("%p", s)
log.LoggerWContext(ctx).Debug("Adding struct with address " + addr + " to the pool")
p.structs[addr] = s
p.refreshStruct(ctx, s)
}
} | go | {
"resource": ""
} |
q30385 | refreshRefreshables | train | func (p *Pool) refreshRefreshables(ctx context.Context) {
for _, r := range p.refreshables {
r.Refresh(ctx)
}
} | go | {
"resource": ""
} |
q30386 | refreshStruct | train | func (p *Pool) refreshStruct(ctx context.Context, s interface{}) {
v := reflect.ValueOf(s)
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
// Check if s itself is a PfconfigObject, otherwise, we cycle though its fields and process them
if o, ok := v.Addr().Interface().(PfconfigObje... | go | {
"resource": ""
} |
q30387 | refreshStructs | train | func (p *Pool) refreshStructs(ctx context.Context) {
for _, o := range p.structs {
p.refreshStruct(ctx, o)
}
} | go | {
"resource": ""
} |
q30388 | acquireWriteLock | train | func (p *Pool) acquireWriteLock(ctx context.Context) (bool, uint64) {
defer func() {
if r := recover(); r != nil {
log.LoggerWContext(ctx).Warn("Couldn't acquire lock for pfconfig pool")
}
}()
id, err := p.lock.Lock()
if err != nil {
panic("Couldn't acquire lock for pfconfig pool")
}
log.LoggerWContext... | go | {
"resource": ""
} |
q30389 | Refresh | train | func (p *Pool) Refresh(ctx context.Context) bool {
log.LoggerWContext(ctx).Debug("Refreshing pfconfig pool")
var locked bool
var id uint64
if locked, id = p.acquireWriteLock(ctx); !locked {
return false
}
log.LoggerWContext(ctx).Debug("Refresh got lock ID", id)
defer func(ctx context.Context) {
log.LoggerWC... | go | {
"resource": ""
} |
q30390 | Match | train | func (r *ComplexRule) Match(req *http.Request) bool {
// validate RequestMatcher
// includes if and path
if !r.RequestMatcher.Match(req) {
return false
}
// validate extensions
if !r.matchExt(req.URL.Path) {
return false
}
// if regex is nil, ignore
if r.Regexp == nil {
return true
}
// otherwise val... | go | {
"resource": ""
} |
q30391 | Typify | train | func Typify(m *dns.Msg, t time.Time) (Type, *dns.OPT) {
if m == nil {
return OtherError, nil
}
opt := m.IsEdns0()
do := false
if opt != nil {
do = opt.Do()
}
if m.Opcode == dns.OpcodeUpdate {
return Update, opt
}
// Check transfer and update first
if m.Opcode == dns.OpcodeNotify {
return Meta, opt
... | go | {
"resource": ""
} |
q30392 | HasListenerWithAddress | train | func HasListenerWithAddress(addr string) bool {
instancesMu.Lock()
defer instancesMu.Unlock()
for _, inst := range instances {
for _, sln := range inst.servers {
if listenerAddrEqual(sln.listener, addr) {
return true
}
}
}
return false
} | go | {
"resource": ""
} |
q30393 | ValidateAndExecuteDirectives | train | func ValidateAndExecuteDirectives(cdyfile Input, inst *Instance, justValidate bool) error {
// If parsing only inst will be nil, create an instance for this function call only.
if justValidate {
inst = &Instance{serverType: cdyfile.ServerType(), wg: new(sync.WaitGroup)}
}
stypeName := cdyfile.ServerType()
sty... | go | {
"resource": ""
} |
q30394 | TransferIn | train | func (z *Zone) TransferIn() error {
if len(z.TransferFrom) == 0 {
return nil
}
m := new(dns.Msg)
m.SetAxfr(z.origin)
z1 := z.Copy()
var (
Err error
tr string
)
Transfer:
for _, tr = range z.TransferFrom {
t := new(dns.Transfer)
c, err := t.In(m, tr)
if err != nil {
log.Printf("[ERROR] Failed t... | go | {
"resource": ""
} |
q30395 | NewResponseRecorder | train | func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
return &ResponseRecorder{
ResponseWriter: w,
status: http.StatusOK,
start: time.Now(),
}
} | go | {
"resource": ""
} |
q30396 | Flush | train | func (r *ResponseRecorder) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
} else {
panic(NonFlusherError{Underlying: r.ResponseWriter}) // should be recovered at the beginning of middleware stack
}
} | go | {
"resource": ""
} |
q30397 | setup | train | func setup(c *caddy.Controller) error {
mdconfigs, err := markdownParse(c)
if err != nil {
return err
}
cfg := httpserver.GetConfig(c)
md := Markdown{
Root: cfg.Root,
FileSys: http.Dir(cfg.Root),
Configs: mdconfigs,
IndexFiles: []string{"index.md"},
}
cfg.AddMiddleware(func(next httpserv... | go | {
"resource": ""
} |
q30398 | HostQualifies | train | func HostQualifies(hostname string) bool {
return hostname != "localhost" && // localhost is ineligible
// hostname must not be empty
strings.TrimSpace(hostname) != "" &&
// must not contain wildcard (*) characters (until CA supports it)
!strings.Contains(hostname, "*") &&
// must not start or end with a ... | go | {
"resource": ""
} |
q30399 | saveCertResource | train | func saveCertResource(storage Storage, cert acme.CertificateResource) error {
// Save cert, private key, and metadata
siteData := &SiteData{
Cert: cert.Certificate,
Key: cert.PrivateKey,
}
var err error
siteData.Meta, err = json.MarshalIndent(&cert, "", "\t")
if err == nil {
err = storage.StoreSite(cert.Do... | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.