msg.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package goStrongswanVici
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "fmt"
  7. "io"
  8. "strconv"
  9. )
  10. type segmentType byte
  11. const (
  12. stCMD_REQUEST segmentType = 0
  13. stCMD_RESPONSE = 1
  14. stCMD_UNKNOWN = 2
  15. stEVENT_REGISTER = 3
  16. stEVENT_UNREGISTER = 4
  17. stEVENT_CONFIRM = 5
  18. stEVENT_UNKNOWN = 6
  19. stEVENT = 7
  20. )
  21. func (t segmentType) hasName() bool {
  22. switch t {
  23. case stCMD_REQUEST, stEVENT_REGISTER, stEVENT_UNREGISTER, stEVENT:
  24. return true
  25. }
  26. return false
  27. }
  28. func (t segmentType) isValid() bool {
  29. switch t {
  30. case stCMD_REQUEST, stCMD_RESPONSE, stCMD_UNKNOWN, stEVENT_REGISTER,
  31. stEVENT_UNREGISTER, stEVENT_CONFIRM, stEVENT_UNKNOWN, stEVENT:
  32. return true
  33. }
  34. return false
  35. }
  36. func (t segmentType) hasMsg() bool {
  37. switch t {
  38. case stCMD_REQUEST, stCMD_RESPONSE, stEVENT:
  39. return true
  40. }
  41. return false
  42. }
  43. type elementType byte
  44. const (
  45. etSECTION_START elementType = 1
  46. etSECTION_END = 2
  47. etKEY_VALUE = 3
  48. etLIST_START = 4
  49. etLIST_ITEM = 5
  50. etLIST_END = 6
  51. )
  52. type segment struct {
  53. typ segmentType
  54. name string
  55. msg map[string]interface{}
  56. }
  57. //msg 在内部以下列3种类型表示(降低复杂度)
  58. // string
  59. // map[string]interface{}
  60. // []string
  61. func writeSegment(w io.Writer, msg segment) (err error) {
  62. if !msg.typ.isValid() {
  63. return fmt.Errorf("[writeSegment] msg.typ %d not defined", msg.typ)
  64. }
  65. buf := &bytes.Buffer{}
  66. buf.WriteByte(byte(msg.typ))
  67. //name
  68. if msg.typ.hasName() {
  69. err = writeString1(buf, msg.name)
  70. if err != nil {
  71. fmt.Printf("error returned from writeString1i \n")
  72. return
  73. }
  74. }
  75. if msg.typ.hasMsg() {
  76. err = writeMap(buf, msg.msg)
  77. if err != nil {
  78. fmt.Printf("error retruned from writeMap \n")
  79. return
  80. }
  81. }
  82. //写长度
  83. err = binary.Write(w, binary.BigEndian, uint32(buf.Len()))
  84. if err != nil {
  85. fmt.Printf("[writeSegment] error writing to binary \n")
  86. return
  87. }
  88. _, err = buf.WriteTo(w)
  89. if err != nil {
  90. fmt.Printf("[writeSegment] error writing to buffer \n")
  91. return
  92. }
  93. return nil
  94. }
  95. func readSegment(inR io.Reader) (msg segment, err error) {
  96. //长度
  97. var length uint32
  98. err = binary.Read(inR, binary.BigEndian, &length)
  99. if err != nil {
  100. return
  101. }
  102. r := bufio.NewReader(&io.LimitedReader{
  103. R: inR,
  104. N: int64(length),
  105. })
  106. //类型
  107. c, err := r.ReadByte()
  108. if err != nil {
  109. return
  110. }
  111. msg.typ = segmentType(c)
  112. if !msg.typ.isValid() {
  113. return msg, fmt.Errorf("[readSegment] msg.typ %d not defined", msg.typ)
  114. }
  115. if msg.typ.hasName() {
  116. msg.name, err = readString1(r)
  117. if err != nil {
  118. return
  119. }
  120. }
  121. if msg.typ.hasMsg() {
  122. msg.msg, err = readMap(r, true)
  123. if err != nil {
  124. return
  125. }
  126. }
  127. return
  128. }
  129. //一个字节长度的字符串
  130. func writeString1(w *bytes.Buffer, s string) (err error) {
  131. length := len(s)
  132. if length > 255 {
  133. return fmt.Errorf("[writeString1] length>255")
  134. }
  135. w.WriteByte(byte(length))
  136. w.WriteString(s)
  137. return
  138. }
  139. func readString1(r *bufio.Reader) (s string, err error) {
  140. length, err := r.ReadByte()
  141. if err != nil {
  142. return
  143. }
  144. buf := make([]byte, length)
  145. _, err = io.ReadFull(r, buf)
  146. if err != nil {
  147. return
  148. }
  149. return string(buf), nil
  150. }
  151. //两个字节长度的字符串
  152. func writeString2(w *bytes.Buffer, s string) (err error) {
  153. length := len(s)
  154. if length > 65535 {
  155. return fmt.Errorf("[writeString2] length>65535")
  156. }
  157. binary.Write(w, binary.BigEndian, uint16(length))
  158. w.WriteString(s)
  159. return
  160. }
  161. func readString2(r io.Reader) (s string, err error) {
  162. var length uint16
  163. err = binary.Read(r, binary.BigEndian, &length)
  164. if err != nil {
  165. return
  166. }
  167. buf := make([]byte, length)
  168. _, err = io.ReadFull(r, buf)
  169. if err != nil {
  170. return
  171. }
  172. return string(buf), nil
  173. }
  174. func writeKeyMap(w *bytes.Buffer, name string, msg map[string]interface{}) (err error) {
  175. w.WriteByte(byte(etSECTION_START))
  176. err = writeString1(w, name)
  177. if err != nil {
  178. return
  179. }
  180. writeMap(w, msg)
  181. w.WriteByte(byte(etSECTION_END))
  182. return nil
  183. }
  184. func writeKeyList(w *bytes.Buffer, name string, msg []string) (err error) {
  185. w.WriteByte(byte(etLIST_START))
  186. err = writeString1(w, name)
  187. if err != nil {
  188. return
  189. }
  190. for _, s := range msg {
  191. w.WriteByte(byte(etLIST_ITEM))
  192. err = writeString2(w, s)
  193. if err != nil {
  194. return
  195. }
  196. }
  197. w.WriteByte(byte(etLIST_END))
  198. return nil
  199. }
  200. func writeKeyString(w *bytes.Buffer, name string, msg string) (err error) {
  201. w.WriteByte(byte(etKEY_VALUE))
  202. err = writeString1(w, name)
  203. if err != nil {
  204. return
  205. }
  206. err = writeString2(w, msg)
  207. return
  208. }
  209. func writeMap(w *bytes.Buffer, msg map[string]interface{}) (err error) {
  210. for k, v := range msg {
  211. switch t := v.(type) {
  212. case map[string]interface{}:
  213. writeKeyMap(w, k, t)
  214. case []string:
  215. writeKeyList(w, k, t)
  216. case string:
  217. writeKeyString(w, k, t)
  218. case []interface{}:
  219. str := make([]string, len(t))
  220. for i := range t {
  221. str[i] = t[i].(string)
  222. }
  223. writeKeyList(w, k, str)
  224. default:
  225. return fmt.Errorf("[writeMap] can not write type %T right now", msg)
  226. }
  227. }
  228. return nil
  229. }
  230. //SECTION_START has been read already.
  231. func readKeyMap(r *bufio.Reader) (key string, msg map[string]interface{}, err error) {
  232. key, err = readString1(r)
  233. if err != nil {
  234. return
  235. }
  236. msg, err = readMap(r, false)
  237. return
  238. }
  239. //LIST_START has been read already.
  240. func readKeyList(r *bufio.Reader) (key string, msg []string, err error) {
  241. key, err = readString1(r)
  242. if err != nil {
  243. return
  244. }
  245. msg = []string{}
  246. for {
  247. var c byte
  248. c, err = r.ReadByte()
  249. if err != nil {
  250. return
  251. }
  252. switch elementType(c) {
  253. case etLIST_ITEM:
  254. value, err := readString2(r)
  255. if err != nil {
  256. return "", nil, err
  257. }
  258. msg = append(msg, value)
  259. case etLIST_END: //end of outer list
  260. return key, msg, nil
  261. default:
  262. return "", nil, fmt.Errorf("[readKeyList] protocol error 2")
  263. }
  264. }
  265. return
  266. }
  267. //KEY_VALUE has been read already.
  268. func readKeyString(r *bufio.Reader) (key string, msg string, err error) {
  269. key, err = readString1(r)
  270. if err != nil {
  271. return
  272. }
  273. msg, err = readString2(r)
  274. if err != nil {
  275. return
  276. }
  277. return
  278. }
  279. // Since the original key chosen can have duplicates,
  280. // this function is used to map the original key to a new one
  281. // to make them unique.
  282. func getNewKeyToHandleDuplicates(key string, msg map[string]interface{}) string {
  283. if _, ok := msg[key]; !ok {
  284. return key
  285. }
  286. for i := 0; ; i++ {
  287. newKey := key + "##" + strconv.Itoa(i)
  288. if _, ok := msg[newKey]; !ok {
  289. return newKey
  290. }
  291. }
  292. }
  293. //SECTION_START has been read already.
  294. func readMap(r *bufio.Reader, isRoot bool) (msg map[string]interface{}, err error) {
  295. msg = map[string]interface{}{}
  296. for {
  297. c, err := r.ReadByte()
  298. if err == io.EOF && isRoot { //may be root section
  299. return msg, nil
  300. }
  301. if err != nil {
  302. return nil, err
  303. }
  304. switch elementType(c) {
  305. case etSECTION_START:
  306. key, value, err := readKeyMap(r)
  307. if err != nil {
  308. return nil, err
  309. }
  310. msg[getNewKeyToHandleDuplicates(key, msg)] = value
  311. case etLIST_START:
  312. key, value, err := readKeyList(r)
  313. if err != nil {
  314. return nil, err
  315. }
  316. msg[getNewKeyToHandleDuplicates(key, msg)] = value
  317. case etKEY_VALUE:
  318. key, value, err := readKeyString(r)
  319. if err != nil {
  320. return nil, err
  321. }
  322. msg[getNewKeyToHandleDuplicates(key, msg)] = value
  323. case etSECTION_END: //end of outer section
  324. return msg, nil
  325. default:
  326. panic(fmt.Errorf("[readMap] protocol error 1, %d %#v", c, msg))
  327. //return nil, fmt.Errorf("[readMap] protocol error 1, %d",c)
  328. }
  329. }
  330. return
  331. }