<commit_before>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
	Package fmt implements formatted I/O with functions analogous
	to C's printf and scanf.  The format 'verbs' are derived from C's but
	are simpler.

	Printing

	The verbs:

	General:
		%v	the value in a default format.
			when printing structs, the plus flag (%+v) adds field names
		%#v	a Go-syntax representation of the value
		%T	a Go-syntax representation of the type of the value
		%%	a literal percent sign; consumes no value

	Boolean:
		%t	the word true or false
	Integer:
		%b	base 2
		%c	the character represented by the corresponding Unicode code point
		%d	base 10
		%o	base 8
		%q	a single-quoted character literal safely escaped with Go syntax.
		%x	base 16, with lower-case letters for a-f
		%X	base 16, with upper-case letters for A-F
		%U	Unicode format: U+1234; same as "U+%04X"
	Floating-point and complex constituents:
		%b	decimalless scientific notation with exponent a power of two,
			in the manner of strconv.FormatFloat with the 'b' format,
			e.g. -123456p-78
		%e	scientific notation, e.g. -1234.456e+78
		%E	scientific notation, e.g. -1234.456E+78
		%f	decimal point but no exponent, e.g. 123.456
		%F	synonym for %f
		%g	whichever of %e or %f produces more compact output
		%G	whichever of %E or %f produces more compact output
	String and slice of bytes:
		%s	the uninterpreted bytes of the string or slice
		%q	a double-quoted string safely escaped with Go syntax
		%x	base 16, lower-case, two characters per byte
		%X	base 16, upper-case, two characters per byte
	Pointer:
		%p	base 16 notation, with leading 0x

	There is no 'u' flag.  Integers are printed unsigned if they have unsigned type.
	Similarly, there is no need to specify the size of the operand (int8, int64).

	Width is specified by an optional decimal number immediately following the verb.
	If absent, the width is whatever is necessary to represent the value.
	Precision is specified after the (optional) width by a period followed by a
	decimal number. If no period is present, a default precision is used.
	A period with no following number specifies a precision of zero.
	Examples:
		%f:    default width, default precision
		%9f    width 9, default precision
		%.2f   default width, precision 2
		%9.2f  width 9, precision 2
		%9.f   width 9, precision 0

	Width and precision are measured in units of Unicode code points.
	(This differs from C's printf where the units are numbers
	of bytes.) Either or both of the flags may be replaced with the
	character '*', causing their values to be obtained from the next
	operand, which must be of type int.

	For most values, width is the minimum number of characters to output,
	padding the formatted form with spaces if necessary.
	For strings, precision is the maximum number of characters to output,
	truncating if necessary.

	For floating-point values, width sets the minimum width of the field and
	precision sets the number of places after the decimal, if appropriate,
	except that for %g/%G it sets the total number of digits. For example,
	given 123.45 the format %6.2f prints 123.45 while %.4g prints 123.5.
	The default precision for %e and %f is 6; for %g it is the smallest
	number of digits necessary to identify the value uniquely.

	For complex numbers, the width and precision apply to the two
	components independently and the result is parenthesized, so %f applied
	to 1.2+3.4i produces (1.200000+3.400000i).

	Other flags:
		+	always print a sign for numeric values;
			guarantee ASCII-only output for %q (%+q)
		-	pad with spaces on the right rather than the left (left-justify the field)
		#	alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
			0X for hex (%#X); suppress 0x for %p (%#p);
			for %q, print a raw (backquoted) string if strconv.CanBackquote
			returns true;
			write e.g. U+0078 'x' if the character is printable for %U (%#U).
		' '	(space) leave a space for elided sign in numbers (% d);
			put spaces between bytes printing strings or slices in hex (% x, % X)
		0	pad with leading zeros rather than spaces;
			for numbers, this moves the padding after the sign

	Flags are ignored by verbs that do not expect them.
	For example there is no alternate decimal format, so %#d and %d
	behave identically.

	For each Printf-like function, there is also a Print function
	that takes no format and is equivalent to saying %v for every
	operand.  Another variant Println inserts blanks between
	operands and appends a newline.

	Regardless of the verb, if an operand is an interface value,
	the internal concrete value is used, not the interface itself.
	Thus:
		var i interface{} = 23
		fmt.Printf("%v\n", i)
	will print 23.

	Except when printed using the verbs %T and %p, special
	formatting considerations apply for operands that implement
	certain interfaces. In order of application:

	1. If an operand implements the Formatter interface, it will
	be invoked. Formatter provides fine control of formatting.

	2. If the %v verb is used with the # flag (%#v) and the operand
	implements the GoStringer interface, that will be invoked.

	If the format (which is implicitly %v for Println etc.) is valid
	for a string (%s %q %v %x %X), the following two rules apply:

	3. If an operand implements the error interface, the Error method
	will be invoked to convert the object to a string, which will then
	be formatted as required by the verb (if any).

	4. If an operand implements method String() string, that method
	will be invoked to convert the object to a string, which will then
	be formatted as required by the verb (if any).

	For compound operands such as slices and structs, the format
	applies to the elements of each operand, recursively, not to the
	operand as a whole. Thus %q will quote each element of a slice
	of strings, and %6.2f will control formatting for each element
	of a floating-point array.

	To avoid recursion in cases such as
		type X string
		func (x X) String() string { return Sprintf("<%s>", x) }
	convert the value before recurring:
		func (x X) String() string { return Sprintf("<%s>", string(x)) }

	Explicit argument indexes:

	In Printf, Sprintf, and Fprintf, the default behavior is for each
	formatting verb to format successive arguments passed in the call.
	However, the notation [n] immediately before the verb indicates that the
	nth one-indexed argument is to be formatted instead. The same notation
	before a '*' for a width or precision selects the argument index holding
	the value. After processing a bracketed expression [n], arguments n+1,
	n+2, etc. will be processed unless otherwise directed.

	For example,
		fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
	will yield "22 11", while
		fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6),
	equivalent to
		fmt.Sprintf("%6.2f", 12.0),
	will yield " 12.00". Because an explicit index affects subsequent verbs,
	this notation can be used to print the same values multiple times
	by resetting the index for the first argument to be repeated:
		fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
	will yield "16 17 0x10 0x11".

	Format errors:

	If an invalid argument is given for a verb, such as providing
	a string to %d, the generated string will contain a
	description of the problem, as in these examples:

		Wrong type or unknown verb: %!verb(type=value)
			Printf("%d", hi):          %!d(string=hi)
		Too many arguments: %!(EXTRA type=value)
			Printf("hi", "guys"):      hi%!(EXTRA string=guys)
		Too few arguments: %!verb(MISSING)
			Printf("hi%d"):            hi %!d(MISSING)
		Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
			Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
			Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
		Invalid or invalid use of argument index: %!(BADINDEX)
			Printf("%*[2]d", 7):       %!d(BADINDEX)
			Printf("%.[2]d", 7):       %!d(BADINDEX)

	All errors begin with the string "%!" followed sometimes
	by a single character (the verb) and end with a parenthesized
	description.

	If an Error or String method triggers a panic when called by a
	print routine, the fmt package reformats the error message
	from the panic, decorating it with an indication that it came
	through the fmt package.  For example, if a String method
	calls panic("bad"), the resulting formatted message will look
	like
		%!s(PANIC=bad)

	The %!s just shows the print verb in use when the failure
	occurred.

	Scanning

	An analogous set of functions scans formatted text to yield
	values.  Scan, Scanf and Scanln read from os.Stdin; Fscan,
	Fscanf and Fscanln read from a specified io.Reader; Sscan,
	Sscanf and Sscanln read from an argument string.  Scanln,
	Fscanln and Sscanln stop scanning at a newline and require that
	the items be followed by one; Scanf, Fscanf and Sscanf require
	newlines in the input to match newlines in the format; the other
	routines treat newlines as spaces.

	Scanf, Fscanf, and Sscanf parse the arguments according to a
	format string, analogous to that of Printf.  For example, %x
	will scan an integer as a hexadecimal number, and %v will scan
	the default representation format for the value.

	The formats behave analogously to those of Printf with the
	following exceptions:

		%p is not implemented
		%T is not implemented
		%e %E %f %F %g %G are all equivalent and scan any floating point or complex value
		%s and %v on strings scan a space-delimited token
		Flags # and + are not implemented.

	The familiar base-setting prefixes 0 (octal) and 0x
	(hexadecimal) are accepted when scanning integers without a
	format or with the %v verb.

	Width is interpreted in the input text (%5s means at most
	five runes of input will be read to scan a string) but there
	is no syntax for scanning with a precision (no %5.2f, just
	%5f).

	When scanning with a format, all non-empty runs of space
	characters (except newline) are equivalent to a single
	space in both the format and the input.  With that proviso,
	text in the format string must match the input text; scanning
	stops if it does not, with the return value of the function
	indicating the number of arguments scanned.

	In all the scanning functions, a carriage return followed
	immediately by a newline is treated as a plain newline
	(\r\n means the same as \n).

	In all the scanning functions, if an operand implements method
	Scan (that is, it implements the Scanner interface) that
	method will be used to scan the text for that operand.  Also,
	if the number of arguments scanned is less than the number of
	arguments provided, an error is returned.

	All arguments to be scanned must be either pointers to basic
	types or implementations of the Scanner interface.

	Note: Fscan etc. can read one character (rune) past the input
	they return, which means that a loop calling a scan routine
	may skip some of the input.  This is usually a problem only
	when there is no space between input values.  If the reader
	provided to Fscan implements ReadRune, that method will be used
	to read characters.  If the reader also implements UnreadRune,
	that method will be used to save the character and successive
	calls will not lose data.  To attach ReadRune and UnreadRune
	methods to a reader without that capability, use
	bufio.NewReader.
*/
package fmt
<commit_msg>fmt: document that self-recursive data structures can be fatal<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
	Package fmt implements formatted I/O with functions analogous
	to C's printf and scanf.  The format 'verbs' are derived from C's but
	are simpler.

	Printing

	The verbs:

	General:
		%v	the value in a default format.
			when printing structs, the plus flag (%+v) adds field names
		%#v	a Go-syntax representation of the value
		%T	a Go-syntax representation of the type of the value
		%%	a literal percent sign; consumes no value

	Boolean:
		%t	the word true or false
	Integer:
		%b	base 2
		%c	the character represented by the corresponding Unicode code point
		%d	base 10
		%o	base 8
		%q	a single-quoted character literal safely escaped with Go syntax.
		%x	base 16, with lower-case letters for a-f
		%X	base 16, with upper-case letters for A-F
		%U	Unicode format: U+1234; same as "U+%04X"
	Floating-point and complex constituents:
		%b	decimalless scientific notation with exponent a power of two,
			in the manner of strconv.FormatFloat with the 'b' format,
			e.g. -123456p-78
		%e	scientific notation, e.g. -1234.456e+78
		%E	scientific notation, e.g. -1234.456E+78
		%f	decimal point but no exponent, e.g. 123.456
		%F	synonym for %f
		%g	whichever of %e or %f produces more compact output
		%G	whichever of %E or %f produces more compact output
	String and slice of bytes:
		%s	the uninterpreted bytes of the string or slice
		%q	a double-quoted string safely escaped with Go syntax
		%x	base 16, lower-case, two characters per byte
		%X	base 16, upper-case, two characters per byte
	Pointer:
		%p	base 16 notation, with leading 0x

	There is no 'u' flag.  Integers are printed unsigned if they have unsigned type.
	Similarly, there is no need to specify the size of the operand (int8, int64).

	Width is specified by an optional decimal number immediately following the verb.
	If absent, the width is whatever is necessary to represent the value.
	Precision is specified after the (optional) width by a period followed by a
	decimal number. If no period is present, a default precision is used.
	A period with no following number specifies a precision of zero.
	Examples:
		%f:    default width, default precision
		%9f    width 9, default precision
		%.2f   default width, precision 2
		%9.2f  width 9, precision 2
		%9.f   width 9, precision 0

	Width and precision are measured in units of Unicode code points.
	(This differs from C's printf where the units are numbers
	of bytes.) Either or both of the flags may be replaced with the
	character '*', causing their values to be obtained from the next
	operand, which must be of type int.

	For most values, width is the minimum number of characters to output,
	padding the formatted form with spaces if necessary.
	For strings, precision is the maximum number of characters to output,
	truncating if necessary.

	For floating-point values, width sets the minimum width of the field and
	precision sets the number of places after the decimal, if appropriate,
	except that for %g/%G it sets the total number of digits. For example,
	given 123.45 the format %6.2f prints 123.45 while %.4g prints 123.5.
	The default precision for %e and %f is 6; for %g it is the smallest
	number of digits necessary to identify the value uniquely.

	For complex numbers, the width and precision apply to the two
	components independently and the result is parenthesized, so %f applied
	to 1.2+3.4i produces (1.200000+3.400000i).

	Other flags:
		+	always print a sign for numeric values;
			guarantee ASCII-only output for %q (%+q)
		-	pad with spaces on the right rather than the left (left-justify the field)
		#	alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
			0X for hex (%#X); suppress 0x for %p (%#p);
			for %q, print a raw (backquoted) string if strconv.CanBackquote
			returns true;
			write e.g. U+0078 'x' if the character is printable for %U (%#U).
		' '	(space) leave a space for elided sign in numbers (% d);
			put spaces between bytes printing strings or slices in hex (% x, % X)
		0	pad with leading zeros rather than spaces;
			for numbers, this moves the padding after the sign

	Flags are ignored by verbs that do not expect them.
	For example there is no alternate decimal format, so %#d and %d
	behave identically.

	For each Printf-like function, there is also a Print function
	that takes no format and is equivalent to saying %v for every
	operand.  Another variant Println inserts blanks between
	operands and appends a newline.

	Regardless of the verb, if an operand is an interface value,
	the internal concrete value is used, not the interface itself.
	Thus:
		var i interface{} = 23
		fmt.Printf("%v\n", i)
	will print 23.

	Except when printed using the verbs %T and %p, special
	formatting considerations apply for operands that implement
	certain interfaces. In order of application:

	1. If an operand implements the Formatter interface, it will
	be invoked. Formatter provides fine control of formatting.

	2. If the %v verb is used with the # flag (%#v) and the operand
	implements the GoStringer interface, that will be invoked.

	If the format (which is implicitly %v for Println etc.) is valid
	for a string (%s %q %v %x %X), the following two rules apply:

	3. If an operand implements the error interface, the Error method
	will be invoked to convert the object to a string, which will then
	be formatted as required by the verb (if any).

	4. If an operand implements method String() string, that method
	will be invoked to convert the object to a string, which will then
	be formatted as required by the verb (if any).

	For compound operands such as slices and structs, the format
	applies to the elements of each operand, recursively, not to the
	operand as a whole. Thus %q will quote each element of a slice
	of strings, and %6.2f will control formatting for each element
	of a floating-point array.

	To avoid recursion in cases such as
		type X string
		func (x X) String() string { return Sprintf("<%s>", x) }
	convert the value before recurring:
		func (x X) String() string { return Sprintf("<%s>", string(x)) }
	Infinite recursion can also be triggered by self-referential data
	structures, such as a slice that contains itself as an element, if
	that type has a String method. Such pathologies are rare, however,
	and the package does not protect against them.

	Explicit argument indexes:

	In Printf, Sprintf, and Fprintf, the default behavior is for each
	formatting verb to format successive arguments passed in the call.
	However, the notation [n] immediately before the verb indicates that the
	nth one-indexed argument is to be formatted instead. The same notation
	before a '*' for a width or precision selects the argument index holding
	the value. After processing a bracketed expression [n], arguments n+1,
	n+2, etc. will be processed unless otherwise directed.

	For example,
		fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
	will yield "22 11", while
		fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6),
	equivalent to
		fmt.Sprintf("%6.2f", 12.0),
	will yield " 12.00". Because an explicit index affects subsequent verbs,
	this notation can be used to print the same values multiple times
	by resetting the index for the first argument to be repeated:
		fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
	will yield "16 17 0x10 0x11".

	Format errors:

	If an invalid argument is given for a verb, such as providing
	a string to %d, the generated string will contain a
	description of the problem, as in these examples:

		Wrong type or unknown verb: %!verb(type=value)
			Printf("%d", hi):          %!d(string=hi)
		Too many arguments: %!(EXTRA type=value)
			Printf("hi", "guys"):      hi%!(EXTRA string=guys)
		Too few arguments: %!verb(MISSING)
			Printf("hi%d"):            hi %!d(MISSING)
		Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
			Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
			Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
		Invalid or invalid use of argument index: %!(BADINDEX)
			Printf("%*[2]d", 7):       %!d(BADINDEX)
			Printf("%.[2]d", 7):       %!d(BADINDEX)

	All errors begin with the string "%!" followed sometimes
	by a single character (the verb) and end with a parenthesized
	description.

	If an Error or String method triggers a panic when called by a
	print routine, the fmt package reformats the error message
	from the panic, decorating it with an indication that it came
	through the fmt package.  For example, if a String method
	calls panic("bad"), the resulting formatted message will look
	like
		%!s(PANIC=bad)

	The %!s just shows the print verb in use when the failure
	occurred.

	Scanning

	An analogous set of functions scans formatted text to yield
	values.  Scan, Scanf and Scanln read from os.Stdin; Fscan,
	Fscanf and Fscanln read from a specified io.Reader; Sscan,
	Sscanf and Sscanln read from an argument string.  Scanln,
	Fscanln and Sscanln stop scanning at a newline and require that
	the items be followed by one; Scanf, Fscanf and Sscanf require
	newlines in the input to match newlines in the format; the other
	routines treat newlines as spaces.

	Scanf, Fscanf, and Sscanf parse the arguments according to a
	format string, analogous to that of Printf.  For example, %x
	will scan an integer as a hexadecimal number, and %v will scan
	the default representation format for the value.

	The formats behave analogously to those of Printf with the
	following exceptions:

		%p is not implemented
		%T is not implemented
		%e %E %f %F %g %G are all equivalent and scan any floating point or complex value
		%s and %v on strings scan a space-delimited token
		Flags # and + are not implemented.

	The familiar base-setting prefixes 0 (octal) and 0x
	(hexadecimal) are accepted when scanning integers without a
	format or with the %v verb.

	Width is interpreted in the input text (%5s means at most
	five runes of input will be read to scan a string) but there
	is no syntax for scanning with a precision (no %5.2f, just
	%5f).

	When scanning with a format, all non-empty runs of space
	characters (except newline) are equivalent to a single
	space in both the format and the input.  With that proviso,
	text in the format string must match the input text; scanning
	stops if it does not, with the return value of the function
	indicating the number of arguments scanned.

	In all the scanning functions, a carriage return followed
	immediately by a newline is treated as a plain newline
	(\r\n means the same as \n).

	In all the scanning functions, if an operand implements method
	Scan (that is, it implements the Scanner interface) that
	method will be used to scan the text for that operand.  Also,
	if the number of arguments scanned is less than the number of
	arguments provided, an error is returned.

	All arguments to be scanned must be either pointers to basic
	types or implementations of the Scanner interface.

	Note: Fscan etc. can read one character (rune) past the input
	they return, which means that a loop calling a scan routine
	may skip some of the input.  This is usually a problem only
	when there is no space between input values.  If the reader
	provided to Fscan implements ReadRune, that method will be used
	to read characters.  If the reader also implements UnreadRune,
	that method will be used to save the character and successive
	calls will not lose data.  To attach ReadRune and UnreadRune
	methods to a reader without that capability, use
	bufio.NewReader.
*/
package fmt
<|endoftext|>


<commit_before>// +build windows

package mousetrap

import (
    "os"
    "fmt"
    "syscall"
    "strings"
    "unsafe"
)

const (
    th32cs_snapprocess uintptr = 0x2
)

type processEntry32 struct {
    dwSize uint32
    cntUsage uint32
    th32ProcessID uint32
    th32DefaultHeapID int
    th32ModuleID uint32
    cntThreads uint32
    th32ParentProcessID uint32
    pcPriClassBase int32
    dwFlags uint32
    szExeFile [0x00000104]byte
}

func getProcessEntry(pid int) (pe *processEntry32, err error) {
    kernel := syscall.MustLoadDLL("kernel32.dll")
    CreateToolhelp32Snapshot := kernel.MustFindProc("CreateToolhelp32Snapshot")
    Process32First := kernel.MustFindProc("Process32First")
    Process32Next := kernel.MustFindProc("Process32Next")
    CloseHandle := kernel.MustFindProc("CloseHandle")

    snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0));
    if (snapshot == uintptr(syscall.InvalidHandle)) {
        err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
        return
    }

    var processEntry processEntry32
    processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
    ok, _ , e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
    if ok == 0 {
        err = fmt.Errorf("Process32First: %v", e1)
        goto closeHandle;
    }

    for {
        if processEntry.th32ProcessID == uint32(pid) {
            pe = &processEntry
            goto closeHandle;
        }

        ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
        if ok == 0 {
            err = fmt.Errorf("Process32Next: %v", e1)
            goto closeHandle;
        }
    }

closeHandle:
    CloseHandle.Call(snapshot);
    return
}

