func (e *Elm327) Init() bool { logger.Log("Initializing ELM327 on " + e.Serial.SerialPort) e.Type = "ELM327" e.Desc = "Not connected" e.Serial.SetBaud(9600) ok := e.Serial.Init() if !ok { logger.Log("Could not open ELM327 device") return false } e.Serial.SetPromptChar(62) // > var resp []string fmt.Println("Clearing buffers") //e.Serial.ReadLn() // Clear buffer fmt.Println("Sending Reset") resp, _ = e.SendCmd("ATI") e.Type = resp[0] fmt.Println("Turning off echo") e.SendCmd("ATE0") e.SendCmd("ATH0") vin := e.GetVIN() if len(vin) > 0 { fmt.Println("got vin: ", vin) e.Desc = "VIN: " + vin e.Year = obd.GetYearFromVIN(vin) e.Make = obd.GetMakeFromVIN(vin) e.VehicleAttributes = obd.GetModelFromVIN(vin) } e.GetProto() e.SendCmd("ATH1") e.SendCmd("ATR0") // Turn off responses return true }
func haxTransmitHandler(w http.ResponseWriter, r *http.Request) { logger.Log("Transmit Packet") auth_err := checkAuth(w, r) if auth_err != nil { return } vars := mux.Vars(r) canId, canId_err := strconv.Atoi(vars["id"]) if canId_err != nil { http.Error(w, canId_err.Error(), http.StatusNotFound) return } dev, dev_err := core.GetDeviceById(canId) if dev_err != nil { http.Error(w, dev_err.Error(), http.StatusNotFound) return } session, _ := store.Get(r, "canibus") userName := session.Values["user"].(string) user, _ := core.GetUserByName(userName) hax := dev.GetHackSession() if hax == nil { http.Error(w, "Session not configured", http.StatusNotFound) return } if !hax.IsActiveUser(user) { http.Error(w, "You are not a part of this hacksession", http.StatusNotFound) return } jsonTx := r.FormValue("tx") var TxPkts []api.TransmitPacket jerr := json.Unmarshal([]byte(jsonTx), &TxPkts) if jerr != nil { logger.Log("Transmit unmarshal error on: " + jsonTx) http.Error(w, jerr.Error(), http.StatusNotFound) return } for i := range TxPkts { inject_err := hax.InjectPacket(user, TxPkts[i]) if inject_err != nil { logger.Log("Transmit packet error: " + inject_err.Error()) http.Error(w, inject_err.Error(), http.StatusNotFound) return } } fmt.Fprintf(w, "%s", "OK") }
func haxStopHandler(w http.ResponseWriter, r *http.Request) { logger.Log("Stop Sniffer") auth_err := checkAuth(w, r) if auth_err != nil { return } vars := mux.Vars(r) canId, canId_err := strconv.Atoi(vars["id"]) if canId_err != nil { http.Error(w, canId_err.Error(), http.StatusNotFound) return } dev, dev_err := core.GetDeviceById(canId) if dev_err != nil { http.Error(w, dev_err.Error(), http.StatusNotFound) return } session, _ := store.Get(r, "canibus") userName := session.Values["user"].(string) user, _ := core.GetUserByName(userName) hax := dev.GetHackSession() if hax == nil { http.Error(w, "Session not configured", http.StatusNotFound) return } if !hax.IsActiveUser(user) { http.Error(w, "You are not a part of this hacksession", http.StatusNotFound) return } dev.StopSniffing() fmt.Fprintf(w, "%s", "OK") }
func (e *Elm327) Writeln(line string) { line = line + "\r" err := e.Serial.Write([]byte(line)) if err != nil { logger.Log("Could not write to ELM327") } }
func StartSPAWebListener(root string, ip string, port string) error { web_root = root r := mux.NewRouter() r.HandleFunc("/", homeHandler) r.HandleFunc("/login", loginHandler) r.HandleFunc("/logout", logoutHandler) r.HandleFunc("/partials/lobby.html", partialLobbyHandler) r.HandleFunc("/candevice/{id}/config", configCanHandler) r.HandleFunc("/candevice/{id}/join", joinHaxHandler) r.HandleFunc("/candevice/{id}/info", candeviceInfoHandler) r.HandleFunc("/hax/{id}/packets", haxPacketsHandler) r.HandleFunc("/hax/{id}/start", haxStartHandler) r.HandleFunc("/hax/{id}/stop", haxStopHandler) r.HandleFunc("/hax/{id}/transmit", haxTransmitHandler) r.HandleFunc("/candevices", candevicesHandler) r.HandleFunc("/lobby/AddSimulator", addSimHandler) http.Handle("/partials/", http.FileServer(http.Dir(root))) http.Handle("/js/", http.FileServer(http.Dir(root))) http.Handle("/css/", http.FileServer(http.Dir(root))) http.Handle("/fonts/", http.FileServer(http.Dir(root))) http.Handle("/images/", http.FileServer(http.Dir(root))) http.Handle("/bootstrap/", http.FileServer(http.Dir(root))) http.Handle("/", r) remote := ip + ":" + port logger.Log("Starting CANiBUS Web server on " + remote) err := http.ListenAndServe(remote, nil) if err != nil { return logger.Err("Could not bind web to port: " + err.Error()) } return nil }
func candevicesHandler(w http.ResponseWriter, r *http.Request) { config := core.GetConfig() drivers := config.GetDrivers() var data []CanDeviceJSON for i := range drivers { dev := CanDeviceJSON{} dev.Id = drivers[i].GetId() dev.DeviceType = drivers[i].DeviceType() dev.DeviceDesc = drivers[i].DeviceDesc() hax := drivers[i].GetHackSession() if hax == nil { dev.HackSession = "Idle" } else { dev.HackSession = hax.GetState() } dev.Year = drivers[i].GetYear() dev.Make = drivers[i].GetMake() dev.Model = drivers[i].GetModel() data = append(data, dev) } j, err := json.Marshal(data) if err != nil { logger.Log("Could not convert candevices to json") return } fmt.Fprintf(w, "%s", j) }
// ProcessCommand processes client commands from the network socket func (c *Client) ProcessCommand(cmd string) { //fmt.Println("DEBUG: process cmd: ", cmd) aCmd, err := c.ProcessIncoming(cmd) if err != nil { fmt.Println(err) return } switch aCmd.Action { case "Login": c.ProcessLogin(aCmd) case "": logger.Log("Invalid Cmd request") return default: logger.Log("Unkown action:" + aCmd.Action) } }
// StartListener starts a listening socket on a given port and IP func StartListener(ip string, port string) error { serverInit() remote := ip + ":" + port logger.Log("Starting CANiBUS Server on " + remote) ln, err := net.Listen("tcp", remote) if err != nil { return logger.Err("Could not bind to port: " + err.Error()) } logger.Log("Server started") defer ln.Close() for { conn, err := ln.Accept() if err != nil { fmt.Println(err) continue } go handleConnection(conn) } return nil }
func partialLobbyHandler(w http.ResponseWriter, r *http.Request) { logger.Log("Lobby checking auth...") auth_err := checkAuth(w, r) if auth_err != nil { return } p, err := loadPage("partials/lobby.html") if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } fmt.Fprintf(w, "%s", p.Body) }
func (mcp *GoodThopter) Init() bool { c := &serial.Config{Name: "/dev/ttyUSB0", Baud: 115200} c.Name = mcp.SerialPort s, err := serial.OpenPort(c) if err != nil { logger.Log("Could not init GoodThopter") return false } mcp.Serial = s // setRTS(1) // setDTR(1) // setDTR(0) mcp.readCmd() if mcp.Verb != 0x7f { logger.Log("TODO: didn't get proper verb. retry") return false } // infostring() // monitorclocking() // mon_connected() return true }
func loginHandler(w http.ResponseWriter, r *http.Request) { user := r.FormValue("username") logger.Log("User logged in: " + user) cmd := &api.Cmd{} cmd.Action = "Login" cmd.Arg = make([]string, 1) cmd.Arg[0] = user err := api.ProcessLogin(cmd) if err != nil { http.Redirect(w, r, "/", http.StatusFound) return } session, _ := store.Get(r, "canibus") session.Values["user"] = user session.Save(r, w) logger.Log("Cookie saved") var NewUser canibususer.CanibusUser NewUser.SetName(user) core.AddUser(&NewUser) fmt.Fprintf(w, "OK") //http.Redirect(w, r, "/#/lobby", http.StatusFound) }
// ProcessOutgoing formats API to client request output syntax func (c *Client) ProcessOutgoing(apiStruct interface{}) { var outgoing string switch c.Lang { case LANG_JSON: x, err := json.Marshal(apiStruct) if err != nil { logger.Log("Could not create JSON server message") return } outgoing = string(x) default: x, err := xml.Marshal(apiStruct) if err != nil { logger.Log("Could not create XML server message") return } outgoing = string(x) } if outgoing != "" { c.Outgoing <- outgoing + "\n" } }
func (c *Config) LoadConfig(conf string) { if len(conf) == 0 { logger.Log("No config file given") return } cfile, err := os.Open(conf) if err != nil { logger.Log("Could not open config file") return } var elem []ConfigElement dec := json.NewDecoder(cfile) for { err = dec.Decode(&elem) if err != nil && err != io.EOF { fmt.Println("Error:", err) logger.Log("Could not decode config element") } else { if err == io.EOF { break } for i := range elem { if elem[i].DeviceType == "simulator" { dev := &candevice.Simulator{} dev.SetPacketFile(elem[i].DeviceFile) c.AppendDriver(dev) } else if elem[i].DeviceType == "elm327" { dev := &candevice.Elm327{} dev.SetSerial(elem[i].DeviceSerial) c.AppendDriver(dev) } else { fmt.Printf("Unknown config setting: %+v\n", elem[i]) } } } } cfile.Close() }
// ProcessLogin assumes Arg0 = Name func (c *Client) ProcessLogin(cmd *api.Cmd) { switch len(cmd.Arg) { case 1: if cmd.Arg[0] == "" { c.sendError("Login", "Invalid Name") return } c.Name = cmd.Arg[0] // Do we want to make this uniq? c.State = STATE_LOBBY logger.Log(c.Name + " logged in") default: c.sendError("Login", "Wrong number of arguments needed to login") } }
func handleConnection(conn net.Conn) { logger.Log(fmt.Sprintf("Incoming Connection from %s", conn.RemoteAddr())) buffer := make([]byte, 1024) bytesRead, error := conn.Read(buffer) if error != nil { logger.Log(fmt.Sprintf("Error reading data: %s", error)) Close(conn) return } newClient := &Client{} nudge := string(buffer[0:bytesRead]) switch strings.TrimSpace(nudge) { case "lang:xml": newClient.Lang = LANG_XML case "lang:json": newClient.Lang = LANG_JSON default: logger.Log("Invalid nudge string") Close(conn) return } // Valid nugde string GData.LastId += 1 newClient.Id = GData.LastId newClient.Incoming = make(chan string) newClient.Outgoing = make(chan string) newClient.Conn = conn newClient.Quit = make(chan bool) go ClientWriter(newClient) go ClientReader(newClient) GData.ClientList.PushBack(*newClient) go HandleIncoming() newClient.ProcessOutgoing(api.ServerVersion) }
func addSimHandler(w http.ResponseWriter, r *http.Request) { config := core.GetConfig() dev := &candevice.Simulator{} newId := config.AppendDriver(dev) data := CanDeviceJSON{} data.Id = newId data.DeviceType = dev.DeviceType() data.HackSession = "Idle" j, err := json.Marshal(data) if err != nil { logger.Log("Could not convert candevices to json") return } fmt.Fprintf(w, "%s", j) }
func StartWebListener(root string, ip string, port string) error { web_root = root http.HandleFunc("/", rootHandler) http.HandleFunc("/login", loginHandler) http.HandleFunc("/logout", logoutHandler) http.HandleFunc("/lobby", lobbyHandler) http.HandleFunc("/config", configHandler) http.HandleFunc("/hacksession", hacksessionHandler) //http.Handle("/chatLobby", websocket.Handler(chatLobbyHandler)) remote := ip + ":" + port logger.Log("Starting CANiBUS Web server on " + remote) err := http.ListenAndServe(remote, nil) if err != nil { return logger.Err("Could not bind web to port: " + err.Error()) } return nil }
func haxPacketsHandler(w http.ResponseWriter, r *http.Request) { auth_err := checkAuth(w, r) if auth_err != nil { return } vars := mux.Vars(r) canId, canId_err := strconv.Atoi(vars["id"]) if canId_err != nil { http.Error(w, canId_err.Error(), http.StatusNotFound) return } dev, dev_err := core.GetDeviceById(canId) if dev_err != nil { http.Error(w, dev_err.Error(), http.StatusNotFound) return } session, _ := store.Get(r, "canibus") userName := session.Values["user"].(string) user, _ := core.GetUserByName(userName) hax := dev.GetHackSession() if hax == nil { http.Error(w, "Session not configured", http.StatusNotFound) return } if !hax.IsActiveUser(user) { http.Error(w, "You are not a part of this hacksession", http.StatusNotFound) return } packets := hax.GetPackets(user) j, err := json.Marshal(packets) if err != nil { logger.Log("Could not convert can packets to json") return } fmt.Fprintf(w, "%s", j) }
func candeviceInfoHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) canId, canId_err := strconv.Atoi(vars["id"]) if canId_err != nil { http.Error(w, canId_err.Error(), http.StatusNotFound) return } dev, dev_err := core.GetDeviceById(canId) if dev_err != nil { http.Error(w, dev_err.Error(), http.StatusNotFound) return } data := CanDeviceJSON{} data.Id = dev.GetId() data.DeviceType = dev.DeviceType() data.DeviceDesc = dev.DeviceDesc() j, err := json.Marshal(data) if err != nil { logger.Log("Could not convert candevices to json") return } fmt.Fprintf(w, "%s", j) }
func configCanHandler(w http.ResponseWriter, r *http.Request) { logger.Log("Config CAN Device, checking auth...") auth_err := checkAuth(w, r) if auth_err != nil { return } vars := mux.Vars(r) canId, canId_err := strconv.Atoi(vars["id"]) if canId_err != nil { http.Error(w, canId_err.Error(), http.StatusNotFound) return } dev, dev_err := core.GetDeviceById(canId) if dev_err != nil { http.Error(w, dev_err.Error(), http.StatusNotFound) return } session, _ := store.Get(r, "canibus") userName := session.Values["user"].(string) user, _ := core.GetUserByName(userName) if dev.GetHackSession() == nil { hacks := hacksession.HackSession{} hacks.SetState(hacksession.STATE_CONFIG) hacks.SetDevice(dev) user.SetDeviceId(dev.GetId()) dev.SetHackSession(&hacks) hacks.AddUser(user) } p, err := loadPage("partials/config.html") if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } fmt.Fprintf(w, "%s", p.Body) }
func Close(conn net.Conn) { logger.Log(fmt.Sprintf("%s closed connection", conn.RemoteAddr())) conn.Close() }