func (w *whitelist) dropBoundingSet() error {
	w.pid.Clear(capability.BOUNDS)
	w.pid.Set(capability.BOUNDS, w.keep...)
	return w.pid.Apply(capability.BOUNDS)
}

func ( w * whitelist ) dropBoundingSet ( ) error { w . pid . Clear ( capability . BOUNDS ) w . pid . Set ( capability . BOUNDS , w . keep ... ) return w . pid . Apply ( capability . BOUNDS ) }

// dropBoundingSet drops the capability bounding set to those specified in the whitelist.

dropBoundingSet drops the capability bounding set to those specified in the whitelist .


func (w *whitelist) drop() error {
	w.pid.Clear(allCapabilityTypes)
	w.pid.Set(allCapabilityTypes, w.keep...)
	return w.pid.Apply(allCapabilityTypes)
}

func ( w * whitelist ) drop ( ) error { w . pid . Clear ( allCapabilityTypes ) w . pid . Set ( allCapabilityTypes , w . keep ... ) return w . pid . Apply ( allCapabilityTypes ) }

// drop drops all capabilities for the current process except those specified in the whitelist.

drop drops all capabilities for the current process except those specified in the whitelist .


func (s *CpusetGroup) ensureParent(current, root string) error {
	parent := filepath.Dir(current)
	if filepath.Clean(parent) == root {
		return nil
	}
	if err := s.ensureParent(parent, root); err != nil {
		return err
	}
	if err := os.MkdirAll(current, 0755); err != nil && !os.IsExist(err) {
		return err
	}
	return s.copyIfNeeded(current, parent)
}

func ( s * CpusetGroup ) ensureParent ( current , root string ) error { parent := filepath . Dir ( current ) if filepath . Clean ( parent ) == root { return nil } if err := s . ensureParent ( parent , root ) ; err != nil { return err } if err := os . MkdirAll ( current , 0755 ) ; err != nil && ! os . IsExist ( err ) { return err } return s . copyIfNeeded ( current , parent ) }

// ensureParent makes sure that the parent directory of current is created
// and populated with the proper cpus and mems files copied from
// it's parent.

ensureParent makes sure that the parent directory of current is created and populated with the proper cpus and mems files copied from it s parent .


func (p Process) Pid() (int, error) {
	// math.MinInt32 is returned here, because it's invalid value
	// for the kill() system call.
	if p.ops == nil {
		return math.MinInt32, newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted)
	}
	return p.ops.pid(), nil
}


func (p Process) Signal(sig os.Signal) error {
	if p.ops == nil {
		return newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted)
	}
	return p.ops.signal(sig)
}

func ( p Process ) Signal ( sig os . Signal ) error { if p . ops == nil { return newGenericError ( fmt . Errorf ( " " ) , ProcessNotExecuted ) } return p . ops . signal ( sig ) }

// Signal sends a signal to the Process.


func (p *Process) NewConsole(rootuid int) (Console, error) {
	console, err := newConsole(rootuid, rootuid)
	if err != nil {
		return nil, err
	}
	p.consolePath = console.Path()
	return console, nil
}

func ( p * Process ) NewConsole ( rootuid int ) ( Console , error ) { console , err := newConsole ( rootuid , rootuid ) if err != nil { return nil , err } p . consolePath = console . Path ( ) return console , nil }

// NewConsole creates new console for process and returns it


func setupRootfs(config *configs.Config, console *linuxConsole) (err error) {
	if err := prepareRoot(config); err != nil {
		return newSystemError(err)
	}
	for _, m := range config.Mounts {
		for _, precmd := range m.PremountCmds {
			if err := mountCmd(precmd); err != nil {
				return newSystemError(err)
			}
		}
		if err := mountToRootfs(m, config.Rootfs, config.MountLabel); err != nil {
			return newSystemError(err)
		}

		for _, postcmd := range m.PostmountCmds {
			if err := mountCmd(postcmd); err != nil {
				return newSystemError(err)
			}
		}
	}
	if err := createDevices(config); err != nil {
		return newSystemError(err)
	}
	if err := setupPtmx(config, console); err != nil {
		return newSystemError(err)
	}
	if err := setupDevSymlinks(config.Rootfs); err != nil {
		return newSystemError(err)
	}
	if err := syscall.Chdir(config.Rootfs); err != nil {
		return newSystemError(err)
	}
	if config.NoPivotRoot {
		err = msMoveRoot(config.Rootfs)
	} else {
		err = pivotRoot(config.Rootfs, config.PivotDir)
	}
	if err != nil {
		return newSystemError(err)
	}
	if err := reOpenDevNull(config.Rootfs); err != nil {
		return newSystemError(err)
	}
	if config.Readonlyfs {
		if err := setReadonly(); err != nil {
			return newSystemError(err)
		}
	}
	syscall.Umask(0022)
	return nil
}

func setupRootfs ( config * configs . Config , console * linuxConsole ) ( err error ) { if err := prepareRoot ( config ) ; err != nil { return newSystemError ( err ) } for _ , m := range config . Mounts { for _ , precmd := range m . PremountCmds { if err := mountCmd ( precmd ) ; err != nil { return newSystemError ( err ) } } if err := mountToRootfs ( m , config . Rootfs , config . MountLabel ) ; err != nil { return newSystemError ( err ) } for _ , postcmd := range m . PostmountCmds { if err := mountCmd ( postcmd ) ; err != nil { return newSystemError ( err ) } } } if err := createDevices ( config ) ; err != nil { return newSystemError ( err ) } if err := setupPtmx ( config , console ) ; err != nil { return newSystemError ( err ) } if err := setupDevSymlinks ( config . Rootfs ) ; err != nil { return newSystemError ( err ) } if err := syscall . Chdir ( config . Rootfs ) ; err != nil { return newSystemError ( err ) } if config . NoPivotRoot { err = msMoveRoot ( config . Rootfs ) } else { err = pivotRoot ( config . Rootfs , config . PivotDir ) } if err != nil { return newSystemError ( err ) } if err := reOpenDevNull ( config . Rootfs ) ; err != nil { return newSystemError ( err ) } if config . Readonlyfs { if err := setReadonly ( ) ; err != nil { return newSystemError ( err ) } } syscall . Umask ( 0022 ) return nil }

// setupRootfs sets up the devices, mount points, and filesystems for use inside a
// new mount namespace.

setupRootfs sets up the devices mount points and filesystems for use inside a new mount namespace .


func createDevices(config *configs.Config) error {
	oldMask := syscall.Umask(0000)
	for _, node := range config.Devices {
		// containers running in a user namespace are not allowed to mknod
		// devices so we can just bind mount it from the host.
		if err := createDeviceNode(config.Rootfs, node, config.Namespaces.Contains(configs.NEWUSER)); err != nil {
			syscall.Umask(oldMask)
			return err
		}
	}
	syscall.Umask(oldMask)
	return nil
}

// Create the device nodes in the container.

Create the device nodes in the container .


func createDeviceNode(rootfs string, node *configs.Device, bind bool) error {
	dest := filepath.Join(rootfs, node.Path)
	if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
		return err
	}

	if bind {
		f, err := os.Create(dest)
		if err != nil && !os.IsExist(err) {
			return err
		}
		if f != nil {
			f.Close()
		}
		return syscall.Mount(node.Path, dest, "bind", syscall.MS_BIND, "")
	}
	if err := mknodDevice(dest, node); err != nil {
		if os.IsExist(err) {
			return nil
		}
		return err
	}
	return nil
}

func createDeviceNode ( rootfs string , node * configs . Device , bind bool ) error { dest := filepath . Join ( rootfs , node . Path ) if err := os . MkdirAll ( filepath . Dir ( dest ) , 0755 ) ; err != nil { return err } if bind { f , err := os . Create ( dest ) if err != nil && ! os . IsExist ( err ) { return err } if f != nil { f . Close ( ) } return syscall . Mount ( node . Path , dest , " " , syscall . MS_BIND , " " ) } if err := mknodDevice ( dest , node ) ; err != nil { if os . IsExist ( err ) { return nil } return err } return nil }

// Creates the device node in the rootfs of the container.

Creates the device node in the rootfs of the container .


func remountReadonly(path string) error {
	for i := 0; i < 5; i++ {
		if err := syscall.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil && !os.IsNotExist(err) {
			switch err {
			case syscall.EINVAL:
				// Probably not a mountpoint, use bind-mount
				if err := syscall.Mount(path, path, "", syscall.MS_BIND, ""); err != nil {
					return err
				}
				return syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "")
			case syscall.EBUSY:
				time.Sleep(100 * time.Millisecond)
				continue
			default:
				return err
			}
		}
		return nil
	}
	return fmt.Errorf("unable to mount %s as readonly max retries reached", path)
}

// remountReadonly will bind over the top of an existing path and ensure that it is read-only.

remountReadonly will bind over the top of an existing path and ensure that it is read - only .


func joinCpuset(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "cpuset")
	if err != nil && !cgroups.IsNotFound(err) {
		return err
	}

	s := &fs.CpusetGroup{}

	return s.ApplyDir(path, c, pid)
}

func joinCpuset ( c * configs . Cgroup , pid int ) error { path , err := getSubsystemPath ( c , " " ) if err != nil && ! cgroups . IsNotFound ( err ) { return err } s := & fs . CpusetGroup { } return s . ApplyDir ( path , c , pid ) }

// systemd does not atm set up the cpuset controller, so we must manually
// join it. Additionally that is a very finicky controller where each
// level must have a full setup as the default for a new directory is "no cpus"

systemd does not atm set up the cpuset controller so we must manually join it . Additionally that is a very finicky controller where each level must have a full setup as the default for a new directory is no cpus


func joinBlkio(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "blkio")
	if err != nil {
		return err
	}
	if c.BlkioWeightDevice != "" {
		if err := writeFile(path, "blkio.weight_device", c.BlkioWeightDevice); err != nil {
			return err
		}
	}
	if c.BlkioThrottleReadBpsDevice != "" {
		if err := writeFile(path, "blkio.throttle.read_bps_device", c.BlkioThrottleReadBpsDevice); err != nil {
			return err
		}
	}
	if c.BlkioThrottleWriteBpsDevice != "" {
		if err := writeFile(path, "blkio.throttle.write_bps_device", c.BlkioThrottleWriteBpsDevice); err != nil {
			return err
		}
	}
	if c.BlkioThrottleReadIOpsDevice != "" {
		if err := writeFile(path, "blkio.throttle.read_iops_device", c.BlkioThrottleReadIOpsDevice); err != nil {
			return err
		}
	}
	if c.BlkioThrottleWriteIOpsDevice != "" {
		if err := writeFile(path, "blkio.throttle.write_iops_device", c.BlkioThrottleWriteIOpsDevice); err != nil {
			return err
		}
	}

	return nil
}

func joinBlkio ( c * configs . Cgroup , pid int ) error { path , err := getSubsystemPath ( c , " " ) if err != nil { return err } if c . BlkioWeightDevice != " " { if err := writeFile ( path , " " , c . BlkioWeightDevice ) ; err != nil { return err } } if c . BlkioThrottleReadBpsDevice != " " { if err := writeFile ( path , " " , c . BlkioThrottleReadBpsDevice ) ; err != nil { return err } } if c . BlkioThrottleWriteBpsDevice != " " { if err := writeFile ( path , " " , c . BlkioThrottleWriteBpsDevice ) ; err != nil { return err } } if c . BlkioThrottleReadIOpsDevice != " " { if err := writeFile ( path , " " , c . BlkioThrottleReadIOpsDevice ) ; err != nil { return err } } if c . BlkioThrottleWriteIOpsDevice != " " { if err := writeFile ( path , " " , c . BlkioThrottleWriteIOpsDevice ) ; err != nil { return err } } return nil }

// `BlockIODeviceWeight` property of systemd does not work properly, and systemd
// expects device path instead of major minor numbers, which is also confusing
// for users. So we use fs work around for now.

BlockIODeviceWeight property of systemd does not work properly and systemd expects device path instead of major minor numbers which is also confusing for users . So we use fs work around for now .


func (p *setnsProcess) execSetns() error {
	err := p.cmd.Start()
	p.childPipe.Close()
	if err != nil {
		return newSystemError(err)
	}
	status, err := p.cmd.Process.Wait()
	if err != nil {
		p.cmd.Wait()
		return newSystemError(err)
	}
	if !status.Success() {
		p.cmd.Wait()
		return newSystemError(&exec.ExitError{ProcessState: status})
	}
	var pid *pid
	if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil {
		p.cmd.Wait()
		return newSystemError(err)
	}

	process, err := os.FindProcess(pid.Pid)
	if err != nil {
		return err
	}

	p.cmd.Process = process
	return nil
}

func ( p * setnsProcess ) execSetns ( ) error { err := p . cmd . Start ( ) p . childPipe . Close ( ) if err != nil { return newSystemError ( err ) } status , err := p . cmd . Process . Wait ( ) if err != nil { p . cmd . Wait ( ) return newSystemError ( err ) } if ! status . Success ( ) { p . cmd . Wait ( ) return newSystemError ( & exec . ExitError { ProcessState : status } ) } var pid * pid if err := json . NewDecoder ( p . parentPipe ) . Decode ( & pid ) ; err != nil { p . cmd . Wait ( ) return newSystemError ( err ) } process , err := os . FindProcess ( pid . Pid ) if err != nil { return err } p . cmd . Process = process return nil }