func getppid() (pid int, err error) {
    pe, err := getProcessEntry(os.Getpid())
    if err != nil {
        return
    }

    pid = int(pe.th32ParentProcessID)
    return
}

func InvokedFromCommandLine() (bool, error) {
    ppid, err := getppid()
    if err != nil {
        return true, err
    }

    pe, err := getProcessEntry(ppid)
    if err != nil {
        return true, err
    }

    var path string
    for i, b := range pe.szExeFile[:] {
        if b == 0 {
            path = string(pe.szExeFile[:i])
            break
        }
    }

    isExplorer := strings.HasSuffix(path, "explorer.exe")
    return !isExplorer, nil
}
<commit_msg>defer handle close<commit_after>// +build windows
package mousetrap

import (
    "os"
    "fmt"
    "syscall"
    "strings"
    "unsafe"
)

const (
    th32cs_snapprocess uintptr = 0x2
)

type processEntry32 struct {
    dwSize uint32
    cntUsage uint32
    th32ProcessID uint32
    th32DefaultHeapID int
    th32ModuleID uint32
    cntThreads uint32
    th32ParentProcessID uint32
    pcPriClassBase int32
    dwFlags uint32
    szExeFile [0x00000104]byte
}

func getProcessEntry(pid int) (pe *processEntry32, err error) {
    kernel := syscall.MustLoadDLL("kernel32.dll")
    CreateToolhelp32Snapshot := kernel.MustFindProc("CreateToolhelp32Snapshot")
    Process32First := kernel.MustFindProc("Process32First")
    Process32Next := kernel.MustFindProc("Process32Next")
    CloseHandle := kernel.MustFindProc("CloseHandle")

    snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0));
    if (snapshot == uintptr(syscall.InvalidHandle)) {
        err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
        return
    }
    defer CloseHandle.Call(snapshot)

    var processEntry processEntry32
    processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
    ok, _ , e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
    if ok == 0 {
        err = fmt.Errorf("Process32First: %v", e1)
        return
    }

    for {
        if processEntry.th32ProcessID == uint32(pid) {
            pe = &processEntry
            return
        }

        ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
        if ok == 0 {
            err = fmt.Errorf("Process32Next: %v", e1)
            return
        }
    }
}

