sip.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. // CanDecode returns the set of layer types that this DecodingLayer can decode
  214. func (s *SIP) CanDecode() gopacket.LayerClass {
  215. return LayerTypeSIP
  216. }
  217. // NextLayerType returns the layer type contained by this DecodingLayer
  218. func (s *SIP) NextLayerType() gopacket.LayerType {
  219. return gopacket.LayerTypePayload
  220. }
  221. // DecodeFromBytes decodes the slice into the SIP struct.
  222. func (s *SIP) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
  223. // Init some vars for parsing follow-up
  224. var countLines int
  225. var line []byte
  226. var err error
  227. var offset int
  228. // Iterate on all lines of the SIP Headers
  229. // and stop when we reach the SDP (aka when the new line
  230. // is at index 0 of the remaining packet)
  231. buffer := bytes.NewBuffer(data)
  232. for {
  233. // Read next line
  234. line, err = buffer.ReadBytes(byte('\n'))
  235. if err != nil {
  236. if err == io.EOF {
  237. if len(bytes.Trim(line, "\r\n")) > 0 {
  238. df.SetTruncated()
  239. }
  240. break
  241. } else {
  242. return err
  243. }
  244. }
  245. offset += len(line)
  246. // Trim the new line delimiters
  247. line = bytes.Trim(line, "\r\n")
  248. // Empty line, we hit Body
  249. if len(line) == 0 {
  250. break
  251. }
  252. // First line is the SIP request/response line
  253. // Other lines are headers
  254. if countLines == 0 {
  255. err = s.ParseFirstLine(line)
  256. if err != nil {
  257. return err
  258. }
  259. } else {
  260. err = s.ParseHeader(line)
  261. if err != nil {
  262. return err
  263. }
  264. }
  265. countLines++
  266. }
  267. s.BaseLayer = BaseLayer{Contents: data[:offset], Payload: data[offset:]}
  268. return nil
  269. }
  270. // ParseFirstLine will compute the first line of a SIP packet.
  271. // The first line will tell us if it's a request or a response.
  272. //
  273. // Examples of first line of SIP Prococol :
  274. //
  275. // Request : INVITE bob@example.com SIP/2.0
  276. // Response : SIP/2.0 200 OK
  277. // Response : SIP/2.0 501 Not Implemented
  278. //
  279. func (s *SIP) ParseFirstLine(firstLine []byte) error {
  280. var err error
  281. // Splits line by space
  282. splits := strings.SplitN(string(firstLine), " ", 3)
  283. // We must have at least 3 parts
  284. if len(splits) < 3 {
  285. return fmt.Errorf("invalid first SIP line: '%s'", string(firstLine))
  286. }
  287. // Determine the SIP packet type
  288. if strings.HasPrefix(splits[0], "SIP") {
  289. // --> Response
  290. s.IsResponse = true
  291. // Validate SIP Version
  292. s.Version, err = GetSIPVersion(splits[0])
  293. if err != nil {
  294. return err
  295. }
  296. // Compute code
  297. s.ResponseCode, err = strconv.Atoi(splits[1])
  298. if err != nil {
  299. return err
  300. }
  301. // Compute status line
  302. s.ResponseStatus = splits[2]
  303. } else {
  304. // --> Request
  305. // Validate method
  306. s.Method, err = GetSIPMethod(splits[0])
  307. if err != nil {
  308. return err
  309. }
  310. s.RequestURI = splits[1]
  311. // Validate SIP Version
  312. s.Version, err = GetSIPVersion(splits[2])
  313. if err != nil {
  314. return err
  315. }
  316. }
  317. return nil
  318. }
  319. // ParseHeader will parse a SIP Header
  320. // SIP Headers are quite simple, there are colon separated name and value
  321. // Headers can be spread over multiple lines
  322. //
  323. // Examples of header :
  324. //
  325. // CSeq: 1 REGISTER
  326. // Via: SIP/2.0/UDP there.com:5060
  327. // Authorization:Digest username="UserB",
  328. // realm="MCI WorldCom SIP",
  329. // nonce="1cec4341ae6cbe5a359ea9c8e88df84f", opaque="",
  330. // uri="sip:ss2.wcom.com", response="71ba27c64bd01de719686aa4590d5824"
  331. //
  332. func (s *SIP) ParseHeader(header []byte) (err error) {
  333. // Ignore empty headers
  334. if len(header) == 0 {
  335. return
  336. }
  337. // Check if this is the following of last header
  338. // RFC 3261 - 7.3.1 - Header Field Format specify that following lines of
  339. // multiline headers must begin by SP or TAB
  340. if header[0] == '\t' || header[0] == ' ' {
  341. header = bytes.TrimSpace(header)
  342. s.Headers[s.lastHeaderParsed][len(s.Headers[s.lastHeaderParsed])-1] += fmt.Sprintf(" %s", string(header))
  343. return
  344. }
  345. // Find the ':' to separate header name and value
  346. index := bytes.Index(header, []byte(":"))
  347. if index >= 0 {
  348. headerName := strings.ToLower(string(bytes.Trim(header[:index], " ")))
  349. headerValue := string(bytes.Trim(header[index+1:], " "))
  350. // Add header to object
  351. s.Headers[headerName] = append(s.Headers[headerName], headerValue)
  352. s.lastHeaderParsed = headerName
  353. // Compute specific headers
  354. err = s.ParseSpecificHeaders(headerName, headerValue)
  355. if err != nil {
  356. return err
  357. }
  358. }
  359. return nil
  360. }
  361. // ParseSpecificHeaders will parse some specific key values from
  362. // specific headers like CSeq or Content-Length integer values
  363. func (s *SIP) ParseSpecificHeaders(headerName string, headerValue string) (err error) {
  364. switch headerName {
  365. case "cseq":
  366. // CSeq header value is formatted like that :
  367. // CSeq: 123 INVITE
  368. // We split the value to parse Cseq integer value, and method
  369. splits := strings.Split(headerValue, " ")
  370. if len(splits) > 1 {
  371. // Parse Cseq
  372. s.cseq, err = strconv.ParseInt(splits[0], 10, 64)
  373. if err != nil {
  374. return err
  375. }
  376. // Validate method
  377. if s.IsResponse {
  378. s.Method, err = GetSIPMethod(splits[1])
  379. if err != nil {
  380. return err
  381. }
  382. }
  383. }
  384. case "content-length":
  385. // Parse Content-Length
  386. s.contentLength, err = strconv.ParseInt(headerValue, 10, 64)
  387. if err != nil {
  388. return err
  389. }
  390. }
  391. return nil
  392. }
  393. // GetAllHeaders will return the full headers of the
  394. // current SIP packets in a map[string][]string
  395. func (s *SIP) GetAllHeaders() map[string][]string {
  396. return s.Headers
  397. }
  398. // GetHeader will return all the headers with
  399. // the specified name.
  400. func (s *SIP) GetHeader(headerName string) []string {
  401. headerName = strings.ToLower(headerName)
  402. h := make([]string, 0)
  403. if _, ok := s.Headers[headerName]; ok {
  404. if len(s.Headers[headerName]) > 0 {
  405. return s.Headers[headerName]
  406. } else if len(s.Headers[compactSipHeadersCorrespondance[headerName]]) > 0 {
  407. return s.Headers[compactSipHeadersCorrespondance[headerName]]
  408. }
  409. }
  410. return h
  411. }
  412. // GetFirstHeader will return the first header with
  413. // the specified name. If the current SIP packet has multiple
  414. // headers with the same name, it returns the first.
  415. func (s *SIP) GetFirstHeader(headerName string) string {
  416. headerName = strings.ToLower(headerName)
  417. if _, ok := s.Headers[headerName]; ok {
  418. if len(s.Headers[headerName]) > 0 {
  419. return s.Headers[headerName][0]
  420. } else if len(s.Headers[compactSipHeadersCorrespondance[headerName]]) > 0 {
  421. return s.Headers[compactSipHeadersCorrespondance[headerName]][0]
  422. }
  423. }
  424. return ""
  425. }
  426. //
  427. // Some handy getters for most used SIP headers
  428. //
  429. // GetAuthorization will return the Authorization
  430. // header of the current SIP packet
  431. func (s *SIP) GetAuthorization() string {
  432. return s.GetFirstHeader("Authorization")
  433. }
  434. // GetFrom will return the From
  435. // header of the current SIP packet
  436. func (s *SIP) GetFrom() string {
  437. return s.GetFirstHeader("From")
  438. }
  439. // GetTo will return the To
  440. // header of the current SIP packet
  441. func (s *SIP) GetTo() string {
  442. return s.GetFirstHeader("To")
  443. }
  444. // GetContact will return the Contact
  445. // header of the current SIP packet
  446. func (s *SIP) GetContact() string {
  447. return s.GetFirstHeader("Contact")
  448. }
  449. // GetCallID will return the Call-ID
  450. // header of the current SIP packet
  451. func (s *SIP) GetCallID() string {
  452. return s.GetFirstHeader("Call-ID")
  453. }
  454. // GetUserAgent will return the User-Agent
  455. // header of the current SIP packet
  456. func (s *SIP) GetUserAgent() string {
  457. return s.GetFirstHeader("User-Agent")
  458. }
  459. // GetContentLength will return the parsed integer
  460. // Content-Length header of the current SIP packet
  461. func (s *SIP) GetContentLength() int64 {
  462. return s.contentLength
  463. }
  464. // GetCSeq will return the parsed integer CSeq header
  465. // header of the current SIP packet
  466. func (s *SIP) GetCSeq() int64 {
  467. return s.cseq
  468. }