// execSetns runs the process that executes C code to perform the setns calls
// because setns support requires the C process to fork off a child and perform the setns
// before the go runtime boots, we wait on the process to die and receive the child's pid
// over the provided pipe.

execSetns runs the process that executes C code to perform the setns calls because setns support requires the C process to fork off a child and perform the setns before the go runtime boots we wait on the process to die and receive the child s pid over the provided pipe .


func GetAllSubsystems() ([]string, error) {
	f, err := os.Open("/proc/cgroups")
	if err != nil {
		return nil, err
	}
	defer f.Close()

	subsystems := []string{}

	s := bufio.NewScanner(f)
	for s.Scan() {
		if err := s.Err(); err != nil {
			return nil, err
		}
		text := s.Text()
		if text[0] != '#' {
			parts := strings.Fields(text)
			if len(parts) >= 4 && parts[3] != "0" {
				subsystems = append(subsystems, parts[0])
			}
		}
	}
	return subsystems, nil
}

func GetAllSubsystems ( ) ( [ ] string , error ) { f , err := os . Open ( " " ) if err != nil { return nil , err } defer f . Close ( ) subsystems := [ ] string { } s := bufio . NewScanner ( f ) for s . Scan ( ) { if err := s . Err ( ) ; err != nil { return nil , err } text := s . Text ( ) if text [ 0 ] != '#' { parts := strings . Fields ( text ) if len ( parts ) >= 4 && parts [ 3 ] != " " { subsystems = append ( subsystems , parts [ 0 ] ) } } } return subsystems , nil }

// Returns all the cgroup subsystems supported by the kernel


func GetThisCgroupDir(subsystem string) (string, error) {
	f, err := os.Open("/proc/self/cgroup")
	if err != nil {
		return "", err
	}
	defer f.Close()

	return ParseCgroupFile(subsystem, f)
}

func GetThisCgroupDir ( subsystem string ) ( string , error ) { f , err := os . Open ( " " ) if err != nil { return " " , err } defer f . Close ( ) return ParseCgroupFile ( subsystem , f ) }

// Returns the relative path to the cgroup docker is running in.

Returns the relative path to the cgroup docker is running in .


func Capture(userSkip int) Stacktrace {
	var (
		skip   = userSkip + 1 // add one for our own function
		frames []Frame
	)
	for i := skip; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		frames = append(frames, NewFrame(pc, file, line))
	}
	return Stacktrace{
		Frames: frames,
	}
}

func
Capture
(
userSkip
int
)
Stacktrace
{
var
(
skip
=
userSkip
+
1
// add one for our own function
frames
[
]
Frame
)
for
i
:=
skip
;
;
i
++
{
pc
,
file
,
line
,
ok
:=
runtime
.
Caller
(
i
)
if
!
ok
{
break
}
frames
=
append
(
frames
,
NewFrame
(
pc
,
file
,
line
)
)
}
return
Stacktrace
{
Frames
:
frames
,
}
}

// Caputure captures a stacktrace for the current calling go program
//
// skip is the number of frames to skip

Caputure captures a stacktrace for the current calling go program skip is the number of frames to skip


func getCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) {
	contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile))
	if err != nil {
		return 0, err
	}

	return parseUint(strings.TrimSpace(string(contents)), 10, 64)
}

func getCgroupParamUint ( cgroupPath , cgroupFile string ) ( uint64 , error ) { contents , err := ioutil . ReadFile ( filepath . Join ( cgroupPath , cgroupFile ) ) if err != nil { return 0 , err } return parseUint ( strings . TrimSpace ( string ( contents ) ) , 10 , 64 ) }

// Gets a single uint64 value from the specified cgroup file.

Gets a single uint64 value from the specified cgroup file .


func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) {
	groupReader, err := os.Open(groupPath)
	if err != nil {
		return nil, fmt.Errorf("Failed to open group file: %v", err)
	}
	defer groupReader.Close()

	groups, err := ParseGroupFilter(groupReader, func(g Group) bool {
		for _, ag := range additionalGroups {
			if g.Name == ag || strconv.Itoa(g.Gid) == ag {
				return true
			}
		}
		return false
	})
	if err != nil {
		return nil, fmt.Errorf("Unable to find additional groups %v: %v", additionalGroups, err)
	}

	gidMap := make(map[int]struct{})
	for _, ag := range additionalGroups {
		var found bool
		for _, g := range groups {
			// if we found a matched group either by name or gid, take the
			// first matched as correct
			if g.Name == ag || strconv.Itoa(g.Gid) == ag {
				if _, ok := gidMap[g.Gid]; !ok {
					gidMap[g.Gid] = struct{}{}
					found = true
					break
				}
			}
		}
		// we asked for a group but didn't find it. let's check to see
		// if we wanted a numeric group
		if !found {
			gid, err := strconv.Atoi(ag)
			if err != nil {
				return nil, fmt.Errorf("Unable to find group %s", ag)
			}
			// Ensure gid is inside gid range.
			if gid < minId || gid > maxId {
				return nil, ErrRange
			}
			gidMap[gid] = struct{}{}
		}
	}
	gids := []int{}
	for gid := range gidMap {
		gids = append(gids, gid)
	}
	return gids, nil
}

// GetAdditionalGroupsPath looks up a list of groups by name or group id
// against the group file. If a group name cannot be found, an error will be
// returned. If a group id cannot be found, it will be returned as-is.

GetAdditionalGroupsPath looks up a list of groups by name or group id against the group file . If a group name cannot be found an error will be returned . If a group id cannot be found it will be returned as - is .


func addArgsFromEnv(evar string, args *[]string) {
	if e := os.Getenv(evar); e != "" {
		for _, f := range strings.Fields(e) {
			*args = append(*args, f)
		}
	}
	fmt.Printf(">>> criu %v\n", *args)
}

func addArgsFromEnv ( evar string , args * [ ] string ) { if e := os . Getenv ( evar ) ; e != " " { for _ , f := range strings . Fields ( e ) { * args = append ( * args , f ) } } fmt . Printf ( " \n " , * args ) }

// XXX debug support, remove when debugging done.

XXX debug support remove when debugging done .


func InitLabels(options []string) (string, string, error) {
	if !selinux.SelinuxEnabled() {
		return "", "", nil
	}
	processLabel, mountLabel := selinux.GetLxcContexts()
	if processLabel != "" {
		pcon := selinux.NewContext(processLabel)
		mcon := selinux.NewContext(mountLabel)
		for _, opt := range options {
			if opt == "disable" {
				return "", "", nil
			}
			if i := strings.Index(opt, ":"); i == -1 {
				return "", "", fmt.Errorf("Bad SELinux Option")
			}
			con := strings.SplitN(opt, ":", 2)
			pcon[con[0]] = con[1]
			if con[0] == "level" || con[0] == "user" {
				mcon[con[0]] = con[1]
			}
		}
		processLabel = pcon.Get()
		mountLabel = mcon.Get()
	}
	return processLabel, mountLabel, nil
}

func InitLabels ( options [ ] string ) ( string , string , error ) { if ! selinux . SelinuxEnabled ( ) { return " " , " " , nil } processLabel , mountLabel := selinux . GetLxcContexts ( ) if processLabel != " " { pcon := selinux . NewContext ( processLabel ) mcon := selinux . NewContext ( mountLabel ) for _ , opt := range options { if opt == " " { return " " , " " , nil } if i := strings . Index ( opt , " " ) ; i == - 1 { return " " , " " , fmt . Errorf ( " " ) } con := strings . SplitN ( opt , " " , 2 ) pcon [ con [ 0 ] ] = con [ 1 ] if con [ 0 ] == " " || con [ 0 ] == " " { mcon [ con [ 0 ] ] = con [ 1 ] } } processLabel = pcon . Get ( ) mountLabel = mcon . Get ( ) } return processLabel , mountLabel , nil }

// InitLabels returns the process label and file labels to be used within
// the container.  A list of options can be passed into this function to alter
// the labels.  The labels returned will include a random MCS String, that is
// guaranteed to be unique.

InitLabels returns the process label and file labels to be used within the container . A list of options can be passed into this function to alter the labels . The labels returned will include a random MCS String that is guaranteed to be unique .


func SetFileLabel(path string, fileLabel string) error {
	if selinux.SelinuxEnabled() && fileLabel != "" {
		return selinux.Setfilecon(path, fileLabel)
	}
	return nil
}

func SetFileLabel ( path string , fileLabel string ) error { if selinux . SelinuxEnabled ( ) && fileLabel != " " { return selinux . Setfilecon ( path , fileLabel ) } return nil }

// SetFileLabel modifies the "path" label to the specified file label

SetFileLabel modifies the path label to the specified file label


func SetFileCreateLabel(fileLabel string) error {
	if selinux.SelinuxEnabled() {
		return selinux.Setfscreatecon(fileLabel)
	}
	return nil
}

func SetFileCreateLabel ( fileLabel string ) error { if selinux . SelinuxEnabled ( ) { return selinux . Setfscreatecon ( fileLabel ) } return nil }

// Tell the kernel the label for all files to be created


func Relabel(path string, fileLabel string, relabel string) error {
	exclude_path := []string{"/", "/usr", "/etc"}
	if fileLabel == "" {
		return nil
	}
	if !strings.ContainsAny(relabel, "zZ") {
		return nil
	}
	for _, p := range exclude_path {
		if path == p {
			return fmt.Errorf("Relabeling of %s is not allowed", path)
		}
	}
	if strings.Contains(relabel, "z") && strings.Contains(relabel, "Z") {
		return fmt.Errorf("Bad SELinux option z and Z can not be used together")
	}
	if strings.Contains(relabel, "z") {
		c := selinux.NewContext(fileLabel)
		c["level"] = "s0"
		fileLabel = c.Get()
	}
	return selinux.Chcon(path, fileLabel, true)
}

func Relabel ( path string , fileLabel string , relabel string ) error { exclude_path := [ ] string { " " , " " , " " } if fileLabel == " " { return nil } if ! strings . ContainsAny ( relabel , " " ) { return nil } for _ , p := range exclude_path { if path == p { return fmt . Errorf ( " " , path ) } } if strings . Contains ( relabel , " " ) && strings . Contains ( relabel , " " ) { return fmt . Errorf ( " " ) } if strings . Contains ( relabel , " " ) { c := selinux . NewContext ( fileLabel ) c [ " " ] = " " fileLabel = c . Get ( ) } return selinux . Chcon ( path , fileLabel , true ) }

// Change the label of path to the filelabel string.  If the relabel string
// is "z", relabel will change the MCS label to s0.  This will allow all
// containers to share the content.  If the relabel string is a "Z" then
// the MCS label should continue to be used.  SELinux will use this field
// to make sure the content can not be shared by other containes.

Change the label of path to the filelabel string . If the relabel string is z relabel will change the MCS label to s0 . This will allow all containers to share the content . If the relabel string is a Z then the MCS label should continue to be used . SELinux will use this field to make sure the content can not be shared by other containes .


func NetworkGetRoutes() ([]Route, error) {
	s, err := getNetlinkSocket()
	if err != nil {
		return nil, err
	}
	defer s.Close()

	wb := newNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_DUMP)

	msg := newIfInfomsg(syscall.AF_UNSPEC)
	wb.AddData(msg)

	if err := s.Send(wb); err != nil {
		return nil, err
	}

	pid, err := s.GetPid()
	if err != nil {
		return nil, err
	}

	res := make([]Route, 0)

outer:
	for {
		msgs, err := s.Receive()
		if err != nil {
			return nil, err
		}
		for _, m := range msgs {
			if err := s.CheckMessage(m, wb.Seq, pid); err != nil {
				if err == io.EOF {
					break outer
				}
				return nil, err
			}
			if m.Header.Type != syscall.RTM_NEWROUTE {
				continue
			}

			var r Route

			msg := (*RtMsg)(unsafe.Pointer(&m.Data[0:syscall.SizeofRtMsg][0]))

			if msg.Flags&syscall.RTM_F_CLONED != 0 {
				// Ignore cloned routes
				continue
			}

			if msg.Table != syscall.RT_TABLE_MAIN {
				// Ignore non-main tables
				continue
			}

			if msg.Family != syscall.AF_INET {
				// Ignore non-ipv4 routes
				continue
			}

			if msg.Dst_len == 0 {
				// Default routes
				r.Default = true
			}

			attrs, err := syscall.ParseNetlinkRouteAttr(&m)
			if err != nil {
				return nil, err
			}
			for _, attr := range attrs {
				switch attr.Attr.Type {
				case syscall.RTA_DST:
					ip := attr.Value
					r.IPNet = &net.IPNet{
						IP:   ip,
						Mask: net.CIDRMask(int(msg.Dst_len), 8*len(ip)),
					}
				case syscall.RTA_OIF:
					index := int(native.Uint32(attr.Value[0:4]))
					r.Iface, _ = net.InterfaceByIndex(index)
				}
			}
			if r.Default || r.IPNet != nil {
				res = append(res, r)
			}
		}
	}

	return res, nil
}

