<commit_before>// Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
// Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.
// Copyright (c) 2016 Andriy Pylypenko. All rights reserved.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package sippy

import (
    "fmt"
    "math"
    "strconv"
    "strings"
    "sync/atomic"

    "sippy/net"
    "sippy/sdp"
    "sippy/types"
)

type _rtpps_side struct {
    otherside       *_rtpps_side
    owner           *Rtp_proxy_session
    session_exists  bool
    laddress        string
    raddress        *sippy_net.HostPort
    codecs          string
    repacketize     int
    after_sdp_change func(sippy_types.RtpProxyUpdateResult)
    from_tag        string
    to_tag          string
}

func (self *_rtpps_side) _play(prompt_name string, times int, result_callback func(string), index int) {
    if ! self.session_exists {
        return
    }
    if ! self.otherside.session_exists {
        self.otherside.update("0.0.0.0", "0", func(*rtpproxy_update_result) { self.__play(prompt_name, times, result_callback, index) }, "", index, "IP4")
        return
    }
    self.__play(prompt_name, times, result_callback, index)
}

func (self *_rtpps_side) __play(prompt_name string, times int, result_callback func(string), index int) {
    command := fmt.Sprintf("P%d %s-%d %s %s %s %s", times, self.owner.call_id, index, prompt_name, self.codecs, self.from_tag, self.to_tag)
    self.owner.send_command(command, func(r string) { self.owner.command_result(r, result_callback) })
}

func (self *_rtpps_side) update(remote_ip string, remote_port string, result_callback func(*rtpproxy_update_result), options/*= ""*/ string, index /*= 0*/int, atype /*= "IP4"*/string) {
    var sbind_supported, is_local, tnot_supported bool
    var err error

    command := "U"
    self.owner.max_index = int(math.Max(float64(self.owner.max_index), float64(index)))
    if sbind_supported, err = self.owner.SBindSupported(); err != nil {
        return
    }
    if is_local, err = self.owner.IsLocal(); err != nil {
        return
    }
    if tnot_supported, err = self.owner.TNotSupported(); err != nil {
        return
    }
    if sbind_supported {
        if self.raddress != nil {
            //if self.owner.IsLocal() && atype == "IP4" {
            //    options += fmt.Sprintf("L%s", self.laddress)
            //} else if ! self.owner.IsLocal() {
            //    options += fmt.Sprintf("R%s", self.raddress.Host.String())
            //}
            options += "R" + self.raddress.Host.String()
        } else if self.laddress != "" && is_local {
            options += "L" + self.laddress
        }
    }
    command += options
    if self.otherside.session_exists {
        command += fmt.Sprintf(" %s-%d %s %s %s %s", self.owner.call_id, index, remote_ip, remote_port, self.from_tag, self.to_tag)
    } else {
        command += fmt.Sprintf(" %s-%d %s %s %s", self.owner.call_id, index, remote_ip, remote_port, self.from_tag)
    }
    if self.owner.notify_socket != "" && index == 0 && tnot_supported {
        command += fmt.Sprintf(" %s %s", self.owner.notify_socket, self.owner.notify_tag)
    }
    self.owner.send_command(command, func(r string) { self.update_result(r, remote_ip, atype, result_callback) })
}

func (self *_rtpps_side) update_result(result, remote_ip, atype string, result_callback func(*rtpproxy_update_result)) {
    //print "%s.update_result(%s)" % (id(self), result)
    //result_callback, face, callback_parameters = args
    self.session_exists = true
    if result == "" {
        result_callback(nil)
        return
    }
    t1 := strings.Fields(result)
    if t1[0][0] == 'E' {
        result_callback(nil)
        return
    }
    rtpproxy_port, err := strconv.Atoi(t1[0])
    if err != nil || rtpproxy_port == 0 {
        result_callback(nil)
        return
    }
    family := "IP4"
    rtpproxy_address := ""
    if len(t1) > 1 {
        rtpproxy_address = t1[1]
        if len(t1) > 2 && t1[2] == "6" {
            family = "IP6"
        }
    } else {
        if rtpproxy_address, err = self.owner.GetProxyAddress(); err != nil {
            return
        }
    }
    sendonly := false
    if atype == "IP4" && remote_ip == "0.0.0.0" {
        sendonly = true
    } else if atype == "IP6" && remote_ip == "::" {
        sendonly = true
    }
    result_callback(&rtpproxy_update_result{
        rtpproxy_address    : rtpproxy_address,
        rtpproxy_port       : t1[0],
        family              : family,
        sendonly            : sendonly,
    })
}

func (self *_rtpps_side) _on_sdp_change(sdp_body sippy_types.MsgBody, result_callback func(sippy_types.MsgBody)) error {
    parsed_body, err := sdp_body.GetSdp()
    if err != nil {
        return err
    }
    sects := []*sippy_sdp.SdpMediaDescription{}
    for _, sect := range parsed_body.GetSections() {
        switch strings.ToLower(sect.GetMHeader().GetTransport()) {
        case "udp", "udptl", "rtp/avp", "rtp/savp", "udp/bfcp":
            sects = append(sects, sect)
        default:
        }
    }
    if len(sects) == 0 {
        result_callback(sdp_body)
        return nil
    }
    formats := sects[0].GetMHeader().GetFormats()
    self.codecs = strings.Join(formats, ",")
    options := ""
    if self.repacketize > 0 {
        options = fmt.Sprintf("z%d", self.repacketize)
    }
    sections_left := int64(len(sects))
    for i, sect := range sects {
        sect_options := options
        if sect.GetCHeader().GetAType() == "IP6" {
            sect_options = "6" + options
        }
        self.update(sect.GetCHeader().GetAddr(), sect.GetMHeader().GetPort(),
              func (res *rtpproxy_update_result) { self._sdp_change_finish(res, sdp_body, parsed_body, sect, &sections_left, result_callback) },
              sect_options, i, sect.GetCHeader().GetAType())
    }
    return nil
}

func (self *_rtpps_side) _sdp_change_finish(cb_args *rtpproxy_update_result, sdp_body sippy_types.MsgBody, parsed_body sippy_types.Sdp, sect *sippy_sdp.SdpMediaDescription, sections_left *int64, result_callback func(sippy_types.MsgBody)) {
    if cb_args != nil {
        if self.after_sdp_change != nil {
            self.after_sdp_change(cb_args)
        }
        sect.GetCHeader().SetAType(cb_args.family)
        sect.GetCHeader().SetAddr(cb_args.rtpproxy_address)
        if sect.GetMHeader().GetPort() != "0" {
            sect.GetMHeader().SetPort(cb_args.rtpproxy_port)
        }
        if cb_args.sendonly {
            sect.RemoveAHeader("sendrecv")
            sect.RemoveAHeader("sendonly")
            sect.AddHeader("a", "sendonly")
        }
        if self.repacketize > 0 {
            sect.RemoveAHeader("ptime:")
            sect.AddHeader("a", fmt.Sprintf("ptime:%d", self.repacketize))
        }
    }
    if atomic.AddInt64(sections_left, -1) > 0 {
        // more work is in progress
        return
    }
    if self.owner.insert_nortpp {
        parsed_body.AppendAHeader("nortpproxy=yes")
    }
    sdp_body.SetNeedsUpdate(false)
    // RFC4566
    // *******
    // For privacy reasons, it is sometimes desirable to obfuscate the
    // username and IP address of the session originator.  If this is a
    // concern, an arbitrary <username> and private <unicast-address> MAY be
    // chosen to populate the "o=" field, provided that these are selected
    // in a manner that does not affect the global uniqueness of the field.
    // *******
    origin := parsed_body.GetOHeader()
    origin.SetAddress("192.0.2.1")
    origin.SetAddressType("IP4")
    origin.SetNetworkType("IN")
    result_callback(sdp_body)
}

func (self *_rtpps_side) _stop_play(cb func(string), index int) {
    if ! self.otherside.session_exists {
        return
    }
    command := fmt.Sprintf("S %s-%d %s %s", self.owner.call_id, index, self.from_tag, self.to_tag)
    self.owner.send_command(command, func(r string) { self.owner.command_result(r, cb) })
}
<commit_msg>Prevent possible infinite recursion.<commit_after>// Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
// Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.
// Copyright (c) 2016 Andriy Pylypenko. All rights reserved.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package sippy

import (
    "fmt"
    "math"
    "strconv"
    "strings"
    "sync/atomic"

    "sippy/net"
    "sippy/sdp"
    "sippy/types"
)

type _rtpps_side struct {
    otherside       *_rtpps_side
    owner           *Rtp_proxy_session
    session_exists  bool
    laddress        string
    raddress        *sippy_net.HostPort
    codecs          string
    repacketize     int
    after_sdp_change func(sippy_types.RtpProxyUpdateResult)
    from_tag        string
    to_tag          string
}

func (self *_rtpps_side) _play(prompt_name string, times int, result_callback func(string), index int) {
    if ! self.session_exists {
        return
    }
    if ! self.otherside.session_exists {
        self.otherside.update("0.0.0.0", "0", func(*rtpproxy_update_result) { self.__play(prompt_name, times, result_callback, index) }, "", index, "IP4")
        return
    }
    self.__play(prompt_name, times, result_callback, index)
}

func (self *_rtpps_side) __play(prompt_name string, times int, result_callback func(string), index int) {
    command := fmt.Sprintf("P%d %s-%d %s %s %s %s", times, self.owner.call_id, index, prompt_name, self.codecs, self.from_tag, self.to_tag)
    self.owner.send_command(command, func(r string) { self.owner.command_result(r, result_callback) })
}

func (self *_rtpps_side) update(remote_ip string, remote_port string, result_callback func(*rtpproxy_update_result), options/*= ""*/ string, index /*= 0*/int, atype /*= "IP4"*/string) {
    var sbind_supported, is_local, tnot_supported bool
    var err error

    command := "U"
    self.owner.max_index = int(math.Max(float64(self.owner.max_index), float64(index)))
    if sbind_supported, err = self.owner.SBindSupported(); err != nil {
        return
    }
    if is_local, err = self.owner.IsLocal(); err != nil {
        return
    }
    if tnot_supported, err = self.owner.TNotSupported(); err != nil {
        return
    }
    if sbind_supported {
        if self.raddress != nil {
            //if self.owner.IsLocal() && atype == "IP4" {
            //    options += fmt.Sprintf("L%s", self.laddress)
            //} else if ! self.owner.IsLocal() {
            //    options += fmt.Sprintf("R%s", self.raddress.Host.String())
            //}
            options += "R" + self.raddress.Host.String()
        } else if self.laddress != "" && is_local {
            options += "L" + self.laddress
        }
    }
    command += options
    if self.otherside.session_exists {
        command += fmt.Sprintf(" %s-%d %s %s %s %s", self.owner.call_id, index, remote_ip, remote_port, self.from_tag, self.to_tag)
    } else {
        command += fmt.Sprintf(" %s-%d %s %s %s", self.owner.call_id, index, remote_ip, remote_port, self.from_tag)
    }
    if self.owner.notify_socket != "" && index == 0 && tnot_supported {
        command += fmt.Sprintf(" %s %s", self.owner.notify_socket, self.owner.notify_tag)
    }
    self.owner.send_command(command, func(r string) { self.update_result(r, remote_ip, atype, result_callback) })
}

func (self *_rtpps_side) update_result(result, remote_ip, atype string, result_callback func(*rtpproxy_update_result)) {
    //print "%s.update_result(%s)" % (id(self), result)
    //result_callback, face, callback_parameters = args
    self.session_exists = true
    if result == "" {
        result_callback(nil)
        return
    }
    t1 := strings.Fields(result)
    if t1[0][0] == 'E' {
        result_callback(nil)
        return
    }
    rtpproxy_port, err := strconv.Atoi(t1[0])
    if err != nil || rtpproxy_port == 0 {
        result_callback(nil)
        return
    }
    family := "IP4"
    rtpproxy_address := ""
    if len(t1) > 1 {
        rtpproxy_address = t1[1]
        if len(t1) > 2 && t1[2] == "6" {
            family = "IP6"
        }
    } else {
        if rtpproxy_address, err = self.owner.GetProxyAddress(); err != nil {
            return
        }
    }
    sendonly := false
    if atype == "IP4" && remote_ip == "0.0.0.0" {
        sendonly = true
    } else if atype == "IP6" && remote_ip == "::" {
        sendonly = true
    }
    result_callback(&rtpproxy_update_result{
        rtpproxy_address    : rtpproxy_address,
        rtpproxy_port       : t1[0],
        family              : family,
        sendonly            : sendonly,
    })
}

