sip_to_pjsip.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. #!/usr/bin/python
  2. import optparse
  3. import astdicts
  4. import astconfigparser
  5. import socket
  6. import re
  7. PREFIX = 'pjsip_'
  8. ###############################################################################
  9. ### some utility functions
  10. ###############################################################################
  11. def section_by_type(section, pjsip, type):
  12. """Finds a section based upon the given type, adding it if not found."""
  13. def __find_dict(mdicts, key, val):
  14. """Given a list of mult-dicts, return the multi-dict that contains
  15. the given key/value pair."""
  16. def found(d):
  17. return key in d and val in d[key]
  18. try:
  19. return [d for d in mdicts if found(d)][0]
  20. except IndexError:
  21. raise LookupError("Dictionary not located for key = %s, value = %s"
  22. % (key, val))
  23. try:
  24. return __find_dict(pjsip.section(section), 'type', type)
  25. except LookupError:
  26. # section for type doesn't exist, so add
  27. sect = pjsip.add_section(section)
  28. sect['type'] = type
  29. return sect
  30. def set_value(key=None, val=None, section=None, pjsip=None,
  31. nmapped=None, type='endpoint'):
  32. """Sets the key to the value within the section in pjsip.conf"""
  33. def _set_value(k, v, s, r, n):
  34. set_value(key if key else k, v, s, r, n, type)
  35. # if no value or section return the set_value
  36. # function with the enclosed key and type
  37. if not val and not section:
  38. return _set_value
  39. # otherwise try to set the value
  40. section_by_type(section, pjsip, type)[key] = \
  41. val[0] if isinstance(val, list) else val
  42. def merge_value(key=None, val=None, section=None, pjsip=None,
  43. nmapped=None, type='endpoint', section_to=None):
  44. """Merge values from the given section with those from the default."""
  45. def _merge_value(k, v, s, r, n):
  46. merge_value(key if key else k, v, s, r, n, type, section_to)
  47. # if no value or section return the merge_value
  48. # function with the enclosed key and type
  49. if not val and not section:
  50. return _merge_value
  51. # should return a single value section list
  52. try:
  53. sect = sip.section(section)[0]
  54. except LookupError:
  55. sect = sip.default(section)[0]
  56. # for each merged value add it to pjsip.conf
  57. for i in sect.get_merged(key):
  58. set_value(key, i, section_to if section_to else section,
  59. pjsip, nmapped, type)
  60. def non_mapped(nmapped):
  61. """Write non-mapped sip.conf values to the non-mapped object"""
  62. def _non_mapped(section, key, val):
  63. """Writes a non-mapped value from sip.conf to the non-mapped object."""
  64. if section not in nmapped:
  65. nmapped[section] = astconfigparser.Section()
  66. if isinstance(val, list):
  67. for v in val:
  68. # since coming from sip.conf we can assume
  69. # single section lists
  70. nmapped[section][0][key] = v
  71. else:
  72. nmapped[section][0][key] = val
  73. return _non_mapped
  74. ###############################################################################
  75. ### mapping functions -
  76. ### define f(key, val, section) where key/val are the key/value pair to
  77. ### write to given section in pjsip.conf
  78. ###############################################################################
  79. def set_dtmfmode(key, val, section, pjsip, nmapped):
  80. """
  81. Sets the dtmfmode value. If value matches allowable option in pjsip
  82. then map it, otherwise set it to none.
  83. """
  84. key = 'dtmf_mode'
  85. # available pjsip.conf values: rfc4733, inband, info, none
  86. if val == 'inband' or val == 'info':
  87. set_value(key, val, section, pjsip, nmapped)
  88. elif val == 'rfc2833':
  89. set_value(key, 'rfc4733', section, pjsip, nmapped)
  90. else:
  91. nmapped(section, key, val + " ; did not fully map - set to none")
  92. set_value(key, 'none', section, pjsip, nmapped)
  93. def from_nat(key, val, section, pjsip, nmapped):
  94. """Sets values from nat into the appropriate pjsip.conf options."""
  95. # nat from sip.conf can be comma separated list of values:
  96. # yes/no, [auto_]force_rport, [auto_]comedia
  97. if 'yes' in val:
  98. set_value('rtp_symmetric', 'yes', section, pjsip, nmapped)
  99. set_value('rewrite_contact', 'yes', section, pjsip, nmapped)
  100. if 'comedia' in val:
  101. set_value('rtp_symmetric', 'yes', section, pjsip, nmapped)
  102. if 'force_rport' in val:
  103. set_value('force_rport', 'yes', section, pjsip, nmapped)
  104. set_value('rewrite_contact', 'yes', section, pjsip, nmapped)
  105. def set_timers(key, val, section, pjsip, nmapped):
  106. """
  107. Sets the timers in pjsip.conf from the session-timers option
  108. found in sip.conf.
  109. """
  110. # pjsip.conf values can be yes/no, required, always
  111. if val == 'originate':
  112. set_value('timers', 'always', section, pjsip, nmapped)
  113. elif val == 'accept':
  114. set_value('timers', 'required', section, pjsip, nmapped)
  115. elif val == 'never':
  116. set_value('timers', 'no', section, pjsip, nmapped)
  117. else:
  118. set_value('timers', 'yes', section, pjsip, nmapped)
  119. def set_direct_media(key, val, section, pjsip, nmapped):
  120. """
  121. Maps values from the sip.conf comma separated direct_media option
  122. into pjsip.conf direct_media options.
  123. """
  124. if 'yes' in val:
  125. set_value('direct_media', 'yes', section, pjsip, nmapped)
  126. if 'update' in val:
  127. set_value('direct_media_method', 'update', section, pjsip, nmapped)
  128. if 'outgoing' in val:
  129. set_value('directed_media_glare_mitigation', 'outgoing', section,
  130. pjsip, nmapped)
  131. if 'nonat' in val:
  132. set_value('disable_directed_media_on_nat', 'yes', section, pjsip,
  133. nmapped)
  134. if 'no' in val:
  135. set_value('direct_media', 'no', section, pjsip, nmapped)
  136. def from_sendrpid(key, val, section, pjsip, nmapped):
  137. """Sets the send_rpid/pai values in pjsip.conf."""
  138. if val == 'yes' or val == 'rpid':
  139. set_value('send_rpid', 'yes', section, pjsip, nmapped)
  140. elif val == 'pai':
  141. set_value('send_pai', 'yes', section, pjsip, nmapped)
  142. def set_media_encryption(key, val, section, pjsip, nmapped):
  143. """Sets the media_encryption value in pjsip.conf"""
  144. try:
  145. dtls = sip.get(section, 'dtlsenable')[0]
  146. if dtls == 'yes':
  147. # If DTLS is enabled, then that overrides SDES encryption.
  148. return
  149. except LookupError:
  150. pass
  151. if val == 'yes':
  152. set_value('media_encryption', 'sdes', section, pjsip, nmapped)
  153. def from_recordfeature(key, val, section, pjsip, nmapped):
  154. """
  155. If record on/off feature is set to automixmon then set
  156. one_touch_recording, otherwise it can't be mapped.
  157. """
  158. set_value('one_touch_recording', 'yes', section, pjsip, nmapped)
  159. set_value(key, val, section, pjsip, nmapped)
  160. def set_record_on_feature(key, val, section, pjsip, nmapped):
  161. """Sets the record_on_feature in pjsip.conf"""
  162. from_recordfeature('record_on_feature', val, section, pjsip, nmapped)
  163. def set_record_off_feature(key, val, section, pjsip, nmapped):
  164. """Sets the record_off_feature in pjsip.conf"""
  165. from_recordfeature('record_off_feature', val, section, pjsip, nmapped)
  166. def from_progressinband(key, val, section, pjsip, nmapped):
  167. """Sets the inband_progress value in pjsip.conf"""
  168. # progressinband can = yes/no/never
  169. if val == 'never':
  170. val = 'no'
  171. set_value('inband_progress', val, section, pjsip, nmapped)
  172. def build_host(config, host, section, port_key):
  173. """
  174. Returns a string composed of a host:port. This assumes that the host
  175. may have a port as part of the initial value. The port_key is only used
  176. if the host does not already have a port set on it.
  177. Throws a LookupError if the key does not exist
  178. """
  179. port = None
  180. try:
  181. socket.inet_pton(socket.AF_INET6, host)
  182. if not host.startswith('['):
  183. # SIP URI will need brackets.
  184. host = '[' + host + ']'
  185. else:
  186. # If brackets are present, there may be a port as well
  187. port = re.match('\[.*\]:(\d+)', host)
  188. except socket.error:
  189. # No biggie. It's just not an IPv6 address
  190. port = re.match('.*:(\d+)', host)
  191. result = host
  192. if not port:
  193. try:
  194. port = config.get(section, port_key)[0]
  195. result += ':' + port
  196. except LookupError:
  197. pass
  198. return result
  199. def from_host(key, val, section, pjsip, nmapped):
  200. """
  201. Sets contact info in an AOR section in pjsip.conf using 'host'
  202. and 'port' data from sip.conf
  203. """
  204. # all aors have the same name as the endpoint so makes
  205. # it easy to set endpoint's 'aors' value
  206. set_value('aors', section, section, pjsip, nmapped)
  207. if val == 'dynamic':
  208. # Easy case. Just set the max_contacts on the aor and we're done
  209. set_value('max_contacts', 1, section, pjsip, nmapped, 'aor')
  210. return
  211. result = 'sip:'
  212. # More difficult case. The host will be either a hostname or
  213. # IP address and may or may not have a port specified. pjsip.conf
  214. # expects the contact to be a SIP URI.
  215. user = None
  216. try:
  217. user = sip.multi_get(section, ['defaultuser', 'username'])[0]
  218. result += user + '@'
  219. except LookupError:
  220. # It's fine if there's no user name
  221. pass
  222. result += build_host(sip, val, section, 'port')
  223. set_value('contact', result, section, pjsip, nmapped, 'aor')
  224. def from_mailbox(key, val, section, pjsip, nmapped):
  225. """
  226. Determines whether a mailbox configured in sip.conf should map to
  227. an endpoint or aor in pjsip.conf. If subscribemwi is true, then the
  228. mailboxes are set on an aor. Otherwise the mailboxes are set on the
  229. endpoint.
  230. """
  231. try:
  232. subscribemwi = sip.get(section, 'subscribemwi')[0]
  233. except LookupError:
  234. # No subscribemwi option means default it to 'no'
  235. subscribemwi = 'no'
  236. set_value('mailboxes', val, section, pjsip, nmapped, 'aor'
  237. if subscribemwi == 'yes' else 'endpoint')
  238. def setup_auth(key, val, section, pjsip, nmapped):
  239. """
  240. Sets up authentication information for a specific endpoint based on the
  241. 'secret' setting on a peer in sip.conf
  242. """
  243. set_value('username', section, section, pjsip, nmapped, 'auth')
  244. # In chan_sip, if a secret and an md5secret are both specified on a peer,
  245. # then in practice, only the md5secret is used. If both are encountered
  246. # then we build an auth section that has both an md5_cred and password.
  247. # However, the auth_type will indicate to authenticators to use the
  248. # md5_cred, so like with sip.conf, the password will be there but have
  249. # no purpose.
  250. if key == 'secret':
  251. set_value('password', val, section, pjsip, nmapped, 'auth')
  252. else:
  253. set_value('md5_cred', val, section, pjsip, nmapped, 'auth')
  254. set_value('auth_type', 'md5', section, pjsip, nmapped, 'auth')
  255. realms = [section]
  256. try:
  257. auths = sip.get('authentication', 'auth')
  258. for i in auths:
  259. user, at, realm = i.partition('@')
  260. realms.append(realm)
  261. except LookupError:
  262. pass
  263. realm_str = ','.join(realms)
  264. set_value('auth', section, section, pjsip, nmapped)
  265. set_value('outbound_auth', realm_str, section, pjsip, nmapped)
  266. def setup_ident(key, val, section, pjsip, nmapped):
  267. """
  268. Examines the 'type' field for a sip.conf peer and creates an identify
  269. section if the type is either 'peer' or 'friend'. The identify section uses
  270. either the host or defaultip field of the sip.conf peer.
  271. """
  272. if val != 'peer' and val != 'friend':
  273. return
  274. try:
  275. ip = sip.get(section, 'host')[0]
  276. except LookupError:
  277. return
  278. if ip == 'dynamic':
  279. try:
  280. ip = sip.get(section, 'defaultip')[0]
  281. except LookupError:
  282. return
  283. set_value('endpoint', section, section, pjsip, nmapped, 'identify')
  284. set_value('match', ip, section, pjsip, nmapped, 'identify')
  285. def from_encryption_taglen(key, val, section, pjsip, nmapped):
  286. """Sets the srtp_tag32 option based on sip.conf encryption_taglen"""
  287. if val == '32':
  288. set_value('srtp_tag_32', 'yes', section, pjsip, nmapped)
  289. def from_dtlsenable(key, val, section, pjsip, nmapped):
  290. """Optionally sets media_encryption=dtls based on sip.conf dtlsenable"""
  291. if val == 'yes':
  292. set_value('media_encryption', 'dtls', section, pjsip, nmapped)
  293. ###############################################################################
  294. # options in pjsip.conf on an endpoint that have no sip.conf equivalent:
  295. # type, rtp_ipv6, 100rel, trust_id_outbound, aggregate_mwi,
  296. # connected_line_method
  297. # known sip.conf peer keys that can be mapped to a pjsip.conf section/key
  298. peer_map = [
  299. # sip.conf option mapping function pjsip.conf option(s)
  300. ###########################################################################
  301. ['context', set_value],
  302. ['dtmfmode', set_dtmfmode],
  303. ['disallow', merge_value],
  304. ['allow', merge_value],
  305. ['nat', from_nat], # rtp_symmetric, force_rport,
  306. # rewrite_contact
  307. ['icesupport', set_value('ice_support')],
  308. ['autoframing', set_value('use_ptime')],
  309. ['outboundproxy', set_value('outbound_proxy')],
  310. ['mohsuggest', set_value('moh_suggest')],
  311. ['session-timers', set_timers], # timers
  312. ['session-minse', set_value('timers_min_se')],
  313. ['session-expires', set_value('timers_sess_expires')],
  314. ['externip', set_value('external_media_address')],
  315. ['externhost', set_value('external_media_address')],
  316. # identify_by ?
  317. ['directmedia', set_direct_media], # direct_media
  318. # direct_media_method
  319. # directed_media_glare_mitigation
  320. # disable_directed_media_on_nat
  321. ['callerid', set_value], # callerid
  322. ['callingpres', set_value('callerid_privacy')],
  323. ['cid_tag', set_value('callerid_tag')],
  324. ['trustpid', set_value('trust_id_inbound')],
  325. ['sendrpid', from_sendrpid], # send_pai, send_rpid
  326. ['send_diversion', set_value],
  327. ['encrpytion', set_media_encryption],
  328. ['avpf', set_value('use_avpf')],
  329. ['recordonfeature', set_record_on_feature], # automixon
  330. ['recordofffeature', set_record_off_feature], # automixon
  331. ['progressinband', from_progressinband], # in_band_progress
  332. ['callgroup', set_value('call_group')],
  333. ['pickupgroup', set_value('pickup_group')],
  334. ['namedcallgroup', set_value('named_call_group')],
  335. ['namedpickupgroup', set_value('named_pickup_group')],
  336. ['allowtransfer', set_value('allow_transfer')],
  337. ['fromuser', set_value('from_user')],
  338. ['fromdomain', set_value('from_domain')],
  339. ['mwifrom', set_value('mwi_from_user')],
  340. ['tos_audio', set_value],
  341. ['tos_video', set_value],
  342. ['cos_audio', set_value],
  343. ['cos_video', set_value],
  344. ['sdpowner', set_value('sdp_owner')],
  345. ['sdpsession', set_value('sdp_session')],
  346. ['tonezone', set_value('tone_zone')],
  347. ['language', set_value],
  348. ['allowsubscribe', set_value('allow_subscribe')],
  349. ['subminexpiry', set_value('sub_min_expiry')],
  350. ['rtp_engine', set_value],
  351. ['mailbox', from_mailbox],
  352. ['busylevel', set_value('device_state_busy_at')],
  353. ['secret', setup_auth],
  354. ['md5secret', setup_auth],
  355. ['type', setup_ident],
  356. ['dtlsenable', from_dtlsenable],
  357. ['dtlsverify', set_value('dtls_verify')],
  358. ['dtlsrekey', set_value('dtls_rekey')],
  359. ['dtlscertfile', set_value('dtls_cert_file')],
  360. ['dtlsprivatekey', set_value('dtls_private_key')],
  361. ['dtlscipher', set_value('dtls_cipher')],
  362. ['dtlscafile', set_value('dtls_ca_file')],
  363. ['dtlscapath', set_value('dtls_ca_path')],
  364. ['dtlssetup', set_value('dtls_setup')],
  365. ['encryption_taglen', from_encryption_taglen],
  366. ############################ maps to an aor ###################################
  367. ['host', from_host], # contact, max_contacts
  368. ['qualifyfreq', set_value('qualify_frequency', type='aor')],
  369. ############################# maps to auth#####################################
  370. # type = auth
  371. # username
  372. # password
  373. # md5_cred
  374. # realm
  375. # nonce_lifetime
  376. # auth_type
  377. ######################### maps to acl/security ################################
  378. ['permit', merge_value(type='acl', section_to='acl')],
  379. ['deny', merge_value(type='acl', section_to='acl')],
  380. ['acl', merge_value(type='acl', section_to='acl')],
  381. ['contactpermit', merge_value('contact_permit', type='acl', section_to='acl')],
  382. ['contactdeny', merge_value('contact_deny', type='acl', section_to='acl')],
  383. ['contactacl', merge_value('contact_acl', type='acl', section_to='acl')],
  384. ########################### maps to transport #################################
  385. # type = transport
  386. # protocol
  387. # bind
  388. # async_operations
  389. # ca_list_file
  390. # cert_file
  391. # privkey_file
  392. # password
  393. # external_signaling_address - externip & externhost
  394. # external_signaling_port
  395. # external_media_address
  396. # domain
  397. # verify_server
  398. # verify_client
  399. # require_client_cert
  400. # method
  401. # cipher
  402. # localnet
  403. ######################### maps to domain_alias ################################
  404. # type = domain_alias
  405. # domain
  406. ######################### maps to registration ################################
  407. # type = registration
  408. # server_uri
  409. # client_uri
  410. # contact_user
  411. # transport
  412. # outbound_proxy
  413. # expiration
  414. # retry_interval
  415. # max_retries
  416. # auth_rejection_permanent
  417. # outbound_auth
  418. ########################### maps to identify ##################################
  419. # type = identify
  420. # endpoint
  421. # match
  422. ]
  423. def add_localnet(section, pjsip, nmapped):
  424. """
  425. Adds localnet values from sip.conf's general section to a transport in
  426. pjsip.conf. Ideally, we would have just created a template with the
  427. localnet sections, but because this is a script, it's not hard to add
  428. the same thing on to every transport.
  429. """
  430. try:
  431. merge_value('local_net', sip.get('general', 'localnet')[0], 'general',
  432. pjsip, nmapped, 'transport', section)
  433. except LookupError:
  434. # No localnet options configured. No biggie!
  435. pass
  436. def set_transport_common(section, pjsip, nmapped):
  437. """
  438. sip.conf has several global settings that in pjsip.conf apply to individual
  439. transports. This function adds these global settings to each individual
  440. transport.
  441. The settings included are:
  442. localnet
  443. tos_sip
  444. cos_sip
  445. """
  446. try:
  447. merge_value('local_net', sip.get('general', 'localnet')[0], 'general',
  448. pjsip, nmapped, 'transport', section)
  449. except LookupError:
  450. # No localnet options configured. Move on.
  451. pass
  452. try:
  453. set_value('tos', sip.get('general', 'sip_tos')[0], 'general', pjsip,
  454. nmapped, 'transport', section)
  455. except LookupError:
  456. pass
  457. try:
  458. set_value('cos', sip.get('general', 'sip_cos')[0], 'general', pjsip,
  459. nmapped, 'transport', section)
  460. except LookupError:
  461. pass
  462. def split_hostport(addr):
  463. """
  464. Given an address in the form 'addr:port' separate the addr and port
  465. components.
  466. Returns a two-tuple of strings, (addr, port). If no port is present in the
  467. string, then the port section of the tuple is None.
  468. """
  469. try:
  470. socket.inet_pton(socket.AF_INET6, addr)
  471. if not addr.startswith('['):
  472. return (addr, None)
  473. else:
  474. # If brackets are present, there may be a port as well
  475. match = re.match('\[(.*\)]:(\d+)', addr)
  476. if match:
  477. return (match.group(1), match.group(2))
  478. else:
  479. return (addr, None)
  480. except socket.error:
  481. pass
  482. # IPv4 address or hostname
  483. host, sep, port = addr.rpartition(':')
  484. if not sep and not port:
  485. return (host, None)
  486. else:
  487. return (host, port)
  488. def create_udp(sip, pjsip, nmapped):
  489. """
  490. Creates a 'transport-udp' section in the pjsip.conf file based
  491. on the following settings from sip.conf:
  492. bindaddr (or udpbindaddr)
  493. bindport
  494. externaddr (or externip)
  495. externhost
  496. """
  497. bind = sip.multi_get('general', ['udpbindaddr', 'bindaddr'])[0]
  498. bind = build_host(sip, bind, 'general', 'bindport')
  499. try:
  500. extern_addr = sip.multi_get('general', ['externaddr', 'externip',
  501. 'externhost'])[0]
  502. host, port = split_hostport(extern_addr)
  503. set_value('external_signaling_address', host, 'transport-udp', pjsip,
  504. nmapped, 'transport')
  505. if port:
  506. set_value('external_signaling_port', port, 'transport-udp', pjsip,
  507. nmapped, 'transport')
  508. except LookupError:
  509. pass
  510. set_value('protocol', 'udp', 'transport-udp', pjsip, nmapped, 'transport')
  511. set_value('bind', bind, 'transport-udp', pjsip, nmapped, 'transport')
  512. set_transport_common('transport-udp', pjsip, nmapped)
  513. def create_tcp(sip, pjsip, nmapped):
  514. """
  515. Creates a 'transport-tcp' section in the pjsip.conf file based
  516. on the following settings from sip.conf:
  517. tcpenable
  518. tcpbindaddr
  519. externtcpport
  520. """
  521. try:
  522. enabled = sip.get('general', 'tcpenable')[0]
  523. except:
  524. # No value means disabled by default. No need for a tranport
  525. return
  526. if enabled == 'no':
  527. return
  528. try:
  529. bind = sip.get('general', 'tcpbindaddr')[0]
  530. bind = build_host(sip, bind, 'general', 'bindport')
  531. except LookupError:
  532. # No tcpbindaddr means to default to the udpbindaddr
  533. bind = pjsip.get('transport-udp', 'bind')[0]
  534. try:
  535. extern_addr = sip.multi_get('general', ['externaddr', 'externip',
  536. 'externhost'])[0]
  537. host, port = split_hostport(extern_addr)
  538. try:
  539. tcpport = sip.get('general', 'externtcpport')[0]
  540. except:
  541. tcpport = port
  542. set_value('external_signaling_address', host, 'transport-tcp', pjsip,
  543. nmapped, 'transport')
  544. if tcpport:
  545. set_value('external_signaling_port', tcpport, 'transport-tcp',
  546. pjsip, nmapped, 'transport')
  547. except LookupError:
  548. pass
  549. set_value('protocol', 'tcp', 'transport-tcp', pjsip, nmapped, 'transport')
  550. set_value('bind', bind, 'transport-tcp', pjsip, nmapped, 'transport')
  551. set_transport_common('transport-tcp', pjsip, nmapped)
  552. def set_tls_bindaddr(val, pjsip, nmapped):
  553. """
  554. Creates the TCP bind address. This has two possible methods of
  555. working:
  556. Use the 'tlsbindaddr' option from sip.conf directly if it has both
  557. an address and port. If no port is present, use 5061
  558. If there is no 'tlsbindaddr' option present in sip.conf, use the
  559. previously-established UDP bind address and port 5061
  560. """
  561. try:
  562. bind = sip.get('general', 'tlsbindaddr')[0]
  563. explicit = True
  564. except LookupError:
  565. # No tlsbindaddr means to default to the bindaddr but with standard TLS
  566. # port
  567. bind = pjsip.get('transport-udp', 'bind')[0]
  568. explicit = False
  569. matchv4 = re.match('\d+\.\d+\.\d+\.\d+:\d+', bind)
  570. matchv6 = re.match('\[.*\]:d+', bind)
  571. if matchv4 or matchv6:
  572. if explicit:
  573. # They provided a port. We'll just use it.
  574. set_value('bind', bind, 'transport-tls', pjsip, nmapped,
  575. 'transport')
  576. return
  577. else:
  578. # Need to strip the port from the UDP address
  579. index = bind.rfind(':')
  580. bind = bind[:index]
  581. # Reaching this point means either there was no port provided or we
  582. # stripped the port off. We need to add on the default 5061 port
  583. bind += ':5061'
  584. set_value('bind', bind, 'transport-tls', pjsip, nmapped, 'transport')
  585. def set_tls_private_key(val, pjsip, nmapped):
  586. """Sets privkey_file based on sip.conf tlsprivatekey or sslprivatekey"""
  587. set_value('priv_key_file', val, 'transport-tls', pjsip, nmapped,
  588. 'transport')
  589. def set_tls_cipher(val, pjsip, nmapped):
  590. """Sets cipher based on sip.conf tlscipher or sslcipher"""
  591. set_value('cipher', val, 'transport-tls', pjsip, nmapped, 'transport')
  592. def set_tls_cafile(val, pjsip, nmapped):
  593. """Sets ca_list_file based on sip.conf tlscafile"""
  594. set_value('ca_list_file', val, 'transport-tls', pjsip, nmapped,
  595. 'transport')
  596. def set_tls_verifyclient(val, pjsip, nmapped):
  597. """Sets verify_client based on sip.conf tlsverifyclient"""
  598. set_value('verify_client', val, 'transport-tls', pjsip, nmapped,
  599. 'transport')
  600. def set_tls_verifyserver(val, pjsip, nmapped):
  601. """Sets verify_server based on sip.conf tlsdontverifyserver"""
  602. if val == 'no':
  603. set_value('verify_server', 'yes', 'transport-tls', pjsip, nmapped,
  604. 'transport')
  605. else:
  606. set_value('verify_server', 'no', 'transport-tls', pjsip, nmapped,
  607. 'transport')
  608. def set_tls_method(val, pjsip, nmapped):
  609. """Sets method based on sip.conf tlsclientmethod or sslclientmethod"""
  610. set_value('method', val, 'transport-tls', pjsip, nmapped, 'transport')
  611. def create_tls(sip, pjsip, nmapped):
  612. """
  613. Creates a 'transport-tls' section in pjsip.conf based on the following
  614. settings from sip.conf:
  615. tlsenable (or sslenable)
  616. tlsbindaddr (or sslbindaddr)
  617. tlsprivatekey (or sslprivatekey)
  618. tlscipher (or sslcipher)
  619. tlscafile
  620. tlscapath (or tlscadir)
  621. tlscertfile (or sslcert or tlscert)
  622. tlsverifyclient
  623. tlsdontverifyserver
  624. tlsclientmethod (or sslclientmethod)
  625. """
  626. tls_map = [
  627. (['tlsbindaddr', 'sslbindaddr'], set_tls_bindaddr),
  628. (['tlsprivatekey', 'sslprivatekey'], set_tls_private_key),
  629. (['tlscipher', 'sslcipher'], set_tls_cipher),
  630. (['tlscafile'], set_tls_cafile),
  631. (['tlsverifyclient'], set_tls_verifyclient),
  632. (['tlsdontverifyserver'], set_tls_verifyserver),
  633. (['tlsclientmethod', 'sslclientmethod'], set_tls_method)
  634. ]
  635. try:
  636. enabled = sip.multi_get('general', ['tlsenable', 'sslenable'])[0]
  637. except LookupError:
  638. # Not enabled. Don't create a transport
  639. return
  640. if enabled == 'no':
  641. return
  642. set_value('protocol', 'tls', 'transport-tls', pjsip, nmapped, 'transport')
  643. for i in tls_map:
  644. try:
  645. i[1](sip.multi_get('general', i[0])[0], pjsip, nmapped)
  646. except LookupError:
  647. pass
  648. set_transport_common('transport-tls', pjsip, nmapped)
  649. try:
  650. extern_addr = sip.multi_get('general', ['externaddr', 'externip',
  651. 'externhost'])[0]
  652. host, port = split_hostport(extern_addr)
  653. try:
  654. tlsport = sip.get('general', 'externtlsport')[0]
  655. except:
  656. tlsport = port
  657. set_value('external_signaling_address', host, 'transport-tls', pjsip,
  658. nmapped, 'transport')
  659. if tlsport:
  660. set_value('external_signaling_port', tlsport, 'transport-tls',
  661. pjsip, nmapped, 'transport')
  662. except LookupError:
  663. pass
  664. def map_transports(sip, pjsip, nmapped):
  665. """
  666. Finds options in sip.conf general section pertaining to
  667. transport configuration and creates appropriate transport
  668. configuration sections in pjsip.conf.
  669. sip.conf only allows a single UDP transport, TCP transport,
  670. and TLS transport. As such, the mapping into PJSIP can be made
  671. consistent by defining three sections:
  672. transport-udp
  673. transport-tcp
  674. transport-tls
  675. To accommodate the default behaviors in sip.conf, we'll need to
  676. create the UDP transport first, followed by the TCP and TLS transports.
  677. """
  678. # First create a UDP transport. Even if no bind parameters were provided
  679. # in sip.conf, chan_sip would always bind to UDP 0.0.0.0:5060
  680. create_udp(sip, pjsip, nmapped)
  681. # TCP settings may be dependent on UDP settings, so do it second.
  682. create_tcp(sip, pjsip, nmapped)
  683. create_tls(sip, pjsip, nmapped)
  684. def map_auth(sip, pjsip, nmapped):
  685. """
  686. Creates auth sections based on entries in the authentication section of
  687. sip.conf. pjsip.conf section names consist of "auth_" followed by the name
  688. of the realm.
  689. """
  690. try:
  691. auths = sip.get('authentication', 'auth')
  692. except LookupError:
  693. return
  694. for i in auths:
  695. creds, at, realm = i.partition('@')
  696. if not at and not realm:
  697. # Invalid. Move on
  698. continue
  699. user, colon, secret = creds.partition(':')
  700. if not secret:
  701. user, sharp, md5 = creds.partition('#')
  702. if not md5:
  703. #Invalid. move on
  704. continue
  705. section = "auth_" + realm
  706. set_value('realm', realm, section, pjsip, nmapped, 'auth')
  707. set_value('username', user, section, pjsip, nmapped, 'auth')
  708. if secret:
  709. set_value('password', secret, section, pjsip, nmapped, 'auth')
  710. else:
  711. set_value('md5_cred', md5, section, pjsip, nmapped, 'auth')
  712. set_value('auth_type', 'md5', section, pjsip, nmapped, 'auth')
  713. class Registration:
  714. """
  715. Class for parsing and storing information in a register line in sip.conf.
  716. """
  717. def __init__(self, line, retry_interval, max_attempts, outbound_proxy):
  718. self.retry_interval = retry_interval
  719. self.max_attempts = max_attempts
  720. self.outbound_proxy = outbound_proxy
  721. self.parse(line)
  722. def parse(self, line):
  723. """
  724. Initial parsing routine for register lines in sip.conf.
  725. This splits the line into the part before the host, and the part
  726. after the '@' symbol. These two parts are then passed to their
  727. own parsing routines
  728. """
  729. # register =>
  730. # [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
  731. prehost, at, host_part = line.rpartition('@')
  732. if not prehost:
  733. raise
  734. self.parse_host_part(host_part)
  735. self.parse_user_part(prehost)
  736. def parse_host_part(self, host_part):
  737. """
  738. Parsing routine for the part after the final '@' in a register line.
  739. The strategy is to use partition calls to peel away the data starting
  740. from the right and working to the left.
  741. """
  742. pre_expiry, sep, expiry = host_part.partition('~')
  743. pre_extension, sep, self.extension = pre_expiry.partition('/')
  744. self.host, sep, self.port = pre_extension.partition(':')
  745. self.expiry = expiry if expiry else '120'
  746. def parse_user_part(self, user_part):
  747. """
  748. Parsing routine for the part before the final '@' in a register line.
  749. The only mandatory part of this line is the user portion. The strategy
  750. here is to start by using partition calls to remove everything to
  751. the right of the user, then finish by using rpartition calls to remove
  752. everything to the left of the user.
  753. """
  754. colons = user_part.count(':')
  755. if (colons == 3):
  756. # :domainport:secret:authuser
  757. pre_auth, sep, port_auth = user_part.partition(':')
  758. self.domainport, sep, auth = port_auth.partition(':')
  759. self.secret, sep, self.authuser = auth.partition(':')
  760. elif (colons == 2):
  761. # :secret:authuser
  762. pre_auth, sep, auth = user_part.partition(':')
  763. self.secret, sep, self.authuser = auth.partition(':')
  764. elif (colons == 1):
  765. # :secret
  766. pre_auth, sep, self.secret = user_part.partition(':')
  767. elif (colons == 0):
  768. # No port, secret, or authuser
  769. pre_auth = user_part
  770. else:
  771. # Invalid setting
  772. raise
  773. pre_domain, sep, self.domain = pre_auth.partition('@')
  774. self.peer, sep, post_peer = pre_domain.rpartition('?')
  775. transport, sep, self.user = post_peer.rpartition('://')
  776. self.protocol = transport if transport else 'udp'
  777. def write(self, pjsip, nmapped):
  778. """
  779. Write parsed registration data into a section in pjsip.conf
  780. Most of the data in self will get written to a registration section.
  781. However, there will also need to be an auth section created if a
  782. secret or authuser is present.
  783. General mapping of values:
  784. A combination of self.host and self.port is server_uri
  785. A combination of self.user, self.domain, and self.domainport is
  786. client_uri
  787. self.expiry is expiration
  788. self.extension is contact_user
  789. self.protocol will map to one of the mapped transports
  790. self.secret and self.authuser will result in a new auth section, and
  791. outbound_auth will point to that section.
  792. XXX self.peer really doesn't map to anything :(
  793. """
  794. section = 'reg_' + self.host
  795. set_value('retry_interval', self.retry_interval, section, pjsip,
  796. nmapped, 'registration')
  797. set_value('max_retries', self.max_attempts, section, pjsip, nmapped,
  798. 'registration')
  799. if self.extension:
  800. set_value('contact_user', self.extension, section, pjsip, nmapped,
  801. 'registration')
  802. set_value('expiration', self.expiry, section, pjsip, nmapped,
  803. 'registration')
  804. if self.protocol == 'udp':
  805. set_value('transport', 'transport-udp', section, pjsip, nmapped,
  806. 'registration')
  807. elif self.protocol == 'tcp':
  808. set_value('transport', 'transport-tcp', section, pjsip, nmapped,
  809. 'registration')
  810. elif self.protocol == 'tls':
  811. set_value('transport', 'transport-tls', section, pjsip, nmapped,
  812. 'registration')
  813. auth_section = 'auth_reg_' + self.host
  814. if self.secret:
  815. set_value('password', self.secret, auth_section, pjsip, nmapped,
  816. 'auth')
  817. set_value('username', self.authuser or self.user, auth_section,
  818. pjsip, nmapped, 'auth')
  819. set_value('outbound_auth', auth_section, section, pjsip, nmapped,
  820. 'registration')
  821. client_uri = "sip:%s@" % self.user
  822. if self.domain:
  823. client_uri += self.domain
  824. else:
  825. client_uri += self.host
  826. if self.domainport:
  827. client_uri += ":" + self.domainport
  828. elif self.port:
  829. client_uri += ":" + self.port
  830. set_value('client_uri', client_uri, section, pjsip, nmapped,
  831. 'registration')
  832. server_uri = "sip:%s" % self.host
  833. if self.port:
  834. server_uri += ":" + self.port
  835. set_value('server_uri', server_uri, section, pjsip, nmapped,
  836. 'registration')
  837. if self.outbound_proxy:
  838. set_value('outboundproxy', self.outbound_proxy, section, pjsip,
  839. nmapped, 'registartion')
  840. def map_registrations(sip, pjsip, nmapped):
  841. """
  842. Gathers all necessary outbound registration data in sip.conf and creates
  843. corresponding registration sections in pjsip.conf
  844. """
  845. try:
  846. regs = sip.get('general', 'register')
  847. except LookupError:
  848. return
  849. try:
  850. retry_interval = sip.get('general', 'registertimeout')[0]
  851. except LookupError:
  852. retry_interval = '20'
  853. try:
  854. max_attempts = sip.get('general', 'registerattempts')[0]
  855. except LookupError:
  856. max_attempts = '10'
  857. try:
  858. outbound_proxy = sip.get('general', 'outboundproxy')[0]
  859. except LookupError:
  860. outbound_proxy = ''
  861. for i in regs:
  862. reg = Registration(i, retry_interval, max_attempts, outbound_proxy)
  863. reg.write(pjsip, nmapped)
  864. def map_peer(sip, section, pjsip, nmapped):
  865. """
  866. Map the options from a peer section in sip.conf into the appropriate
  867. sections in pjsip.conf
  868. """
  869. for i in peer_map:
  870. try:
  871. # coming from sip.conf the values should mostly be a list with a
  872. # single value. In the few cases that they are not a specialized
  873. # function (see merge_value) is used to retrieve the values.
  874. i[1](i[0], sip.get(section, i[0])[0], section, pjsip, nmapped)
  875. except LookupError:
  876. pass # key not found in sip.conf
  877. def find_non_mapped(sections, nmapped):
  878. """
  879. Determine sip.conf options that were not properly mapped to pjsip.conf
  880. options.
  881. """
  882. for section, sect in sections.iteritems():
  883. try:
  884. # since we are pulling from sip.conf this should always
  885. # be a single value list
  886. sect = sect[0]
  887. # loop through the section and store any values that were not
  888. # mapped
  889. for key in sect.keys(True):
  890. for i in peer_map:
  891. if i[0] == key:
  892. break
  893. else:
  894. nmapped(section, key, sect[key])
  895. except LookupError:
  896. pass
  897. def convert(sip, filename, non_mappings, include):
  898. """
  899. Entry point for configuration file conversion. This
  900. function will create a pjsip.conf object and begin to
  901. map specific sections from sip.conf into it.
  902. Returns the new pjsip.conf object once completed
  903. """
  904. pjsip = astconfigparser.MultiOrderedConfigParser()
  905. non_mappings[filename] = astdicts.MultiOrderedDict()
  906. nmapped = non_mapped(non_mappings[filename])
  907. if not include:
  908. # Don't duplicate transport and registration configs
  909. map_transports(sip, pjsip, nmapped)
  910. map_registrations(sip, pjsip, nmapped)
  911. map_auth(sip, pjsip, nmapped)
  912. for section in sip.sections():
  913. if section == 'authentication':
  914. pass
  915. else:
  916. map_peer(sip, section, pjsip, nmapped)
  917. find_non_mapped(sip.defaults(), nmapped)
  918. find_non_mapped(sip.sections(), nmapped)
  919. for key, val in sip.includes().iteritems():
  920. pjsip.add_include(PREFIX + key, convert(val, PREFIX + key,
  921. non_mappings, True)[0])
  922. return pjsip, non_mappings
  923. def write_pjsip(filename, pjsip, non_mappings):
  924. """
  925. Write pjsip.conf file to disk
  926. """
  927. try:
  928. with open(filename, 'wt') as fp:
  929. fp.write(';--\n')
  930. fp.write(';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n')
  931. fp.write('Non mapped elements start\n')
  932. fp.write(';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n')
  933. astconfigparser.write_dicts(fp, non_mappings[filename])
  934. fp.write(';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n')
  935. fp.write('Non mapped elements end\n')
  936. fp.write(';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n')
  937. fp.write('--;\n\n')
  938. # write out include file(s)
  939. pjsip.write(fp)
  940. except IOError:
  941. print "Could not open file ", filename, " for writing"
  942. ###############################################################################
  943. def cli_options():
  944. """
  945. Parse command line options and apply them. If invalid input is given,
  946. print usage information
  947. """
  948. global PREFIX
  949. usage = "usage: %prog [options] [input-file [output-file]]\n\n" \
  950. "input-file defaults to 'sip.conf'\n" \
  951. "output-file defaults to 'pjsip.conf'"
  952. parser = optparse.OptionParser(usage=usage)
  953. parser.add_option('-p', '--prefix', dest='prefix', default=PREFIX,
  954. help='output prefix for include files')
  955. options, args = parser.parse_args()
  956. PREFIX = options.prefix
  957. sip_filename = args[0] if len(args) else 'sip.conf'
  958. pjsip_filename = args[1] if len(args) == 2 else 'pjsip.conf'
  959. return sip_filename, pjsip_filename
  960. if __name__ == "__main__":
  961. sip_filename, pjsip_filename = cli_options()
  962. # configuration parser for sip.conf
  963. sip = astconfigparser.MultiOrderedConfigParser()
  964. sip.read(sip_filename)
  965. pjsip, non_mappings = convert(sip, pjsip_filename, dict(), False)
  966. write_pjsip(pjsip_filename, pjsip, non_mappings)