func
NetworkGetRoutes
(
)
(
[
]
Route
,
error
)
{
s
,
err
:=
getNetlinkSocket
(
)
if
err
!=
{
return
,
err
}
defer
s
.
Close
(
)
wb
:=
newNetlinkRequest
(
syscall
.
RTM_GETROUTE
,
syscall
.
NLM_F_DUMP
)
msg
:=
newIfInfomsg
(
syscall
.
AF_UNSPEC
)
wb
.
AddData
(
msg
)
if
err
:=
s
.
Send
(
wb
)
;
err
!=
{
return
,
err
}
pid
,
err
:=
s
.
GetPid
(
)
if
err
!=
{
return
,
err
}
res
:=
make
(
[
]
Route
,
0
)
outer
:
for
{
msgs
,
err
:=
s
.
Receive
(
)
if
err
!=
{
return
,
err
}
for
_
,
m
:=
range
msgs
{
if
err
:=
s
.
CheckMessage
(
m
,
wb
.
Seq
,
pid
)
;
err
!=
{
if
err
==
io
.
EOF
{
break
outer
}
return
,
err
}
if
m
.
Header
.
Type
!=
syscall
.
RTM_NEWROUTE
{
continue
}
var
r
Route
msg
:=
(
*
RtMsg
)
(
unsafe
.
Pointer
(
&
m
.
Data
[
0
:
syscall
.
SizeofRtMsg
]
[
0
]
)
)
if
msg
.
Flags
&
syscall
.
RTM_F_CLONED
!=
0
{
// Ignore cloned routes
continue
}
if
msg
.
Table
!=
syscall
.
RT_TABLE_MAIN
{
// Ignore non-main tables
continue
}
if
msg
.
Family
!=
syscall
.
AF_INET
{
// Ignore non-ipv4 routes
continue
}
if
msg
.
Dst_len
==
0
{
// Default routes
r
.
Default
=
true
}
attrs
,
err
:=
syscall
.
ParseNetlinkRouteAttr
(
&
m
)
if
err
!=
{
return
,
err
}
for
_
,
attr
:=
range
attrs
{
switch
attr
.
Attr
.
Type
{
case
syscall
.
RTA_DST
:
ip
:=
attr
.
Value
r
.
IPNet
=
&
net
.
IPNet
{
IP
:
ip
,
Mask
:
net
.
CIDRMask
(
int
(
msg
.
Dst_len
)
,
8
*
len
(
ip
)
)
,
}
case
syscall
.
RTA_OIF
:
index
:=
int
(
native
.
Uint32
(
attr
.
Value
[
0
:
4
]
)
)
r
.
Iface
,
_
=
net
.
InterfaceByIndex
(
index
)
}
}
if
r
.
Default
||
r
.
IPNet
!=
{
res
=
append
(
res
,
r
)
}
}
}
return
res
,
}

// Returns an array of IPNet for all the currently routed subnets on ipv4
// This is similar to the first column of "ip route" output

Returns an array of IPNet for all the currently routed subnets on ipv4 This is similar to the first column of ip route output


func CreateBridge(name string, setMacAddr bool) error {
	if len(name) >= IFNAMSIZ {
		return fmt.Errorf("Interface name %s too long", name)
	}

	s, err := getIfSocket()
	if err != nil {
		return err
	}
	defer syscall.Close(s)

	nameBytePtr, err := syscall.BytePtrFromString(name)
	if err != nil {
		return err
	}
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), SIOC_BRADDBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 {
		return err
	}
	if setMacAddr {
		return SetMacAddress(name, randMacAddr())
	}
	return nil
}

func CreateBridge ( name string , setMacAddr bool ) error { if len ( name ) >= IFNAMSIZ { return fmt . Errorf ( " " , name ) } s , err := getIfSocket ( ) if err != nil { return err } defer syscall . Close ( s ) nameBytePtr , err := syscall . BytePtrFromString ( name ) if err != nil { return err } if _ , _ , err := syscall . Syscall ( syscall . SYS_IOCTL , uintptr ( s ) , SIOC_BRADDBR , uintptr ( unsafe . Pointer ( nameBytePtr ) ) ) ; err != 0 { return err } if setMacAddr { return SetMacAddress ( name , randMacAddr ( ) ) } return nil }

// Create the actual bridge device.  This is more backward-compatible than
// netlink.NetworkLinkAdd and works on RHEL 6.

Create the actual bridge device . This is more backward - compatible than netlink . NetworkLinkAdd and works on RHEL 6 .


func DeleteBridge(name string) error {
	s, err := getIfSocket()
	if err != nil {
		return err
	}
	defer syscall.Close(s)

	nameBytePtr, err := syscall.BytePtrFromString(name)
	if err != nil {
		return err
	}

	var ifr ifreqFlags
	copy(ifr.IfrnName[:len(ifr.IfrnName)-1], []byte(name))
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s),
		syscall.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifr))); err != 0 {
		return err
	}

	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s),
		SIOC_BRDELBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 {
		return err
	}
	return nil
}

func DeleteBridge ( name string ) error { s , err := getIfSocket ( ) if err != nil { return err } defer syscall . Close ( s ) nameBytePtr , err := syscall . BytePtrFromString ( name ) if err != nil { return err } var ifr ifreqFlags copy ( ifr . IfrnName [ : len ( ifr . IfrnName ) - 1 ] , [ ] byte ( name ) ) if _ , _ , err := syscall . Syscall ( syscall . SYS_IOCTL , uintptr ( s ) , syscall . SIOCSIFFLAGS , uintptr ( unsafe . Pointer ( & ifr ) ) ) ; err != 0 { return err } if _ , _ , err := syscall . Syscall ( syscall . SYS_IOCTL , uintptr ( s ) , SIOC_BRDELBR , uintptr ( unsafe . Pointer ( nameBytePtr ) ) ) ; err != 0 { return err } return nil }


func AddToBridge(iface, master *net.Interface) error {
	return ifIoctBridge(iface, master, SIOC_BRADDIF)
}

func AddToBridge ( iface , master * net . Interface ) error { return ifIoctBridge ( iface , master , SIOC_BRADDIF ) }

// Add a slave to a bridge device.  This is more backward-compatible than
// netlink.NetworkSetMaster and works on RHEL 6.

Add a slave to a bridge device . This is more backward - compatible than netlink . NetworkSetMaster and works on RHEL 6 .


func DelFromBridge(iface, master *net.Interface) error {
	return ifIoctBridge(iface, master, SIOC_BRDELIF)
}

func DelFromBridge ( iface , master * net . Interface ) error { return ifIoctBridge ( iface , master , SIOC_BRDELIF ) }

// Detach a slave from a bridge device.  This is more backward-compatible than
// netlink.NetworkSetMaster and works on RHEL 6.

Detach a slave from a bridge device . This is more backward - compatible than netlink . NetworkSetMaster and works on RHEL 6 .


func labelIndex(labels *bpfLabels, lb string) uint32 {
	var id uint32
	for id = 0; id < uint32(len(*labels)); id++ {
		if strings.EqualFold(lb, (*labels)[id].label) {
			return id
		}
	}
	*labels = append(*labels, bpfLabel{lb, 0xffffffff})
	return id
}

func labelIndex ( labels * bpfLabels , lb string ) uint32 { var id uint32 for id = 0 ; id < uint32 ( len ( * labels ) ) ; id ++ { if strings . EqualFold ( lb , ( * labels ) [ id ] . label ) { return id } } * labels = append ( * labels , bpfLabel { lb , 0xffffffff } ) return id }

// labelIndex returns the index for the label if it exists in the slice.
// if it does not exist in the slice it appends the label lb to the end
// of the slice and returns the index.

labelIndex returns the index for the label if it exists in the slice . if it does not exist in the slice it appends the label lb to the end of the slice and returns the index .


func getSelinuxMountPoint() string {
	if selinuxfs != "unknown" {
		return selinuxfs
	}
	selinuxfs = ""

	mounts, err := mount.GetMounts()
	if err != nil {
		return selinuxfs
	}
	for _, mount := range mounts {
		if mount.Fstype == "selinuxfs" {
			selinuxfs = mount.Mountpoint
			break
		}
	}
	if selinuxfs != "" {
		var buf syscall.Statfs_t
		syscall.Statfs(selinuxfs, &buf)
		if (buf.Flags & stRdOnly) == 1 {
			selinuxfs = ""
		}
	}
	return selinuxfs
}

func getSelinuxMountPoint ( ) string { if selinuxfs != " " { return selinuxfs } selinuxfs = " " mounts , err := mount . GetMounts ( ) if err != nil { return selinuxfs } for _ , mount := range mounts { if mount . Fstype == " " { selinuxfs = mount . Mountpoint break } } if selinuxfs != " " { var buf syscall . Statfs_t syscall . Statfs ( selinuxfs , & buf ) if ( buf . Flags & stRdOnly ) == 1 { selinuxfs = " " } } return selinuxfs }

// getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
// filesystem or an empty string if no mountpoint is found.  Selinuxfs is
// a proc-like pseudo-filesystem that exposes the selinux policy API to
// processes.  The existence of an selinuxfs mount is used to determine
// whether selinux is currently enabled or not.

getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs filesystem or an empty string if no mountpoint is found . Selinuxfs is a proc - like pseudo - filesystem that exposes the selinux policy API to processes . The existence of an selinuxfs mount is used to determine whether selinux is currently enabled or not .


func SelinuxEnabled() bool {
	if selinuxEnabledChecked {
		return selinuxEnabled
	}
	selinuxEnabledChecked = true
	if fs := getSelinuxMountPoint(); fs != "" {
		if con, _ := Getcon(); con != "kernel" {
			selinuxEnabled = true
		}
	}
	return selinuxEnabled
}

func SelinuxEnabled ( ) bool { if selinuxEnabledChecked { return selinuxEnabled } selinuxEnabledChecked = true if fs := getSelinuxMountPoint ( ) ; fs != " " { if con , _ := Getcon ( ) ; con != " " { selinuxEnabled = true } } return selinuxEnabled }

// SelinuxEnabled returns whether selinux is currently enabled.

SelinuxEnabled returns whether selinux is currently enabled .


func Setfilecon(path string, scon string) error {
	return system.Lsetxattr(path, xattrNameSelinux, []byte(scon), 0)
}

func Setfilecon ( path string , scon string ) error { return system . Lsetxattr ( path , xattrNameSelinux , [ ] byte ( scon ) , 0 ) }

// Setfilecon sets the SELinux label for this path or returns an error.

Setfilecon sets the SELinux label for this path or returns an error .


func Getfilecon(path string) (string, error) {
	con, err := system.Lgetxattr(path, xattrNameSelinux)

	// Trim the NUL byte at the end of the byte buffer, if present.
	if con[len(con)-1] == '\x00' {
		con = con[:len(con)-1]
	}
	return string(con), err
}

// Getfilecon returns the SELinux label for this path or returns an error.

Getfilecon returns the SELinux label for this path or returns an error .


func badPrefix(fpath string) error {
	var badprefixes = []string{"/usr"}

	for _, prefix := range badprefixes {
		if fpath == prefix || strings.HasPrefix(fpath, fmt.Sprintf("%s/", prefix)) {
			return fmt.Errorf("Relabeling content in %s is not allowed.", prefix)
		}
	}
	return nil
}

func badPrefix ( fpath string ) error { var badprefixes = [ ] string { " " } for _ , prefix := range badprefixes { if fpath == prefix || strings . HasPrefix ( fpath , fmt . Sprintf ( " " , prefix ) ) { return fmt . Errorf ( " " , prefix ) } } return nil }

// Prevent users from relabing system files


func Chcon(fpath string, scon string, recurse bool) error {
	if scon == "" {
		return nil
	}
	if err := badPrefix(fpath); err != nil {
		return err
	}
	callback := func(p string, info os.FileInfo, err error) error {
		return Setfilecon(p, scon)
	}

	if recurse {
		return filepath.Walk(fpath, callback)
	}

	return Setfilecon(fpath, scon)
}

func Chcon ( fpath string , scon string , recurse bool ) error { if scon == " " { return nil } if err := badPrefix ( fpath ) ; err != nil { return err } callback := func ( p string , info os . FileInfo , err error ) error { return Setfilecon ( p , scon ) } if recurse { return filepath . Walk ( fpath , callback ) } return Setfilecon ( fpath , scon ) }

// Change the fpath file object to the SELinux label scon.
// If the fpath is a directory and recurse is true Chcon will walk the
// directory tree setting the label

Change the fpath file object to the SELinux label scon . If the fpath is a directory and recurse is true Chcon will walk the directory tree setting the label


func DupSecOpt(src string) []string {
	if src == "" {
		return nil
	}
	con := NewContext(src)
	if con["user"] == "" ||
		con["role"] == "" ||
		con["type"] == "" ||
		con["level"] == "" {
		return nil
	}
	return []string{"label:user:" + con["user"],
		"label:role:" + con["role"],
		"label:type:" + con["type"],
		"label:level:" + con["level"]}
}

func DupSecOpt ( src string ) [ ] string { if src == " " { return nil } con := NewContext ( src ) if con [ " " ] == " " || con [ " " ] == " " || con [ " " ] == " " || con [ " " ] == " " { return nil } return [ ] string { " " + con [ " " ] , " " + con [ " " ] , " " + con [ " " ] , " " + con [ " " ] } }

