chan_sip.c 288 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376
  1. /*
  2. * Asterisk -- A telephony toolkit for Linux.
  3. *
  4. * Implementation of Session Initiation Protocol
  5. *
  6. * Copyright (C) 2004, Digium, Inc.
  7. *
  8. * Mark Spencer <markster@digium.com>
  9. *
  10. * This program is free software, distributed under the terms of
  11. * the GNU General Public License
  12. */
  13. #include <stdio.h>
  14. #include <ctype.h>
  15. #include <string.h>
  16. #include <asterisk/lock.h>
  17. #include <asterisk/channel.h>
  18. #include <asterisk/channel_pvt.h>
  19. #include <asterisk/config.h>
  20. #include <asterisk/logger.h>
  21. #include <asterisk/module.h>
  22. #include <asterisk/pbx.h>
  23. #include <asterisk/options.h>
  24. #include <asterisk/lock.h>
  25. #include <asterisk/sched.h>
  26. #include <asterisk/io.h>
  27. #include <asterisk/rtp.h>
  28. #include <asterisk/acl.h>
  29. #include <asterisk/manager.h>
  30. #include <asterisk/callerid.h>
  31. #include <asterisk/cli.h>
  32. #include <asterisk/md5.h>
  33. #include <asterisk/app.h>
  34. #include <asterisk/musiconhold.h>
  35. #include <asterisk/dsp.h>
  36. #include <asterisk/features.h>
  37. #include <asterisk/acl.h>
  38. #include <asterisk/srv.h>
  39. #include <asterisk/astdb.h>
  40. #include <asterisk/causes.h>
  41. #include <asterisk/utils.h>
  42. #ifdef OSP_SUPPORT
  43. #include <asterisk/astosp.h>
  44. #endif
  45. #include <sys/socket.h>
  46. #include <sys/ioctl.h>
  47. #include <net/if.h>
  48. #include <errno.h>
  49. #include <unistd.h>
  50. #include <stdlib.h>
  51. #include <fcntl.h>
  52. #include <netdb.h>
  53. #include <arpa/inet.h>
  54. #include <signal.h>
  55. #include <sys/signal.h>
  56. #include <netinet/in_systm.h>
  57. #include <netinet/ip.h>
  58. #ifdef SIP_MYSQL_FRIENDS
  59. #define MYSQL_FRIENDS
  60. #include <mysql/mysql.h>
  61. #endif
  62. #ifndef DEFAULT_USERAGENT
  63. #define DEFAULT_USERAGENT "Asterisk PBX"
  64. #endif
  65. #define VIDEO_CODEC_MASK 0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
  66. #ifndef IPTOS_MINCOST
  67. #define IPTOS_MINCOST 0x02
  68. #endif
  69. /* #define VOCAL_DATA_HACK */
  70. #define SIPDUMPER
  71. #define DEFAULT_DEFAULT_EXPIRY 120
  72. #define DEFAULT_MAX_EXPIRY 3600
  73. /* guard limit must be larger than guard secs */
  74. /* guard min must be < 1000, and should be >= 250 */
  75. #define EXPIRY_GUARD_SECS 15 /* How long before expiry do we reregister */
  76. #define EXPIRY_GUARD_LIMIT 30 /* Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */
  77. #define EXPIRY_GUARD_MIN 500 /* This is the minimum guard time applied. If GUARD_PCT turns out
  78. to be lower than this, it will use this time instead. This is in
  79. milliseconds. */
  80. #define EXPIRY_GUARD_PCT 0.20 /* Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT */
  81. #ifndef MAX
  82. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  83. #endif
  84. #define CALLERID_UNKNOWN "Unknown"
  85. /* --- Choices for DTMF support in SIP channel */
  86. #define SIP_DTMF_RFC2833 (1 << 0)
  87. #define SIP_DTMF_INBAND (1 << 1)
  88. #define SIP_DTMF_INFO (1 << 2)
  89. static int max_expiry = DEFAULT_MAX_EXPIRY;
  90. static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
  91. #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
  92. #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
  93. #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
  94. #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
  95. #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
  96. /* MYSQL_FRIENDS: Check if peer exists in database and read some configuration
  97. from databse (not all options supported though) */
  98. #ifdef MYSQL_FRIENDS
  99. AST_MUTEX_DEFINE_STATIC(mysqllock);
  100. static MYSQL *mysql;
  101. static char mydbuser[80];
  102. static char mydbpass[80];
  103. static char mydbhost[80];
  104. static char mydbname[80];
  105. #endif
  106. /* SIP Debug */
  107. #define DEBUG_READ 0 /* Recieved data */
  108. #define DEBUG_SEND 1 /* Transmit data */
  109. static char *desc = "Session Initiation Protocol (SIP)";
  110. static char *type = "SIP";
  111. static char *tdesc = "Session Initiation Protocol (SIP)";
  112. static char *config = "sip.conf";
  113. #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
  114. /* From RFC2543, this should be 1500, so it's up to the ability of
  115. remote devices as to whether it will be accepted when more than that*/
  116. #define SIP_MAX_PACKET 4096
  117. #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
  118. static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
  119. static char default_context[AST_MAX_EXTENSION] = "default";
  120. static char default_language[MAX_LANGUAGE] = "";
  121. static char default_callerid[AST_MAX_EXTENSION] = "asterisk";
  122. static char default_fromdomain[AST_MAX_EXTENSION] = "";
  123. static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
  124. static int srvlookup = 0;
  125. static int pedanticsipchecking = 0;
  126. static int autocreatepeer = 0;
  127. static int relaxdtmf = 0;
  128. static int global_rtptimeout = 0;
  129. static int global_rtpholdtimeout = 0;
  130. static int global_trustrpid = 0;
  131. static int global_progressinband = 0;
  132. #ifdef OSP_SUPPORT
  133. static int global_ospauth = 0;
  134. #endif
  135. static int usecnt =0;
  136. AST_MUTEX_DEFINE_STATIC(usecnt_lock);
  137. /* Protect the interface list (of sip_pvt's) */
  138. AST_MUTEX_DEFINE_STATIC(iflock);
  139. /* Protect the monitoring thread, so only one process can kill or start it, and not
  140. when it's doing something critical. */
  141. AST_MUTEX_DEFINE_STATIC(netlock);
  142. AST_MUTEX_DEFINE_STATIC(monlock);
  143. /* This is the thread for the monitor which checks for input on the channels
  144. which are not currently in use. */
  145. static pthread_t monitor_thread = AST_PTHREADT_NULL;
  146. static int restart_monitor(void);
  147. /* Codecs that we support by default: */
  148. static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
  149. static int noncodeccapability = AST_RTP_DTMF;
  150. static struct in_addr __ourip;
  151. static int ourport;
  152. static int sipdebug = 0;
  153. static struct sockaddr_in debugaddr;
  154. static int tos = 0;
  155. static int videosupport = 0;
  156. static int global_dtmfmode = SIP_DTMF_RFC2833; /* DTMF mode default */
  157. static int recordhistory = 0;
  158. static int global_promiscredir;
  159. static char global_musicclass[MAX_LANGUAGE] = ""; /* Global music on hold class */
  160. static char global_realm[MAXHOSTNAMELEN] = "asterisk"; /* Default realm */
  161. static char regcontext[AST_MAX_EXTENSION] = "";
  162. /* Expire slowly */
  163. static int expiry = 900;
  164. static struct sched_context *sched;
  165. static struct io_context *io;
  166. /* The private structures of the sip channels are linked for
  167. selecting outgoing channels */
  168. #define SIP_MAX_HEADERS 64
  169. #define SIP_MAX_LINES 64
  170. #define DEC_IN_USE 0
  171. #define INC_IN_USE 1
  172. #define DEC_OUT_USE 2
  173. #define INC_OUT_USE 3
  174. static struct ast_codec_pref prefs;
  175. /* sip_request: The data grabbed from the UDP socket */
  176. struct sip_request {
  177. char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
  178. char *rlPart2; /* The Request URI or Response Status */
  179. int len;
  180. int headers; /* SIP Headers */
  181. char *header[SIP_MAX_HEADERS];
  182. int lines; /* SDP Content */
  183. char *line[SIP_MAX_LINES];
  184. char data[SIP_MAX_PACKET];
  185. };
  186. struct sip_pkt;
  187. struct sip_route {
  188. struct sip_route *next;
  189. char hop[0];
  190. };
  191. struct sip_history {
  192. char event[80];
  193. struct sip_history *next;
  194. };
  195. /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call */
  196. static struct sip_pvt {
  197. ast_mutex_t lock; /* Channel private lock */
  198. char callid[80]; /* Global CallID */
  199. char randdata[80]; /* Random data */
  200. struct ast_codec_pref prefs; /* codec prefs */
  201. unsigned int ocseq; /* Current outgoing seqno */
  202. unsigned int icseq; /* Current incoming seqno */
  203. unsigned int callgroup; /* Call group */
  204. unsigned int pickupgroup; /* Pickup group */
  205. int lastinvite; /* Last Cseq of invite */
  206. int alreadygone; /* Whether or not we've already been destroyed by or peer */
  207. int needdestroy; /* if we need to be destroyed */
  208. int capability; /* Special capability (codec) */
  209. int novideo; /* Didn't get video in invite, don't offer */
  210. int jointcapability; /* Supported capability at both ends (codecs ) */
  211. int peercapability; /* Supported peer capability */
  212. int prefcodec; /* Preferred codec (outbound only) */
  213. int noncodeccapability;
  214. int outgoing; /* Outgoing or incoming call? */
  215. int authtries; /* Times we've tried to authenticate */
  216. int insecure; /* Don't check source port/ip */
  217. int expiry; /* How long we take to expire */
  218. int branch; /* One random number */
  219. int canreinvite; /* Do we support reinvite */
  220. int ringing; /* Have sent 180 ringing */
  221. int progress; /* Have sent 183 message progress */
  222. int tag; /* Another random number */
  223. int nat; /* Whether to try to support NAT */
  224. int sessionid; /* SDP Session ID */
  225. int sessionversion; /* SDP Session Version */
  226. struct sockaddr_in sa; /* Our peer */
  227. struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
  228. struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
  229. int redircodecs; /* Redirect codecs */
  230. struct sockaddr_in recv; /* Received as */
  231. struct in_addr ourip; /* Our IP */
  232. struct ast_channel *owner; /* Who owns us */
  233. char exten[AST_MAX_EXTENSION]; /* Extension where to start */
  234. char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
  235. char referred_by[AST_MAX_EXTENSION]; /* Place to store REFERRED-BY extension */
  236. char refer_contact[AST_MAX_EXTENSION]; /* Place to store Contact info from a REFER extension */
  237. struct sip_pvt *refer_call; /* Call we are referring */
  238. struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
  239. int route_persistant; /* Is this the "real" route? */
  240. char from[256]; /* The From: header */
  241. char useragent[256]; /* User agent in SIP request */
  242. char context[AST_MAX_EXTENSION]; /* Context for this call */
  243. char fromdomain[MAXHOSTNAMELEN]; /* Domain to show in the from field */
  244. char fromuser[AST_MAX_EXTENSION]; /* User to show in the user field */
  245. char fromname[AST_MAX_EXTENSION]; /* Name to show in the user field */
  246. char tohost[MAXHOSTNAMELEN]; /* Host we should put in the "to" field */
  247. char language[MAX_LANGUAGE]; /* Default language for this call */
  248. char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
  249. char rdnis[256]; /* Referring DNIS */
  250. char theirtag[256]; /* Their tag */
  251. char username[256];
  252. char peername[256];
  253. char authname[256]; /* Who we use for authentication */
  254. char uri[256]; /* Original requested URI */
  255. char peersecret[256];
  256. char peermd5secret[256];
  257. char callerid[256]; /* Caller*ID */
  258. int restrictcid; /* hide presentation from remote user */
  259. char via[256];
  260. char fullcontact[128]; /* Extra parameters to go in the "To" header */
  261. char accountcode[20]; /* Account code */
  262. char our_contact[256]; /* Our contact header */
  263. char realm[MAXHOSTNAMELEN]; /* Authorization realm */
  264. char nonce[256]; /* Authorization nonce */
  265. char opaque[256]; /* Opaque nonsense */
  266. char qop[80]; /* Quality of Protection, since SIP wasn't complicated enough yet. */
  267. char domain[MAXHOSTNAMELEN]; /* Authorization domain */
  268. char lastmsg[256]; /* Last Message sent/received */
  269. int amaflags; /* AMA Flags */
  270. int pendinginvite; /* Any pending invite */
  271. int needreinvite; /* Do we need to send another reinvite? */
  272. int pendingbye; /* Need to send bye after we ack? */
  273. int gotrefer; /* Got a refer? */
  274. #ifdef OSP_SUPPORT
  275. int ospauth; /* Allow OSP Authentication */
  276. int osphandle; /* OSP Handle for call */
  277. time_t ospstart; /* OSP Start time */
  278. #endif
  279. struct sip_request initreq; /* Initial request */
  280. int maxtime; /* Max time for first response */
  281. int initid; /* Auto-congest ID if appropriate */
  282. int autokillid; /* Auto-kill ID */
  283. time_t lastrtprx; /* Last RTP received */
  284. int rtptimeout; /* RTP timeout time */
  285. int rtpholdtimeout; /* RTP timeout when on hold */
  286. int subscribed;
  287. int stateid;
  288. int dialogver;
  289. int promiscredir; /* Promiscuous redirection */
  290. int trustrpid;
  291. int progressinband;
  292. int dtmfmode;
  293. struct ast_dsp *vad;
  294. struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
  295. struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
  296. struct ast_rtp *rtp; /* RTP Session */
  297. struct ast_rtp *vrtp; /* Video RTP session */
  298. struct sip_pkt *packets; /* Packets scheduled for re-transmission */
  299. struct sip_history *history; /* History of this SIP dialog */
  300. struct sip_pvt *next; /* Next call in chain */
  301. } *iflist = NULL;
  302. #define FLAG_RESPONSE (1 << 0)
  303. #define FLAG_FATAL (1 << 1)
  304. /* sip packet - read in sipsock_read, transmitted in send_request */
  305. struct sip_pkt {
  306. struct sip_pkt *next; /* Next packet */
  307. int retrans; /* Retransmission number */
  308. int seqno; /* Sequence number */
  309. int flags; /* non-zero if this is a response packet (e.g. 200 OK) */
  310. struct sip_pvt *owner; /* Owner call */
  311. int retransid; /* Retransmission ID */
  312. int packetlen; /* Length of packet */
  313. char data[0];
  314. };
  315. /* Structure for SIP user data. User's place calls to us */
  316. struct sip_user {
  317. /* Users who can access various contexts */
  318. char name[80];
  319. char secret[80];
  320. char md5secret[80];
  321. char context[AST_MAX_EXTENSION];
  322. char callerid[80];
  323. char accountcode[20];
  324. char language[MAX_LANGUAGE];
  325. char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
  326. char useragent[256]; /* User agent in SIP request */
  327. unsigned int callgroup;
  328. unsigned int pickupgroup;
  329. struct ast_codec_pref prefs; /* codec prefs */
  330. int nat;
  331. int hascallerid;
  332. int amaflags;
  333. int insecure;
  334. int canreinvite;
  335. int capability;
  336. #ifdef OSP_SUPPORT
  337. int ospauth; /* Allow OSP Authentication */
  338. #endif
  339. int dtmfmode;
  340. int inUse;
  341. int incominglimit;
  342. int outUse;
  343. int outgoinglimit;
  344. int promiscredir;
  345. int restrictcid;
  346. int trustrpid;
  347. int progressinband;
  348. struct ast_ha *ha;
  349. #ifdef MYSQL_USERS
  350. int temponly;
  351. #endif /* MYSQL_FRIENDS */
  352. struct sip_user *next;
  353. };
  354. /* Structure for SIP peer data, we place calls to peers if registred or fixed IP address (host) */
  355. struct sip_peer {
  356. char name[80];
  357. char secret[80];
  358. char md5secret[80];
  359. char context[AST_MAX_EXTENSION]; /* JK02: peers need context too to allow parking etc */
  360. char username[80];
  361. char tohost[MAXHOSTNAMELEN];
  362. char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
  363. char fromuser[80];
  364. char fromdomain[MAXHOSTNAMELEN];
  365. char fullcontact[256];
  366. char mailbox[AST_MAX_EXTENSION];
  367. char language[MAX_LANGUAGE];
  368. char musicclass[MAX_LANGUAGE]; /* Music on Hold class */
  369. char useragent[256]; /* User agent in SIP request */
  370. struct ast_codec_pref prefs; /* codec prefs */
  371. int lastmsgssent;
  372. time_t lastmsgcheck;
  373. int dynamic;
  374. int expire;
  375. int expiry;
  376. int capability;
  377. int rtptimeout;
  378. int rtpholdtimeout;
  379. int insecure;
  380. #ifdef OSP_SUPPORT
  381. int ospauth; /* Allow OSP Authentication */
  382. #endif
  383. int nat;
  384. int canreinvite;
  385. unsigned int callgroup;
  386. unsigned int pickupgroup;
  387. int promiscredir;
  388. int dtmfmode;
  389. int trustrpid;
  390. int progressinband;
  391. struct sockaddr_in addr;
  392. struct in_addr mask;
  393. /* Qualification */
  394. struct sip_pvt *call; /* Call pointer */
  395. int pokeexpire; /* When to expire poke */
  396. int lastms; /* How long last response took (in ms), or -1 for no response */
  397. int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
  398. struct timeval ps; /* Ping send time */
  399. struct sockaddr_in defaddr;
  400. struct ast_ha *ha;
  401. int delme;
  402. int selfdestruct;
  403. int lastmsg;
  404. int temponly;
  405. struct sip_peer *next;
  406. };
  407. AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
  408. static int sip_reloading = 0;
  409. #define REG_STATE_UNREGISTERED 0
  410. #define REG_STATE_REGSENT 1
  411. #define REG_STATE_AUTHSENT 2
  412. #define REG_STATE_REGISTERED 3
  413. #define REG_STATE_REJECTED 4
  414. #define REG_STATE_TIMEOUT 5
  415. #define REG_STATE_NOAUTH 6
  416. #define SIP_NAT_NEVER 0
  417. #define SIP_NAT_RFC3581 (1 << 0)
  418. #define SIP_NAT_ROUTE (1 << 2)
  419. #define SIP_NAT_ALWAYS (SIP_NAT_ROUTE | SIP_NAT_RFC3581)
  420. /* sip_registry: Registrations with other SIP proxies */
  421. struct sip_registry {
  422. int portno; /* Optional port override */
  423. char username[80]; /* Who we are registering as */
  424. char authuser[80]; /* Who we *authenticate* as */
  425. char hostname[MAXHOSTNAMELEN];
  426. char secret[80]; /* Password or key name in []'s */
  427. char md5secret[80];
  428. char contact[256]; /* Contact extension */
  429. char random[80];
  430. int expire; /* Sched ID of expiration */
  431. int timeout; /* sched id of sip_reg_timeout */
  432. int refresh; /* How often to refresh */
  433. struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
  434. int regstate;
  435. int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
  436. char callid[80]; /* Global CallID for this registry */
  437. unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
  438. struct sockaddr_in us; /* Who the server thinks we are */
  439. /* Saved headers */
  440. char realm[MAXHOSTNAMELEN]; /* Authorization realm */
  441. char nonce[256]; /* Authorization nonce */
  442. char domain[MAXHOSTNAMELEN]; /* Authorization domain */
  443. char opaque[256]; /* Opaque nonsense */
  444. char qop[80]; /* Quality of Protection. */
  445. char lastmsg[256]; /* Last Message sent/received */
  446. struct sip_registry *next;
  447. };
  448. /*--- The user list: Users and friends ---*/
  449. static struct ast_user_list {
  450. struct sip_user *users;
  451. ast_mutex_t lock;
  452. } userl;
  453. /*--- The peer list: Peers and Friends ---*/
  454. static struct ast_peer_list {
  455. struct sip_peer *peers;
  456. ast_mutex_t lock;
  457. } peerl;
  458. /*--- The register list: Other SIP proxys we register with and call ---*/
  459. static struct ast_register_list {
  460. struct sip_registry *registrations;
  461. ast_mutex_t lock;
  462. int recheck;
  463. } regl;
  464. #define REINVITE_INVITE 1
  465. #define REINVITE_UPDATE 2
  466. static int __sip_do_register(struct sip_registry *r);
  467. static int sipsock = -1;
  468. static int global_nat = SIP_NAT_RFC3581;
  469. static int global_canreinvite = REINVITE_INVITE;
  470. static struct sockaddr_in bindaddr;
  471. static struct sockaddr_in externip;
  472. static struct ast_ha *localaddr;
  473. static struct ast_frame *sip_read(struct ast_channel *ast);
  474. static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
  475. static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
  476. static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header);
  477. static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
  478. static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
  479. static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, char *osptoken,int init);
  480. static int transmit_reinvite_with_sdp(struct sip_pvt *p);
  481. static int transmit_info_with_digit(struct sip_pvt *p, char digit);
  482. static int transmit_message_with_text(struct sip_pvt *p, char *text);
  483. static int transmit_refer(struct sip_pvt *p, char *dest);
  484. static struct sip_peer *temp_peer(char *name);
  485. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
  486. static void free_old_route(struct sip_route *route);
  487. static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
  488. static int update_user_counter(struct sip_pvt *fup, int event);
  489. static void prune_peers(void);
  490. static int sip_do_reload(void);
  491. /*--- sip_debug_test_addr: See if we pass debug IP filter */
  492. static inline int sip_debug_test_addr(struct sockaddr_in *addr)
  493. {
  494. if (sipdebug == 0)
  495. return 0;
  496. if (debugaddr.sin_addr.s_addr) {
  497. if (((ntohs(debugaddr.sin_port) != 0)
  498. && (debugaddr.sin_port != addr->sin_port))
  499. || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
  500. return 0;
  501. }
  502. return 1;
  503. }
  504. static inline int sip_debug_test_pvt(struct sip_pvt *p)
  505. {
  506. if (sipdebug == 0)
  507. return 0;
  508. return sip_debug_test_addr(((p->nat & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
  509. }
  510. /*--- __sip_xmit: Transmit SIP message ---*/
  511. static int __sip_xmit(struct sip_pvt *p, char *data, int len)
  512. {
  513. int res;
  514. char iabuf[INET_ADDRSTRLEN];
  515. // ast_log(LOG_WARNING, "__sip_xmit from '%s' to '%s'\n", "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
  516. if (p->nat & SIP_NAT_ROUTE)
  517. res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
  518. else
  519. res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
  520. if (res != len) {
  521. ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, strerror(errno));
  522. }
  523. return res;
  524. }
  525. static void sip_destroy(struct sip_pvt *p);
  526. /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
  527. /* Only used for outbound registrations */
  528. static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
  529. {
  530. /*
  531. * Using the localaddr structure built up with localnet statements
  532. * apply it to their address to see if we need to substitute our
  533. * externip or can get away with our internal bindaddr
  534. */
  535. struct sockaddr_in theirs;
  536. theirs.sin_addr = *them;
  537. if (localaddr && externip.sin_addr.s_addr &&
  538. ast_apply_ha(localaddr, &theirs)) {
  539. char iabuf[INET_ADDRSTRLEN];
  540. memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
  541. ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
  542. ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
  543. }
  544. else if (bindaddr.sin_addr.s_addr)
  545. memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
  546. else
  547. return ast_ouraddrfor(them, us);
  548. return 0;
  549. }
  550. static int append_history(struct sip_pvt *p, char *event, char *data)
  551. {
  552. struct sip_history *hist, *prev;
  553. char *c;
  554. if (!recordhistory)
  555. return 0;
  556. hist = malloc(sizeof(struct sip_history));
  557. if (hist) {
  558. memset(hist, 0, sizeof(struct sip_history));
  559. snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
  560. /* Trim up nicely */
  561. c = hist->event;
  562. while(*c) {
  563. if ((*c == '\r') || (*c == '\n')) {
  564. *c = '\0';
  565. break;
  566. }
  567. c++;
  568. }
  569. /* Enqueue into history */
  570. prev = p->history;
  571. if (prev) {
  572. while(prev->next)
  573. prev = prev->next;
  574. prev->next = hist;
  575. } else {
  576. p->history = hist;
  577. }
  578. }
  579. return 0;
  580. }
  581. /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
  582. static int retrans_pkt(void *data)
  583. {
  584. struct sip_pkt *pkt=data, *prev, *cur;
  585. int res = 0;
  586. char iabuf[INET_ADDRSTRLEN];
  587. ast_mutex_lock(&pkt->owner->lock);
  588. if (pkt->retrans < MAX_RETRANS) {
  589. pkt->retrans++;
  590. if (sip_debug_test_pvt(pkt->owner)) {
  591. if (pkt->owner->nat & SIP_NAT_ROUTE)
  592. ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
  593. else
  594. ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
  595. }
  596. append_history(pkt->owner, "ReTx", pkt->data);
  597. __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
  598. res = 1;
  599. } else {
  600. ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (pkt->flags & FLAG_FATAL) ? "Critical" : "Non-critical", (pkt->flags & FLAG_RESPONSE) ? "Response" : "Request");
  601. append_history(pkt->owner, "MaxRetries", pkt->flags & FLAG_FATAL ? "(Critical)" : "(Non-critical)");
  602. pkt->retransid = -1;
  603. if (pkt->flags & FLAG_FATAL) {
  604. while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
  605. ast_mutex_unlock(&pkt->owner->lock);
  606. usleep(1);
  607. ast_mutex_lock(&pkt->owner->lock);
  608. }
  609. if (pkt->owner->owner) {
  610. pkt->owner->alreadygone=1;
  611. ast_queue_hangup(pkt->owner->owner);
  612. ast_mutex_unlock(&pkt->owner->owner->lock);
  613. } else {
  614. /* If no owner, destroy now */
  615. pkt->owner->needdestroy = 1;
  616. }
  617. }
  618. /* In any case, go ahead and remove the packet */
  619. prev = NULL;
  620. cur = pkt->owner->packets;
  621. while(cur) {
  622. if (cur == pkt)
  623. break;
  624. prev = cur;
  625. cur = cur->next;
  626. }
  627. if (cur) {
  628. if (prev)
  629. prev->next = cur->next;
  630. else
  631. pkt->owner->packets = cur->next;
  632. ast_mutex_unlock(&pkt->owner->lock);
  633. free(cur);
  634. pkt = NULL;
  635. } else
  636. ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
  637. }
  638. if (pkt)
  639. ast_mutex_unlock(&pkt->owner->lock);
  640. return res;
  641. }
  642. /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
  643. static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
  644. {
  645. struct sip_pkt *pkt;
  646. pkt = malloc(sizeof(struct sip_pkt) + len + 1);
  647. if (!pkt)
  648. return -1;
  649. memset(pkt, 0, sizeof(struct sip_pkt));
  650. memcpy(pkt->data, data, len);
  651. pkt->packetlen = len;
  652. pkt->next = p->packets;
  653. pkt->owner = p;
  654. pkt->seqno = seqno;
  655. pkt->flags = resp;
  656. pkt->data[len] = '\0';
  657. if (fatal)
  658. pkt->flags |= FLAG_FATAL;
  659. /* Schedule retransmission */
  660. pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
  661. pkt->next = p->packets;
  662. p->packets = pkt;
  663. __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
  664. if (!strncasecmp(pkt->data, "INVITE", 6)) {
  665. /* Note this is a pending invite */
  666. p->pendinginvite = seqno;
  667. }
  668. return 0;
  669. }
  670. /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
  671. static int __sip_autodestruct(void *data)
  672. {
  673. struct sip_pvt *p = data;
  674. p->autokillid = -1;
  675. ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
  676. append_history(p, "AutoDestroy", "");
  677. if (p->owner) {
  678. ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
  679. ast_queue_hangup(p->owner);
  680. } else {
  681. sip_destroy(p);
  682. }
  683. return 0;
  684. }
  685. /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
  686. static int sip_scheddestroy(struct sip_pvt *p, int ms)
  687. {
  688. char tmp[80];
  689. if (sip_debug_test_pvt(p))
  690. ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
  691. if (recordhistory) {
  692. snprintf(tmp, sizeof(tmp), "%d ms", ms);
  693. append_history(p, "SchedDestroy", tmp);
  694. }
  695. if (p->autokillid > -1)
  696. ast_sched_del(sched, p->autokillid);
  697. p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
  698. return 0;
  699. }
  700. /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
  701. static int sip_cancel_destroy(struct sip_pvt *p)
  702. {
  703. if (p->autokillid > -1)
  704. ast_sched_del(sched, p->autokillid);
  705. append_history(p, "CancelDestroy", "");
  706. p->autokillid = -1;
  707. return 0;
  708. }
  709. /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
  710. static int __sip_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
  711. {
  712. struct sip_pkt *cur, *prev = NULL;
  713. int res = -1;
  714. int resetinvite = 0;
  715. /* Just in case... */
  716. if (!msg) msg = "___NEVER___";
  717. cur = p->packets;
  718. while(cur) {
  719. if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp) &&
  720. ((cur->flags & FLAG_RESPONSE) ||
  721. (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
  722. if (!resp && (seqno == p->pendinginvite)) {
  723. ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
  724. p->pendinginvite = 0;
  725. resetinvite = 1;
  726. }
  727. /* this is our baby */
  728. if (prev)
  729. prev->next = cur->next;
  730. else
  731. p->packets = cur->next;
  732. if (cur->retransid > -1)
  733. ast_sched_del(sched, cur->retransid);
  734. free(cur);
  735. res = 0;
  736. break;
  737. }
  738. prev = cur;
  739. cur = cur->next;
  740. }
  741. ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
  742. return res;
  743. }
  744. /* Pretend to ack all packets */
  745. static int __sip_pretend_ack(struct sip_pvt *p)
  746. {
  747. while(p->packets) {
  748. __sip_ack(p, p->packets->seqno, (p->packets->flags & FLAG_RESPONSE), p->packets->data);
  749. }
  750. return 0;
  751. }
  752. /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
  753. static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, const char *msg)
  754. {
  755. struct sip_pkt *cur;
  756. int res = -1;
  757. cur = p->packets;
  758. while(cur) {
  759. if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp) &&
  760. ((cur->flags & FLAG_RESPONSE) ||
  761. (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
  762. /* this is our baby */
  763. if (cur->retransid > -1)
  764. ast_sched_del(sched, cur->retransid);
  765. cur->retransid = -1;
  766. res = 0;
  767. break;
  768. }
  769. cur = cur->next;
  770. }
  771. ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
  772. return res;
  773. }
  774. static void parse(struct sip_request *req);
  775. static char *get_header(struct sip_request *req, char *name);
  776. static void copy_request(struct sip_request *dst,struct sip_request *src);
  777. static void parse_copy(struct sip_request *dst, struct sip_request *src)
  778. {
  779. memset(dst, 0, sizeof(*dst));
  780. memcpy(dst->data, src->data, sizeof(dst->data));
  781. dst->len = src->len;
  782. parse(dst);
  783. }
  784. /*--- send_response: Transmit response on SIP request---*/
  785. static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
  786. {
  787. int res;
  788. char iabuf[INET_ADDRSTRLEN];
  789. struct sip_request tmp;
  790. char tmpmsg[80];
  791. if (sip_debug_test_pvt(p)) {
  792. if (p->nat & SIP_NAT_ROUTE)
  793. ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
  794. else
  795. ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
  796. }
  797. if (reliable) {
  798. if (recordhistory) {
  799. parse_copy(&tmp, req);
  800. snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
  801. append_history(p, "TxRespRel", tmpmsg);
  802. }
  803. res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
  804. } else {
  805. if (recordhistory) {
  806. parse_copy(&tmp, req);
  807. snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
  808. append_history(p, "TxResp", tmpmsg);
  809. }
  810. res = __sip_xmit(p, req->data, req->len);
  811. }
  812. if (res > 0)
  813. res = 0;
  814. return res;
  815. }
  816. /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
  817. static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
  818. {
  819. int res;
  820. char iabuf[INET_ADDRSTRLEN];
  821. struct sip_request tmp;
  822. char tmpmsg[80];
  823. if (sip_debug_test_pvt(p)) {
  824. if (p->nat & SIP_NAT_ROUTE)
  825. ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
  826. else
  827. ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
  828. }
  829. if (reliable) {
  830. if (recordhistory) {
  831. parse_copy(&tmp, req);
  832. snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
  833. append_history(p, "TxReqRel", tmpmsg);
  834. }
  835. res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
  836. } else {
  837. if (recordhistory) {
  838. parse_copy(&tmp, req);
  839. snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
  840. append_history(p, "TxReq", tmpmsg);
  841. }
  842. res = __sip_xmit(p, req->data, req->len);
  843. }
  844. return res;
  845. }
  846. /*--- url_decode: Decode SIP URL ---*/
  847. static void url_decode(char *s)
  848. {
  849. char *o = s;
  850. unsigned int tmp;
  851. while(*s) {
  852. switch(*s) {
  853. case '%':
  854. if (strlen(s) > 2) {
  855. if (sscanf(s + 1, "%2x", &tmp) == 1) {
  856. *o = tmp;
  857. s += 2; /* Will be incremented once more when we break out */
  858. break;
  859. }
  860. }
  861. /* Fall through if something wasn't right with the formatting */
  862. default:
  863. *o = *s;
  864. }
  865. s++;
  866. o++;
  867. }
  868. *o = '\0';
  869. }
  870. /*--- ditch_braces: Pick out text in braces from character string ---*/
  871. static char *ditch_braces(char *tmp)
  872. {
  873. char *c = tmp;
  874. char *n;
  875. char *q;
  876. if ((q = strchr(tmp, '"')) ) {
  877. c = q + 1;
  878. if ((q = strchr(c, '"')) )
  879. c = q + 1;
  880. else {
  881. ast_log(LOG_WARNING, "No closing quote in '%s'\n", tmp);
  882. c = tmp;
  883. }
  884. }
  885. if ((n = strchr(c, '<')) ) {
  886. c = n + 1;
  887. while(*c && *c != '>') c++;
  888. if (*c != '>') {
  889. ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
  890. } else {
  891. *c = '\0';
  892. }
  893. return n+1;
  894. }
  895. return c;
  896. }
  897. /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
  898. /* Called from PBX core text message functions */
  899. static int sip_sendtext(struct ast_channel *ast, char *text)
  900. {
  901. struct sip_pvt *p = ast->pvt->pvt;
  902. int debug=sip_debug_test_pvt(p);
  903. if (debug)
  904. ast_verbose("Sending text %s on %s\n", text, ast->name);
  905. if (!p)
  906. return -1;
  907. if (!text || ast_strlen_zero(text))
  908. return 0;
  909. if (debug)
  910. ast_verbose("Really sending text %s on %s\n", text, ast->name);
  911. transmit_message_with_text(p, text);
  912. return 0;
  913. }
  914. #ifdef MYSQL_USERS
  915. /* Ehud Gavron 08-Jun-2004: */
  916. /* The Mysql stuff works great for peers but not for users. */
  917. /* Unfortunately multi-line phones (e.g. cisco 7960) and many */
  918. /* SIP users behind the same NAT gateway need users. So.... */
  919. /* */
  920. /* mysql_update_user is not needed */
  921. /*--- mysql_host: Get user from database ---*/
  922. static struct sip_user *mysql_user(char *user)
  923. {
  924. struct sip_user *u;
  925. int success = 0;
  926. u = malloc(sizeof(struct sip_user));
  927. memset(u, 0, sizeof(struct sip_user));
  928. if (mysql && (!user || (strlen(user) < 128))) {
  929. char query[512];
  930. char *name = NULL;
  931. int numfields, x;
  932. time_t regseconds, nowtime;
  933. MYSQL_RES *result;
  934. MYSQL_FIELD *fields;
  935. MYSQL_ROW rowval;
  936. if (user) {
  937. name = alloca(strlen(user) * 2 + 1);
  938. mysql_real_escape_string(mysql, name, user, strlen(user));
  939. }
  940. snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds, callerid, restrictcid FROM sipfriends WHERE name=\"%s\"", name);
  941. ast_mutex_lock(&mysqllock);
  942. mysql_query(mysql, query);
  943. if ((result = mysql_store_result(mysql))) {
  944. if ((rowval = mysql_fetch_row(result))) {
  945. numfields = mysql_num_fields(result);
  946. fields = mysql_fetch_fields(result);
  947. success = 1;
  948. for (x=0;x<numfields;x++) {
  949. if (rowval[x]) {
  950. if (!strcasecmp(fields[x].name, "secret")) {
  951. strncpy(u->secret, rowval[x], sizeof(u->secret) - 1);
  952. } else if (!strcasecmp(fields[x].name, "name")) {
  953. strncpy(u->name, rowval[x], sizeof(u->name) - 1);
  954. } else if (!strcasecmp(fields[x].name, "context")) {
  955. strncpy(u->context, rowval[x], sizeof(u->context) - 1);
  956. } else if (!strcasecmp(fields[x].name, "username")) {
  957. strncpy(u->name, rowval[x], sizeof(u->name) - 1);
  958. } else if (!strcasecmp(fields[x].name, "regseconds")) {
  959. if (sscanf(rowval[x], "%li", &regseconds) != 1)
  960. regseconds = 0;
  961. } else if (!strcasecmp(fields[x].name, "restrictcid")) {
  962. u->restrictcid = *(rowval[x])-'0';
  963. } else if (!strcasecmp(fields[x].name, "callerid")) {
  964. strncpy(u->callerid, rowval[x], sizeof(u->callerid) - 1);
  965. u->hascallerid=1;
  966. }
  967. }
  968. }
  969. time(&nowtime);
  970. }
  971. mysql_free_result(result);
  972. result = NULL;
  973. }
  974. ast_mutex_unlock(&mysqllock);
  975. }
  976. if (!success) {
  977. free(u);
  978. u = NULL;
  979. } else {
  980. u->capability = global_capability;
  981. u->nat = global_nat;
  982. u->dtmfmode = global_dtmfmode;
  983. u->insecure = 1;
  984. u->temponly = 1;
  985. }
  986. return u;
  987. }
  988. #endif /* MYSQL_USERS */
  989. #ifdef MYSQL_FRIENDS
  990. /*--- mysql_update_peer: Update peer from database ---*/
  991. /* This function adds registration state to database */
  992. static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
  993. {
  994. if (mysql && (strlen(peer) < 128)) {
  995. char query[512];
  996. char *name;
  997. char *uname;
  998. char iabuf[INET_ADDRSTRLEN];
  999. time_t nowtime;
  1000. name = alloca(strlen(peer) * 2 + 1);
  1001. uname = alloca(strlen(username) * 2 + 1);
  1002. time(&nowtime);
  1003. mysql_real_escape_string(mysql, name, peer, strlen(peer));
  1004. mysql_real_escape_string(mysql, uname, username, strlen(username));
  1005. snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
  1006. ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
  1007. ast_mutex_lock(&mysqllock);
  1008. if (mysql_real_query(mysql, query, strlen(query)))
  1009. ast_log(LOG_WARNING, "Unable to update database\n");
  1010. ast_mutex_unlock(&mysqllock);
  1011. }
  1012. }
  1013. /*--- mysql_peer: Get peer from database ---*/
  1014. static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
  1015. {
  1016. struct sip_peer *p;
  1017. int success = 0;
  1018. p = malloc(sizeof(struct sip_peer));
  1019. memset(p, 0, sizeof(struct sip_peer));
  1020. if (mysql && (!peer || (strlen(peer) < 128))) {
  1021. char query[512];
  1022. char *name = NULL;
  1023. int numfields, x;
  1024. int port;
  1025. char iabuf[INET_ADDRSTRLEN];
  1026. time_t regseconds, nowtime;
  1027. MYSQL_RES *result;
  1028. MYSQL_FIELD *fields;
  1029. MYSQL_ROW rowval;
  1030. if (peer) {
  1031. name = alloca(strlen(peer) * 2 + 1);
  1032. mysql_real_escape_string(mysql, name, peer, strlen(peer));
  1033. }
  1034. if (sin)
  1035. snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
  1036. else
  1037. snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
  1038. ast_mutex_lock(&mysqllock);
  1039. mysql_query(mysql, query);
  1040. if ((result = mysql_store_result(mysql))) {
  1041. if ((rowval = mysql_fetch_row(result))) {
  1042. numfields = mysql_num_fields(result);
  1043. fields = mysql_fetch_fields(result);
  1044. success = 1;
  1045. p->addr.sin_family = AF_INET;
  1046. for (x=0;x<numfields;x++) {
  1047. if (rowval[x]) {
  1048. if (!strcasecmp(fields[x].name, "secret")) {
  1049. strncpy(p->secret, rowval[x], sizeof(p->secret) - 1);
  1050. } else if (!strcasecmp(fields[x].name, "name")) {
  1051. strncpy(p->name, rowval[x], sizeof(p->name) - 1);
  1052. } else if (!strcasecmp(fields[x].name, "context")) {
  1053. strncpy(p->context, rowval[x], sizeof(p->context) - 1);
  1054. } else if (!strcasecmp(fields[x].name, "username")) {
  1055. strncpy(p->username, rowval[x], sizeof(p->username) - 1);
  1056. } else if (!strcasecmp(fields[x].name, "ipaddr")) {
  1057. inet_aton(rowval[x], &p->addr.sin_addr);
  1058. } else if (!strcasecmp(fields[x].name, "port")) {
  1059. if (sscanf(rowval[x], "%i", &port) != 1)
  1060. port = 0;
  1061. p->addr.sin_port = htons(port);
  1062. } else if (!strcasecmp(fields[x].name, "regseconds")) {
  1063. if (sscanf(rowval[x], "%li", &regseconds) != 1)
  1064. regseconds = 0;
  1065. }
  1066. }
  1067. }
  1068. time(&nowtime);
  1069. if (nowtime > regseconds)
  1070. memset(&p->addr, 0, sizeof(p->addr));
  1071. }
  1072. mysql_free_result(result);
  1073. result = NULL;
  1074. }
  1075. ast_mutex_unlock(&mysqllock);
  1076. }
  1077. if (!success) {
  1078. free(p);
  1079. p = NULL;
  1080. } else {
  1081. p->dynamic = 1;
  1082. p->capability = global_capability;
  1083. p->nat = global_nat;
  1084. p->dtmfmode = global_dtmfmode;
  1085. p->promiscredir = global_promiscredir;
  1086. p->insecure = 1;
  1087. p->pokeexpire = -1;
  1088. p->expire = -1;
  1089. p->temponly = 1;
  1090. }
  1091. return p;
  1092. }
  1093. #endif /* MYSQL_FRIENDS */
  1094. /*--- update_peer: Update peer data in database (if used) ---*/
  1095. static void update_peer(struct sip_peer *p, int expiry)
  1096. {
  1097. #ifdef MYSQL_FRIENDS
  1098. if (p->temponly)
  1099. mysql_update_peer(p->name, &p->addr, p->username, expiry);
  1100. #endif
  1101. return;
  1102. }
  1103. /*--- find_peer: Locate peer by name or ip address */
  1104. static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
  1105. {
  1106. struct sip_peer *p = NULL;
  1107. p = peerl.peers;
  1108. if (peer) {
  1109. /* Find by peer name */
  1110. while(p) {
  1111. if (!strcasecmp(p->name, peer)) {
  1112. break;
  1113. }
  1114. p = p->next;
  1115. }
  1116. }
  1117. else {
  1118. /* Find by sin */
  1119. while(p) {
  1120. if (!inaddrcmp(&p->addr, sin) ||
  1121. (p->insecure &&
  1122. (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
  1123. break;
  1124. }
  1125. p = p->next;
  1126. }
  1127. }
  1128. #ifdef MYSQL_FRIENDS
  1129. if (!p) {
  1130. p = mysql_peer(peer, sin);
  1131. }
  1132. #endif
  1133. return(p);
  1134. }
  1135. /*--- find_user: Locate user by name */
  1136. static struct sip_user *find_user(char *name)
  1137. {
  1138. struct sip_user *u = NULL;
  1139. u = userl.users;
  1140. while(u) {
  1141. if (!strcasecmp(u->name, name)) {
  1142. break;
  1143. }
  1144. u = u->next;
  1145. }
  1146. #ifdef MYSQL_USERS
  1147. if (!u) {
  1148. u = mysql_user(name);
  1149. }
  1150. #endif /* MYSQL_USERS */
  1151. return(u);
  1152. }
  1153. /*--- create_addr: create address structure from peer definition ---*/
  1154. /* Or, if peer not found, find it in the global DNS */
  1155. /* returns TRUE on failure, FALSE on success */
  1156. static int create_addr(struct sip_pvt *r, char *opeer)
  1157. {
  1158. struct hostent *hp;
  1159. struct ast_hostent ahp;
  1160. struct sip_peer *p;
  1161. int found=0;
  1162. char *port;
  1163. char *callhost;
  1164. int portno;
  1165. char host[MAXHOSTNAMELEN], *hostn;
  1166. char peer[256]="";
  1167. strncpy(peer, opeer, sizeof(peer) - 1);
  1168. port = strchr(peer, ':');
  1169. if (port) {
  1170. *port = '\0';
  1171. port++;
  1172. }
  1173. r->sa.sin_family = AF_INET;
  1174. ast_mutex_lock(&peerl.lock);
  1175. p = find_peer(peer, NULL);
  1176. if (p) {
  1177. found++;
  1178. r->capability = p->capability;
  1179. r->nat = p->nat;
  1180. if (r->rtp) {
  1181. ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (r->nat & SIP_NAT_ROUTE));
  1182. ast_rtp_setnat(r->rtp, (r->nat & SIP_NAT_ROUTE));
  1183. }
  1184. if (r->vrtp) {
  1185. ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (r->nat & SIP_NAT_ROUTE));
  1186. ast_rtp_setnat(r->vrtp, (r->nat & SIP_NAT_ROUTE));
  1187. }
  1188. strncpy(r->peername, p->username, sizeof(r->peername)-1);
  1189. strncpy(r->authname, p->username, sizeof(r->authname)-1);
  1190. strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
  1191. strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
  1192. strncpy(r->username, p->username, sizeof(r->username)-1);
  1193. strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
  1194. strncpy(r->fullcontact, p->fullcontact, sizeof(r->fullcontact)-1);
  1195. if (!r->initreq.headers && !ast_strlen_zero(p->fromdomain)) {
  1196. if ((callhost = strchr(r->callid, '@'))) {
  1197. strncpy(callhost + 1, p->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
  1198. }
  1199. }
  1200. if (ast_strlen_zero(r->tohost)) {
  1201. if (p->addr.sin_addr.s_addr)
  1202. ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->addr.sin_addr);
  1203. else
  1204. ast_inet_ntoa(r->tohost, sizeof(r->tohost), p->defaddr.sin_addr);
  1205. }
  1206. if (!ast_strlen_zero(p->fromdomain))
  1207. strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
  1208. if (!ast_strlen_zero(p->fromuser))
  1209. strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
  1210. r->insecure = p->insecure;
  1211. r->canreinvite = p->canreinvite;
  1212. r->maxtime = p->maxms;
  1213. r->callgroup = p->callgroup;
  1214. r->pickupgroup = p->pickupgroup;
  1215. if (p->dtmfmode) {
  1216. r->dtmfmode = p->dtmfmode;
  1217. if (r->dtmfmode & SIP_DTMF_RFC2833)
  1218. r->noncodeccapability |= AST_RTP_DTMF;
  1219. else
  1220. r->noncodeccapability &= ~AST_RTP_DTMF;
  1221. }
  1222. r->promiscredir = p->promiscredir;
  1223. strncpy(r->context, p->context,sizeof(r->context)-1);
  1224. r->rtptimeout = p->rtptimeout;
  1225. r->rtpholdtimeout = p->rtpholdtimeout;
  1226. if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
  1227. (!p->maxms || ((p->lastms >= 0) && (p->lastms <= p->maxms)))) {
  1228. if (p->addr.sin_addr.s_addr) {
  1229. r->sa.sin_addr = p->addr.sin_addr;
  1230. r->sa.sin_port = p->addr.sin_port;
  1231. } else {
  1232. r->sa.sin_addr = p->defaddr.sin_addr;
  1233. r->sa.sin_port = p->defaddr.sin_port;
  1234. }
  1235. memcpy(&r->recv, &r->sa, sizeof(r->recv));
  1236. } else {
  1237. if (p->temponly) {
  1238. if (p->ha) {
  1239. ast_free_ha(p->ha);
  1240. }
  1241. free(p);
  1242. }
  1243. p = NULL;
  1244. }
  1245. }
  1246. ast_mutex_unlock(&peerl.lock);
  1247. if (!p && !found) {
  1248. hostn = peer;
  1249. if (port)
  1250. portno = atoi(port);
  1251. else
  1252. portno = DEFAULT_SIP_PORT;
  1253. if (srvlookup) {
  1254. char service[MAXHOSTNAMELEN];
  1255. int tportno;
  1256. int ret;
  1257. snprintf(service, sizeof(service), "_sip._udp.%s", peer);
  1258. ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
  1259. if (ret > 0) {
  1260. hostn = host;
  1261. portno = tportno;
  1262. }
  1263. }
  1264. hp = ast_gethostbyname(hostn, &ahp);
  1265. if (hp) {
  1266. strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
  1267. memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
  1268. r->sa.sin_port = htons(portno);
  1269. memcpy(&r->recv, &r->sa, sizeof(r->recv));
  1270. return 0;
  1271. } else {
  1272. ast_log(LOG_WARNING, "No such host: %s\n", peer);
  1273. return -1;
  1274. }
  1275. } else if (!p)
  1276. return -1;
  1277. else {
  1278. if (p->temponly) {
  1279. if (p->ha) {
  1280. ast_free_ha(p->ha);
  1281. }
  1282. free(p);
  1283. }
  1284. return 0;
  1285. }
  1286. }
  1287. /*--- auto_congest: Scheduled congestion on a call ---*/
  1288. static int auto_congest(void *nothing)
  1289. {
  1290. struct sip_pvt *p = nothing;
  1291. ast_mutex_lock(&p->lock);
  1292. p->initid = -1;
  1293. if (p->owner) {
  1294. if (!ast_mutex_trylock(&p->owner->lock)) {
  1295. ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
  1296. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  1297. ast_mutex_unlock(&p->owner->lock);
  1298. }
  1299. }
  1300. ast_mutex_unlock(&p->lock);
  1301. return 0;
  1302. }
  1303. /*--- sip_call: Initiate SIP call from PBX ---*/
  1304. /* used from the dial() application */
  1305. static int sip_call(struct ast_channel *ast, char *dest, int timeout)
  1306. {
  1307. int res;
  1308. struct sip_pvt *p;
  1309. char *vxml_url = NULL;
  1310. char *distinctive_ring = NULL;
  1311. char *osptoken = NULL;
  1312. #ifdef OSP_SUPPORT
  1313. char *osphandle = NULL;
  1314. #endif
  1315. struct varshead *headp;
  1316. struct ast_var_t *current;
  1317. p = ast->pvt->pvt;
  1318. if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
  1319. ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
  1320. return -1;
  1321. }
  1322. /* Check whether there is vxml_url, distinctive ring variables */
  1323. headp=&ast->varshead;
  1324. AST_LIST_TRAVERSE(headp,current,entries) {
  1325. /* Check whether there is a VXML_URL variable */
  1326. if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
  1327. {
  1328. vxml_url = ast_var_value(current);
  1329. } else
  1330. /* Check whether there is a ALERT_INFO variable */
  1331. if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
  1332. {
  1333. distinctive_ring = ast_var_value(current);
  1334. }
  1335. #ifdef OSP_SUPPORT
  1336. else if (!strcasecmp(ast_var_name(current), "OSPTOKEN")) {
  1337. osptoken = ast_var_value(current);
  1338. } else if (!strcasecmp(ast_var_name(current), "OSPHANDLE")) {
  1339. osphandle = ast_var_value(current);
  1340. }
  1341. #endif
  1342. }
  1343. res = 0;
  1344. p->outgoing = 1;
  1345. #ifdef OSP_SUPPORT
  1346. if (!osptoken || !osphandle || (sscanf(osphandle, "%i", &p->osphandle) != 1)) {
  1347. /* Force Disable OSP support */
  1348. osptoken = NULL;
  1349. osphandle = NULL;
  1350. p->osphandle = -1;
  1351. }
  1352. #endif
  1353. ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
  1354. res = update_user_counter(p,INC_OUT_USE);
  1355. if ( res != -1 ) {
  1356. p->restrictcid = ast->restrictcid;
  1357. p->jointcapability = p->capability;
  1358. transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, osptoken, 1);
  1359. if (p->maxtime) {
  1360. /* Initialize auto-congest time */
  1361. p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
  1362. }
  1363. }
  1364. return res;
  1365. }
  1366. /*--- __sip_destroy: Execute destrucion of call structure, release memory---*/
  1367. static void __sip_destroy(struct sip_pvt *p, int lockowner)
  1368. {
  1369. struct sip_pvt *cur, *prev = NULL;
  1370. struct sip_pkt *cp;
  1371. struct sip_history *hist;
  1372. if (sip_debug_test_pvt(p))
  1373. ast_verbose("Destroying call '%s'\n", p->callid);
  1374. if (p->stateid > -1)
  1375. ast_extension_state_del(p->stateid, NULL);
  1376. if (p->initid > -1)
  1377. ast_sched_del(sched, p->initid);
  1378. if (p->autokillid > -1)
  1379. ast_sched_del(sched, p->autokillid);
  1380. if (p->rtp) {
  1381. ast_rtp_destroy(p->rtp);
  1382. }
  1383. if (p->vrtp) {
  1384. ast_rtp_destroy(p->vrtp);
  1385. }
  1386. if (p->route) {
  1387. free_old_route(p->route);
  1388. p->route = NULL;
  1389. }
  1390. if (p->registry) {
  1391. /* Carefully unlink from registry */
  1392. struct sip_registry *reg;
  1393. ast_mutex_lock(&regl.lock);
  1394. reg = regl.registrations;
  1395. while(reg) {
  1396. if ((reg == p->registry) && (p->registry->call == p))
  1397. p->registry->call=NULL;
  1398. reg = reg->next;
  1399. }
  1400. ast_mutex_unlock(&regl.lock);
  1401. }
  1402. /* Unlink us from the owner if we have one */
  1403. if (p->owner) {
  1404. if (lockowner)
  1405. ast_mutex_lock(&p->owner->lock);
  1406. ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
  1407. p->owner->pvt->pvt = NULL;
  1408. if (lockowner)
  1409. ast_mutex_unlock(&p->owner->lock);
  1410. }
  1411. /* Clear history */
  1412. while(p->history) {
  1413. hist = p->history;
  1414. p->history = p->history->next;
  1415. free(hist);
  1416. }
  1417. cur = iflist;
  1418. while(cur) {
  1419. if (cur == p) {
  1420. if (prev)
  1421. prev->next = cur->next;
  1422. else
  1423. iflist = cur->next;
  1424. break;
  1425. }
  1426. prev = cur;
  1427. cur = cur->next;
  1428. }
  1429. if (!cur) {
  1430. ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
  1431. } else {
  1432. if (p->initid > -1)
  1433. ast_sched_del(sched, p->initid);
  1434. while((cp = p->packets)) {
  1435. p->packets = p->packets->next;
  1436. if (cp->retransid > -1)
  1437. ast_sched_del(sched, cp->retransid);
  1438. free(cp);
  1439. }
  1440. ast_mutex_destroy(&p->lock);
  1441. free(p);
  1442. }
  1443. }
  1444. /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
  1445. /* Note: This is going to be replaced by app_groupcount */
  1446. static int update_user_counter(struct sip_pvt *fup, int event)
  1447. {
  1448. char name[256] = "";
  1449. struct sip_user *u;
  1450. strncpy(name, fup->username, sizeof(name) - 1);
  1451. ast_mutex_lock(&userl.lock);
  1452. u = find_user(name);
  1453. if (!u) {
  1454. ast_log(LOG_DEBUG, "%s is not a local user\n", name);
  1455. ast_mutex_unlock(&userl.lock);
  1456. return 0;
  1457. }
  1458. switch(event) {
  1459. /* incoming and outgoing affects the inUse counter */
  1460. case DEC_OUT_USE:
  1461. case DEC_IN_USE:
  1462. if ( u->inUse > 0 ) {
  1463. u->inUse--;
  1464. } else {
  1465. u->inUse = 0;
  1466. }
  1467. break;
  1468. case INC_IN_USE:
  1469. case INC_OUT_USE:
  1470. if (u->incominglimit > 0 ) {
  1471. if (u->inUse >= u->incominglimit) {
  1472. ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
  1473. /* inc inUse as well */
  1474. if ( event == INC_OUT_USE ) {
  1475. u->inUse++;
  1476. }
  1477. ast_mutex_unlock(&userl.lock);
  1478. return -1;
  1479. }
  1480. }
  1481. u->inUse++;
  1482. ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
  1483. break;
  1484. /* we don't use these anymore
  1485. case DEC_OUT_USE:
  1486. if ( u->outUse > 0 ) {
  1487. u->outUse--;
  1488. } else {
  1489. u->outUse = 0;
  1490. }
  1491. break;
  1492. case INC_OUT_USE:
  1493. if ( u->outgoinglimit > 0 ) {
  1494. if ( u->outUse >= u->outgoinglimit ) {
  1495. ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
  1496. ast_mutex_unlock(&userl.lock);
  1497. return -1;
  1498. }
  1499. }
  1500. u->outUse++;
  1501. break;
  1502. */
  1503. default:
  1504. ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
  1505. }
  1506. ast_mutex_unlock(&userl.lock);
  1507. #ifdef MYSQL_USERS
  1508. if (u && u->temponly)
  1509. free(u);
  1510. #endif
  1511. return 0;
  1512. }
  1513. /*--- sip_destroy: Destroy SIP call structure ---*/
  1514. static void sip_destroy(struct sip_pvt *p)
  1515. {
  1516. ast_mutex_lock(&iflock);
  1517. __sip_destroy(p, 1);
  1518. ast_mutex_unlock(&iflock);
  1519. }
  1520. static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
  1521. static int hangup_sip2cause(int cause)
  1522. {
  1523. /* Possible values from causes.h
  1524. AST_CAUSE_NOTDEFINED AST_CAUSE_NORMAL AST_CAUSE_BUSY
  1525. AST_CAUSE_FAILURE AST_CAUSE_CONGESTION AST_CAUSE_UNALLOCATED
  1526. */
  1527. switch(cause) {
  1528. case 404: /* Not found */
  1529. return AST_CAUSE_UNALLOCATED;
  1530. case 483: /* Too many hops */
  1531. return AST_CAUSE_FAILURE;
  1532. case 486:
  1533. return AST_CAUSE_BUSY;
  1534. default:
  1535. return AST_CAUSE_NORMAL;
  1536. }
  1537. /* Never reached */
  1538. return 0;
  1539. }
  1540. static char *hangup_cause2sip(int cause)
  1541. {
  1542. switch(cause)
  1543. {
  1544. case AST_CAUSE_FAILURE:
  1545. return "500 Server internal failure";
  1546. case AST_CAUSE_CONGESTION:
  1547. return "503 Service Unavailable";
  1548. case AST_CAUSE_BUSY:
  1549. return "486 Busy";
  1550. default:
  1551. return NULL;
  1552. }
  1553. /* Never reached */
  1554. return 0;
  1555. }
  1556. /*--- sip_hangup: Hangup SIP call */
  1557. static int sip_hangup(struct ast_channel *ast)
  1558. {
  1559. struct sip_pvt *p = ast->pvt->pvt;
  1560. int needcancel = 0;
  1561. int needdestroy = 0;
  1562. if (option_debug)
  1563. ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
  1564. if (!ast->pvt->pvt) {
  1565. ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
  1566. return 0;
  1567. }
  1568. ast_mutex_lock(&p->lock);
  1569. #ifdef OSP_SUPPORT
  1570. if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
  1571. ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
  1572. }
  1573. #endif
  1574. if ( p->outgoing ) {
  1575. ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
  1576. update_user_counter(p, DEC_OUT_USE);
  1577. } else {
  1578. ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
  1579. update_user_counter(p, DEC_IN_USE);
  1580. }
  1581. /* Determine how to disconnect */
  1582. if (p->owner != ast) {
  1583. ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
  1584. ast_mutex_unlock(&p->lock);
  1585. return 0;
  1586. }
  1587. if (!ast || (ast->_state != AST_STATE_UP))
  1588. needcancel = 1;
  1589. /* Disconnect */
  1590. p = ast->pvt->pvt;
  1591. if (p->vad) {
  1592. ast_dsp_free(p->vad);
  1593. }
  1594. p->owner = NULL;
  1595. ast->pvt->pvt = NULL;
  1596. ast_mutex_lock(&usecnt_lock);
  1597. usecnt--;
  1598. ast_mutex_unlock(&usecnt_lock);
  1599. ast_update_use_count();
  1600. needdestroy = 1;
  1601. /* Start the process if it's not already started */
  1602. if (!p->alreadygone && !ast_strlen_zero(p->initreq.data)) {
  1603. if (needcancel) {
  1604. if (p->outgoing) {
  1605. transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
  1606. /* Actually don't destroy us yet, wait for the 487 on our original
  1607. INVITE, but do set an autodestruct just in case we never get it. */
  1608. needdestroy = 0;
  1609. sip_scheddestroy(p, 15000);
  1610. if ( p->initid != -1 ) {
  1611. /* channel still up - reverse dec of inUse counter
  1612. only if the channel is not auto-congested */
  1613. if ( p->outgoing ) {
  1614. update_user_counter(p, INC_OUT_USE);
  1615. }
  1616. else {
  1617. update_user_counter(p, INC_IN_USE);
  1618. }
  1619. }
  1620. } else {
  1621. char *res;
  1622. if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
  1623. transmit_response_reliable(p, res, &p->initreq, 1);
  1624. } else
  1625. transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
  1626. }
  1627. } else {
  1628. if (!p->pendinginvite) {
  1629. /* Send a hangup */
  1630. transmit_request_with_auth(p, "BYE", 0, 1, 1);
  1631. } else {
  1632. /* Note we will need a BYE when this all settles out
  1633. but we can't send one while we have "INVITE" outstanding. */
  1634. p->pendingbye = 1;
  1635. p->needreinvite = 0;
  1636. }
  1637. }
  1638. }
  1639. p->needdestroy = needdestroy;
  1640. ast_mutex_unlock(&p->lock);
  1641. return 0;
  1642. }
  1643. /*--- sip_answer: Answer SIP call , send 200 OK on Invite */
  1644. static int sip_answer(struct ast_channel *ast)
  1645. {
  1646. int res = 0,fmt;
  1647. char *codec;
  1648. struct sip_pvt *p = ast->pvt->pvt;
  1649. ast_mutex_lock(&p->lock);
  1650. if (ast->_state != AST_STATE_UP) {
  1651. #ifdef OSP_SUPPORT
  1652. time(&p->ospstart);
  1653. #endif
  1654. codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
  1655. if (codec) {
  1656. fmt=ast_getformatbyname(codec);
  1657. if (fmt) {
  1658. ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
  1659. if (p->jointcapability & fmt) {
  1660. p->jointcapability &= fmt;
  1661. p->capability &= fmt;
  1662. } else
  1663. ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
  1664. } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
  1665. }
  1666. ast_setstate(ast, AST_STATE_UP);
  1667. if (option_debug)
  1668. ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
  1669. res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
  1670. }
  1671. ast_mutex_unlock(&p->lock);
  1672. return res;
  1673. }
  1674. /*--- sip_write: Send response, support audio media ---*/
  1675. static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
  1676. {
  1677. struct sip_pvt *p = ast->pvt->pvt;
  1678. int res = 0;
  1679. if (frame->frametype == AST_FRAME_VOICE) {
  1680. if (!(frame->subclass & ast->nativeformats)) {
  1681. ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
  1682. frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
  1683. return 0;
  1684. }
  1685. if (p) {
  1686. ast_mutex_lock(&p->lock);
  1687. if (p->rtp) {
  1688. if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
  1689. transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
  1690. p->progress = 1;
  1691. }
  1692. res = ast_rtp_write(p->rtp, frame);
  1693. }
  1694. ast_mutex_unlock(&p->lock);
  1695. }
  1696. } else if (frame->frametype == AST_FRAME_VIDEO) {
  1697. if (p) {
  1698. ast_mutex_lock(&p->lock);
  1699. if (p->vrtp) {
  1700. if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
  1701. transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
  1702. p->progress = 1;
  1703. }
  1704. res = ast_rtp_write(p->vrtp, frame);
  1705. }
  1706. ast_mutex_unlock(&p->lock);
  1707. }
  1708. } else if (frame->frametype == AST_FRAME_IMAGE) {
  1709. return 0;
  1710. } else {
  1711. ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
  1712. return 0;
  1713. }
  1714. return res;
  1715. }
  1716. /*--- sip_fixup: Fix up a channel: If a channel is consumed, this is called.
  1717. Basically update any ->owner links ----*/
  1718. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
  1719. {
  1720. struct sip_pvt *p = newchan->pvt->pvt;
  1721. ast_mutex_lock(&p->lock);
  1722. if (p->owner != oldchan) {
  1723. ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
  1724. ast_mutex_unlock(&p->lock);
  1725. return -1;
  1726. }
  1727. p->owner = newchan;
  1728. ast_mutex_unlock(&p->lock);
  1729. return 0;
  1730. }
  1731. /*--- sip_senddigit: Send DTMF character on SIP channel */
  1732. /* within one call, we're able to transmit in many methods simultaneously */
  1733. static int sip_senddigit(struct ast_channel *ast, char digit)
  1734. {
  1735. struct sip_pvt *p = ast->pvt->pvt;
  1736. if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
  1737. transmit_info_with_digit(p, digit);
  1738. }
  1739. if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
  1740. ast_rtp_senddigit(p->rtp, digit);
  1741. }
  1742. /* If in-band DTMF is desired, send that */
  1743. if (p->dtmfmode & SIP_DTMF_INBAND)
  1744. return -1;
  1745. return 0;
  1746. }
  1747. /*--- sip_transfer: Transfer SIP call */
  1748. static int sip_transfer(struct ast_channel *ast, char *dest)
  1749. {
  1750. struct sip_pvt *p = ast->pvt->pvt;
  1751. int res;
  1752. res = transmit_refer(p, dest);
  1753. return res;
  1754. }
  1755. /*--- sip_indicate: Play indication to user */
  1756. /* With SIP a lot of indications is sent as messages, letting the device play
  1757. the indication - busy signal, congestion etc */
  1758. static int sip_indicate(struct ast_channel *ast, int condition)
  1759. {
  1760. struct sip_pvt *p = ast->pvt->pvt;
  1761. switch(condition) {
  1762. case AST_CONTROL_RINGING:
  1763. if (ast->_state == AST_STATE_RING) {
  1764. if (!p->progress) {
  1765. transmit_response(p, "180 Ringing", &p->initreq);
  1766. p->ringing = 1;
  1767. if (!p->progressinband)
  1768. break;
  1769. } else {
  1770. /* Oops, we've sent progress tones. Let Asterisk do it instead */
  1771. }
  1772. }
  1773. return -1;
  1774. case AST_CONTROL_BUSY:
  1775. if (ast->_state != AST_STATE_UP) {
  1776. transmit_response(p, "486 Busy Here", &p->initreq);
  1777. p->alreadygone = 1;
  1778. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  1779. break;
  1780. }
  1781. return -1;
  1782. case AST_CONTROL_CONGESTION:
  1783. if (ast->_state != AST_STATE_UP) {
  1784. transmit_response(p, "503 Service Unavailable", &p->initreq);
  1785. p->alreadygone = 1;
  1786. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  1787. break;
  1788. }
  1789. return -1;
  1790. case AST_CONTROL_PROGRESS:
  1791. case AST_CONTROL_PROCEEDING:
  1792. if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
  1793. transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
  1794. p->progress = 1;
  1795. break;
  1796. }
  1797. return -1;
  1798. case -1:
  1799. return -1;
  1800. default:
  1801. ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
  1802. return -1;
  1803. }
  1804. return 0;
  1805. }
  1806. /*--- sip_new: Initiate a call in the SIP channel */
  1807. /* called from sip_request_call (calls from the pbx ) */
  1808. static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
  1809. {
  1810. struct ast_channel *tmp;
  1811. int fmt;
  1812. ast_mutex_unlock(&i->lock);
  1813. /* Don't hold a sip pvt lock while we allocate a channel */
  1814. tmp = ast_channel_alloc(1);
  1815. ast_mutex_lock(&i->lock);
  1816. if (tmp) {
  1817. /* Select our native format based on codec preference until we receive
  1818. something from another device to the contrary. */
  1819. ast_mutex_lock(&i->lock);
  1820. if (i->jointcapability)
  1821. tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
  1822. else if (i->capability)
  1823. tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
  1824. else
  1825. tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
  1826. ast_mutex_unlock(&i->lock);
  1827. fmt = ast_best_codec(tmp->nativeformats);
  1828. if (title)
  1829. snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
  1830. else
  1831. if (strchr(i->fromdomain,':'))
  1832. {
  1833. snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
  1834. }
  1835. else
  1836. {
  1837. snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
  1838. }
  1839. tmp->type = type;
  1840. if (i->dtmfmode & SIP_DTMF_INBAND) {
  1841. i->vad = ast_dsp_new();
  1842. ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
  1843. if (relaxdtmf)
  1844. ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
  1845. }
  1846. tmp->fds[0] = ast_rtp_fd(i->rtp);
  1847. tmp->fds[1] = ast_rtcp_fd(i->rtp);
  1848. if (i->vrtp) {
  1849. tmp->fds[2] = ast_rtp_fd(i->vrtp);
  1850. tmp->fds[3] = ast_rtcp_fd(i->vrtp);
  1851. }
  1852. if (state == AST_STATE_RING)
  1853. tmp->rings = 1;
  1854. tmp->adsicpe = AST_ADSI_UNAVAILABLE;
  1855. tmp->writeformat = fmt;
  1856. tmp->pvt->rawwriteformat = fmt;
  1857. tmp->readformat = fmt;
  1858. tmp->pvt->rawreadformat = fmt;
  1859. tmp->pvt->pvt = i;
  1860. tmp->pvt->send_text = sip_sendtext;
  1861. tmp->pvt->call = sip_call;
  1862. tmp->pvt->hangup = sip_hangup;
  1863. tmp->pvt->answer = sip_answer;
  1864. tmp->pvt->read = sip_read;
  1865. tmp->pvt->write = sip_write;
  1866. tmp->pvt->write_video = sip_write;
  1867. tmp->pvt->indicate = sip_indicate;
  1868. tmp->pvt->transfer = sip_transfer;
  1869. tmp->pvt->fixup = sip_fixup;
  1870. tmp->pvt->send_digit = sip_senddigit;
  1871. tmp->pvt->bridge = ast_rtp_bridge;
  1872. tmp->callgroup = i->callgroup;
  1873. tmp->pickupgroup = i->pickupgroup;
  1874. tmp->restrictcid = i->restrictcid;
  1875. if (!ast_strlen_zero(i->accountcode))
  1876. strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
  1877. if (i->amaflags)
  1878. tmp->amaflags = i->amaflags;
  1879. if (!ast_strlen_zero(i->language))
  1880. strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
  1881. if (!ast_strlen_zero(i->musicclass))
  1882. strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
  1883. i->owner = tmp;
  1884. ast_mutex_lock(&usecnt_lock);
  1885. usecnt++;
  1886. ast_mutex_unlock(&usecnt_lock);
  1887. strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
  1888. strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
  1889. if (!ast_strlen_zero(i->callerid))
  1890. tmp->callerid = strdup(i->callerid);
  1891. if (!ast_strlen_zero(i->rdnis))
  1892. tmp->rdnis = strdup(i->rdnis);
  1893. if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
  1894. tmp->dnid = strdup(i->exten);
  1895. tmp->priority = 1;
  1896. if (!ast_strlen_zero(i->domain)) {
  1897. pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
  1898. }
  1899. if (!ast_strlen_zero(i->useragent)) {
  1900. pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
  1901. }
  1902. if (!ast_strlen_zero(i->callid)) {
  1903. pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
  1904. }
  1905. ast_setstate(tmp, state);
  1906. if (state != AST_STATE_DOWN) {
  1907. if (ast_pbx_start(tmp)) {
  1908. ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
  1909. ast_hangup(tmp);
  1910. tmp = NULL;
  1911. }
  1912. }
  1913. } else
  1914. ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
  1915. return tmp;
  1916. }
  1917. static struct cfalias {
  1918. char *fullname;
  1919. char *shortname;
  1920. } aliases[] = {
  1921. { "Content-Type", "c" },
  1922. { "Content-Encoding", "e" },
  1923. { "From", "f" },
  1924. { "Call-ID", "i" },
  1925. { "Contact", "m" },
  1926. { "Content-Length", "l" },
  1927. { "Subject", "s" },
  1928. { "To", "t" },
  1929. { "Supported", "k" },
  1930. { "Refer-To", "r" },
  1931. { "Referred-By", "b" },
  1932. { "Allow-Events", "u" },
  1933. { "Event", "o" },
  1934. { "Via", "v" },
  1935. };
  1936. /*--- get_sdp_by_line: Reads one line of SIP message body */
  1937. static char* get_sdp_by_line(char* line, char *name, int nameLen) {
  1938. if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
  1939. char* r = line + nameLen + 1;
  1940. while (*r && (*r < 33)) ++r;
  1941. return r;
  1942. }
  1943. return "";
  1944. }
  1945. /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
  1946. but the name wrongly applies _only_ sdp */
  1947. static char *get_sdp(struct sip_request *req, char *name) {
  1948. int x;
  1949. int len = strlen(name);
  1950. char *r;
  1951. for (x=0; x<req->lines; x++) {
  1952. r = get_sdp_by_line(req->line[x], name, len);
  1953. if (r[0] != '\0') return r;
  1954. }
  1955. return "";
  1956. }
  1957. static void sdpLineNum_iterator_init(int* iterator) {
  1958. *iterator = 0;
  1959. }
  1960. static char* get_sdp_iterate(int* iterator,
  1961. struct sip_request *req, char *name) {
  1962. int len = strlen(name);
  1963. char *r;
  1964. while (*iterator < req->lines) {
  1965. r = get_sdp_by_line(req->line[(*iterator)++], name, len);
  1966. if (r[0] != '\0') return r;
  1967. }
  1968. return "";
  1969. }
  1970. static char *__get_header(struct sip_request *req, char *name, int *start)
  1971. {
  1972. int x;
  1973. int len = strlen(name);
  1974. char *r;
  1975. if (pedanticsipchecking) {
  1976. /* Technically you can place arbitrary whitespace both before and after the ':' in
  1977. a header, although RFC3261 clearly says you shouldn't before, and place just
  1978. one afterwards. If you shouldn't do it, what absolute idiot decided it was
  1979. a good idea to say you can do it, and if you can do it, why in the hell would
  1980. you say you shouldn't. */
  1981. for (x=*start;x<req->headers;x++) {
  1982. if (!strncasecmp(req->header[x], name, len)) {
  1983. r = req->header[x] + len;
  1984. while(*r && (*r < 33))
  1985. r++;
  1986. if (*r == ':') {
  1987. r++ ;
  1988. while(*r && (*r < 33))
  1989. r++;
  1990. *start = x+1;
  1991. return r;
  1992. }
  1993. }
  1994. }
  1995. } else {
  1996. /* We probably shouldn't even bother counting whitespace afterwards but
  1997. I guess for backwards compatibility we will */
  1998. for (x=*start;x<req->headers;x++) {
  1999. if (!strncasecmp(req->header[x], name, len) &&
  2000. (req->header[x][len] == ':')) {
  2001. r = req->header[x] + len + 1;
  2002. while(*r && (*r < 33))
  2003. r++;
  2004. *start = x+1;
  2005. return r;
  2006. }
  2007. }
  2008. }
  2009. /* Try aliases */
  2010. for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
  2011. if (!strcasecmp(aliases[x].fullname, name))
  2012. return __get_header(req, aliases[x].shortname, start);
  2013. /* Don't return NULL, so get_header is always a valid pointer */
  2014. return "";
  2015. }
  2016. /*--- get_header: Get header from SIP request ---*/
  2017. static char *get_header(struct sip_request *req, char *name)
  2018. {
  2019. int start = 0;
  2020. return __get_header(req, name, &start);
  2021. }
  2022. /*--- sip_rtp_read: Read RTP from network ---*/
  2023. static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
  2024. {
  2025. /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
  2026. struct ast_frame *f;
  2027. static struct ast_frame null_frame = { AST_FRAME_NULL, };
  2028. switch(ast->fdno) {
  2029. case 0:
  2030. f = ast_rtp_read(p->rtp); /* RTP Audio */
  2031. break;
  2032. case 1:
  2033. f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
  2034. break;
  2035. case 2:
  2036. f = ast_rtp_read(p->vrtp); /* RTP Video */
  2037. break;
  2038. case 3:
  2039. f = ast_rtcp_read(p->vrtp); /* RTCP Control Channel for video */
  2040. break;
  2041. default:
  2042. f = &null_frame;
  2043. }
  2044. /* Don't send RFC2833 if we're not supposed to */
  2045. if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
  2046. return &null_frame;
  2047. if (p->owner) {
  2048. /* We already hold the channel lock */
  2049. if (f->frametype == AST_FRAME_VOICE) {
  2050. if (f->subclass != p->owner->nativeformats) {
  2051. ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
  2052. p->owner->nativeformats = f->subclass;
  2053. ast_set_read_format(p->owner, p->owner->readformat);
  2054. ast_set_write_format(p->owner, p->owner->writeformat);
  2055. }
  2056. if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
  2057. f = ast_dsp_process(p->owner,p->vad,f);
  2058. if (f && (f->frametype == AST_FRAME_DTMF))
  2059. ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
  2060. }
  2061. }
  2062. }
  2063. return f;
  2064. }
  2065. /*--- sip_read: Read SIP RTP from channel */
  2066. static struct ast_frame *sip_read(struct ast_channel *ast)
  2067. {
  2068. struct ast_frame *fr;
  2069. struct sip_pvt *p = ast->pvt->pvt;
  2070. ast_mutex_lock(&p->lock);
  2071. fr = sip_rtp_read(ast, p);
  2072. time(&p->lastrtprx);
  2073. ast_mutex_unlock(&p->lock);
  2074. return fr;
  2075. }
  2076. /*--- build_callid: Build SIP CALLID header ---*/
  2077. static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
  2078. {
  2079. int res;
  2080. int val;
  2081. int x;
  2082. char iabuf[INET_ADDRSTRLEN];
  2083. for (x=0;x<4;x++) {
  2084. val = rand();
  2085. res = snprintf(callid, len, "%08x", val);
  2086. len -= res;
  2087. callid += res;
  2088. }
  2089. if (!ast_strlen_zero(fromdomain))
  2090. snprintf(callid, len, "@%s", fromdomain);
  2091. else
  2092. /* It's not important that we really use our right IP here... */
  2093. snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
  2094. }
  2095. /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
  2096. static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat)
  2097. {
  2098. struct sip_pvt *p;
  2099. char iabuf[INET_ADDRSTRLEN];
  2100. p = malloc(sizeof(struct sip_pvt));
  2101. if (!p)
  2102. return NULL;
  2103. /* Keep track of stuff */
  2104. memset(p, 0, sizeof(struct sip_pvt));
  2105. ast_mutex_init(&p->lock);
  2106. p->initid = -1;
  2107. p->autokillid = -1;
  2108. p->stateid = -1;
  2109. p->prefs = prefs;
  2110. #ifdef OSP_SUPPORT
  2111. p->osphandle = -1;
  2112. #endif
  2113. if (sin) {
  2114. memcpy(&p->sa, sin, sizeof(p->sa));
  2115. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  2116. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  2117. } else {
  2118. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  2119. }
  2120. p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
  2121. if (videosupport)
  2122. p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
  2123. p->branch = rand();
  2124. p->tag = rand();
  2125. /* Start with 101 instead of 1 */
  2126. p->ocseq = 101;
  2127. if (!p->rtp) {
  2128. ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
  2129. ast_mutex_destroy(&p->lock);
  2130. free(p);
  2131. return NULL;
  2132. }
  2133. ast_rtp_settos(p->rtp, tos);
  2134. if (p->vrtp)
  2135. ast_rtp_settos(p->vrtp, tos);
  2136. if (useglobal_nat && sin) {
  2137. /* Setup NAT structure according to global settings if we have an address */
  2138. p->nat = global_nat;
  2139. memcpy(&p->recv, sin, sizeof(p->recv));
  2140. ast_rtp_setnat(p->rtp, (p->nat & SIP_NAT_ROUTE));
  2141. if (p->vrtp)
  2142. ast_rtp_setnat(p->vrtp, (p->nat & SIP_NAT_ROUTE));
  2143. }
  2144. strncpy(p->fromdomain, default_fromdomain, sizeof(p->fromdomain) - 1);
  2145. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  2146. if (p->nat != SIP_NAT_NEVER)
  2147. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  2148. else
  2149. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  2150. if (!callid)
  2151. build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
  2152. else
  2153. strncpy(p->callid, callid, sizeof(p->callid) - 1);
  2154. /* Assume reinvite OK and via INVITE */
  2155. p->canreinvite = global_canreinvite;
  2156. /* Assign default music on hold class */
  2157. strncpy(p->musicclass, global_musicclass, sizeof(p->musicclass) - 1);
  2158. p->dtmfmode = global_dtmfmode;
  2159. p->promiscredir = global_promiscredir;
  2160. p->trustrpid = global_trustrpid;
  2161. p->progressinband = global_progressinband;
  2162. #ifdef OSP_SUPPORT
  2163. p->ospauth = global_ospauth;
  2164. #endif
  2165. p->rtptimeout = global_rtptimeout;
  2166. p->rtpholdtimeout = global_rtpholdtimeout;
  2167. p->capability = global_capability;
  2168. if (p->dtmfmode & SIP_DTMF_RFC2833)
  2169. p->noncodeccapability |= AST_RTP_DTMF;
  2170. strncpy(p->context, default_context, sizeof(p->context) - 1);
  2171. /* Add to list */
  2172. ast_mutex_lock(&iflock);
  2173. p->next = iflist;
  2174. iflist = p;
  2175. ast_mutex_unlock(&iflock);
  2176. if (option_debug)
  2177. ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
  2178. return p;
  2179. }
  2180. /*--- find_call: Connect incoming SIP message to current call or create new call structure */
  2181. /* Called by handle_request ,sipsock_read */
  2182. static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
  2183. {
  2184. struct sip_pvt *p;
  2185. char *callid;
  2186. char tmp[256] = "";
  2187. char iabuf[INET_ADDRSTRLEN];
  2188. char *cmd;
  2189. char *tag = "", *c;
  2190. callid = get_header(req, "Call-ID");
  2191. if (pedanticsipchecking) {
  2192. /* In principle Call-ID's uniquely identify a call, however some vendors
  2193. (i.e. Pingtel) send multiple calls with the same Call-ID and different
  2194. tags in order to simplify billing. The RFC does state that we have to
  2195. compare tags in addition to the call-id, but this generate substantially
  2196. more overhead which is totally unnecessary for the vast majority of sane
  2197. SIP implementations, and thus Asterisk does not enable this behavior
  2198. by default. Short version: You'll need this option to support conferencing
  2199. on the pingtel */
  2200. strncpy(tmp, req->header[0], sizeof(tmp) - 1);
  2201. cmd = tmp;
  2202. c = strchr(tmp, ' ');
  2203. if (c)
  2204. *c = '\0';
  2205. if (!strcasecmp(cmd, "SIP/2.0"))
  2206. strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
  2207. else
  2208. strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
  2209. tag = ast_strcasestr(tmp, "tag=");
  2210. if (tag) {
  2211. tag += 4;
  2212. c = strchr(tag, ';');
  2213. if (c)
  2214. *c = '\0';
  2215. }
  2216. }
  2217. if (ast_strlen_zero(callid)) {
  2218. ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  2219. return NULL;
  2220. }
  2221. ast_mutex_lock(&iflock);
  2222. p = iflist;
  2223. while(p) {
  2224. if (!strcmp(p->callid, callid) &&
  2225. (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
  2226. /* Found the call */
  2227. ast_mutex_lock(&p->lock);
  2228. ast_mutex_unlock(&iflock);
  2229. return p;
  2230. }
  2231. p = p->next;
  2232. }
  2233. ast_mutex_unlock(&iflock);
  2234. p = sip_alloc(callid, sin, 1);
  2235. if (p)
  2236. ast_mutex_lock(&p->lock);
  2237. return p;
  2238. }
  2239. /*--- sip_register: Parse register=> line in sip.conf and add to registry */
  2240. static int sip_register(char *value, int lineno)
  2241. {
  2242. struct sip_registry *reg;
  2243. char copy[256] = "";
  2244. char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
  2245. char *porta=NULL;
  2246. char *contact=NULL;
  2247. char *stringp=NULL;
  2248. if (!value)
  2249. return -1;
  2250. strncpy(copy, value, sizeof(copy)-1);
  2251. stringp=copy;
  2252. username = stringp;
  2253. hostname = strrchr(stringp, '@');
  2254. if (hostname) {
  2255. *hostname = '\0';
  2256. hostname++;
  2257. }
  2258. if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
  2259. ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
  2260. return -1;
  2261. }
  2262. stringp=username;
  2263. username = strsep(&stringp, ":");
  2264. if (username) {
  2265. secret = strsep(&stringp, ":");
  2266. if (secret)
  2267. authuser = strsep(&stringp, ":");
  2268. }
  2269. stringp = hostname;
  2270. hostname = strsep(&stringp, "/");
  2271. if (hostname)
  2272. contact = strsep(&stringp, "/");
  2273. if (!contact || ast_strlen_zero(contact))
  2274. contact = "s";
  2275. stringp=hostname;
  2276. hostname = strsep(&stringp, ":");
  2277. porta = strsep(&stringp, ":");
  2278. if (porta && !atoi(porta)) {
  2279. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  2280. return -1;
  2281. }
  2282. reg = malloc(sizeof(struct sip_registry));
  2283. if (reg) {
  2284. memset(reg, 0, sizeof(struct sip_registry));
  2285. strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
  2286. if (username)
  2287. strncpy(reg->username, username, sizeof(reg->username)-1);
  2288. if (hostname)
  2289. strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
  2290. if (authuser)
  2291. strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
  2292. if (secret)
  2293. strncpy(reg->secret, secret, sizeof(reg->secret)-1);
  2294. reg->expire = -1;
  2295. reg->timeout = -1;
  2296. reg->refresh = default_expiry;
  2297. reg->portno = porta ? atoi(porta) : 0;
  2298. reg->callid_valid = 0;
  2299. reg->ocseq = 101;
  2300. ast_mutex_lock(&regl.lock);
  2301. reg->next = regl.registrations;
  2302. regl.registrations = reg;
  2303. ast_mutex_unlock(&regl.lock);
  2304. } else {
  2305. ast_log(LOG_ERROR, "Out of memory\n");
  2306. return -1;
  2307. }
  2308. return 0;
  2309. }
  2310. /*--- lws2sws: Parse multiline SIP headers into one header */
  2311. /* This is enabled if pedanticsipchecking is enabled */
  2312. static int lws2sws(char *msgbuf, int len)
  2313. {
  2314. int h = 0, t = 0;
  2315. int lws = 0;
  2316. for (; h < len;) {
  2317. /* Eliminate all CRs */
  2318. if (msgbuf[h] == '\r') {
  2319. h++;
  2320. continue;
  2321. }
  2322. /* Check for end-of-line */
  2323. if (msgbuf[h] == '\n') {
  2324. /* Check for end-of-message */
  2325. if (h + 1 == len)
  2326. break;
  2327. /* Check for a continuation line */
  2328. if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
  2329. /* Merge continuation line */
  2330. h++;
  2331. continue;
  2332. }
  2333. /* Propagate LF and start new line */
  2334. msgbuf[t++] = msgbuf[h++];
  2335. lws = 0;
  2336. continue;
  2337. }
  2338. if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
  2339. if (lws) {
  2340. h++;
  2341. continue;
  2342. }
  2343. msgbuf[t++] = msgbuf[h++];
  2344. lws = 1;
  2345. continue;
  2346. }
  2347. msgbuf[t++] = msgbuf[h++];
  2348. if (lws)
  2349. lws = 0;
  2350. }
  2351. msgbuf[t] = '\0';
  2352. return t;
  2353. }
  2354. /*--- parse: Parse a SIP message ----*/
  2355. static void parse(struct sip_request *req)
  2356. {
  2357. /* Divide fields by NULL's */
  2358. char *c;
  2359. int f = 0;
  2360. c = req->data;
  2361. /* First header starts immediately */
  2362. req->header[f] = c;
  2363. while(*c) {
  2364. if (*c == '\n') {
  2365. /* We've got a new header */
  2366. *c = 0;
  2367. #if 0
  2368. printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
  2369. #endif
  2370. if (ast_strlen_zero(req->header[f])) {
  2371. /* Line by itself means we're now in content */
  2372. c++;
  2373. break;
  2374. }
  2375. if (f >= SIP_MAX_HEADERS - 1) {
  2376. ast_log(LOG_WARNING, "Too many SIP headers...\n");
  2377. } else
  2378. f++;
  2379. req->header[f] = c + 1;
  2380. } else if (*c == '\r') {
  2381. /* Ignore but eliminate \r's */
  2382. *c = 0;
  2383. }
  2384. c++;
  2385. }
  2386. /* Check for last header */
  2387. if (!ast_strlen_zero(req->header[f]))
  2388. f++;
  2389. req->headers = f;
  2390. /* Now we process any mime content */
  2391. f = 0;
  2392. req->line[f] = c;
  2393. while(*c) {
  2394. if (*c == '\n') {
  2395. /* We've got a new line */
  2396. *c = 0;
  2397. #if 0
  2398. printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
  2399. #endif
  2400. if (f >= SIP_MAX_LINES - 1) {
  2401. ast_log(LOG_WARNING, "Too many SDP lines...\n");
  2402. } else
  2403. f++;
  2404. req->line[f] = c + 1;
  2405. } else if (*c == '\r') {
  2406. /* Ignore and eliminate \r's */
  2407. *c = 0;
  2408. }
  2409. c++;
  2410. }
  2411. /* Check for last line */
  2412. if (!ast_strlen_zero(req->line[f]))
  2413. f++;
  2414. req->lines = f;
  2415. if (*c)
  2416. ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
  2417. }
  2418. /*--- process_sdp: Process SIP SDP ---*/
  2419. static int process_sdp(struct sip_pvt *p, struct sip_request *req)
  2420. {
  2421. char *m;
  2422. char *c;
  2423. char *a;
  2424. char host[258];
  2425. char iabuf[INET_ADDRSTRLEN];
  2426. int len = -1;
  2427. int portno = -1;
  2428. int vportno = -1;
  2429. int peercapability, peernoncodeccapability;
  2430. int vpeercapability=0, vpeernoncodeccapability=0;
  2431. struct sockaddr_in sin;
  2432. char *codecs;
  2433. struct hostent *hp;
  2434. struct ast_hostent ahp;
  2435. int codec;
  2436. int iterator;
  2437. int sendonly = 0;
  2438. int x;
  2439. int found;
  2440. int debug=sip_debug_test_pvt(p);
  2441. /* Update our last rtprx when we receive an SDP, too */
  2442. time(&p->lastrtprx);
  2443. /* Get codec and RTP info from SDP */
  2444. if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
  2445. ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
  2446. return -1;
  2447. }
  2448. m = get_sdp(req, "m");
  2449. c = get_sdp(req, "c");
  2450. if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
  2451. ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
  2452. return -1;
  2453. }
  2454. if (sscanf(c, "IN IP4 %256s", host) != 1) {
  2455. ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
  2456. return -1;
  2457. }
  2458. /* XXX This could block for a long time, and block the main thread! XXX */
  2459. hp = ast_gethostbyname(host, &ahp);
  2460. if (!hp) {
  2461. ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
  2462. return -1;
  2463. }
  2464. sdpLineNum_iterator_init(&iterator);
  2465. p->novideo = 1;
  2466. while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
  2467. found = 0;
  2468. if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
  2469. found = 1;
  2470. portno = x;
  2471. /* Scan through the RTP payload types specified in a "m=" line: */
  2472. ast_rtp_pt_clear(p->rtp);
  2473. codecs = m + len;
  2474. while(!ast_strlen_zero(codecs)) {
  2475. if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
  2476. ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
  2477. return -1;
  2478. }
  2479. if (debug)
  2480. ast_verbose("Found RTP audio format %d\n", codec);
  2481. ast_rtp_set_m_type(p->rtp, codec);
  2482. codecs += len;
  2483. /* Skip over any whitespace */
  2484. while(*codecs && (*codecs < 33)) codecs++;
  2485. }
  2486. }
  2487. if (p->vrtp)
  2488. ast_rtp_pt_clear(p->vrtp); /* Must be cleared in case no m=video line exists */
  2489. if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
  2490. found = 1;
  2491. p->novideo = 0;
  2492. vportno = x;
  2493. /* Scan through the RTP payload types specified in a "m=" line: */
  2494. codecs = m + len;
  2495. while(!ast_strlen_zero(codecs)) {
  2496. if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
  2497. ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
  2498. return -1;
  2499. }
  2500. if (debug)
  2501. ast_verbose("Found video format %s\n", ast_getformatname(codec));
  2502. ast_rtp_set_m_type(p->vrtp, codec);
  2503. codecs += len;
  2504. /* Skip over any whitespace */
  2505. while(*codecs && (*codecs < 33)) codecs++;
  2506. }
  2507. }
  2508. if (!found)
  2509. ast_log(LOG_WARNING, "Unknown SDP media type in offer %s\n", m);
  2510. }
  2511. if (portno == -1 && vportno == -1) {
  2512. /* No acceptable offer found in SDP */
  2513. return -2;
  2514. }
  2515. /* RTP addresses and ports for audio and video */
  2516. sin.sin_family = AF_INET;
  2517. memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
  2518. /* Setup audio port number */
  2519. sin.sin_port = htons(portno);
  2520. if (p->rtp && sin.sin_port) {
  2521. ast_rtp_set_peer(p->rtp, &sin);
  2522. if (debug) {
  2523. ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  2524. ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  2525. }
  2526. }
  2527. /* Setup video port number */
  2528. sin.sin_port = htons(vportno);
  2529. if (p->vrtp && sin.sin_port) {
  2530. ast_rtp_set_peer(p->vrtp, &sin);
  2531. if (debug) {
  2532. ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  2533. ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
  2534. }
  2535. }
  2536. /* Next, scan through each "a=rtpmap:" line, noting each
  2537. * specified RTP payload type (with corresponding MIME subtype):
  2538. */
  2539. sdpLineNum_iterator_init(&iterator);
  2540. while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
  2541. char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
  2542. if (!strcasecmp(a, "sendonly")) {
  2543. sendonly=1;
  2544. continue;
  2545. }
  2546. if (!strcasecmp(a, "sendrecv")) {
  2547. sendonly=0;
  2548. }
  2549. if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2)
  2550. continue;
  2551. if (debug)
  2552. ast_verbose("Found description format %s\n", mimeSubtype);
  2553. /* Note: should really look at the 'freq' and '#chans' params too */
  2554. ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
  2555. if (p->vrtp)
  2556. ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
  2557. }
  2558. /* Now gather all of the codecs that were asked for: */
  2559. ast_rtp_get_current_formats(p->rtp,
  2560. &peercapability, &peernoncodeccapability);
  2561. if (p->vrtp)
  2562. ast_rtp_get_current_formats(p->vrtp,
  2563. &vpeercapability, &vpeernoncodeccapability);
  2564. p->jointcapability = p->capability & (peercapability | vpeercapability);
  2565. p->peercapability = (peercapability | vpeercapability);
  2566. p->noncodeccapability = noncodeccapability & peernoncodeccapability;
  2567. if (debug) {
  2568. /* shame on whoever coded this.... */
  2569. const unsigned slen=512;
  2570. char s1[slen], s2[slen], s3[slen], s4[slen];
  2571. ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
  2572. ast_getformatname_multiple(s1, slen, p->capability),
  2573. ast_getformatname_multiple(s2, slen, peercapability),
  2574. ast_getformatname_multiple(s3, slen, vpeercapability),
  2575. ast_getformatname_multiple(s4, slen, p->jointcapability));
  2576. ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
  2577. ast_getformatname_multiple(s1, slen, noncodeccapability),
  2578. ast_getformatname_multiple(s2, slen, peernoncodeccapability),
  2579. ast_getformatname_multiple(s3, slen, p->noncodeccapability));
  2580. }
  2581. if (!p->jointcapability) {
  2582. ast_log(LOG_NOTICE, "No compatible codecs!\n");
  2583. return -1;
  2584. }
  2585. if (p->owner) {
  2586. if (!(p->owner->nativeformats & p->jointcapability)) {
  2587. const unsigned slen=512;
  2588. char s1[slen], s2[slen];
  2589. ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n",
  2590. ast_getformatname_multiple(s1, slen, p->jointcapability),
  2591. ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
  2592. p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1);
  2593. ast_set_read_format(p->owner, p->owner->readformat);
  2594. ast_set_write_format(p->owner, p->owner->writeformat);
  2595. }
  2596. if (p->owner->bridge) {
  2597. /* Turn on/off music on hold if we are holding/unholding */
  2598. if (sin.sin_addr.s_addr && !sendonly) {
  2599. ast_moh_stop(p->owner->bridge);
  2600. } else {
  2601. ast_moh_start(p->owner->bridge, NULL);
  2602. if (sendonly)
  2603. ast_rtp_stop(p->rtp);
  2604. }
  2605. }
  2606. }
  2607. return 0;
  2608. }
  2609. /*--- add_header: Add header to SIP message */
  2610. static int add_header(struct sip_request *req, char *var, char *value)
  2611. {
  2612. if (req->headers == SIP_MAX_HEADERS) {
  2613. ast_log(LOG_WARNING, "Out of SIP header space\n");
  2614. return -1;
  2615. }
  2616. if (req->lines) {
  2617. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  2618. return -1;
  2619. }
  2620. if (req->len >= sizeof(req->data) - 4) {
  2621. ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
  2622. return -1;
  2623. }
  2624. req->header[req->headers] = req->data + req->len;
  2625. snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
  2626. req->len += strlen(req->header[req->headers]);
  2627. req->headers++;
  2628. return 0;
  2629. }
  2630. /*--- add_blank_header: Add blank header to SIP message */
  2631. static int add_blank_header(struct sip_request *req)
  2632. {
  2633. if (req->headers == SIP_MAX_HEADERS) {
  2634. ast_log(LOG_WARNING, "Out of SIP header space\n");
  2635. return -1;
  2636. }
  2637. if (req->lines) {
  2638. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  2639. return -1;
  2640. }
  2641. if (req->len >= sizeof(req->data) - 4) {
  2642. ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
  2643. return -1;
  2644. }
  2645. req->header[req->headers] = req->data + req->len;
  2646. snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
  2647. req->len += strlen(req->header[req->headers]);
  2648. req->headers++;
  2649. return 0;
  2650. }
  2651. /*--- add_line: Add content (not header) to SIP message */
  2652. static int add_line(struct sip_request *req, char *line)
  2653. {
  2654. if (req->lines == SIP_MAX_LINES) {
  2655. ast_log(LOG_WARNING, "Out of line space\n");
  2656. return -1;
  2657. }
  2658. if (!req->lines) {
  2659. /* Add extra empty return */
  2660. snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
  2661. req->len += strlen(req->data + req->len);
  2662. }
  2663. if (req->len >= sizeof(req->data) - 4) {
  2664. ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
  2665. return -1;
  2666. }
  2667. req->line[req->lines] = req->data + req->len;
  2668. snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
  2669. req->len += strlen(req->line[req->lines]);
  2670. req->lines++;
  2671. return 0;
  2672. }
  2673. /*--- copy_header: Copy one header field from one request to another */
  2674. static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
  2675. {
  2676. char *tmp;
  2677. tmp = get_header(orig, field);
  2678. if (!ast_strlen_zero(tmp)) {
  2679. /* Add what we're responding to */
  2680. return add_header(req, field, tmp);
  2681. }
  2682. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  2683. return -1;
  2684. }
  2685. /*--- copy_all_header: Copy all headers from one request to another ---*/
  2686. static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
  2687. {
  2688. char *tmp;
  2689. int start = 0;
  2690. int copied = 0;
  2691. for (;;) {
  2692. tmp = __get_header(orig, field, &start);
  2693. if (!ast_strlen_zero(tmp)) {
  2694. /* Add what we're responding to */
  2695. add_header(req, field, tmp);
  2696. copied++;
  2697. } else
  2698. break;
  2699. }
  2700. return copied ? 0 : -1;
  2701. }
  2702. /*--- copy_via_headers: Copy SIP VIA Headers from one request to another ---*/
  2703. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
  2704. {
  2705. char tmp[256]="", *oh, *end;
  2706. int start = 0;
  2707. int copied = 0;
  2708. char new[256];
  2709. char iabuf[INET_ADDRSTRLEN];
  2710. for (;;) {
  2711. oh = __get_header(orig, field, &start);
  2712. if (!ast_strlen_zero(oh)) {
  2713. /* Strip ;rport */
  2714. strncpy(tmp, oh, sizeof(tmp) - 1);
  2715. oh = strstr(tmp, ";rport");
  2716. if (oh) {
  2717. end = strchr(oh + 1, ';');
  2718. if (end)
  2719. memmove(oh, end, strlen(end) + 1);
  2720. else
  2721. *oh = '\0';
  2722. }
  2723. if (!copied && (p->nat == SIP_NAT_ALWAYS)) {
  2724. /* Whoo hoo! Now we can indicate port address translation too! Just
  2725. another RFC (RFC3581). I'll leave the original comments in for
  2726. posterity. */
  2727. snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
  2728. add_header(req, field, new);
  2729. } else {
  2730. /* Add what we're responding to */
  2731. add_header(req, field, tmp);
  2732. }
  2733. copied++;
  2734. } else
  2735. break;
  2736. }
  2737. if (!copied) {
  2738. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  2739. return -1;
  2740. }
  2741. return 0;
  2742. }
  2743. /*--- add_route: Add route header into request per learned route ---*/
  2744. static void add_route(struct sip_request *req, struct sip_route *route)
  2745. {
  2746. char r[256], *p;
  2747. int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
  2748. if (!route) return;
  2749. p = r;
  2750. while (route) {
  2751. n = strlen(route->hop);
  2752. if ((n+3)>rem) break;
  2753. if (p != r) {
  2754. *p++ = ',';
  2755. --rem;
  2756. }
  2757. *p++ = '<';
  2758. strncpy(p, route->hop, rem); p += n;
  2759. *p++ = '>';
  2760. rem -= (n+2);
  2761. route = route->next;
  2762. }
  2763. *p = '\0';
  2764. add_header(req, "Route", r);
  2765. }
  2766. /*--- set_destination: Set destination from SIP URI ---*/
  2767. static void set_destination(struct sip_pvt *p, char *uri)
  2768. {
  2769. char *h, *maddr, hostname[256] = "";
  2770. char iabuf[INET_ADDRSTRLEN];
  2771. int port, hn;
  2772. struct hostent *hp;
  2773. struct ast_hostent ahp;
  2774. int debug=sip_debug_test_pvt(p);
  2775. /* Parse uri to h (host) and port - uri is already just the part inside the <> */
  2776. /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
  2777. if (debug)
  2778. ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
  2779. /* Find and parse hostname */
  2780. h = strchr(uri, '@');
  2781. if (h)
  2782. ++h;
  2783. else {
  2784. h = uri;
  2785. if (strncmp(h, "sip:", 4) == 0)
  2786. h += 4;
  2787. else if (strncmp(h, "sips:", 5) == 0)
  2788. h += 5;
  2789. }
  2790. hn = strcspn(h, ":;>");
  2791. if (hn > (sizeof(hostname) - 1)) hn = sizeof(hostname) - 1;
  2792. strncpy(hostname, h, hn); hostname[hn] = '\0'; /* safe */
  2793. h+=hn;
  2794. /* Is "port" present? if not default to 5060 */
  2795. if (*h == ':') {
  2796. /* Parse port */
  2797. ++h;
  2798. port = strtol(h, &h, 10);
  2799. }
  2800. else
  2801. port = 5060;
  2802. /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
  2803. maddr = strstr(h, "maddr=");
  2804. if (maddr) {
  2805. maddr += 6;
  2806. hn = strspn(maddr, "0123456789.");
  2807. if (hn > (sizeof(hostname) - 1)) hn = sizeof(hostname) - 1;
  2808. strncpy(hostname, maddr, hn); hostname[hn] = '\0'; /* safe */
  2809. }
  2810. hp = ast_gethostbyname(hostname, &ahp);
  2811. if (hp == NULL) {
  2812. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  2813. return;
  2814. }
  2815. p->sa.sin_family = AF_INET;
  2816. memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
  2817. p->sa.sin_port = htons(port);
  2818. if (debug)
  2819. ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), port);
  2820. }
  2821. /*--- init_resp: Initialize SIP response, based on SIP request ---*/
  2822. static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
  2823. {
  2824. /* Initialize a response */
  2825. if (req->headers || req->len) {
  2826. ast_log(LOG_WARNING, "Request already initialized?!?\n");
  2827. return -1;
  2828. }
  2829. req->header[req->headers] = req->data + req->len;
  2830. snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
  2831. req->len += strlen(req->header[req->headers]);
  2832. req->headers++;
  2833. return 0;
  2834. }
  2835. /*--- init_req: Initialize SIP request ---*/
  2836. static int init_req(struct sip_request *req, char *resp, char *recip)
  2837. {
  2838. /* Initialize a response */
  2839. if (req->headers || req->len) {
  2840. ast_log(LOG_WARNING, "Request already initialized?!?\n");
  2841. return -1;
  2842. }
  2843. req->header[req->headers] = req->data + req->len;
  2844. snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
  2845. req->len += strlen(req->header[req->headers]);
  2846. req->headers++;
  2847. return 0;
  2848. }
  2849. static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
  2850. {
  2851. char newto[256] = "", *ot;
  2852. memset(resp, 0, sizeof(*resp));
  2853. init_resp(resp, msg, req);
  2854. copy_via_headers(p, resp, req, "Via");
  2855. if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
  2856. copy_header(resp, req, "From");
  2857. ot = get_header(req, "To");
  2858. if (!ast_strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
  2859. /* Add the proper tag if we don't have it already. If they have specified
  2860. their tag, use it. Otherwise, use our own tag */
  2861. if (!ast_strlen_zero(p->theirtag) && p->outgoing)
  2862. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  2863. else if (p->tag && !p->outgoing)
  2864. snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
  2865. else {
  2866. strncpy(newto, ot, sizeof(newto) - 1);
  2867. newto[sizeof(newto) - 1] = '\0';
  2868. }
  2869. ot = newto;
  2870. }
  2871. add_header(resp, "To", ot);
  2872. copy_header(resp, req, "Call-ID");
  2873. copy_header(resp, req, "CSeq");
  2874. add_header(resp, "User-Agent", default_useragent);
  2875. add_header(resp, "Allow", ALLOWED_METHODS);
  2876. if (p->expiry) {
  2877. /* For registration responses, we also need expiry and
  2878. contact info */
  2879. char contact[256];
  2880. char tmp[256];
  2881. snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
  2882. snprintf(tmp, sizeof(tmp), "%d", p->expiry);
  2883. add_header(resp, "Expires", tmp);
  2884. add_header(resp, "Contact", contact);
  2885. } else {
  2886. add_header(resp, "Contact", p->our_contact);
  2887. }
  2888. return 0;
  2889. }
  2890. /*--- reqprep: Initialize a SIP request packet ---*/
  2891. static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
  2892. {
  2893. struct sip_request *orig = &p->initreq;
  2894. char stripped[80] ="";
  2895. char tmp[80];
  2896. char newto[256];
  2897. char iabuf[INET_ADDRSTRLEN];
  2898. char *c, *n;
  2899. char *ot, *of;
  2900. memset(req, 0, sizeof(struct sip_request));
  2901. snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
  2902. if (!seqno) {
  2903. p->ocseq++;
  2904. seqno = p->ocseq;
  2905. }
  2906. if (newbranch) {
  2907. p->branch ^= rand();
  2908. if (p->nat & SIP_NAT_RFC3581)
  2909. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  2910. else /* Some implementations (e.g. Uniden UIP200) can't handle rport being in the message!! */
  2911. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  2912. }
  2913. if (!strcasecmp(msg, "CANCEL")) {
  2914. c = p->initreq.rlPart2; /* Use original URI */
  2915. } else if (!strcasecmp(msg, "ACK")) {
  2916. c = p->initreq.rlPart2;
  2917. } else if (!ast_strlen_zero(p->uri)) {
  2918. c = p->uri;
  2919. } else {
  2920. /* We have no URI, use To: or From: header as URI (depending on direction) */
  2921. if (p->outgoing)
  2922. strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
  2923. else
  2924. strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
  2925. c = strchr(stripped, '<');
  2926. if (c)
  2927. c++;
  2928. else
  2929. c = stripped;
  2930. n = strchr(c, '>');
  2931. if (n)
  2932. *n = '\0';
  2933. n = strchr(c, ';');
  2934. if (n)
  2935. *n = '\0';
  2936. }
  2937. init_req(req, msg, c);
  2938. snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
  2939. add_header(req, "Via", p->via);
  2940. if (p->route) {
  2941. set_destination(p, p->route->hop);
  2942. add_route(req, p->route->next);
  2943. }
  2944. ot = get_header(orig, "To");
  2945. of = get_header(orig, "From");
  2946. /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
  2947. as our original request, including tag (or presumably lack thereof) */
  2948. if (!ast_strcasestr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
  2949. /* Add the proper tag if we don't have it already. If they have specified
  2950. their tag, use it. Otherwise, use our own tag */
  2951. if (p->outgoing && !ast_strlen_zero(p->theirtag))
  2952. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  2953. else if (!p->outgoing)
  2954. snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
  2955. else
  2956. snprintf(newto, sizeof(newto), "%s", ot);
  2957. ot = newto;
  2958. }
  2959. if (p->outgoing) {
  2960. add_header(req, "From", of);
  2961. add_header(req, "To", ot);
  2962. } else {
  2963. add_header(req, "From", ot);
  2964. add_header(req, "To", of);
  2965. }
  2966. add_header(req, "Contact", p->our_contact);
  2967. copy_header(req, orig, "Call-ID");
  2968. add_header(req, "CSeq", tmp);
  2969. add_header(req, "User-Agent", default_useragent);
  2970. return 0;
  2971. }
  2972. static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
  2973. {
  2974. struct sip_request resp;
  2975. int seqno = 0;
  2976. if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
  2977. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
  2978. return -1;
  2979. }
  2980. respprep(&resp, p, msg, req);
  2981. add_header(&resp, "Content-Length", "0");
  2982. add_blank_header(&resp);
  2983. return send_response(p, &resp, reliable, seqno);
  2984. }
  2985. /*--- transmit_response: Transmit response, no retransmits */
  2986. static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
  2987. {
  2988. return __transmit_response(p, msg, req, 0);
  2989. }
  2990. /*--- transmit_response: Transmit response, Make sure you get a reply */
  2991. static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
  2992. {
  2993. return __transmit_response(p, msg, req, fatal ? 2 : 1);
  2994. }
  2995. /*--- append_date: Append date to SIP message ---*/
  2996. static void append_date(struct sip_request *req)
  2997. {
  2998. char tmpdat[256];
  2999. struct tm tm;
  3000. time_t t;
  3001. time(&t);
  3002. gmtime_r(&t, &tm);
  3003. strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
  3004. add_header(req, "Date", tmpdat);
  3005. }
  3006. /*--- transmit_response_with_date: Append date and content length before transmitting response ---*/
  3007. static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
  3008. {
  3009. struct sip_request resp;
  3010. respprep(&resp, p, msg, req);
  3011. append_date(&resp);
  3012. add_header(&resp, "Content-Length", "0");
  3013. add_blank_header(&resp);
  3014. return send_response(p, &resp, 0, 0);
  3015. }
  3016. /*--- transmit_response_with_allow: Append Accept header, content length before transmitting response ---*/
  3017. static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
  3018. {
  3019. struct sip_request resp;
  3020. respprep(&resp, p, msg, req);
  3021. add_header(&resp, "Accept", "application/sdp");
  3022. add_header(&resp, "Content-Length", "0");
  3023. add_blank_header(&resp);
  3024. return send_response(p, &resp, reliable, 0);
  3025. }
  3026. /* transmit_response_with_auth: Respond with authorization request */
  3027. static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable, char *header)
  3028. {
  3029. struct sip_request resp;
  3030. char tmp[256];
  3031. int seqno = 0;
  3032. if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
  3033. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
  3034. return -1;
  3035. }
  3036. snprintf(tmp, sizeof(tmp), "Digest realm=\"%s\", nonce=\"%s\"", global_realm, randdata);
  3037. respprep(&resp, p, msg, req);
  3038. add_header(&resp, header, tmp);
  3039. add_header(&resp, "Content-Length", "0");
  3040. add_blank_header(&resp);
  3041. return send_response(p, &resp, reliable, seqno);
  3042. }
  3043. /*--- add_text: Add text body to SIP message ---*/
  3044. static int add_text(struct sip_request *req, char *text)
  3045. {
  3046. /* XXX Convert \n's to \r\n's XXX */
  3047. int len = strlen(text);
  3048. char clen[256];
  3049. snprintf(clen, sizeof(clen), "%d", len);
  3050. add_header(req, "Content-Type", "text/plain");
  3051. add_header(req, "Content-Length", clen);
  3052. add_line(req, text);
  3053. return 0;
  3054. }
  3055. /*--- add_digit: add DTMF INFO tone to sip message ---*/
  3056. /* Always adds default duration 250 ms, regardless of what came in over the line */
  3057. static int add_digit(struct sip_request *req, char digit)
  3058. {
  3059. char tmp[256];
  3060. int len;
  3061. char clen[256];
  3062. snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
  3063. len = strlen(tmp);
  3064. snprintf(clen, sizeof(clen), "%d", len);
  3065. add_header(req, "Content-Type", "application/dtmf-relay");
  3066. add_header(req, "Content-Length", clen);
  3067. add_line(req, tmp);
  3068. return 0;
  3069. }
  3070. /*--- add_sdp: Add Session Description Protocol message ---*/
  3071. static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
  3072. {
  3073. int len = 0;
  3074. int codec = 0;
  3075. int pref_codec = 0;
  3076. int alreadysent = 0;
  3077. char costr[80];
  3078. struct sockaddr_in sin;
  3079. struct sockaddr_in vsin;
  3080. char v[256] = "";
  3081. char s[256] = "";
  3082. char o[256] = "";
  3083. char c[256] = "";
  3084. char t[256] = "";
  3085. char m[256] = "";
  3086. char m2[256] = "";
  3087. char a[1024] = "";
  3088. char a2[1024] = "";
  3089. char iabuf[INET_ADDRSTRLEN];
  3090. int x = 0;
  3091. int capability = 0 ;
  3092. struct sockaddr_in dest;
  3093. struct sockaddr_in vdest = { 0, };
  3094. int debug=0;
  3095. debug = sip_debug_test_pvt(p);
  3096. /* XXX We break with the "recommendation" and send our IP, in order that our
  3097. peer doesn't have to ast_gethostbyname() us XXX */
  3098. len = 0;
  3099. if (!p->rtp) {
  3100. ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
  3101. return -1;
  3102. }
  3103. capability = p->capability;
  3104. if (!p->sessionid) {
  3105. p->sessionid = getpid();
  3106. p->sessionversion = p->sessionid;
  3107. } else
  3108. p->sessionversion++;
  3109. ast_rtp_get_us(p->rtp, &sin);
  3110. if (p->vrtp)
  3111. ast_rtp_get_us(p->vrtp, &vsin);
  3112. if (p->redirip.sin_addr.s_addr) {
  3113. dest.sin_port = p->redirip.sin_port;
  3114. dest.sin_addr = p->redirip.sin_addr;
  3115. if (p->redircodecs)
  3116. capability = p->redircodecs;
  3117. } else {
  3118. dest.sin_addr = p->ourip;
  3119. dest.sin_port = sin.sin_port;
  3120. }
  3121. /* Determine video destination */
  3122. if (p->vrtp) {
  3123. if (p->vredirip.sin_addr.s_addr) {
  3124. vdest.sin_port = p->vredirip.sin_port;
  3125. vdest.sin_addr = p->vredirip.sin_addr;
  3126. } else {
  3127. vdest.sin_addr = p->ourip;
  3128. vdest.sin_port = vsin.sin_port;
  3129. }
  3130. }
  3131. if (debug){
  3132. ast_verbose("We're at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(sin.sin_port));
  3133. if (p->vrtp)
  3134. ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ntohs(vsin.sin_port));
  3135. }
  3136. snprintf(v, sizeof(v), "v=0\r\n");
  3137. snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
  3138. snprintf(s, sizeof(s), "s=session\r\n");
  3139. snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
  3140. snprintf(t, sizeof(t), "t=0 0\r\n");
  3141. snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
  3142. snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
  3143. /* Prefer the codec we were requested to use, first, no matter what */
  3144. if (capability & p->prefcodec) {
  3145. if (debug)
  3146. ast_verbose("Answering/Requesting with root capability 0x%x (%s)\n", p->prefcodec, ast_getformatname(p->prefcodec));
  3147. codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
  3148. if (codec > -1) {
  3149. snprintf(costr, sizeof(costr), " %d", codec);
  3150. if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
  3151. strncat(m, costr, sizeof(m) - strlen(m) - 1);
  3152. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
  3153. strncpy(a, costr, sizeof(a) - 1);
  3154. } else {
  3155. strncat(m2, costr, sizeof(m2) - strlen(m2) - 1);
  3156. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
  3157. strncpy(a2, costr, sizeof(a2) - 1);
  3158. }
  3159. }
  3160. alreadysent |= p->prefcodec;
  3161. }
  3162. /* Start by sending our preferred codecs */
  3163. for (x = 0 ; x < 32 ; x++) {
  3164. if(!(pref_codec = ast_codec_pref_index(&p->prefs,x)))
  3165. break;
  3166. if ((capability & pref_codec) && !(alreadysent & pref_codec)) {
  3167. if (debug)
  3168. ast_verbose("Answering with preferred capability 0x%x (%s)\n", pref_codec, ast_getformatname(pref_codec));
  3169. codec = ast_rtp_lookup_code(p->rtp, 1, pref_codec);
  3170. if (codec > -1) {
  3171. snprintf(costr, sizeof(costr), " %d", codec);
  3172. if (pref_codec <= AST_FORMAT_MAX_AUDIO) {
  3173. strncat(m, costr, sizeof(m) - strlen(m) - 1);
  3174. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, pref_codec));
  3175. strncat(a, costr, sizeof(a) - strlen(a) - 1);
  3176. } else {
  3177. strncat(m2, costr, sizeof(m2) - strlen(m2) - 1);
  3178. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, pref_codec));
  3179. strncat(a2, costr, sizeof(a2) - strlen(a) - 1);
  3180. }
  3181. }
  3182. }
  3183. alreadysent |= pref_codec;
  3184. }
  3185. /* Now send any other common codecs, and non-codec formats: */
  3186. for (x = 1; x <= ((videosupport && p->vrtp) ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
  3187. if ((capability & x) && !(alreadysent & x)) {
  3188. if (debug)
  3189. ast_verbose("Answering with capability 0x%x (%s)\n", x, ast_getformatname(x));
  3190. codec = ast_rtp_lookup_code(p->rtp, 1, x);
  3191. if (codec > -1) {
  3192. snprintf(costr, sizeof(costr), " %d", codec);
  3193. if (x <= AST_FORMAT_MAX_AUDIO) {
  3194. strncat(m, costr, sizeof(m) - strlen(m) - 1);
  3195. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
  3196. strncat(a, costr, sizeof(a) - strlen(a) - 1);
  3197. } else {
  3198. strncat(m2, costr, sizeof(m2) - strlen(m2) - 1);
  3199. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
  3200. strncat(a2, costr, sizeof(a2) - strlen(a2) - 1);
  3201. }
  3202. }
  3203. }
  3204. }
  3205. for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
  3206. if (p->noncodeccapability & x) {
  3207. if (debug)
  3208. ast_verbose("Answering with non-codec capability 0x%x (%s)\n", x, ast_rtp_lookup_mime_subtype(0, x));
  3209. codec = ast_rtp_lookup_code(p->rtp, 0, x);
  3210. if (codec > -1) {
  3211. snprintf(costr, sizeof(costr), " %d", codec);
  3212. strncat(m, costr, sizeof(m) - strlen(m) - 1);
  3213. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
  3214. strncat(a, costr, sizeof(a) - strlen(a) - 1);
  3215. if (x == AST_RTP_DTMF) {
  3216. /* Indicate we support DTMF and FLASH... */
  3217. snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
  3218. codec);
  3219. strncat(a, costr, sizeof(a) - strlen(a) - 1);
  3220. }
  3221. }
  3222. }
  3223. }
  3224. strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a) - 1);
  3225. if (strlen(m) < sizeof(m) - 2)
  3226. strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
  3227. if (strlen(m2) < sizeof(m2) - 2)
  3228. strncat(m2, "\r\n", sizeof(m2) - strlen(m2) - 1);
  3229. if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
  3230. ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
  3231. len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
  3232. if ((p->vrtp) && (!p->novideo) && (capability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
  3233. len += strlen(m2) + strlen(a2);
  3234. snprintf(costr, sizeof(costr), "%d", len);
  3235. add_header(resp, "Content-Type", "application/sdp");
  3236. add_header(resp, "Content-Length", costr);
  3237. add_line(resp, v);
  3238. add_line(resp, o);
  3239. add_line(resp, s);
  3240. add_line(resp, c);
  3241. add_line(resp, t);
  3242. add_line(resp, m);
  3243. add_line(resp, a);
  3244. if ((p->vrtp) && (!p->novideo) && (capability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
  3245. add_line(resp, m2);
  3246. add_line(resp, a2);
  3247. }
  3248. /* Update lastrtprx when we send our SDP */
  3249. time(&p->lastrtprx);
  3250. return 0;
  3251. }
  3252. /*--- copy_request: copy SIP request (mostly used to save request for responses) ---*/
  3253. static void copy_request(struct sip_request *dst,struct sip_request *src)
  3254. {
  3255. long offset;
  3256. int x;
  3257. offset = ((void *)dst) - ((void *)src);
  3258. /* First copy stuff */
  3259. memcpy(dst, src, sizeof(*dst));
  3260. /* Now fix pointer arithmetic */
  3261. for (x=0;x<src->headers;x++)
  3262. dst->header[x] += offset;
  3263. for (x=0;x<src->lines;x++)
  3264. dst->line[x] += offset;
  3265. }
  3266. /*--- transmit_response_with_sdp: Used for 200 OK ---*/
  3267. static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
  3268. {
  3269. struct sip_request resp;
  3270. int seqno;
  3271. if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
  3272. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
  3273. return -1;
  3274. }
  3275. respprep(&resp, p, msg, req);
  3276. ast_rtp_offered_from_local(p->rtp, 0);
  3277. add_sdp(&resp, p);
  3278. return send_response(p, &resp, retrans, seqno);
  3279. }
  3280. /*--- determine_firstline_parts: parse first line of incoming SIP request */
  3281. static int determine_firstline_parts( struct sip_request *req ) {
  3282. char *e, *cmd;
  3283. int len;
  3284. cmd= req->header[0];
  3285. while(*cmd && (*cmd < 33)) {
  3286. cmd++;
  3287. }
  3288. if (!*cmd) {
  3289. return -1;
  3290. }
  3291. e= cmd;
  3292. while(*e && (*e > 32)) {
  3293. e++;
  3294. }
  3295. /* Get the command */
  3296. if (*e) {
  3297. *e = '\0';
  3298. e++;
  3299. }
  3300. req->rlPart1= cmd;
  3301. while( *e && ( *e < 33 ) ) {
  3302. e++;
  3303. }
  3304. if( !*e ) {
  3305. return -1;
  3306. }
  3307. if ( !strcasecmp(cmd, "SIP/2.0") ) {
  3308. /* We have a response */
  3309. req->rlPart2= e;
  3310. len= strlen( req->rlPart2 );
  3311. if( len < 2 ) { return -1; }
  3312. e+= len - 1;
  3313. while( *e && *e<33 ) {
  3314. e--;
  3315. }
  3316. *(++e)= '\0';
  3317. } else {
  3318. /* We have a request */
  3319. if( *e == '<' ) {
  3320. e++;
  3321. if( !*e ) { return -1; }
  3322. }
  3323. req->rlPart2= e; /* URI */
  3324. if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
  3325. return -1;
  3326. }
  3327. while( isspace( *(--e) ) ) {}
  3328. if( *e == '>' ) {
  3329. *e= '\0';
  3330. } else {
  3331. *(++e)= '\0';
  3332. }
  3333. }
  3334. return 1;
  3335. }
  3336. /*--- transmit_reinvite_with_sdp: Transmit reinvite with SDP :-) ---*/
  3337. /* A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
  3338. INVITE that opened the SIP dialogue
  3339. We reinvite so that the audio stream (RTP) go directly between
  3340. the SIP UAs. SIP Signalling stays with * in the path.
  3341. */
  3342. static int transmit_reinvite_with_sdp(struct sip_pvt *p)
  3343. {
  3344. struct sip_request req;
  3345. if (p->canreinvite == REINVITE_UPDATE)
  3346. reqprep(&req, p, "UPDATE", 0, 1);
  3347. else
  3348. reqprep(&req, p, "INVITE", 0, 1);
  3349. add_header(&req, "Allow", ALLOWED_METHODS);
  3350. ast_rtp_offered_from_local(p->rtp, 1);
  3351. add_sdp(&req, p);
  3352. /* Use this as the basis */
  3353. copy_request(&p->initreq, &req);
  3354. parse(&p->initreq);
  3355. if (sip_debug_test_pvt(p))
  3356. ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  3357. determine_firstline_parts(&p->initreq);
  3358. p->lastinvite = p->ocseq;
  3359. p->outgoing = 1;
  3360. return send_request(p, &req, 1, p->ocseq);
  3361. }
  3362. /*--- extract_uri: Check Contact: URI of SIP message ---*/
  3363. static void extract_uri(struct sip_pvt *p, struct sip_request *req)
  3364. {
  3365. char stripped[256]="";
  3366. char *c, *n;
  3367. strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
  3368. c = strchr(stripped, '<');
  3369. if (c)
  3370. c++;
  3371. else
  3372. c = stripped;
  3373. n = strchr(c, '>');
  3374. if (n)
  3375. *n = '\0';
  3376. n = strchr(c, ';');
  3377. if (n)
  3378. *n = '\0';
  3379. if (c && !ast_strlen_zero(c))
  3380. strncpy(p->uri, c, sizeof(p->uri) - 1);
  3381. }
  3382. /*--- build_contact: Build contact header - the contact header we send out ---*/
  3383. static void build_contact(struct sip_pvt *p)
  3384. {
  3385. char iabuf[INET_ADDRSTRLEN];
  3386. /* Construct Contact: header */
  3387. if (ourport != 5060)
  3388. snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport);
  3389. else
  3390. snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip));
  3391. }
  3392. /*--- initreqprep: Initiate SIP request to peer/user ---*/
  3393. static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
  3394. {
  3395. char invite[256]="";
  3396. char from[256];
  3397. char to[256];
  3398. char tmp[80];
  3399. char iabuf[INET_ADDRSTRLEN];
  3400. char cid[256];
  3401. char *l = default_callerid, *n=NULL;
  3402. snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
  3403. if (p->owner && p->owner->callerid) {
  3404. strncpy(cid, p->owner->callerid, sizeof(cid) - 1);
  3405. cid[sizeof(cid) - 1] = '\0';
  3406. ast_callerid_parse(cid, &n, &l);
  3407. if (l)
  3408. ast_shrink_phone_number(l);
  3409. if (!l || (!ast_isphonenumber(l) && default_callerid[0]))
  3410. l = default_callerid;
  3411. }
  3412. /* if user want's his callerid restricted */
  3413. if (p->restrictcid) {
  3414. l = CALLERID_UNKNOWN;
  3415. n = l;
  3416. }
  3417. if (!n || ast_strlen_zero(n))
  3418. n = l;
  3419. /* Allow user to be overridden */
  3420. if (!ast_strlen_zero(p->fromuser))
  3421. l = p->fromuser;
  3422. else /* Save for any further attempts */
  3423. strncpy(p->fromuser, l, sizeof(p->fromuser) - 1);
  3424. /* Allow user to be overridden */
  3425. if (!ast_strlen_zero(p->fromname))
  3426. n = p->fromname;
  3427. else /* Save for any further attempts */
  3428. strncpy(p->fromname, n, sizeof(p->fromname) - 1);
  3429. if ((ourport != 5060) && ast_strlen_zero(p->fromdomain))
  3430. snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, ourport, p->tag);
  3431. else
  3432. snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, ast_strlen_zero(p->fromdomain) ? ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip) : p->fromdomain, p->tag);
  3433. /* If we're calling a registred SIP peer, use the fullcontact to dial to the peer */
  3434. if (!ast_strlen_zero(p->fullcontact)) {
  3435. /* If we have full contact, trust it */
  3436. strncpy(invite, p->fullcontact, sizeof(invite) - 1);
  3437. /* Otherwise, use the username while waiting for registration */
  3438. } else if (!ast_strlen_zero(p->username)) {
  3439. if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
  3440. snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
  3441. } else {
  3442. snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
  3443. }
  3444. } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
  3445. snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
  3446. } else {
  3447. snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
  3448. }
  3449. strncpy(p->uri, invite, sizeof(p->uri) - 1);
  3450. /* If there is a VXML URL append it to the SIP URL */
  3451. if (vxml_url)
  3452. {
  3453. snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
  3454. }
  3455. else
  3456. {
  3457. snprintf(to, sizeof(to), "<%s>", invite);
  3458. }
  3459. memset(req, 0, sizeof(struct sip_request));
  3460. init_req(req, cmd, invite);
  3461. snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
  3462. add_header(req, "Via", p->via);
  3463. /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
  3464. * OTOH, then we won't have anything in p->route anyway */
  3465. add_header(req, "From", from);
  3466. strncpy(p->exten, l, sizeof(p->exten) - 1);
  3467. build_contact(p);
  3468. add_header(req, "To", to);
  3469. add_header(req, "Contact", p->our_contact);
  3470. add_header(req, "Call-ID", p->callid);
  3471. add_header(req, "CSeq", tmp);
  3472. add_header(req, "User-Agent", default_useragent);
  3473. }
  3474. /*--- transmit_invite: Build REFER/INVITE/OPTIONS message and trasmit it ---*/
  3475. static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, char *osptoken, int init)
  3476. {
  3477. struct sip_request req;
  3478. char iabuf[INET_ADDRSTRLEN];
  3479. if (init) {
  3480. /* Bump branch even on initial requests */
  3481. p->branch ^= rand();
  3482. if (p->nat & SIP_NAT_RFC3581)
  3483. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  3484. else /* Work around buggy UNIDEN UIP200 firmware */
  3485. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  3486. initreqprep(&req, p, cmd, vxml_url);
  3487. } else
  3488. reqprep(&req, p, cmd, 0, 1);
  3489. if (auth)
  3490. add_header(&req, authheader, auth);
  3491. append_date(&req);
  3492. if (!strcasecmp(cmd, "REFER")) {
  3493. if (!ast_strlen_zero(p->refer_to))
  3494. add_header(&req, "Refer-To", p->refer_to);
  3495. if (!ast_strlen_zero(p->referred_by))
  3496. add_header(&req, "Referred-By", p->referred_by);
  3497. }
  3498. #ifdef OSP_SUPPORT
  3499. if (osptoken && !ast_strlen_zero(osptoken)) {
  3500. add_header(&req, "P-OSP-Auth-Token", osptoken);
  3501. }
  3502. #endif
  3503. if (distinctive_ring && !ast_strlen_zero(distinctive_ring))
  3504. {
  3505. add_header(&req, "Alert-Info",distinctive_ring);
  3506. }
  3507. add_header(&req, "Allow", ALLOWED_METHODS);
  3508. if (sdp) {
  3509. ast_rtp_offered_from_local(p->rtp, 1);
  3510. add_sdp(&req, p);
  3511. } else {
  3512. add_header(&req, "Content-Length", "0");
  3513. add_blank_header(&req);
  3514. }
  3515. if (!p->initreq.headers) {
  3516. /* Use this as the basis */
  3517. copy_request(&p->initreq, &req);
  3518. parse(&p->initreq);
  3519. if (sip_debug_test_pvt(p))
  3520. ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  3521. determine_firstline_parts(&p->initreq);
  3522. }
  3523. p->lastinvite = p->ocseq;
  3524. return send_request(p, &req, init ? 2 : 1, p->ocseq);
  3525. }
  3526. /*--- transmit_state_notify: Used in the SUBSCRIBE notification subsystem ----*/
  3527. static int transmit_state_notify(struct sip_pvt *p, int state, int full)
  3528. {
  3529. char tmp[4000];
  3530. int maxbytes = 0;
  3531. int bytes = 0;
  3532. char from[256], to[256];
  3533. char *t, *c, *a;
  3534. char *mfrom, *mto;
  3535. struct sip_request req;
  3536. char clen[20];
  3537. memset(from, 0, sizeof(from));
  3538. memset(to, 0, sizeof(to));
  3539. strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
  3540. c = ditch_braces(from);
  3541. if (strncmp(c, "sip:", 4)) {
  3542. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  3543. return -1;
  3544. }
  3545. if ((a = strchr(c, ';'))) {
  3546. *a = '\0';
  3547. }
  3548. mfrom = c;
  3549. reqprep(&req, p, "NOTIFY", 0, 1);
  3550. if (p->subscribed == 1) {
  3551. strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
  3552. c = ditch_braces(to);
  3553. if (strncmp(c, "sip:", 4)) {
  3554. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  3555. return -1;
  3556. }
  3557. if ((a = strchr(c, ';'))) {
  3558. *a = '\0';
  3559. }
  3560. mto = c;
  3561. add_header(&req, "Event", "presence");
  3562. add_header(&req, "Subscription-State", "active");
  3563. add_header(&req, "Content-Type", "application/xpidf+xml");
  3564. if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
  3565. state = 2;
  3566. else if (state==AST_EXTENSION_INUSE)
  3567. state = 1;
  3568. else
  3569. state = 0;
  3570. t = tmp;
  3571. maxbytes = sizeof(tmp);
  3572. bytes = snprintf(t, maxbytes, "<?xml version=\"1.0\"?>\n");
  3573. t += bytes;
  3574. maxbytes -= bytes;
  3575. bytes = snprintf(t, maxbytes, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
  3576. t += bytes;
  3577. maxbytes -= bytes;
  3578. bytes = snprintf(t, maxbytes, "<presence>\n");
  3579. t += bytes;
  3580. maxbytes -= bytes;
  3581. bytes = snprintf(t, maxbytes, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
  3582. t += bytes;
  3583. maxbytes -= bytes;
  3584. bytes = snprintf(t, maxbytes, "<atom id=\"%s\">\n", p->exten);
  3585. t += bytes;
  3586. maxbytes -= bytes;
  3587. bytes = snprintf(t, maxbytes, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
  3588. t += bytes;
  3589. maxbytes -= bytes;
  3590. bytes = snprintf(t, maxbytes, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
  3591. t += bytes;
  3592. maxbytes -= bytes;
  3593. bytes = snprintf(t, maxbytes, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
  3594. t += bytes;
  3595. maxbytes -= bytes;
  3596. bytes = snprintf(t, maxbytes, "</address>\n</atom>\n</presence>\n");
  3597. } else {
  3598. add_header(&req, "Event", "dialog");
  3599. add_header(&req, "Content-Type", "application/dialog-info+xml");
  3600. t = tmp;
  3601. maxbytes = sizeof(tmp);
  3602. bytes = snprintf(t, maxbytes, "<?xml version=\"1.0\"?>\n");
  3603. t += bytes;
  3604. maxbytes -= bytes;
  3605. bytes = snprintf(t, maxbytes, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mfrom);
  3606. t += bytes;
  3607. maxbytes -= bytes;
  3608. bytes = snprintf(t, maxbytes, "<dialog id=\"%s\">\n", p->exten);
  3609. t += bytes;
  3610. maxbytes -= bytes;
  3611. bytes = snprintf(t, maxbytes, "<state>%s</state>\n", state ? "confirmed" : "terminated");
  3612. t += bytes;
  3613. maxbytes -= bytes;
  3614. bytes = snprintf(t, maxbytes, "</dialog>\n</dialog-info>\n");
  3615. }
  3616. if (t > tmp + sizeof(tmp))
  3617. ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
  3618. snprintf(clen, sizeof(clen), "%d", (int)strlen(tmp));
  3619. add_header(&req, "Content-Length", clen);
  3620. add_line(&req, tmp);
  3621. return send_request(p, &req, 1, p->ocseq);
  3622. }
  3623. /*--- transmit_notify_with_mwi: Notify user of messages waiting in voicemail ---*/
  3624. /* Notification only works for registred peers with mailbox= definitions
  3625. * in sip.conf
  3626. * We use the SIP Event package message-summary
  3627. * MIME type defaults to "application/simple-message-summary";
  3628. */
  3629. static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs)
  3630. {
  3631. struct sip_request req;
  3632. char tmp[256];
  3633. char tmp2[256];
  3634. char clen[20];
  3635. initreqprep(&req, p, "NOTIFY", NULL);
  3636. add_header(&req, "Event", "message-summary");
  3637. add_header(&req, "Content-Type", notifymime);
  3638. snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
  3639. snprintf(tmp2, sizeof(tmp2), "Voice-Message: %d/%d\r\n", newmsgs, oldmsgs);
  3640. snprintf(clen, sizeof(clen), "%d", (int)(strlen(tmp) + strlen(tmp2)));
  3641. add_header(&req, "Content-Length", clen);
  3642. add_line(&req, tmp);
  3643. add_line(&req, tmp2);
  3644. if (!p->initreq.headers) {
  3645. /* Use this as the basis */
  3646. copy_request(&p->initreq, &req);
  3647. parse(&p->initreq);
  3648. if (sip_debug_test_pvt(p))
  3649. ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  3650. determine_firstline_parts(&p->initreq);
  3651. }
  3652. return send_request(p, &req, 1, p->ocseq);
  3653. }
  3654. /*--- transmit_notify_with_sipfrag: Notify a transferring party of the status of trasnfer ---*/
  3655. /* Apparently the draft SIP REFER structure was too simple, so it was decided that the
  3656. * status of transfers also needed to be sent via NOTIFY instead of just the 202 Accepted
  3657. * that had worked heretofore.
  3658. */
  3659. static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq)
  3660. {
  3661. struct sip_request req;
  3662. char tmp[256];
  3663. char clen[20];
  3664. reqprep(&req, p, "NOTIFY", 0, 1);
  3665. snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
  3666. add_header(&req, "Event", tmp);
  3667. add_header(&req, "Subscription-state", "terminated;reason=noresource");
  3668. add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
  3669. strncpy(tmp, "SIP/2.0 200 OK", sizeof(tmp) - 1);
  3670. snprintf(clen, sizeof(clen), "%d", (int)(strlen(tmp)));
  3671. add_header(&req, "Content-Length", clen);
  3672. add_line(&req, tmp);
  3673. if (!p->initreq.headers) {
  3674. /* Use this as the basis */
  3675. copy_request(&p->initreq, &req);
  3676. parse(&p->initreq);
  3677. if (sip_debug_test_pvt(p))
  3678. ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  3679. determine_firstline_parts(&p->initreq);
  3680. }
  3681. return send_request(p, &req, 1, p->ocseq);
  3682. }
  3683. static char *regstate2str(int regstate)
  3684. {
  3685. switch(regstate) {
  3686. case REG_STATE_UNREGISTERED:
  3687. return "Unregistered";
  3688. case REG_STATE_REGSENT:
  3689. return "Request Sent";
  3690. case REG_STATE_AUTHSENT:
  3691. return "Auth. Sent";
  3692. case REG_STATE_REGISTERED:
  3693. return "Registered";
  3694. case REG_STATE_REJECTED:
  3695. return "Rejected";
  3696. case REG_STATE_TIMEOUT:
  3697. return "Timeout";
  3698. case REG_STATE_NOAUTH:
  3699. return "No Authentication";
  3700. default:
  3701. return "Unknown";
  3702. }
  3703. }
  3704. static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
  3705. /*--- sip_reregister: Update registration with SIP Proxy---*/
  3706. static int sip_reregister(void *data)
  3707. {
  3708. /* if we are here, we know that we need to reregister. */
  3709. struct sip_registry *r=(struct sip_registry *)data;
  3710. if (sipdebug)
  3711. ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
  3712. ast_mutex_lock(&regl.lock);
  3713. r->expire = -1;
  3714. __sip_do_register(r);
  3715. ast_mutex_unlock(&regl.lock);
  3716. return 0;
  3717. }
  3718. /*--- __sip_do_register: Register with SIP proxy ---*/
  3719. static int __sip_do_register(struct sip_registry *r)
  3720. {
  3721. int res;
  3722. res=transmit_register(r, "REGISTER", NULL, NULL);
  3723. return res;
  3724. }
  3725. /*--- sip_reg_timeout: Registration timeout, register again */
  3726. static int sip_reg_timeout(void *data)
  3727. {
  3728. /* if we are here, our registration timed out, so we'll just do it over */
  3729. struct sip_registry *r=data;
  3730. struct sip_pvt *p;
  3731. int res;
  3732. ast_mutex_lock(&regl.lock);
  3733. ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again\n", r->username, r->hostname);
  3734. if (r->call) {
  3735. /* Unlink us, destroy old call. Locking is not relevent here because all this happens
  3736. in the single SIP manager thread. */
  3737. p = r->call;
  3738. p->registry = NULL;
  3739. r->call = NULL;
  3740. p->needdestroy = 1;
  3741. /* Pretend to ACK anything just in case */
  3742. __sip_pretend_ack(p);
  3743. }
  3744. r->regstate=REG_STATE_UNREGISTERED;
  3745. manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nUser: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
  3746. r->timeout = -1;
  3747. res=transmit_register(r, "REGISTER", NULL, NULL);
  3748. ast_mutex_unlock(&regl.lock);
  3749. return 0;
  3750. }
  3751. /*--- transmit_register: Transmit register to SIP proxy or UA ---*/
  3752. static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
  3753. {
  3754. struct sip_request req;
  3755. char from[256];
  3756. char to[256];
  3757. char tmp[80];
  3758. char via[80];
  3759. char addr[80];
  3760. char iabuf[INET_ADDRSTRLEN];
  3761. struct sip_pvt *p;
  3762. /* exit if we are already in process with this registrar ?*/
  3763. if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
  3764. ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
  3765. return 0;
  3766. }
  3767. if (r->call) {
  3768. if (!auth) {
  3769. ast_log(LOG_WARNING, "Already have a call??\n");
  3770. return 0;
  3771. } else
  3772. p = r->call;
  3773. } else {
  3774. /* Build callid for registration if we haven't registred before */
  3775. if (!r->callid_valid) {
  3776. build_callid(r->callid, sizeof(r->callid), __ourip, default_fromdomain);
  3777. r->callid_valid = 1;
  3778. }
  3779. /* Allocate SIP packet for registration */
  3780. p=sip_alloc( r->callid, NULL, 0);
  3781. if (!p) {
  3782. ast_log(LOG_WARNING, "Unable to allocate registration call\n");
  3783. return 0;
  3784. }
  3785. /* Find address to hostname */
  3786. if (create_addr(p,r->hostname)) {
  3787. /* we have what we hope is a temporary network error,
  3788. * probably DNS. We need to reschedule a registration try */
  3789. sip_destroy(p);
  3790. if (r->timeout > -1) {
  3791. ast_log(LOG_WARNING, "Still have a registration timeout (create_addr() error), %d\n", r->timeout);
  3792. ast_sched_del(sched, r->timeout);
  3793. }
  3794. r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
  3795. return 0;
  3796. }
  3797. /* Copy back Call-ID in case create_addr changed it */
  3798. strncpy(r->callid, p->callid, sizeof(r->callid) - 1);
  3799. if (r->portno)
  3800. p->sa.sin_port = htons(r->portno);
  3801. p->outgoing = 1; /* Registration is outgoing call */
  3802. r->call=p; /* Save pointer to SIP packet */
  3803. p->registry=r; /* Add pointer to registry in packet */
  3804. if (!ast_strlen_zero(r->secret)) /* Secret (password) */
  3805. strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
  3806. if (!ast_strlen_zero(r->md5secret))
  3807. strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
  3808. /* User name in this realm
  3809. - if authuser is set, use that, otherwise use username */
  3810. if (!ast_strlen_zero(r->authuser)) {
  3811. strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
  3812. strncpy(p->authname, r->authuser, sizeof(p->authname)-1);
  3813. } else {
  3814. if (!ast_strlen_zero(r->username)) {
  3815. strncpy(p->peername, r->username, sizeof(p->peername)-1);
  3816. strncpy(p->authname, r->username, sizeof(p->authname)-1);
  3817. strncpy(p->fromuser, r->username, sizeof(p->fromuser)-1);
  3818. }
  3819. }
  3820. if (!ast_strlen_zero(r->username))
  3821. strncpy(p->username, r->username, sizeof(p->username)-1);
  3822. /* Save extension in packet */
  3823. strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
  3824. /*
  3825. check which address we should use in our contact header
  3826. based on whether the remote host is on the external or
  3827. internal network so we can register through nat
  3828. */
  3829. if (ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip))
  3830. memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
  3831. build_contact(p);
  3832. }
  3833. /* set up a timeout */
  3834. if (auth==NULL) {
  3835. if (r->timeout > -1) {
  3836. ast_log(LOG_WARNING, "Still have a registration timeout, %d\n", r->timeout);
  3837. ast_sched_del(sched, r->timeout);
  3838. }
  3839. r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
  3840. ast_log(LOG_DEBUG, "Scheduled a registration timeout # %d\n", r->timeout);
  3841. }
  3842. if (strchr(r->username, '@')) {
  3843. snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
  3844. if (!ast_strlen_zero(p->theirtag))
  3845. snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
  3846. else
  3847. snprintf(to, sizeof(to), "<sip:%s>", r->username);
  3848. } else {
  3849. snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, p->tohost, p->tag);
  3850. if (!ast_strlen_zero(p->theirtag))
  3851. snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
  3852. else
  3853. snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
  3854. }
  3855. snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
  3856. strncpy(p->uri, addr, sizeof(p->uri) - 1);
  3857. p->branch ^= rand();
  3858. memset(&req, 0, sizeof(req));
  3859. init_req(&req, cmd, addr);
  3860. /* Add to CSEQ */
  3861. snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
  3862. p->ocseq = r->ocseq;
  3863. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  3864. if (p->nat & SIP_NAT_RFC3581)
  3865. snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  3866. else /* Work around buggy UNIDEN UIP200 firmware */
  3867. snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  3868. add_header(&req, "Via", via);
  3869. add_header(&req, "From", from);
  3870. add_header(&req, "To", to);
  3871. add_header(&req, "Call-ID", p->callid);
  3872. add_header(&req, "CSeq", tmp);
  3873. add_header(&req, "User-Agent", default_useragent);
  3874. if (auth) /* Add auth header */
  3875. add_header(&req, authheader, auth);
  3876. else if ( !ast_strlen_zero(r->nonce) ) {
  3877. char digest[1024];
  3878. /* We have auth data to reuse, build a digest header! */
  3879. if (sipdebug)
  3880. ast_log(LOG_DEBUG, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
  3881. strncpy(p->realm, r->realm, sizeof(p->realm)-1);
  3882. strncpy(p->nonce, r->nonce, sizeof(p->nonce)-1);
  3883. strncpy(p->domain, r->domain, sizeof(p->domain)-1);
  3884. strncpy(p->opaque, r->opaque, sizeof(p->opaque)-1);
  3885. strncpy(p->qop, r->qop, sizeof(p->qop)-1);
  3886. memset(digest,0,sizeof(digest));
  3887. build_reply_digest(p, "REGISTER", digest, sizeof(digest));
  3888. add_header(&req, "Authorization", digest);
  3889. }
  3890. snprintf(tmp, sizeof(tmp), "%d", default_expiry);
  3891. add_header(&req, "Expires", tmp);
  3892. add_header(&req, "Contact", p->our_contact);
  3893. add_header(&req, "Event", "registration");
  3894. add_header(&req, "Content-Length", "0");
  3895. add_blank_header(&req);
  3896. copy_request(&p->initreq, &req);
  3897. parse(&p->initreq);
  3898. if (sip_debug_test_pvt(p))
  3899. ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
  3900. determine_firstline_parts(&p->initreq);
  3901. r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
  3902. return send_request(p, &req, 2, p->ocseq);
  3903. }
  3904. /*--- transmit_message_with_text: Transmit text with SIP MESSAGE method ---*/
  3905. static int transmit_message_with_text(struct sip_pvt *p, char *text)
  3906. {
  3907. struct sip_request req;
  3908. reqprep(&req, p, "MESSAGE", 0, 1);
  3909. add_text(&req, text);
  3910. return send_request(p, &req, 1, p->ocseq);
  3911. }
  3912. /*--- transmit_refer: Transmit SIP REFER message ---*/
  3913. static int transmit_refer(struct sip_pvt *p, char *dest)
  3914. {
  3915. struct sip_request req;
  3916. char from[256];
  3917. char *of, *c;
  3918. char referto[256];
  3919. if (p->outgoing)
  3920. of = get_header(&p->initreq, "To");
  3921. else
  3922. of = get_header(&p->initreq, "From");
  3923. strncpy(from, of, sizeof(from) - 1);
  3924. of = ditch_braces(from);
  3925. strncpy(p->from,of,sizeof(p->from) - 1);
  3926. if (strncmp(of, "sip:", 4)) {
  3927. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  3928. } else
  3929. of += 4;
  3930. /* Get just the username part */
  3931. if ((c = strchr(of, '@'))) {
  3932. *c = '\0';
  3933. c++;
  3934. }
  3935. if (c) {
  3936. snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
  3937. } else {
  3938. snprintf(referto, sizeof(referto), "<sip:%s>", dest);
  3939. }
  3940. /* save in case we get 407 challenge */
  3941. strncpy(p->refer_to, referto, sizeof(p->refer_to) - 1);
  3942. strncpy(p->referred_by, p->our_contact, sizeof(p->referred_by) - 1);
  3943. reqprep(&req, p, "REFER", 0, 1);
  3944. add_header(&req, "Refer-To", referto);
  3945. if (!ast_strlen_zero(p->our_contact))
  3946. add_header(&req, "Referred-By", p->our_contact);
  3947. add_blank_header(&req);
  3948. return send_request(p, &req, 1, p->ocseq);
  3949. }
  3950. /*--- transmit_info_with_digit: Send SIP INFO dtmf message, see Cisco documentation on cisco.co
  3951. m ---*/
  3952. static int transmit_info_with_digit(struct sip_pvt *p, char digit)
  3953. {
  3954. struct sip_request req;
  3955. reqprep(&req, p, "INFO", 0, 1);
  3956. add_digit(&req, digit);
  3957. return send_request(p, &req, 1, p->ocseq);
  3958. }
  3959. /*--- transmit_request: transmit generic SIP request ---*/
  3960. static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable, int newbranch)
  3961. {
  3962. struct sip_request resp;
  3963. reqprep(&resp, p, msg, seqno, newbranch);
  3964. add_header(&resp, "Content-Length", "0");
  3965. add_blank_header(&resp);
  3966. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  3967. }
  3968. /*--- transmit_request_with_auth: Transmit SIP request, auth added ---*/
  3969. static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable, int newbranch)
  3970. {
  3971. struct sip_request resp;
  3972. reqprep(&resp, p, msg, seqno, newbranch);
  3973. if (*p->realm)
  3974. {
  3975. char digest[1024];
  3976. memset(digest,0,sizeof(digest));
  3977. build_reply_digest(p, msg, digest, sizeof(digest));
  3978. add_header(&resp, "Proxy-Authorization", digest);
  3979. }
  3980. add_header(&resp, "Content-Length", "0");
  3981. add_blank_header(&resp);
  3982. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  3983. }
  3984. static void register_peer_exten(struct sip_peer *peer, int onoff)
  3985. {
  3986. unsigned char multi[256]="";
  3987. char *stringp, *ext;
  3988. if (!ast_strlen_zero(regcontext)) {
  3989. strncpy(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi) - 1);
  3990. stringp = multi;
  3991. while((ext = strsep(&stringp, "&"))) {
  3992. if (onoff)
  3993. ast_add_extension(regcontext, 1, ext, 1, NULL, "Noop", strdup(peer->name), free, type);
  3994. else
  3995. ast_context_remove_extension(regcontext, ext, 1, NULL);
  3996. }
  3997. }
  3998. }
  3999. /*--- expire_register: Expire registration of SIP peer ---*/
  4000. static int expire_register(void *data)
  4001. {
  4002. struct sip_peer *p = data;
  4003. memset(&p->addr, 0, sizeof(p->addr));
  4004. ast_db_del("SIP/Registry", p->name);
  4005. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", p->name);
  4006. register_peer_exten(p, 0);
  4007. p->expire = -1;
  4008. ast_device_state_changed("SIP/%s", p->name);
  4009. if (p->selfdestruct) {
  4010. p->delme = 1;
  4011. prune_peers();
  4012. }
  4013. return 0;
  4014. }
  4015. static int sip_poke_peer(struct sip_peer *peer);
  4016. static int sip_poke_peer_s(void *data)
  4017. {
  4018. struct sip_peer *peer = data;
  4019. peer->pokeexpire = -1;
  4020. sip_poke_peer(peer);
  4021. return 0;
  4022. }
  4023. /*--- reg_source_db: Save registration in Asterisk DB ---*/
  4024. static void reg_source_db(struct sip_peer *p)
  4025. {
  4026. char data[256];
  4027. char iabuf[INET_ADDRSTRLEN];
  4028. struct in_addr in;
  4029. char *c, *d, *u, *e;
  4030. int expiry;
  4031. if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
  4032. c = strchr(data, ':');
  4033. if (c) {
  4034. *c = '\0';
  4035. c++;
  4036. if (inet_aton(data, &in)) {
  4037. d = strchr(c, ':');
  4038. if (d) {
  4039. *d = '\0';
  4040. d++;
  4041. u = strchr(d, ':');
  4042. if (u) {
  4043. *u = '\0';
  4044. u++;
  4045. e = strchr(u, ':');
  4046. if (e) {
  4047. *e = '\0';
  4048. e++;
  4049. strncpy(p->fullcontact, e, sizeof(p->fullcontact) - 1);
  4050. }
  4051. strncpy(p->username, u, sizeof(p->username) - 1);
  4052. }
  4053. if (option_verbose > 2)
  4054. ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding '%s' at %s@%s:%d for %d\n", p->name,
  4055. p->username, ast_inet_ntoa(iabuf, sizeof(iabuf), in), atoi(c), atoi(d));
  4056. expiry = atoi(d);
  4057. memset(&p->addr, 0, sizeof(p->addr));
  4058. p->addr.sin_family = AF_INET;
  4059. p->addr.sin_addr = in;
  4060. p->addr.sin_port = htons(atoi(c));
  4061. if (sipsock < 0) {
  4062. /* SIP isn't up yet, so schedule a poke only, pretty soon */
  4063. if (p->pokeexpire > -1)
  4064. ast_sched_del(sched, p->pokeexpire);
  4065. p->pokeexpire = ast_sched_add(sched, rand() % 5000 + 1, sip_poke_peer_s, p);
  4066. } else
  4067. sip_poke_peer(p);
  4068. if (p->expire > -1)
  4069. ast_sched_del(sched, p->expire);
  4070. p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, (void *)p);
  4071. register_peer_exten(p, 1);
  4072. }
  4073. }
  4074. }
  4075. }
  4076. }
  4077. /*--- parse_contact: Parse contact header and save registration ---*/
  4078. static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
  4079. {
  4080. char contact[80]= "";
  4081. char data[256];
  4082. char iabuf[INET_ADDRSTRLEN];
  4083. char *expires = get_header(req, "Expires");
  4084. int expiry = atoi(expires);
  4085. char *c, *n, *pt;
  4086. int port;
  4087. char *useragent;
  4088. struct hostent *hp;
  4089. struct ast_hostent ahp;
  4090. struct sockaddr_in oldsin;
  4091. if (ast_strlen_zero(expires)) {
  4092. expires = strstr(get_header(req, "Contact"), "expires=");
  4093. if (expires) {
  4094. if (sscanf(expires + 8, "%d;", &expiry) != 1)
  4095. expiry = default_expiry;
  4096. } else {
  4097. /* Nothing has been specified */
  4098. expiry = default_expiry;
  4099. }
  4100. }
  4101. /* Look for brackets */
  4102. strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
  4103. c = contact;
  4104. if ((n=strchr(c, '<'))) {
  4105. c = n + 1;
  4106. n = strchr(c, '>');
  4107. /* Lose the part after the > */
  4108. if (n)
  4109. *n = '\0';
  4110. }
  4111. if (!strcasecmp(c, "*") || !expiry) {
  4112. /* This means remove all registrations and return OK */
  4113. memset(&p->addr, 0, sizeof(p->addr));
  4114. if (p->expire > -1)
  4115. ast_sched_del(sched, p->expire);
  4116. p->expire = -1;
  4117. ast_db_del("SIP/Registry", p->name);
  4118. register_peer_exten(p, 0);
  4119. p->fullcontact[0] = '\0';
  4120. p->useragent[0] = '\0';
  4121. p->lastms = 0;
  4122. if (option_verbose > 2)
  4123. ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
  4124. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unregistered\r\n", p->name);
  4125. return 0;
  4126. }
  4127. strncpy(p->fullcontact, c, sizeof(p->fullcontact) - 1);
  4128. /* For the 200 OK, we should use the received contact */
  4129. snprintf(pvt->our_contact, sizeof(pvt->our_contact) - 1, "<%s>", c);
  4130. /* Make sure it's a SIP URL */
  4131. if (strncasecmp(c, "sip:", 4)) {
  4132. ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
  4133. } else
  4134. c += 4;
  4135. /* Ditch q */
  4136. n = strchr(c, ';');
  4137. if (n) {
  4138. *n = '\0';
  4139. }
  4140. /* Grab host */
  4141. n = strchr(c, '@');
  4142. if (!n) {
  4143. n = c;
  4144. c = NULL;
  4145. } else {
  4146. *n = '\0';
  4147. n++;
  4148. }
  4149. pt = strchr(n, ':');
  4150. if (pt) {
  4151. *pt = '\0';
  4152. pt++;
  4153. port = atoi(pt);
  4154. } else
  4155. port = DEFAULT_SIP_PORT;
  4156. memcpy(&oldsin, &p->addr, sizeof(oldsin));
  4157. if (!(p->nat & SIP_NAT_ROUTE)) {
  4158. /* XXX This could block for a long time XXX */
  4159. hp = ast_gethostbyname(n, &ahp);
  4160. if (!hp) {
  4161. ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
  4162. return -1;
  4163. }
  4164. p->addr.sin_family = AF_INET;
  4165. memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
  4166. p->addr.sin_port = htons(port);
  4167. } else {
  4168. /* Don't trust the contact field. Just use what they came to us
  4169. with */
  4170. memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
  4171. }
  4172. if (c)
  4173. strncpy(p->username, c, sizeof(p->username) - 1);
  4174. else
  4175. p->username[0] = '\0';
  4176. if (p->expire > -1)
  4177. ast_sched_del(sched, p->expire);
  4178. if ((expiry < 1) || (expiry > max_expiry))
  4179. expiry = max_expiry;
  4180. if (!p->temponly)
  4181. p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
  4182. pvt->expiry = expiry;
  4183. snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->username, p->fullcontact);
  4184. ast_db_put("SIP/Registry", p->name, data);
  4185. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", p->name);
  4186. if (inaddrcmp(&p->addr, &oldsin)) {
  4187. sip_poke_peer(p);
  4188. if (option_verbose > 2)
  4189. ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->name, ast_inet_ntoa(iabuf, sizeof(iabuf), p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
  4190. register_peer_exten(p, 1);
  4191. }
  4192. /* Save User agent */
  4193. useragent = get_header(req, "User-Agent");
  4194. if(useragent && strcasecmp(useragent, p->useragent)) {
  4195. strncpy(p->useragent, useragent, sizeof(p->useragent) - 1);
  4196. if (option_verbose > 3) {
  4197. ast_verbose(VERBOSE_PREFIX_3 "Saved useragent \"%s\" for peer %s\n",p->useragent,p->name);
  4198. }
  4199. }
  4200. return 0;
  4201. }
  4202. /*--- free_old_route: Remove route from route list ---*/
  4203. static void free_old_route(struct sip_route *route)
  4204. {
  4205. struct sip_route *next;
  4206. while (route) {
  4207. next = route->next;
  4208. free(route);
  4209. route = next;
  4210. }
  4211. }
  4212. /*--- list_route: List all routes - mostly for debugging ---*/
  4213. static void list_route(struct sip_route *route)
  4214. {
  4215. if (!route) {
  4216. ast_verbose("list_route: no route\n");
  4217. return;
  4218. }
  4219. while (route) {
  4220. ast_verbose("list_route: hop: <%s>\n", route->hop);
  4221. route = route->next;
  4222. }
  4223. }
  4224. /*--- build_route: Build route list from Record-Route header ---*/
  4225. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
  4226. {
  4227. struct sip_route *thishop, *head, *tail;
  4228. int start = 0;
  4229. int len;
  4230. char *rr, *contact, *c;
  4231. /* Once a persistant route is set, don't fool with it */
  4232. if (p->route && p->route_persistant) {
  4233. ast_log(LOG_DEBUG, "build_route: Retaining previous route: <%s>\n", p->route->hop);
  4234. return;
  4235. }
  4236. if (p->route) {
  4237. free_old_route(p->route);
  4238. p->route = NULL;
  4239. }
  4240. p->route_persistant = backwards;
  4241. /* We build up head, then assign it to p->route when we're done */
  4242. head = NULL; tail = head;
  4243. /* 1st we pass through all the hops in any Record-Route headers */
  4244. for (;;) {
  4245. /* Each Record-Route header */
  4246. rr = __get_header(req, "Record-Route", &start);
  4247. if (*rr == '\0') break;
  4248. for (;;) {
  4249. /* Each route entry */
  4250. /* Find < */
  4251. rr = strchr(rr, '<');
  4252. if (!rr) break; /* No more hops */
  4253. ++rr;
  4254. len = strcspn(rr, ">");
  4255. /* Make a struct route */
  4256. thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
  4257. if (thishop) {
  4258. strncpy(thishop->hop, rr, len); /* safe */
  4259. thishop->hop[len] = '\0';
  4260. ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
  4261. /* Link in */
  4262. if (backwards) {
  4263. /* Link in at head so they end up in reverse order */
  4264. thishop->next = head;
  4265. head = thishop;
  4266. /* If this was the first then it'll be the tail */
  4267. if (!tail) tail = thishop;
  4268. } else {
  4269. thishop->next = NULL;
  4270. /* Link in at the end */
  4271. if (tail)
  4272. tail->next = thishop;
  4273. else
  4274. head = thishop;
  4275. tail = thishop;
  4276. }
  4277. }
  4278. rr += len+1;
  4279. }
  4280. }
  4281. /* 2nd append the Contact: if there is one */
  4282. /* Can be multiple Contact headers, comma separated values - we just take the first */
  4283. contact = get_header(req, "Contact");
  4284. if (!ast_strlen_zero(contact)) {
  4285. ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
  4286. /* Look for <: delimited address */
  4287. c = strchr(contact, '<');
  4288. if (c) {
  4289. /* Take to > */
  4290. ++c;
  4291. len = strcspn(c, ">");
  4292. } else {
  4293. /* No <> - just take the lot */
  4294. c = contact; len = strlen(contact);
  4295. }
  4296. thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
  4297. if (thishop) {
  4298. strncpy(thishop->hop, c, len); /* safe */
  4299. thishop->hop[len] = '\0';
  4300. thishop->next = NULL;
  4301. /* Goes at the end */
  4302. if (tail)
  4303. tail->next = thishop;
  4304. else
  4305. head = thishop;
  4306. }
  4307. }
  4308. /* Store as new route */
  4309. p->route = head;
  4310. /* For debugging dump what we ended up with */
  4311. if (sip_debug_test_pvt(p))
  4312. list_route(p->route);
  4313. }
  4314. /*--- md5_hash: Produce MD5 hash of value. Used for authentication ---*/
  4315. static void md5_hash(char *output, char *input)
  4316. {
  4317. struct MD5Context md5;
  4318. unsigned char digest[16];
  4319. char *ptr;
  4320. int x;
  4321. MD5Init(&md5);
  4322. MD5Update(&md5, input, strlen(input));
  4323. MD5Final(digest, &md5);
  4324. ptr = output;
  4325. for (x=0;x<16;x++)
  4326. ptr += sprintf(ptr, "%2.2x", digest[x]);
  4327. }
  4328. /*--- check_auth: Check user authorization from peer definition ---*/
  4329. /* Some actions, like REGISTER and INVITEs from peers require
  4330. authentication (if peer have secret set) */
  4331. static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *md5secret, char *method, char *uri, int reliable, int ignore)
  4332. {
  4333. int res = -1;
  4334. char *response = "407 Proxy Authentication Required";
  4335. char *reqheader = "Proxy-Authorization";
  4336. char *respheader = "Proxy-Authenticate";
  4337. char *authtoken;
  4338. #ifdef OSP_SUPPORT
  4339. char tmp[80];
  4340. char *osptoken;
  4341. unsigned int osptimelimit;
  4342. #endif
  4343. /* Always OK if no secret */
  4344. if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)
  4345. #ifdef OSP_SUPPORT
  4346. && !p->ospauth
  4347. #endif
  4348. )
  4349. return 0;
  4350. if (!strcasecmp(method, "REGISTER")) {
  4351. /* On a REGISTER, we have to use 401 and its family of headers instead of 407 and its family
  4352. of headers -- GO SIP! Whoo hoo! Two things that do the same thing but are used in
  4353. different circumstances! What a surprise. */
  4354. response = "401 Unauthorized";
  4355. reqheader = "Authorization";
  4356. respheader = "WWW-Authenticate";
  4357. }
  4358. #ifdef OSP_SUPPORT
  4359. else if (p->ospauth) {
  4360. ast_log(LOG_DEBUG, "Checking OSP Authentication!\n");
  4361. osptoken = get_header(req, "P-OSP-Auth-Token");
  4362. /* Check for token existence */
  4363. if (!strlen(osptoken))
  4364. return -1;
  4365. /* Validate token */
  4366. if (ast_osp_validate(NULL, osptoken, &p->osphandle, &osptimelimit, p->callerid, p->sa.sin_addr, p->exten) < 1)
  4367. return -1;
  4368. snprintf(tmp, sizeof(tmp), "%d", p->osphandle);
  4369. pbx_builtin_setvar_helper(p->owner, "OSPHANDLE", tmp);
  4370. /* If ospauth is 'exclusive' don't require further authentication */
  4371. if ((p->ospauth > 1) || (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)))
  4372. return 0;
  4373. }
  4374. #endif
  4375. authtoken = get_header(req, reqheader);
  4376. if (ignore && !ast_strlen_zero(randdata) && ast_strlen_zero(authtoken)) {
  4377. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  4378. information */
  4379. if (!ast_strlen_zero(randdata)) {
  4380. if (!reliable) {
  4381. /* Resend message if this was NOT a reliable delivery. Otherwise the
  4382. retransmission should get it */
  4383. transmit_response_with_auth(p, response, req, randdata, reliable, respheader);
  4384. /* Schedule auto destroy in 15 seconds */
  4385. sip_scheddestroy(p, 15000);
  4386. }
  4387. res = 1;
  4388. }
  4389. } else if (ast_strlen_zero(randdata) || ast_strlen_zero(authtoken)) {
  4390. snprintf(randdata, randlen, "%08x", rand());
  4391. transmit_response_with_auth(p, response, req, randdata, reliable, respheader);
  4392. /* Schedule auto destroy in 15 seconds */
  4393. sip_scheddestroy(p, 15000);
  4394. res = 1;
  4395. } else {
  4396. /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
  4397. an example in the spec of just what it is you're doing a hash on. */
  4398. char a1[256];
  4399. char a2[256];
  4400. char a1_hash[256];
  4401. char a2_hash[256];
  4402. char resp[256];
  4403. char resp_hash[256]="";
  4404. char tmp[256] = "";
  4405. char *c;
  4406. char *z;
  4407. char *ua_hash ="";
  4408. char *resp_uri ="";
  4409. char *nonce = "";
  4410. /* Find their response among the mess that we'r sent for comparison */
  4411. strncpy(tmp, authtoken, sizeof(tmp) - 1);
  4412. c = tmp;
  4413. while(c) {
  4414. while (*c && (*c < 33)) c++;
  4415. if (!*c)
  4416. break;
  4417. if (!strncasecmp(c, "response=", strlen("response="))) {
  4418. c+= strlen("response=");
  4419. if ((*c == '\"')) {
  4420. ua_hash=++c;
  4421. if((c = strchr(c,'\"')))
  4422. *c = '\0';
  4423. } else {
  4424. ua_hash=c;
  4425. if((c = strchr(c,',')))
  4426. *c = '\0';
  4427. }
  4428. } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
  4429. c+= strlen("uri=");
  4430. if ((*c == '\"')) {
  4431. resp_uri=++c;
  4432. if((c = strchr(c,'\"')))
  4433. *c = '\0';
  4434. } else {
  4435. resp_uri=c;
  4436. if((c = strchr(c,',')))
  4437. *c = '\0';
  4438. }
  4439. } else if (!strncasecmp(c, "nonce=", strlen("nonce=")))
  4440. {
  4441. c+= strlen("nonce=");
  4442. if ((*c == '\"')) {
  4443. nonce=++c;
  4444. if ((c = strchr(c,'\"')))
  4445. *c = '\0';
  4446. } else {
  4447. nonce=c;
  4448. if ((c = strchr(c,',')))
  4449. *c = '\0';
  4450. }
  4451. } else
  4452. if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
  4453. if (c)
  4454. c++;
  4455. }
  4456. /* Check if the nonce the client sends is the same as we are testing authentication with */
  4457. if (strncasecmp(randdata, nonce, randlen)) {
  4458. ast_log(LOG_WARNING, "Stale nonce received from '%s'\n", get_header(req, "To"));
  4459. snprintf(randdata, randlen, "%08x", rand());
  4460. transmit_response_with_auth(p, response, req, randdata, reliable, respheader);
  4461. /* Schedule auto destroy in 15 seconds */
  4462. sip_scheddestroy(p, 15000);
  4463. return 1;
  4464. } else {
  4465. snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
  4466. if(!ast_strlen_zero(resp_uri))
  4467. snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
  4468. else
  4469. snprintf(a2, sizeof(a2), "%s:%s", method, uri);
  4470. if (!ast_strlen_zero(md5secret))
  4471. snprintf(a1_hash, sizeof(a1_hash), "%s", md5secret);
  4472. else
  4473. md5_hash(a1_hash, a1);
  4474. md5_hash(a2_hash, a2);
  4475. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
  4476. md5_hash(resp_hash, resp);
  4477. /* resp_hash now has the expected response, compare the two */
  4478. if (ua_hash && !strncasecmp(ua_hash, resp_hash, strlen(resp_hash))) {
  4479. /* Auth is OK */
  4480. return 0;
  4481. }
  4482. }
  4483. }
  4484. return res;
  4485. }
  4486. /*--- cb_extensionstate: Part of thte SUBSCRIBE support subsystem ---*/
  4487. static int cb_extensionstate(char *context, char* exten, int state, void *data)
  4488. {
  4489. struct sip_pvt *p = data;
  4490. if (state == -1) {
  4491. sip_scheddestroy(p, 15000);
  4492. p->stateid = -1;
  4493. return 0;
  4494. }
  4495. transmit_state_notify(p, state, 1);
  4496. if (option_debug)
  4497. ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
  4498. return 0;
  4499. }
  4500. /*--- register_verify: Verify registration of user */
  4501. static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri, int ignore)
  4502. {
  4503. int res = -1;
  4504. struct sip_peer *peer;
  4505. char tmp[256] = "";
  4506. char iabuf[INET_ADDRSTRLEN];
  4507. char *name, *c;
  4508. char *t;
  4509. /* Terminate URI */
  4510. t = uri;
  4511. while(*t && (*t > 32) && (*t != ';'))
  4512. t++;
  4513. *t = '\0';
  4514. strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
  4515. c = ditch_braces(tmp);
  4516. /* Ditch ;user=phone */
  4517. name = strchr(c, ';');
  4518. if (name)
  4519. *name = '\0';
  4520. if (!strncmp(c, "sip:", 4)) {
  4521. name = c + 4;
  4522. } else {
  4523. name = c;
  4524. ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  4525. }
  4526. c = strchr(name, '@');
  4527. if (c)
  4528. *c = '\0';
  4529. strncpy(p->exten, name, sizeof(p->exten) - 1);
  4530. build_contact(p);
  4531. ast_mutex_lock(&peerl.lock);
  4532. peer = find_peer(name, NULL);
  4533. if (!(peer && ast_apply_ha(peer->ha, sin))) {
  4534. if (peer && peer->temponly) {
  4535. if (peer->ha) {
  4536. ast_free_ha(peer->ha);
  4537. }
  4538. free(peer);
  4539. }
  4540. peer = NULL;
  4541. }
  4542. ast_mutex_unlock(&peerl.lock);
  4543. if (peer) {
  4544. if (!peer->dynamic) {
  4545. ast_log(LOG_NOTICE, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
  4546. } else {
  4547. p->nat = peer->nat;
  4548. transmit_response(p, "100 Trying", req);
  4549. if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, peer->md5secret, "REGISTER", uri, 0, ignore))) {
  4550. sip_cancel_destroy(p);
  4551. if (parse_contact(p, peer, req)) {
  4552. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  4553. } else {
  4554. update_peer(peer, p->expiry);
  4555. /* Say OK and ask subsystem to retransmit msg counter */
  4556. transmit_response_with_date(p, "200 OK", req);
  4557. peer->lastmsgssent = -1;
  4558. res = 0;
  4559. }
  4560. }
  4561. }
  4562. }
  4563. if (!peer && autocreatepeer) {
  4564. /* Create peer if we have autocreate mode enabled */
  4565. peer = temp_peer(name);
  4566. if (peer) {
  4567. ast_mutex_lock(&peerl.lock);
  4568. peer->next = peerl.peers;
  4569. peerl.peers = peer;
  4570. ast_mutex_unlock(&peerl.lock);
  4571. peer->lastmsgssent = -1;
  4572. sip_cancel_destroy(p);
  4573. if (parse_contact(p, peer, req)) {
  4574. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  4575. } else {
  4576. /* Say OK and ask subsystem to retransmit msg counter */
  4577. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
  4578. transmit_response_with_date(p, "200 OK", req);
  4579. peer->lastmsgssent = -1;
  4580. res = 0;
  4581. }
  4582. }
  4583. }
  4584. if (!res) {
  4585. ast_device_state_changed("SIP/%s", peer->name);
  4586. }
  4587. if (res < 0)
  4588. transmit_response(p, "403 Forbidden", &p->initreq);
  4589. if (peer && peer->temponly) {
  4590. if (peer->ha) {
  4591. ast_free_ha(peer->ha);
  4592. }
  4593. free(peer);
  4594. }
  4595. return res;
  4596. }
  4597. /*--- get_rdnis: get referring dnis ---*/
  4598. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
  4599. {
  4600. char tmp[256] = "", *c, *a;
  4601. struct sip_request *req;
  4602. req = oreq;
  4603. if (!req)
  4604. req = &p->initreq;
  4605. strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
  4606. if (ast_strlen_zero(tmp))
  4607. return 0;
  4608. c = ditch_braces(tmp);
  4609. if (strncmp(c, "sip:", 4)) {
  4610. ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
  4611. return -1;
  4612. }
  4613. c += 4;
  4614. if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
  4615. *a = '\0';
  4616. }
  4617. if (sip_debug_test_pvt(p))
  4618. ast_verbose("RDNIS is %s\n", c);
  4619. strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
  4620. return 0;
  4621. }
  4622. /*--- get_destination: Find out who the call is for --*/
  4623. static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
  4624. {
  4625. char tmp[256] = "", *c, *a;
  4626. char tmpf[256]= "", *fr;
  4627. struct sip_request *req;
  4628. req = oreq;
  4629. if (!req)
  4630. req = &p->initreq;
  4631. if (req->rlPart2)
  4632. strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
  4633. c = ditch_braces(tmp);
  4634. strncpy(tmpf, get_header(req, "From"), sizeof(tmpf) - 1);
  4635. fr = ditch_braces(tmpf);
  4636. if (strncmp(c, "sip:", 4)) {
  4637. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  4638. return -1;
  4639. }
  4640. c += 4;
  4641. if (!ast_strlen_zero(fr)) {
  4642. if (strncmp(fr, "sip:", 4)) {
  4643. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", fr);
  4644. return -1;
  4645. }
  4646. fr += 4;
  4647. } else
  4648. fr = NULL;
  4649. if ((a = strchr(c, '@'))) {
  4650. *a = '\0';
  4651. a++;
  4652. strncpy(p->domain, a, sizeof(p->domain)-1);
  4653. }
  4654. if ((a = strchr(c, ';'))) {
  4655. *a = '\0';
  4656. }
  4657. if (fr) {
  4658. if ((a = strchr(fr, ';')))
  4659. *a = '\0';
  4660. if ((a = strchr(fr, '@'))) {
  4661. *a = '\0';
  4662. strncpy(p->fromdomain, a + 1, sizeof(p->fromdomain) - 1);
  4663. } else
  4664. strncpy(p->fromdomain, fr, sizeof(p->fromdomain) - 1);
  4665. }
  4666. if (pedanticsipchecking)
  4667. url_decode(c);
  4668. if (sip_debug_test_pvt(p))
  4669. ast_verbose("Looking for %s in %s\n", c, p->context);
  4670. if (ast_exists_extension(NULL, p->context, c, 1, fr) ||
  4671. !strcmp(c, ast_pickup_ext())) {
  4672. if (!oreq)
  4673. strncpy(p->exten, c, sizeof(p->exten) - 1);
  4674. return 0;
  4675. }
  4676. if (ast_canmatch_extension(NULL, p->context, c, 1, fr) ||
  4677. !strncmp(c, ast_pickup_ext(),strlen(c))) {
  4678. return 1;
  4679. }
  4680. return -1;
  4681. }
  4682. /*--- hex2int: Convert hex code to integer ---*/
  4683. static int hex2int(char a)
  4684. {
  4685. if ((a >= '0') && (a <= '9')) {
  4686. return a - '0';
  4687. } else if ((a >= 'a') && (a <= 'f')) {
  4688. return a - 'a' + 10;
  4689. } else if ((a >= 'A') && (a <= 'F')) {
  4690. return a - 'A' + 10;
  4691. }
  4692. return 0;
  4693. }
  4694. /*--- get_refer_info: Call transfer support (new standard) ---*/
  4695. static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
  4696. {
  4697. char tmp[256] = "", *c, *a;
  4698. char tmp2[256] = "", *c2, *a2;
  4699. char tmp3[256];
  4700. char tmp4[256];
  4701. char tmp5[256] = ""; /* CallID to replace */
  4702. struct sip_request *req;
  4703. struct sip_pvt *p2;
  4704. req = oreq;
  4705. if (!req)
  4706. req = &p->initreq;
  4707. strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
  4708. strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
  4709. strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
  4710. strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
  4711. c = ditch_braces(tmp);
  4712. c2 = ditch_braces(tmp2);
  4713. if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
  4714. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  4715. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
  4716. return -1;
  4717. }
  4718. c += 4;
  4719. c2 += 4;
  4720. if ((a = strchr(c, '?'))) {
  4721. /* Search for arguemnts */
  4722. *a = '\0';
  4723. a++;
  4724. if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
  4725. strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
  4726. a = tmp5;
  4727. while ((a = strchr(a, '%'))) {
  4728. /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
  4729. back to an '@' */
  4730. if (strlen(a) < 3)
  4731. break;
  4732. *a = hex2int(a[1]) * 16 + hex2int(a[2]);
  4733. memmove(a + 1, a+3, strlen(a + 3) + 1);
  4734. a++;
  4735. }
  4736. if ((a = strchr(tmp5, '%')))
  4737. *a = '\0';
  4738. if ((a = strchr(tmp5, ';')))
  4739. *a = '\0';
  4740. /* Skip leading whitespace */
  4741. while(tmp5[0] && (tmp5[0] < 33))
  4742. memmove(tmp5, tmp5+1, strlen(tmp5));
  4743. }
  4744. }
  4745. if ((a = strchr(c, '@')))
  4746. *a = '\0';
  4747. if ((a = strchr(c, ';')))
  4748. *a = '\0';
  4749. if ((a2 = strchr(c2, '@')))
  4750. *a2 = '\0';
  4751. if ((a2 = strchr(c2, ';')))
  4752. *a2 = '\0';
  4753. if (sip_debug_test_pvt(p)) {
  4754. ast_verbose("Looking for %s in %s\n", c, p->context);
  4755. ast_verbose("Looking for %s in %s\n", c2, p->context);
  4756. }
  4757. if (!ast_strlen_zero(tmp5)) {
  4758. /* This is a supervised transfer */
  4759. ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
  4760. strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
  4761. strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
  4762. strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
  4763. p->refer_call = NULL;
  4764. ast_mutex_lock(&iflock);
  4765. /* Search interfaces and find the match */
  4766. p2 = iflist;
  4767. while(p2) {
  4768. if (!strcmp(p2->callid, tmp5)) {
  4769. /* Go ahead and lock it (and its owner) before returning */
  4770. ast_mutex_lock(&p2->lock);
  4771. if (p2->owner) {
  4772. while(ast_mutex_trylock(&p2->owner->lock)) {
  4773. ast_mutex_unlock(&p2->lock);
  4774. usleep(1);
  4775. ast_mutex_lock(&p2->lock);
  4776. if (!p2->owner)
  4777. break;
  4778. }
  4779. }
  4780. p->refer_call = p2;
  4781. break;
  4782. }
  4783. p2 = p2->next;
  4784. }
  4785. ast_mutex_unlock(&iflock);
  4786. if (p->refer_call) {
  4787. if (p->refer_call == p) {
  4788. ast_log(LOG_NOTICE, "Supervised transfer attempted to transfer into same call id (%s == %s)!\n", tmp5, p->callid);
  4789. p->refer_call = NULL;
  4790. } else
  4791. return 0;
  4792. } else
  4793. ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
  4794. } else if (ast_exists_extension(NULL, p->context, c, 1, NULL) || !strcmp(c, ast_parking_ext())) {
  4795. /* This is an unsupervised transfer */
  4796. ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
  4797. ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
  4798. ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
  4799. strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
  4800. strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
  4801. strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
  4802. p->refer_call = NULL;
  4803. return 0;
  4804. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  4805. return 1;
  4806. }
  4807. return -1;
  4808. }
  4809. /*--- get_also_info: Call transfer support (old way, depreciated)--*/
  4810. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
  4811. {
  4812. char tmp[256] = "", *c, *a;
  4813. struct sip_request *req;
  4814. req = oreq;
  4815. if (!req)
  4816. req = &p->initreq;
  4817. strncpy(tmp, get_header(req, "Also"), sizeof(tmp) - 1);
  4818. c = ditch_braces(tmp);
  4819. if (strncmp(c, "sip:", 4)) {
  4820. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  4821. return -1;
  4822. }
  4823. c += 4;
  4824. if ((a = strchr(c, '@')))
  4825. *a = '\0';
  4826. if ((a = strchr(c, ';')))
  4827. *a = '\0';
  4828. if (sip_debug_test_pvt(p)) {
  4829. ast_verbose("Looking for %s in %s\n", c, p->context);
  4830. }
  4831. if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
  4832. /* This is an unsupervised transfer */
  4833. ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
  4834. strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
  4835. strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
  4836. strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
  4837. p->refer_call = NULL;
  4838. return 0;
  4839. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  4840. return 1;
  4841. }
  4842. return -1;
  4843. }
  4844. /*--- check_via: check Via: headers ---*/
  4845. static int check_via(struct sip_pvt *p, struct sip_request *req)
  4846. {
  4847. char via[256] = "";
  4848. char iabuf[INET_ADDRSTRLEN];
  4849. char *c, *pt;
  4850. struct hostent *hp;
  4851. struct ast_hostent ahp;
  4852. memset(via, 0, sizeof(via));
  4853. strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
  4854. c = strchr(via, ';');
  4855. if (c)
  4856. *c = '\0';
  4857. c = strchr(via, ' ');
  4858. if (c) {
  4859. *c = '\0';
  4860. c++;
  4861. while(*c && (*c < 33))
  4862. c++;
  4863. if (strcasecmp(via, "SIP/2.0/UDP")) {
  4864. ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
  4865. return -1;
  4866. }
  4867. pt = strchr(c, ':');
  4868. if (pt) {
  4869. *pt = '\0';
  4870. pt++;
  4871. }
  4872. hp = ast_gethostbyname(c, &ahp);
  4873. if (!hp) {
  4874. ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
  4875. return -1;
  4876. }
  4877. memset(&p->sa, 0, sizeof(p->sa));
  4878. p->sa.sin_family = AF_INET;
  4879. memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
  4880. p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
  4881. c = strstr(via, ";rport");
  4882. if (c && (c[6] != '='))
  4883. p->nat |= SIP_NAT_ROUTE;
  4884. if (sip_debug_test_pvt(p)) {
  4885. if (p->nat & SIP_NAT_ROUTE)
  4886. ast_verbose("Sending to %s : %d (NAT)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
  4887. else
  4888. ast_verbose("Sending to %s : %d (non-NAT)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port));
  4889. }
  4890. }
  4891. return 0;
  4892. }
  4893. /*--- get_calleridname: Get caller id name from SIP headers ---*/
  4894. static char *get_calleridname(char *input,char *output, size_t outputsize)
  4895. {
  4896. char *end = strchr(input,'<');
  4897. char *tmp = strchr(input,'\"');
  4898. int bytes = 0;
  4899. int maxbytes = outputsize - 1;
  4900. if (!end || (end == input)) return NULL;
  4901. /* move away from "<" */
  4902. end--;
  4903. /* we found "name" */
  4904. if (tmp && tmp < end) {
  4905. end = strchr(tmp+1,'\"');
  4906. if (!end) return NULL;
  4907. bytes = (int)(end-tmp-1);
  4908. /* protect the output buffer */
  4909. if (bytes > maxbytes) {
  4910. bytes = maxbytes;
  4911. }
  4912. strncpy(output, tmp+1, bytes); /* safe */
  4913. output[maxbytes] = '\0';
  4914. } else {
  4915. /* we didn't find "name" */
  4916. /* clear the empty characters in the begining*/
  4917. while(*input && (*input < 33))
  4918. input++;
  4919. /* clear the empty characters in the end */
  4920. while(*end && (*end < 33) && end > input)
  4921. end--;
  4922. if (end >= input) {
  4923. bytes = (int)(end-input)+1;
  4924. /* protect the output buffer */
  4925. if (bytes > maxbytes) {
  4926. bytes = maxbytes;
  4927. }
  4928. strncpy(output, input, bytes); /* safe */
  4929. output[maxbytes] = '\0';
  4930. }
  4931. else
  4932. return(NULL);
  4933. }
  4934. return output;
  4935. }
  4936. /*--- get_rpid_num: Get caller id number from Remote-Party-ID header field
  4937. * Returns true if number should be restricted (privacy setting found)
  4938. * output is set to NULL if no number found
  4939. */
  4940. static int get_rpid_num(char *input,char *output, int maxlen)
  4941. {
  4942. char *start;
  4943. char *end;
  4944. start = strchr(input,':');
  4945. if (!start) {
  4946. output[0] = '\0';
  4947. return 0;
  4948. }
  4949. start++;
  4950. /* we found "number" */
  4951. strncpy(output,start,maxlen-1);
  4952. output[maxlen-1] = '\0';
  4953. end = strchr(output,'@');
  4954. if (end)
  4955. *end = '\0';
  4956. else
  4957. output[0] = '\0';
  4958. if(strstr(input,"privacy=full") || strstr(input,"privacy=uri"))
  4959. return 1;
  4960. return 0;
  4961. }
  4962. /*--- check_user: Check if matching user or peer is defined ---*/
  4963. static int check_user_full(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable, struct sockaddr_in *sin, int ignore, char *mailbox, int mailboxlen)
  4964. {
  4965. struct sip_user *user;
  4966. struct sip_peer *peer;
  4967. char *of, from[256] = "", *c;
  4968. char *rpid,rpid_num[50];
  4969. char iabuf[INET_ADDRSTRLEN];
  4970. int res = 0;
  4971. char *t;
  4972. char calleridname[50];
  4973. int debug=sip_debug_test_addr(sin);
  4974. /* Terminate URI */
  4975. t = uri;
  4976. while(*t && (*t > 32) && (*t != ';'))
  4977. t++;
  4978. *t = '\0';
  4979. of = get_header(req, "From");
  4980. strncpy(from, of, sizeof(from) - 1);
  4981. memset(calleridname,0,sizeof(calleridname));
  4982. get_calleridname(from, calleridname, sizeof(calleridname));
  4983. rpid = get_header(req, "Remote-Party-ID");
  4984. memset(rpid_num,0,sizeof(rpid_num));
  4985. if(!ast_strlen_zero(rpid))
  4986. p->restrictcid = get_rpid_num(rpid,rpid_num, sizeof(rpid_num));
  4987. of = ditch_braces(from);
  4988. if (ast_strlen_zero(p->exten)) {
  4989. t = uri;
  4990. if (!strncmp(t, "sip:", 4))
  4991. t+= 4;
  4992. strncpy(p->exten, t, sizeof(p->exten) - 1);
  4993. t = strchr(p->exten, '@');
  4994. if (t)
  4995. *t = '\0';
  4996. if (ast_strlen_zero(p->our_contact))
  4997. build_contact(p);
  4998. }
  4999. if (strncmp(of, "sip:", 4)) {
  5000. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  5001. } else
  5002. of += 4;
  5003. /* Get just the username part */
  5004. if ((c = strchr(of, '@')))
  5005. *c = '\0';
  5006. if ((c = strchr(of, ':')))
  5007. *c = '\0';
  5008. if (*calleridname)
  5009. snprintf(p->callerid,sizeof(p->callerid),"\"%s\" <%s>",calleridname,of);
  5010. else
  5011. strncpy(p->callerid, of, sizeof(p->callerid) - 1);
  5012. if (ast_strlen_zero(of))
  5013. return 0;
  5014. ast_mutex_lock(&userl.lock);
  5015. user = find_user(of);
  5016. /* Find user based on user name in the from header */
  5017. if (!mailbox && user && ast_apply_ha(user->ha, sin)) {
  5018. p->prefs = user->prefs;
  5019. p->nat = user->nat;
  5020. #ifdef OSP_SUPPORT
  5021. p->ospauth = user->ospauth;
  5022. #endif
  5023. p->trustrpid = user->trustrpid;
  5024. p->progressinband = user->progressinband;
  5025. /* replace callerid if rpid found, and not restricted */
  5026. if(!ast_strlen_zero(rpid_num) && p->trustrpid) {
  5027. if (*calleridname)
  5028. snprintf(p->callerid, sizeof(p->callerid), "\"%s\" <%s>",calleridname,rpid_num);
  5029. else
  5030. strncpy(p->callerid, rpid_num, sizeof(p->callerid) - 1);
  5031. }
  5032. if (p->rtp) {
  5033. ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (p->nat & SIP_NAT_ROUTE));
  5034. ast_rtp_setnat(p->rtp, (p->nat & SIP_NAT_ROUTE));
  5035. }
  5036. if (p->vrtp) {
  5037. ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (p->nat & SIP_NAT_ROUTE));
  5038. ast_rtp_setnat(p->vrtp, (p->nat & SIP_NAT_ROUTE));
  5039. }
  5040. if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, user->md5secret, cmd, uri, reliable, ignore))) {
  5041. sip_cancel_destroy(p);
  5042. if (!ast_strlen_zero(user->context))
  5043. strncpy(p->context, user->context, sizeof(p->context) - 1);
  5044. if (!ast_strlen_zero(user->callerid) && !ast_strlen_zero(p->callerid))
  5045. strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
  5046. strncpy(p->username, user->name, sizeof(p->username) - 1);
  5047. strncpy(p->peersecret, user->secret, sizeof(p->peersecret) - 1);
  5048. strncpy(p->peermd5secret, user->md5secret, sizeof(p->peermd5secret) - 1);
  5049. strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
  5050. strncpy(p->language, user->language, sizeof(p->language) -1);
  5051. strncpy(p->musicclass, user->musicclass, sizeof(p->musicclass) -1);
  5052. p->canreinvite = user->canreinvite;
  5053. p->amaflags = user->amaflags;
  5054. p->callgroup = user->callgroup;
  5055. p->pickupgroup = user->pickupgroup;
  5056. p->restrictcid = user->restrictcid;
  5057. p->capability = user->capability;
  5058. p->jointcapability = user->capability;
  5059. if (p->peercapability)
  5060. p->jointcapability &= p->peercapability;
  5061. p->promiscredir = user->promiscredir;
  5062. if (user->dtmfmode) {
  5063. p->dtmfmode = user->dtmfmode;
  5064. if (p->dtmfmode & SIP_DTMF_RFC2833)
  5065. p->noncodeccapability |= AST_RTP_DTMF;
  5066. else
  5067. p->noncodeccapability &= ~AST_RTP_DTMF;
  5068. }
  5069. }
  5070. if (user && debug)
  5071. ast_verbose("Found user '%s'\n", user->name);
  5072. } else {
  5073. if (!mailbox && user && debug)
  5074. ast_verbose("Found user '%s', but fails host access\n", user->name);
  5075. user = NULL;
  5076. }
  5077. #ifdef MYSQL_USERS
  5078. if (user && user->temponly)
  5079. free(user);
  5080. #endif
  5081. ast_mutex_unlock(&userl.lock);
  5082. if (!user) {
  5083. /* If we didn't find a user match, check for peers */
  5084. ast_mutex_lock(&peerl.lock);
  5085. /* Look for peer based on the IP address we received data from */
  5086. /* If peer is registred from this IP address or have this as a default
  5087. IP address, this call is from the peer
  5088. */
  5089. peer = find_peer(NULL, &p->recv);
  5090. if (peer) {
  5091. if (debug)
  5092. ast_verbose("Found peer '%s'\n", peer->name);
  5093. /* Take the peer */
  5094. p->nat = peer->nat;
  5095. p->trustrpid = peer->trustrpid;
  5096. p->progressinband = peer->progressinband;
  5097. /* replace callerid if rpid found, and not restricted */
  5098. if(!ast_strlen_zero(rpid_num) && p->trustrpid) {
  5099. if (*calleridname)
  5100. snprintf(p->callerid,sizeof(p->callerid),"\"%s\" <%s>",calleridname,rpid_num);
  5101. else
  5102. strncpy(p->callerid, rpid_num, sizeof(p->callerid) - 1);
  5103. }
  5104. #ifdef OSP_SUPPORT
  5105. p->ospauth = peer->ospauth;
  5106. #endif
  5107. if (p->rtp) {
  5108. ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (p->nat & SIP_NAT_ROUTE));
  5109. ast_rtp_setnat(p->rtp, (p->nat & SIP_NAT_ROUTE));
  5110. }
  5111. if (p->vrtp) {
  5112. ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (p->nat & SIP_NAT_ROUTE));
  5113. ast_rtp_setnat(p->vrtp, (p->nat & SIP_NAT_ROUTE));
  5114. }
  5115. strncpy(p->peersecret, peer->secret, sizeof(p->peersecret)-1);
  5116. p->peersecret[sizeof(p->peersecret)-1] = '\0';
  5117. strncpy(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret)-1);
  5118. p->peermd5secret[sizeof(p->peermd5secret)-1] = '\0';
  5119. if (peer->insecure > 1) {
  5120. /* Pretend there is no required authentication if insecure is "very" */
  5121. p->peersecret[0] = '\0';
  5122. p->peermd5secret[0] = '\0';
  5123. }
  5124. if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, p->peersecret, p->peermd5secret, cmd, uri, reliable, ignore))) {
  5125. p->canreinvite = peer->canreinvite;
  5126. strncpy(p->peername, peer->name, sizeof(p->peername) - 1);
  5127. strncpy(p->authname, peer->name, sizeof(p->authname) - 1);
  5128. if (mailbox)
  5129. snprintf(mailbox, mailboxlen, ",%s,", peer->mailbox);
  5130. if (!ast_strlen_zero(peer->username)) {
  5131. strncpy(p->username, peer->username, sizeof(p->username) - 1);
  5132. strncpy(p->authname, peer->username, sizeof(p->authname) - 1);
  5133. }
  5134. strncpy(p->fullcontact, peer->fullcontact, sizeof(p->fullcontact) - 1);
  5135. if (!ast_strlen_zero(peer->context))
  5136. strncpy(p->context, peer->context, sizeof(p->context) - 1);
  5137. strncpy(p->peersecret, peer->secret, sizeof(p->peersecret) - 1);
  5138. strncpy(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret) - 1);
  5139. strncpy(p->language, peer->language, sizeof(p->language) -1);
  5140. p->callgroup = peer->callgroup;
  5141. p->pickupgroup = peer->pickupgroup;
  5142. p->capability = peer->capability;
  5143. p->jointcapability = peer->capability;
  5144. if (p->peercapability)
  5145. p->jointcapability &= p->peercapability;
  5146. p->promiscredir = peer->promiscredir;
  5147. if (peer->dtmfmode) {
  5148. p->dtmfmode = peer->dtmfmode;
  5149. if (p->dtmfmode & SIP_DTMF_RFC2833)
  5150. p->noncodeccapability |= AST_RTP_DTMF;
  5151. else
  5152. p->noncodeccapability &= ~AST_RTP_DTMF;
  5153. }
  5154. }
  5155. if (peer->temponly) {
  5156. if (peer->ha) {
  5157. ast_free_ha(peer->ha);
  5158. }
  5159. free(peer);
  5160. }
  5161. } else
  5162. if (debug)
  5163. ast_verbose("Found no matching peer or user for '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
  5164. ast_mutex_unlock(&peerl.lock);
  5165. }
  5166. return res;
  5167. }
  5168. static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable, struct sockaddr_in *sin, int ignore)
  5169. {
  5170. return check_user_full(p, req, cmd, uri, reliable, sin, ignore, NULL, 0);
  5171. }
  5172. /*--- get_msg_text: Get text out of a SIP MESSAGE ---*/
  5173. static int get_msg_text(char *buf, int len, struct sip_request *req)
  5174. {
  5175. int x;
  5176. int y;
  5177. buf[0] = '\0';
  5178. y = len - strlen(buf) - 5;
  5179. if (y < 0)
  5180. y = 0;
  5181. for (x=0;x<req->lines;x++) {
  5182. strncat(buf, req->line[x], y); /* safe */
  5183. y -= strlen(req->line[x]) + 1;
  5184. if (y < 0)
  5185. y = 0;
  5186. if (y != 0)
  5187. strcat(buf, "\n"); /* safe */
  5188. }
  5189. return 0;
  5190. }
  5191. /*--- receive_message: Receive SIP MESSAGE method messages ---*/
  5192. /* we handle messages within current calls currently */
  5193. static void receive_message(struct sip_pvt *p, struct sip_request *req)
  5194. {
  5195. char buf[1024];
  5196. struct ast_frame f;
  5197. if (get_msg_text(buf, sizeof(buf), req)) {
  5198. ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
  5199. return;
  5200. }
  5201. if (p->owner) {
  5202. if (sip_debug_test_pvt(p))
  5203. ast_verbose("Message received: '%s'\n", buf);
  5204. memset(&f, 0, sizeof(f));
  5205. f.frametype = AST_FRAME_TEXT;
  5206. f.subclass = 0;
  5207. f.offset = 0;
  5208. f.data = buf;
  5209. f.datalen = strlen(buf);
  5210. ast_queue_frame(p->owner, &f);
  5211. }
  5212. }
  5213. /*--- sip_show_inuse: CLI Command to show calls within limits set by
  5214. outgoinglimit and incominglimit ---*/
  5215. static int sip_show_inuse(int fd, int argc, char *argv[]) {
  5216. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-15.15s\n"
  5217. #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-15.15s\n"
  5218. struct sip_user *user;
  5219. char ilimits[40] = "";
  5220. char olimits[40] = "";
  5221. char iused[40];
  5222. char oused[40];
  5223. if (argc != 3)
  5224. return RESULT_SHOWUSAGE;
  5225. ast_mutex_lock(&userl.lock);
  5226. user = userl.users;
  5227. ast_cli(fd, FORMAT, "Username", "incoming", "Limit","outgoing","Limit");
  5228. for(user=userl.users;user;user=user->next) {
  5229. if (user->incominglimit)
  5230. snprintf(ilimits, sizeof(ilimits), "%d", user->incominglimit);
  5231. else
  5232. strncpy(ilimits, "N/A", sizeof(ilimits) - 1);
  5233. if (user->outgoinglimit)
  5234. snprintf(olimits, sizeof(olimits), "%d", user->outgoinglimit);
  5235. else
  5236. strncpy(olimits, "N/A", sizeof(olimits) - 1);
  5237. snprintf(iused, sizeof(iused), "%d", user->inUse);
  5238. snprintf(oused, sizeof(oused), "%d", user->outUse);
  5239. ast_cli(fd, FORMAT2, user->name, iused, ilimits,oused,olimits);
  5240. }
  5241. ast_mutex_unlock(&userl.lock);
  5242. return RESULT_SUCCESS;
  5243. #undef FORMAT
  5244. #undef FORMAT2
  5245. }
  5246. static char *nat2str(int nat)
  5247. {
  5248. switch(nat) {
  5249. case SIP_NAT_NEVER:
  5250. return "No";
  5251. case SIP_NAT_ROUTE:
  5252. return "Route";
  5253. case SIP_NAT_ALWAYS:
  5254. return "Always";
  5255. case SIP_NAT_RFC3581:
  5256. return "RFC3581";
  5257. default:
  5258. return "Unknown";
  5259. }
  5260. }
  5261. /*--- sip_show_users: CLI Command 'SIP Show Users' ---*/
  5262. static int sip_show_users(int fd, int argc, char *argv[])
  5263. {
  5264. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s%-5.5s\n"
  5265. struct sip_user *user;
  5266. if (argc != 3)
  5267. return RESULT_SHOWUSAGE;
  5268. ast_mutex_lock(&userl.lock);
  5269. ast_cli(fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
  5270. for(user=userl.users;user;user=user->next) {
  5271. ast_cli(fd, FORMAT, user->name,
  5272. user->secret,
  5273. user->accountcode,
  5274. user->context,
  5275. user->ha ? "Yes" : "No",
  5276. nat2str(user->nat));
  5277. }
  5278. ast_mutex_unlock(&userl.lock);
  5279. return RESULT_SUCCESS;
  5280. #undef FORMAT
  5281. }
  5282. /*--- sip_show_peers: CLI Show Peers command */
  5283. static int sip_show_peers(int fd, int argc, char *argv[])
  5284. {
  5285. #define FORMAT2 "%-15.15s %-15.15s %s %s %s %-15.15s %-8s %-10s\n"
  5286. #define FORMAT "%-15.15s %-15.15s %s %s %s %-15.15s %-8d %-10s\n"
  5287. struct sip_peer *peer;
  5288. char name[256] = "";
  5289. char iabuf[INET_ADDRSTRLEN];
  5290. if (argc != 3 && argc != 5)
  5291. return RESULT_SHOWUSAGE;
  5292. ast_mutex_lock(&peerl.lock);
  5293. ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Mask", "Port", "Status");
  5294. for (peer = peerl.peers;peer;peer = peer->next) {
  5295. char nm[20] = "";
  5296. char status[20] = "";
  5297. int print_line = -1;
  5298. char srch[2000];
  5299. ast_inet_ntoa(nm, sizeof(nm), peer->mask);
  5300. if (!ast_strlen_zero(peer->username))
  5301. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  5302. else
  5303. strncpy(name, peer->name, sizeof(name) - 1);
  5304. if (peer->maxms) {
  5305. if (peer->lastms < 0)
  5306. strncpy(status, "UNREACHABLE", sizeof(status) - 1);
  5307. else if (peer->lastms > peer->maxms)
  5308. snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
  5309. else if (peer->lastms)
  5310. snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
  5311. else
  5312. strncpy(status, "UNKNOWN", sizeof(status) - 1);
  5313. } else
  5314. strncpy(status, "Unmonitored", sizeof(status) - 1);
  5315. snprintf(srch, sizeof(srch), FORMAT, name,
  5316. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
  5317. peer->dynamic ? " D " : " ", /* Dynamic or not? */
  5318. (peer->nat & SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
  5319. peer->ha ? " A " : " ", /* permit/deny */
  5320. nm,
  5321. ntohs(peer->addr.sin_port), status);
  5322. if (argc == 5) {
  5323. if (!strcasecmp(argv[3],"include") && strstr(srch,argv[4])) {
  5324. print_line = -1;
  5325. } else if (!strcasecmp(argv[3],"exclude") && !strstr(srch,argv[4])) {
  5326. print_line = 1;
  5327. } else if (!strcasecmp(argv[3],"begin") && !strncasecmp(srch,argv[4],strlen(argv[4]))) {
  5328. print_line = -1;
  5329. } else {
  5330. print_line = 0;
  5331. }
  5332. }
  5333. if (print_line) {
  5334. ast_cli(fd, FORMAT, name,
  5335. peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
  5336. peer->dynamic ? " D " : " ", /* Dynamic or not? */
  5337. (peer->nat & SIP_NAT_ROUTE) ? " N " : " ", /* NAT=yes? */
  5338. peer->ha ? " A " : " ", /* permit/deny */
  5339. nm,
  5340. ntohs(peer->addr.sin_port), status);
  5341. }
  5342. }
  5343. ast_mutex_unlock(&peerl.lock);
  5344. return RESULT_SUCCESS;
  5345. #undef FORMAT
  5346. #undef FORMAT2
  5347. }
  5348. /*--- print_group: Print call group and pickup group ---*/
  5349. static void print_group(int fd, unsigned int group)
  5350. {
  5351. unsigned int i;
  5352. int first=1;
  5353. for (i=0; i<=31; i++) { /* Max group is 31 */
  5354. if (group & (1 << i)) {
  5355. if (!first) {
  5356. ast_cli(fd, ", ");
  5357. } else {
  5358. first=0;
  5359. }
  5360. ast_cli(fd, "%u", i);
  5361. }
  5362. }
  5363. ast_cli(fd, " (%u)\n", group);
  5364. }
  5365. /*--- sip_show_peer: Show one peer in detail ---*/
  5366. static int sip_show_peer(int fd, int argc, char *argv[])
  5367. {
  5368. char status[30] = "";
  5369. char iabuf[INET_ADDRSTRLEN];
  5370. struct sip_peer *peer;
  5371. char codec_buf[512];
  5372. struct ast_codec_pref *pref;
  5373. int x = 0, codec = 0;
  5374. if (argc != 4)
  5375. return RESULT_SHOWUSAGE;
  5376. ast_mutex_lock(&peerl.lock);
  5377. peer = find_peer(argv[3], NULL);
  5378. if (peer) {
  5379. ast_cli(fd,"\n\n");
  5380. ast_cli(fd, " * Name : %s\n", peer->name);
  5381. ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
  5382. ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
  5383. ast_cli(fd, " Context : %s\n", peer->context);
  5384. ast_cli(fd, " Language : %s\n", peer->language);
  5385. ast_cli(fd, " FromUser : %s\n", peer->fromuser);
  5386. ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
  5387. ast_cli(fd, " Callgroup : ");
  5388. print_group(fd, peer->callgroup);
  5389. ast_cli(fd, " Pickupgroup : ");
  5390. print_group(fd, peer->pickupgroup);
  5391. ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
  5392. ast_cli(fd, " LastMsgsSent : %d\n", peer->lastmsgssent);
  5393. ast_cli(fd, " Dynamic : %s\n", (peer->dynamic?"Yes":"No"));
  5394. ast_cli(fd, " Expire : %ld seconds\n", ast_sched_when(sched,peer->expire));
  5395. ast_cli(fd, " Expiry : %d\n", peer->expiry);
  5396. ast_cli(fd, " Insecure : %s\n", (peer->insecure?((peer->insecure == 2)?"Very":"Yes"):"No") );
  5397. ast_cli(fd, " Nat : %s\n", nat2str(peer->nat));
  5398. ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
  5399. ast_cli(fd, " CanReinvite : %s\n", (peer->canreinvite?"Yes":"No"));
  5400. ast_cli(fd, " PromiscRedir : %s\n", (peer->promiscredir?"Yes":"No"));
  5401. /* - is enumerated */
  5402. ast_cli(fd, " DTMFmode : ");
  5403. if (peer->dtmfmode == SIP_DTMF_RFC2833)
  5404. ast_cli(fd, "rfc2833 ");
  5405. if (peer->dtmfmode == SIP_DTMF_INFO)
  5406. ast_cli(fd, "info ");
  5407. if (peer->dtmfmode == SIP_DTMF_INBAND)
  5408. ast_cli(fd, "inband ");
  5409. ast_cli(fd, "\n" );
  5410. ast_cli(fd, " LastMsg : %d\n", peer->lastmsg);
  5411. ast_cli(fd, " ToHost : %s\n", peer->tohost);
  5412. ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
  5413. ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
  5414. ast_cli(fd, " Username : %s\n", peer->username);
  5415. ast_cli(fd, " Codecs : ");
  5416. ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
  5417. ast_cli(fd, "%s\n", codec_buf);
  5418. ast_cli(fd, " Codec Order : (");
  5419. pref = &peer->prefs;
  5420. for(x = 0; x < 32 ; x++) {
  5421. codec = ast_codec_pref_index(pref,x);
  5422. if(!codec)
  5423. break;
  5424. ast_cli(fd, "%s", ast_getformatname(codec));
  5425. if(x < 31 && ast_codec_pref_index(pref,x+1))
  5426. ast_cli(fd, "|");
  5427. }
  5428. if (!x)
  5429. ast_cli(fd, "none");
  5430. ast_cli(fd, ")\n");
  5431. ast_cli(fd, " Status : ");
  5432. if (peer->lastms < 0)
  5433. strncpy(status, "UNREACHABLE", sizeof(status) - 1);
  5434. else if (peer->lastms > peer->maxms)
  5435. snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
  5436. else if (peer->lastms)
  5437. snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
  5438. else
  5439. strncpy(status, "UNKNOWN", sizeof(status) - 1);
  5440. ast_cli(fd, "%s\n",status);
  5441. ast_cli(fd, " Useragent : %s\n", peer->useragent);
  5442. ast_cli(fd, " Full Contact : %s\n", peer->fullcontact);
  5443. ast_cli(fd,"\n");
  5444. } else {
  5445. ast_cli(fd,"Peer %s not found.\n", argv[3]);
  5446. ast_cli(fd,"\n");
  5447. }
  5448. ast_mutex_unlock(&peerl.lock);
  5449. return RESULT_SUCCESS;
  5450. }
  5451. /*--- sip_show_registry: Show SIP Registry (registrations with other SIP proxies ---*/
  5452. static int sip_show_registry(int fd, int argc, char *argv[])
  5453. {
  5454. #define FORMAT2 "%-30.30s %-12.12s %8.8s %-20.20s\n"
  5455. #define FORMAT "%-30.30s %-12.12s %8d %-20.20s\n"
  5456. struct sip_registry *reg;
  5457. char host[80];
  5458. if (argc != 3)
  5459. return RESULT_SHOWUSAGE;
  5460. ast_mutex_lock(&regl.lock);
  5461. ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
  5462. for (reg = regl.registrations;reg;reg = reg->next) {
  5463. snprintf(host, sizeof(host), "%s:%d", reg->hostname, reg->portno ? reg->portno : DEFAULT_SIP_PORT);
  5464. ast_cli(fd, FORMAT, host,
  5465. reg->username, reg->refresh, regstate2str(reg->regstate));
  5466. }
  5467. ast_mutex_unlock(&regl.lock);
  5468. return RESULT_SUCCESS;
  5469. #undef FORMAT
  5470. #undef FORMAT2
  5471. }
  5472. /* Forward declaration */
  5473. static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions);
  5474. /*--- sip_show_channels: Show active SIP channels ---*/
  5475. static int sip_show_channels(int fd, int argc, char *argv[])
  5476. {
  5477. return __sip_show_channels(fd, argc, argv, 0);
  5478. }
  5479. /*--- sip_show_subscriptions: Show active SIP subscriptions ---*/
  5480. static int sip_show_subscriptions(int fd, int argc, char *argv[])
  5481. {
  5482. return __sip_show_channels(fd, argc, argv, 1);
  5483. }
  5484. static int __sip_show_channels(int fd, int argc, char *argv[], int subscriptions)
  5485. {
  5486. #define FORMAT3 "%-15.15s %-10.10s %-21.21s %-15.15s\n"
  5487. #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %s\n"
  5488. #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-6.6s%s\n"
  5489. struct sip_pvt *cur;
  5490. char iabuf[INET_ADDRSTRLEN];
  5491. int numchans = 0;
  5492. if (argc != 3)
  5493. return RESULT_SHOWUSAGE;
  5494. ast_mutex_lock(&iflock);
  5495. cur = iflist;
  5496. if (!subscriptions)
  5497. ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Format");
  5498. else
  5499. ast_cli(fd, FORMAT3, "Peer", "User", "Call ID", "URI");
  5500. while (cur) {
  5501. if (!cur->subscribed && !subscriptions) {
  5502. ast_cli(fd, FORMAT, ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr),
  5503. ast_strlen_zero(cur->username) ? ( ast_strlen_zero(cur->callerid) ? "(None)" : cur->callerid ) : cur->username,
  5504. cur->callid,
  5505. cur->ocseq, cur->icseq,
  5506. ast_getformatname(cur->owner ? cur->owner->nativeformats : 0), cur->needdestroy ? "(d)" : "" );
  5507. numchans++;
  5508. }
  5509. if (cur->subscribed && subscriptions) {
  5510. ast_cli(fd, FORMAT3, ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr),
  5511. ast_strlen_zero(cur->username) ? ( ast_strlen_zero(cur->callerid) ? "(None)" : cur->callerid ) : cur->username,
  5512. cur->callid, cur->uri);
  5513. }
  5514. cur = cur->next;
  5515. }
  5516. ast_mutex_unlock(&iflock);
  5517. if (!subscriptions)
  5518. ast_cli(fd, "%d active SIP channel(s)\n", numchans);
  5519. else
  5520. ast_cli(fd, "%d active SIP subscriptions(s)\n", numchans);
  5521. return RESULT_SUCCESS;
  5522. #undef FORMAT
  5523. #undef FORMAT2
  5524. #undef FORMAT3
  5525. }
  5526. /*--- complete_sipch: Support routine for 'sip show channel' CLI ---*/
  5527. static char *complete_sipch(char *line, char *word, int pos, int state)
  5528. {
  5529. int which=0;
  5530. struct sip_pvt *cur;
  5531. char *c = NULL;
  5532. ast_mutex_lock(&iflock);
  5533. cur = iflist;
  5534. while(cur) {
  5535. if (!strncasecmp(word, cur->callid, strlen(word))) {
  5536. if (++which > state) {
  5537. c = strdup(cur->callid);
  5538. break;
  5539. }
  5540. }
  5541. cur = cur->next;
  5542. }
  5543. ast_mutex_unlock(&iflock);
  5544. return c;
  5545. }
  5546. /*--- sip_show_channel: Show details of one call ---*/
  5547. static int sip_show_channel(int fd, int argc, char *argv[])
  5548. {
  5549. struct sip_pvt *cur;
  5550. char tmp[256];
  5551. char iabuf[INET_ADDRSTRLEN];
  5552. size_t len;
  5553. int found = 0;
  5554. if (argc != 4)
  5555. return RESULT_SHOWUSAGE;
  5556. len = strlen(argv[3]);
  5557. ast_mutex_lock(&iflock);
  5558. cur = iflist;
  5559. while(cur) {
  5560. if (!strncasecmp(cur->callid, argv[3],len)) {
  5561. ast_cli(fd,"\n");
  5562. if (cur->subscribed)
  5563. ast_cli(fd, " * Subscription\n");
  5564. else
  5565. ast_cli(fd, " * SIP Call\n");
  5566. ast_cli(fd, " Direction: %s\n", cur->outgoing?"Outgoing":"Incoming");
  5567. ast_cli(fd, " Call-ID: %s\n", cur->callid);
  5568. ast_cli(fd, " Our Codec Capability: %d\n", cur->capability);
  5569. ast_cli(fd, " Non-Codec Capability: %d\n", cur->noncodeccapability);
  5570. ast_cli(fd, " Their Codec Capability: %d\n", cur->peercapability);
  5571. ast_cli(fd, " Joint Codec Capability: %d\n", cur->jointcapability);
  5572. ast_cli(fd, " Format %s\n", ast_getformatname(cur->owner ? cur->owner->nativeformats : 0) );
  5573. ast_cli(fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->sa.sin_addr), ntohs(cur->sa.sin_port));
  5574. ast_cli(fd, " Received Address: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), cur->recv.sin_addr), ntohs(cur->recv.sin_port));
  5575. ast_cli(fd, " NAT Support: %s\n", nat2str(cur->nat));
  5576. ast_cli(fd, " Our Tag: %08d\n", cur->tag);
  5577. ast_cli(fd, " Their Tag: %s\n", cur->theirtag);
  5578. ast_cli(fd, " SIP User agent: %s\n", cur->useragent);
  5579. if (!ast_strlen_zero(cur->username))
  5580. ast_cli(fd, " Username: %s\n", cur->username);
  5581. if (!ast_strlen_zero(cur->peername))
  5582. ast_cli(fd, " Peername: %s\n", cur->peername);
  5583. if (!ast_strlen_zero(cur->uri))
  5584. ast_cli(fd, " Original uri: %s\n", cur->uri);
  5585. if (!ast_strlen_zero(cur->callerid))
  5586. ast_cli(fd, " Caller-ID: %s\n", cur->callerid);
  5587. ast_cli(fd, " Need Destroy: %d\n", cur->needdestroy);
  5588. ast_cli(fd, " Last Message: %s\n", cur->lastmsg);
  5589. ast_cli(fd, " Promiscuous Redir: %s\n", cur->promiscredir ? "Yes" : "No");
  5590. ast_cli(fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
  5591. tmp[0] = '\0';
  5592. if (cur->dtmfmode & SIP_DTMF_RFC2833)
  5593. strncat(tmp, "rfc2833 ", sizeof(tmp) - strlen(tmp) - 1);
  5594. if (cur->dtmfmode & SIP_DTMF_INFO)
  5595. strncat(tmp, "info ", sizeof(tmp) - strlen(tmp) - 1);
  5596. if (cur->dtmfmode & SIP_DTMF_INBAND)
  5597. strncat(tmp, "inband ", sizeof(tmp) - strlen(tmp) - 1);
  5598. ast_cli(fd, " DTMF Mode: %s\n\n", tmp);
  5599. found++;
  5600. }
  5601. cur = cur->next;
  5602. }
  5603. ast_mutex_unlock(&iflock);
  5604. if (!found)
  5605. ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
  5606. return RESULT_SUCCESS;
  5607. }
  5608. /*--- sip_show_channel: Show details of one call ---*/
  5609. static int sip_show_history(int fd, int argc, char *argv[])
  5610. {
  5611. struct sip_pvt *cur;
  5612. struct sip_history *hist;
  5613. size_t len;
  5614. int x;
  5615. int found = 0;
  5616. if (argc != 4)
  5617. return RESULT_SHOWUSAGE;
  5618. if (!recordhistory)
  5619. ast_cli(fd, "\n***Note: History recording is currently DISABLED. Use 'sip history' to ENABLE.\n");
  5620. len = strlen(argv[3]);
  5621. ast_mutex_lock(&iflock);
  5622. cur = iflist;
  5623. while(cur) {
  5624. if (!strncasecmp(cur->callid, argv[3],len)) {
  5625. ast_cli(fd,"\n");
  5626. if (cur->subscribed)
  5627. ast_cli(fd, " * Subscription\n");
  5628. else
  5629. ast_cli(fd, " * SIP Call\n");
  5630. x = 0;
  5631. hist = cur->history;
  5632. while(hist) {
  5633. x++;
  5634. ast_cli(fd, "%d. %s\n", x, hist->event);
  5635. hist = hist->next;
  5636. }
  5637. if (!x)
  5638. ast_cli(fd, "Call '%s' has no history\n", cur->callid);
  5639. found++;
  5640. }
  5641. cur = cur->next;
  5642. }
  5643. ast_mutex_unlock(&iflock);
  5644. if (!found)
  5645. ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
  5646. return RESULT_SUCCESS;
  5647. }
  5648. /*--- receive_info: Receive SIP INFO Message ---*/
  5649. /* Doesn't read the duration of the DTMF signal */
  5650. static void receive_info(struct sip_pvt *p, struct sip_request *req)
  5651. {
  5652. char buf[1024] = "";
  5653. unsigned int event;
  5654. char resp = 0;
  5655. struct ast_frame f;
  5656. char *c;
  5657. /* Need to check the media/type */
  5658. if ( (!strcasecmp(get_header(req, "Content-Type"), "application/vnd.nortelnetworks.digits")) ||
  5659. (!strcasecmp(get_header(req, "Content-Type"), "application/dtmf-relay")) ) {
  5660. /* Try getting the "signal=" part */
  5661. if (ast_strlen_zero(c = get_sdp(req, "Signal")) && ast_strlen_zero(c = get_sdp(req, "d"))) {
  5662. ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
  5663. transmit_response(p, "200 OK", req); /* Should return error */
  5664. return;
  5665. } else {
  5666. strncpy(buf, c, sizeof(buf) - 1);
  5667. }
  5668. if (p->owner) { /* PBX call */
  5669. if (!ast_strlen_zero(buf)) {
  5670. if (sipdebug)
  5671. ast_verbose("* DTMF received: '%c'\n", buf[0]);
  5672. if (buf[0] == '*')
  5673. event = 10;
  5674. else if (buf[0] == '#')
  5675. event = 11;
  5676. else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
  5677. event = 12 + buf[0] - 'A';
  5678. else
  5679. event = atoi(buf);
  5680. if (event < 10) {
  5681. resp = '0' + event;
  5682. } else if (event < 11) {
  5683. resp = '*';
  5684. } else if (event < 12) {
  5685. resp = '#';
  5686. } else if (event < 16) {
  5687. resp = 'A' + (event - 12);
  5688. }
  5689. /* Build DTMF frame and deliver to PBX for transmission to other call leg*/
  5690. memset(&f, 0, sizeof(f));
  5691. f.frametype = AST_FRAME_DTMF;
  5692. f.subclass = resp;
  5693. f.offset = 0;
  5694. f.data = NULL;
  5695. f.datalen = 0;
  5696. ast_queue_frame(p->owner, &f);
  5697. }
  5698. transmit_response(p, "200 OK", req);
  5699. return;
  5700. } else {
  5701. transmit_response(p, "481 Call leg/transaction does not exist", req);
  5702. p->needdestroy = 1;
  5703. }
  5704. return;
  5705. }
  5706. /* Other type of INFO message, not really understood by Asterisk */
  5707. /* if (get_msg_text(buf, sizeof(buf), req)) { */
  5708. ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
  5709. transmit_response(p, "415 Unsupported media type", req);
  5710. return;
  5711. }
  5712. /*--- sip_do_debug: Enable SIP Debugging in CLI ---*/
  5713. static int sip_do_debug_ip(int fd, int argc, char *argv[])
  5714. {
  5715. struct hostent *hp;
  5716. struct ast_hostent ahp;
  5717. char iabuf[INET_ADDRSTRLEN];
  5718. int port = 0;
  5719. char *p, *arg;
  5720. if (argc != 4)
  5721. return RESULT_SHOWUSAGE;
  5722. arg = argv[3];
  5723. p = strstr(arg, ":");
  5724. if (p) {
  5725. *p = '\0';
  5726. p++;
  5727. port = atoi(p);
  5728. }
  5729. hp = ast_gethostbyname(arg, &ahp);
  5730. if (hp == NULL) {
  5731. return RESULT_SHOWUSAGE;
  5732. }
  5733. debugaddr.sin_family = AF_INET;
  5734. memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
  5735. debugaddr.sin_port = htons(port);
  5736. if (port == 0)
  5737. ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr));
  5738. else
  5739. ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr), port);
  5740. sipdebug = 1;
  5741. return RESULT_SUCCESS;
  5742. }
  5743. static int sip_do_debug_peer(int fd, int argc, char *argv[])
  5744. {
  5745. struct sip_peer *peer;
  5746. char iabuf[INET_ADDRSTRLEN];
  5747. if (argc != 4)
  5748. return RESULT_SHOWUSAGE;
  5749. ast_mutex_lock(&peerl.lock);
  5750. for (peer = peerl.peers;peer;peer = peer->next)
  5751. if (!strcmp(peer->name, argv[3]))
  5752. break;
  5753. ast_mutex_unlock(&peerl.lock);
  5754. #ifdef MYSQL_FRIENDS
  5755. if (!peer)
  5756. peer = mysql_peer(argv[3], NULL);
  5757. #endif
  5758. if (peer) {
  5759. if (peer->addr.sin_addr.s_addr) {
  5760. debugaddr.sin_family = AF_INET;
  5761. memcpy(&debugaddr.sin_addr, &peer->addr.sin_addr, sizeof(debugaddr.sin_addr));
  5762. debugaddr.sin_port = peer->addr.sin_port;
  5763. ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), debugaddr.sin_addr), ntohs(debugaddr.sin_port));
  5764. sipdebug = 1;
  5765. } else
  5766. ast_cli(fd, "Unable to get IP address of peer '%s'\n", argv[3]);
  5767. if (peer->temponly)
  5768. free(peer);
  5769. peer = NULL;
  5770. } else
  5771. ast_cli(fd, "No such peer '%s'\n", argv[3]);
  5772. return RESULT_SUCCESS;
  5773. }
  5774. static int sip_do_debug(int fd, int argc, char *argv[])
  5775. {
  5776. if (argc != 2) {
  5777. if (argc != 4)
  5778. return RESULT_SHOWUSAGE;
  5779. else if (strncmp(argv[2], "ip\0", 3) == 0)
  5780. return sip_do_debug_ip(fd, argc, argv);
  5781. else if (strncmp(argv[2], "peer\0", 5) == 0)
  5782. return sip_do_debug_peer(fd, argc, argv);
  5783. else return RESULT_SHOWUSAGE;
  5784. }
  5785. sipdebug = 1;
  5786. memset(&debugaddr, 0, sizeof(debugaddr));
  5787. ast_cli(fd, "SIP Debugging Enabled\n");
  5788. return RESULT_SUCCESS;
  5789. }
  5790. static int sip_do_history(int fd, int argc, char *argv[])
  5791. {
  5792. if (argc != 2) {
  5793. return RESULT_SHOWUSAGE;
  5794. }
  5795. recordhistory = 1;
  5796. ast_cli(fd, "SIP History Recording Enabled (use 'sip show history')\n");
  5797. return RESULT_SUCCESS;
  5798. }
  5799. static int sip_no_history(int fd, int argc, char *argv[])
  5800. {
  5801. if (argc != 3) {
  5802. return RESULT_SHOWUSAGE;
  5803. }
  5804. recordhistory = 0;
  5805. ast_cli(fd, "SIP History Recording Disabled\n");
  5806. return RESULT_SUCCESS;
  5807. }
  5808. /*--- sip_no_debug: Disable SIP Debugging in CLI ---*/
  5809. static int sip_no_debug(int fd, int argc, char *argv[])
  5810. {
  5811. if (argc != 3)
  5812. return RESULT_SHOWUSAGE;
  5813. sipdebug = 0;
  5814. ast_cli(fd, "SIP Debugging Disabled\n");
  5815. return RESULT_SUCCESS;
  5816. }
  5817. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *digest, int digest_len);
  5818. /*--- do_register_auth: Authenticate for outbound registration ---*/
  5819. static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader) {
  5820. char digest[1024];
  5821. p->authtries++;
  5822. memset(digest,0,sizeof(digest));
  5823. if (reply_digest(p, req, header, "REGISTER", digest, sizeof(digest))) {
  5824. /* There's nothing to use for authentication */
  5825. /* No digest challenge in request */
  5826. if (sip_debug_test_pvt(p))
  5827. ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
  5828. /* No old challenge */
  5829. return -1;
  5830. }
  5831. if (sip_debug_test_pvt(p))
  5832. ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
  5833. return transmit_register(p->registry,"REGISTER",digest, respheader);
  5834. }
  5835. /*--- do_proxy_auth: Add authentication on outbound SIP packet ---*/
  5836. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init) {
  5837. char digest[1024];
  5838. p->authtries++;
  5839. memset(digest,0,sizeof(digest));
  5840. if (reply_digest(p, req, header, msg, digest, sizeof(digest) )) {
  5841. /* No way to authenticate */
  5842. return -1;
  5843. }
  5844. /* Now we have a reply digest */
  5845. return transmit_invite(p,msg,!strcasecmp(msg, "INVITE"),digest, respheader, NULL,NULL,NULL, init);
  5846. }
  5847. /*--- reply_digest: reply to authentication for outbound registrations ---*/
  5848. /* This is used for register= servers in sip.conf, SIP proxies we register
  5849. with for receiving calls from. */
  5850. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
  5851. char tmp[512] = "";
  5852. char *realm = "";
  5853. char *nonce = "";
  5854. char *domain = "";
  5855. char *opaque = "";
  5856. char *qop = "";
  5857. char *c;
  5858. strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
  5859. if (ast_strlen_zero(tmp))
  5860. return -1;
  5861. c = tmp;
  5862. c+=strlen("Digest ");
  5863. while (c) {
  5864. while (*c && (*c < 33)) c++;
  5865. if (!*c)
  5866. break;
  5867. if (!strncasecmp(c,"realm=", strlen("realm="))) {
  5868. c+=strlen("realm=");
  5869. if ((*c == '\"')) {
  5870. realm=++c;
  5871. if ((c = strchr(c,'\"')))
  5872. *c = '\0';
  5873. } else {
  5874. realm = c;
  5875. if ((c = strchr(c,',')))
  5876. *c = '\0';
  5877. }
  5878. } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
  5879. c+=strlen("nonce=");
  5880. if ((*c == '\"')) {
  5881. nonce=++c;
  5882. if ((c = strchr(c,'\"')))
  5883. *c = '\0';
  5884. } else {
  5885. nonce = c;
  5886. if ((c = strchr(c,',')))
  5887. *c = '\0';
  5888. }
  5889. } else if (!strncasecmp(c, "opaque=", strlen("opaque="))) {
  5890. c+=strlen("opaque=");
  5891. if ((*c == '\"')) {
  5892. opaque=++c;
  5893. if ((c = strchr(c,'\"')))
  5894. *c = '\0';
  5895. } else {
  5896. opaque = c;
  5897. if ((c = strchr(c,',')))
  5898. *c = '\0';
  5899. }
  5900. } else if (!strncasecmp(c, "qop=", strlen("qop="))) {
  5901. c+=strlen("qop=");
  5902. if ((*c == '\"')) {
  5903. qop=++c;
  5904. if ((c = strchr(c,'\"')))
  5905. *c = '\0';
  5906. } else {
  5907. qop = c;
  5908. if ((c = strchr(c,',')))
  5909. *c = '\0';
  5910. }
  5911. } else if (!strncasecmp(c, "domain=", strlen("domain="))) {
  5912. c+=strlen("domain=");
  5913. if ((*c == '\"')) {
  5914. domain=++c;
  5915. if ((c = strchr(c,'\"')))
  5916. *c = '\0';
  5917. } else {
  5918. domain = c;
  5919. if ((c = strchr(c,',')))
  5920. *c = '\0';
  5921. }
  5922. } else
  5923. c = strchr(c,',');
  5924. if (c)
  5925. c++;
  5926. }
  5927. if (strlen(tmp) >= sizeof(tmp))
  5928. ast_log(LOG_WARNING, "Buffer overflow detected! Please file a bug.\n");
  5929. /* copy realm and nonce for later authorization of CANCELs and BYEs */
  5930. strncpy(p->realm, realm, sizeof(p->realm)-1);
  5931. strncpy(p->nonce, nonce, sizeof(p->nonce)-1);
  5932. strncpy(p->domain, domain, sizeof(p->domain)-1);
  5933. strncpy(p->opaque, opaque, sizeof(p->opaque)-1);
  5934. strncpy(p->qop, qop, sizeof(p->qop)-1);
  5935. /* Save auth data for following registrations */
  5936. if (p->registry) {
  5937. struct sip_registry *r = p->registry;
  5938. strncpy(r->realm, p->realm, sizeof(r->realm)-1);
  5939. strncpy(r->nonce, p->nonce, sizeof(r->nonce)-1);
  5940. strncpy(r->domain, p->domain, sizeof(r->domain)-1);
  5941. strncpy(r->opaque, p->opaque, sizeof(r->opaque)-1);
  5942. strncpy(r->qop, p->qop, sizeof(r->qop)-1);
  5943. }
  5944. build_reply_digest(p, orig_header, digest, digest_len);
  5945. return 0;
  5946. }
  5947. /*--- build_reply_digest: Build reply digest ---*/
  5948. /* Build digest challenge for authentication of peers (for registration)
  5949. and users (for calls). Also used for authentication of CANCEL and BYE */
  5950. static int build_reply_digest(struct sip_pvt *p, char* orig_header, char* digest, int digest_len)
  5951. {
  5952. char a1[256];
  5953. char a2[256];
  5954. char a1_hash[256];
  5955. char a2_hash[256];
  5956. char resp[256];
  5957. char resp_hash[256];
  5958. char uri[256] = "";
  5959. char cnonce[80];
  5960. char iabuf[INET_ADDRSTRLEN];
  5961. if (!ast_strlen_zero(p->domain))
  5962. strncpy(uri, p->domain, sizeof(uri) - 1);
  5963. else if (!ast_strlen_zero(p->uri))
  5964. strncpy(uri, p->uri, sizeof(uri) - 1);
  5965. else
  5966. snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
  5967. snprintf(cnonce, sizeof(cnonce), "%08x", rand());
  5968. snprintf(a1,sizeof(a1),"%s:%s:%s",p->authname,p->realm,p->peersecret);
  5969. snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
  5970. if (!ast_strlen_zero(p->peermd5secret))
  5971. strncpy(a1_hash, p->peermd5secret, sizeof(a1_hash) - 1);
  5972. else
  5973. md5_hash(a1_hash,a1);
  5974. md5_hash(a2_hash,a2);
  5975. /* XXX We hard code the nonce-number to 1... What are the odds? Are we seriously going to keep
  5976. track of every nonce we've seen? Also we hard code to "auth"... XXX */
  5977. if (!ast_strlen_zero(p->qop))
  5978. snprintf(resp,sizeof(resp),"%s:%s:%s:%s:%s:%s",a1_hash,p->nonce, "00000001", cnonce, "auth", a2_hash);
  5979. else
  5980. snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,p->nonce,a2_hash);
  5981. md5_hash(resp_hash,resp);
  5982. /* XXX We hard code our qop to "auth" for now. XXX */
  5983. if (!ast_strlen_zero(p->qop))
  5984. snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\", qop=\"%s\", cnonce=\"%s\", nc=%s",p->authname,p->realm,uri,p->nonce,resp_hash, p->opaque, "auth", cnonce, "00000001");
  5985. else
  5986. snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"",p->authname,p->realm,uri,p->nonce,resp_hash, p->opaque);
  5987. return 0;
  5988. }
  5989. static char show_users_usage[] =
  5990. "Usage: sip show users\n"
  5991. " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
  5992. static char show_inuse_usage[] =
  5993. "Usage: sip show inuse\n"
  5994. " List all users known to the SIP (Session Initiation Protocol) subsystem usage counters and limits.\n";
  5995. static char show_channels_usage[] =
  5996. "Usage: sip show channels\n"
  5997. " Lists all currently active SIP channels.\n";
  5998. static char show_channel_usage[] =
  5999. "Usage: sip show channel <channel>\n"
  6000. " Provides detailed status on a given SIP channel.\n";
  6001. static char show_history_usage[] =
  6002. "Usage: sip show history <channel>\n"
  6003. " Provides detailed dialog history on a given SIP channel.\n";
  6004. static char show_peers_usage[] =
  6005. "Usage: sip show peers\n"
  6006. " Lists all known SIP peers.\n";
  6007. static char show_peer_usage[] =
  6008. "Usage: sip show peer <peername>\n"
  6009. " Lists all details on one SIP peer and the current status.\n";
  6010. static char show_reg_usage[] =
  6011. "Usage: sip show registry\n"
  6012. " Lists all registration requests and status.\n";
  6013. static char debug_usage[] =
  6014. "Usage: sip debug\n"
  6015. " Enables dumping of SIP packets for debugging purposes\n\n"
  6016. " sip debug ip <host[:PORT]>\n"
  6017. " Enables dumping of SIP packets to and from host.\n\n"
  6018. " sip debug peer <peername>\n"
  6019. " Enables dumping of SIP packets to and from host.\n"
  6020. " Require peer to be registered.\n";
  6021. static char no_debug_usage[] =
  6022. "Usage: sip no debug\n"
  6023. " Disables dumping of SIP packets for debugging purposes\n";
  6024. static char no_history_usage[] =
  6025. "Usage: sip no history\n"
  6026. " Disables recording of SIP dialog history for debugging purposes\n";
  6027. static char history_usage[] =
  6028. "Usage: sip history\n"
  6029. " Enables recording of SIP dialog history for debugging purposes.\n"
  6030. "Use 'sip show history' to view the history of a call number.\n";
  6031. static char sip_reload_usage[] =
  6032. "Usage: sip reload\n"
  6033. " Reloads SIP configuration from sip.conf\n";
  6034. static char show_subscriptions_usage[] =
  6035. "Usage: sip show subscriptions\n"
  6036. " Shows active SIP subscriptions for extension states\n";
  6037. static struct ast_cli_entry cli_show_users =
  6038. { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
  6039. static struct ast_cli_entry cli_show_subscriptions =
  6040. { { "sip", "show", "subscriptions", NULL }, sip_show_subscriptions, "Show active SIP subscriptions", show_subscriptions_usage};
  6041. static struct ast_cli_entry cli_show_channels =
  6042. { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
  6043. static struct ast_cli_entry cli_show_channel =
  6044. { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch };
  6045. static struct ast_cli_entry cli_show_history =
  6046. { { "sip", "show", "history", NULL }, sip_show_history, "Show SIP dialog history", show_history_usage, complete_sipch };
  6047. static struct ast_cli_entry cli_debug_ip =
  6048. { { "sip", "debug", "ip", NULL }, sip_do_debug, "Enable SIP debugging on IP", debug_usage };
  6049. static struct ast_cli_entry cli_debug_peer =
  6050. { { "sip", "debug", "peer", NULL }, sip_do_debug, "Enable SIP debugging on Peername", debug_usage };
  6051. static struct ast_cli_entry cli_show_peer =
  6052. { { "sip", "show", "peer", NULL }, sip_show_peer, "Show details on specific SIP peer", show_peer_usage };
  6053. static struct ast_cli_entry cli_show_peers =
  6054. { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
  6055. static struct ast_cli_entry cli_show_peers_include =
  6056. { { "sip", "show", "peers", "include", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
  6057. static struct ast_cli_entry cli_show_peers_exclude =
  6058. { { "sip", "show", "peers", "exclude", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
  6059. static struct ast_cli_entry cli_show_peers_begin =
  6060. { { "sip", "show", "peers", "begin", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
  6061. static struct ast_cli_entry cli_inuse_show =
  6062. { { "sip", "show", "inuse", NULL }, sip_show_inuse, "List all inuse/limit", show_inuse_usage };
  6063. static struct ast_cli_entry cli_show_registry =
  6064. { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
  6065. static struct ast_cli_entry cli_debug =
  6066. { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
  6067. static struct ast_cli_entry cli_history =
  6068. { { "sip", "history", NULL }, sip_do_history, "Enable SIP history", history_usage };
  6069. static struct ast_cli_entry cli_no_history =
  6070. { { "sip", "no", "history", NULL }, sip_no_history, "Disable SIP history", no_history_usage };
  6071. static struct ast_cli_entry cli_no_debug =
  6072. { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
  6073. /*--- parse_moved_contact: Parse 302 Moved temporalily response */
  6074. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
  6075. {
  6076. char tmp[256] = "";
  6077. char *s, *e;
  6078. strncpy(tmp, get_header(req, "Contact"), sizeof(tmp) - 1);
  6079. s = ditch_braces(tmp);
  6080. e = strchr(s, ';');
  6081. if (e)
  6082. *e = '\0';
  6083. if (p->promiscredir) {
  6084. if (!strncasecmp(s, "sip:", 4))
  6085. s += 4;
  6086. e = strchr(s, '/');
  6087. if (e)
  6088. *e = '\0';
  6089. ast_log(LOG_DEBUG, "Found promiscuous redirection to 'SIP/%s'\n", s);
  6090. if (p->owner)
  6091. snprintf(p->owner->call_forward, sizeof(p->owner->call_forward), "SIP/%s", s);
  6092. } else {
  6093. e = strchr(tmp, '@');
  6094. if (e)
  6095. *e = '\0';
  6096. e = strchr(tmp, '/');
  6097. if (e)
  6098. *e = '\0';
  6099. if (!strncasecmp(s, "sip:", 4))
  6100. s += 4;
  6101. ast_log(LOG_DEBUG, "Found 302 Redirect to extension '%s'\n", s);
  6102. if (p->owner)
  6103. strncpy(p->owner->call_forward, s, sizeof(p->owner->call_forward) - 1);
  6104. }
  6105. }
  6106. /*--- check_pendings: Check pending actions on SIP call ---*/
  6107. static void check_pendings(struct sip_pvt *p)
  6108. {
  6109. /* Go ahead and send bye at this point */
  6110. if (p->pendingbye) {
  6111. transmit_request_with_auth(p, "BYE", 0, 1, 1);
  6112. p->needdestroy = 1;
  6113. p->needreinvite = 0;
  6114. } else if (p->needreinvite) {
  6115. ast_log(LOG_DEBUG, "Sending pending reinvite on '%s'\n", p->callid);
  6116. /* Didn't get to reinvite yet, so do it now */
  6117. transmit_reinvite_with_sdp(p);
  6118. p->needreinvite = 0;
  6119. }
  6120. }
  6121. /*--- handle_response: Handle SIP response in dialogue ---*/
  6122. static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore)
  6123. {
  6124. char *to;
  6125. char *msg, *c;
  6126. struct ast_channel *owner;
  6127. struct sip_peer *peer;
  6128. int pingtime;
  6129. struct timeval tv;
  6130. int seqno=0;
  6131. char iabuf[INET_ADDRSTRLEN];
  6132. c = get_header(req, "Cseq");
  6133. if (sscanf(c, "%d ", &seqno) != 1) {
  6134. ast_log(LOG_WARNING, "Unable to determine sequence number\n");
  6135. }
  6136. msg = strchr(c, ' ');
  6137. if (!msg) msg = ""; else msg++;
  6138. owner = p->owner;
  6139. if (owner)
  6140. owner->hangupcause = hangup_sip2cause(resp);
  6141. /* Acknowledge whatever it is destined for */
  6142. if ((resp >= 100) && (resp <= 199))
  6143. __sip_semi_ack(p, seqno, 0, msg);
  6144. else
  6145. __sip_ack(p, seqno, 0, msg);
  6146. /* Get their tag if we haven't already */
  6147. to = get_header(req, "To");
  6148. to = ast_strcasestr(to, "tag=");
  6149. if (to) {
  6150. to += 4;
  6151. strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
  6152. to = strchr(p->theirtag, ';');
  6153. if (to)
  6154. *to = '\0';
  6155. }
  6156. if (p->peerpoke) {
  6157. /* We don't really care what the response is, just that it replied back.
  6158. Well, as long as it's not a 100 response... since we might
  6159. need to hang around for something more "difinitive" */
  6160. if (resp != 100) {
  6161. int statechanged = 0;
  6162. int newstate = 0;
  6163. peer = p->peerpoke;
  6164. gettimeofday(&tv, NULL);
  6165. pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
  6166. (tv.tv_usec - peer->ps.tv_usec) / 1000;
  6167. if (pingtime < 1)
  6168. pingtime = 1;
  6169. if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
  6170. if (pingtime <= peer->maxms) {
  6171. ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
  6172. statechanged = 1;
  6173. newstate = 1;
  6174. }
  6175. } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
  6176. if (pingtime > peer->maxms) {
  6177. ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
  6178. statechanged = 1;
  6179. newstate = 2;
  6180. }
  6181. }
  6182. if (!peer->lastms)
  6183. statechanged = 1;
  6184. peer->lastms = pingtime;
  6185. peer->call = NULL;
  6186. if (statechanged) {
  6187. ast_device_state_changed("SIP/%s", peer->name);
  6188. if (newstate == 2) {
  6189. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, pingtime);
  6190. } else {
  6191. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, pingtime);
  6192. }
  6193. }
  6194. if (peer->pokeexpire > -1)
  6195. ast_sched_del(sched, peer->pokeexpire);
  6196. if (!strcasecmp(msg, "INVITE"))
  6197. transmit_request(p, "ACK", seqno, 0, 0);
  6198. p->needdestroy = 1;
  6199. /* Try again eventually */
  6200. if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
  6201. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
  6202. else
  6203. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
  6204. }
  6205. } else if (p->outgoing) {
  6206. /* Acknowledge sequence number */
  6207. if (p->initid > -1) {
  6208. /* Don't auto congest anymore since we've gotten something useful back */
  6209. ast_sched_del(sched, p->initid);
  6210. p->initid = -1;
  6211. }
  6212. switch(resp) {
  6213. case 100:
  6214. if (!strcasecmp(msg, "INVITE")) {
  6215. sip_cancel_destroy(p);
  6216. }
  6217. break;
  6218. case 183:
  6219. if (!strcasecmp(msg, "INVITE")) {
  6220. sip_cancel_destroy(p);
  6221. if (!ast_strlen_zero(get_header(req, "Content-Type")))
  6222. process_sdp(p, req);
  6223. if (p->owner) {
  6224. /* Queue a progress frame */
  6225. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  6226. }
  6227. }
  6228. break;
  6229. case 180:
  6230. if (!strcasecmp(msg, "INVITE")) {
  6231. sip_cancel_destroy(p);
  6232. if (p->owner) {
  6233. ast_queue_control(p->owner, AST_CONTROL_RINGING);
  6234. if (p->owner->_state != AST_STATE_UP)
  6235. ast_setstate(p->owner, AST_STATE_RINGING);
  6236. }
  6237. }
  6238. break;
  6239. case 200:
  6240. if (!strcasecmp(msg, "NOTIFY")) {
  6241. /* They got the notify, this is the end */
  6242. if (p->owner) {
  6243. ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
  6244. ast_queue_hangup(p->owner);
  6245. } else {
  6246. if (!p->subscribed) {
  6247. p->needdestroy = 1;
  6248. }
  6249. }
  6250. } else if (!strcasecmp(msg, "INVITE")) {
  6251. sip_cancel_destroy(p);
  6252. if (!ast_strlen_zero(get_header(req, "Content-Type")))
  6253. process_sdp(p, req);
  6254. /* Save Record-Route for any later requests we make on this dialogue */
  6255. build_route(p, req, 1);
  6256. if (p->owner) {
  6257. if (p->owner->_state != AST_STATE_UP) {
  6258. #ifdef OSP_SUPPORT
  6259. time(&p->ospstart);
  6260. #endif
  6261. ast_queue_control(p->owner, AST_CONTROL_ANSWER);
  6262. } else {
  6263. struct ast_frame af = { AST_FRAME_NULL, };
  6264. ast_queue_frame(p->owner, &af);
  6265. }
  6266. } else /* It's possible we're getting an ACK after we've tried to disconnect
  6267. by sending CANCEL */
  6268. p->pendingbye = 1;
  6269. p->authtries = 0;
  6270. /* If I understand this right, the branch is different for a non-200 ACK only */
  6271. transmit_request(p, "ACK", seqno, 0, 1);
  6272. check_pendings(p);
  6273. } else if (!strcasecmp(msg, "REGISTER")) {
  6274. /* char *exp; */
  6275. int expires, expires_ms;
  6276. struct sip_registry *r;
  6277. r=p->registry;
  6278. if (r) {
  6279. r->regstate=REG_STATE_REGISTERED;
  6280. manager_event(EVENT_FLAG_SYSTEM, "Registry", "Channel: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
  6281. ast_log(LOG_DEBUG, "Registration successful\n");
  6282. if (r->timeout > -1) {
  6283. ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
  6284. ast_sched_del(sched, r->timeout);
  6285. }
  6286. r->timeout=-1;
  6287. r->call = NULL;
  6288. p->registry = NULL;
  6289. p->needdestroy = 1;
  6290. /* set us up for re-registering */
  6291. /* figure out how long we got registered for */
  6292. if (r->expire > -1)
  6293. ast_sched_del(sched, r->expire);
  6294. /* according to section 6.13 of RFC, contact headers override
  6295. expires headers, so check those first */
  6296. expires = 0;
  6297. if (!ast_strlen_zero(get_header(req, "Contact"))) {
  6298. char *contact = NULL;
  6299. char *tmptmp = NULL;
  6300. int start = 0;
  6301. for(;;) {
  6302. contact = __get_header(req, "Contact", &start);
  6303. /* this loop ensures we get a contact header about our register request */
  6304. if(!ast_strlen_zero(contact)) {
  6305. if( (tmptmp=strstr(contact, p->our_contact))) {
  6306. contact=tmptmp;
  6307. break;
  6308. }
  6309. } else
  6310. break;
  6311. }
  6312. tmptmp = strstr(contact, "expires=");
  6313. if (tmptmp) {
  6314. if (sscanf(tmptmp + 8, "%d;", &expires) != 1)
  6315. expires = 0;
  6316. }
  6317. }
  6318. if (!expires) expires=atoi(get_header(req, "expires"));
  6319. if (!expires) expires=default_expiry;
  6320. expires_ms = expires * 1000;
  6321. if (expires <= EXPIRY_GUARD_LIMIT)
  6322. expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT),EXPIRY_GUARD_MIN);
  6323. else
  6324. expires_ms -= EXPIRY_GUARD_SECS * 1000;
  6325. if (sipdebug)
  6326. ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d ms)\n", r->hostname, expires, expires_ms);
  6327. r->refresh= (int) expires_ms / 1000;
  6328. /* Schedule re-registration before we expire */
  6329. r->expire=ast_sched_add(sched, expires_ms, sip_reregister, r);
  6330. } else
  6331. ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
  6332. }
  6333. break;
  6334. case 401: /* Not www-authorized on REGISTER */
  6335. if (!strcasecmp(msg, "INVITE")) {
  6336. /* First we ACK */
  6337. transmit_request(p, "ACK", seqno, 0, 0);
  6338. /* Then we AUTH */
  6339. p->theirtag[0]='\0'; /* forget their old tag, so we don't match tags when getting response */
  6340. if ((p->authtries > 1) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", "INVITE", 1)) {
  6341. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
  6342. p->needdestroy = 1;
  6343. }
  6344. } else if (p->registry && !strcasecmp(msg, "REGISTER")) {
  6345. if ((p->authtries > 1) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
  6346. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s'\n", get_header(&p->initreq, "From"));
  6347. p->needdestroy = 1;
  6348. }
  6349. } else
  6350. p->needdestroy = 1;
  6351. break;
  6352. case 403: /* Forbidden - we failed authentication */
  6353. if (!strcasecmp(msg, "INVITE")) {
  6354. /* First we ACK */
  6355. transmit_request(p, "ACK", seqno, 0, 0);
  6356. ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for INVITE to '%s'\n", get_header(&p->initreq, "From"));
  6357. if (owner)
  6358. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  6359. p->needdestroy = 1;
  6360. } else if (p->registry && !strcasecmp(msg, "REGISTER")) {
  6361. ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
  6362. p->needdestroy = 1;
  6363. } else {
  6364. ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for %s\n", msg);
  6365. }
  6366. break;
  6367. case 407:
  6368. if (!strcasecmp(msg, "INVITE")) {
  6369. /* First we ACK */
  6370. transmit_request(p, "ACK", seqno, 0, 0);
  6371. /* Then we AUTH */
  6372. /* But only if the packet wasn't marked as ignore in handle_request */
  6373. if(!ignore){
  6374. p->theirtag[0]='\0'; /* forget their old tag, so we don't match tags when getting response */
  6375. if ((p->authtries > 1) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", "INVITE", 1)) {
  6376. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
  6377. p->needdestroy = 1;
  6378. }
  6379. }
  6380. } else if (!strcasecmp(msg, "BYE") || !strcasecmp(msg, "REFER")) {
  6381. if (ast_strlen_zero(p->authname))
  6382. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
  6383. msg, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
  6384. if ((p->authtries > 1) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", msg, 0)) {
  6385. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
  6386. p->needdestroy = 1;
  6387. }
  6388. } else if (p->registry && !strcasecmp(msg, "REGISTER")) {
  6389. if ((p->authtries > 1) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
  6390. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
  6391. p->needdestroy = 1;
  6392. }
  6393. } else
  6394. p->needdestroy = 1;
  6395. break;
  6396. case 501: /* Not Implemented */
  6397. if (!strcasecmp(msg, "INVITE")) {
  6398. if (p->owner)
  6399. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  6400. } else
  6401. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), msg);
  6402. break;
  6403. default:
  6404. if ((resp >= 300) && (resp < 700)) {
  6405. if ((option_verbose > 2) && (resp != 487))
  6406. ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
  6407. p->alreadygone = 1;
  6408. if (p->rtp) {
  6409. /* Immediately stop RTP */
  6410. ast_rtp_stop(p->rtp);
  6411. }
  6412. if (p->vrtp) {
  6413. /* Immediately stop VRTP */
  6414. ast_rtp_stop(p->vrtp);
  6415. }
  6416. /* XXX Locking issues?? XXX */
  6417. switch(resp) {
  6418. case 300: /* Multiple Choices */
  6419. case 301: /* Moved permenantly */
  6420. case 302: /* Moved temporarily */
  6421. case 305: /* Use Proxy */
  6422. parse_moved_contact(p, req);
  6423. if (p->owner)
  6424. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  6425. break;
  6426. case 487:
  6427. /* channel now destroyed - dec the inUse counter */
  6428. if ( p->outgoing ) {
  6429. update_user_counter(p, DEC_OUT_USE);
  6430. }
  6431. else {
  6432. update_user_counter(p, DEC_IN_USE);
  6433. }
  6434. break;
  6435. case 482: /* SIP is incapable of performing a hairpin call, which
  6436. is yet another failure of not having a layer 2 (again, YAY
  6437. IETF for thinking ahead). So we treat this as a call
  6438. forward and hope we end up at the right place... */
  6439. ast_log(LOG_DEBUG, "Hairpin detected, setting up call forward for what it's worth\n");
  6440. if (p->owner)
  6441. snprintf(p->owner->call_forward, sizeof(p->owner->call_forward), "Local/%s@%s", p->username, p->context);
  6442. /* Fall through */
  6443. case 486: /* Busy here */
  6444. case 600: /* Busy everywhere */
  6445. case 603: /* Decline */
  6446. if (p->owner)
  6447. ast_queue_control(p->owner, AST_CONTROL_BUSY);
  6448. break;
  6449. case 480: /* Temporarily Unavailable */
  6450. case 404: /* Not Found */
  6451. case 410: /* Gone */
  6452. case 400: /* Bad Request */
  6453. case 500: /* Server error */
  6454. case 503: /* Service Unavailable */
  6455. if (owner)
  6456. ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
  6457. break;
  6458. default:
  6459. /* Send hangup */
  6460. if (owner)
  6461. ast_queue_hangup(p->owner);
  6462. break;
  6463. }
  6464. /* ACK on invite */
  6465. if (!strcasecmp(msg, "INVITE"))
  6466. transmit_request(p, "ACK", seqno, 0, 0);
  6467. p->alreadygone = 1;
  6468. if (!p->owner)
  6469. p->needdestroy = 1;
  6470. } else if ((resp >= 100) && (resp < 200)) {
  6471. if (!strcasecmp(msg, "INVITE")) {
  6472. sip_cancel_destroy(p);
  6473. if (!ast_strlen_zero(get_header(req, "Content-Type")))
  6474. process_sdp(p, req);
  6475. if (p->owner) {
  6476. /* Queue a progress frame */
  6477. ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
  6478. }
  6479. }
  6480. } else
  6481. ast_log(LOG_NOTICE, "Don't know anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
  6482. }
  6483. } else {
  6484. if (sip_debug_test_pvt(p))
  6485. ast_verbose("Message is %s\n", msg);
  6486. switch(resp) {
  6487. case 200:
  6488. /* Change branch since this is a 200 response */
  6489. if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
  6490. transmit_request(p, "ACK", seqno, 0, 1);
  6491. break;
  6492. case 407:
  6493. if (!strcasecmp(msg, "BYE") || !strcasecmp(msg, "REFER")) {
  6494. if (ast_strlen_zero(p->authname))
  6495. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
  6496. msg, ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port));
  6497. if ((p->authtries > 1) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", msg, 0)) {
  6498. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
  6499. p->needdestroy = 1;
  6500. }
  6501. }
  6502. break;
  6503. }
  6504. }
  6505. }
  6506. struct sip_dual {
  6507. struct ast_channel *chan1;
  6508. struct ast_channel *chan2;
  6509. struct sip_request req;
  6510. };
  6511. static void *sip_park_thread(void *stuff)
  6512. {
  6513. struct ast_channel *chan1, *chan2;
  6514. struct sip_dual *d;
  6515. struct sip_request req;
  6516. int ext;
  6517. int res;
  6518. d = stuff;
  6519. chan1 = d->chan1;
  6520. chan2 = d->chan2;
  6521. copy_request(&req, &d->req);
  6522. free(d);
  6523. ast_mutex_lock(&chan1->lock);
  6524. ast_do_masquerade(chan1);
  6525. ast_mutex_unlock(&chan1->lock);
  6526. res = ast_park_call(chan1, chan2, 0, &ext);
  6527. /* Then hangup */
  6528. ast_hangup(chan2);
  6529. ast_log(LOG_DEBUG, "Parked on extension '%d'\n", ext);
  6530. return NULL;
  6531. }
  6532. static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req)
  6533. {
  6534. struct sip_dual *d;
  6535. struct ast_channel *chan1m, *chan2m;
  6536. pthread_t th;
  6537. chan1m = ast_channel_alloc(0);
  6538. chan2m = ast_channel_alloc(0);
  6539. if (chan2m && chan1m) {
  6540. snprintf(chan1m->name, sizeof(chan1m->name), "Parking/%s", chan1->name);
  6541. /* Make formats okay */
  6542. chan1m->readformat = chan1->readformat;
  6543. chan1m->writeformat = chan1->writeformat;
  6544. ast_channel_masquerade(chan1m, chan1);
  6545. /* Setup the extensions and such */
  6546. strncpy(chan1m->context, chan1->context, sizeof(chan1m->context) - 1);
  6547. strncpy(chan1m->exten, chan1->exten, sizeof(chan1m->exten) - 1);
  6548. chan1m->priority = chan1->priority;
  6549. /* We make a clone of the peer channel too, so we can play
  6550. back the announcement */
  6551. snprintf(chan2m->name, sizeof (chan2m->name), "SIPPeer/%s",chan2->name);
  6552. /* Make formats okay */
  6553. chan2m->readformat = chan2->readformat;
  6554. chan2m->writeformat = chan2->writeformat;
  6555. ast_channel_masquerade(chan2m, chan2);
  6556. /* Setup the extensions and such */
  6557. strncpy(chan2m->context, chan2->context, sizeof(chan2m->context) - 1);
  6558. strncpy(chan2m->exten, chan2->exten, sizeof(chan2m->exten) - 1);
  6559. chan2m->priority = chan2->priority;
  6560. ast_mutex_lock(&chan2m->lock);
  6561. if (ast_do_masquerade(chan2m)) {
  6562. ast_log(LOG_WARNING, "Masquerade failed :(\n");
  6563. ast_mutex_unlock(&chan2m->lock);
  6564. ast_hangup(chan2m);
  6565. return -1;
  6566. }
  6567. ast_mutex_unlock(&chan2m->lock);
  6568. } else {
  6569. if (chan1m)
  6570. ast_hangup(chan1m);
  6571. if (chan2m)
  6572. ast_hangup(chan2m);
  6573. return -1;
  6574. }
  6575. d = malloc(sizeof(struct sip_dual));
  6576. if (d) {
  6577. memset(d, 0, sizeof(*d));
  6578. /* Save original request for followup */
  6579. copy_request(&d->req, req);
  6580. d->chan1 = chan1m;
  6581. d->chan2 = chan2m;
  6582. if (!ast_pthread_create(&th, NULL, sip_park_thread, d))
  6583. return 0;
  6584. free(d);
  6585. }
  6586. return -1;
  6587. }
  6588. static void ast_quiet_chan(struct ast_channel *chan) {
  6589. if(chan && chan->_state == AST_STATE_UP) {
  6590. if(chan->generatordata)
  6591. ast_deactivate_generator(chan);
  6592. }
  6593. }
  6594. /*--- attempt_transfer: Attempt transfer of SIP call ---*/
  6595. static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
  6596. {
  6597. int res = 0;
  6598. struct ast_channel
  6599. *chana = NULL,
  6600. *chanb = NULL,
  6601. *bridgea = NULL,
  6602. *bridgeb = NULL,
  6603. *peera = NULL,
  6604. *peerb = NULL,
  6605. *peerc = NULL,
  6606. *peerd = NULL;
  6607. if (!p1->owner || !p2->owner) {
  6608. ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
  6609. return -1;
  6610. }
  6611. chana = p1->owner;
  6612. chanb = p2->owner;
  6613. bridgea = p1->owner->bridge;
  6614. bridgeb = p2->owner->bridge;
  6615. if (bridgea) {
  6616. peera = chana;
  6617. peerb = chanb;
  6618. peerc = bridgea;
  6619. peerd = bridgeb;
  6620. } else if(bridgeb) {
  6621. peera = chanb;
  6622. peerb = chana;
  6623. peerc = bridgeb;
  6624. peerd = bridgea;
  6625. }
  6626. if(peera && peerb && peerc && (peerb != peerc)) {
  6627. ast_quiet_chan(peera);
  6628. ast_quiet_chan(peerb);
  6629. ast_quiet_chan(peerc);
  6630. ast_quiet_chan(peerd);
  6631. if (peera->cdr && peerb->cdr) {
  6632. peerb->cdr = ast_cdr_append(peerb->cdr, peera->cdr);
  6633. } else if(peera->cdr) {
  6634. peerb->cdr = peera->cdr;
  6635. }
  6636. peera->cdr = NULL;
  6637. if (peerb->cdr && peerc->cdr) {
  6638. peerb->cdr = ast_cdr_append(peerb->cdr, peerc->cdr);
  6639. } else if(peerc->cdr) {
  6640. peerb->cdr = peerc->cdr;
  6641. }
  6642. peerc->cdr = NULL;
  6643. if (ast_channel_masquerade(peerb, peerc)) {
  6644. ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
  6645. res = -1;
  6646. }
  6647. return res;
  6648. } else {
  6649. return -1;
  6650. }
  6651. return 0;
  6652. }
  6653. /*--- handle_request: Handle SIP requests (methods) ---*/
  6654. /* this is where all incoming requests go first */
  6655. static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
  6656. {
  6657. /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
  6658. relatively static */
  6659. struct sip_request resp;
  6660. char *cmd;
  6661. char *cseq;
  6662. char *from;
  6663. char *e;
  6664. char *useragent;
  6665. struct ast_channel *c=NULL;
  6666. struct ast_channel *transfer_to;
  6667. int seqno;
  6668. int len;
  6669. int ignore=0;
  6670. int respid;
  6671. int res;
  6672. int gotdest;
  6673. char iabuf[INET_ADDRSTRLEN];
  6674. struct ast_frame af = { AST_FRAME_NULL, };
  6675. int debug = sip_debug_test_pvt(p);
  6676. /* Clear out potential response */
  6677. memset(&resp, 0, sizeof(resp));
  6678. /* Get Method and Cseq */
  6679. cseq = get_header(req, "Cseq");
  6680. cmd = req->header[0];
  6681. /* Must have Cseq */
  6682. if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq))
  6683. return -1;
  6684. if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
  6685. ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
  6686. return -1;
  6687. }
  6688. /* Get the command */
  6689. cseq += len;
  6690. /* Determine the request URI for sip, sips or tel URIs */
  6691. if( determine_firstline_parts( req ) < 0 ) {
  6692. return -1;
  6693. }
  6694. cmd= req->rlPart1;
  6695. e= req->rlPart2;
  6696. /* Save useragent of the client */
  6697. useragent = get_header(req, "User-Agent");
  6698. strncpy(p->useragent, useragent, sizeof(p->useragent)-1);
  6699. if (strcasecmp(cmd, "SIP/2.0")) {
  6700. /* Request coming in */
  6701. if (p->icseq && (p->icseq > seqno)) {
  6702. ast_log(LOG_DEBUG, "Ignoring too old packet packet %d (expecting >= %d)\n", seqno, p->icseq);
  6703. return -1;
  6704. } else if (p->icseq && (p->icseq == seqno) && (strcasecmp(cmd, "CANCEL") || p->alreadygone)) {
  6705. /* ignore means "don't do anything with it" but still have to
  6706. respond appropriately. We do this if we receive a repeat of
  6707. the last sequence number */
  6708. ignore=1;
  6709. }
  6710. if (ast_strlen_zero(p->theirtag)) {
  6711. from = get_header(req, "From");
  6712. from = ast_strcasestr(from, "tag=");
  6713. if (from) {
  6714. from += 4;
  6715. strncpy(p->theirtag, from, sizeof(p->theirtag) - 1);
  6716. from = strchr(p->theirtag, ';');
  6717. if (from)
  6718. *from = '\0';
  6719. }
  6720. }
  6721. snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
  6722. } else {
  6723. /* Response to our request -- Do some sanity checks */
  6724. if (!p->initreq.headers) {
  6725. ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about.\n");
  6726. p->needdestroy = 1;
  6727. return 0;
  6728. } else if (p->ocseq && (p->ocseq < seqno)) {
  6729. ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
  6730. return -1;
  6731. } else if (p->ocseq && (p->ocseq != seqno)) {
  6732. /* ignore means "don't do anything with it" but still have to
  6733. respond appropriately */
  6734. ignore=1;
  6735. }
  6736. }
  6737. if (strcmp(cmd, "SIP/2.0") && (seqno >= p->icseq))
  6738. /* Next should follow monotonically (but not necessarily
  6739. incrementally -- thanks again to the genius authors of SIP --
  6740. increasing */
  6741. p->icseq = seqno;
  6742. /* Initialize the context if it hasn't been already */
  6743. if (!strcasecmp(cmd, "OPTIONS")) {
  6744. res = get_destination(p, req);
  6745. build_contact(p);
  6746. /* XXX Should we authenticate OPTIONS? XXX */
  6747. if (ast_strlen_zero(p->context))
  6748. strncpy(p->context, default_context, sizeof(p->context) - 1);
  6749. if (res < 0)
  6750. transmit_response_with_allow(p, "404 Not Found", req, 0);
  6751. else if (res > 0)
  6752. transmit_response_with_allow(p, "484 Address Incomplete", req, 0);
  6753. else
  6754. transmit_response_with_allow(p, "200 OK", req, 0);
  6755. /* Destroy if this OPTIONS was the opening request, but not if
  6756. it's in the middle of a normal call flow. */
  6757. if (!p->lastinvite)
  6758. p->needdestroy = 1;
  6759. } else if (!strcasecmp(cmd, "INVITE")) {
  6760. if (p->outgoing && p->owner && (p->owner->_state != AST_STATE_UP)) {
  6761. /* This is a call to ourself. Send ourselves an error code and stop
  6762. processing immediately, as SIP really has no good mechanism for
  6763. being able to call yourself */
  6764. transmit_response(p, "482 Loop Detected", req);
  6765. /* We do NOT destroy p here, so that our response will be accepted */
  6766. return 0;
  6767. }
  6768. if (!ignore) {
  6769. /* Use this as the basis */
  6770. if (debug)
  6771. ast_verbose("Using latest request as basis request\n");
  6772. sip_cancel_destroy(p);
  6773. /* This call is no longer outgoing if it ever was */
  6774. p->outgoing = 0;
  6775. /* This also counts as a pending invite */
  6776. p->pendinginvite = seqno;
  6777. copy_request(&p->initreq, req);
  6778. check_via(p, req);
  6779. if (p->owner) {
  6780. /* Handle SDP here if we already have an owner */
  6781. if (!ast_strlen_zero(get_header(req, "Content-Type"))) {
  6782. if (process_sdp(p, req)) {
  6783. transmit_response(p, "488 Not acceptable here", req);
  6784. p->needdestroy = 1;
  6785. return -1;
  6786. }
  6787. } else {
  6788. p->jointcapability = p->capability;
  6789. ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
  6790. }
  6791. }
  6792. } else if (debug)
  6793. ast_verbose("Ignoring this request\n");
  6794. if (!p->lastinvite && !ignore && !p->owner) {
  6795. /* Handle authentication if this is our first invite */
  6796. res = check_user(p, req, cmd, e, 1, sin, ignore);
  6797. if (res) {
  6798. if (res < 0) {
  6799. ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
  6800. if (ignore)
  6801. transmit_response(p, "403 Forbidden", req);
  6802. else
  6803. transmit_response_reliable(p, "403 Forbidden", req, 1);
  6804. p->needdestroy = 1;
  6805. }
  6806. return 0;
  6807. }
  6808. /* Process the SDP portion */
  6809. if (!ast_strlen_zero(get_header(req, "Content-Type"))) {
  6810. if (process_sdp(p, req)) {
  6811. transmit_response(p, "488 Not acceptable here", req);
  6812. p->needdestroy = 1;
  6813. return -1;
  6814. }
  6815. } else {
  6816. p->jointcapability = p->capability;
  6817. ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
  6818. }
  6819. /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
  6820. if (p->owner)
  6821. ast_queue_frame(p->owner, &af);
  6822. /* Initialize the context if it hasn't been already */
  6823. if (ast_strlen_zero(p->context))
  6824. strncpy(p->context, default_context, sizeof(p->context) - 1);
  6825. /* Check number of concurrent calls -vs- incoming limit HERE */
  6826. ast_log(LOG_DEBUG, "Check for res for %s\n", p->username);
  6827. res = update_user_counter(p,INC_IN_USE);
  6828. if (res) {
  6829. if (res < 0) {
  6830. ast_log(LOG_DEBUG, "Failed to place call for user %s, too many calls\n", p->username);
  6831. p->needdestroy = 1;
  6832. }
  6833. return 0;
  6834. }
  6835. /* Get destination right away */
  6836. gotdest = get_destination(p, NULL);
  6837. get_rdnis(p, NULL);
  6838. extract_uri(p, req);
  6839. build_contact(p);
  6840. if (gotdest) {
  6841. if (gotdest < 0) {
  6842. if (ignore)
  6843. transmit_response(p, "404 Not Found", req);
  6844. else
  6845. transmit_response_reliable(p, "404 Not Found", req, 1);
  6846. update_user_counter(p,DEC_IN_USE);
  6847. } else {
  6848. if (ignore)
  6849. transmit_response(p, "484 Address Incomplete", req);
  6850. else
  6851. transmit_response_reliable(p, "484 Address Incomplete", req, 1);
  6852. update_user_counter(p,DEC_IN_USE);
  6853. }
  6854. p->needdestroy = 1;
  6855. } else {
  6856. /* If no extension was specified, use the s one */
  6857. if (ast_strlen_zero(p->exten))
  6858. strncpy(p->exten, "s", sizeof(p->exten) - 1);
  6859. /* Initialize tag */
  6860. p->tag = rand();
  6861. /* First invitation */
  6862. c = sip_new(p, AST_STATE_DOWN, ast_strlen_zero(p->username) ? NULL : p->username );
  6863. *recount = 1;
  6864. /* Save Record-Route for any later requests we make on this dialogue */
  6865. build_route(p, req, 0);
  6866. if (c) {
  6867. /* Pre-lock the call */
  6868. ast_mutex_lock(&c->lock);
  6869. }
  6870. }
  6871. } else
  6872. c = p->owner;
  6873. if (!ignore && p)
  6874. p->lastinvite = seqno;
  6875. if (c) {
  6876. switch(c->_state) {
  6877. case AST_STATE_DOWN:
  6878. transmit_response(p, "100 Trying", req);
  6879. ast_setstate(c, AST_STATE_RING);
  6880. if (strcmp(p->exten, ast_pickup_ext())) {
  6881. if (ast_pbx_start(c)) {
  6882. ast_log(LOG_WARNING, "Failed to start PBX :(\n");
  6883. /* Unlock locks so ast_hangup can do its magic */
  6884. ast_mutex_unlock(&c->lock);
  6885. ast_mutex_unlock(&p->lock);
  6886. ast_hangup(c);
  6887. ast_mutex_lock(&p->lock);
  6888. if (ignore)
  6889. transmit_response(p, "503 Unavailable", req);
  6890. else
  6891. transmit_response_reliable(p, "503 Unavailable", req, 1);
  6892. c = NULL;
  6893. }
  6894. } else {
  6895. ast_mutex_unlock(&c->lock);
  6896. if (ast_pickup_call(c)) {
  6897. ast_log(LOG_NOTICE, "Nothing to pick up\n");
  6898. if (ignore)
  6899. transmit_response(p, "503 Unavailable", req);
  6900. else
  6901. transmit_response_reliable(p, "503 Unavailable", req, 1);
  6902. p->alreadygone = 1;
  6903. /* Unlock locks so ast_hangup can do its magic */
  6904. ast_mutex_unlock(&p->lock);
  6905. ast_hangup(c);
  6906. ast_mutex_lock(&p->lock);
  6907. c = NULL;
  6908. } else {
  6909. ast_mutex_unlock(&p->lock);
  6910. ast_setstate(c, AST_STATE_DOWN);
  6911. ast_hangup(c);
  6912. ast_mutex_lock(&p->lock);
  6913. c = NULL;
  6914. }
  6915. }
  6916. break;
  6917. case AST_STATE_RING:
  6918. transmit_response(p, "100 Trying", req);
  6919. break;
  6920. case AST_STATE_RINGING:
  6921. transmit_response(p, "180 Ringing", req);
  6922. break;
  6923. case AST_STATE_UP:
  6924. transmit_response_with_sdp(p, "200 OK", req, 1);
  6925. break;
  6926. default:
  6927. ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
  6928. transmit_response(p, "100 Trying", req);
  6929. }
  6930. } else {
  6931. if (p && !p->needdestroy) {
  6932. if (!p->jointcapability) {
  6933. if (ignore)
  6934. transmit_response(p, "488 Not Acceptable Here", req);
  6935. else
  6936. transmit_response_reliable(p, "488 Not Acceptable Here", req, 1);
  6937. p->needdestroy = 1;
  6938. } else {
  6939. ast_log(LOG_NOTICE, "Unable to create/find channel\n");
  6940. if (ignore)
  6941. transmit_response(p, "503 Unavailable", req);
  6942. else
  6943. transmit_response_reliable(p, "503 Unavailable", req, 1);
  6944. p->needdestroy = 1;
  6945. }
  6946. }
  6947. }
  6948. } else if (!strcasecmp(cmd, "REFER")) {
  6949. ast_log(LOG_DEBUG, "We found a REFER!\n");
  6950. if (ast_strlen_zero(p->context))
  6951. strncpy(p->context, default_context, sizeof(p->context) - 1);
  6952. res = get_refer_info(p, req);
  6953. if (res < 0)
  6954. transmit_response_with_allow(p, "404 Not Found", req, 1);
  6955. else if (res > 0)
  6956. transmit_response_with_allow(p, "484 Address Incomplete", req, 1);
  6957. else {
  6958. int nobye = 0;
  6959. if (!ignore) {
  6960. if (p->refer_call) {
  6961. ast_log(LOG_DEBUG,"202 Accepted (supervised)\n");
  6962. attempt_transfer(p, p->refer_call);
  6963. if (p->refer_call->owner)
  6964. ast_mutex_unlock(&p->refer_call->owner->lock);
  6965. ast_mutex_unlock(&p->refer_call->lock);
  6966. p->refer_call = NULL;
  6967. p->gotrefer = 1;
  6968. } else {
  6969. ast_log(LOG_DEBUG,"202 Accepted (blind)\n");
  6970. c = p->owner;
  6971. if (c) {
  6972. transfer_to = c->bridge;
  6973. if (transfer_to) {
  6974. ast_moh_stop(transfer_to);
  6975. if (!strcmp(p->refer_to, ast_parking_ext())) {
  6976. /* Must release c's lock now, because it will not longer
  6977. be accessible after the transfer! */
  6978. *nounlock = 1;
  6979. ast_mutex_unlock(&c->lock);
  6980. sip_park(transfer_to, c, req);
  6981. nobye = 1;
  6982. } else {
  6983. /* Must release c's lock now, because it will not longer
  6984. be accessible after the transfer! */
  6985. *nounlock = 1;
  6986. ast_mutex_unlock(&c->lock);
  6987. ast_async_goto(transfer_to,p->context, p->refer_to,1);
  6988. }
  6989. } else {
  6990. ast_queue_hangup(p->owner);
  6991. }
  6992. }
  6993. p->gotrefer = 1;
  6994. }
  6995. transmit_response(p, "202 Accepted", req);
  6996. transmit_notify_with_sipfrag(p, seqno);
  6997. /* Always increment on a BYE */
  6998. if (!nobye) {
  6999. transmit_request_with_auth(p, "BYE", 0, 1, 1);
  7000. p->alreadygone = 1;
  7001. }
  7002. }
  7003. }
  7004. } else if (!strcasecmp(cmd, "CANCEL")) {
  7005. check_via(p, req);
  7006. p->alreadygone = 1;
  7007. if (p->rtp) {
  7008. /* Immediately stop RTP */
  7009. ast_rtp_stop(p->rtp);
  7010. }
  7011. if (p->vrtp) {
  7012. /* Immediately stop VRTP */
  7013. ast_rtp_stop(p->vrtp);
  7014. }
  7015. if (p->owner)
  7016. ast_queue_hangup(p->owner);
  7017. else
  7018. p->needdestroy = 1;
  7019. if (p->initreq.len > 0) {
  7020. if (!ignore)
  7021. transmit_response_reliable(p, "487 Request Terminated", &p->initreq, 1);
  7022. transmit_response(p, "200 OK", req);
  7023. } else {
  7024. transmit_response(p, "481 Call Leg Does Not Exist", req);
  7025. }
  7026. } else if (!strcasecmp(cmd, "BYE")) {
  7027. copy_request(&p->initreq, req);
  7028. check_via(p, req);
  7029. p->alreadygone = 1;
  7030. if (p->rtp) {
  7031. /* Immediately stop RTP */
  7032. ast_rtp_stop(p->rtp);
  7033. }
  7034. if (p->vrtp) {
  7035. /* Immediately stop VRTP */
  7036. ast_rtp_stop(p->vrtp);
  7037. }
  7038. if (!ast_strlen_zero(get_header(req, "Also"))) {
  7039. ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
  7040. ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
  7041. if (ast_strlen_zero(p->context))
  7042. strncpy(p->context, default_context, sizeof(p->context) - 1);
  7043. res = get_also_info(p, req);
  7044. if (!res) {
  7045. c = p->owner;
  7046. if (c) {
  7047. transfer_to = c->bridge;
  7048. if (transfer_to) {
  7049. /* Don't actually hangup here... */
  7050. ast_moh_stop(transfer_to);
  7051. ast_async_goto(transfer_to,p->context, p->refer_to,1);
  7052. } else
  7053. ast_queue_hangup(p->owner);
  7054. }
  7055. } else {
  7056. ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr));
  7057. ast_queue_hangup(p->owner);
  7058. }
  7059. } else if (p->owner)
  7060. ast_queue_hangup(p->owner);
  7061. else
  7062. p->needdestroy = 1;
  7063. transmit_response(p, "200 OK", req);
  7064. } else if (!strcasecmp(cmd, "MESSAGE")) {
  7065. if (p->lastinvite) {
  7066. if (!ignore) {
  7067. if (debug)
  7068. ast_verbose("Receiving message!\n");
  7069. receive_message(p, req);
  7070. }
  7071. transmit_response(p, "200 OK", req);
  7072. } else {
  7073. transmit_response(p, "405 Method Not Allowed", req);
  7074. p->needdestroy = 1;
  7075. }
  7076. } else if (!strcasecmp(cmd, "SUBSCRIBE")) {
  7077. if (!ignore) {
  7078. /* Use this as the basis */
  7079. if (debug)
  7080. ast_verbose("Using latest SUBSCRIBE request as basis request\n");
  7081. /* This call is no longer outgoing if it ever was */
  7082. p->outgoing = 0;
  7083. copy_request(&p->initreq, req);
  7084. check_via(p, req);
  7085. } else if (debug)
  7086. ast_verbose("Ignoring this request\n");
  7087. if (!p->lastinvite) {
  7088. char mailbox[256]="";
  7089. int found = 0;
  7090. /* Handle authentication if this is our first subscribe */
  7091. res = check_user_full(p, req, cmd, e, 0, sin, ignore, mailbox, sizeof(mailbox));
  7092. if (res) {
  7093. if (res < 0) {
  7094. ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
  7095. p->needdestroy = 1;
  7096. }
  7097. return 0;
  7098. }
  7099. /* Initialize the context if it hasn't been already */
  7100. if (ast_strlen_zero(p->context))
  7101. strncpy(p->context, default_context, sizeof(p->context) - 1);
  7102. /* Get destination right away */
  7103. gotdest = get_destination(p, NULL);
  7104. build_contact(p);
  7105. if (gotdest) {
  7106. if (gotdest < 0)
  7107. transmit_response(p, "404 Not Found", req);
  7108. else
  7109. transmit_response(p, "484 Address Incomplete", req);
  7110. p->needdestroy = 1;
  7111. } else {
  7112. /* Initialize tag */
  7113. p->tag = rand();
  7114. if (!strcmp(get_header(req, "Accept"), "application/dialog-info+xml"))
  7115. p->subscribed = 2;
  7116. else if (!strcmp(get_header(req, "Accept"), "application/simple-message-summary")) {
  7117. /* Looks like they actually want a mailbox */
  7118. /* At this point, we should check if they subscribe to a mailbox that
  7119. has the same extension as the peer or the mailbox id. If we configure
  7120. the context to be the same as a SIP domain, we could check mailbox
  7121. context as well. To be able to securely accept subscribes on mailbox
  7122. IDs, not extensions, we need to check the digest auth user to make
  7123. sure that the user has access to the mailbox.
  7124. Since we do not act on this subscribe anyway, we might as well
  7125. accept any authenticated peer with a mailbox definition in their
  7126. config section.
  7127. */
  7128. if (!ast_strlen_zero(mailbox)) {
  7129. found++;
  7130. }
  7131. if (found) {
  7132. transmit_response(p, "200 OK", req);
  7133. p->needdestroy = 1;
  7134. } else {
  7135. transmit_response(p, "403 Forbidden", req);
  7136. p->needdestroy = 1;
  7137. }
  7138. return 0;
  7139. } else
  7140. p->subscribed = 1;
  7141. if (p->subscribed)
  7142. p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
  7143. }
  7144. } else
  7145. c = p->owner;
  7146. if (!ignore && p)
  7147. p->lastinvite = seqno;
  7148. if (p && !p->needdestroy) {
  7149. if (!(p->expiry = atoi(get_header(req, "Expires")))) {
  7150. transmit_response(p, "200 OK", req);
  7151. p->needdestroy = 1;
  7152. return 0;
  7153. }
  7154. /* The next line can be removed if the SNOM200 Expires bug is fixed */
  7155. if (p->subscribed == 1) {
  7156. if (p->expiry>max_expiry) {
  7157. p->expiry = max_expiry;
  7158. }
  7159. }
  7160. /* Go ahead and free RTP port */
  7161. if (p->rtp) {
  7162. ast_rtp_destroy(p->rtp);
  7163. p->rtp = NULL;
  7164. }
  7165. if (p->vrtp) {
  7166. ast_rtp_destroy(p->vrtp);
  7167. p->vrtp = NULL;
  7168. }
  7169. transmit_response(p, "200 OK", req);
  7170. sip_scheddestroy(p, (p->expiry+10)*1000);
  7171. transmit_state_notify(p, ast_extension_state(NULL, p->context, p->exten),1);
  7172. }
  7173. } else if (!strcasecmp(cmd, "INFO")) {
  7174. if (!ignore) {
  7175. if (debug)
  7176. ast_verbose("Receiving DTMF!\n");
  7177. receive_info(p, req);
  7178. } else { /* if ignoring, transmit response */
  7179. transmit_response(p, "200 OK", req);
  7180. }
  7181. } else if (!strcasecmp(cmd, "NOTIFY")) {
  7182. /* XXX we get NOTIFY's from some servers. WHY?? Maybe we should
  7183. look into this someday XXX */
  7184. transmit_response(p, "200 OK", req);
  7185. if (!p->lastinvite) p->needdestroy = 1;
  7186. } else if (!strcasecmp(cmd, "REGISTER")) {
  7187. /* Use this as the basis */
  7188. if (debug)
  7189. ast_verbose("Using latest request as basis request\n");
  7190. copy_request(&p->initreq, req);
  7191. check_via(p, req);
  7192. if ((res = register_verify(p, sin, req, e, ignore)) < 0)
  7193. ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s'\n", get_header(req, "To"), ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
  7194. if (res < 1) {
  7195. /* Go ahead and free RTP port */
  7196. if (p->rtp) {
  7197. ast_rtp_destroy(p->rtp);
  7198. p->rtp = NULL;
  7199. }
  7200. if (p->vrtp) {
  7201. ast_rtp_destroy(p->vrtp);
  7202. p->vrtp = NULL;
  7203. }
  7204. /* Destroy the session, but keep us around for just a bit in case they don't
  7205. get our 200 OK */
  7206. sip_scheddestroy(p, 15*1000);
  7207. }
  7208. } else if (!strcasecmp(cmd, "ACK")) {
  7209. /* Make sure we don't ignore this */
  7210. if (seqno == p->pendinginvite) {
  7211. p->pendinginvite = 0;
  7212. __sip_ack(p, seqno, FLAG_RESPONSE, NULL);
  7213. if (!ast_strlen_zero(get_header(req, "Content-Type"))) {
  7214. if (process_sdp(p, req))
  7215. return -1;
  7216. }
  7217. check_pendings(p);
  7218. }
  7219. if (!p->lastinvite && ast_strlen_zero(p->randdata))
  7220. p->needdestroy = 1;
  7221. } else if (!strcasecmp(cmd, "SIP/2.0")) {
  7222. extract_uri(p, req);
  7223. while(*e && (*e < 33)) e++;
  7224. if (sscanf(e, "%i %n", &respid, &len) != 1) {
  7225. ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
  7226. } else {
  7227. handle_response(p, respid, e + len, req,ignore);
  7228. }
  7229. } else {
  7230. transmit_response_with_allow(p, "405 Method Not Allowed", req, 0);
  7231. ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
  7232. cmd, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr));
  7233. /* If this is some new method, and we don't have a call, destroy it now */
  7234. if (!p->initreq.headers)
  7235. p->needdestroy = 1;
  7236. }
  7237. return 0;
  7238. }
  7239. /*--- sipsock_read: Read data from SIP socket ---*/
  7240. /* Successful messages is connected to SIP call and forwarded to handle_request() */
  7241. static int sipsock_read(int *id, int fd, short events, void *ignore)
  7242. {
  7243. struct sip_request req;
  7244. struct sockaddr_in sin = { 0, };
  7245. struct sip_pvt *p;
  7246. int res;
  7247. int len;
  7248. int nounlock;
  7249. int recount = 0;
  7250. int debug;
  7251. len = sizeof(sin);
  7252. memset(&req, 0, sizeof(req));
  7253. res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
  7254. if (res < 0) {
  7255. if (errno == EAGAIN)
  7256. ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
  7257. else if (errno != ECONNREFUSED)
  7258. ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
  7259. return 1;
  7260. }
  7261. req.data[res] = '\0';
  7262. req.len = res;
  7263. debug = sip_debug_test_addr(&sin);
  7264. if (debug)
  7265. ast_verbose("\n\nSip read: \n%s\n", req.data);
  7266. req.len = lws2sws(req.data, req.len);
  7267. parse(&req);
  7268. if (debug)
  7269. ast_verbose("%d headers, %d lines\n", req.headers, req.lines);
  7270. if (req.headers < 2) {
  7271. /* Must have at least two headers */
  7272. return 1;
  7273. }
  7274. /* Process request, with netlock held */
  7275. retrylock:
  7276. ast_mutex_lock(&netlock);
  7277. p = find_call(&req, &sin);
  7278. if (p) {
  7279. /* Go ahead and lock the owner if it has one -- we may need it */
  7280. if (p->owner && ast_mutex_trylock(&p->owner->lock)) {
  7281. ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
  7282. ast_mutex_unlock(&p->lock);
  7283. ast_mutex_unlock(&netlock);
  7284. /* Sleep infintismly short amount of time */
  7285. usleep(1);
  7286. goto retrylock;
  7287. }
  7288. memcpy(&p->recv, &sin, sizeof(p->recv));
  7289. if (recordhistory) {
  7290. char tmp[80] = "";
  7291. /* This is a response, note what it was for */
  7292. snprintf(tmp, sizeof(tmp), "%s / %s", req.data, get_header(&req, "CSeq"));
  7293. append_history(p, "Rx", tmp);
  7294. }
  7295. nounlock = 0;
  7296. handle_request(p, &req, &sin, &recount, &nounlock);
  7297. if (p->owner && !nounlock)
  7298. ast_mutex_unlock(&p->owner->lock);
  7299. ast_mutex_unlock(&p->lock);
  7300. }
  7301. ast_mutex_unlock(&netlock);
  7302. if (recount)
  7303. ast_update_use_count();
  7304. return 1;
  7305. }
  7306. /*--- sip_send_mwi_to_peer: Send message waiting indication ---*/
  7307. static int sip_send_mwi_to_peer(struct sip_peer *peer)
  7308. {
  7309. /* Called with peerl lock, but releases it */
  7310. struct sip_pvt *p;
  7311. char name[256] = "";
  7312. char iabuf[INET_ADDRSTRLEN];
  7313. int newmsgs, oldmsgs;
  7314. /* Check for messages */
  7315. ast_app_messagecount(peer->mailbox, &newmsgs, &oldmsgs);
  7316. time(&peer->lastmsgcheck);
  7317. /* Return now if it's the same thing we told them last time */
  7318. if (((newmsgs << 8) | (oldmsgs)) == peer->lastmsgssent) {
  7319. ast_mutex_unlock(&peerl.lock);
  7320. return 0;
  7321. }
  7322. p = sip_alloc(NULL, NULL, 0);
  7323. if (!p) {
  7324. ast_log(LOG_WARNING, "Unable to build sip pvt data for MWI\n");
  7325. ast_mutex_unlock(&peerl.lock);
  7326. return -1;
  7327. }
  7328. strncpy(name, peer->name, sizeof(name) - 1);
  7329. peer->lastmsgssent = ((newmsgs << 8) | (oldmsgs));
  7330. ast_mutex_unlock(&peerl.lock);
  7331. if (create_addr(p, name)) {
  7332. /* Maybe they're not registered, etc. */
  7333. sip_destroy(p);
  7334. return 0;
  7335. }
  7336. /* Recalculate our side, and recalculate Call ID */
  7337. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  7338. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  7339. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  7340. if (p->nat & SIP_NAT_RFC3581)
  7341. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  7342. else /* UNIDEN UIP200 bug */
  7343. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  7344. build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
  7345. /* Send MWI */
  7346. p->outgoing = 1;
  7347. transmit_notify_with_mwi(p, newmsgs, oldmsgs);
  7348. sip_scheddestroy(p, 15000);
  7349. return 0;
  7350. }
  7351. /*--- do_monitor: The SIP monitoring thread ---*/
  7352. static void *do_monitor(void *data)
  7353. {
  7354. int res;
  7355. struct sip_pvt *sip;
  7356. struct sip_peer *peer;
  7357. time_t t;
  7358. int fastrestart =0;
  7359. int lastpeernum = -1;
  7360. int curpeernum;
  7361. int reloading;
  7362. /* Add an I/O event to our UDP socket */
  7363. if (sipsock > -1)
  7364. ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  7365. /* This thread monitors all the frame relay interfaces which are not yet in use
  7366. (and thus do not have a separate thread) indefinitely */
  7367. /* From here on out, we die whenever asked */
  7368. for(;;) {
  7369. /* Check for a reload request */
  7370. ast_mutex_lock(&sip_reload_lock);
  7371. reloading = sip_reloading;
  7372. sip_reloading = 0;
  7373. ast_mutex_unlock(&sip_reload_lock);
  7374. if (reloading) {
  7375. if (option_verbose > 0)
  7376. ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
  7377. sip_do_reload();
  7378. }
  7379. /* Check for interfaces needing to be killed */
  7380. ast_mutex_lock(&iflock);
  7381. restartsearch:
  7382. time(&t);
  7383. sip = iflist;
  7384. while(sip) {
  7385. ast_mutex_lock(&sip->lock);
  7386. if (sip->rtp && sip->owner && (sip->owner->_state == AST_STATE_UP) && sip->lastrtprx && (sip->rtptimeout || sip->rtpholdtimeout) && !sip->redirip.sin_addr.s_addr) {
  7387. if (t > sip->lastrtprx + sip->rtptimeout) {
  7388. /* Might be a timeout now -- see if we're on hold */
  7389. struct sockaddr_in sin;
  7390. ast_rtp_get_peer(sip->rtp, &sin);
  7391. if (sin.sin_addr.s_addr ||
  7392. (sip->rtpholdtimeout &&
  7393. (t > sip->lastrtprx + sip->rtpholdtimeout))) {
  7394. /* Needs a hangup */
  7395. if (sip->rtptimeout) {
  7396. while(sip->owner && ast_mutex_trylock(&sip->owner->lock)) {
  7397. ast_mutex_unlock(&sip->lock);
  7398. usleep(1);
  7399. ast_mutex_lock(&sip->lock);
  7400. }
  7401. if (sip->owner) {
  7402. ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n", sip->owner->name, (long)(t - sip->lastrtprx));
  7403. /* Issue a softhangup */
  7404. ast_softhangup(sip->owner, AST_SOFTHANGUP_DEV);
  7405. ast_mutex_unlock(&sip->owner->lock);
  7406. }
  7407. }
  7408. }
  7409. }
  7410. }
  7411. if (sip->needdestroy && !sip->packets && !sip->owner) {
  7412. ast_mutex_unlock(&sip->lock);
  7413. __sip_destroy(sip, 1);
  7414. goto restartsearch;
  7415. }
  7416. ast_mutex_unlock(&sip->lock);
  7417. sip = sip->next;
  7418. }
  7419. ast_mutex_unlock(&iflock);
  7420. /* Don't let anybody kill us right away. Nobody should lock the interface list
  7421. and wait for the monitor list, but the other way around is okay. */
  7422. ast_mutex_lock(&monlock);
  7423. /* Lock the network interface */
  7424. ast_mutex_lock(&netlock);
  7425. /* Okay, now that we know what to do, release the network lock */
  7426. ast_mutex_unlock(&netlock);
  7427. /* And from now on, we're okay to be killed, so release the monitor lock as well */
  7428. ast_mutex_unlock(&monlock);
  7429. pthread_testcancel();
  7430. /* Wait for sched or io */
  7431. res = ast_sched_wait(sched);
  7432. if ((res < 0) || (res > 1000))
  7433. res = 1000;
  7434. /* If we might need to send more mailboxes, don't wait long at all.*/
  7435. if (fastrestart)
  7436. res = 1;
  7437. res = ast_io_wait(io, res);
  7438. ast_mutex_lock(&monlock);
  7439. if (res >= 0)
  7440. ast_sched_runq(sched);
  7441. /* needs work to send mwi to mysql peers */
  7442. ast_mutex_lock(&peerl.lock);
  7443. peer = peerl.peers;
  7444. time(&t);
  7445. fastrestart = 0;
  7446. curpeernum = 0;
  7447. while(peer) {
  7448. if ((curpeernum > lastpeernum) && !ast_strlen_zero(peer->mailbox) && ((t - peer->lastmsgcheck) > 10)) {
  7449. sip_send_mwi_to_peer(peer);
  7450. fastrestart = 1;
  7451. lastpeernum = curpeernum;
  7452. break;
  7453. }
  7454. curpeernum++;
  7455. peer = peer->next;
  7456. }
  7457. /* Remember, sip_send_mwi_to_peer releases the lock if we've called it */
  7458. if (!peer) {
  7459. /* Reset where we come from */
  7460. lastpeernum = -1;
  7461. ast_mutex_unlock(&peerl.lock);
  7462. }
  7463. ast_mutex_unlock(&monlock);
  7464. }
  7465. /* Never reached */
  7466. return NULL;
  7467. }
  7468. /*--- restart_monitor: Start the channel monitor thread ---*/
  7469. static int restart_monitor(void)
  7470. {
  7471. pthread_attr_t attr;
  7472. /* If we're supposed to be stopped -- stay stopped */
  7473. if (monitor_thread == AST_PTHREADT_STOP)
  7474. return 0;
  7475. if (ast_mutex_lock(&monlock)) {
  7476. ast_log(LOG_WARNING, "Unable to lock monitor\n");
  7477. return -1;
  7478. }
  7479. if (monitor_thread == pthread_self()) {
  7480. ast_mutex_unlock(&monlock);
  7481. ast_log(LOG_WARNING, "Cannot kill myself\n");
  7482. return -1;
  7483. }
  7484. if (monitor_thread != AST_PTHREADT_NULL) {
  7485. /* Wake up the thread */
  7486. pthread_kill(monitor_thread, SIGURG);
  7487. } else {
  7488. pthread_attr_init(&attr);
  7489. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  7490. /* Start a new monitor */
  7491. if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
  7492. ast_mutex_unlock(&monlock);
  7493. ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
  7494. return -1;
  7495. }
  7496. }
  7497. ast_mutex_unlock(&monlock);
  7498. return 0;
  7499. }
  7500. /*--- sip_poke_noanswer: No answer to Qualify poke ---*/
  7501. static int sip_poke_noanswer(void *data)
  7502. {
  7503. struct sip_peer *peer = data;
  7504. peer->pokeexpire = -1;
  7505. if (peer->lastms > -1) {
  7506. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!\n", peer->name);
  7507. manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
  7508. }
  7509. if (peer->call)
  7510. sip_destroy(peer->call);
  7511. peer->call = NULL;
  7512. peer->lastms = -1;
  7513. ast_device_state_changed("SIP/%s", peer->name);
  7514. /* Try again quickly */
  7515. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
  7516. return 0;
  7517. }
  7518. /*--- sip_poke_peer: Check availability of peer, also keep NAT open ---*/
  7519. /* This is done with the interval in qualify= option in sip.conf */
  7520. /* Default is 2 seconds */
  7521. static int sip_poke_peer(struct sip_peer *peer)
  7522. {
  7523. struct sip_pvt *p;
  7524. char iabuf[INET_ADDRSTRLEN];
  7525. if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
  7526. /* IF we have no IP, or this isn't to be monitored, return
  7527. imeediately after clearing things out */
  7528. if (peer->pokeexpire > -1)
  7529. ast_sched_del(sched, peer->pokeexpire);
  7530. peer->lastms = 0;
  7531. peer->pokeexpire = -1;
  7532. peer->call = NULL;
  7533. return 0;
  7534. }
  7535. if (peer->call > 0) {
  7536. ast_log(LOG_NOTICE, "Still have a call...\n");
  7537. sip_destroy(peer->call);
  7538. }
  7539. p = peer->call = sip_alloc(NULL, NULL, 0);
  7540. if (!peer->call) {
  7541. ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
  7542. return -1;
  7543. }
  7544. memcpy(&p->sa, &peer->addr, sizeof(p->sa));
  7545. memcpy(&p->recv, &peer->addr, sizeof(p->sa));
  7546. /* Send options to peer's fullcontact */
  7547. if (!ast_strlen_zero(peer->fullcontact)) {
  7548. strncpy (p->fullcontact, peer->fullcontact, sizeof(p->fullcontact));
  7549. }
  7550. if (!ast_strlen_zero(p->tohost))
  7551. strncpy(p->tohost, peer->tohost, sizeof(p->tohost) - 1);
  7552. else
  7553. ast_inet_ntoa(p->tohost, sizeof(p->tohost), peer->addr.sin_addr);
  7554. /* Recalculate our side, and recalculate Call ID */
  7555. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  7556. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  7557. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  7558. if (p->nat & SIP_NAT_RFC3581)
  7559. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  7560. else
  7561. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  7562. build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
  7563. if (peer->pokeexpire > -1)
  7564. ast_sched_del(sched, peer->pokeexpire);
  7565. p->peerpoke = peer;
  7566. p->outgoing = 1;
  7567. #ifdef VOCAL_DATA_HACK
  7568. strncpy(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username) - 1);
  7569. transmit_invite(p, "INVITE", 0, NULL, NULL, NULL,NULL,NULL, 1);
  7570. #else
  7571. transmit_invite(p, "OPTIONS", 0, NULL, NULL, NULL,NULL,NULL, 1);
  7572. #endif
  7573. gettimeofday(&peer->ps, NULL);
  7574. peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
  7575. return 0;
  7576. }
  7577. /*--- sip_devicestate: Part of PBX channel interface ---*/
  7578. static int sip_devicestate(void *data)
  7579. {
  7580. char *ext, *host;
  7581. char tmp[256] = "";
  7582. char *dest = data;
  7583. struct hostent *hp;
  7584. struct ast_hostent ahp;
  7585. struct sip_peer *p;
  7586. int found = 0;
  7587. int res = AST_DEVICE_INVALID;
  7588. strncpy(tmp, dest, sizeof(tmp) - 1);
  7589. host = strchr(tmp, '@');
  7590. if (host) {
  7591. *host = '\0';
  7592. host++;
  7593. ext = tmp;
  7594. } else {
  7595. host = tmp;
  7596. ext = NULL;
  7597. }
  7598. ast_mutex_lock(&peerl.lock);
  7599. p = find_peer(host, NULL);
  7600. if (p) {
  7601. found++;
  7602. res = AST_DEVICE_UNAVAILABLE;
  7603. if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
  7604. (!p->maxms || ((p->lastms > -1) && (p->lastms <= p->maxms)))) {
  7605. /* peer found and valid */
  7606. res = AST_DEVICE_UNKNOWN;
  7607. }
  7608. }
  7609. ast_mutex_unlock(&peerl.lock);
  7610. if (!p && !found) {
  7611. hp = ast_gethostbyname(host, &ahp);
  7612. if (hp)
  7613. res = AST_DEVICE_UNKNOWN;
  7614. }
  7615. return res;
  7616. }
  7617. /*--- sip_request: PBX interface function -build SIP pvt structure ---*/
  7618. /* SIP calls initiated by the PBX arrive here */
  7619. static struct ast_channel *sip_request(char *type, int format, void *data)
  7620. {
  7621. int oldformat;
  7622. struct sip_pvt *p;
  7623. struct ast_channel *tmpc = NULL;
  7624. char *ext, *host;
  7625. char tmp[256] = "";
  7626. char iabuf[INET_ADDRSTRLEN];
  7627. char *dest = data;
  7628. oldformat = format;
  7629. format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
  7630. if (!format) {
  7631. ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
  7632. return NULL;
  7633. }
  7634. p = sip_alloc(NULL, NULL, 0);
  7635. if (!p) {
  7636. ast_log(LOG_WARNING, "Unable to build sip pvt data for '%s'\n", (char *)data);
  7637. return NULL;
  7638. }
  7639. strncpy(tmp, dest, sizeof(tmp) - 1);
  7640. host = strchr(tmp, '@');
  7641. if (host) {
  7642. *host = '\0';
  7643. host++;
  7644. ext = tmp;
  7645. } else {
  7646. ext = strchr(tmp, '/');
  7647. if (ext) {
  7648. *ext++ = '\0';
  7649. host = tmp;
  7650. }
  7651. else {
  7652. host = tmp;
  7653. ext = NULL;
  7654. }
  7655. }
  7656. /* Assign a default capability */
  7657. p->capability = global_capability;
  7658. if (create_addr(p, host)) {
  7659. sip_destroy(p);
  7660. return NULL;
  7661. }
  7662. if (ast_strlen_zero(p->peername) && ext)
  7663. strncpy(p->peername, ext, sizeof(p->peername) - 1);
  7664. /* Recalculate our side, and recalculate Call ID */
  7665. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  7666. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  7667. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  7668. if (p->nat & SIP_NAT_RFC3581)
  7669. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  7670. else /* UNIDEN bug */
  7671. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
  7672. build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
  7673. /* We have an extension to call, don't use the full contact here */
  7674. /* This to enable dialling registred peers with extension dialling,
  7675. like SIP/peername/extension
  7676. SIP/peername will still use the full contact */
  7677. if (ext) {
  7678. strncpy(p->username, ext, sizeof(p->username) - 1);
  7679. p->fullcontact[0] = 0;
  7680. }
  7681. #if 0
  7682. printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
  7683. #endif
  7684. p->prefcodec = format;
  7685. ast_mutex_lock(&p->lock);
  7686. tmpc = sip_new(p, AST_STATE_DOWN, host);
  7687. ast_mutex_unlock(&p->lock);
  7688. if (!tmpc)
  7689. sip_destroy(p);
  7690. ast_update_use_count();
  7691. restart_monitor();
  7692. return tmpc;
  7693. }
  7694. /*--- build_user: Initiate a SIP user structure from sip.conf ---*/
  7695. static struct sip_user *build_user(char *name, struct ast_variable *v)
  7696. {
  7697. struct sip_user *user;
  7698. int format;
  7699. struct ast_ha *oldha = NULL;
  7700. user = (struct sip_user *)malloc(sizeof(struct sip_user));
  7701. if (user) {
  7702. memset(user, 0, sizeof(struct sip_user));
  7703. strncpy(user->name, name, sizeof(user->name)-1);
  7704. oldha = user->ha;
  7705. user->ha = NULL;
  7706. /* set the usage flag to a sane staring value*/
  7707. user->inUse = 0;
  7708. user->outUse = 0;
  7709. user->capability = global_capability;
  7710. user->canreinvite = global_canreinvite;
  7711. user->trustrpid = global_trustrpid;
  7712. user->dtmfmode = global_dtmfmode;
  7713. user->progressinband = global_progressinband;
  7714. user->nat = global_nat;
  7715. user->prefs = prefs;
  7716. #ifdef OSP_SUPPORT
  7717. user->ospauth = global_ospauth;
  7718. #endif
  7719. /* set default context */
  7720. strncpy(user->context, default_context, sizeof(user->context)-1);
  7721. strncpy(user->language, default_language, sizeof(user->language)-1);
  7722. strncpy(user->musicclass, global_musicclass, sizeof(user->musicclass)-1);
  7723. while(v) {
  7724. if (!strcasecmp(v->name, "context")) {
  7725. strncpy(user->context, v->value, sizeof(user->context) - 1);
  7726. } else if (!strcasecmp(v->name, "permit") ||
  7727. !strcasecmp(v->name, "deny")) {
  7728. user->ha = ast_append_ha(v->name, v->value, user->ha);
  7729. } else if (!strcasecmp(v->name, "secret")) {
  7730. strncpy(user->secret, v->value, sizeof(user->secret)-1);
  7731. } else if (!strcasecmp(v->name, "md5secret")) {
  7732. strncpy(user->md5secret, v->value, sizeof(user->md5secret)-1);
  7733. } else if (!strcasecmp(v->name, "promiscredir")) {
  7734. user->promiscredir = ast_true(v->value);
  7735. } else if (!strcasecmp(v->name, "dtmfmode")) {
  7736. if (!strcasecmp(v->value, "inband"))
  7737. user->dtmfmode=SIP_DTMF_INBAND;
  7738. else if (!strcasecmp(v->value, "rfc2833"))
  7739. user->dtmfmode = SIP_DTMF_RFC2833;
  7740. else if (!strcasecmp(v->value, "info"))
  7741. user->dtmfmode = SIP_DTMF_INFO;
  7742. else {
  7743. ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
  7744. user->dtmfmode = SIP_DTMF_RFC2833;
  7745. }
  7746. } else if (!strcasecmp(v->name, "canreinvite")) {
  7747. if (!strcasecmp(v->value, "update"))
  7748. user->canreinvite = REINVITE_UPDATE;
  7749. else
  7750. user->canreinvite = ast_true(v->value);
  7751. } else if (!strcasecmp(v->name, "nat")) {
  7752. if (!strcasecmp(v->value, "never"))
  7753. user->nat = SIP_NAT_NEVER;
  7754. else if (!strcasecmp(v->value, "route"))
  7755. user->nat = SIP_NAT_ROUTE;
  7756. else if (ast_true(v->value))
  7757. user->nat = SIP_NAT_ALWAYS;
  7758. else
  7759. user->nat = SIP_NAT_RFC3581;
  7760. } else if (!strcasecmp(v->name, "callerid")) {
  7761. strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
  7762. user->hascallerid=1;
  7763. } else if (!strcasecmp(v->name, "callgroup")) {
  7764. user->callgroup = ast_get_group(v->value);
  7765. } else if (!strcasecmp(v->name, "pickupgroup")) {
  7766. user->pickupgroup = ast_get_group(v->value);
  7767. } else if (!strcasecmp(v->name, "language")) {
  7768. strncpy(user->language, v->value, sizeof(user->language)-1);
  7769. } else if (!strcasecmp(v->name, "musiconhold")) {
  7770. strncpy(user->musicclass, v->value, sizeof(user->musicclass)-1);
  7771. } else if (!strcasecmp(v->name, "accountcode")) {
  7772. strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
  7773. } else if (!strcasecmp(v->name, "incominglimit")) {
  7774. user->incominglimit = atoi(v->value);
  7775. if (user->incominglimit < 0)
  7776. user->incominglimit = 0;
  7777. } else if (!strcasecmp(v->name, "outgoinglimit")) {
  7778. user->outgoinglimit = atoi(v->value);
  7779. if (user->outgoinglimit < 0)
  7780. user->outgoinglimit = 0;
  7781. } else if (!strcasecmp(v->name, "amaflags")) {
  7782. format = ast_cdr_amaflags2int(v->value);
  7783. if (format < 0) {
  7784. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  7785. } else {
  7786. user->amaflags = format;
  7787. }
  7788. } else if (!strcasecmp(v->name, "allow")) {
  7789. ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
  7790. } else if (!strcasecmp(v->name, "disallow")) {
  7791. ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 0);
  7792. } else if (!strcasecmp(v->name, "insecure")) {
  7793. user->insecure = ast_true(v->value);
  7794. } else if (!strcasecmp(v->name, "restrictcid")) {
  7795. user->restrictcid = ast_true(v->value);
  7796. } else if (!strcasecmp(v->name, "trustrpid")) {
  7797. user->trustrpid = ast_true(v->value);
  7798. } else if (!strcasecmp(v->name, "progressinband")) {
  7799. user->progressinband = ast_true(v->value);
  7800. #ifdef OSP_SUPPORT
  7801. } else if (!strcasecmp(v->name, "ospauth")) {
  7802. if (!strcasecmp(v->value, "exclusive")) {
  7803. user->ospauth = 2;
  7804. } else if (ast_true(v->value)) {
  7805. user->ospauth = 1;
  7806. } else
  7807. user->ospauth = 0;
  7808. #endif
  7809. }
  7810. /*else if (strcasecmp(v->name,"type"))
  7811. * ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  7812. */
  7813. v = v->next;
  7814. }
  7815. }
  7816. if (oldha)
  7817. ast_free_ha(oldha);
  7818. return user;
  7819. }
  7820. /*--- temp_peer: Create temporary peer (used in autocreatepeer mode) ---*/
  7821. static struct sip_peer *temp_peer(char *name)
  7822. {
  7823. struct sip_peer *peer;
  7824. peer = malloc(sizeof(struct sip_peer));
  7825. if (!peer)
  7826. return NULL;
  7827. memset(peer, 0, sizeof(struct sip_peer));
  7828. peer->expire = -1;
  7829. peer->pokeexpire = -1;
  7830. strncpy(peer->name, name, sizeof(peer->name)-1);
  7831. strncpy(peer->context, default_context, sizeof(peer->context)-1);
  7832. strncpy(peer->language, default_language, sizeof(peer->language)-1);
  7833. strncpy(peer->musicclass, global_musicclass, sizeof(peer->musicclass)-1);
  7834. peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
  7835. peer->addr.sin_family = AF_INET;
  7836. peer->expiry = expiry;
  7837. peer->capability = global_capability;
  7838. /* Assume can reinvite */
  7839. peer->canreinvite = global_canreinvite;
  7840. peer->dtmfmode = global_dtmfmode;
  7841. peer->promiscredir = global_promiscredir;
  7842. peer->nat = global_nat;
  7843. peer->rtptimeout = global_rtptimeout;
  7844. peer->rtpholdtimeout = global_rtpholdtimeout;
  7845. peer->selfdestruct = 1;
  7846. peer->dynamic = 1;
  7847. peer->trustrpid = global_trustrpid;
  7848. peer->progressinband = global_progressinband;
  7849. peer->prefs = prefs;
  7850. #ifdef OSP_SUPPORT
  7851. peer->ospauth = global_ospauth;
  7852. #endif
  7853. reg_source_db(peer);
  7854. return peer;
  7855. }
  7856. /*--- build_peer: Build peer from config file ---*/
  7857. static struct sip_peer *build_peer(char *name, struct ast_variable *v)
  7858. {
  7859. struct sip_peer *peer;
  7860. struct sip_peer *prev;
  7861. struct ast_ha *oldha = NULL;
  7862. int maskfound=0;
  7863. int found=0;
  7864. prev = NULL;
  7865. ast_mutex_lock(&peerl.lock);
  7866. peer = peerl.peers;
  7867. while(peer) {
  7868. if (!strcasecmp(peer->name, name)) {
  7869. break;
  7870. }
  7871. prev = peer;
  7872. peer = peer->next;
  7873. }
  7874. if (peer) {
  7875. found++;
  7876. /* Already in the list, remove it and it will be added back (or FREE'd) */
  7877. if (prev) {
  7878. prev->next = peer->next;
  7879. } else {
  7880. peerl.peers = peer->next;
  7881. }
  7882. ast_mutex_unlock(&peerl.lock);
  7883. } else {
  7884. ast_mutex_unlock(&peerl.lock);
  7885. peer = malloc(sizeof(struct sip_peer));
  7886. if (peer) {
  7887. memset(peer, 0, sizeof(struct sip_peer));
  7888. peer->expire = -1;
  7889. peer->pokeexpire = -1;
  7890. }
  7891. }
  7892. if (peer) {
  7893. peer->lastmsgssent = -1;
  7894. if (!found) {
  7895. strncpy(peer->name, name, sizeof(peer->name)-1);
  7896. peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
  7897. peer->addr.sin_family = AF_INET;
  7898. peer->defaddr.sin_family = AF_INET;
  7899. peer->expiry = expiry;
  7900. }
  7901. strncpy(peer->context, default_context, sizeof(peer->context)-1);
  7902. strncpy(peer->language, default_language, sizeof(peer->language)-1);
  7903. strncpy(peer->musicclass, global_musicclass, sizeof(peer->musicclass)-1);
  7904. peer->secret[0] = '\0';
  7905. peer->md5secret[0] = '\0';
  7906. peer->fromdomain[0] = '\0';
  7907. peer->fromuser[0] = '\0';
  7908. peer->regexten[0] = '\0';
  7909. peer->mailbox[0] = '\0';
  7910. peer->callgroup = 0;
  7911. peer->pickupgroup = 0;
  7912. peer->maxms = 0;
  7913. peer->prefs = prefs;
  7914. oldha = peer->ha;
  7915. peer->ha = NULL;
  7916. peer->addr.sin_family = AF_INET;
  7917. peer->capability = global_capability;
  7918. /* Assume can reinvite */
  7919. peer->canreinvite = global_canreinvite;
  7920. peer->rtptimeout = global_rtptimeout;
  7921. peer->rtpholdtimeout = global_rtpholdtimeout;
  7922. peer->dtmfmode = global_dtmfmode;
  7923. peer->promiscredir = global_promiscredir;
  7924. peer->trustrpid = global_trustrpid;
  7925. peer->progressinband = global_progressinband;
  7926. #ifdef OSP_SUPPORT
  7927. peer->ospauth = global_ospauth;
  7928. #endif
  7929. while(v) {
  7930. if (!strcasecmp(v->name, "secret"))
  7931. strncpy(peer->secret, v->value, sizeof(peer->secret)-1);
  7932. else if (!strcasecmp(v->name, "md5secret"))
  7933. strncpy(peer->md5secret, v->value, sizeof(peer->md5secret)-1);
  7934. else if (!strcasecmp(v->name, "canreinvite")) {
  7935. if (!strcasecmp(v->value, "update"))
  7936. peer->canreinvite = REINVITE_UPDATE;
  7937. else
  7938. peer->canreinvite = ast_true(v->value);
  7939. } else if (!strcasecmp(v->name, "nat")) {
  7940. if (!strcasecmp(v->value, "rfc3581"))
  7941. peer->nat = SIP_NAT_RFC3581;
  7942. else if (!strcasecmp(v->value, "route"))
  7943. peer->nat = SIP_NAT_ROUTE;
  7944. else if (ast_true(v->value))
  7945. peer->nat = SIP_NAT_ALWAYS;
  7946. else
  7947. peer->nat = SIP_NAT_NEVER;
  7948. } else if (!strcasecmp(v->name, "context"))
  7949. strncpy(peer->context, v->value, sizeof(peer->context)-1);
  7950. else if (!strcasecmp(v->name, "fromdomain"))
  7951. strncpy(peer->fromdomain, v->value, sizeof(peer->fromdomain)-1);
  7952. else if (!strcasecmp(v->name, "promiscredir"))
  7953. peer->promiscredir = ast_true(v->value);
  7954. else if (!strcasecmp(v->name, "fromuser"))
  7955. strncpy(peer->fromuser, v->value, sizeof(peer->fromuser)-1);
  7956. else if (!strcasecmp(v->name, "dtmfmode")) {
  7957. if (!strcasecmp(v->value, "inband"))
  7958. peer->dtmfmode=SIP_DTMF_INBAND;
  7959. else if (!strcasecmp(v->value, "rfc2833"))
  7960. peer->dtmfmode = SIP_DTMF_RFC2833;
  7961. else if (!strcasecmp(v->value, "info"))
  7962. peer->dtmfmode = SIP_DTMF_INFO;
  7963. else {
  7964. ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
  7965. peer->dtmfmode = SIP_DTMF_RFC2833;
  7966. }
  7967. } else if (!strcasecmp(v->name, "host")) {
  7968. if (!strcasecmp(v->value, "dynamic")) {
  7969. /* They'll register with us */
  7970. peer->dynamic = 1;
  7971. if (!found) {
  7972. /* Initialize stuff iff we're not found, otherwise
  7973. we keep going with what we had */
  7974. memset(&peer->addr.sin_addr, 0, 4);
  7975. if (peer->addr.sin_port) {
  7976. /* If we've already got a port, make it the default rather than absolute */
  7977. peer->defaddr.sin_port = peer->addr.sin_port;
  7978. peer->addr.sin_port = 0;
  7979. }
  7980. }
  7981. } else {
  7982. /* Non-dynamic. Make sure we become that way if we're not */
  7983. if (peer->expire > -1)
  7984. ast_sched_del(sched, peer->expire);
  7985. peer->expire = -1;
  7986. peer->dynamic = 0;
  7987. if (ast_get_ip(&peer->addr, v->value)) {
  7988. free(peer);
  7989. return NULL;
  7990. }
  7991. strncpy(peer->tohost, v->value, sizeof(peer->tohost) - 1);
  7992. }
  7993. if (!maskfound)
  7994. inet_aton("255.255.255.255", &peer->mask);
  7995. } else if (!strcasecmp(v->name, "defaultip")) {
  7996. if (ast_get_ip(&peer->defaddr, v->value)) {
  7997. free(peer);
  7998. return NULL;
  7999. }
  8000. } else if (!strcasecmp(v->name, "permit") ||
  8001. !strcasecmp(v->name, "deny")) {
  8002. peer->ha = ast_append_ha(v->name, v->value, peer->ha);
  8003. } else if (!strcasecmp(v->name, "mask")) {
  8004. maskfound++;
  8005. inet_aton(v->value, &peer->mask);
  8006. } else if (!strcasecmp(v->name, "port")) {
  8007. if (peer->dynamic)
  8008. peer->defaddr.sin_port = htons(atoi(v->value));
  8009. else
  8010. peer->addr.sin_port = htons(atoi(v->value));
  8011. } else if (!strcasecmp(v->name, "username")) {
  8012. strncpy(peer->username, v->value, sizeof(peer->username)-1);
  8013. } else if (!strcasecmp(v->name, "language")) {
  8014. strncpy(peer->language, v->value, sizeof(peer->language)-1);
  8015. } else if (!strcasecmp(v->name, "regexten")) {
  8016. strncpy(peer->regexten, v->value, sizeof(peer->regexten)-1);
  8017. } else if (!strcasecmp(v->name, "musiconhold")) {
  8018. strncpy(peer->musicclass, v->value, sizeof(peer->musicclass)-1);
  8019. } else if (!strcasecmp(v->name, "mailbox")) {
  8020. strncpy(peer->mailbox, v->value, sizeof(peer->mailbox)-1);
  8021. } else if (!strcasecmp(v->name, "callgroup")) {
  8022. peer->callgroup = ast_get_group(v->value);
  8023. } else if (!strcasecmp(v->name, "pickupgroup")) {
  8024. peer->pickupgroup = ast_get_group(v->value);
  8025. } else if (!strcasecmp(v->name, "allow")) {
  8026. ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
  8027. } else if (!strcasecmp(v->name, "disallow")) {
  8028. ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
  8029. } else if (!strcasecmp(v->name, "insecure")) {
  8030. if (!strcasecmp(v->value, "very")) {
  8031. peer->insecure = 2;
  8032. } else if (ast_true(v->value))
  8033. peer->insecure = 1;
  8034. else
  8035. peer->insecure = 0;
  8036. } else if (!strcasecmp(v->name, "rtptimeout")) {
  8037. if ((sscanf(v->value, "%d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
  8038. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  8039. peer->rtptimeout = global_rtptimeout;
  8040. }
  8041. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  8042. if ((sscanf(v->value, "%d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
  8043. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  8044. peer->rtpholdtimeout = global_rtpholdtimeout;
  8045. }
  8046. } else if (!strcasecmp(v->name, "qualify")) {
  8047. if (!strcasecmp(v->value, "no")) {
  8048. peer->maxms = 0;
  8049. } else if (!strcasecmp(v->value, "yes")) {
  8050. peer->maxms = DEFAULT_MAXMS;
  8051. } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
  8052. ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
  8053. peer->maxms = 0;
  8054. }
  8055. } else if (!strcasecmp(v->name, "trustrpid")) {
  8056. peer->trustrpid = ast_true(v->value);
  8057. } else if (!strcasecmp(v->name, "progressinband")) {
  8058. peer->progressinband = ast_true(v->value);
  8059. #ifdef OSP_SUPPORT
  8060. } else if (!strcasecmp(v->name, "ospauth")) {
  8061. if (!strcasecmp(v->value, "exclusive")) {
  8062. peer->ospauth = 2;
  8063. } else if (ast_true(v->value)) {
  8064. peer->ospauth = 1;
  8065. } else
  8066. peer->ospauth = 0;
  8067. #endif
  8068. }
  8069. /* else if (strcasecmp(v->name,"type"))
  8070. * ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  8071. */
  8072. v=v->next;
  8073. }
  8074. if (!found && peer->dynamic)
  8075. reg_source_db(peer);
  8076. peer->delme = 0;
  8077. }
  8078. if (oldha)
  8079. ast_free_ha(oldha);
  8080. return peer;
  8081. }
  8082. /*--- reload_config: Re-read SIP.conf config file ---*/
  8083. static int reload_config(void)
  8084. {
  8085. struct ast_config *cfg;
  8086. struct ast_variable *v;
  8087. struct sip_peer *peer;
  8088. struct sip_user *user;
  8089. struct ast_hostent ahp;
  8090. char *cat;
  8091. char *utype;
  8092. struct hostent *hp;
  8093. int format;
  8094. int oldport = ntohs(bindaddr.sin_port);
  8095. char iabuf[INET_ADDRSTRLEN];
  8096. global_dtmfmode = SIP_DTMF_RFC2833;
  8097. global_promiscredir = 0;
  8098. cfg = ast_load(config);
  8099. /* We *must* have a config file otherwise stop immediately */
  8100. if (!cfg) {
  8101. ast_log(LOG_NOTICE, "Unable to load config %s, SIP disabled\n", config);
  8102. return 0;
  8103. }
  8104. global_nat = SIP_NAT_RFC3581;
  8105. memset(&bindaddr, 0, sizeof(bindaddr));
  8106. memset(&localaddr, 0, sizeof(localaddr));
  8107. memset(&externip, 0, sizeof(externip));
  8108. memset(&prefs, 0 , sizeof(struct ast_codec_pref));
  8109. /* Initialize some reasonable defaults */
  8110. strncpy(default_context, "default", sizeof(default_context) - 1);
  8111. default_language[0] = '\0';
  8112. default_fromdomain[0] = '\0';
  8113. strncpy(default_useragent, DEFAULT_USERAGENT, sizeof(default_useragent) - 1);
  8114. strncpy(global_realm, "asterisk", sizeof(global_realm) - 1);
  8115. global_realm[sizeof(global_realm)-1] = '\0';
  8116. global_canreinvite = REINVITE_INVITE;
  8117. videosupport = 0;
  8118. relaxdtmf = 0;
  8119. ourport = DEFAULT_SIP_PORT;
  8120. global_rtptimeout = 0;
  8121. global_rtpholdtimeout = 0;
  8122. pedanticsipchecking=0;
  8123. v = ast_variable_browse(cfg, "general");
  8124. while(v) {
  8125. /* Create the interface list */
  8126. if (!strcasecmp(v->name, "context")) {
  8127. strncpy(default_context, v->value, sizeof(default_context)-1);
  8128. } else if (!strcasecmp(v->name, "realm")) {
  8129. strncpy(global_realm, v->value, sizeof(global_realm)-1);
  8130. global_realm[sizeof(global_realm)-1] = '\0';
  8131. } else if (!strcasecmp(v->name, "useragent")) {
  8132. strncpy(default_useragent, v->value, sizeof(default_useragent)-1);
  8133. ast_log(LOG_DEBUG, "Setting User Agent Name to %s\n",
  8134. default_useragent);
  8135. } else if (!strcasecmp(v->name, "relaxdtmf")) {
  8136. relaxdtmf = ast_true(v->value);
  8137. } else if (!strcasecmp(v->name, "promiscredir")) {
  8138. global_promiscredir = ast_true(v->value);
  8139. } else if (!strcasecmp(v->name, "dtmfmode")) {
  8140. if (!strcasecmp(v->value, "inband"))
  8141. global_dtmfmode=SIP_DTMF_INBAND;
  8142. else if (!strcasecmp(v->value, "rfc2833"))
  8143. global_dtmfmode = SIP_DTMF_RFC2833;
  8144. else if (!strcasecmp(v->value, "info"))
  8145. global_dtmfmode = SIP_DTMF_INFO;
  8146. else {
  8147. ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
  8148. global_dtmfmode = SIP_DTMF_RFC2833;
  8149. }
  8150. } else if (!strcasecmp(v->name, "rtptimeout")) {
  8151. if ((sscanf(v->value, "%d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
  8152. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  8153. global_rtptimeout = 0;
  8154. }
  8155. } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
  8156. if ((sscanf(v->value, "%d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
  8157. ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
  8158. global_rtpholdtimeout = 0;
  8159. }
  8160. } else if (!strcasecmp(v->name, "videosupport")) {
  8161. videosupport = ast_true(v->value);
  8162. } else if (!strcasecmp(v->name, "notifymimetype")) {
  8163. strncpy(notifymime, v->value, sizeof(notifymime) - 1);
  8164. } else if (!strcasecmp(v->name, "musicclass")) {
  8165. strncpy(global_musicclass, v->value, sizeof(global_musicclass) - 1);
  8166. } else if (!strcasecmp(v->name, "language")) {
  8167. strncpy(default_language, v->value, sizeof(default_language)-1);
  8168. } else if (!strcasecmp(v->name, "regcontext")) {
  8169. strncpy(regcontext, v->value, sizeof(regcontext) - 1);
  8170. /* Create context if it doesn't exist already */
  8171. if (!ast_context_find(regcontext))
  8172. ast_context_create(NULL, regcontext, type);
  8173. } else if (!strcasecmp(v->name, "callerid")) {
  8174. strncpy(default_callerid, v->value, sizeof(default_callerid)-1);
  8175. } else if (!strcasecmp(v->name, "fromdomain")) {
  8176. strncpy(default_fromdomain, v->value, sizeof(default_fromdomain)-1);
  8177. } else if (!strcasecmp(v->name, "nat")) {
  8178. if (!strcasecmp(v->value, "rfc3581"))
  8179. global_nat = SIP_NAT_RFC3581;
  8180. else if (!strcasecmp(v->value, "route"))
  8181. global_nat = SIP_NAT_ROUTE;
  8182. else if (ast_true(v->value))
  8183. global_nat = SIP_NAT_ALWAYS;
  8184. else
  8185. global_nat = SIP_NAT_NEVER;
  8186. } else if (!strcasecmp(v->name, "autocreatepeer")) {
  8187. autocreatepeer = ast_true(v->value);
  8188. } else if (!strcasecmp(v->name, "srvlookup")) {
  8189. srvlookup = ast_true(v->value);
  8190. } else if (!strcasecmp(v->name, "trustrpid")) {
  8191. global_trustrpid = ast_true(v->value);
  8192. } else if (!strcasecmp(v->name, "progressinband")) {
  8193. global_progressinband = ast_true(v->value);
  8194. #ifdef OSP_SUPPORT
  8195. } else if (!strcasecmp(v->name, "ospauth")) {
  8196. if (!strcasecmp(v->value, "exclusive")) {
  8197. global_ospauth = 2;
  8198. } else if (ast_true(v->value)) {
  8199. global_ospauth = 1;
  8200. } else
  8201. global_ospauth = 0;
  8202. #endif
  8203. } else if (!strcasecmp(v->name, "pedantic")) {
  8204. pedanticsipchecking = ast_true(v->value);
  8205. } else if (!strcasecmp(v->name, "canreinvite")) {
  8206. if (!strcasecmp(v->value, "update"))
  8207. global_canreinvite = REINVITE_UPDATE;
  8208. else
  8209. global_canreinvite = ast_true(v->value);
  8210. } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
  8211. max_expiry = atoi(v->value);
  8212. if (max_expiry < 1)
  8213. max_expiry = DEFAULT_MAX_EXPIRY;
  8214. } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
  8215. default_expiry = atoi(v->value);
  8216. if (default_expiry < 1)
  8217. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  8218. } else if (!strcasecmp(v->name, "bindaddr")) {
  8219. if (!(hp = ast_gethostbyname(v->value, &ahp))) {
  8220. ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
  8221. } else {
  8222. memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
  8223. }
  8224. } else if (!strcasecmp(v->name, "localnet")) {
  8225. struct ast_ha *na;
  8226. if (!(na = ast_append_ha("d", v->value, localaddr)))
  8227. ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
  8228. else
  8229. localaddr = na;
  8230. } else if (!strcasecmp(v->name, "localmask")) {
  8231. ast_log(LOG_WARNING, "Use of localmask is no long supported -- use localnet with mask syntax\n");
  8232. } else if (!strcasecmp(v->name, "externip")) {
  8233. if (!(hp = ast_gethostbyname(v->value, &ahp)))
  8234. ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
  8235. else
  8236. memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
  8237. } else if (!strcasecmp(v->name, "allow")) {
  8238. ast_parse_allow_disallow(&prefs, &global_capability, v->value, 1);
  8239. } else if (!strcasecmp(v->name, "disallow")) {
  8240. ast_parse_allow_disallow(&prefs, &global_capability, v->value, 0);
  8241. } else if (!strcasecmp(v->name, "register")) {
  8242. sip_register(v->value, v->lineno);
  8243. } else if (!strcasecmp(v->name, "recordhistory")) {
  8244. recordhistory = ast_true(v->value);
  8245. } else if (!strcasecmp(v->name, "tos")) {
  8246. if (sscanf(v->value, "%i", &format) == 1)
  8247. tos = format & 0xff;
  8248. else if (!strcasecmp(v->value, "lowdelay"))
  8249. tos = IPTOS_LOWDELAY;
  8250. else if (!strcasecmp(v->value, "throughput"))
  8251. tos = IPTOS_THROUGHPUT;
  8252. else if (!strcasecmp(v->value, "reliability"))
  8253. tos = IPTOS_RELIABILITY;
  8254. else if (!strcasecmp(v->value, "mincost"))
  8255. tos = IPTOS_MINCOST;
  8256. else if (!strcasecmp(v->value, "none"))
  8257. tos = 0;
  8258. else
  8259. ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
  8260. } else if (!strcasecmp(v->name, "port")) {
  8261. if (sscanf(v->value, "%i", &ourport) == 1) {
  8262. bindaddr.sin_port = htons(ourport);
  8263. } else {
  8264. ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
  8265. }
  8266. #ifdef MYSQL_FRIENDS
  8267. } else if (!strcasecmp(v->name, "dbuser")) {
  8268. strncpy(mydbuser, v->value, sizeof(mydbuser) - 1);
  8269. } else if (!strcasecmp(v->name, "dbpass")) {
  8270. strncpy(mydbpass, v->value, sizeof(mydbpass) - 1);
  8271. } else if (!strcasecmp(v->name, "dbhost")) {
  8272. strncpy(mydbhost, v->value, sizeof(mydbhost) - 1);
  8273. } else if (!strcasecmp(v->name, "dbname")) {
  8274. strncpy(mydbname, v->value, sizeof(mydbname) - 1);
  8275. #endif
  8276. }
  8277. /* else if (strcasecmp(v->name,"type"))
  8278. * ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  8279. */
  8280. v = v->next;
  8281. }
  8282. cat = ast_category_browse(cfg, NULL);
  8283. while(cat) {
  8284. if (strcasecmp(cat, "general")) {
  8285. utype = ast_variable_retrieve(cfg, cat, "type");
  8286. if (utype) {
  8287. if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
  8288. user = build_user(cat, ast_variable_browse(cfg, cat));
  8289. if (user) {
  8290. ast_mutex_lock(&userl.lock);
  8291. user->next = userl.users;
  8292. userl.users = user;
  8293. ast_mutex_unlock(&userl.lock);
  8294. }
  8295. }
  8296. if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
  8297. peer = build_peer(cat, ast_variable_browse(cfg, cat));
  8298. if (peer) {
  8299. ast_mutex_lock(&peerl.lock);
  8300. peer->next = peerl.peers;
  8301. peerl.peers = peer;
  8302. ast_mutex_unlock(&peerl.lock);
  8303. }
  8304. } else if (strcasecmp(utype, "user")) {
  8305. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
  8306. }
  8307. } else
  8308. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  8309. }
  8310. cat = ast_category_browse(cfg, cat);
  8311. }
  8312. if (ast_find_ourip(&__ourip, bindaddr)) {
  8313. ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
  8314. return 0;
  8315. }
  8316. if (!ntohs(bindaddr.sin_port))
  8317. bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
  8318. bindaddr.sin_family = AF_INET;
  8319. ast_mutex_lock(&netlock);
  8320. if ((sipsock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
  8321. close(sipsock);
  8322. sipsock = -1;
  8323. }
  8324. if (sipsock < 0) {
  8325. sipsock = socket(AF_INET, SOCK_DGRAM, 0);
  8326. if (sipsock < 0) {
  8327. ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
  8328. } else {
  8329. /* Allow SIP clients on the same host to access us: */
  8330. const int reuseFlag = 1;
  8331. setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
  8332. (const char*)&reuseFlag,
  8333. sizeof reuseFlag);
  8334. if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
  8335. ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
  8336. ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
  8337. strerror(errno));
  8338. close(sipsock);
  8339. sipsock = -1;
  8340. } else {
  8341. if (option_verbose > 1) {
  8342. ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
  8343. ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port));
  8344. ast_verbose(VERBOSE_PREFIX_2 "Using TOS bits %d\n", tos);
  8345. }
  8346. if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))
  8347. ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
  8348. }
  8349. }
  8350. }
  8351. ast_mutex_unlock(&netlock);
  8352. ast_destroy(cfg);
  8353. #ifdef MYSQL_FRIENDS
  8354. /* Connect to db if appropriate */
  8355. if (!mysql && !ast_strlen_zero(mydbname)) {
  8356. mysql = mysql_init(NULL);
  8357. if (!mysql_real_connect(mysql, mydbhost[0] ? mydbhost : NULL, mydbuser, mydbpass, mydbname, 0, NULL, 0)) {
  8358. memset(mydbpass, '*', strlen(mydbpass));
  8359. ast_log(LOG_WARNING, "Database connection failed (db=%s, host=%s, user=%s, pass=%s)!\n",
  8360. mydbname, mydbhost, mydbuser, mydbpass);
  8361. free(mysql);
  8362. mysql = NULL;
  8363. } else
  8364. ast_verbose(VERBOSE_PREFIX_1 "Connected to database '%s' on '%s' as '%s'\n",
  8365. mydbname, mydbhost, mydbuser);
  8366. }
  8367. #endif
  8368. return 0;
  8369. }
  8370. static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan)
  8371. {
  8372. struct sip_pvt *p;
  8373. struct ast_rtp *rtp = NULL;
  8374. p = chan->pvt->pvt;
  8375. if (p) {
  8376. ast_mutex_lock(&p->lock);
  8377. if (p->rtp && p->canreinvite)
  8378. rtp = p->rtp;
  8379. ast_mutex_unlock(&p->lock);
  8380. }
  8381. return rtp;
  8382. }
  8383. static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan)
  8384. {
  8385. struct sip_pvt *p;
  8386. struct ast_rtp *rtp = NULL;
  8387. p = chan->pvt->pvt;
  8388. if (p) {
  8389. ast_mutex_lock(&p->lock);
  8390. if (p->vrtp && p->canreinvite)
  8391. rtp = p->vrtp;
  8392. ast_mutex_unlock(&p->lock);
  8393. }
  8394. return rtp;
  8395. }
  8396. /*--- sip_set_rtp_peer: Set the RTP peer for this call ---*/
  8397. static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
  8398. {
  8399. struct sip_pvt *p;
  8400. p = chan->pvt->pvt;
  8401. if (p) {
  8402. ast_mutex_lock(&p->lock);
  8403. if (rtp)
  8404. ast_rtp_get_peer(rtp, &p->redirip);
  8405. else
  8406. memset(&p->redirip, 0, sizeof(p->redirip));
  8407. if (vrtp)
  8408. ast_rtp_get_peer(vrtp, &p->vredirip);
  8409. else
  8410. memset(&p->vredirip, 0, sizeof(p->vredirip));
  8411. p->redircodecs = codecs;
  8412. if (!p->gotrefer) {
  8413. if (!p->pendinginvite)
  8414. transmit_reinvite_with_sdp(p);
  8415. else if (!p->pendingbye) {
  8416. ast_log(LOG_DEBUG, "Deferring reinvite on '%s'\n", p->callid);
  8417. p->needreinvite = 1;
  8418. }
  8419. }
  8420. /* Reset lastrtprx timer */
  8421. time(&p->lastrtprx);
  8422. ast_mutex_unlock(&p->lock);
  8423. return 0;
  8424. }
  8425. return -1;
  8426. }
  8427. static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
  8428. static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
  8429. static char *app_dtmfmode = "SIPDtmfMode";
  8430. /*--- sip_dtmfmode: change the DTMFmode for a SIP call (application) ---*/
  8431. static int sip_dtmfmode(struct ast_channel *chan, void *data)
  8432. {
  8433. struct sip_pvt *p;
  8434. char *mode;
  8435. if (data)
  8436. mode = (char *)data;
  8437. else {
  8438. ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
  8439. return 0;
  8440. }
  8441. ast_mutex_lock(&chan->lock);
  8442. if (chan->type != type) {
  8443. ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
  8444. ast_mutex_unlock(&chan->lock);
  8445. return 0;
  8446. }
  8447. p = chan->pvt->pvt;
  8448. if (p) {
  8449. ast_mutex_lock(&p->lock);
  8450. if (!strcasecmp(mode,"info"))
  8451. p->dtmfmode = SIP_DTMF_INFO;
  8452. else if (!strcasecmp(mode,"rfc2833"))
  8453. p->dtmfmode = SIP_DTMF_RFC2833;
  8454. else if (!strcasecmp(mode,"inband"))
  8455. p->dtmfmode = SIP_DTMF_INBAND;
  8456. else
  8457. ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
  8458. if (p->dtmfmode & SIP_DTMF_INBAND) {
  8459. if (!p->vad) {
  8460. p->vad = ast_dsp_new();
  8461. ast_dsp_set_features(p->vad, DSP_FEATURE_DTMF_DETECT);
  8462. }
  8463. } else {
  8464. if (p->vad) {
  8465. ast_dsp_free(p->vad);
  8466. p->vad = NULL;
  8467. }
  8468. }
  8469. ast_mutex_unlock(&p->lock);
  8470. }
  8471. ast_mutex_unlock(&chan->lock);
  8472. return 0;
  8473. }
  8474. static int sip_get_codec(struct ast_channel *chan)
  8475. {
  8476. struct sip_pvt *p = chan->pvt->pvt;
  8477. return p->peercapability;
  8478. }
  8479. static struct ast_rtp_protocol sip_rtp = {
  8480. get_rtp_info: sip_get_rtp_peer,
  8481. get_vrtp_info: sip_get_vrtp_peer,
  8482. set_rtp_peer: sip_set_rtp_peer,
  8483. get_codec: sip_get_codec,
  8484. };
  8485. /*--- delete_users: Delete all registred users ---*/
  8486. /* Also, check registations with other SIP proxies */
  8487. static void delete_users(void)
  8488. {
  8489. struct sip_user *user, *userlast;
  8490. struct sip_peer *peer;
  8491. struct sip_registry *reg, *regn;
  8492. /* Delete all users */
  8493. ast_mutex_lock(&userl.lock);
  8494. for (user=userl.users;user;) {
  8495. ast_free_ha(user->ha);
  8496. userlast = user;
  8497. user=user->next;
  8498. free(userlast);
  8499. }
  8500. userl.users=NULL;
  8501. ast_mutex_unlock(&userl.lock);
  8502. ast_mutex_lock(&regl.lock);
  8503. for (reg = regl.registrations;reg;) {
  8504. regn = reg->next;
  8505. /* Really delete */
  8506. if (reg->call) {
  8507. /* Clear registry before destroying to ensure
  8508. we don't get reentered trying to grab the registry lock */
  8509. reg->call->registry = NULL;
  8510. sip_destroy(reg->call);
  8511. }
  8512. if (reg->expire > -1)
  8513. ast_sched_del(sched, reg->expire);
  8514. if (reg->timeout > -1)
  8515. ast_sched_del(sched, reg->timeout);
  8516. free(reg);
  8517. reg = regn;
  8518. }
  8519. regl.registrations = NULL;
  8520. ast_mutex_unlock(&regl.lock);
  8521. ast_mutex_lock(&peerl.lock);
  8522. for (peer=peerl.peers;peer;) {
  8523. /* Assume all will be deleted, and we'll find out for sure later */
  8524. peer->delme = 1;
  8525. peer = peer->next;
  8526. }
  8527. ast_mutex_unlock(&peerl.lock);
  8528. }
  8529. /*--- prune_peers: Delete all peers marked for deletion ---*/
  8530. static void prune_peers(void)
  8531. {
  8532. /* Prune peers who still are supposed to be deleted */
  8533. struct sip_peer *peer, *peerlast, *peernext;
  8534. ast_mutex_lock(&peerl.lock);
  8535. peerlast = NULL;
  8536. for (peer=peerl.peers;peer;) {
  8537. peernext = peer->next;
  8538. if (peer->delme) {
  8539. /* Delete it, it needs to disappear */
  8540. if (peer->call)
  8541. sip_destroy(peer->call);
  8542. if (peer->expire > -1)
  8543. ast_sched_del(sched, peer->expire);
  8544. if (peer->pokeexpire > -1)
  8545. ast_sched_del(sched, peer->pokeexpire);
  8546. register_peer_exten(peer, 0);
  8547. free(peer);
  8548. if (peerlast)
  8549. peerlast->next = peernext;
  8550. else
  8551. peerl.peers = peernext;
  8552. } else
  8553. peerlast = peer;
  8554. peer=peernext;
  8555. }
  8556. ast_mutex_unlock(&peerl.lock);
  8557. }
  8558. /* Send all of our registrations, spaced out to avoid suicide*/
  8559. static void sip_send_all_registers(void)
  8560. {
  8561. struct sip_registry *reg;
  8562. int ms;
  8563. ast_mutex_lock(&regl.lock);
  8564. for (reg = regl.registrations; reg; reg = reg->next) {
  8565. if (reg->expire > -1)
  8566. ast_sched_del(sched, reg->expire);
  8567. ms = (rand() >> 12) & 0x1fff;
  8568. reg->expire = ast_sched_add(sched, ms, sip_reregister, reg);
  8569. }
  8570. ast_mutex_unlock(&regl.lock);
  8571. }
  8572. /*--- sip_do_reload: Reload module */
  8573. static int sip_do_reload(void)
  8574. {
  8575. struct sip_peer *peer;
  8576. delete_users();
  8577. reload_config();
  8578. prune_peers();
  8579. sip_send_all_registers();
  8580. ast_mutex_lock(&peerl.lock);
  8581. for (peer = peerl.peers; peer; peer = peer->next)
  8582. sip_poke_peer(peer);
  8583. ast_mutex_unlock(&peerl.lock);
  8584. return 0;
  8585. }
  8586. /*--- sip_reload: Force reload of module from cli ---*/
  8587. static int sip_reload(int fd, int argc, char *argv[])
  8588. {
  8589. ast_mutex_lock(&sip_reload_lock);
  8590. if (sip_reloading) {
  8591. ast_verbose("Previous SIP reload not yet done\n");
  8592. } else
  8593. sip_reloading = 1;
  8594. ast_mutex_unlock(&sip_reload_lock);
  8595. restart_monitor();
  8596. return 0;
  8597. }
  8598. int reload(void)
  8599. {
  8600. return sip_reload(0, 0, NULL);
  8601. }
  8602. static struct ast_cli_entry cli_sip_reload =
  8603. { { "sip", "reload", NULL }, sip_reload, "Reload SIP configuration", sip_reload_usage };
  8604. /*--- load_module: PBX load module - initialization ---*/
  8605. int load_module()
  8606. {
  8607. int res;
  8608. struct sip_peer *peer;
  8609. ast_mutex_init(&userl.lock);
  8610. ast_mutex_init(&peerl.lock);
  8611. ast_mutex_init(&regl.lock);
  8612. sched = sched_context_create();
  8613. if (!sched) {
  8614. ast_log(LOG_WARNING, "Unable to create schedule context\n");
  8615. }
  8616. io = io_context_create();
  8617. if (!io) {
  8618. ast_log(LOG_WARNING, "Unable to create I/O context\n");
  8619. }
  8620. res = reload_config();
  8621. if (!res) {
  8622. /* Make sure we can register our sip channel type */
  8623. if (ast_channel_register_ex(type, tdesc, ((AST_FORMAT_MAX_AUDIO << 1) - 1), sip_request, sip_devicestate)) {
  8624. ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
  8625. return -1;
  8626. }
  8627. ast_cli_register(&cli_show_users);
  8628. ast_cli_register(&cli_show_subscriptions);
  8629. ast_cli_register(&cli_show_channels);
  8630. ast_cli_register(&cli_show_channel);
  8631. ast_cli_register(&cli_show_history);
  8632. ast_cli_register(&cli_show_peer);
  8633. ast_cli_register(&cli_show_peers);
  8634. ast_cli_register(&cli_show_peers_begin);
  8635. ast_cli_register(&cli_show_peers_include);
  8636. ast_cli_register(&cli_show_peers_exclude);
  8637. ast_cli_register(&cli_show_registry);
  8638. ast_cli_register(&cli_debug);
  8639. ast_cli_register(&cli_debug_ip);
  8640. ast_cli_register(&cli_debug_peer);
  8641. ast_cli_register(&cli_no_debug);
  8642. ast_cli_register(&cli_history);
  8643. ast_cli_register(&cli_no_history);
  8644. ast_cli_register(&cli_sip_reload);
  8645. ast_cli_register(&cli_inuse_show);
  8646. sip_rtp.type = type;
  8647. ast_rtp_proto_register(&sip_rtp);
  8648. ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
  8649. ast_mutex_lock(&peerl.lock);
  8650. for (peer = peerl.peers; peer; peer = peer->next)
  8651. sip_poke_peer(peer);
  8652. ast_mutex_unlock(&peerl.lock);
  8653. sip_send_all_registers();
  8654. /* And start the monitor for the first time */
  8655. restart_monitor();
  8656. }
  8657. return res;
  8658. }
  8659. int unload_module()
  8660. {
  8661. struct sip_pvt *p, *pl;
  8662. /* First, take us out of the channel loop */
  8663. ast_unregister_application(app_dtmfmode);
  8664. ast_cli_unregister(&cli_show_users);
  8665. ast_cli_unregister(&cli_show_channels);
  8666. ast_cli_unregister(&cli_show_channel);
  8667. ast_cli_unregister(&cli_show_history);
  8668. ast_cli_unregister(&cli_show_peer);
  8669. ast_cli_unregister(&cli_show_peers);
  8670. ast_cli_unregister(&cli_show_peers_include);
  8671. ast_cli_unregister(&cli_show_peers_exclude);
  8672. ast_cli_unregister(&cli_show_peers_begin);
  8673. ast_cli_unregister(&cli_show_registry);
  8674. ast_cli_unregister(&cli_show_subscriptions);
  8675. ast_cli_unregister(&cli_debug);
  8676. ast_cli_unregister(&cli_debug_ip);
  8677. ast_cli_unregister(&cli_debug_peer);
  8678. ast_cli_unregister(&cli_no_debug);
  8679. ast_cli_unregister(&cli_history);
  8680. ast_cli_unregister(&cli_no_history);
  8681. ast_cli_unregister(&cli_sip_reload);
  8682. ast_cli_unregister(&cli_inuse_show);
  8683. ast_rtp_proto_unregister(&sip_rtp);
  8684. ast_channel_unregister(type);
  8685. if (!ast_mutex_lock(&iflock)) {
  8686. /* Hangup all interfaces if they have an owner */
  8687. p = iflist;
  8688. while(p) {
  8689. if (p->owner)
  8690. ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
  8691. p = p->next;
  8692. }
  8693. iflist = NULL;
  8694. ast_mutex_unlock(&iflock);
  8695. } else {
  8696. ast_log(LOG_WARNING, "Unable to lock the interface list\n");
  8697. return -1;
  8698. }
  8699. if (!ast_mutex_lock(&monlock)) {
  8700. if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
  8701. pthread_cancel(monitor_thread);
  8702. pthread_kill(monitor_thread, SIGURG);
  8703. pthread_join(monitor_thread, NULL);
  8704. }
  8705. monitor_thread = AST_PTHREADT_STOP;
  8706. ast_mutex_unlock(&monlock);
  8707. } else {
  8708. ast_log(LOG_WARNING, "Unable to lock the monitor\n");
  8709. return -1;
  8710. }
  8711. if (!ast_mutex_lock(&iflock)) {
  8712. /* Destroy all the interfaces and free their memory */
  8713. p = iflist;
  8714. while(p) {
  8715. pl = p;
  8716. p = p->next;
  8717. /* Free associated memory */
  8718. ast_mutex_destroy(&pl->lock);
  8719. free(pl);
  8720. }
  8721. iflist = NULL;
  8722. ast_mutex_unlock(&iflock);
  8723. } else {
  8724. ast_log(LOG_WARNING, "Unable to lock the interface list\n");
  8725. return -1;
  8726. }
  8727. /* Free memory for local network address mask */
  8728. if (localaddr) {
  8729. ast_free_ha(localaddr);
  8730. }
  8731. ast_mutex_destroy(&userl.lock);
  8732. ast_mutex_destroy(&peerl.lock);
  8733. ast_mutex_destroy(&regl.lock);
  8734. close(sipsock);
  8735. return 0;
  8736. }
  8737. int usecount()
  8738. {
  8739. int res;
  8740. ast_mutex_lock(&usecnt_lock);
  8741. res = usecnt;
  8742. ast_mutex_unlock(&usecnt_lock);
  8743. return res;
  8744. }
  8745. char *key()
  8746. {
  8747. return ASTERISK_GPL_KEY;
  8748. }
  8749. char *description()
  8750. {
  8751. return desc;
  8752. }