chan_sip.c 198 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979
  1. /*
  2. * Asterisk -- A telephony toolkit for Linux.
  3. *
  4. * Implementation of Session Initiation Protocol
  5. *
  6. * Copyright (C) 1999, Mark Spencer
  7. *
  8. * Mark Spencer <markster@linux-support.net>
  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 <pthread.h>
  16. #include <string.h>
  17. #include <asterisk/lock.h>
  18. #include <asterisk/channel.h>
  19. #include <asterisk/channel_pvt.h>
  20. #include <asterisk/config.h>
  21. #include <asterisk/logger.h>
  22. #include <asterisk/module.h>
  23. #include <asterisk/pbx.h>
  24. #include <asterisk/options.h>
  25. #include <asterisk/lock.h>
  26. #include <asterisk/sched.h>
  27. #include <asterisk/io.h>
  28. #include <asterisk/rtp.h>
  29. #include <asterisk/acl.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/parking.h>
  37. #include <asterisk/acl.h>
  38. #include <asterisk/srv.h>
  39. #include <asterisk/astdb.h>
  40. #include <asterisk/causes.h>
  41. #include <sys/socket.h>
  42. #include <sys/ioctl.h>
  43. #include <net/if.h>
  44. #include <errno.h>
  45. #include <unistd.h>
  46. #include <stdlib.h>
  47. #include <fcntl.h>
  48. #include <netdb.h>
  49. #include <arpa/inet.h>
  50. #include <pthread.h>
  51. #include <signal.h>
  52. #include <sys/signal.h>
  53. #include <netinet/in_systm.h>
  54. #include <netinet/ip.h>
  55. #ifdef SIP_MYSQL_FRIENDS
  56. #define MYSQL_FRIENDS
  57. #include <mysql/mysql.h>
  58. #endif
  59. #ifndef IPTOS_MINCOST
  60. #define IPTOS_MINCOST 0x02
  61. #endif
  62. /* #define VOCAL_DATA_HACK */
  63. #define SIPDUMPER
  64. #define DEFAULT_DEFAULT_EXPIRY 120
  65. #define DEFAULT_MAX_EXPIRY 3600
  66. #define EXPIRY_GUARD_SECS 15
  67. #define CALLERID_UNKNOWN "Unknown"
  68. #define SIP_DTMF_RFC2833 (1 << 0)
  69. #define SIP_DTMF_INBAND (1 << 1)
  70. #define SIP_DTMF_INFO (1 << 2)
  71. static int max_expiry = DEFAULT_MAX_EXPIRY;
  72. static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
  73. #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
  74. #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
  75. #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
  76. #define DEFAULT_RETRANS 1000 /* How frequently to retransmit */
  77. #define MAX_RETRANS 5 /* Try only 5 times for retransmissions */
  78. #ifdef MYSQL_FRIENDS
  79. static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
  80. static MYSQL *mysql;
  81. static char mydbuser[80];
  82. static char mydbpass[80];
  83. static char mydbhost[80];
  84. static char mydbname[80];
  85. #endif
  86. static char *desc = "Session Initiation Protocol (SIP)";
  87. static char *type = "SIP";
  88. static char *tdesc = "Session Initiation Protocol (SIP)";
  89. static char *config = "sip.conf";
  90. #define DEFAULT_SIP_PORT 5060 /* From RFC 2543 */
  91. #define SIP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
  92. #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
  93. static char context[AST_MAX_EXTENSION] = "default";
  94. static char language[MAX_LANGUAGE] = "";
  95. static char callerid[AST_MAX_EXTENSION] = "asterisk";
  96. static char fromdomain[AST_MAX_EXTENSION] = "";
  97. static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
  98. static int srvlookup = 0;
  99. static int pedanticsipchecking = 0;
  100. static int autocreatepeer = 0;
  101. static int usecnt =0;
  102. static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
  103. /* Protect the interface list (of sip_pvt's) */
  104. static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
  105. /* Protect the monitoring thread, so only one process can kill or start it, and not
  106. when it's doing something critical. */
  107. static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
  108. static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
  109. /* This is the thread for the monitor which checks for input on the channels
  110. which are not currently in use. */
  111. static pthread_t monitor_thread = AST_PTHREADT_NULL;
  112. static int restart_monitor(void);
  113. /* Codecs that we support by default: */
  114. static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
  115. static int noncodeccapability = AST_RTP_DTMF;
  116. static char ourhost[256];
  117. static struct in_addr __ourip;
  118. static int ourport;
  119. static int sipdebug = 0;
  120. static int tos = 0;
  121. static int videosupport = 0;
  122. static int globaldtmfmode = SIP_DTMF_RFC2833;
  123. /* Expire slowly */
  124. static int expiry = 900;
  125. static struct sched_context *sched;
  126. static struct io_context *io;
  127. /* The private structures of the sip channels are linked for
  128. selecting outgoing channels */
  129. #define SIP_MAX_HEADERS 64
  130. #define SIP_MAX_LINES 64
  131. #define DEC_IN_USE 0
  132. #define INC_IN_USE 1
  133. #define DEC_OUT_USE 2
  134. #define INC_OUT_USE 3
  135. static struct sip_codec_pref {
  136. int codec;
  137. struct sip_codec_pref *next;
  138. } *prefs;
  139. struct sip_request {
  140. char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
  141. char *rlPart2; /* The Request URI or Response Status */
  142. int len;
  143. int headers; /* SIP Headers */
  144. char *header[SIP_MAX_HEADERS];
  145. int lines; /* SDP Content */
  146. char *line[SIP_MAX_LINES];
  147. char data[SIP_MAX_PACKET];
  148. };
  149. struct sip_pkt;
  150. struct sip_route {
  151. struct sip_route *next;
  152. char hop[0];
  153. };
  154. static struct sip_pvt {
  155. ast_mutex_t lock; /* Channel private lock */
  156. char callid[80]; /* Global CallID */
  157. char randdata[80]; /* Random data */
  158. unsigned int ocseq; /* Current outgoing seqno */
  159. unsigned int icseq; /* Current incoming seqno */
  160. unsigned int callgroup;
  161. unsigned int pickupgroup;
  162. int lastinvite; /* Last Cseq of invite */
  163. int alreadygone; /* Whether or not we've already been destroyed by or peer */
  164. int needdestroy; /* if we need to be destroyed */
  165. int capability; /* Special capability */
  166. int jointcapability; /* Supported capability at both ends */
  167. int noncodeccapability;
  168. int outgoing; /* Outgoing or incoming call? */
  169. int authtries; /* Times we've tried to authenticate */
  170. int insecure; /* Don't check source port/ip */
  171. int expiry; /* How long we take to expire */
  172. int branch; /* One random number */
  173. int canreinvite; /* Do we support reinvite */
  174. int ringing; /* Have sent 180 ringing */
  175. int progress; /* Have sent 183 message progress */
  176. int tag; /* Another random number */
  177. int nat; /* Whether to try to support NAT */
  178. int sessionid; /* SDP Session ID */
  179. int sessionversion; /* SDP Session Version */
  180. struct sockaddr_in sa; /* Our peer */
  181. struct sockaddr_in redirip; /* Where our RTP should be going if not to us */
  182. struct sockaddr_in vredirip; /* Where our Video RTP should be going if not to us */
  183. struct sockaddr_in recv; /* Received as */
  184. struct in_addr ourip; /* Our IP */
  185. struct ast_channel *owner; /* Who owns us */
  186. char exten[AST_MAX_EXTENSION]; /* Extention where to start */
  187. char refer_to[AST_MAX_EXTENSION]; /* Place to store REFER-TO extension */
  188. char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
  189. char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
  190. struct sip_pvt *refer_call; /* Call we are referring */
  191. struct sip_route *route; /* Head of linked list of routing steps (fm Record-Route) */
  192. char remote_party_id[256];
  193. char from[256];
  194. char context[AST_MAX_EXTENSION];
  195. char fromdomain[AST_MAX_EXTENSION]; /* Domain to show in the from field */
  196. char fromuser[AST_MAX_EXTENSION]; /* Domain to show in the user field */
  197. char tohost[AST_MAX_EXTENSION]; /* Host we should put in the "to" field */
  198. char language[MAX_LANGUAGE];
  199. char rdnis[256]; /* Referring DNIS */
  200. char theirtag[256]; /* Their tag */
  201. char username[256];
  202. char peername[256];
  203. char uri[256]; /* Original requested URI */
  204. char peersecret[256];
  205. char peermd5secret[256];
  206. char callerid[256]; /* Caller*ID */
  207. int restrictcid; /* hide presentation from remote user */
  208. char via[256];
  209. char accountcode[20]; /* Account code */
  210. char our_contact[256]; /* Our contact header */
  211. char realm[256]; /* Authorization realm */
  212. char nonce[256]; /* Authorization nonce */
  213. char opaque[256]; /* Opaque nonsense */
  214. char domain[256]; /* Authorization nonce */
  215. char lastmsg[256]; /* Last Message sent/received */
  216. int amaflags; /* AMA Flags */
  217. int pendinginvite; /* Any pending invite */
  218. int pendingbye; /* Need to send bye after we ack? */
  219. int gotrefer; /* Got a refer? */
  220. struct sip_request initreq; /* Initial request */
  221. int maxtime; /* Max time for first response */
  222. int initid; /* Auto-congest ID if appropriate */
  223. int autokillid; /* Auto-kill ID */
  224. int subscribed;
  225. int stateid;
  226. int dialogver;
  227. int dtmfmode;
  228. struct ast_dsp *vad;
  229. struct sip_peer *peerpoke; /* If this calls is to poke a peer, which one */
  230. struct sip_registry *registry; /* If this is a REGISTER call, to which registry */
  231. struct ast_rtp *rtp; /* RTP Session */
  232. struct ast_rtp *vrtp; /* Video RTP session */
  233. struct sip_pkt *packets; /* Packets scheduled for re-transmission */
  234. struct sip_pvt *next;
  235. } *iflist = NULL;
  236. struct sip_pkt {
  237. struct sip_pkt *next; /* Next packet */
  238. int retrans; /* Retransmission number */
  239. int seqno; /* Sequence number */
  240. int resp; /* non-zero if this is a response packet (e.g. 200 OK) */
  241. struct sip_pvt *owner; /* Owner call */
  242. int retransid; /* Retransmission ID */
  243. int packetlen; /* Length of packet */
  244. char data[0];
  245. };
  246. struct sip_user {
  247. /* Users who can access various contexts */
  248. char name[80];
  249. char secret[80];
  250. char md5secret[80];
  251. char context[80];
  252. char callerid[80];
  253. char methods[80];
  254. char accountcode[20];
  255. char language[MAX_LANGUAGE];
  256. unsigned int callgroup;
  257. unsigned int pickupgroup;
  258. int nat;
  259. int hascallerid;
  260. int amaflags;
  261. int insecure;
  262. int canreinvite;
  263. int capability;
  264. int dtmfmode;
  265. int inUse;
  266. int incominglimit;
  267. int outUse;
  268. int outgoinglimit;
  269. int restrictcid;
  270. struct ast_ha *ha;
  271. struct sip_user *next;
  272. };
  273. struct sip_peer {
  274. char name[80];
  275. char secret[80];
  276. char md5secret[80];
  277. char context[80]; /* JK02: peers need context too to allow parking etc */
  278. char methods[80];
  279. char username[80];
  280. char tohost[80];
  281. char fromuser[80];
  282. char fromdomain[80];
  283. char mailbox[AST_MAX_EXTENSION];
  284. int lastmsgssent;
  285. time_t lastmsgcheck;
  286. int dynamic;
  287. int expire;
  288. int expiry;
  289. int capability;
  290. int insecure;
  291. int nat;
  292. int canreinvite;
  293. unsigned int callgroup;
  294. unsigned int pickupgroup;
  295. int dtmfmode;
  296. struct sockaddr_in addr;
  297. struct in_addr mask;
  298. /* Qualification */
  299. struct sip_pvt *call; /* Call pointer */
  300. int pokeexpire; /* When to expire poke */
  301. int lastms; /* How long last response took (in ms), or -1 for no response */
  302. int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
  303. struct timeval ps; /* Ping send time */
  304. struct sockaddr_in defaddr;
  305. struct ast_ha *ha;
  306. int delme;
  307. int selfdestruct;
  308. int lastmsg;
  309. int temponly;
  310. struct sip_peer *next;
  311. };
  312. static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
  313. static int sip_reloading = 0;
  314. #define REG_STATE_UNREGISTERED 0
  315. #define REG_STATE_REGSENT 1
  316. #define REG_STATE_AUTHSENT 2
  317. #define REG_STATE_REGISTERED 3
  318. #define REG_STATE_REJECTED 4
  319. #define REG_STATE_TIMEOUT 5
  320. #define REG_STATE_NOAUTH 6
  321. struct sip_registry {
  322. struct sockaddr_in addr; /* Who we connect to for registration purposes */
  323. char username[80]; /* Who we are registering as */
  324. char authuser[80]; /* Who we *authenticate* as */
  325. char hostname[80];
  326. char secret[80]; /* Password or key name in []'s */
  327. char md5secret[80];
  328. char contact[80]; /* Contact extension */
  329. char random[80];
  330. int expire; /* Sched ID of expiration */
  331. int timeout; /* sched id of sip_reg_timeout */
  332. int refresh; /* How often to refresh */
  333. struct sip_pvt *call; /* create a sip_pvt structure for each outbound "registration call" in progress */
  334. int regstate;
  335. int callid_valid; /* 0 means we haven't chosen callid for this registry yet. */
  336. char callid[80]; /* Global CallID for this registry */
  337. unsigned int ocseq; /* Sequence number we got to for REGISTERs for this registry */
  338. struct sockaddr_in us; /* Who the server thinks we are */
  339. struct sip_registry *next;
  340. };
  341. static struct ast_user_list {
  342. struct sip_user *users;
  343. ast_mutex_t lock;
  344. } userl = { NULL, AST_MUTEX_INITIALIZER };
  345. static struct ast_peer_list {
  346. struct sip_peer *peers;
  347. ast_mutex_t lock;
  348. } peerl = { NULL, AST_MUTEX_INITIALIZER };
  349. static struct ast_register_list {
  350. struct sip_registry *registrations;
  351. ast_mutex_t lock;
  352. int recheck;
  353. } regl = { NULL, AST_MUTEX_INITIALIZER };
  354. #define REINVITE_INVITE 1
  355. #define REINVITE_UPDATE 2
  356. static int __sip_do_register(struct sip_registry *r);
  357. static int sipsock = -1;
  358. static int globalnat = 0;
  359. static int globalcanreinvite = REINVITE_INVITE;
  360. static struct sockaddr_in bindaddr;
  361. static struct sockaddr_in localnet;
  362. static struct sockaddr_in localmask;
  363. static struct sockaddr_in externip;
  364. static struct ast_frame *sip_read(struct ast_channel *ast);
  365. static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
  366. static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
  367. static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
  368. static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
  369. static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
  370. static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
  371. static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
  372. static int transmit_info_with_digit(struct sip_pvt *p, char digit);
  373. static int transmit_message_with_text(struct sip_pvt *p, char *text);
  374. static int transmit_refer(struct sip_pvt *p, char *dest);
  375. static struct sip_peer *temp_peer(char *name);
  376. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
  377. // static char *getsipuri(char *header);
  378. static void free_old_route(struct sip_route *route);
  379. static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
  380. static int find_user(struct sip_pvt *fup, int event);
  381. static void prune_peers(void);
  382. static int sip_do_reload(void);
  383. static int __sip_xmit(struct sip_pvt *p, char *data, int len)
  384. {
  385. int res;
  386. if (p->nat)
  387. res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
  388. else
  389. res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
  390. if (res != len) {
  391. ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
  392. }
  393. return res;
  394. }
  395. static void sip_destroy(struct sip_pvt *p);
  396. static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
  397. {
  398. /*
  399. check to see if them is contained in our localnet/mask,
  400. if not, use our externip for us, otherwise use the
  401. real internal address in bindaddr
  402. */
  403. if (localnet.sin_addr.s_addr && externip.sin_addr.s_addr &&
  404. ((htonl(them->s_addr) & htonl(localnet.sin_addr.s_addr)) != htonl(localnet.sin_addr.s_addr)))
  405. memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
  406. else if (bindaddr.sin_addr.s_addr)
  407. memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
  408. else
  409. return ast_ouraddrfor(them, us);
  410. return 0;
  411. }
  412. static int retrans_pkt(void *data)
  413. {
  414. struct sip_pkt *pkt=data;
  415. int res = 0;
  416. ast_mutex_lock(&pkt->owner->lock);
  417. if (pkt->retrans < MAX_RETRANS) {
  418. pkt->retrans++;
  419. if (sipdebug) {
  420. if (pkt->owner->nat)
  421. ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
  422. else
  423. ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
  424. }
  425. __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
  426. res = 1;
  427. } else {
  428. ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
  429. pkt->retransid = -1;
  430. while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
  431. ast_mutex_unlock(&pkt->owner->lock);
  432. usleep(1);
  433. ast_mutex_lock(&pkt->owner->lock);
  434. }
  435. if (pkt->owner->owner) {
  436. /* XXX Potential deadlocK?? XXX */
  437. ast_queue_hangup(pkt->owner->owner, 0);
  438. ast_mutex_unlock(&pkt->owner->owner->lock);
  439. } else {
  440. /* If no owner, destroy now */
  441. pkt->owner->needdestroy = 1;
  442. }
  443. }
  444. if (pkt)
  445. ast_mutex_unlock(&pkt->owner->lock);
  446. return res;
  447. }
  448. static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
  449. {
  450. struct sip_pkt *pkt;
  451. pkt = malloc(sizeof(struct sip_pkt) + len);
  452. if (!pkt)
  453. return -1;
  454. memset(pkt, 0, sizeof(struct sip_pkt));
  455. memcpy(pkt->data, data, len);
  456. pkt->packetlen = len;
  457. pkt->next = p->packets;
  458. pkt->owner = p;
  459. pkt->seqno = seqno;
  460. pkt->resp = resp;
  461. /* Schedule retransmission */
  462. pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
  463. pkt->next = p->packets;
  464. p->packets = pkt;
  465. __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
  466. if (!strncasecmp(pkt->data, "INVITE", 6)) {
  467. /* Note this is a pending invite */
  468. p->pendinginvite = seqno;
  469. }
  470. return 0;
  471. }
  472. static int __sip_autodestruct(void *data)
  473. {
  474. struct sip_pvt *p = data;
  475. p->autokillid = -1;
  476. ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
  477. if (p->owner) {
  478. ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
  479. ast_queue_hangup(p->owner, 0);
  480. } else {
  481. sip_destroy(p);
  482. }
  483. return 0;
  484. }
  485. static int sip_scheddestroy(struct sip_pvt *p, int ms)
  486. {
  487. if (p->autokillid > -1)
  488. ast_sched_del(sched, p->autokillid);
  489. p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
  490. return 0;
  491. }
  492. static int sip_cancel_destroy(struct sip_pvt *p)
  493. {
  494. if (p->autokillid > -1)
  495. ast_sched_del(sched, p->autokillid);
  496. p->autokillid = -1;
  497. return 0;
  498. }
  499. static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
  500. {
  501. struct sip_pkt *cur, *prev = NULL;
  502. int res = -1;
  503. int resetinvite = 0;
  504. cur = p->packets;
  505. while(cur) {
  506. if ((cur->seqno == seqno) && (cur->resp == resp)) {
  507. if (!resp && (seqno == p->pendinginvite)) {
  508. ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
  509. p->pendinginvite = 0;
  510. resetinvite = 1;
  511. }
  512. /* this is our baby */
  513. if (prev)
  514. prev->next = cur->next;
  515. else
  516. p->packets = cur->next;
  517. if (cur->retransid > -1)
  518. ast_sched_del(sched, cur->retransid);
  519. free(cur);
  520. res = 0;
  521. break;
  522. }
  523. prev = cur;
  524. cur = cur->next;
  525. }
  526. ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
  527. return res;
  528. }
  529. static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
  530. {
  531. struct sip_pkt *cur;
  532. int res = -1;
  533. cur = p->packets;
  534. while(cur) {
  535. if ((cur->seqno == seqno) && (cur->resp == resp)) {
  536. /* this is our baby */
  537. if (cur->retransid > -1)
  538. ast_sched_del(sched, cur->retransid);
  539. cur->retransid = -1;
  540. res = 0;
  541. break;
  542. }
  543. cur = cur->next;
  544. }
  545. 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");
  546. return res;
  547. }
  548. static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
  549. {
  550. int res;
  551. if (sipdebug) {
  552. if (p->nat)
  553. ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
  554. else
  555. ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
  556. }
  557. if (reliable)
  558. res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
  559. else
  560. res = __sip_xmit(p, req->data, req->len);
  561. if (res > 0)
  562. res = 0;
  563. return res;
  564. }
  565. static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
  566. {
  567. int res;
  568. if (sipdebug) {
  569. if (p->nat)
  570. ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
  571. else
  572. ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
  573. }
  574. if (reliable)
  575. res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
  576. else
  577. res = __sip_xmit(p, req->data, req->len);
  578. return res;
  579. }
  580. static char *ditch_braces(char *tmp)
  581. {
  582. char *c = tmp;
  583. char *n;
  584. if ((n = strchr(tmp, '<')) ) {
  585. c = n + 1;
  586. while(*c && *c != '>') c++;
  587. if (*c != '>') {
  588. ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
  589. } else {
  590. *c = '\0';
  591. }
  592. return n+1;
  593. }
  594. return c;
  595. }
  596. static int sip_sendtext(struct ast_channel *ast, char *text)
  597. {
  598. struct sip_pvt *p = ast->pvt->pvt;
  599. if (sipdebug)
  600. ast_verbose("Sending text %s on %s\n", text, ast->name);
  601. if (!p)
  602. return -1;
  603. if (!text || !strlen(text))
  604. return 0;
  605. if (sipdebug)
  606. ast_verbose("Really sending text %s on %s\n", text, ast->name);
  607. transmit_message_with_text(p, text);
  608. return 0;
  609. }
  610. #ifdef MYSQL_FRIENDS
  611. static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
  612. {
  613. if (mysql && (strlen(peer) < 128)) {
  614. char query[512];
  615. char *name;
  616. char *uname;
  617. time_t nowtime;
  618. name = alloca(strlen(peer) * 2 + 1);
  619. uname = alloca(strlen(username) * 2 + 1);
  620. time(&nowtime);
  621. mysql_real_escape_string(mysql, name, peer, strlen(peer));
  622. mysql_real_escape_string(mysql, uname, username, strlen(username));
  623. snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"",
  624. inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
  625. ast_mutex_lock(&mysqllock);
  626. if (mysql_real_query(mysql, query, strlen(query)))
  627. ast_log(LOG_WARNING, "Unable to update database\n");
  628. ast_mutex_unlock(&mysqllock);
  629. }
  630. }
  631. static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
  632. {
  633. struct sip_peer *p;
  634. int success = 0;
  635. p = malloc(sizeof(struct sip_peer));
  636. memset(p, 0, sizeof(struct sip_peer));
  637. if (mysql && (!peer || (strlen(peer) < 128))) {
  638. char query[512];
  639. char *name = NULL;
  640. int numfields, x;
  641. int port;
  642. time_t regseconds, nowtime;
  643. MYSQL_RES *result;
  644. MYSQL_FIELD *fields;
  645. MYSQL_ROW rowval;
  646. if (peer) {
  647. name = alloca(strlen(peer) * 2 + 1);
  648. mysql_real_escape_string(mysql, name, peer, strlen(peer));
  649. }
  650. if (sin)
  651. snprintf(query, sizeof(query), "SELECT * FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
  652. else
  653. snprintf(query, sizeof(query), "SELECT * FROM sipfriends WHERE name=\"%s\"", name);
  654. ast_mutex_lock(&mysqllock);
  655. mysql_query(mysql, query);
  656. if ((result = mysql_store_result(mysql))) {
  657. if ((rowval = mysql_fetch_row(result))) {
  658. numfields = mysql_num_fields(result);
  659. fields = mysql_fetch_fields(result);
  660. success = 1;
  661. for (x=0;x<numfields;x++) {
  662. if (rowval[x]) {
  663. if (!strcasecmp(fields[x].name, "secret")) {
  664. strncpy(p->secret, rowval[x], sizeof(p->secret));
  665. } else if (!strcasecmp(fields[x].name, "name")) {
  666. strncpy(p->name, rowval[x], sizeof(p->name) - 1);
  667. } else if (!strcasecmp(fields[x].name, "context")) {
  668. strncpy(p->context, rowval[x], sizeof(p->context) - 1);
  669. } else if (!strcasecmp(fields[x].name, "username")) {
  670. strncpy(p->username, rowval[x], sizeof(p->username) - 1);
  671. } else if (!strcasecmp(fields[x].name, "ipaddr")) {
  672. inet_aton(rowval[x], &p->addr.sin_addr);
  673. } else if (!strcasecmp(fields[x].name, "port")) {
  674. if (sscanf(rowval[x], "%i", &port) != 1)
  675. port = 0;
  676. p->addr.sin_port = htons(port);
  677. } else if (!strcasecmp(fields[x].name, "regseconds")) {
  678. if (sscanf(rowval[x], "%li", &regseconds) != 1)
  679. regseconds = 0;
  680. }
  681. }
  682. }
  683. time(&nowtime);
  684. if (nowtime > regseconds)
  685. memset(&p->addr, 0, sizeof(p->addr));
  686. }
  687. mysql_free_result(result);
  688. result = NULL;
  689. }
  690. ast_mutex_unlock(&mysqllock);
  691. }
  692. if (!success) {
  693. free(p);
  694. p = NULL;
  695. } else {
  696. p->dynamic = 1;
  697. p->capability = capability;
  698. p->nat = globalnat;
  699. p->dtmfmode = globaldtmfmode;
  700. p->insecure = 1;
  701. p->expire = -1;
  702. p->temponly = 1;
  703. }
  704. return p;
  705. }
  706. #endif /* MYSQL_FRIENDS */
  707. static int create_addr(struct sip_pvt *r, char *peer)
  708. {
  709. struct hostent *hp;
  710. struct ast_hostent ahp;
  711. struct sip_peer *p;
  712. int found=0;
  713. char *port;
  714. int portno;
  715. char host[256], *hostn;
  716. r->sa.sin_family = AF_INET;
  717. ast_mutex_lock(&peerl.lock);
  718. p = peerl.peers;
  719. while(p) {
  720. if (!strcasecmp(p->name, peer))
  721. break;
  722. p = p->next;
  723. }
  724. #ifdef MYSQL_FRIENDS
  725. if (!p)
  726. p = mysql_peer(peer, NULL);
  727. #endif
  728. if (p) {
  729. found++;
  730. r->capability = p->capability;
  731. r->nat = p->nat;
  732. if (r->rtp) {
  733. ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
  734. ast_rtp_setnat(r->rtp, r->nat);
  735. }
  736. if (r->vrtp) {
  737. ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
  738. ast_rtp_setnat(r->vrtp, r->nat);
  739. }
  740. strncpy(r->peername, p->username, sizeof(r->peername)-1);
  741. strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
  742. strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
  743. strncpy(r->username, p->username, sizeof(r->username)-1);
  744. strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
  745. if (!strlen(r->tohost)) {
  746. if (p->addr.sin_addr.s_addr)
  747. snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
  748. else
  749. snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
  750. }
  751. if (strlen(p->fromdomain))
  752. strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
  753. if (strlen(p->fromuser))
  754. strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
  755. r->insecure = p->insecure;
  756. r->canreinvite = p->canreinvite;
  757. r->maxtime = p->maxms;
  758. r->callgroup = p->callgroup;
  759. r->pickupgroup = p->pickupgroup;
  760. if (p->dtmfmode) {
  761. r->dtmfmode = p->dtmfmode;
  762. if (r->dtmfmode & SIP_DTMF_RFC2833)
  763. r->noncodeccapability |= AST_RTP_DTMF;
  764. else
  765. r->noncodeccapability &= ~AST_RTP_DTMF;
  766. }
  767. strncpy(r->context, p->context,sizeof(r->context)-1);
  768. if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
  769. (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
  770. if (p->addr.sin_addr.s_addr) {
  771. r->sa.sin_addr = p->addr.sin_addr;
  772. r->sa.sin_port = p->addr.sin_port;
  773. } else {
  774. r->sa.sin_addr = p->defaddr.sin_addr;
  775. r->sa.sin_port = p->defaddr.sin_port;
  776. }
  777. memcpy(&r->recv, &r->sa, sizeof(r->recv));
  778. } else {
  779. if (p->temponly)
  780. free(p);
  781. p = NULL;
  782. }
  783. }
  784. ast_mutex_unlock(&peerl.lock);
  785. if (!p && !found) {
  786. if ((port=strchr(peer, ':'))) {
  787. *port='\0';
  788. port++;
  789. }
  790. hostn = peer;
  791. if (port)
  792. portno = atoi(port);
  793. else
  794. portno = DEFAULT_SIP_PORT;
  795. if (srvlookup) {
  796. char service[256];
  797. int tportno;
  798. int ret;
  799. snprintf(service, sizeof(service), "_sip._udp.%s", peer);
  800. ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
  801. if (ret > 0) {
  802. hostn = host;
  803. portno = tportno;
  804. }
  805. }
  806. hp = ast_gethostbyname(hostn, &ahp);
  807. if (hp) {
  808. strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
  809. memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
  810. r->sa.sin_port = htons(portno);
  811. memcpy(&r->recv, &r->sa, sizeof(r->recv));
  812. return 0;
  813. } else {
  814. ast_log(LOG_WARNING, "No such host: %s\n", peer);
  815. return -1;
  816. }
  817. } else if (!p)
  818. return -1;
  819. else {
  820. if (p->temponly)
  821. free(p);
  822. return 0;
  823. }
  824. }
  825. static int auto_congest(void *nothing)
  826. {
  827. struct sip_pvt *p = nothing;
  828. ast_mutex_lock(&p->lock);
  829. p->initid = -1;
  830. if (p->owner) {
  831. if (!ast_mutex_trylock(&p->owner->lock)) {
  832. ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
  833. ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
  834. ast_mutex_unlock(&p->owner->lock);
  835. }
  836. }
  837. ast_mutex_unlock(&p->lock);
  838. return 0;
  839. }
  840. static void sip_prefs_free(void)
  841. {
  842. struct sip_codec_pref *cur, *next;
  843. cur = prefs;
  844. while(cur) {
  845. next = cur->next;
  846. free(cur);
  847. cur = next;
  848. }
  849. prefs = NULL;
  850. }
  851. static void sip_pref_remove(int format)
  852. {
  853. struct sip_codec_pref *cur, *prev=NULL;
  854. cur = prefs;
  855. while(cur) {
  856. if (cur->codec == format) {
  857. if (prev)
  858. prev->next = cur->next;
  859. else
  860. prefs = cur->next;
  861. free(cur);
  862. return;
  863. }
  864. prev = cur;
  865. cur = cur->next;
  866. }
  867. }
  868. static int sip_pref_append(int format)
  869. {
  870. struct sip_codec_pref *cur, *tmp;
  871. sip_pref_remove(format);
  872. tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
  873. if (!tmp)
  874. return -1;
  875. memset(tmp, 0, sizeof(struct sip_codec_pref));
  876. tmp->codec = format;
  877. if (prefs) {
  878. cur = prefs;
  879. while(cur->next)
  880. cur = cur->next;
  881. cur->next = tmp;
  882. } else
  883. prefs = tmp;
  884. return 0;
  885. }
  886. static int sip_codec_choose(int formats)
  887. {
  888. struct sip_codec_pref *cur;
  889. formats &= (AST_FORMAT_MAX_AUDIO - 1);
  890. cur = prefs;
  891. while(cur) {
  892. if (formats & cur->codec)
  893. return cur->codec;
  894. cur = cur->next;
  895. }
  896. return ast_best_codec(formats);
  897. }
  898. static int sip_call(struct ast_channel *ast, char *dest, int timeout)
  899. {
  900. int res;
  901. struct sip_pvt *p;
  902. char *vxml_url = NULL;
  903. char *distinctive_ring = NULL;
  904. struct varshead *headp;
  905. struct ast_var_t *current;
  906. p = ast->pvt->pvt;
  907. if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
  908. ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
  909. return -1;
  910. }
  911. /* Check whether there is vxml_url, distinctive ring variables */
  912. headp=&ast->varshead;
  913. AST_LIST_TRAVERSE(headp,current,entries) {
  914. /* Check whether there is a VXML_URL variable */
  915. if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
  916. {
  917. vxml_url = ast_var_value(current);
  918. break;
  919. }
  920. /* Check whether there is a ALERT_INFO variable */
  921. if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
  922. {
  923. distinctive_ring = ast_var_value(current);
  924. break;
  925. }
  926. }
  927. res = 0;
  928. p->outgoing = 1;
  929. ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
  930. res = find_user(p,INC_OUT_USE);
  931. if ( res != -1 ) {
  932. p->restrictcid = ast->restrictcid;
  933. p->jointcapability = p->capability;
  934. transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
  935. if (p->maxtime) {
  936. /* Initialize auto-congest time */
  937. p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
  938. }
  939. }
  940. return res;
  941. }
  942. static void __sip_destroy(struct sip_pvt *p, int lockowner)
  943. {
  944. struct sip_pvt *cur, *prev = NULL;
  945. struct sip_pkt *cp;
  946. if (sipdebug)
  947. ast_log(LOG_DEBUG, "Destroying call '%s'\n", p->callid);
  948. if (p->stateid > -1)
  949. ast_extension_state_del(p->stateid, NULL);
  950. if (p->initid > -1)
  951. ast_sched_del(sched, p->initid);
  952. if (p->autokillid > -1)
  953. ast_sched_del(sched, p->autokillid);
  954. if (p->rtp) {
  955. ast_rtp_destroy(p->rtp);
  956. }
  957. if (p->vrtp) {
  958. ast_rtp_destroy(p->vrtp);
  959. }
  960. if (p->route) {
  961. free_old_route(p->route);
  962. p->route = NULL;
  963. }
  964. if (p->registry) {
  965. /* Carefully unlink from registry */
  966. struct sip_registry *reg;
  967. ast_mutex_lock(&regl.lock);
  968. reg = regl.registrations;
  969. while(reg) {
  970. if ((reg == p->registry) && (p->registry->call == p))
  971. p->registry->call=NULL;
  972. reg = reg->next;
  973. }
  974. ast_mutex_unlock(&regl.lock);
  975. }
  976. /* Unlink us from the owner if we have one */
  977. if (p->owner) {
  978. if (lockowner)
  979. ast_mutex_lock(&p->owner->lock);
  980. ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
  981. p->owner->pvt->pvt = NULL;
  982. if (lockowner)
  983. ast_mutex_unlock(&p->owner->lock);
  984. }
  985. cur = iflist;
  986. while(cur) {
  987. if (cur == p) {
  988. if (prev)
  989. prev->next = cur->next;
  990. else
  991. iflist = cur->next;
  992. break;
  993. }
  994. prev = cur;
  995. cur = cur->next;
  996. }
  997. if (!cur) {
  998. ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
  999. } else {
  1000. if (p->initid > -1)
  1001. ast_sched_del(sched, p->initid);
  1002. while((cp = p->packets)) {
  1003. p->packets = p->packets->next;
  1004. if (cp->retransid > -1)
  1005. ast_sched_del(sched, cp->retransid);
  1006. free(cp);
  1007. }
  1008. free(p);
  1009. }
  1010. }
  1011. static int find_user(struct sip_pvt *fup, int event)
  1012. {
  1013. char name[256] = "";
  1014. struct sip_user *u;
  1015. strncpy(name, fup->username, sizeof(name) - 1);
  1016. ast_mutex_lock(&userl.lock);
  1017. u = userl.users;
  1018. while(u) {
  1019. if (!strcasecmp(u->name, name)) {
  1020. break;
  1021. }
  1022. u = u->next;
  1023. }
  1024. if (!u) {
  1025. ast_log(LOG_DEBUG, "%s is not a local user\n", name);
  1026. ast_mutex_unlock(&userl.lock);
  1027. return 0;
  1028. }
  1029. switch(event) {
  1030. /* incoming and outgoing affects the inUse counter */
  1031. case DEC_OUT_USE:
  1032. case DEC_IN_USE:
  1033. if ( u->inUse > 0 ) {
  1034. u->inUse--;
  1035. } else {
  1036. u->inUse = 0;
  1037. }
  1038. break;
  1039. case INC_IN_USE:
  1040. case INC_OUT_USE:
  1041. if (u->incominglimit > 0 ) {
  1042. if (u->inUse >= u->incominglimit) {
  1043. ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
  1044. ast_mutex_unlock(&userl.lock);
  1045. /* inc inUse as well */
  1046. if ( event == INC_OUT_USE ) {
  1047. u->inUse++;
  1048. }
  1049. return -1;
  1050. }
  1051. }
  1052. u->inUse++;
  1053. ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
  1054. break;
  1055. /* we don't use these anymore
  1056. case DEC_OUT_USE:
  1057. if ( u->outUse > 0 ) {
  1058. u->outUse--;
  1059. } else {
  1060. u->outUse = 0;
  1061. }
  1062. break;
  1063. case INC_OUT_USE:
  1064. if ( u->outgoinglimit > 0 ) {
  1065. if ( u->outUse >= u->outgoinglimit ) {
  1066. ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
  1067. ast_mutex_unlock(&userl.lock);
  1068. return -1;
  1069. }
  1070. }
  1071. u->outUse++;
  1072. break;
  1073. */
  1074. default:
  1075. ast_log(LOG_ERROR, "find_user(%s,%d) called with no event!\n",u->name,event);
  1076. }
  1077. ast_mutex_unlock(&userl.lock);
  1078. return 0;
  1079. }
  1080. static void sip_destroy(struct sip_pvt *p)
  1081. {
  1082. ast_mutex_lock(&iflock);
  1083. __sip_destroy(p, 1);
  1084. ast_mutex_unlock(&iflock);
  1085. }
  1086. static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
  1087. static int hangup_sip2cause(int cause)
  1088. {
  1089. switch(cause)
  1090. {
  1091. case 486:
  1092. return AST_CAUSE_BUSY;
  1093. default:
  1094. return AST_CAUSE_NORMAL;
  1095. }
  1096. /* Never reached */
  1097. return 0;
  1098. }
  1099. static char *hangup_cause2sip(int cause)
  1100. {
  1101. switch(cause)
  1102. {
  1103. case AST_CAUSE_BUSY:
  1104. return "486 Busy";
  1105. default:
  1106. return NULL;
  1107. }
  1108. /* Never reached */
  1109. return 0;
  1110. }
  1111. static int sip_hangup(struct ast_channel *ast)
  1112. {
  1113. struct sip_pvt *p = ast->pvt->pvt;
  1114. int needcancel = 0;
  1115. int needdestroy = 0;
  1116. if (option_debug)
  1117. ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
  1118. if (!ast->pvt->pvt) {
  1119. ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
  1120. return 0;
  1121. }
  1122. ast_mutex_lock(&p->lock);
  1123. if ( p->outgoing ) {
  1124. ast_log(LOG_DEBUG, "find_user(%s) - decrement outUse counter\n", p->username);
  1125. find_user(p, DEC_OUT_USE);
  1126. } else {
  1127. ast_log(LOG_DEBUG, "find_user(%s) - decrement inUse counter\n", p->username);
  1128. find_user(p, DEC_IN_USE);
  1129. }
  1130. /* Determine how to disconnect */
  1131. if (p->owner != ast) {
  1132. ast_log(LOG_WARNING, "Huh? We aren't the owner?\n");
  1133. ast_mutex_unlock(&p->lock);
  1134. return 0;
  1135. }
  1136. if (!ast || (ast->_state != AST_STATE_UP))
  1137. needcancel = 1;
  1138. /* Disconnect */
  1139. p = ast->pvt->pvt;
  1140. if (p->vad) {
  1141. ast_dsp_free(p->vad);
  1142. }
  1143. p->owner = NULL;
  1144. ast->pvt->pvt = NULL;
  1145. ast_mutex_lock(&usecnt_lock);
  1146. usecnt--;
  1147. ast_mutex_unlock(&usecnt_lock);
  1148. ast_update_use_count();
  1149. needdestroy = 1;
  1150. /* Start the process if it's not already started */
  1151. if (!p->alreadygone && strlen(p->initreq.data)) {
  1152. if (needcancel) {
  1153. if (p->outgoing) {
  1154. transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
  1155. /* Actually don't destroy us yet, wait for the 487 on our original
  1156. INVITE, but do set an autodestruct just in case. */
  1157. needdestroy = 0;
  1158. sip_scheddestroy(p, 15000);
  1159. if ( p->initid != -1 ) {
  1160. /* channel still up - reverse dec of inUse counter
  1161. only if the channel is not auto-congested */
  1162. if ( p->outgoing ) {
  1163. find_user(p, INC_OUT_USE);
  1164. }
  1165. else {
  1166. find_user(p, INC_IN_USE);
  1167. }
  1168. }
  1169. } else {
  1170. char *res;
  1171. if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
  1172. transmit_response_reliable(p, res, &p->initreq);
  1173. } else
  1174. transmit_response_reliable(p, "403 Forbidden", &p->initreq);
  1175. }
  1176. } else {
  1177. if (!p->pendinginvite) {
  1178. /* Send a hangup */
  1179. transmit_request_with_auth(p, "BYE", 0, 1);
  1180. } else {
  1181. /* Note we will need a BYE when this all settles out
  1182. but we can't send one while we have "INVITE" outstanding. */
  1183. p->pendingbye = 1;
  1184. }
  1185. }
  1186. }
  1187. p->needdestroy = needdestroy;
  1188. ast_mutex_unlock(&p->lock);
  1189. return 0;
  1190. }
  1191. static int sip_answer(struct ast_channel *ast)
  1192. {
  1193. int res = 0,fmt;
  1194. char *codec;
  1195. struct sip_pvt *p = ast->pvt->pvt;
  1196. if (ast->_state != AST_STATE_UP) {
  1197. codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
  1198. if (codec) {
  1199. fmt=ast_getformatbyname(codec);
  1200. if (fmt) {
  1201. ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
  1202. p->jointcapability=fmt;
  1203. } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
  1204. }
  1205. ast_setstate(ast, AST_STATE_UP);
  1206. if (option_debug)
  1207. ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
  1208. res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
  1209. }
  1210. return res;
  1211. }
  1212. static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
  1213. {
  1214. struct sip_pvt *p = ast->pvt->pvt;
  1215. int res = 0;
  1216. if (frame->frametype == AST_FRAME_VOICE) {
  1217. if (!(frame->subclass & ast->nativeformats)) {
  1218. ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
  1219. frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
  1220. return -1;
  1221. }
  1222. if (p) {
  1223. ast_mutex_lock(&p->lock);
  1224. if (p->rtp) {
  1225. if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
  1226. transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
  1227. p->progress = 1;
  1228. }
  1229. res = ast_rtp_write(p->rtp, frame);
  1230. }
  1231. ast_mutex_unlock(&p->lock);
  1232. }
  1233. } else if (frame->frametype == AST_FRAME_VIDEO) {
  1234. if (p) {
  1235. ast_mutex_lock(&p->lock);
  1236. if (p->vrtp) {
  1237. if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
  1238. transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
  1239. p->progress = 1;
  1240. }
  1241. res = ast_rtp_write(p->vrtp, frame);
  1242. }
  1243. ast_mutex_unlock(&p->lock);
  1244. }
  1245. } else if (frame->frametype == AST_FRAME_IMAGE) {
  1246. return 0;
  1247. } else {
  1248. ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
  1249. return 0;
  1250. }
  1251. return res;
  1252. }
  1253. static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
  1254. {
  1255. struct sip_pvt *p = newchan->pvt->pvt;
  1256. ast_mutex_lock(&p->lock);
  1257. if (p->owner != oldchan) {
  1258. ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
  1259. ast_mutex_unlock(&p->lock);
  1260. return -1;
  1261. }
  1262. p->owner = newchan;
  1263. ast_mutex_unlock(&p->lock);
  1264. return 0;
  1265. }
  1266. static int sip_senddigit(struct ast_channel *ast, char digit)
  1267. {
  1268. struct sip_pvt *p = ast->pvt->pvt;
  1269. if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
  1270. transmit_info_with_digit(p, digit);
  1271. }
  1272. if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
  1273. ast_rtp_senddigit(p->rtp, digit);
  1274. }
  1275. /* If in-band DTMF is desired, send that */
  1276. if (p->dtmfmode & SIP_DTMF_INBAND)
  1277. return -1;
  1278. return 0;
  1279. }
  1280. static int sip_transfer(struct ast_channel *ast, char *dest)
  1281. {
  1282. struct sip_pvt *p = ast->pvt->pvt;
  1283. int res;
  1284. res = transmit_refer(p, dest);
  1285. return res;
  1286. }
  1287. static int sip_indicate(struct ast_channel *ast, int condition)
  1288. {
  1289. struct sip_pvt *p = ast->pvt->pvt;
  1290. switch(condition) {
  1291. case AST_CONTROL_RINGING:
  1292. if (ast->_state == AST_STATE_RING) {
  1293. if (!p->progress) {
  1294. transmit_response(p, "180 Ringing", &p->initreq);
  1295. p->ringing = 1;
  1296. break;
  1297. } else {
  1298. /* Oops, we've sent progress tones. Let Asterisk do it instead */
  1299. }
  1300. }
  1301. return -1;
  1302. case AST_CONTROL_BUSY:
  1303. if (ast->_state != AST_STATE_UP) {
  1304. transmit_response(p, "486 Busy Here", &p->initreq);
  1305. p->alreadygone = 1;
  1306. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  1307. break;
  1308. }
  1309. return -1;
  1310. case AST_CONTROL_CONGESTION:
  1311. if (ast->_state != AST_STATE_UP) {
  1312. transmit_response(p, "503 Service Unavailable", &p->initreq);
  1313. p->alreadygone = 1;
  1314. ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
  1315. break;
  1316. }
  1317. return -1;
  1318. case AST_CONTROL_PROGRESS:
  1319. if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
  1320. transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
  1321. p->progress = 1;
  1322. break;
  1323. }
  1324. return -1;
  1325. case -1:
  1326. return -1;
  1327. default:
  1328. ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
  1329. return -1;
  1330. }
  1331. return 0;
  1332. }
  1333. static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
  1334. {
  1335. struct ast_channel *tmp;
  1336. int fmt;
  1337. tmp = ast_channel_alloc(1);
  1338. if (tmp) {
  1339. /* Select our native format based on codec preference until we receive
  1340. something from another device to the contrary. */
  1341. if (i->jointcapability)
  1342. tmp->nativeformats = sip_codec_choose(i->jointcapability);
  1343. else if (i->capability)
  1344. tmp->nativeformats = sip_codec_choose(i->capability);
  1345. else
  1346. tmp->nativeformats = sip_codec_choose(capability);
  1347. fmt = ast_best_codec(tmp->nativeformats);
  1348. if (title)
  1349. snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
  1350. else
  1351. if (strchr(i->fromdomain,':'))
  1352. {
  1353. snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
  1354. }
  1355. else
  1356. {
  1357. snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
  1358. }
  1359. tmp->type = type;
  1360. if (i->dtmfmode & SIP_DTMF_INBAND) {
  1361. i->vad = ast_dsp_new();
  1362. ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
  1363. }
  1364. tmp->fds[0] = ast_rtp_fd(i->rtp);
  1365. tmp->fds[1] = ast_rtcp_fd(i->rtp);
  1366. if (i->vrtp) {
  1367. tmp->fds[2] = ast_rtp_fd(i->vrtp);
  1368. tmp->fds[3] = ast_rtcp_fd(i->vrtp);
  1369. }
  1370. ast_setstate(tmp, state);
  1371. if (state == AST_STATE_RING)
  1372. tmp->rings = 1;
  1373. tmp->adsicpe = AST_ADSI_UNAVAILABLE;
  1374. tmp->writeformat = fmt;
  1375. tmp->pvt->rawwriteformat = fmt;
  1376. tmp->readformat = fmt;
  1377. tmp->pvt->rawreadformat = fmt;
  1378. tmp->pvt->pvt = i;
  1379. tmp->pvt->send_text = sip_sendtext;
  1380. tmp->pvt->call = sip_call;
  1381. tmp->pvt->hangup = sip_hangup;
  1382. tmp->pvt->answer = sip_answer;
  1383. tmp->pvt->read = sip_read;
  1384. tmp->pvt->write = sip_write;
  1385. tmp->pvt->write_video = sip_write;
  1386. tmp->pvt->indicate = sip_indicate;
  1387. tmp->pvt->transfer = sip_transfer;
  1388. tmp->pvt->fixup = sip_fixup;
  1389. tmp->pvt->send_digit = sip_senddigit;
  1390. tmp->pvt->bridge = ast_rtp_bridge;
  1391. tmp->callgroup = i->callgroup;
  1392. tmp->pickupgroup = i->pickupgroup;
  1393. tmp->restrictcid = i->restrictcid;
  1394. if (strlen(i->accountcode))
  1395. strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
  1396. if (i->amaflags)
  1397. tmp->amaflags = i->amaflags;
  1398. if (strlen(i->language))
  1399. strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
  1400. i->owner = tmp;
  1401. ast_mutex_lock(&usecnt_lock);
  1402. usecnt++;
  1403. ast_mutex_unlock(&usecnt_lock);
  1404. strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
  1405. strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
  1406. if (strlen(i->callerid))
  1407. tmp->callerid = strdup(i->callerid);
  1408. if (strlen(i->rdnis))
  1409. tmp->rdnis = strdup(i->rdnis);
  1410. tmp->priority = 1;
  1411. if (strlen(i->domain)) {
  1412. pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
  1413. }
  1414. if (state != AST_STATE_DOWN) {
  1415. if (ast_pbx_start(tmp)) {
  1416. ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
  1417. ast_hangup(tmp);
  1418. tmp = NULL;
  1419. }
  1420. }
  1421. } else
  1422. ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
  1423. return tmp;
  1424. }
  1425. static struct cfalias {
  1426. char *fullname;
  1427. char *shortname;
  1428. } aliases[] = {
  1429. { "Content-Type", "c" },
  1430. { "Content-Encoding", "e" },
  1431. { "From", "f" },
  1432. { "Call-ID", "i" },
  1433. { "Contact", "m" },
  1434. { "Content-Length", "l" },
  1435. { "Subject", "s" },
  1436. { "To", "t" },
  1437. { "Via", "v" },
  1438. };
  1439. static char* get_sdp_by_line(char* line, char *name, int nameLen) {
  1440. if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
  1441. char* r = line + nameLen + 1;
  1442. while (*r && (*r < 33)) ++r;
  1443. return r;
  1444. }
  1445. return "";
  1446. }
  1447. static char *get_sdp(struct sip_request *req, char *name) {
  1448. int x;
  1449. int len = strlen(name);
  1450. char *r;
  1451. for (x=0; x<req->lines; x++) {
  1452. r = get_sdp_by_line(req->line[x], name, len);
  1453. if (r[0] != '\0') return r;
  1454. }
  1455. return "";
  1456. }
  1457. static void sdpLineNum_iterator_init(int* iterator) {
  1458. *iterator = 0;
  1459. }
  1460. static char* get_sdp_iterate(int* iterator,
  1461. struct sip_request *req, char *name) {
  1462. int len = strlen(name);
  1463. char *r;
  1464. while (*iterator < req->lines) {
  1465. r = get_sdp_by_line(req->line[(*iterator)++], name, len);
  1466. if (r[0] != '\0') return r;
  1467. }
  1468. return "";
  1469. }
  1470. static char *__get_header(struct sip_request *req, char *name, int *start)
  1471. {
  1472. int x;
  1473. int len = strlen(name);
  1474. char *r;
  1475. for (x=*start;x<req->headers;x++) {
  1476. if (!strncasecmp(req->header[x], name, len) &&
  1477. (req->header[x][len] == ':')) {
  1478. r = req->header[x] + len + 1;
  1479. while(*r && (*r < 33))
  1480. r++;
  1481. *start = x+1;
  1482. return r;
  1483. }
  1484. }
  1485. /* Try aliases */
  1486. for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++)
  1487. if (!strcasecmp(aliases[x].fullname, name))
  1488. return __get_header(req, aliases[x].shortname, start);
  1489. /* Don't return NULL, so get_header is always a valid pointer */
  1490. return "";
  1491. }
  1492. static char *get_header(struct sip_request *req, char *name)
  1493. {
  1494. int start = 0;
  1495. return __get_header(req, name, &start);
  1496. }
  1497. static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
  1498. {
  1499. /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
  1500. struct ast_frame *f;
  1501. static struct ast_frame null_frame = { AST_FRAME_NULL, };
  1502. switch(ast->fdno) {
  1503. case 0:
  1504. f = ast_rtp_read(p->rtp);
  1505. break;
  1506. case 1:
  1507. f = ast_rtcp_read(p->rtp);
  1508. break;
  1509. case 2:
  1510. f = ast_rtp_read(p->vrtp);
  1511. break;
  1512. case 3:
  1513. f = ast_rtcp_read(p->vrtp);
  1514. break;
  1515. default:
  1516. f = &null_frame;
  1517. }
  1518. /* Don't send RFC2833 if we're not supposed to */
  1519. if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
  1520. return &null_frame;
  1521. if (p->owner) {
  1522. /* We already hold the channel lock */
  1523. if (f->frametype == AST_FRAME_VOICE) {
  1524. if (f->subclass != p->owner->nativeformats) {
  1525. ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
  1526. p->owner->nativeformats = f->subclass;
  1527. ast_set_read_format(p->owner, p->owner->readformat);
  1528. ast_set_write_format(p->owner, p->owner->writeformat);
  1529. }
  1530. if (p->dtmfmode & SIP_DTMF_INBAND) {
  1531. f = ast_dsp_process(p->owner,p->vad,f,0);
  1532. }
  1533. }
  1534. }
  1535. return f;
  1536. }
  1537. static struct ast_frame *sip_read(struct ast_channel *ast)
  1538. {
  1539. struct ast_frame *fr;
  1540. struct sip_pvt *p = ast->pvt->pvt;
  1541. ast_mutex_lock(&p->lock);
  1542. fr = sip_rtp_read(ast, p);
  1543. ast_mutex_unlock(&p->lock);
  1544. return fr;
  1545. }
  1546. static void build_callid(char *callid, int len, struct in_addr ourip)
  1547. {
  1548. int res;
  1549. int val;
  1550. int x;
  1551. for (x=0;x<4;x++) {
  1552. val = rand();
  1553. res = snprintf(callid, len, "%08x", val);
  1554. len -= res;
  1555. callid += res;
  1556. }
  1557. /* It's not important that we really use our right IP here... */
  1558. snprintf(callid, len, "@%s", inet_ntoa(ourip));
  1559. }
  1560. static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
  1561. {
  1562. struct sip_pvt *p;
  1563. p = malloc(sizeof(struct sip_pvt));
  1564. if (!p)
  1565. return NULL;
  1566. /* Keep track of stuff */
  1567. memset(p, 0, sizeof(struct sip_pvt));
  1568. p->initid = -1;
  1569. p->autokillid = -1;
  1570. p->stateid = -1;
  1571. p->rtp = ast_rtp_new(sched, io, 1, 0);
  1572. if (videosupport)
  1573. p->vrtp = ast_rtp_new(sched, io, 1, 0);
  1574. p->branch = rand();
  1575. p->tag = rand();
  1576. /* Start with 101 instead of 1 */
  1577. p->ocseq = 101;
  1578. if (!p->rtp) {
  1579. ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
  1580. free(p);
  1581. return NULL;
  1582. }
  1583. ast_rtp_settos(p->rtp, tos);
  1584. if (p->vrtp)
  1585. ast_rtp_settos(p->vrtp, tos);
  1586. if (useglobalnat && sin) {
  1587. /* Setup NAT structure according to global settings if we have an address */
  1588. p->nat = globalnat;
  1589. memcpy(&p->recv, sin, sizeof(p->recv));
  1590. ast_rtp_setnat(p->rtp, p->nat);
  1591. if (p->vrtp)
  1592. ast_rtp_setnat(p->vrtp, p->nat);
  1593. }
  1594. ast_mutex_init(&p->lock);
  1595. if (sin) {
  1596. memcpy(&p->sa, sin, sizeof(p->sa));
  1597. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  1598. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  1599. } else {
  1600. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  1601. }
  1602. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  1603. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
  1604. if (!callid)
  1605. build_callid(p->callid, sizeof(p->callid), p->ourip);
  1606. else
  1607. strncpy(p->callid, callid, sizeof(p->callid) - 1);
  1608. /* Assume reinvite OK and via INVITE */
  1609. p->canreinvite = globalcanreinvite;
  1610. p->dtmfmode = globaldtmfmode;
  1611. p->capability = capability;
  1612. if (p->dtmfmode & SIP_DTMF_RFC2833)
  1613. p->noncodeccapability |= AST_RTP_DTMF;
  1614. strncpy(p->context, context, sizeof(p->context) - 1);
  1615. strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
  1616. /* Add to list */
  1617. ast_mutex_lock(&iflock);
  1618. p->next = iflist;
  1619. iflist = p;
  1620. ast_mutex_unlock(&iflock);
  1621. if (option_debug)
  1622. ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
  1623. return p;
  1624. }
  1625. static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
  1626. {
  1627. struct sip_pvt *p;
  1628. char *callid;
  1629. char tmp[256] = "";
  1630. char *cmd;
  1631. char *tag = "", *c;
  1632. int themisfrom;
  1633. callid = get_header(req, "Call-ID");
  1634. if (pedanticsipchecking) {
  1635. /* In principle Call-ID's uniquely identify a call, however some vendors
  1636. (i.e. Pingtel) send multiple calls with the same Call-ID and different
  1637. tags in order to simplify billing. The RFC does state that we have to
  1638. compare tags in addition to the call-id, but this generate substantially
  1639. more overhead which is totally unnecessary for the vast majority of sane
  1640. SIP implementations, and thus Asterisk does not enable this behavior
  1641. by default. Short version: You'll need this option to support conferencing
  1642. on the pingtel */
  1643. strncpy(tmp, req->header[0], sizeof(tmp) - 1);
  1644. cmd = tmp;
  1645. c = strchr(tmp, ' ');
  1646. if (c)
  1647. *c = '\0';
  1648. if (!strcasecmp(cmd, "SIP/2.0")) {
  1649. themisfrom = 0;
  1650. } else {
  1651. themisfrom = 1;
  1652. }
  1653. if (themisfrom)
  1654. strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
  1655. else
  1656. strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
  1657. tag = strstr(tmp, "tag=");
  1658. if (tag) {
  1659. tag += 4;
  1660. c = strchr(tag, ';');
  1661. if (c)
  1662. *c = '\0';
  1663. }
  1664. }
  1665. if (!strlen(callid)) {
  1666. ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
  1667. return NULL;
  1668. }
  1669. ast_mutex_lock(&iflock);
  1670. p = iflist;
  1671. while(p) {
  1672. if (!strcmp(p->callid, callid) &&
  1673. (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
  1674. /* Found the call */
  1675. ast_mutex_lock(&p->lock);
  1676. ast_mutex_unlock(&iflock);
  1677. return p;
  1678. }
  1679. p = p->next;
  1680. }
  1681. ast_mutex_unlock(&iflock);
  1682. p = sip_alloc(callid, sin, 1);
  1683. if (p)
  1684. ast_mutex_lock(&p->lock);
  1685. return p;
  1686. }
  1687. static int sip_register(char *value, int lineno)
  1688. {
  1689. struct sip_registry *reg;
  1690. char copy[256] = "";
  1691. char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
  1692. char *porta=NULL;
  1693. char *contact=NULL;
  1694. char *stringp=NULL;
  1695. struct hostent *hp;
  1696. struct ast_hostent ahp;
  1697. if (!value)
  1698. return -1;
  1699. strncpy(copy, value, sizeof(copy)-1);
  1700. stringp=copy;
  1701. username = stringp;
  1702. hostname = strrchr(stringp, '@');
  1703. if (hostname) {
  1704. *hostname = '\0';
  1705. hostname++;
  1706. }
  1707. if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
  1708. ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
  1709. return -1;
  1710. }
  1711. stringp=username;
  1712. username = strsep(&stringp, ":");
  1713. if (username) {
  1714. secret = strsep(&stringp, ":");
  1715. if (secret)
  1716. authuser = strsep(&stringp, ":");
  1717. }
  1718. stringp = hostname;
  1719. hostname = strsep(&stringp, "/");
  1720. if (hostname)
  1721. contact = strsep(&stringp, "/");
  1722. if (!contact || !strlen(contact))
  1723. contact = "s";
  1724. stringp=hostname;
  1725. hostname = strsep(&stringp, ":");
  1726. porta = strsep(&stringp, ":");
  1727. if (porta && !atoi(porta)) {
  1728. ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
  1729. return -1;
  1730. }
  1731. hp = ast_gethostbyname(hostname, &ahp);
  1732. if (!hp) {
  1733. ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
  1734. return -1;
  1735. }
  1736. reg = malloc(sizeof(struct sip_registry));
  1737. if (reg) {
  1738. memset(reg, 0, sizeof(struct sip_registry));
  1739. strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
  1740. if (username)
  1741. strncpy(reg->username, username, sizeof(reg->username)-1);
  1742. if (hostname)
  1743. strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
  1744. if (authuser)
  1745. strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
  1746. if (secret)
  1747. strncpy(reg->secret, secret, sizeof(reg->secret)-1);
  1748. reg->expire = -1;
  1749. reg->timeout = -1;
  1750. reg->refresh = default_expiry;
  1751. reg->addr.sin_family = AF_INET;
  1752. memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
  1753. reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
  1754. reg->callid_valid = 0;
  1755. reg->ocseq = 101;
  1756. ast_mutex_lock(&regl.lock);
  1757. reg->next = regl.registrations;
  1758. regl.registrations = reg;
  1759. ast_mutex_unlock(&regl.lock);
  1760. } else {
  1761. ast_log(LOG_ERROR, "Out of memory\n");
  1762. return -1;
  1763. }
  1764. return 0;
  1765. }
  1766. static void parse(struct sip_request *req)
  1767. {
  1768. /* Divide fields by NULL's */
  1769. char *c;
  1770. int f = 0;
  1771. c = req->data;
  1772. /* First header starts immediately */
  1773. req->header[f] = c;
  1774. while(*c) {
  1775. if (*c == '\n') {
  1776. /* We've got a new header */
  1777. *c = 0;
  1778. #if 0
  1779. printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
  1780. #endif
  1781. if (!strlen(req->header[f])) {
  1782. /* Line by itself means we're now in content */
  1783. c++;
  1784. break;
  1785. }
  1786. if (f >= SIP_MAX_HEADERS - 1) {
  1787. ast_log(LOG_WARNING, "Too many SIP headers...\n");
  1788. } else
  1789. f++;
  1790. req->header[f] = c + 1;
  1791. } else if (*c == '\r') {
  1792. /* Ignore but eliminate \r's */
  1793. *c = 0;
  1794. }
  1795. c++;
  1796. }
  1797. /* Check for last header */
  1798. if (strlen(req->header[f]))
  1799. f++;
  1800. req->headers = f;
  1801. /* Now we process any mime content */
  1802. f = 0;
  1803. req->line[f] = c;
  1804. while(*c) {
  1805. if (*c == '\n') {
  1806. /* We've got a new line */
  1807. *c = 0;
  1808. #if 0
  1809. printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
  1810. #endif
  1811. if (f >= SIP_MAX_LINES - 1) {
  1812. ast_log(LOG_WARNING, "Too many SDP lines...\n");
  1813. } else
  1814. f++;
  1815. req->line[f] = c + 1;
  1816. } else if (*c == '\r') {
  1817. /* Ignore and eliminate \r's */
  1818. *c = 0;
  1819. }
  1820. c++;
  1821. }
  1822. /* Check for last line */
  1823. if (strlen(req->line[f]))
  1824. f++;
  1825. req->lines = f;
  1826. if (sipdebug)
  1827. ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
  1828. if (*c)
  1829. ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
  1830. }
  1831. static int process_sdp(struct sip_pvt *p, struct sip_request *req)
  1832. {
  1833. char *m;
  1834. char *c;
  1835. char *a;
  1836. char host[258];
  1837. int len = -1;
  1838. int portno=0;
  1839. int vportno=0;
  1840. int peercapability, peernoncodeccapability;
  1841. int vpeercapability=0, vpeernoncodeccapability=0;
  1842. struct sockaddr_in sin;
  1843. char *codecs;
  1844. struct hostent *hp;
  1845. struct ast_hostent ahp;
  1846. int codec;
  1847. int iterator;
  1848. int sendonly = 0;
  1849. int x;
  1850. /* Get codec and RTP info from SDP */
  1851. if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
  1852. ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
  1853. return -1;
  1854. }
  1855. m = get_sdp(req, "m");
  1856. c = get_sdp(req, "c");
  1857. if (!strlen(m) || !strlen(c)) {
  1858. ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
  1859. return -1;
  1860. }
  1861. if (sscanf(c, "IN IP4 %256s", host) != 1) {
  1862. ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
  1863. return -1;
  1864. }
  1865. /* XXX This could block for a long time, and block the main thread! XXX */
  1866. hp = ast_gethostbyname(host, &ahp);
  1867. if (!hp) {
  1868. ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
  1869. return -1;
  1870. }
  1871. sdpLineNum_iterator_init(&iterator);
  1872. while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
  1873. if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
  1874. portno = x;
  1875. // Scan through the RTP payload types specified in a "m=" line:
  1876. ast_rtp_pt_clear(p->rtp);
  1877. codecs = m + len;
  1878. while(strlen(codecs)) {
  1879. if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
  1880. ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
  1881. return -1;
  1882. }
  1883. if (sipdebug)
  1884. ast_verbose("Found audio format %s\n", ast_getformatname(codec));
  1885. ast_rtp_set_m_type(p->rtp, codec);
  1886. codecs += len;
  1887. /* Skip over any whitespace */
  1888. while(*codecs && (*codecs < 33)) codecs++;
  1889. }
  1890. }
  1891. if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
  1892. vportno = x;
  1893. // Scan through the RTP payload types specified in a "m=" line:
  1894. ast_rtp_pt_clear(p->vrtp);
  1895. codecs = m + len;
  1896. while(strlen(codecs)) {
  1897. if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
  1898. ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
  1899. return -1;
  1900. }
  1901. if (sipdebug)
  1902. ast_verbose("Found video format %s\n", ast_getformatname(codec));
  1903. ast_rtp_set_m_type(p->vrtp, codec);
  1904. codecs += len;
  1905. /* Skip over any whitespace */
  1906. while(*codecs && (*codecs < 33)) codecs++;
  1907. }
  1908. }
  1909. }
  1910. sin.sin_family = AF_INET;
  1911. memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
  1912. /* Setup audio port number */
  1913. sin.sin_port = htons(portno);
  1914. if (p->rtp && sin.sin_port)
  1915. ast_rtp_set_peer(p->rtp, &sin);
  1916. /* Setup video port number */
  1917. sin.sin_port = htons(vportno);
  1918. if (p->vrtp && sin.sin_port)
  1919. ast_rtp_set_peer(p->vrtp, &sin);
  1920. #if 0
  1921. printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  1922. #endif
  1923. // Next, scan through each "a=rtpmap:" line, noting each
  1924. // specified RTP payload type (with corresponding MIME subtype):
  1925. sdpLineNum_iterator_init(&iterator);
  1926. while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
  1927. char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
  1928. if (!strcasecmp(a, "sendonly")) {
  1929. sendonly=1;
  1930. continue;
  1931. }
  1932. if (!strcasecmp(a, "sendrecv")) {
  1933. sendonly=0;
  1934. }
  1935. if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
  1936. if (sipdebug)
  1937. ast_verbose("Found description format %s\n", mimeSubtype);
  1938. // Note: should really look at the 'freq' and '#chans' params too
  1939. ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
  1940. if (p->vrtp)
  1941. ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
  1942. }
  1943. // Now gather all of the codecs that were asked for:
  1944. ast_rtp_get_current_formats(p->rtp,
  1945. &peercapability, &peernoncodeccapability);
  1946. if (p->vrtp)
  1947. ast_rtp_get_current_formats(p->vrtp,
  1948. &vpeercapability, &vpeernoncodeccapability);
  1949. p->jointcapability = p->capability & (peercapability | vpeercapability);
  1950. p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
  1951. if (sipdebug) {
  1952. ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
  1953. p->capability, peercapability, vpeercapability, p->jointcapability);
  1954. ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
  1955. noncodeccapability, peernoncodeccapability,
  1956. p->noncodeccapability);
  1957. }
  1958. if (!p->jointcapability) {
  1959. ast_log(LOG_WARNING, "No compatible codecs!\n");
  1960. return -1;
  1961. }
  1962. if (p->owner) {
  1963. if (!(p->owner->nativeformats & p->jointcapability)) {
  1964. ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->jointcapability, p->owner->nativeformats);
  1965. p->owner->nativeformats = sip_codec_choose(p->jointcapability);
  1966. ast_set_read_format(p->owner, p->owner->readformat);
  1967. ast_set_write_format(p->owner, p->owner->writeformat);
  1968. }
  1969. if (p->owner->bridge) {
  1970. /* Turn on/off music on hold if we are holding/unholding */
  1971. if (sin.sin_addr.s_addr && !sendonly) {
  1972. ast_moh_stop(p->owner->bridge);
  1973. } else {
  1974. ast_moh_start(p->owner->bridge, NULL);
  1975. }
  1976. }
  1977. }
  1978. return 0;
  1979. }
  1980. static int add_header(struct sip_request *req, char *var, char *value)
  1981. {
  1982. if (req->len >= sizeof(req->data) - 4) {
  1983. ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
  1984. return -1;
  1985. }
  1986. if (req->lines) {
  1987. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  1988. return -1;
  1989. }
  1990. req->header[req->headers] = req->data + req->len;
  1991. snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
  1992. req->len += strlen(req->header[req->headers]);
  1993. if (req->headers < SIP_MAX_HEADERS)
  1994. req->headers++;
  1995. else {
  1996. ast_log(LOG_WARNING, "Out of header space\n");
  1997. return -1;
  1998. }
  1999. return 0;
  2000. }
  2001. static int add_blank_header(struct sip_request *req)
  2002. {
  2003. if (req->len >= sizeof(req->data) - 4) {
  2004. ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
  2005. return -1;
  2006. }
  2007. if (req->lines) {
  2008. ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
  2009. return -1;
  2010. }
  2011. req->header[req->headers] = req->data + req->len;
  2012. snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
  2013. req->len += strlen(req->header[req->headers]);
  2014. if (req->headers < SIP_MAX_HEADERS)
  2015. req->headers++;
  2016. else {
  2017. ast_log(LOG_WARNING, "Out of header space\n");
  2018. return -1;
  2019. }
  2020. return 0;
  2021. }
  2022. static int add_line(struct sip_request *req, char *line)
  2023. {
  2024. if (req->len >= sizeof(req->data) - 4) {
  2025. ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
  2026. return -1;
  2027. }
  2028. if (!req->lines) {
  2029. /* Add extra empty return */
  2030. snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
  2031. req->len += strlen(req->data + req->len);
  2032. }
  2033. req->line[req->lines] = req->data + req->len;
  2034. snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
  2035. req->len += strlen(req->line[req->lines]);
  2036. if (req->lines < SIP_MAX_LINES)
  2037. req->lines++;
  2038. else {
  2039. ast_log(LOG_WARNING, "Out of line space\n");
  2040. return -1;
  2041. }
  2042. return 0;
  2043. }
  2044. static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
  2045. {
  2046. char *tmp;
  2047. tmp = get_header(orig, field);
  2048. if (strlen(tmp)) {
  2049. /* Add what we're responding to */
  2050. return add_header(req, field, tmp);
  2051. }
  2052. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  2053. return -1;
  2054. }
  2055. static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
  2056. {
  2057. char *tmp;
  2058. int start = 0;
  2059. int copied = 0;
  2060. for (;;) {
  2061. tmp = __get_header(orig, field, &start);
  2062. if (strlen(tmp)) {
  2063. /* Add what we're responding to */
  2064. add_header(req, field, tmp);
  2065. copied++;
  2066. } else
  2067. break;
  2068. }
  2069. return copied ? 0 : -1;
  2070. }
  2071. static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
  2072. {
  2073. char *tmp;
  2074. int start = 0;
  2075. int copied = 0;
  2076. char new[256];
  2077. for (;;) {
  2078. tmp = __get_header(orig, field, &start);
  2079. if (strlen(tmp)) {
  2080. if (!copied && p->nat) {
  2081. #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
  2082. /* SLD: FIXME: Nice try, but the received= should not have a port */
  2083. /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
  2084. /* MAS: Yup, RFC says you can't do it. No way to indicate PAT...
  2085. good job fellas. */
  2086. if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
  2087. snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
  2088. else
  2089. #endif
  2090. snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
  2091. add_header(req, field, new);
  2092. } else {
  2093. /* Add what we're responding to */
  2094. add_header(req, field, tmp);
  2095. }
  2096. copied++;
  2097. } else
  2098. break;
  2099. }
  2100. if (!copied) {
  2101. ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
  2102. return -1;
  2103. }
  2104. return 0;
  2105. }
  2106. /* Add Route: header into request per learned route */
  2107. static void add_route(struct sip_request *req, struct sip_route *route)
  2108. {
  2109. char r[256], *p;
  2110. int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
  2111. if (!route) return;
  2112. p = r;
  2113. while (route) {
  2114. n = strlen(route->hop);
  2115. if ((n+3)>rem) break;
  2116. if (p != r) {
  2117. *p++ = ',';
  2118. --rem;
  2119. }
  2120. *p++ = '<';
  2121. strcpy(p, route->hop); p += n;
  2122. *p++ = '>';
  2123. rem -= (n+2);
  2124. route = route->next;
  2125. }
  2126. *p = '\0';
  2127. add_header(req, "Route", r);
  2128. }
  2129. static void set_destination(struct sip_pvt *p, char *uri)
  2130. {
  2131. char *h, *maddr, hostname[256];
  2132. int port, hn;
  2133. struct hostent *hp;
  2134. struct ast_hostent ahp;
  2135. /* Parse uri to h (host) and port - uri is already just the part inside the <> */
  2136. /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
  2137. if (sipdebug)
  2138. ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
  2139. /* Find and parse hostname */
  2140. h = strchr(uri, '@');
  2141. if (h)
  2142. ++h;
  2143. else {
  2144. h = uri;
  2145. if (strncmp(h, "sip:", 4) == 0)
  2146. h += 4;
  2147. else if (strncmp(h, "sips:", 5) == 0)
  2148. h += 5;
  2149. }
  2150. hn = strcspn(h, ":;>");
  2151. if (hn>255) hn=255;
  2152. strncpy(hostname, h, hn); hostname[hn] = '\0';
  2153. h+=hn;
  2154. /* Is "port" present? if not default to 5060 */
  2155. if (*h == ':') {
  2156. /* Parse port */
  2157. ++h;
  2158. port = strtol(h, &h, 10);
  2159. }
  2160. else
  2161. port = 5060;
  2162. /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
  2163. maddr = strstr(h, "maddr=");
  2164. if (maddr) {
  2165. maddr += 6;
  2166. hn = strspn(maddr, "0123456789.");
  2167. if (hn>255) hn=255;
  2168. strncpy(hostname, maddr, hn); hostname[hn] = '\0';
  2169. }
  2170. hp = ast_gethostbyname(hostname, &ahp);
  2171. if (hp == NULL) {
  2172. ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
  2173. return;
  2174. }
  2175. p->sa.sin_family = AF_INET;
  2176. memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
  2177. p->sa.sin_port = htons(port);
  2178. if (sipdebug)
  2179. ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
  2180. }
  2181. static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
  2182. {
  2183. /* Initialize a response */
  2184. if (req->headers || req->len) {
  2185. ast_log(LOG_WARNING, "Request already initialized?!?\n");
  2186. return -1;
  2187. }
  2188. req->header[req->headers] = req->data + req->len;
  2189. snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
  2190. req->len += strlen(req->header[req->headers]);
  2191. if (req->headers < SIP_MAX_HEADERS)
  2192. req->headers++;
  2193. else
  2194. ast_log(LOG_WARNING, "Out of header space\n");
  2195. return 0;
  2196. }
  2197. static int init_req(struct sip_request *req, char *resp, char *recip)
  2198. {
  2199. /* Initialize a response */
  2200. if (req->headers || req->len) {
  2201. ast_log(LOG_WARNING, "Request already initialized?!?\n");
  2202. return -1;
  2203. }
  2204. req->header[req->headers] = req->data + req->len;
  2205. snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
  2206. req->len += strlen(req->header[req->headers]);
  2207. if (req->headers < SIP_MAX_HEADERS)
  2208. req->headers++;
  2209. else
  2210. ast_log(LOG_WARNING, "Out of header space\n");
  2211. return 0;
  2212. }
  2213. static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
  2214. {
  2215. char newto[256] = "", *ot;
  2216. memset(resp, 0, sizeof(*resp));
  2217. init_resp(resp, msg, req);
  2218. copy_via_headers(p, resp, req, "Via");
  2219. if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
  2220. copy_header(resp, req, "From");
  2221. ot = get_header(req, "To");
  2222. if (!strstr(ot, "tag=")) {
  2223. /* Add the proper tag if we don't have it already. If they have specified
  2224. their tag, use it. Otherwise, use our own tag */
  2225. if (strlen(p->theirtag) && p->outgoing)
  2226. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  2227. else if (p->tag && !p->outgoing)
  2228. snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
  2229. else
  2230. strncpy(newto, ot, sizeof(newto) - 1);
  2231. ot = newto;
  2232. }
  2233. add_header(resp, "To", ot);
  2234. copy_header(resp, req, "Call-ID");
  2235. copy_header(resp, req, "CSeq");
  2236. add_header(resp, "User-Agent", "Asterisk PBX");
  2237. add_header(resp, "Allow", ALLOWED_METHODS);
  2238. if (p->expiry) {
  2239. /* For registration responses, we also need expiry and
  2240. contact info */
  2241. char contact[256];
  2242. char tmp[256];
  2243. snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
  2244. snprintf(tmp, sizeof(tmp), "%d", p->expiry);
  2245. add_header(resp, "Expires", tmp);
  2246. add_header(resp, "Contact", contact);
  2247. } else {
  2248. add_header(resp, "Contact", p->our_contact);
  2249. }
  2250. return 0;
  2251. }
  2252. static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
  2253. {
  2254. struct sip_request *orig = &p->initreq;
  2255. char stripped[80] ="";
  2256. char tmp[80];
  2257. char newto[256];
  2258. char *c, *n;
  2259. char *ot, *of;
  2260. memset(req, 0, sizeof(struct sip_request));
  2261. snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
  2262. if (!seqno) {
  2263. p->ocseq++;
  2264. seqno = p->ocseq;
  2265. }
  2266. if (strlen(p->uri)) {
  2267. c = p->uri;
  2268. } else {
  2269. if (p->outgoing)
  2270. strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
  2271. else
  2272. strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
  2273. c = strchr(stripped, '<');
  2274. if (c)
  2275. c++;
  2276. else
  2277. c = stripped;
  2278. n = strchr(c, '>');
  2279. if (n)
  2280. *n = '\0';
  2281. n = strchr(c, ';');
  2282. if (n)
  2283. *n = '\0';
  2284. }
  2285. init_req(req, msg, c);
  2286. snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
  2287. add_header(req, "Via", p->via);
  2288. if (p->route) {
  2289. set_destination(p, p->route->hop);
  2290. add_route(req, p->route->next);
  2291. }
  2292. ot = get_header(orig, "To");
  2293. of = get_header(orig, "From");
  2294. /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
  2295. as our original request, including tag (or presumably lack thereof) */
  2296. if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
  2297. /* Add the proper tag if we don't have it already. If they have specified
  2298. their tag, use it. Otherwise, use our own tag */
  2299. if (p->outgoing && strlen(p->theirtag))
  2300. snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
  2301. else if (!p->outgoing)
  2302. snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
  2303. else
  2304. snprintf(newto, sizeof(newto), "%s", ot);
  2305. ot = newto;
  2306. }
  2307. if (p->outgoing) {
  2308. add_header(req, "From", of);
  2309. add_header(req, "To", ot);
  2310. } else {
  2311. add_header(req, "From", ot);
  2312. add_header(req, "To", of);
  2313. }
  2314. add_header(req, "Contact", p->our_contact);
  2315. copy_header(req, orig, "Call-ID");
  2316. add_header(req, "CSeq", tmp);
  2317. add_header(req, "User-Agent", "Asterisk PBX");
  2318. return 0;
  2319. }
  2320. static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
  2321. {
  2322. struct sip_request resp;
  2323. int seqno = 0;
  2324. if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
  2325. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
  2326. return -1;
  2327. }
  2328. respprep(&resp, p, msg, req);
  2329. add_header(&resp, "Content-Length", "0");
  2330. add_blank_header(&resp);
  2331. return send_response(p, &resp, reliable, seqno);
  2332. }
  2333. static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
  2334. {
  2335. return __transmit_response(p, msg, req, 0);
  2336. }
  2337. static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
  2338. {
  2339. return __transmit_response(p, msg, req, 1);
  2340. }
  2341. static void append_date(struct sip_request *req)
  2342. {
  2343. char tmpdat[256];
  2344. struct tm tm;
  2345. time_t t;
  2346. time(&t);
  2347. gmtime_r(&t, &tm);
  2348. strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
  2349. add_header(req, "Date", tmpdat);
  2350. }
  2351. static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
  2352. {
  2353. struct sip_request resp;
  2354. respprep(&resp, p, msg, req);
  2355. append_date(&resp);
  2356. add_header(&resp, "Content-Length", "0");
  2357. add_blank_header(&resp);
  2358. return send_response(p, &resp, 0, 0);
  2359. }
  2360. static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
  2361. {
  2362. struct sip_request resp;
  2363. respprep(&resp, p, msg, req);
  2364. add_header(&resp, "Accept", "application/sdp");
  2365. add_header(&resp, "Content-Length", "0");
  2366. add_blank_header(&resp);
  2367. return send_response(p, &resp, 0, 0);
  2368. }
  2369. static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
  2370. {
  2371. struct sip_request resp;
  2372. char tmp[256];
  2373. int seqno = 0;
  2374. if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
  2375. ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
  2376. return -1;
  2377. }
  2378. snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
  2379. respprep(&resp, p, msg, req);
  2380. add_header(&resp, "Proxy-Authenticate", tmp);
  2381. add_header(&resp, "Content-Length", "0");
  2382. add_blank_header(&resp);
  2383. return send_response(p, &resp, reliable, seqno);
  2384. }
  2385. static int add_text(struct sip_request *req, char *text)
  2386. {
  2387. /* XXX Convert \n's to \r\n's XXX */
  2388. int len = strlen(text);
  2389. char clen[256];
  2390. snprintf(clen, sizeof(clen), "%d", len);
  2391. add_header(req, "Content-Type", "text/plain");
  2392. add_header(req, "Content-Length", clen);
  2393. add_line(req, text);
  2394. return 0;
  2395. }
  2396. static int add_digit(struct sip_request *req, char digit)
  2397. {
  2398. char tmp[256];
  2399. int len;
  2400. char clen[256];
  2401. snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
  2402. len = strlen(tmp);
  2403. snprintf(clen, sizeof(clen), "%d", len);
  2404. add_header(req, "Content-Type", "application/dtmf-relay");
  2405. add_header(req, "Content-Length", clen);
  2406. add_line(req, tmp);
  2407. return 0;
  2408. }
  2409. static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
  2410. {
  2411. int len;
  2412. int codec;
  2413. int alreadysent = 0;
  2414. char costr[80];
  2415. struct sockaddr_in sin;
  2416. struct sockaddr_in vsin;
  2417. struct sip_codec_pref *cur;
  2418. char v[256];
  2419. char s[256];
  2420. char o[256];
  2421. char c[256];
  2422. char t[256];
  2423. char m[256];
  2424. char m2[256];
  2425. char a[1024] = "";
  2426. char a2[1024] = "";
  2427. int x;
  2428. struct sockaddr_in dest;
  2429. struct sockaddr_in vdest = { 0, };
  2430. /* XXX We break with the "recommendation" and send our IP, in order that our
  2431. peer doesn't have to ast_gethostbyname() us XXX */
  2432. len = 0;
  2433. if (!p->rtp) {
  2434. ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
  2435. return -1;
  2436. }
  2437. if (!p->sessionid) {
  2438. p->sessionid = getpid();
  2439. p->sessionversion = p->sessionid;
  2440. } else
  2441. p->sessionversion++;
  2442. ast_rtp_get_us(p->rtp, &sin);
  2443. if (p->vrtp)
  2444. ast_rtp_get_us(p->vrtp, &vsin);
  2445. if (p->redirip.sin_addr.s_addr) {
  2446. dest.sin_port = p->redirip.sin_port;
  2447. dest.sin_addr = p->redirip.sin_addr;
  2448. } else if (rtp) {
  2449. ast_rtp_get_peer(rtp, &dest);
  2450. } else {
  2451. dest.sin_addr = p->ourip;
  2452. dest.sin_port = sin.sin_port;
  2453. }
  2454. /* Determine video destination */
  2455. if (p->vrtp) {
  2456. if (p->vredirip.sin_addr.s_addr) {
  2457. vdest.sin_port = p->vredirip.sin_port;
  2458. vdest.sin_addr = p->vredirip.sin_addr;
  2459. } else if (vrtp) {
  2460. ast_rtp_get_peer(vrtp, &vdest);
  2461. } else {
  2462. vdest.sin_addr = p->ourip;
  2463. vdest.sin_port = vsin.sin_port;
  2464. }
  2465. }
  2466. if (sipdebug)
  2467. ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port));
  2468. if (sipdebug && p->vrtp)
  2469. ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));
  2470. snprintf(v, sizeof(v), "v=0\r\n");
  2471. snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
  2472. snprintf(s, sizeof(s), "s=session\r\n");
  2473. snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
  2474. snprintf(t, sizeof(t), "t=0 0\r\n");
  2475. snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
  2476. snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
  2477. /* Start by sending our preferred codecs */
  2478. cur = prefs;
  2479. while(cur) {
  2480. if (p->jointcapability & cur->codec) {
  2481. if (sipdebug)
  2482. ast_verbose("Answering with preferred capability %d\n", cur->codec);
  2483. codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
  2484. if (codec > -1) {
  2485. snprintf(costr, sizeof(costr), " %d", codec);
  2486. if (cur->codec < AST_FORMAT_MAX_AUDIO) {
  2487. strncat(m, costr, sizeof(m) - strlen(m));
  2488. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
  2489. strncat(a, costr, sizeof(a));
  2490. } else {
  2491. strncat(m2, costr, sizeof(m2) - strlen(m2));
  2492. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
  2493. strncat(a2, costr, sizeof(a2));
  2494. }
  2495. }
  2496. }
  2497. alreadysent |= cur->codec;
  2498. cur = cur->next;
  2499. }
  2500. /* Now send any other common codecs, and non-codec formats: */
  2501. for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
  2502. if ((p->jointcapability & x) && !(alreadysent & x)) {
  2503. if (sipdebug)
  2504. ast_verbose("Answering with capability %d\n", x);
  2505. codec = ast_rtp_lookup_code(p->rtp, 1, x);
  2506. if (codec > -1) {
  2507. snprintf(costr, sizeof(costr), " %d", codec);
  2508. if (x < AST_FORMAT_MAX_AUDIO) {
  2509. strncat(m, costr, sizeof(m) - strlen(m));
  2510. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
  2511. strncat(a, costr, sizeof(a) - strlen(a));
  2512. } else {
  2513. strncat(m2, costr, sizeof(m2) - strlen(m2));
  2514. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
  2515. strncat(a2, costr, sizeof(a2) - strlen(a2));
  2516. }
  2517. }
  2518. }
  2519. }
  2520. for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
  2521. if (p->noncodeccapability & x) {
  2522. if (sipdebug)
  2523. ast_verbose("Answering with non-codec capability %d\n", x);
  2524. codec = ast_rtp_lookup_code(p->rtp, 0, x);
  2525. if (codec > -1) {
  2526. snprintf(costr, sizeof(costr), " %d", codec);
  2527. strncat(m, costr, sizeof(m) - strlen(m));
  2528. snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
  2529. strncat(a, costr, sizeof(a) - strlen(a));
  2530. if (x == AST_RTP_DTMF) {
  2531. /* Indicate we support DTMF... Not sure about 16, but MSN supports it so dang it, we will too... */
  2532. snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
  2533. codec);
  2534. strncat(a, costr, sizeof(a) - strlen(a));
  2535. }
  2536. }
  2537. }
  2538. }
  2539. strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
  2540. if (strlen(m) < sizeof(m) - 2)
  2541. strcat(m, "\r\n");
  2542. if (strlen(m2) < sizeof(m2) - 2)
  2543. strcat(m2, "\r\n");
  2544. if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
  2545. ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
  2546. len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
  2547. if (p->vrtp)
  2548. len += strlen(m2) + strlen(a2);
  2549. snprintf(costr, sizeof(costr), "%d", len);
  2550. add_header(resp, "Content-Type", "application/sdp");
  2551. add_header(resp, "Content-Length", costr);
  2552. add_line(resp, v);
  2553. add_line(resp, o);
  2554. add_line(resp, s);
  2555. add_line(resp, c);
  2556. add_line(resp, t);
  2557. add_line(resp, m);
  2558. add_line(resp, a);
  2559. if (p->vrtp) {
  2560. add_line(resp, m2);
  2561. add_line(resp, a2);
  2562. }
  2563. return 0;
  2564. }
  2565. static void copy_request(struct sip_request *dst,struct sip_request *src)
  2566. {
  2567. long offset;
  2568. int x;
  2569. offset = ((void *)dst) - ((void *)src);
  2570. /* First copy stuff */
  2571. memcpy(dst, src, sizeof(*dst));
  2572. /* Now fix pointer arithmetic */
  2573. for (x=0;x<src->headers;x++)
  2574. dst->header[x] += offset;
  2575. for (x=0;x<src->lines;x++)
  2576. dst->line[x] += offset;
  2577. }
  2578. static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
  2579. {
  2580. struct sip_request resp;
  2581. int seqno;
  2582. if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
  2583. ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
  2584. return -1;
  2585. }
  2586. respprep(&resp, p, msg, req);
  2587. add_sdp(&resp, p, NULL, NULL);
  2588. return send_response(p, &resp, retrans, seqno);
  2589. }
  2590. static int determine_firstline_parts( struct sip_request *req ) {
  2591. char *e, *cmd;
  2592. int len;
  2593. cmd= req->header[0];
  2594. while(*cmd && (*cmd < 33)) {
  2595. cmd++;
  2596. }
  2597. if (!*cmd) {
  2598. return -1;
  2599. }
  2600. e= cmd;
  2601. while(*e && (*e > 32)) {
  2602. e++;
  2603. }
  2604. /* Get the command */
  2605. if (*e) {
  2606. *e = '\0';
  2607. e++;
  2608. }
  2609. req->rlPart1= cmd;
  2610. while( *e && ( *e < 33 ) ) {
  2611. e++;
  2612. }
  2613. if( !*e ) {
  2614. return -1;
  2615. }
  2616. if ( !strcasecmp(cmd, "SIP/2.0") ) {
  2617. /* We have a response */
  2618. req->rlPart2= e;
  2619. len= strlen( req->rlPart2 );
  2620. if( len < 2 ) { return -1; }
  2621. e+= len - 1;
  2622. while( *e && *e<33 ) {
  2623. e--;
  2624. }
  2625. *(++e)= '\0';
  2626. } else {
  2627. /* We have a request */
  2628. if( *e == '<' ) {
  2629. e++;
  2630. if( !*e ) { return -1; }
  2631. }
  2632. req->rlPart2= e;
  2633. if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
  2634. return -1;
  2635. }
  2636. while( isspace( *(--e) ) ) {}
  2637. if( *e == '>' ) {
  2638. *e= '\0';
  2639. } else {
  2640. *(++e)= '\0';
  2641. }
  2642. }
  2643. return 1;
  2644. }
  2645. static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
  2646. {
  2647. struct sip_request req;
  2648. if (p->canreinvite == REINVITE_UPDATE)
  2649. reqprep(&req, p, "UPDATE", 0);
  2650. else {
  2651. p->branch++;
  2652. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
  2653. reqprep(&req, p, "INVITE", 0);
  2654. }
  2655. add_header(&req, "Allow", ALLOWED_METHODS);
  2656. add_sdp(&req, p, rtp, vrtp);
  2657. /* Use this as the basis */
  2658. copy_request(&p->initreq, &req);
  2659. parse(&p->initreq);
  2660. determine_firstline_parts(&p->initreq);
  2661. p->lastinvite = p->ocseq;
  2662. p->outgoing = 1;
  2663. return send_request(p, &req, 1, p->ocseq);
  2664. }
  2665. static void extract_uri(struct sip_pvt *p, struct sip_request *req)
  2666. {
  2667. char stripped[256]="";
  2668. char *c, *n;
  2669. strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
  2670. c = strchr(stripped, '<');
  2671. if (c)
  2672. c++;
  2673. else
  2674. c = stripped;
  2675. n = strchr(c, '>');
  2676. if (n)
  2677. *n = '\0';
  2678. n = strchr(c, ';');
  2679. if (n)
  2680. *n = '\0';
  2681. if (c && strlen(c))
  2682. strncpy(p->uri, c, sizeof(p->uri) - 1);
  2683. }
  2684. static void build_contact(struct sip_pvt *p)
  2685. {
  2686. /* Construct Contact: header */
  2687. if (ourport != 5060)
  2688. snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
  2689. else
  2690. snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
  2691. }
  2692. static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
  2693. {
  2694. char invite[256];
  2695. char from[256];
  2696. char to[256];
  2697. char tmp[80];
  2698. char cid[256];
  2699. char *l = callerid, *n=NULL;
  2700. snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
  2701. if (p->owner && p->owner->callerid) {
  2702. strcpy(cid, p->owner->callerid);
  2703. ast_callerid_parse(cid, &n, &l);
  2704. if (l)
  2705. ast_shrink_phone_number(l);
  2706. if (!l || !ast_isphonenumber(l))
  2707. l = callerid;
  2708. }
  2709. /* if user want's his callerid restricted */
  2710. if (p->restrictcid) {
  2711. l = CALLERID_UNKNOWN;
  2712. n = l;
  2713. }
  2714. if (!n || !strlen(n))
  2715. n = l;
  2716. /* Allow user to be overridden */
  2717. if (strlen(p->fromuser))
  2718. l = p->fromuser;
  2719. if ((ourport != 5060) && !strlen(p->fromdomain))
  2720. snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), ourport, p->tag);
  2721. else
  2722. snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
  2723. if (strlen(p->username)) {
  2724. if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
  2725. snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
  2726. } else {
  2727. snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
  2728. }
  2729. } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
  2730. snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
  2731. } else {
  2732. snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
  2733. }
  2734. strncpy(p->uri, invite, sizeof(p->uri) - 1);
  2735. /* If there is a VXML URL append it to the SIP URL */
  2736. if (vxml_url)
  2737. {
  2738. snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
  2739. }
  2740. else
  2741. {
  2742. snprintf(to, sizeof(to), "<%s>", invite );
  2743. }
  2744. memset(req, 0, sizeof(struct sip_request));
  2745. init_req(req, cmd, invite);
  2746. snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
  2747. add_header(req, "Via", p->via);
  2748. /* SLD: FIXME?: do Route: here too? I think not cos this is the first request.
  2749. * OTOH, then we won't have anything in p->route anyway */
  2750. add_header(req, "From", from);
  2751. strncpy(p->exten, l, sizeof(p->exten) - 1);
  2752. build_contact(p);
  2753. add_header(req, "To", to);
  2754. add_header(req, "Contact", p->our_contact);
  2755. add_header(req, "Call-ID", p->callid);
  2756. add_header(req, "CSeq", tmp);
  2757. add_header(req, "User-Agent", "Asterisk PBX");
  2758. }
  2759. static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
  2760. {
  2761. struct sip_request req;
  2762. if (init)
  2763. initreqprep(&req, p, cmd, vxml_url);
  2764. else
  2765. reqprep(&req, p, cmd, 0);
  2766. if (auth)
  2767. add_header(&req, authheader, auth);
  2768. append_date(&req);
  2769. if (!strcasecmp(cmd, "REFER")) {
  2770. if (strlen(p->refer_to))
  2771. add_header(&req, "Refer-To", p->refer_to);
  2772. if (strlen(p->referred_by))
  2773. add_header(&req, "Referred-By", p->referred_by);
  2774. }
  2775. if (distinctive_ring)
  2776. {
  2777. add_header(&req, "Alert-info",distinctive_ring);
  2778. }
  2779. add_header(&req, "Allow", ALLOWED_METHODS);
  2780. if (sdp) {
  2781. add_sdp(&req, p, NULL, NULL);
  2782. } else {
  2783. add_header(&req, "Content-Length", "0");
  2784. add_blank_header(&req);
  2785. }
  2786. if (!p->initreq.headers) {
  2787. /* Use this as the basis */
  2788. copy_request(&p->initreq, &req);
  2789. parse(&p->initreq);
  2790. determine_firstline_parts(&p->initreq);
  2791. }
  2792. p->lastinvite = p->ocseq;
  2793. return send_request(p, &req, 1, p->ocseq);
  2794. }
  2795. static int transmit_state_notify(struct sip_pvt *p, int state, int full)
  2796. {
  2797. char tmp[2000];
  2798. char from[256], to[256];
  2799. char *t, *c, *a;
  2800. char *mfrom, *mto;
  2801. struct sip_request req;
  2802. char clen[20];
  2803. strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
  2804. c = ditch_braces(from);
  2805. if (strncmp(c, "sip:", 4)) {
  2806. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  2807. return -1;
  2808. }
  2809. if ((a = strchr(c, ';'))) {
  2810. *a = '\0';
  2811. }
  2812. mfrom = c;
  2813. reqprep(&req, p, "NOTIFY", 0);
  2814. if (p->subscribed == 1) {
  2815. strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
  2816. c = ditch_braces(to);
  2817. if (strncmp(c, "sip:", 4)) {
  2818. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  2819. return -1;
  2820. }
  2821. if ((a = strchr(c, ';'))) {
  2822. *a = '\0';
  2823. }
  2824. mto = c;
  2825. add_header(&req, "Content-Type", "application/xpidf+xml");
  2826. if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
  2827. state = 2;
  2828. else if (state==AST_EXTENSION_INUSE)
  2829. state = 1;
  2830. else
  2831. state = 0;
  2832. t = tmp;
  2833. sprintf(t, "<?xml version=\"1.0\"?>\n");
  2834. t = tmp + strlen(tmp);
  2835. sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
  2836. t = tmp + strlen(tmp);
  2837. sprintf(t, "<presence>\n");
  2838. t = tmp + strlen(tmp);
  2839. sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
  2840. t = tmp + strlen(tmp);
  2841. sprintf(t, "<atom id=\"%s\">\n", p->exten);
  2842. t = tmp + strlen(tmp);
  2843. sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
  2844. t = tmp + strlen(tmp);
  2845. sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
  2846. t = tmp + strlen(tmp);
  2847. sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
  2848. t = tmp + strlen(tmp);
  2849. sprintf(t, "</address>\n</atom>\n</presence>\n");
  2850. } else {
  2851. add_header(&req, "Event", "dialog");
  2852. add_header(&req, "Content-Type", "application/dialog-info+xml");
  2853. t = tmp;
  2854. sprintf(t, "<?xml version=\"1.0\"?>\n");
  2855. t = tmp + strlen(tmp);
  2856. sprintf(t, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mfrom);
  2857. t = tmp + strlen(tmp);
  2858. sprintf(t, "<dialog id=\"%s\">\n", p->exten);
  2859. t = tmp + strlen(tmp);
  2860. sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
  2861. t = tmp + strlen(tmp);
  2862. sprintf(t, "</dialog>\n</dialog-info>\n");
  2863. }
  2864. if (t > tmp + sizeof(tmp))
  2865. ast_log(LOG_WARNING, "Buffer overflow detected!! (Please file a bug report)\n");
  2866. snprintf(clen, sizeof(clen), "%d", strlen(tmp));
  2867. add_header(&req, "Content-Length", clen);
  2868. add_line(&req, tmp);
  2869. return send_request(p, &req, 1, p->ocseq);
  2870. }
  2871. static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
  2872. {
  2873. struct sip_request req;
  2874. char tmp[256];
  2875. char tmp2[256];
  2876. char clen[20];
  2877. initreqprep(&req, p, "NOTIFY", NULL);
  2878. add_header(&req, "Event", "message-summary");
  2879. add_header(&req, "Content-Type", notifymime);
  2880. snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
  2881. snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
  2882. snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
  2883. add_header(&req, "Content-Length", clen);
  2884. add_line(&req, tmp);
  2885. add_line(&req, tmp2);
  2886. if (!p->initreq.headers) {
  2887. /* Use this as the basis */
  2888. copy_request(&p->initreq, &req);
  2889. parse(&p->initreq);
  2890. determine_firstline_parts(&p->initreq);
  2891. }
  2892. return send_request(p, &req, 1, p->ocseq);
  2893. }
  2894. static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
  2895. static int sip_reregister(void *data)
  2896. {
  2897. /* if we are here, we know that we need to reregister. */
  2898. struct sip_registry *r=(struct sip_registry *)data;
  2899. ast_mutex_lock(&regl.lock);
  2900. r->expire = -1;
  2901. __sip_do_register(r);
  2902. ast_mutex_unlock(&regl.lock);
  2903. return 0;
  2904. }
  2905. static int __sip_do_register(struct sip_registry *r)
  2906. {
  2907. int res;
  2908. res=transmit_register(r, "REGISTER", NULL, NULL);
  2909. return res;
  2910. }
  2911. static int sip_reg_timeout(void *data)
  2912. {
  2913. /* if we are here, our registration timed out, so we'll just do it over */
  2914. struct sip_registry *r=data;
  2915. struct sip_pvt *p;
  2916. int res;
  2917. ast_mutex_lock(&regl.lock);
  2918. ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr));
  2919. if (r->call) {
  2920. /* Unlink us, destroy old call. Locking is not relevent here because all this happens
  2921. in the single SIP manager thread. */
  2922. p = r->call;
  2923. p->registry = NULL;
  2924. r->call = NULL;
  2925. p->needdestroy = 1;
  2926. }
  2927. r->regstate=REG_STATE_UNREGISTERED;
  2928. r->timeout = -1;
  2929. res=transmit_register(r, "REGISTER", NULL, NULL);
  2930. ast_mutex_unlock(&regl.lock);
  2931. return 0;
  2932. }
  2933. static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
  2934. {
  2935. struct sip_request req;
  2936. char from[256];
  2937. char to[256];
  2938. char tmp[80];
  2939. char via[80];
  2940. char addr[80];
  2941. struct sip_pvt *p;
  2942. struct ast_hostent ahp;
  2943. struct hostent *hp;
  2944. /* exit if we are already in process with this registrar ?*/
  2945. if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
  2946. ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
  2947. return 0;
  2948. }
  2949. if (r->call) {
  2950. if (!auth) {
  2951. ast_log(LOG_WARNING, "Already have a call??\n");
  2952. return 0;
  2953. } else
  2954. p = r->call;
  2955. } else {
  2956. if (!r->callid_valid) {
  2957. build_callid(r->callid, sizeof(r->callid), __ourip);
  2958. r->callid_valid = 1;
  2959. }
  2960. p=sip_alloc( r->callid, &r->addr, 0);
  2961. if (!p) {
  2962. ast_log(LOG_WARNING, "Unable to allocate registration call\n");
  2963. return 0;
  2964. }
  2965. p->outgoing = 1;
  2966. r->call=p;
  2967. p->registry=r;
  2968. strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
  2969. strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
  2970. if (strlen(r->authuser))
  2971. strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
  2972. else
  2973. strncpy(p->peername, r->username, sizeof(p->peername)-1);
  2974. strncpy(p->username, r->username, sizeof(p->username)-1);
  2975. strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
  2976. /*
  2977. check which address we should use in our contact header
  2978. based on whether the remote host is on the external or
  2979. internal network so we can register through nat
  2980. */
  2981. if ((hp = ast_gethostbyname(r->hostname, &ahp))) {
  2982. if (ast_sip_ouraddrfor((struct in_addr *)hp->h_addr, &p->ourip))
  2983. memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
  2984. }
  2985. build_contact(p);
  2986. }
  2987. /* set up a timeout */
  2988. if (auth==NULL) {
  2989. if (r->timeout > -1) {
  2990. ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
  2991. ast_sched_del(sched, r->timeout);
  2992. }
  2993. r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
  2994. ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
  2995. }
  2996. if (strchr(r->username, '@')) {
  2997. snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
  2998. snprintf(to, sizeof(to), "<sip:%s>", r->username);
  2999. } else {
  3000. snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
  3001. snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, r->hostname);
  3002. }
  3003. snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
  3004. strncpy(p->uri, addr, sizeof(p->uri) - 1);
  3005. memset(&req, 0, sizeof(req));
  3006. init_req(&req, cmd, addr);
  3007. snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
  3008. p->ocseq = r->ocseq;
  3009. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  3010. snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
  3011. add_header(&req, "Via", via);
  3012. add_header(&req, "From", from);
  3013. add_header(&req, "To", to);
  3014. add_header(&req, "Call-ID", p->callid);
  3015. add_header(&req, "CSeq", tmp);
  3016. add_header(&req, "User-Agent", "Asterisk PBX");
  3017. if (auth)
  3018. add_header(&req, authheader, auth);
  3019. snprintf(tmp, sizeof(tmp), "%d", default_expiry);
  3020. add_header(&req, "Expires", tmp);
  3021. add_header(&req, "Contact", p->our_contact);
  3022. add_header(&req, "Event", "registration");
  3023. add_header(&req, "Content-Length", "0");
  3024. add_blank_header(&req);
  3025. copy_request(&p->initreq, &req);
  3026. parse(&p->initreq);
  3027. determine_firstline_parts(&p->initreq);
  3028. r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
  3029. return send_request(p, &req, 1, p->ocseq);
  3030. }
  3031. static int transmit_message_with_text(struct sip_pvt *p, char *text)
  3032. {
  3033. struct sip_request req;
  3034. reqprep(&req, p, "MESSAGE", 0);
  3035. add_text(&req, text);
  3036. return send_request(p, &req, 1, p->ocseq);
  3037. }
  3038. static int transmit_refer(struct sip_pvt *p, char *dest)
  3039. {
  3040. struct sip_request req;
  3041. char from[256];
  3042. char *of, *c;
  3043. char referto[256];
  3044. if (p->outgoing)
  3045. of = get_header(&p->initreq, "To");
  3046. else
  3047. of = get_header(&p->initreq, "From");
  3048. strncpy(from, of, sizeof(from) - 1);
  3049. of = ditch_braces(from);
  3050. strncpy(p->from,of,sizeof(p->from) - 1);
  3051. if (strncmp(of, "sip:", 4)) {
  3052. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  3053. } else
  3054. of += 4;
  3055. /* Get just the username part */
  3056. if ((c = strchr(of, '@'))) {
  3057. *c = '\0';
  3058. c++;
  3059. }
  3060. if (c) {
  3061. snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
  3062. } else {
  3063. snprintf(referto, sizeof(referto), "<sip:%s>", dest);
  3064. }
  3065. /* save in case we get 407 challenge */
  3066. strncpy(p->refer_to, referto, sizeof(p->refer_to) - 1);
  3067. strncpy(p->referred_by, p->our_contact, sizeof(p->referred_by) - 1);
  3068. reqprep(&req, p, "REFER", 0);
  3069. add_header(&req, "Refer-To", referto);
  3070. if (strlen(p->our_contact))
  3071. add_header(&req, "Referred-By", p->our_contact);
  3072. add_blank_header(&req);
  3073. return send_request(p, &req, 1, p->ocseq);
  3074. }
  3075. static int transmit_info_with_digit(struct sip_pvt *p, char digit)
  3076. {
  3077. struct sip_request req;
  3078. reqprep(&req, p, "INFO", 0);
  3079. add_digit(&req, digit);
  3080. return send_request(p, &req, 1, p->ocseq);
  3081. }
  3082. static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
  3083. {
  3084. struct sip_request resp;
  3085. reqprep(&resp, p, msg, seqno);
  3086. add_header(&resp, "Content-Length", "0");
  3087. add_blank_header(&resp);
  3088. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  3089. }
  3090. static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
  3091. {
  3092. struct sip_request resp;
  3093. reqprep(&resp, p, msg, seqno);
  3094. if (*p->realm)
  3095. {
  3096. char digest[256];
  3097. memset(digest,0,sizeof(digest));
  3098. build_reply_digest(p, msg, digest, sizeof(digest));
  3099. add_header(&resp, "Proxy-Authorization", digest);
  3100. }
  3101. add_header(&resp, "Content-Length", "0");
  3102. add_blank_header(&resp);
  3103. return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
  3104. }
  3105. static int expire_register(void *data)
  3106. {
  3107. struct sip_peer *p = data;
  3108. memset(&p->addr, 0, sizeof(p->addr));
  3109. ast_db_del("SIP/Registry", p->name);
  3110. p->expire = -1;
  3111. ast_device_state_changed("SIP/%s", p->name);
  3112. if (p->selfdestruct) {
  3113. p->delme = 1;
  3114. prune_peers();
  3115. }
  3116. return 0;
  3117. }
  3118. static int sip_poke_peer(struct sip_peer *peer);
  3119. static void reg_source_db(struct sip_peer *p)
  3120. {
  3121. char data[80];
  3122. struct in_addr in;
  3123. char *c, *d, *u;
  3124. int expiry;
  3125. if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
  3126. c = strchr(data, ':');
  3127. if (c) {
  3128. *c = '\0';
  3129. c++;
  3130. if (inet_aton(data, &in)) {
  3131. d = strchr(c, ':');
  3132. if (d) {
  3133. *d = '\0';
  3134. d++;
  3135. u = strchr(d, ':');
  3136. if (u) {
  3137. *u = '\0';
  3138. u++;
  3139. strncpy(p->username, u, sizeof(p->username));
  3140. }
  3141. ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding '%s' at %s@%s:%d for %d\n", p->name,
  3142. p->username, inet_ntoa(in), atoi(c), atoi(d));
  3143. sip_poke_peer(p);
  3144. expiry = atoi(d);
  3145. memset(&p->addr, 0, sizeof(p->addr));
  3146. p->addr.sin_family = AF_INET;
  3147. p->addr.sin_addr = in;
  3148. p->addr.sin_port = htons(atoi(c));
  3149. if (p->expire > -1)
  3150. ast_sched_del(sched, p->expire);
  3151. p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, (void *)p);
  3152. }
  3153. }
  3154. }
  3155. }
  3156. }
  3157. static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
  3158. {
  3159. char contact[80]= "";
  3160. char data[256];
  3161. char *expires = get_header(req, "Expires");
  3162. int expiry = atoi(expires);
  3163. char *c, *n, *pt;
  3164. int port;
  3165. struct hostent *hp;
  3166. struct ast_hostent ahp;
  3167. struct sockaddr_in oldsin;
  3168. if (!strlen(expires)) {
  3169. expires = strstr(get_header(req, "Contact"), "expires=");
  3170. if (expires) {
  3171. if (sscanf(expires + 8, "%d;", &expiry) != 1)
  3172. expiry = default_expiry;
  3173. } else {
  3174. /* Nothing has been specified */
  3175. expiry = default_expiry;
  3176. }
  3177. }
  3178. /* Look for brackets */
  3179. strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
  3180. c = contact;
  3181. if ((n=strchr(c, '<'))) {
  3182. c = n + 1;
  3183. n = strchr(c, '>');
  3184. /* Lose the part after the > */
  3185. if (n)
  3186. *n = '\0';
  3187. }
  3188. if (!strcasecmp(c, "*") || !expiry) {
  3189. /* This means remove all registrations and return OK */
  3190. memset(&p->addr, 0, sizeof(p->addr));
  3191. if (p->expire > -1)
  3192. ast_sched_del(sched, p->expire);
  3193. p->expire = -1;
  3194. ast_db_del("SIP/Registry", p->name);
  3195. if (option_verbose > 2)
  3196. ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->name);
  3197. return 0;
  3198. }
  3199. /* Make sure it's a SIP URL */
  3200. if (strncasecmp(c, "sip:", 4)) {
  3201. ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
  3202. } else
  3203. c += 4;
  3204. /* Ditch q */
  3205. n = strchr(c, ';');
  3206. if (n)
  3207. *n = '\0';
  3208. /* Grab host */
  3209. n = strchr(c, '@');
  3210. if (!n) {
  3211. n = c;
  3212. c = NULL;
  3213. } else {
  3214. *n = '\0';
  3215. n++;
  3216. }
  3217. pt = strchr(n, ':');
  3218. if (pt) {
  3219. *pt = '\0';
  3220. pt++;
  3221. port = atoi(pt);
  3222. } else
  3223. port = DEFAULT_SIP_PORT;
  3224. memcpy(&oldsin, &p->addr, sizeof(oldsin));
  3225. if (!p->nat) {
  3226. /* XXX This could block for a long time XXX */
  3227. hp = ast_gethostbyname(n, &ahp);
  3228. if (!hp) {
  3229. ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
  3230. return -1;
  3231. }
  3232. p->addr.sin_family = AF_INET;
  3233. memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
  3234. p->addr.sin_port = htons(port);
  3235. } else {
  3236. /* Don't trust the contact field. Just use what they came to us
  3237. with */
  3238. memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
  3239. }
  3240. if (c)
  3241. strncpy(p->username, c, sizeof(p->username) - 1);
  3242. else
  3243. strcpy(p->username, "");
  3244. if (p->expire > -1)
  3245. ast_sched_del(sched, p->expire);
  3246. if ((expiry < 1) || (expiry > max_expiry))
  3247. expiry = max_expiry;
  3248. if (!p->temponly)
  3249. p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
  3250. pvt->expiry = expiry;
  3251. snprintf(data, sizeof(data), "%s:%d:%d:%s", inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expiry, p->username);
  3252. ast_db_put("SIP/Registry", p->name, data);
  3253. if (inaddrcmp(&p->addr, &oldsin)) {
  3254. sip_poke_peer(p);
  3255. if (option_verbose > 2)
  3256. ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->name, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
  3257. }
  3258. return 0;
  3259. }
  3260. static void free_old_route(struct sip_route *route)
  3261. {
  3262. struct sip_route *next;
  3263. while (route) {
  3264. next = route->next;
  3265. free(route);
  3266. route = next;
  3267. }
  3268. }
  3269. static void list_route(struct sip_route *route)
  3270. {
  3271. if (!route) {
  3272. ast_verbose("list_route: no route\n");
  3273. return;
  3274. }
  3275. while (route) {
  3276. ast_verbose("list_route: hop: <%s>\n", route->hop);
  3277. route = route->next;
  3278. }
  3279. }
  3280. static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
  3281. {
  3282. struct sip_route *thishop, *head, *tail;
  3283. int start = 0;
  3284. int len;
  3285. char *rr, *contact, *c;
  3286. if (p->route) {
  3287. free_old_route(p->route);
  3288. p->route = NULL;
  3289. }
  3290. /* We build up head, then assign it to p->route when we're done */
  3291. head = NULL; tail = head;
  3292. /* 1st we pass through all the hops in any Record-Route headers */
  3293. for (;;) {
  3294. /* Each Record-Route header */
  3295. rr = __get_header(req, "Record-Route", &start);
  3296. if (*rr == '\0') break;
  3297. for (;;) {
  3298. /* Each route entry */
  3299. /* Find < */
  3300. rr = strchr(rr, '<');
  3301. if (!rr) break; /* No more hops */
  3302. ++rr;
  3303. len = strcspn(rr, ">");
  3304. /* Make a struct route */
  3305. thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
  3306. if (thishop) {
  3307. strncpy(thishop->hop, rr, len);
  3308. thishop->hop[len] = '\0';
  3309. ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
  3310. /* Link in */
  3311. if (backwards) {
  3312. /* Link in at head so they end up in reverse order */
  3313. thishop->next = head;
  3314. head = thishop;
  3315. /* If this was the first then it'll be the tail */
  3316. if (!tail) tail = thishop;
  3317. } else {
  3318. thishop->next = NULL;
  3319. /* Link in at the end */
  3320. if (tail)
  3321. tail->next = thishop;
  3322. else
  3323. head = thishop;
  3324. tail = thishop;
  3325. }
  3326. }
  3327. rr += len+1;
  3328. }
  3329. }
  3330. /* 2nd append the Contact: if there is one */
  3331. /* Can be multiple Contact headers, comma separated values - we just take the first */
  3332. contact = get_header(req, "Contact");
  3333. if (strlen(contact)) {
  3334. ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
  3335. /* Look for <: delimited address */
  3336. c = strchr(contact, '<');
  3337. if (c) {
  3338. /* Take to > */
  3339. ++c;
  3340. len = strcspn(c, ">");
  3341. } else {
  3342. /* No <> - just take the lot */
  3343. c = contact; len = strlen(contact);
  3344. }
  3345. thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
  3346. if (thishop) {
  3347. strncpy(thishop->hop, c, len);
  3348. thishop->hop[len] = '\0';
  3349. thishop->next = NULL;
  3350. /* Goes at the end */
  3351. if (tail)
  3352. tail->next = thishop;
  3353. else
  3354. head = thishop;
  3355. }
  3356. }
  3357. /* Store as new route */
  3358. p->route = head;
  3359. /* For debugging dump what we ended up with */
  3360. if (sipdebug)
  3361. list_route(p->route);
  3362. }
  3363. static void md5_hash(char *output, char *input)
  3364. {
  3365. struct MD5Context md5;
  3366. unsigned char digest[16];
  3367. char *ptr;
  3368. int x;
  3369. MD5Init(&md5);
  3370. MD5Update(&md5, input, strlen(input));
  3371. MD5Final(digest, &md5);
  3372. ptr = output;
  3373. for (x=0;x<16;x++)
  3374. ptr += sprintf(ptr, "%2.2x", digest[x]);
  3375. }
  3376. 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)
  3377. {
  3378. int res = -1;
  3379. /* Always OK if no secret */
  3380. if (!strlen(secret) && !strlen(md5secret))
  3381. return 0;
  3382. if (ignore) {
  3383. /* This is a retransmitted invite/register/etc, don't reconstruct authentication
  3384. information */
  3385. if (strlen(randdata)) {
  3386. if (!reliable) {
  3387. /* Resend message if this was NOT a reliable delivery. Otherwise the
  3388. retransmission should get it */
  3389. transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
  3390. /* Schedule auto destroy in 15 seconds */
  3391. sip_scheddestroy(p, 15000);
  3392. }
  3393. res = 1;
  3394. }
  3395. } else if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
  3396. snprintf(randdata, randlen, "%08x", rand());
  3397. transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
  3398. /* Schedule auto destroy in 15 seconds */
  3399. sip_scheddestroy(p, 15000);
  3400. res = 1;
  3401. } else {
  3402. /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
  3403. an example in the spec of just what it is you're doing a hash on. */
  3404. char a1[256];
  3405. char a2[256];
  3406. char a1_hash[256];
  3407. char a2_hash[256];
  3408. char resp[256];
  3409. char resp_hash[256]="";
  3410. char tmp[256] = "";
  3411. char *c;
  3412. char *z;
  3413. char *response ="";
  3414. char *resp_uri ="";
  3415. /* Find their response among the mess that we'r sent for comparison */
  3416. strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
  3417. c = tmp;
  3418. while(c) {
  3419. while (*c && (*c < 33)) c++;
  3420. if (!*c)
  3421. break;
  3422. if (!strncasecmp(c, "response=", strlen("response="))) {
  3423. c+= strlen("response=");
  3424. if ((*c == '\"')) {
  3425. response=++c;
  3426. if((c = strchr(c,'\"')))
  3427. *c = '\0';
  3428. } else {
  3429. response=c;
  3430. if((c = strchr(c,',')))
  3431. *c = '\0';
  3432. }
  3433. } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
  3434. c+= strlen("uri=");
  3435. if ((*c == '\"')) {
  3436. resp_uri=++c;
  3437. if((c = strchr(c,'\"')))
  3438. *c = '\0';
  3439. } else {
  3440. resp_uri=c;
  3441. if((c = strchr(c,',')))
  3442. *c = '\0';
  3443. }
  3444. } else
  3445. if ((z = strchr(c,' ')) || (z = strchr(c,','))) c=z;
  3446. if (c)
  3447. c++;
  3448. }
  3449. snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
  3450. if(strlen(resp_uri))
  3451. snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
  3452. else
  3453. snprintf(a2, sizeof(a2), "%s:%s", method, uri);
  3454. if (strlen(md5secret))
  3455. snprintf(a1_hash, sizeof(a1_hash), "%s", md5secret);
  3456. else
  3457. md5_hash(a1_hash, a1);
  3458. md5_hash(a2_hash, a2);
  3459. snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
  3460. md5_hash(resp_hash, resp);
  3461. /* resp_hash now has the expected response, compare the two */
  3462. if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
  3463. /* Auth is OK */
  3464. res = 0;
  3465. }
  3466. /* Assume success ;-) */
  3467. /* Eliminate random data */
  3468. strcpy(randdata, "");
  3469. }
  3470. return res;
  3471. }
  3472. static int cb_extensionstate(char *context, char* exten, int state, void *data)
  3473. {
  3474. struct sip_pvt *p = data;
  3475. if (state == -1) {
  3476. sip_scheddestroy(p, 15000);
  3477. p->stateid = -1;
  3478. return 0;
  3479. }
  3480. transmit_state_notify(p, state, 1);
  3481. if (option_debug)
  3482. ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
  3483. return 0;
  3484. }
  3485. static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri, int ignore)
  3486. {
  3487. int res = -1;
  3488. struct sip_peer *peer;
  3489. char tmp[256] = "";
  3490. char *name, *c;
  3491. char *t;
  3492. /* Terminate URI */
  3493. t = uri;
  3494. while(*t && (*t > 32) && (*t != ';'))
  3495. t++;
  3496. *t = '\0';
  3497. strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
  3498. c = ditch_braces(tmp);
  3499. /* Ditch ;user=phone */
  3500. name = strchr(c, ';');
  3501. if (name)
  3502. *name = '\0';
  3503. if (!strncmp(c, "sip:", 4)) {
  3504. name = c + 4;
  3505. } else {
  3506. name = c;
  3507. ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
  3508. }
  3509. c = strchr(name, '@');
  3510. if (c)
  3511. *c = '\0';
  3512. strncpy(p->exten, name, sizeof(p->exten) - 1);
  3513. build_contact(p);
  3514. ast_mutex_lock(&peerl.lock);
  3515. peer = peerl.peers;
  3516. while(peer) {
  3517. if (!strcasecmp(peer->name, name) && ast_apply_ha(peer->ha,sin))
  3518. break;
  3519. peer = peer->next;
  3520. }
  3521. ast_mutex_unlock(&peerl.lock);
  3522. #ifdef MYSQL_FRIENDS
  3523. if (!peer)
  3524. peer = mysql_peer(name, NULL);
  3525. #endif
  3526. if (peer) {
  3527. if (!peer->dynamic) {
  3528. ast_log(LOG_NOTICE, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
  3529. } else {
  3530. p->nat = peer->nat;
  3531. transmit_response(p, "100 Trying", req);
  3532. if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, peer->md5secret, "REGISTER", uri, 0, ignore))) {
  3533. sip_cancel_destroy(p);
  3534. if (parse_contact(p, peer, req)) {
  3535. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  3536. } else {
  3537. #ifdef MYSQL_FRIENDS
  3538. if (peer->temponly)
  3539. mysql_update_peer(peer->name, &peer->addr, peer->username, p->expiry);
  3540. #endif
  3541. /* Say OK and ask subsystem to retransmit msg counter */
  3542. transmit_response_with_date(p, "200 OK", req);
  3543. peer->lastmsgssent = -1;
  3544. res = 0;
  3545. }
  3546. }
  3547. }
  3548. }
  3549. if (!peer && autocreatepeer) {
  3550. /* Create peer if we have autocreate mode enabled */
  3551. peer = temp_peer(name);
  3552. if (peer) {
  3553. peer->next = peerl.peers;
  3554. peerl.peers = peer;
  3555. peer->lastmsgssent = -1;
  3556. sip_cancel_destroy(p);
  3557. if (parse_contact(p, peer, req)) {
  3558. ast_log(LOG_WARNING, "Failed to parse contact info\n");
  3559. } else {
  3560. /* Say OK and ask subsystem to retransmit msg counter */
  3561. transmit_response_with_date(p, "200 OK", req);
  3562. peer->lastmsgssent = -1;
  3563. res = 0;
  3564. }
  3565. }
  3566. }
  3567. if (!res) {
  3568. ast_device_state_changed("SIP/%s", peer->name);
  3569. }
  3570. if (res < 0)
  3571. transmit_response(p, "401 Unauthorized", &p->initreq);
  3572. if (peer && peer->temponly)
  3573. free(peer);
  3574. return res;
  3575. }
  3576. static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
  3577. {
  3578. char tmp[256] = "", *c, *a;
  3579. struct sip_request *req;
  3580. req = oreq;
  3581. if (!req)
  3582. req = &p->initreq;
  3583. strncpy(tmp, get_header(req, "Diversion"), sizeof(tmp) - 1);
  3584. if (!strlen(tmp))
  3585. return 0;
  3586. c = ditch_braces(tmp);
  3587. if (strncmp(c, "sip:", 4)) {
  3588. ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", c);
  3589. return -1;
  3590. }
  3591. c += 4;
  3592. if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
  3593. *a = '\0';
  3594. }
  3595. if (sipdebug)
  3596. ast_verbose("RDNIS is %s\n", c);
  3597. strncpy(p->rdnis, c, sizeof(p->rdnis) - 1);
  3598. return 0;
  3599. }
  3600. static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
  3601. {
  3602. char tmp[256] = "", *c, *a;
  3603. char tmpf[256]= "", *fr;
  3604. struct sip_request *req;
  3605. req = oreq;
  3606. if (!req)
  3607. req = &p->initreq;
  3608. if (req->rlPart2)
  3609. strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
  3610. c = ditch_braces(tmp);
  3611. strncpy(tmpf, get_header(req, "From"), sizeof(tmpf) - 1);
  3612. fr = ditch_braces(tmpf);
  3613. if (strncmp(c, "sip:", 4)) {
  3614. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  3615. return -1;
  3616. }
  3617. c += 4;
  3618. if (strlen(fr)) {
  3619. if (strncmp(fr, "sip:", 4)) {
  3620. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", fr);
  3621. return -1;
  3622. }
  3623. fr += 4;
  3624. } else
  3625. fr = NULL;
  3626. if ((a = strchr(c, '@'))) {
  3627. *a = '\0';
  3628. a++;
  3629. strncpy(p->domain, a, sizeof(p->domain)-1);
  3630. }
  3631. if ((a = strchr(c, ';'))) {
  3632. *a = '\0';
  3633. }
  3634. if (fr) {
  3635. if ((a = strchr(fr, '@')) || (a = strchr(fr, ';'))) {
  3636. *a = '\0';
  3637. }
  3638. }
  3639. if (sipdebug)
  3640. ast_verbose("Looking for %s in %s\n", c, p->context);
  3641. if (ast_exists_extension(NULL, p->context, c, 1, fr) ||
  3642. !strcmp(c, ast_pickup_ext())) {
  3643. if (!oreq)
  3644. strncpy(p->exten, c, sizeof(p->exten) - 1);
  3645. return 0;
  3646. }
  3647. if (ast_canmatch_extension(NULL, p->context, c, 1, fr) ||
  3648. !strncmp(c, ast_pickup_ext(),strlen(c))) {
  3649. return 1;
  3650. }
  3651. return -1;
  3652. }
  3653. static int hex2int(char a)
  3654. {
  3655. if ((a >= '0') && (a <= '9')) {
  3656. return a - '0';
  3657. } else if ((a >= 'a') && (a <= 'f')) {
  3658. return a - 'a' + 10;
  3659. } else if ((a >= 'A') && (a <= 'F')) {
  3660. return a - 'A' + 10;
  3661. }
  3662. return 0;
  3663. }
  3664. static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
  3665. {
  3666. char tmp[256] = "", *c, *a;
  3667. char tmp2[256] = "", *c2, *a2;
  3668. char tmp3[256];
  3669. char tmp4[256];
  3670. char tmp5[256] = ""; /* CallID to replace */
  3671. struct sip_request *req;
  3672. struct sip_pvt *p2;
  3673. req = oreq;
  3674. if (!req)
  3675. req = &p->initreq;
  3676. strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
  3677. strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
  3678. strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
  3679. strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
  3680. c = ditch_braces(tmp);
  3681. c2 = ditch_braces(tmp2);
  3682. if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
  3683. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  3684. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c2);
  3685. return -1;
  3686. }
  3687. c += 4;
  3688. c2 += 4;
  3689. if ((a = strchr(c, '?'))) {
  3690. /* Search for arguemnts */
  3691. *a = '\0';
  3692. a++;
  3693. if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
  3694. strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
  3695. a = tmp5;
  3696. while ((a = strchr(a, '%'))) {
  3697. /* Yuck! Pingtel converts the '@' to a %40, icky icky! Convert
  3698. back to an '@' */
  3699. if (strlen(a) < 3)
  3700. break;
  3701. *a = hex2int(a[1]) * 16 + hex2int(a[2]);
  3702. memmove(a + 1, a+3, strlen(a + 3) + 1);
  3703. a++;
  3704. }
  3705. if ((a = strchr(tmp5, '%')))
  3706. *a = '\0';
  3707. if ((a = strchr(tmp5, ';')))
  3708. *a = '\0';
  3709. /* Skip leading whitespace */
  3710. while(tmp5[0] && (tmp5[0] < 33))
  3711. memmove(tmp5, tmp5+1, strlen(tmp5));
  3712. }
  3713. }
  3714. if ((a = strchr(c, '@')))
  3715. *a = '\0';
  3716. if ((a = strchr(c, ';')))
  3717. *a = '\0';
  3718. if ((a2 = strchr(c2, '@')))
  3719. *a2 = '\0';
  3720. if ((a2 = strchr(c2, ';')))
  3721. *a2 = '\0';
  3722. if (sipdebug) {
  3723. ast_verbose("Looking for %s in %s\n", c, p->context);
  3724. ast_verbose("Looking for %s in %s\n", c2, p->context);
  3725. }
  3726. if (strlen(tmp5)) {
  3727. /* This is a supervised transfer */
  3728. ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
  3729. strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
  3730. strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
  3731. strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
  3732. strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
  3733. p->refer_call = NULL;
  3734. ast_mutex_lock(&iflock);
  3735. /* Search interfaces and find the match */
  3736. p2 = iflist;
  3737. while(p2) {
  3738. if (!strcmp(p2->callid, tmp5)) {
  3739. /* Go ahead and lock it before returning */
  3740. ast_mutex_lock(&p2->lock);
  3741. p->refer_call = p2;
  3742. break;
  3743. }
  3744. p2 = p2->next;
  3745. }
  3746. ast_mutex_unlock(&iflock);
  3747. if (p->refer_call)
  3748. return 0;
  3749. else
  3750. ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
  3751. } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
  3752. /* This is an unsupervised transfer */
  3753. ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
  3754. ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
  3755. ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
  3756. ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
  3757. strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
  3758. strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
  3759. strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
  3760. strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
  3761. p->refer_call = NULL;
  3762. return 0;
  3763. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  3764. return 1;
  3765. }
  3766. return -1;
  3767. }
  3768. static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
  3769. {
  3770. char tmp[256] = "", *c, *a;
  3771. struct sip_request *req;
  3772. req = oreq;
  3773. if (!req)
  3774. req = &p->initreq;
  3775. strncpy(tmp, get_header(req, "Also"), sizeof(tmp) - 1);
  3776. c = ditch_braces(tmp);
  3777. if (strncmp(c, "sip:", 4)) {
  3778. ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
  3779. return -1;
  3780. }
  3781. c += 4;
  3782. if ((a = strchr(c, '@')))
  3783. *a = '\0';
  3784. if ((a = strchr(c, ';')))
  3785. *a = '\0';
  3786. if (sipdebug) {
  3787. ast_verbose("Looking for %s in %s\n", c, p->context);
  3788. }
  3789. if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
  3790. /* This is an unsupervised transfer */
  3791. ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
  3792. strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
  3793. strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
  3794. strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
  3795. strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
  3796. p->refer_call = NULL;
  3797. return 0;
  3798. } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
  3799. return 1;
  3800. }
  3801. return -1;
  3802. }
  3803. static int check_via(struct sip_pvt *p, struct sip_request *req)
  3804. {
  3805. char via[256] = "";
  3806. char *c, *pt;
  3807. struct hostent *hp;
  3808. struct ast_hostent ahp;
  3809. memset(via, 0, sizeof(via));
  3810. strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
  3811. c = strchr(via, ';');
  3812. if (c)
  3813. *c = '\0';
  3814. c = strchr(via, ' ');
  3815. if (c) {
  3816. *c = '\0';
  3817. c++;
  3818. while(*c && (*c < 33))
  3819. c++;
  3820. if (strcmp(via, "SIP/2.0/UDP")) {
  3821. ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
  3822. return -1;
  3823. }
  3824. pt = strchr(c, ':');
  3825. if (pt) {
  3826. *pt = '\0';
  3827. pt++;
  3828. }
  3829. hp = ast_gethostbyname(c, &ahp);
  3830. if (!hp) {
  3831. ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
  3832. return -1;
  3833. }
  3834. memset(&p->sa, 0, sizeof(p->sa));
  3835. p->sa.sin_family = AF_INET;
  3836. memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
  3837. p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
  3838. if (sipdebug) {
  3839. if (p->nat)
  3840. ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
  3841. else
  3842. ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
  3843. }
  3844. }
  3845. return 0;
  3846. }
  3847. static char *get_calleridname(char *input,char *output)
  3848. {
  3849. char *end = strchr(input,'<');
  3850. char *tmp = strchr(input,'\"');
  3851. if (!end || (end == input)) return NULL;
  3852. /* move away from "<" */
  3853. end--;
  3854. /* we found "name" */
  3855. if (tmp && tmp < end) {
  3856. end = strchr(tmp+1,'\"');
  3857. if (!end) return NULL;
  3858. strncpy(output,tmp+1,(int)(end-tmp-1));
  3859. } else {
  3860. /* we didn't find "name" */
  3861. /* clear the empty characters in the begining*/
  3862. while(*input && (*input < 33))
  3863. input++;
  3864. /* clear the empty characters in the end */
  3865. while(*end && (*end < 33) && end > input)
  3866. end--;
  3867. if (end >= input)
  3868. strncpy(output,input,(int)(end-input)+1);
  3869. else
  3870. output = NULL;
  3871. }
  3872. return output;
  3873. }
  3874. static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri, int reliable, struct sockaddr_in *sin, int ignore)
  3875. {
  3876. struct sip_user *user;
  3877. struct sip_peer *peer;
  3878. char *of, from[256] = "", *c;
  3879. int res = 0;
  3880. char *t;
  3881. char calleridname[50];
  3882. /* Terminate URI */
  3883. t = uri;
  3884. while(*t && (*t > 32) && (*t != ';'))
  3885. t++;
  3886. *t = '\0';
  3887. of = get_header(req, "From");
  3888. strncpy(from, of, sizeof(from) - 1);
  3889. memset(calleridname,0,sizeof(calleridname));
  3890. get_calleridname(from,calleridname);
  3891. of = ditch_braces(from);
  3892. if (!strlen(p->exten)) {
  3893. t = uri;
  3894. if (!strncmp(t, "sip:", 4))
  3895. t+= 4;
  3896. strncpy(p->exten, t, sizeof(p->exten) - 1);
  3897. t = strchr(p->exten, '@');
  3898. if (t)
  3899. *t = '\0';
  3900. if (!strlen(p->our_contact))
  3901. build_contact(p);
  3902. }
  3903. if (strncmp(of, "sip:", 4)) {
  3904. ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
  3905. } else
  3906. of += 4;
  3907. /* Get just the username part */
  3908. if ((c = strchr(of, '@')))
  3909. *c = '\0';
  3910. if ((c = strchr(of, ':')))
  3911. *c = '\0';
  3912. if (*calleridname)
  3913. sprintf(p->callerid,"\"%s\" <%s>",calleridname,of);
  3914. else
  3915. strncpy(p->callerid, of, sizeof(p->callerid) - 1);
  3916. if (!strlen(of))
  3917. return 0;
  3918. ast_mutex_lock(&userl.lock);
  3919. user = userl.users;
  3920. while(user) {
  3921. if (!strcasecmp(user->name, of) && ast_apply_ha(user->ha,sin)) {
  3922. p->nat = user->nat;
  3923. if (p->rtp) {
  3924. ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
  3925. ast_rtp_setnat(p->rtp, p->nat);
  3926. }
  3927. if (p->vrtp) {
  3928. ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", p->nat);
  3929. ast_rtp_setnat(p->vrtp, p->nat);
  3930. }
  3931. if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, user->md5secret, cmd, uri, reliable, ignore))) {
  3932. sip_cancel_destroy(p);
  3933. if (strlen(user->context))
  3934. strncpy(p->context, user->context, sizeof(p->context) - 1);
  3935. if (strlen(user->callerid) && strlen(p->callerid))
  3936. strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
  3937. strncpy(p->username, user->name, sizeof(p->username) - 1);
  3938. strncpy(p->peersecret, user->secret, sizeof(p->peersecret) - 1);
  3939. strncpy(p->peermd5secret, user->md5secret, sizeof(p->peermd5secret) - 1);
  3940. strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode) -1);
  3941. strncpy(p->language, user->language, sizeof(p->language) -1);
  3942. p->canreinvite = user->canreinvite;
  3943. p->amaflags = user->amaflags;
  3944. p->callgroup = user->callgroup;
  3945. p->pickupgroup = user->pickupgroup;
  3946. p->restrictcid = user->restrictcid;
  3947. p->capability = user->capability;
  3948. p->jointcapability = user->capability;
  3949. if (user->dtmfmode) {
  3950. p->dtmfmode = user->dtmfmode;
  3951. if (p->dtmfmode & SIP_DTMF_RFC2833)
  3952. p->noncodeccapability |= AST_RTP_DTMF;
  3953. else
  3954. p->noncodeccapability &= ~AST_RTP_DTMF;
  3955. }
  3956. }
  3957. break;
  3958. }
  3959. user = user->next;
  3960. }
  3961. ast_mutex_unlock(&userl.lock);
  3962. if (!user) {
  3963. /* If we didn't find a user match, check for peers */
  3964. ast_mutex_lock(&peerl.lock);
  3965. peer = peerl.peers;
  3966. while(peer) {
  3967. if (!inaddrcmp(&peer->addr, &p->recv) ||
  3968. (peer->insecure && (peer->addr.sin_addr.s_addr == p->recv.sin_addr.s_addr))) {
  3969. break;
  3970. }
  3971. peer = peer->next;
  3972. }
  3973. ast_mutex_unlock(&peerl.lock);
  3974. #ifdef MYSQL_FRIENDS
  3975. if (!peer)
  3976. peer = mysql_peer(NULL, sin);
  3977. #endif
  3978. if (peer) {
  3979. /* Take the peer */
  3980. p->nat = peer->nat;
  3981. if (p->rtp) {
  3982. ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
  3983. ast_rtp_setnat(p->rtp, p->nat);
  3984. }
  3985. if (p->vrtp) {
  3986. ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", p->nat);
  3987. ast_rtp_setnat(p->vrtp, p->nat);
  3988. }
  3989. p->canreinvite = peer->canreinvite;
  3990. if (strlen(peer->username))
  3991. strncpy(p->username, peer->username, sizeof(p->username) - 1);
  3992. strncpy(p->peername, peer->name, sizeof(p->peername) - 1);
  3993. if (strlen(peer->context))
  3994. strncpy(p->context, peer->context, sizeof(p->context) - 1);
  3995. strncpy(p->peersecret, peer->secret, sizeof(p->peersecret) - 1);
  3996. strncpy(p->peermd5secret, peer->md5secret, sizeof(p->peermd5secret) - 1);
  3997. p->callgroup = peer->callgroup;
  3998. p->pickupgroup = peer->pickupgroup;
  3999. p->capability = peer->capability;
  4000. p->jointcapability = peer->capability;
  4001. if (peer->dtmfmode) {
  4002. p->dtmfmode = peer->dtmfmode;
  4003. if (p->dtmfmode & SIP_DTMF_RFC2833)
  4004. p->noncodeccapability |= AST_RTP_DTMF;
  4005. else
  4006. p->noncodeccapability &= ~AST_RTP_DTMF;
  4007. }
  4008. if (peer->temponly)
  4009. free(peer);
  4010. }
  4011. }
  4012. return res;
  4013. }
  4014. static int get_msg_text(char *buf, int len, struct sip_request *req)
  4015. {
  4016. int x;
  4017. int y;
  4018. strcpy(buf, "");
  4019. y = len - strlen(buf) - 5;
  4020. if (y < 0)
  4021. y = 0;
  4022. for (x=0;x<req->lines;x++) {
  4023. strncat(buf, req->line[x], y);
  4024. y -= strlen(req->line[x]) + 1;
  4025. if (y < 0)
  4026. y = 0;
  4027. if (y != 0)
  4028. strcat(buf, "\n");
  4029. }
  4030. return 0;
  4031. }
  4032. static void receive_message(struct sip_pvt *p, struct sip_request *req)
  4033. {
  4034. char buf[1024];
  4035. struct ast_frame f;
  4036. if (get_msg_text(buf, sizeof(buf), req)) {
  4037. ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
  4038. return;
  4039. }
  4040. if (p->owner) {
  4041. if (sipdebug)
  4042. ast_verbose("Message received: '%s'\n", buf);
  4043. memset(&f, 0, sizeof(f));
  4044. f.frametype = AST_FRAME_TEXT;
  4045. f.subclass = 0;
  4046. f.offset = 0;
  4047. f.data = buf;
  4048. f.datalen = strlen(buf);
  4049. ast_queue_frame(p->owner, &f, 0);
  4050. }
  4051. }
  4052. static int sip_show_inuse(int fd, int argc, char *argv[]) {
  4053. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-15.15s\n"
  4054. #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-15.15s\n"
  4055. struct sip_user *user;
  4056. char ilimits[40];
  4057. char olimits[40];
  4058. char iused[40];
  4059. char oused[40];
  4060. if (argc != 3)
  4061. return RESULT_SHOWUSAGE;
  4062. ast_mutex_lock(&userl.lock);
  4063. user = userl.users;
  4064. ast_cli(fd, FORMAT, "Username", "incoming", "Limit","outgoing","Limit");
  4065. for(user=userl.users;user;user=user->next) {
  4066. if (user->incominglimit)
  4067. snprintf(ilimits, sizeof(ilimits), "%d", user->incominglimit);
  4068. else
  4069. strcpy(ilimits, "N/A");
  4070. if (user->outgoinglimit)
  4071. snprintf(olimits, sizeof(olimits), "%d", user->outgoinglimit);
  4072. else
  4073. strcpy(olimits, "N/A");
  4074. snprintf(iused, sizeof(iused), "%d", user->inUse);
  4075. snprintf(oused, sizeof(oused), "%d", user->outUse);
  4076. ast_cli(fd, FORMAT2, user->name, iused, ilimits,oused,olimits);
  4077. }
  4078. ast_mutex_unlock(&userl.lock);
  4079. return RESULT_SUCCESS;
  4080. #undef FORMAT
  4081. #undef FORMAT2
  4082. }
  4083. static int sip_show_users(int fd, int argc, char *argv[])
  4084. {
  4085. #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
  4086. struct sip_user *user;
  4087. if (argc != 3)
  4088. return RESULT_SHOWUSAGE;
  4089. ast_mutex_lock(&userl.lock);
  4090. ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
  4091. for(user=userl.users;user;user=user->next) {
  4092. ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
  4093. user->context,user->ha ? "Yes" : "No");
  4094. }
  4095. ast_mutex_unlock(&userl.lock);
  4096. return RESULT_SUCCESS;
  4097. #undef FORMAT
  4098. }
  4099. static int sip_show_peers(int fd, int argc, char *argv[])
  4100. {
  4101. #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
  4102. #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
  4103. struct sip_peer *peer;
  4104. char name[256] = "";
  4105. if (argc != 3)
  4106. return RESULT_SHOWUSAGE;
  4107. ast_mutex_lock(&peerl.lock);
  4108. ast_cli(fd, FORMAT2, "Name/username", "Host", " ", "Mask", "Port", "Status");
  4109. for (peer = peerl.peers;peer;peer = peer->next) {
  4110. char nm[20] = "";
  4111. char status[20];
  4112. strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
  4113. if (strlen(peer->username))
  4114. snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
  4115. else
  4116. strncpy(name, peer->name, sizeof(name) - 1);
  4117. if (peer->maxms) {
  4118. if (peer->lastms < 0)
  4119. strcpy(status, "UNREACHABLE");
  4120. else if (peer->lastms > peer->maxms)
  4121. snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
  4122. else if (peer->lastms)
  4123. snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
  4124. else
  4125. strcpy(status, "UNKNOWN");
  4126. } else
  4127. strcpy(status, "Unmonitored");
  4128. ast_cli(fd, FORMAT, name,
  4129. peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
  4130. peer->dynamic ? "(D)" : " ",
  4131. nm,
  4132. ntohs(peer->addr.sin_port), status);
  4133. }
  4134. ast_mutex_unlock(&peerl.lock);
  4135. return RESULT_SUCCESS;
  4136. #undef FORMAT
  4137. #undef FORMAT2
  4138. }
  4139. static char *regstate2str(int regstate)
  4140. {
  4141. switch(regstate) {
  4142. case REG_STATE_UNREGISTERED:
  4143. return "Unregistered";
  4144. case REG_STATE_REGSENT:
  4145. return "Request Sent";
  4146. case REG_STATE_AUTHSENT:
  4147. return "Auth. Sent";
  4148. case REG_STATE_REGISTERED:
  4149. return "Registered";
  4150. case REG_STATE_REJECTED:
  4151. return "Rejected";
  4152. case REG_STATE_TIMEOUT:
  4153. return "Timeout";
  4154. case REG_STATE_NOAUTH:
  4155. return "No Authentication";
  4156. default:
  4157. return "Unknown";
  4158. }
  4159. }
  4160. static int sip_show_registry(int fd, int argc, char *argv[])
  4161. {
  4162. #define FORMAT2 "%-20.20s %-10.10s %8.8s %-20.20s\n"
  4163. #define FORMAT "%-20.20s %-10.10s %8d %-20.20s\n"
  4164. struct sip_registry *reg;
  4165. char host[80];
  4166. if (argc != 3)
  4167. return RESULT_SHOWUSAGE;
  4168. ast_mutex_lock(&regl.lock);
  4169. ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
  4170. for (reg = regl.registrations;reg;reg = reg->next) {
  4171. snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
  4172. ast_cli(fd, FORMAT, host,
  4173. reg->username, reg->refresh, regstate2str(reg->regstate));
  4174. }
  4175. ast_mutex_unlock(&regl.lock);
  4176. return RESULT_SUCCESS;
  4177. #undef FORMAT
  4178. #undef FORMAT2
  4179. }
  4180. static int sip_show_channels(int fd, int argc, char *argv[])
  4181. {
  4182. #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
  4183. #define FORMAT "%-15.15s %-10.10s %-11.11s %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s%s\n"
  4184. struct sip_pvt *cur;
  4185. int numchans = 0;
  4186. if (argc != 3)
  4187. return RESULT_SHOWUSAGE;
  4188. ast_mutex_lock(&iflock);
  4189. cur = iflist;
  4190. ast_cli(fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
  4191. while (cur) {
  4192. if (!cur->subscribed) {
  4193. ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr),
  4194. strlen(cur->username) ? cur->username : ( strlen(cur->callerid) ? cur->callerid: "(None)" ),
  4195. cur->callid,
  4196. cur->ocseq, cur->icseq,
  4197. 0,
  4198. 0,
  4199. ast_getformatname(cur->owner ? cur->owner->nativeformats : 0), cur->needdestroy ? "(d)" : "" );
  4200. numchans++;
  4201. }
  4202. cur = cur->next;
  4203. }
  4204. ast_mutex_unlock(&iflock);
  4205. ast_cli(fd, "%d active SIP channel(s)\n", numchans);
  4206. return RESULT_SUCCESS;
  4207. #undef FORMAT
  4208. #undef FORMAT2
  4209. }
  4210. static char *complete_sipch(char *line, char *word, int pos, int state)
  4211. {
  4212. int which=0;
  4213. struct sip_pvt *cur;
  4214. char *c = NULL;
  4215. ast_mutex_lock(&iflock);
  4216. cur = iflist;
  4217. while(cur) {
  4218. if (!strncasecmp(word, cur->callid, strlen(word))) {
  4219. if (++which > state) {
  4220. c = strdup(cur->callid);
  4221. break;
  4222. }
  4223. }
  4224. cur = cur->next;
  4225. }
  4226. ast_mutex_unlock(&iflock);
  4227. return c;
  4228. }
  4229. static int sip_show_channel(int fd, int argc, char *argv[])
  4230. {
  4231. struct sip_pvt *cur;
  4232. char tmp[256];
  4233. size_t len;
  4234. if (argc != 4)
  4235. return RESULT_SHOWUSAGE;
  4236. len = strlen(argv[3]);
  4237. ast_mutex_lock(&iflock);
  4238. cur = iflist;
  4239. while(cur) {
  4240. if (!strncasecmp(cur->callid, argv[3],len)) {
  4241. ast_cli(fd, "Call-ID: %s\n", cur->callid);
  4242. ast_cli(fd, "Our Codec Capability: %d\n", cur->capability);
  4243. ast_cli(fd, "Non-Codec Capability: %d\n", cur->noncodeccapability);
  4244. ast_cli(fd, "Joint Codec Capability: %d\n", cur->jointcapability);
  4245. ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
  4246. ast_cli(fd, "Received Address: %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
  4247. ast_cli(fd, "NAT Support: %s\n", cur->nat ? "Yes" : "No");
  4248. ast_cli(fd, "Our Tag: %08d\n", cur->tag);
  4249. ast_cli(fd, "Their Tag: %s\n", cur->theirtag);
  4250. ast_cli(fd, "Need Destroy: %d\n", cur->needdestroy);
  4251. ast_cli(fd, "Last Message: %s\n", cur->lastmsg);
  4252. strcpy(tmp, "");
  4253. if (cur->dtmfmode & SIP_DTMF_RFC2833)
  4254. strcat(tmp, "rfc2833 ");
  4255. if (cur->dtmfmode & SIP_DTMF_INFO)
  4256. strcat(tmp, "info ");
  4257. if (cur->dtmfmode & SIP_DTMF_INBAND)
  4258. strcat(tmp, "inband ");
  4259. ast_cli(fd, "DTMF Mode: %s\n\n", tmp);
  4260. }
  4261. cur = cur->next;
  4262. }
  4263. ast_mutex_unlock(&iflock);
  4264. if (!cur)
  4265. ast_cli(fd, "No such SIP Call ID starting with '%s'\n", argv[3]);
  4266. return RESULT_SUCCESS;
  4267. }
  4268. static void receive_info(struct sip_pvt *p, struct sip_request *req)
  4269. {
  4270. char buf[1024] = "";
  4271. unsigned int event;
  4272. char resp = 0;
  4273. struct ast_frame f;
  4274. char *c;
  4275. /* Try getting the "signal=" part */
  4276. if (strlen(c = get_sdp(req, "Signal")) || strlen(c = get_sdp(req, "d"))) {
  4277. strncpy(buf, c, sizeof(buf) - 1);
  4278. } else if (get_msg_text(buf, sizeof(buf), req)) {
  4279. /* Normal INFO method */
  4280. ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
  4281. return;
  4282. }
  4283. if (p->owner) {
  4284. if (strlen(buf)) {
  4285. if (sipdebug)
  4286. ast_verbose("DTMF received: '%c'\n", buf[0]);
  4287. if (buf[0] == '*')
  4288. event = 10;
  4289. else if (buf[0] == '#')
  4290. event = 11;
  4291. else
  4292. event = atoi(buf);
  4293. if (event < 10) {
  4294. resp = '0' + event;
  4295. } else if (event < 11) {
  4296. resp = '*';
  4297. } else if (event < 12) {
  4298. resp = '#';
  4299. } else if (event < 16) {
  4300. resp = 'A' + (event - 12);
  4301. }
  4302. memset(&f, 0, sizeof(f));
  4303. f.frametype = AST_FRAME_DTMF;
  4304. f.subclass = resp;
  4305. f.offset = 0;
  4306. f.data = NULL;
  4307. f.datalen = 0;
  4308. ast_queue_frame(p->owner, &f, 0);
  4309. }
  4310. }
  4311. }
  4312. static int sip_do_debug(int fd, int argc, char *argv[])
  4313. {
  4314. if (argc != 2)
  4315. return RESULT_SHOWUSAGE;
  4316. sipdebug = 1;
  4317. ast_cli(fd, "SIP Debugging Enabled\n");
  4318. return RESULT_SUCCESS;
  4319. }
  4320. static int sip_no_debug(int fd, int argc, char *argv[])
  4321. {
  4322. if (argc != 3)
  4323. return RESULT_SHOWUSAGE;
  4324. sipdebug = 0;
  4325. ast_cli(fd, "SIP Debugging Disabled\n");
  4326. return RESULT_SUCCESS;
  4327. }
  4328. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *digest, int digest_len);
  4329. static int do_register_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader) {
  4330. char digest[1024];
  4331. p->authtries++;
  4332. memset(digest,0,sizeof(digest));
  4333. if (reply_digest(p,req, header, "REGISTER", digest, sizeof(digest))) {
  4334. /* There's nothing to use for authentication */
  4335. return -1;
  4336. }
  4337. return transmit_register(p->registry,"REGISTER",digest, respheader);
  4338. }
  4339. static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init) {
  4340. char digest[1024];
  4341. p->authtries++;
  4342. memset(digest,0,sizeof(digest));
  4343. if (reply_digest(p,req, "Proxy-Authenticate", msg, digest, sizeof(digest) )) {
  4344. /* No way to authenticate */
  4345. return -1;
  4346. }
  4347. return transmit_invite(p,msg,!strcasecmp(msg, "INVITE"),digest, respheader, NULL,NULL, init);
  4348. }
  4349. static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
  4350. char tmp[512] = "";
  4351. char *realm = "";
  4352. char *nonce = "";
  4353. char *domain = "";
  4354. char *opaque = "";
  4355. char *c;
  4356. strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
  4357. if (!strlen(tmp))
  4358. return -1;
  4359. c = tmp;
  4360. c+=strlen("Digest ");
  4361. while (c) {
  4362. while (*c && (*c < 33)) c++;
  4363. if (!*c)
  4364. break;
  4365. if (!strncasecmp(c,"realm=", strlen("realm="))) {
  4366. c+=strlen("realm=");
  4367. if ((*c == '\"')) {
  4368. realm=++c;
  4369. if ((c = strchr(c,'\"')))
  4370. *c = '\0';
  4371. } else {
  4372. realm = c;
  4373. if ((c = strchr(c,',')))
  4374. *c = '\0';
  4375. }
  4376. } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
  4377. c+=strlen("nonce=");
  4378. if ((*c == '\"')) {
  4379. nonce=++c;
  4380. if ((c = strchr(c,'\"')))
  4381. *c = '\0';
  4382. } else {
  4383. nonce = c;
  4384. if ((c = strchr(c,',')))
  4385. *c = '\0';
  4386. }
  4387. } else if (!strncasecmp(c, "opaque=", strlen("opaque="))) {
  4388. c+=strlen("opaque=");
  4389. if ((*c == '\"')) {
  4390. opaque=++c;
  4391. if ((c = strchr(c,'\"')))
  4392. *c = '\0';
  4393. } else {
  4394. opaque = c;
  4395. if ((c = strchr(c,',')))
  4396. *c = '\0';
  4397. }
  4398. } else if (!strncasecmp(c, "domain=", strlen("domain="))) {
  4399. c+=strlen("domain=");
  4400. if ((*c == '\"')) {
  4401. domain=++c;
  4402. if ((c = strchr(c,'\"')))
  4403. *c = '\0';
  4404. } else {
  4405. domain = c;
  4406. if ((c = strchr(c,',')))
  4407. *c = '\0';
  4408. }
  4409. } else
  4410. c = strchr(c,',');
  4411. if (c)
  4412. c++;
  4413. }
  4414. if (strlen(tmp) >= sizeof(tmp))
  4415. ast_log(LOG_WARNING, "Buffer overflow detected! Please file a bug.\n");
  4416. /* copy realm and nonce for later authorization of CANCELs and BYEs */
  4417. strncpy(p->realm, realm, sizeof(p->realm)-1);
  4418. strncpy(p->nonce, nonce, sizeof(p->nonce)-1);
  4419. strncpy(p->domain, domain, sizeof(p->domain)-1);
  4420. strncpy(p->opaque, opaque, sizeof(p->opaque)-1);
  4421. build_reply_digest(p, orig_header, digest, digest_len);
  4422. return 0;
  4423. }
  4424. static int build_reply_digest(struct sip_pvt *p, char* orig_header, char* digest, int digest_len)
  4425. {
  4426. char a1[256];
  4427. char a2[256];
  4428. char a1_hash[256];
  4429. char a2_hash[256];
  4430. char resp[256];
  4431. char resp_hash[256];
  4432. char uri[256] = "";
  4433. if (strlen(p->domain))
  4434. strncpy(uri, p->domain, sizeof(uri) - 1);
  4435. else if (strlen(p->uri))
  4436. strncpy(uri, p->uri, sizeof(uri) - 1);
  4437. else
  4438. snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
  4439. snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,p->realm,p->peersecret);
  4440. snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
  4441. if (strlen(p->peermd5secret))
  4442. strncpy(a1_hash, p->peermd5secret, sizeof(a1_hash) - 1);
  4443. else
  4444. md5_hash(a1_hash,a1);
  4445. md5_hash(a2_hash,a2);
  4446. snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,p->nonce,a2_hash);
  4447. md5_hash(resp_hash,resp);
  4448. snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\", opaque=\"%s\"",p->peername,p->realm,uri,p->nonce,resp_hash, p->opaque);
  4449. return 0;
  4450. }
  4451. static char show_users_usage[] =
  4452. "Usage: sip show users\n"
  4453. " Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
  4454. static char show_inuse_usage[] =
  4455. "Usage: sip show inuse\n"
  4456. " List all users known to the SIP (Session Initiation Protocol) subsystem usage counters and limits.\n";
  4457. static char show_channels_usage[] =
  4458. "Usage: sip show channels\n"
  4459. " Lists all currently active SIP channels.\n";
  4460. static char show_channel_usage[] =
  4461. "Usage: sip show channel <channel>\n"
  4462. " Provides detailed status on a given SIP channel.\n";
  4463. static char show_peers_usage[] =
  4464. "Usage: sip show peers\n"
  4465. " Lists all known SIP peers.\n";
  4466. static char show_reg_usage[] =
  4467. "Usage: sip show registry\n"
  4468. " Lists all registration requests and status.\n";
  4469. static char debug_usage[] =
  4470. "Usage: sip debug\n"
  4471. " Enables dumping of SIP packets for debugging purposes\n";
  4472. static char no_debug_usage[] =
  4473. "Usage: sip no debug\n"
  4474. " Disables dumping of SIP packets for debugging purposes\n";
  4475. static char sip_reload_usage[] =
  4476. "Usage: sip reload\n"
  4477. " Reloads SIP configuration from sip.conf\n";
  4478. static struct ast_cli_entry cli_show_users =
  4479. { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
  4480. static struct ast_cli_entry cli_show_channels =
  4481. { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
  4482. static struct ast_cli_entry cli_show_channel =
  4483. { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch };
  4484. static struct ast_cli_entry cli_show_peers =
  4485. { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
  4486. static struct ast_cli_entry cli_inuse_show =
  4487. { { "sip", "show", "inuse", NULL }, sip_show_inuse, "List all inuse/limit", show_inuse_usage };
  4488. static struct ast_cli_entry cli_show_registry =
  4489. { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
  4490. static struct ast_cli_entry cli_debug =
  4491. { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
  4492. static struct ast_cli_entry cli_no_debug =
  4493. { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
  4494. static int sip_poke_peer_s(void *data)
  4495. {
  4496. struct sip_peer *peer = data;
  4497. peer->pokeexpire = -1;
  4498. sip_poke_peer(peer);
  4499. return 0;
  4500. }
  4501. static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
  4502. {
  4503. char tmp[256] = "";
  4504. char *s, *e;
  4505. strncpy(tmp, get_header(req, "Contact"), sizeof(tmp) - 1);
  4506. s = ditch_braces(tmp);
  4507. e = strchr(tmp, '@');
  4508. if (e)
  4509. *e = '\0';
  4510. if (!strncasecmp(s, "sip:", 4))
  4511. s += 4;
  4512. ast_log(LOG_DEBUG, "Found 302 Redirect to extension '%s'\n", s);
  4513. if (p->owner)
  4514. strncpy(p->owner->call_forward, s, sizeof(p->owner->call_forward) - 1);
  4515. }
  4516. static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int ignore)
  4517. {
  4518. char *to;
  4519. char *msg, *c;
  4520. struct ast_channel *owner;
  4521. struct sip_peer *peer;
  4522. int pingtime;
  4523. struct timeval tv;
  4524. int seqno=0;
  4525. c = get_header(req, "Cseq");
  4526. if (sscanf(c, "%d ", &seqno) != 1) {
  4527. ast_log(LOG_WARNING, "Unable to determine sequence number\n");
  4528. }
  4529. msg = strchr(c, ' ');
  4530. if (!msg) msg = ""; else msg++;
  4531. owner = p->owner;
  4532. if (owner)
  4533. owner->hangupcause = hangup_sip2cause(resp);
  4534. /* Acknowledge whatever it is destined for */
  4535. if ((resp >= 100) && (resp <= 199))
  4536. __sip_semi_ack(p, seqno, 0);
  4537. else
  4538. __sip_ack(p, seqno, 0);
  4539. /* Get their tag if we haven't already */
  4540. to = get_header(req, "To");
  4541. to = strstr(to, "tag=");
  4542. if (to) {
  4543. to += 4;
  4544. strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
  4545. to = strchr(p->theirtag, ';');
  4546. if (to)
  4547. *to = '\0';
  4548. }
  4549. if (p->peerpoke) {
  4550. /* We don't really care what the response is, just that it replied back.
  4551. Well, as long as it's not a 100 response... since we might
  4552. need to hang around for something more "difinitive" */
  4553. if (resp != 100) {
  4554. int statechanged = 0;
  4555. peer = p->peerpoke;
  4556. gettimeofday(&tv, NULL);
  4557. pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
  4558. (tv.tv_usec - peer->ps.tv_usec) / 1000;
  4559. if (pingtime < 1)
  4560. pingtime = 1;
  4561. if ((peer->lastms < 0) || (peer->lastms > peer->maxms)) {
  4562. if (pingtime <= peer->maxms) {
  4563. ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
  4564. statechanged = 1;
  4565. }
  4566. } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
  4567. if (pingtime > peer->maxms) {
  4568. ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
  4569. statechanged = 1;
  4570. }
  4571. }
  4572. if (!peer->lastms)
  4573. statechanged = 1;
  4574. peer->lastms = pingtime;
  4575. peer->call = NULL;
  4576. if (statechanged)
  4577. ast_device_state_changed("SIP/%s", peer->name);
  4578. if (peer->pokeexpire > -1)
  4579. ast_sched_del(sched, peer->pokeexpire);
  4580. if (!strcasecmp(msg, "INVITE"))
  4581. transmit_request(p, "ACK", seqno, 0);
  4582. p->needdestroy = 1;
  4583. /* Try again eventually */
  4584. if ((peer->lastms < 0) || (peer->lastms > peer->maxms))
  4585. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
  4586. else
  4587. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
  4588. }
  4589. } else if (p->outgoing) {
  4590. /* Acknowledge sequence number */
  4591. if (p->initid > -1) {
  4592. /* Don't auto congest anymore since we've gotten something useful back */
  4593. ast_sched_del(sched, p->initid);
  4594. p->initid = -1;
  4595. }
  4596. switch(resp) {
  4597. case 100:
  4598. break;
  4599. case 183:
  4600. if (!strcasecmp(msg, "INVITE")) {
  4601. if (strlen(get_header(req, "Content-Type")))
  4602. process_sdp(p, req);
  4603. if (p->owner) {
  4604. /* Queue a progress frame */
  4605. ast_queue_control(p->owner, AST_CONTROL_PROGRESS, 0);
  4606. }
  4607. }
  4608. break;
  4609. case 180:
  4610. if (p->owner) {
  4611. ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
  4612. if (p->owner->_state != AST_STATE_UP)
  4613. ast_setstate(p->owner, AST_STATE_RINGING);
  4614. }
  4615. break;
  4616. case 200:
  4617. if (!strcasecmp(msg, "NOTIFY")) {
  4618. /* They got the notify, this is the end */
  4619. if (p->owner) {
  4620. ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
  4621. ast_queue_hangup(p->owner, 0);
  4622. } else {
  4623. if (!p->subscribed) {
  4624. p->needdestroy = 1;
  4625. }
  4626. }
  4627. } else if (!strcasecmp(msg, "INVITE")) {
  4628. if (strlen(get_header(req, "Content-Type")))
  4629. process_sdp(p, req);
  4630. /* Save Record-Route for any later requests we make on this dialogue */
  4631. build_route(p, req, 1);
  4632. if (p->owner) {
  4633. if (p->owner->_state != AST_STATE_UP) {
  4634. ast_setstate(p->owner, AST_STATE_UP);
  4635. ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
  4636. } else {
  4637. struct ast_frame af = { AST_FRAME_NULL, };
  4638. ast_queue_frame(p->owner, &af, 0);
  4639. }
  4640. }
  4641. p->authtries = 0;
  4642. transmit_request(p, "ACK", seqno, 0);
  4643. /* Go ahead and send bye at this point */
  4644. if (p->pendingbye) {
  4645. transmit_request_with_auth(p, "BYE", 0, 1);
  4646. p->needdestroy = 1;
  4647. }
  4648. } else if (!strcasecmp(msg, "REGISTER")) {
  4649. /* char *exp; */
  4650. int expires;
  4651. struct sip_registry *r;
  4652. r=p->registry;
  4653. if (r) {
  4654. r->regstate=REG_STATE_REGISTERED;
  4655. ast_log(LOG_DEBUG, "Registration successful\n");
  4656. if (r->timeout > -1) {
  4657. ast_log(LOG_DEBUG, "Cancelling timeout %d\n", r->timeout);
  4658. ast_sched_del(sched, r->timeout);
  4659. }
  4660. r->timeout=-1;
  4661. r->call = NULL;
  4662. p->registry = NULL;
  4663. p->needdestroy = 1;
  4664. /* set us up for re-registering */
  4665. /* figure out how long we got registered for */
  4666. if (r->expire > -1)
  4667. ast_sched_del(sched, r->expire);
  4668. expires=atoi(get_header(req, "expires"));
  4669. if (!expires) expires=default_expiry;
  4670. if (expires > EXPIRY_GUARD_SECS)
  4671. expires -= EXPIRY_GUARD_SECS;
  4672. r->expire=ast_sched_add(sched, expires*1000, sip_reregister, r);
  4673. } else
  4674. ast_log(LOG_WARNING, "Got 200 OK on REGISTER that isn't a register\n");
  4675. }
  4676. break;
  4677. case 401: /* Not authorized on REGISTER */
  4678. if (!strcasecmp(msg, "INVITE")) {
  4679. /* First we ACK */
  4680. transmit_request(p, "ACK", seqno, 0);
  4681. /* Then we AUTH */
  4682. if ((p->authtries > 1) || do_proxy_auth(p, req, "WWW-Authenticate", "Authorization", "INVITE", 1)) {
  4683. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
  4684. p->needdestroy = 1;
  4685. }
  4686. } else if (p->registry && !strcasecmp(msg, "REGISTER")) {
  4687. if ((p->authtries > 1) || do_register_auth(p, req, "WWW-Authenticate", "Authorization")) {
  4688. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s'\n", get_header(&p->initreq, "From"));
  4689. p->needdestroy = 1;
  4690. }
  4691. } else
  4692. p->needdestroy = 1;
  4693. break;
  4694. case 407:
  4695. if (!strcasecmp(msg, "INVITE")) {
  4696. /* First we ACK */
  4697. transmit_request(p, "ACK", seqno, 0);
  4698. /* Then we AUTH */
  4699. /* But only if the packet wasn't marked as ignore in handle_request */
  4700. if(!ignore){
  4701. if ((p->authtries > 1) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", "INVITE", 1)) {
  4702. ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
  4703. p->needdestroy = 1;
  4704. }
  4705. }
  4706. } else if (!strcasecmp(msg, "BYE") || !strcasecmp(msg, "REFER")) {
  4707. if (!strlen(p->peername))
  4708. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
  4709. msg, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
  4710. if ((p->authtries > 1) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", msg, 0)) {
  4711. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
  4712. p->needdestroy = 1;
  4713. }
  4714. } else if (p->registry && !strcasecmp(msg, "REGISTER")) {
  4715. if ((p->authtries > 1) || do_register_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization")) {
  4716. ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
  4717. p->needdestroy = 1;
  4718. }
  4719. } else
  4720. p->needdestroy = 1;
  4721. break;
  4722. case 501: /* Not Implemented */
  4723. if (!strcasecmp(msg, "INVITE"))
  4724. ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
  4725. else
  4726. ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", inet_ntoa(p->sa.sin_addr), msg);
  4727. break;
  4728. default:
  4729. if ((resp >= 300) && (resp < 700)) {
  4730. if ((option_verbose > 2) && (resp != 487))
  4731. ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
  4732. p->alreadygone = 1;
  4733. if (p->rtp) {
  4734. /* Immediately stop RTP */
  4735. ast_rtp_stop(p->rtp);
  4736. }
  4737. if (p->vrtp) {
  4738. /* Immediately stop VRTP */
  4739. ast_rtp_stop(p->vrtp);
  4740. }
  4741. /* XXX Locking issues?? XXX */
  4742. switch(resp) {
  4743. case 300: /* Multiple Choices */
  4744. case 301: /* Moved permenantly */
  4745. case 302: /* Moved temporarily */
  4746. case 305: /* Use Proxy */
  4747. parse_moved_contact(p, req);
  4748. if (p->owner)
  4749. ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
  4750. break;
  4751. case 487:
  4752. /* channel now destroyed - dec the inUse counter */
  4753. if ( p->outgoing ) {
  4754. find_user(p, DEC_OUT_USE);
  4755. }
  4756. else {
  4757. find_user(p, DEC_IN_USE);
  4758. }
  4759. break;
  4760. case 486: /* Busy here */
  4761. case 600: /* Busy everywhere */
  4762. if (p->owner)
  4763. ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
  4764. break;
  4765. case 480: /* Temporarily Unavailable */
  4766. case 404: /* Not Found */
  4767. case 410: /* Gone */
  4768. case 500: /* Server error */
  4769. if (owner)
  4770. ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
  4771. break;
  4772. default:
  4773. /* Send hangup */
  4774. if (owner)
  4775. ast_queue_hangup(p->owner, 0);
  4776. break;
  4777. }
  4778. /* ACK on invite */
  4779. if (!strcasecmp(msg, "INVITE"))
  4780. transmit_request(p, "ACK", seqno, 0);
  4781. p->alreadygone = 1;
  4782. if (!p->owner)
  4783. p->needdestroy = 1;
  4784. } else
  4785. ast_log(LOG_NOTICE, "Dunno anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : inet_ntoa(p->sa.sin_addr));
  4786. }
  4787. } else {
  4788. if (sipdebug)
  4789. ast_verbose("Message is %s\n", msg);
  4790. switch(resp) {
  4791. case 200:
  4792. if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
  4793. transmit_request(p, "ACK", seqno, 0);
  4794. break;
  4795. case 407:
  4796. if (!strcasecmp(msg, "BYE") || !strcasecmp(msg, "REFER")) {
  4797. if (!strlen(p->peername))
  4798. ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
  4799. msg, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
  4800. if ((p->authtries > 1) || do_proxy_auth(p, req, "Proxy-Authenticate", "Proxy-Authorization", msg, 0)) {
  4801. ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
  4802. p->needdestroy = 1;
  4803. }
  4804. }
  4805. break;
  4806. }
  4807. }
  4808. }
  4809. static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
  4810. {
  4811. if (!p1->owner || !p2->owner) {
  4812. ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
  4813. return -1;
  4814. }
  4815. if (p1->owner->bridge) {
  4816. if (p2->owner->bridge)
  4817. ast_moh_stop(p2->owner->bridge);
  4818. ast_moh_stop(p1->owner->bridge);
  4819. ast_moh_stop(p1->owner);
  4820. ast_moh_stop(p2->owner);
  4821. if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
  4822. ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
  4823. return -1;
  4824. }
  4825. } else if (p2->owner->bridge) {
  4826. ast_moh_stop(p2->owner->bridge);
  4827. ast_moh_stop(p2->owner);
  4828. ast_moh_stop(p1->owner);
  4829. if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
  4830. ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
  4831. return -1;
  4832. }
  4833. } else {
  4834. ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
  4835. if (p1->owner)
  4836. ast_softhangup_nolock(p1->owner, AST_SOFTHANGUP_DEV);
  4837. if (p2->owner)
  4838. ast_softhangup_nolock(p2->owner, AST_SOFTHANGUP_DEV);
  4839. return -1;
  4840. }
  4841. return 0;
  4842. }
  4843. static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount)
  4844. {
  4845. /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
  4846. relatively static */
  4847. struct sip_request resp;
  4848. char *cmd;
  4849. char *cseq;
  4850. char *from;
  4851. char *e;
  4852. struct ast_channel *c=NULL;
  4853. struct ast_channel *transfer_to;
  4854. int seqno;
  4855. int len;
  4856. int ignore=0;
  4857. int respid;
  4858. int res;
  4859. int gotdest;
  4860. struct ast_frame af = { AST_FRAME_NULL, };
  4861. /* Clear out potential response */
  4862. memset(&resp, 0, sizeof(resp));
  4863. /* Get Method and Cseq */
  4864. cseq = get_header(req, "Cseq");
  4865. cmd = req->header[0];
  4866. /* Must have Cseq */
  4867. if (!strlen(cmd) || !strlen(cseq))
  4868. return -1;
  4869. if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
  4870. ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
  4871. return -1;
  4872. }
  4873. /* Get the command */
  4874. cseq += len;
  4875. /* Determine the request URI for sip, sips or tel URIs */
  4876. if( determine_firstline_parts( req ) < 0 ) {
  4877. return -1;
  4878. }
  4879. cmd= req->rlPart1;
  4880. e= req->rlPart2;
  4881. if (strcasecmp(cmd, "SIP/2.0")) {
  4882. /* Request coming in */
  4883. if (p->icseq && (p->icseq < seqno)) {
  4884. ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
  4885. return -1;
  4886. } else if (p->icseq && (p->icseq != seqno)) {
  4887. /* ignore means "don't do anything with it" but still have to
  4888. respond appropriately */
  4889. ignore=1;
  4890. }
  4891. if (!strlen(p->theirtag)) {
  4892. from = get_header(req, "From");
  4893. from = strstr(from, "tag=");
  4894. if (from) {
  4895. from += 4;
  4896. strncpy(p->theirtag, from, sizeof(p->theirtag) - 1);
  4897. from = strchr(p->theirtag, ';');
  4898. if (from)
  4899. *from = '\0';
  4900. }
  4901. }
  4902. snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
  4903. } else {
  4904. /* Response to our request -- Do some sanity checks */
  4905. if (!p->initreq.headers) {
  4906. ast_log(LOG_DEBUG, "That's odd... Got a response on a call we dont know about.\n");
  4907. p->needdestroy = 1;
  4908. return 0;
  4909. } else if (p->ocseq && (p->ocseq < seqno)) {
  4910. ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
  4911. return -1;
  4912. } else if (p->ocseq && (p->ocseq != seqno)) {
  4913. /* ignore means "don't do anything with it" but still have to
  4914. respond appropriately */
  4915. ignore=1;
  4916. }
  4917. }
  4918. if (strcmp(cmd, "SIP/2.0") && (seqno >= p->icseq))
  4919. /* Next should follow monotonically increasing */
  4920. p->icseq = seqno + 1;
  4921. /* Initialize the context if it hasn't been already */
  4922. if (!strcasecmp(cmd, "OPTIONS")) {
  4923. res = get_destination(p, req);
  4924. build_contact(p);
  4925. /* XXX Should we authenticate OPTIONS? XXX */
  4926. if (!strlen(p->context))
  4927. strncpy(p->context, context, sizeof(p->context) - 1);
  4928. if (res < 0)
  4929. transmit_response_with_allow(p, "404 Not Found", req);
  4930. else if (res > 0)
  4931. transmit_response_with_allow(p, "484 Address Incomplete", req);
  4932. else
  4933. transmit_response_with_allow(p, "200 OK", req);
  4934. /* Destroy if this OPTIONS was the opening request, but not if
  4935. it's in the middle of a normal call flow. */
  4936. if (!p->lastinvite)
  4937. p->needdestroy = 1;
  4938. } else if (!strcasecmp(cmd, "INVITE")) {
  4939. if (p->outgoing && p->owner && (p->owner->_state != AST_STATE_UP)) {
  4940. /* This is a call to ourself. Send ourselves an error code and stop
  4941. processing immediately, as SIP really has no good mechanism for
  4942. being able to call yourself */
  4943. transmit_response(p, "482 Loop Detected", req);
  4944. /* We do NOT destroy p here, so that our response will be accepted */
  4945. return 0;
  4946. }
  4947. /* Process the SDP portion */
  4948. if (!ignore) {
  4949. /* Use this as the basis */
  4950. if (sipdebug)
  4951. ast_verbose("Using latest request as basis request\n");
  4952. /* This call is no longer outgoing if it ever was */
  4953. p->outgoing = 0;
  4954. copy_request(&p->initreq, req);
  4955. check_via(p, req);
  4956. if (strlen(get_header(req, "Content-Type"))) {
  4957. if (process_sdp(p, req))
  4958. return -1;
  4959. } else {
  4960. p->jointcapability = p->capability;
  4961. ast_log(LOG_DEBUG, "Hm.... No sdp for the moment\n");
  4962. }
  4963. /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
  4964. if (p->owner)
  4965. ast_queue_frame(p->owner, &af, 0);
  4966. } else if (sipdebug)
  4967. ast_verbose("Ignoring this request\n");
  4968. if (!p->lastinvite) {
  4969. /* Handle authentication if this is our first invite */
  4970. res = check_user(p, req, cmd, e, 1, sin, ignore);
  4971. if (res) {
  4972. if (res < 0) {
  4973. ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
  4974. p->needdestroy = 1;
  4975. }
  4976. return 0;
  4977. }
  4978. /* Initialize the context if it hasn't been already */
  4979. if (!strlen(p->context))
  4980. strncpy(p->context, context, sizeof(p->context) - 1);
  4981. /* Check number of concurrent calls -vs- incoming limit HERE */
  4982. ast_log(LOG_DEBUG, "Check for res for %s\n", p->username);
  4983. res = find_user(p,INC_IN_USE);
  4984. if (res) {
  4985. if (res < 0) {
  4986. ast_log(LOG_DEBUG, "Failed to place call for user %s, too many calls\n", p->username);
  4987. p->needdestroy = 1;
  4988. }
  4989. return 0;
  4990. }
  4991. /* Get destination right away */
  4992. gotdest = get_destination(p, NULL);
  4993. get_rdnis(p, NULL);
  4994. extract_uri(p, req);
  4995. build_contact(p);
  4996. if (gotdest) {
  4997. if (gotdest < 0) {
  4998. transmit_response(p, "404 Not Found", req);
  4999. find_user(p,DEC_IN_USE);
  5000. } else {
  5001. transmit_response(p, "484 Address Incomplete", req);
  5002. find_user(p,DEC_IN_USE);
  5003. }
  5004. p->needdestroy = 1;
  5005. } else {
  5006. /* If no extension was specified, use the s one */
  5007. if (!strlen(p->exten))
  5008. strncpy(p->exten, "s", sizeof(p->exten) - 1);
  5009. /* Initialize tag */
  5010. p->tag = rand();
  5011. /* First invitation */
  5012. c = sip_new(p, AST_STATE_DOWN, strlen(p->username) ? p->username : NULL);
  5013. *recount = 1;
  5014. /* Save Record-Route for any later requests we make on this dialogue */
  5015. build_route(p, req, 0);
  5016. if (c) {
  5017. /* Pre-lock the call */
  5018. ast_mutex_lock(&c->lock);
  5019. }
  5020. }
  5021. } else
  5022. c = p->owner;
  5023. if (!ignore && p)
  5024. p->lastinvite = seqno;
  5025. if (c) {
  5026. switch(c->_state) {
  5027. case AST_STATE_DOWN:
  5028. transmit_response(p, "100 Trying", req);
  5029. ast_setstate(c, AST_STATE_RING);
  5030. if (strcmp(p->exten, ast_pickup_ext())) {
  5031. if (ast_pbx_start(c)) {
  5032. ast_log(LOG_WARNING, "Failed to start PBX :(\n");
  5033. /* Unlock locks so ast_hangup can do its magic */
  5034. ast_mutex_unlock(&c->lock);
  5035. ast_mutex_unlock(&p->lock);
  5036. ast_hangup(c);
  5037. ast_mutex_lock(&p->lock);
  5038. transmit_response_reliable(p, "503 Unavailable", req);
  5039. c = NULL;
  5040. }
  5041. } else {
  5042. ast_mutex_unlock(&c->lock);
  5043. if (ast_pickup_call(c)) {
  5044. ast_log(LOG_NOTICE, "Nothing to pick up\n");
  5045. transmit_response_reliable(p, "503 Unavailable", req);
  5046. p->alreadygone = 1;
  5047. /* Unlock locks so ast_hangup can do its magic */
  5048. ast_mutex_unlock(&p->lock);
  5049. ast_hangup(c);
  5050. ast_mutex_lock(&p->lock);
  5051. c = NULL;
  5052. } else {
  5053. ast_mutex_unlock(&p->lock);
  5054. ast_setstate(c, AST_STATE_DOWN);
  5055. ast_hangup(c);
  5056. ast_mutex_lock(&p->lock);
  5057. c = NULL;
  5058. }
  5059. }
  5060. break;
  5061. case AST_STATE_RING:
  5062. transmit_response(p, "100 Trying", req);
  5063. break;
  5064. case AST_STATE_RINGING:
  5065. transmit_response(p, "180 Ringing", req);
  5066. break;
  5067. case AST_STATE_UP:
  5068. transmit_response_with_sdp(p, "200 OK", req, 1);
  5069. break;
  5070. default:
  5071. ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
  5072. transmit_response(p, "100 Trying", req);
  5073. }
  5074. } else {
  5075. if (p && !p->needdestroy) {
  5076. ast_log(LOG_NOTICE, "Unable to create/find channel\n");
  5077. transmit_response_reliable(p, "503 Unavailable", req);
  5078. p->needdestroy = 1;
  5079. }
  5080. }
  5081. } else if (!strcasecmp(cmd, "REFER")) {
  5082. ast_log(LOG_DEBUG, "We found a REFER!\n");
  5083. if (!strlen(p->context))
  5084. strncpy(p->context, context, sizeof(p->context) - 1);
  5085. res = get_refer_info(p, req);
  5086. if (res < 0)
  5087. transmit_response_with_allow(p, "404 Not Found", req);
  5088. else if (res > 0)
  5089. transmit_response_with_allow(p, "484 Address Incomplete", req);
  5090. else {
  5091. transmit_response(p, "202 Accepted", req);
  5092. if (p->refer_call) {
  5093. ast_log(LOG_DEBUG,"202 Accepted (supervised)\n");
  5094. attempt_transfer(p, p->refer_call);
  5095. ast_mutex_unlock(&p->refer_call->lock);
  5096. p->refer_call = NULL;
  5097. p->gotrefer = 1;
  5098. } else {
  5099. ast_log(LOG_DEBUG,"202 Accepted (blind)\n");
  5100. c = p->owner;
  5101. if (c) {
  5102. transfer_to = c->bridge;
  5103. if (transfer_to) {
  5104. ast_moh_stop(transfer_to);
  5105. ast_async_goto(transfer_to,p->context, p->refer_to,1, 1);
  5106. } else {
  5107. ast_queue_hangup(p->owner, 0);
  5108. }
  5109. }
  5110. p->gotrefer = 1;
  5111. }
  5112. /* Always increment on a BYE */
  5113. transmit_request_with_auth(p, "BYE", 0, 1);
  5114. p->alreadygone = 1;
  5115. }
  5116. } else if (!strcasecmp(cmd, "CANCEL")) {
  5117. check_via(p, req);
  5118. p->alreadygone = 1;
  5119. if (p->rtp) {
  5120. /* Immediately stop RTP */
  5121. ast_rtp_stop(p->rtp);
  5122. }
  5123. if (p->vrtp) {
  5124. /* Immediately stop VRTP */
  5125. ast_rtp_stop(p->vrtp);
  5126. }
  5127. if (p->owner)
  5128. ast_queue_hangup(p->owner, 0);
  5129. else
  5130. p->needdestroy = 1;
  5131. if (p->initreq.len > 0) {
  5132. transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
  5133. transmit_response(p, "200 OK", req);
  5134. } else {
  5135. transmit_response_reliable(p, "481 Call Leg Does Not Exist", req);
  5136. }
  5137. } else if (!strcasecmp(cmd, "BYE")) {
  5138. copy_request(&p->initreq, req);
  5139. check_via(p, req);
  5140. p->alreadygone = 1;
  5141. if (p->rtp) {
  5142. /* Immediately stop RTP */
  5143. ast_rtp_stop(p->rtp);
  5144. }
  5145. if (p->vrtp) {
  5146. /* Immediately stop VRTP */
  5147. ast_rtp_stop(p->vrtp);
  5148. }
  5149. if (strlen(get_header(req, "Also"))) {
  5150. ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
  5151. inet_ntoa(p->recv.sin_addr));
  5152. if (!strlen(p->context))
  5153. strncpy(p->context, context, sizeof(p->context) - 1);
  5154. res = get_also_info(p, req);
  5155. if (!res) {
  5156. c = p->owner;
  5157. if (c) {
  5158. transfer_to = c->bridge;
  5159. if (transfer_to) {
  5160. /* Don't actually hangup here... */
  5161. ast_moh_stop(transfer_to);
  5162. ast_async_goto(transfer_to,p->context, p->refer_to,1, 1);
  5163. } else
  5164. ast_queue_hangup(p->owner, 0);
  5165. }
  5166. } else {
  5167. ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", inet_ntoa(p->recv.sin_addr));
  5168. ast_queue_hangup(p->owner, 0);
  5169. }
  5170. } else if (p->owner)
  5171. ast_queue_hangup(p->owner, 0);
  5172. else
  5173. p->needdestroy = 1;
  5174. transmit_response(p, "200 OK", req);
  5175. } else if (!strcasecmp(cmd, "MESSAGE")) {
  5176. if (sipdebug)
  5177. ast_verbose("Receiving message!\n");
  5178. receive_message(p, req);
  5179. transmit_response(p, "200 OK", req);
  5180. } else if (!strcasecmp(cmd, "SUBSCRIBE")) {
  5181. if (!ignore) {
  5182. /* Use this as the basis */
  5183. if (sipdebug)
  5184. ast_verbose("Using latest SUBSCRIBE request as basis request\n");
  5185. /* This call is no longer outgoing if it ever was */
  5186. p->outgoing = 0;
  5187. copy_request(&p->initreq, req);
  5188. check_via(p, req);
  5189. } else if (sipdebug)
  5190. ast_verbose("Ignoring this request\n");
  5191. if (!p->lastinvite) {
  5192. /* Handle authentication if this is our first subscribe */
  5193. res = check_user(p, req, cmd, e, 0, sin, ignore);
  5194. if (res) {
  5195. if (res < 0) {
  5196. ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
  5197. p->needdestroy = 1;
  5198. }
  5199. return 0;
  5200. }
  5201. /* Initialize the context if it hasn't been already */
  5202. if (!strlen(p->context))
  5203. strncpy(p->context, context, sizeof(p->context) - 1);
  5204. /* Get destination right away */
  5205. gotdest = get_destination(p, NULL);
  5206. build_contact(p);
  5207. if (gotdest) {
  5208. if (gotdest < 0)
  5209. transmit_response(p, "404 Not Found", req);
  5210. else
  5211. transmit_response(p, "484 Address Incomplete", req);
  5212. p->needdestroy = 1;
  5213. } else {
  5214. /* Initialize tag */
  5215. p->tag = rand();
  5216. if (!strcmp(get_header(req, "Accept"), "application/dialog-info+xml"))
  5217. p->subscribed = 2;
  5218. else
  5219. p->subscribed = 1;
  5220. p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
  5221. }
  5222. } else
  5223. c = p->owner;
  5224. if (!ignore && p)
  5225. p->lastinvite = seqno;
  5226. if (p) {
  5227. if (!(p->expiry = atoi(get_header(req, "Expires")))) {
  5228. transmit_response(p, "200 OK", req);
  5229. p->needdestroy = 1;
  5230. return 0;
  5231. }
  5232. // The next line can be removed if the SNOM200 Expires bug is fixed
  5233. if (p->subscribed == 1) {
  5234. if (p->expiry>max_expiry)
  5235. p->expiry = max_expiry;
  5236. }
  5237. transmit_response(p, "200 OK", req);
  5238. sip_scheddestroy(p, (p->expiry+10)*1000);
  5239. transmit_state_notify(p, ast_extension_state(NULL, p->context, p->exten),1);
  5240. }
  5241. } else if (!strcasecmp(cmd, "INFO")) {
  5242. if (sipdebug)
  5243. ast_verbose("Receiving DTMF!\n");
  5244. receive_info(p, req);
  5245. transmit_response(p, "200 OK", req);
  5246. } else if (!strcasecmp(cmd, "REGISTER")) {
  5247. /* Use this as the basis */
  5248. if (sipdebug)
  5249. ast_verbose("Using latest request as basis request\n");
  5250. copy_request(&p->initreq, req);
  5251. check_via(p, req);
  5252. if ((res = register_verify(p, sin, req, e, ignore)) < 0)
  5253. ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s'\n", get_header(req, "To"), inet_ntoa(sin->sin_addr));
  5254. if (res < 1) {
  5255. p->needdestroy = 1;
  5256. }
  5257. } else if (!strcasecmp(cmd, "ACK")) {
  5258. /* Uhm, I haven't figured out the point of the ACK yet. Are we
  5259. supposed to retransmit responses until we get an ack?
  5260. Make sure this is on a valid call */
  5261. __sip_ack(p, seqno, 1);
  5262. if (strlen(get_header(req, "Content-Type"))) {
  5263. if (process_sdp(p, req))
  5264. return -1;
  5265. }
  5266. if (!p->lastinvite && !strlen(p->randdata))
  5267. p->needdestroy = 1;
  5268. } else if (!strcasecmp(cmd, "SIP/2.0")) {
  5269. extract_uri(p, req);
  5270. while(*e && (*e < 33)) e++;
  5271. if (sscanf(e, "%i %n", &respid, &len) != 1) {
  5272. ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
  5273. } else {
  5274. handle_response(p, respid, e + len, req,ignore);
  5275. }
  5276. } else {
  5277. transmit_response_with_allow(p, "405 Method Not Allowed", req);
  5278. ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
  5279. cmd, inet_ntoa(p->sa.sin_addr));
  5280. /* If this is some new method, and we don't have a call, destroy it now */
  5281. if (!p->initreq.headers)
  5282. p->needdestroy = 1;
  5283. }
  5284. return 0;
  5285. }
  5286. static int sipsock_read(int *id, int fd, short events, void *ignore)
  5287. {
  5288. struct sip_request req;
  5289. struct sockaddr_in sin = { 0, };
  5290. struct sip_pvt *p;
  5291. int res;
  5292. int len;
  5293. int recount = 0;
  5294. len = sizeof(sin);
  5295. memset(&req, 0, sizeof(req));
  5296. res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
  5297. if (res < 0) {
  5298. if (errno != ECONNREFUSED)
  5299. ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
  5300. return 1;
  5301. }
  5302. req.data[res] = '\0';
  5303. req.len = res;
  5304. if (sipdebug)
  5305. ast_verbose("\n\nSip read: \n%s\n", req.data);
  5306. parse(&req);
  5307. if (req.headers < 2) {
  5308. /* Must have at least two headers */
  5309. return 1;
  5310. }
  5311. /* Process request, with netlock held */
  5312. retrylock:
  5313. ast_mutex_lock(&netlock);
  5314. p = find_call(&req, &sin);
  5315. if (p) {
  5316. /* Go ahead and lock the owner if it has one -- we may need it */
  5317. if (p->owner && ast_mutex_trylock(&p->owner->lock)) {
  5318. ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
  5319. ast_mutex_unlock(&p->lock);
  5320. ast_mutex_unlock(&netlock);
  5321. /* Sleep infintismly short amount of time */
  5322. usleep(1);
  5323. goto retrylock;
  5324. }
  5325. memcpy(&p->recv, &sin, sizeof(p->recv));
  5326. handle_request(p, &req, &sin, &recount);
  5327. if (p->owner)
  5328. ast_mutex_unlock(&p->owner->lock);
  5329. ast_mutex_unlock(&p->lock);
  5330. }
  5331. ast_mutex_unlock(&netlock);
  5332. if (recount)
  5333. ast_update_use_count();
  5334. return 1;
  5335. }
  5336. static int sip_send_mwi_to_peer(struct sip_peer *peer)
  5337. {
  5338. /* Called with peerl lock, but releases it */
  5339. struct sip_pvt *p;
  5340. char name[256] = "";
  5341. int newmsgs, oldmsgs;
  5342. /* Check for messages */
  5343. ast_app_messagecount(peer->mailbox, &newmsgs, &oldmsgs);
  5344. time(&peer->lastmsgcheck);
  5345. /* Return now if it's the same thing we told them last time */
  5346. if (((newmsgs << 8) | (oldmsgs)) == peer->lastmsgssent) {
  5347. ast_mutex_unlock(&peerl.lock);
  5348. return 0;
  5349. }
  5350. p = sip_alloc(NULL, NULL, 0);
  5351. if (!p) {
  5352. ast_log(LOG_WARNING, "Unable to build sip pvt data for MWI\n");
  5353. ast_mutex_unlock(&peerl.lock);
  5354. return -1;
  5355. }
  5356. strncpy(name, peer->name, sizeof(name) - 1);
  5357. peer->lastmsgssent = ((newmsgs << 8) | (oldmsgs));
  5358. ast_mutex_unlock(&peerl.lock);
  5359. if (create_addr(p, name)) {
  5360. /* Maybe they're not registered, etc. */
  5361. sip_destroy(p);
  5362. return 0;
  5363. }
  5364. /* Recalculate our side, and recalculate Call ID */
  5365. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  5366. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  5367. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  5368. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
  5369. build_callid(p->callid, sizeof(p->callid), p->ourip);
  5370. /* Send MWI */
  5371. p->outgoing = 1;
  5372. transmit_notify(p, newmsgs, oldmsgs);
  5373. sip_scheddestroy(p, 15000);
  5374. return 0;
  5375. }
  5376. static void *do_monitor(void *data)
  5377. {
  5378. int res;
  5379. struct sip_pvt *sip;
  5380. struct sip_peer *peer;
  5381. time_t t;
  5382. int fastrestart =0;
  5383. int lastpeernum = -1;
  5384. int curpeernum;
  5385. int reloading;
  5386. /* Add an I/O event to our UDP socket */
  5387. if (sipsock > -1)
  5388. ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
  5389. /* This thread monitors all the frame relay interfaces which are not yet in use
  5390. (and thus do not have a separate thread) indefinitely */
  5391. /* From here on out, we die whenever asked */
  5392. for(;;) {
  5393. /* Check for a reload request */
  5394. ast_mutex_lock(&sip_reload_lock);
  5395. reloading = sip_reloading;
  5396. sip_reloading = 0;
  5397. ast_mutex_unlock(&sip_reload_lock);
  5398. if (reloading) {
  5399. if (option_verbose > 0)
  5400. ast_verbose(VERBOSE_PREFIX_1 "Reloading SIP\n");
  5401. sip_do_reload();
  5402. }
  5403. /* Check for interfaces needing to be killed */
  5404. ast_mutex_lock(&iflock);
  5405. restartsearch:
  5406. sip = iflist;
  5407. while(sip) {
  5408. ast_mutex_lock(&sip->lock);
  5409. if (sip->needdestroy && (!sip->packets || (sip->packets->retransid == -1))) {
  5410. ast_mutex_unlock(&sip->lock);
  5411. __sip_destroy(sip, 1);
  5412. goto restartsearch;
  5413. }
  5414. ast_mutex_unlock(&sip->lock);
  5415. sip = sip->next;
  5416. }
  5417. ast_mutex_unlock(&iflock);
  5418. /* Don't let anybody kill us right away. Nobody should lock the interface list
  5419. and wait for the monitor list, but the other way around is okay. */
  5420. ast_mutex_lock(&monlock);
  5421. /* Lock the network interface */
  5422. ast_mutex_lock(&netlock);
  5423. /* Okay, now that we know what to do, release the network lock */
  5424. ast_mutex_unlock(&netlock);
  5425. /* And from now on, we're okay to be killed, so release the monitor lock as well */
  5426. ast_mutex_unlock(&monlock);
  5427. pthread_testcancel();
  5428. /* Wait for sched or io */
  5429. res = ast_sched_wait(sched);
  5430. if ((res < 0) || (res > 1000))
  5431. res = 1000;
  5432. /* If we might need to send more mailboxes, don't wait long at all.*/
  5433. if (fastrestart)
  5434. res = 1;
  5435. res = ast_io_wait(io, res);
  5436. ast_mutex_lock(&monlock);
  5437. if (res >= 0)
  5438. ast_sched_runq(sched);
  5439. ast_mutex_lock(&peerl.lock);
  5440. peer = peerl.peers;
  5441. time(&t);
  5442. fastrestart = 0;
  5443. curpeernum = 0;
  5444. while(peer) {
  5445. if ((curpeernum > lastpeernum) && strlen(peer->mailbox) && ((t - peer->lastmsgcheck) > 10)) {
  5446. sip_send_mwi_to_peer(peer);
  5447. fastrestart = 1;
  5448. lastpeernum = curpeernum;
  5449. break;
  5450. }
  5451. curpeernum++;
  5452. peer = peer->next;
  5453. }
  5454. /* Remember, sip_send_mwi_to_peer releases the lock if we've called it */
  5455. if (!peer) {
  5456. /* Reset where we come from */
  5457. lastpeernum = -1;
  5458. ast_mutex_unlock(&peerl.lock);
  5459. }
  5460. ast_mutex_unlock(&monlock);
  5461. }
  5462. /* Never reached */
  5463. return NULL;
  5464. }
  5465. static int restart_monitor(void)
  5466. {
  5467. /* If we're supposed to be stopped -- stay stopped */
  5468. if (monitor_thread == AST_PTHREADT_STOP)
  5469. return 0;
  5470. if (ast_mutex_lock(&monlock)) {
  5471. ast_log(LOG_WARNING, "Unable to lock monitor\n");
  5472. return -1;
  5473. }
  5474. if (monitor_thread == pthread_self()) {
  5475. ast_mutex_unlock(&monlock);
  5476. ast_log(LOG_WARNING, "Cannot kill myself\n");
  5477. return -1;
  5478. }
  5479. if (monitor_thread != AST_PTHREADT_NULL) {
  5480. /* Wake up the thread */
  5481. pthread_kill(monitor_thread, SIGURG);
  5482. } else {
  5483. /* Start a new monitor */
  5484. if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
  5485. ast_mutex_unlock(&monlock);
  5486. ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
  5487. return -1;
  5488. }
  5489. }
  5490. ast_mutex_unlock(&monlock);
  5491. return 0;
  5492. }
  5493. static int sip_poke_noanswer(void *data)
  5494. {
  5495. struct sip_peer *peer = data;
  5496. peer->pokeexpire = -1;
  5497. if (peer->lastms > -1)
  5498. ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!\n", peer->name);
  5499. if (peer->call)
  5500. sip_destroy(peer->call);
  5501. peer->call = NULL;
  5502. peer->lastms = -1;
  5503. ast_device_state_changed("SIP/%s", peer->name);
  5504. /* Try again quickly */
  5505. peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
  5506. return 0;
  5507. }
  5508. static int sip_poke_peer(struct sip_peer *peer)
  5509. {
  5510. struct sip_pvt *p;
  5511. if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
  5512. /* IF we have no IP, or this isn't to be monitored, return
  5513. imeediately after clearing things out */
  5514. peer->lastms = 0;
  5515. peer->pokeexpire = -1;
  5516. peer->call = NULL;
  5517. return 0;
  5518. }
  5519. if (peer->call > 0) {
  5520. ast_log(LOG_NOTICE, "Still have a call...\n");
  5521. sip_destroy(peer->call);
  5522. }
  5523. p = peer->call = sip_alloc(NULL, NULL, 0);
  5524. if (!peer->call) {
  5525. ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
  5526. return -1;
  5527. }
  5528. memcpy(&p->sa, &peer->addr, sizeof(p->sa));
  5529. memcpy(&p->recv, &peer->addr, sizeof(p->sa));
  5530. if (strlen(p->tohost))
  5531. strncpy(p->tohost, peer->tohost, sizeof(p->tohost) - 1);
  5532. else
  5533. snprintf(p->tohost, sizeof(p->tohost), "%s", inet_ntoa(peer->addr.sin_addr));
  5534. /* Recalculate our side, and recalculate Call ID */
  5535. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  5536. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  5537. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  5538. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
  5539. build_callid(p->callid, sizeof(p->callid), p->ourip);
  5540. if (peer->pokeexpire > -1)
  5541. ast_sched_del(sched, peer->pokeexpire);
  5542. p->peerpoke = peer;
  5543. p->outgoing = 1;
  5544. #ifdef VOCAL_DATA_HACK
  5545. strncpy(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
  5546. transmit_invite(p, "INVITE", 0, NULL, NULL, NULL,NULL, 1);
  5547. #else
  5548. transmit_invite(p, "OPTIONS", 0, NULL, NULL, NULL,NULL, 1);
  5549. #endif
  5550. gettimeofday(&peer->ps, NULL);
  5551. peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
  5552. return 0;
  5553. }
  5554. static int sip_devicestate(void *data)
  5555. {
  5556. char *ext, *host;
  5557. char tmp[256] = "";
  5558. char *dest = data;
  5559. struct hostent *hp;
  5560. struct ast_hostent ahp;
  5561. struct sip_peer *p;
  5562. int found = 0;
  5563. int res = AST_DEVICE_INVALID;
  5564. strncpy(tmp, dest, sizeof(tmp) - 1);
  5565. host = strchr(tmp, '@');
  5566. if (host) {
  5567. *host = '\0';
  5568. host++;
  5569. ext = tmp;
  5570. } else {
  5571. host = tmp;
  5572. ext = NULL;
  5573. }
  5574. ast_mutex_lock(&peerl.lock);
  5575. p = peerl.peers;
  5576. while (p) {
  5577. if (!strcasecmp(p->name, host)) {
  5578. found++;
  5579. res = AST_DEVICE_UNAVAILABLE;
  5580. if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
  5581. (!p->maxms || ((p->lastms > -1) && (p->lastms <= p->maxms)))) {
  5582. /* peer found and valid */
  5583. res = AST_DEVICE_UNKNOWN;
  5584. break;
  5585. }
  5586. }
  5587. p = p->next;
  5588. }
  5589. ast_mutex_unlock(&peerl.lock);
  5590. if (!p && !found) {
  5591. hp = ast_gethostbyname(host, &ahp);
  5592. if (hp)
  5593. res = AST_DEVICE_UNKNOWN;
  5594. }
  5595. return res;
  5596. }
  5597. static struct ast_channel *sip_request(char *type, int format, void *data)
  5598. {
  5599. int oldformat;
  5600. struct sip_pvt *p;
  5601. struct ast_channel *tmpc = NULL;
  5602. char *ext, *host;
  5603. char tmp[256] = "";
  5604. char *dest = data;
  5605. oldformat = format;
  5606. format &= capability;
  5607. if (!format) {
  5608. ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(capability));
  5609. return NULL;
  5610. }
  5611. p = sip_alloc(NULL, NULL, 0);
  5612. if (!p) {
  5613. ast_log(LOG_WARNING, "Unable to build sip pvt data for '%s'\n", (char *)data);
  5614. return NULL;
  5615. }
  5616. strncpy(tmp, dest, sizeof(tmp) - 1);
  5617. host = strchr(tmp, '@');
  5618. if (host) {
  5619. *host = '\0';
  5620. host++;
  5621. ext = tmp;
  5622. } else {
  5623. ext = strchr(tmp, '/');
  5624. if (ext) {
  5625. *ext++ = '\0';
  5626. host = tmp;
  5627. }
  5628. else {
  5629. host = tmp;
  5630. ext = NULL;
  5631. }
  5632. }
  5633. /* Assign a default capability */
  5634. p->capability = capability;
  5635. if (create_addr(p, host)) {
  5636. sip_destroy(p);
  5637. return NULL;
  5638. }
  5639. if (!strlen(p->peername) && ext)
  5640. strncpy(p->peername, ext, sizeof(p->peername) - 1);
  5641. /* Recalculate our side, and recalculate Call ID */
  5642. if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
  5643. memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
  5644. /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
  5645. snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
  5646. build_callid(p->callid, sizeof(p->callid), p->ourip);
  5647. if (ext)
  5648. strncpy(p->username, ext, sizeof(p->username) - 1);
  5649. #if 0
  5650. printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
  5651. #endif
  5652. tmpc = sip_new(p, AST_STATE_DOWN, host);
  5653. if (!tmpc)
  5654. sip_destroy(p);
  5655. ast_update_use_count();
  5656. restart_monitor();
  5657. return tmpc;
  5658. }
  5659. static struct sip_user *build_user(char *name, struct ast_variable *v)
  5660. {
  5661. struct sip_user *user;
  5662. int format;
  5663. struct ast_ha *oldha = NULL;
  5664. user = (struct sip_user *)malloc(sizeof(struct sip_user));
  5665. if (user) {
  5666. memset(user, 0, sizeof(struct sip_user));
  5667. strncpy(user->name, name, sizeof(user->name)-1);
  5668. oldha = user->ha;
  5669. user->ha = NULL;
  5670. /* set the usage flag to a sane staring value*/
  5671. user->inUse = 0;
  5672. user->outUse = 0;
  5673. user->capability = capability;
  5674. user->canreinvite = REINVITE_INVITE;
  5675. /* JK02: set default context */
  5676. strcpy(user->context, context);
  5677. strcpy(user->language, language);
  5678. while(v) {
  5679. if (!strcasecmp(v->name, "context")) {
  5680. strncpy(user->context, v->value, sizeof(user->context));
  5681. } else if (!strcasecmp(v->name, "permit") ||
  5682. !strcasecmp(v->name, "deny")) {
  5683. user->ha = ast_append_ha(v->name, v->value, user->ha);
  5684. } else if (!strcasecmp(v->name, "auth")) {
  5685. strncpy(user->methods, v->value, sizeof(user->methods)-1);
  5686. } else if (!strcasecmp(v->name, "secret")) {
  5687. strncpy(user->secret, v->value, sizeof(user->secret)-1);
  5688. } else if (!strcasecmp(v->name, "md5secret")) {
  5689. strncpy(user->md5secret, v->value, sizeof(user->secret)-1);
  5690. } else if (!strcasecmp(v->name, "dtmfmode")) {
  5691. if (!strcasecmp(v->value, "inband"))
  5692. user->dtmfmode=SIP_DTMF_INBAND;
  5693. else if (!strcasecmp(v->value, "rfc2833"))
  5694. user->dtmfmode = SIP_DTMF_RFC2833;
  5695. else if (!strcasecmp(v->value, "info"))
  5696. user->dtmfmode = SIP_DTMF_INFO;
  5697. else {
  5698. ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
  5699. user->dtmfmode = SIP_DTMF_RFC2833;
  5700. }
  5701. } else if (!strcasecmp(v->name, "canreinvite")) {
  5702. if (!strcasecmp(v->value, "update"))
  5703. user->canreinvite = REINVITE_UPDATE;
  5704. else
  5705. user->canreinvite = ast_true(v->value);
  5706. } else if (!strcasecmp(v->name, "nat")) {
  5707. user->nat = ast_true(v->value);
  5708. } else if (!strcasecmp(v->name, "callerid")) {
  5709. strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
  5710. user->hascallerid=1;
  5711. } else if (!strcasecmp(v->name, "callgroup")) {
  5712. user->callgroup = ast_get_group(v->value);
  5713. } else if (!strcasecmp(v->name, "pickupgroup")) {
  5714. user->pickupgroup = ast_get_group(v->value);
  5715. } else if (!strcasecmp(v->name, "language")) {
  5716. strncpy(user->language, v->value, sizeof(user->language)-1);
  5717. } else if (!strcasecmp(v->name, "accountcode")) {
  5718. strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
  5719. } else if (!strcasecmp(v->name, "incominglimit")) {
  5720. user->incominglimit = atoi(v->value);
  5721. if (user->incominglimit < 0)
  5722. user->incominglimit = 0;
  5723. } else if (!strcasecmp(v->name, "outgoinglimit")) {
  5724. user->outgoinglimit = atoi(v->value);
  5725. if (user->outgoinglimit < 0)
  5726. user->outgoinglimit = 0;
  5727. } else if (!strcasecmp(v->name, "amaflags")) {
  5728. format = ast_cdr_amaflags2int(v->value);
  5729. if (format < 0) {
  5730. ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
  5731. } else {
  5732. user->amaflags = format;
  5733. }
  5734. } else if (!strcasecmp(v->name, "allow")) {
  5735. format = ast_getformatbyname(v->value);
  5736. if (format < 1)
  5737. ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
  5738. else
  5739. user->capability |= format;
  5740. } else if (!strcasecmp(v->name, "disallow")) {
  5741. format = ast_getformatbyname(v->value);
  5742. if (format < 1)
  5743. ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
  5744. else
  5745. user->capability &= ~format;
  5746. } else if (!strcasecmp(v->name, "insecure")) {
  5747. user->insecure = ast_true(v->value);
  5748. } else if (!strcasecmp(v->name, "restrictcid")) {
  5749. user->restrictcid = ast_true(v->value);
  5750. } //else if (strcasecmp(v->name,"type"))
  5751. // ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  5752. v = v->next;
  5753. }
  5754. }
  5755. if (!strlen(user->methods)) {
  5756. if (strlen(user->secret))
  5757. strncpy(user->methods, "md5,plaintext", sizeof(user->methods) - 1);
  5758. else if (strlen(user->md5secret))
  5759. strncpy(user->methods, "md5", sizeof(user->methods) - 1);
  5760. }
  5761. if (oldha)
  5762. ast_free_ha(oldha);
  5763. return user;
  5764. }
  5765. static struct sip_peer *temp_peer(char *name)
  5766. {
  5767. struct sip_peer *peer;
  5768. peer = malloc(sizeof(struct sip_peer));
  5769. memset(peer, 0, sizeof(struct sip_peer));
  5770. peer->expire = -1;
  5771. peer->pokeexpire = -1;
  5772. strncpy(peer->name, name, sizeof(peer->name)-1);
  5773. strncpy(peer->context, context, sizeof(peer->context)-1);
  5774. peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
  5775. peer->expiry = expiry;
  5776. peer->capability = capability;
  5777. /* Assume can reinvite */
  5778. peer->canreinvite = globalcanreinvite;
  5779. peer->dtmfmode = globaldtmfmode;
  5780. peer->nat = globalnat;
  5781. peer->selfdestruct = 1;
  5782. peer->dynamic = 1;
  5783. strcpy(peer->methods, "md5,plaintext");
  5784. reg_source_db(peer);
  5785. return peer;
  5786. }
  5787. static struct sip_peer *build_peer(char *name, struct ast_variable *v)
  5788. {
  5789. struct sip_peer *peer;
  5790. struct sip_peer *prev;
  5791. struct ast_ha *oldha = NULL;
  5792. int maskfound=0;
  5793. int format;
  5794. int found=0;
  5795. prev = NULL;
  5796. ast_mutex_lock(&peerl.lock);
  5797. peer = peerl.peers;
  5798. while(peer) {
  5799. if (!strcasecmp(peer->name, name)) {
  5800. break;
  5801. }
  5802. prev = peer;
  5803. peer = peer->next;
  5804. }
  5805. if (peer) {
  5806. found++;
  5807. /* Already in the list, remove it and it will be added back (or FREE'd) */
  5808. if (prev) {
  5809. prev->next = peer->next;
  5810. } else {
  5811. peerl.peers = peer->next;
  5812. }
  5813. ast_mutex_unlock(&peerl.lock);
  5814. } else {
  5815. ast_mutex_unlock(&peerl.lock);
  5816. peer = malloc(sizeof(struct sip_peer));
  5817. memset(peer, 0, sizeof(struct sip_peer));
  5818. peer->expire = -1;
  5819. peer->pokeexpire = -1;
  5820. }
  5821. peer->lastmsgssent = -1;
  5822. if (peer) {
  5823. if (!found) {
  5824. strncpy(peer->name, name, sizeof(peer->name)-1);
  5825. strncpy(peer->context, context, sizeof(peer->context)-1);
  5826. peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
  5827. peer->expiry = expiry;
  5828. }
  5829. oldha = peer->ha;
  5830. peer->ha = NULL;
  5831. peer->capability = capability;
  5832. /* Assume can reinvite */
  5833. peer->canreinvite = REINVITE_INVITE;
  5834. peer->dtmfmode = 0;
  5835. while(v) {
  5836. if (!strcasecmp(v->name, "secret"))
  5837. strncpy(peer->secret, v->value, sizeof(peer->secret)-1);
  5838. else if (!strcasecmp(v->name, "md5secret"))
  5839. strncpy(peer->md5secret, v->value, sizeof(peer->md5secret)-1);
  5840. else if (!strcasecmp(v->name, "auth"))
  5841. strncpy(peer->methods, v->value, sizeof(peer->methods)-1);
  5842. else if (!strcasecmp(v->name, "canreinvite")) {
  5843. if (!strcasecmp(v->value, "update"))
  5844. peer->canreinvite = REINVITE_UPDATE;
  5845. else
  5846. peer->canreinvite = ast_true(v->value);
  5847. } else if (!strcasecmp(v->name, "nat"))
  5848. peer->nat = ast_true(v->value);
  5849. else if (!strcasecmp(v->name, "context"))
  5850. strncpy(peer->context, v->value, sizeof(peer->context)-1);
  5851. else if (!strcasecmp(v->name, "fromdomain"))
  5852. strncpy(peer->fromdomain, v->value, sizeof(peer->fromdomain)-1);
  5853. else if (!strcasecmp(v->name, "fromuser"))
  5854. strncpy(peer->fromuser, v->value, sizeof(peer->fromuser)-1);
  5855. else if (!strcasecmp(v->name, "dtmfmode")) {
  5856. if (!strcasecmp(v->value, "inband"))
  5857. peer->dtmfmode=SIP_DTMF_INBAND;
  5858. else if (!strcasecmp(v->value, "rfc2833"))
  5859. peer->dtmfmode = SIP_DTMF_RFC2833;
  5860. else if (!strcasecmp(v->value, "info"))
  5861. peer->dtmfmode = SIP_DTMF_INFO;
  5862. else {
  5863. ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
  5864. peer->dtmfmode = SIP_DTMF_RFC2833;
  5865. }
  5866. } else if (!strcasecmp(v->name, "host")) {
  5867. if (!strcasecmp(v->value, "dynamic")) {
  5868. /* They'll register with us */
  5869. peer->dynamic = 1;
  5870. if (!found) {
  5871. /* Initialize stuff iff we're not found, otherwise
  5872. we keep going with what we had */
  5873. memset(&peer->addr.sin_addr, 0, 4);
  5874. if (peer->addr.sin_port) {
  5875. /* If we've already got a port, make it the default rather than absolute */
  5876. peer->defaddr.sin_port = peer->addr.sin_port;
  5877. peer->addr.sin_port = 0;
  5878. }
  5879. }
  5880. } else {
  5881. /* Non-dynamic. Make sure we become that way if we're not */
  5882. if (peer->expire > -1)
  5883. ast_sched_del(sched, peer->expire);
  5884. peer->expire = -1;
  5885. peer->dynamic = 0;
  5886. if (ast_get_ip(&peer->addr, v->value)) {
  5887. free(peer);
  5888. return NULL;
  5889. }
  5890. strncpy(peer->tohost, v->value, sizeof(peer->tohost) - 1);
  5891. }
  5892. if (!maskfound)
  5893. inet_aton("255.255.255.255", &peer->mask);
  5894. } else if (!strcasecmp(v->name, "defaultip")) {
  5895. if (ast_get_ip(&peer->defaddr, v->value)) {
  5896. free(peer);
  5897. return NULL;
  5898. }
  5899. } else if (!strcasecmp(v->name, "permit") ||
  5900. !strcasecmp(v->name, "deny")) {
  5901. peer->ha = ast_append_ha(v->name, v->value, peer->ha);
  5902. } else if (!strcasecmp(v->name, "mask")) {
  5903. maskfound++;
  5904. inet_aton(v->value, &peer->mask);
  5905. } else if (!strcasecmp(v->name, "port")) {
  5906. if (peer->dynamic)
  5907. peer->defaddr.sin_port = htons(atoi(v->value));
  5908. else
  5909. peer->addr.sin_port = htons(atoi(v->value));
  5910. } else if (!strcasecmp(v->name, "username")) {
  5911. strncpy(peer->username, v->value, sizeof(peer->username)-1);
  5912. } else if (!strcasecmp(v->name, "mailbox")) {
  5913. strncpy(peer->mailbox, v->value, sizeof(peer->mailbox)-1);
  5914. } else if (!strcasecmp(v->name, "callgroup")) {
  5915. peer->callgroup = ast_get_group(v->value);
  5916. } else if (!strcasecmp(v->name, "pickupgroup")) {
  5917. peer->pickupgroup = ast_get_group(v->value);
  5918. } else if (!strcasecmp(v->name, "allow")) {
  5919. format = ast_getformatbyname(v->value);
  5920. if (format < 1)
  5921. ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
  5922. else
  5923. peer->capability |= format;
  5924. } else if (!strcasecmp(v->name, "disallow")) {
  5925. format = ast_getformatbyname(v->value);
  5926. if (format < 1)
  5927. ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
  5928. else
  5929. peer->capability &= ~format;
  5930. } else if (!strcasecmp(v->name, "insecure")) {
  5931. peer->insecure = ast_true(v->value);
  5932. } else if (!strcasecmp(v->name, "qualify")) {
  5933. if (!strcasecmp(v->value, "no")) {
  5934. peer->maxms = 0;
  5935. } else if (!strcasecmp(v->value, "yes")) {
  5936. peer->maxms = DEFAULT_MAXMS;
  5937. } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
  5938. 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);
  5939. peer->maxms = 0;
  5940. }
  5941. } //else if (strcasecmp(v->name,"type"))
  5942. // ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  5943. v=v->next;
  5944. }
  5945. if (!strlen(peer->methods))
  5946. strcpy(peer->methods, "md5,plaintext");
  5947. if (!found && peer->dynamic)
  5948. reg_source_db(peer);
  5949. peer->delme = 0;
  5950. }
  5951. if (oldha)
  5952. ast_free_ha(oldha);
  5953. return peer;
  5954. }
  5955. static int reload_config(void)
  5956. {
  5957. struct ast_config *cfg;
  5958. struct ast_variable *v;
  5959. struct sip_peer *peer;
  5960. struct sip_user *user;
  5961. struct ast_hostent ahp;
  5962. char *cat;
  5963. char *utype;
  5964. struct hostent *hp;
  5965. int format;
  5966. int oldport = ntohs(bindaddr.sin_port);
  5967. globaldtmfmode = SIP_DTMF_RFC2833;
  5968. if (gethostname(ourhost, sizeof(ourhost))) {
  5969. ast_log(LOG_WARNING, "Unable to get hostname, SIP disabled\n");
  5970. return 0;
  5971. }
  5972. cfg = ast_load(config);
  5973. /* We *must* have a config file otherwise stop immediately */
  5974. if (!cfg) {
  5975. ast_log(LOG_NOTICE, "Unable to load config %s, SIP disabled\n", config);
  5976. return 0;
  5977. }
  5978. globalnat = 0;
  5979. sip_prefs_free();
  5980. memset(&bindaddr, 0, sizeof(bindaddr));
  5981. memset(&localnet, 0, sizeof(localnet));
  5982. memset(&localmask, 0, sizeof(localmask));
  5983. memset(&externip, 0, sizeof(externip));
  5984. /* Initialize some reasonable defaults */
  5985. strncpy(context, "default", sizeof(context) - 1);
  5986. strcpy(language, "");
  5987. strcpy(fromdomain, "");
  5988. globalcanreinvite = REINVITE_INVITE;
  5989. videosupport = 0;
  5990. pedanticsipchecking=0;
  5991. v = ast_variable_browse(cfg, "general");
  5992. while(v) {
  5993. /* Create the interface list */
  5994. if (!strcasecmp(v->name, "context")) {
  5995. strncpy(context, v->value, sizeof(context)-1);
  5996. } else if (!strcasecmp(v->name, "dtmfmode")) {
  5997. if (!strcasecmp(v->value, "inband"))
  5998. globaldtmfmode=SIP_DTMF_INBAND;
  5999. else if (!strcasecmp(v->value, "rfc2833"))
  6000. globaldtmfmode = SIP_DTMF_RFC2833;
  6001. else if (!strcasecmp(v->value, "info"))
  6002. globaldtmfmode = SIP_DTMF_INFO;
  6003. else {
  6004. ast_log(LOG_WARNING, "Unknown dtmf mode '%s', using rfc2833\n", v->value);
  6005. globaldtmfmode = SIP_DTMF_RFC2833;
  6006. }
  6007. } else if (!strcasecmp(v->name, "videosupport")) {
  6008. videosupport = ast_true(v->value);
  6009. } else if (!strcasecmp(v->name, "notifymimetype")) {
  6010. strncpy(notifymime, v->value, sizeof(notifymime) - 1);
  6011. } else if (!strcasecmp(v->name, "language")) {
  6012. strncpy(language, v->value, sizeof(language)-1);
  6013. } else if (!strcasecmp(v->name, "callerid")) {
  6014. strncpy(callerid, v->value, sizeof(callerid)-1);
  6015. } else if (!strcasecmp(v->name, "fromdomain")) {
  6016. strncpy(fromdomain, v->value, sizeof(fromdomain)-1);
  6017. } else if (!strcasecmp(v->name, "nat")) {
  6018. globalnat = ast_true(v->value);
  6019. } else if (!strcasecmp(v->name, "autocreatepeer")) {
  6020. autocreatepeer = ast_true(v->value);
  6021. } else if (!strcasecmp(v->name, "srvlookup")) {
  6022. srvlookup = ast_true(v->value);
  6023. } else if (!strcasecmp(v->name, "pedantic")) {
  6024. pedanticsipchecking = ast_true(v->value);
  6025. } else if (!strcasecmp(v->name, "canreinvite")) {
  6026. if (!strcasecmp(v->value, "update"))
  6027. globalcanreinvite = REINVITE_UPDATE;
  6028. else
  6029. globalcanreinvite = ast_true(v->value);
  6030. } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
  6031. max_expiry = atoi(v->value);
  6032. if (max_expiry < 1)
  6033. max_expiry = DEFAULT_MAX_EXPIRY;
  6034. } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
  6035. default_expiry = atoi(v->value);
  6036. if (default_expiry < 1)
  6037. default_expiry = DEFAULT_DEFAULT_EXPIRY;
  6038. } else if (!strcasecmp(v->name, "bindaddr")) {
  6039. if (!(hp = ast_gethostbyname(v->value, &ahp))) {
  6040. ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
  6041. } else {
  6042. memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
  6043. }
  6044. } else if (!strcasecmp(v->name, "localnet")) {
  6045. if (!(hp = ast_gethostbyname(v->value, &ahp)))
  6046. ast_log(LOG_WARNING, "Invalid localnet keyword: %s\n", v->value);
  6047. else
  6048. memcpy(&localnet.sin_addr, hp->h_addr, sizeof(localnet.sin_addr));
  6049. } else if (!strcasecmp(v->name, "localmask")) {
  6050. if (!(hp = ast_gethostbyname(v->value, &ahp)))
  6051. ast_log(LOG_WARNING, "Invalid localmask keyword: %s\n", v->value);
  6052. else
  6053. memcpy(&localmask.sin_addr, hp->h_addr, sizeof(localmask.sin_addr));
  6054. } else if (!strcasecmp(v->name, "externip")) {
  6055. if (!(hp = ast_gethostbyname(v->value, &ahp)))
  6056. ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
  6057. else
  6058. memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
  6059. } else if (!strcasecmp(v->name, "allow")) {
  6060. format = ast_getformatbyname(v->value);
  6061. if (format < 1)
  6062. ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
  6063. else {
  6064. capability |= format;
  6065. sip_pref_append(format);
  6066. }
  6067. } else if (!strcasecmp(v->name, "disallow")) {
  6068. format = ast_getformatbyname(v->value);
  6069. if (format < 1)
  6070. ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
  6071. else {
  6072. capability &= ~format;
  6073. sip_pref_remove(format);
  6074. }
  6075. } else if (!strcasecmp(v->name, "register")) {
  6076. sip_register(v->value, v->lineno);
  6077. } else if (!strcasecmp(v->name, "tos")) {
  6078. if (sscanf(v->value, "%i", &format) == 1)
  6079. tos = format & 0xff;
  6080. else if (!strcasecmp(v->value, "lowdelay"))
  6081. tos = IPTOS_LOWDELAY;
  6082. else if (!strcasecmp(v->value, "throughput"))
  6083. tos = IPTOS_THROUGHPUT;
  6084. else if (!strcasecmp(v->value, "reliability"))
  6085. tos = IPTOS_RELIABILITY;
  6086. else if (!strcasecmp(v->value, "mincost"))
  6087. tos = IPTOS_MINCOST;
  6088. else if (!strcasecmp(v->value, "none"))
  6089. tos = 0;
  6090. else
  6091. ast_log(LOG_WARNING, "Invalid tos value at line %d, should be 'lowdelay', 'throughput', 'reliability', 'mincost', or 'none'\n", v->lineno);
  6092. } else if (!strcasecmp(v->name, "port")) {
  6093. if (sscanf(v->value, "%i", &ourport) == 1) {
  6094. bindaddr.sin_port = htons(ourport);
  6095. } else {
  6096. ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
  6097. }
  6098. #ifdef MYSQL_FRIENDS
  6099. } else if (!strcasecmp(v->name, "dbuser")) {
  6100. strncpy(mydbuser, v->value, sizeof(mydbuser) - 1);
  6101. } else if (!strcasecmp(v->name, "dbpass")) {
  6102. strncpy(mydbpass, v->value, sizeof(mydbpass) - 1);
  6103. } else if (!strcasecmp(v->name, "dbhost")) {
  6104. strncpy(mydbhost, v->value, sizeof(mydbhost) - 1);
  6105. } else if (!strcasecmp(v->name, "dbname")) {
  6106. strncpy(mydbname, v->value, sizeof(mydbname) - 1);
  6107. #endif
  6108. } //else if (strcasecmp(v->name,"type"))
  6109. // ast_log(LOG_WARNING, "Ignoring %s\n", v->name);
  6110. v = v->next;
  6111. }
  6112. cat = ast_category_browse(cfg, NULL);
  6113. while(cat) {
  6114. if (strcasecmp(cat, "general")) {
  6115. utype = ast_variable_retrieve(cfg, cat, "type");
  6116. if (utype) {
  6117. if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
  6118. user = build_user(cat, ast_variable_browse(cfg, cat));
  6119. if (user) {
  6120. ast_mutex_lock(&userl.lock);
  6121. user->next = userl.users;
  6122. userl.users = user;
  6123. ast_mutex_unlock(&userl.lock);
  6124. }
  6125. }
  6126. if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
  6127. peer = build_peer(cat, ast_variable_browse(cfg, cat));
  6128. if (peer) {
  6129. ast_mutex_lock(&peerl.lock);
  6130. peer->next = peerl.peers;
  6131. peerl.peers = peer;
  6132. ast_mutex_unlock(&peerl.lock);
  6133. }
  6134. } else if (strcasecmp(utype, "user")) {
  6135. ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
  6136. }
  6137. } else
  6138. ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
  6139. }
  6140. cat = ast_category_browse(cfg, cat);
  6141. }
  6142. if (ntohl(bindaddr.sin_addr.s_addr)) {
  6143. memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
  6144. } else {
  6145. hp = ast_gethostbyname(ourhost, &ahp);
  6146. if (!hp) {
  6147. ast_log(LOG_WARNING, "Unable to get IP address for %s, SIP disabled\n", ourhost);
  6148. return 0;
  6149. }
  6150. memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
  6151. }
  6152. if (!ntohs(bindaddr.sin_port))
  6153. bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
  6154. bindaddr.sin_family = AF_INET;
  6155. ast_mutex_lock(&netlock);
  6156. if ((sipsock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
  6157. close(sipsock);
  6158. sipsock = -1;
  6159. }
  6160. if (sipsock < 0) {
  6161. sipsock = socket(AF_INET, SOCK_DGRAM, 0);
  6162. if (sipsock < 0) {
  6163. ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
  6164. } else {
  6165. // Allow SIP clients on the same host to access us:
  6166. const int reuseFlag = 1;
  6167. setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
  6168. (const char*)&reuseFlag,
  6169. sizeof reuseFlag);
  6170. if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
  6171. ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
  6172. inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
  6173. strerror(errno));
  6174. close(sipsock);
  6175. sipsock = -1;
  6176. } else {
  6177. if (option_verbose > 1) {
  6178. ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n",
  6179. inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
  6180. ast_verbose(VERBOSE_PREFIX_2 "Using TOS bits %d\n", tos);
  6181. }
  6182. if (setsockopt(sipsock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))
  6183. ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
  6184. }
  6185. }
  6186. }
  6187. ast_mutex_unlock(&netlock);
  6188. ast_destroy(cfg);
  6189. #ifdef MYSQL_FRIENDS
  6190. /* Connect to db if appropriate */
  6191. if (!mysql && strlen(mydbname)) {
  6192. mysql = mysql_init(NULL);
  6193. if (!mysql_real_connect(mysql, mydbhost[0] ? mydbhost : NULL, mydbuser, mydbpass, mydbname, 0, NULL, 0)) {
  6194. memset(mydbpass, '*', strlen(mydbpass));
  6195. ast_log(LOG_WARNING, "Database connection failed (db=%s, host=%s, user=%s, pass=%s)!\n",
  6196. mydbname, mydbhost, mydbuser, mydbpass);
  6197. free(mysql);
  6198. mysql = NULL;
  6199. } else
  6200. ast_verbose(VERBOSE_PREFIX_1 "Connected to database '%s' on '%s' as '%s'\n",
  6201. mydbname, mydbhost, mydbuser);
  6202. }
  6203. #endif
  6204. return 0;
  6205. }
  6206. static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan)
  6207. {
  6208. struct sip_pvt *p;
  6209. p = chan->pvt->pvt;
  6210. if (p && p->rtp && p->canreinvite)
  6211. return p->rtp;
  6212. return NULL;
  6213. }
  6214. static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan)
  6215. {
  6216. struct sip_pvt *p;
  6217. p = chan->pvt->pvt;
  6218. if (p && p->vrtp && p->canreinvite)
  6219. return p->vrtp;
  6220. return NULL;
  6221. }
  6222. static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
  6223. {
  6224. struct sip_pvt *p;
  6225. p = chan->pvt->pvt;
  6226. if (p) {
  6227. if (rtp)
  6228. ast_rtp_get_peer(rtp, &p->redirip);
  6229. else
  6230. memset(&p->redirip, 0, sizeof(p->redirip));
  6231. if (vrtp)
  6232. ast_rtp_get_peer(vrtp, &p->vredirip);
  6233. else
  6234. memset(&p->vredirip, 0, sizeof(p->vredirip));
  6235. if (!p->gotrefer) {
  6236. transmit_reinvite_with_sdp(p, rtp, vrtp);
  6237. p->outgoing = 1;
  6238. }
  6239. return 0;
  6240. }
  6241. return -1;
  6242. }
  6243. static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
  6244. static char *descrip_dtmfmode = "SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
  6245. static char *app_dtmfmode = "SIPDtmfMode";
  6246. static int sip_dtmfmode(struct ast_channel *chan, void *data)
  6247. {
  6248. struct sip_pvt *p = chan->pvt->pvt;
  6249. char *mode;
  6250. if (chan->type != type) {
  6251. ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
  6252. return 0;
  6253. }
  6254. if (data)
  6255. mode = (char *)data;
  6256. else {
  6257. ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
  6258. return 0;
  6259. }
  6260. if (!strcasecmp(mode,"info"))
  6261. p->dtmfmode = SIP_DTMF_INFO;
  6262. else if (!strcasecmp(mode,"rfc2833"))
  6263. p->dtmfmode = SIP_DTMF_RFC2833;
  6264. else if (!strcasecmp(mode,"inband"))
  6265. p->dtmfmode = SIP_DTMF_INBAND;
  6266. else
  6267. ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n",mode);
  6268. return 0;
  6269. }
  6270. static int sip_get_codec(struct ast_channel *chan)
  6271. {
  6272. struct sip_pvt *p = chan->pvt->pvt;
  6273. return p->capability;
  6274. }
  6275. static struct ast_rtp_protocol sip_rtp = {
  6276. get_rtp_info: sip_get_rtp_peer,
  6277. get_vrtp_info: sip_get_vrtp_peer,
  6278. set_rtp_peer: sip_set_rtp_peer,
  6279. get_codec: sip_get_codec,
  6280. };
  6281. static void delete_users(void)
  6282. {
  6283. struct sip_user *user, *userlast;
  6284. struct sip_peer *peer;
  6285. struct sip_registry *reg, *regn;
  6286. /* Delete all users */
  6287. ast_mutex_lock(&userl.lock);
  6288. for (user=userl.users;user;) {
  6289. ast_free_ha(user->ha);
  6290. userlast = user;
  6291. user=user->next;
  6292. free(userlast);
  6293. }
  6294. userl.users=NULL;
  6295. ast_mutex_unlock(&userl.lock);
  6296. ast_mutex_lock(&regl.lock);
  6297. for (reg = regl.registrations;reg;) {
  6298. regn = reg->next;
  6299. /* Really delete */
  6300. if (reg->call) {
  6301. /* Clear registry before destroying to ensure
  6302. we don't get reentered trying to grab the registry lock */
  6303. reg->call->registry = NULL;
  6304. sip_destroy(reg->call);
  6305. }
  6306. if (reg->expire > -1)
  6307. ast_sched_del(sched, reg->expire);
  6308. if (reg->timeout > -1)
  6309. ast_sched_del(sched, reg->timeout);
  6310. free(reg);
  6311. reg = regn;
  6312. }
  6313. regl.registrations = NULL;
  6314. ast_mutex_unlock(&regl.lock);
  6315. ast_mutex_lock(&peerl.lock);
  6316. for (peer=peerl.peers;peer;) {
  6317. /* Assume all will be deleted, and we'll find out for sure later */
  6318. peer->delme = 1;
  6319. peer = peer->next;
  6320. }
  6321. ast_mutex_unlock(&peerl.lock);
  6322. }
  6323. static void prune_peers(void)
  6324. {
  6325. /* Prune peers who still are supposed to be deleted */
  6326. struct sip_peer *peer, *peerlast, *peernext;
  6327. ast_mutex_lock(&peerl.lock);
  6328. peerlast = NULL;
  6329. for (peer=peerl.peers;peer;) {
  6330. peernext = peer->next;
  6331. if (peer->delme) {
  6332. /* Delete it, it needs to disappear */
  6333. if (peer->call)
  6334. sip_destroy(peer->call);
  6335. if (peer->expire > -1)
  6336. ast_sched_del(sched, peer->expire);
  6337. if (peer->pokeexpire > -1)
  6338. ast_sched_del(sched, peer->pokeexpire);
  6339. free(peer);
  6340. if (peerlast)
  6341. peerlast->next = peernext;
  6342. else
  6343. peerl.peers = peernext;
  6344. } else
  6345. peerlast = peer;
  6346. peer=peernext;
  6347. }
  6348. ast_mutex_unlock(&peerl.lock);
  6349. }
  6350. static int sip_do_reload(void)
  6351. {
  6352. struct sip_registry *reg;
  6353. struct sip_peer *peer;
  6354. delete_users();
  6355. reload_config();
  6356. prune_peers();
  6357. /* And start the monitor for the first time */
  6358. ast_mutex_lock(&regl.lock);
  6359. for (reg = regl.registrations; reg; reg = reg->next)
  6360. __sip_do_register(reg);
  6361. ast_mutex_unlock(&regl.lock);
  6362. ast_mutex_lock(&peerl.lock);
  6363. for (peer = peerl.peers; peer; peer = peer->next)
  6364. sip_poke_peer(peer);
  6365. ast_mutex_unlock(&peerl.lock);
  6366. return 0;
  6367. }
  6368. static int sip_reload(int fd, int argc, char *argv[])
  6369. {
  6370. ast_mutex_lock(&sip_reload_lock);
  6371. if (sip_reloading) {
  6372. ast_verbose("Previous SIP reload not yet done\n");
  6373. } else
  6374. sip_reloading = 1;
  6375. ast_mutex_unlock(&sip_reload_lock);
  6376. restart_monitor();
  6377. return 0;
  6378. }
  6379. int reload(void)
  6380. {
  6381. return sip_reload(0, 0, NULL);
  6382. }
  6383. static struct ast_cli_entry cli_sip_reload =
  6384. { { "sip", "reload", NULL }, sip_reload, "Reload SIP configuration", sip_reload_usage };
  6385. int load_module()
  6386. {
  6387. int res;
  6388. struct sip_peer *peer;
  6389. struct sip_registry *reg;
  6390. sched = sched_context_create();
  6391. if (!sched) {
  6392. ast_log(LOG_WARNING, "Unable to create schedule context\n");
  6393. }
  6394. io = io_context_create();
  6395. if (!io) {
  6396. ast_log(LOG_WARNING, "Unable to create I/O context\n");
  6397. }
  6398. res = reload_config();
  6399. if (!res) {
  6400. /* Make sure we can register our sip channel type */
  6401. if (ast_channel_register_ex(type, tdesc, capability, sip_request, sip_devicestate)) {
  6402. ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
  6403. return -1;
  6404. }
  6405. ast_cli_register(&cli_show_users);
  6406. ast_cli_register(&cli_show_channels);
  6407. ast_cli_register(&cli_show_channel);
  6408. ast_cli_register(&cli_show_peers);
  6409. ast_cli_register(&cli_show_registry);
  6410. ast_cli_register(&cli_debug);
  6411. ast_cli_register(&cli_no_debug);
  6412. ast_cli_register(&cli_sip_reload);
  6413. ast_cli_register(&cli_inuse_show);
  6414. sip_rtp.type = type;
  6415. ast_rtp_proto_register(&sip_rtp);
  6416. ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
  6417. ast_mutex_lock(&peerl.lock);
  6418. for (peer = peerl.peers; peer; peer = peer->next)
  6419. sip_poke_peer(peer);
  6420. ast_mutex_unlock(&peerl.lock);
  6421. ast_mutex_lock(&regl.lock);
  6422. for (reg = regl.registrations; reg; reg = reg->next)
  6423. __sip_do_register(reg);
  6424. ast_mutex_unlock(&regl.lock);
  6425. /* And start the monitor for the first time */
  6426. restart_monitor();
  6427. }
  6428. return res;
  6429. }
  6430. int unload_module()
  6431. {
  6432. struct sip_pvt *p, *pl;
  6433. /* First, take us out of the channel loop */
  6434. ast_unregister_application(app_dtmfmode);
  6435. ast_cli_unregister(&cli_show_users);
  6436. ast_cli_unregister(&cli_show_channels);
  6437. ast_cli_unregister(&cli_show_channel);
  6438. ast_cli_unregister(&cli_show_peers);
  6439. ast_cli_unregister(&cli_show_registry);
  6440. ast_cli_unregister(&cli_debug);
  6441. ast_cli_unregister(&cli_no_debug);
  6442. ast_cli_unregister(&cli_sip_reload);
  6443. ast_cli_unregister(&cli_inuse_show);
  6444. ast_rtp_proto_unregister(&sip_rtp);
  6445. ast_channel_unregister(type);
  6446. if (!ast_mutex_lock(&iflock)) {
  6447. /* Hangup all interfaces if they have an owner */
  6448. p = iflist;
  6449. while(p) {
  6450. if (p->owner)
  6451. ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
  6452. p = p->next;
  6453. }
  6454. iflist = NULL;
  6455. ast_mutex_unlock(&iflock);
  6456. } else {
  6457. ast_log(LOG_WARNING, "Unable to lock the interface list\n");
  6458. return -1;
  6459. }
  6460. if (!ast_mutex_lock(&monlock)) {
  6461. if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
  6462. pthread_cancel(monitor_thread);
  6463. pthread_kill(monitor_thread, SIGURG);
  6464. pthread_join(monitor_thread, NULL);
  6465. }
  6466. monitor_thread = AST_PTHREADT_STOP;
  6467. ast_mutex_unlock(&monlock);
  6468. } else {
  6469. ast_log(LOG_WARNING, "Unable to lock the monitor\n");
  6470. return -1;
  6471. }
  6472. if (!ast_mutex_lock(&iflock)) {
  6473. /* Destroy all the interfaces and free their memory */
  6474. p = iflist;
  6475. while(p) {
  6476. pl = p;
  6477. p = p->next;
  6478. /* Free associated memory */
  6479. free(pl);
  6480. }
  6481. iflist = NULL;
  6482. ast_mutex_unlock(&iflock);
  6483. } else {
  6484. ast_log(LOG_WARNING, "Unable to lock the interface list\n");
  6485. return -1;
  6486. }
  6487. return 0;
  6488. }
  6489. int usecount()
  6490. {
  6491. int res;
  6492. ast_mutex_lock(&usecnt_lock);
  6493. res = usecnt;
  6494. ast_mutex_unlock(&usecnt_lock);
  6495. return res;
  6496. }
  6497. char *key()
  6498. {
  6499. return ASTERISK_GPL_KEY;
  6500. }
  6501. char *description()
  6502. {
  6503. return desc;
  6504. }
  6505. #if 0
  6506. // XXX What is this?
  6507. static char *getsipuri(char *header)
  6508. {
  6509. char *c, *d, *retval;
  6510. int n;
  6511. if (!(c=strstr(header, "sip"))) {
  6512. return NULL;
  6513. }
  6514. if (!(d=strchr(c, '@'))) {
  6515. return NULL;
  6516. }
  6517. n=d-c;
  6518. retval=(char *)malloc(n+1);
  6519. strncpy(retval, c, n);
  6520. *(retval+n)='\0';
  6521. return retval;
  6522. }
  6523. #endif