// DupSecOpt takes an SELinux process label and returns security options that
// can will set the SELinux Type and Level for future container processes

DupSecOpt takes an SELinux process label and returns security options that can will set the SELinux Type and Level for future container processes


func (v *veth) attach(n *configs.Network) (err error) {
	bridge, err := net.InterfaceByName(n.Bridge)
	if err != nil {
		return err
	}
	host, err := net.InterfaceByName(n.HostInterfaceName)
	if err != nil {
		return err
	}
	if err := netlink.AddToBridge(host, bridge); err != nil {
		return err
	}
	if err := netlink.NetworkSetMTU(host, n.Mtu); err != nil {
		return err
	}
	if n.HairpinMode {
		if err := netlink.SetHairpinMode(host, true); err != nil {
			return err
		}
	}
	if err := netlink.NetworkLinkUp(host); err != nil {
		return err
	}

	return nil
}

func ( v * veth ) attach ( n * configs . Network ) ( err error ) { bridge , err := net . InterfaceByName ( n . Bridge ) if err != nil { return err } host , err := net . InterfaceByName ( n . HostInterfaceName ) if err != nil { return err } if err := netlink . AddToBridge ( host , bridge ) ; err != nil { return err } if err := netlink . NetworkSetMTU ( host , n . Mtu ) ; err != nil { return err } if n . HairpinMode { if err := netlink . SetHairpinMode ( host , true ) ; err != nil { return err } } if err := netlink . NetworkLinkUp ( host ) ; err != nil { return err } return nil }

// attach a container network interface to an external network


func (c *Context) Add(s *Syscall) {
	c.syscalls[s.Value] = s
}

func ( c * Context ) Add ( s * Syscall ) { c . syscalls [ s . Value ] = s }

// Add will add the specified syscall, action, and arguments to the seccomp
// Context.

Add will add the specified syscall action and arguments to the seccomp Context .


func (c *Context) Load() error {
	filter, err := c.newFilter()
	if err != nil {
		return err
	}
	if err := prctl(prSetNoNewPrivileges, 1, 0, 0, 0); err != nil {
		return err
	}
	prog := newSockFprog(filter)
	return prog.set()
}

func ( c * Context ) Load ( ) error { filter , err := c . newFilter ( ) if err != nil { return err } if err := prctl ( prSetNoNewPrivileges , 1 , 0 , 0 , 0 ) ; err != nil { return err } prog := newSockFprog ( filter ) return prog . set ( ) }

// Load will apply the Context to the calling process makeing any secccomp process changes
// apply after the context is loaded.

Load will apply the Context to the calling process makeing any secccomp process changes apply after the context is loaded .


func newGraph() *graph {
	return &graph{
		idToNodes:     make(map[ID]Node),
		nodeToSources: make(map[ID]map[ID]float64),
		nodeToTargets: make(map[ID]map[ID]float64),
		//
		// without this
		// panic: assignment to entry in nil map
	}
}


func MakeDisjointSet(forests *Forests, name string) {
	newDS := &DisjointSet{}
	newDS.represent = name
	members := make(map[string]struct{})
	members[name] = struct{}{}
	newDS.members = members
	forests.mu.Lock()
	defer forests.mu.Unlock()
	forests.data[newDS] = struct{}{}
}

func MakeDisjointSet ( forests * Forests , name string ) { newDS := & DisjointSet { } newDS . represent = name members := make ( map [ string ] struct { } ) members [ name ] = struct { } { } newDS . members = members forests . mu . Lock ( ) defer forests . mu . Unlock ( ) forests . data [ newDS ] = struct { } { } }

// MakeDisjointSet creates a DisjointSet.


func FindSet(forests *Forests, name string) *DisjointSet {
	forests.mu.Lock()
	defer forests.mu.Unlock()
	for data := range forests.data {
		if data.represent == name {
			return data
		}
		for k := range data.members {
			if k == name {
				return data
			}
		}
	}
	return nil
}

func FindSet ( forests * Forests , name string ) * DisjointSet { forests . mu . Lock ( ) defer forests . mu . Unlock ( ) for data := range forests . data { if data . represent == name { return data } for k := range data . members { if k == name { return data } } } return nil }

// FindSet returns the DisjointSet with the represent name.

FindSet returns the DisjointSet with the represent name .


func Union(forests *Forests, ds1, ds2 *DisjointSet) {
	newDS := &DisjointSet{}
	newDS.represent = ds1.represent
	newDS.members = ds1.members
	for k := range ds2.members {
		newDS.members[k] = struct{}{}
	}
	forests.mu.Lock()
	defer forests.mu.Unlock()
	forests.data[newDS] = struct{}{}
	delete(forests.data, ds1)
	delete(forests.data, ds2)
}

func Union ( forests * Forests , ds1 , ds2 * DisjointSet ) { newDS := & DisjointSet { } newDS . represent = ds1 . represent newDS . members = ds1 . members for k := range ds2 . members { newDS . members [ k ] = struct { } { } } forests . mu . Lock ( ) defer forests . mu . Unlock ( ) forests . data [ newDS ] = struct { } { } delete ( forests . data , ds1 ) delete ( forests . data , ds2 ) }

// Union unions two DisjointSet, with ds1's represent.

Union unions two DisjointSet with ds1 s represent .


func (c *Client) Me() (*User, error) {
	user := &User{}

	err := c.request("GET", "me", user, nil, nil)
	if err != nil {
		return nil, err
	}

	return user, nil
}

func ( c * Client ) Me ( ) ( * User , error ) { user := & User { } err := c . request ( " " , " " , user , nil , nil ) if err != nil { return nil , err } return user , nil }

// Me returns information about the current user


func (c *Client) ListProjects() ([]*Project, error) {
	projects := []*Project{}

	err := c.request("GET", "projects", &projects, nil, nil)
	if err != nil {
		return nil, err
	}

	for _, project := range projects {
		if err := cleanupProject(project); err != nil {
			return nil, err
		}
	}

	return projects, nil
}

func ( c * Client ) ListProjects ( ) ( [ ] * Project , error ) { projects := [ ] * Project { } err := c . request ( " " , " " , & projects , nil , nil ) if err != nil { return nil , err } for _ , project := range projects { if err := cleanupProject ( project ) ; err != nil { return nil , err } } return projects , nil }

// ListProjects returns the list of projects the user is watching


func (c *Client) DisableProject(account, repo string) error {
	return c.request("DELETE", fmt.Sprintf("project/%s/%s/enable", account, repo), nil, nil, nil)
}

func ( c * Client ) DisableProject ( account , repo string ) error { return c . request ( " " , fmt . Sprintf ( " " , account , repo ) , nil , nil , nil ) }


func (c *Client) FollowProject(account, repo string) (*Project, error) {
	project := &Project{}

	err := c.request("POST", fmt.Sprintf("project/%s/%s/follow", account, repo), project, nil, nil)
	if err != nil {
		return nil, err
	}

	if err := cleanupProject(project); err != nil {
		return nil, err
	}

	return project, nil
}

func ( c * Client ) FollowProject ( account , repo string ) ( * Project , error ) { project := & Project { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo ) , project , nil , nil ) if err != nil { return nil , err } if err := cleanupProject ( project ) ; err != nil { return nil , err } return project , nil }


func (c *Client) GetProject(account, repo string) (*Project, error) {
	projects, err := c.ListProjects()
	if err != nil {
		return nil, err
	}

	for _, project := range projects {
		if account == project.Username && repo == project.Reponame {
			return project, nil
		}
	}

	return nil, nil
}

func ( c * Client ) GetProject ( account , repo string ) ( * Project , error ) { projects , err := c . ListProjects ( ) if err != nil { return nil , err } for _ , project := range projects { if account == project . Username && repo == project . Reponame { return project , nil } } return nil , nil }

// GetProject retrieves a specific project
// Returns nil of the project is not in the list of watched projects

GetProject retrieves a specific project Returns nil of the project is not in the list of watched projects


func (c *Client) ListRecentBuilds(limit, offset int) ([]*Build, error) {
	return c.recentBuilds("recent-builds", nil, limit, offset)
}

func ( c * Client ) ListRecentBuilds ( limit , offset int ) ( [ ] * Build , error ) { return c . recentBuilds ( " " , nil , limit , offset ) }

// ListRecentBuilds fetches the list of recent builds for all repositories the user is watching
// If limit is -1, fetches all builds

ListRecentBuilds fetches the list of recent builds for all repositories the user is watching If limit is - 1 fetches all builds


func (c *Client) ListRecentBuildsForProject(account, repo, branch, status string, limit, offset int) ([]*Build, error) {
	path := fmt.Sprintf("project/%s/%s", account, repo)
	if branch != "" {
		path = fmt.Sprintf("%s/tree/%s", path, branch)
	}

	params := url.Values{}
	if status != "" {
		params.Set("filter", status)
	}

	return c.recentBuilds(path, params, limit, offset)
}

func ( c * Client ) ListRecentBuildsForProject ( account , repo , branch , status string , limit , offset int ) ( [ ] * Build , error ) { path := fmt . Sprintf ( " " , account , repo ) if branch != " " { path = fmt . Sprintf ( " " , path , branch ) } params := url . Values { } if status != " " { params . Set ( " " , status ) } return c . recentBuilds ( path , params , limit , offset ) }

// ListRecentBuildsForProject fetches the list of recent builds for the given repository
// The status and branch parameters are used to further filter results if non-empty
// If limit is -1, fetches all builds

ListRecentBuildsForProject fetches the list of recent builds for the given repository The status and branch parameters are used to further filter results if non - empty If limit is - 1 fetches all builds


func (c *Client) ListBuildArtifacts(account, repo string, buildNum int) ([]*Artifact, error) {
	artifacts := []*Artifact{}

	err := c.request("GET", fmt.Sprintf("project/%s/%s/%d/artifacts", account, repo, buildNum), &artifacts, nil, nil)
	if err != nil {
		return nil, err
	}

	return artifacts, nil
}

func ( c * Client ) ListBuildArtifacts ( account , repo string , buildNum int ) ( [ ] * Artifact , error ) { artifacts := [ ] * Artifact { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo , buildNum ) , & artifacts , nil , nil ) if err != nil { return nil , err } return artifacts , nil }

// ListBuildArtifacts fetches the build artifacts for the given build


func (c *Client) AddSSHUser(account, repo string, buildNum int) (*Build, error) {
	build := &Build{}

	err := c.request("POST", fmt.Sprintf("project/%s/%s/%d/ssh-users", account, repo, buildNum), build, nil, nil)
	if err != nil {
		return nil, err
	}

	return build, nil
}

func ( c * Client ) AddSSHUser ( account , repo string , buildNum int ) ( * Build , error ) { build := & Build { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo , buildNum ) , build , nil , nil ) if err != nil { return nil , err } return build , nil }

// AddSSHUser adds the user associated with the API token to the list of valid
// SSH users for a build.
//
// The API token being used must be a user API token

AddSSHUser adds the user associated with the API token to the list of valid SSH users for a build . The API token being used must be a user API token


func (c *Client) Build(account, repo, branch string) (*Build, error) {
	return c.BuildOpts(account, repo, branch, nil)
}

func ( c * Client ) Build ( account , repo , branch string ) ( * Build , error ) { return c . BuildOpts ( account , repo , branch , nil ) }

// Build triggers a new build for the given project for the given
// project on the given branch.
// Returns the new build information

Build triggers a new build for the given project for the given project on the given branch . Returns the new build information


func (c *Client) ParameterizedBuild(account, repo, branch string, buildParameters map[string]string) (*Build, error) {
	opts := map[string]interface{}{"build_parameters": buildParameters}
	return c.BuildOpts(account, repo, branch, opts)
}

func ( c * Client ) ParameterizedBuild ( account , repo , branch string , buildParameters map [ string ] string ) ( * Build , error ) { opts := map [ string ] interface { } { " " : buildParameters } return c . BuildOpts ( account , repo , branch , opts ) }

// ParameterizedBuild triggers a new parameterized build for the given
// project on the given branch, Marshaling the struct into json and passing
// in the post body.
// Returns the new build information

ParameterizedBuild triggers a new parameterized build for the given project on the given branch Marshaling the struct into json and passing in the post body . Returns the new build information


func (c *Client) BuildOpts(account, repo, branch string, opts map[string]interface{}) (*Build, error) {
	build := &Build{}

	err := c.request("POST", fmt.Sprintf("project/%s/%s/tree/%s", account, repo, branch), build, nil, opts)
	if err != nil {
		return nil, err
	}

	return build, nil
}

func ( c * Client ) BuildOpts ( account , repo , branch string , opts map [ string ] interface { } ) ( * Build , error ) { build := & Build { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo , branch ) , build , nil , opts ) if err != nil { return nil , err } return build , nil }

// BuildOpts triggeres a new build for the givent project on the given
// branch, Marshaling the struct into json and passing
// in the post body.
// Returns the new build information

BuildOpts triggeres a new build for the givent project on the given branch Marshaling the struct into json and passing in the post body . Returns the new build information


func (c *Client) ClearCache(account, repo string) (string, error) {
	status := &struct {
		Status string `json:"status"`
	}{}

	err := c.request("DELETE", fmt.Sprintf("project/%s/%s/build-cache", account, repo), status, nil, nil)
	if err != nil {
		return "", err
	}

	return status.Status, nil
}

