res_pjsip.c 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2013, Digium, Inc.
  5. *
  6. * Mark Michelson <mmichelson@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. #include "asterisk.h"
  19. #include <pjsip.h>
  20. /* Needed for SUBSCRIBE, NOTIFY, and PUBLISH method definitions */
  21. #include <pjsip_simple.h>
  22. #include <pjsip/sip_transaction.h>
  23. #include <pj/timer.h>
  24. #include <pjlib.h>
  25. #include <pjmedia/errno.h>
  26. #include "asterisk/res_pjsip.h"
  27. #include "asterisk/strings.h"
  28. #include "pjsip/sip_parser.h"
  29. #include "res_pjsip/include/res_pjsip_private.h"
  30. #include "asterisk/linkedlists.h"
  31. #include "asterisk/logger.h"
  32. #include "asterisk/lock.h"
  33. #include "asterisk/utils.h"
  34. #include "asterisk/astobj2.h"
  35. #include "asterisk/module.h"
  36. #include "asterisk/serializer.h"
  37. #include "asterisk/threadpool.h"
  38. #include "asterisk/taskprocessor.h"
  39. #include "asterisk/uuid.h"
  40. #include "asterisk/sorcery.h"
  41. #include "asterisk/file.h"
  42. #include "asterisk/causes.h"
  43. #include "asterisk/cli.h"
  44. #include "asterisk/callerid.h"
  45. #include "asterisk/res_pjsip_cli.h"
  46. #include "asterisk/test.h"
  47. #include "asterisk/res_pjsip_presence_xml.h"
  48. #include "asterisk/res_pjproject.h"
  49. #include "asterisk/utf8.h"
  50. #include "asterisk/acl.h"
  51. /*** MODULEINFO
  52. <depend>pjproject</depend>
  53. <depend>res_pjproject</depend>
  54. <depend>res_sorcery_config</depend>
  55. <depend>res_sorcery_memory</depend>
  56. <depend>res_sorcery_astdb</depend>
  57. <use type="module">res_statsd</use>
  58. <use type="module">res_geolocation</use>
  59. <support_level>core</support_level>
  60. ***/
  61. #define MOD_DATA_CONTACT "contact"
  62. /*! Number of serializers in pool if one not supplied. */
  63. #define SERIALIZER_POOL_SIZE 8
  64. /*! Pool of serializers to use if not supplied. */
  65. static struct ast_serializer_pool *sip_serializer_pool;
  66. static pjsip_endpoint *ast_pjsip_endpoint;
  67. static struct ast_threadpool *sip_threadpool;
  68. /*! Local host address for IPv4 */
  69. static pj_sockaddr host_ip_ipv4;
  70. /*! Local host address for IPv4 (string form) */
  71. static char host_ip_ipv4_string[PJ_INET6_ADDRSTRLEN];
  72. /*! Local host address for IPv6 */
  73. static pj_sockaddr host_ip_ipv6;
  74. /*! Local host address for IPv6 (string form) */
  75. static char host_ip_ipv6_string[PJ_INET6_ADDRSTRLEN];
  76. void ast_sip_add_date_header(pjsip_tx_data *tdata)
  77. {
  78. char date[256];
  79. struct tm tm;
  80. time_t t = time(NULL);
  81. gmtime_r(&t, &tm);
  82. strftime(date, sizeof(date), "%a, %d %b %Y %T GMT", &tm);
  83. ast_sip_add_header(tdata, "Date", date);
  84. }
  85. static int register_service(void *data)
  86. {
  87. pjsip_module **module = data;
  88. if (!ast_pjsip_endpoint) {
  89. ast_log(LOG_ERROR, "There is no PJSIP endpoint. Unable to register services\n");
  90. return -1;
  91. }
  92. if (pjsip_endpt_register_module(ast_pjsip_endpoint, *module) != PJ_SUCCESS) {
  93. ast_log(LOG_ERROR, "Unable to register module %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
  94. return -1;
  95. }
  96. ast_debug(1, "Registered SIP service %.*s (%p)\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name), *module);
  97. return 0;
  98. }
  99. int ast_sip_register_service(pjsip_module *module)
  100. {
  101. return ast_sip_push_task_wait_servant(NULL, register_service, &module);
  102. }
  103. static int unregister_service(void *data)
  104. {
  105. pjsip_module **module = data;
  106. if (!ast_pjsip_endpoint) {
  107. return -1;
  108. }
  109. pjsip_endpt_unregister_module(ast_pjsip_endpoint, *module);
  110. ast_debug(1, "Unregistered SIP service %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
  111. return 0;
  112. }
  113. void ast_sip_unregister_service(pjsip_module *module)
  114. {
  115. ast_sip_push_task_wait_servant(NULL, unregister_service, &module);
  116. }
  117. static struct ast_sip_authenticator *registered_authenticator;
  118. int ast_sip_register_authenticator(struct ast_sip_authenticator *auth)
  119. {
  120. if (registered_authenticator) {
  121. ast_log(LOG_WARNING, "Authenticator %p is already registered. Cannot register a new one\n", registered_authenticator);
  122. return -1;
  123. }
  124. registered_authenticator = auth;
  125. ast_debug(1, "Registered SIP authenticator module %p\n", auth);
  126. return 0;
  127. }
  128. void ast_sip_unregister_authenticator(struct ast_sip_authenticator *auth)
  129. {
  130. if (registered_authenticator != auth) {
  131. ast_log(LOG_WARNING, "Trying to unregister authenticator %p but authenticator %p registered\n",
  132. auth, registered_authenticator);
  133. return;
  134. }
  135. registered_authenticator = NULL;
  136. ast_debug(1, "Unregistered SIP authenticator %p\n", auth);
  137. }
  138. int ast_sip_requires_authentication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
  139. {
  140. if (endpoint->allow_unauthenticated_options
  141. && !pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_options_method)) {
  142. ast_debug(3, "Skipping OPTIONS authentication due to endpoint configuration\n");
  143. return 0;
  144. }
  145. if (!registered_authenticator) {
  146. ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is not required\n");
  147. return 0;
  148. }
  149. return registered_authenticator->requires_authentication(endpoint, rdata);
  150. }
  151. enum ast_sip_check_auth_result ast_sip_check_authentication(struct ast_sip_endpoint *endpoint,
  152. pjsip_rx_data *rdata, pjsip_tx_data *tdata)
  153. {
  154. if (!registered_authenticator) {
  155. ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is successful\n");
  156. return AST_SIP_AUTHENTICATION_SUCCESS;
  157. }
  158. return registered_authenticator->check_authentication(endpoint, rdata, tdata);
  159. }
  160. static struct ast_sip_outbound_authenticator *registered_outbound_authenticator;
  161. int ast_sip_register_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
  162. {
  163. if (registered_outbound_authenticator) {
  164. ast_log(LOG_WARNING, "Outbound authenticator %p is already registered. Cannot register a new one\n", registered_outbound_authenticator);
  165. return -1;
  166. }
  167. registered_outbound_authenticator = auth;
  168. ast_debug(1, "Registered SIP outbound authenticator module %p\n", auth);
  169. return 0;
  170. }
  171. void ast_sip_unregister_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
  172. {
  173. if (registered_outbound_authenticator != auth) {
  174. ast_log(LOG_WARNING, "Trying to unregister outbound authenticator %p but outbound authenticator %p registered\n",
  175. auth, registered_outbound_authenticator);
  176. return;
  177. }
  178. registered_outbound_authenticator = NULL;
  179. ast_debug(1, "Unregistered SIP outbound authenticator %p\n", auth);
  180. }
  181. int ast_sip_create_request_with_auth(const struct ast_sip_auth_vector *auths, pjsip_rx_data *challenge,
  182. pjsip_tx_data *old_request, pjsip_tx_data **new_request)
  183. {
  184. if (!registered_outbound_authenticator) {
  185. ast_log(LOG_WARNING, "No SIP outbound authenticator registered. Cannot respond to authentication challenge\n");
  186. return -1;
  187. }
  188. return registered_outbound_authenticator->create_request_with_auth(auths, challenge, old_request, new_request);
  189. }
  190. struct endpoint_identifier_list {
  191. const char *name;
  192. unsigned int priority;
  193. struct ast_sip_endpoint_identifier *identifier;
  194. AST_RWLIST_ENTRY(endpoint_identifier_list) list;
  195. };
  196. static AST_RWLIST_HEAD_STATIC(endpoint_identifiers, endpoint_identifier_list);
  197. int ast_sip_register_endpoint_identifier_with_name(struct ast_sip_endpoint_identifier *identifier,
  198. const char *name)
  199. {
  200. char *prev, *current, *identifier_order;
  201. struct endpoint_identifier_list *iter, *id_list_item;
  202. SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  203. id_list_item = ast_calloc(1, sizeof(*id_list_item));
  204. if (!id_list_item) {
  205. ast_log(LOG_ERROR, "Unable to add endpoint identifier. Out of memory.\n");
  206. return -1;
  207. }
  208. id_list_item->identifier = identifier;
  209. id_list_item->name = name;
  210. ast_debug(1, "Register endpoint identifier %s(%p)\n", name ?: "", identifier);
  211. if (ast_strlen_zero(name)) {
  212. /* if an identifier has no name then place in front */
  213. AST_RWLIST_INSERT_HEAD(&endpoint_identifiers, id_list_item, list);
  214. return 0;
  215. }
  216. /* see if the name of the identifier is in the global endpoint_identifier_order list */
  217. identifier_order = prev = current = ast_sip_get_endpoint_identifier_order();
  218. if (ast_strlen_zero(identifier_order)) {
  219. id_list_item->priority = UINT_MAX;
  220. AST_RWLIST_INSERT_TAIL(&endpoint_identifiers, id_list_item, list);
  221. ast_free(identifier_order);
  222. return 0;
  223. }
  224. id_list_item->priority = 0;
  225. while ((current = strchr(current, ','))) {
  226. ++id_list_item->priority;
  227. if (!strncmp(prev, name, current - prev)
  228. && strlen(name) == current - prev) {
  229. break;
  230. }
  231. prev = ++current;
  232. }
  233. if (!current) {
  234. /* check to see if it is the only or last item */
  235. if (!strcmp(prev, name)) {
  236. ++id_list_item->priority;
  237. } else {
  238. id_list_item->priority = UINT_MAX;
  239. }
  240. }
  241. if (id_list_item->priority == UINT_MAX || AST_RWLIST_EMPTY(&endpoint_identifiers)) {
  242. /* if not in the endpoint_identifier_order list then consider it less in
  243. priority and add it to the end */
  244. AST_RWLIST_INSERT_TAIL(&endpoint_identifiers, id_list_item, list);
  245. ast_free(identifier_order);
  246. return 0;
  247. }
  248. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_identifiers, iter, list) {
  249. if (id_list_item->priority < iter->priority) {
  250. AST_RWLIST_INSERT_BEFORE_CURRENT(id_list_item, list);
  251. break;
  252. }
  253. if (!AST_RWLIST_NEXT(iter, list)) {
  254. AST_RWLIST_INSERT_AFTER(&endpoint_identifiers, iter, id_list_item, list);
  255. break;
  256. }
  257. }
  258. AST_RWLIST_TRAVERSE_SAFE_END;
  259. ast_free(identifier_order);
  260. return 0;
  261. }
  262. int ast_sip_register_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
  263. {
  264. return ast_sip_register_endpoint_identifier_with_name(identifier, NULL);
  265. }
  266. void ast_sip_unregister_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
  267. {
  268. struct endpoint_identifier_list *iter;
  269. SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  270. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_identifiers, iter, list) {
  271. if (iter->identifier == identifier) {
  272. AST_RWLIST_REMOVE_CURRENT(list);
  273. ast_free(iter);
  274. ast_debug(1, "Unregistered endpoint identifier %p\n", identifier);
  275. break;
  276. }
  277. }
  278. AST_RWLIST_TRAVERSE_SAFE_END;
  279. }
  280. struct ast_sip_endpoint *ast_sip_identify_endpoint(pjsip_rx_data *rdata)
  281. {
  282. struct endpoint_identifier_list *iter;
  283. struct ast_sip_endpoint *endpoint = NULL;
  284. SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
  285. AST_RWLIST_TRAVERSE(&endpoint_identifiers, iter, list) {
  286. ast_assert(iter->identifier->identify_endpoint != NULL);
  287. endpoint = iter->identifier->identify_endpoint(rdata);
  288. if (endpoint) {
  289. break;
  290. }
  291. }
  292. return endpoint;
  293. }
  294. char *ast_sip_rdata_get_header_value(pjsip_rx_data *rdata, const pj_str_t str)
  295. {
  296. pjsip_generic_string_hdr *hdr;
  297. pj_str_t hdr_val;
  298. hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str, NULL);
  299. if (!hdr) {
  300. return NULL;
  301. }
  302. pj_strdup_with_null(rdata->tp_info.pool, &hdr_val, &hdr->hvalue);
  303. return hdr_val.ptr;
  304. }
  305. static int do_cli_dump_endpt(void *v_a)
  306. {
  307. struct ast_cli_args *a = v_a;
  308. ast_pjproject_log_intercept_begin(a->fd);
  309. pjsip_endpt_dump(ast_sip_get_pjsip_endpoint(), a->argc == 4 ? PJ_TRUE : PJ_FALSE);
  310. ast_pjproject_log_intercept_end();
  311. return 0;
  312. }
  313. static char *cli_dump_endpt(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  314. {
  315. switch (cmd) {
  316. case CLI_INIT:
  317. #ifdef AST_DEVMODE
  318. e->command = "pjsip dump endpt [details]";
  319. e->usage =
  320. "Usage: pjsip dump endpt [details]\n"
  321. " Dump the res_pjsip endpt internals.\n"
  322. "\n"
  323. "Warning: PJPROJECT documents that the function used by this\n"
  324. "CLI command may cause a crash when asking for details because\n"
  325. "it tries to access all active memory pools.\n";
  326. #else
  327. /*
  328. * In non-developer mode we will not document or make easily accessible
  329. * the details option even though it is still available. The user has
  330. * to know it exists to use it. Presumably they would also be aware of
  331. * the potential crash warning.
  332. */
  333. e->command = "pjsip dump endpt";
  334. e->usage =
  335. "Usage: pjsip dump endpt\n"
  336. " Dump the res_pjsip endpt internals.\n";
  337. #endif /* AST_DEVMODE */
  338. return NULL;
  339. case CLI_GENERATE:
  340. return NULL;
  341. }
  342. if (4 < a->argc
  343. || (a->argc == 4 && strcasecmp(a->argv[3], "details"))) {
  344. return CLI_SHOWUSAGE;
  345. }
  346. ast_sip_push_task_wait_servant(NULL, do_cli_dump_endpt, a);
  347. return CLI_SUCCESS;
  348. }
  349. static char *cli_show_endpoint_identifiers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  350. {
  351. #define ENDPOINT_IDENTIFIER_FORMAT "%-20.20s\n"
  352. struct endpoint_identifier_list *iter;
  353. switch (cmd) {
  354. case CLI_INIT:
  355. e->command = "pjsip show identifiers";
  356. e->usage = "Usage: pjsip show identifiers\n"
  357. " List all registered endpoint identifiers\n";
  358. return NULL;
  359. case CLI_GENERATE:
  360. return NULL;
  361. }
  362. if (a->argc != 3) {
  363. return CLI_SHOWUSAGE;
  364. }
  365. ast_cli(a->fd, ENDPOINT_IDENTIFIER_FORMAT, "Identifier Names:");
  366. {
  367. SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
  368. AST_RWLIST_TRAVERSE(&endpoint_identifiers, iter, list) {
  369. ast_cli(a->fd, ENDPOINT_IDENTIFIER_FORMAT,
  370. iter->name ? iter->name : "name not specified");
  371. }
  372. }
  373. return CLI_SUCCESS;
  374. #undef ENDPOINT_IDENTIFIER_FORMAT
  375. }
  376. static char *cli_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  377. {
  378. struct ast_sip_cli_context context;
  379. switch (cmd) {
  380. case CLI_INIT:
  381. e->command = "pjsip show settings";
  382. e->usage = "Usage: pjsip show settings\n"
  383. " Show global and system configuration options\n";
  384. return NULL;
  385. case CLI_GENERATE:
  386. return NULL;
  387. }
  388. context.output_buffer = ast_str_create(256);
  389. if (!context.output_buffer) {
  390. ast_cli(a->fd, "Could not allocate output buffer.\n");
  391. return CLI_FAILURE;
  392. }
  393. if (sip_cli_print_global(&context) || sip_cli_print_system(&context)) {
  394. ast_free(context.output_buffer);
  395. ast_cli(a->fd, "Error retrieving settings.\n");
  396. return CLI_FAILURE;
  397. }
  398. ast_cli(a->fd, "%s", ast_str_buffer(context.output_buffer));
  399. ast_free(context.output_buffer);
  400. return CLI_SUCCESS;
  401. }
  402. static struct ast_cli_entry cli_commands[] = {
  403. AST_CLI_DEFINE(cli_dump_endpt, "Dump the res_pjsip endpt internals"),
  404. AST_CLI_DEFINE(cli_show_settings, "Show global and system configuration options"),
  405. AST_CLI_DEFINE(cli_show_endpoint_identifiers, "List registered endpoint identifiers")
  406. };
  407. AST_RWLIST_HEAD_STATIC(endpoint_formatters, ast_sip_endpoint_formatter);
  408. void ast_sip_register_endpoint_formatter(struct ast_sip_endpoint_formatter *obj)
  409. {
  410. SCOPED_LOCK(lock, &endpoint_formatters, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  411. AST_RWLIST_INSERT_TAIL(&endpoint_formatters, obj, next);
  412. }
  413. void ast_sip_unregister_endpoint_formatter(struct ast_sip_endpoint_formatter *obj)
  414. {
  415. struct ast_sip_endpoint_formatter *i;
  416. SCOPED_LOCK(lock, &endpoint_formatters, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  417. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_formatters, i, next) {
  418. if (i == obj) {
  419. AST_RWLIST_REMOVE_CURRENT(next);
  420. break;
  421. }
  422. }
  423. AST_RWLIST_TRAVERSE_SAFE_END;
  424. }
  425. int ast_sip_format_endpoint_ami(struct ast_sip_endpoint *endpoint,
  426. struct ast_sip_ami *ami, int *count)
  427. {
  428. int res = 0;
  429. struct ast_sip_endpoint_formatter *i;
  430. SCOPED_LOCK(lock, &endpoint_formatters, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
  431. *count = 0;
  432. AST_RWLIST_TRAVERSE(&endpoint_formatters, i, next) {
  433. if (i->format_ami && ((res = i->format_ami(endpoint, ami)) < 0)) {
  434. return res;
  435. }
  436. if (!res) {
  437. (*count)++;
  438. }
  439. }
  440. return 0;
  441. }
  442. pjsip_endpoint *ast_sip_get_pjsip_endpoint(void)
  443. {
  444. return ast_pjsip_endpoint;
  445. }
  446. int ast_sip_will_uri_survive_restart(pjsip_sip_uri *uri, struct ast_sip_endpoint *endpoint,
  447. pjsip_rx_data *rdata)
  448. {
  449. pj_str_t host_name;
  450. int result = 1;
  451. /* Determine if the contact cannot survive a restart/boot. */
  452. if (uri->port == rdata->pkt_info.src_port
  453. && !pj_strcmp(&uri->host,
  454. pj_cstr(&host_name, rdata->pkt_info.src_name))
  455. /* We have already checked if the URI scheme is sip: or sips: */
  456. && PJSIP_TRANSPORT_IS_RELIABLE(rdata->tp_info.transport)) {
  457. pj_str_t type_name;
  458. /* Determine the transport parameter value */
  459. if (!strcasecmp("WSS", rdata->tp_info.transport->type_name)) {
  460. /* WSS is special, as it needs to be ws. */
  461. pj_cstr(&type_name, "ws");
  462. } else {
  463. pj_cstr(&type_name, rdata->tp_info.transport->type_name);
  464. }
  465. if (!pj_stricmp(&uri->transport_param, &type_name)
  466. && (endpoint->nat.rewrite_contact
  467. /* Websockets are always rewritten */
  468. || !pj_stricmp(&uri->transport_param,
  469. pj_cstr(&type_name, "ws")))) {
  470. /*
  471. * The contact was rewritten to the reliable transport's
  472. * source address. Disconnecting the transport for any
  473. * reason invalidates the contact.
  474. */
  475. result = 0;
  476. }
  477. }
  478. return result;
  479. }
  480. pjsip_sip_uri *ast_sip_get_contact_sip_uri(pjsip_tx_data *tdata)
  481. {
  482. pjsip_contact_hdr *contact = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL);
  483. if (!contact || (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri))) {
  484. return NULL;
  485. }
  486. return pjsip_uri_get_uri(contact->uri);
  487. }
  488. /*! \brief Callback function for finding the transport the request is going out on */
  489. static int find_transport_state_in_use(void *obj, void *arg, int flags)
  490. {
  491. struct ast_sip_transport_state *transport_state = obj;
  492. struct ast_sip_request_transport_details *details = arg;
  493. /* If an explicit transport or factory matches then this is what is in use, if we are unavailable
  494. * to compare based on that we make sure that the type is the same and the source IP address/port are the same
  495. */
  496. if (transport_state && ((details->transport && details->transport == transport_state->transport) ||
  497. (details->factory && details->factory == transport_state->factory) ||
  498. ((details->type == transport_state->type) && (transport_state->factory) &&
  499. !pj_strcmp(&transport_state->factory->addr_name.host, &details->local_address) &&
  500. transport_state->factory->addr_name.port == details->local_port))) {
  501. return CMP_MATCH | CMP_STOP;
  502. }
  503. return 0;
  504. }
  505. struct ast_sip_transport_state *ast_sip_find_transport_state_in_use(struct ast_sip_request_transport_details *details) {
  506. RAII_VAR(struct ao2_container *, transport_states, NULL, ao2_cleanup);
  507. if (!(transport_states = ast_sip_get_transport_states())) {
  508. return NULL;
  509. }
  510. return ao2_callback(transport_states, 0, find_transport_state_in_use, details);
  511. }
  512. int ast_sip_rewrite_uri_to_local(pjsip_sip_uri *uri, pjsip_tx_data *tdata) {
  513. RAII_VAR(struct ast_sip_transport *, transport, NULL, ao2_cleanup);
  514. RAII_VAR(struct ast_sip_transport_state *, transport_state, NULL, ao2_cleanup);
  515. struct ast_sip_request_transport_details details = { 0, };
  516. pjsip_sip_uri *tmp_uri;
  517. pjsip_dialog *dlg;
  518. struct ast_sockaddr addr = { { 0, } };
  519. if ((tmp_uri = ast_sip_get_contact_sip_uri(tdata))) {
  520. pj_strdup(tdata->pool, &uri->host, &tmp_uri->host);
  521. uri->port = tmp_uri->port;
  522. } else if ((dlg = pjsip_tdata_get_dlg(tdata))
  523. && (tmp_uri = pjsip_uri_get_uri(dlg->local.info->uri))
  524. && (PJSIP_URI_SCHEME_IS_SIP(tmp_uri) || PJSIP_URI_SCHEME_IS_SIPS(tmp_uri))) {
  525. pj_strdup(tdata->pool, &uri->host, &tmp_uri->host);
  526. uri->port = tmp_uri->port;
  527. }
  528. if (ast_sip_set_request_transport_details(&details, tdata, 1)
  529. || !(transport_state = ast_sip_find_transport_state_in_use(&details))
  530. || !(transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_state->id))) {
  531. return 0;
  532. }
  533. if (transport_state->localnet) {
  534. ast_sockaddr_parse(&addr, tdata->tp_info.dst_name, PARSE_PORT_FORBID);
  535. ast_sockaddr_set_port(&addr, tdata->tp_info.dst_port);
  536. if (ast_sip_transport_is_local(transport_state, &addr)) {
  537. return 0;
  538. }
  539. }
  540. if (!ast_sockaddr_isnull(&transport_state->external_signaling_address)) {
  541. pj_strdup2(tdata->pool, &uri->host, ast_sockaddr_stringify_host(&transport_state->external_signaling_address));
  542. }
  543. if (transport->external_signaling_port) {
  544. uri->port = transport->external_signaling_port;
  545. }
  546. return 0;
  547. }
  548. int ast_sip_set_request_transport_details(struct ast_sip_request_transport_details *details, pjsip_tx_data *tdata,
  549. int use_ipv6) {
  550. pjsip_sip_uri *uri;
  551. pjsip_via_hdr *via;
  552. long transport_type;
  553. if (!details || !tdata) {
  554. return -1;
  555. }
  556. /* If IPv6 should be considered, un-set Bit 7 to make TCP6 equal to TCP and TLS6 equal to TLS */
  557. transport_type = use_ipv6 ? tdata->tp_info.transport->key.type & ~(PJSIP_TRANSPORT_IPV6)
  558. : tdata->tp_info.transport->key.type;
  559. if (tdata->tp_sel.type == PJSIP_TPSELECTOR_TRANSPORT) {
  560. details->transport = tdata->tp_sel.u.transport;
  561. } else if (tdata->tp_sel.type == PJSIP_TPSELECTOR_LISTENER) {
  562. details->factory = tdata->tp_sel.u.listener;
  563. } else if (transport_type == PJSIP_TRANSPORT_UDP || transport_type == PJSIP_TRANSPORT_UDP6) {
  564. /* Connectionless uses the same transport for all requests */
  565. details->type = AST_TRANSPORT_UDP;
  566. details->transport = tdata->tp_info.transport;
  567. } else {
  568. if (transport_type == PJSIP_TRANSPORT_TCP) {
  569. details->type = AST_TRANSPORT_TCP;
  570. } else if (transport_type == PJSIP_TRANSPORT_TLS) {
  571. details->type = AST_TRANSPORT_TLS;
  572. } else {
  573. /* Unknown transport type, we can't map. */
  574. return -1;
  575. }
  576. if ((uri = ast_sip_get_contact_sip_uri(tdata))) {
  577. details->local_address = uri->host;
  578. details->local_port = uri->port;
  579. } else if ((tdata->msg->type == PJSIP_REQUEST_MSG) &&
  580. (via = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL))) {
  581. details->local_address = via->sent_by.host;
  582. details->local_port = via->sent_by.port;
  583. } else {
  584. return -1;
  585. }
  586. if (!details->local_port) {
  587. details->local_port = (details->type == AST_TRANSPORT_TLS) ? 5061 : 5060;
  588. }
  589. }
  590. return 0;
  591. }
  592. int ast_sip_get_transport_name(const struct ast_sip_endpoint *endpoint,
  593. pjsip_sip_uri *sip_uri, char *buf, size_t buf_len)
  594. {
  595. char *host = NULL;
  596. static const pj_str_t x_name = { AST_SIP_X_AST_TXP, AST_SIP_X_AST_TXP_LEN };
  597. pjsip_param *x_transport;
  598. if (!ast_strlen_zero(endpoint->transport)) {
  599. ast_copy_string(buf, endpoint->transport, buf_len);
  600. return 0;
  601. }
  602. x_transport = pjsip_param_find(&sip_uri->other_param, &x_name);
  603. if (!x_transport) {
  604. return -1;
  605. }
  606. /* Only use x_transport if the uri host is an ip (4 or 6) address */
  607. host = ast_alloca(sip_uri->host.slen + 1);
  608. ast_copy_pj_str(host, &sip_uri->host, sip_uri->host.slen + 1);
  609. if (!ast_sockaddr_parse(NULL, host, PARSE_PORT_FORBID)) {
  610. return -1;
  611. }
  612. ast_copy_pj_str(buf, &x_transport->value, buf_len);
  613. return 0;
  614. }
  615. int ast_sip_dlg_set_transport(const struct ast_sip_endpoint *endpoint, pjsip_dialog *dlg,
  616. pjsip_tpselector *selector)
  617. {
  618. pjsip_sip_uri *uri;
  619. pjsip_tpselector sel = { .type = PJSIP_TPSELECTOR_NONE, };
  620. uri = pjsip_uri_get_uri(dlg->target);
  621. if (!selector) {
  622. selector = &sel;
  623. }
  624. ast_sip_set_tpselector_from_ep_or_uri(endpoint, uri, selector);
  625. pjsip_dlg_set_transport(dlg, selector);
  626. if (selector == &sel) {
  627. ast_sip_tpselector_unref(&sel);
  628. }
  629. return 0;
  630. }
  631. static int sip_dialog_create_from(pj_pool_t *pool, pj_str_t *from, const char *user,
  632. const char *domain, const pj_str_t *target, pjsip_tpselector *selector)
  633. {
  634. pj_str_t tmp, local_addr;
  635. pjsip_uri *uri;
  636. pjsip_sip_uri *sip_uri;
  637. pjsip_transport_type_e type;
  638. int local_port;
  639. char default_user[PJSIP_MAX_URL_SIZE];
  640. if (ast_strlen_zero(user)) {
  641. ast_sip_get_default_from_user(default_user, sizeof(default_user));
  642. user = default_user;
  643. }
  644. /* Parse the provided target URI so we can determine what transport it will end up using */
  645. pj_strdup_with_null(pool, &tmp, target);
  646. if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
  647. (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
  648. return -1;
  649. }
  650. sip_uri = pjsip_uri_get_uri(uri);
  651. /* Determine the transport type to use */
  652. type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
  653. if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
  654. if (type == PJSIP_TRANSPORT_UNSPECIFIED
  655. || !(pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE)) {
  656. type = PJSIP_TRANSPORT_TLS;
  657. }
  658. } else if (!sip_uri->transport_param.slen) {
  659. type = PJSIP_TRANSPORT_UDP;
  660. } else if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
  661. return -1;
  662. }
  663. /* If the host is IPv6 turn the transport into an IPv6 version */
  664. if (pj_strchr(&sip_uri->host, ':')) {
  665. type |= PJSIP_TRANSPORT_IPV6;
  666. }
  667. /* In multidomain scenario, username may contain @ with domain info */
  668. if (!ast_sip_get_disable_multi_domain() && strchr(user, '@')) {
  669. from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
  670. from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
  671. "<sip:%s%s%s>",
  672. user,
  673. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
  674. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
  675. return 0;
  676. }
  677. if (!ast_strlen_zero(domain)) {
  678. from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
  679. from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
  680. "<sip:%s@%s%s%s>",
  681. user,
  682. domain,
  683. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
  684. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
  685. return 0;
  686. }
  687. /* Get the local bound address for the transport that will be used when communicating with the provided URI */
  688. if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()), pool, type, selector,
  689. &local_addr, &local_port) != PJ_SUCCESS) {
  690. /* If no local address can be retrieved using the transport manager use the host one */
  691. pj_strdup(pool, &local_addr, pj_gethostname());
  692. local_port = pjsip_transport_get_default_port_for_type(PJSIP_TRANSPORT_UDP);
  693. }
  694. /* If IPv6 was specified in the transport, set the proper type */
  695. if (pj_strchr(&local_addr, ':')) {
  696. type |= PJSIP_TRANSPORT_IPV6;
  697. }
  698. from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
  699. from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
  700. "<sip:%s@%s%.*s%s:%d%s%s>",
  701. user,
  702. (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
  703. (int)local_addr.slen,
  704. local_addr.ptr,
  705. (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
  706. local_port,
  707. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
  708. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
  709. return 0;
  710. }
  711. int ast_sip_set_tpselector_from_transport(const struct ast_sip_transport *transport, pjsip_tpselector *selector)
  712. {
  713. int res = 0;
  714. struct ast_sip_transport_state *transport_state;
  715. transport_state = ast_sip_get_transport_state(ast_sorcery_object_get_id(transport));
  716. if (!transport_state) {
  717. ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport state for '%s'\n",
  718. ast_sorcery_object_get_id(transport));
  719. return -1;
  720. }
  721. /* Only flows maintain dynamic state which needs protection */
  722. if (transport_state->flow) {
  723. ao2_lock(transport_state);
  724. }
  725. if (transport_state->transport) {
  726. selector->type = PJSIP_TPSELECTOR_TRANSPORT;
  727. selector->u.transport = transport_state->transport;
  728. pjsip_transport_add_ref(selector->u.transport);
  729. } else if (transport_state->factory) {
  730. selector->type = PJSIP_TPSELECTOR_LISTENER;
  731. selector->u.listener = transport_state->factory;
  732. } else if (transport->type == AST_TRANSPORT_WS || transport->type == AST_TRANSPORT_WSS) {
  733. /* The WebSocket transport has no factory as it can not create outgoing connections, so
  734. * even if an endpoint is locked to a WebSocket transport we let the PJSIP logic
  735. * find the existing connection if available and use it.
  736. */
  737. } else if (transport->flow) {
  738. /* This is a child of another transport, so we need to establish a new connection */
  739. #ifdef HAVE_PJSIP_TRANSPORT_DISABLE_CONNECTION_REUSE
  740. selector->disable_connection_reuse = PJ_TRUE;
  741. #else
  742. ast_log(LOG_WARNING, "Connection reuse could not be disabled on transport '%s' as support is not available\n",
  743. ast_sorcery_object_get_id(transport));
  744. #endif
  745. } else {
  746. res = -1;
  747. }
  748. if (transport_state->flow) {
  749. ao2_unlock(transport_state);
  750. }
  751. ao2_ref(transport_state, -1);
  752. return res;
  753. }
  754. int ast_sip_set_tpselector_from_transport_name(const char *transport_name, pjsip_tpselector *selector)
  755. {
  756. RAII_VAR(struct ast_sip_transport *, transport, NULL, ao2_cleanup);
  757. if (ast_strlen_zero(transport_name)) {
  758. return 0;
  759. }
  760. transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_name);
  761. if (!transport) {
  762. ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport '%s'\n",
  763. transport_name);
  764. return -1;
  765. }
  766. return ast_sip_set_tpselector_from_transport(transport, selector);
  767. }
  768. int ast_sip_set_tpselector_from_ep_or_uri(const struct ast_sip_endpoint *endpoint,
  769. pjsip_sip_uri *sip_uri, pjsip_tpselector *selector)
  770. {
  771. char transport_name[128];
  772. if (ast_sip_get_transport_name(endpoint, sip_uri, transport_name, sizeof(transport_name))) {
  773. return 0;
  774. }
  775. return ast_sip_set_tpselector_from_transport_name(transport_name, selector);
  776. }
  777. void ast_sip_tpselector_unref(pjsip_tpselector *selector)
  778. {
  779. if (selector->type == PJSIP_TPSELECTOR_TRANSPORT && selector->u.transport) {
  780. pjsip_transport_dec_ref(selector->u.transport);
  781. }
  782. }
  783. void ast_sip_add_usereqphone(const struct ast_sip_endpoint *endpoint, pj_pool_t *pool, pjsip_uri *uri)
  784. {
  785. pjsip_sip_uri *sip_uri;
  786. int i = 0;
  787. static const pj_str_t STR_PHONE = { "phone", 5 };
  788. if (!endpoint || !endpoint->usereqphone || (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
  789. return;
  790. }
  791. sip_uri = pjsip_uri_get_uri(uri);
  792. if (!pj_strlen(&sip_uri->user)) {
  793. return;
  794. }
  795. if (pj_strbuf(&sip_uri->user)[0] == '+') {
  796. i = 1;
  797. }
  798. /* Test URI user against allowed characters in AST_DIGIT_ANY */
  799. for (; i < pj_strlen(&sip_uri->user); i++) {
  800. if (!strchr(AST_DIGIT_ANY, pj_strbuf(&sip_uri->user)[i])) {
  801. break;
  802. }
  803. }
  804. if (i < pj_strlen(&sip_uri->user)) {
  805. return;
  806. }
  807. sip_uri->user_param = STR_PHONE;
  808. }
  809. pjsip_dialog *ast_sip_create_dialog_uac(const struct ast_sip_endpoint *endpoint,
  810. const char *uri, const char *request_user)
  811. {
  812. char enclosed_uri[PJSIP_MAX_URL_SIZE];
  813. pj_str_t local_uri = { "sip:temp@temp", 13 }, remote_uri, target_uri;
  814. pj_status_t res;
  815. pjsip_dialog *dlg = NULL;
  816. const char *outbound_proxy = endpoint->outbound_proxy;
  817. pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
  818. static const pj_str_t HCONTACT = { "Contact", 7 };
  819. if (!ast_begins_with(uri, "<")) {
  820. snprintf(enclosed_uri, sizeof(enclosed_uri), "<%s>", uri);
  821. } else {
  822. snprintf(enclosed_uri, sizeof(enclosed_uri), "%s", uri);
  823. }
  824. pj_cstr(&remote_uri, enclosed_uri);
  825. pj_cstr(&target_uri, uri);
  826. res = pjsip_dlg_create_uac(pjsip_ua_instance(), &local_uri, NULL, &remote_uri, &target_uri, &dlg);
  827. if (res == PJ_SUCCESS && !(PJSIP_URI_SCHEME_IS_SIP(dlg->target) || PJSIP_URI_SCHEME_IS_SIPS(dlg->target))) {
  828. /* dlg->target is a pjsip_other_uri, but it's assumed to be a
  829. * pjsip_sip_uri below. Fail fast. */
  830. res = PJSIP_EINVALIDURI;
  831. pjsip_dlg_terminate(dlg);
  832. }
  833. if (res != PJ_SUCCESS) {
  834. if (res == PJSIP_EINVALIDURI) {
  835. ast_log(LOG_ERROR,
  836. "Endpoint '%s': Could not create dialog to invalid URI '%s'. Is endpoint registered and reachable?\n",
  837. ast_sorcery_object_get_id(endpoint), uri);
  838. }
  839. return NULL;
  840. }
  841. /* We have to temporarily bump up the sess_count here so the dialog is not prematurely destroyed */
  842. dlg->sess_count++;
  843. ast_sip_dlg_set_transport(endpoint, dlg, &selector);
  844. if (sip_dialog_create_from(dlg->pool, &local_uri, endpoint->fromuser, endpoint->fromdomain, &remote_uri, &selector)) {
  845. dlg->sess_count--;
  846. pjsip_dlg_terminate(dlg);
  847. ast_sip_tpselector_unref(&selector);
  848. return NULL;
  849. }
  850. ast_sip_tpselector_unref(&selector);
  851. /* Update the dialog with the new local URI, we do it afterwards so we can use the dialog pool for construction */
  852. pj_strdup_with_null(dlg->pool, &dlg->local.info_str, &local_uri);
  853. dlg->local.info->uri = pjsip_parse_uri(dlg->pool, dlg->local.info_str.ptr, dlg->local.info_str.slen, 0);
  854. if (!dlg->local.info->uri) {
  855. ast_log(LOG_ERROR,
  856. "Could not parse URI '%s' for endpoint '%s'\n",
  857. dlg->local.info_str.ptr, ast_sorcery_object_get_id(endpoint));
  858. dlg->sess_count--;
  859. pjsip_dlg_terminate(dlg);
  860. return NULL;
  861. }
  862. dlg->local.contact = pjsip_parse_hdr(dlg->pool, &HCONTACT, local_uri.ptr, local_uri.slen, NULL);
  863. if (!ast_strlen_zero(endpoint->contact_user)) {
  864. pjsip_sip_uri *sip_uri;
  865. sip_uri = pjsip_uri_get_uri(dlg->local.contact->uri);
  866. pj_strdup2(dlg->pool, &sip_uri->user, endpoint->contact_user);
  867. }
  868. /* If a request user has been specified and we are permitted to change it, do so */
  869. if (!ast_strlen_zero(request_user)) {
  870. pjsip_sip_uri *sip_uri;
  871. if (PJSIP_URI_SCHEME_IS_SIP(dlg->target) || PJSIP_URI_SCHEME_IS_SIPS(dlg->target)) {
  872. sip_uri = pjsip_uri_get_uri(dlg->target);
  873. pj_strdup2(dlg->pool, &sip_uri->user, request_user);
  874. }
  875. if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) || PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri)) {
  876. sip_uri = pjsip_uri_get_uri(dlg->remote.info->uri);
  877. pj_strdup2(dlg->pool, &sip_uri->user, request_user);
  878. }
  879. }
  880. /* Add the user=phone parameter if applicable */
  881. ast_sip_add_usereqphone(endpoint, dlg->pool, dlg->target);
  882. ast_sip_add_usereqphone(endpoint, dlg->pool, dlg->remote.info->uri);
  883. ast_sip_add_usereqphone(endpoint, dlg->pool, dlg->local.info->uri);
  884. if (!ast_strlen_zero(outbound_proxy)) {
  885. pjsip_route_hdr route_set, *route;
  886. static const pj_str_t ROUTE_HNAME = { "Route", 5 };
  887. pj_str_t tmp;
  888. pj_list_init(&route_set);
  889. pj_strdup2_with_null(dlg->pool, &tmp, outbound_proxy);
  890. if (!(route = pjsip_parse_hdr(dlg->pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
  891. ast_log(LOG_ERROR, "Could not create dialog to endpoint '%s' as outbound proxy URI '%s' is not valid\n",
  892. ast_sorcery_object_get_id(endpoint), outbound_proxy);
  893. dlg->sess_count--;
  894. pjsip_dlg_terminate(dlg);
  895. return NULL;
  896. }
  897. pj_list_insert_nodes_before(&route_set, route);
  898. pjsip_dlg_set_route_set(dlg, &route_set);
  899. }
  900. dlg->sess_count--;
  901. return dlg;
  902. }
  903. /*!
  904. * \brief Determine if a SIPS Contact header is required.
  905. *
  906. * This uses the guideline provided in RFC 3261 Section 12.1.1 to
  907. * determine if the Contact header must be a sips: URI.
  908. *
  909. * \param rdata The incoming dialog-starting request
  910. * \retval 0 SIPS not required
  911. * \retval 1 SIPS required
  912. */
  913. static int uas_use_sips_contact(pjsip_rx_data *rdata)
  914. {
  915. pjsip_rr_hdr *record_route;
  916. if (PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.msg->line.req.uri)) {
  917. return 1;
  918. }
  919. record_route = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_RECORD_ROUTE, NULL);
  920. if (record_route) {
  921. if (PJSIP_URI_SCHEME_IS_SIPS(&record_route->name_addr)) {
  922. return 1;
  923. }
  924. } else {
  925. pjsip_contact_hdr *contact;
  926. contact = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL);
  927. ast_assert(contact != NULL);
  928. if (PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
  929. return 1;
  930. }
  931. }
  932. return 0;
  933. }
  934. typedef pj_status_t (*create_dlg_uac)(pjsip_user_agent *ua, pjsip_rx_data *rdata,
  935. const pj_str_t *contact, pjsip_dialog **p_dlg);
  936. static pjsip_dialog *create_dialog_uas(const struct ast_sip_endpoint *endpoint,
  937. pjsip_rx_data *rdata, pj_status_t *status, create_dlg_uac create_fun)
  938. {
  939. pjsip_dialog *dlg;
  940. pj_str_t contact;
  941. pjsip_transport_type_e type = rdata->tp_info.transport->key.type;
  942. pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
  943. pjsip_transport *transport;
  944. pjsip_contact_hdr *contact_hdr;
  945. ast_assert(status != NULL);
  946. contact_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL);
  947. if (!contact_hdr || ast_sip_set_tpselector_from_ep_or_uri(endpoint, pjsip_uri_get_uri(contact_hdr->uri),
  948. &selector)) {
  949. return NULL;
  950. }
  951. transport = rdata->tp_info.transport;
  952. if (selector.type == PJSIP_TPSELECTOR_TRANSPORT) {
  953. transport = selector.u.transport;
  954. }
  955. type = transport->key.type;
  956. contact.ptr = pj_pool_alloc(rdata->tp_info.pool, PJSIP_MAX_URL_SIZE);
  957. contact.slen = pj_ansi_snprintf(contact.ptr, PJSIP_MAX_URL_SIZE,
  958. "<%s:%s%s%s%.*s%s:%d%s%s>",
  959. uas_use_sips_contact(rdata) ? "sips" : "sip",
  960. (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
  961. S_OR(endpoint->contact_user, ""),
  962. (!ast_strlen_zero(endpoint->contact_user)) ? "@" : "",
  963. (int)transport->local_name.host.slen,
  964. transport->local_name.host.ptr,
  965. (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
  966. transport->local_name.port,
  967. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
  968. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
  969. *status = create_fun(pjsip_ua_instance(), rdata, &contact, &dlg);
  970. if (*status != PJ_SUCCESS) {
  971. char err[PJ_ERR_MSG_SIZE];
  972. pj_strerror(*status, err, sizeof(err));
  973. ast_log(LOG_ERROR, "Could not create dialog with endpoint %s. %s\n",
  974. ast_sorcery_object_get_id(endpoint), err);
  975. ast_sip_tpselector_unref(&selector);
  976. return NULL;
  977. }
  978. dlg->sess_count++;
  979. pjsip_dlg_set_transport(dlg, &selector);
  980. dlg->sess_count--;
  981. ast_sip_tpselector_unref(&selector);
  982. return dlg;
  983. }
  984. pjsip_dialog *ast_sip_create_dialog_uas(const struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata, pj_status_t *status)
  985. {
  986. #ifdef HAVE_PJSIP_DLG_CREATE_UAS_AND_INC_LOCK
  987. pjsip_dialog *dlg;
  988. dlg = create_dialog_uas(endpoint, rdata, status, pjsip_dlg_create_uas_and_inc_lock);
  989. if (dlg) {
  990. pjsip_dlg_dec_lock(dlg);
  991. }
  992. return dlg;
  993. #else
  994. return create_dialog_uas(endpoint, rdata, status, pjsip_dlg_create_uas);
  995. #endif
  996. }
  997. pjsip_dialog *ast_sip_create_dialog_uas_locked(const struct ast_sip_endpoint *endpoint,
  998. pjsip_rx_data *rdata, pj_status_t *status)
  999. {
  1000. #ifdef HAVE_PJSIP_DLG_CREATE_UAS_AND_INC_LOCK
  1001. return create_dialog_uas(endpoint, rdata, status, pjsip_dlg_create_uas_and_inc_lock);
  1002. #else
  1003. /*
  1004. * This is put here in order to be compatible with older versions of pjproject.
  1005. * Best we can do in this case is immediately lock after getting the dialog.
  1006. * However, that does leave a "gap" between creating and locking.
  1007. */
  1008. pjsip_dialog *dlg;
  1009. dlg = create_dialog_uas(endpoint, rdata, status, pjsip_dlg_create_uas);
  1010. if (dlg) {
  1011. pjsip_dlg_inc_lock(dlg);
  1012. }
  1013. return dlg;
  1014. #endif
  1015. }
  1016. int ast_sip_create_rdata_with_contact(pjsip_rx_data *rdata, char *packet, const char *src_name, int src_port,
  1017. char *transport_type, const char *local_name, int local_port, const char *contact)
  1018. {
  1019. pj_str_t tmp;
  1020. /*
  1021. * Initialize the error list in case there is a parse error
  1022. * in the given packet.
  1023. */
  1024. pj_list_init(&rdata->msg_info.parse_err);
  1025. rdata->tp_info.transport = PJ_POOL_ZALLOC_T(rdata->tp_info.pool, pjsip_transport);
  1026. if (!rdata->tp_info.transport) {
  1027. return -1;
  1028. }
  1029. ast_copy_string(rdata->pkt_info.packet, packet, sizeof(rdata->pkt_info.packet));
  1030. ast_copy_string(rdata->pkt_info.src_name, src_name, sizeof(rdata->pkt_info.src_name));
  1031. rdata->pkt_info.src_port = src_port;
  1032. pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&tmp, src_name), &rdata->pkt_info.src_addr);
  1033. pj_sockaddr_set_port(&rdata->pkt_info.src_addr, src_port);
  1034. pjsip_parse_rdata(packet, strlen(packet), rdata);
  1035. if (!rdata->msg_info.msg || !pj_list_empty(&rdata->msg_info.parse_err)) {
  1036. return -1;
  1037. }
  1038. if (!ast_strlen_zero(contact)) {
  1039. pjsip_contact_hdr *contact_hdr;
  1040. contact_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL);
  1041. if (contact_hdr) {
  1042. contact_hdr->uri = pjsip_parse_uri(rdata->tp_info.pool, (char *)contact,
  1043. strlen(contact), PJSIP_PARSE_URI_AS_NAMEADDR);
  1044. if (!contact_hdr->uri) {
  1045. ast_log(LOG_WARNING, "Unable to parse contact URI from '%s'.\n", contact);
  1046. return -1;
  1047. }
  1048. }
  1049. }
  1050. pj_strdup2(rdata->tp_info.pool, &rdata->msg_info.via->recvd_param, rdata->pkt_info.src_name);
  1051. rdata->msg_info.via->rport_param = -1;
  1052. rdata->tp_info.transport->key.type = pjsip_transport_get_type_from_name(pj_cstr(&tmp, transport_type));
  1053. rdata->tp_info.transport->type_name = transport_type;
  1054. pj_strdup2(rdata->tp_info.pool, &rdata->tp_info.transport->local_name.host, local_name);
  1055. rdata->tp_info.transport->local_name.port = local_port;
  1056. return 0;
  1057. }
  1058. int ast_sip_create_rdata(pjsip_rx_data *rdata, char *packet, const char *src_name, int src_port,
  1059. char *transport_type, const char *local_name, int local_port)
  1060. {
  1061. return ast_sip_create_rdata_with_contact(rdata, packet, src_name, src_port, transport_type,
  1062. local_name, local_port, NULL);
  1063. }
  1064. /* PJSIP doesn't know about the INFO method, so we have to define it ourselves */
  1065. static const pjsip_method info_method = {PJSIP_OTHER_METHOD, {"INFO", 4} };
  1066. static const pjsip_method message_method = {PJSIP_OTHER_METHOD, {"MESSAGE", 7} };
  1067. static const pjsip_method refer_method = {PJSIP_OTHER_METHOD, {"REFER", 5} };
  1068. static struct {
  1069. const char *method;
  1070. const pjsip_method *pmethod;
  1071. } methods [] = {
  1072. { "INVITE", &pjsip_invite_method },
  1073. { "CANCEL", &pjsip_cancel_method },
  1074. { "ACK", &pjsip_ack_method },
  1075. { "BYE", &pjsip_bye_method },
  1076. { "REGISTER", &pjsip_register_method },
  1077. { "OPTIONS", &pjsip_options_method },
  1078. { "SUBSCRIBE", &pjsip_subscribe_method },
  1079. { "NOTIFY", &pjsip_notify_method },
  1080. { "PUBLISH", &pjsip_publish_method },
  1081. { "INFO", &info_method },
  1082. { "MESSAGE", &message_method },
  1083. { "REFER", &refer_method },
  1084. };
  1085. static const pjsip_method *get_pjsip_method(const char *method)
  1086. {
  1087. int i;
  1088. for (i = 0; i < ARRAY_LEN(methods); ++i) {
  1089. if (!strcmp(method, methods[i].method)) {
  1090. return methods[i].pmethod;
  1091. }
  1092. }
  1093. return NULL;
  1094. }
  1095. static int create_in_dialog_request(const pjsip_method *method, struct pjsip_dialog *dlg, pjsip_tx_data **tdata)
  1096. {
  1097. if (pjsip_dlg_create_request(dlg, method, -1, tdata) != PJ_SUCCESS) {
  1098. ast_log(LOG_WARNING, "Unable to create in-dialog request.\n");
  1099. return -1;
  1100. }
  1101. return 0;
  1102. }
  1103. static pj_bool_t supplement_on_rx_request(pjsip_rx_data *rdata);
  1104. static pjsip_module supplement_module = {
  1105. .name = { "Out of dialog supplement hook", 29 },
  1106. .id = -1,
  1107. .priority = PJSIP_MOD_PRIORITY_APPLICATION - 1,
  1108. .on_rx_request = supplement_on_rx_request,
  1109. };
  1110. static int create_out_of_dialog_request(const pjsip_method *method, struct ast_sip_endpoint *endpoint,
  1111. const char *uri, struct ast_sip_contact *provided_contact, pjsip_tx_data **tdata)
  1112. {
  1113. RAII_VAR(struct ast_sip_contact *, contact, ao2_bump(provided_contact), ao2_cleanup);
  1114. pj_str_t remote_uri;
  1115. pj_str_t from;
  1116. pj_pool_t *pool;
  1117. pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
  1118. pjsip_uri *sip_uri;
  1119. const char *fromuser;
  1120. if (ast_strlen_zero(uri)) {
  1121. if (!endpoint && (!contact || ast_strlen_zero(contact->uri))) {
  1122. ast_log(LOG_ERROR, "An endpoint and/or uri must be specified\n");
  1123. return -1;
  1124. }
  1125. if (!contact) {
  1126. contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
  1127. }
  1128. if (!contact || ast_strlen_zero(contact->uri)) {
  1129. ast_log(LOG_WARNING, "Unable to retrieve contact for endpoint %s\n",
  1130. ast_sorcery_object_get_id(endpoint));
  1131. return -1;
  1132. }
  1133. pj_cstr(&remote_uri, contact->uri);
  1134. } else {
  1135. pj_cstr(&remote_uri, uri);
  1136. }
  1137. pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Outbound request", 256, 256);
  1138. if (!pool) {
  1139. ast_log(LOG_ERROR, "Unable to create PJLIB memory pool\n");
  1140. return -1;
  1141. }
  1142. sip_uri = pjsip_parse_uri(pool, remote_uri.ptr, remote_uri.slen, 0);
  1143. if (!sip_uri || (!PJSIP_URI_SCHEME_IS_SIP(sip_uri) && !PJSIP_URI_SCHEME_IS_SIPS(sip_uri))) {
  1144. ast_log(LOG_ERROR, "Unable to create outbound %.*s request to endpoint %s as URI '%s' is not valid\n",
  1145. (int) pj_strlen(&method->name), pj_strbuf(&method->name),
  1146. endpoint ? ast_sorcery_object_get_id(endpoint) : "<none>",
  1147. pj_strbuf(&remote_uri));
  1148. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1149. return -1;
  1150. }
  1151. ast_sip_set_tpselector_from_ep_or_uri(endpoint, pjsip_uri_get_uri(sip_uri), &selector);
  1152. fromuser = endpoint ? (!ast_strlen_zero(endpoint->fromuser) ? endpoint->fromuser : ast_sorcery_object_get_id(endpoint)) : NULL;
  1153. if (sip_dialog_create_from(pool, &from, fromuser,
  1154. endpoint ? endpoint->fromdomain : NULL, &remote_uri, &selector)) {
  1155. ast_log(LOG_ERROR, "Unable to create From header for %.*s request to endpoint %s\n",
  1156. (int) pj_strlen(&method->name), pj_strbuf(&method->name),
  1157. endpoint ? ast_sorcery_object_get_id(endpoint) : "<none>");
  1158. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1159. ast_sip_tpselector_unref(&selector);
  1160. return -1;
  1161. }
  1162. if (pjsip_endpt_create_request(ast_sip_get_pjsip_endpoint(), method, &remote_uri,
  1163. &from, &remote_uri, &from, NULL, -1, NULL, tdata) != PJ_SUCCESS) {
  1164. ast_log(LOG_ERROR, "Unable to create outbound %.*s request to endpoint %s\n",
  1165. (int) pj_strlen(&method->name), pj_strbuf(&method->name),
  1166. endpoint ? ast_sorcery_object_get_id(endpoint) : "<none>");
  1167. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1168. ast_sip_tpselector_unref(&selector);
  1169. return -1;
  1170. }
  1171. pjsip_tx_data_set_transport(*tdata, &selector);
  1172. ast_sip_tpselector_unref(&selector);
  1173. if (endpoint && !ast_strlen_zero(endpoint->contact_user)){
  1174. pjsip_contact_hdr *contact_hdr;
  1175. pjsip_sip_uri *contact_uri;
  1176. static const pj_str_t HCONTACT = { "Contact", 7 };
  1177. static const pj_str_t HCONTACTSHORT = { "m", 1 };
  1178. contact_hdr = pjsip_msg_find_hdr_by_names((*tdata)->msg, &HCONTACT, &HCONTACTSHORT, NULL);
  1179. if (contact_hdr) {
  1180. contact_uri = pjsip_uri_get_uri(contact_hdr->uri);
  1181. pj_strdup2((*tdata)->pool, &contact_uri->user, endpoint->contact_user);
  1182. }
  1183. }
  1184. /* Add the user=phone parameter if applicable */
  1185. ast_sip_add_usereqphone(endpoint, (*tdata)->pool, (*tdata)->msg->line.req.uri);
  1186. /* If an outbound proxy is specified on the endpoint apply it to this request */
  1187. if (endpoint && !ast_strlen_zero(endpoint->outbound_proxy) &&
  1188. ast_sip_set_outbound_proxy((*tdata), endpoint->outbound_proxy)) {
  1189. ast_log(LOG_ERROR, "Unable to apply outbound proxy on request %.*s to endpoint %s as outbound proxy URI '%s' is not valid\n",
  1190. (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint),
  1191. endpoint->outbound_proxy);
  1192. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1193. return -1;
  1194. }
  1195. ast_sip_mod_data_set((*tdata)->pool, (*tdata)->mod_data, supplement_module.id, MOD_DATA_CONTACT, ao2_bump(contact));
  1196. /* We can release this pool since request creation copied all the necessary
  1197. * data into the outbound request's pool
  1198. */
  1199. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1200. return 0;
  1201. }
  1202. int ast_sip_create_request(const char *method, struct pjsip_dialog *dlg,
  1203. struct ast_sip_endpoint *endpoint, const char *uri,
  1204. struct ast_sip_contact *contact, pjsip_tx_data **tdata)
  1205. {
  1206. const pjsip_method *pmethod = get_pjsip_method(method);
  1207. if (!pmethod) {
  1208. ast_log(LOG_WARNING, "Unknown method '%s'. Cannot send request\n", method);
  1209. return -1;
  1210. }
  1211. if (dlg) {
  1212. return create_in_dialog_request(pmethod, dlg, tdata);
  1213. } else {
  1214. ast_assert(endpoint != NULL);
  1215. return create_out_of_dialog_request(pmethod, endpoint, uri, contact, tdata);
  1216. }
  1217. }
  1218. AST_RWLIST_HEAD_STATIC(supplements, ast_sip_supplement);
  1219. void ast_sip_register_supplement(struct ast_sip_supplement *supplement)
  1220. {
  1221. struct ast_sip_supplement *iter;
  1222. int inserted = 0;
  1223. SCOPED_LOCK(lock, &supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  1224. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&supplements, iter, next) {
  1225. if (iter->priority > supplement->priority) {
  1226. AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
  1227. inserted = 1;
  1228. break;
  1229. }
  1230. }
  1231. AST_RWLIST_TRAVERSE_SAFE_END;
  1232. if (!inserted) {
  1233. AST_RWLIST_INSERT_TAIL(&supplements, supplement, next);
  1234. }
  1235. }
  1236. void ast_sip_unregister_supplement(struct ast_sip_supplement *supplement)
  1237. {
  1238. struct ast_sip_supplement *iter;
  1239. SCOPED_LOCK(lock, &supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
  1240. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&supplements, iter, next) {
  1241. if (supplement == iter) {
  1242. AST_RWLIST_REMOVE_CURRENT(next);
  1243. break;
  1244. }
  1245. }
  1246. AST_RWLIST_TRAVERSE_SAFE_END;
  1247. }
  1248. static int send_in_dialog_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg)
  1249. {
  1250. if (pjsip_dlg_send_request(dlg, tdata, -1, NULL) != PJ_SUCCESS) {
  1251. ast_log(LOG_WARNING, "Unable to send in-dialog request.\n");
  1252. return -1;
  1253. }
  1254. return 0;
  1255. }
  1256. static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
  1257. {
  1258. pj_str_t method;
  1259. if (ast_strlen_zero(supplement_method)) {
  1260. return PJ_TRUE;
  1261. }
  1262. pj_cstr(&method, supplement_method);
  1263. return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
  1264. }
  1265. #define TIMER_INACTIVE 0
  1266. #define TIMEOUT_TIMER2 5
  1267. /*! \brief Structure to hold information about an outbound request */
  1268. struct send_request_data {
  1269. /*! The endpoint associated with this request */
  1270. struct ast_sip_endpoint *endpoint;
  1271. /*! Information to be provided to the callback upon receipt of a response */
  1272. void *token;
  1273. /*! The callback to be called upon receipt of a response */
  1274. void (*callback)(void *token, pjsip_event *e);
  1275. /*! Number of challenges received. */
  1276. unsigned int challenge_count;
  1277. };
  1278. static void send_request_data_destroy(void *obj)
  1279. {
  1280. struct send_request_data *req_data = obj;
  1281. ao2_cleanup(req_data->endpoint);
  1282. }
  1283. static struct send_request_data *send_request_data_alloc(struct ast_sip_endpoint *endpoint,
  1284. void *token, void (*callback)(void *token, pjsip_event *e))
  1285. {
  1286. struct send_request_data *req_data;
  1287. req_data = ao2_alloc_options(sizeof(*req_data), send_request_data_destroy,
  1288. AO2_ALLOC_OPT_LOCK_NOLOCK);
  1289. if (!req_data) {
  1290. return NULL;
  1291. }
  1292. req_data->endpoint = ao2_bump(endpoint);
  1293. req_data->token = token;
  1294. req_data->callback = callback;
  1295. return req_data;
  1296. }
  1297. struct send_request_wrapper {
  1298. /*! Information to be provided to the callback upon receipt of a response */
  1299. void *token;
  1300. /*! The callback to be called upon receipt of a response */
  1301. void (*callback)(void *token, pjsip_event *e);
  1302. /*! Non-zero when the callback is called. */
  1303. unsigned int cb_called;
  1304. /*! Non-zero if endpt_send_request_cb() was called. */
  1305. unsigned int send_cb_called;
  1306. /*! Timeout timer. */
  1307. pj_timer_entry *timeout_timer;
  1308. /*! Original timeout. */
  1309. pj_int32_t timeout;
  1310. /*! The transmit data. */
  1311. pjsip_tx_data *tdata;
  1312. };
  1313. /*! \internal This function gets called by pjsip when the transaction ends,
  1314. * even if it timed out. The lock prevents a race condition if both the pjsip
  1315. * transaction timer and our own timer expire simultaneously.
  1316. */
  1317. static void endpt_send_request_cb(void *token, pjsip_event *e)
  1318. {
  1319. struct send_request_wrapper *req_wrapper = token;
  1320. unsigned int cb_called;
  1321. /*
  1322. * Needed because we cannot otherwise tell if this callback was
  1323. * called when pjsip_endpt_send_request() returns error.
  1324. */
  1325. req_wrapper->send_cb_called = 1;
  1326. if (e->body.tsx_state.type == PJSIP_EVENT_TIMER) {
  1327. ast_debug(2, "%p: PJSIP tsx timer expired\n", req_wrapper);
  1328. if (req_wrapper->timeout_timer
  1329. && req_wrapper->timeout_timer->id != TIMEOUT_TIMER2) {
  1330. ast_debug(3, "%p: Timeout already handled\n", req_wrapper);
  1331. ao2_ref(req_wrapper, -1);
  1332. return;
  1333. }
  1334. } else {
  1335. ast_debug(2, "%p: PJSIP tsx response received\n", req_wrapper);
  1336. }
  1337. ao2_lock(req_wrapper);
  1338. /* It's possible that our own timer was already processing while
  1339. * we were waiting on the lock so check the timer id. If it's
  1340. * still TIMER2 then we still need to process.
  1341. */
  1342. if (req_wrapper->timeout_timer
  1343. && req_wrapper->timeout_timer->id == TIMEOUT_TIMER2) {
  1344. int timers_cancelled = 0;
  1345. ast_debug(3, "%p: Cancelling timer\n", req_wrapper);
  1346. timers_cancelled = pj_timer_heap_cancel_if_active(
  1347. pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
  1348. req_wrapper->timeout_timer, TIMER_INACTIVE);
  1349. if (timers_cancelled > 0) {
  1350. /* If the timer was cancelled the callback will never run so
  1351. * clean up its reference to the wrapper.
  1352. */
  1353. ast_debug(3, "%p: Timer cancelled\n", req_wrapper);
  1354. ao2_ref(req_wrapper, -1);
  1355. } else {
  1356. /*
  1357. * If it wasn't cancelled, it MAY be in the callback already
  1358. * waiting on the lock. When we release the lock, it will
  1359. * now know not to proceed.
  1360. */
  1361. ast_debug(3, "%p: Timer already expired\n", req_wrapper);
  1362. }
  1363. }
  1364. cb_called = req_wrapper->cb_called;
  1365. req_wrapper->cb_called = 1;
  1366. ao2_unlock(req_wrapper);
  1367. /* It's possible that our own timer expired and called the callbacks
  1368. * so no need to call them again.
  1369. */
  1370. if (!cb_called && req_wrapper->callback) {
  1371. req_wrapper->callback(req_wrapper->token, e);
  1372. ast_debug(2, "%p: Callbacks executed\n", req_wrapper);
  1373. }
  1374. ao2_ref(req_wrapper, -1);
  1375. }
  1376. /*! \internal This function gets called by our own timer when it expires.
  1377. * If the timer is cancelled however, the function does NOT get called.
  1378. * The lock prevents a race condition if both the pjsip transaction timer
  1379. * and our own timer expire simultaneously.
  1380. */
  1381. static void send_request_timer_callback(pj_timer_heap_t *theap, pj_timer_entry *entry)
  1382. {
  1383. struct send_request_wrapper *req_wrapper = entry->user_data;
  1384. unsigned int cb_called;
  1385. ast_debug(2, "%p: Internal tsx timer expired after %d msec\n",
  1386. req_wrapper, req_wrapper->timeout);
  1387. ao2_lock(req_wrapper);
  1388. /*
  1389. * If the id is not TIMEOUT_TIMER2 then the timer was cancelled
  1390. * before we got the lock or it was already handled so just clean up.
  1391. */
  1392. if (entry->id != TIMEOUT_TIMER2) {
  1393. ao2_unlock(req_wrapper);
  1394. ast_debug(3, "%p: Timeout already handled\n", req_wrapper);
  1395. ao2_ref(req_wrapper, -1);
  1396. return;
  1397. }
  1398. entry->id = TIMER_INACTIVE;
  1399. ast_debug(3, "%p: Timer handled here\n", req_wrapper);
  1400. cb_called = req_wrapper->cb_called;
  1401. req_wrapper->cb_called = 1;
  1402. ao2_unlock(req_wrapper);
  1403. if (!cb_called && req_wrapper->callback) {
  1404. pjsip_event event;
  1405. PJSIP_EVENT_INIT_TX_MSG(event, req_wrapper->tdata);
  1406. event.body.tsx_state.type = PJSIP_EVENT_TIMER;
  1407. req_wrapper->callback(req_wrapper->token, &event);
  1408. ast_debug(2, "%p: Callbacks executed\n", req_wrapper);
  1409. }
  1410. ao2_ref(req_wrapper, -1);
  1411. }
  1412. static void send_request_wrapper_destructor(void *obj)
  1413. {
  1414. struct send_request_wrapper *req_wrapper = obj;
  1415. pjsip_tx_data_dec_ref(req_wrapper->tdata);
  1416. ast_debug(2, "%p: wrapper destroyed\n", req_wrapper);
  1417. }
  1418. static pj_status_t endpt_send_request(struct ast_sip_endpoint *endpoint,
  1419. pjsip_tx_data *tdata, pj_int32_t timeout, void *token, pjsip_endpt_send_callback cb)
  1420. {
  1421. struct send_request_wrapper *req_wrapper;
  1422. pj_status_t ret_val;
  1423. pjsip_endpoint *endpt = ast_sip_get_pjsip_endpoint();
  1424. if (!cb && token) {
  1425. /* Silly. Without a callback we cannot do anything with token. */
  1426. pjsip_tx_data_dec_ref(tdata);
  1427. return PJ_EINVAL;
  1428. }
  1429. /* Create wrapper to detect if the callback was actually called on an error. */
  1430. req_wrapper = ao2_alloc(sizeof(*req_wrapper), send_request_wrapper_destructor);
  1431. if (!req_wrapper) {
  1432. pjsip_tx_data_dec_ref(tdata);
  1433. return PJ_ENOMEM;
  1434. }
  1435. ast_debug(2, "%p: Wrapper created\n", req_wrapper);
  1436. req_wrapper->token = token;
  1437. req_wrapper->callback = cb;
  1438. req_wrapper->timeout = timeout;
  1439. req_wrapper->timeout_timer = NULL;
  1440. req_wrapper->tdata = tdata;
  1441. /* Add a reference to tdata. The wrapper destructor cleans it up. */
  1442. pjsip_tx_data_add_ref(tdata);
  1443. if (timeout > 0) {
  1444. pj_time_val timeout_timer_val = { timeout / 1000, timeout % 1000 };
  1445. req_wrapper->timeout_timer = PJ_POOL_ALLOC_T(tdata->pool, pj_timer_entry);
  1446. ast_debug(2, "%p: Set timer to %d msec\n", req_wrapper, timeout);
  1447. pj_timer_entry_init(req_wrapper->timeout_timer, TIMEOUT_TIMER2,
  1448. req_wrapper, send_request_timer_callback);
  1449. /* We need to insure that the wrapper and tdata are available if/when the
  1450. * timer callback is executed.
  1451. */
  1452. ao2_ref(req_wrapper, +1);
  1453. ret_val = pj_timer_heap_schedule(pjsip_endpt_get_timer_heap(endpt),
  1454. req_wrapper->timeout_timer, &timeout_timer_val);
  1455. if (ret_val != PJ_SUCCESS) {
  1456. ast_log(LOG_ERROR,
  1457. "Failed to set timer. Not sending %.*s request to endpoint %s.\n",
  1458. (int) pj_strlen(&tdata->msg->line.req.method.name),
  1459. pj_strbuf(&tdata->msg->line.req.method.name),
  1460. endpoint ? ast_sorcery_object_get_id(endpoint) : "<unknown>");
  1461. ao2_t_ref(req_wrapper, -2, "Drop timer and routine ref");
  1462. pjsip_tx_data_dec_ref(tdata);
  1463. return ret_val;
  1464. }
  1465. }
  1466. /* We need to insure that the wrapper and tdata are available when the
  1467. * transaction callback is executed.
  1468. */
  1469. ao2_ref(req_wrapper, +1);
  1470. ret_val = pjsip_endpt_send_request(endpt, tdata, -1, req_wrapper, endpt_send_request_cb);
  1471. if (ret_val != PJ_SUCCESS) {
  1472. char errmsg[PJ_ERR_MSG_SIZE];
  1473. if (!req_wrapper->send_cb_called) {
  1474. /* endpt_send_request_cb is not expected to ever be called now. */
  1475. ao2_ref(req_wrapper, -1);
  1476. }
  1477. /* Complain of failure to send the request. */
  1478. pj_strerror(ret_val, errmsg, sizeof(errmsg));
  1479. ast_log(LOG_ERROR, "Error %d '%s' sending %.*s request to endpoint %s\n",
  1480. (int) ret_val, errmsg, (int) pj_strlen(&tdata->msg->line.req.method.name),
  1481. pj_strbuf(&tdata->msg->line.req.method.name),
  1482. endpoint ? ast_sorcery_object_get_id(endpoint) : "<unknown>");
  1483. if (timeout > 0) {
  1484. int timers_cancelled;
  1485. ao2_lock(req_wrapper);
  1486. timers_cancelled = pj_timer_heap_cancel_if_active(
  1487. pjsip_endpt_get_timer_heap(endpt),
  1488. req_wrapper->timeout_timer, TIMER_INACTIVE);
  1489. if (timers_cancelled > 0) {
  1490. ao2_ref(req_wrapper, -1);
  1491. }
  1492. /* Was the callback called? */
  1493. if (req_wrapper->cb_called) {
  1494. /*
  1495. * Yes so we cannot report any error. The callback
  1496. * has already freed any resources associated with
  1497. * token.
  1498. */
  1499. ret_val = PJ_SUCCESS;
  1500. } else {
  1501. /*
  1502. * No so we claim it is called so our caller can free
  1503. * any resources associated with token because of
  1504. * failure.
  1505. */
  1506. req_wrapper->cb_called = 1;
  1507. }
  1508. ao2_unlock(req_wrapper);
  1509. } else if (req_wrapper->cb_called) {
  1510. /*
  1511. * We cannot report any error. The callback has
  1512. * already freed any resources associated with
  1513. * token.
  1514. */
  1515. ret_val = PJ_SUCCESS;
  1516. }
  1517. }
  1518. ao2_ref(req_wrapper, -1);
  1519. return ret_val;
  1520. }
  1521. int ast_sip_failover_request(pjsip_tx_data *tdata)
  1522. {
  1523. pjsip_via_hdr *via;
  1524. if (!tdata || !tdata->dest_info.addr.count
  1525. || (tdata->dest_info.cur_addr == tdata->dest_info.addr.count - 1)) {
  1526. /* No more addresses to try */
  1527. return 0;
  1528. }
  1529. /* Try next address */
  1530. ++tdata->dest_info.cur_addr;
  1531. via = (pjsip_via_hdr*)pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL);
  1532. via->branch_param.slen = 0;
  1533. pjsip_tx_data_invalidate_msg(tdata);
  1534. return 1;
  1535. }
  1536. static void send_request_cb(void *token, pjsip_event *e);
  1537. static int check_request_status(struct send_request_data *req_data, pjsip_event *e)
  1538. {
  1539. struct ast_sip_endpoint *endpoint;
  1540. pjsip_transaction *tsx;
  1541. pjsip_tx_data *tdata;
  1542. int res = 0;
  1543. if (!(endpoint = ao2_bump(req_data->endpoint))) {
  1544. return 0;
  1545. }
  1546. tsx = e->body.tsx_state.tsx;
  1547. switch (tsx->status_code) {
  1548. case 401:
  1549. case 407:
  1550. /* Resend the request with a challenge response if we are challenged. */
  1551. res = ++req_data->challenge_count < MAX_RX_CHALLENGES /* Not in a challenge loop */
  1552. && !ast_sip_create_request_with_auth(&endpoint->outbound_auths,
  1553. e->body.tsx_state.src.rdata, tsx->last_tx, &tdata);
  1554. break;
  1555. case 408:
  1556. case 503:
  1557. if ((res = ast_sip_failover_request(tsx->last_tx))) {
  1558. tdata = tsx->last_tx;
  1559. /*
  1560. * Bump the ref since it will be on a new transaction and
  1561. * we don't want it to go away along with the old transaction.
  1562. */
  1563. pjsip_tx_data_add_ref(tdata);
  1564. }
  1565. break;
  1566. }
  1567. if (res) {
  1568. res = endpt_send_request(endpoint, tdata, -1,
  1569. req_data, send_request_cb) == PJ_SUCCESS;
  1570. }
  1571. ao2_ref(endpoint, -1);
  1572. return res;
  1573. }
  1574. static void send_request_cb(void *token, pjsip_event *e)
  1575. {
  1576. struct send_request_data *req_data = token;
  1577. pjsip_rx_data *challenge;
  1578. struct ast_sip_supplement *supplement;
  1579. if (e->type == PJSIP_EVENT_TSX_STATE) {
  1580. switch(e->body.tsx_state.type) {
  1581. case PJSIP_EVENT_TRANSPORT_ERROR:
  1582. case PJSIP_EVENT_TIMER:
  1583. /*
  1584. * Check the request status on transport error or timeout. A transport
  1585. * error can occur when a TCP socket closes and that can be the result
  1586. * of a 503. Also we may need to failover on a timeout (408).
  1587. */
  1588. if (check_request_status(req_data, e)) {
  1589. return;
  1590. }
  1591. break;
  1592. case PJSIP_EVENT_RX_MSG:
  1593. challenge = e->body.tsx_state.src.rdata;
  1594. /*
  1595. * Call any supplements that want to know about a response
  1596. * with any received data.
  1597. */
  1598. AST_RWLIST_RDLOCK(&supplements);
  1599. AST_LIST_TRAVERSE(&supplements, supplement, next) {
  1600. if (supplement->incoming_response
  1601. && does_method_match(&challenge->msg_info.cseq->method.name,
  1602. supplement->method)) {
  1603. supplement->incoming_response(req_data->endpoint, challenge);
  1604. }
  1605. }
  1606. AST_RWLIST_UNLOCK(&supplements);
  1607. if (check_request_status(req_data, e)) {
  1608. /*
  1609. * Request with challenge response or failover sent.
  1610. * Passed our req_data ref to the new request.
  1611. */
  1612. return;
  1613. }
  1614. break;
  1615. default:
  1616. ast_log(LOG_ERROR, "Unexpected PJSIP event %u\n", e->body.tsx_state.type);
  1617. break;
  1618. }
  1619. }
  1620. if (req_data->callback) {
  1621. req_data->callback(req_data->token, e);
  1622. }
  1623. ao2_ref(req_data, -1);
  1624. }
  1625. int ast_sip_send_out_of_dialog_request(pjsip_tx_data *tdata,
  1626. struct ast_sip_endpoint *endpoint, int timeout, void *token,
  1627. void (*callback)(void *token, pjsip_event *e))
  1628. {
  1629. struct ast_sip_supplement *supplement;
  1630. struct send_request_data *req_data;
  1631. struct ast_sip_contact *contact;
  1632. req_data = send_request_data_alloc(endpoint, token, callback);
  1633. if (!req_data) {
  1634. pjsip_tx_data_dec_ref(tdata);
  1635. return -1;
  1636. }
  1637. if (endpoint) {
  1638. ast_sip_message_apply_transport(endpoint->transport, tdata);
  1639. }
  1640. contact = ast_sip_mod_data_get(tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT);
  1641. AST_RWLIST_RDLOCK(&supplements);
  1642. AST_LIST_TRAVERSE(&supplements, supplement, next) {
  1643. if (supplement->outgoing_request
  1644. && does_method_match(&tdata->msg->line.req.method.name, supplement->method)) {
  1645. supplement->outgoing_request(endpoint, contact, tdata);
  1646. }
  1647. }
  1648. AST_RWLIST_UNLOCK(&supplements);
  1649. ast_sip_mod_data_set(tdata->pool, tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT, NULL);
  1650. ao2_cleanup(contact);
  1651. if (endpt_send_request(endpoint, tdata, timeout, req_data, send_request_cb)
  1652. != PJ_SUCCESS) {
  1653. ao2_cleanup(req_data);
  1654. return -1;
  1655. }
  1656. return 0;
  1657. }
  1658. int ast_sip_send_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg,
  1659. struct ast_sip_endpoint *endpoint, void *token,
  1660. void (*callback)(void *token, pjsip_event *e))
  1661. {
  1662. ast_assert(tdata->msg->type == PJSIP_REQUEST_MSG);
  1663. if (dlg) {
  1664. return send_in_dialog_request(tdata, dlg);
  1665. } else {
  1666. return ast_sip_send_out_of_dialog_request(tdata, endpoint, -1, token, callback);
  1667. }
  1668. }
  1669. int ast_sip_set_outbound_proxy(pjsip_tx_data *tdata, const char *proxy)
  1670. {
  1671. pjsip_route_hdr *route;
  1672. static const pj_str_t ROUTE_HNAME = { "Route", 5 };
  1673. pj_str_t tmp;
  1674. pj_strdup2_with_null(tdata->pool, &tmp, proxy);
  1675. if (!(route = pjsip_parse_hdr(tdata->pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
  1676. return -1;
  1677. }
  1678. pj_list_insert_nodes_before(&tdata->msg->hdr, (pjsip_hdr*)route);
  1679. return 0;
  1680. }
  1681. int ast_sip_add_header(pjsip_tx_data *tdata, const char *name, const char *value)
  1682. {
  1683. pj_str_t hdr_name;
  1684. pj_str_t hdr_value;
  1685. pjsip_generic_string_hdr *hdr;
  1686. pj_cstr(&hdr_name, name);
  1687. pj_cstr(&hdr_value, value);
  1688. hdr = pjsip_generic_string_hdr_create(tdata->pool, &hdr_name, &hdr_value);
  1689. pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) hdr);
  1690. return 0;
  1691. }
  1692. pjsip_generic_string_hdr *ast_sip_add_header2(pjsip_tx_data *tdata,
  1693. const char *name, const char *value)
  1694. {
  1695. pj_str_t hdr_name;
  1696. pj_str_t hdr_value;
  1697. pjsip_generic_string_hdr *hdr;
  1698. pj_cstr(&hdr_name, name);
  1699. pj_cstr(&hdr_value, value);
  1700. hdr = pjsip_generic_string_hdr_create(tdata->pool, &hdr_name, &hdr_value);
  1701. pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) hdr);
  1702. return hdr;
  1703. }
  1704. static pjsip_msg_body *ast_body_to_pjsip_body(pj_pool_t *pool, const struct ast_sip_body *body)
  1705. {
  1706. pj_str_t type;
  1707. pj_str_t subtype;
  1708. pj_str_t body_text;
  1709. pj_cstr(&type, body->type);
  1710. pj_cstr(&subtype, body->subtype);
  1711. pj_cstr(&body_text, body->body_text);
  1712. return pjsip_msg_body_create(pool, &type, &subtype, &body_text);
  1713. }
  1714. int ast_sip_add_body(pjsip_tx_data *tdata, const struct ast_sip_body *body)
  1715. {
  1716. pjsip_msg_body *pjsip_body = ast_body_to_pjsip_body(tdata->pool, body);
  1717. tdata->msg->body = pjsip_body;
  1718. return 0;
  1719. }
  1720. int ast_sip_add_body_multipart(pjsip_tx_data *tdata, const struct ast_sip_body *bodies[], int num_bodies)
  1721. {
  1722. int i;
  1723. /* NULL for type and subtype automatically creates "multipart/mixed" */
  1724. pjsip_msg_body *body = pjsip_multipart_create(tdata->pool, NULL, NULL);
  1725. for (i = 0; i < num_bodies; ++i) {
  1726. pjsip_multipart_part *part = pjsip_multipart_create_part(tdata->pool);
  1727. part->body = ast_body_to_pjsip_body(tdata->pool, bodies[i]);
  1728. pjsip_multipart_add_part(tdata->pool, body, part);
  1729. }
  1730. tdata->msg->body = body;
  1731. return 0;
  1732. }
  1733. int ast_sip_append_body(pjsip_tx_data *tdata, const char *body_text)
  1734. {
  1735. size_t combined_size = strlen(body_text) + tdata->msg->body->len;
  1736. struct ast_str *body_buffer = ast_str_alloca(combined_size);
  1737. ast_str_set(&body_buffer, 0, "%.*s%s", (int) tdata->msg->body->len, (char *) tdata->msg->body->data, body_text);
  1738. tdata->msg->body->data = pj_pool_alloc(tdata->pool, combined_size);
  1739. pj_memcpy(tdata->msg->body->data, ast_str_buffer(body_buffer), combined_size);
  1740. tdata->msg->body->len = combined_size;
  1741. return 0;
  1742. }
  1743. struct ast_taskprocessor *ast_sip_create_serializer_group(const char *name, struct ast_serializer_shutdown_group *shutdown_group)
  1744. {
  1745. return ast_threadpool_serializer_group(name, sip_threadpool, shutdown_group);
  1746. }
  1747. struct ast_taskprocessor *ast_sip_create_serializer(const char *name)
  1748. {
  1749. return ast_sip_create_serializer_group(name, NULL);
  1750. }
  1751. int ast_sip_push_task(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
  1752. {
  1753. if (!serializer) {
  1754. serializer = ast_serializer_pool_get(sip_serializer_pool);
  1755. }
  1756. return ast_taskprocessor_push(serializer, sip_task, task_data);
  1757. }
  1758. struct sync_task_data {
  1759. ast_mutex_t lock;
  1760. ast_cond_t cond;
  1761. int complete;
  1762. int fail;
  1763. int (*task)(void *);
  1764. void *task_data;
  1765. };
  1766. static int sync_task(void *data)
  1767. {
  1768. struct sync_task_data *std = data;
  1769. int ret;
  1770. std->fail = std->task(std->task_data);
  1771. /*
  1772. * Once we unlock std->lock after signaling, we cannot access
  1773. * std again. The thread waiting within ast_sip_push_task_wait()
  1774. * is free to continue and release its local variable (std).
  1775. */
  1776. ast_mutex_lock(&std->lock);
  1777. std->complete = 1;
  1778. ast_cond_signal(&std->cond);
  1779. ret = std->fail;
  1780. ast_mutex_unlock(&std->lock);
  1781. return ret;
  1782. }
  1783. static int ast_sip_push_task_wait(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
  1784. {
  1785. /* This method is an onion */
  1786. struct sync_task_data std;
  1787. memset(&std, 0, sizeof(std));
  1788. ast_mutex_init(&std.lock);
  1789. ast_cond_init(&std.cond, NULL);
  1790. std.task = sip_task;
  1791. std.task_data = task_data;
  1792. if (ast_sip_push_task(serializer, sync_task, &std)) {
  1793. ast_mutex_destroy(&std.lock);
  1794. ast_cond_destroy(&std.cond);
  1795. return -1;
  1796. }
  1797. ast_mutex_lock(&std.lock);
  1798. while (!std.complete) {
  1799. ast_cond_wait(&std.cond, &std.lock);
  1800. }
  1801. ast_mutex_unlock(&std.lock);
  1802. ast_mutex_destroy(&std.lock);
  1803. ast_cond_destroy(&std.cond);
  1804. return std.fail;
  1805. }
  1806. int ast_sip_push_task_wait_servant(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
  1807. {
  1808. if (ast_sip_thread_is_servant()) {
  1809. return sip_task(task_data);
  1810. }
  1811. return ast_sip_push_task_wait(serializer, sip_task, task_data);
  1812. }
  1813. int ast_sip_push_task_synchronous(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
  1814. {
  1815. return ast_sip_push_task_wait_servant(serializer, sip_task, task_data);
  1816. }
  1817. int ast_sip_push_task_wait_serializer(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
  1818. {
  1819. if (!serializer) {
  1820. /* Caller doesn't care which PJSIP serializer the task executes under. */
  1821. serializer = ast_serializer_pool_get(sip_serializer_pool);
  1822. if (!serializer) {
  1823. /* No serializer picked to execute the task */
  1824. return -1;
  1825. }
  1826. }
  1827. if (ast_taskprocessor_is_task(serializer)) {
  1828. /*
  1829. * We are the requested serializer so we must execute
  1830. * the task now or deadlock waiting on ourself to
  1831. * execute it.
  1832. */
  1833. return sip_task(task_data);
  1834. }
  1835. return ast_sip_push_task_wait(serializer, sip_task, task_data);
  1836. }
  1837. void ast_copy_pj_str(char *dest, const pj_str_t *src, size_t size)
  1838. {
  1839. size_t chars_to_copy = MIN(size - 1, pj_strlen(src));
  1840. memcpy(dest, pj_strbuf(src), chars_to_copy);
  1841. dest[chars_to_copy] = '\0';
  1842. }
  1843. int ast_copy_pj_str2(char **dest, const pj_str_t *src)
  1844. {
  1845. int res = ast_asprintf(dest, "%.*s", (int)pj_strlen(src), pj_strbuf(src));
  1846. if (res < 0) {
  1847. *dest = NULL;
  1848. }
  1849. return res;
  1850. }
  1851. int ast_sip_are_media_types_equal(pjsip_media_type *a, pjsip_media_type *b)
  1852. {
  1853. int rc = 0;
  1854. if (a != NULL && b != NULL) {
  1855. rc = pjsip_media_type_cmp(a, b, 0) ? 0 : 1;
  1856. }
  1857. return rc;
  1858. }
  1859. int ast_sip_is_media_type_in(pjsip_media_type *a, ...)
  1860. {
  1861. int rc = 0;
  1862. pjsip_media_type *b = NULL;
  1863. va_list ap;
  1864. ast_assert(a != NULL);
  1865. va_start(ap, a);
  1866. while ((b = va_arg(ap, pjsip_media_type *)) != (pjsip_media_type *)SENTINEL) {
  1867. if (pjsip_media_type_cmp(a, b, 0) == 0) {
  1868. rc = 1;
  1869. break;
  1870. }
  1871. }
  1872. va_end(ap);
  1873. return rc;
  1874. }
  1875. int ast_sip_is_content_type(pjsip_media_type *content_type, char *type, char *subtype)
  1876. {
  1877. pjsip_media_type compare;
  1878. if (!content_type) {
  1879. return 0;
  1880. }
  1881. pjsip_media_type_init2(&compare, type, subtype);
  1882. return pjsip_media_type_cmp(content_type, &compare, 0) ? 0 : -1;
  1883. }
  1884. pj_caching_pool caching_pool;
  1885. pj_pool_t *memory_pool;
  1886. pj_thread_t *monitor_thread;
  1887. static int monitor_continue;
  1888. static void *monitor_thread_exec(void *endpt)
  1889. {
  1890. while (monitor_continue) {
  1891. const pj_time_val delay = {0, 10};
  1892. pjsip_endpt_handle_events(ast_pjsip_endpoint, &delay);
  1893. }
  1894. return NULL;
  1895. }
  1896. static void stop_monitor_thread(void)
  1897. {
  1898. monitor_continue = 0;
  1899. pj_thread_join(monitor_thread);
  1900. }
  1901. AST_THREADSTORAGE(pj_thread_storage);
  1902. AST_THREADSTORAGE(servant_id_storage);
  1903. #define SIP_SERVANT_ID 0x5E2F1D
  1904. static void sip_thread_start(void)
  1905. {
  1906. pj_thread_desc *desc;
  1907. pj_thread_t *thread;
  1908. uint32_t *servant_id;
  1909. servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
  1910. if (!servant_id) {
  1911. ast_log(LOG_ERROR, "Could not set SIP servant ID in thread-local storage.\n");
  1912. return;
  1913. }
  1914. *servant_id = SIP_SERVANT_ID;
  1915. desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
  1916. if (!desc) {
  1917. ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
  1918. return;
  1919. }
  1920. pj_bzero(*desc, sizeof(*desc));
  1921. if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
  1922. ast_log(LOG_ERROR, "Couldn't register thread with PJLIB.\n");
  1923. }
  1924. }
  1925. int ast_sip_thread_is_servant(void)
  1926. {
  1927. uint32_t *servant_id;
  1928. if (monitor_thread &&
  1929. pthread_self() == *(pthread_t *)pj_thread_get_os_handle(monitor_thread)) {
  1930. return 1;
  1931. }
  1932. servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
  1933. if (!servant_id) {
  1934. return 0;
  1935. }
  1936. return *servant_id == SIP_SERVANT_ID;
  1937. }
  1938. void *ast_sip_dict_get(void *ht, const char *key)
  1939. {
  1940. unsigned int hval = 0;
  1941. if (!ht) {
  1942. return NULL;
  1943. }
  1944. return pj_hash_get(ht, key, PJ_HASH_KEY_STRING, &hval);
  1945. }
  1946. void *ast_sip_dict_set(pj_pool_t* pool, void *ht,
  1947. const char *key, void *val)
  1948. {
  1949. if (!ht) {
  1950. ht = pj_hash_create(pool, 11);
  1951. }
  1952. pj_hash_set(pool, ht, key, PJ_HASH_KEY_STRING, 0, val);
  1953. return ht;
  1954. }
  1955. static pj_bool_t supplement_on_rx_request(pjsip_rx_data *rdata)
  1956. {
  1957. struct ast_sip_supplement *supplement;
  1958. if (pjsip_rdata_get_dlg(rdata)) {
  1959. return PJ_FALSE;
  1960. }
  1961. AST_RWLIST_RDLOCK(&supplements);
  1962. AST_LIST_TRAVERSE(&supplements, supplement, next) {
  1963. if (supplement->incoming_request
  1964. && does_method_match(&rdata->msg_info.msg->line.req.method.name, supplement->method)) {
  1965. struct ast_sip_endpoint *endpoint;
  1966. endpoint = ast_pjsip_rdata_get_endpoint(rdata);
  1967. supplement->incoming_request(endpoint, rdata);
  1968. ao2_cleanup(endpoint);
  1969. }
  1970. }
  1971. AST_RWLIST_UNLOCK(&supplements);
  1972. return PJ_FALSE;
  1973. }
  1974. static void supplement_outgoing_response(pjsip_tx_data *tdata, struct ast_sip_endpoint *sip_endpoint)
  1975. {
  1976. struct ast_sip_supplement *supplement;
  1977. pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
  1978. struct ast_sip_contact *contact = ast_sip_mod_data_get(tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT);
  1979. if (sip_endpoint) {
  1980. ast_sip_message_apply_transport(sip_endpoint->transport, tdata);
  1981. }
  1982. AST_RWLIST_RDLOCK(&supplements);
  1983. AST_LIST_TRAVERSE(&supplements, supplement, next) {
  1984. if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
  1985. supplement->outgoing_response(sip_endpoint, contact, tdata);
  1986. }
  1987. }
  1988. AST_RWLIST_UNLOCK(&supplements);
  1989. ast_sip_mod_data_set(tdata->pool, tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT, NULL);
  1990. ao2_cleanup(contact);
  1991. }
  1992. int ast_sip_send_response(pjsip_response_addr *res_addr, pjsip_tx_data *tdata, struct ast_sip_endpoint *sip_endpoint)
  1993. {
  1994. pj_status_t status;
  1995. supplement_outgoing_response(tdata, sip_endpoint);
  1996. status = pjsip_endpt_send_response(ast_sip_get_pjsip_endpoint(), res_addr, tdata, NULL, NULL);
  1997. if (status != PJ_SUCCESS) {
  1998. pjsip_tx_data_dec_ref(tdata);
  1999. }
  2000. return status == PJ_SUCCESS ? 0 : -1;
  2001. }
  2002. static void pool_destroy_callback(void *arg)
  2003. {
  2004. pj_pool_t *pool = (pj_pool_t *)arg;
  2005. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  2006. }
  2007. static void clean_contact_from_tdata(pjsip_tx_data *tdata)
  2008. {
  2009. struct ast_sip_contact *contact;
  2010. contact = ast_sip_mod_data_get(tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT);
  2011. ao2_cleanup(contact);
  2012. ast_sip_mod_data_set(tdata->pool, tdata->mod_data, supplement_module.id, MOD_DATA_CONTACT, NULL);
  2013. pjsip_tx_data_dec_ref(tdata);
  2014. }
  2015. int ast_sip_send_stateful_response(pjsip_rx_data *rdata, pjsip_tx_data *tdata, struct ast_sip_endpoint *sip_endpoint)
  2016. {
  2017. pjsip_transaction *tsx;
  2018. pj_grp_lock_t *tsx_glock;
  2019. pj_pool_t *pool;
  2020. /* Create and initialize global lock pool */
  2021. pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "stateful response", PJSIP_POOL_TSX_LEN, PJSIP_POOL_TSX_INC);
  2022. if (!pool){
  2023. /* ast_sip_create_response bumps the refcount of the contact and adds it to the tdata.
  2024. * We'll leak that reference if we don't get rid of it here.
  2025. */
  2026. clean_contact_from_tdata(tdata);
  2027. return -1;
  2028. }
  2029. /* Create with handler so that we can release the pool once the glock derefs out */
  2030. if(pj_grp_lock_create_w_handler(pool, NULL, pool, &pool_destroy_callback, &tsx_glock) != PJ_SUCCESS) {
  2031. clean_contact_from_tdata(tdata);
  2032. pool_destroy_callback((void *) pool);
  2033. return -1;
  2034. }
  2035. /* We need an additional reference as the qualify thread may destroy this out
  2036. * from under us. Add it now before it gets added to the tsx. */
  2037. pj_grp_lock_add_ref(tsx_glock);
  2038. if (pjsip_tsx_create_uas2(NULL, rdata, tsx_glock, &tsx) != PJ_SUCCESS) {
  2039. clean_contact_from_tdata(tdata);
  2040. pj_grp_lock_dec_ref(tsx_glock);
  2041. return -1;
  2042. }
  2043. pjsip_tsx_recv_msg(tsx, rdata);
  2044. supplement_outgoing_response(tdata, sip_endpoint);
  2045. if (pjsip_tsx_send_msg(tsx, tdata) != PJ_SUCCESS) {
  2046. pj_grp_lock_dec_ref(tsx_glock);
  2047. pjsip_tx_data_dec_ref(tdata);
  2048. return -1;
  2049. }
  2050. pj_grp_lock_dec_ref(tsx_glock);
  2051. return 0;
  2052. }
  2053. int ast_sip_create_response(const pjsip_rx_data *rdata, int st_code,
  2054. struct ast_sip_contact *contact, pjsip_tx_data **tdata)
  2055. {
  2056. int res = pjsip_endpt_create_response(ast_sip_get_pjsip_endpoint(), rdata, st_code, NULL, tdata);
  2057. if (!res) {
  2058. ast_sip_mod_data_set((*tdata)->pool, (*tdata)->mod_data, supplement_module.id, MOD_DATA_CONTACT, ao2_bump(contact));
  2059. }
  2060. return res;
  2061. }
  2062. int ast_sip_get_host_ip(int af, pj_sockaddr *addr)
  2063. {
  2064. if (af == pj_AF_INET() && !ast_strlen_zero(host_ip_ipv4_string)) {
  2065. pj_sockaddr_copy_addr(addr, &host_ip_ipv4);
  2066. return 0;
  2067. } else if (af == pj_AF_INET6() && !ast_strlen_zero(host_ip_ipv6_string)) {
  2068. pj_sockaddr_copy_addr(addr, &host_ip_ipv6);
  2069. return 0;
  2070. }
  2071. return -1;
  2072. }
  2073. const char *ast_sip_get_host_ip_string(int af)
  2074. {
  2075. if (af == pj_AF_INET()) {
  2076. return host_ip_ipv4_string;
  2077. } else if (af == pj_AF_INET6()) {
  2078. return host_ip_ipv6_string;
  2079. }
  2080. return NULL;
  2081. }
  2082. int ast_sip_dtmf_to_str(const enum ast_sip_dtmf_mode dtmf,
  2083. char *buf, size_t buf_len)
  2084. {
  2085. switch (dtmf) {
  2086. case AST_SIP_DTMF_NONE:
  2087. ast_copy_string(buf, "none", buf_len);
  2088. break;
  2089. case AST_SIP_DTMF_RFC_4733:
  2090. ast_copy_string(buf, "rfc4733", buf_len);
  2091. break;
  2092. case AST_SIP_DTMF_INBAND:
  2093. ast_copy_string(buf, "inband", buf_len);
  2094. break;
  2095. case AST_SIP_DTMF_INFO:
  2096. ast_copy_string(buf, "info", buf_len);
  2097. break;
  2098. case AST_SIP_DTMF_AUTO:
  2099. ast_copy_string(buf, "auto", buf_len);
  2100. break;
  2101. case AST_SIP_DTMF_AUTO_INFO:
  2102. ast_copy_string(buf, "auto_info", buf_len);
  2103. break;
  2104. default:
  2105. buf[0] = '\0';
  2106. return -1;
  2107. }
  2108. return 0;
  2109. }
  2110. int ast_sip_str_to_dtmf(const char * dtmf_mode)
  2111. {
  2112. int result = -1;
  2113. if (!strcasecmp(dtmf_mode, "info")) {
  2114. result = AST_SIP_DTMF_INFO;
  2115. } else if (!strcasecmp(dtmf_mode, "rfc4733")) {
  2116. result = AST_SIP_DTMF_RFC_4733;
  2117. } else if (!strcasecmp(dtmf_mode, "inband")) {
  2118. result = AST_SIP_DTMF_INBAND;
  2119. } else if (!strcasecmp(dtmf_mode, "none")) {
  2120. result = AST_SIP_DTMF_NONE;
  2121. } else if (!strcasecmp(dtmf_mode, "auto")) {
  2122. result = AST_SIP_DTMF_AUTO;
  2123. } else if (!strcasecmp(dtmf_mode, "auto_info")) {
  2124. result = AST_SIP_DTMF_AUTO_INFO;
  2125. }
  2126. return result;
  2127. }
  2128. const char *ast_sip_call_codec_pref_to_str(struct ast_flags pref)
  2129. {
  2130. const char *value;
  2131. if (ast_sip_call_codec_pref_test(pref, LOCAL) && ast_sip_call_codec_pref_test(pref, INTERSECT) && ast_sip_call_codec_pref_test(pref, ALL)) {
  2132. value = "local";
  2133. } else if (ast_sip_call_codec_pref_test(pref, LOCAL) && ast_sip_call_codec_pref_test(pref, UNION) && ast_sip_call_codec_pref_test(pref, ALL)) {
  2134. value = "local_merge";
  2135. } else if (ast_sip_call_codec_pref_test(pref, LOCAL) && ast_sip_call_codec_pref_test(pref, INTERSECT) && ast_sip_call_codec_pref_test(pref, FIRST)) {
  2136. value = "local_first";
  2137. } else if (ast_sip_call_codec_pref_test(pref, REMOTE) && ast_sip_call_codec_pref_test(pref, INTERSECT) && ast_sip_call_codec_pref_test(pref, ALL)) {
  2138. value = "remote";
  2139. } else if (ast_sip_call_codec_pref_test(pref, REMOTE) && ast_sip_call_codec_pref_test(pref, UNION) && ast_sip_call_codec_pref_test(pref, ALL)) {
  2140. value = "remote_merge";
  2141. } else if (ast_sip_call_codec_pref_test(pref, REMOTE) && ast_sip_call_codec_pref_test(pref, UNION) && ast_sip_call_codec_pref_test(pref, FIRST)) {
  2142. value = "remote_first";
  2143. } else {
  2144. value = "unknown";
  2145. }
  2146. return value;
  2147. }
  2148. int ast_sip_call_codec_str_to_pref(struct ast_flags *pref, const char *pref_str, int is_outgoing)
  2149. {
  2150. pref->flags = 0;
  2151. if (strcmp(pref_str, "local") == 0) {
  2152. ast_set_flag(pref, AST_SIP_CALL_CODEC_PREF_LOCAL | AST_SIP_CALL_CODEC_PREF_INTERSECT | AST_SIP_CALL_CODEC_PREF_ALL);
  2153. } else if (is_outgoing && strcmp(pref_str, "local_merge") == 0) {
  2154. ast_set_flag(pref, AST_SIP_CALL_CODEC_PREF_LOCAL | AST_SIP_CALL_CODEC_PREF_UNION | AST_SIP_CALL_CODEC_PREF_ALL);
  2155. } else if (strcmp(pref_str, "local_first") == 0) {
  2156. ast_set_flag(pref, AST_SIP_CALL_CODEC_PREF_LOCAL | AST_SIP_CALL_CODEC_PREF_INTERSECT | AST_SIP_CALL_CODEC_PREF_FIRST);
  2157. } else if (strcmp(pref_str, "remote") == 0) {
  2158. ast_set_flag(pref, AST_SIP_CALL_CODEC_PREF_REMOTE | AST_SIP_CALL_CODEC_PREF_INTERSECT | AST_SIP_CALL_CODEC_PREF_ALL);
  2159. } else if (is_outgoing && strcmp(pref_str, "remote_merge") == 0) {
  2160. ast_set_flag(pref, AST_SIP_CALL_CODEC_PREF_REMOTE | AST_SIP_CALL_CODEC_PREF_UNION | AST_SIP_CALL_CODEC_PREF_ALL);
  2161. } else if (strcmp(pref_str, "remote_first") == 0) {
  2162. ast_set_flag(pref, AST_SIP_CALL_CODEC_PREF_REMOTE | AST_SIP_CALL_CODEC_PREF_UNION | AST_SIP_CALL_CODEC_PREF_FIRST);
  2163. } else {
  2164. return -1;
  2165. }
  2166. return 0;
  2167. }
  2168. /*!
  2169. * \internal
  2170. * \brief Set an ast_party_id name and number based on an identity header.
  2171. * \param hdr From, P-Asserted-Identity, or Remote-Party-ID header on incoming message
  2172. * \param[out] id The ID to set data on
  2173. */
  2174. static void set_id_from_hdr(pjsip_fromto_hdr *hdr, struct ast_party_id *id)
  2175. {
  2176. char cid_name[AST_CHANNEL_NAME];
  2177. char cid_num[AST_CHANNEL_NAME];
  2178. size_t cid_name_size = AST_CHANNEL_NAME;
  2179. pjsip_name_addr *id_name_addr = (pjsip_name_addr *) hdr->uri;
  2180. char *semi;
  2181. enum ast_utf8_replace_result result;
  2182. ast_copy_pj_str(cid_num, ast_sip_pjsip_uri_get_username(hdr->uri), sizeof(cid_num));
  2183. /* Always truncate caller-id number at a semicolon. */
  2184. semi = strchr(cid_num, ';');
  2185. if (semi) {
  2186. /*
  2187. * We need to be able to handle URI's looking like
  2188. * "sip:1235557890;phone-context=national@x.x.x.x;user=phone"
  2189. *
  2190. * Where the uri->user field will result in:
  2191. * "1235557890;phone-context=national"
  2192. *
  2193. * People don't care about anything after the semicolon
  2194. * showing up on their displays even though the RFC
  2195. * allows the semicolon.
  2196. */
  2197. *semi = '\0';
  2198. }
  2199. /*
  2200. * It's safe to pass a NULL or empty string as the source.
  2201. * The result will be an empty string assuming the destination
  2202. * size was at least 1.
  2203. */
  2204. result = ast_utf8_replace_invalid_chars(cid_name, &cid_name_size,
  2205. id_name_addr->display.ptr, id_name_addr->display.slen);
  2206. if (result != AST_UTF8_REPLACE_VALID) {
  2207. ast_log(LOG_WARNING, "CallerID Name '" PJSTR_PRINTF_SPEC
  2208. "' for number '%s' has invalid UTF-8 characters which "
  2209. "were replaced",
  2210. PJSTR_PRINTF_VAR(id_name_addr->display), cid_num);
  2211. }
  2212. ast_free(id->name.str);
  2213. id->name.str = ast_strdup(cid_name);
  2214. if (!ast_strlen_zero(cid_name)) {
  2215. id->name.valid = 1;
  2216. }
  2217. ast_free(id->number.str);
  2218. id->number.str = ast_strdup(cid_num);
  2219. if (!ast_strlen_zero(cid_num)) {
  2220. id->number.valid = 1;
  2221. }
  2222. }
  2223. /*!
  2224. * \internal
  2225. * \brief Get a P-Asserted-Identity or Remote-Party-ID header from an incoming message
  2226. *
  2227. * This function will parse the header as if it were a From header. This allows for us
  2228. * to easily manipulate the URI, as well as add, modify, or remove parameters from the
  2229. * header
  2230. *
  2231. * \param rdata The incoming message
  2232. * \param header_name The name of the ID header to find
  2233. * \retval NULL No ID header present or unable to parse ID header
  2234. * \retval non-NULL The parsed ID header
  2235. */
  2236. static pjsip_fromto_hdr *get_id_header(pjsip_rx_data *rdata, const pj_str_t *header_name)
  2237. {
  2238. static const pj_str_t from = { "From", 4 };
  2239. pj_str_t header_content;
  2240. pjsip_fromto_hdr *parsed_hdr;
  2241. pjsip_generic_string_hdr *ident = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg,
  2242. header_name, NULL);
  2243. int parsed_len;
  2244. if (!ident) {
  2245. return NULL;
  2246. }
  2247. pj_strdup_with_null(rdata->tp_info.pool, &header_content, &ident->hvalue);
  2248. parsed_hdr = pjsip_parse_hdr(rdata->tp_info.pool, &from, header_content.ptr,
  2249. pj_strlen(&header_content), &parsed_len);
  2250. if (!parsed_hdr) {
  2251. return NULL;
  2252. }
  2253. return parsed_hdr;
  2254. }
  2255. /*!
  2256. * \internal
  2257. * \brief Set an ast_party_id structure based on data in a P-Asserted-Identity header
  2258. *
  2259. * This makes use of \ref set_id_from_hdr for setting name and number. It uses
  2260. * the contents of a Privacy header in order to set presentation information.
  2261. *
  2262. * \param rdata The incoming message
  2263. * \param[out] id The ID to set
  2264. * \retval 0 Successfully set the party ID
  2265. * \retval non-zero Could not set the party ID
  2266. */
  2267. static int set_id_from_pai(pjsip_rx_data *rdata, struct ast_party_id *id)
  2268. {
  2269. static const pj_str_t pai_str = { "P-Asserted-Identity", 19 };
  2270. static const pj_str_t privacy_str = { "Privacy", 7 };
  2271. pjsip_fromto_hdr *pai_hdr = get_id_header(rdata, &pai_str);
  2272. pjsip_generic_string_hdr *privacy;
  2273. if (!pai_hdr) {
  2274. return -1;
  2275. }
  2276. set_id_from_hdr(pai_hdr, id);
  2277. if (!id->number.valid) {
  2278. return -1;
  2279. }
  2280. privacy = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &privacy_str, NULL);
  2281. if (!privacy || !pj_stricmp2(&privacy->hvalue, "none")) {
  2282. id->number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  2283. id->name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
  2284. } else {
  2285. id->number.presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  2286. id->name.presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
  2287. }
  2288. return 0;
  2289. }
  2290. /*!
  2291. * \internal
  2292. * \brief Set an ast_party_id structure based on data in a Remote-Party-ID header
  2293. *
  2294. * This makes use of \ref set_id_from_hdr for setting name and number. It uses
  2295. * the privacy and screen parameters in order to set presentation information.
  2296. *
  2297. * \param rdata The incoming message
  2298. * \param[out] id The ID to set
  2299. * \retval 0 Succesfully set the party ID
  2300. * \retval non-zero Could not set the party ID
  2301. */
  2302. static int set_id_from_rpid(pjsip_rx_data *rdata, struct ast_party_id *id)
  2303. {
  2304. static const pj_str_t rpid_str = { "Remote-Party-ID", 15 };
  2305. static const pj_str_t privacy_str = { "privacy", 7 };
  2306. static const pj_str_t screen_str = { "screen", 6 };
  2307. pjsip_fromto_hdr *rpid_hdr = get_id_header(rdata, &rpid_str);
  2308. pjsip_param *screen;
  2309. pjsip_param *privacy;
  2310. if (!rpid_hdr) {
  2311. return -1;
  2312. }
  2313. set_id_from_hdr(rpid_hdr, id);
  2314. if (!id->number.valid) {
  2315. return -1;
  2316. }
  2317. privacy = pjsip_param_find(&rpid_hdr->other_param, &privacy_str);
  2318. screen = pjsip_param_find(&rpid_hdr->other_param, &screen_str);
  2319. if (privacy && !pj_stricmp2(&privacy->value, "full")) {
  2320. id->number.presentation = AST_PRES_RESTRICTED;
  2321. id->name.presentation = AST_PRES_RESTRICTED;
  2322. } else {
  2323. id->number.presentation = AST_PRES_ALLOWED;
  2324. id->name.presentation = AST_PRES_ALLOWED;
  2325. }
  2326. if (screen && !pj_stricmp2(&screen->value, "yes")) {
  2327. id->number.presentation |= AST_PRES_USER_NUMBER_PASSED_SCREEN;
  2328. id->name.presentation |= AST_PRES_USER_NUMBER_PASSED_SCREEN;
  2329. } else {
  2330. id->number.presentation |= AST_PRES_USER_NUMBER_UNSCREENED;
  2331. id->name.presentation |= AST_PRES_USER_NUMBER_UNSCREENED;
  2332. }
  2333. return 0;
  2334. }
  2335. /*!
  2336. * \internal
  2337. * \brief Set an ast_party_id structure based on data in a From
  2338. *
  2339. * This makes use of \ref set_id_from_hdr for setting name and number. It uses
  2340. * no information from the message in order to set privacy. It relies on endpoint
  2341. * configuration for privacy information.
  2342. *
  2343. * \param rdata The incoming message
  2344. * \param[out] id The ID to set
  2345. * \retval 0 Succesfully set the party ID
  2346. * \retval non-zero Could not set the party ID
  2347. */
  2348. static int set_id_from_from(struct pjsip_rx_data *rdata, struct ast_party_id *id)
  2349. {
  2350. pjsip_fromto_hdr *from = pjsip_msg_find_hdr(rdata->msg_info.msg,
  2351. PJSIP_H_FROM, rdata->msg_info.msg->hdr.next);
  2352. if (!from) {
  2353. /* This had better not happen */
  2354. return -1;
  2355. }
  2356. set_id_from_hdr(from, id);
  2357. if (!id->number.valid) {
  2358. return -1;
  2359. }
  2360. return 0;
  2361. }
  2362. int ast_sip_set_id_connected_line(struct pjsip_rx_data *rdata, struct ast_party_id *id)
  2363. {
  2364. return !set_id_from_pai(rdata, id) || !set_id_from_rpid(rdata, id) ? 0 : -1;
  2365. }
  2366. int ast_sip_set_id_from_invite(struct pjsip_rx_data *rdata, struct ast_party_id *id, struct ast_party_id *default_id, int trust_inbound)
  2367. {
  2368. if (trust_inbound && (!set_id_from_pai(rdata, id) || !set_id_from_rpid(rdata, id))) {
  2369. /* Trusted: Check PAI and RPID */
  2370. ast_free(id->tag);
  2371. id->tag = ast_strdup(default_id->tag);
  2372. return 0;
  2373. }
  2374. /* Not trusted: check the endpoint config or use From. */
  2375. ast_party_id_copy(id, default_id);
  2376. if (!default_id->number.valid) {
  2377. set_id_from_from(rdata, id);
  2378. }
  2379. return 0;
  2380. }
  2381. /*!
  2382. * \brief Set name and number information on an identity header.
  2383. *
  2384. * \param pool Memory pool to use for string duplication
  2385. * \param id_hdr A From, P-Asserted-Identity, or Remote-Party-ID header to modify
  2386. * \param id The identity information to apply to the header
  2387. */
  2388. void ast_sip_modify_id_header(pj_pool_t *pool, pjsip_fromto_hdr *id_hdr, const struct ast_party_id *id)
  2389. {
  2390. pjsip_name_addr *id_name_addr;
  2391. pjsip_sip_uri *id_uri;
  2392. id_name_addr = (pjsip_name_addr *) id_hdr->uri;
  2393. id_uri = pjsip_uri_get_uri(id_name_addr->uri);
  2394. if (id->name.valid) {
  2395. if (!ast_strlen_zero(id->name.str)) {
  2396. int name_buf_len = strlen(id->name.str) * 2 + 1;
  2397. char *name_buf = ast_alloca(name_buf_len);
  2398. ast_escape_quoted(id->name.str, name_buf, name_buf_len);
  2399. pj_strdup2(pool, &id_name_addr->display, name_buf);
  2400. } else {
  2401. pj_strdup2(pool, &id_name_addr->display, NULL);
  2402. }
  2403. }
  2404. if (id->number.valid) {
  2405. pj_strdup2(pool, &id_uri->user, id->number.str);
  2406. }
  2407. }
  2408. /*!
  2409. * \brief Find a contact and insert a "user@" into its URI.
  2410. *
  2411. * \param to Original destination (for error messages only)
  2412. * \param endpoint_name Endpoint name (for error messages only)
  2413. * \param aors Command separated list of AORs
  2414. * \param user The user to insert in the contact URI
  2415. * \param uri Pointer to buffer in which to return the URI. Must be freed by caller.
  2416. *
  2417. * \return 0 Success
  2418. * \return -1 Fail
  2419. *
  2420. * \note If the contact URI found for the endpoint already has a user in
  2421. * its URI, it will be replaced by the user passed as an argument to this function.
  2422. */
  2423. static int insert_user_in_contact_uri(const char *to, const char *endpoint_name, const char *aors,
  2424. const char *user, char **uri)
  2425. {
  2426. RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
  2427. pj_pool_t *pool;
  2428. pjsip_name_addr *name_addr;
  2429. pjsip_sip_uri *sip_uri;
  2430. int err = 0;
  2431. contact = ast_sip_location_retrieve_contact_from_aor_list(aors);
  2432. if (!contact) {
  2433. ast_log(LOG_WARNING, "Dest: '%s'. Couldn't find contact for endpoint '%s'\n",
  2434. to, endpoint_name);
  2435. return -1;
  2436. }
  2437. pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "uri-user-insert", 128, 128);
  2438. if (!pool) {
  2439. ast_log(LOG_WARNING, "Failed to allocate ParseUri endpoint pool.\n");
  2440. return -1;
  2441. }
  2442. name_addr = (pjsip_name_addr *) pjsip_parse_uri(pool, (char*)contact->uri, strlen(contact->uri), PJSIP_PARSE_URI_AS_NAMEADDR);
  2443. if (!name_addr || (!PJSIP_URI_SCHEME_IS_SIP(name_addr->uri) && !PJSIP_URI_SCHEME_IS_SIPS(name_addr->uri))) {
  2444. ast_log(LOG_WARNING, "Failed to parse URI '%s'\n", contact->uri);
  2445. err = -1;
  2446. goto out;
  2447. }
  2448. ast_debug(3, "Dest: '%s' User: '%s' Endpoint: '%s' ContactURI: '%s'\n", to, user, endpoint_name, contact->uri);
  2449. sip_uri = pjsip_uri_get_uri(name_addr->uri);
  2450. pj_strset2(&sip_uri->user, (char*)user);
  2451. *uri = ast_malloc(PJSIP_MAX_URL_SIZE);
  2452. if (!(*uri)) {
  2453. err = -1;
  2454. goto out;
  2455. }
  2456. pjsip_uri_print(PJSIP_URI_IN_REQ_URI, name_addr, *uri, PJSIP_MAX_URL_SIZE);
  2457. out:
  2458. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  2459. return err;
  2460. }
  2461. /*!
  2462. * \internal
  2463. * \brief Get endpoint and URI when the destination is only a single token
  2464. *
  2465. * "destination" could be one of the following:
  2466. * \verbatim
  2467. endpoint_name
  2468. hostname
  2469. * \endverbatim
  2470. *
  2471. * \param to
  2472. * \param destination
  2473. * \param get_default_outbound If nonzero, try to retrieve the default
  2474. * outbound endpoint if no endpoint was found.
  2475. * Otherwise, return NULL if no endpoint was found.
  2476. * \param uri Pointer to URI variable. Must be freed by caller - even if the return value is NULL!
  2477. * \return endpoint
  2478. */
  2479. static struct ast_sip_endpoint *handle_single_token(const char *to, char *destination, int get_default_outbound, char **uri) {
  2480. RAII_VAR(struct ast_sip_contact*, contact, NULL, ao2_cleanup);
  2481. char *endpoint_name = NULL;
  2482. struct ast_sip_endpoint *endpoint = NULL;
  2483. /*
  2484. * If "destination" is just one token, it could be an endpoint name
  2485. * or a hostname without a scheme.
  2486. */
  2487. endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", destination);
  2488. if (!endpoint) {
  2489. /*
  2490. * We can only assume it's a hostname.
  2491. */
  2492. char *temp_uri = ast_malloc(strlen(destination) + strlen("sip:") + 1);
  2493. if (!temp_uri) {
  2494. goto failure;
  2495. }
  2496. sprintf(temp_uri, "sip:%s", destination);
  2497. *uri = temp_uri;
  2498. if (get_default_outbound) {
  2499. endpoint = ast_sip_default_outbound_endpoint();
  2500. }
  2501. ast_debug(3, "Dest: '%s' Didn't find endpoint so adding scheme and using URI '%s'%s\n",
  2502. to, *uri, get_default_outbound ? " with default endpoint" : "");
  2503. return endpoint;
  2504. }
  2505. /*
  2506. * It's an endpoint
  2507. */
  2508. endpoint_name = destination;
  2509. contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
  2510. if (!contact) {
  2511. ast_log(LOG_WARNING, "Dest: '%s'. Found endpoint '%s' but didn't find an aor/contact for it\n",
  2512. to, endpoint_name);
  2513. ao2_cleanup(endpoint);
  2514. goto failure;
  2515. }
  2516. *uri = ast_strdup(contact->uri);
  2517. if (!(*uri)) {
  2518. ao2_cleanup(endpoint);
  2519. goto failure;
  2520. }
  2521. ast_debug(3, "Dest: '%s' Found endpoint '%s' and found contact with URI '%s'\n",
  2522. to, endpoint_name, *uri);
  2523. return endpoint;
  2524. failure:
  2525. *uri = NULL;
  2526. return NULL;
  2527. }
  2528. /*!
  2529. * \internal
  2530. * \brief Get endpoint and URI when the destination contained a '/'
  2531. *
  2532. * "to" could be one of the following:
  2533. * \verbatim
  2534. endpoint/aor
  2535. endpoint/<sip[s]:host>
  2536. endpoint/<sip[s]:user@host>
  2537. endpoint/"Bob" <sip[s]:host>
  2538. endpoint/"Bob" <sip[s]:user@host>
  2539. endpoint/sip[s]:host
  2540. endpoint/sip[s]:user@host
  2541. endpoint/host
  2542. endpoint/user@host
  2543. * \endverbatim
  2544. *
  2545. * \param to Destination
  2546. * \param uri Pointer to URI variable. Must be freed by caller - even if the return value is NULL!
  2547. * \param destination, slash, atsign, scheme
  2548. * \return endpoint
  2549. */
  2550. static struct ast_sip_endpoint *handle_slash(const char *to, char *destination, char **uri,
  2551. char *slash, char *atsign, char *scheme)
  2552. {
  2553. char *endpoint_name = NULL;
  2554. struct ast_sip_endpoint *endpoint = NULL;
  2555. struct ast_sip_contact *contact = NULL;
  2556. char *user = NULL;
  2557. char *afterslash = slash + 1;
  2558. struct ast_sip_aor *aor;
  2559. if (ast_begins_with(destination, "PJSIP/")) {
  2560. ast_debug(3, "Dest: '%s' Dialplan format'\n", to);
  2561. /*
  2562. * This has to be the form PJSIP/user@endpoint
  2563. */
  2564. if (!atsign || strchr(afterslash, '/')) {
  2565. /*
  2566. * If there's no "user@" or there's a slash somewhere after
  2567. * "PJSIP/" then we go no further.
  2568. */
  2569. ast_log(LOG_WARNING,
  2570. "Dest: '%s'. Destinations beginning with 'PJSIP/' must be in the form of 'PJSIP/user@endpoint'\n",
  2571. to);
  2572. goto failure;
  2573. }
  2574. *atsign = '\0';
  2575. user = afterslash;
  2576. endpoint_name = atsign + 1;
  2577. ast_debug(3, "Dest: '%s' User: '%s' Endpoint: '%s'\n", to, user, endpoint_name);
  2578. } else {
  2579. /*
  2580. * Either...
  2581. * endpoint/aor
  2582. * endpoint/uri
  2583. */
  2584. *slash = '\0';
  2585. endpoint_name = destination;
  2586. ast_debug(3, "Dest: '%s' Endpoint: '%s'\n", to, endpoint_name);
  2587. }
  2588. endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name);
  2589. if (!endpoint) {
  2590. ast_log(LOG_WARNING, "Dest: '%s'. Didn't find endpoint with name '%s'\n",
  2591. to, endpoint_name);
  2592. goto failure;
  2593. }
  2594. if (scheme) {
  2595. /*
  2596. * If we found a scheme, then everything after the slash MUST be a URI.
  2597. * We don't need to do any further modification.
  2598. */
  2599. *uri = ast_strdup(afterslash);
  2600. if (!(*uri)) {
  2601. goto failure;
  2602. }
  2603. ast_debug(3, "Dest: '%s' Found endpoint '%s' and found URI '%s' after '/'\n",
  2604. to, endpoint_name, *uri);
  2605. return endpoint;
  2606. }
  2607. if (user) {
  2608. /*
  2609. * This has to be the form PJSIP/user@endpoint
  2610. */
  2611. int rc;
  2612. /*
  2613. * Set the return URI to be the endpoint's contact URI with the user
  2614. * portion set to the user that was specified before the endpoint name.
  2615. */
  2616. rc = insert_user_in_contact_uri(to, endpoint_name, endpoint->aors, user, uri);
  2617. if (rc != 0) {
  2618. /*
  2619. * insert_user_in_contact_uri prints the warning message.
  2620. */
  2621. goto failure;
  2622. }
  2623. ast_debug(3, "Dest: '%s' User: '%s' Endpoint: '%s' URI: '%s'\n", to, user,
  2624. endpoint_name, *uri);
  2625. return endpoint;
  2626. }
  2627. /*
  2628. * We're now left with two possibilities...
  2629. * endpoint/aor
  2630. * endpoint/uri-without-scheme
  2631. */
  2632. aor = ast_sip_location_retrieve_aor(afterslash);
  2633. if (!aor) {
  2634. /*
  2635. * It's probably a URI without a scheme but we don't have a way to tell
  2636. * for sure. We're going to assume it is and prepend it with a scheme.
  2637. */
  2638. *uri = ast_malloc(strlen(afterslash) + strlen("sip:") + 1);
  2639. if (!(*uri)) {
  2640. goto failure;
  2641. }
  2642. sprintf(*uri, "sip:%s", afterslash);
  2643. ast_debug(3, "Dest: '%s' Found endpoint '%s' but didn't find aor after '/' so using URI '%s'\n",
  2644. to, endpoint_name, *uri);
  2645. return endpoint;
  2646. }
  2647. /*
  2648. * Only one possibility left... There was an aor name after the slash.
  2649. */
  2650. ast_debug(3, "Dest: '%s' Found endpoint '%s' and found aor '%s' after '/'\n",
  2651. to, endpoint_name, ast_sorcery_object_get_id(aor));
  2652. contact = ast_sip_location_retrieve_first_aor_contact(aor);
  2653. if (!contact) {
  2654. ast_log(LOG_WARNING, "Dest: '%s'. Found endpoint '%s' but didn't find contact for aor '%s'\n",
  2655. to, endpoint_name, ast_sorcery_object_get_id(aor));
  2656. ao2_cleanup(aor);
  2657. goto failure;
  2658. }
  2659. *uri = ast_strdup(contact->uri);
  2660. ao2_cleanup(contact);
  2661. ao2_cleanup(aor);
  2662. if (!(*uri)) {
  2663. goto failure;
  2664. }
  2665. ast_debug(3, "Dest: '%s' Found endpoint '%s' and found contact with URI '%s' for aor '%s'\n",
  2666. to, endpoint_name, *uri, ast_sorcery_object_get_id(aor));
  2667. return endpoint;
  2668. failure:
  2669. ao2_cleanup(endpoint);
  2670. *uri = NULL;
  2671. return NULL;
  2672. }
  2673. /*!
  2674. * \internal
  2675. * \brief Get endpoint and URI when the destination contained a '@' but no '/' or scheme
  2676. *
  2677. * "to" could be one of the following:
  2678. * \verbatim
  2679. <sip[s]:user@host>
  2680. "Bob" <sip[s]:user@host>
  2681. sip[s]:user@host
  2682. user@host
  2683. * \endverbatim
  2684. *
  2685. * \param to Destination
  2686. * \param uri Pointer to URI variable. Must be freed by caller - even if the return value is NULL!
  2687. * \param destination, slash, atsign, scheme
  2688. * \param get_default_outbound If nonzero, try to retrieve the default
  2689. * outbound endpoint if no endpoint was found.
  2690. * Otherwise, return NULL if no endpoint was found.
  2691. * \return endpoint
  2692. */
  2693. static struct ast_sip_endpoint *handle_atsign(const char *to, char *destination, char **uri,
  2694. char *slash, char *atsign, char *scheme, int get_default_outbound)
  2695. {
  2696. char *endpoint_name = NULL;
  2697. struct ast_sip_endpoint *endpoint = NULL;
  2698. struct ast_sip_contact *contact = NULL;
  2699. char *afterat = atsign + 1;
  2700. *atsign = '\0';
  2701. endpoint_name = destination;
  2702. /* Apparently there may be ';<user_options>' after the endpoint name ??? */
  2703. AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(endpoint_name);
  2704. endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name);
  2705. if (!endpoint) {
  2706. /*
  2707. * It's probably a uri with a user but without a scheme but we don't have a way to tell.
  2708. * We're going to assume it is and prepend it with a scheme.
  2709. */
  2710. *uri = ast_malloc(strlen(to) + strlen("sip:") + 1);
  2711. if (!(*uri)) {
  2712. goto failure;
  2713. }
  2714. sprintf(*uri, "sip:%s", to);
  2715. if (get_default_outbound) {
  2716. endpoint = ast_sip_default_outbound_endpoint();
  2717. }
  2718. ast_debug(3, "Dest: '%s' Didn't find endpoint before the '@' so using URI '%s'%s\n",
  2719. to, *uri, get_default_outbound ? " with default endpoint" : "");
  2720. return endpoint;
  2721. }
  2722. /*
  2723. * OK, it's an endpoint and a domain (which we ignore)
  2724. */
  2725. contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
  2726. if (!contact) {
  2727. ast_log(LOG_WARNING, "Dest: '%s'. Found endpoint '%s' but didn't find contact\n",
  2728. to, endpoint_name);
  2729. goto failure;
  2730. }
  2731. *uri = ast_strdup(contact->uri);
  2732. ao2_cleanup(contact);
  2733. if (!(*uri)) {
  2734. goto failure;
  2735. }
  2736. ast_debug(3, "Dest: '%s' Found endpoint '%s' and found contact with URI '%s' (discarding domain %s)\n",
  2737. to, endpoint_name, *uri, afterat);
  2738. return endpoint;
  2739. failure:
  2740. ao2_cleanup(endpoint);
  2741. *uri = NULL;
  2742. return NULL;
  2743. }
  2744. struct ast_sip_endpoint *ast_sip_get_endpoint(const char *to, int get_default_outbound, char **uri)
  2745. {
  2746. char *destination;
  2747. char *slash = NULL;
  2748. char *atsign = NULL;
  2749. char *scheme = NULL;
  2750. struct ast_sip_endpoint *endpoint = NULL;
  2751. destination = ast_strdupa(to);
  2752. slash = strchr(destination, '/');
  2753. atsign = strchr(destination, '@');
  2754. scheme = S_OR(strstr(destination, "sip:"), strstr(destination, "sips:"));
  2755. if (!slash && !atsign && !scheme) {
  2756. /*
  2757. * If there's only a single token, it can be either...
  2758. * endpoint
  2759. * host
  2760. */
  2761. return handle_single_token(to, destination, get_default_outbound, uri);
  2762. }
  2763. if (slash) {
  2764. /*
  2765. * If there's a '/', then the form must be one of the following...
  2766. * PJSIP/user@endpoint
  2767. * endpoint/aor
  2768. * endpoint/uri
  2769. */
  2770. return handle_slash(to, destination, uri, slash, atsign, scheme);
  2771. }
  2772. if (atsign && !scheme) {
  2773. /*
  2774. * If there's an '@' but no scheme then it's either following an endpoint name
  2775. * and being followed by a domain name (which we discard).
  2776. * OR is's a user@host uri without a scheme. It's probably the latter but because
  2777. * endpoint@domain looks just like user@host, we'll test for endpoint first.
  2778. */
  2779. return handle_atsign(to, destination, uri, slash, atsign, scheme, get_default_outbound);
  2780. }
  2781. /*
  2782. * If all else fails, we assume it's a URI or just a hostname.
  2783. */
  2784. if (scheme) {
  2785. *uri = ast_strdup(destination);
  2786. if (!(*uri)) {
  2787. goto failure;
  2788. }
  2789. ast_debug(3, "Dest: '%s' Didn't find an endpoint but did find a scheme so using URI '%s'%s\n",
  2790. to, *uri, get_default_outbound ? " with default endpoint" : "");
  2791. } else {
  2792. *uri = ast_malloc(strlen(destination) + strlen("sip:") + 1);
  2793. if (!(*uri)) {
  2794. goto failure;
  2795. }
  2796. sprintf(*uri, "sip:%s", destination);
  2797. ast_debug(3, "Dest: '%s' Didn't find an endpoint and didn't find scheme so adding scheme and using URI '%s'%s\n",
  2798. to, *uri, get_default_outbound ? " with default endpoint" : "");
  2799. }
  2800. if (get_default_outbound) {
  2801. endpoint = ast_sip_default_outbound_endpoint();
  2802. }
  2803. return endpoint;
  2804. failure:
  2805. ao2_cleanup(endpoint);
  2806. *uri = NULL;
  2807. return NULL;
  2808. }
  2809. int ast_sip_update_to_uri(pjsip_tx_data *tdata, const char *to)
  2810. {
  2811. pjsip_name_addr *parsed_name_addr;
  2812. pjsip_sip_uri *sip_uri;
  2813. pjsip_name_addr *tdata_name_addr;
  2814. pjsip_sip_uri *tdata_sip_uri;
  2815. pjsip_to_hdr *to_hdr;
  2816. char *buf = NULL;
  2817. #define DEBUG_BUF_SIZE 256
  2818. parsed_name_addr = (pjsip_name_addr *) pjsip_parse_uri(tdata->pool, (char*)to, strlen(to),
  2819. PJSIP_PARSE_URI_AS_NAMEADDR);
  2820. if (!parsed_name_addr || (!PJSIP_URI_SCHEME_IS_SIP(parsed_name_addr->uri)
  2821. && !PJSIP_URI_SCHEME_IS_SIPS(parsed_name_addr->uri))) {
  2822. ast_log(LOG_WARNING, "To address '%s' is not a valid SIP/SIPS URI\n", to);
  2823. return -1;
  2824. }
  2825. sip_uri = pjsip_uri_get_uri(parsed_name_addr->uri);
  2826. if (DEBUG_ATLEAST(3)) {
  2827. buf = ast_alloca(DEBUG_BUF_SIZE);
  2828. pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, sip_uri, buf, DEBUG_BUF_SIZE);
  2829. ast_debug(3, "Parsed To: %.*s %s\n", (int)parsed_name_addr->display.slen,
  2830. parsed_name_addr->display.ptr, buf);
  2831. }
  2832. to_hdr = PJSIP_MSG_TO_HDR(tdata->msg);
  2833. tdata_name_addr = to_hdr ? (pjsip_name_addr *) to_hdr->uri : NULL;
  2834. if (!tdata_name_addr || (!PJSIP_URI_SCHEME_IS_SIP(tdata_name_addr->uri)
  2835. && !PJSIP_URI_SCHEME_IS_SIPS(tdata_name_addr->uri))) {
  2836. /* Highly unlikely but we have to check */
  2837. ast_log(LOG_WARNING, "tdata To address '%s' is not a valid SIP/SIPS URI\n", to);
  2838. return -1;
  2839. }
  2840. tdata_sip_uri = pjsip_uri_get_uri(tdata_name_addr->uri);
  2841. if (DEBUG_ATLEAST(3)) {
  2842. buf[0] = '\0';
  2843. pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, tdata_sip_uri, buf, DEBUG_BUF_SIZE);
  2844. ast_debug(3, "Original tdata To: %.*s %s\n", (int)tdata_name_addr->display.slen,
  2845. tdata_name_addr->display.ptr, buf);
  2846. }
  2847. /* Replace the uri */
  2848. pjsip_sip_uri_assign(tdata->pool, tdata_sip_uri, sip_uri);
  2849. /* The display name isn't part of the URI so we need to replace it separately */
  2850. pj_strdup(tdata->pool, &tdata_name_addr->display, &parsed_name_addr->display);
  2851. if (DEBUG_ATLEAST(3)) {
  2852. buf[0] = '\0';
  2853. pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, tdata_sip_uri, buf, 256);
  2854. ast_debug(3, "New tdata To: %.*s %s\n", (int)tdata_name_addr->display.slen,
  2855. tdata_name_addr->display.ptr, buf);
  2856. }
  2857. return 0;
  2858. #undef DEBUG_BUF_SIZE
  2859. }
  2860. int ast_sip_update_from(pjsip_tx_data *tdata, char *from)
  2861. {
  2862. pjsip_name_addr *name_addr;
  2863. pjsip_sip_uri *uri;
  2864. pjsip_name_addr *parsed_name_addr;
  2865. pjsip_from_hdr *from_hdr;
  2866. if (ast_strlen_zero(from)) {
  2867. return 0;
  2868. }
  2869. from_hdr = PJSIP_MSG_FROM_HDR(tdata->msg);
  2870. if (!from_hdr) {
  2871. return -1;
  2872. }
  2873. name_addr = (pjsip_name_addr *) from_hdr->uri;
  2874. uri = pjsip_uri_get_uri(name_addr);
  2875. parsed_name_addr = (pjsip_name_addr *) pjsip_parse_uri(tdata->pool, from,
  2876. strlen(from), PJSIP_PARSE_URI_AS_NAMEADDR);
  2877. if (parsed_name_addr) {
  2878. pjsip_sip_uri *parsed_uri;
  2879. if (!PJSIP_URI_SCHEME_IS_SIP(parsed_name_addr->uri)
  2880. && !PJSIP_URI_SCHEME_IS_SIPS(parsed_name_addr->uri)) {
  2881. ast_log(LOG_WARNING, "From address '%s' is not a valid SIP/SIPS URI\n", from);
  2882. return -1;
  2883. }
  2884. parsed_uri = pjsip_uri_get_uri(parsed_name_addr->uri);
  2885. if (pj_strlen(&parsed_name_addr->display)) {
  2886. pj_strdup(tdata->pool, &name_addr->display, &parsed_name_addr->display);
  2887. }
  2888. /* Unlike the To header, we only want to replace the user, host and port */
  2889. pj_strdup(tdata->pool, &uri->user, &parsed_uri->user);
  2890. pj_strdup(tdata->pool, &uri->host, &parsed_uri->host);
  2891. uri->port = parsed_uri->port;
  2892. return 0;
  2893. } else {
  2894. /* assume it is 'user[@domain]' format */
  2895. char *domain = strchr(from, '@');
  2896. if (domain) {
  2897. pj_str_t pj_from;
  2898. pj_strset3(&pj_from, from, domain);
  2899. pj_strdup(tdata->pool, &uri->user, &pj_from);
  2900. pj_strdup2(tdata->pool, &uri->host, domain + 1);
  2901. } else {
  2902. pj_strdup2(tdata->pool, &uri->user, from);
  2903. }
  2904. return 0;
  2905. }
  2906. return -1;
  2907. }
  2908. static void remove_request_headers(pjsip_endpoint *endpt)
  2909. {
  2910. const pjsip_hdr *request_headers = pjsip_endpt_get_request_headers(endpt);
  2911. pjsip_hdr *iter = request_headers->next;
  2912. while (iter != request_headers) {
  2913. pjsip_hdr *to_erase = iter;
  2914. iter = iter->next;
  2915. pj_list_erase(to_erase);
  2916. }
  2917. }
  2918. long ast_sip_threadpool_queue_size(void)
  2919. {
  2920. return ast_threadpool_queue_size(sip_threadpool);
  2921. }
  2922. struct ast_threadpool *ast_sip_threadpool(void)
  2923. {
  2924. return sip_threadpool;
  2925. }
  2926. int ast_sip_is_uri_sip_sips(pjsip_uri *uri)
  2927. {
  2928. return (PJSIP_URI_SCHEME_IS_SIP(uri) || PJSIP_URI_SCHEME_IS_SIPS(uri));
  2929. }
  2930. int ast_sip_is_allowed_uri(pjsip_uri *uri)
  2931. {
  2932. return (ast_sip_is_uri_sip_sips(uri) || PJSIP_URI_SCHEME_IS_TEL(uri));
  2933. }
  2934. const pj_str_t *ast_sip_pjsip_uri_get_username(pjsip_uri *uri)
  2935. {
  2936. if (ast_sip_is_uri_sip_sips(uri)) {
  2937. pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(uri);
  2938. if (!sip_uri) {
  2939. return &AST_PJ_STR_EMPTY;
  2940. }
  2941. return &sip_uri->user;
  2942. } else if (PJSIP_URI_SCHEME_IS_TEL(uri)) {
  2943. pjsip_tel_uri *tel_uri = pjsip_uri_get_uri(uri);
  2944. if (!tel_uri) {
  2945. return &AST_PJ_STR_EMPTY;
  2946. }
  2947. return &tel_uri->number;
  2948. }
  2949. return &AST_PJ_STR_EMPTY;
  2950. }
  2951. const pj_str_t *ast_sip_pjsip_uri_get_hostname(pjsip_uri *uri)
  2952. {
  2953. if (ast_sip_is_uri_sip_sips(uri)) {
  2954. pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(uri);
  2955. if (!sip_uri) {
  2956. return &AST_PJ_STR_EMPTY;
  2957. }
  2958. return &sip_uri->host;
  2959. } else if (PJSIP_URI_SCHEME_IS_TEL(uri)) {
  2960. return &AST_PJ_STR_EMPTY;
  2961. }
  2962. return &AST_PJ_STR_EMPTY;
  2963. }
  2964. struct pjsip_param *ast_sip_pjsip_uri_get_other_param(pjsip_uri *uri, const pj_str_t *param_str)
  2965. {
  2966. if (ast_sip_is_uri_sip_sips(uri)) {
  2967. pjsip_sip_uri *sip_uri = pjsip_uri_get_uri(uri);
  2968. if (!sip_uri) {
  2969. return NULL;
  2970. }
  2971. return pjsip_param_find(&sip_uri->other_param, param_str);
  2972. } else if (PJSIP_URI_SCHEME_IS_TEL(uri)) {
  2973. pjsip_tel_uri *tel_uri = pjsip_uri_get_uri(uri);
  2974. if (!tel_uri) {
  2975. return NULL;
  2976. }
  2977. return pjsip_param_find(&tel_uri->other_param, param_str);
  2978. }
  2979. return NULL;
  2980. }
  2981. /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
  2982. const int ast_sip_hangup_sip2cause(int cause)
  2983. {
  2984. /* Possible values taken from causes.h */
  2985. switch(cause) {
  2986. case 401: /* Unauthorized */
  2987. return AST_CAUSE_CALL_REJECTED;
  2988. case 403: /* Not found */
  2989. return AST_CAUSE_CALL_REJECTED;
  2990. case 404: /* Not found */
  2991. return AST_CAUSE_UNALLOCATED;
  2992. case 405: /* Method not allowed */
  2993. return AST_CAUSE_INTERWORKING;
  2994. case 407: /* Proxy authentication required */
  2995. return AST_CAUSE_CALL_REJECTED;
  2996. case 408: /* No reaction */
  2997. return AST_CAUSE_NO_USER_RESPONSE;
  2998. case 409: /* Conflict */
  2999. return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
  3000. case 410: /* Gone */
  3001. return AST_CAUSE_NUMBER_CHANGED;
  3002. case 411: /* Length required */
  3003. return AST_CAUSE_INTERWORKING;
  3004. case 413: /* Request entity too large */
  3005. return AST_CAUSE_INTERWORKING;
  3006. case 414: /* Request URI too large */
  3007. return AST_CAUSE_INTERWORKING;
  3008. case 415: /* Unsupported media type */
  3009. return AST_CAUSE_INTERWORKING;
  3010. case 420: /* Bad extension */
  3011. return AST_CAUSE_NO_ROUTE_DESTINATION;
  3012. case 480: /* No answer */
  3013. return AST_CAUSE_NO_ANSWER;
  3014. case 481: /* No answer */
  3015. return AST_CAUSE_INTERWORKING;
  3016. case 482: /* Loop detected */
  3017. return AST_CAUSE_INTERWORKING;
  3018. case 483: /* Too many hops */
  3019. return AST_CAUSE_NO_ANSWER;
  3020. case 484: /* Address incomplete */
  3021. return AST_CAUSE_INVALID_NUMBER_FORMAT;
  3022. case 485: /* Ambiguous */
  3023. return AST_CAUSE_UNALLOCATED;
  3024. case 486: /* Busy everywhere */
  3025. return AST_CAUSE_BUSY;
  3026. case 487: /* Request terminated */
  3027. return AST_CAUSE_INTERWORKING;
  3028. case 488: /* No codecs approved */
  3029. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  3030. case 491: /* Request pending */
  3031. return AST_CAUSE_INTERWORKING;
  3032. case 493: /* Undecipherable */
  3033. return AST_CAUSE_INTERWORKING;
  3034. case 500: /* Server internal failure */
  3035. return AST_CAUSE_FAILURE;
  3036. case 501: /* Call rejected */
  3037. return AST_CAUSE_FACILITY_REJECTED;
  3038. case 502:
  3039. return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
  3040. case 503: /* Service unavailable */
  3041. return AST_CAUSE_CONGESTION;
  3042. case 504: /* Gateway timeout */
  3043. return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
  3044. case 505: /* SIP version not supported */
  3045. return AST_CAUSE_INTERWORKING;
  3046. case 600: /* Busy everywhere */
  3047. return AST_CAUSE_USER_BUSY;
  3048. case 603: /* Decline */
  3049. return AST_CAUSE_CALL_REJECTED;
  3050. case 604: /* Does not exist anywhere */
  3051. return AST_CAUSE_UNALLOCATED;
  3052. case 606: /* Not acceptable */
  3053. return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
  3054. default:
  3055. if (cause < 500 && cause >= 400) {
  3056. /* 4xx class error that is unknown - someting wrong with our request */
  3057. return AST_CAUSE_INTERWORKING;
  3058. } else if (cause < 600 && cause >= 500) {
  3059. /* 5xx class error - problem in the remote end */
  3060. return AST_CAUSE_CONGESTION;
  3061. } else if (cause < 700 && cause >= 600) {
  3062. /* 6xx - global errors in the 4xx class */
  3063. return AST_CAUSE_INTERWORKING;
  3064. }
  3065. return AST_CAUSE_NORMAL;
  3066. }
  3067. /* Never reached */
  3068. return 0;
  3069. }
  3070. struct response_code_map {
  3071. int code;
  3072. const char *long_name;
  3073. const char *short_name;
  3074. };
  3075. /*
  3076. * This map was generated from sip_msg.h with
  3077. *
  3078. * sed -n -r -e 's/^\s+(PJSIP_SC_([^ =]+))\s*=\s*[0-9]+,/{ \1, "\1", "\2" },/gp' \
  3079. * third-party/pjproject/source/pjsip/include/pjsip/sip_msg.h
  3080. *
  3081. */
  3082. static const struct response_code_map rc_map[] = {
  3083. { PJSIP_SC_NULL, "PJSIP_SC_NULL", "NULL" },
  3084. { PJSIP_SC_TRYING, "PJSIP_SC_TRYING", "TRYING" },
  3085. { PJSIP_SC_RINGING, "PJSIP_SC_RINGING", "RINGING" },
  3086. { PJSIP_SC_CALL_BEING_FORWARDED, "PJSIP_SC_CALL_BEING_FORWARDED", "CALL_BEING_FORWARDED" },
  3087. { PJSIP_SC_QUEUED, "PJSIP_SC_QUEUED", "QUEUED" },
  3088. { PJSIP_SC_PROGRESS, "PJSIP_SC_PROGRESS", "PROGRESS" },
  3089. { PJSIP_SC_EARLY_DIALOG_TERMINATED, "PJSIP_SC_EARLY_DIALOG_TERMINATED", "EARLY_DIALOG_TERMINATED" },
  3090. { PJSIP_SC_OK, "PJSIP_SC_OK", "OK" },
  3091. { PJSIP_SC_ACCEPTED, "PJSIP_SC_ACCEPTED", "ACCEPTED" },
  3092. { PJSIP_SC_NO_NOTIFICATION, "PJSIP_SC_NO_NOTIFICATION", "NO_NOTIFICATION" },
  3093. { PJSIP_SC_MULTIPLE_CHOICES, "PJSIP_SC_MULTIPLE_CHOICES", "MULTIPLE_CHOICES" },
  3094. { PJSIP_SC_MOVED_PERMANENTLY, "PJSIP_SC_MOVED_PERMANENTLY", "MOVED_PERMANENTLY" },
  3095. { PJSIP_SC_MOVED_TEMPORARILY, "PJSIP_SC_MOVED_TEMPORARILY", "MOVED_TEMPORARILY" },
  3096. { PJSIP_SC_USE_PROXY, "PJSIP_SC_USE_PROXY", "USE_PROXY" },
  3097. { PJSIP_SC_ALTERNATIVE_SERVICE, "PJSIP_SC_ALTERNATIVE_SERVICE", "ALTERNATIVE_SERVICE" },
  3098. { PJSIP_SC_BAD_REQUEST, "PJSIP_SC_BAD_REQUEST", "BAD_REQUEST" },
  3099. { PJSIP_SC_UNAUTHORIZED, "PJSIP_SC_UNAUTHORIZED", "UNAUTHORIZED" },
  3100. { PJSIP_SC_PAYMENT_REQUIRED, "PJSIP_SC_PAYMENT_REQUIRED", "PAYMENT_REQUIRED" },
  3101. { PJSIP_SC_FORBIDDEN, "PJSIP_SC_FORBIDDEN", "FORBIDDEN" },
  3102. { PJSIP_SC_NOT_FOUND, "PJSIP_SC_NOT_FOUND", "NOT_FOUND" },
  3103. { PJSIP_SC_METHOD_NOT_ALLOWED, "PJSIP_SC_METHOD_NOT_ALLOWED", "METHOD_NOT_ALLOWED" },
  3104. { PJSIP_SC_NOT_ACCEPTABLE, "PJSIP_SC_NOT_ACCEPTABLE", "NOT_ACCEPTABLE" },
  3105. { PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED, "PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED", "PROXY_AUTHENTICATION_REQUIRED" },
  3106. { PJSIP_SC_REQUEST_TIMEOUT, "PJSIP_SC_REQUEST_TIMEOUT", "REQUEST_TIMEOUT" },
  3107. { PJSIP_SC_CONFLICT, "PJSIP_SC_CONFLICT", "CONFLICT" },
  3108. { PJSIP_SC_GONE, "PJSIP_SC_GONE", "GONE" },
  3109. { PJSIP_SC_LENGTH_REQUIRED, "PJSIP_SC_LENGTH_REQUIRED", "LENGTH_REQUIRED" },
  3110. { PJSIP_SC_CONDITIONAL_REQUEST_FAILED, "PJSIP_SC_CONDITIONAL_REQUEST_FAILED", "CONDITIONAL_REQUEST_FAILED" },
  3111. { PJSIP_SC_REQUEST_ENTITY_TOO_LARGE, "PJSIP_SC_REQUEST_ENTITY_TOO_LARGE", "REQUEST_ENTITY_TOO_LARGE" },
  3112. { PJSIP_SC_REQUEST_URI_TOO_LONG, "PJSIP_SC_REQUEST_URI_TOO_LONG", "REQUEST_URI_TOO_LONG" },
  3113. { PJSIP_SC_UNSUPPORTED_MEDIA_TYPE, "PJSIP_SC_UNSUPPORTED_MEDIA_TYPE", "UNSUPPORTED_MEDIA_TYPE" },
  3114. { PJSIP_SC_UNSUPPORTED_URI_SCHEME, "PJSIP_SC_UNSUPPORTED_URI_SCHEME", "UNSUPPORTED_URI_SCHEME" },
  3115. { PJSIP_SC_UNKNOWN_RESOURCE_PRIORITY, "PJSIP_SC_UNKNOWN_RESOURCE_PRIORITY", "UNKNOWN_RESOURCE_PRIORITY" },
  3116. { PJSIP_SC_BAD_EXTENSION, "PJSIP_SC_BAD_EXTENSION", "BAD_EXTENSION" },
  3117. { PJSIP_SC_EXTENSION_REQUIRED, "PJSIP_SC_EXTENSION_REQUIRED", "EXTENSION_REQUIRED" },
  3118. { PJSIP_SC_SESSION_TIMER_TOO_SMALL, "PJSIP_SC_SESSION_TIMER_TOO_SMALL", "SESSION_TIMER_TOO_SMALL" },
  3119. { PJSIP_SC_INTERVAL_TOO_BRIEF, "PJSIP_SC_INTERVAL_TOO_BRIEF", "INTERVAL_TOO_BRIEF" },
  3120. { PJSIP_SC_BAD_LOCATION_INFORMATION, "PJSIP_SC_BAD_LOCATION_INFORMATION", "BAD_LOCATION_INFORMATION" },
  3121. { PJSIP_SC_USE_IDENTITY_HEADER, "PJSIP_SC_USE_IDENTITY_HEADER", "USE_IDENTITY_HEADER" },
  3122. { PJSIP_SC_PROVIDE_REFERRER_HEADER, "PJSIP_SC_PROVIDE_REFERRER_HEADER", "PROVIDE_REFERRER_HEADER" },
  3123. { PJSIP_SC_FLOW_FAILED, "PJSIP_SC_FLOW_FAILED", "FLOW_FAILED" },
  3124. { PJSIP_SC_ANONIMITY_DISALLOWED, "PJSIP_SC_ANONIMITY_DISALLOWED", "ANONIMITY_DISALLOWED" },
  3125. { PJSIP_SC_BAD_IDENTITY_INFO, "PJSIP_SC_BAD_IDENTITY_INFO", "BAD_IDENTITY_INFO" },
  3126. { PJSIP_SC_UNSUPPORTED_CERTIFICATE, "PJSIP_SC_UNSUPPORTED_CERTIFICATE", "UNSUPPORTED_CERTIFICATE" },
  3127. { PJSIP_SC_INVALID_IDENTITY_HEADER, "PJSIP_SC_INVALID_IDENTITY_HEADER", "INVALID_IDENTITY_HEADER" },
  3128. { PJSIP_SC_FIRST_HOP_LACKS_OUTBOUND_SUPPORT, "PJSIP_SC_FIRST_HOP_LACKS_OUTBOUND_SUPPORT", "FIRST_HOP_LACKS_OUTBOUND_SUPPORT" },
  3129. { PJSIP_SC_MAX_BREADTH_EXCEEDED, "PJSIP_SC_MAX_BREADTH_EXCEEDED", "MAX_BREADTH_EXCEEDED" },
  3130. { PJSIP_SC_BAD_INFO_PACKAGE, "PJSIP_SC_BAD_INFO_PACKAGE", "BAD_INFO_PACKAGE" },
  3131. { PJSIP_SC_CONSENT_NEEDED, "PJSIP_SC_CONSENT_NEEDED", "CONSENT_NEEDED" },
  3132. { PJSIP_SC_TEMPORARILY_UNAVAILABLE, "PJSIP_SC_TEMPORARILY_UNAVAILABLE", "TEMPORARILY_UNAVAILABLE" },
  3133. { PJSIP_SC_CALL_TSX_DOES_NOT_EXIST, "PJSIP_SC_CALL_TSX_DOES_NOT_EXIST", "CALL_TSX_DOES_NOT_EXIST" },
  3134. { PJSIP_SC_LOOP_DETECTED, "PJSIP_SC_LOOP_DETECTED", "LOOP_DETECTED" },
  3135. { PJSIP_SC_TOO_MANY_HOPS, "PJSIP_SC_TOO_MANY_HOPS", "TOO_MANY_HOPS" },
  3136. { PJSIP_SC_ADDRESS_INCOMPLETE, "PJSIP_SC_ADDRESS_INCOMPLETE", "ADDRESS_INCOMPLETE" },
  3137. { PJSIP_SC_BUSY_HERE, "PJSIP_SC_BUSY_HERE", "BUSY_HERE" },
  3138. { PJSIP_SC_REQUEST_TERMINATED, "PJSIP_SC_REQUEST_TERMINATED", "REQUEST_TERMINATED" },
  3139. { PJSIP_SC_NOT_ACCEPTABLE_HERE, "PJSIP_SC_NOT_ACCEPTABLE_HERE", "NOT_ACCEPTABLE_HERE" },
  3140. { PJSIP_SC_BAD_EVENT, "PJSIP_SC_BAD_EVENT", "BAD_EVENT" },
  3141. { PJSIP_SC_REQUEST_UPDATED, "PJSIP_SC_REQUEST_UPDATED", "REQUEST_UPDATED" },
  3142. { PJSIP_SC_REQUEST_PENDING, "PJSIP_SC_REQUEST_PENDING", "REQUEST_PENDING" },
  3143. { PJSIP_SC_UNDECIPHERABLE, "PJSIP_SC_UNDECIPHERABLE", "UNDECIPHERABLE" },
  3144. { PJSIP_SC_SECURITY_AGREEMENT_NEEDED, "PJSIP_SC_SECURITY_AGREEMENT_NEEDED", "SECURITY_AGREEMENT_NEEDED" },
  3145. { PJSIP_SC_INTERNAL_SERVER_ERROR, "PJSIP_SC_INTERNAL_SERVER_ERROR", "INTERNAL_SERVER_ERROR" },
  3146. { PJSIP_SC_NOT_IMPLEMENTED, "PJSIP_SC_NOT_IMPLEMENTED", "NOT_IMPLEMENTED" },
  3147. { PJSIP_SC_BAD_GATEWAY, "PJSIP_SC_BAD_GATEWAY", "BAD_GATEWAY" },
  3148. { PJSIP_SC_SERVICE_UNAVAILABLE, "PJSIP_SC_SERVICE_UNAVAILABLE", "SERVICE_UNAVAILABLE" },
  3149. { PJSIP_SC_SERVER_TIMEOUT, "PJSIP_SC_SERVER_TIMEOUT", "SERVER_TIMEOUT" },
  3150. { PJSIP_SC_VERSION_NOT_SUPPORTED, "PJSIP_SC_VERSION_NOT_SUPPORTED", "VERSION_NOT_SUPPORTED" },
  3151. { PJSIP_SC_MESSAGE_TOO_LARGE, "PJSIP_SC_MESSAGE_TOO_LARGE", "MESSAGE_TOO_LARGE" },
  3152. { PJSIP_SC_PUSH_NOTIFICATION_SERVICE_NOT_SUPPORTED, "PJSIP_SC_PUSH_NOTIFICATION_SERVICE_NOT_SUPPORTED", "PUSH_NOTIFICATION_SERVICE_NOT_SUPPORTED" },
  3153. { PJSIP_SC_PRECONDITION_FAILURE, "PJSIP_SC_PRECONDITION_FAILURE", "PRECONDITION_FAILURE" },
  3154. { PJSIP_SC_BUSY_EVERYWHERE, "PJSIP_SC_BUSY_EVERYWHERE", "BUSY_EVERYWHERE" },
  3155. { PJSIP_SC_DECLINE, "PJSIP_SC_DECLINE", "DECLINE" },
  3156. { PJSIP_SC_DOES_NOT_EXIST_ANYWHERE, "PJSIP_SC_DOES_NOT_EXIST_ANYWHERE", "DOES_NOT_EXIST_ANYWHERE" },
  3157. { PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE, "PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE", "NOT_ACCEPTABLE_ANYWHERE" },
  3158. { PJSIP_SC_UNWANTED, "PJSIP_SC_UNWANTED", "UNWANTED" },
  3159. { PJSIP_SC_REJECTED, "PJSIP_SC_REJECTED", "REJECTED" },
  3160. };
  3161. int ast_sip_str2rc(const char *name)
  3162. {
  3163. int i;
  3164. if (ast_strlen_zero(name)) {
  3165. return -1;
  3166. }
  3167. for (i = 0; i < ARRAY_LEN(rc_map); i++) {
  3168. if (strcasecmp(rc_map[i].short_name, name) == 0 ||
  3169. strcasecmp(rc_map[i].long_name, name) == 0) {
  3170. return rc_map[i].code;
  3171. }
  3172. }
  3173. return -1;
  3174. }
  3175. #ifdef TEST_FRAMEWORK
  3176. AST_TEST_DEFINE(xml_sanitization_end_null)
  3177. {
  3178. char sanitized[8];
  3179. switch (cmd) {
  3180. case TEST_INIT:
  3181. info->name = "xml_sanitization_end_null";
  3182. info->category = "/res/res_pjsip/";
  3183. info->summary = "Ensure XML sanitization works as expected with a long string";
  3184. info->description = "This test sanitizes a string which exceeds the output\n"
  3185. "buffer size. Once done the string is confirmed to be NULL terminated.";
  3186. return AST_TEST_NOT_RUN;
  3187. case TEST_EXECUTE:
  3188. break;
  3189. }
  3190. ast_sip_sanitize_xml("aaaaaaaaaaaa", sanitized, sizeof(sanitized));
  3191. if (sanitized[7] != '\0') {
  3192. ast_test_status_update(test, "Sanitized XML string is not null-terminated when it should be\n");
  3193. return AST_TEST_FAIL;
  3194. }
  3195. return AST_TEST_PASS;
  3196. }
  3197. AST_TEST_DEFINE(xml_sanitization_exceeds_buffer)
  3198. {
  3199. char sanitized[8];
  3200. switch (cmd) {
  3201. case TEST_INIT:
  3202. info->name = "xml_sanitization_exceeds_buffer";
  3203. info->category = "/res/res_pjsip/";
  3204. info->summary = "Ensure XML sanitization does not exceed buffer when output won't fit";
  3205. info->description = "This test sanitizes a string which before sanitization would\n"
  3206. "fit within the output buffer. After sanitization, however, the string would\n"
  3207. "exceed the buffer. Once done the string is confirmed to be NULL terminated.";
  3208. return AST_TEST_NOT_RUN;
  3209. case TEST_EXECUTE:
  3210. break;
  3211. }
  3212. ast_sip_sanitize_xml("<><><>&", sanitized, sizeof(sanitized));
  3213. if (sanitized[7] != '\0') {
  3214. ast_test_status_update(test, "Sanitized XML string is not null-terminated when it should be\n");
  3215. return AST_TEST_FAIL;
  3216. }
  3217. return AST_TEST_PASS;
  3218. }
  3219. #endif
  3220. /*!
  3221. * \internal
  3222. * \brief Reload configuration within a PJSIP thread
  3223. */
  3224. static int reload_configuration_task(void *obj)
  3225. {
  3226. ast_res_pjsip_reload_configuration();
  3227. ast_res_pjsip_init_options_handling(1);
  3228. ast_sip_initialize_dns();
  3229. return 0;
  3230. }
  3231. static int unload_pjsip(void *data)
  3232. {
  3233. /*
  3234. * These calls need the pjsip endpoint and serializer to clean up.
  3235. * If they're not set, then there's nothing to clean up anyway.
  3236. */
  3237. if (ast_pjsip_endpoint && sip_serializer_pool) {
  3238. ast_res_pjsip_cleanup_options_handling();
  3239. ast_res_pjsip_cleanup_message_filter();
  3240. ast_sip_destroy_distributor();
  3241. ast_sip_destroy_transport_management();
  3242. ast_res_pjsip_destroy_configuration();
  3243. ast_sip_destroy_system();
  3244. ast_sip_destroy_global_headers();
  3245. ast_sip_unregister_service(&supplement_module);
  3246. ast_sip_destroy_transport_events();
  3247. }
  3248. if (monitor_thread) {
  3249. stop_monitor_thread();
  3250. monitor_thread = NULL;
  3251. }
  3252. if (memory_pool) {
  3253. /* This mimics the behavior of pj_pool_safe_release
  3254. * which was introduced in pjproject 2.6.
  3255. */
  3256. pj_pool_t *temp_pool = memory_pool;
  3257. memory_pool = NULL;
  3258. pj_pool_release(temp_pool);
  3259. }
  3260. ast_pjsip_endpoint = NULL;
  3261. if (caching_pool.lock) {
  3262. ast_pjproject_caching_pool_destroy(&caching_pool);
  3263. }
  3264. pj_shutdown();
  3265. return 0;
  3266. }
  3267. static int load_pjsip(void)
  3268. {
  3269. const unsigned int flags = 0; /* no port, no brackets */
  3270. pj_status_t status;
  3271. /* The third parameter is just copied from
  3272. * example code from PJLIB. This can be adjusted
  3273. * if necessary.
  3274. */
  3275. ast_pjproject_caching_pool_init(&caching_pool, NULL, 1024 * 1024);
  3276. if (pjsip_endpt_create(&caching_pool.factory, "SIP", &ast_pjsip_endpoint) != PJ_SUCCESS) {
  3277. ast_log(LOG_ERROR, "Failed to create PJSIP endpoint structure. Aborting load\n");
  3278. goto error;
  3279. }
  3280. /* PJSIP will automatically try to add a Max-Forwards header. Since we want to control that,
  3281. * we need to stop PJSIP from doing it automatically
  3282. */
  3283. remove_request_headers(ast_pjsip_endpoint);
  3284. memory_pool = pj_pool_create(&caching_pool.factory, "SIP", 1024, 1024, NULL);
  3285. if (!memory_pool) {
  3286. ast_log(LOG_ERROR, "Failed to create memory pool for SIP. Aborting load\n");
  3287. goto error;
  3288. }
  3289. if (!pj_gethostip(pj_AF_INET(), &host_ip_ipv4)) {
  3290. pj_sockaddr_print(&host_ip_ipv4, host_ip_ipv4_string, sizeof(host_ip_ipv4_string), flags);
  3291. ast_verb(3, "Local IPv4 address determined to be: %s\n", host_ip_ipv4_string);
  3292. }
  3293. if (!pj_gethostip(pj_AF_INET6(), &host_ip_ipv6)) {
  3294. pj_sockaddr_print(&host_ip_ipv6, host_ip_ipv6_string, sizeof(host_ip_ipv6_string), flags);
  3295. ast_verb(3, "Local IPv6 address determined to be: %s\n", host_ip_ipv6_string);
  3296. }
  3297. pjsip_tsx_layer_init_module(ast_pjsip_endpoint);
  3298. pjsip_ua_init_module(ast_pjsip_endpoint, NULL);
  3299. monitor_continue = 1;
  3300. status = pj_thread_create(memory_pool, "SIP", (pj_thread_proc *) &monitor_thread_exec,
  3301. NULL, PJ_THREAD_DEFAULT_STACK_SIZE * 2, 0, &monitor_thread);
  3302. if (status != PJ_SUCCESS) {
  3303. ast_log(LOG_ERROR, "Failed to start SIP monitor thread. Aborting load\n");
  3304. goto error;
  3305. }
  3306. return AST_MODULE_LOAD_SUCCESS;
  3307. error:
  3308. return AST_MODULE_LOAD_DECLINE;
  3309. }
  3310. /*
  3311. * This is a place holder function to ensure that pjmedia_strerr() is at
  3312. * least directly referenced by this module to ensure that the loader
  3313. * linker will link to the function. If a module only indirectly
  3314. * references a function from another module, such as a callback parameter
  3315. * to a function, the loader linker has been known to miss the link.
  3316. */
  3317. void never_called_res_pjsip(void);
  3318. void never_called_res_pjsip(void)
  3319. {
  3320. pjmedia_strerror(0, NULL, 0);
  3321. }
  3322. /* Definitions of media types declared "extern" in res_pjsip.h */
  3323. pjsip_media_type pjsip_media_type_application_json;
  3324. pjsip_media_type pjsip_media_type_application_media_control_xml;
  3325. pjsip_media_type pjsip_media_type_application_pidf_xml;
  3326. pjsip_media_type pjsip_media_type_application_xpidf_xml;
  3327. pjsip_media_type pjsip_media_type_application_cpim_xpidf_xml;
  3328. pjsip_media_type pjsip_media_type_application_rlmi_xml;
  3329. pjsip_media_type pjsip_media_type_application_simple_message_summary;
  3330. pjsip_media_type pjsip_media_type_application_sdp;
  3331. pjsip_media_type pjsip_media_type_multipart_alternative;
  3332. pjsip_media_type pjsip_media_type_multipart_mixed;
  3333. pjsip_media_type pjsip_media_type_multipart_related;
  3334. pjsip_media_type pjsip_media_type_text_plain;
  3335. static int load_module(void)
  3336. {
  3337. struct ast_threadpool_options options;
  3338. /* pjproject and config_system need to be initialized before all else */
  3339. if (pj_init() != PJ_SUCCESS) {
  3340. return AST_MODULE_LOAD_DECLINE;
  3341. }
  3342. if (pjlib_util_init() != PJ_SUCCESS) {
  3343. goto error;
  3344. }
  3345. /* Register PJMEDIA error codes for SDP parsing errors */
  3346. if (pj_register_strerror(PJMEDIA_ERRNO_START, PJ_ERRNO_SPACE_SIZE, pjmedia_strerror)
  3347. != PJ_SUCCESS) {
  3348. ast_log(LOG_WARNING, "Failed to register pjmedia error codes. Codes will not be decoded.\n");
  3349. }
  3350. /* Initialize common media types */
  3351. pjsip_media_type_init2(&pjsip_media_type_application_json, "application", "json");
  3352. pjsip_media_type_init2(&pjsip_media_type_application_media_control_xml, "application", "media_control+xml");
  3353. pjsip_media_type_init2(&pjsip_media_type_application_pidf_xml, "application", "pidf+xml");
  3354. pjsip_media_type_init2(&pjsip_media_type_application_xpidf_xml, "application", "xpidf+xml");
  3355. pjsip_media_type_init2(&pjsip_media_type_application_cpim_xpidf_xml, "application", "cpim-xpidf+xml");
  3356. pjsip_media_type_init2(&pjsip_media_type_application_rlmi_xml, "application", "rlmi+xml");
  3357. pjsip_media_type_init2(&pjsip_media_type_application_sdp, "application", "sdp");
  3358. pjsip_media_type_init2(&pjsip_media_type_application_simple_message_summary, "application", "simple-message-summary");
  3359. pjsip_media_type_init2(&pjsip_media_type_multipart_alternative, "multipart", "alternative");
  3360. pjsip_media_type_init2(&pjsip_media_type_multipart_mixed, "multipart", "mixed");
  3361. pjsip_media_type_init2(&pjsip_media_type_multipart_related, "multipart", "related");
  3362. pjsip_media_type_init2(&pjsip_media_type_text_plain, "text", "plain");
  3363. if (ast_sip_initialize_system()) {
  3364. ast_log(LOG_ERROR, "Failed to initialize SIP 'system' configuration section. Aborting load\n");
  3365. goto error;
  3366. }
  3367. /* The serializer needs threadpool and threadpool needs pjproject to be initialized so it's next */
  3368. sip_get_threadpool_options(&options);
  3369. options.thread_start = sip_thread_start;
  3370. sip_threadpool = ast_threadpool_create("pjsip", NULL, &options);
  3371. if (!sip_threadpool) {
  3372. goto error;
  3373. }
  3374. sip_serializer_pool = ast_serializer_pool_create(
  3375. "pjsip/default", SERIALIZER_POOL_SIZE, sip_threadpool, -1);
  3376. if (!sip_serializer_pool) {
  3377. ast_log(LOG_ERROR, "Failed to create SIP serializer pool. Aborting load\n");
  3378. goto error;
  3379. }
  3380. if (ast_sip_initialize_scheduler()) {
  3381. ast_log(LOG_ERROR, "Failed to start scheduler. Aborting load\n");
  3382. goto error;
  3383. }
  3384. /* Now load all the pjproject infrastructure. */
  3385. if (load_pjsip()) {
  3386. goto error;
  3387. }
  3388. if (ast_sip_initialize_transport_events()) {
  3389. ast_log(LOG_ERROR, "Failed to initialize SIP transport monitor. Aborting load\n");
  3390. goto error;
  3391. }
  3392. ast_sip_initialize_dns();
  3393. ast_sip_initialize_global_headers();
  3394. if (ast_res_pjsip_preinit_options_handling()) {
  3395. ast_log(LOG_ERROR, "Failed to pre-initialize OPTIONS handling. Aborting load\n");
  3396. goto error;
  3397. }
  3398. if (ast_res_pjsip_initialize_configuration()) {
  3399. ast_log(LOG_ERROR, "Failed to initialize SIP configuration. Aborting load\n");
  3400. goto error;
  3401. }
  3402. ast_sip_initialize_resolver();
  3403. ast_sip_initialize_dns();
  3404. if (ast_sip_initialize_transport_management()) {
  3405. ast_log(LOG_ERROR, "Failed to initialize SIP transport management. Aborting load\n");
  3406. goto error;
  3407. }
  3408. if (ast_sip_initialize_distributor()) {
  3409. ast_log(LOG_ERROR, "Failed to register distributor module. Aborting load\n");
  3410. goto error;
  3411. }
  3412. if (ast_sip_register_service(&supplement_module)) {
  3413. ast_log(LOG_ERROR, "Failed to initialize supplement hooks. Aborting load\n");
  3414. goto error;
  3415. }
  3416. if (ast_res_pjsip_init_options_handling(0)) {
  3417. ast_log(LOG_ERROR, "Failed to initialize OPTIONS handling. Aborting load\n");
  3418. goto error;
  3419. }
  3420. /*
  3421. * It is OK to prune the contacts now that
  3422. * ast_res_pjsip_init_options_handling() has added the contact observer
  3423. * of res/res_pjsip/pjsip_options.c to sorcery (to ensure that any
  3424. * pruned contacts are removed from this module's data structure).
  3425. */
  3426. ast_sip_location_prune_boot_contacts();
  3427. if (ast_res_pjsip_init_message_filter()) {
  3428. ast_log(LOG_ERROR, "Failed to initialize message IP updating. Aborting load\n");
  3429. goto error;
  3430. }
  3431. ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
  3432. AST_TEST_REGISTER(xml_sanitization_end_null);
  3433. AST_TEST_REGISTER(xml_sanitization_exceeds_buffer);
  3434. return AST_MODULE_LOAD_SUCCESS;
  3435. error:
  3436. unload_pjsip(NULL);
  3437. /* These functions all check for NULLs and are safe to call at any time */
  3438. ast_sip_destroy_scheduler();
  3439. ast_serializer_pool_destroy(sip_serializer_pool);
  3440. ast_threadpool_shutdown(sip_threadpool);
  3441. return AST_MODULE_LOAD_DECLINE;
  3442. }
  3443. static int reload_module(void)
  3444. {
  3445. /*
  3446. * We must wait for the reload to complete so multiple
  3447. * reloads cannot happen at the same time.
  3448. */
  3449. if (ast_sip_push_task_wait_servant(NULL, reload_configuration_task, NULL)) {
  3450. ast_log(LOG_WARNING, "Failed to reload PJSIP\n");
  3451. return -1;
  3452. }
  3453. return 0;
  3454. }
  3455. static int unload_module(void)
  3456. {
  3457. AST_TEST_UNREGISTER(xml_sanitization_end_null);
  3458. AST_TEST_UNREGISTER(xml_sanitization_exceeds_buffer);
  3459. ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
  3460. /* The thread this is called from cannot call PJSIP/PJLIB functions,
  3461. * so we have to push the work to the threadpool to handle
  3462. */
  3463. ast_sip_push_task_wait_servant(NULL, unload_pjsip, NULL);
  3464. ast_sip_destroy_scheduler();
  3465. ast_serializer_pool_destroy(sip_serializer_pool);
  3466. ast_threadpool_shutdown(sip_threadpool);
  3467. return 0;
  3468. }
  3469. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Basic SIP resource",
  3470. .support_level = AST_MODULE_SUPPORT_CORE,
  3471. .load = load_module,
  3472. .unload = unload_module,
  3473. .reload = reload_module,
  3474. .load_pri = AST_MODPRI_CHANNEL_DEPEND - 5,
  3475. .requires = "dnsmgr,res_pjproject,res_sorcery_config,res_sorcery_memory,res_sorcery_astdb",
  3476. .optional_modules = "res_geolocation,res_statsd",
  3477. );