func (self *_rtpps_side) _on_sdp_change(sdp_body sippy_types.MsgBody, result_callback func(sippy_types.MsgBody)) error {
    parsed_body, err := sdp_body.GetSdp()
    if err != nil {
        return err
    }
    sects := []*sippy_sdp.SdpMediaDescription{}
    for _, sect := range parsed_body.GetSections() {
        switch strings.ToLower(sect.GetMHeader().GetTransport()) {
        case "udp", "udptl", "rtp/avp", "rtp/savp", "udp/bfcp":
            sects = append(sects, sect)
        default:
        }
    }
    if len(sects) == 0 {
        sdp_body.SetNeedsUpdate(false)
        result_callback(sdp_body)
        return nil
    }
    formats := sects[0].GetMHeader().GetFormats()
    self.codecs = strings.Join(formats, ",")
    options := ""
    if self.repacketize > 0 {
        options = fmt.Sprintf("z%d", self.repacketize)
    }
    sections_left := int64(len(sects))
    for i, sect := range sects {
        sect_options := options
        if sect.GetCHeader().GetAType() == "IP6" {
            sect_options = "6" + options
        }
        self.update(sect.GetCHeader().GetAddr(), sect.GetMHeader().GetPort(),
              func (res *rtpproxy_update_result) { self._sdp_change_finish(res, sdp_body, parsed_body, sect, &sections_left, result_callback) },
              sect_options, i, sect.GetCHeader().GetAType())
    }
    return nil
}

func (self *_rtpps_side) _sdp_change_finish(cb_args *rtpproxy_update_result, sdp_body sippy_types.MsgBody, parsed_body sippy_types.Sdp, sect *sippy_sdp.SdpMediaDescription, sections_left *int64, result_callback func(sippy_types.MsgBody)) {
    if cb_args != nil {
        if self.after_sdp_change != nil {
            self.after_sdp_change(cb_args)
        }
        sect.GetCHeader().SetAType(cb_args.family)
        sect.GetCHeader().SetAddr(cb_args.rtpproxy_address)
        if sect.GetMHeader().GetPort() != "0" {
            sect.GetMHeader().SetPort(cb_args.rtpproxy_port)
        }
        if cb_args.sendonly {
            sect.RemoveAHeader("sendrecv")
            sect.RemoveAHeader("sendonly")
            sect.AddHeader("a", "sendonly")
        }
        if self.repacketize > 0 {
            sect.RemoveAHeader("ptime:")
            sect.AddHeader("a", fmt.Sprintf("ptime:%d", self.repacketize))
        }
    }
    if atomic.AddInt64(sections_left, -1) > 0 {
        // more work is in progress
        return
    }
    if self.owner.insert_nortpp {
        parsed_body.AppendAHeader("nortpproxy=yes")
    }
    sdp_body.SetNeedsUpdate(false)
    // RFC4566
    // *******
    // For privacy reasons, it is sometimes desirable to obfuscate the
    // username and IP address of the session originator.  If this is a
    // concern, an arbitrary <username> and private <unicast-address> MAY be
    // chosen to populate the "o=" field, provided that these are selected
    // in a manner that does not affect the global uniqueness of the field.
    // *******
    origin := parsed_body.GetOHeader()
    origin.SetAddress("192.0.2.1")
    origin.SetAddressType("IP4")
    origin.SetNetworkType("IN")
    result_callback(sdp_body)
}

func (self *_rtpps_side) _stop_play(cb func(string), index int) {
    if ! self.otherside.session_exists {
        return
    }
    command := fmt.Sprintf("S %s-%d %s %s", self.owner.call_id, index, self.from_tag, self.to_tag)
    self.owner.send_command(command, func(r string) { self.owner.command_result(r, cb) })
}
<|endoftext|>


<commit_before>package main

import "os/exec"
import "strings"
import "runtime"
import "color"
import "os"

func main() {

  Green := color.New(color.FgGreen)
  BoldGreen := Green.Add(color.Bold)
  Yellow := color.New(color.FgYellow)
  BoldYellow := Yellow.Add(color.Bold)
  Red := color.New(color.FgRed)
  BoldRed := Red.Add(color.Bold)
  White := color.New(color.FgWhite)
  BoldWhite := White.Add(color.Bold)

  color.Red(" ██░ ██ ▓█████  ██▀███   ▄████▄   █    ██  ██▓    ▓█████   ██████ ")
  color.Red("▓██░ ██▒▓█   ▀ ▓██ ▒ ██▒▒██▀ ▀█   ██  ▓██▒▓██▒    ▓█   ▀ ▒██    ▒ ")
  color.Red("▒██▀▀██░▒███   ▓██ ░▄█ ▒▒▓█    ▄ ▓██  ▒██░▒██░    ▒███   ░ ▓██▄   ")
  color.Red("░▓█ ░██ ▒▓█  ▄ ▒██▀▀█▄  ▒▓▓▄ ▄██▒▓▓█  ░██░▒██░    ▒▓█  ▄   ▒   ██▒")
  color.Red("░▓█▒░██▓░▒████▒░██▓ ▒██▒▒ ▓███▀ ░▒▒█████▓ ░██████▒░▒████▒▒██████▒▒")
  color.Red(" ▒ ░░▒░▒░░ ▒░ ░░ ▒▓ ░▒▓░░ ░▒ ▒  ░░▒▓▒ ▒ ▒ ░ ▒░▓  ░░░ ▒░ ░▒ ▒▓▒ ▒ ░")
  color.Red(" ▒ ░▒░ ░ ░ ░  ░  ░▒ ░ ▒░  ░  ▒   ░░▒░ ░ ░ ░ ░ ▒  ░ ░ ░  ░░ ░▒  ░ ░")
  color.Red(" ░  ░░ ░   ░     ░░   ░ ░         ░░░ ░ ░   ░ ░      ░   ░  ░  ░  ")
  color.Red(" ░  ░  ░   ░  ░   ░     ░ ░         ░         ░  ░   ░  ░      ░  ")
  color.Red("                        ░                                         ")

  color.Green("\n+ -- --=[      HERCULES FRAMEWORK           ]")
  BoldGreen.Println("+ -- --=[            Ege Balcı              ]")

  BoldWhite.Println("\n\n[*] STARTING HERCULES SETUP \n")

  BoldYellow.Println("[*] Detecting OS...")

  if runtime.GOOS == "linux" {
    OsVersion, _ := exec.Command("sh", "-c", "uname -a").Output()
    BoldYellow.Println("[*] OS Detected : " + string(OsVersion))
    BoldYellow.Println("[*] Installing golang...")
    Go := exec.Command("sh", "-c", "apt-get install golang")
    Go.Stdout = os.Stdout
    Go.Stdin = os.Stdin
    Go.Run()
    BoldYellow.Println("[*] Installing upx...")
    UPX := exec.Command("sh", "-c", "apt-get install upx")
    UPX.Stdout = os.Stdout
    UPX.Stdin = os.Stdin
    UPX.Run()
    BoldYellow.Println("[*] Installing openssl...")
    OSSL := exec.Command("sh", "-c", "apt-get install openssl")
    OSSL.Stdout = os.Stdout
    OSSL.Stdin = os.Stdin
    OSSL.Run()
    BoldYellow.Println("[*] Installing git...")
    Git := exec.Command("sh", "-c", "apt-get install git")
    Git.Stdout = os.Stdout
    Git.Stdin = os.Stdin
    Git.Run()

    BoldYellow.Println("[*] Cloning EGESPLOIT Library...")
    exec.Command("sh", "-c", "git clone https://github.com/EgeBalci/EGESPLOIT.git").Run()
    exec.Command("sh", "-c", "mv EGESPLOIT /usr/lib/go/src/").Run()

    BoldYellow.Println("[*] Cloning color Library...")
    exec.Command("sh", "-c", "git clone https://github.com/fatih/color.git").Run()
    exec.Command("sh", "-c", "mv color /usr/lib/go/src/").Run()

    Stat, Err := CheckValid()

    if Stat == false {
      BoldYellow.Println("\n")
      BoldRed.Println(Err)
    }else{
      BoldGreen.Println("\n\n[+] Setup completed successfully")
    }

  }else if runtime.GOOS != "linux" {
    BoldRed.Println("[!] ERROR : HERCULES+ only supports linux distributions")
  }

}

func CheckValid()  (bool, string){
  OutESP, _ := exec.Command("sh", "-c", "cd /usr/lib/go/src/ && ls").Output()
  if (!strings.Contains(string(OutESP), "EGESPLOIT")) {
    return false, "[!] ERROR : EGESPLOIT library is not installed"
  }

  OutCL, _ := exec.Command("sh", "-c", "cd /usr/lib/go/src/ && ls").Output()
  if (!strings.Contains(string(OutCL), "color")) {
    return false, "[!] ERROR : color library is not installed"
  }

  OutUPX, _ := exec.Command("sh", "-c", "upx").Output()
  if (!strings.Contains(string(OutUPX), "Copyright")) {
    return false, "[!] ERROR : upx is not installed"
  }

  OutGO, _ := exec.Command("sh", "-c", "go version").Output()
  if (!strings.Contains(string(OutGO), "version")) {
    return false, "[!] ERROR : golang is not installed"
  }

  return true, ""

}
<commit_msg>Update Setup.go<commit_after>package main

import "os/exec"
import "strings"
import "runtime"
import "color"
import "os"

func main() {

  Green := color.New(color.FgGreen)
  BoldGreen := Green.Add(color.Bold)
  Yellow := color.New(color.FgYellow)
  BoldYellow := Yellow.Add(color.Bold)
  Red := color.New(color.FgRed)
  BoldRed := Red.Add(color.Bold)
  White := color.New(color.FgWhite)
  BoldWhite := White.Add(color.Bold)

  color.Red(" ██░ ██ ▓█████  ██▀███   ▄████▄   █    ██  ██▓    ▓█████   ██████ ")
  color.Red("▓██░ ██▒▓█   ▀ ▓██ ▒ ██▒▒██▀ ▀█   ██  ▓██▒▓██▒    ▓█   ▀ ▒██    ▒ ")
  color.Red("▒██▀▀██░▒███   ▓██ ░▄█ ▒▒▓█    ▄ ▓██  ▒██░▒██░    ▒███   ░ ▓██▄   ")
  color.Red("░▓█ ░██ ▒▓█  ▄ ▒██▀▀█▄  ▒▓▓▄ ▄██▒▓▓█  ░██░▒██░    ▒▓█  ▄   ▒   ██▒")
  color.Red("░▓█▒░██▓░▒████▒░██▓ ▒██▒▒ ▓███▀ ░▒▒█████▓ ░██████▒░▒████▒▒██████▒▒")
  color.Red(" ▒ ░░▒░▒░░ ▒░ ░░ ▒▓ ░▒▓░░ ░▒ ▒  ░░▒▓▒ ▒ ▒ ░ ▒░▓  ░░░ ▒░ ░▒ ▒▓▒ ▒ ░")
  color.Red(" ▒ ░▒░ ░ ░ ░  ░  ░▒ ░ ▒░  ░  ▒   ░░▒░ ░ ░ ░ ░ ▒  ░ ░ ░  ░░ ░▒  ░ ░")
  color.Red(" ░  ░░ ░   ░     ░░   ░ ░         ░░░ ░ ░   ░ ░      ░   ░  ░  ░  ")
  color.Red(" ░  ░  ░   ░  ░   ░     ░ ░         ░         ░  ░   ░  ░      ░  ")
  color.Red("                        ░                                         ")

  color.Green("\n+ -- --=[      HERCULES FRAMEWORK           ]")
  BoldGreen.Println("+ -- --=[            Ege Balcı              ]")

  BoldWhite.Println("\n\n[*] STARTING HERCULES SETUP \n")

  BoldYellow.Println("[*] Detecting OS...")

  if runtime.GOOS == "linux" {
    OsVersion, _ := exec.Command("sh", "-c", "uname -a").Output()
    BoldYellow.Println("[*] OS Detected : " + string(OsVersion))
    BoldYellow.Println("[*] Installing golang...")
    Go := exec.Command("sh", "-c", "apt-get install golang")
    Go.Stdout = os.Stdout
    Go.Stdin = os.Stdin
    Go.Run()
    BoldYellow.Println("[*] Installing upx...")
    UPX := exec.Command("sh", "-c", "apt-get install upx")
    UPX.Stdout = os.Stdout
    UPX.Stdin = os.Stdin
    UPX.Run()
    BoldYellow.Println("[*] Installing openssl...")
    OSSL := exec.Command("sh", "-c", "apt-get install openssl")
    OSSL.Stdout = os.Stdout
    OSSL.Stdin = os.Stdin
    OSSL.Run()
    BoldYellow.Println("[*] Installing git...")
    Git := exec.Command("sh", "-c", "apt-get install git")
    Git.Stdout = os.Stdout
    Git.Stdin = os.Stdin
    Git.Run()

    BoldYellow.Println("[*] Cloning EGESPLOIT Library...")
    exec.Command("sh", "-c", "git clone https://github.com/EgeBalci/EGESPLOIT.git").Run()
    exec.Command("sh", "-c", "cp EGESPLOIT /usr/lib/go-1.6/src/").Run()
    exec.Command("sh", "-c", "mv EGESPLOIT /usr/lib/go/src/").Run()

    BoldYellow.Println("[*] Cloning color Library...")
    exec.Command("sh", "-c", "git clone https://github.com/fatih/color.git").Run()
    exec.Command("sh", "-c", "cp color /usr/lib/go-1.6/src/").Run()
    exec.Command("sh", "-c", "mv color /usr/lib/go/src/").Run()// /usr/lib/go-1.6/src/

    Stat, Err := CheckValid()

    if Stat == false {
      BoldYellow.Println("\n")
      BoldRed.Println(Err)
    }else{
      BoldGreen.Println("\n\n[+] Setup completed successfully")
    }

  }else if runtime.GOOS != "linux" {
    BoldRed.Println("[!] ERROR : HERCULES+ only supports linux distributions")
  }

}