func ( c * Client ) ClearCache ( account , repo string ) ( string , error ) { status := & struct { Status string `json:"status"` } { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo ) , status , nil , nil ) if err != nil { return " " , err } return status . Status , nil }

// ClearCache clears the cache of the specified project
// Returns the status returned by CircleCI

ClearCache clears the cache of the specified project Returns the status returned by CircleCI


func (c *Client) DeleteEnvVar(account, repo, name string) error {
	return c.request("DELETE", fmt.Sprintf("project/%s/%s/envvar/%s", account, repo, name), nil, nil, nil)
}

func ( c * Client ) DeleteEnvVar ( account , repo , name string ) error { return c . request ( " " , fmt . Sprintf ( " " , account , repo , name ) , nil , nil , nil ) }

// DeleteEnvVar deletes the specified environment variable from the project


func (c *Client) AddSSHKey(account, repo, hostname, privateKey string) error {
	key := &struct {
		Hostname   string `json:"hostname"`
		PrivateKey string `json:"private_key"`
	}{hostname, privateKey}
	return c.request("POST", fmt.Sprintf("project/%s/%s/ssh-key", account, repo), nil, nil, key)
}

func ( c * Client ) AddSSHKey ( account , repo , hostname , privateKey string ) error { key := & struct { Hostname string `json:"hostname"` PrivateKey string `json:"private_key"` } { hostname , privateKey } return c . request ( " " , fmt . Sprintf ( " " , account , repo ) , nil , nil , key ) }

// AddSSHKey adds a new SSH key to the project


func (c *Client) GetActionOutputs(a *Action) ([]*Output, error) {
	if !a.HasOutput || a.OutputURL == "" {
		return nil, nil
	}

	req, err := http.NewRequest("GET", a.OutputURL, nil)
	if err != nil {
		return nil, err
	}

	c.debugRequest(req)

	resp, err := c.client().Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	c.debugResponse(resp)

	output := []*Output{}
	if err = json.NewDecoder(resp.Body).Decode(&output); err != nil {
		return nil, err
	}

	return output, nil
}

func ( c * Client ) GetActionOutputs ( a * Action ) ( [ ] * Output , error ) { if ! a . HasOutput || a . OutputURL == " " { return nil , nil } req , err := http . NewRequest ( " " , a . OutputURL , nil ) if err != nil { return nil , err } c . debugRequest ( req ) resp , err := c . client ( ) . Do ( req ) if err != nil { return nil , err } defer resp . Body . Close ( ) c . debugResponse ( resp ) output := [ ] * Output { } if err = json . NewDecoder ( resp . Body ) . Decode ( & output ) ; err != nil { return nil , err } return output , nil }

// GetActionOutputs fetches the output for the given action
// If the action has no output, returns nil

GetActionOutputs fetches the output for the given action If the action has no output returns nil


func (c *Client) ListCheckoutKeys(account, repo string) ([]*CheckoutKey, error) {
	checkoutKeys := []*CheckoutKey{}

	err := c.request("GET", fmt.Sprintf("project/%s/%s/checkout-key", account, repo), &checkoutKeys, nil, nil)
	if err != nil {
		return nil, err
	}

	return checkoutKeys, nil
}

func ( c * Client ) ListCheckoutKeys ( account , repo string ) ( [ ] * CheckoutKey , error ) { checkoutKeys := [ ] * CheckoutKey { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo ) , & checkoutKeys , nil , nil ) if err != nil { return nil , err } return checkoutKeys , nil }

// ListCheckoutKeys fetches the checkout keys associated with the given project


func (c *Client) CreateCheckoutKey(account, repo, keyType string) (*CheckoutKey, error) {
	checkoutKey := &CheckoutKey{}

	body := struct {
		KeyType string `json:"type"`
	}{KeyType: keyType}

	err := c.request("POST", fmt.Sprintf("project/%s/%s/checkout-key", account, repo), checkoutKey, nil, body)
	if err != nil {
		return nil, err
	}

	return checkoutKey, nil
}

func ( c * Client ) CreateCheckoutKey ( account , repo , keyType string ) ( * CheckoutKey , error ) { checkoutKey := & CheckoutKey { } body := struct { KeyType string `json:"type"` } { KeyType : keyType } err := c . request ( " " , fmt . Sprintf ( " " , account , repo ) , checkoutKey , nil , body ) if err != nil { return nil , err } return checkoutKey , nil }

// CreateCheckoutKey creates a new checkout key for a project
// Valid key types are currently deploy-key and github-user-key
//
// The github-user-key type requires that the API token being used be a user API token

CreateCheckoutKey creates a new checkout key for a project Valid key types are currently deploy - key and github - user - key The github - user - key type requires that the API token being used be a user API token


func (c *Client) GetCheckoutKey(account, repo, fingerprint string) (*CheckoutKey, error) {
	checkoutKey := &CheckoutKey{}

	err := c.request("GET", fmt.Sprintf("project/%s/%s/checkout-key/%s", account, repo, fingerprint), &checkoutKey, nil, nil)
	if err != nil {
		return nil, err
	}

	return checkoutKey, nil
}

func ( c * Client ) GetCheckoutKey ( account , repo , fingerprint string ) ( * CheckoutKey , error ) { checkoutKey := & CheckoutKey { } err := c . request ( " " , fmt . Sprintf ( " " , account , repo , fingerprint ) , & checkoutKey , nil , nil ) if err != nil { return nil , err } return checkoutKey , nil }

// GetCheckoutKey fetches the checkout key for the given project by fingerprint


func (c *Client) DeleteCheckoutKey(account, repo, fingerprint string) error {
	return c.request("DELETE", fmt.Sprintf("project/%s/%s/checkout-key/%s", account, repo, fingerprint), nil, nil, nil)
}

func ( c * Client ) DeleteCheckoutKey ( account , repo , fingerprint string ) error { return c . request ( " " , fmt . Sprintf ( " " , account , repo , fingerprint ) , nil , nil , nil ) }

// DeleteCheckoutKey fetches the checkout key for the given project by fingerprint


func New(opts ...Option) (*Client, error) {
	// The default configuration.
	conf := &config{
		Client: clientConfig{
			Rate: 1,
		},
		Conn: connConfig{
			Addr:        ":8125",
			FlushPeriod: 100 * time.Millisecond,
			// Worst-case scenario:
			// Ethernet MTU - IPv6 Header - TCP Header = 1500 - 40 - 20 = 1440
			MaxPacketSize: 1440,
			Network:       "udp",
		},
	}
	for _, o := range opts {
		o(conf)
	}

	conn, err := newConn(conf.Conn, conf.Client.Muted)
	c := &Client{
		conn:  conn,
		muted: conf.Client.Muted,
	}
	if err != nil {
		c.muted = true
		return c, err
	}
	c.rate = conf.Client.Rate
	c.prefix = conf.Client.Prefix
	c.tags = joinTags(conf.Conn.TagFormat, conf.Client.Tags)
	return c, nil
}


func (c *Client) Clone(opts ...Option) *Client {
	tf := c.conn.tagFormat
	conf := &config{
		Client: clientConfig{
			Rate:   c.rate,
			Prefix: c.prefix,
			Tags:   splitTags(tf, c.tags),
		},
	}
	for _, o := range opts {
		o(conf)
	}

	clone := &Client{
		conn:   c.conn,
		muted:  c.muted || conf.Client.Muted,
		rate:   conf.Client.Rate,
		prefix: conf.Client.Prefix,
		tags:   joinTags(tf, conf.Client.Tags),
	}
	clone.conn = c.conn
	return clone
}

func ( c * Client ) Clone ( opts ... Option ) * Client { tf := c . conn . tagFormat conf := & config { Client : clientConfig { Rate : c . rate , Prefix : c . prefix , Tags : splitTags ( tf , c . tags ) , } , } for _ , o := range opts { o ( conf ) } clone := & Client { conn : c . conn , muted : c . muted || conf . Client . Muted , rate : conf . Client . Rate , prefix : conf . Client . Prefix , tags : joinTags ( tf , conf . Client . Tags ) , } clone . conn = c . conn return clone }

// Clone returns a clone of the Client. The cloned Client inherits its
// configuration from its parent.
//
// All cloned Clients share the same connection, so cloning a Client is a cheap
// operation.

Clone returns a clone of the Client . The cloned Client inherits its configuration from its parent . All cloned Clients share the same connection so cloning a Client is a cheap operation .


func (c *Client) Count(bucket string, n interface{}) {
	if c.skip() {
		return
	}
	c.conn.metric(c.prefix, bucket, n, "c", c.rate, c.tags)
}

func ( c * Client ) Count ( bucket string , n interface { } ) { if c . skip ( ) { return } c . conn . metric ( c . prefix , bucket , n , " " , c . rate , c . tags ) }


func (c *Client) Gauge(bucket string, value interface{}) {
	if c.skip() {
		return
	}
	c.conn.gauge(c.prefix, bucket, value, c.tags)
}

func ( c * Client ) Gauge ( bucket string , value interface { } ) { if c . skip ( ) { return } c . conn . gauge ( c . prefix , bucket , value , c . tags ) }

// Gauge records an absolute value for the given bucket.

Gauge records an absolute value for the given bucket .


func (c *Client) Timing(bucket string, value interface{}) {
	if c.skip() {
		return
	}
	c.conn.metric(c.prefix, bucket, value, "ms", c.rate, c.tags)
}

func ( c * Client ) Timing ( bucket string , value interface { } ) { if c . skip ( ) { return } c . conn . metric ( c . prefix , bucket , value , " " , c . rate , c . tags ) }

// Timing sends a timing value to a bucket.

Timing sends a timing value to a bucket .


func (t Timing) Send(bucket string) {
	t.c.Timing(bucket, int(t.Duration()/time.Millisecond))
}

func ( t Timing ) Send ( bucket string ) { t . c . Timing ( bucket , int ( t . Duration ( ) / time . Millisecond ) ) }

// Send sends the time elapsed since the creation of the Timing.

Send sends the time elapsed since the creation of the Timing .


func (c *Client) Unique(bucket string, value string) {
	if c.skip() {
		return
	}
	c.conn.unique(c.prefix, bucket, value, c.tags)
}

func ( c * Client ) Unique ( bucket string , value string ) { if c . skip ( ) { return } c . conn . unique ( c . prefix , bucket , value , c . tags ) }

// Unique sends the given value to a set bucket.

Unique sends the given value to a set bucket .


func (c *Client) Flush() {
	if c.muted {
		return
	}
	c.conn.mu.Lock()
	c.conn.flush(0)
	c.conn.mu.Unlock()
}

func ( c * Client ) Flush ( ) { if c . muted { return } c . conn . mu . Lock ( ) c . conn . flush ( 0 ) c . conn . mu . Unlock ( ) }


func (c *Client) Close() {
	if c.muted {
		return
	}
	c.conn.mu.Lock()
	c.conn.flush(0)
	c.conn.handleError(c.conn.w.Close())
	c.conn.closed = true
	c.conn.mu.Unlock()
}

func ( c * Client ) Close ( ) { if c . muted { return } c . conn . mu . Lock ( ) c . conn . flush ( 0 ) c . conn . handleError ( c . conn . w . Close ( ) ) c . conn . closed = true c . conn . mu . Unlock ( ) }

// Close flushes the Client's buffer and releases the associated ressources. The
// Client and all the cloned Clients must not be used afterward.

Close flushes the Client s buffer and releases the associated ressources . The Client and all the cloned Clients must not be used afterward .


func SampleRate(rate float32) Option {
	return Option(func(c *config) {
		c.Client.Rate = rate
	})
}

func SampleRate ( rate float32 ) Option { return Option ( func ( c * config ) { c . Client . Rate = rate } ) }

// SampleRate sets the sample rate of the Client. It allows sending the metrics
// less often which can be useful for performance intensive code paths.

SampleRate sets the sample rate of the Client . It allows sending the metrics less often which can be useful for performance intensive code paths .


func Prefix(p string) Option {
	return Option(func(c *config) {
		c.Client.Prefix += strings.TrimSuffix(p, ".") + "."
	})
}

func Prefix ( p string ) Option { return Option ( func ( c * config ) { c . Client . Prefix += strings . TrimSuffix ( p , " " ) + " " } ) }

// Prefix appends the prefix that will be used in every bucket name.
//
// Note that when used in cloned, the prefix of the parent Client is not
// replaced but is prepended to the given prefix.

Prefix appends the prefix that will be used in every bucket name . Note that when used in cloned the prefix of the parent Client is not replaced but is prepended to the given prefix .


func TagsFormat(tf TagFormat) Option {
	return Option(func(c *config) {
		c.Conn.TagFormat = tf
	})
}

func TagsFormat ( tf TagFormat ) Option { return Option ( func ( c * config ) { c . Conn . TagFormat = tf } ) }


