sip.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. // Copyright 2017 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. package layers
  7. import (
  8. "bytes"
  9. "fmt"
  10. "io"
  11. "strconv"
  12. "strings"
  13. "github.com/google/gopacket"
  14. )
  15. // SIPVersion defines the different versions of the SIP Protocol
  16. type SIPVersion uint8
  17. // Represents all the versions of SIP protocol
  18. const (
  19. SIPVersion1 SIPVersion = 1
  20. SIPVersion2 SIPVersion = 2
  21. )
  22. func (sv SIPVersion) String() string {
  23. switch sv {
  24. default:
  25. // Defaulting to SIP/2.0
  26. return "SIP/2.0"
  27. case SIPVersion1:
  28. return "SIP/1.0"
  29. case SIPVersion2:
  30. return "SIP/2.0"
  31. }
  32. }
  33. // GetSIPVersion is used to get SIP version constant
  34. func GetSIPVersion(version string) (SIPVersion, error) {
  35. switch strings.ToUpper(version) {
  36. case "SIP/1.0":
  37. return SIPVersion1, nil
  38. case "SIP/2.0":
  39. return SIPVersion2, nil
  40. default:
  41. return 0, fmt.Errorf("Unknown SIP version: '%s'", version)
  42. }
  43. }
  44. // SIPMethod defines the different methods of the SIP Protocol
  45. // defined in the different RFC's
  46. type SIPMethod uint16
  47. // Here are all the SIP methods
  48. const (
  49. SIPMethodInvite SIPMethod = 1 // INVITE [RFC3261]
  50. SIPMethodAck SIPMethod = 2 // ACK [RFC3261]
  51. SIPMethodBye SIPMethod = 3 // BYE [RFC3261]
  52. SIPMethodCancel SIPMethod = 4 // CANCEL [RFC3261]
  53. SIPMethodOptions SIPMethod = 5 // OPTIONS [RFC3261]
  54. SIPMethodRegister SIPMethod = 6 // REGISTER [RFC3261]
  55. SIPMethodPrack SIPMethod = 7 // PRACK [RFC3262]
  56. SIPMethodSubscribe SIPMethod = 8 // SUBSCRIBE [RFC6665]
  57. SIPMethodNotify SIPMethod = 9 // NOTIFY [RFC6665]
  58. SIPMethodPublish SIPMethod = 10 // PUBLISH [RFC3903]
  59. SIPMethodInfo SIPMethod = 11 // INFO [RFC6086]
  60. SIPMethodRefer SIPMethod = 12 // REFER [RFC3515]
  61. SIPMethodMessage SIPMethod = 13 // MESSAGE [RFC3428]
  62. SIPMethodUpdate SIPMethod = 14 // UPDATE [RFC3311]
  63. SIPMethodPing SIPMethod = 15 // PING [https://tools.ietf.org/html/draft-fwmiller-ping-03]
  64. )
  65. func (sm SIPMethod) String() string {
  66. switch sm {
  67. default:
  68. return "Unknown method"
  69. case SIPMethodInvite:
  70. return "INVITE"
  71. case SIPMethodAck:
  72. return "ACK"
  73. case SIPMethodBye:
  74. return "BYE"
  75. case SIPMethodCancel:
  76. return "CANCEL"
  77. case SIPMethodOptions:
  78. return "OPTIONS"
  79. case SIPMethodRegister:
  80. return "REGISTER"
  81. case SIPMethodPrack:
  82. return "PRACK"
  83. case SIPMethodSubscribe:
  84. return "SUBSCRIBE"
  85. case SIPMethodNotify:
  86. return "NOTIFY"
  87. case SIPMethodPublish:
  88. return "PUBLISH"
  89. case SIPMethodInfo:
  90. return "INFO"
  91. case SIPMethodRefer:
  92. return "REFER"
  93. case SIPMethodMessage:
  94. return "MESSAGE"
  95. case SIPMethodUpdate:
  96. return "UPDATE"
  97. case SIPMethodPing:
  98. return "PING"
  99. }
  100. }
  101. // GetSIPMethod returns the constant of a SIP method
  102. // from its string
  103. func GetSIPMethod(method string) (SIPMethod, error) {
  104. switch strings.ToUpper(method) {
  105. case "INVITE":
  106. return SIPMethodInvite, nil
  107. case "ACK":
  108. return SIPMethodAck, nil
  109. case "BYE":
  110. return SIPMethodBye, nil
  111. case "CANCEL":
  112. return SIPMethodCancel, nil
  113. case "OPTIONS":
  114. return SIPMethodOptions, nil
  115. case "REGISTER":
  116. return SIPMethodRegister, nil
  117. case "PRACK":
  118. return SIPMethodPrack, nil
  119. case "SUBSCRIBE":
  120. return SIPMethodSubscribe, nil
  121. case "NOTIFY":
  122. return SIPMethodNotify, nil
  123. case "PUBLISH":
  124. return SIPMethodPublish, nil
  125. case "INFO":
  126. return SIPMethodInfo, nil
  127. case "REFER":
  128. return SIPMethodRefer, nil
  129. case "MESSAGE":
  130. return SIPMethodMessage, nil
  131. case "UPDATE":
  132. return SIPMethodUpdate, nil
  133. case "PING":
  134. return SIPMethodPing, nil
  135. default:
  136. return 0, fmt.Errorf("Unknown SIP method: '%s'", method)
  137. }
  138. }
  139. // Here is a correspondance between long header names and short
  140. // as defined in rfc3261 in section 20
  141. var compactSipHeadersCorrespondance = map[string]string{
  142. "accept-contact": "a",
  143. "allow-events": "u",
  144. "call-id": "i",
  145. "contact": "m",
  146. "content-encoding": "e",
  147. "content-length": "l",
  148. "content-type": "c",
  149. "event": "o",
  150. "from": "f",
  151. "identity": "y",
  152. "refer-to": "r",
  153. "referred-by": "b",
  154. "reject-contact": "j",
  155. "request-disposition": "d",
  156. "session-expires": "x",
  157. "subject": "s",
  158. "supported": "k",
  159. "to": "t",
  160. "via": "v",
  161. }
  162. // SIP object will contains information about decoded SIP packet.
  163. // -> The SIP Version
  164. // -> The SIP Headers (in a map[string][]string because of multiple headers with the same name
  165. // -> The SIP Method
  166. // -> The SIP Response code (if it's a response)
  167. // -> The SIP Status line (if it's a response)
  168. // You can easily know the type of the packet with the IsResponse boolean
  169. //
  170. type SIP struct {
  171. BaseLayer
  172. // Base information
  173. Version SIPVersion
  174. Method SIPMethod
  175. Headers map[string][]string
  176. // Request
  177. RequestURI string
  178. // Response
  179. IsResponse bool
  180. ResponseCode int
  181. ResponseStatus string
  182. // Private fields
  183. cseq int64
  184. contentLength int64
  185. lastHeaderParsed string
  186. }
  187. // decodeSIP decodes the byte slice into a SIP type. It also
  188. // setups the application Layer in PacketBuilder.
  189. func decodeSIP(data []byte, p gopacket.PacketBuilder) error {
  190. s := NewSIP()
  191. err := s.DecodeFromBytes(data, p)
  192. if err != nil {
  193. return err
  194. }
  195. p.AddLayer(s)
  196. p.SetApplicationLayer(s)
  197. return nil
  198. }
  199. // NewSIP instantiates a new empty SIP object
  200. func NewSIP() *SIP {
  201. s := new(SIP)
  202. s.Headers = make(map[string][]string)
  203. return s
  204. }
  205. // LayerType returns gopacket.LayerTypeSIP.
  206. func (s *SIP) LayerType() gopacket.LayerType {
  207. return LayerTypeSIP
  208. }
  209. // Payload returns the base layer payload
  210. func (s *SIP) Payload() []byte {
  211. return s.BaseLayer.Payload
  212. }
  213. // DecodeFromBytes decodes the slice into the SIP struct.
  214. func (s *SIP) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
  215. // Init some vars for parsing follow-up
  216. var countLines int
  217. var line []byte
  218. var err error
  219. // Clean leading new line
  220. data = bytes.Trim(data, "\n")
  221. // Iterate on all lines of the SIP Headers
  222. // and stop when we reach the SDP (aka when the new line
  223. // is at index 0 of the remaining packet)
  224. buffer := bytes.NewBuffer(data)
  225. for {
  226. // Read next line
  227. line, err = buffer.ReadBytes(byte('\n'))
  228. if err != nil {
  229. if err == io.EOF {
  230. break
  231. } else {
  232. return err
  233. }
  234. }
  235. // Trim the new line delimiters
  236. line = bytes.Trim(line, "\r\n")
  237. // Empty line, we hit Body
  238. // Putting packet remain in Paypload
  239. if len(line) == 0 {
  240. s.BaseLayer.Payload = buffer.Bytes()
  241. break
  242. }
  243. // First line is the SIP request/response line
  244. // Other lines are headers
  245. if countLines == 0 {
  246. err = s.ParseFirstLine(line)
  247. if err != nil {
  248. return err
  249. }
  250. } else {
  251. err = s.ParseHeader(line)
  252. if err != nil {
  253. return err
  254. }
  255. }
  256. countLines++
  257. }
  258. return nil
  259. }
  260. // ParseFirstLine will compute the first line of a SIP packet.
  261. // The first line will tell us if it's a request or a response.
  262. //
  263. // Examples of first line of SIP Prococol :
  264. //
  265. // Request : INVITE bob@example.com SIP/2.0
  266. // Response : SIP/2.0 200 OK
  267. // Response : SIP/2.0 501 Not Implemented
  268. //
  269. func (s *SIP) ParseFirstLine(firstLine []byte) error {
  270. var err error
  271. // Splits line by space
  272. splits := strings.SplitN(string(firstLine), " ", 3)
  273. // We must have at least 3 parts
  274. if len(splits) < 3 {
  275. return fmt.Errorf("invalid first SIP line: '%s'", string(firstLine))
  276. }
  277. // Determine the SIP packet type
  278. if strings.HasPrefix(splits[0], "SIP") {
  279. // --> Response
  280. s.IsResponse = true
  281. // Validate SIP Version
  282. s.Version, err = GetSIPVersion(splits[0])
  283. if err != nil {
  284. return err
  285. }
  286. // Compute code
  287. s.ResponseCode, err = strconv.Atoi(splits[1])
  288. if err != nil {
  289. return err
  290. }
  291. // Compute status line
  292. s.ResponseStatus = splits[2]
  293. } else {
  294. // --> Request
  295. // Validate method
  296. s.Method, err = GetSIPMethod(splits[0])
  297. if err != nil {
  298. return err
  299. }
  300. s.RequestURI = splits[1]
  301. // Validate SIP Version
  302. s.Version, err = GetSIPVersion(splits[2])
  303. if err != nil {
  304. return err
  305. }
  306. }
  307. return nil
  308. }
  309. // ParseHeader will parse a SIP Header
  310. // SIP Headers are quite simple, there are colon separated name and value
  311. // Headers can be spread over multiple lines
  312. //
  313. // Examples of header :
  314. //
  315. // CSeq: 1 REGISTER
  316. // Via: SIP/2.0/UDP there.com:5060
  317. // Authorization:Digest username="UserB",
  318. // realm="MCI WorldCom SIP",
  319. // nonce="1cec4341ae6cbe5a359ea9c8e88df84f", opaque="",
  320. // uri="sip:ss2.wcom.com", response="71ba27c64bd01de719686aa4590d5824"
  321. //
  322. func (s *SIP) ParseHeader(header []byte) (err error) {
  323. // Ignore empty headers
  324. if len(header) == 0 {
  325. return
  326. }
  327. // Check if this is the following of last header
  328. // RFC 3261 - 7.3.1 - Header Field Format specify that following lines of
  329. // multiline headers must begin by SP or TAB
  330. if header[0] == '\t' || header[0] == ' ' {
  331. header = bytes.TrimSpace(header)
  332. s.Headers[s.lastHeaderParsed][len(s.Headers[s.lastHeaderParsed])-1] += fmt.Sprintf(" %s", string(header))
  333. return
  334. }
  335. // Find the ':' to separate header name and value
  336. index := bytes.Index(header, []byte(":"))
  337. if index >= 0 {
  338. headerName := strings.ToLower(string(bytes.Trim(header[:index], " ")))
  339. headerValue := string(bytes.Trim(header[index+1:], " "))
  340. // Add header to object
  341. s.Headers[headerName] = append(s.Headers[headerName], headerValue)
  342. s.lastHeaderParsed = headerName
  343. // Compute specific headers
  344. err = s.ParseSpecificHeaders(headerName, headerValue)
  345. if err != nil {
  346. return err
  347. }
  348. }
  349. return nil
  350. }
  351. // ParseSpecificHeaders will parse some specific key values from
  352. // specific headers like CSeq or Content-Length integer values
  353. func (s *SIP) ParseSpecificHeaders(headerName string, headerValue string) (err error) {
  354. switch headerName {
  355. case "cseq":
  356. // CSeq header value is formatted like that :
  357. // CSeq: 123 INVITE
  358. // We split the value to parse Cseq integer value, and method
  359. splits := strings.Split(headerValue, " ")
  360. if len(splits) > 1 {
  361. // Parse Cseq
  362. s.cseq, err = strconv.ParseInt(splits[0], 10, 64)
  363. if err != nil {
  364. return err
  365. }
  366. // Validate method
  367. if s.IsResponse {
  368. s.Method, err = GetSIPMethod(splits[1])
  369. if err != nil {
  370. return err
  371. }
  372. }
  373. }
  374. case "content-length":
  375. // Parse Content-Length
  376. s.contentLength, err = strconv.ParseInt(headerValue, 10, 64)
  377. if err != nil {
  378. return err
  379. }
  380. }
  381. return nil
  382. }
  383. // GetAllHeaders will return the full headers of the
  384. // current SIP packets in a map[string][]string
  385. func (s *SIP) GetAllHeaders() map[string][]string {
  386. return s.Headers
  387. }
  388. // GetHeader will return all the headers with
  389. // the specified name.
  390. func (s *SIP) GetHeader(headerName string) []string {
  391. headerName = strings.ToLower(headerName)
  392. h := make([]string, 0)
  393. if _, ok := s.Headers[headerName]; ok {
  394. if len(s.Headers[headerName]) > 0 {
  395. return s.Headers[headerName]
  396. } else if len(s.Headers[compactSipHeadersCorrespondance[headerName]]) > 0 {
  397. return s.Headers[compactSipHeadersCorrespondance[headerName]]
  398. }
  399. }
  400. return h
  401. }
  402. // GetFirstHeader will return the first header with
  403. // the specified name. If the current SIP packet has multiple
  404. // headers with the same name, it returns the first.
  405. func (s *SIP) GetFirstHeader(headerName string) string {
  406. headerName = strings.ToLower(headerName)
  407. if _, ok := s.Headers[headerName]; ok {
  408. if len(s.Headers[headerName]) > 0 {
  409. return s.Headers[headerName][0]
  410. } else if len(s.Headers[compactSipHeadersCorrespondance[headerName]]) > 0 {
  411. return s.Headers[compactSipHeadersCorrespondance[headerName]][0]
  412. }
  413. }
  414. return ""
  415. }
  416. //
  417. // Some handy getters for most used SIP headers
  418. //
  419. // GetAuthorization will return the Authorization
  420. // header of the current SIP packet
  421. func (s *SIP) GetAuthorization() string {
  422. return s.GetFirstHeader("Authorization")
  423. }
  424. // GetFrom will return the From
  425. // header of the current SIP packet
  426. func (s *SIP) GetFrom() string {
  427. return s.GetFirstHeader("From")
  428. }
  429. // GetTo will return the To
  430. // header of the current SIP packet
  431. func (s *SIP) GetTo() string {
  432. return s.GetFirstHeader("To")
  433. }
  434. // GetContact will return the Contact
  435. // header of the current SIP packet
  436. func (s *SIP) GetContact() string {
  437. return s.GetFirstHeader("Contact")
  438. }
  439. // GetCallID will return the Call-ID
  440. // header of the current SIP packet
  441. func (s *SIP) GetCallID() string {
  442. return s.GetFirstHeader("Call-ID")
  443. }
  444. // GetUserAgent will return the User-Agent
  445. // header of the current SIP packet
  446. func (s *SIP) GetUserAgent() string {
  447. return s.GetFirstHeader("User-Agent")
  448. }
  449. // GetContentLength will return the parsed integer
  450. // Content-Length header of the current SIP packet
  451. func (s *SIP) GetContentLength() int64 {
  452. return s.contentLength
  453. }
  454. // GetCSeq will return the parsed integer CSeq header
  455. // header of the current SIP packet
  456. func (s *SIP) GetCSeq() int64 {
  457. return s.cseq
  458. }