func CheckValid()  (bool, string){
  OutESP, _ := exec.Command("sh", "-c", "cd /usr/lib/go/src/ && ls").Output()
  if (!strings.Contains(string(OutESP), "EGESPLOIT")) {
    return false, "[!] ERROR : EGESPLOIT library is not installed"
  }

  OutESP2, _ := exec.Command("sh", "-c", "cd /usr/lib/go-1.6/src/ && ls").Output()
  if (!strings.Contains(string(OutESP2), "EGESPLOIT")) {
    return false, "[!] ERROR : EGESPLOIT library is not installed"
  }

  OutCL, _ := exec.Command("sh", "-c", "cd /usr/lib/go/src/ && ls").Output()
  if (!strings.Contains(string(OutCL), "color")) {
    return false, "[!] ERROR : color library is not installed"
  }

  OutCL2, _ := exec.Command("sh", "-c", "cd /usr/lib/go-1.6/src/ && ls").Output()
  if (!strings.Contains(string(OutCL2), "color")) {
    return false, "[!] ERROR : color library is not installed"
  }

  OutUPX, _ := exec.Command("sh", "-c", "upx").Output()
  if (!strings.Contains(string(OutUPX), "Copyright")) {
    return false, "[!] ERROR : upx is not installed"
  }

  OutGO, _ := exec.Command("sh", "-c", "go version").Output()
  if (!strings.Contains(string(OutGO), "version")) {
    return false, "[!] ERROR : golang is not installed"
  }

  return true, ""

}
<|endoftext|>


<commit_before>package main

import (
	"compress/bzip2"
	"fmt"
	"io"
	"log"
	"os"

	"github.com/dustin/go-wikiparse"
)

func main() {
	r, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatalf("Error opening %v: %v", os.Args[1], err)
	}
	defer r.Close()

	bz := bzip2.NewReader(r)

	ir := wikiparse.NewIndexReader(bz)
	for {
		e, err := ir.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatalf("Error reading stream:  %v", err)
		}

		fmt.Println(e.String())
	}
}
<commit_msg>Removed indexfix<commit_after><|endoftext|>


<commit_before>package main

import (
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"

	"example.com/internal/taskstore"
	"github.com/gin-gonic/gin"
)

type taskServer struct {
	// Mutex protects access to the 'store' field. We don't make assumptions
	// about the safety of any method of store, so all accesses are protected.
	sync.Mutex
	store *taskstore.TaskStore
}

func NewTaskServer() *taskServer {
	store := taskstore.New()
	return &taskServer{store: store}
}

func (ts *taskServer) getAllTasksHandler(c *gin.Context) {
	ts.Lock()
	allTasks := ts.store.GetAllTasks()
	ts.Unlock()

	c.JSON(http.StatusOK, allTasks)
}

func (ts *taskServer) createTaskHandler(c *gin.Context) {
	type RequestTask struct {
		Text string    `json:"text"`
		Tags []string  `json:"tags"`
		Due  time.Time `json:"due"`
	}

	var rt RequestTask
	if err := c.ShouldBindJSON(&rt); err != nil {
		c.String(http.StatusBadRequest, err.Error())
	}

	ts.Lock()
	id := ts.store.CreateTask(rt.Text, rt.Tags, rt.Due)
	ts.Unlock()

	c.JSON(http.StatusOK, gin.H{"Id": id})
}

func (ts *taskServer) getTaskHandler(c *gin.Context) {
	id, err := strconv.Atoi(c.Params.ByName("id"))
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	ts.Lock()
	task, err := ts.store.GetTask(id)
	ts.Unlock()

	if err != nil {
		c.String(http.StatusNotFound, err.Error())
		return
	}

	c.JSON(http.StatusOK, task)
}

func main() {
	router := gin.Default()
	server := NewTaskServer()

	router.POST("/task/", server.createTaskHandler)
	router.GET("/task/", server.getAllTasksHandler)
	router.GET("/task/:id", server.getTaskHandler)

	// TODO: need StrictSlash equivalent?
	// TODO: note that Default() already has some default middleware setup

	router.Run("localhost:" + os.Getenv("SERVERPORT"))
}
<commit_msg>Finished all handlers for gin<commit_after>package main

import (
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"

	"example.com/internal/taskstore"
	"github.com/gin-gonic/gin"
)

type taskServer struct {
	// Mutex protects access to the 'store' field. We don't make assumptions
	// about the safety of any method of store, so all accesses are protected.
	sync.Mutex
	store *taskstore.TaskStore
}

func NewTaskServer() *taskServer {
	store := taskstore.New()
	return &taskServer{store: store}
}

func (ts *taskServer) getAllTasksHandler(c *gin.Context) {
	ts.Lock()
	allTasks := ts.store.GetAllTasks()
	ts.Unlock()

	c.JSON(http.StatusOK, allTasks)
}

func (ts *taskServer) deleteAllTasksHandler(c *gin.Context) {
	ts.Lock()
	ts.store.DeleteAllTasks()
	ts.Unlock()
}

func (ts *taskServer) createTaskHandler(c *gin.Context) {
	type RequestTask struct {
		Text string    `json:"text"`
		Tags []string  `json:"tags"`
		Due  time.Time `json:"due"`
	}

	var rt RequestTask
	if err := c.ShouldBindJSON(&rt); err != nil {
		c.String(http.StatusBadRequest, err.Error())
	}

	ts.Lock()
	id := ts.store.CreateTask(rt.Text, rt.Tags, rt.Due)
	ts.Unlock()

	c.JSON(http.StatusOK, gin.H{"Id": id})
}

func (ts *taskServer) getTaskHandler(c *gin.Context) {
	id, err := strconv.Atoi(c.Params.ByName("id"))
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	ts.Lock()
	task, err := ts.store.GetTask(id)
	ts.Unlock()

	if err != nil {
		c.String(http.StatusNotFound, err.Error())
		return
	}

	c.JSON(http.StatusOK, task)
}

func (ts *taskServer) deleteTaskHandler(c *gin.Context) {
	id, err := strconv.Atoi(c.Params.ByName("id"))
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	ts.Lock()
	err = ts.store.DeleteTask(id)
	ts.Unlock()

	if err != nil {
		c.String(http.StatusNotFound, err.Error())
	}
}

func (ts *taskServer) tagHandler(c *gin.Context) {
	tag := c.Params.ByName("tag")
	ts.Lock()
	tasks := ts.store.GetTasksByTag(tag)
	ts.Unlock()

	c.JSON(http.StatusOK, tasks)
}

func (ts *taskServer) dueHandler(c *gin.Context) {
	badRequestError := func() {
		c.String(http.StatusBadRequest, "expect /due/<year>/<month>/<day>, got %v", c.FullPath())
	}

	year, err := strconv.Atoi(c.Params.ByName("year"))
	if err != nil {
		badRequestError()
		return
	}

	month, err := strconv.Atoi(c.Params.ByName("month"))
	if err != nil || month < int(time.January) || month > int(time.December) {
		badRequestError()
		return
	}

	day, err := strconv.Atoi(c.Params.ByName("day"))
	if err != nil {
		badRequestError()
		return
	}

	ts.Lock()
	tasks := ts.store.GetTasksByDueDate(year, time.Month(month), day)
	ts.Unlock()

	c.JSON(http.StatusOK, tasks)
}

func main() {
	router := gin.Default()
	server := NewTaskServer()

	router.POST("/task/", server.createTaskHandler)
	router.GET("/task/", server.getAllTasksHandler)
	router.DELETE("/task/", server.deleteAllTasksHandler)
	router.GET("/task/:id", server.getTaskHandler)
	router.DELETE("/task/:id", server.deleteTaskHandler)
	router.GET("/tag/:tag", server.tagHandler)
	router.GET("/due/:year/:month/:day", server.dueHandler)

	// TODO: need StrictSlash equivalent?
	// TODO: note that Default() already has some default middleware setup

	router.Run("localhost:" + os.Getenv("SERVERPORT"))
}
<|endoftext|>


<commit_before>// Copyright 2017 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package acl

import (
	"context"
	"fmt"
	"regexp"
	"sort"
	"strings"

	"github.com/luci/luci-go/common/data/stringset"
	"github.com/luci/luci-go/common/errors"
	"github.com/luci/luci-go/common/retry/transient"
	"github.com/luci/luci-go/scheduler/appengine/messages"
	"github.com/luci/luci-go/server/auth"
	"github.com/luci/luci-go/server/auth/identity"
)

// GrantsByRole can answer questions who can READ and who OWNS the task.
type GrantsByRole struct {
	Owners  []string `gae:",noindex"`
	Readers []string `gae:",noindex"`
}

func (g *GrantsByRole) IsOwner(c context.Context) (bool, error) {
	return hasGrant(c, g.Owners, groupsAdministrators)
}

func (g *GrantsByRole) IsReader(c context.Context) (bool, error) {
	if len(g.Readers) == 0 && len(g.Owners) == 0 {
		// This is here for backwards compatiblity before ACLs were introduced.
		// If Job doesn't specify READERs nor OWNERS explicitely, everybody can read.
		// TODO(tAndrii): remove once every Job/Trigger has ACLs specified.
		return true, nil
	}
	return hasGrant(c, g.Owners, g.Readers, groupsAdministrators)
}

func (g *GrantsByRole) Equal(o *GrantsByRole) bool {
	eqSlice := func(a, b []string) bool {
		if len(a) != len(b) {
			return false
		}
		for i := range a {
			if a[i] != b[i] {
				return false
			}
		}
		return true
	}
	return eqSlice(g.Owners, o.Owners) && eqSlice(g.Readers, o.Readers)
}

// AclSets are parsed and indexed `AclSet` of a project.
type AclSets map[string][]*messages.Acl

// ValidateAclSets validates list of AclSet of a project and returns AclSets.
func ValidateAclSets(sets []*messages.AclSet) (AclSets, error) {
	as := make(AclSets, len(sets))
	for _, s := range sets {
		if s.Name == "" {
			return nil, fmt.Errorf("missing 'name' field'")
		}
		if !aclSetNameRe.MatchString(s.Name) {
			return nil, fmt.Errorf("%q is not valid value for 'name' field", s.Name)
		}
		if _, isDup := as[s.Name]; isDup {
			return nil, fmt.Errorf("aclSet name %q is not unique", s.Name)
		}
		if len(s.GetAcls()) == 0 {
			return nil, fmt.Errorf("aclSet %q has no entries", s.Name)
		}
		as[s.Name] = s.GetAcls()
	}
	return as, nil
}

// ValidateTaskAcls validates task's ACLs and returns TaskAcls.
func ValidateTaskAcls(pSets AclSets, tSets []string, tAcls []*messages.Acl) (*GrantsByRole, error) {
	grantsLists := make([][]*messages.Acl, 0, 1+len(tSets))
	if err := validateGrants(tAcls); err != nil {
		return nil, err
	}
	grantsLists = append(grantsLists, tAcls)
	for _, set := range tSets {
		grantsList, exists := pSets[set]
		if !exists {
			return nil, fmt.Errorf("referencing AclSet '%s' which doesn't exist", set)
		}
		grantsLists = append(grantsLists, grantsList)
	}
	mg := mergeGrants(grantsLists...)
	if n := len(mg.Owners) + len(mg.Readers); n > maxGrantsPerJob {
		return nil, fmt.Errorf("Job or Trigger can have at most %d acls, but %d given", maxGrantsPerJob, n)
	}
	return mg, nil
}

////////////////////////////////////////////////////////////////////////////////

var (
	// aclSetNameRe is used to validate AclSet Name field.
	aclSetNameRe = regexp.MustCompile(`^[0-9A-Za-z_\-\.]{1,100}$`)
	// maxGrantsPerJob is how many different grants are specified for a job.
	maxGrantsPerJob = 32

	groupsAdministrators = []string{"group:administrators"}
)

func validateGrants(gs []*messages.Acl) error {
	for _, g := range gs {
		switch {
		case g.GetRole() != messages.Acl_OWNER && g.GetRole() != messages.Acl_READER:
			return fmt.Errorf("invalid role %q", g.GetRole())
		case g.GetGrantedTo() == "":
			return fmt.Errorf("missing granted_to for role %s", g.GetRole())
		case strings.HasPrefix(g.GetGrantedTo(), "group:"):
			if g.GetGrantedTo()[len("group:"):] == "" {
				return fmt.Errorf("invalid granted_to %q for role %s: needs a group name", g.GetGrantedTo(), g.GetRole())
			}
		default:
			id := g.GetGrantedTo()
			if !strings.ContainsRune(g.GetGrantedTo(), ':') {
				id = "user:" + g.GetGrantedTo()
			}
			if _, err := identity.MakeIdentity(id); err != nil {
				return errors.Annotate(err, "invalid granted_to %q for role %s", g.GetGrantedTo(), g.GetRole()).Err()
			}
		}
	}
	return nil
}