func Tags(tags ...string) Option {
	if len(tags)%2 != 0 {
		panic("statsd: Tags only accepts an even number of arguments")
	}

	return Option(func(c *config) {
		if len(tags) == 0 {
			return
		}

		newTags := make([]tag, len(tags)/2)
		for i := 0; i < len(tags)/2; i++ {
			newTags[i] = tag{K: tags[2*i], V: tags[2*i+1]}
		}

		for _, newTag := range newTags {
			exists := false
			for _, oldTag := range c.Client.Tags {
				if newTag.K == oldTag.K {
					exists = true
					oldTag.V = newTag.V
				}
			}
			if !exists {
				c.Client.Tags = append(c.Client.Tags, tag{
					K: newTag.K,
					V: newTag.V,
				})
			}
		}
	})
}

func Tags ( tags ... string ) Option { if len ( tags ) % 2 != 0 { panic ( " " ) } return Option ( func ( c * config ) { if len ( tags ) == 0 { return } newTags := make ( [ ] tag , len ( tags ) / 2 ) for i := 0 ; i < len ( tags ) / 2 ; i ++ { newTags [ i ] = tag { K : tags [ 2 * i ] , V : tags [ 2 * i + 1 ] } } for _ , newTag := range newTags { exists := false for _ , oldTag := range c . Client . Tags { if newTag . K == oldTag . K { exists = true oldTag . V = newTag . V } } if ! exists { c . Client . Tags = append ( c . Client . Tags , tag { K : newTag . K , V : newTag . V , } ) } } } ) }

// Tags appends the given tags to the tags sent with every metrics. If a tag
// already exists, it is replaced.
//
// The tags must be set as key-value pairs. If the number of tags is not even,
// Tags panics.
//
// If the format of tags have not been set using the TagsFormat option, the tags
// will be ignored.

Tags appends the given tags to the tags sent with every metrics . If a tag already exists it is replaced . The tags must be set as key - value pairs . If the number of tags is not even Tags panics . If the format of tags have not been set using the TagsFormat option the tags will be ignored .


func (c *conn) flush(n int) {
	if len(c.buf) == 0 {
		return
	}
	if n == 0 {
		n = len(c.buf)
	}

	// Trim the last \n, StatsD does not like it.
	_, err := c.w.Write(c.buf[:n-1])
	c.handleError(err)
	if n < len(c.buf) {
		copy(c.buf, c.buf[n:])
	}
	c.buf = c.buf[:len(c.buf)-n]
}

// flush flushes the first n bytes of the buffer.
// If n is 0, the whole buffer is flushed.

flush flushes the first n bytes of the buffer . If n is 0 the whole buffer is flushed .


func BuildQwerty() Graph {
	data, err := data.Asset("data/Qwerty.json")
	if err != nil {
		panic("Can't find asset")
	}
	return getAdjancencyGraphFromFile(data, "qwerty")
}

func BuildQwerty ( ) Graph { data , err := data . Asset ( " " ) if err != nil { panic ( " " ) } return getAdjancencyGraphFromFile ( data , " " ) }


func BuildDvorak() Graph {
	data, err := data.Asset("data/Dvorak.json")
	if err != nil {
		panic("Can't find asset")
	}
	return getAdjancencyGraphFromFile(data, "dvorak")
}

func BuildDvorak ( ) Graph { data , err := data . Asset ( " " ) if err != nil { panic ( " " ) } return getAdjancencyGraphFromFile ( data , " " ) }


func BuildKeypad() Graph {
	data, err := data.Asset("data/Keypad.json")
	if err != nil {
		panic("Can't find asset")
	}
	return getAdjancencyGraphFromFile(data, "keypad")
}

func BuildKeypad ( ) Graph { data , err := data . Asset ( " " ) if err != nil { panic ( " " ) } return getAdjancencyGraphFromFile ( data , " " ) }


func BuildMacKeypad() Graph {
	data, err := data.Asset("data/MacKeypad.json")
	if err != nil {
		panic("Can't find asset")
	}
	return getAdjancencyGraphFromFile(data, "mac_keypad")
}

func BuildMacKeypad ( ) Graph { data , err := data . Asset ( " " ) if err != nil { panic ( " " ) } return getAdjancencyGraphFromFile ( data , " " ) }

//BuildMacKeypad builds the Mac Keypad Graph


func BuildLeet() Graph {
	data, err := data.Asset("data/L33t.json")
	if err != nil {
		panic("Can't find asset")
	}
	return getAdjancencyGraphFromFile(data, "keypad")
}

func BuildLeet ( ) Graph { data , err := data . Asset ( " " ) if err != nil { panic ( " " ) } return getAdjancencyGraphFromFile ( data , " " ) }


func DictionaryEntropy(match match.Match, rank float64) float64 {
	baseEntropy := math.Log2(rank)
	upperCaseEntropy := extraUpperCaseEntropy(match)
	//TODO: L33t
	return baseEntropy + upperCaseEntropy
}

func
DictionaryEntropy
(
match
match
.
Match
,
rank
float64
)
float64
{
baseEntropy
:=
math
.
Log2
(
rank
)
upperCaseEntropy
:=
extraUpperCaseEntropy
(
match
)
//TODO: L33t
return
baseEntropy
+
upperCaseEntropy
}

// DictionaryEntropy calculates the entropy of a dictionary match


func SpatialEntropy(match match.Match, turns int, shiftCount int) float64 {
	var s, d float64
	if match.DictionaryName == "qwerty" || match.DictionaryName == "dvorak" {
		//todo: verify qwerty and dvorak have the same length and degree
		s = float64(len(adjacency.BuildQwerty().Graph))
		d = adjacency.BuildQwerty().CalculateAvgDegree()
	} else {
		s = float64(keyPadStartingPositions)
		d = keyPadAvgDegree
	}

	possibilities := float64(0)

	length := float64(len(match.Token))

	//TODO: Should this be <= or just < ?
	//Estimate the number of possible patterns w/ length L or less with t turns or less
	for i := float64(2); i <= length+1; i++ {
		possibleTurns := math.Min(float64(turns), i-1)
		for j := float64(1); j <= possibleTurns+1; j++ {
			x := zxcvbnmath.NChoseK(i-1, j-1) * s * math.Pow(d, j)
			possibilities += x
		}
	}

	entropy := math.Log2(possibilities)
	//add extra entropu for shifted keys. ( % instead of 5 A instead of a)
	//Math is similar to extra entropy for uppercase letters in dictionary matches.

	if S := float64(shiftCount); S > float64(0) {
		possibilities = float64(0)
		U := length - S

		for i := float64(0); i < math.Min(S, U)+1; i++ {
			possibilities += zxcvbnmath.NChoseK(S+U, i)
		}

		entropy += math.Log2(possibilities)
	}

	return entropy
}

// SpatialEntropy calculates the entropy for spatial matches


func RepeatEntropy(match match.Match) float64 {
	cardinality := CalcBruteForceCardinality(match.Token)
	entropy := math.Log2(cardinality * float64(len(match.Token)))

	return entropy
}

func RepeatEntropy ( match match . Match ) float64 { cardinality := CalcBruteForceCardinality ( match . Token ) entropy := math . Log2 ( cardinality * float64 ( len ( match . Token ) ) ) return entropy }

// RepeatEntropy calculates the entropy for repeating entropy


func SequenceEntropy(match match.Match, dictionaryLength int, ascending bool) float64 {
	firstChar := match.Token[0]
	baseEntropy := float64(0)
	if string(firstChar) == "a" || string(firstChar) == "1" {
		baseEntropy = float64(0)
	} else {
		baseEntropy = math.Log2(float64(dictionaryLength))
		//TODO: should this be just the first or any char?
		if unicode.IsUpper(rune(firstChar)) {
			baseEntropy++
		}
	}

	if !ascending {
		baseEntropy++
	}
	return baseEntropy + math.Log2(float64(len(match.Token)))
}

// SequenceEntropy calculates the entropy for sequences such as 4567 or cdef


func ExtraLeetEntropy(match match.Match, password string) float64 {
	var subsitutions float64
	var unsub float64
	subPassword := password[match.I:match.J]
	for index, char := range subPassword {
		if string(char) != string(match.Token[index]) {
			subsitutions++
		} else {
			//TODO: Make this only true for 1337 chars that are not subs?
			unsub++
		}
	}

	var possibilities float64

	for i := float64(0); i <= math.Min(subsitutions, unsub)+1; i++ {
		possibilities += zxcvbnmath.NChoseK(subsitutions+unsub, i)
	}

	if possibilities <= 1 {
		return float64(1)
	}
	return math.Log2(possibilities)
}

// ExtraLeetEntropy calulates the added entropy provied by l33t substitustions


func DateEntropy(dateMatch match.DateMatch) float64 {
	var entropy float64
	if dateMatch.Year < 100 {
		entropy = math.Log2(numDays * numMonths * 100)
	} else {
		entropy = math.Log2(numDays * numMonths * numYears)
	}

	if dateMatch.Separator != "" {
		entropy += 2 //add two bits for separator selection [/,-,.,etc]
	}
	return entropy
}

// DateEntropy calculates the entropy provided by a date


func Omnimatch(password string, userInputs []string, filters ...func(match.Matcher) bool) (matches []match.Match) {

	//Can I run into the issue where nil is not equal to nil?
	if dictionaryMatchers == nil || adjacencyGraphs == nil {
		loadFrequencyList()
	}

	if userInputs != nil {
		userInputMatcher := buildDictMatcher("user_inputs", buildRankedDict(userInputs))
		matches = userInputMatcher(password)
	}

	for _, matcher := range matchers {
		shouldBeFiltered := false
		for i := range filters {
			if filters[i](matcher) {
				shouldBeFiltered = true
				break
			}
		}
		if !shouldBeFiltered {
			matches = append(matches, matcher.MatchingFunc(password)...)
		}
	}
	sort.Sort(match.Matches(matches))
	return matches
}

// Omnimatch runs all matchers against the password


func Null(in []byte, pos int) (int, error) {
	switch in[pos] {
	case 'n':
		return expect(in, pos, n...)
		return pos + 4, nil
	default:
		return 0, errUnexpectedValue
	}
}

func Null ( in [ ] byte , pos int ) ( int , error ) { switch in [ pos ] { case 'n' : return expect ( in , pos , n ... ) return pos + 4 , nil default : return 0 , errUnexpectedValue } }

// Null verifies the contents of bytes provided is a null starting as pos


func Number(in []byte, pos int) (int, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	max := len(in)
	for {
		v := in[pos]
		switch v {
		case '-', '+', '.', 'e', 'E', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0':
			pos++
		default:
			return pos, nil
		}

		if pos >= max {
			return pos, nil
		}
	}

	return pos, nil
}

