Page1of56 IntroductiontoTelephonyApplicationDevelopmentUsing Asterisk,Asterisk Java,andSIP bycokordarakaanggajananuraga PutuSutawijaya GerakBagaiBadai(StormlikeMovements)
Page2of56 Irackedmyminds,nogemstobefound,foranimpressiveopeningline... So,outoffrustrationIwrite... Frankly,Ihavenoideafortheopeningparagraphsofthisbooklet.AllIhaveisasetofconcepts/ideas roamingtheemptyspaceinmyhead...well,i'lljustletthemalloutnow. Raka'sMindMap Thisbookletisaboutallofthemandnoneoftheminparticular(huh?).Imean,ittouchesthesubjects drawnabovetovariouslevelsofdetail.somearementionedbriefly,andsomegetquiteanextensive coverage(foranintroduction).iuseaprogramthatiwroteasavehicle[res.1],andi'llstartmy explanationfromtheobjectives(therequirementsoftheprogram).itreflectsmylearningstylethat usuallystartswith what?tellme,followedby how?showme,andendsupin why?theories please. Withoutfurtherado:InthisarticleI'mgoingtointroduceyoutotechniques,libraries,andtoolsfor developingtelephonyservices.we'lluseallopensourcestuffshere(cool,huh!?),likeasterisk, Asterisk JavaLibrary,Ethereal,SIPp,andNISTJAINSIPlibrary. Audience Well,Icanthinkofatleast2groupsofpeople.First:thosewho'veneverbeenintouchwithtelephony andctistuffs.iwasinthatgroup.butonceigotmyhandsonasterisk,anopensourcepbx,igot excited.itwaslike: Wow,kewl,Icandostuffswiththisthing...quiteeasily!.Ihopeafterreadingthis article,they'llfindtelephonyapplicationdevelopmentinteresting,andwouldliketogiveitatry. Thesecondgroupis:thosewho'vebeeninthisdomainforsometime,haveheardofthewordAsterisk andsipbuzzingaroundthem,butnotquitesurewhereandhowtostartmakingsomethingoutofthem. Ihopethisarticlecanbesomekindofaguidemap. Istartedfromzero,Ithink.IstudiedtheSIPspecification[Ref.5],somerelevantbooks,installedand playedaroundwithasteriskandrelatedstuffs,scrolledthroughlotsofpacketscapturedusingethereal, etc.ienjoyedtheprocess,anditworkedquitewellforme.atleastithinknowi'msufficientlyoriented formyfurtherendeavor.i'dliketosharethatapproachwithyouthroughthisarticle. Bytheway:ifyou'relookingforthetableofcontents,it'sattheendofthisbooklet.
Page3of56 AllYouNeedIs... love...,andseveralsoftwares!here'sthelistofthingsthatyouneedtohaveinyourcomputer: Asterisk,thatwillserveasourbackend.Amongotherthings,itswitchesincomingcallstoregistered extensions.inthisoccasion,we'regoingtomonitortheeventshappeninginanasterisksothatwe knowwhenacallisstartedandended. Youwouldn'tfinddetailedinformationabouthowtoinstall,run,andadministeranAsteriskboxhere. Referencessuchas[Ref.2]and[Ref.6]dothatjobalotbetter.However,Iwillgiveyouanexplanation justenoughtoquicklysetupyourasteriskboxandconfiguringitinordertomakeourprogramworks. Asterisk Java,aprogramminglibrarythatwe'llusetointeractwithAsteriskfromtheprogramthat we'regoingtodevelopwithjava.thekindofinteractionspossibleare: a) ListeningtoeventssentbyAsterisk. Asterisksendalleventshappeninginittoalltheregisteredlisteners.It'sasocketbased communication.ourprogramwillopenasocket,throughwhichitregistersitselftoasterisk (viaamanagerinterface)sothateventsgeneratedbyasteriskwillarriveonthatsocket. b) SendingactionstoAsteriskthroughtheconnectionbetweenourprogramandthemanager interface.we'llreceivearesponseforanactionthatwesendtoasterisk. c) SendingcommandstoAsteriskthroughthesocalled agichannel.we'llgetareplyfora commandthatwesendtoasterisk. Sidenote.Thedistinctionbetweencommandandactionisnotyetclearforme.Iguessactionismore general,inthesensethatwecansendanactiontoasteriskanytime.ontheotherhand,wesend commandthroughanagichannel,that'sonlyavailableinthecontextofanexecutionofanagiscript. ExecutionofanAGIscript,inturn,istriggeredbyacallmadethroughtheAsteriskbox.So,Iguess, thescopeofacommandislimitedtoaparticularcall. SIPp.ItisaprogramthatwecanusetogenerateSIPsignalingtraffic.Typicallyitisusedtostress testasip basedtelecommunicationsystem.inourcase,weneedtomakesurethatourprogram performscorrectlyinamore or lessrealisticsituation(callscominginandoutsimultaneously). Therefore,weuseSIPptosimulatemultiplecalls. Ethereal,anopensourceGUInetworkprotocolanalyzer.Itletsyouinteractivelybrowsepacketdata fromalivenetworkorfromapreviouslysavedcapturefile.asitoldyouearlier,iwalkedmywayfrom thebottomupinunderstandingthesestuffs.hmm...,well,notexactly.ofcourse,firstireadsome referencesabouthowthingswork(forexample:communicationbetweensipendpoints),thenimoved ontoapidocumentationstogetsomepracticalinsights.butmaybebecausei'maskeptic,ifeltthe needtoreallyseewhat'sbeingexchangedthroughthewire,thesequence,etc.forthatreason,iopened myethereal,startsniffing,andtrytoconfirmwhati'veread. Inourprogram,particularlywhenevercreationofconferenceroomisdetected,weneedtosneakina dummyparticipantintothatroomforareasonthatwillbeexplainedlater.thatdummyparticipant
Page4of56 basicallyisasoftwareagentthatdialsintotheconference,andstaysthereuntileverybodyelseleave theroom.i'vedecidedtoimplementtheestablishment(andtear down)ofthecallsessionbetweenthat softwareagentandasteriskusingsip. Sidenote.Actuallywehaveatleast2choicesofcallsignallingprotocolwithanAsteriskbox:IAX2 andsip.ichoosesipfortworeasons: AtthetimeofwritingtherewasnoIAXprogramminglibraryinJava,atleastnottheopensourced one.inthisoccasionilimitthechoiceonlytoopensourcesoftwaresandlibraries. Thepurposeofthisarticleistogivethereaderssomekindofbirdviewovertheworldoftelephony applicationdevelopment,usingemergingopenstandardsandopensourcesoftwares.we'renotgoing forthedepthrightnow,butinsteadforthebreadth.followingthe moreismore principle,ibringon SIPtothetable.Thetalkabout whichoneismoresuitableforparticularcase,siporiax? isbetter leftforanotherarticle,iguess. SIPisinterestingandpromising,Icantellyou.Ifyoucheckbigtelecommunicationvendors'websites, you'llfindthattheyallhavesiprelatedstuffsintheirproductline(beitsoftwareorhardware).a scoopofknowledgeonsipmightbebeneficialforyoutoplayinthatmarket. WeneedJAIN SIP.ItisaJava standardinterfacetosipsignalingstack(whateverthatmeans:).from practicalpointofview,ourjavaprogramconstructs,sends,receives,andreadssipmessagesusing classesandinterfacesspecifiedinjain SIP.There'sanopensourceimplementationofJAIN SIP specificationfromnationalinstituteofstandardandtesting[res.7]. DoesJAIN SIPvaguelyremindyouofJDBC...?Exactly!
Page5of56 MissionBriefing First,let'sdefineanobjective.WewanttocreatesomethinglikeinFig.1.Let'scallitCallWatcher. Fig.1.CallWatcher'smainwindow singlepartycalls Theapplicationhas3panels: SinglePartyCalls CallswhichareanswereddirectlybyAsteriskshouldshowupinthispanel(Fig.1).For example:inourdialplan,wespecifythatcallscomingintoextension600willbeansweredby anasterisk'sbuilt inivrthatsimplyechoeswhateverthecallerissaying.thatcallshould showupinthesinglepartycallspanel. TwoPartiesCalls Callswhichareterminatedatanotheruseragent1(UA)outsideofAsteriskshouldshowupin thispanel(fig.2).forexample:wehaveconfiguredinourdialplanthatincomingcallto extension101mustbeswitchedtoagent#01.thatcallshouldshowupinthetwopartiescalls panels.inthispanel,theidofthecaller thatcouldbehertelephonenumber isshowninthe CallerIDcolumn.ThedialedextensionisshownintheCalledIDcolumn. Fig.2.CallWatcher'smainwindow twopartiescalls ConferenceCalls: Conferencecallswillshowupinthispanel(Fig.3).Thenumberofparticipantsinthe conferenceisshownintheparticipantscolumn.forexample:wehaveconfiguredthatthose whodialstheextension5400willbejoinedtoconferenceroom#400. Aconferenceroomwiththatnumberwillbeautomaticallycreatedincasenosuchroom currentlyexists.asaresult,weshouldseeanewentry(row)isaddedtotheconferencecalls 1 Somethingthatoriginatescalls/whereacallisterminated.A(SIP)phoneisanexampleofuseragent.
Page6of56 panel.otherwise(iftheroomexists),thevalueofparticipantcolumninthecorresponding entryinthepanelshouldbeincrementedbyone.similarly,wheneversomeoneleavesa conferencethethevalueofparticipantcolumnshouldbedecrementedbyone. Fig.3.CallWatcher'smainwindow conferencecalls OnallthepanelsthereisacolumnnamedState.Thatcolumnsshowsthestateofthecall.Acallcanbe inanyofthisstate: IDLE:initialstate CONNECTING:whenAsteriskisabletolocatetheotherparty towhichthecallshouldbe connected,inthecaseoftwopartiescall andisintheprocessofconnectingbothparties. ACTIVE:whenthecallisactive(involvedpartiesaretalkingtoeachother). INVALID:whenthecallhasbeentorn down.inthecaseofconferencecall,itisinvalidwhen everyone(includingthedummyparticipant)haslefttheconferenceroom.theconferenceroom isalsoautomaticallydisposed. Additionaly,userofCallWatchercanperformanactiononanactivecall.Shedoesthatbyselectingan activecall,andclickthebuttonthatrepresentstheactionshewantstoexecute.asyoucanseeinfig.1 throughfig.3,therearetwopossibleactions: Drop:thiswillterminatetheselectedcall.Inthecaseofconferencecall,everyoneintheroom willbekickedoutfirst. Monitor:thiswillinstructAsterisktorecordtheselectedcall. InthecaseofSinglePartycall,it'sclearthatwe'reinterestedinwhatthecallersaidandheard. Sowe'lltapinthechannelbetweenthecallerandtheAsteriskbox. InthecaseofTwoPartiescall,we'reinterestedinwhateitherthecallerorthecalleesaidand heard.there'snodifference,butyouhavetopickone(ipickthecaller). InthecaseofConferencecall,we'reinterestedinwhatthedummyparticipant heard.why? Becausethedummyparticipantwasthereduringthewholeconferencesession.Other participantsmightleftandrejoined,thusmissedsomepartsofthediscussion.that'snotthe casewiththedummyparticipant.forthatreasonwe'lltapinthechannelbetweenthedummy participantandtheasteriskbox. Well,that'sit.Quiterougharequirement.Wearegoingtorefineourrequirementsaswemoveonwith thedesignand further withtheimplementation.
Page7of56 TheDesign...,aStaticView Thefirststepindesigningasystem,particularlysystemdevelopedinanobject orientedway,is understandingthedomain.thisinvolvesidentifyingtheconceptswithinthedomain,howthey're relatedtoeachother,andhowtheyworktogethertoaccomplishasetofobjectives.theoutcomeofthat processissomethingcalleddomainmodel. Agoodplacetostartisanexistingstandard,likeJTAPI(JavaTelephonyAPI).Iadoptedseveral conceptsthatilearnedfromjtapi[res.6].overviewofthedesignisshowninfig.4.pleasekeepin mind,we'renotimplementingjtapihere(it'snoteasy).themodelthatipresenthereworksinour specificsituation,butmightnotworkinother/moregeneralsituations.itissomethingsimpleenough tounderstand,implement,andexplain...,butstillconceptuallycorrect(oratleastmakesenoughsense). Fig.4.Classdiagram Let'sstartwiththecentralconcept: Call.Itrepresentsatelephonecall,theinformationflowing betweentheserviceproviderandthecallparticipants2.theinformationflowbetweenacallparticipant andtheproviderthroughanlogicalconduitthatwecall Channel.Eachparticipantisrepresentedby itsaddress;wecallit CallEndpointinourmodel. Anotherveryimportantconceptinourmodelisthe Provider.It'sanabstractionoftelephonyservice providersoftware.let'stakealookatsomeofthethingsthatwecandowithaprovider: 2 DefinitionisborrowedfromoneofJTAPIWhitepapers(TheJavaTelephonyAPI AnOverview).
Page8of56 drop(callcall); monitor(callcall); Abstractioneffectivelymeansthattheonewhousesitdoesn'treallyknow(norcare)howthose operationsarecarriedout.allsheneedstoknowistheeffectoftheoperation,whichinthecaseof droppingacall(forexample)is:alltheparticipantswillbedisconnectedfromthecallandthecallwill becomeinvalid.wesimplydelegatethatdirtyjobtoourunderlyingtelephonysystem...,asterisk. Sidenote.PleasenoticethatinourmodelProviderisaninterface,notaclass.There'sactuallya concreteclass notshowninthediagram thatimplementsprovider.itsnameis AsteriskProvider. ItcontainsthelogicsofcommunicatingwithAsterisk. EventhoughwehavenootherimplementationofProvider,andneitherdowehaveanyplantocreate anotherimplementationofprovider(thattalkswithpbxotherthanasterisk),stillit'sagoodideato keepthatproviderinterface.iresistthetempation(oraharrasmentfromafriendofmine)toconvert ProviderintoaclassandmoveallthelogicsfromAsteriskProviderintoProvider(andconsequently purgeasteriskprovider). ThegeneralrulethatIapplyis:anabstractionofanexternalsystem suchasasterisk shouldbe interface ified.iteasesthetestingbecausethenwecandosomekindofscenariobasedtestings,even withouttheexistenceofthatexternalsystem.thisinterfacebasedprogramminggetsalongverywell withtestdrivendevelopment(particularlyusingmockobjectapproach). Foracomparison,takealookatthefollowingdiagramthatIstolefromJTAPIWhitepaper[Ref.1]. TheChannelinourmodelismoreorlessequivalentto ConnectioninJTAPI'smodel.The CallEndpointinourmodelisarippedoffversionof AddressinJTAPI'smodel. Fig.5.JTAPI'scallmodel
Page9of56 Let'sgobacktothetelephoneCall.Wehave3typesofcall3: SinglePartyCall TwoPartiesCall ConferenceCall SinglePartyCall SinglePartyCallisacallwithonlyoneparticipant(thusonechannel).Ithappenswhensomeonecalls anextensioninasteriskwhichisconfiguredtoswitchthecalltoanasterisk'sbuilt inivr.thereisa flowofinformationonlybetweenthecallerandtheasterisk.theclass SinglePartyCallinourmodel representsthisconcept. Fig.6.AsteriskCLI singlepartycall WhenIcalledtheextension600 mappedtoechoapplication thelogthatiobservedonasterisk's CommandLineInterface(CLI)wasliketheoneshowninFig.6.Thatlogconfirmedmethatthereare indeedcaseswhenacallhasonlyonechannel. TwoPartiesCall TwoPartiesCallisacallwithtwoparticipants twochannels justlikeanormalphonecallthatmost ofuswouldexpect:).theclass TwoPartiesCallinourmodelstandsforthisconcept. Inourasteriskdialplan,acalltocertainnumberswillbeswitchedtoanotherpartyoutsideofAsterisk. Forexampleifsomeonecallstheextension101,shewillbeconnectedtosomeonenamed Agent1.In thatcasetheparticipantsofthecallare:mrs.janedoe(thecaller)andagent1.takealookatfig.7 (sothatyou'reconvinced:): Fig.7.AsteriskCLI twopartiescall 3 Warning:theyarepurelyproductofmyimagination.YouwillnotfindtheminJTAPIspecification.
Page10of56 ConferenceCall ConferenceCallisacallthatcanhavemorethantwoparticipants(thereforemorethantwochannels). Theclass ConferenceCallinourmodelcorrespondstothisconcept. Asteriskhasabuilt inapplicationforconferencing.itsnameismeetme.there'saslightdifference betweenasterisk'smodelandours(regardingconference).takealookatfig.8. Fig.8.AsteriskCLI conferencecall LookslikeinAsterisk'smodelaconferenceisnotareallycall.It'smorelikeacollectionofsingleparty callswhicharedestinedtoanextensionwhichisconfiguredtoswitchthecalltoaparticularconference room,wheretheinformationfromthecallersaremixedandthendistributedtoeveryparticipants. IdecidednottofollowAsterisk'smodel.IwantedtobeasconsistentaspossiblewiththemodelthatI learnedinjtapi.noneofthesubtypesofjavax.telephony.callinjtapihasasetofcallsasits property.instead,aninstanceofjavax.telephony.callhasasetofinstancesof javax.telephony.connection.therefore,inourmodel ConferenceCallismodeledtohaveasetof instancesofchannel.
Page11of56 TheDesign...,theDynamics Let'sstartwithasimplequestion: WhocreatesinstancesofCalls?.Let'ssee...acallisactuallya conceptwithinthetelephonysystem.imean,acallisestablishedinthetelephonysystem.takealook againatfig.6tofig.8.it'sunderstandableifsomeonesays Ah,currentlythereare5callsgoingon intheasteriskbox afterseeingthereportintheasteriskclithatresultedfromanexecutionof showchannels command. InourmodelthetelephonysystemisrepresentedbyaninstanceofProvider.Thereforeitmakessense toassigntheresponsibilityofinstantiatingcallstoprovider.currentlythere'snomechanismthatlets usersofourprogramtoinstructprovidertocreateacall(callcreationisnoton demand).instead,calls arecreatedautomaticallywithintheprovideronnotificationsreceivedfromtheunderlyingtelephony system. InstanceofProviderisastatefulobject itholdsinstancesofcall.becauseofmemoryusage consideration,wedecidedtomaketheproviderholdsonlytheactivecalls.werefertothosecallsas attachedcalls4.togetthelistofcallsattachedtoaprovidersimplyinvokethemethod getattachedcalls()onit. Aboycried: but...,ialsowanttobenotifiedwhenacalliscreated,and atthesametime obtain thereferencetothatinstanceofcall. Soweinventedaninterfacenamed ProviderListenertocalmthatboy.Ithas2methods: callattached(callcall) calldetached(callcall) Accordingly,weaddmethodsintoProvidertoregisterandunregisteralistenertoit.Thosemethods are: addlistener(providerlistenerlistener) removelistener(providerlistenerlistener) Inourprogramtheclassthatcontrolstheuserinterfaces net.raka.agiexp.gui.main implements ProviderListener.WheneveranewinstanceofCallisattachedtotheproviderthatitlistensto,anew row thatshowsinformationaboutthecall willbeaddedtothetableintheappropriatepanel (dependingontheconcretetypeofthecall). Callconstructionisamulti stepsprocess.it'snotliketheasterisksimplynotifiesourjavaapplication oncewheneveranewcalliscreatedwithintheasterisk,andpassesalongalltheinformationneededto createaninstanceofcallinourjavaprogram.thelibrarythatwe'reusingtocommunicatewith Asterisk Asterisk Java worksatthelowerlevel.whatthelibrarypassestoourjavaapplicationare notificationsabouttheeventsthattakeplaceintheasterisk,intheformofinstancesof ManagerEvent. 4 Whenacallbecomesinvaliditwillbedetachedfromtheprovidertowhichitwaspreviouslyattached.
Page12of56 Evensomethingassimpleascallingtheextension600 thatismappedtotheechoapplication will triggerasequenceofmanagereventsasshowninfig.8.looselyspeaking,thatsequenceofevents buildsupthesinglepartycall. Fig.8.Managereventsgeneratedwhen600isdialed ANewChannelEvent likethefirsteventinfig.8 givesanindicationtoourapplicationthatsomeone /somethingisconnectingtotheasterisk.butatthatpointwecannotfigureoutifitisasingleparty call,twopartiescall,orconferencecall.moreinformationisneeded,thatisthevalueofthenextevents inthesequence.onlywhenthesequenceofeventsturnouttobeliketheoneinfig.8,forexample,we canconcludethatanewsinglepartycallhasbeencreated. Analysisofsequenceofmanagereventswillbediscussedthoroughlyintheimplementationsection. Thepointhereis:weneedsomethingthatkeepstrackoftheevents,andinstantiatesaCallatan appropriatepointintime.inourmodelthat something is CallConstruction.Youcanthinkofan instanceofcallconstructionasafinitestatemachine.youfeedmanagereventstoit,sequentially.ifit acceptstheevent(forprocessing)thenitwillswitchitsstate,dependingonthetypeandtheproperties
Page13of56 oftheevent.whenitarrivestoaspecificstate letscallit callinstantiationstate itwillinstantiate thecorrecttypecall. So,wehaveamanagereventbeingpassedaround.Firstoff,amanagereventisraisedbyAsterisk.Then ittravelsthroughatcpsockettoasteriskproviderthatactsas ManagerEventHandler5thathasonly onemethod,namely handleevent(managereventevent).seearrow#1infig.9. Fig.9.Callconstruction AsteriskProviderwillfirstiteratethroughtheattachedcalls,toseeifanyofthemwould accept the managerevent.itdoesthatbycallingthe process(managereventevent)oneachinstanceofcall(see arrow#2).themethodwillreturntrueifthecallacceptstheevent,orfalseotherwise. AninstanceofCallalsokeepstrackofManagerEventsinordertobeabletodecideifitshouldupdate itsstate.ofcoursenotalleventspassedintoitwillbeacceptedbythecall.acalldetermines acceptabilityofaneventbasedonitscurrentstateandthepreviouseventsthatithasaccepted. IfnoneofthecallsaccepttheeventthenAsteriskProviderwilliteratethroughtheliving CallConstructions.Again,itcallsamethodnamed process(managereventevent)oneachinstanceof CallConstruction(seearrow#3).IfnoneofthemacceptstheeventthenAsteriskProviderwillinspect thetypeoftheevent.ifitisa NewChannelEventandthestateofthechannelis Ring,thenanew instanceofcallconstructionwillbecreatedandaddedtothelistoflivingcallconstructions. Otherwise ifthere'sacallconstructionthatacceptstheevent andtheeventcausesthe CallConstructiontomoveontothe callinstantiationstate,anewinstanceofcallwillbecreatedand attachedtotheasteriskprovider(seearrow#4).then,thecallconstructionwillberemovedfromthe listoflivingcallconstructions. Anotherconceptneedsexplainingisthejavainterface CallListener.Acallwillnotifyitslistenersof interestingeventsthathappeninit.calllistenerhasthefollowingmethod,amongothers: statechanged(intoldstate,callcall) Theclassthatcontrolstheuserinterfacesinourprogram net.raka.agiexp.gui.main alsoimplements CallListener,sothatitcanupdatethedisplayonthetableofcalls(eachtimeanyofthecallsthatit keepstrackofchangesitsstate). 5 AninterfacedefinedintheAsterisk JavalibrarythathandleseventsreceivedfromanAsteriskserver.
Page14of56 SettingUptheEnvironment Let'ssetupourplaygroundbeforejumpingintothefunpartthatiscoding...,startingwiththe installationofasterisk.oh,diditellyouthatweneedtoworkonlinuxos?i'musingopensuse10at home,butasteriskcanrunin(m)anyflavoroflinux. Asterisk Theinstallationiseasy.Onceyouhaveitdownloadedfromhttp://www.asterisk.orgjustdothe followingsteps: 1. Unpackthatfile(i.e.:tarxzvfasterisk 1.2.4.tar.gz) 2. Gotothedirectorywhereyouunpackedthefile 3. Typeinthecommandline:make 4. Thentype:makeinstall Nowwecanmoveontotheconfigurationstage.Asteriskwilllookforitsconfigurationfilesunderthe directory/etc/asterisk/.therearemorethanadozenofconfigurationfiles(mucho),eachofthem controlsparticularaspectofanasteriskserver.ifyou'relazy(likeme),youwouldn'twanttowrite thosefilesfromthescratch.rather,you'dsimplytypemakesampleinthecommandline.thatwill copysampleconfigurationfilesto/etc/asterisk. Amongthoseconfigurationfiles,wewillbeconcernedwithonlyfourofthem: sip.conf extensions.conf manager.conf meetme.conf Andlet'sstartwithsip.conf... sip.conf Amongotherthings,herewedefinethelocallyconnectedSIPphones,whichcanbeofanyofthese types:user,peer,andfriend. ForaUAthatcanonlyplacecallstoAsteriskwesetthetypetouser.TheUAwillbeasked authenticateitselfeverytimeitplacesacall.theauthenticationusernameandthepassword sentbytheua(inresponsetothechallenge)willbematchedagainstthenameoftheentryand thepasswordspecifiedforthatentry,respectively. FortheUAthatAsteriskcanplacecallsto inadditiontoreceivingcallsfrom wesetthetype topeer.thatuaiskindoftrustedbyasterisk,meaningthatitwillnotbeaskedfor authentication(password)whenplacingacall. However,fortheUAtobeabletoreceivecalls,Asteriskneedstoknowitslocation.Registration bytheua isawayofnotifyingasteriskaboutitslocation.onlythenasteriskwillaskfor authenticationusernameandpassword.
Page15of56 Thelasttype,friend,isuser+peerinone. MostofthetimeIsetthelocallyconnectedphonestofriend,though.However,toletpeopleinthe officetoplaceorreceiveacalltooutsidepartiesthroughanothersipserver(e.g.:freeworlddialup), wedefineanentryoftypepeer. Let'sexperimentalittle.First,copyandpastethefollowinglinestotheendofyoursip.conf. [johndoe] type=user secret=p@55w0rd host=dynamic canreinvite=no [goldenboy] type=peer secret=p@55w0rd host=dynamic canreinvite=no (And...?)Let'sreadaboutextensions.confbeforerunninganything:). extensions.conf ThisfilecontainsthedialplanofanAsteriskbox.It'satextfilewherewe inasimplestscenario specifiessomethinglike ifthecallerdials103thenswitchthecalltojeniffertheceo'sassistant.the book[ref.2]succintlydescribesitas:...theheartofanyasterisksystem,asitdefineshowasteriskhandlesinboundandoutbound calls.inanutshell,itconsistsofalistofinstructionsorstepsthatasteriskwillfollow. Dialplanarebrokenintosectionscalledcontext,whichisanamedgroupofextensions.Someofthe contextsdefinedinthesampleextensions.confare:international,longdistance,local,default,and demo.nowlet'stakealookagainatsip.conf.youshouldfind,inthegeneralsection,somethinglikein Fig.10: Fig.10.Aportionofsip.conf Thehighlitedlinesaysthat:thecallswhichcomethroughtheSIPchannel,fromacaller/userwhose contextisunknown/undefined,willbeputinthecontextnameddefault.thedefaultcontextinthe sampleextension.confisdefinedthefollowingway: Fig.11.Thedefaultcontextinthesampleextensions.conf Ok,itleadsustoanothercontextnameddemo(grr...).Thereareseveralextensionsdefinedinthedemo
Page16of56 context,withtheextension600beingoneofthem(seefig.12). Fig.12.Theextension600definedinthedemocontext Theuserjohndoedoesn'thaveitscontextdefined(insip.conf).Thereforethecallfromjohndoewillbe placedindefaultcontext.furthermoreiftheextensioncalledbyjohndoeis600,thenitwillbe(1) greetedwiththeplaybackofanaudiofilenameddemo echotest,then(2)handledbyanapplication namedecho(thatsimplyechoesbackwhateverthecallersays),and(3)greetedagainwiththeplayback ofanaudiofilenameddemo echodone.let'sproveit,bymakingacall. Yourfirstcall First,starttheAsteriskbytypingasteriskinthecommandline,followedbytypingasterisk vvvvvvvvvvrtogetintotheasteriskcli(sothatwecanseewhat'sgoingon).toexitfromthecli withoutkillingasterisk'sprocess typeexitinthecli.tostoptheasterisktypestopnow. Next,let'sconfigureyoursoftphone.Thereareatleast2freeSIPsoftphonesthatrunsonLinux: KPhone(opensource)andXten Xlite.Onthisoccasionwe'lluseKphone.WiththeKphone,first,you needtoconfiguretheidentitythatitwillusewhenplacingacall.followthestepsdisplayedinfig.13. Youhavetosetthe HostPartofSIPURL totheipaddressofyourasteriskbox. Step1 Step2 Fig.13.KPhoneidentityconfiguration
Page17of56 Onceyou'redonewithstep2,clicktheOKbutton,thenyouwillhavetorestartyourKphone(exitand rerun).toplaceacall,typethesipurlofthedestination whichinthiscase600@90.0.0.15 inthe Kphoneaddressbar(seeFig.14),followedbyhittingtheEnterkey6.Whenyou'repromptedfor passwordtypep@55w0rd.that'sit...,areyouconnectednow? Fig.14.KPhone Yoursecondcall Nowlet'strythefollowingscenario: ifsomeone(suchasjohndoe)callstheextension666,hewillbe transferredtogoldenboy....thefirstthingyou'llhavetodoisregisteringtheextension666tothe defaultcontext.copythefollowinglines... exten=>666,1,dial(sip/goldenboy) exten=>666,n,hangup...andpastethemintoextensions.conf,insidethedefinitionofdefaultcontext,suchthatyour extensions.conflookslikefig.15. Fig.15.Definitionofdefaultcontext,afterthemodification NowyouhavetorunanotherinstanceofKphoneforthepeergoldenboy.Ifyouhavemorethanone machine,you'relucky,youjusthavetorepeattheidentityconfigurationstepsexplainedaboveonthe othermachine,specifyinggoldenboyastheauthenticationusername.otherwiseyou'llhavetodotwo things: 1. Createanotherlinuxuseronyourmachine,openanewinstanceofKonsole,loginasthatnew userfromthatconsole,andrunkphonefromtheconsole.followthestepsexemplifiedinfig. 16. 6 ChangethehostpartoftheSIPURLtotheIPaddressyourAsteriskbox.
Page18of56 Fig.16.RunninganotherinstanceofKphone(asusernemo) 2. DoalittletrickwiththeKphonebecausebydefaultKPhonewilltrytohaveanexclusiveaccess tothesoundcardduringaphonecall.thetrickbasicallyisconfiguringatleastoneofthe instancesofkphonetousenulldevice(/dev/null).followthestepsexemplifiedinfig.17. Step1 Step2 Fig.17.ConfiguringKPhonetouse/dev/null Inourscenario,thisinstanceofKPhoneisgoingtoreceiveacall.Thereforeithastoregisteritselfto theasterisk.let'sregisterthephoneunderthenamegoldenboy.followthestepsshowninfig.18.
Page19of56 Step1 Step2 Fig.18.Registeringgoldenboy Toverifyif(locationof)thephonehasbeenregisteredintheAsterisk,gotoAsteriskCLIandtypesip showpeers.fromtheexampleoutputofthecommand seefig.19 wecantellthatthephoneis locatedonthemachine90.0.0.15andisboundtoport5062. Fig.19.Verifyingregistrationofsippeer Atlast,youcanmakeyoursecondcallnow.FromthefirstinstanceofKphone(johndoe),dial 666@90.0.0.15(changetheIPaddress).That'sit...,areyouconnectednow?That'sallaboutthe installationandconfigurationofasterisk.ihopeyoudidn'trunintoanytroubles.next,let'sgetdirty withthecodes!
Page20of56 Implementation Beforeanythingelse,Isuggestthatyoudownloadthesourcecodeofyourapplicationfrom[Res.1]. ThenyouimporttheprojectintoyourEclipseworkspaceandtrytoresolvethelibrarydependency issuesbyyourself.here'showtheprojectstructurelooksonmyeclipse: Fig.20.Eclipsescreenshot(...ateaser;) Let'sbeginourjourneyfromtheconstructoroftheMainclass.TherearethreethingsthatMaindoes whenitsbeinginstantiated,theyare:bopeningaconnectiontotheasteriskbox,cregisteringitself totheasteriskproviderasoneofitslisteners,anddregisteringasteriskproviderasthehandlerof managereventsreceivedfromtheasteriskbox(throughtheconnectionestablishedinstep.1).please takealookatfig.21toseethecorrespondinglinesofcode. Fig.21.SnippetfromconstructorofMainclass
Page21of56 Nowlet'sseehow,roughly,thedisplay(userinterface)isupdatedtoshowtheinformationaboutthe newcalleverytimeanewcallisestablishedintheasteriskbox.youmusthaveunderstoodthatwhena callisestablishedintheasteriskbox,acorrespondinginstanceofcallwillbeattachedtothe AsteriskProvider7.Beingoneofthelistenersoftheprovider,Mainwillreceiveanotificationofthat event(b). Fig.22.SnippetfromconstructorofMainclass Theproviderpassinthecalltothelisteners(whendoingthenotification).Main,inthiscase,will inspecttheconcretetypeoftheinstanceofcallthatitreceivesinthenotification.dependingonthe concretetype,mainwilladdthecalltoanyofthefollowingliststhatitmaintains:singlepartycalls, twopartiescalls,orconferencecalls(c).thelinesofcodeinmainthatcorrespondstothisstepis showninfig.23. Fig.23.ImplementationofcallAttachedinMainclass TheMainclasspushesthenotificationfurthertoaninstanceof PresentationModelbycallingthe callattached(...)methodonthatpresentationmodel(d).presentationmodelrepresentsthestateand behaviorofthepresentationindependentlyoftheguicontrolsusedintheuserinterface.forexample, insteadofhavingthelogicsthatdecidewhetherornotthemonitorbuttoninthepanelwhichshows singlepartycallsshouldbeenabled,mixedwiththecodesthatdefinethingslikedimensionandlaying 7 WhichisthereasonwhyIdrawaprojectionlightfromtheAsteriskboxtotheAsteriskProvider toindicatethatthe AsteriskProviderisrepresentationoftheAsteriskboxintheworldofourprogram.
Page22of56 outoftheguicontrols,wekeepthemintwoseparateclasses: DefinitionsofGUIcontrolsgotoaclassnamed AgiExp. ThelogicsmentionedpreviouslygotoPresentationModel. Theideaisthatthepresentationmodelcanbeusedwithvariouspresentationtechnologies(beitSwing, web,orothers).ofcourse,thenwehavetoprovideabindingbetweenthepresentationmodelandthe userinterfacethatliesontopofit,somehow.formoreaboutpresentationmodel,goto[ref.3]. Ourpresentationmodelpushesthenotificationevenfurther,toitslisteners(thatareinstancesof PresentationModel.Listener),withAgiExpbeingoneofthem(E).Inresponse,AgiExpwillaskthe appropriatetabletorefreshitselftoreflectthelatestcontentofthecorrespondinglistofcallspulledout fromthepresentationmodel(f).thefollowingfigureshowsthesectionofcodesinagiexpfrom wheretherequestforarefreshissent. Fig.24.ThedefinitionofmethodcallAttachedinAgiExp. Respondingtotherequest,thetablewillfirstaskitsmodelforthenumberofrowsthatshouldbe displayed(seepointb infig.25).then,foreachcolumnintherowitwillagainaskitsmodelforthe valuetobedisplayed(c)8. 8 ThisisatypicalwayofimplementingaTableModel.Iassumethatyou'requitefamiliarwithSwingprogramming.
Page23of56 Fig.25.AsectionofcodesinAgiExp.SinglePartyCallsTableModel Sothatwashow anewrowisaddedtothetable.nowi'mgoingtoexplainthe howanentry ina table isupdated.whenyouruntheprogram(later),youwillobservethatthestateofthecall changesoverthetime,untilfinallyitendsupininvalidstate.thefollowingisascientific explanationforthatphenomena. TakealookagainatFig.23,theretheMainregistersitselfasalistenertoan(new)instanceofCall passedtoit.beinga CallListener,themainclassimplementsthefollowingmethods: voidstatechanged(intoldstate,callcall) voidchanneladded(conferencecallconferencecall,channelchannel) voidchannelremoved(conferencecallconferencecall,channelchannel) Everytimethestateofthecallchanges,forexample,thecallwillnotifyitslistenersbyinvokingthe method statechanged(...)oneachoneofthem.thefollowingfigureshowshowmainreactstothe changesofstateofacall: Fig.26.ThedefinitionofmethodstateChangedinMain
Page24of56 [Finally...]We'reabouttogothroughanotherinterestingpartofourjourney,interactingwithAsterisk thatis.i'mgoingtoshowyou,first,howtoreceiveandhandlemanagereventsthatcomethrougha managerconnection.i'llputitinitsownsection,forit'squiteextensive.so,please,bearwithme. Receivingandhandlingmanagerevents AnyobjectthatwantstoreceivemanagereventsfromAsteriskhastosatisfythefollowing requirements: Implementsajavainterfacenamed ManagerEventHandler,whichispartoftheAsterisk Java librarythatwe'reusing.theasteriskproviderclassdoesit. Beregisteredtothemanagerconnectionasoneofitshandlers.Amanagerconnectionisan instanceof ManagerConnection alsopartofasterisk Javalibrary thatrepresentsa (network)connectiontotheasteriskbox.themainclassdoesitfortheasteriskprovider,by invokingthemethod addeventhandler(...)onthemanagerconnection(seefig.21pointd). TheonlymethoddeclaredinManagerEventHandleris handleevent(managereventevent).the followingfigureshowshowitisimplementedinasteriskprovider.isuggestthatyoualsotakealook backatfig.9,you'llnoticethatthelinesofcodeinfig.27istheotherformofthediagraminfig.9. Youcancomparethempoint by arrow,e.g.:pointb infig.27correspondstoarrow#1infig.9. Fig.27.ThedefinitionofmethodstateChangedinMain BynowyoumightbewonderinghowdoIknowthataNewChannelEventina Ring stateindicatesa newcall.myanswer: fromanalysisofsequenceofmanagerevents.here,i'llshowyou...
Page25of56 Analysisofsequenceofmanagerevents Thewayforanexternalprogramtoknowwhat'sgoingoninAsteriskisbymonitoringitthrough managerinterface.well,actually,managerinterfaceservestwopurposes:(1)monitoringand(2) controllingasteriskfromexternalprograms.we'llfocusonthemonitoringpartinthissection. There'snothingfancyhere;Asterisksimplysendsmanagereventstoeveryexternalprogramthathasa managerconnectiontoit.themanagereventsreceivedareorderedintime.however,aneventisnot necessarilyrelatedtotheothereventthatcamebeforeit.therefore,theprogramneedssomekindofa statemachinetosortoutandmakesenseoftheevents. ForeverydistincteventinAsteriskthere'sauniquetypeofmanagerevent(sorry).Thefollowingfigure listsallthetypesofmanagerevent.inourprogramwe'regoingtodealonlywithasmallsubsetofit, namely ChannelEvent(andallitssubtypes), LinkageEvent,and MeetMeEvent. Fig.28.ThetypehierarchyofclassManagerEvent IhavecreatedasimpleprogramthatconnectstotheAsteriskmanagerinterface,anddumpsallthe eventsitreceivestothescreen.thenameoftheprogramis EventDumper.Beforeyoucanrunitwe needtomakesurethatmanagerinterfaceisenabledinasteriskandcreateamanageraccountin Asterisk. Wedothatbymodifyingthefile/etc/asterisk/manager.conf.Gotothegeneralsectionandsetthe enabledpropertytoyes.itisalsoagoodideatouncommentthedisplayconnectproperties(sothatyou canconfirmifyourprogramreallyisconnected).youshouldcomeupwithsomethinglikeinfig.29. Fig.29.Generalsectioninmanager.conf Toaddamanageraccount,addthefollowinglinestotheendofthefile.RemembertochangetheIP
Page26of56 address 90.0.0.15intheexamplebelow totheipaddressofthemachinewhereyou'regoingto connectfrom(i.e.:theipaddressofthemachinewhereourprogramwillberanon). [agiexp] secret=password deny=0.0.0.0/0.0.0.0 permit=90.0.0.15/255.255.255.0 read=system,call,log,verbose,command,agent,user,action write=system,call,log,verbose,command,agent,user,action Herearethestepsforobtainingsequenceofmanagereventsgeneratedbyacall: StartorrestartAsterisk(itwouldn'tpickupthechangeyou'vemadetothemanager.confunless yourestartit). RunEventDumperfromyourEclipseasjavaapplication.Theprogramrequiresthatyoupass threeargumentstoit:(1)theipaddressoftheasteriskbox,(2)theusernameofthemanager accountfortheconnection,and(3)thepasswordofthemanageraccount.youshouldsee somethinglikebelowintheoutputconsoleoftheeventdumperapplication: Thenstartthekphone,thistimelet'sauthenticateasuserjohndoe.First,let'sfindoutmanager eventsgeneratedbyasinglepartycall.dial600@90.0.0.15.alltheeventsduringthecallare showninfig.30.
Page27of56 Fig.30.Managereventsgeneratedforasinglepartycall Let'snotjumpintoanyconclusionsoquickly.Weyethavetoseetheeventsgeneratedbyatwo partiescall.trymakingacallfromjohndoetogoldenboy.alltheeventsgeneratedareshown infig.31. Fig.31.Managereventsgeneratedforasinglepartycall Trybothexperiments makingasinglepartyandtwopartiescall severaltimes,justtobesure.from thoselogsonethingyoucanquicklyspotis:theyallstartwithnewchanneleventwhosestateisring. That'showcametotheconclusionthattheAsteriskProvidershouldknowthatwhenthateventcamein, anewcallshouldbeconstructed(i.e.anewcallconstructionshouldbecommenced)9.therefore,we havethelinesofcodeasisshowninfig.32inasteriskprovider. 9 I'mnotshowingyoutheeventsfromaconferencecall.Toonoisy.But,believeme,it'sthesame.Crescentmyheart.
Page28of56 Fig.32.Managereventsgeneratedforasinglepartycall WheninstantiatedtheCallConstructionwillgodirectlytoitsfirststate,thatiswaitingfor NewExtenEventtocomein.TheFig.33showsthestatediagramofacallconstruction.Tobemore exact,it'slimitedtotheareawithinthegreenborder.theeventsarerelatedtoeachotherbytheir uniqueid,withtheuniqueidofthenewchanneleventasthebasis.inotherwords,aparticularinstance ofcallconstructionwillonlyprocesseventswhoseuniqueidmatchesthebasis. Fig.33.Statediagramofacallconstruction
Page29of56 Rightafteritreachesanyofthe creation states(theoneswithredborder),thecallconstructionwill godirectlytoitsfinalstate.fromthatpointonitnolongerexpectsforevents(becausesubsequent relatedeventswillbehandledbythecallitjustcreated).thereforeitwillremoveitselffromthelistof livingcallconstructionsmaintainedbytheasteriskprovider.thelinesofcodethatcorrespondtofig. 33isshowninFig.34(they'rewithintheprocessEvent(...)methoddefinedinclassCallConstruction). Fig.34.ImplementationofprocessEvent(...)inCallConstruction YoumightbeaskingrightnowhowdoIdecided,forexample,toinstantiateaSinglePartyCallwhenan instanceofnewstateeventwhosestateisupandapplicationisnotmeetmeisreceived.well,firstly, I'vemadecomparisonsbetweenvariouscallscenarios.SoIjustknow(believeitlikeyoubelievein god10 ha!).second:it'sbecauseatthatmomenttheprogramwillalreadyhavealltheinformationit needstoinstantiateasinglepartycall. 10 Ifyoudon'tbelieveingod,you'relostdude.Ihavenotimetoconvinceyouanddoasalvationforyou.Hehehe...
Page30of56 Ok,nomorequestions.Let'sseehowacallhandlesmanagereventspassedtoit.We'llstartwithsingle partycall.thefollowingfigureshowsthestatediagramofasinglepartycall. Fig.35.StateDiagramofsinglepartycall And...Fig.36belowshowshowatwopartiescallhandlesmanagereventspassedtoit. Fig.36.StateDiagramoftwopartiescall Onethingincommonbetweenthewayasinglepartyandtwopartiescallfiltertheevents(suchthat only relevant eventscouldaffectitsstate)isthattheycheckthenameofthechanneloftheevent by calling getchannel()ontheevent andcompareitwiththeidofthedescriptorofthechannelofthe call(phew!). ThefollowingfigureshowsthejavacoderepresentationofFig.36.It'sthecodewithinthemethod processevent(...)intheclasstwopartiescall.togetaverygoodgraspoftheconceptsandmechanics,i
Page31of56 encourageyoutoplaywiththedebuggerandexperimentwithvariousscenariossuchaswhere(1) goldenboydoesn'tregistertoasterisk,(2)johndoehangsupthecallbeforegoldenboypicksupthecall, and(3)goldenboyrejectsthecall. Fig.37.SourcecoderepresentationofFig.36
Page32of56 Testing(#1) Nowlet'stryrunningourprogram(yay!).We'llfirstdofunctionaltestingmanually.Automatictesting willbeexplainedlater.herearethestepsyoushouldfollow: 1. MakesurethatAsteriskisrunning...,withthemanagerinterfaceenabled. 2. Runthemainclassofourprogram,namelynet.raka.agiexp.gui.Main.Youcandothatdirectly fromeclipse.don'tforgettopassinthefollowingprogramarguments: 1. TheIPaddressoftheAsteriskbox. 2. Theaccountnameinmanagerinterface(e.g.:agiexp). 3. Thepasswordoftheaccountinmanagerinterface(e.g.:password) 4. TheportnumberwhereAsterisk'sSIPserviceisboundto(bydefaultit's5060.Checkthe valueofpropertynamedbindportinthegeneralsectionin/etc/asterisk/sip.conf). 5. TheIPaddressofthemachinewhereyou'rerunningthisprogram.Don'tuse127.0.0.1or localhost,useactualipnumber.thisvalueisusedbyconferencecallmonitor,whichi'll explainlater. 6. Theportnumberwheretheconferencecallmonitorwillbeboundtoo.Useanyportwhich isnotoccupied(e.g.:7000).thisvalueisalsousedbyconferencecallmonitor. 3. Makethecalls: 1. Trycalling600fromjohndoe,andwatchthetableinthetabnamed SinglePartyCalls in ourprogram. 2. Trycallinggoldenboyfromjohndoe(dial666).Watchthetableinthetab TwoParties Calls.ExperimentwiththescenariosImentionedpreviously.
Page33of56 Howwasit?Ihopeyouweresatisfied.Didyounoticethatwhenyouclickedontherowthatdisplaysan activecall,thetwobuttonsatthebottomrightcornerofthepanelbecameactive? ClickingtheDropbutton,thecallwillbe,well,dropped(allthepartiesconnectedtothecall willbekickedout,andattheendthecallwillbecomeinvalid). YoucanclicktheMonitorbuttontorecordtheconversationwithinthecall.Ispecifiedinthe codethatthefilewillbesavedin/var/recordings. Umm...,you'veguessedit.We'renowgettingtotheotheruseofAsteriskmanagerinterface,for controlling.solet'sgetbacktocode(wehavemuchtolearn).
Page34of56 ImplementationAgain(ControllingAsterisk) TheactionhandlerofthosebuttonsaredefinedintheclassAgiExp.Theclickingonthedropbutton,for example,willendupinthe drop(callcall)methoddeclaredinprovider.thefollowingdiagram showsthepaththattheclickingwillgothroughtoreachthedrop(...)methodinprovider. Fig.38.Memberscalling'drop(Call)' inworkspace Sonowlet'stakealookattheimplementationofthedrop(...)methodinAsteriskProvider. Fig.39.Memberscalling'drop(Call)' inworkspace So...controllingAsteriskfromexternalprogramisassimpleassendingoutaninstanceof ManagerActionthroughthemanagerconnection.Inthecaseofdroppingacall,wesendaninstanceof HangupAction.Forrecordingacall,wesendaninstanceof MonitorAction.Thefollowingfigure displaysallthestandardmanageractions.butitdoesn'tmeanallofthemcanbeused.thenumberof actionsavailablearedeterminedbythemodulespresentlyloadedintheasterisk.
Page35of56 Fig.40.Memberscalling'drop(Call)' inworkspace Inmostcases,maybe,thestandardactionsprovidedbyAsterisk Javasufficetogetyourjobdone.But, incaseyourfancyrequirementrequires(ugh)youtosendanactionthat'snotinthelistabove,youcan haveyourcustomactionbymakingaclassthatextends AbstractManagerAction.Ofcourse,onthe Asteriskside,theremustalsobeamoduleloadedthatcanhandleyourcustomaction. (What'stheguidelineforimplementingacustomaction otherthanextending AbstractManagerAction?) Notmuch.Iseethataninstanceofmanageractionthatwethrowintothemanagerconnectionissent throughthewireasaplaintext,inaverysimpleformat...,key valuepairs.thefollowingiswhatigot frometherealwhentheprogramsentamonitoraction: action:monitor actionid:421988_3# file:/var/recordings/ 1059416815 channel:sip/johndoe d54a mix:true format:wav Thattextisconstructedoutofthepropertiesoftheaction.Youcanverifythisinformationbytakinga lookatthesourcecodeofmonitoraction.theclasshasthefollowingmethods:getaction(), getactionid(),getfile(),getchannel(),getmix(),andgetformat().ifyou'restillunconvinced whatan infidel thencheckouttheimplementationofthemethod buildaction(...)inclass ActionBuilderImpl(partofAsterisk Java). Conclusion:ifyouhaveathirdpartymodulethatprovidesexternallyaccessibleextrafunctionalities installedinyourasterisk,andyouwanttobeabletoaccessthemfromyourjavaprogram,thenaskfor thedocumentationthatexplainsthekey valuepairsaccepted/requiredbythosefunctionalities.then, onthejavaside,youonlyhavetomakesurethatyourcustommanageraction(s)hastheappropriate getters(forallthekeysspecifiedinthedocumentation)11. 11 JustfollowtheJavaBeanconventionforthenamingofthegetters.
Page36of56 ImplementationReturns(ConferenceCall) Conferencecallisthefinalpieceinourprogram.Iputitthelast,separatedfromtheexplanationabout thetwoothercalls,because(1)thereareotherconfigurationthingstodoinordertomakeitwork(a tinyhassle!),and(2)thereareothernewconceptsandtechniquesthati'dliketointroduce. Zaptelinstallation Tomaketheconferencefeature usingmeetme availableonyourasterisk,youhavetodoseveral things.firstofall,meetmerequiresatimingdeviceinordertooperate(asteriskwon tevencompileit ifnotimingdeviceisfound).alldigiumpcihardwareprovidesa1 khztiminginterface.ifyoulack thepcihardwarerequiredtoprovidetiming,theztdummydrivercanbeusedasatimingdevice12.so..., youneedtoinstallzapteldriversonyourlinux.here'saquickinstruction: 1. Downloadzaptel 1.2.x.tar.gzfromAsterisk'swebsite[Res.2],andunpackit. 2. Iassumethatyoudon'thaveDigiumPCIhardware.So,youneedtohaveztdummycompiled too.editthethemakefile(ofzaptel),andlookforthefollowingsection(andremovethehash thatprecedesztdummy): MODULES:=zapteltor2torisawcusbwcfxowctdmwctdm24xxp\ ztdynamicztd ethwct1xxpwct4xxpwcte11xppciradio\ ztd loc#ztdummy *)IfyourLinuxuseskernel2.6.x,youdon'thavetodothis. 3. Finallydothe:(1)makeclean,(2)make,(3)makeinstall,and(4)makeconfig. 4. Re compileandre installasterisk. That'sallthereistoit.Well,notreally.Atleastnotinmycase.Idon'tknowwhatiswrongwithmy Linux(orzaptelinstallation),IhavetodothefollowingritualbeforestartingAsterisk: Fig.41.Mysillyritual Meetmeconfiguration TheconfigurationoptionsfortheMeetMeconferencingsystemarefoundin/etc/asterisk/meetme.conf. Insidetheconfigurationfile,youdefineconferenceroomsandoptionalnumericpasswords(ifa passwordisdefinedhere,callerwillberequiredtoenterapasswordforenteringtheconferenceroom). Todefineaconferenceroom(withnumber400,andwithoutpassword),simplyaddthefollowingline totheendofmeetme.conf: 12 Again,Icopied and pastedseveralsentencesfrom[ref.2] Chapter3,onCompilingZaptel.
Page37of56 conf=>400 Now,tosupportsuch requirement as: ifthecallerdialsthenumber5xxx,thensheshouldbejoined toconferenceroom#xxx,wehavetoaddthefollowinglinesintheextension.conf(puttheminthe sectionfordefaultcontext): exten=>_5xxx,1,meetme(${exten:1},i) exten=>_5xxx,n,hangup Thereyouhaveyourconferencingsystemsetup.Re startasterisk,followedbymakingacall(from johndoe)tothenumber5400andonceyou'reconnectedtotheconferenceroom,justfollowthe instructiononthephone(afterthetoneblablabla...)13.well,iguessaconferencewouldn'tbeveryfun withonlyonepersonintheroom.so,trymakingacallfromotherua(e.g.:goldenboy)to540014. Observe!YoucanstartwithcheckingAsterisk'sstatusfromtheCLI(seeFig.42). Fig.42.Checkingchannels&meetmestatus Backtoourprogram Thelogicofcreationofaconferencecallgoeslikethis(thisistoclarifythediagraminFig.33): Incomingcallstoaconferenceroomgothroughthesamestatetransitions,thatis:waitingfor NewExtenEvent waitingfornewstateevent waitingformeetmejoinevent creationof conferencecall. However,onlythefirstcallshouldcausethecreationofaninstanceofConferenceCall(B).As longasthefirstcallhasn'tlefttheconferenceroom,thesubsequentcallsshouldbeadded asa newchannel totheinstanceofconferencecallcreatedpreviously(c). ThelogicabovetranslatestothefollowingjavacodesintheclassCallConstruction: 13 Youneedtoinstallapackagenamedasterisk soundtobeabletoheartheinstruction.asterisk soundissimplya collectionofaudiofiles. 14 It'sbettertocarryonthisexperimentinalocalareanetworkwithseveralcomputers(sothatyoucanreallyplaywith sound remember?thesoundcardexclusiveaccessproblem).butifyou'reonlyinterestedinthesignalling,it'soktorun allthephonesinasinglecomputer.
Page38of56 Fig.43.Conferencecallcreationlogic Well,therewasnothingnewintheaboveexplanation(justareiterationofprocessingofmanager events).thetwonewinterestingthingsthatipromisedareintegrationusingasteriskgateway Interface(AGI)andprogrammingwithSIPstacklibrary.Let'sbeginwithAGI.
Page39of56 LeMayeur PortraitofNiPolok Sorryfortheinterruption,butIhavetogivesomewordsofcautiontoyou.It'saboutthestatemachine. Idon'twantto(mis)leadyoutothinkthatthestatemachineinthisprogramisreusable(canbeusedin allkindsofsituationinvolvingdetectionofcreationanddestructionofacallinasterisk). Iwouldsaythatastatemachineishighlyrelated(coupled?)tothedialplan.Evenalittlemodification tothedialplanmightrenderthestatemachineuseless.forexample,ifyouusedafunctionotherthan DialtomakeanoutboundcallfromyourAsterisk,thenyouwouldnotseethetwopartiescallshowup intheuserinterface.it'sbecauseourstatemachineassumesthatthelifecyleofatwopartiescallbegins whenanewextenevent whoseapplicationpropertyissettodial isreceived(seeagainfig.34,blue shadedarea). So,Ithink,indevelopingatelephonyapplication(usingtheapproachsimilartotheoneweusehere) firstyouhavetounderstandtherequirementsforthedialplan.thenyouhaveitsstructurewelldefined, sothatyouknowallthepossiblesequenceofevents.finallyyoudesignyourstatemachinebasedon that.
Page40of56 AsteriskGatewayInterface(AGI) TheAsteriskGatewayInterface,orAGI,providesastandardinterfacebywhichexternalprogramsmay controltheasteriskdialplan. Youmusthaverealizedthatthe language weuseinthe/etc/asterisk/extensions.conftocraftthe dialplanisverysimple(andlimited).itsupportsbranchinginaverylimitedway,throughtheuseof dialplanfunctionsnamedgotoif.itdoesn'tevenseemtosupportlooping.wecandosimplestring patternmatching,though,likewedidwiththeextensiontoaccessaconference(_5xxx). Clearlyother additional waysofcontrollingadialplanisrequired...,withotherlanguageswhichare morecapable(andmorepopular).that'sthecaseforagi;it'swhatcgiistowebservertoasterisk. YoucanprogramanAGIinlanguagessuchasC,python,Java,andmaybesomeothers. TheAGIscriptcanbedeployedinthesamemachineastheAsterisk(asisthecommoncasewithCor python basedagiscript),oronaremotemachine(inwhichcase,thecommunicationisconducted betweenasteriskandtheagiserverthathoststhescriptthroughasocket,usingfastagiprotocol). Inourprogramwetakethelaterapproach,andtheprogramminglanguagethatweusetocreatethe scriptisjava.thelibraryasterisk JavacomeswithclassesthatallowustorunanAGIserverin embededmode(inadditiontoastandaloneagiserverprogram).nowlet'stakealookhowwecallour remotelydeployedagiscriptfromtheasterisk.replacethefollowinglinesofcode(thatyouput earlier)fromextensions.conf: exten=>_5xxx,1,meetme(${exten:1},i) exten=>_5xxx,n,hangup...with... exten=>_5xxx,1,agi(agi://90.0.0.15/conferencemonitor?roomid=${exten:1}) exten=>_5xxx,n,meetme(${exten:1},i) exten=>_5xxx,n,hangup Basedontheconfigurationabove,whenacallenterstheextension5XXX,arequestwillbesenttoan AGIserverrunningonthemachine90.0.0.15toexecuteascriptwhichismappedtoanidentifier conferencemonitor.aparameternamedroomid,whosevalueissettoxxx,willbepassedalongthe request.onsuccessfulreturnfromtheexecutionofthescript,thenextlineinthedialplanwillbe executed. TohaveacustomAGIserver,youhavetocreateaclassthatextends DefaultAGIServer.Furthermore, theinstanceofthatservermusthaveitsmappingstrategyset.amappingstrategydetermineswhich instanceof AGIScripthastobecalledtoserviceagiven AGIRequest. Wesetthemappingstrategybycalling setmappingstrategy(...)onthatinstanceofagiserver15.in ourcase,weassignaninstanceof ConfMonitorMappingStrategytoourserver,thatreturnsan instanceof ConferenceMonitorScriptfortherequestsmadetoconferenceMonitor. 15 ThemappingforstandaloneAGIserverisspecifiedinapropertiesfilenamedagiserver.conf.
Page41of56 Fig.44.SourcecodeofConfMonitorAgiServer Ourserverislaunchedduringtheinitializationofourprogram.Wedothatbystartinganewthread fromtherun()methodinourmainclass thatinstantiatesandruntheserver(seefig.45). Fig.45.StartingembededAGIserver AnAGIscript,inourjavaprogram,isaninstanceofaclassthatextends BaseAGIScript.Theclass hastoimplementstheservice(...)method.thefollowingfigureshowstheimplementationofthe service(...)methodinconferencemonitorscript.
Page42of56 Fig.46.Theservice(...)methodofConferenceMonitorScript Ourscriptsimplydelegatesthecalltoaninstanceof ConferenceMonitor,askingittomonitora conferencewiththegivenroomid. Whyalltheseintricacies(withthescript,conferencemonitoring,andall)? Well,withthescript,basicallywewanttointerceptcallstoaconferenceroom,suchthatwecansneak inadummy(silent)participanttotheroom(ifwehaven'talreadydoneso).sneakinginthatdummy participantisthetaskthatweassigntoconferencemonitor.howdoesitaccomplishthetask?it'sthe topicforthenextsection...
Page43of56 ASipofSIP Firstofall...,whatisSIP?It'sanend to end,client serversignallingprotocol.signallingintelephone systemisthekeymechanismbywhichtelephonecallsaresetupandterminated.manyvalueadded servicesinatelephonesystemaremadepossiblebyhavingprogramsthatminglewiththesignalling process.examplesofvalueaddedservicesare:pbxfeatures,groupcalling,clicktoconnect,andmany kindsofintelligentnetwork(in)16services. SignallingonSIPiscarriedthroughIPnetwork(thereforeit'saVoIPprotocol).Itisspecifiedinan RFCnumbered3261.Thekindsofentityinthenetworkthatcandealwithsignallingmessagesare17: UserAgent(userapplication),thatcanbefurtherclassifiedinto3types: UAClient(originatescalls) UAServer(listenforincomingcalls) B2B(back to back)ua SIPProxyServer:relayscallsignalling,i.e.actsasbothclientandserver. SIPRedirectServer:redirectscallerstootherservers. SIPRegistrar:acceptsregistrationrequestsfromusers. OnethingfromSIPthatattractsmemostisthefactthatitusesplaintextforthemessagesusedinthe signalling.theformatisalsosimple,attribute value pair(that'slooksverymuchlikehttp messages).so,aslongasyouunderstandtheprotocolspecification,andknowhowtoparseand constructthosemessagesinyourprogram,you'regoodtogo18.thesipentitiesmentionedaboveare basically(sip)messageprocessors,thatbehaveinsuchwaythattheyconformtoaspecification.the followingfigureshowsanexampleofsipmessage. Fig.47.AnexampleofSIPmessage 16 Intelligentnetworkisacollecionofserversandotherresourcesusedtocontrolcallsetupandtoprovidemediaservices suchasannouncements,voicemail,etc. 17 Here dealwith meanssending,accepting,modifying,orpassing/redirecting. 18 Well,maybeintheharshrealityit'snotthatsimple.
Page44of56 Inourprogram,weimplementaverysimpleUAclient.Tohelpuswiththeconstructionandparsingof SIPmessages(amongotherthings19)weuseNIST SIPthatisanopensourceimplementationofa specificationnamedjainsipissuedbyjavacommunityprocess. ThisUAclientrepresentsadummyparticipantthatweputinaconferenceroom.Foreachactive conferencewehaveadistinctinstanceofuaclient.asaclient,theonlythingsitdoesare:(1)making acalltotheconferenceroom,and(2)disconnectingitselffromtheconferenceroomwhenthe conferenceends.thedetailsofthoseoperationsareencapsulatedinaclassnamed NoteTaker,that hasthefollowingmethods: joinconference(stringroomid) leaveconference() InstantiationofNoteTakerandinvocationofitsjoinConference(...)methodtakeplaceinsidethe executionofthe monitorconference(...)methodofconferencemonitor(seefig.47). Fig.48.ImplementationofmonitorConference(...)inConferenceMonitor YoucansaythatConferenceMonitorisallears,becauseitimplementssomanylistenerinterfaces: SipListener20,ProviderListener,andCallListener. AsaSIPlistener,itprocessesresponseeventsitreceivesfromtheSIPpeer21,insidethe processresponse(...)method(whereithasthechancetosendthesipackmessage,thatmarks thecompletionofacallsetup,backtothepeer). Asaproviderlistener,itregistersitselfaslistenertoaconferencecallwheneveritreceivesa notificationthata(conference)callhasbeenattachedtotheprovider. Asacalllistener,itlistenstothedynamicofaconferencecall.Insidethe channelremoved(...)method,ithasthechancetocheckthenumberofremainingparticipantsin theroom,andaskthenotetakertodisconnectitselffromtheroomifthenumberis1(seefig. 49). 19 Ifyou'rearegexpguru,forexample,youmightthinkyoudon'tneedlibraryjustfortextprocessing.However,thereare somemorehighlevelconceptsabovesipmessages,suchasdialogandtransaction.ifyou'dliketoworkwiththem, easily,you'dwanttousespecializedlibrarylikejain SIP. 20 AninterfacedefinedinJAIN SIP. 21 TheotherSIPentitythatitcommunicateswith,whichinourcaseistheAsteriskbox.
Page45of56 Fig.48.ImplementationofmonitorConference(...)inConferenceMonitor Wegettotheimportantquestionsnow:(1)whatmessagesareexchangedduringcallsetupandtear down,(2)howdoweconstruct/parsethem,and(3)howdowesendthem.let'sbeginwiththe messages.thefollowingfigureshowsthesignallingofanormalcaseofsessionsetupandteardown. Fig.49.Setupandteardownofacallsession InSIPparlance,makingacallis sendinganinvitation (tothecallee).thecallerdoesthatbysending asiprequestwhosemethodnameissettoinvite(pointbinfig.50).theanswererwillsendthe responsetothelocationdestinationspecifiedinthefirstviafieldintherequest,whichinourexample itisport5062onmachinewithip90.0.0.15(pointc). ThelocationspecifiedintheViafieldisnotnecesarillythesameasthelocationofthecaller.It's possiblethattherequesthastravelledthroughproxy(s)beforeitreachedthedestination(whereeach proxyinthesignallingpathinsertedaviafieldbeforethefirstviafieldfoundintherequest).however, wecanalwaystelltheultimatedestinationfortheresponsefromthevaluespecifiedinthecontactfield intherequest(pointd).
Page46of56 TheINVITErequestcontainsasessiondescriptionthatindicatesthedesiredcommunicationmeans (audio,video,etc),parametersofthosemeans(suchascodectypes),andaddressaddressesfor receivingmediamediafromthepartywhowillanswerthecall.inourexample,thesenderspecifies thatitsupportscodecspcma,ilbc,gsm,andpcmu.italsospecifiesthatit'swaitingforthemedia onport1032(pointe). TheOKresponsefromtheanswereralsocontainsasessiondescription.inourexampleitsaysthatit supportsgsm,pcmu,andpcma,andisreceivingmediaonport16454(pointf). Fig.50.ExampleSIPmessages What'stheroleofAsteriskinaSIPcall?Theansweris:itcanbeeitheraback to backuseragent(b2b UA)oraSIPproxy.AsaB2BUAitstaysinthemediapathofthecall(whichmeans,therewillbe2 mediaconnectionsinthecall:(1)betweencallerandasterisk,and(2)betweenasteriskandthe answerer).asasipproxy,therewillbedirectmediaconnectionsbetweenthecallerandtheanswerer. (seefig.51).
Page47of56 Asteriskasproxy Asteriskasback to backagent Fig.51.AsteriskinaaSIPcall AsteriskwillactasaproxyifboththecallerandtheanswerersupportsRe INVITE,whichisa mechanismofmodifyingthesessiondescriptionduringthecall.foruathatweregisterinsip.conf,we cansetitsre invitabilitybysettingthecanreinvitepropertytono.inourprogramwehavethemallset tono.thereasonisbecauseweuseasterisk'sbuilt inmonitorapplicationforrecordingthecall.that applicationrequiresthatasteriskbeinthemediapath. AnothervalidreasonforoperatingAsteriskasB2BUAistofreeusfromworryingtoomuchabout compatibilityissues(esp.regardingcodecsupports)betweentheuasinvolvedinthecall,because Asteriskwillironouttheincompatibility(ifany)byperformingtranscoding. I'mnotgoingtoexplainhowtouseJAIN SIPAPIindetail.Isuggestthatyoutakealookatthe implementationofjoinconference()andleaveconference()methodinnotetakeranddecipherthecode byyourself.hints: FrominsidethejoinConference()wesendtheINVITE FrominsidetheprocessResponse()wesendtheACK(whenappropriate). FrominsidetheleaveConference()wesendtheBYE. Abitmoreconfigurationsfortheconference... First,weneedtoregisteraUAtotheAsterisk,thatcanonlymakescallstoit.Thisisforthenotetaker. So,first,copyandpastethefollowinglinestotheendofyoursip.conf. [notetaker] type=friend host=90.0.0.15 port=7000 canreinvite=no context=notetaker WesetthehosttoaspecificIPaddressinsteadofdynamic.Theport,too,issettoaspecificnumber. ThereasonisbecausewewanttokeeptheimplementationofNoteTakerverysimple(wedon'twantto implementregistrationstepinourcode).therefore,it'simportantthatwerunourprogramona
Page48of56 machinewhoseipaddressmatchesthehostwespecifyhere,andwemustalsotellourprogram throughexecutionparameters tobindthenotetakertotheportwespecifyhere(7000). Wealsospecifythatcallsfromnotetakerbeputinaseparatecontextnamednotetaker.Thisistomake surethatcallsfromnotetaker thatshouldbedirectedtowardaconferenceroom willnotbeconfused withcallsfromotheruas(thatmightgotosomewhereelse).i'llexplain,butfirstcopyandpastethe followinglinestotheendofextensions.conf. [notetaker] exten=>_xxx,1,meetme(${exten},i) exten=>_xxx,n,hangup Rememberthatintheextensions.conf,forcallsthatentertheextension5XXX,wedropthefirstnumber fromtheextension(5)andpasstherestit(xxx)totheconferencemonitorscriptasaparameternamed roomid?...right,youdorememberit:).well,thenotetakerwillsendaninviterequestto XXX@your.asterisk.host. Now,let'ssupposewedidn'tputthetwolinesabove anythingexcept[notetaker] inaseparate contextthatisexclusiveforcallsfromuanotetaker.andalso,supposethatwehadaconferenceroom withnumber666(registerdinmeetme.conf).then(bummer!)thecallfromnotetakerwoulddirectedto goldenboy(assumingthatwealsohavedefinedextension666forgoldenboyinthesamecontext). That'sallfortheSIP. Let'smoveontothelastsection(yay!)...,stresstestingwithSIPp.
Page49of56 StressTestingwithSIPp SIPpisan(opensource)performancetestingtoolforSIPprotocol.WeuseittosimulatemultipleUAs makingacallatthesametime.youmusthaverealizedthatacallsession(1)startswiththesendingof aninvitation(oracceptinginvitation),(2)isterminatedwithteardown(sending/recevingabye),and (3)anythingthathappeninbetween.Together,theymakeacallscenario. WithSIPp,wespecifythescenarioinanXMLfilethatcontainstheSIPrequeststobesent,andthe expectedresponses.they'reprocessedindocumentorder fromtoptothebottomofthedocument whenthescenarioisbeingplayed.inthefile,asiprequestisenclosedwithina<recv>tag,whilea <resp>tagcontainsinformationaboutanexpectedresponse.formoreinformationaboutthecontent ofascenariofile,pleaseconsultsippdocumentation[ref.4]. Inourexperimentwehavetwoscenariofiles.Oneofthemrepresentsthescenariofromthestandpoint ofthecaller22,andtheotheronerepresentsthescenarioofthesamecallfromthestandpointofthe answerer23. Sidenote.HowdoIknowwhattowriteinthescenariofiles?Theanswer:copy and paste(andabitof editing)fromsiptrafficofarealcall,madefromsipphonethatiknowworks(e.g.:kphoneand Xlite),capturedusingEthereal. Forexample:IknowthatAsteriskSIPservicewasboundtoport5060,andKPhonewasboundto anotherport(let'ssay5062).whatididwasacopy and pasteofsipmessagesoriginatingfromport 5062andgoingport5060intocaller.xml,andviceversafortheanswerer.xml. Easy,eh?Believeme,Etherealisa(network)programmerbestfriend:).Here'sanicescreenshotofit: 22 Thefilenamedcaller.xmlunderconf/intheprojectdirectory. 23 Thefilenamedanswerer.xml.
Page50of56 Inordertomakethingssimplerforthetesting,weneedtolifttherequirementforthecallerto authenticate.wedothatbydeleting/commentingoutthesecretlineintheuseragentconfiguration parametersinsip.conf(seefig.52). Fig.52.Commentoutthesecretline Theotherthingweneedtodoisdroppingtherequirementfortheuseragentswhichareassignedto receivecallstoregister24.thisisdonebychangingthehostpropertyoftheuseragentfromdynamicto anipnumber,andbyspecifyingaportnumberinthesip.conf.and,justlikethecaller,wealsodrop therequirementfortheanswerertoauthenticate.seefig.53. Fig.53.Changetostaticregistration Nowyou'reset!Ihavepreparedtwoscriptfiles:caller.shandanswerer.sh.Thefollowingfigureshows thecontentofcaller.sh. Fig.54.Thecontentofcaller.sh Accordingtothescript:theinstanceofSIPpwillplaythescenariospecifiedincaller.xml(B).The maximumnumberofcallsthatthesippinstancewillgenerateis5(c),andeachuseragentassociated withacallwillbeboundtoarandomlyselecteddistinctport(d).thesiprequestwillbesenttosip servicerunningonport5060inmachine90.0.0.15,whichinourcaseistheasterisk'ssipservice(e). Finally,thevaluestoreplacethe fields inthescenariofilearereadfromafilenamedcaller.csv(f), seefig.55. 24 ThisisduetocurrentlimitationinSIPp,whichI'llexplainattheendofthissection.
Page51of56 Fig.55.Valuesforfieldsincaller.xmlarereadfromcaller.csv Theotherside answerer.sh isconfiguredtoruninudpmonosocketmode( tu1commandline parameter)thatmeansalltheuseragentsitstartswillbeboundtothesameportnumber(specified through pcommandlineparameter),whichinourcaseis600125. Nowwe'rereadyto(stress)testtheapplication.Followthesesteps: 1. RunourapplicationfromEclipse(orfromthecommandlinebyexecutiontherunapp.shscript) 2. Runtheanswerer.sh 3. Runthecaller.sh Goodluck,andenjoy.Foryourreference,here'sascreenshotofexecutionofanswerer.sh&caller.sh. answerer caller 25 Itmustmatchtheportnumberwespecifyinsip.confforuseragentsthatweassigntoanswerthecalls(e.g.:goldenboy).
Page52of56 AnalysisofproblemwithregisteringfromSIPp. Thereareatleast2possiblemodesofexecutionofSIPp:servermodeandclientmode.Inthetesting scenarioforoursoftware,specificallyforthecaseofinboundcall,wewouldlikethesippinstance thatsimulatestheua(useragent)ofacontactcenteragenttoberunninginservermode.ontheother hand,thesippinstancethatsimulatestheuaofacustomerwhomakesacalltothecontactcenter shouldberunninginclientmode. Whenrunninginservermode,SIPpmaintainsmapofactivecallsthatitishandling.Eachcallinthe mapisidentifiedbyitscall ID.WheneverSIPpreceivesSIPmessagewhoseCall IDdoesn'thave correspondingentryinthemap,itwillcreateanewinstanceofcall(inthememory)andstorethatcall inthemap(seesipp.cppline2060).iusesippversion1.1(unstable)snapshot2006 01 20(...andthis problemcontinuestoexistinthelatestsnapshot,2006 03 15). Whenrunninginclientmode,thatmessagewillbeconsideredasout of callmessage,andwillbe treatedassuch(discarded);seesipp.cppline2091. Unfortunately,wecan'tsetthemodethroughsomekindofexecutionoption(s)...,SIPpwillfigureitout byitself,inan"interesting"way.itwillsetitsmodeofexecutiontoservermodeonlyifthefirst instructioninthescenariofileisa<recv>(seescenario.cppline521).previouslywehadaproblem relatedtothis,becauseinouroldanswerer.xmlthefirstmessageisa<send>thatsendsasipmessage forregisteringthelocationoftheuaoftheagenttotheasterisk(suchthatasteriskknowswhereto forwardthesipmessagetowheneveritreceivesanincominginvitefromtheuaofthecustomer). WeneedtoadapttothissituationbyremovingtheneedfortheUAoftheagenttoregisteritself,sowe cancommentoutalltheinstructionsthatprecedesthe<recv>forinviteintheanswerer.xml. Thiscanbeachievedbymodifying/etc/asterisk/sip.conf.Previously,foreachagentinthatfile,weset thehostpropertytodynamic.nowweneedtoswitchtostaticmode,byspecifyinganipaddressto thatproperty.additionaly,weneedtospecifytheport(towhichtheuaoftheagentisexpectedto listenforsipmessages).inourcase,wespecifythatallagentuaswillbelisteningtothesame(udp) port:6001.correspondingly,weneedtosetthetransportmodeoftheinstanceofsippfortheagent's UAtoUDPMonoSocket(inanswerer.shwenowhavethe tu1 p6001switch). AnalysisofproblemwithauthenticatingfromSIPp. Theauth_uriincludedbySIPpintheresponsetotheproxyauthenticationchallengedoesn'tmatchthe onewhichisexpectedbyasterisk.theonegeneratebysippiscomposedofremote_ip:remote_port (e.g.:90.0.0.15:5060),whileasteriskexpectsittobeservice@remote_ip:remote_port. Theauth_urisentbySIPpcanbeforcedtoavaluespecifiedthrough auth_uricommandline parameterwhenrunningsipp.however,withthistrickalltheuseragentsgeneratedbysippcanonly makeacalltoonesipuri,thatisthevalueofauth_uriparameter. That'snotappropriateinoursituationbecausewewanttohavemultipleagentsmakingcallsto differentdestinations:someofthemcall600,theotheronescall666,andtherestcall5400&5500.
Page53of56 References 1. JTAPIWhitepapers:http://java.sun.com/products/jtapi/reference/whitepapers 2. JimVanMeggelen,JaredSmith,andLeifMadsen. AsteriskTM.TheFutureofTelephony. O'Reilly,September2005. 3. PresentationModel:http://www.martinfowler.com/eaaDev/PresentationModel.html 4. SIPp1.1Reference:http://sipp.sourceforge.net/doc1.1/reference.html 5. RFC3261:http://www.ietf.org/rfc/rfc3261.txt 6. Asterisk'sWiki:http://www.voip.org/wiki Asterisk Resources 1. Sourcecodeoftheprogram:http://www.simitel.com/resources/booklet1/article_1.tar.gz 2. Asteriskwebsite:http://www.asterisk.org 3. Asterisk Javalibrary:http://sourceforge.net/projects/asterisk java 4. SIPp:http://sipp.sourceforge.net 5. Ethereal:http://www.ethereal.com 6. JTAPI:http://java.sun.com/products/jtapi/index.jsp 7. NIST SIPlibrary:http://jain sip.dev.java.net Abouttheauthor... CokordaRakaAnggaJananuraga,abalinesebornin1978.HemovedfromBalitoMexico in2005,andcurrentlyisworkingforatelecommunicationsoftwarecompanynamed Simitel.Helovestoeatthegreasysucklingpig(babiguling),atraditionalbalinesefood... Whatelse?Hmm...Iguessthat'sall. HasbeenprogrammingwithJavasince6yearsago,andstillcanstandituntilnow(let's see...). Hepostshisrantstohisblogathttp://www.jroller.com/page/donrakaandcanbecontacted atrakabali78@yahoo.com
Page54of56 Troubleshooting 1. Q:MysoftphonefreezeswhenItriedmakingcallfromit. A:Isyourcomputerdisconnectedfromthenetwork? Ifyes,makesurethatintheroutingconfigurationofyournetworkdevice(ethernet)the defaultgatewayissettonone.ihaven'tgotachancetofindoutwhy.ithappenedtome once,andsettingdefaultgatewaytononesolvedmyproblem.
Page55of56 TableofContents 1. 2. 3. 4. 5. Preface Audience AllYouNeedIs... MissionBriefing TheDesign,aStaticView 1. SinglePartyCall 2. TwoPartiesCall 3. ConferenceCall 6. TheDesign...,theDynamics 7. SettingUptheEnvironment 1. Asterisk 2. sip.conf 3. extensions.conf 4. Yourfirstcall 5. Yoursecondcall 8. Implementation 1. Receivingandhandlingmanagerevents 2. Analysisofsequenceofmanagerevents 9. Testing(#1) 10. ImplementationAgain(ControllingAsterisk) 11. ImplementationReturns(ConferenceCall) 1. ZaptelInstallation 2. MeetMeconfiguration 3. AsteriskGatewayInterface 4. ASipofSIP 5. Abitmoreconfigurationsfortheconference 12. StressTestingwithSIPp 13. References 14. Resources 15. AbouttheAuthor 16. Troubleshooting 2 2 3 5 7 9 9 10 11 14 14 14 15 16 17 20 24 25 32 34 36 36 36 40 43 47 49 53 53 53 54
Page56of56 IhopeyouenjoyedreadingthedocumentasmuchasIenjoyedwritingit.Also,Ihopethatyoufindthe documentuseful,foryou,orformemberofyourteam.pleasesendyourfeedback(critics,suggestions, etc.)torakabali78@yahoo.com.becauseineedtoknowwhetherornoti'vemademyselfclearenough, inanefficientway.i'mlookingforwardtoyourfeedback!inthemeantime,i'llbewiththeseguys preparingsatay.cya.