// mergeGrants merges valid grants into GrantsByRole, removing and sorting duplicates.
func mergeGrants(grantsLists ...[]*messages.Acl) *GrantsByRole {
	all := map[messages.Acl_Role]stringset.Set{
		messages.Acl_OWNER:  stringset.New(maxGrantsPerJob),
		messages.Acl_READER: stringset.New(maxGrantsPerJob),
	}
	for _, grantsList := range grantsLists {
		for _, g := range grantsList {
			all[g.GetRole()].Add(g.GetGrantedTo())
		}
	}
	sortedSlice := func(s stringset.Set) []string {
		r := s.ToSlice()
		sort.Strings(r)
		return r
	}
	return &GrantsByRole{
		Owners:  sortedSlice(all[messages.Acl_OWNER]),
		Readers: sortedSlice(all[messages.Acl_READER]),
	}
}

// hasGrant is current user is covered by any given grants.
func hasGrant(c context.Context, grantsList ...[]string) (bool, error) {
	currentIdentity := auth.CurrentIdentity(c)
	groups := []string{}
	for _, grants := range grantsList {
		for _, grant := range grants {
			if strings.HasPrefix(grant, "group:") {
				groups = append(groups, grant[len("group:"):])
				continue
			}
			grantedIdentity := identity.Identity(grant)
			if !strings.ContainsRune(grant, ':') {
				// Just email.
				grantedIdentity = identity.Identity("user:" + grant)
			}
			if grantedIdentity == currentIdentity {
				return true, nil
			}
		}
	}
	if isMember, err := auth.IsMember(c, groups...); err != nil {
		return false, transient.Tag.Apply(err)
	} else {
		return isMember, nil
	}
}
<commit_msg>scheduler: fix import.<commit_after>// Copyright 2017 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package acl

import (
	"fmt"
	"regexp"
	"sort"
	"strings"

	"github.com/luci/luci-go/common/data/stringset"
	"github.com/luci/luci-go/common/errors"
	"github.com/luci/luci-go/common/retry/transient"
	"github.com/luci/luci-go/scheduler/appengine/messages"
	"github.com/luci/luci-go/server/auth"
	"github.com/luci/luci-go/server/auth/identity"
	"golang.org/x/net/context"
)

// GrantsByRole can answer questions who can READ and who OWNS the task.
type GrantsByRole struct {
	Owners  []string `gae:",noindex"`
	Readers []string `gae:",noindex"`
}

func (g *GrantsByRole) IsOwner(c context.Context) (bool, error) {
	return hasGrant(c, g.Owners, groupsAdministrators)
}

func (g *GrantsByRole) IsReader(c context.Context) (bool, error) {
	if len(g.Readers) == 0 && len(g.Owners) == 0 {
		// This is here for backwards compatiblity before ACLs were introduced.
		// If Job doesn't specify READERs nor OWNERS explicitely, everybody can read.
		// TODO(tAndrii): remove once every Job/Trigger has ACLs specified.
		return true, nil
	}
	return hasGrant(c, g.Owners, g.Readers, groupsAdministrators)
}

func (g *GrantsByRole) Equal(o *GrantsByRole) bool {
	eqSlice := func(a, b []string) bool {
		if len(a) != len(b) {
			return false
		}
		for i := range a {
			if a[i] != b[i] {
				return false
			}
		}
		return true
	}
	return eqSlice(g.Owners, o.Owners) && eqSlice(g.Readers, o.Readers)
}

// AclSets are parsed and indexed `AclSet` of a project.
type AclSets map[string][]*messages.Acl

// ValidateAclSets validates list of AclSet of a project and returns AclSets.
func ValidateAclSets(sets []*messages.AclSet) (AclSets, error) {
	as := make(AclSets, len(sets))
	for _, s := range sets {
		if s.Name == "" {
			return nil, fmt.Errorf("missing 'name' field'")
		}
		if !aclSetNameRe.MatchString(s.Name) {
			return nil, fmt.Errorf("%q is not valid value for 'name' field", s.Name)
		}
		if _, isDup := as[s.Name]; isDup {
			return nil, fmt.Errorf("aclSet name %q is not unique", s.Name)
		}
		if len(s.GetAcls()) == 0 {
			return nil, fmt.Errorf("aclSet %q has no entries", s.Name)
		}
		as[s.Name] = s.GetAcls()
	}
	return as, nil
}

// ValidateTaskAcls validates task's ACLs and returns TaskAcls.
func ValidateTaskAcls(pSets AclSets, tSets []string, tAcls []*messages.Acl) (*GrantsByRole, error) {
	grantsLists := make([][]*messages.Acl, 0, 1+len(tSets))
	if err := validateGrants(tAcls); err != nil {
		return nil, err
	}
	grantsLists = append(grantsLists, tAcls)
	for _, set := range tSets {
		grantsList, exists := pSets[set]
		if !exists {
			return nil, fmt.Errorf("referencing AclSet '%s' which doesn't exist", set)
		}
		grantsLists = append(grantsLists, grantsList)
	}
	mg := mergeGrants(grantsLists...)
	if n := len(mg.Owners) + len(mg.Readers); n > maxGrantsPerJob {
		return nil, fmt.Errorf("Job or Trigger can have at most %d acls, but %d given", maxGrantsPerJob, n)
	}
	return mg, nil
}

////////////////////////////////////////////////////////////////////////////////

var (
	// aclSetNameRe is used to validate AclSet Name field.
	aclSetNameRe = regexp.MustCompile(`^[0-9A-Za-z_\-\.]{1,100}$`)
	// maxGrantsPerJob is how many different grants are specified for a job.
	maxGrantsPerJob = 32

	groupsAdministrators = []string{"group:administrators"}
)

func validateGrants(gs []*messages.Acl) error {
	for _, g := range gs {
		switch {
		case g.GetRole() != messages.Acl_OWNER && g.GetRole() != messages.Acl_READER:
			return fmt.Errorf("invalid role %q", g.GetRole())
		case g.GetGrantedTo() == "":
			return fmt.Errorf("missing granted_to for role %s", g.GetRole())
		case strings.HasPrefix(g.GetGrantedTo(), "group:"):
			if g.GetGrantedTo()[len("group:"):] == "" {
				return fmt.Errorf("invalid granted_to %q for role %s: needs a group name", g.GetGrantedTo(), g.GetRole())
			}
		default:
			id := g.GetGrantedTo()
			if !strings.ContainsRune(g.GetGrantedTo(), ':') {
				id = "user:" + g.GetGrantedTo()
			}
			if _, err := identity.MakeIdentity(id); err != nil {
				return errors.Annotate(err, "invalid granted_to %q for role %s", g.GetGrantedTo(), g.GetRole()).Err()
			}
		}
	}
	return nil
}

// mergeGrants merges valid grants into GrantsByRole, removing and sorting duplicates.
func mergeGrants(grantsLists ...[]*messages.Acl) *GrantsByRole {
	all := map[messages.Acl_Role]stringset.Set{
		messages.Acl_OWNER:  stringset.New(maxGrantsPerJob),
		messages.Acl_READER: stringset.New(maxGrantsPerJob),
	}
	for _, grantsList := range grantsLists {
		for _, g := range grantsList {
			all[g.GetRole()].Add(g.GetGrantedTo())
		}
	}
	sortedSlice := func(s stringset.Set) []string {
		r := s.ToSlice()
		sort.Strings(r)
		return r
	}
	return &GrantsByRole{
		Owners:  sortedSlice(all[messages.Acl_OWNER]),
		Readers: sortedSlice(all[messages.Acl_READER]),
	}
}

// hasGrant is current user is covered by any given grants.
func hasGrant(c context.Context, grantsList ...[]string) (bool, error) {
	currentIdentity := auth.CurrentIdentity(c)
	groups := []string{}
	for _, grants := range grantsList {
		for _, grant := range grants {
			if strings.HasPrefix(grant, "group:") {
				groups = append(groups, grant[len("group:"):])
				continue
			}
			grantedIdentity := identity.Identity(grant)
			if !strings.ContainsRune(grant, ':') {
				// Just email.
				grantedIdentity = identity.Identity("user:" + grant)
			}
			if grantedIdentity == currentIdentity {
				return true, nil
			}
		}
	}
	if isMember, err := auth.IsMember(c, groups...); err != nil {
		return false, transient.Tag.Apply(err)
	} else {
		return isMember, nil
	}
}
<|endoftext|>


<commit_before>package w32syscall

import (
	"syscall"
	"unsafe"
)

var (
	modkernel32 = syscall.NewLazyDLL("kernel32.dll")
	modadvapi32 = syscall.NewLazyDLL("advapi32.dll")
	moduser32   = syscall.NewLazyDLL("user32.dll")

	procGetDynamicTimeZoneInformation = modkernel32.NewProc("GetDynamicTimeZoneInformation")
	procSetDynamicTimeZoneInformation = modkernel32.NewProc("SetDynamicTimeZoneInformation")

	procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
	procLookupPrivilegeValue  = modadvapi32.NewProc("LookupPrivilegeValueW")
	procRegCreateKeyExW       = modadvapi32.NewProc("RegCreateKeyExW")
	procRegDeleteKeyValueW    = modadvapi32.NewProc("RegDeleteKeyValueW")
	procRegDeleteTreeW        = modadvapi32.NewProc("RegDeleteTreeW")
	procRegGetValueW          = modadvapi32.NewProc("RegGetValueW")
	procRegSetKeyValueW       = modadvapi32.NewProc("RegSetKeyValueW")

	procEnumChildWindows    = moduser32.NewProc("EnumChildWindows")
	procEnumWindows         = moduser32.NewProc("EnumWindows")
	procExitWindowsEx       = moduser32.NewProc("ExitWindowsEx")
	procFindWindowW         = moduser32.NewProc("FindWindowW")
	procGetClassLongW       = moduser32.NewProc("GetClassLongW")
	procGetForegroundWindow = moduser32.NewProc("GetForegroundWindow")
	procSetForegroundWindow = moduser32.NewProc("SetForegroundWindow")
	procSendInput           = moduser32.NewProc("SendInput")
	procSendMessageW        = moduser32.NewProc("SendMessageW")
)