func Number ( in [ ] byte , pos int ) ( int , error ) { pos , err := skipSpace ( in , pos ) if err != nil { return 0 , err } max := len ( in ) for { v := in [ pos ] switch v { case '-' , '+' , '.' , 'e' , 'E' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' : pos ++ default : return pos , nil } if pos >= max { return pos , nil } } return pos , nil }

// Number returns the end position of the number that begins at the specified pos


func Array(in []byte, pos int) (int, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	if v := in[pos]; v != '[' {
		return 0, newError(pos, v)
	}
	pos++

	// clean initial spaces
	pos, err = skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	if in[pos] == ']' {
		return pos + 1, nil
	}

	for {
		// data
		pos, err = Any(in, pos)
		if err != nil {
			return 0, err
		}

		pos, err = skipSpace(in, pos)
		if err != nil {
			return 0, err
		}

		switch in[pos] {
		case ',':
			pos++
		case ']':
			return pos + 1, nil
		}
	}
}

func
Array
(
in
[
]
byte
,
pos
int
)
(
int
,
error
)
{
pos
,
err
:=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
if
v
:=
in
[
pos
]
;
v
!=
'['
{
return
0
,
newError
(
pos
,
v
)
}
pos
++
// clean initial spaces
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
if
in
[
pos
]
==
']'
{
return
pos
+
1
,
}
for
{
// data
pos
,
err
=
Any
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
switch
in
[
pos
]
{
case
','
:
pos
++
case
']'
:
return
pos
+
1
,
}
}
}

// Array returns the position of the end of the array that begins at the position specified


func FindRange(in []byte, pos, from, to int) ([]byte, error) {
	if to < from {
		return nil, errToLessThanFrom
	}

	pos, err := skipSpace(in, pos)
	if err != nil {
		return nil, err
	}

	if v := in[pos]; v != '[' {
		return nil, newError(pos, v)
	}
	pos++

	idx := 0
	itemStart := pos

	for {
		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		if idx == from {
			itemStart = pos
		}

		// data
		pos, err = Any(in, pos)
		if err != nil {
			return nil, err
		}

		if idx == to {
			data := in[itemStart:pos]
			result := make([]byte, 0, len(data)+2)
			result = append(result, '[')
			result = append(result, data...)
			result = append(result, ']')
			return result, nil
		}

		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		switch in[pos] {
		case ',':
			pos++
		case ']':
			return nil, errIndexOutOfBounds
		}

		idx++
	}
}

func
FindRange
(
in
[
]
byte
,
pos
,
from
,
to
int
)
(
[
]
byte
,
error
)
{
if
to
<
from
{
return
,
errToLessThanFrom
}
pos
,
err
:=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
v
:=
in
[
pos
]
;
v
!=
'['
{
return
,
newError
(
pos
,
v
)
}
pos
++
idx
:=
0
itemStart
:=
pos
for
{
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
idx
==
from
{
itemStart
=
pos
}
// data
pos
,
err
=
Any
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
idx
==
to
{
data
:=
in
[
itemStart
:
pos
]
result
:=
make
(
[
]
byte
,
0
,
len
(
data
)
+
2
)
result
=
append
(
result
,
'['
)
result
=
append
(
result
,
data
...
)
result
=
append
(
result
,
']'
)
return
result
,
}
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
switch
in
[
pos
]
{
case
','
:
pos
++
case
']'
:
return
,
errIndexOutOfBounds
}
idx
++
}
}

// FindRange finds the elements of an array between the specified indexes; inclusive

FindRange finds the elements of an array between the specified indexes ; inclusive


func Object(in []byte, pos int) (int, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	if v := in[pos]; v != '{' {
		return 0, newError(pos, v)
	}
	pos++

	// clean initial spaces
	pos, err = skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	if in[pos] == '}' {
		return pos + 1, nil
	}

	for {
		// key
		pos, err = String(in, pos)
		if err != nil {
			return 0, err
		}

		// leading spaces
		pos, err = skipSpace(in, pos)
		if err != nil {
			return 0, err
		}

		// colon
		pos, err = expect(in, pos, ':')
		if err != nil {
			return 0, err
		}

		// data
		pos, err = Any(in, pos)
		if err != nil {
			return 0, err
		}

		pos, err = skipSpace(in, pos)
		if err != nil {
			return 0, err
		}

		switch in[pos] {
		case ',':
			pos++
		case '}':
			return pos + 1, nil
		}
	}
}

func
Object
(
in
[
]
byte
,
pos
int
)
(
int
,
error
)
{
pos
,
err
:=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
if
v
:=
in
[
pos
]
;
v
!=
'{'
{
return
0
,
newError
(
pos
,
v
)
}
pos
++
// clean initial spaces
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
if
in
[
pos
]
==
'}'
{
return
pos
+
1
,
}
for
{
// key
pos
,
err
=
String
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
// leading spaces
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
// colon
pos
,
err
=
expect
(
in
,
pos
,
':'
)
if
err
!=
{
return
0
,
err
}
// data
pos
,
err
=
Any
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
0
,
err
}
switch
in
[
pos
]
{
case
','
:
pos
++
case
'}'
:
return
pos
+
1
,
}
}
}

// Object returns the position of the end of the object that begins at the specified pos


func FindKey(in []byte, pos int, k []byte) ([]byte, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return nil, err
	}

	if v := in[pos]; v != '{' {
		return nil, newError(pos, v)
	}
	pos++

	for {
		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		keyStart := pos
		// key
		pos, err = String(in, pos)
		if err != nil {
			return nil, err
		}
		key := in[keyStart+1 : pos-1]
		match := bytes.Equal(k, key)

		// leading spaces
		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		// colon
		pos, err = expect(in, pos, ':')
		if err != nil {
			return nil, err
		}

		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		valueStart := pos
		// data
		pos, err = Any(in, pos)
		if err != nil {
			return nil, err
		}

		if match {
			return in[valueStart:pos], nil
		}

		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		switch in[pos] {
		case ',':
			pos++
		case '}':
			return nil, errKeyNotFound
		}
	}
}

func
FindKey
(
in
[
]
byte
,
pos
int
,
k
[
]
byte
)
(
[
]
byte
,
error
)
{
pos
,
err
:=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
v
:=
in
[
pos
]
;
v
!=
'{'
{
return
,
newError
(
pos
,
v
)
}
pos
++
for
{
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
keyStart
:=
pos
// key
pos
,
err
=
String
(
in
,
pos
)
if
err
!=
{
return
,
err
}
key
:=
in
[
keyStart
+
1
:
pos
1
]
match
:=
bytes
.
Equal
(
k
,
key
)
// leading spaces
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
// colon
pos
,
err
=
expect
(
in
,
pos
,
':'
)
if
err
!=
{
return
,
err
}
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
valueStart
:=
pos
// data
pos
,
err
=
Any
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
match
{
return
in
[
valueStart
:
pos
]
,
}
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
switch
in
[
pos
]
{
case
','
:
pos
++
case
'}'
:
return
,
errKeyNotFound
}
}
}

// FindKey accepts a JSON object and returns the value associated with the key specified


func FindIndex(in []byte, pos, index int) ([]byte, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return nil, err
	}

	if v := in[pos]; v != '[' {
		return nil, newError(pos, v)
	}
	pos++

	idx := 0
	for {
		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		itemStart := pos
		// data
		pos, err = Any(in, pos)
		if err != nil {
			return nil, err
		}
		if index == idx {
			return in[itemStart:pos], nil
		}

		pos, err = skipSpace(in, pos)
		if err != nil {
			return nil, err
		}

		switch in[pos] {
		case ',':
			pos++
		case ']':
			return nil, errIndexOutOfBounds
		}

		idx++
	}
}

func
FindIndex
(
in
[
]
byte
,
pos
,
index
int
)
(
[
]
byte
,
error
)
{
pos
,
err
:=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
v
:=
in
[
pos
]
;
v
!=
'['
{
return
,
newError
(
pos
,
v
)
}
pos
++
idx
:=
0
for
{
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
itemStart
:=
pos
// data
pos
,
err
=
Any
(
in
,
pos
)
if
err
!=
{
return
,
err
}
if
index
==
idx
{
return
in
[
itemStart
:
pos
]
,
}
pos
,
err
=
skipSpace
(
in
,
pos
)
if
err
!=
{
return
,
err
}
switch
in
[
pos
]
{
case
','
:
pos
++
case
']'
:
return
,
errIndexOutOfBounds
}
idx
++
}
}

// FindIndex accepts a JSON array and return the value of the element at the specified index


func Dot(key string) OpFunc {
	key = strings.TrimSpace(key)
	if key == "" {
		return func(in []byte) ([]byte, error) { return in, nil }
	}

	k := []byte(key)

	return func(in []byte) ([]byte, error) {
		return scanner.FindKey(in, 0, k)
	}
}

func Dot ( key string ) OpFunc { key = strings . TrimSpace ( key ) if key == " " { return func ( in [ ] byte ) ( [ ] byte , error ) { return in , nil } } k := [ ] byte ( key ) return func ( in [ ] byte ) ( [ ] byte , error ) { return scanner . FindKey ( in , 0 , k ) } }

// Dot extract the specific key from the map provided; to extract a nested value, use the Dot Op in conjunction with the
// Chain Op

Dot extract the specific key from the map provided ; to extract a nested value use the Dot Op in conjunction with the Chain Op


func Chain(filters ...Op) OpFunc {
	return func(in []byte) ([]byte, error) {
		if filters == nil {
			return in, nil
		}

		var err error
		data := in
		for _, filter := range filters {
			data, err = filter.Apply(data)
			if err != nil {
				return nil, err
			}
		}

		return data, nil
	}
}

func Chain ( filters ... Op ) OpFunc { return func ( in [ ] byte ) ( [ ] byte , error ) { if filters == nil { return in , nil } var err error data := in for _ , filter := range filters { data , err = filter . Apply ( data ) if err != nil { return nil , err } } return data , nil } }

// Chain executes a series of operations in the order provided


func Index(index int) OpFunc {
	return func(in []byte) ([]byte, error) {
		return scanner.FindIndex(in, 0, index)
	}
}

func Index ( index int ) OpFunc { return func ( in [ ] byte ) ( [ ] byte , error ) { return scanner . FindIndex ( in , 0 , index ) } }

// Index extracts a specific element from the array provided


func Range(from, to int) OpFunc {
	return func(in []byte) ([]byte, error) {
		return scanner.FindRange(in, 0, from, to)
	}
}

func Range ( from , to int ) OpFunc { return func ( in [ ] byte ) ( [ ] byte , error ) { return scanner . FindRange ( in , 0 , from , to ) } }

// Range extracts a selection of elements from the array provided, inclusive

Range extracts a selection of elements from the array provided inclusive


func String(in []byte, pos int) (int, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	max := len(in)

	if v := in[pos]; v != '"' {
		return 0, newError(pos, v)
	}
	pos++

	for {
		switch in[pos] {
		case '\\':
			if in[pos+1] == '"' {
				pos++
			}
		case '"':
			return pos + 1, nil
		}
		pos++

		if pos >= max {
			break
		}
	}

	return 0, errors.New("unclosed string")
}

func String ( in [ ] byte , pos int ) ( int , error ) { pos , err := skipSpace ( in , pos ) if err != nil { return 0 , err } max := len ( in ) if v := in [ pos ] ; v != '"' { return 0 , newError ( pos , v ) } pos ++ for { switch in [ pos ] { case '\\' : if in [ pos + 1 ] == '"' { pos ++ } case '"' : return pos + 1 , nil } pos ++ if pos >= max { break } } return 0 , errors . New ( " " ) }

// String returns the position of the string that begins at the specified pos


func Boolean(in []byte, pos int) (int, error) {
	switch in[pos] {
	case 't':
		return expect(in, pos, t...)
	case 'f':
		return expect(in, pos, f...)
	default:
		return 0, errUnexpectedValue
	}
}

func Boolean ( in [ ] byte , pos int ) ( int , error ) { switch in [ pos ] { case 't' : return expect ( in , pos , t ... ) case 'f' : return expect ( in , pos , f ... ) default : return 0 , errUnexpectedValue } }

// Boolean matches a boolean at the specified position


func Must(op Op, err error) Op {
	if err != nil {
		panic(fmt.Errorf("unable to parse selector; %v", err.Error()))
	}

	return op
}

func Must ( op Op , err error ) Op { if err != nil { panic ( fmt . Errorf ( " " , err . Error ( ) ) ) } return op }

// Must is a convenience method similar to template.Must

Must is a convenience method similar to template . Must


func Parse(selector string) (Op, error) {
	segments := strings.Split(selector, ".")

	ops := make([]Op, 0, len(segments))
	for _, segment := range segments {
		key := strings.TrimSpace(segment)
		if key == "" {
			continue
		}

		if op, ok := parseArray(key); ok {
			ops = append(ops, op)
			continue
		}

		ops = append(ops, Dot(key))
	}

	return Chain(ops...), nil
}

func Parse ( selector string ) ( Op , error ) { segments := strings . Split ( selector , " " ) ops := make ( [ ] Op , 0 , len ( segments ) ) for _ , segment := range segments { key := strings . TrimSpace ( segment ) if key == " " { continue } if op , ok := parseArray ( key ) ; ok { ops = append ( ops , op ) continue } ops = append ( ops , Dot ( key ) ) } return Chain ( ops ... ) , nil }

// Parse takes a string representation of a selector and returns the corresponding Op definition


func Any(in []byte, pos int) (int, error) {
	pos, err := skipSpace(in, pos)
	if err != nil {
		return 0, err
	}

	switch in[pos] {
	case '"':
		return String(in, pos)
	case '{':
		return Object(in, pos)
	case '.', '-', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0':
		return Number(in, pos)
	case '[':
		return Array(in, pos)
	case 't', 'f':
		return Boolean(in, pos)
	case 'n':
		return Null(in, pos)
	default:
		max := len(in) - pos
		if max > 20 {
			max = 20
		}

		return 0, opErr{
			pos:     pos,
			msg:     "invalid object",
			content: string(in[pos : pos+max]),
		}
	}
}