func getppid() (pid int, err error) {
    pe, err := getProcessEntry(os.Getpid())
    if err != nil {
        return
    }

    pid = int(pe.th32ParentProcessID)
    return
}

func InvokedFromCommandLine() (bool, error) {
    ppid, err := getppid()
    if err != nil {
        return true, err
    }

    pe, err := getProcessEntry(ppid)
    if err != nil {
        return true, err
    }

    var path string
    for i, b := range pe.szExeFile[:] {
        if b == 0 {
            path = string(pe.szExeFile[:i])
            break
        }
    }

    isExplorer := strings.HasSuffix(path, "explorer.exe")
    return !isExplorer, nil
}
<|endoftext|>


<commit_before>package nomad

import (
	"fmt"
	"log"
	"math/rand"
	"net"
	"sync/atomic"
	"time"

	"github.com/hashicorp/consul/lib/freeport"
	"github.com/hashicorp/nomad/command/agent/consul"
	"github.com/hashicorp/nomad/helper/testlog"
	"github.com/hashicorp/nomad/nomad/mock"
	"github.com/hashicorp/nomad/nomad/structs"
	"github.com/mitchellh/go-testing-interface"
)

var (
	nodeNumber uint32 = 0
)

func TestACLServer(t testing.T, cb func(*Config)) (*Server, *structs.ACLToken) {
	server := TestServer(t, func(c *Config) {
		c.ACLEnabled = true
		if cb != nil {
			cb(c)
		}
	})
	token := mock.ACLManagementToken()
	err := server.State().BootstrapACLTokens(1, 0, token)
	if err != nil {
		t.Fatalf("failed to bootstrap ACL token: %v", err)
	}
	return server, token
}

func TestServer(t testing.T, cb func(*Config)) *Server {
	// Setup the default settings
	config := DefaultConfig()
	config.Build = "0.7.0+unittest"
	config.DevMode = true
	nodeNum := atomic.AddUint32(&nodeNumber, 1)
	config.NodeName = fmt.Sprintf("nomad-%03d", nodeNum)

	// Tighten the Serf timing
	config.SerfConfig.MemberlistConfig.BindAddr = "127.0.0.1"
	config.SerfConfig.MemberlistConfig.SuspicionMult = 2
	config.SerfConfig.MemberlistConfig.RetransmitMult = 2
	config.SerfConfig.MemberlistConfig.ProbeTimeout = 50 * time.Millisecond
	config.SerfConfig.MemberlistConfig.ProbeInterval = 100 * time.Millisecond
	config.SerfConfig.MemberlistConfig.GossipInterval = 100 * time.Millisecond

	// Tighten the Raft timing
	config.RaftConfig.LeaderLeaseTimeout = 50 * time.Millisecond
	config.RaftConfig.HeartbeatTimeout = 50 * time.Millisecond
	config.RaftConfig.ElectionTimeout = 50 * time.Millisecond
	config.RaftTimeout = 500 * time.Millisecond

	// Disable Vault
	f := false
	config.VaultConfig.Enabled = &f

	// Squelch output when -v isn't specified
	config.LogOutput = testlog.NewWriter(t)

	// Invoke the callback if any
	if cb != nil {
		cb(config)
	}

	// Enable raft as leader if we have bootstrap on
	config.RaftConfig.StartAsLeader = !config.DevDisableBootstrap

	logger := log.New(config.LogOutput, fmt.Sprintf("[%s] ", config.NodeName), log.LstdFlags)
	catalog := consul.NewMockCatalog(logger)

	for i := 10; i >= 0; i-- {
		// Get random ports
		ports := freeport.GetT(t, 2)
		config.RPCAddr = &net.TCPAddr{
			IP:   []byte{127, 0, 0, 1},
			Port: ports[0],
		}
		config.SerfConfig.MemberlistConfig.BindPort = ports[1]

		// Create server
		server, err := NewServer(config, catalog, logger)
		if err == nil {
			return server
		} else if i == 0 {
			t.Fatalf("err: %v", err)
		} else {
			if server != nil {
				server.Shutdown()
			}
			wait := time.Duration(rand.Int31n(2000)) * time.Millisecond
			time.Sleep(wait)
		}
	}

	return nil
}

func TestJoin(t testing.T, s1 *Server, other ...*Server) {
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfConfig.MemberlistConfig.BindPort)
	for _, s2 := range other {
		if num, err := s2.Join([]string{addr}); err != nil {
			t.Fatalf("err: %v", err)
		} else if num != 1 {
			t.Fatalf("bad: %d", num)
		}
	}
}
<commit_msg>Fix autopilot tests<commit_after>package nomad

import (
	"fmt"
	"log"
	"math/rand"
	"net"
	"sync/atomic"
	"time"

	"github.com/hashicorp/consul/lib/freeport"
	"github.com/hashicorp/nomad/command/agent/consul"
	"github.com/hashicorp/nomad/helper/testlog"
	"github.com/hashicorp/nomad/nomad/mock"
	"github.com/hashicorp/nomad/nomad/structs"
	"github.com/mitchellh/go-testing-interface"
)

var (
	nodeNumber uint32 = 0
)

func TestACLServer(t testing.T, cb func(*Config)) (*Server, *structs.ACLToken) {
	server := TestServer(t, func(c *Config) {
		c.ACLEnabled = true
		if cb != nil {
			cb(c)
		}
	})
	token := mock.ACLManagementToken()
	err := server.State().BootstrapACLTokens(1, 0, token)
	if err != nil {
		t.Fatalf("failed to bootstrap ACL token: %v", err)
	}
	return server, token
}

func TestServer(t testing.T, cb func(*Config)) *Server {
	// Setup the default settings
	config := DefaultConfig()
	config.Build = "0.8.0+unittest"
	config.DevMode = true
	nodeNum := atomic.AddUint32(&nodeNumber, 1)
	config.NodeName = fmt.Sprintf("nomad-%03d", nodeNum)

	// Tighten the Serf timing
	config.SerfConfig.MemberlistConfig.BindAddr = "127.0.0.1"
	config.SerfConfig.MemberlistConfig.SuspicionMult = 2
	config.SerfConfig.MemberlistConfig.RetransmitMult = 2
	config.SerfConfig.MemberlistConfig.ProbeTimeout = 50 * time.Millisecond
	config.SerfConfig.MemberlistConfig.ProbeInterval = 100 * time.Millisecond
	config.SerfConfig.MemberlistConfig.GossipInterval = 100 * time.Millisecond

	// Tighten the Raft timing
	config.RaftConfig.LeaderLeaseTimeout = 50 * time.Millisecond
	config.RaftConfig.HeartbeatTimeout = 50 * time.Millisecond
	config.RaftConfig.ElectionTimeout = 50 * time.Millisecond
	config.RaftTimeout = 500 * time.Millisecond

	// Disable Vault
	f := false
	config.VaultConfig.Enabled = &f

	// Squelch output when -v isn't specified
	config.LogOutput = testlog.NewWriter(t)

	// Tighten the autopilot timing
	config.AutopilotConfig.ServerStabilizationTime = 100 * time.Millisecond
	config.ServerHealthInterval = 50 * time.Millisecond
	config.AutopilotInterval = 100 * time.Millisecond

	// Invoke the callback if any
	if cb != nil {
		cb(config)
	}

	// Enable raft as leader if we have bootstrap on
	config.RaftConfig.StartAsLeader = !config.DevDisableBootstrap

	logger := log.New(config.LogOutput, fmt.Sprintf("[%s] ", config.NodeName), log.LstdFlags)
	catalog := consul.NewMockCatalog(logger)

	for i := 10; i >= 0; i-- {
		// Get random ports
		ports := freeport.GetT(t, 2)
		config.RPCAddr = &net.TCPAddr{
			IP:   []byte{127, 0, 0, 1},
			Port: ports[0],
		}
		config.SerfConfig.MemberlistConfig.BindPort = ports[1]

		// Create server
		server, err := NewServer(config, catalog, logger)
		if err == nil {
			return server
		} else if i == 0 {
			t.Fatalf("err: %v", err)
		} else {
			if server != nil {
				server.Shutdown()
			}
			wait := time.Duration(rand.Int31n(2000)) * time.Millisecond
			time.Sleep(wait)
		}
	}

	return nil
}