func GetDynamicTimeZoneInformation(timeZoneInformation *DynamicTimeZoneInformation) (err error) {
	r0, _, e1 := syscall.Syscall(procGetDynamicTimeZoneInformation.Addr(), 1,
		uintptr(unsafe.Pointer(timeZoneInformation)),
		0,
		0)
	if r0 == TIME_ZONE_ID_INVALID {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func SetDynamicTimeZoneInformation(timeZoneInformation *DynamicTimeZoneInformation) (err error) {
	r0, _, e1 := syscall.Syscall(procSetDynamicTimeZoneInformation.Addr(), 1,
		uintptr(unsafe.Pointer(timeZoneInformation)),
		0,
		0)
	if r0 == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func AdjustTokenPrivileges(tokenHandle syscall.Token, disableAllPrivileges bool, newState *TokenPrivileges, bufferLength uint32, previousState *TokenPrivileges, returnLength *uint32) (err error) {
	var _p0 uint32
	if disableAllPrivileges {
		_p0 = 1
	} else {
		_p0 = 0
	}
	r1, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6,
		uintptr(tokenHandle),
		uintptr(_p0),
		uintptr(unsafe.Pointer(newState)),
		uintptr(bufferLength),
		uintptr(unsafe.Pointer(previousState)),
		uintptr(unsafe.Pointer(returnLength)))
	if r1 == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func LookupPrivilegeValue(systemName, name *uint16, luid *Luid) (err error) {
	r1, _, e1 := syscall.Syscall(procLookupPrivilegeValue.Addr(), 3,
		uintptr(unsafe.Pointer(systemName)),
		uintptr(unsafe.Pointer(name)),
		uintptr(unsafe.Pointer(luid)))
	if r1 == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func RegCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desiredAccess uint32, securityAttributes *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) {
	r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(securityAttributes)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition)))
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegDeleteKeyValue(key syscall.Handle, subkey *uint16, valname *uint16) (regerrno error) {
	r0, _, _ := syscall.Syscall(procRegDeleteKeyValueW.Addr(), 3, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(unsafe.Pointer(valname)))
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegDeleteTree(key syscall.Handle, subkey *uint16) (regerrno error) {
	r0, _, _ := syscall.Syscall(procRegDeleteTreeW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0)
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegGetValue(key syscall.Handle, subkey *uint16, valname *uint16, flags uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) {
	r0, _, _ := syscall.Syscall9(procRegGetValueW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(unsafe.Pointer(valname)), uintptr(flags), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0, 0)
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegSetKeyValue(key syscall.Handle, subkey *uint16, valname *uint16, valtype uint32, buf *byte, buflen uint32) (regerrno error) {
	r0, _, _ := syscall.Syscall6(procRegSetKeyValueW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(unsafe.Pointer(valname)), uintptr(valtype), uintptr(unsafe.Pointer(buf)), uintptr(buflen))
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func EnumChildWindows(hwndParent syscall.Handle, callback func(hwnd syscall.Handle, lparam uintptr) bool, lparam uintptr) (err error) {
	cb := func(hwnd syscall.Handle, lparam uintptr) int {
		if callback(hwnd, lparam) {
			return 1
		} else {
			return 0
		}
	}
	r1, _, e1 := syscall.Syscall(procEnumChildWindows.Addr(), 3, uintptr(hwndParent), syscall.NewCallback(cb), lparam)
	if r1 != 0 {
		if e1 != 0 {
			err = error(e1)
			return
		}
	}
	return
}

func EnumWindows(callback func(hwnd syscall.Handle, lparam uintptr) bool, lparam uintptr) (err error) {
	cb := func(hwnd syscall.Handle, lparam uintptr) int {
		if callback(hwnd, lparam) {
			return 1
		} else {
			return 0
		}
	}
	r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, syscall.NewCallback(cb), lparam, 0)
	if r1 != 0 {
		if e1 != 0 {
			err = error(e1)
			return
		}
	}
	return
}

func ExitWindowsEx(flags uint, reason uint32) (err error) {
	r1, _, e1 := syscall.Syscall(procExitWindowsEx.Addr(), 2, uintptr(flags), uintptr(reason), 0)
	if r1 != 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func FindWindowW(className, windowName *uint16) (handle syscall.Handle, err error) {
	r1, _, e1 := syscall.Syscall(procFindWindowW.Addr(), 2, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(windowName)), 0)
	if r1 != 0 {
		handle = syscall.Handle(r1)
	} else {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func SetForegroundWindow(hwnd syscall.Handle) bool {
	r1, _, _ := syscall.Syscall(procSetForegroundWindow.Addr(), 1, uintptr(hwnd), 0, 0)
	return r1 != 0
}

func GetForegroundWindow() syscall.Handle {
	r1, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 0, 0, 0, 0)
	return syscall.Handle(r1)
}

func GetClassLong(hwnd syscall.Handle, index int) (result uintptr, err error) {
	result, _, e1 := syscall.Syscall(procGetClassLongW.Addr(), 2, uintptr(hwnd), uintptr(index), 0)
	if result == 0 {
		err = error(e1)
	}
	return
}

func SendInput(inputCount uint, inputs *Input, byteSize int) (count int, err error) {
	r1, _, e1 := syscall.Syscall(procSendInput.Addr(), 3, uintptr(inputCount), uintptr(unsafe.Pointer(inputs)), uintptr(byteSize))
	if r1 != 0 {
		count = int(r1)
	} else {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func SendMessage(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) (result uintptr, err error) {
	result, _, e1 := syscall.Syscall6(procSendMessageW.Addr(), 4, uintptr(hwnd), uintptr(msg), wparam, lparam, 0, 0)
	if e1 != 0 {
		err = error(e1)
		return
	}
	return
}
<commit_msg>Add GetClassName<commit_after>package w32syscall

import (
	"syscall"
	"unsafe"
)

var (
	modkernel32 = syscall.NewLazyDLL("kernel32.dll")
	modadvapi32 = syscall.NewLazyDLL("advapi32.dll")
	moduser32   = syscall.NewLazyDLL("user32.dll")

	procGetDynamicTimeZoneInformation = modkernel32.NewProc("GetDynamicTimeZoneInformation")
	procSetDynamicTimeZoneInformation = modkernel32.NewProc("SetDynamicTimeZoneInformation")

	procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
	procLookupPrivilegeValue  = modadvapi32.NewProc("LookupPrivilegeValueW")
	procRegCreateKeyExW       = modadvapi32.NewProc("RegCreateKeyExW")
	procRegDeleteKeyValueW    = modadvapi32.NewProc("RegDeleteKeyValueW")
	procRegDeleteTreeW        = modadvapi32.NewProc("RegDeleteTreeW")
	procRegGetValueW          = modadvapi32.NewProc("RegGetValueW")
	procRegSetKeyValueW       = modadvapi32.NewProc("RegSetKeyValueW")

	procEnumChildWindows    = moduser32.NewProc("EnumChildWindows")
	procEnumWindows         = moduser32.NewProc("EnumWindows")
	procExitWindowsEx       = moduser32.NewProc("ExitWindowsEx")
	procFindWindowW         = moduser32.NewProc("FindWindowW")
	procGetClassNameW       = moduser32.NewProc("GetClassNameW")
	procGetClassLongW       = moduser32.NewProc("GetClassLongW")
	procGetForegroundWindow = moduser32.NewProc("GetForegroundWindow")
	procSetForegroundWindow = moduser32.NewProc("SetForegroundWindow")
	procSendInput           = moduser32.NewProc("SendInput")
	procSendMessageW        = moduser32.NewProc("SendMessageW")
)

func GetDynamicTimeZoneInformation(timeZoneInformation *DynamicTimeZoneInformation) (err error) {
	r0, _, e1 := syscall.Syscall(procGetDynamicTimeZoneInformation.Addr(), 1,
		uintptr(unsafe.Pointer(timeZoneInformation)),
		0,
		0)
	if r0 == TIME_ZONE_ID_INVALID {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func SetDynamicTimeZoneInformation(timeZoneInformation *DynamicTimeZoneInformation) (err error) {
	r0, _, e1 := syscall.Syscall(procSetDynamicTimeZoneInformation.Addr(), 1,
		uintptr(unsafe.Pointer(timeZoneInformation)),
		0,
		0)
	if r0 == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func AdjustTokenPrivileges(tokenHandle syscall.Token, disableAllPrivileges bool, newState *TokenPrivileges, bufferLength uint32, previousState *TokenPrivileges, returnLength *uint32) (err error) {
	var _p0 uint32
	if disableAllPrivileges {
		_p0 = 1
	} else {
		_p0 = 0
	}
	r1, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6,
		uintptr(tokenHandle),
		uintptr(_p0),
		uintptr(unsafe.Pointer(newState)),
		uintptr(bufferLength),
		uintptr(unsafe.Pointer(previousState)),
		uintptr(unsafe.Pointer(returnLength)))
	if r1 == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func LookupPrivilegeValue(systemName, name *uint16, luid *Luid) (err error) {
	r1, _, e1 := syscall.Syscall(procLookupPrivilegeValue.Addr(), 3,
		uintptr(unsafe.Pointer(systemName)),
		uintptr(unsafe.Pointer(name)),
		uintptr(unsafe.Pointer(luid)))
	if r1 == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func RegCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desiredAccess uint32, securityAttributes *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) {
	r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(securityAttributes)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition)))
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegDeleteKeyValue(key syscall.Handle, subkey *uint16, valname *uint16) (regerrno error) {
	r0, _, _ := syscall.Syscall(procRegDeleteKeyValueW.Addr(), 3, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(unsafe.Pointer(valname)))
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegDeleteTree(key syscall.Handle, subkey *uint16) (regerrno error) {
	r0, _, _ := syscall.Syscall(procRegDeleteTreeW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0)
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegGetValue(key syscall.Handle, subkey *uint16, valname *uint16, flags uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) {
	r0, _, _ := syscall.Syscall9(procRegGetValueW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(unsafe.Pointer(valname)), uintptr(flags), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0, 0)
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func RegSetKeyValue(key syscall.Handle, subkey *uint16, valname *uint16, valtype uint32, buf *byte, buflen uint32) (regerrno error) {
	r0, _, _ := syscall.Syscall6(procRegSetKeyValueW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(unsafe.Pointer(valname)), uintptr(valtype), uintptr(unsafe.Pointer(buf)), uintptr(buflen))
	if r0 != 0 {
		regerrno = syscall.Errno(r0)
	}
	return
}

func EnumChildWindows(hwndParent syscall.Handle, callback func(hwnd syscall.Handle, lparam uintptr) bool, lparam uintptr) (err error) {
	cb := func(hwnd syscall.Handle, lparam uintptr) int {
		if callback(hwnd, lparam) {
			return 1
		} else {
			return 0
		}
	}
	r1, _, e1 := syscall.Syscall(procEnumChildWindows.Addr(), 3, uintptr(hwndParent), syscall.NewCallback(cb), lparam)
	if r1 != 0 {
		if e1 != 0 {
			err = error(e1)
			return
		}
	}
	return
}

func EnumWindows(callback func(hwnd syscall.Handle, lparam uintptr) bool, lparam uintptr) (err error) {
	cb := func(hwnd syscall.Handle, lparam uintptr) int {
		if callback(hwnd, lparam) {
			return 1
		} else {
			return 0
		}
	}
	r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, syscall.NewCallback(cb), lparam, 0)
	if r1 != 0 {
		if e1 != 0 {
			err = error(e1)
			return
		}
	}
	return
}

func ExitWindowsEx(flags uint, reason uint32) (err error) {
	r1, _, e1 := syscall.Syscall(procExitWindowsEx.Addr(), 2, uintptr(flags), uintptr(reason), 0)
	if r1 != 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func FindWindowW(className, windowName *uint16) (handle syscall.Handle, err error) {
	r1, _, e1 := syscall.Syscall(procFindWindowW.Addr(), 2, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(windowName)), 0)
	if r1 != 0 {
		handle = syscall.Handle(r1)
	} else {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func SetForegroundWindow(hwnd syscall.Handle) bool {
	r1, _, _ := syscall.Syscall(procSetForegroundWindow.Addr(), 1, uintptr(hwnd), 0, 0)
	return r1 != 0
}

func GetForegroundWindow() syscall.Handle {
	r1, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 0, 0, 0, 0)
	return syscall.Handle(r1)
}

func GetClassLong(hwnd syscall.Handle, index int) (result uintptr, err error) {
	result, _, e1 := syscall.Syscall(procGetClassLongW.Addr(), 2, uintptr(hwnd), uintptr(index), 0)
	if result == 0 {
		err = error(e1)
	}
	return
}

func GetClassName(hwnd syscall.Handle, buf []uint16, buflen int) (err error) {
	result, _, e1 := syscall.Syscall(procGetClassNameW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(&buf[0])), uintptr(buflen))
	if result == 0 {
		err = error(e1)
	}
	return
}

func SendInput(inputCount uint, inputs *Input, byteSize int) (count int, err error) {
	r1, _, e1 := syscall.Syscall(procSendInput.Addr(), 3, uintptr(inputCount), uintptr(unsafe.Pointer(inputs)), uintptr(byteSize))
	if r1 != 0 {
		count = int(r1)
	} else {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func SendMessage(hwnd syscall.Handle, msg uint32, wparam, lparam uintptr) (result uintptr, err error) {
	result, _, e1 := syscall.Syscall6(procSendMessageW.Addr(), 4, uintptr(hwnd), uintptr(msg), wparam, lparam, 0, 0)
	if e1 != 0 {
		err = error(e1)
		return
	}
	return
}
<|endoftext|>


<commit_before>// Copyright 2015 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"runtime"

	"github.com/google/syzkaller/pkg/csource"
	"github.com/google/syzkaller/prog"
	_ "github.com/google/syzkaller/sys"
)

var (
	flagOS         = flag.String("os", runtime.GOOS, "target os")
	flagArch       = flag.String("arch", runtime.GOARCH, "target arch")
	flagThreaded   = flag.Bool("threaded", false, "create threaded program")
	flagCollide    = flag.Bool("collide", false, "create collide program")
	flagRepeat     = flag.Bool("repeat", false, "repeat program infinitely or not")
	flagProcs      = flag.Int("procs", 1, "number of parallel processes")
	flagSandbox    = flag.String("sandbox", "", "sandbox to use (none, setuid, namespace)")
	flagProg       = flag.String("prog", "", "file with program to convert (required)")
	flagFaultCall  = flag.Int("fault_call", -1, "inject fault into this call (0-based)")
	flagFaultNth   = flag.Int("fault_nth", 0, "inject fault on n-th operation (0-based)")
	flagEnableTun  = flag.Bool("tun", false, "set up TUN/TAP interface")
	flagUseTmpDir  = flag.Bool("tmpdir", false, "create a temporary dir and execute inside it")
	flagCgroups    = flag.Bool("cgroups", false, "enable cgroups support")
	flagNetdev     = flag.Bool("netdev", false, "setup various net devices")
	flagResetNet   = flag.Bool("resetnet", false, "reset net namespace after each test")
	flagHandleSegv = flag.Bool("segv", false, "catch and ignore SIGSEGV")
	flagWaitRepeat = flag.Bool("waitrepeat", false, "wait for each repeat attempt")
	flagDebug      = flag.Bool("debug", false, "generate debug printfs")
)

func main() {
	flag.Parse()
	if *flagProg == "" {
		flag.PrintDefaults()
		os.Exit(1)
	}
	target, err := prog.GetTarget(*flagOS, *flagArch)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		os.Exit(1)
	}
	data, err := ioutil.ReadFile(*flagProg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to read prog file: %v\n", err)
		os.Exit(1)
	}
	p, err := target.Deserialize(data)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to deserialize the program: %v\n", err)
		os.Exit(1)
	}
	opts := csource.Options{
		Threaded:      *flagThreaded,
		Collide:       *flagCollide,
		Repeat:        *flagRepeat,
		Procs:         *flagProcs,
		Sandbox:       *flagSandbox,
		Fault:         *flagFaultCall >= 0,
		FaultCall:     *flagFaultCall,
		FaultNth:      *flagFaultNth,
		EnableTun:     *flagEnableTun,
		UseTmpDir:     *flagUseTmpDir,
		EnableCgroups: *flagCgroups,
		EnableNetdev:  *flagNetdev,
		ResetNet:      *flagResetNet,
		HandleSegv:    *flagHandleSegv,
		WaitRepeat:    *flagWaitRepeat,
		Debug:         *flagDebug,
		Repro:         false,
	}
	src, err := csource.Write(p, opts)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate C source: %v\n", err)
		os.Exit(1)
	}
	if formatted, err := csource.Format(src); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	} else {
		src = formatted
	}
	os.Stdout.Write(src)
}
<commit_msg>tools/syz-prog2c: allow to test build of the resulting program<commit_after>// Copyright 2015 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"runtime"

	"github.com/google/syzkaller/pkg/csource"
	"github.com/google/syzkaller/prog"
	_ "github.com/google/syzkaller/sys"
)

var (
	flagOS         = flag.String("os", runtime.GOOS, "target os")
	flagArch       = flag.String("arch", runtime.GOARCH, "target arch")
	flagBuild      = flag.Bool("build", false, "also build the generated program")
	flagThreaded   = flag.Bool("threaded", false, "create threaded program")
	flagCollide    = flag.Bool("collide", false, "create collide program")
	flagRepeat     = flag.Bool("repeat", false, "repeat program infinitely or not")
	flagProcs      = flag.Int("procs", 1, "number of parallel processes")
	flagSandbox    = flag.String("sandbox", "", "sandbox to use (none, setuid, namespace)")
	flagProg       = flag.String("prog", "", "file with program to convert (required)")
	flagFaultCall  = flag.Int("fault_call", -1, "inject fault into this call (0-based)")
	flagFaultNth   = flag.Int("fault_nth", 0, "inject fault on n-th operation (0-based)")
	flagEnableTun  = flag.Bool("tun", false, "set up TUN/TAP interface")
	flagUseTmpDir  = flag.Bool("tmpdir", false, "create a temporary dir and execute inside it")
	flagCgroups    = flag.Bool("cgroups", false, "enable cgroups support")
	flagNetdev     = flag.Bool("netdev", false, "setup various net devices")
	flagResetNet   = flag.Bool("resetnet", false, "reset net namespace after each test")
	flagHandleSegv = flag.Bool("segv", false, "catch and ignore SIGSEGV")
	flagWaitRepeat = flag.Bool("waitrepeat", false, "wait for each repeat attempt")
	flagDebug      = flag.Bool("debug", false, "generate debug printfs")
)

func main() {
	flag.Parse()
	if *flagProg == "" {
		flag.PrintDefaults()
		os.Exit(1)
	}
	target, err := prog.GetTarget(*flagOS, *flagArch)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		os.Exit(1)
	}
	data, err := ioutil.ReadFile(*flagProg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to read prog file: %v\n", err)
		os.Exit(1)
	}
	p, err := target.Deserialize(data)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to deserialize the program: %v\n", err)
		os.Exit(1)
	}
	opts := csource.Options{
		Threaded:      *flagThreaded,
		Collide:       *flagCollide,
		Repeat:        *flagRepeat,
		Procs:         *flagProcs,
		Sandbox:       *flagSandbox,
		Fault:         *flagFaultCall >= 0,
		FaultCall:     *flagFaultCall,
		FaultNth:      *flagFaultNth,
		EnableTun:     *flagEnableTun,
		UseTmpDir:     *flagUseTmpDir,
		EnableCgroups: *flagCgroups,
		EnableNetdev:  *flagNetdev,
		ResetNet:      *flagResetNet,
		HandleSegv:    *flagHandleSegv,
		WaitRepeat:    *flagWaitRepeat,
		Debug:         *flagDebug,
		Repro:         false,
	}
	src, err := csource.Write(p, opts)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to generate C source: %v\n", err)
		os.Exit(1)
	}
	if formatted, err := csource.Format(src); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	} else {
		src = formatted
	}
	os.Stdout.Write(src)
	if !*flagBuild {
		return
	}
	bin, err := csource.Build(target, src)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to build C source: %v\n", err)
		os.Exit(1)
	}
	os.Remove(bin)
	fmt.Fprintf(os.Stderr, "binary build OK\n")
}
<|endoftext|>


<commit_before>package ztls

import (
	"crypto/rsa"
	"encoding/binary"
	"encoding/json"
	"math/big"

	"github.com/zmap/zgrab/ztools/x509"
)

type TLSVersion uint16

type ServerHello struct {
	Version             TLSVersion  `json:"version"`
	Random              []byte      `json:"random"`
	SessionID           []byte      `json:"session_id"`
	CipherSuite         CipherSuite `json:"cipher_suite"`
	CompressionMethod   uint8       `json:"compression_method"`
	OcspStapling        bool        `json:"ocsp_stapling"`
	TicketSupported     bool        `json:"ticket"`
	SecureRenegotiation bool        `json:"secure_renegotiation"`
	HeartbeatSupported  bool        `json:"heartbeat"`
}

// ServerCertificates represents a TLS certificates message in a format friendly to the golang JSON library.
// ValidationError should be non-nil whenever Valid is false.
type Certificates struct {
	Certificates       [][]byte
	ParsedCertificates []*x509.Certificate
}

// ServerKeyExchange represents the raw key data sent by the server in TLS key exchange message
type ServerKeyExchange struct {
	Key []byte `json:"key"`
}

// Finished represents a TLS Finished message
type Finished struct {
	VerifyData []byte `json:"verify_data"`
}

// ServerHandshake stores all of the messages sent by the server during a standard TLS Handshake.
// It implements zgrab.EventData interface
type ServerHandshake struct {
	ServerHello        *ServerHello       `json:"server_hello"`
	ServerCertificates *Certificates      `json:"server_certificates"`
	ServerKeyExchange  *ServerKeyExchange `json:"server_key_exchange"`
	RSAExportParams    *RSAExportParams   `json:"rsa_export_params,omitempty"`
	DHExportParams     *DHParams          `json:"dh_export_params,omitempty"`
	DHParams           *DHParams          `json:"dh_params,omitempty"`
	ServerFinished     *Finished          `json:"server_finished"`
}

func (c *Conn) GetHandshakeLog() *ServerHandshake {
	return c.handshakeLog
}

func (m *serverHelloMsg) MakeLog() *ServerHello {
	sh := new(ServerHello)
	sh.Version = TLSVersion(m.vers)
	sh.Random = make([]byte, len(m.random))
	copy(sh.Random, m.random)
	sh.SessionID = make([]byte, len(m.sessionId))
	copy(sh.SessionID, m.sessionId)
	sh.CipherSuite = CipherSuite(m.cipherSuite)
	sh.CompressionMethod = m.compressionMethod
	sh.OcspStapling = m.ocspStapling
	sh.TicketSupported = m.ticketSupported
	sh.SecureRenegotiation = m.secureRenegotiation
	sh.HeartbeatSupported = m.heartbeatEnabled
	return sh
}

func (m *certificateMsg) MakeLog() *Certificates {
	sc := new(Certificates)
	sc.Certificates = make([][]byte, len(m.certificates))
	for idx, cert := range m.certificates {
		sc.Certificates[idx] = make([]byte, len(cert))
		copy(sc.Certificates[idx], cert)
	}
	return sc
}

func (m *serverKeyExchangeMsg) MakeLog() *ServerKeyExchange {
	skx := new(ServerKeyExchange)
	skx.Key = make([]byte, len(m.key))
	copy(skx.Key, m.key)
	return skx
}

func (m *finishedMsg) MakeLog() *Finished {
	sf := new(Finished)
	sf.VerifyData = make([]byte, len(m.verifyData))
	copy(sf.VerifyData, m.verifyData)
	return sf
}

type ExportSignatureAlgorithm uint16

var exportHashes = []string{
	"MD5",
	"SHA-1",
	"SHA-224",
	"SHA-256",
	"SHA-384",
	"SHA-512",
}

var exportAlgorithms = []string{
	"anon",
	"RSA",
	"DSA",
	"ECDSA",
}

func (esa *ExportSignatureAlgorithm) MarshalJSON() ([]byte, error) {
	value := uint16(*esa)
	hash := int(byte(value >> 8))
	alg := int(byte(value))

	var aux struct {
		Value    uint16 `json:"value"`
		HashName string `json:"hash_name,omitempty"`
		HashID   int    `json:"hash_id"`
		AlgName  string `json:"algorithm_name,omitempty"`
		AlgID    int    `json:"algorithm_id"`
	}
	if hash < len(exportHashes) {
		aux.HashName = exportHashes[hash]
	}
	if alg < len(exportAlgorithms) {
		aux.AlgName = exportAlgorithms[alg]
	}
	aux.Value = value
	aux.HashID = hash
	aux.AlgID = alg
	return json.Marshal(&aux)
}

type RSAExportParams struct {
	PublicKey rsa.PublicKey `json:"-"`
	Modulus   []byte        `json:"modulus"`
	Exponent  uint32        `json:"exponent"`
	Length    int           `json:"length"`
}

type DHParams struct {
	P  *big.Int
	G  *big.Int
	Ys *big.Int
}

func (p *DHParams) MarshalJSON() ([]byte, error) {
	var aux struct {
		P        []byte `json:"prime"`
		PrimeLen int    `json:"prime_length"`
		G        []byte `json:"generator"`
		Ys       []byte `json:"public_exponent"`
	}
	aux.P = p.P.Bytes()
	aux.PrimeLen = p.P.BitLen()
	aux.G = p.G.Bytes()
	aux.Ys = p.Ys.Bytes()
	return json.Marshal(&aux)
}

func (p *rsaExportParams) MakeLog() *RSAExportParams {
	out := new(RSAExportParams)
	exponent := uint32(0)
	for _, b := range p.rawExponent {
		exponent <<= 8
		exponent |= uint32(b)
	}
	modulus := big.NewInt(0)
	modulus.SetBytes(p.rawModulus)
	key := rsa.PublicKey{
		N: modulus,
		E: int(exponent),
	}
	out.PublicKey = key
	out.Modulus = modulus.Bytes()
	out.Exponent = exponent
	out.Length = modulus.BitLen()
	return out
}

func (p *DHParams) unmarshal(buf []byte) bool {
	if len(buf) < 2 {
		return false
	}
	pLength := binary.BigEndian.Uint16(buf)
	buf = buf[2:]

	if len(buf) < int(pLength) {
		return false
	}
	pBytes := buf[0:pLength]
	buf = buf[pLength:]
	p.P = big.NewInt(0)
	p.P.SetBytes(pBytes)

	if len(buf) < 2 {
		return false
	}
	gLength := binary.BigEndian.Uint16(buf)
	buf = buf[2:]

	if len(buf) < int(gLength) {
		return false
	}
	gBytes := buf[0:gLength]
	buf = buf[gLength:]
	p.G = big.NewInt(0)
	p.G.SetBytes(gBytes)

	if len(buf) < 2 {
		return false
	}
	ysLength := binary.BigEndian.Uint16(buf)
	buf = buf[2:]

	if len(buf) < int(ysLength) {
		return false
	}
	ysBytes := buf[0:ysLength]
	p.Ys = big.NewInt(0)
	p.Ys.SetBytes(ysBytes)

	return true
}
<commit_msg>Add ClientHello random to output<commit_after>package ztls

import (
	"crypto/rsa"
	"encoding/binary"
	"encoding/json"
	"math/big"

	"github.com/zmap/zgrab/ztools/x509"
)

type TLSVersion uint16

type ClientHello struct {
	Random    []byte `json:"random"`
	SessionID []byte `json:"session_id,omitempty"`
}

type ServerHello struct {
	Version             TLSVersion  `json:"version"`
	Random              []byte      `json:"random"`
	SessionID           []byte      `json:"session_id"`
	CipherSuite         CipherSuite `json:"cipher_suite"`
	CompressionMethod   uint8       `json:"compression_method"`
	OcspStapling        bool        `json:"ocsp_stapling"`
	TicketSupported     bool        `json:"ticket"`
	SecureRenegotiation bool        `json:"secure_renegotiation"`
	HeartbeatSupported  bool        `json:"heartbeat"`
}

// ServerCertificates represents a TLS certificates message in a format friendly to the golang JSON library.
// ValidationError should be non-nil whenever Valid is false.
type Certificates struct {
	Certificates       [][]byte
	ParsedCertificates []*x509.Certificate
}

// ServerKeyExchange represents the raw key data sent by the server in TLS key exchange message
type ServerKeyExchange struct {
	Key []byte `json:"key"`
}

// Finished represents a TLS Finished message
type Finished struct {
	VerifyData []byte `json:"verify_data"`
}

// ServerHandshake stores all of the messages sent by the server during a standard TLS Handshake.
// It implements zgrab.EventData interface
type ServerHandshake struct {
	ClientHello        *ClientHello       `json:"client_hello,omitempty"`
	ServerHello        *ServerHello       `json:"server_hello"`
	ServerCertificates *Certificates      `json:"server_certificates"`
	ServerKeyExchange  *ServerKeyExchange `json:"server_key_exchange"`
	RSAExportParams    *RSAExportParams   `json:"rsa_export_params,omitempty"`
	DHExportParams     *DHParams          `json:"dh_export_params,omitempty"`
	DHParams           *DHParams          `json:"dh_params,omitempty"`
	ServerFinished     *Finished          `json:"server_finished"`
}

func (c *Conn) GetHandshakeLog() *ServerHandshake {
	return c.handshakeLog
}

func (m *clientHelloMsg) MakeLog() *ClientHello {
	ch := new(ClientHello)
	ch.Random = make([]byte, len(m.random))
	copy(ch.Random, m.random)
	ch.SessionID = make([]byte, len(m.sessionId))
	copy(ch.SessionID, m.sessionId)
	return ch
}

func (m *serverHelloMsg) MakeLog() *ServerHello {
	sh := new(ServerHello)
	sh.Version = TLSVersion(m.vers)
	sh.Random = make([]byte, len(m.random))
	copy(sh.Random, m.random)
	sh.SessionID = make([]byte, len(m.sessionId))
	copy(sh.SessionID, m.sessionId)
	sh.CipherSuite = CipherSuite(m.cipherSuite)
	sh.CompressionMethod = m.compressionMethod
	sh.OcspStapling = m.ocspStapling
	sh.TicketSupported = m.ticketSupported
	sh.SecureRenegotiation = m.secureRenegotiation
	sh.HeartbeatSupported = m.heartbeatEnabled
	return sh
}

func (m *certificateMsg) MakeLog() *Certificates {
	sc := new(Certificates)
	sc.Certificates = make([][]byte, len(m.certificates))
	for idx, cert := range m.certificates {
		sc.Certificates[idx] = make([]byte, len(cert))
		copy(sc.Certificates[idx], cert)
	}
	return sc
}

func (m *serverKeyExchangeMsg) MakeLog() *ServerKeyExchange {
	skx := new(ServerKeyExchange)
	skx.Key = make([]byte, len(m.key))
	copy(skx.Key, m.key)
	return skx
}

func (m *finishedMsg) MakeLog() *Finished {
	sf := new(Finished)
	sf.VerifyData = make([]byte, len(m.verifyData))
	copy(sf.VerifyData, m.verifyData)
	return sf
}

type ExportSignatureAlgorithm uint16

var exportHashes = []string{
	"MD5",
	"SHA-1",
	"SHA-224",
	"SHA-256",
	"SHA-384",
	"SHA-512",
}

var exportAlgorithms = []string{
	"anon",
	"RSA",
	"DSA",
	"ECDSA",
}

func (esa *ExportSignatureAlgorithm) MarshalJSON() ([]byte, error) {
	value := uint16(*esa)
	hash := int(byte(value >> 8))
	alg := int(byte(value))

	var aux struct {
		Value    uint16 `json:"value"`
		HashName string `json:"hash_name,omitempty"`
		HashID   int    `json:"hash_id"`
		AlgName  string `json:"algorithm_name,omitempty"`
		AlgID    int    `json:"algorithm_id"`
	}
	if hash < len(exportHashes) {
		aux.HashName = exportHashes[hash]
	}
	if alg < len(exportAlgorithms) {
		aux.AlgName = exportAlgorithms[alg]
	}
	aux.Value = value
	aux.HashID = hash
	aux.AlgID = alg
	return json.Marshal(&aux)
}

type RSAExportParams struct {
	PublicKey rsa.PublicKey `json:"-"`
	Modulus   []byte        `json:"modulus"`
	Exponent  uint32        `json:"exponent"`
	Length    int           `json:"length"`
}

type DHParams struct {
	P  *big.Int
	G  *big.Int
	Ys *big.Int
}

func (p *DHParams) MarshalJSON() ([]byte, error) {
	var aux struct {
		P        []byte `json:"prime"`
		PrimeLen int    `json:"prime_length"`
		G        []byte `json:"generator"`
		Ys       []byte `json:"public_exponent"`
	}
	aux.P = p.P.Bytes()
	aux.PrimeLen = p.P.BitLen()
	aux.G = p.G.Bytes()
	aux.Ys = p.Ys.Bytes()
	return json.Marshal(&aux)
}

func (p *rsaExportParams) MakeLog() *RSAExportParams {
	out := new(RSAExportParams)
	exponent := uint32(0)
	for _, b := range p.rawExponent {
		exponent <<= 8
		exponent |= uint32(b)
	}
	modulus := big.NewInt(0)
	modulus.SetBytes(p.rawModulus)
	key := rsa.PublicKey{
		N: modulus,
		E: int(exponent),
	}
	out.PublicKey = key
	out.Modulus = modulus.Bytes()
	out.Exponent = exponent
	out.Length = modulus.BitLen()
	return out
}

func (p *DHParams) unmarshal(buf []byte) bool {
	if len(buf) < 2 {
		return false
	}
	pLength := binary.BigEndian.Uint16(buf)
	buf = buf[2:]

	if len(buf) < int(pLength) {
		return false
	}
	pBytes := buf[0:pLength]
	buf = buf[pLength:]
	p.P = big.NewInt(0)
	p.P.SetBytes(pBytes)

	if len(buf) < 2 {
		return false
	}
	gLength := binary.BigEndian.Uint16(buf)
	buf = buf[2:]

	if len(buf) < int(gLength) {
		return false
	}
	gBytes := buf[0:gLength]
	buf = buf[gLength:]
	p.G = big.NewInt(0)
	p.G.SetBytes(gBytes)

	if len(buf) < 2 {
		return false
	}
	ysLength := binary.BigEndian.Uint16(buf)
	buf = buf[2:]

	if len(buf) < int(ysLength) {
		return false
	}
	ysBytes := buf[0:ysLength]
	p.Ys = big.NewInt(0)
	p.Ys.SetBytes(ysBytes)

	return true
}
<|endoftext|>


<commit_before>package push

import (
	"path"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("HTTP random route", func() {
	var (
		appName string
	)

	BeforeEach(func() {
		appName = "short-app-name" // used on purpose to fit route length requirement
	})

	When("passed the --random-route flag", func() {
		When("the app does not already exist", func() {
			It("generates a random route for the app", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "--no-start")
					Eventually(session).Should(Say("routes:"))
					Eventually(session).Should(Say(`(?i)\+\s+%s-[\w]+-[\w]+.%s`, appName, helpers.DefaultSharedDomain()))
					Eventually(session).Should(Exit(0))
				})

				appSession := helpers.CF("app", appName)
				Eventually(appSession).Should(Say(`name:\s+%s`, appName))
				Eventually(appSession).Should(Say(`(?i)routes:\s+%s-[\w]+-[\w]+.%s`, appName, helpers.DefaultSharedDomain()))
				Eventually(appSession).Should(Exit(0))
			})
		})

		When("the app exists and has an existing route", func() {
			It("does not generate a random route for the app", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "--no-start")
					Eventually(session).ShouldNot(Say(`\+\s+%s-[\w]+`, appName))
					Eventually(session).Should(Exit(0))
				})
			})

			When("also passed an http domain", func() {
				var domain helpers.Domain

				BeforeEach(func() {
					domain = helpers.NewDomain(organization, helpers.NewDomainName("some-domain"))
					domain.Create()
				})

				AfterEach(func() {
					domain.Delete()
				})

				It("does not create a new route with the provided domain name", func() {
					helpers.WithHelloWorldApp(func(dir string) {
						session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "-d", domain.Name, "--no-start")
						Eventually(session).ShouldNot(Say(`(?i)\+\s+%s-[\w]+-[\w]+.%s`, appName, domain.Name))
						Eventually(session).Should(Exit(0))
					})
				})
			})
		})

		When("also passed an http domain", func() {
			var domain helpers.Domain

			BeforeEach(func() {
				domain = helpers.NewDomain(organization, helpers.NewDomainName("some-domain"))
				domain.Create()
			})

			AfterEach(func() {
				domain.Delete()
			})

			It("creates a new route with the provided domain", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "-d", domain.Name, "--no-start")
					Eventually(session).Should(Say(`(?i)\+\s+%s-[\w]+-[\w]+.%s`, appName, domain.Name))
					Eventually(session).Should(Exit(0))
				})
			})
		})
	})

	When("passed the random-route manifest property", func() {
		var manifest map[string]interface{}

		BeforeEach(func() {
			manifest = map[string]interface{}{
				"applications": []map[string]interface{}{
					{
						"name":         appName,
						"random-route": true,
					},
				},
			}

			helpers.WithHelloWorldApp(func(dir string) {
				helpers.WriteManifest(path.Join(dir, "manifest.yml"), manifest)
				session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--no-start")
				Eventually(session).Should(Say("routes:"))
				Eventually(session).Should(Say(`(?i)\+\s+%s-[\w]+-[\w]+.%s`, appName, helpers.DefaultSharedDomain()))
				Eventually(session).Should(Exit(0))
			})
		})

		It("generates a random route for the app", func() {
			session := helpers.CF("app", appName)
			Eventually(session).Should(Say(`name:\s+%s`, appName))
			Eventually(session).Should(Say(`(?i)routes:\s+%s-[\w]+-[\w]+.%s`, appName, helpers.DefaultSharedDomain()))
			Eventually(session).Should(Exit(0))
		})

		When("the app has an existing route", func() {
			It("does not generate a random route for the app", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					helpers.WriteManifest(path.Join(dir, "manifest.yml"), manifest)

					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--no-start")
					Eventually(session).ShouldNot(Say(`\+\s+%s-[\w]+`, appName))
					Eventually(session).Should(Exit(0))
				})
			})
		})
	})
})
<commit_msg>Extract random route regexp to a constant<commit_after>package push

