1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-21 09:36:34 -05:00

format code

This commit is contained in:
V2Ray 2015-09-16 00:06:22 +02:00
parent 4c963a51ed
commit 54fe1ed8b1
10 changed files with 119 additions and 119 deletions

16
id.go
View File

@ -26,8 +26,8 @@ func NewID(id string) (ID, error) {
if err != nil { if err != nil {
return ID{}, log.Error("Failed to parse id %s", id) return ID{}, log.Error("Failed to parse id %s", id)
} }
md5hash := md5.New() md5hash := md5.New()
md5hash.Write(idBytes) md5hash.Write(idBytes)
md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")) md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21"))
cmdKey := md5.Sum(nil) cmdKey := md5.Sum(nil)
@ -58,7 +58,7 @@ func (v ID) TimeHash(timeSec int64) []byte {
} }
func (v ID) Hash(data []byte) []byte { func (v ID) Hash(data []byte) []byte {
hasher := hmac.New(md5.New, v.Bytes) hasher := hmac.New(md5.New, v.Bytes)
hasher.Write(data) hasher.Write(data)
return hasher.Sum(nil) return hasher.Sum(nil)
} }
@ -68,8 +68,8 @@ func (v ID) CmdKey() []byte {
} }
func TimestampHash(timeSec int64) []byte { func TimestampHash(timeSec int64) []byte {
md5hash := md5.New() md5hash := md5.New()
buffer := []byte{ buffer := []byte{
byte(timeSec >> 56), byte(timeSec >> 56),
byte(timeSec >> 48), byte(timeSec >> 48),
byte(timeSec >> 40), byte(timeSec >> 40),
@ -80,9 +80,9 @@ func TimestampHash(timeSec int64) []byte {
byte(timeSec), byte(timeSec),
} }
md5hash.Write(buffer) md5hash.Write(buffer)
md5hash.Write(buffer) md5hash.Write(buffer)
md5hash.Write(buffer) md5hash.Write(buffer)
md5hash.Write(buffer) md5hash.Write(buffer)
return md5hash.Sum(nil) return md5hash.Sum(nil)
} }

View File

@ -57,7 +57,7 @@ func ReadAuthentication(reader io.Reader) (auth Socks5AuthenticationRequest, err
return return
} }
if nBytes - 2 != int(auth.nMethods) { if nBytes-2 != int(auth.nMethods) {
err = fmt.Errorf("Unmatching number of auth methods, expecting %d, but got %d", auth.nMethods, nBytes) err = fmt.Errorf("Unmatching number of auth methods, expecting %d, but got %d", auth.nMethods, nBytes)
return return
} }
@ -78,7 +78,7 @@ func NewAuthenticationResponse(authMethod byte) *Socks5AuthenticationResponse {
} }
func (r *Socks5AuthenticationResponse) ToBytes() []byte { func (r *Socks5AuthenticationResponse) ToBytes() []byte {
return []byte{r.version, r.authMethod} return []byte{r.version, r.authMethod}
} }
func WriteAuthentication(writer io.Writer, response *Socks5AuthenticationResponse) error { func WriteAuthentication(writer io.Writer, response *Socks5AuthenticationResponse) error {
@ -87,54 +87,54 @@ func WriteAuthentication(writer io.Writer, response *Socks5AuthenticationRespons
} }
type Socks5UserPassRequest struct { type Socks5UserPassRequest struct {
version byte version byte
username string username string
password string password string
} }
func (request Socks5UserPassRequest) IsValid(username string, password string) bool { func (request Socks5UserPassRequest) IsValid(username string, password string) bool {
return request.username == username && request.password == password return request.username == username && request.password == password
} }
func ReadUserPassRequest(reader io.Reader) (request Socks5UserPassRequest, err error) { func ReadUserPassRequest(reader io.Reader) (request Socks5UserPassRequest, err error) {
buffer := make([]byte, 256) buffer := make([]byte, 256)
_, err = reader.Read(buffer[0:2]) _, err = reader.Read(buffer[0:2])
if err != nil { if err != nil {
return return
} }
request.version = buffer[0] request.version = buffer[0]
nUsername := buffer[1] nUsername := buffer[1]
nBytes, err := reader.Read(buffer[:nUsername]) nBytes, err := reader.Read(buffer[:nUsername])
if err != nil { if err != nil {
return return
} }
request.username = string(buffer[:nBytes]) request.username = string(buffer[:nBytes])
_, err = reader.Read(buffer[0:1]) _, err = reader.Read(buffer[0:1])
if err != nil { if err != nil {
return return
} }
nPassword := buffer[0] nPassword := buffer[0]
nBytes, err = reader.Read(buffer[:nPassword]) nBytes, err = reader.Read(buffer[:nPassword])
if err != nil { if err != nil {
return return
} }
request.password = string(buffer[:nBytes]) request.password = string(buffer[:nBytes])
return return
} }
type Socks5UserPassResponse struct { type Socks5UserPassResponse struct {
version byte version byte
status byte status byte
} }
func NewSocks5UserPassResponse(status byte) Socks5UserPassResponse { func NewSocks5UserPassResponse(status byte) Socks5UserPassResponse {
return Socks5UserPassResponse{socksVersion, status} return Socks5UserPassResponse{socksVersion, status}
} }
func WriteUserPassResponse(writer io.Writer, response Socks5UserPassResponse) error { func WriteUserPassResponse(writer io.Writer, response Socks5UserPassResponse) error {
_, err := writer.Write([]byte{response.version, response.status}) _, err := writer.Write([]byte{response.version, response.status})
return err return err
} }
const ( const (

View File

@ -65,8 +65,8 @@ func (r *VMessRequestReader) Read(reader io.Reader) (*VMessRequest, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
log.Debug("Read user hash: %v", buffer[:nBytes]) log.Debug("Read user hash: %v", buffer[:nBytes])
userId, timeSec, valid := r.vUserSet.GetUser(buffer[:nBytes]) userId, timeSec, valid := r.vUserSet.GetUser(buffer[:nBytes])
if !valid { if !valid {
@ -187,9 +187,9 @@ func NewVMessRequestWriter() *VMessRequestWriter {
func (w *VMessRequestWriter) Write(writer io.Writer, request *VMessRequest) error { func (w *VMessRequestWriter) Write(writer io.Writer, request *VMessRequest) error {
buffer := make([]byte, 0, 300) buffer := make([]byte, 0, 300)
userHash, timeSec := request.UserId.TimeRangeHash(30) userHash, timeSec := request.UserId.TimeRangeHash(30)
log.Debug("Writing userhash: %v", userHash) log.Debug("Writing userhash: %v", userHash)
buffer = append(buffer, userHash...) buffer = append(buffer, userHash...)
encryptionBegin := len(buffer) encryptionBegin := len(buffer)

View File

@ -13,7 +13,7 @@ import (
) )
func TestVMessSerialization(t *testing.T) { func TestVMessSerialization(t *testing.T) {
t.Skip(); t.Skip()
assert := unit.Assert(t) assert := unit.Assert(t)
userId, err := core.NewID("2b2966ac-16aa-4fbf-8d81-c5f172a3da51") userId, err := core.NewID("2b2966ac-16aa-4fbf-8d81-c5f172a3da51")

View File

@ -1,9 +1,9 @@
package socks package socks
import ( import (
"bufio" "bufio"
"errors" "errors"
"io" "io"
"net" "net"
"strconv" "strconv"
@ -16,7 +16,7 @@ import (
var ( var (
ErrorAuthenticationFailed = errors.New("None of the authentication methods is allowed.") ErrorAuthenticationFailed = errors.New("None of the authentication methods is allowed.")
ErrorCommandNotSupported = errors.New("Client requested an unsupported command.") ErrorCommandNotSupported = errors.New("Client requested an unsupported command.")
ErrorInvalidUser = errors.New("Invalid username or password.") ErrorInvalidUser = errors.New("Invalid username or password.")
) )
// SocksServer is a SOCKS 5 proxy server // SocksServer is a SOCKS 5 proxy server
@ -63,8 +63,8 @@ func (server *SocksServer) AcceptConnections(listener net.Listener) error {
func (server *SocksServer) HandleConnection(connection net.Conn) error { func (server *SocksServer) HandleConnection(connection net.Conn) error {
defer connection.Close() defer connection.Close()
reader := bufio.NewReader(connection) reader := bufio.NewReader(connection)
auth, err := socksio.ReadAuthentication(reader) auth, err := socksio.ReadAuthentication(reader)
if err != nil { if err != nil {
@ -87,23 +87,23 @@ func (server *SocksServer) HandleConnection(connection net.Conn) error {
authResponse := socksio.NewAuthenticationResponse(expectedAuthMethod) authResponse := socksio.NewAuthenticationResponse(expectedAuthMethod)
socksio.WriteAuthentication(connection, authResponse) socksio.WriteAuthentication(connection, authResponse)
if server.config.AuthMethod == JsonAuthMethodUserPass { if server.config.AuthMethod == JsonAuthMethodUserPass {
upRequest, err := socksio.ReadUserPassRequest(reader) upRequest, err := socksio.ReadUserPassRequest(reader)
if err != nil { if err != nil {
log.Error("Failed to read username and password: %v", err) log.Error("Failed to read username and password: %v", err)
return err return err
} }
status := byte(0) status := byte(0)
if ! upRequest.IsValid(server.config.Username, server.config.Password) { if !upRequest.IsValid(server.config.Username, server.config.Password) {
status = byte(0xFF) status = byte(0xFF)
} }
upResponse := socksio.NewSocks5UserPassResponse(status) upResponse := socksio.NewSocks5UserPassResponse(status)
socksio.WriteUserPassResponse(connection, upResponse) socksio.WriteUserPassResponse(connection, upResponse)
if status != byte(0) { if status != byte(0) {
return ErrorInvalidUser return ErrorInvalidUser
} }
} }
request, err := socksio.ReadRequest(reader) request, err := socksio.ReadRequest(reader)
if err != nil { if err != nil {

View File

@ -2,7 +2,7 @@ package vmess
import ( import (
"encoding/json" "encoding/json"
"net" "net"
"github.com/v2ray/v2ray-core" "github.com/v2ray/v2ray-core"
"github.com/v2ray/v2ray-core/log" "github.com/v2ray/v2ray-core/log"
@ -44,10 +44,10 @@ func (config VNextConfig) ToVNextServer() VNextServer {
} }
users = append(users, vuser) users = append(users, vuser)
} }
ip := net.ParseIP(config.Address) ip := net.ParseIP(config.Address)
if ip == nil { if ip == nil {
panic(log.Error("Unable to parse VNext IP: %s", config.Address)) panic(log.Error("Unable to parse VNext IP: %s", config.Address))
} }
return VNextServer{ return VNextServer{
v2net.IPAddress(ip, config.Port), v2net.IPAddress(ip, config.Port),
users} users}

View File

@ -55,7 +55,7 @@ func (handler *VMessInboundHandler) HandleConnection(connection net.Conn) error
request, err := reader.Read(connection) request, err := reader.Read(connection)
if err != nil { if err != nil {
log.Debug("Failed to parse VMess request: %v", err) log.Debug("Failed to parse VMess request: %v", err)
return err return err
} }
log.Debug("Received request for %s", request.Address.String()) log.Debug("Received request for %s", request.Address.String())

View File

@ -66,24 +66,24 @@ func (handler *VMessOutboundHandler) Start(ray core.OutboundRay) error {
} }
func startCommunicate(request *vmessio.VMessRequest, dest v2net.Address, ray core.OutboundRay) error { func startCommunicate(request *vmessio.VMessRequest, dest v2net.Address, ray core.OutboundRay) error {
input := ray.OutboundInput() input := ray.OutboundInput()
output := ray.OutboundOutput() output := ray.OutboundOutput()
conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{dest.IP, int(dest.Port), ""}) conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{dest.IP, int(dest.Port), ""})
log.Debug("VMessOutbound dialing tcp: %s", dest.String()) log.Debug("VMessOutbound dialing tcp: %s", dest.String())
if err != nil { if err != nil {
log.Error("Failed to open tcp (%s): %v", dest.String(), err) log.Error("Failed to open tcp (%s): %v", dest.String(), err)
close(output) close(output)
return err return err
} }
defer conn.Close() defer conn.Close()
defer close(output) defer close(output)
requestFinish := make(chan bool) requestFinish := make(chan bool)
responseFinish := make(chan bool) responseFinish := make(chan bool)
go handleRequest(conn, request, input, requestFinish) go handleRequest(conn, request, input, requestFinish)
go handleResponse(conn, request, output, responseFinish) go handleResponse(conn, request, output, responseFinish)
<-requestFinish <-requestFinish
conn.CloseWrite() conn.CloseWrite()
@ -92,27 +92,27 @@ func startCommunicate(request *vmessio.VMessRequest, dest v2net.Address, ray cor
} }
func handleRequest(conn *net.TCPConn, request *vmessio.VMessRequest, input <-chan []byte, finish chan<- bool) error { func handleRequest(conn *net.TCPConn, request *vmessio.VMessRequest, input <-chan []byte, finish chan<- bool) error {
defer close(finish) defer close(finish)
requestWriter := vmessio.NewVMessRequestWriter() requestWriter := vmessio.NewVMessRequestWriter()
err := requestWriter.Write(conn, request) err := requestWriter.Write(conn, request)
if err != nil { if err != nil {
log.Error("Failed to write VMess request: %v", err) log.Error("Failed to write VMess request: %v", err)
return err return err
} }
encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn) encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn)
if err != nil { if err != nil {
log.Error("Failed to create encrypt writer: %v", err) log.Error("Failed to create encrypt writer: %v", err)
return err return err
} }
v2net.ChanToWriter(encryptRequestWriter, input) v2net.ChanToWriter(encryptRequestWriter, input)
return nil return nil
} }
func handleResponse(conn *net.TCPConn, request *vmessio.VMessRequest, output chan<- []byte, finish chan<- bool) error { func handleResponse(conn *net.TCPConn, request *vmessio.VMessRequest, output chan<- []byte, finish chan<- bool) error {
defer close(finish) defer close(finish)
responseKey := md5.Sum(request.RequestKey[:]) responseKey := md5.Sum(request.RequestKey[:])
responseIV := md5.Sum(request.RequestIV[:]) responseIV := md5.Sum(request.RequestIV[:])
response := vmessio.VMessResponse{} response := vmessio.VMessResponse{}
@ -129,9 +129,9 @@ func handleResponse(conn *net.TCPConn, request *vmessio.VMessRequest, output cha
log.Error("Failed to create decrypt reader: %v", err) log.Error("Failed to create decrypt reader: %v", err)
return err return err
} }
v2net.ReaderToChan(output, decryptResponseReader) v2net.ReaderToChan(output, decryptResponseReader)
return nil return nil
} }
type VMessOutboundHandlerFactory struct { type VMessOutboundHandlerFactory struct {

View File

@ -16,22 +16,22 @@ import (
var ( var (
configFile = flag.String("config", "", "Config file for this Point server.") configFile = flag.String("config", "", "Config file for this Point server.")
logLevel = flag.String("loglevel", "", "Level of log info to be printed to console, available value: debug, info, warning, error") logLevel = flag.String("loglevel", "", "Level of log info to be printed to console, available value: debug, info, warning, error")
) )
func main() { func main() {
flag.Parse() flag.Parse()
switch *logLevel { switch *logLevel {
case "debug": case "debug":
log.SetLogLevel(log.DebugLevel) log.SetLogLevel(log.DebugLevel)
case "info": case "info":
log.SetLogLevel(log.InfoLevel) log.SetLogLevel(log.InfoLevel)
case "warning": case "warning":
log.SetLogLevel(log.WarningLevel) log.SetLogLevel(log.WarningLevel)
case "error": case "error":
log.SetLogLevel(log.ErrorLevel) log.SetLogLevel(log.ErrorLevel)
} }
if configFile == nil || len(*configFile) == 0 { if configFile == nil || len(*configFile) == 0 {
panic(log.Error("Config file is not set.")) panic(log.Error("Config file is not set."))

View File

@ -20,8 +20,8 @@ type TimedUserSet struct {
} }
type indexTimePair struct { type indexTimePair struct {
index int index int
timeSec int64 timeSec int64
} }
type hashEntry struct { type hashEntry struct {
@ -47,8 +47,8 @@ func (us *TimedUserSet) updateUserHash(tick <-chan time.Time) {
for { for {
now := <-tick now := <-tick
nowSec := now.UTC().Unix() nowSec := now.UTC().Unix()
remove2Sec := nowSec - cacheDurationSec remove2Sec := nowSec - cacheDurationSec
if remove2Sec > lastSec2Remove { if remove2Sec > lastSec2Remove {
for lastSec2Remove+1 < remove2Sec { for lastSec2Remove+1 < remove2Sec {
entry := <-hash2Remove entry := <-hash2Remove
@ -56,15 +56,15 @@ func (us *TimedUserSet) updateUserHash(tick <-chan time.Time) {
delete(us.userHashes, entry.hash) delete(us.userHashes, entry.hash)
} }
} }
for lastSec < nowSec + cacheDurationSec { for lastSec < nowSec+cacheDurationSec {
for idx, id := range us.validUserIds { for idx, id := range us.validUserIds {
idHash := id.TimeHash(lastSec) idHash := id.TimeHash(lastSec)
hash2Remove <- hashEntry{string(idHash), lastSec} hash2Remove <- hashEntry{string(idHash), lastSec}
us.userHashes[string(idHash)] = indexTimePair{idx, lastSec} us.userHashes[string(idHash)] = indexTimePair{idx, lastSec}
} }
lastSec ++ lastSec++
} }
} }
} }