func TestJoin(t testing.T, s1 *Server, other ...*Server) {
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfConfig.MemberlistConfig.BindPort)
	for _, s2 := range other {
		if num, err := s2.Join([]string{addr}); err != nil {
			t.Fatalf("err: %v", err)
		} else if num != 1 {
			t.Fatalf("bad: %d", num)
		}
	}
}
<|endoftext|>


<commit_before>package notice

import (
	"encoding/json"
	"fmt"
	"net/http"

	"appengine"
	"appengine/taskqueue"
)

func init() { http.HandleFunc("/", handler) }

func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	// Decode the name and bucket of the notification
	var n struct {
		Name   string `json:"name"`
		Bucket string `json:"bucket"`
	}
	err := json.NewDecoder(r.Body).Decode(&n)
	if err != nil {
		c.Errorf("invalid notification: %v", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Add a new task to the queue
	t := &taskqueue.Task{
		Method:  "PULL",
		Payload: []byte(n.Bucket + "/" + n.Name),
	}
	_, err = taskqueue.Add(c, t, "abelana-in")
	if err != nil {
		c.Errorf("add task to queue: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	fmt.Fprintln(w, "OK")
}
<commit_msg>added missing return<commit_after>package notice

import (
	"encoding/json"
	"fmt"
	"net/http"

	"appengine"
	"appengine/taskqueue"
)

func init() { http.HandleFunc("/", handler) }

func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	// Decode the name and bucket of the notification
	var n struct {
		Name   string `json:"name"`
		Bucket string `json:"bucket"`
	}
	err := json.NewDecoder(r.Body).Decode(&n)
	if err != nil {
		c.Errorf("invalid notification: %v", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Add a new task to the queue
	t := &taskqueue.Task{
		Method:  "PULL",
		Payload: []byte(n.Bucket + "/" + n.Name),
	}
	_, err = taskqueue.Add(c, t, "abelana-in")
	if err != nil {
		c.Errorf("add task to queue: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Fprintln(w, "OK")
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package btcws

import (
	"encoding/json"
	"errors"
	"github.com/conformal/btcjson"
)

var (
	// ErrNtfnUnexpected describes an error where an unexpected
	// notification is received when unmarshaling into a concrete
	// Notification variable.
	ErrNtfnUnexpected = errors.New("notification unexpected")

	// ErrNtfnNotFound describes an error where a parser does not
	// handle unmarshaling a notification.
	ErrNtfnNotFound = errors.New("notification not found")
)

const (
	// BlockConnectedNtfnId is the id of the btcd blockconnected
	// notification.
	BlockConnectedNtfnId = "btcd:blockconnected"

	// BlockDisconnectedNtfnId is the id of the btcd blockdisconnected
	// notification.
	BlockDisconnectedNtfnId = "btcd:blockdisconnected"

	//TxMinedNtfnId is the id of the btcd txmined notification.
	TxMinedNtfnId = "btcd:txmined"
)

type newNtfnFn func() Notification

func newBlockConnectedNtfn() Notification {
	return &BlockConnectedNtfn{}
}

func newBlockDisconnectedNtfn() Notification {
	return &BlockDisconnectedNtfn{}
}

func newTxMinedNtfn() Notification {
	return &TxMinedNtfn{}
}

var newNtfnFns = map[string]newNtfnFn{
	BlockConnectedNtfnId:    newBlockConnectedNtfn,
	BlockDisconnectedNtfnId: newBlockDisconnectedNtfn,
	TxMinedNtfnId:           newTxMinedNtfn,
}

// ParseMarshaledNtfn attempts to unmarshal a marshaled notification
// into the notification described by id.
func ParseMarshaledNtfn(id string, b []byte) (Notification, error) {
	if newFn, ok := newNtfnFns[id]; ok {
		n := newFn()
		if err := n.UnmarshalJSON(b); err != nil {
			return nil, err
		}
		return n, nil
	}
	return nil, ErrNtfnNotFound
}

// Notification is an interface implemented by all notification types.
type Notification interface {
	json.Marshaler
	json.Unmarshaler
	Id() interface{}
}

// BlockConnectedNtfn is a type handling custom marshaling and
// unmarshaling of blockconnected JSON websocket notifications.
type BlockConnectedNtfn struct {
	Hash   string `json:"hash"`
	Height int32  `json:"height"`
}

type blockConnectedResult BlockConnectedNtfn

// Enforce that BlockConnectedNtfn satisfies the Notification interface.
var _ Notification = &BlockConnectedNtfn{}

// NewBlockConnectedNtfn creates a new BlockConnectedNtfn.
func NewBlockConnectedNtfn(hash string, height int32) *BlockConnectedNtfn {
	return &BlockConnectedNtfn{
		Hash:   hash,
		Height: height,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *BlockConnectedNtfn) Id() interface{} {
	return BlockConnectedNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *BlockConnectedNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *BlockConnectedNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result blockConnectedResult `json:"result"`
		Error  *btcjson.Error       `json:"error"`
		Id     interface{}          `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = BlockConnectedNtfn(ntfn.Result)
	return nil
}

// BlockDisconnectedNtfn is a type handling custom marshaling and
// unmarshaling of blockdisconnected JSON websocket notifications.
type BlockDisconnectedNtfn struct {
	Hash   string `json:"hash"`
	Height int32  `json:"height"`
}

type blockDisconnectedResult BlockDisconnectedNtfn

// Enforce that BlockDisconnectedNtfn satisfies the Notification interface.
var _ Notification = &BlockDisconnectedNtfn{}

// NewBlockDisconnectedNtfn creates a new BlockConnectedNtfn.
func NewBlockDisconnectedNtfn(hash string, height int32) *BlockDisconnectedNtfn {
	return &BlockDisconnectedNtfn{
		Hash:   hash,
		Height: height,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *BlockDisconnectedNtfn) Id() interface{} {
	return BlockDisconnectedNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *BlockDisconnectedNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *BlockDisconnectedNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result blockDisconnectedResult `json:"result"`
		Error  *btcjson.Error          `json:"error"`
		Id     interface{}             `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = BlockDisconnectedNtfn(ntfn.Result)
	return nil
}

// TxMinedNtfn is a type handling custom marshaling and
// unmarshaling of txmined JSON websocket notifications.
type TxMinedNtfn struct {
	TxID        string `json:"txid"`
	BlockHash   string `json:"blockhash"`
	BlockHeight int32  `json:"blockheight"`
	BlockTime   int64  `json:"blocktime"`
	Index       int    `json:"index"`
}

type txMinedResult TxMinedNtfn

// Enforce that TxMinedNtfn satisfies the Notification interface.
var _ Notification = &TxMinedNtfn{}

// NewTxMinedNtfn creates a new TxMinedNtfn.
func NewTxMinedNtfn(txid, blockhash string, blockheight int32,
	blocktime int64, index int) *TxMinedNtfn {

	return &TxMinedNtfn{
		TxID:        txid,
		BlockHash:   blockhash,
		BlockHeight: blockheight,
		BlockTime:   blocktime,
		Index:       index,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *TxMinedNtfn) Id() interface{} {
	return TxMinedNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *TxMinedNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *TxMinedNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result txMinedResult  `json:"result"`
		Error  *btcjson.Error `json:"error"`
		Id     interface{}    `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = TxMinedNtfn(ntfn.Result)
	return nil
}
<commit_msg>Add btcwallet:newtx notification support.<commit_after>// Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package btcws

import (
	"encoding/json"
	"errors"
	"github.com/conformal/btcjson"
)

var (
	// ErrNtfnUnexpected describes an error where an unexpected
	// notification is received when unmarshaling into a concrete
	// Notification variable.
	ErrNtfnUnexpected = errors.New("notification unexpected")

	// ErrNtfnNotFound describes an error where a parser does not
	// handle unmarshaling a notification.
	ErrNtfnNotFound = errors.New("notification not found")
)

const (
	// BlockConnectedNtfnId is the id of the btcd blockconnected
	// notification.
	BlockConnectedNtfnId = "btcd:blockconnected"

	// BlockDisconnectedNtfnId is the id of the btcd blockdisconnected
	// notification.
	BlockDisconnectedNtfnId = "btcd:blockdisconnected"

	// TxMinedNtfnId is the id of the btcd txmined notification.
	TxMinedNtfnId = "btcd:txmined"

	// TxNtfnId is the id of the btcwallet newtx notification.
	TxNtfnId = "btcwallet:newtx"
)

type newNtfnFn func() Notification

func newBlockConnectedNtfn() Notification {
	return &BlockConnectedNtfn{}
}

func newBlockDisconnectedNtfn() Notification {
	return &BlockDisconnectedNtfn{}
}

func newTxMinedNtfn() Notification {
	return &TxMinedNtfn{}
}

func newTxNtfn() Notification {
	return &TxNtfn{}
}

var newNtfnFns = map[string]newNtfnFn{
	BlockConnectedNtfnId:    newBlockConnectedNtfn,
	BlockDisconnectedNtfnId: newBlockDisconnectedNtfn,
	TxMinedNtfnId:           newTxMinedNtfn,
	TxNtfnId:                newTxNtfn,
}

// ParseMarshaledNtfn attempts to unmarshal a marshaled notification
// into the notification described by id.
func ParseMarshaledNtfn(id string, b []byte) (Notification, error) {
	if newFn, ok := newNtfnFns[id]; ok {
		n := newFn()
		if err := n.UnmarshalJSON(b); err != nil {
			return nil, err
		}
		return n, nil
	}
	return nil, ErrNtfnNotFound
}

// Notification is an interface implemented by all notification types.
type Notification interface {
	json.Marshaler
	json.Unmarshaler
	Id() interface{}
}

// BlockConnectedNtfn is a type handling custom marshaling and
// unmarshaling of blockconnected JSON websocket notifications.
type BlockConnectedNtfn struct {
	Hash   string `json:"hash"`
	Height int32  `json:"height"`
}

type blockConnectedResult BlockConnectedNtfn

// Enforce that BlockConnectedNtfn satisfies the Notification interface.
var _ Notification = &BlockConnectedNtfn{}

// NewBlockConnectedNtfn creates a new BlockConnectedNtfn.
func NewBlockConnectedNtfn(hash string, height int32) *BlockConnectedNtfn {
	return &BlockConnectedNtfn{
		Hash:   hash,
		Height: height,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *BlockConnectedNtfn) Id() interface{} {
	return BlockConnectedNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *BlockConnectedNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *BlockConnectedNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result blockConnectedResult `json:"result"`
		Error  *btcjson.Error       `json:"error"`
		Id     interface{}          `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = BlockConnectedNtfn(ntfn.Result)
	return nil
}

// BlockDisconnectedNtfn is a type handling custom marshaling and
// unmarshaling of blockdisconnected JSON websocket notifications.
type BlockDisconnectedNtfn struct {
	Hash   string `json:"hash"`
	Height int32  `json:"height"`
}

type blockDisconnectedResult BlockDisconnectedNtfn

// Enforce that BlockDisconnectedNtfn satisfies the Notification interface.
var _ Notification = &BlockDisconnectedNtfn{}

// NewBlockDisconnectedNtfn creates a new BlockConnectedNtfn.
func NewBlockDisconnectedNtfn(hash string, height int32) *BlockDisconnectedNtfn {
	return &BlockDisconnectedNtfn{
		Hash:   hash,
		Height: height,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *BlockDisconnectedNtfn) Id() interface{} {
	return BlockDisconnectedNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *BlockDisconnectedNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *BlockDisconnectedNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result blockDisconnectedResult `json:"result"`
		Error  *btcjson.Error          `json:"error"`
		Id     interface{}             `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = BlockDisconnectedNtfn(ntfn.Result)
	return nil
}

// TxMinedNtfn is a type handling custom marshaling and
// unmarshaling of txmined JSON websocket notifications.
type TxMinedNtfn struct {
	TxID        string `json:"txid"`
	BlockHash   string `json:"blockhash"`
	BlockHeight int32  `json:"blockheight"`
	BlockTime   int64  `json:"blocktime"`
	Index       int    `json:"index"`
}

type txMinedResult TxMinedNtfn

// Enforce that TxMinedNtfn satisfies the Notification interface.
var _ Notification = &TxMinedNtfn{}

// NewTxMinedNtfn creates a new TxMinedNtfn.
func NewTxMinedNtfn(txid, blockhash string, blockheight int32,
	blocktime int64, index int) *TxMinedNtfn {

	return &TxMinedNtfn{
		TxID:        txid,
		BlockHash:   blockhash,
		BlockHeight: blockheight,
		BlockTime:   blocktime,
		Index:       index,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *TxMinedNtfn) Id() interface{} {
	return TxMinedNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *TxMinedNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *TxMinedNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result txMinedResult  `json:"result"`
		Error  *btcjson.Error `json:"error"`
		Id     interface{}    `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = TxMinedNtfn(ntfn.Result)
	return nil
}

// TxNtfn is a type handling custom marshaling and
// unmarshaling of newtx JSON websocket notifications.
type TxNtfn struct {
	Account string `json:"account"`
	Details map[string]interface{} `json:"details"`
}

type txNtfnResult TxNtfn

// Enforce that TxNtfn satisfies the Notification interface.
var _ Notification = &TxNtfn{}

// NewTxNtfn creates a new TxNtfn.
func NewTxNtfn(account string, details map[string]interface{}) *TxNtfn {
	return &TxNtfn{
		Account: account,
		Details: details,
	}
}

// Id satisifies the Notification interface by returning the id of the
// notification.
func (n *TxNtfn) Id() interface{} {
	return TxNtfnId
}

// MarshalJSON returns the JSON encoding of n.  Part of the Notification
// interface.
func (n *TxNtfn) MarshalJSON() ([]byte, error) {
	id := n.Id()
	reply := btcjson.Reply{
		Result: *n,
		Id:     &id,
	}
	return json.Marshal(reply)
}

// UnmarshalJSON unmarshals the JSON encoding of n into n.  Part of
// the Notification interface.
func (n *TxNtfn) UnmarshalJSON(b []byte) error {
	var ntfn struct {
		Result txNtfnResult   `json:"result"`
		Error  *btcjson.Error `json:"error"`
		Id     interface{}    `json:"id"`
	}
	if err := json.Unmarshal(b, &ntfn); err != nil {
		return err
	}

	// Notification IDs must match expected.
	if n.Id() != ntfn.Id {
		return ErrNtfnUnexpected
	}

	*n = TxNtfn(ntfn.Result)
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package lxc

import (
	"fmt"

	"launchpad.net/juju-core/instance"
)

type lxcInstance struct {
	id string
}

// Id returns a provider-generated identifier for the Instance.
func (lxc *lxcInstance) Id() instance.Id {
	return instance.Id(lxc.id)
}

// DNSName returns the DNS name for the instance.
// If the name is not yet allocated, it will return
// an ErrNoDNSName error.
func (lxc *lxcInstance) DNSName() (string, error) {
	return "", instance.ErrNoDNSName
}

// WaitDNSName returns the DNS name for the instance,
// waiting until it is allocated if necessary.
func (lxc *lxcInstance) WaitDNSName() (string, error) {
	return "", instance.ErrNoDNSName
}

// OpenPorts opens the given ports on the instance, which
// should have been started with the given machine id.
func (lxc *lxcInstance) OpenPorts(machineId string, ports []instance.Port) error {
	return fmt.Errorf("not implemented")
}

// ClosePorts closes the given ports on the instance, which
// should have been started with the given machine id.
func (lxc *lxcInstance) ClosePorts(machineId string, ports []instance.Port) error {
	return fmt.Errorf("not implemented")
}

// Ports returns the set of ports open on the instance, which
// should have been started with the given machine id.
// The ports are returned as sorted by state.SortPorts.
func (lxc *lxcInstance) Ports(machineId string) ([]instance.Port, error) {
	return nil, fmt.Errorf("not implemented")
}

// Metadata returns the characteristics of the instance.
func (lxc *lxcInstance) Metadata() *instance.Metadata {
	return nil
}
<commit_msg>Add explicit interface implementation check, and change function comments.<commit_after>// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package lxc

import (
	"fmt"

	"launchpad.net/juju-core/instance"
)

type lxcInstance struct {
	id string
}

var _ instance.Instance = (*lxcInstance)(nil)

// Id implements instance.Instance.Id.
func (lxc *lxcInstance) Id() instance.Id {
	return instance.Id(lxc.id)
}

// DNSName implements instance.Instance.DNSName.
func (lxc *lxcInstance) DNSName() (string, error) {
	return "", instance.ErrNoDNSName
}

// WaitDNSName implements instance.Instance.WaitDNSName.
func (lxc *lxcInstance) WaitDNSName() (string, error) {
	return "", instance.ErrNoDNSName
}

// OpenPorts implements instance.Instance.OpenPorts.
func (lxc *lxcInstance) OpenPorts(machineId string, ports []instance.Port) error {
	return fmt.Errorf("not implemented")
}

// ClosePorts implements instance.Instance.ClosePorts.
func (lxc *lxcInstance) ClosePorts(machineId string, ports []instance.Port) error {
	return fmt.Errorf("not implemented")
}

// Ports implements instance.Instance.Ports.
func (lxc *lxcInstance) Ports(machineId string) ([]instance.Port, error) {
	return nil, fmt.Errorf("not implemented")
}

// Metadata implements instance.Instance.Metadata.
func (lxc *lxcInstance) Metadata() *instance.Metadata {
	return nil
}
<|endoftext|>


<commit_before>package irc

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"testing"
)

func TestEncode(t *testing.T) {

	var err error
	var n int
	target := ":Namename!username@hostname COMMAND arg1 arg2 arg3 arg4 arg5 arg6 arg7 :Message message message message message\r\n"

	msg := &Msg{prefix: s2b("Namename!username@hostname"),
		cmd:      s2b("COMMAND"),
		trailing: s2b("Message message message message message"),
	}

	msg.SetParams(bytes.Split(s2b("arg1 arg2 arg3 arg4 arg5 arg6 arg7"), []byte{space})...)

	buf := bytes.NewBuffer([]byte{})
	enc := NewEncoder(buf)
	n, err = enc.Encode(msg)

	if n == 0 || err != nil || buf.String() != target {
		t.Error(n, err, fmt.Sprintf("+%x+", buf.String()))
	}
}

func TestEncodeEmptyMsg(t *testing.T) {
	msg := new(Msg)
	msg.SetParams(bytes.Split(s2b("arg1 arg2 arg3 arg4 arg5 arg6 arg7"), []byte{space})...)
	buf := bytes.NewBuffer([]byte{})
	enc := NewEncoder(buf)
	n, err := enc.Encode(msg)

	if err == nil {
		t.Error(n, err, fmt.Sprintf("+%x+", buf.String()))
	}

}

func BenchmarkEncoder(b *testing.B) {
	msg := new(Msg)
	name := s2b("Namename")
	cmd := s2b("COMMAND")
	trailing := s2b("Message message message message message")
	params := bytes.Split(s2b("arg1 arg2 arg3 arg4 arg5 arg6 arg7"), []byte{space})
	enc := NewEncoder(ioutil.Discard)
	msg.SetParams(params...)
	msg.SetCmd(cmd)
	msg.SetTrailing(trailing)
	msg.SetName(name)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		n, err := enc.Encode(msg)
		if n == 0 || err != nil {
			b.Fatal(n, err, msg)
		}
	}
}
<commit_msg>add encoder example<commit_after>package irc

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"testing"
)

func TestEncode(t *testing.T) {

	var err error
	var n int
	target := ":Namename!username@hostname COMMAND arg1 arg2 arg3 arg4 arg5 arg6 arg7 :Message message message message message\r\n"

	msg := &Msg{prefix: s2b("Namename!username@hostname"),
		cmd:      s2b("COMMAND"),
		trailing: s2b("Message message message message message"),
	}

	msg.SetParams(bytes.Split(s2b("arg1 arg2 arg3 arg4 arg5 arg6 arg7"), []byte{space})...)

	buf := bytes.NewBuffer([]byte{})
	enc := NewEncoder(buf)
	n, err = enc.Encode(msg)

	if n == 0 || err != nil || buf.String() != target {
		t.Error(n, err, fmt.Sprintf("+%x+", buf.String()))
	}
}

func ExampleEncoder() {
	buf := bytes.NewBuffer([]byte{})
	enc := NewEncoder(buf)
	msg := new(Msg)
	msg.SetCmd([]byte("NICK"))
	msg.SetParams([]byte("hello world"))
	_, _ = enc.Encode(msg)
	fmt.Println(buf.String()) // NICK
}

func TestEncodeEmptyMsg(t *testing.T) {
	msg := new(Msg)
	msg.SetParams(bytes.Split(s2b("arg1 arg2 arg3 arg4 arg5 arg6 arg7"), []byte{space})...)
	buf := bytes.NewBuffer([]byte{})
	enc := NewEncoder(buf)
	n, err := enc.Encode(msg)

	if err == nil {
		t.Error(n, err, fmt.Sprintf("+%x+", buf.String()))
	}

}

func BenchmarkEncoder(b *testing.B) {
	msg := new(Msg)
	name := s2b("Namename")
	cmd := s2b("COMMAND")
	trailing := s2b("Message message message message message")
	params := bytes.Split(s2b("arg1 arg2 arg3 arg4 arg5 arg6 arg7"), []byte{space})
	enc := NewEncoder(ioutil.Discard)
	msg.SetParams(params...)
	msg.SetCmd(cmd)
	msg.SetTrailing(trailing)
	msg.SetName(name)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		n, err := enc.Encode(msg)
		if n == 0 || err != nil {
			b.Fatal(n, err, msg)
		}
	}
}
<|endoftext|>


<commit_before>package engineio

import (
	"fmt"
)

type XHR struct {
	Polling
}

func (xhr *XHR) InitXHR(req *Request) {
	xhr.InitPolling(req)
	xhr.Polling.doWrite = func(data []byte) {
		contentType := "text/plains; charset=UTF-8"
		contentLength := fmt.Sprintf("%d", len(data))
		xhr.res.Header().Set("Content-Type", contentType)
		xhr.res.Header().Set("Content-Length", contentLength)
		xhr.headers(req)
		xhr.res.WriteHeader(200)
		xhr.res.Write(data)
	}

	xhr.Polling.headers = func(req *Request) {
		xhr.Emit("headers", req.res.Header())
	}
}

func (xhr *XHR) onRequest(req *Request) {
	if "OPTIONS" == req.httpReq.Method {
		res := req.res
		xhr.headers(req)
		res.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		res.WriteHeader(200)
		res.Write([]byte("TEST"))
	} else {
		xhr.Polling.onRequest(req)
	}
}
<commit_msg>cleanup debug info.<commit_after>package engineio

import (
	"fmt"
)

type XHR struct {
	Polling
}

func (xhr *XHR) InitXHR(req *Request) {
	xhr.InitPolling(req)
	xhr.Polling.doWrite = func(data []byte) {
		contentType := "text/plains; charset=UTF-8"
		contentLength := fmt.Sprintf("%d", len(data))
		xhr.res.Header().Set("Content-Type", contentType)
		xhr.res.Header().Set("Content-Length", contentLength)
		xhr.headers(req)
		xhr.res.WriteHeader(200)
		xhr.res.Write(data)
	}

	xhr.Polling.headers = func(req *Request) {
		xhr.Emit("headers", req.res.Header())
	}
}

func (xhr *XHR) onRequest(req *Request) {
	if "OPTIONS" == req.httpReq.Method {
		res := req.res
		xhr.headers(req)
		res.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		res.WriteHeader(200)
		res.Write(nil)
	} else {
		xhr.Polling.onRequest(req)
	}
}
<|endoftext|>


<commit_before>package goStrongswanVici

import (
	"fmt"
	"strconv"
)

//from list-sa event
type IkeSa struct {
	Uniqueid        string               `json:"uniqueid"` //called ike_id in terminate() argument.
	Version         string               `json:"version"`
	State           string               `json:"state"` //had saw: ESTABLISHED
	Local_host      string               `json:"local-host"`
	Local_port      string               `json:"local-port"`
	Local_id        string               `json:"local-id"`
	Remote_host     string               `json:"remote-host"`
	Remote_port     string               `json:"remote-port"`
	Remote_id       string               `json:"remote-id"`
	Remote_xauth_id string               `json:"remote-xauth-id"` //client username
	Initiator       string               `json:"initiator"`
	Initiator_spi   string               `json:"initiator-spi"`
	Responder_spi   string               `json:"responder-spi"`
	Encr_alg        string               `json:"encr-alg"`
	Encr_keysize    string               `json:"encr-keysize"`
	Integ_alg       string               `json:"integ-alg"`
	Integ_keysize   string               `json:"integ-keysize"`
	Prf_alg         string               `json:"prf-alg"`
	Dh_group        string               `json:"dh-group"`
	Established     string               `json:"established"`
	Rekey_time      string               `json:"rekey-time"`
	Reauth_time     string               `json:"reauth-time"`
	Remote_vips     []string             `json:"remote-vips"`
	Child_sas       map[string]Child_sas `json:"child-sas"` //key means child-sa-name(conn name in ipsec.conf)
}

type Child_sas struct {
	Reqid         string   `json:"reqid"`
	State         string   `json:"state"` //had saw: INSTALLED
	Mode          string   `json:"mode"`  //had saw: TUNNEL
	Protocol      string   `json:"protocol"`
	Encap         string   `json:"encap"`
	Spi_in        string   `json:"spi-in"`
	Spi_out       string   `json:"spi-out"`
	Cpi_in        string   `json:"cpi-in"`
	Cpi_out       string   `json:"cpi-out"`
	Encr_alg      string   `json:"encr-alg"`
	Encr_keysize  string   `json:"encr-keysize"`
	Integ_alg     string   `json:"integ-alg"`
	Integ_keysize string   `json:"integ-keysize"`
	Prf_alg       string   `json:"prf-alg"`
	Dh_group      string   `json:"dh-group"`
	Esn           string   `json:"esn"`
	Bytes_in      string   `json:"bytes-in"` //bytes into this machine
	Packets_in    string   `json:"packets-in"`
	Use_in        string   `json:"use-in"`
	Bytes_out     string   `json:"bytes-out"` // bytes out of this machine
	Packets_out   string   `json:"packets-out"`
	Use_out       string   `json:"use-out"`
	Rekey_time    string   `json:"rekey-time"`
	Life_time     string   `json:"life-time"`
	Install_time  string   `json:"install-time"`
	Local_ts      []string `json:"local-ts"`
	Remote_ts     []string `json:"remote-ts"`
}

func (s *Child_sas) GetBytesIn() uint64 {
	num, err := strconv.ParseUint(s.Bytes_in, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

func (s *Child_sas) GetBytesOut() uint64 {
	num, err := strconv.ParseUint(s.Bytes_out, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

// To be simple, list all clients that are connecting to this server .
// A client is a sa.
// Lists currently active IKE_SAs
func (c *ClientConn) ListSas(ike string, ike_id string) (sas []map[string]IkeSa, err error) {
	sas = []map[string]IkeSa{}
	var eventErr error
	//register event
	err = c.RegisterEvent("list-sa", func(response map[string]interface{}) {
		sa := &map[string]IkeSa{}
		err = ConvertFromGeneral(response, sa)
		if err != nil {
			fmt.Printf("list-sa event error: %s\n", err)
			eventErr = err
			return
		}
		sas = append(sas, *sa)
		//fmt.Printf("event %#v\n", response)
	})
	if err != nil {
		return
	}
	if eventErr != nil {
		return
	}

	inMap := map[string]interface{}{}
	if ike != "" {
		inMap["ike"] = ike
	}
	if ike_id != "" {
		inMap["ike_id"] = ike_id
	}
	_, err = c.Request("list-sas", inMap)
	if err != nil {
		return
	}
	//fmt.Printf("request finish %#v\n", sas)
	err = c.UnregisterEvent("list-sa")
	if err != nil {
		return
	}
	return
}

//a vpn conn in the strongswan server
type VpnConnInfo struct {
	IkeSa
	Child_sas
	IkeSaName   string //looks like conn name in ipsec.conf, content is same as ChildSaName
	ChildSaName string //looks like conn name in ipsec.conf
}

func (c *VpnConnInfo) GuessUserName() string {
	if c.Remote_xauth_id != "" {
		return c.Remote_xauth_id
	}
	if c.Remote_id != "" {
		return c.Remote_id
	}
	return ""
}

// a helper method to avoid complex data struct in ListSas
// if it only have one child_sas ,it will put it into info.Child_sas
func (c *ClientConn) ListAllVpnConnInfo() (list []VpnConnInfo, err error) {
	sasList, err := c.ListSas("", "")
	if err != nil {
		return
	}
	list = make([]VpnConnInfo, len(sasList))
	for i, sa := range sasList {
		info := VpnConnInfo{}
		if len(sa) != 1 {
			fmt.Printf("[vici.ListAllVpnConnInfo] warning: len(sa)[%d]!=1\n", len(sa))
		}
		for ikeSaName, ikeSa := range sa {
			info.IkeSaName = ikeSaName
			info.IkeSa = ikeSa
			//if len(ikeSa.Child_sas) != 1 {
			//	fmt.Println("[vici.ListAllVpnConnInfo] warning: len(ikeSa.Child_sas)[%d]!=1", len(ikeSa.Child_sas))
			//}
			for childSaName, childSa := range ikeSa.Child_sas {
				info.ChildSaName = childSaName
				info.Child_sas = childSa
				break
			}
			break
		}
		if len(info.IkeSa.Child_sas) == 1 {
			info.IkeSa.Child_sas = nil
		}
		list[i] = info
	}
	return
}
<commit_msg>Add queued tasks information to list SA infor per doc<commit_after>package goStrongswanVici

import (
	"fmt"
	"strconv"
)

//from list-sa event
type IkeSa struct {
	Uniqueid        string               `json:"uniqueid"` //called ike_id in terminate() argument.
	Version         string               `json:"version"`
	State           string               `json:"state"` //had saw: ESTABLISHED
	Local_host      string               `json:"local-host"`
	Local_port      string               `json:"local-port"`
	Local_id        string               `json:"local-id"`
	Remote_host     string               `json:"remote-host"`
	Remote_port     string               `json:"remote-port"`
	Remote_id       string               `json:"remote-id"`
	Remote_xauth_id string               `json:"remote-xauth-id"` //client username
	Initiator       string               `json:"initiator"`
	Initiator_spi   string               `json:"initiator-spi"`
	Responder_spi   string               `json:"responder-spi"`
	Encr_alg        string               `json:"encr-alg"`
	Encr_keysize    string               `json:"encr-keysize"`
	Integ_alg       string               `json:"integ-alg"`
	Integ_keysize   string               `json:"integ-keysize"`
	Prf_alg         string               `json:"prf-alg"`
	Dh_group        string               `json:"dh-group"`
	Established     string               `json:"established"`
	Rekey_time      string               `json:"rekey-time"`
	Reauth_time     string               `json:"reauth-time"`
	Remote_vips     []string             `json:"remote-vips"`
	Child_sas       map[string]Child_sas `json:"child-sas"` //key means child-sa-name(conn name in ipsec.conf)
	Tasks_active    []string             `json:"tasks-active"`
}

type Child_sas struct {
	Reqid         string   `json:"reqid"`
	State         string   `json:"state"` //had saw: INSTALLED
	Mode          string   `json:"mode"`  //had saw: TUNNEL
	Protocol      string   `json:"protocol"`
	Encap         string   `json:"encap"`
	Spi_in        string   `json:"spi-in"`
	Spi_out       string   `json:"spi-out"`
	Cpi_in        string   `json:"cpi-in"`
	Cpi_out       string   `json:"cpi-out"`
	Encr_alg      string   `json:"encr-alg"`
	Encr_keysize  string   `json:"encr-keysize"`
	Integ_alg     string   `json:"integ-alg"`
	Integ_keysize string   `json:"integ-keysize"`
	Prf_alg       string   `json:"prf-alg"`
	Dh_group      string   `json:"dh-group"`
	Esn           string   `json:"esn"`
	Bytes_in      string   `json:"bytes-in"` //bytes into this machine
	Packets_in    string   `json:"packets-in"`
	Use_in        string   `json:"use-in"`
	Bytes_out     string   `json:"bytes-out"` // bytes out of this machine
	Packets_out   string   `json:"packets-out"`
	Use_out       string   `json:"use-out"`
	Rekey_time    string   `json:"rekey-time"`
	Life_time     string   `json:"life-time"`
	Install_time  string   `json:"install-time"`
	Local_ts      []string `json:"local-ts"`
	Remote_ts     []string `json:"remote-ts"`
}

func (s *Child_sas) GetBytesIn() uint64 {
	num, err := strconv.ParseUint(s.Bytes_in, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

func (s *Child_sas) GetBytesOut() uint64 {
	num, err := strconv.ParseUint(s.Bytes_out, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

func (s *Child_sas) GetPacketsIn() uint64 {
	num, err := strconv.ParseUint(s.Packets_in, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

func (s *Child_sas) GetPacketsOut() uint64 {
	num, err := strconv.ParseUint(s.Packets_out, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

// To be simple, list all clients that are connecting to this server .
// A client is a sa.
// Lists currently active IKE_SAs
func (c *ClientConn) ListSas(ike string, ike_id string) (sas []map[string]IkeSa, err error) {
	sas = []map[string]IkeSa{}
	var eventErr error
	//register event
	err = c.RegisterEvent("list-sa", func(response map[string]interface{}) {
		sa := &map[string]IkeSa{}
		err = ConvertFromGeneral(response, sa)
		if err != nil {
			fmt.Printf("list-sa event error: %s\n", err)
			eventErr = err
			return
		}
		sas = append(sas, *sa)
		//fmt.Printf("event %#v\n", response)
	})
	if err != nil {
		return
	}
	if eventErr != nil {
		return
	}

	inMap := map[string]interface{}{}
	if ike != "" {
		inMap["ike"] = ike
	}
	if ike_id != "" {
		inMap["ike_id"] = ike_id
	}
	_, err = c.Request("list-sas", inMap)
	if err != nil {
		return
	}
	//fmt.Printf("request finish %#v\n", sas)
	err = c.UnregisterEvent("list-sa")
	if err != nil {
		return
	}
	return
}

//a vpn conn in the strongswan server
type VpnConnInfo struct {
	IkeSa
	Child_sas
	IkeSaName   string //looks like conn name in ipsec.conf, content is same as ChildSaName
	ChildSaName string //looks like conn name in ipsec.conf
}

func (c *VpnConnInfo) GuessUserName() string {
	if c.Remote_xauth_id != "" {
		return c.Remote_xauth_id
	}
	if c.Remote_id != "" {
		return c.Remote_id
	}
	return ""
}

// a helper method to avoid complex data struct in ListSas
// if it only have one child_sas ,it will put it into info.Child_sas
func (c *ClientConn) ListAllVpnConnInfo() (list []VpnConnInfo, err error) {
	sasList, err := c.ListSas("", "")
	if err != nil {
		return
	}
	list = make([]VpnConnInfo, len(sasList))
	for i, sa := range sasList {
		info := VpnConnInfo{}
		if len(sa) != 1 {
			fmt.Printf("[vici.ListAllVpnConnInfo] warning: len(sa)[%d]!=1\n", len(sa))
		}
		for ikeSaName, ikeSa := range sa {
			info.IkeSaName = ikeSaName
			info.IkeSa = ikeSa
			//if len(ikeSa.Child_sas) != 1 {
			//	fmt.Println("[vici.ListAllVpnConnInfo] warning: len(ikeSa.Child_sas)[%d]!=1", len(ikeSa.Child_sas))
			//}
			for childSaName, childSa := range ikeSa.Child_sas {
				info.ChildSaName = childSaName
				info.Child_sas = childSa
				break
			}
			break
		}
		if len(info.IkeSa.Child_sas) == 1 {
			info.IkeSa.Child_sas = nil
		}
		list[i] = info
	}
	return
}
<|endoftext|>


<commit_before>/*

	golden is a package designed to make it possible to compare a game to a
	golden run for testing purposes. It takes a record saved in
	storage/filesystem format and compares it.

*/
package golden

import (
	"errors"
	"github.com/jkomoros/boardgame"
	"github.com/jkomoros/boardgame/storage/filesystem/record"
	"github.com/jkomoros/boardgame/storage/memory"
	"github.com/yudai/gojsondiff"
	"github.com/yudai/gojsondiff/formatter"
	"io/ioutil"
	"path/filepath"
	"reflect"
	"strconv"
)

//Compare is the primary method in the package. It takes a game delegate and a
//filename denoting a record to compare against. delegate shiould be a fresh
//delegate not yet affiliated with a manager. It compares every version and
//move in the history (ignoring things that shouldn't be the same, like
//timestamps) and reports the first place they divrge. Any time it finds a
//move not proposed by AdminPlayerIndex it will propose that move. As long as
//your game uses state.Rand() for all randomness and is otherwise
//deterministic then everything should work.
func Compare(delegate boardgame.GameDelegate, recFilename string) error {

	manager, err := boardgame.NewGameManager(delegate, memory.NewStorageManager())

	if err != nil {
		return errors.New("Couldn't create new manager: " + err.Error())
	}

	rec, err := record.New(recFilename)

	if err != nil {
		return errors.New("Couldn't create record: " + err.Error())
	}

	return compare(manager, rec)

}

//CompareFolder is like Compare, except it will iterate through any file in
//recFolder that ends in .json. Errors if any of those files cannot be parsed
//into recs.
func CompareFolder(delegate boardgame.GameDelegate, recFolder string) error {
	manager, err := boardgame.NewGameManager(delegate, memory.NewStorageManager())

	if err != nil {
		return errors.New("Couldn't create new manager: " + err.Error())
	}

	infos, err := ioutil.ReadDir(recFolder)

	if err != nil {
		return errors.New("Couldn't read folder: " + err.Error())
	}

	for _, info := range infos {
		if info.IsDir() {
			continue
		}

		if filepath.Ext(info.Name()) != ".json" {
			continue
		}

		rec, err := record.New(filepath.Join(recFolder, info.Name()))

		if err != nil {
			return errors.New("File with name " + info.Name() + " couldn't be loaded into rec: " + err.Error())
		}

		if err := compare(manager, rec); err != nil {
			return errors.New("File named " + info.Name() + " had compare error: " + err.Error())
		}

	}

	return nil
}

func compare(manager *boardgame.GameManager, rec *record.Record) error {
	game, err := manager.Internals().RecreateGame(rec.Game())

	if err != nil {
		return errors.New("Couldn't create game: " + err.Error())
	}

	lastVerifiedVersion := 0

	for !game.Finished() {
		//Verify all new moves that have happened since the last time we
		//checked (often, fix-up moves).
		for lastVerifiedVersion < game.Version() {
			stateToCompare, err := rec.State(lastVerifiedVersion)

			if err != nil {
				return errors.New("Couldn't get " + strconv.Itoa(lastVerifiedVersion) + " state: " + err.Error())
			}

			if err := compareJsonBlobs(game.State(lastVerifiedVersion).StorageRecord(), stateToCompare); err != nil {
				return errors.New("State " + strconv.Itoa(lastVerifiedVersion) + " compared differently: " + err.Error())
			}

			if lastVerifiedVersion > 0 {

				//Version 0 has no associated move

				recMove, err := rec.Move(lastVerifiedVersion)

				if err != nil {
					return errors.New("Couldn't get move " + strconv.Itoa(lastVerifiedVersion) + " from record")
				}

				moves := game.MoveRecords(lastVerifiedVersion)

				if len(moves) < 1 {
					return errors.New("Didn't fetch historical move records for " + strconv.Itoa(lastVerifiedVersion))
				}

				//Warning: records are modified by this method
				if err := compareMoveStorageRecords(moves[len(moves)-1], recMove); err != nil {
					return errors.New("Move " + strconv.Itoa(lastVerifiedVersion) + " compared differently: " + err.Error())
				}
			}

			lastVerifiedVersion++
		}

		nextMoveRec, err := rec.Move(lastVerifiedVersion + 1)

		if err != nil {
			//We'll assume that menas that's all of the moves there are to make.
			break
		}

		if nextMoveRec.Proposer < 0 {
			//We could be waiting for a timer to fire.
			//If there was a timer, try to force it to fire early.
			if manager.Internals().ForceNextTimer() {
				continue
			}

			//There wasn't a timer pending, so it's just an error
			return errors.New("At version " + strconv.Itoa(lastVerifiedVersion) + " the next player move to apply was not applied by a player")
		}

		nextMove, err := nextMoveRec.Inflate(game)

		if err != nil {
			return errors.New("Couldn't inflate move: " + err.Error())
		}

		if err := <-game.ProposeMove(nextMove, nextMoveRec.Proposer); err != nil {
			return errors.New("Couldn't propose next move in chain: " + err.Error())
		}

	}

	if game.Finished() != rec.Game().Finished {
		return errors.New("Game finished did not match rec")
	}

	if !reflect.DeepEqual(game.Winners(), rec.Game().Winners) {
		return errors.New("Game winners did not match")
	}

	return nil
}

var differ = gojsondiff.New()

var diffformatter = formatter.NewDeltaFormatter()

func compareJsonBlobs(one, two []byte) error {

	diff, err := differ.Compare(one, two)

	if err != nil {
		return errors.New("Couldn't diff: " + err.Error())
	}

	if diff.Modified() {

		str, err := diffformatter.Format(diff)

		if err != nil {
			return errors.New("Couldn't format diff: " + err.Error())
		}

		return errors.New("Diff: " + str)
	}

	return nil

}

//warning: modifies the records
func compareMoveStorageRecords(one, two *boardgame.MoveStorageRecord) error {

	if one == nil {
		return errors.New("One was nil")
	}

	if two == nil {
		return errors.New("Two was nil")
	}

	oneBlob := one.Blob
	twoBlob := two.Blob

	//Set the fields we know might differ to known values
	one.Blob = nil
	two.Blob = nil

	two.Timestamp = one.Timestamp

	if !reflect.DeepEqual(one, two) {
		return errors.New("Move storage records differed in base fields")
	}

	return compareJsonBlobs(oneBlob, twoBlob)

}
<commit_msg>Fixed a MADDENING bug that was preventing games with Timers from working correctly. game.State(version).StorageRecord() doesn't necessarily match what's in storage, for one type only: Timers, since they rely on timerManager state. Took a note about it. Part of #648.<commit_after>/*

	golden is a package designed to make it possible to compare a game to a
	golden run for testing purposes. It takes a record saved in
	storage/filesystem format and compares it.

*/
package golden

import (
	"errors"
	"github.com/jkomoros/boardgame"
	"github.com/jkomoros/boardgame/storage/filesystem/record"
	"github.com/jkomoros/boardgame/storage/memory"
	"github.com/yudai/gojsondiff"
	"github.com/yudai/gojsondiff/formatter"
	"io/ioutil"
	"path/filepath"
	"reflect"
	"strconv"
)

//Compare is the primary method in the package. It takes a game delegate and a
//filename denoting a record to compare against. delegate shiould be a fresh
//delegate not yet affiliated with a manager. It compares every version and
//move in the history (ignoring things that shouldn't be the same, like
//timestamps) and reports the first place they divrge. Any time it finds a
//move not proposed by AdminPlayerIndex it will propose that move. As long as
//your game uses state.Rand() for all randomness and is otherwise
//deterministic then everything should work.
func Compare(delegate boardgame.GameDelegate, recFilename string) error {

	manager, err := boardgame.NewGameManager(delegate, memory.NewStorageManager())

	if err != nil {
		return errors.New("Couldn't create new manager: " + err.Error())
	}

	rec, err := record.New(recFilename)

	if err != nil {
		return errors.New("Couldn't create record: " + err.Error())
	}

	return compare(manager, rec)

}

//CompareFolder is like Compare, except it will iterate through any file in
//recFolder that ends in .json. Errors if any of those files cannot be parsed
//into recs.
func CompareFolder(delegate boardgame.GameDelegate, recFolder string) error {
	manager, err := boardgame.NewGameManager(delegate, memory.NewStorageManager())

	if err != nil {
		return errors.New("Couldn't create new manager: " + err.Error())
	}

	infos, err := ioutil.ReadDir(recFolder)

	if err != nil {
		return errors.New("Couldn't read folder: " + err.Error())
	}

	for _, info := range infos {
		if info.IsDir() {
			continue
		}

		if filepath.Ext(info.Name()) != ".json" {
			continue
		}

		rec, err := record.New(filepath.Join(recFolder, info.Name()))

		if err != nil {
			return errors.New("File with name " + info.Name() + " couldn't be loaded into rec: " + err.Error())
		}

		if err := compare(manager, rec); err != nil {
			return errors.New("File named " + info.Name() + " had compare error: " + err.Error())
		}

	}

	return nil
}

func compare(manager *boardgame.GameManager, rec *record.Record) error {
	game, err := manager.Internals().RecreateGame(rec.Game())

	if err != nil {
		return errors.New("Couldn't create game: " + err.Error())
	}

	lastVerifiedVersion := 0

	for !game.Finished() {
		//Verify all new moves that have happened since the last time we
		//checked (often, fix-up moves).
		for lastVerifiedVersion < game.Version() {
			stateToCompare, err := rec.State(lastVerifiedVersion)

			if err != nil {
				return errors.New("Couldn't get " + strconv.Itoa(lastVerifiedVersion) + " state: " + err.Error())
			}

			//We used to just do
			//game.State(lastVerifiedVersion).StorageRecord(), but that
			//doesn't guarantee that it's the same as
			//manager.Storage().State() because it relies on state in
			//timerManager. This is unexpected and needs its own issue.
			storageRec, err := manager.Storage().State(game.Id(), lastVerifiedVersion)

			if err != nil {
				return errors.New("Couldn't get state storage rec from game: " + err.Error())
			}

			if err := compareJsonBlobs(storageRec, stateToCompare); err != nil {
				return errors.New("State " + strconv.Itoa(lastVerifiedVersion) + " compared differently: " + err.Error())
			}

			if lastVerifiedVersion > 0 {

				//Version 0 has no associated move

				recMove, err := rec.Move(lastVerifiedVersion)

				if err != nil {
					return errors.New("Couldn't get move " + strconv.Itoa(lastVerifiedVersion) + " from record")
				}

				moves := game.MoveRecords(lastVerifiedVersion)

				if len(moves) < 1 {
					return errors.New("Didn't fetch historical move records for " + strconv.Itoa(lastVerifiedVersion))
				}

				//Warning: records are modified by this method
				if err := compareMoveStorageRecords(moves[len(moves)-1], recMove); err != nil {
					return errors.New("Move " + strconv.Itoa(lastVerifiedVersion) + " compared differently: " + err.Error())
				}
			}

			lastVerifiedVersion++
		}

		nextMoveRec, err := rec.Move(lastVerifiedVersion + 1)

		if err != nil {
			//We'll assume that menas that's all of the moves there are to make.
			break
		}

		if nextMoveRec.Proposer < 0 {
			//We could be waiting for a timer to fire.
			//If there was a timer, try to force it to fire early.
			if manager.Internals().ForceNextTimer() {
				continue
			}

			//There wasn't a timer pending, so it's just an error
			return errors.New("At version " + strconv.Itoa(lastVerifiedVersion) + " the next player move to apply was not applied by a player")
		}

		nextMove, err := nextMoveRec.Inflate(game)

		if err != nil {
			return errors.New("Couldn't inflate move: " + err.Error())
		}

		if err := <-game.ProposeMove(nextMove, nextMoveRec.Proposer); err != nil {
			return errors.New("Couldn't propose next move in chain: " + err.Error())
		}

	}

	if game.Finished() != rec.Game().Finished {
		return errors.New("Game finished did not match rec")
	}

	if !reflect.DeepEqual(game.Winners(), rec.Game().Winners) {
		return errors.New("Game winners did not match")
	}

	return nil
}

var differ = gojsondiff.New()

var diffformatter = formatter.NewDeltaFormatter()

func compareJsonBlobs(one, two []byte) error {

	diff, err := differ.Compare(one, two)

	if err != nil {
		return errors.New("Couldn't diff: " + err.Error())
	}

	if diff.Modified() {

		str, err := diffformatter.Format(diff)

		if err != nil {
			return errors.New("Couldn't format diff: " + err.Error())
		}

		return errors.New("Diff: " + str)
	}

	return nil

}

//warning: modifies the records
func compareMoveStorageRecords(one, two *boardgame.MoveStorageRecord) error {

	if one == nil {
		return errors.New("One was nil")
	}

	if two == nil {
		return errors.New("Two was nil")
	}

	oneBlob := one.Blob
	twoBlob := two.Blob

	//Set the fields we know might differ to known values
	one.Blob = nil
	two.Blob = nil

	two.Timestamp = one.Timestamp

	if !reflect.DeepEqual(one, two) {
		return errors.New("Move storage records differed in base fields")
	}

	return compareJsonBlobs(oneBlob, twoBlob)

}
<|endoftext|>


<commit_before>package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "os"
    "text/template"
)

var templateFile string

func init() {
    if len(os.Args) != 2 {
        exitError(fmt.Errorf("Usage: %s <template>\n", os.Args[0]))
    }

    templateFile = os.Args[1]
}

func main() {
    getEnv := func(key string) (string) {
        value := os.Getenv(key)
        return value
    }

    funcs := template.FuncMap{ "env": getEnv }

    templateContent, err := ioutil.ReadFile(templateFile)
    if err != nil { exitError(err) }

    parsedTemplate, err := template.New("test").Funcs(funcs).Parse(string(templateContent))
    if err != nil { exitError(err) }

    var output bytes.Buffer
    err = parsedTemplate.Execute(&output, nil)
    if err != nil { exitError(err) }

    fmt.Print(output.String())
}

func exitError(err error) {
    fmt.Println(err)
    os.Exit(1)
}
<commit_msg>Reformat with gofmt<commit_after>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"text/template"
)

var templateFile string

func init() {
	if len(os.Args) != 2 {
		exitError(fmt.Errorf("Usage: %s <template>\n", os.Args[0]))
	}

	templateFile = os.Args[1]
}

func main() {
	getEnv := func(key string) string {
		value := os.Getenv(key)
		return value
	}

	funcs := template.FuncMap{"env": getEnv}

	templateContent, err := ioutil.ReadFile(templateFile)
	if err != nil {
		exitError(err)
	}

	parsedTemplate, err := template.New("test").Funcs(funcs).Parse(string(templateContent))
	if err != nil {
		exitError(err)
	}

	var output bytes.Buffer
	err = parsedTemplate.Execute(&output, nil)
	if err != nil {
		exitError(err)
	}

	fmt.Print(output.String())
}

func exitError(err error) {
	fmt.Println(err)
	os.Exit(1)
}
<|endoftext|>


<commit_before>package env

import (
    "github.com/stretchr/testify/assert"
    "testing"
    "os"
    "code.google.com/p/go-uuid/uuid"
)

func TestIfFallbackWorks(t *testing.T) {
    f := "bar"
    k := uuid.NewRandom().String()
    v := Getenv(k, f)
    assert.Equal(t, v, f)
}

func TestIfEnvWorks(t *testing.T) {
    f := "bar"
    ev := "foo"
    k := uuid.NewRandom().String()

    os.Setenv(k, ev)
    defer os.Unsetenv(k)

    v := Getenv(k, f)
    assert.NotEqual(t, v, f)
    assert.Equal(t, v, ev)
}

func BenchmarkGetEnv(b *testing.B) {
    k := uuid.NewRandom().String()
    for i := 0; i < b.N; i++ {
        _ =  Getenv(k, "")
    }
}<commit_msg>vendor: code.google.com is shutting down<commit_after>package env

import (
	"github.com/pborman/uuid"
	"github.com/stretchr/testify/assert"
	"os"
	"testing"
)

func TestIfFallbackWorks(t *testing.T) {
	f := "bar"
	k := uuid.NewRandom().String()
	v := Getenv(k, f)
	assert.Equal(t, v, f)
}

func TestIfEnvWorks(t *testing.T) {
	f := "bar"
	ev := "foo"
	k := uuid.NewRandom().String()

	os.Setenv(k, ev)
	defer os.Unsetenv(k)

	v := Getenv(k, f)
	assert.NotEqual(t, v, f)
	assert.Equal(t, v, ev)
}

func BenchmarkGetEnv(b *testing.B) {
	k := uuid.NewRandom().String()
	for i := 0; i < b.N; i++ {
		_ = Getenv(k, "")
	}
}
<|endoftext|>