import (
	"path"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("HTTP random route", func() {

	const randomRouteRegexp = `\+\s+%s-[\w]+-[\w]+\.%s`

	var (
		appName string
	)

	BeforeEach(func() {
		appName = "short-app-name" // used on purpose to fit route length requirement
	})

	When("passed the --random-route flag", func() {
		When("the app does not already exist", func() {
			It("generates a random route for the app", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "--no-start")
					Eventually(session).Should(Say("routes:"))
					Eventually(session).Should(Say(randomRouteRegexp, appName, helpers.DefaultSharedDomain()))
					Eventually(session).Should(Exit(0))
				})

				appSession := helpers.CF("app", appName)
				Eventually(appSession).Should(Say(`name:\s+%s`, appName))
				Eventually(appSession).Should(Say(`routes:\s+%s-[\w]+-[\w]+\.%s`, appName, helpers.DefaultSharedDomain()))
				Eventually(appSession).Should(Exit(0))
			})
		})

		When("the app exists and has an existing route", func() {
			It("does not generate a random route for the app", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "--no-start")
					Eventually(session).ShouldNot(Say(`\+\s+%s-[\w]+`, appName))
					Eventually(session).Should(Exit(0))
				})
			})

			When("also passed an http domain", func() {
				var domain helpers.Domain

				BeforeEach(func() {
					domain = helpers.NewDomain(organization, helpers.NewDomainName("some-domain"))
					domain.Create()
				})

				AfterEach(func() {
					domain.Delete()
				})

				It("does not create a new route with the provided domain name", func() {
					helpers.WithHelloWorldApp(func(dir string) {
						session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "-d", domain.Name, "--no-start")
						Eventually(session).ShouldNot(Say(randomRouteRegexp, appName, domain.Name))
						Eventually(session).Should(Exit(0))
					})
				})
			})
		})

		When("also passed an http domain", func() {
			var domain helpers.Domain

			BeforeEach(func() {
				domain = helpers.NewDomain(organization, helpers.NewDomainName("some-domain"))
				domain.Create()
			})

			AfterEach(func() {
				domain.Delete()
			})

			It("creates a new route with the provided domain", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--random-route", "-d", domain.Name, "--no-start")
					Eventually(session).Should(Say(randomRouteRegexp, appName, domain.Name))
					Eventually(session).Should(Exit(0))
				})
			})
		})
	})

	When("passed the random-route manifest property", func() {
		var manifest map[string]interface{}

		BeforeEach(func() {
			manifest = map[string]interface{}{
				"applications": []map[string]interface{}{
					{
						"name":         appName,
						"random-route": true,
					},
				},
			}

			helpers.WithHelloWorldApp(func(dir string) {
				helpers.WriteManifest(path.Join(dir, "manifest.yml"), manifest)
				session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--no-start")
				Eventually(session).Should(Say("routes:"))
				Eventually(session).Should(Say(randomRouteRegexp, appName, helpers.DefaultSharedDomain()))
				Eventually(session).Should(Exit(0))
			})
		})

		It("generates a random route for the app", func() {
			session := helpers.CF("app", appName)
			Eventually(session).Should(Say(`name:\s+%s`, appName))
			Eventually(session).Should(Say(`routes:\s+%s-[\w]+-[\w]+\.%s`, appName, helpers.DefaultSharedDomain()))
			Eventually(session).Should(Exit(0))
		})

		When("the app has an existing route", func() {
			It("does not generate a random route for the app", func() {
				helpers.WithHelloWorldApp(func(dir string) {
					helpers.WriteManifest(path.Join(dir, "manifest.yml"), manifest)

					session := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: dir}, PushCommandName, appName, "--no-start")
					Eventually(session).ShouldNot(Say(`\+\s+%s-[\w]+`, appName))
					Eventually(session).Should(Exit(0))
				})
			})
		})
	})
})
<|endoftext|>