func Any ( in [ ] byte , pos int ) ( int , error ) { pos , err := skipSpace ( in , pos ) if err != nil { return 0 , err } switch in [ pos ] { case '"' : return String ( in , pos ) case '{' : return Object ( in , pos ) case '.' , '-' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' : return Number ( in , pos ) case '[' : return Array ( in , pos ) case 't' , 'f' : return Boolean ( in , pos ) case 'n' : return Null ( in , pos ) default : max := len ( in ) - pos if max > 20 { max = 20 } return 0 , opErr { pos : pos , msg : " " , content : string ( in [ pos : pos + max ] ) , } } }

// Any returns the position of the end of the current element that begins at pos; handles any valid json element

Any returns the position of the end of the current element that begins at pos ; handles any valid json element


func ProxyRequestFromContext(ctx context.Context) (events.APIGatewayProxyRequest, bool) {
	event, ok := ctx.Value(requestContextKey).(events.APIGatewayProxyRequest)
	return event, ok
}

func ProxyRequestFromContext ( ctx context . Context ) ( events . APIGatewayProxyRequest , bool ) { event , ok := ctx . Value ( requestContextKey ) . ( events . APIGatewayProxyRequest ) return event , ok }

// ProxyRequestFromContext extracts the APIGatewayProxyRequest event from ctx.

ProxyRequestFromContext extracts the APIGatewayProxyRequest event from ctx .


func DurationValue(v *strfmt.Duration) strfmt.Duration {
	if v == nil {
		return strfmt.Duration(0)
	}

	return *v
}

func DurationValue ( v * strfmt . Duration ) strfmt . Duration { if v == nil { return strfmt . Duration ( 0 ) } return * v }

// DurationValue returns the value of the Duration pointer passed in or
// the default value if the pointer is nil.

DurationValue returns the value of the Duration pointer passed in or the default value if the pointer is nil .


func Base64Value(v *strfmt.Base64) strfmt.Base64 {
	if v == nil {
		return nil
	}

	return *v
}

func Base64Value ( v * strfmt . Base64 ) strfmt . Base64 { if v == nil { return nil } return * v }

// Base64Value returns the value of the Base64 pointer passed in or
// the default value if the pointer is nil.

Base64Value returns the value of the Base64 pointer passed in or the default value if the pointer is nil .


func URIValue(v *strfmt.URI) strfmt.URI {
	if v == nil {
		return strfmt.URI("")
	}

	return *v
}

func URIValue ( v * strfmt . URI ) strfmt . URI { if v == nil { return strfmt . URI ( " " ) } return * v }

// URIValue returns the value of the URI pointer passed in or
// the default value if the pointer is nil.

URIValue returns the value of the URI pointer passed in or the default value if the pointer is nil .


func EmailValue(v *strfmt.Email) strfmt.Email {
	if v == nil {
		return strfmt.Email("")
	}

	return *v
}

func EmailValue ( v * strfmt . Email ) strfmt . Email { if v == nil { return strfmt . Email ( " " ) } return * v }

// EmailValue returns the value of the Email pointer passed in or
// the default value if the pointer is nil.

EmailValue returns the value of the Email pointer passed in or the default value if the pointer is nil .


func HostnameValue(v *strfmt.Hostname) strfmt.Hostname {
	if v == nil {
		return strfmt.Hostname("")
	}

	return *v
}

func HostnameValue ( v * strfmt . Hostname ) strfmt . Hostname { if v == nil { return strfmt . Hostname ( " " ) } return * v }

// HostnameValue returns the value of the Hostname pointer passed in or
// the default value if the pointer is nil.

HostnameValue returns the value of the Hostname pointer passed in or the default value if the pointer is nil .


func IPv4Value(v *strfmt.IPv4) strfmt.IPv4 {
	if v == nil {
		return strfmt.IPv4("")
	}

	return *v
}

func IPv4Value ( v * strfmt . IPv4 ) strfmt . IPv4 { if v == nil { return strfmt . IPv4 ( " " ) } return * v }

// IPv4Value returns the value of the IPv4 pointer passed in or
// the default value if the pointer is nil.

IPv4Value returns the value of the IPv4 pointer passed in or the default value if the pointer is nil .


func IPv6Value(v *strfmt.IPv6) strfmt.IPv6 {
	if v == nil {
		return strfmt.IPv6("")
	}

	return *v
}

func IPv6Value ( v * strfmt . IPv6 ) strfmt . IPv6 { if v == nil { return strfmt . IPv6 ( " " ) } return * v }

// IPv6Value returns the value of the IPv6 pointer passed in or
// the default value if the pointer is nil.

IPv6Value returns the value of the IPv6 pointer passed in or the default value if the pointer is nil .


func CIDRValue(v *strfmt.CIDR) strfmt.CIDR {
	if v == nil {
		return strfmt.CIDR("")
	}

	return *v
}

func CIDRValue ( v * strfmt . CIDR ) strfmt . CIDR { if v == nil { return strfmt . CIDR ( " " ) } return * v }

// CIDRValue returns the value of the CIDR pointer passed in or
// the default value if the pointer is nil.

CIDRValue returns the value of the CIDR pointer passed in or the default value if the pointer is nil .


func MACValue(v *strfmt.MAC) strfmt.MAC {
	if v == nil {
		return strfmt.MAC("")
	}

	return *v
}

func MACValue ( v * strfmt . MAC ) strfmt . MAC { if v == nil { return strfmt . MAC ( " " ) } return * v }

// MACValue returns the value of the MAC pointer passed in or
// the default value if the pointer is nil.

MACValue returns the value of the MAC pointer passed in or the default value if the pointer is nil .


func UUIDValue(v *strfmt.UUID) strfmt.UUID {
	if v == nil {
		return strfmt.UUID("")
	}

	return *v
}

func UUIDValue ( v * strfmt . UUID ) strfmt . UUID { if v == nil { return strfmt . UUID ( " " ) } return * v }

// UUIDValue returns the value of the UUID pointer passed in or
// the default value if the pointer is nil.

UUIDValue returns the value of the UUID pointer passed in or the default value if the pointer is nil .


func UUID3Value(v *strfmt.UUID3) strfmt.UUID3 {
	if v == nil {
		return strfmt.UUID3("")
	}

	return *v
}

func UUID3Value ( v * strfmt . UUID3 ) strfmt . UUID3 { if v == nil { return strfmt . UUID3 ( " " ) } return * v }

// UUID3Value returns the value of the UUID3 pointer passed in or
// the default value if the pointer is nil.

UUID3Value returns the value of the UUID3 pointer passed in or the default value if the pointer is nil .


func UUID4Value(v *strfmt.UUID4) strfmt.UUID4 {
	if v == nil {
		return strfmt.UUID4("")
	}

	return *v
}

func UUID4Value ( v * strfmt . UUID4 ) strfmt . UUID4 { if v == nil { return strfmt . UUID4 ( " " ) } return * v }

// UUID4Value returns the value of the UUID4 pointer passed in or
// the default value if the pointer is nil.

UUID4Value returns the value of the UUID4 pointer passed in or the default value if the pointer is nil .


func UUID5Value(v *strfmt.UUID5) strfmt.UUID5 {
	if v == nil {
		return strfmt.UUID5("")
	}

	return *v
}

func UUID5Value ( v * strfmt . UUID5 ) strfmt . UUID5 { if v == nil { return strfmt . UUID5 ( " " ) } return * v }

// UUID5Value returns the value of the UUID5 pointer passed in or
// the default value if the pointer is nil.

UUID5Value returns the value of the UUID5 pointer passed in or the default value if the pointer is nil .


func ISBNValue(v *strfmt.ISBN) strfmt.ISBN {
	if v == nil {
		return strfmt.ISBN("")
	}

	return *v
}

func ISBNValue ( v * strfmt . ISBN ) strfmt . ISBN { if v == nil { return strfmt . ISBN ( " " ) } return * v }

// ISBNValue returns the value of the ISBN pointer passed in or
// the default value if the pointer is nil.

ISBNValue returns the value of the ISBN pointer passed in or the default value if the pointer is nil .


func ISBN10Value(v *strfmt.ISBN10) strfmt.ISBN10 {
	if v == nil {
		return strfmt.ISBN10("")
	}

	return *v
}

func ISBN10Value ( v * strfmt . ISBN10 ) strfmt . ISBN10 { if v == nil { return strfmt . ISBN10 ( " " ) } return * v }

// ISBN10Value returns the value of the ISBN10 pointer passed in or
// the default value if the pointer is nil.

ISBN10Value returns the value of the ISBN10 pointer passed in or the default value if the pointer is nil .


func ISBN13Value(v *strfmt.ISBN13) strfmt.ISBN13 {
	if v == nil {
		return strfmt.ISBN13("")
	}

	return *v
}

func ISBN13Value ( v * strfmt . ISBN13 ) strfmt . ISBN13 { if v == nil { return strfmt . ISBN13 ( " " ) } return * v }

// ISBN13Value returns the value of the ISBN13 pointer passed in or
// the default value if the pointer is nil.

ISBN13Value returns the value of the ISBN13 pointer passed in or the default value if the pointer is nil .


func CreditCardValue(v *strfmt.CreditCard) strfmt.CreditCard {
	if v == nil {
		return strfmt.CreditCard("")
	}

	return *v
}

func CreditCardValue ( v * strfmt . CreditCard ) strfmt . CreditCard { if v == nil { return strfmt . CreditCard ( " " ) } return * v }

// CreditCardValue returns the value of the CreditCard pointer passed in or
// the default value if the pointer is nil.

CreditCardValue returns the value of the CreditCard pointer passed in or the default value if the pointer is nil .


func SSNValue(v *strfmt.SSN) strfmt.SSN {
	if v == nil {
		return strfmt.SSN("")
	}

	return *v
}

func SSNValue ( v * strfmt . SSN ) strfmt . SSN { if v == nil { return strfmt . SSN ( " " ) } return * v }

// SSNValue returns the value of the SSN pointer passed in or
// the default value if the pointer is nil.

SSNValue returns the value of the SSN pointer passed in or the default value if the pointer is nil .


func HexColorValue(v *strfmt.HexColor) strfmt.HexColor {
	if v == nil {
		return strfmt.HexColor("")
	}

	return *v
}

func HexColorValue ( v * strfmt . HexColor ) strfmt . HexColor { if v == nil { return strfmt . HexColor ( " " ) } return * v }

// HexColorValue returns the value of the HexColor pointer passed in or
// the default value if the pointer is nil.

HexColorValue returns the value of the HexColor pointer passed in or the default value if the pointer is nil .


func RGBColorValue(v *strfmt.RGBColor) strfmt.RGBColor {
	if v == nil {
		return strfmt.RGBColor("")
	}

	return *v
}

func RGBColorValue ( v * strfmt . RGBColor ) strfmt . RGBColor { if v == nil { return strfmt . RGBColor ( " " ) } return * v }

// RGBColorValue returns the value of the RGBColor pointer passed in or
// the default value if the pointer is nil.

RGBColorValue returns the value of the RGBColor pointer passed in or the default value if the pointer is nil .


func PasswordValue(v *strfmt.Password) strfmt.Password {
	if v == nil {
		return strfmt.Password("")
	}

	return *v
}

func PasswordValue ( v * strfmt . Password ) strfmt . Password { if v == nil { return strfmt . Password ( " " ) } return * v }

// PasswordValue returns the value of the Password pointer passed in or
// the default value if the pointer is nil.

PasswordValue returns the value of the Password pointer passed in or the default value if the pointer is nil .


func (id *ObjectId) MarshalJSON() ([]byte, error) {
	var w jwriter.Writer
	id.MarshalEasyJSON(&w)
	return w.BuildBytes()
}

func ( id * ObjectId ) MarshalJSON ( ) ( [ ] byte , error ) { var w jwriter . Writer id . MarshalEasyJSON ( & w ) return w . BuildBytes ( ) }

// MarshalJSON returns the ObjectId as JSON


func (id *ObjectId) MarshalEasyJSON(w *jwriter.Writer) {
	w.String(bson.ObjectId(*id).Hex())
}

func ( id * ObjectId ) MarshalEasyJSON ( w * jwriter . Writer ) { w . String ( bson . ObjectId ( * id ) . Hex ( ) ) }

// MarshalEasyJSON writes the ObjectId to a easyjson.Writer

MarshalEasyJSON writes the ObjectId to a easyjson . Writer


func (id *ObjectId) UnmarshalJSON(data []byte) error {
	l := jlexer.Lexer{Data: data}
	id.UnmarshalEasyJSON(&l)
	return l.Error()
}

func ( id * ObjectId ) UnmarshalJSON ( data [ ] byte ) error { l := jlexer . Lexer { Data : data } id . UnmarshalEasyJSON ( & l ) return l . Error ( ) }

// UnmarshalJSON sets the ObjectId from JSON


func (id *ObjectId) UnmarshalEasyJSON(in *jlexer.Lexer) {
	if data := in.String(); in.Ok() {
		*id = NewObjectId(data)
	}
}

func ( id * ObjectId ) UnmarshalEasyJSON ( in * jlexer . Lexer ) { if data := in . String ( ) ; in . Ok ( ) { * id = NewObjectId ( data ) } }

// UnmarshalEasyJSON sets the ObjectId from a easyjson.Lexer

UnmarshalEasyJSON sets the ObjectId from a easyjson . Lexer


func (id *ObjectId) SetBSON(raw bson.Raw) error {
	var m bson.M
	if err := raw.Unmarshal(&m); err != nil {
		return err
	}

	if data, ok := m["data"].(string); ok {
		*id = NewObjectId(data)
		return nil
	}

	return errors.New("couldn't unmarshal bson raw value as ObjectId")
}

func ( id * ObjectId ) SetBSON ( raw bson . Raw ) error { var m bson . M if err := raw . Unmarshal ( & m ) ; err != nil { return err } if data , ok := m [ " " ] . ( string ) ; ok { * id = NewObjectId ( data ) return nil } return errors . New ( " " ) }

// SetBSON sets the ObjectId from raw bson data


func (id *ObjectId) DeepCopy() *ObjectId {
	if id == nil {
		return nil
	}
	out := new(ObjectId)
	id.DeepCopyInto(out)
	return out
}

func ( id * ObjectId ) DeepCopy ( ) * ObjectId { if id == nil { return nil } out := new ( ObjectId ) id . DeepCopyInto ( out ) return out }

// DeepCopy copies the receiver into a new ObjectId.

DeepCopy copies the receiver into a new ObjectId .


func IsHostname(str string) bool {
	if !rxHostname.MatchString(str) {
		return false
	}

	// the sum of all label octets and label lengths is limited to 255.
	if len(str) > 255 {
		return false
	}

	// Each node has a label, which is zero to 63 octets in length
	parts := strings.Split(str, ".")
	valid := true
	for _, p := range parts {
		if len(p) > 63 {
			valid = false
		}
	}
	return valid
}

// IsHostname returns true when the string is a valid hostname


func IsEmail(str string) bool {
	addr, e := mail.ParseAddress(str)
	return e == nil && addr.Address != ""
}

func IsEmail ( str string ) bool { addr , e := mail . ParseAddress ( str ) return e == nil && addr . Address != " " }