func upload(res http.ResponseWriter, req *http.Request) { defer logException(res, req) if req.Method == "POST" { file, _, err := req.FormFile("pic") if err != nil { log.Panic(err) } defer file.Close() wr := &manager.MongoWriter{} image, err := asciiEncoder.DecodeImage(file) if err != nil { log.Panic(err) } err = asciiEncoder.Asciify(image, wr) if err != nil { log.Panic(err) } uri := mongoArtManager.Save(wr) http.Redirect(res, req, "/art/"+uri, 302) } }
//generate signature in repeatable way func SignDeterministic(msg []byte, seckey []byte, nonce_seed []byte) []byte { nonce := SumSHA256(nonce_seed) //deterministicly generate nonce var sig []byte = make([]byte, 65) var recid C.int var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0])) var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0])) var nonce_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&nonce[0])) var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0])) if C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != C.int(1) { log.Panic("Invalid secret key") } ret := C.secp256k1_ecdsa_sign_compact( msg_ptr, C.int(len(msg)), sig_ptr, seckey_ptr, nonce_ptr, &recid) sig[64] = byte(int(recid)) if int(recid) > 4 { log.Panic() } if ret != 1 { return SignDeterministic(msg, seckey, nonce_seed) //nonce invalid,retry } return sig }
func (self *Visor) CreateGenesisBlockInit() (SignedBlock, error) { self.GenesisPreconditions() if len(self.Blockchain.Blocks) != 0 || len(self.blockSigs.Sigs) != 0 { log.Panic("Blockchain already has genesis") } if self.Config.BlockchainPubkey != cipher.PubKeyFromSecKey(self.Config.BlockchainSeckey) { log.Panicf("Cannot create genesis block. Invalid secret key for pubkey") } gb := self.Blockchain.CreateGenesisBlock(self.Config.GenesisAddress, self.Config.GenesisTimestamp, self.Config.GenesisCoinVolume) sb := self.SignBlock(gb) if err := self.verifySignedBlock(&sb); err != nil { log.Panic("Signed a fresh genesis block, but its invalid: %v", err) } self.blockSigs.record(&sb) log.Printf("New Genesis:") log.Printf("genesis_time= %v", sb.Block.Head.Time) log.Printf("genesis_address= %v", self.Config.GenesisAddress.String()) log.Printf("genesis_signature= %v", sb.Sig.Hex()) return sb, nil }
func (p *Pool) print(first bool) bool { var out string if !first { coords, err := getCursorPos() if err != nil { log.Panic(err) } coords.Y -= int16(len(p.bars)) coords.X = 0 err = setCursorPos(coords) if err != nil { log.Panic(err) } } isFinished := true for _, bar := range p.bars { if !bar.isFinish { isFinished = false } bar.Update() out += fmt.Sprintf("\r%s\n", bar.String()) } fmt.Print(out) return isFinished }
func main() { jenkins_address := os.Getenv("JENKINS_URL") listen_address := os.Getenv("LISTEN_ADDRESS") if listen_address == "" { listen_address = "[::]:8080" } if jenkins_address == "" { log.Fatalln("Use environment variables JENKINS_URL and LISTEN_ADDRESS (default \"[::]:8080\")") } remote, err := url.Parse(jenkins_address) if err != nil { log.Panic(err) } proxy := httputil.NewSingleHostReverseProxy(remote) http.HandleFunc("/", handler(proxy)) log.Println("jenkins-authentication-proxy", version, "starting") log.Println("Authentication endpoint:", planio_url) err = http.ListenAndServe(listen_address, nil) if err != nil { log.Panic(err) } }
// Loads a blockchain but subdues errors into the logger, or panics. // If no blockchain is found, it creates a new empty one func loadBlockchain(filename string, genAddr coin.Address) *coin.Blockchain { bc := &coin.Blockchain{} created := false if filename != "" { var err error bc, err = LoadBlockchain(filename) if err == nil { if len(bc.Blocks) == 0 { log.Panic("Loaded empty blockchain") } loadedGenAddr := bc.Blocks[0].Body.Transactions[0].Out[0].Address if loadedGenAddr != genAddr { log.Panic("Configured genesis address does not match the " + "address in the blockchain") } created = true } else { if os.IsNotExist(err) { logger.Info("No blockchain file, will create a new blockchain") } else { log.Panicf("Failed to load blockchain file \"%s\": %v", filename, err) } } } if !created { bc = coin.NewBlockchain() } return bc }
func main() { //log.SetLevel(log.DebugLevel) // Create a new client client := client.NewXenAPIClient("127.0.0.1", "username", "password") // Login, this will create a session that is used by all other methods err := client.Login() if err != nil { log.Panic(err) } // Fetch a list of all VMs, unfortunaly this will return templates and the domain controller as well vms, err := client.GetVMs() if err != nil { log.Panic(err) } // Loop thru all VMs for _, vm := range vms { // Fetch information about this vm. This method will also return a list with all available records vm.GetRecord() // Ignore all that is not a VM (templates and domain controller) if !vm.IsVM { continue } // Print out information about the VM fmt.Printf("%s (%s) - %s\n", vm.Name, vm.PowerState, vm.Description) } }
func initDataBase() *sql.DB { db, err := sql.Open("sqlite3", "./sites.db") if err != nil { log.Fatal(err) } defer db.Close() sqlStmt := ` DELETE FROM sites; DROP TABLE sites; ` db.Exec(sqlStmt) if err != nil { log.Panic("%q: %s\n", err, sqlStmt) os.Exit(1) } sqlStmt = ` CREATE TABLE sites (domain TEXT NOT NULL PRIMARY KEY, code INTEGER); ` _, err = db.Exec(sqlStmt) if err != nil { log.Panic("%q: %s\n", err, sqlStmt) os.Exit(1) } return db }
func make_window(w, h int, title string) func() { // Required to make sure that the OpenGL go-routine doesn't get switched // to another thread (=> kerblammo) runtime.LockOSThread() if err := glfw.Init(); err != nil { log.Panic("glfw Error:", err) } err := glfw.OpenWindow(w, h, 0, 0, 0, 0, 0, 0, glfw.Windowed) if err != nil { log.Panic("Error:", err) } if gl.Init() != 0 { log.Panic("gl error") } if *vsync { glfw.SetSwapInterval(1) } else { glfw.SetSwapInterval(0) } glfw.SetWindowTitle(title) glfw.SetWindowSizeCallback(Reshape) Init() return func() { glfw.Terminate() glfw.CloseWindow() log.Print("Cleanup") } }
//recovers the public key from the signature //recovery of pubkey means correct signature func RecoverPubkey(msg []byte, sig []byte) []byte { if len(sig) != 65 { log.Panic() } var recid int = int(sig[64]) pubkey, ret := secp.RecoverPublicKey( sig[0:64], msg, recid) if ret != 1 { log.Printf("RecoverPubkey: code %s", ret) return nil } //var pubkey2 []byte = pubkey1.Bytes() //compressed if pubkey == nil { log.Panic("ERROR: impossible, pubkey nil and ret ==1") } if len(pubkey) != 33 { log.Panic("pubkey length wrong") } return pubkey //nonce1.SetBytes(nonce_seed) }
//raise a pubkey to the power of a seckey func ECDH(pub []byte, sec []byte) []byte { if len(sec) != 32 { log.Panic() } if len(pub) != 33 { log.Panic() } if VerifySeckey(sec) != 1 { log.Printf("Invalid Seckey") } if ret := VerifyPubkey(pub); ret != 1 { log.Printf("Invalid Pubkey, %d", ret) return nil } pubkey_out := secp.Multiply(pub, sec) if pubkey_out == nil { return nil } if len(pubkey_out) != 33 { log.Panic("ERROR: impossible, invalid pubkey length") } return pubkey_out }
func RemoveFromRegistry(r *RpcService) { newServices := make([]*RpcService, 0) for _, v := range NOS.Services { if v != nil { if !v.Equal(r) { newServices = append(newServices, v) } } } NOS.Services = newServices b, err := json.Marshal(NOS) if err != nil { log.Panic(err.String()) } rev, err := DC.Rev() if err != nil { log.Panic(err.String()) } _, err = DC.Set("/servers/config/networkservers.conf", rev, b) if err != nil { log.Panic(err.String()) } }
func RemoveService(i int) { newServices := make([]*RpcService, 0) for k, v := range NOS.Services { if k != i { if v != nil { newServices = append(newServices, v) } } } NOS.Services = newServices b, err := json.Marshal(NOS) if err != nil { log.Panic(err.String()) } rev, err := DC.Rev() if err != nil { log.Panic(err.String()) } _, err = DC.Set("/servers/config/networkservers.conf", rev, b) if err != nil { log.Panic(err.String()) } }
func main() { robot := robot.NewRobot() if err := robot.Start(); err != nil { log.Panic(err) } bot, err := tgbotapi.NewBotAPI(os.Getenv("BOT_TOKEN")) if err != nil { log.Panic(err) } bot.Debug = true u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates, err := bot.GetUpdatesChan(u) if err != nil { log.Panic(err) } for update := range updates { log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) bot.Send(robot.Response(update.Message)) } }
func GetServerIP() string { ifaces, err := net.Interfaces() if err != nil { log.Panic("Can't acess the network interfaces.") } var ip net.IP for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { log.Panic("Can't read the IP.") } for _, addr := range addrs { switch v := addr.(type) { case *net.IPNet: //log.Printf("Evaluating IPNet: %v\r\n", v.IP) if (v.IP.To4() != nil) && !v.IP.IsLinkLocalUnicast() && !v.IP.IsLoopback() && !v.IP.IsMulticast() { ip = v.IP } case *net.IPAddr: //log.Printf("Evaluating IPAddr: %v\r\n", v.IP) if (v.IP.To4() != nil) && !v.IP.IsLinkLocalUnicast() && !v.IP.IsLoopback() && !v.IP.IsMulticast() { ip = v.IP } } } } // process IP address return ip.String() }
func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // output request request, err := httputil.DumpRequest(r, false) if err != nil { fmt.Println(err) } fmt.Println(string(request)) // create client to get site tr := &http.Transport{} //client := http.Client{} r.RequestURI = "" // pay attention : it is very important //response, err := client.Do(r) response, err := tr.RoundTrip(r) if err != nil { log.Panic(err, "not get response") } defer response.Body.Close() data, err := ioutil.ReadAll(response.Body) if err != nil { log.Panic(err, "not get Body") } fmt.Println("Get Body") // save Header for i, j := range response.Header { for _, k := range j { w.Header().Add(i, k) } } w.WriteHeader(response.StatusCode) w.Write(data) }
func authHandle(w http.ResponseWriter, req *http.Request) { c := strings.Count(req.URL.Path, "/") l := len(req.URL.Path) if c == 2 || (c == 3 && req.URL.Path[l-1:l] == "/" && req.URL.Path[l-2:l-1] != "/") { ss := strings.Split(req.URL.Path, "/") user := ss[2] if user == "" { w.WriteHeader(http.StatusBadRequest) } else { switch platform.PlatformGet() { case platform.Windows: if strings.Index(user, ":") != -1 { w.WriteHeader(http.StatusBadRequest) } else { path, _ := authStore.GetFile(strings.ToLower(user)) w.Write([]byte(path + "\n")) } case platform.Linux: path, _ := authStore.GetFile(user) w.Write([]byte(path + "\n")) case platform.Darwin: log.Panic("Darwin not yet supported") default: log.Panic("%v+ not yet supported", runtime.GOOS) } } } else { w.WriteHeader(http.StatusBadRequest) } }
//保存离线消息 func (storage *Storage) SaveMessage(msg *IMMessage) { _, ok := storage.files[msg.receiver] if !ok { path := storage.GetOfflinePath(msg.receiver) fmt.Println("path:", path) file, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) if err != nil { log.Panic("open file") } file_size, err := file.Seek(0, os.SEEK_END) if err != nil { log.Panic("seek file") } if file_size < HEADER_SIZE && file_size > 0 { log.Println("file header is't complete") err = file.Truncate(0) if err != nil { log.Panic("truncate file") } file_size = 0 } if file_size == 0 { storage.WriteHeader(file) } storage.files[msg.receiver] = file } storage.WriteMessage(storage.files[msg.receiver], msg) }
func (mockLive *MockLivestatus) StartMockLivestatus() { var listener net.Listener var err error switch mockLive.ConnectionType { case "tcp": listener, err = net.Listen("tcp", mockLive.LivestatusAddress) case "file": listener, err = net.Listen("unix", mockLive.LivestatusAddress) default: log.Panic("ConnectionType undefined") return } if err != nil { log.Panic(err) } isRunning := true for isRunning { conn, err := listener.Accept() if err != nil { //log.Println(err) continue } go mockLive.handle(conn) mutex.Lock() isRunning = mockLive.isRunning mutex.Unlock() } }
//decode block to bytes func Dec_block(b []byte) (SignedBlock, error) { if len(b) < 16 { log.Panic() } var dln uint64 = le_Uint64(b[0:8]) var seq uint64 = le_Uint64(b[8:16]) var chk uint64 = le_Uint64(b[16:24]) if dln != uint64(len(b)) { log.Panic("Dec_block, length check failed") } b = b[24:] //cleave off header if chk != FnvsHash(b) { log.Panic("Dec_block, checksum failed") } var sb SignedBlock err := encoder.DeserializeRaw(b, &sb) if err != nil { log.Panic("Dec_block, deserialization failed") } if seq != sb.Block.Head.BkSeq { log.Panic("Dec_block, seq mismatch") } return sb, nil }
func main() { client, err := NewClient("localhost", 4807) if err != nil { //error } // some login? header := &Header{ Path: []byte("some/path"), } log.Println(header) err = client.Write(NewBytesMessage(header, []byte("hello"))) if err != nil { log.Panic(err) } err = client.Write(NewBytesMessage(header, []byte("world!"))) if err != nil { log.Panic(err) } var msg CompleteMessage for { msg = <-client.response b := bytes.NewBuffer(msg.Body) log.Println("Response:", msg.Header, b.String()) } }
// Fast path for atomic types. func DeserializeAtomic(in []byte, data interface{}) { n := intDestSize(data) if len(in) < n { log.Panic("Not enough data to deserialize") } if n != 0 { var b [8]byte copy(b[0:n], in[0:n]) bs := b[:n] switch v := data.(type) { case *int8: *v = int8(b[0]) case *uint8: *v = b[0] case *int16: *v = int16(le_Uint16(bs)) case *uint16: *v = le_Uint16(bs) case *int32: *v = int32(le_Uint32(bs)) case *uint32: *v = le_Uint32(bs) case *int64: *v = int64(le_Uint64(bs)) case *uint64: *v = le_Uint64(bs) default: //FIX: this does not get triggered on invalid type in // pass in struct on unit test log.Panic("type not atomic") } } }
//returns nil on failure //crash rather than fail func GeneratePublicKey(k []byte) []byte { //log.Panic() if len(k) != 32 { log.Panic() } var r XYZ var n Number var pk XY //must not be zero //must not be negative //must be less than order of curve n.SetBytes(k) if n.Sign() <= 0 || n.Cmp(&TheCurve.Order.Int) >= 0 { log.Panic("only call for valid seckey, check that seckey is valid first") return nil } ECmultGen(&r, &n) pk.SetXYZ(&r) if pk.IsValid() == false { log.Panic() //should not occur } _pubkey_test(pk) return pk.Bytes() }
func main() { flagTypes := flag.String("types", "jar,src", "") flagDst := flag.String("dst", ".", "") flagRec := flag.Bool("recursive", true, "") flag.Parse() types, err := parseTypes(*flagTypes) if err != nil { log.Panic(err) } if _, err := os.Stat(*flagDst); err != nil { if err := os.MkdirAll(*flagDst, os.ModePerm); err != nil { log.Panic(err) } } var dep repo.Dep for _, arg := range flag.Args() { if err := dep.Parse(arg); err != nil { log.Panic(err) } if err := dep.Download(*flagDst, *flagRec, types); err != nil { log.Panic(err) } } }
//generates deterministic keypair with weak SHA256 hash of seed //internal use only //be extremely careful with golang slice semantics func generateDeterministicKeyPair(seed []byte) ([]byte, []byte) { if seed == nil { log.Panic() } pubkey_len := C.int(33) const seckey_len = 32 var pubkey []byte = make([]byte, pubkey_len) var seckey []byte = make([]byte, seckey_len) var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0])) var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0])) new_seckey: seed = SumSHA256(seed[0:32]) copy(seckey[0:32], seed[0:32]) if C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != 1 { goto new_seckey //rehash seckey until it succeeds, almost never happens } ret := C.secp256k1_ecdsa_pubkey_create( pubkey_ptr, &pubkey_len, seckey_ptr, 1) if ret != 1 { log.Panic("secp256k1-g0, generateDeterministicKeyPair, pubkey generation failing for valid seckey") } return pubkey, seckey }
func main() { // Load config // Create logger // Setup database dbString := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DB_USER, DB_PASSWORD, DB_NAME) db, err := sql.Open("postgres", dbString) if err != nil { log.Panic(err) } err = db.Ping() if err != nil { log.Panic(err) } defer db.Close() // Setup all repositories var repos = Repositories{&repo.UserRepository{db}} user := new(repo.User) user.Username = "******" repos.user.Save(user) }
//raise a pubkey to the power of a seckey func ECDH(pub []byte, sec []byte) []byte { if len(sec) != 32 { log.Panic() } if len(pub) != 33 { log.Panic() } if VerifyPubkey(pub) != 1 { log.Printf("Invalid Pubkey") return nil } if VerifySeckey(sec) != 1 { log.Printf("Invalid Seckey") } var pub2 []byte = make([]byte, 33) copy(pub2[0:33], pub[0:33]) var pub_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pub2[0])) var sec_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sec[0])) ret := C.secp256k1_ecdsa_pubkey_tweak_mul( pub_ptr, C.int(len(pub2)), sec_ptr, ) if ret != 1 { return nil } return pub2 }
func Encrypt3DESECB(input []byte, key []byte) []byte { if len(key) != 24 { log.Panic("Key must be 24 bytes") } block, err := des.NewTripleDESCipher(key) if err != nil { log.Panic(err) } bs := block.BlockSize() //log.Printf("Block size: %d", bs) if len(input)%bs != 0 { log.Panic("Input should be a multiple of blocksize") } //log.Printf("Input length: %d", len(input)) m := len(input) / bs //log.Printf("Going for %d cycles", m) data := []byte{} buf := make([]byte, bs) for i := 0; i < m; i++ { //log.Printf("%d: byte: %s", i, hex.EncodeToString(input[0:bs])) block.Encrypt(buf, input) input = input[bs:] data = append(data, buf...) } return data }
// RegisterTestRequest registers the HTTP request req for testing, such that // any API calls are sent to the provided URL. It returns a closure to delete // the registration. // It should only be used by aetest package. func RegisterTestRequest(req *http.Request, apiURL *url.URL, decorate func(netcontext.Context) netcontext.Context) func() { c := &context{ req: req, apiURL: apiURL, } ctxs.Lock() defer ctxs.Unlock() if _, ok := ctxs.m[req]; ok { log.Panic("req already associated with context") } if _, ok := ctxs.dec[req]; ok { log.Panic("req already associated with context") } if ctxs.dec == nil { ctxs.dec = make(map[*http.Request]func(netcontext.Context) netcontext.Context) } ctxs.m[req] = c ctxs.dec[req] = decorate return func() { ctxs.Lock() delete(ctxs.m, req) delete(ctxs.dec, req) ctxs.Unlock() } }
func main() { flag.Parse() tmpl = template.New("root").Funcs(template.FuncMap{"wrapDescription": wrapDescription}) _, err := tmpl.ParseGlob(path.Join(*templates, "*.tmpl")) if err != nil { log.Panic(err) } l := lib.NewRateLimiter(time.Second/10, 100) defer l.Stop() ln, err := net.Listen("tcp", net.JoinHostPort(*ip, *port)) if err != nil { log.Panic(err) } for { <-l.Throttle conn, err := ln.Accept() if err != nil { log.Print(err) } go handleConnection(conn) } }