<commit_before>package watchy

import (
	"sync"
)

type EventEmitter struct {
	listeners map[string][]Listener
	mu        sync.RWMutex
}

type Listener struct {
	ch   chan interface{}
	once bool
}

func New() *EventEmitter {
	return &EventEmitter{
		listeners: map[string][]Listener{},
	}
}

func (r *EventEmitter) Emit(event string, payload interface{}) {
	r.mu.Lock()
	defer r.mu.Unlock()
	for i := 0; i < len(r.listeners[event]); i++ {
		l := r.listeners[event][i]
		select {
		case l.ch <- payload:
		default:
		}
		if l.once { // remove
			r.listeners[event] = append(r.listeners[event][:i], r.listeners[event][i+1:]...)
			i--
		}
	}
}

func (r *EventEmitter) Once(event string) chan interface{} {
	r.mu.Lock()
	defer r.mu.Unlock()
	ch := make(chan interface{}, 1)

	r.listeners[event] = append(r.listeners[event], Listener{
		ch:   ch,
		once: true,
	})
	return ch
}
<commit_msg>watchy added on<commit_after>package watchy

import (
	"sync"
)

type EventEmitter struct {
	listeners map[string][]Listener
	mu        sync.RWMutex
}

type Listener struct {
	ch   chan interface{}
	once bool
}

