accounts.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package command
  2. import (
  3. "io"
  4. "time"
  5. v2net "github.com/v2ray/v2ray-core/common/net"
  6. "github.com/v2ray/v2ray-core/common/serial"
  7. "github.com/v2ray/v2ray-core/common/uuid"
  8. "github.com/v2ray/v2ray-core/transport"
  9. )
  10. func init() {
  11. RegisterResponseCommand(1, func() Command { return new(SwitchAccount) })
  12. }
  13. // Structure
  14. // 1 byte: host len N
  15. // N bytes: host
  16. // 2 bytes: port
  17. // 16 bytes: uuid
  18. // 2 bytes: alterid
  19. // 8 bytes: time
  20. type SwitchAccount struct {
  21. Host v2net.Address
  22. Port v2net.Port
  23. ID *uuid.UUID
  24. AlterIds serial.Uint16Literal
  25. ValidUntil time.Time
  26. }
  27. func (this *SwitchAccount) Marshal(writer io.Writer) (int, error) {
  28. outBytes := 0
  29. hostStr := ""
  30. if this.Host != nil {
  31. hostStr = this.Host.String()
  32. }
  33. writer.Write([]byte{byte(len(hostStr))})
  34. outBytes++
  35. if len(hostStr) > 0 {
  36. writer.Write([]byte(hostStr))
  37. outBytes += len(hostStr)
  38. }
  39. writer.Write(this.Port.Bytes())
  40. outBytes += 2
  41. idBytes := this.ID.Bytes()
  42. writer.Write(idBytes)
  43. outBytes += len(idBytes)
  44. writer.Write(this.AlterIds.Bytes())
  45. outBytes += 2
  46. timestamp := this.ValidUntil.Unix()
  47. timeBytes := serial.Int64Literal(timestamp).Bytes()
  48. writer.Write(timeBytes)
  49. outBytes += len(timeBytes)
  50. return outBytes, nil
  51. }
  52. func (this *SwitchAccount) Unmarshal(data []byte) error {
  53. lenHost := int(data[0])
  54. if len(data) < lenHost+1 {
  55. return transport.CorruptedPacket
  56. }
  57. this.Host = v2net.ParseAddress(string(data[1 : 1+lenHost]))
  58. portStart := 1 + lenHost
  59. if len(data) < portStart+2 {
  60. return transport.CorruptedPacket
  61. }
  62. this.Port = v2net.PortFromBytes(data[portStart : portStart+2])
  63. idStart := portStart + 2
  64. if len(data) < idStart+16 {
  65. return transport.CorruptedPacket
  66. }
  67. this.ID, _ = uuid.ParseBytes(data[idStart : idStart+16])
  68. alterIdStart := idStart + 16
  69. if len(data) < alterIdStart+2 {
  70. return transport.CorruptedPacket
  71. }
  72. this.AlterIds = serial.ParseUint16(data[alterIdStart : alterIdStart+2])
  73. timeStart := alterIdStart + 2
  74. if len(data) < timeStart+8 {
  75. return transport.CorruptedPacket
  76. }
  77. this.ValidUntil = time.Unix(serial.BytesLiteral(data[timeStart:timeStart+8]).Int64Value(), 0)
  78. return nil
  79. }