func New() *EventEmitter {
	return &EventEmitter{
		listeners: map[string][]Listener{},
	}
}

func (r *EventEmitter) Emit(event string, payload interface{}) {
	r.mu.Lock()
	defer r.mu.Unlock()
	for i := 0; i < len(r.listeners[event]); i++ {
		l := r.listeners[event][i]
		select {
		case l.ch <- payload:
		default:
		}
		if l.once { // remove
			r.listeners[event] = append(r.listeners[event][:i], r.listeners[event][i+1:]...)
			i--
		}
	}
}

func (r *EventEmitter) Once(event string) chan interface{} {
	r.mu.Lock()
	defer r.mu.Unlock()
	ch := make(chan interface{}, 1)

	r.listeners[event] = append(r.listeners[event], Listener{
		ch:   ch,
		once: true,
	})
	return ch
}

func (r *EventEmitter) On(event string) chan interface{} {
	r.mu.Lock()
	defer r.mu.Unlock()
	ch := make(chan interface{}, 1)

	r.listeners[event] = append(r.listeners[event], Listener{
		ch:   ch,
		once: false,
	})
	return ch
}
<|endoftext|>


<commit_before>package cwriter

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"os"

	"github.com/mattn/go-isatty"
)

// NotATTY not a TeleTYpewriter error.
var NotATTY = errors.New("not a terminal")

var cuuAndEd = fmt.Sprintf("%c[%%dA%[1]c[J", 27)

// Writer is a buffered the writer that updates the terminal. The
// contents of writer will be flushed when Flush is called.
type Writer struct {
	out        io.Writer
	buf        bytes.Buffer
	lineCount  int
	fd         uintptr
	isTerminal bool
}

// New returns a new Writer with defaults.
func New(out io.Writer) *Writer {
	w := &Writer{out: out}
	if f, ok := out.(*os.File); ok {
		w.fd = f.Fd()
		w.isTerminal = isatty.IsTerminal(w.fd)
	}
	return w
}

// Flush flushes the underlying buffer.
func (w *Writer) Flush(lineCount int) (err error) {
	// some terminals interpret clear 0 lines as clear 1
	if w.lineCount > 0 {
		w.clearLines()
	}
	w.lineCount = lineCount
	_, err = w.buf.WriteTo(w.out)
	return
}

// Write appends the contents of p to the underlying buffer.
func (w *Writer) Write(p []byte) (n int, err error) {
	return w.buf.Write(p)
}

// WriteString writes string to the underlying buffer.
func (w *Writer) WriteString(s string) (n int, err error) {
	return w.buf.WriteString(s)
}

// ReadFrom reads from the provided io.Reader and writes to the
// underlying buffer.
func (w *Writer) ReadFrom(r io.Reader) (n int64, err error) {
	return w.buf.ReadFrom(r)
}

// GetWidth returns width of underlying terminal.
func (w *Writer) GetWidth() (int, error) {
	if !w.isTerminal {
		return -1, NotATTY
	}
	tw, _, err := GetSize(w.fd)
	return tw, err
}
<commit_msg>const cuuAndEd<commit_after>package cwriter

import (
	"bytes"
	"errors"
	"io"
	"os"

	"github.com/mattn/go-isatty"
)

// NotATTY not a TeleTYpewriter error.
var NotATTY = errors.New("not a terminal")

const cuuAndEd = "\x1b[%dA\x1b[J"

// Writer is a buffered the writer that updates the terminal. The
// contents of writer will be flushed when Flush is called.
type Writer struct {
	out        io.Writer
	buf        bytes.Buffer
	lineCount  int
	fd         uintptr
	isTerminal bool
}

// New returns a new Writer with defaults.
func New(out io.Writer) *Writer {
	w := &Writer{out: out}
	if f, ok := out.(*os.File); ok {
		w.fd = f.Fd()
		w.isTerminal = isatty.IsTerminal(w.fd)
	}
	return w
}

// Flush flushes the underlying buffer.
func (w *Writer) Flush(lineCount int) (err error) {
	// some terminals interpret clear 0 lines as clear 1
	if w.lineCount > 0 {
		w.clearLines()
	}
	w.lineCount = lineCount
	_, err = w.buf.WriteTo(w.out)
	return
}

// Write appends the contents of p to the underlying buffer.
func (w *Writer) Write(p []byte) (n int, err error) {
	return w.buf.Write(p)
}

// WriteString writes string to the underlying buffer.
func (w *Writer) WriteString(s string) (n int, err error) {
	return w.buf.WriteString(s)
}

// ReadFrom reads from the provided io.Reader and writes to the
// underlying buffer.
func (w *Writer) ReadFrom(r io.Reader) (n int64, err error) {
	return w.buf.ReadFrom(r)
}

// GetWidth returns width of underlying terminal.
func (w *Writer) GetWidth() (int, error) {
	if !w.isTerminal {
		return -1, NotATTY
	}
	tw, _, err := GetSize(w.fd)
	return tw, err
}
<|endoftext|>


<commit_before>// TrackBuffer accumulates ADSB messages, grouped by aircraft, and flushes out
// bundles of them.
package trackbuffer

import (
	"sort"
	"time"
	"github.com/skypies/adsb"
)

// A slice of ADSB messages that share the same IcaoId
type Track struct {
	Messages  []*adsb.CompositeMsg
}

type TrackBuffer struct {
	MaxAge      time.Duration // Flush any track with data older than this
	Tracks      map[adsb.IcaoId]*Track
}

func NewTrackBuffer() *TrackBuffer {
	tb := TrackBuffer{
		MaxAge: time.Second*30,
		Tracks: make(map[adsb.IcaoId]*Track),
	}
	return &tb
}

func (t *Track)Age() time.Duration {
	if len(t.Messages)==0 { return time.Duration(time.Hour * 24) }
	return time.Since(t.Messages[0].GeneratedTimestampUTC)
}

func (tb *TrackBuffer)AddTrack(icao adsb.IcaoId) {
	track := Track{
		Messages: []*adsb.CompositeMsg{},
	}
	tb.Tracks[icao] = &track
}

func (tb *TrackBuffer)RemoveTracks(icaos []adsb.IcaoId) []*Track{
	removed := []*Track{}
	for _,icao := range icaos {
		removed = append(removed, tb.Tracks[icao])
		delete(tb.Tracks, icao)
	}
	return removed
}

func (tb *TrackBuffer)AddMessage(m *adsb.CompositeMsg) {
	if _,exists := tb.Tracks[m.Icao24]; exists == false {
		tb.AddTrack(m.Icao24)
	}
	track := tb.Tracks[m.Icao24]
	track.Messages = append(track.Messages, m)
}

func (tb *TrackBuffer)Flush(flushFunc func ([]*adsb.CompositeMsg)) {
	toRemove := []adsb.IcaoId{}

	for id,_ := range tb.Tracks {
		if tb.Tracks[id].Age() > tb.MaxAge {
			toRemove = append(toRemove, id)
		}
	}

	for _,t := range tb.RemoveTracks(toRemove) {
		sort.Sort(adsb.CompositeMsgPtrByTimeAsc(t.Messages))
		flushFunc(t.Messages)
	}
}
<commit_msg>Use channels instead of callbacks for TrackBuffer. Kinda.<commit_after>// TrackBuffer accumulates ADSB messages, grouped by aircraft, and flushes out
// bundles of them.
package trackbuffer

import (
	"sort"
	"time"
	"github.com/skypies/adsb"
)

// A slice of ADSB messages that share the same IcaoId
type Track struct {
	Messages  []*adsb.CompositeMsg
}

type TrackBuffer struct {
	MaxAge      time.Duration // Flush any track with data older than this
	Tracks      map[adsb.IcaoId]*Track
}

func NewTrackBuffer() *TrackBuffer {
	tb := TrackBuffer{
		MaxAge: time.Second*30,
		Tracks: make(map[adsb.IcaoId]*Track),
	}
	return &tb
}

func (t *Track)Age() time.Duration {
	if len(t.Messages)==0 { return time.Duration(time.Hour * 24) }
	return time.Since(t.Messages[0].GeneratedTimestampUTC)
}

func (tb *TrackBuffer)AddTrack(icao adsb.IcaoId) {
	track := Track{
		Messages: []*adsb.CompositeMsg{},
	}
	tb.Tracks[icao] = &track
}

func (tb *TrackBuffer)RemoveTracks(icaos []adsb.IcaoId) []*Track{
	removed := []*Track{}
	for _,icao := range icaos {
		removed = append(removed, tb.Tracks[icao])
		delete(tb.Tracks, icao)
	}
	return removed
}

func (tb *TrackBuffer)AddMessage(m *adsb.CompositeMsg) {
	if _,exists := tb.Tracks[m.Icao24]; exists == false {
		tb.AddTrack(m.Icao24)
	}
	track := tb.Tracks[m.Icao24]
	track.Messages = append(track.Messages, m)
}

func (tb *TrackBuffer)Flush(flushChan chan<- []*adsb.CompositeMsg) {
	toRemove := []adsb.IcaoId{}

	for id,_ := range tb.Tracks {
		if tb.Tracks[id].Age() > tb.MaxAge {
			toRemove = append(toRemove, id)
		}
	}

	for _,t := range tb.RemoveTracks(toRemove) {
		sort.Sort(adsb.CompositeMsgPtrByTimeAsc(t.Messages))
		flushChan <- t.Messages
	}
}
<|endoftext|>


<commit_before>package activitypub

type (
	// LikedCollection is a list of every object from all of the actor's Like activities,
	// added as a side effect. The liked collection MUST be either an OrderedCollection or
	// a Collection and MAY be filtered on privileges of an authenticated user or as
	// appropriate when no authentication is given.
	LikedCollection Liked

	// Liked is a type alias for an Ordered Collection
	Liked OrderedCollection
)
<commit_msg>Added initializer function for liked<commit_after>package activitypub

type (
	// LikedCollection is a list of every object from all of the actor's Like activities,
	// added as a side effect. The liked collection MUST be either an OrderedCollection or
	// a Collection and MAY be filtered on privileges of an authenticated user or as
	// appropriate when no authentication is given.
	LikedCollection Liked

	// Liked is a type alias for an Ordered Collection
	Liked OrderedCollection
)

// LikedCollection initializes a new Outbox
func LikedNew() *Liked {
	id := ObjectID("liked")

	l := Liked{ID: id, Type: OrderedCollectionType}
	l.Name = make(NaturalLanguageValue)
	l.Content = make(NaturalLanguageValue)
	l.Summary = make(NaturalLanguageValue)

	l.TotalItems = 0

	return &l
}
// Append adds an element to an LikedCollection
func (l *LikedCollection) Append(o ObjectOrLink) error {
	l.OrderedItems = append(l.OrderedItems, o)
	l.TotalItems++
	return nil
}

func (l LikedCollection) GetID() ObjectID {
	return l.ID
}
func (l LikedCollection)GetType() ActivityVocabularyType {
	return l.Type
}
<|endoftext|>