id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
722,201
./clinfinity/Clinfinity.c4d/Helpers.c4d/Arrow.c4d/Script.c
/*-- Pfeil --*/ #strict protected func Initialize() { SetAction("Turn"); } static arrow_target; global func SetArrow(iX,iY) { if(FindObject2(Find_ID(_AR1),Find_AtPoint(iX, iY - 16))) return; RemoveObject(FindObject(_AR1)); CreateObject(_AR1,iX,iY,-1); arrow_target = 0; } global func RemoveArrow() { RemoveObject(FindObject(_AR1)); arrow_target = 0; } global func SetArrowToObj(object obj) { if (arrow_target == obj) return(); RemoveObject(FindObject(_AR1)); CreateObject(_AR1, obj->GetX() + obj->GetDefCoreVal("Width") / 4, obj->GetY() - obj->GetDefCoreVal("Height") / 2 - 10, -1); arrow_target = obj; }
722,202
./clinfinity/Clinfinity.c4d/Helpers.c4d/Menu2.c4d/System.c4g/Helpers.c
/*-- Helpers --*/ #strict 2 //Fⁿgt ein Item am Ende eines Array ein global func PushBack(value,&aArray) { return(aArray[GetLength(aArray)]=value); } global func DeleteLast(&aArray) { return SetLength(aArray, GetLength(aArray) - 1); } //Aus Doku geklaut global func SetObjectPicture(idSrcDef, pObj) { SetPicture(GetDefCoreVal("Picture", "DefCore", idSrcDef, 0), GetDefCoreVal("Picture", "DefCore", idSrcDef, 1), GetDefCoreVal("Picture", "DefCore", idSrcDef, 2), GetDefCoreVal("Picture", "DefCore", idSrcDef, 3), pObj); SetGraphics(0, pObj, idSrcDef); return(1); } global func GreyString (string sz) { return Format("<c 888888>%s</c>", sz); }
722,203
./clinfinity/Clinfinity.c4d/Helpers.c4d/Menu2.c4d/System.c4g/Menu.c
/* Menⁿsystem */ #strict 2 static const MS4C_Typ_Bool = 0; static const MS4C_Typ_Enum = 1; static const MS4C_Typ_Range = 2; static const MS4C_Typ_Submenu = 3; //Conditions static const MS4C_Cond_Not = 0; static const MS4C_Cond_And = 1; static const MS4C_Cond_Or = 2; static const MS4C_Cond_Activated = 3; static const MS4C_Cond_Chosen = 4; static const MS4C_Cond_Less = 5; static const MS4C_Cond_Equal = 6; static const MS4C_Cond_Greater = 7; static const MS4C_Verbose_ObjectMessage = 1; static const MS4C_Verbose_GlobalMessage = 2; static const MS4C_Verbose_Log = 4; //Array indices static const MS4C_Symbol_Index = 0; static const MS4C_Caption_Index = 1; static const MS4C_Hash_Index = 2; static const MS4C_Sequence_Index = 3; static const MS4C_Type_Index = 0; static const MS4C_Cond_Index = 1; static const MS4C_Name_Index = 2; static const MS4C_Id_Index = 3; static const MS4C_Data_Index = 4; global func CreateMenuTemplate(id Symbol, string Caption) { var aMenu=CreateArray(4); aMenu[MS4C_Symbol_Index]=Symbol; aMenu[MS4C_Caption_Index]=Caption; aMenu[MS4C_Hash_Index]=CreateHash(); aMenu[MS4C_Sequence_Index]=CreateArray(); return aMenu; } //Fⁿgt dem Menⁿ eine Boolauswahlm÷glichkeit hinzu, Key wird zur Identifizierung benutzt, sollte eindeutig sein global func AddBoolChoice(&menu, array aPath, Key, array aCond, string szName, id idItem, bool fDefault) { if (MenuContains(menu, aPath, Key)) return false; MenuPut(menu, aPath, Key, [MS4C_Typ_Bool, aCond, szName, idItem, fDefault]); return true; } //Fⁿgt dem Menⁿ eine Enumauswahl hinzu global func AddEnumChoice(&menu, array aPath, Key, array aCond, string szName, id idItem) { if (MenuContains(menu, aPath, Key)) return false; MenuPut(menu, aPath, Key, [MS4C_Typ_Enum, aCond, szName, idItem, [CreateHash(),0,0,[]]]); return true; } //Fⁿgt der Enumauswahl mit dem Key Enumkey eine weitere M÷glichkeit hinzu global func AddEnumChoiceItem(&menu, array aPath, Enumkey, Itemkey, string szName, id idItem, Itemvalue, bool fDefault) { if (!MenuContains(menu, aPath, Enumkey)) return false; if (MenuEnumContains(menu, aPath, Enumkey, Itemkey)) return false; MenuEnumPut(menu,aPath,Enumkey,Itemkey,[szName, idItem, Itemvalue]); if (!MenuGet(menu, aPath, Enumkey)[MS4C_Data_Index][1] || fDefault) { MenuGet(menu,aPath,Enumkey)[MS4C_Data_Index][1] = true; MenuGet(menu,aPath,Enumkey)[MS4C_Data_Index][2] = Itemkey; } return true; } //Fⁿgt dem Menⁿ eine Rangeauswahl hinzu global func AddRangeChoice(&menu, array aPath, Key, array aCond, string szName, id idItem, int iMin, int iMax, int iStep, int iDefault) { if (MenuContains(menu, aPath, Key)) return false; MenuPut(menu,aPath,Key,[MS4C_Typ_Range,aCond,szName,idItem,[iMin,iMax,iStep,iDefault]]); return true; } global func AddSubmenu(&menu, array aPath, Key, array aCond, string szName, id idItem, array submenu) { if (MenuContains(menu, aPath, Key)) return false; if (!submenu) submenu = CreateMenuTemplate(idItem, szName); MenuPut(menu,aPath,Key,[MS4C_Typ_Submenu,aCond,szName,idItem,submenu]); return true; } //Erstellt ein Menⁿ ausgehend von dem Template und ein paar unwichtigen Parametern global func CreateMenuByTemplate(object pMenuObject, object pCommandObject, string szCallback, array aTemplate, ExtraData, int iVerbose, bool ForcedValues) { var pMenu=CreateObject(MS4C, 0, 0, GetOwner()); return pMenu->Init(pMenuObject, pCommandObject, szCallback, aTemplate, ExtraData, iVerbose, ForcedValues); } global func GetMenuValues(array aMenu, array aMainMenu, bool ForcedValues) { if (!aMainMenu) aMainMenu = aMenu; var hValues=CreateHash(); var iter = HashIter(aMenu[MS4C_Hash_Index]); // Iterator erzeugen var node; while(node = HashIterNext(iter)) { // Solange es weitere Elemente gibt if(!Evaluate_MenuCond(aMainMenu, node[1][MS4C_Cond_Index]) && !ForcedValues) continue; if(node[1][MS4C_Type_Index]==MS4C_Typ_Bool) HashPut(hValues,node[0],node[1][MS4C_Data_Index]); else if (node[1][MS4C_Type_Index]==MS4C_Typ_Enum) HashPut(hValues,node[0],HashGet(node[1][MS4C_Data_Index][0],node[1][MS4C_Data_Index][2])[2]); else if (node[1][MS4C_Type_Index]==MS4C_Typ_Range) HashPut(hValues,node[0],node[1][MS4C_Data_Index][3]); else if (node[1][MS4C_Type_Index]==MS4C_Typ_Submenu) HashPut(hValues,node[0],GetMenuValues(node[1][MS4C_Data_Index], aMainMenu)); else DebugLog("Unknown value typ"); } return hValues; } global func CreateMenuMessage(array aMenu, array aMainMenu, bool ForcedValues) { if (!aMainMenu) aMainMenu = aMenu; var szTotalMsg=aMenu[MS4C_Caption_Index]; var fFirst=true; for (var Key in aMenu[MS4C_Sequence_Index]) { var value=MenuGet(aMenu,0,Key); if(!Evaluate_MenuCond(aMainMenu, value[MS4C_Cond_Index]) && !ForcedValues) continue; var szMsg=0; if(value[MS4C_Type_Index]==MS4C_Typ_Bool) { if(value[MS4C_Data_Index]) szMsg=Format(value[MS4C_Name_Index]); else continue; } else if(value[MS4C_Type_Index]==MS4C_Typ_Enum) { szMsg=Format("%s: %s",value[MS4C_Name_Index],HashGet(value[MS4C_Data_Index][0],value[MS4C_Data_Index][2])[0]); } else if(value[MS4C_Type_Index]==MS4C_Typ_Range) { szMsg=Format("%s: %d",value[MS4C_Name_Index],value[MS4C_Data_Index][3]); } else if(value[MS4C_Type_Index]==MS4C_Typ_Submenu) { szMsg=Format("(%s)",CreateMenuMessage(value[MS4C_Data_Index], aMainMenu)); } else { szMsg=Format("%s: Unknown value typ",value[MS4C_Name_Index]); } if (fFirst) //Hier hinten, damit nicht angewΣhlte bools nicht alles kapput machen! { szTotalMsg=Format("%s: %s", szTotalMsg, szMsg); fFirst=false; } else szTotalMsg=Format("%s, %s", szTotalMsg, szMsg); } return szTotalMsg; } //Mit funktionslokalen Referenzen wΣre das nicht passiert ..! OMGOMG INEFFIZIENT global func &GetSubmenu(&menu, array aPath, int i) { if(!MenuContains(menu,0,aPath[i])) return 0; if (GetLength(aPath)==i+1) return MenuGet(menu,0,aPath[i])[MS4C_Data_Index]; else return GetSubmenu(MenuGet(menu,0,aPath[i])[MS4C_Data_Index],aPath,i+1); } global func MenuContains(&menu, array aPath, Key) { if (!menu) return false; if (!aPath || aPath == []) return HashContains(menu[MS4C_Hash_Index], Key); else return HashContains(GetSubmenu(menu, aPath)[MS4C_Hash_Index], 0, Key); } global func &MenuGet(&menu, array aPath, Key) { if (!aPath || aPath == []) return HashGet(menu[MS4C_Hash_Index], Key); else return HashGet(GetSubmenu(menu, aPath)[MS4C_Hash_Index], Key); } global func MenuPut(&menu, array aPath, Key, value) { if (!aPath || aPath == []) { HashPut(menu[MS4C_Hash_Index], Key, value); PushBack(Key,menu[MS4C_Sequence_Index]); } else { HashPut(GetSubmenu(menu, aPath)[MS4C_Hash_Index], Key, value); PushBack(Key,GetSubmenu(menu, aPath)[MS4C_Sequence_Index]); } return true; } global func MenuEnumContains(&menu, array aPath, Enumkey, Itemkey) { return HashContains(MenuGet(menu, aPath, Enumkey)[MS4C_Data_Index][0], Itemkey); } global func &MenuEnumGet(&menu, array aPath, Enumkey, Itemkey) { return HashGet(MenuGet(menu, aPath, Enumkey)[MS4C_Data_Index][0], Itemkey); } global func MenuEnumPut(&menu, array aPath, Enumkey, Itemkey, value) { HashPut(MenuGet(menu, aPath, Enumkey)[MS4C_Data_Index][0], Itemkey, value); PushBack(Itemkey, MenuGet(menu, aPath, Enumkey)[MS4C_Data_Index][3]); return true; } //Conds global func MenuCond_Not(Cond) { return([MS4C_Cond_Not, Cond]); } global func MenuCond_And() { var result = [MS4C_Cond_And]; for(var i = 0; Par(i); i++) { result[i+1] = Par(i); } return(result); } global func MenuCond_Or() { var result = [MS4C_Cond_Or]; for(var i = 0; Par(i); i++) result[i+1] = Par(i); return(result); } global func MenuCond_Activated(array Path, Key) { return([MS4C_Cond_Activated, Path, Key]); } global func MenuCond_Chosen(array Path, Enumkey, Itemkey) { return([MS4C_Cond_Chosen, Path, Enumkey, Itemkey]); } global func MenuCond_Less(array Path, Key, value) { return([MS4C_Cond_Less, Path, Key, value]); } global func MenuCond_Equal(array Path, Key, value) { return([MS4C_Cond_Equal, Path, Key, value]); } global func MenuCond_Greater(array Path, Key, value) { return([MS4C_Cond_Greater, Path, Key, value]); } global func Evaluate_MenuCond(array aMenu, array aCond) { if (!aCond || aCond == []) return true; if (aCond[0] == MS4C_Cond_Not) { return !Evaluate_MenuCond(aMenu, aCond[1]); } else if (aCond[0] == MS4C_Cond_And) { for (var i = 1; i < GetLength(aCond); i++) if (!Evaluate_MenuCond(aMenu, aCond[i])) return false; return true; } else if (aCond[0] == MS4C_Cond_Or) { for (var i = 1; i < GetLength(aCond); i++) if (Evaluate_MenuCond(aMenu, aCond[i])) return true; return false; } else if (aCond[0] == MS4C_Cond_Activated) { if (!MenuContains(aMenu, aCond[1], aCond[2])) return false; if (MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Type_Index] != MS4C_Typ_Bool) return false; return MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Data_Index]; } else if (aCond[0] == MS4C_Cond_Chosen) { if (!MenuContains(aMenu, aCond[1], aCond[2])) return false; if (MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Type_Index] != MS4C_Typ_Enum) return false; return MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Data_Index][2] == aCond[3]; } else if (aCond[0] == MS4C_Cond_Less) { if (!MenuContains(aMenu, aCond[1], aCond[2])) return false; if (MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Type_Index] != MS4C_Typ_Range) return false; return MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Data_Index][3] < aCond[3]; } else if (aCond[0] == MS4C_Cond_Equal) { if (!MenuContains(aMenu, aCond[1], aCond[2])) return false; if (MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Type_Index] != MS4C_Typ_Range) return false; return MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Data_Index][3] == aCond[3]; } else if (aCond[0] == MS4C_Cond_Greater) { if (!MenuContains(aMenu, aCond[1], aCond[2])) return false; if (MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Type_Index] != MS4C_Typ_Range) return false; return MenuGet(aMenu, aCond[1], aCond[2])[MS4C_Data_Index][3] > aCond[3]; } }
722,204
./clinfinity/Clinfinity.c4d/Helpers.c4d/Menu2.c4d/Menu.c4d/Script.c
/* Menuobjekt, verwaltet das Menⁿ, nachdem es erstellt wurde. */ #strict 2 local pMenuObject; //Objekt, in dem das Menu gezeigt wird local pCommandObject; //Objekt fⁿr den Callback (wenn Null, GameCall) local szCallback; //Wird in pCommandObject, wenn mit Auswahl fertig local aMenu; //Das Hauptmenu local ExtraData; //ExtraData, wird auch dem Callback ⁿbergeben, sinnvoll, um viele Optionsmenⁿs auf ein mal zu erstellen local iVerbose; local fForcedValues; local aCurrentPath; public func Init(object MenuObject, object CommandObject, string Callback, array Template, Data, int Verbose, bool ForcedValues) { pMenuObject = MenuObject; pCommandObject = CommandObject; szCallback = Callback; aMenu = Template; ExtraData = Data; iVerbose = Verbose; fForcedValues = ForcedValues; aCurrentPath = CreateArray(); ShowMenu(); } private func ShowMenu(int iSelection) { var currentMenu; if (aCurrentPath && aCurrentPath != []) currentMenu = GetSubmenu(aMenu, aCurrentPath); else currentMenu = aMenu; CreateMenu(currentMenu[MS4C_Symbol_Index], pMenuObject, this, 0, currentMenu[MS4C_Caption_Index], 0, 1); var i; for (var Key in currentMenu[MS4C_Sequence_Index]) { var value = MenuGet(currentMenu, 0, Key); var type = value[MS4C_Type_Index]; var cond = value[MS4C_Cond_Index]; var szName = value[MS4C_Name_Index]; var idItem = value[MS4C_Id_Index]; var data = value[MS4C_Data_Index]; if (type == MS4C_Typ_Bool) ShowBool(Key, cond, szName, idItem, data, i); else if (type == MS4C_Typ_Enum) ShowEnum(Key, cond, szName, idItem, data, i); else if (type == MS4C_Typ_Range) ShowRange(Key, cond, szName, idItem, data, i); else if (type == MS4C_Typ_Submenu) ShowSubmenu(Key, cond, szName, idItem, data, i); } AddMenuItem("$Finished$","Finished()",MS4C,pMenuObject,0,0,"$Finished$",2,3); SelectMenuItem(iSelection,pMenuObject); } private func ShowBool(Key, array aCond, string szName, id idItem, data, &i) { var selectable = Evaluate_MenuCond(aMenu, aCond); var def = CreateDummy(idItem, data, true, selectable); var szCaption; if (data) szCaption = Format("$Deactivate$", szName); else szCaption = Format("$Activate$", szName); if (selectable) { AddMenuItem(szCaption, Format("Toggle(%v,%d)", Key, i++), 0, pMenuObject, 0, 0, szCaption, 4, def); } else { szCaption = GreyString(szCaption); AddMenuItem(szCaption, Format("ShowMenu(%d)", i++), 0, pMenuObject, 0, 0, szCaption, 4, def); } RemoveObject(def); } private func ShowEnum(Key, array aCond, string szName, id idItem, data, &i) { var selectable = Evaluate_MenuCond(aMenu, aCond); for (var itemkey in data[3]) { var itemvalue = HashGet(data[0], itemkey); var def = CreateDummy(itemvalue[1], itemkey == data[2], false, selectable); var szCaption = Format("$Choose$", itemvalue[0], szName); if (selectable) { AddMenuItem(szCaption, Format("Choose(%v,%v,%d)", Key, itemkey, i++), 0, pMenuObject, 0, 0, szCaption, 4, def); } else { szCaption = GreyString(szCaption); AddMenuItem(szCaption, Format("ShowMenu(%d)", i++), 0, pMenuObject, 0, 0, szCaption, 4, def); } RemoveObject(def); } } private func ShowRange(Key, array aCond, string szName, id idItem, data, &i) { var selectable = Evaluate_MenuCond(aMenu, aCond); var szCaption = szName; var szIncCaption = Format("$Increase$", szName, data[2]); var szDeCaption = Format("$Decrease$", szName, data[2]); if (selectable) { AddMenuItem(szCaption, Format("ShowMenu(%d)",i++), idItem, pMenuObject, data[3], 0, szCaption); AddMenuItem(szIncCaption, Format("Increase(%v,%d)", Key, i++), MS4C, pMenuObject, 0, 0, szIncCaption, 2, 1); AddMenuItem(szDeCaption ,Format("Decrease(%v,%d)", Key, i++), MS4C, pMenuObject, 0, 0, szDeCaption, 2, 2); } else { szCaption = GreyString(szCaption); szIncCaption = GreyString(szIncCaption); szDeCaption = GreyString(szDeCaption); var def = CreateDummy(idItem, false, false, selectable); AddMenuItem(szCaption, Format("ShowMenu(%d)",i++), 0, pMenuObject, data[3], 0, szCaption, 4, def); RemoveObject(def); def = CreatePlusMinus(true, selectable); AddMenuItem(szIncCaption, Format("ShowMenu(%d)", i++), MS4C, pMenuObject, 0, 0, szIncCaption, 4, def); RemoveObject(def); def = CreatePlusMinus(false, selectable); AddMenuItem(szDeCaption ,Format("ShowMenu(%d)", i++), MS4C, pMenuObject, 0, 0, szDeCaption, 4, def); RemoveObject(def); } } private func ShowSubmenu(Key, array aCond, string szName, id idItem, data, &i) { var selectable = Evaluate_MenuCond(aMenu, aCond); var szCaption = Format("$OpenMenu$", szName); if (selectable) { AddMenuItem(szCaption, Format("OpenMenu(%v,%d)", Key, i++), idItem, pMenuObject, 0, 0, szCaption); } else { var def = CreateDummy(idItem, false, false, selectable); szCaption = GreyString(szCaption); AddMenuItem(szCaption, Format("ShowMenu(%d)", i++), idItem, pMenuObject, 0, 0, szCaption, 4, def); RemoveObject(def); } } protected func Toggle(Key, int iSelection) { ToggleBool(MenuGet(aMenu, aCurrentPath, Key)[MS4C_Data_Index]); ShowMenu(iSelection); } private func ToggleBool(&f) { return f = !f; } protected func Choose(Key,itemkey, int iSelection) { MenuGet(aMenu, aCurrentPath, Key)[MS4C_Data_Index][2]=itemkey; ShowMenu(iSelection); } protected func Increase(Key, int iSelection) { IncreaseRange(MenuGet(aMenu, aCurrentPath, Key)[MS4C_Data_Index]); ShowMenu(iSelection); } private func IncreaseRange(&range) { return range[3]=BoundBy(range[3]+range[2],range[0],range[1]); } protected func Decrease(Key, int iSelection) { DecreaseRange(MenuGet(aMenu, aCurrentPath, Key)[MS4C_Data_Index]); ShowMenu(iSelection); } private func DecreaseRange(&range) { return range[3]=BoundBy(range[3]-range[2],range[0],range[1]); } protected func OpenMenu(Key, int iSelection) { PushBack(Key, aCurrentPath); ShowMenu(); } protected func Finished(bool fAbort) { if (aCurrentPath && aCurrentPath != []) { DeleteLast(aCurrentPath); ShowMenu(); } else { var szMsg=CreateMenuMessage(aMenu,0,fForcedValues); if (iVerbose&MS4C_Verbose_ObjectMessage) Message(szMsg, pMenuObject); if (iVerbose&MS4C_Verbose_GlobalMessage) Message(szMsg); if (iVerbose&MS4C_Verbose_Log) Log(szMsg); if (pCommandObject) pCommandObject->Call(szCallback,GetMenuValues(aMenu,0,fForcedValues),ExtraData,fAbort); else GameCall(szCallback,GetMenuValues(aMenu,0,fForcedValues),ExtraData,fAbort); RemoveObject(); } } public func MenuQueryCancel() { CloseMenu(pMenuObject); Finished(true); return 1; } private func CreateDummy(id idItem, bool fChecked, bool fOverlayForced, bool fSelectable) { var pDummy=CreateObject(MS4C,0,0,-1); if(idItem && FindDefinition(idItem)) { SetObjectPicture(idItem, pDummy); if (fChecked) { SetGraphics("Chosen", pDummy, MS4C, 1, GFXOV_MODE_Picture); SetObjDrawTransform(650,0,5000,0,650,5000, pDummy, 1); } else if(fOverlayForced) { SetGraphics("NotChosen", pDummy, MS4C, 1, GFXOV_MODE_Picture); SetObjDrawTransform(650,0,5000,0,650,5000, pDummy, 1); } } else { if (fChecked) SetPicture(64*3, 0, 64, 64, pDummy); else SetPicture(64*4, 0, 64, 64, pDummy); } if (!fSelectable) SetClrModulation(RGB(128,128,128),pDummy); return pDummy; } private func CreatePlusMinus(bool fPlus, bool fSelectable) { var pDummy=CreateObject(MS4C,0,0,-1); if(fPlus) SetPicture(64*1, 0, 64, 64, pDummy); else SetPicture(64*2, 0, 64, 64, pDummy); if (!fSelectable) SetClrModulation(RGB(128,128,128),pDummy); return pDummy; }
722,205
./clinfinity/Clinfinity.c4d/Helpers.c4d/MenuDeco.c4d/Script.c
/*-- Deco --*/ #strict protected func FrameDecorationBackClr() { return(RGBa(50,50,50,128)); }
722,206
./clinfinity/Clinfinity.c4d/Structures.c4d/Tank.c4d/Script.c
/*-- Steam Tank --*/ #strict 2 #include STBO //StructureBaseObject #include L_DC //Damagecontrol #include L_SS //StorageSystem static steamTrendWarnEffects; // number of animation phases static const STMT_Phases = 10; // amount needed to respawn one clonk static const STMT_RespawnAmount = 100; // number of frames the trend warning analyzes static const STMT_SteamTrendWarningFrames = 800; public func MaxFill() { return 1500; } public func MaxDamage() { return 60; } public func DamageGraphics() { return 2; } // all previous changes in fill level local changes; protected func Initialize() { changes = []; SetAction("Tank"); // steam trend warning if(!steamTrendWarnEffects) steamTrendWarnEffects = []; var team = GetPlayerTeam(GetOwner()); if(!steamTrendWarnEffects[team]) { steamTrendWarnEffects[team] = AddEffect("SteamTrendWarning", 0, 1, 100); EffectVar(0, 0, steamTrendWarnEffects[team]) = team; } SetAlarmLamp(false); SetObjDrawTransform(1000, 0, 3500, 0, 1000, -5000, this, 1); // create dummy effect if this is the first Akku // this ensures that when the last Akku gets destroyed, the display is reset to 0 if(!GetEffect("MatSysSTEM")) AddEffect("MatSysSTEM", 0, 1, 0); AddEffect("MatSysSTEM", 0, 1, 0, this); _inherited(); } protected func DestroyBlast() { // remove waiting Clonks for(var obj in FindObjects(Find_Container(this))) obj->RemoveObject(); return _inherited(...); } // manages delay for steam generation local generate; // bubbling? local bubbling; private func HeavilyDamaged() { return currentDamageGraphic == DamageGraphics(); } protected func Steam() { var shouldBubble = false; if(GetFill() > MaxFill() * 2 / 3) { CreateParticle("Smoke", 30, -18, 0, 0, 50, RGBa(255, 255, 255, 0)); shouldBubble = true; } if(HeavilyDamaged()) { CreateParticle("Smoke", RandomX(-15, 15), RandomX(-20, 5), 0, 0, 50, RGBa(255, 255, 255, 0)); shouldBubble = true; } if(shouldBubble && !bubbling) { Sound("steam_exhaust", 0, 0, 0, 0, 1); bubbling = true; } else if(!shouldBubble && bubbling) { Sound("steam_exhaust", 0, 0, 0, 0, -1); bubbling = false; } // generation if(!generate--) { var change = DoFill(180 + RandomX(-10, 10)); // Produce less steam when heavily damaged. if(HeavilyDamaged()) change -= 25; MatSysMessage(change, STEM); generate = RandomX(350, 450); } // respawn var clonk, i = 0; while(clonk = Contents(i++)) StartRespawn(clonk); } private func StartRespawn(object clonk) { if(GetEffect("Respawn", clonk)) return; var effectNum = AddEffect("Respawn", clonk, 1, KOTH_FPS, this); EffectVar(0, clonk, effectNum) = GetRespawnTime(GetPlayerTeam(clonk->GetOwner())); } protected func FxRespawnTimer(object target, int effectNum, int effectTime) { var timeToWait = EffectVar(0, target, effectNum); Message("@Respawn in %d...", target, Max(0, timeToWait - effectTime) / KOTH_FPS); if(effectTime >= timeToWait && MatSysGetTeamFill(GetOwner(), STEM) >= STMT_RespawnAmount) { MatSysDoTeamFill(-STMT_RespawnAmount, GetOwner(), STEM); target->Exit(); var plr = target->GetOwner(); if(!GetCursor(plr)) SetCursor(plr, target); Message("", target); return -1; } } private func OnFillChange(key, int change) { UpdateDisplay(); PushBack([FrameCounter(), change], changes); } private func UpdateDisplay() { SetPhase(ChangeRange(GetFill(), 0, MaxFill() - 1, STMT_Phases - 1, 0)); return 1; } public func GetChanges(int frames) { var min = FrameCounter() - frames, result = []; for(var i = GetLength(changes) - 1; i && changes[i][0] >= min; i--) PushBack(changes[i][1], result); return result; } public func GlobalSteamChanges(int frames) { var result = 0, num = 0; for(var tank in FindObjects(Find_ID(GetID()), Find_Allied(GetOwner()))) { for(var change in tank->GetChanges(frames)) { result += change; num++; } } return result; } public func ShowChanges() { Message("@Trend: %d", 0, GlobalSteamChanges(750)); ScheduleCall(this, "ShowChanges", 25); } // Steuerung protected func ControlUp() { Message("$TxtStored$", this, GetFill()); } protected func ControlDig(object clonk) { if(Hostile(GetOwner(), clonk->GetOwner())) { clonk->Sound("CommandFailure1"); return; } var physical = clonk->GetPhysical("Energy"); var health = 100 - clonk->GetEnergy() * 100000 / physical; clonk->DoEnergy(-MatSysDoTeamFill(-health, clonk->GetOwner(), STEM) * physical / 100000); } /* Material System fill level */ public func FxMatSysSTEMUpdate(object target, int effectNum, int plr) { if(!this || GetOwner() != plr) return 0; return GetFill(); } public func FxMatSysSTEMChange(object target, int effectNum, int plr, int change) { if(!this || GetOwner() != plr) return 0; return DoFill(change); } /* Steam trend warning */ public func SetAlarmLamp(bool on) { var action; if(on) action = "On"; else action = "Off"; SetGraphics(0, this, ALRM, 1, GFXOV_MODE_Action, action); return true; } global func FxSteamTrendWarningTimer(object target, int effectNum, int effectTime) { var team = EffectVar(0, target, effectNum), players = GetPlayersByTeam(team); var tank = FindObject2(Find_ID(STMT), Find_Allied(players[0])); var warning = EffectVar(1, target, effectNum), next; // Is the steam likely to run out next STMT_SteamTrendWarningFrames? if(tank && MatSysGetTeamFill(players[0], STEM) + tank->GlobalSteamChanges(STMT_SteamTrendWarningFrames) < 0) next = true; else next = false; if(!warning && next || warning && !next) { for(var plr in players) Sound("Warning_blowup", true, 0, 75, plr + 1, next*2 - 1); for(var t in FindObjects(Find_ID(STMT), Find_Allied(players[0]))) t->SetAlarmLamp(next); } EffectVar(1, target, effectNum) = next; }
722,207
./clinfinity/Clinfinity.c4d/Structures.c4d/Tank.c4d/Alarm.c4d/Script.c
/*-- Alarm --*/ #strict 2
722,208
./clinfinity/Clinfinity.c4d/Structures.c4d/Factory.c4d/Script.c
/*-- Factory --*/ #strict 2 #include STBO //StructureBaseObject #include L_DC //Damagecontrol #include NLBO //Nightlight static const FTRY_ProductionActions = 3; public func DamageGraphics() { return 3; } public func MaxDamage() { return 70; } // Array of items that will be produced next, in format [id, amount]. local queue; // Id of the object that is currently in production. local requestedId; // Remaining time on the current production in 20f. // Will always be set to 5 when starting production. local remainingTime; // Batch production: number of items of requestedId which will be produced automatically. local remainingAmount; // Controls the amount of white steam at the end of a production. local steamWhite; protected func Initialize() { queue = []; SetStillOverlayAction("Door18", 1); return inherited(...); } /* Interaktion */ public func ControlDigDouble(object caller) { if(Hostile(GetOwner(), caller->GetOwner())) { Sound("CommandFailure1"); return; } ProductionMenu(caller); } public func ProductionMenu(object caller) { CreateMenu(CXCN, caller, this, 0, "$TxtNoPlrKnowledge$"); var plr = caller->GetOwner(), i = 0, knowledge; while(knowledge = GetPlrKnowledge(plr, 0, i++, C4D_Object | C4D_Vehicle)) { AddMaterialMenuItem("$TxtProduction$: %s", "RequestProduction", knowledge, caller, 0, caller); } } public func ProductionAmountMenu(object caller, id item, int amount) { if(!amount) amount = 1; var index = 0; if(GetMenu(caller)) { index = GetMenuSelection(caller); CloseMenu(caller); } Sound("Click", 0, 0, 100, GetOwner(caller)+1); CreateMenu(CXCN, caller, this, 1, 0, 0, 0, 1); AddMenuItem("$TxtIncrementProduction$", Format("ProductionAmountMenu(Object(%d), %i, %d, 0)", ObjectNumber(caller), item, amount+1), MS4C, caller, 0, 0, "$TxtIncrementProductionDesc$", 2, 1); AddMenuItem("$TxtDecrementProduction$", Format("ProductionAmountMenu(Object(%d), %i, %d, 1)", ObjectNumber(caller), item, Max(amount-1, 1)), MS4C, caller, 0, 0, "$TxtDecrementProductionDesc$", 2, 2); AddMenuItem("$TxtLaunchProduction$", Format("RequestAmountProduction(%i, Object(%d), %d)", item, ObjectNumber(caller), amount), MS4C, caller, 0, 0, "OK", 2, 3); SelectMenuItem(index, caller); PlayerMessage(GetOwner(caller), "%dx {{%i}}", caller, amount, item); } protected func RequestProduction(id item, object caller, bool right) { if(!right) { StartProduction(item, GetOwner(caller), 1); } else { ProductionAmountMenu(caller, item); } } protected func RequestAmountProduction(id item, object caller, int amount) { if(GetMenu(caller)) CloseMenu(caller); StartProduction(item, GetOwner(caller), amount); } /* Produktion */ public func StartProduction(id item, int player, int amount) { if(!amount) amount = 1; if(IsProducing()) { // Add the new item to the queue. PushBack([item, amount], queue); return; } remainingAmount = amount; requestedId = item; SetAction(Format("Produce%d", Random(FTRY_ProductionActions) + 1)); ContinueProduction(); } protected func ContinueProduction() { remainingTime = 5; steamWhite = 0; var steamUsage = requestedId->~FactorySteamUsage() || 50; if(MatSysGetTeamFill(GetOwner(), STEM) >= steamUsage && MatSysSubtractComponents(requestedId, GetOwner())) { MatSysDoTeamFill(-steamUsage, GetOwner(), STEM); } else { CompletedProduction(); } } protected func Produce() { remainingTime--; if(!remainingTime) return CompleteProduction(); } protected func CompleteProduction() { // Create the produced item. var matSys = GetMatSys(GetOwner(), true); if(matSys != 0 && InArray(requestedId, GetMatSysIDs())) { matSys->DoFill(1, requestedId); } else { CreateContents(requestedId); OpenDoor(); } // Continue production if requested. remainingAmount--; if(remainingAmount) { ContinueProduction(); } else { var next = PopElement(queue); if(next) { requestedId = next[0]; remainingAmount = next[1]; ContinueProduction(); } else { CompletedProduction(); } } } public func AbortProduction() { SetAction("Attach"); remainingTime = 0; } private func CompletedProduction() { AbortProduction(); Sound("finish*"); steamWhite = 23; } private func OpenDoor() { SetOverlayAction("Door", 1, true); Schedule("Exit(Contents(), 49, 74)", 20); ScheduleCall(this, "CloseDoor", 60); } protected func CloseDoor() { SetOverlayAction("Door", 1); } /* Callbacks und Effekte */ public func IsProducing() { return remainingTime > 0; } private func Smoking() { if(!IsProducing() && !steamWhite) return; var steamColor = 0; if(steamWhite) { steamWhite--; CreateParticle("Smoke", 25, -10, 0, 0, 70, RGB(255, 255, 255)); CreateParticle("Smoke", 20, -10, 0, 0, 70, RGB(255, 255, 255)); } else { CreateParticle("Smoke", -18, -18, 0, 0, 150, RGBa(0, 0, 0, 0)); CreateParticle("Smoke", -40, -18, 0, 0, 150, RGBa(0, 0, 0, 0)); } }
722,209
./clinfinity/Clinfinity.c4d/Structures.c4d/Quarry.c4d/Script.c
/*-- Quarry --*/ #strict 2 #include STBO ////StructureBaseObject #include NLBO //Nightlight static const QRRY_DroneCount = 3; static const QRRY_MaxSearchDistance = 350; static const QRRY_MaxSearchIterations = 100; local lastRockX, lastRockY; protected func Initialize() { for(var i = 0; i < QRRY_DroneCount; ++i) { var x = GetX() + RandomX(-GetDefWidth(GetID()) / 4, GetDefWidth(GetID()) / 4); var y = GetY() + RandomX(-GetDefHeight(GetID()) / 4, GetDefHeight(GetID()) / 4) + GetDefHeight(DRNE) / 2; DRNE->CreateDrone(x, y, GetOwner(), this); } return inherited(...); } protected func Collection2(object collected) { if(GetAction() != "Stomp") { SetAction("Stomp"); } } protected func Quarry() { Sound("Quarry"); } protected func Stomping() { var rock = Contents(); if(rock != 0) { var matSys = GetMatSys(GetOwner(), true); var id = rock->GetID(); if(matSys != 0 && InArray(id, GetMatSysIDs())) { MatSysDoTeamFill(1, GetOwner(), id); } rock->RemoveObject(); } // Stop when all contents have been stomped. if(Contents() == 0) { SetAction("Attach"); } } public func FindDrillingPosition(&x, &y) { if(GetAction() == "Stomp") { return false; } if(GetMaterial(lastRockX, lastRockY) == Material("Metalearth")) { x = lastRockX + GetX(); y = lastRockY + GetY(); return true; } var searchX = RandomX(-QRRY_MaxSearchDistance, QRRY_MaxSearchDistance); // Search inside a circle: Limit randomly chosen points to the chord for the given x. var h = QRRY_MaxSearchDistance - Abs(searchX); var maxSearchY = Sqrt(2 * QRRY_MaxSearchDistance * h - h ** 2); var searchY = RandomX(-maxSearchY, maxSearchY); for(var i = 0; i < QRRY_MaxSearchIterations; ++i) { if(GetMaterial(searchX, searchY) == Material("Metalearth")) { x = searchX + GetX(); y = searchY + GetY(); lastRockX = searchX; lastRockY = searchY; return true; } } return false; } /* Controls */ protected func ControlUp() { [$TxtShowSearchRadius$] // Show search radius for(var i; i < 360; i++) CreateParticle("PSpark", Cos(i, QRRY_MaxSearchDistance), Sin(i, QRRY_MaxSearchDistance), 0, 0, 70, RGBa(255, 255, 255, 128)); }
722,210
./clinfinity/Clinfinity.c4d/Structures.c4d/Furnace.c4d/Script.c
/*-- Schmelze --*/ #strict 2 #include STBO //StructureBaseObject #include L_DC //Damagecontrol #include L_SS //StorageSystem static const FNCE_SteamUsage = 25; public func MaxDamage() { return 35; } public func DamageGraphics() { return 1; } local productionNum; private func Authorized(object clonk) { var plr = clonk->GetOwner(); // wrong team? if(Hostile(plr, GetOwner())) { Sound("CommandFailure1"); return; } SetOwner(plr); return true; } protected func ControlUp(object clonk) { if(Authorized(clonk)) Produce(); } protected func ControlUpDouble(object clonk) { if(!Authorized(clonk)) return; var menu = CreateMenuTemplate(GetID()); AddRangeChoice(menu, 0, "n", 0, "$Production$", METL, 2, 100, 1, 5); CreateMenuByTemplate(clonk, this, "StartMassProduction", menu); } public func StartMassProduction(array selection, extraData, abort) { if(!abort) { productionNum = HashGet(selection, "n") - 1; Produce(); } } private func Produce() { var plr = GetOwner(); if(MatSysGetTeamFill(plr, ROCK) >= 1 && MatSysGetTeamFill(plr, STEM) >= FNCE_SteamUsage) { if(GetAction() != "Start") { SetAction("Start"); MatSysDoTeamFill(-1, plr, ROCK); MatSysDoTeamFill(-FNCE_SteamUsage, plr, STEM); return true; } } else { Sound("Error"); Message("$TxtNotEnoughInput$", this, FNCE_SteamUsage); productionNum = 0; } } protected func Progress() { if(GetActTime() >= 60) { MatSysDoTeamFill(1, GetOwner(), METL); SetAction("Attach"); if(productionNum > 0) { productionNum--; Produce(); } } }
722,211
./clinfinity/Clinfinity.c4d/Structures.c4d/Steamgen.c4d/Script.c
/*-- Steamgen --*/ #strict 2 #include L_CP //ControlPoint #include B_70 //Basement #include NLBO //Nightlight static const RSMG_ProductionTime = 200; static const RSMG_ProductionRate = 50; public func NoDemolition() { return true; } public func CaptureTime() { return 100; } private func Captured() { StartProduction(); return inherited(...); } private func StartProduction() { ClearScheduleCall(this, "ProduceSteam"); ScheduleCall(this, "ProduceSteam", RSMG_ProductionTime); } protected func ProduceSteam() { MatSysDoTeamFill(RSMG_ProductionRate + RandomX(-10, 10), GetOwner(), STEM); StartProduction(); }
722,212
./clinfinity/Clinfinity.c4d/Structures.c4d/Steamgen.c4d/Basement70.c4d/Script.c
/*-- Fundament --*/ #strict /* Alle Fundamente leiten ihre GrundfunktionalitΣt von BAS7 ab */ #include BAS7 private func BasementID() { return(B_70); } private func BasementWidth() { return(70); }
722,213
./clinfinity/Clinfinity.c4d/Structures.c4d/StructureBaseObject.c4d/Script.c
/* Script: Structure base object Automatically handles attaching to and detaching from platforms. All structures created for Clonk Infinity should adhere to the following rules: - Provide an action with the Procedure "ATTACH". It can either be named "Attach", it will then get set automatically by AttachTo(), or it can have any other name, in which case you must set the action yourself in your structure's Initialize() function. - Inherit from this base object. - Have no bottom vertices the structure stands on. Otherwise, when moving, these vertices get stuck in the platform's solid masks. Other vertices, e.g. at the top, are allowed. Set the proper CNAT values for those. */ #strict 2 protected func Construction() { if(GetCon() < 100) SetCon(100); } protected func Initialize() { var result = _inherited(); var platform = FindObject2(Find_ID(PLTF), Find_AtPoint(0, GetObjHeight() / 2 + 1)); if(platform != 0) { AttachTo(platform); } return result; } protected func Destruction() { var result = _inherited(); if(GetProcedure() == "ATTACH" && GetActionTarget()) { GetActionTarget()->~AttachEvent(this, GetActionTarget(), true, this); } return result; } protected func RejectConstruction(int x, int y, object clonk) { // only allow building on platform if(!FindObject2(Find_ID(PLTF), Find_Allied(clonk->GetOwner()), clonk->Find_AtPoint(x, y + 1))) { Sound("Error"); Message("$OnlyOnPlatform$", clonk); return true; } } /* Function: AttachEvent Event handler, called after an object was attached to a new parent object or detached from it. Buildings by default hand the event to their action target, if they are attached to something. This makes sure platforms (and, in turn, the master platform) get notified of attached/detached objects and can react appropriately. Parameters: attached - The attached object. attachedTo - The new parent object. isDetaching - *true* if the object was detached. *false* if it was attached. source - Source of the event. */ public func AttachEvent(object attached, object attachedTo, bool isDetaching, object source) { if(GetProcedure() == "ATTACH") { GetActionTarget()->~AttachEvent(attached, attachedTo, isDetaching, this); } }
722,214
./clinfinity/Clinfinity.c4d/Structures.c4d/NightlightBaseObject.c4d/Script.c
/* Script: Night light base object By inheriting from this object, a structure's graphics is automatically switched, according to the current state of the day/night cycle. With this, a structure can for example switch on spotlights at night. A structure using alternate graphics for day and night must follow the following rules - Provide GraphicsNight.png - Inherit from NLBO - Call inherited() in the structure's Initialize() and Destruction() functions The following events are then handled automatically - Switching to the according graphics on daybreak and nightfall. - Setting the according graphics when building the structure at nightfall or at night. */ #strict 2 protected func Initialize() { var clock = FindObject2(Find_ID(TIME)); if(clock != 0) { clock->AddAlarmListener(this, GetNightfallTime()); clock->AddAlarmListener(this, GetDaybreakTime()); } if(IsNightfall() || IsNight()) { SetDayNightGraphics("Night"); } return _inherited(); } protected func Destruction() { var clock = FindObject2(Find_ID(TIME)); if(clock != 0) { clock->RemoveAlarmListener(this, GetNightfallTime()); clock->RemoveAlarmListener(this, GetDaybreakTime()); } return _inherited(); } protected func OnAlarm(object clock, int time) { if(IsNightfall()) { ScheduleCall(this, "SetDayNightGraphics", RandomX(TIME_TwilightLength * 1 / 4 / TIME_SecondsPerFrame, TIME_TwilightLength / TIME_SecondsPerFrame), 0, "Night"); } else { ScheduleCall(this, "SetDayNightGraphics", RandomX(1, TIME_TwilightLength / 4 / TIME_SecondsPerFrame), 0, ""); } } protected func SetDayNightGraphics(string graphics) { SetGraphics(graphics); }
722,215
./clinfinity/Clinfinity.c4d/Structures.c4d/FlintFactory.c4d/Script.c
/*-- Flint Factory --*/ #strict 2 #include L_CP //ControlPoint #include B100 //Basement #include NLBO //Nightlight static const RFLN_MaxFlints = 4; public func CaptureZone() { // complete building return Find_InRect(-50, -40, 100, 80); } public func CaptureTime() { return 200; } public func NoDemolition() { return true; } protected func Initialize() { UpdateDisplay(); // position the display correctly SetObjDrawTransform(1000, 0, -25000, 0, 1000, 34000, this, 1); return inherited(...); } private func NumberOfFlints() { return ObjectCount2(Find_Container(this)); } public func UpdateDisplay() { var n = NumberOfFlints(); SetGraphics(0, this, FFFD, 1, GFXOV_MODE_Action, Format("Fill%d", n)); } private func Captured() { for(var obj in FindObjects(Find_Container(this))) obj->RemoveObject(); UpdateDisplay(); StartProduction(); return inherited(...); } protected func DoSmoke(){ CreateParticle("Smoke", -13, -18, 0, 0, 70, RGBa(255, 255, 255, 0)); } private func StartProduction() { if(GetAction() == "Idle" && NumberOfFlints() < RFLN_MaxFlints) SetAction("Producing"); } protected func ProduceFlint() { var flintID, n = Random(8); if(!n) flintID = EFLN; else if(n < 4) flintID = SFLN; else flintID = FLNT; CreateContents(flintID); UpdateDisplay(); StartProduction(); } protected func ControlDig(object clonk) { if(!Hostile(clonk->GetOwner(), GetOwner())) { var flint = FindObject2(Find_Container(this), Sort_Random()); if(flint) { flint->Exit(0, AbsX(clonk->GetX()), AbsY(clonk->GetY())); UpdateDisplay(); StartProduction(); } } return true; }
722,216
./clinfinity/Clinfinity.c4d/Structures.c4d/FlintFactory.c4d/Fill.c4d/Script.c
/*-- Neues Objekt --*/ #strict func Initialize() { return(1); }
722,217
./clinfinity/Clinfinity.c4d/Structures.c4d/FlintFactory.c4d/Basement100.c4d/Script.c
/*-- Fundament --*/ #strict /* Alle Fundamente leiten ihre GrundfunktionalitΣt von BAS7 ab */ #include BAS7 private func BasementID() { return(B100); } private func BasementWidth() { return(100); }
722,218
./clinfinity/Clinfinity.c4d/Structures.c4d/Artillery.c4d/Script.c
/*--- Geschⁿtzturm ---*/ #strict 2 local cannon; #include STBO //StructureBaseObject #include L_DC //Damagecontrol public func MaxDamage() { return 50; } //Hilft der Kanone, loescht die Zielhilfe func Grabbed(object by, bool grab) { if(HasCannon()) HasCannon()->Trajectory(by, !grab); _inherited(by, grab); } /* Kanonensteuerung */ protected func Progress() { SetAction("Attach"); /* if(GetActTime() >= 60) { MatSysDoTeamFill(1, GetOwner(), METL); SetAction("Attach"); } */ } protected func ControlLeft(object obj) { [$TxtRotatecannontothelef$|Image=CT01:0] if(!cannon) return 0; var plr = obj->GetOwner(); // wrong team? if(Hostile(plr, GetOwner())) { Sound("CommandFailure1"); return; } SetOwner(plr); Sound("Click"); return cannon->ComLeft(obj) ; } protected func ControlLeftReleased(object obj) { if(!cannon) return 0; Sound("CannonStop"); return cannon->ComStop(obj); } protected func ControlRight(object obj) { [$TxtRotatecannontotherig$|Image=CT01:2] if(!cannon) return 0; Sound("Click"); return(cannon->ComRight(obj) ); } protected func ControlRightReleased(object obj) { if(!cannon) return 0; Sound("CannonStop"); return(cannon->ComStop(obj)); } protected func ControlDown(object obj) { [$TxtStopcannonrotation$|Method=Classic] if(!cannon) return 0; if(!GetPlrCoreJumpAndRunControl(obj->GetController())) { Sound("Click"); Sound("CannonStop"); return(cannon->ComStop(obj) ); } } protected func ControlThrow(object obj) { [$TxtFire$|Image=CT01:1] if (!cannon) return 0; return cannon->ComFire(obj); } protected func ControlUp(object obj) { [$TxtMorePower$|Image=CT01:4] if(!cannon) return 0; return cannon->ComPowerUp(obj); } protected func ControlDig(object obj) { [$TxtLessPower$|Image=CT01:5] if(!cannon) return 0; return cannon->ComPowerDown(obj); } /* Cannon connection functionality */ public func ConnectCannon(object newCannon) { cannon = newCannon; // Wir rufen die Connect-Funktion der Kanone auf. Somit kann die Kanone // eigene Dinge tun um sich anzubauen. cannon->Connect(this() ); SetR(45, cannon); if(GetX() > LandscapeWidth() / 2) SetR(-45, cannon); // neue Kategorie fⁿr die Kanone um sie in den Hintergrund zu kriegen SetCategory(2, cannon); SetObjectOrder(cannon); Sound("Connect"); } // Diese Funktion k÷nnen die Kanonen aufrufen, um sich an den Geschⁿtzturm anzuschrauben, // wenn es darum geht, ihre Definition zu Σndern. public func ConnectCannonDef(object cannon, id defChg, string action) { if(!action) action = "Attaching"; ChangeDef(defChg, cannon); ObjectSetAction(cannon, action, this() ); } // L÷st die Kanone vom Geschⁿtzturm public func ReleaseCannon() { if(!cannon) return 0; Sound("Connect"); cannon->ComStopDouble(); // Kategorie fⁿr die Kanone wiederherstellen SetCategory(GetDefCategory(GetID(cannon)), cannon); cannon = 0; // Neue Kanonen suchen var i, obj; while(obj = Contents(i++) ) { if(obj->~IsCannon() ) { ConnectCannon(obj); break; } } return 1; } /* Wird von den Kanonen als Turm erkannt */ public func IsCannonTower() { return 1; } public func HasCannon() { return cannon; } /* Zerst÷rung */ protected func Destruction() { if(cannon) cannon->RemoveObject(); return _inherited(...); }
722,219
./clinfinity/Clinfinity.c4d/Structures.c4d/Artillery.c4d/Cannon1.c4d/Script.c
/*--- Kampfgeschⁿtz ---*/ #strict protected func ConnectID() { return(CTW2); } protected func GetAlternativeType() { return(ConnectID()); } func ControlDigDouble(object pObj) { [$TxtConnectcannon$ | Image = CTW3] var pTower = FindObject2(Find_ID(CTW0), Find_Not(Find_Hostile(GetOwner(pObj))), Find_Distance(30)); if(pTower) pTower->ConnectCannon(this); else { Sound("Error"); PlayerMessage(GetOwner(pObj), "$TxtNoTower$", this()); } return(1); } func Grabbed(object pByObject, bool fGrab) { SetOwner(GetOwner(pByObject)); _inherited(pByObject, fGrab); } /* Wird vom Turm als Kanone erkannt */ public func IsCannon() { return(1); } /* An Turm anschrauben */ public func Connect(object pTower) { pTower->ConnectCannonDef(this(), ConnectID() ); } /* AufschlaggerΣusch */ protected func Hit() { Sound("RockHit*"); } /* Forschung */ public func GetResearchBase() { return(CTW0); }
722,220
./clinfinity/Clinfinity.c4d/Structures.c4d/Artillery.c4d/Cannon1.c4d/Cannon1Attached.c4d/Script.c
/*--- Kampfgeschⁿtz (angeschraubt) ---*/ #strict 2 /* ▄berladbar fⁿr andere Kanonen */ protected func RotationSpeed() { return 5; } protected func CannonMobileID() { return CTW3; } protected func CannonAmmo(object obj) { return obj && obj->GetOCF() & OCF_Collectible && obj->~CannonAmmo(); } protected func CannonPowerArray(object obj) { return [6, 8, 12, 14, 18]; } protected func CannonPower(object obj) { return CannonPowerArray(obj)[power]; } protected func CannonSteamUsage(object obj) { return [2, 3, 5, 7, 10][power]; } // SteamUsage*ObjectMass protected func CannonSound(object obj) { return "Cannon"; } protected func CannonSmoke(object obj) { return 1; } // Legacy stuff protected func CannonShootMenuID() {} local power; protected func Initialize() { power = GetLength(CannonPowerArray()); } /* Turm weg? */ protected func AttachTargetLost() { RemoveObject(); } /* Kommandos aus dem Turm */ public func ComLeft(object clonk) { SetAction("Rotating", GetActionTarget()); if(GetRDir() == -RotationSpeed()) ComStop(clonk); else { SetRDir(-RotationSpeed()); Trajectory(clonk); } return 1; } public func ComRight(object clonk) { SetAction("Rotating", GetActionTarget()); if(GetRDir() == RotationSpeed()) ComStop(clonk); else { SetRDir(RotationSpeed()); Trajectory(clonk); } return 1; } public func ComStop(object clonk) { SetAction("Attaching", GetActionTarget()); SetRDir(0); Trajectory(clonk); return 1; } //Wird vom Grabber nicht uebertragen, nur vom Container, Achtung, Aufruf stattdessen im Cannontower public func ComStopDouble(object clonk) { //Log("StopDouble"); Trajectory(clonk, 1); var r = (GetR() + 270) % 360; SetR(r); ChangeDef(CannonMobileID() ); return 1; } public func ComPowerUp(object clonk) { power++; if(power < GetLength(CannonPowerArray())) Sound("Click"); else { power--; Sound("CommandFailure1"); } Trajectory(clonk); } public func ComPowerDown(object clonk) { power--; if(power >= 0) Sound("Click"); else { power++; Sound("CommandFailure1"); } Trajectory(clonk); } public func ComFire(object clonk) { SetAction("Attaching", GetActionTarget()); SetRDir(0); Trajectory(clonk, 1); var ammo = clonk->Contents(); if(CannonAmmo(ammo)) Shoot(ammo, clonk); else if(MatSysDoTeamFill(-1, clonk->GetOwner(), ROCK)) Shoot(clonk->CreateContents(ROCK), clonk); else clonk->Sound("CommandFailure1"); Trajectory(clonk); return 1; } func Trajectory(object clonk, bool fClose) { var projectile = clonk->Contents(); //Log("MenuSelection: %d; Contents: %s", GetMenuSelection(clonk),GetName(projectile)); if(!fClose) AddTrajectory(this, Sin(GetR(), 13) + GetX(this), -Cos(GetR(), 13) + GetY(this), Sin(GetR(), CannonPower(projectile)) * 10, -Cos(GetR(), CannonPower(projectile)) * 10); else { //Log("Remove"); RemoveTrajectory(this); } return 1; } private func Shoot(object projectile, object shooter) { if (!projectile) return 0; //enough Steam? var plr = GetOwner(); var msys = GetMatSys(plr); var steam = CannonSteamUsage(projectile) * GetMass(projectile); if(MatSysGetTeamFill(plr, STEM) < steam) { Sound("Error"); Message("$TxtNotenoughgunpowder1r$", GetActionTarget(), steam); // Remove rocks if(projectile->GetID() == ROCK) { MatSysDoFill(1, shooter->GetOwner(), ROCK); projectile->RemoveObject(); } } else { MatSysDoTeamFill(-steam, plr, STEM); if(CannonSmoke(projectile) ) { Smoke(Sin(GetR(), 13), -Cos(GetR(), 13), 20); Smoke(Sin(GetR(), 18), -Cos(GetR(), 23), 17); Smoke(Sin(GetR(), 22), -Cos(GetR(), 32), 14); Smoke(Sin(GetR(), 25), -Cos(GetR(), 40), 11); } // Controller setzen (Killverfolgung) projectile->SetController(shooter->GetOwner()); //AddTrajectory(this(),Sin(GetR(), 13), -Cos(GetR(), 13),Sin(GetR(), CannonPower(projectile)), -Cos(GetR(), CannonPower(projectile))); Exit(projectile, Sin(GetR(), 13), -Cos(GetR(), 13), GetR(), Sin(GetR(), CannonPower(projectile)), -Cos(GetR(), CannonPower(projectile)), 20); if(GetOCF(projectile) & OCF_CrewMember ) ObjectSetAction(projectile, "Tumble"); Sound(CannonSound(projectile) ); SetPlrView(shooter->GetOwner(), projectile); } }
722,221
./clinfinity/Clinfinity.c4d/Structures.c4d/Sawmill.c4d/Script.c
/*-- Sawmill --*/ #strict 2 #include STBO //StructureBaseObject #include NLBO //Nightlight #include L_DC //Damagecontrol #include L_SS //StorageSystem static const SAWM_RADIUS = 350; // Radius in px static const SAWM_DELAY = 300; public func MaxDamage() { return 20; } local chopping; protected func Initialize(sawmill) { chopping = true; StartChopping(); inherited(...); } protected func ControlUp() { [$TxtShowSearchRadius$] //show Radius for(var i; i < 360; i++) CreateParticle("PSpark", Cos(i, SAWM_RADIUS), Sin(i, SAWM_RADIUS), 0, 0, 70, RGBa(255, 255, 255, 128)); } protected func ControlDig(object clonk) { if(Hostile(GetOwner(), clonk->GetOwner())) { Sound("CommandFailure1"); return; } if(chopping) { chopping = false; ClearScheduleCall(this, "Chop"); Sound("Command"); Message("$TxtOff$", this); } else { chopping = true; StartChopping(); Sound("Ding"); Message("$TxtOn$", this); } } public func StartChopping() { ScheduleCall(this, "Chop", SAWM_DELAY); } protected func Chop() { // Find the biggest tree var tree = FindObject2(Find_Distance(SAWM_RADIUS), Find_Func("IsTree"), Sort_Reverse(Sort_Func("GetCon"))); if(tree) { if(tree->Shrink()) SetAction("GrabWood"); } else { StartChopping(); } } protected func Finish() { MatSysDoTeamFill(2, GetOwner(), WOOD); StartChopping(); }
722,222
./clinfinity/Clinfinity.c4d/Goals.c4d/KOTH.c4d/Script.c
/* Script: King of the Hill Goal: Teams fight for a control point. They try to hold the control point until their timer runs out. */ #strict 2 #include GOAL // assumed frames per second static const KOTH_FPS = 30; // default win time in 'seconds' static const KOTH_WinTime = 180; // number of animation faces for capturing static const KOTH_CapturePhases = 100; // the capture point local cp; // the timer array which tracks progress local timer; // last update frame local lastUpdate; // last team owning the point local lastTeam; // the winner or -1 local winningTeam; protected func Completion() { // Rivalry! CreateObject(RVLR); // HUD position SetPosition(150, 32); // timer initialization timer = CreateArray(GetTeamCount()); var winTime = GameCall("WinningTime") || KOTH_WinTime * KOTH_FPS; for(var i = 0, len = GetLength(timer); i < len; i++) timer[i] = winTime; // no winner initially winningTeam = -1; ScheduleCall(this, "InitialRespawnTime", 300); } protected func InitialRespawnTime() { // initial long respawn time var time = KOTH_FPS * 12; for(var count = GetTeamCount(), i = 0; i < count; i++) { var t = GetTeamByIndex(i); SetRespawnTime(t, time); } } /* Function: SetCP Sets the capture point this goal tracks. Paramters: point - the capture point */ public func SetCP(object point) { if(point->IsControlPoint()) cp = point; } /* Function: IsFulfilled Callback for GOAL. Returns: _true_ if one team has their timer at zero. */ public func IsFulfilled() { // shortcut if(winningTeam != -1) return true; // which player holds the control point? var owner = cp->GetOwner(); if(owner != NO_OWNER) { var team = GetPlayerTeam(owner); if(team != lastTeam) { // shorter respawn times for the attacking team var time = KOTH_FPS * 3; for(var count = GetTeamCount(), i = 0; i < count; i++) { var t = GetTeamByIndex(i); SetRespawnTime(t, time); } SetRespawnTime(team, KOTH_FPS * 7); } lastTeam = team; team--; // subtract time timer[team] -= FrameCounter() - lastUpdate; timer[team] = Max(timer[team], 0); // has this team won? if(timer[team] <= 0) { if(cp->GetCapturingPlayer() != NO_OWNER) { // go into overtime! cp->SetOvertime(true); return false; } winningTeam = team + 1; return true; } } lastUpdate = FrameCounter(); return false; } /* Function: IsFulfilledforPlr Callback for GOAL. Parameters: plr - the player to check Return: _true_ if the given player is in the winning team. */ public func IsFulfilledforPlr(int plr) { return IsFulfilled() && GetPlayerTeam(plr) == winningTeam; } /* Function: UpdateHUD Updates the KOTH-HUD. */ public func UpdateHUD() { // base color: holding team var team = GetPlayerTeam(cp->GetOwner()); if(team) { SetClrModulation(GetTeamColor(team)); } // overlay: capturing team team = GetPlayerTeam(cp->GetCapturingPlayer()); if(team) { var action = Format("Capturing%d", ChangeRange(cp->GetCapturePercentage(), 0, 100, 0, KOTH_CapturePhases - 1)); SetStillOverlayAction(action, 1); SetClrModulation(GetTeamColor(team), 0, 1); } else { // remove overlay SetGraphics(0, 0, 0, 1); } // time // reset for(var i = 0, len = GetLength(timer); i < len; i++) { var t = timer[i] / KOTH_FPS, team = i + 1; var msg = Format("@%d:%.2d", t / 60, t % 60); var flags = 0; if(i > 0) flags = MSG_Multiple; CustomMessage(msg, this, NO_OWNER, 60, 36 + 20 * i, GetTeamColor(team), 0, 0, flags); } } protected func Timer() { IsFulfilled(); UpdateHUD(); }
722,223
./clinfinity/Clinfinity.c4d/Goals.c4d/DUEL.c4d/Script.c
/*-- DUEL GOAL --*/ #strict 2 #include GOAL local fulfilled; protected func Completion() { CreateObject(RVLR, 0, 0, NO_OWNER); } public func IsFulfilled() { return fulfilled; } public func IsFulfilledforPlr(int plr) { var win = !FindObject2(Find_ID(STMT), Find_Hostile(plr)); if(win) fulfilled = true; return win; }
722,224
./clinfinity/Clinfinity.c4d/Rules.c4d/Draft.c4d/Script.c
/* Script: Drafts Rule: When activated, local drafts are placed in the landscape. These drafts accelerate Clonks in the air, although those using the wing suit get a much greater boost. By riding the drafts, gliding Clonks can reach higher or more distant places which are normally inaccessible. Drafts have limited bounds, inside which they accelerate Clonks in the draft's direction. The number of drafts is determined by the number of activated drafts rules: For each rule, one draft is placed. A draft's position is chosen randomly, where it will stay for a configurable duration. You can specify a minimum and maximum value, the actual duration a draft stays is then randomised within these bounds. *Note:* This behaviour can be overridden by implementing a function called "IsDraftPermanent" that returns true. This function may be defined in the scenario script or any rule, goal or environment object. If such a function exists, drafts will only set their position once and then stay. */ #strict 2 /* Variables: Draft size and appearance draftWidth - Width of the draft's bounds, without rotation applied. draftHeight - Height of the draft's bounds, without rotation applied. draftDistance - Distance in which Clonks are searched for, automatically calculated from draftWidth and draftHeight. draftParticleColour - Colour and opacity of emitted draft particles. */ local draftWidth, draftHeight, draftDistance, draftParticleColour; /* Variables: Random placement These variables determine the duration that a draft keeps its position, before repositioning itself randomly. permanentDraft - _true_ if this draft is permanent. minDraftDuration - Minimum duration. maxDraftDuration - Maximum duration. */ local permanentDraft, minDraftDuration, maxDraftDuration; /* Variables: Clonk acceleration maxGliderSpeedUpwards - Maximum speed a glider is accelerated to. gliderAcceleration - Acceleration rate for gliders. Unit is 1/10 pixels per frame. */ local maxGliderSpeedUpwards, gliderAcceleration; local active; protected func Activate(byPlayer) { MessageWindow(GetDesc(), byPlayer); return 1; } protected func Initialize() { SetSize(50, 150); draftParticleColour = RGBa(255, 255, 255, 210); minDraftDuration = 1050; maxDraftDuration = 2100; maxGliderSpeedUpwards = 60; gliderAcceleration = 5; // allow for setting it permanent ScheduleCall(this, "SetRandomPosition", 1); Enable(); } /* Function: SetSize Sets the draft's bounds inside which it accelerates Clonks. The bounds are specified for unrotated drafts. If a draft is rotated, the searching area is rotated automatically as well. Parameters: width - Bounds width. height - Bounds height. */ public func SetSize(int width, int height) { draftWidth = width; draftHeight = height; draftDistance = Sqrt(Pow(draftWidth, 2) + Pow(draftHeight, 2)) / 2; } /* Function: SetPermanent Makes this draft permanent. */ public func SetPermanent() { permanentDraft = true; } /* Function: Enable Enables this draft. */ public func Enable() { if(!GetEffect("Draft", this)) { AddEffect("Draft", this, 1, 10, this); AddEffect("DraftParticle", this, 1, 1, this); return true; } } /* Function: Disable Disables this draft. A disabled draft will continue to exist and will keep its position. Repositioning will still occur. A disabled draft can be re-enabled with <Enable>. */ public func Disable() { RemoveEffect("Draft", this); RemoveEffect("DraftParticle", this); return true; } protected func FxDraftParticleTimer(object target, int effectNum, int effectTime) { var draftDirection = GetR(); if( !Random(2) ) { var x = RandomX(-draftWidth / 2, draftWidth / 2), y = RandomX(-3, 3), speed = RandomX(-draftHeight / 6,-draftHeight / 4); // rotation Rotate(draftDirection, x, y); CreateParticle("WindSpark", x, y, -Sin(draftDirection, speed), Cos(draftDirection, speed), 40, draftParticleColour); } } protected func FxDraftTimer(object target, int effectNum, int effectTime) { var draftDirection = GetR(); var x = 0, y = -draftHeight / 2; Rotate(draftDirection, x, y); var gliders = FindObjects(Find_NoContainer(), Find_Distance(draftDistance, x, y), Find_Category(C4D_Living)); if(GetLength(gliders)) { if(!active) { active = true; ChangeEffect(0, target, effectNum, "Draft", 1); } for( var glider in gliders ) { var gx = glider->GetX() - GetX(), gy = glider->GetY() - GetY(); Rotate(-draftDirection, gx, gy); if(Inside(gx, -draftWidth / 2, draftWidth / 2) && Inside(gy, -draftHeight, 0)) { var xDir = glider->GetXDir(0, 100), yDir = glider->GetYDir(0, 100); var xAcc = Sin(draftDirection, gliderAcceleration * 10), yAcc = -Cos(draftDirection, gliderAcceleration * 10); // Not actually gliding? Less acceleration! if(!glider->~IsGliding()) { xAcc /= 3; yAcc /= 3; } glider->SetXDir(xDir + xAcc, 0, 100); //Message("X: %d, Y: %d", this, xAcc, yAcc); if(yDir > -maxGliderSpeedUpwards * 10) { glider->SetYDir(yDir + yAcc, 0, 100); } } } } else if(active) { active = false; ChangeEffect(0, target, effectNum, "Draft", 10); } } protected func SetRandomPosition() { if(permanentDraft) return; var x = Random(LandscapeWidth()); var y = Random(LandscapeHeight()); var otherDraft = FindObject2( Find_And( Find_ID(GetID()), Find_InRect(AbsX(x) - draftWidth / 2, AbsY(y) - draftHeight, draftWidth, draftHeight) ) ); if(otherDraft != 0) { // Anderes Aufwind-Objekt schon an der Stelle: NΣchstes Frame neue Position suchen. ScheduleCall(this, "SetRandomPosition", 1); } else { if( !GameCallEx("IsDraftPermanent") ) { // Kein anderes Aufwind-Objekt: Neue Position erst in einer Weile suchen. ScheduleCall(this, "SetRandomPosition", RandomX(minDraftDuration, maxDraftDuration)); } SetPosition(x, y); } }
722,225
./clinfinity/Clinfinity.c4d/Rules.c4d/FlintKnowledge.c4d/Script.c
/* Flint Knowledge */ #strict 2 protected func Initialize() { ScheduleCall(0, "ActivateSuperFlints", 17280); ScheduleCall(0, "ActivateTeraFlints", 25920); } protected func ActivateSuperFlints() { Log("$TxtKnowledgeSFLN$"); Sound("Status"); //Count the number of actual players for(var playernumber = 0; playernumber < GetPlayerCount(); playernumber++) SetPlrKnowledge(GetPlayerByIndex(playernumber), EFLN); } protected func ActivateTeraFlints() { Log("$TxtKnowledgeEFLN$"); Sound("Status"); for(var playernumber = 0; playernumber < GetPlayerCount(); playernumber++) SetPlrKnowledge(GetPlayerByIndex(playernumber), EFLN); }
722,226
./clinfinity/Clinfinity.c4d/Vegetation.c4d/Shrub.c4d/Script.c
/*-- Plants --*/ #strict 2 static const Actions = 2; protected func Initialize(obj) { SetAction(Format("Shrub%d", Random(Actions) + 1)); DoCon(-30,obj); /*if (Random(5)) DoCon(-Random(20) - 40); else DoCon(-Random(50) - 20); SetPhase(Random(2)); if (!Random(20)) SetPhase(2); // ZufΣllige Richtung if (Random(2)) SetDir(DIR_Right) */ // Drehung nach ErdoberflΣche var x_off = 18 * GetCon() / 100; var y_off = 15 * GetCon() / 100; var slope = GetSolidOffset(-x_off, y_off) - GetSolidOffset(x_off, y_off); SetR(slope); // H÷he anpassen while (!GBackSolid(0, 5)) SetPosition(GetX(), GetY() + 1); } private func GetSolidOffset(int x, int y) { var i; for (i = -10; GBackSolid(x, y - i) && (i < 10); i++); return(i); } // Bei nahen Explosionen public func OnShockwaveHit(iLevel,iX,iY) { var con=(40*GetCon())/100; iLevel=40+iLevel/2; for(var cnt=0;cnt<10+Random(10);cnt++) CreateParticle("GrassBlade",RandomX(-con/2,con/2),-1,RandomX(-iLevel/3 ,iLevel/3),RandomX(-2*iLevel/3,-iLevel/3),30+Random(30),RGB(255,255,255),0,0); return(RemoveObject()); } // Kann immer von Schockwellen getroffen werden public func CanBeHitByShockwaves(){return(true);} public func BlastObjectsShockwaveCheck(){return(true);}
722,227
./clinfinity/Clinfinity.c4d/Vegetation.c4d/Vine.c4d/Script.c
/*-- Liane --*/ #strict protected func Construction() { // ZufΣlliges Aussehen SetAction("Vine"); SetPhase(Random(10)); // In Kⁿrze Position anpassen AddEffect("AdjustGrowthPos", this(), 1, 1, this()); } public func GetVineLength() { return (GetCon() * GetDefCoreVal("Height") / 100); } public func FxAdjustGrowthPosTimer() { // Effekt entfernen RemoveEffect("AdjustGrowthPos", this()); // Y-Position anpassen (Wachstumsverschiebung der Engine ausgleichen) SetPosition(GetX(), GetY() + GetVineLength()); }
722,228
./clinfinity/Clinfinity.c4d/Vegetation.c4d/Plants.c4d/Script.c
/*-- Plants --*/ #strict 2 static const Actions = 3; protected func Initialize(obj) { SetAction(Format("Plant%d", Random(Actions) + 1)); /*if (Random(5)) DoCon(-Random(20) - 40); else DoCon(-Random(50) - 20); SetPhase(Random(2)); if (!Random(20)) SetPhase(2); // ZufΣllige Richtung if (Random(2)) SetDir(DIR_Right) */ // Drehung nach ErdoberflΣche var x_off = 18 * GetCon() / 100; var y_off = 15 * GetCon() / 100; var slope = GetSolidOffset(-x_off, y_off) - GetSolidOffset(x_off, y_off); SetR(slope); // H÷he anpassen while (!GBackSolid(0, 5)) SetPosition(GetX(), GetY() + 1); } private func GetSolidOffset(int x, int y) { var i; for (i = -10; GBackSolid(x, y - i) && (i < 10); i++); return(i); } // Bei nahen Explosionen public func OnShockwaveHit(iLevel,iX,iY) { var con=(40*GetCon())/100; iLevel=40+iLevel/2; for(var cnt=0;cnt<10+Random(10);cnt++) CreateParticle("GrassBlade",RandomX(-con/2,con/2),-1,RandomX(-iLevel/3 ,iLevel/3),RandomX(-2*iLevel/3,-iLevel/3),30+Random(30),RGB(255,255,255),0,0); return(RemoveObject()); } // Kann immer von Schockwellen getroffen werden public func CanBeHitByShockwaves(){return(true);} public func BlastObjectsShockwaveCheck(){return(true);}
722,229
./clinfinity/Clinfinity.c4d/Vegetation.c4d/Grass.c4d/Script.c
/*-- Grass --*/ #strict protected func Initialize() { // ZufΣllige Gr÷▀e if (Random(5)) DoCon(-Random(20) - 40); else DoCon(-Random(50) - 20); // ZufΣllige Form SetAction("Grass"); SetPhase(Random(2)); if (!Random(20)) SetPhase(2); // ZufΣllige Richtung if (Random(2)) SetDir(DIR_Right); // Drehung nach ErdoberflΣche var x_off = 18 * GetCon() / 100; var y_off = 15 * GetCon() / 100; var slope = GetSolidOffset(-x_off, y_off) - GetSolidOffset(x_off, y_off); SetR(slope); // H÷he anpassen while (!GBackSolid(0, 5)) SetPosition(GetX(), GetY() + 1); // Gras bleibt hinter BΣumen MoveBehindTrees(); ScheduleCall(0, "ListenToTime", 1); } protected func ListenToTime() { var time = FindObject2(Find_ID(TIME)); if(time != 0) { time->AddEventListener(this, "OnNight"); } } private func GetSolidOffset(int x, int y) { var i; for (i = -15; GBackSolid(x, y - i) && (i < 15); i++); return(i); } private func MoveBehindTrees() { var obj; while (obj = FindObject(0, 1,1, 0,0, OCF_Chop(), 0,0, NoContainer(), obj)) if (obj->~IsTree() && (obj->GetCategory() & C4D_StaticBack)) SetObjectOrder(obj, this(), 1); } // Bei nahen Explosionen public func OnShockwaveHit(iLevel,iX,iY) { var con=(40*GetCon())/100; iLevel=40+iLevel/2; for(var cnt=0;cnt<15+Random(10);cnt++) CreateParticle("GrassBlade",RandomX(-con/2,con/2),-1,RandomX(-iLevel/3 ,iLevel/3),RandomX(-2*iLevel/3,-iLevel/3),30+Random(30),RGB(255,255,255),0,0); return(RemoveObject()); } public func OnNight(object source) { if(!Random(10)) { IRRL->SpawnSwarm(GetX(), GetY(), RandomX(5, 10), this); } } // Kann immer von Schockwellen getroffen werden public func CanBeHitByShockwaves(){return(true);} public func BlastObjectsShockwaveCheck(){return(true);}
722,230
./clinfinity/Clinfinity.c4d/Effects.c4d/Light.c4d/Script.c
/* Script: Light Provides functions concerning lights. Taken from the Hazard pack. */ #strict global func IsDark() { return true; } global func CalcLight(&alphamod, &sizemod) { sizemod = 100 + GetDarkness() * 3 / 2; // Stretch up ta 250% alphamod = (100 - GetDarkness()) / 5; // Add 0-20 to alpha // No darkness or darkness value = 0: Almost invisible. if(!IsDark() || !GetDarkness()) alphamod = 30; } /* Function: GetDarkness Returns darkness in percent (0-100). The default value is 0 (no darkness). Scenario scripts, goals and rules may specify other values for darkness by implementing _GetDarkness()_. Returns: Darkness value in percent. */ global func GetDarkness() { return BoundBy(GameCallEx("GetDarkness"), 0, 100); } /* Below: Original Hazard script */ local iColor, bAmbience, iF; //Licht initialisieren, Parameter setzen, etc. protected func Init(int iSize, int iColor, object pTarget, string cGraphics) { if(bAmbience && !IsDark()) Schedule("RemoveObject()",1,0,this()); //Werte if(!iSize) iSize = GetCon(); if(!pTarget) pTarget = GetActionTarget(); SetOwner(GetController(pTarget)); //Setzen und so SetAction("Attach",pTarget); SetPosition(GetX(pTarget),GetY(pTarget)); ChangeColor(iColor); ChangeSize(iSize); ChangeGraphics(cGraphics); } //Wenn das Licht kein Ziel mehr hat -> weg damit. protected func AttachTargetLost() { RemoveObject(); } //Licht ausschalten public func TurnOff() { SetVisibility(VIS_None); } //Licht einschalten public func TurnOn() { SetVisibility(VIS_All); } // gr÷▀e des Lichts Σndern public func ChangeSize(int iNewSize) { var alphamod, sizemod; CalcLight(alphamod, sizemod); iF = iNewSize; SetCon(iF*sizemod/100); } // Licht updaten... verΣndert keine Werte sondern // passt die Anzeige nur an public func Update() { ChangeSize(iF); ChangeColor(iColor); } //Farbe des Lichts Σndern public func ChangeColor(int iNewColor) { iColor = iNewColor; //Wenn keine dunkelheit ist if(!IsDark()) { //Hintergrundlichter ausblenden if(bAmbience) iNewColor = RGBa(255,255,255,255); } var alphamod, sizemod; CalcLight(alphamod, sizemod); var r,g,b,a; SplitRGBaValue(iColor,r,g,b,a); iNewColor = RGBa(r,g,b,Min(a+60+alphamod,255)); SetClrModulation(iNewColor); return(iNewColor); } //Grafik Σndern public func ChangeGraphics(string cNewGraphics) { SetGraphics(cNewGraphics, 0, GetID()); } //festlegen, dass es ein Licht ist. public func IsLight() { return(1); } public func NoWarp() { return(true); } /*-- Globale Funktionen zur Lichterzeugung --*/ //Hilfsfunktion global func CreateLight(id ID, int iSize, int iColor, object pTarget, string sGraphics) { var light = CreateObject(ID, 0, 0, GetController(pTarget)); light->Init(iSize, iColor, pTarget, sGraphics); return(light); } //erzeugt ein Licht mit Gr÷▀e und Farbe und hΣngt es an pTarget global func AddLight(int iSize, int iColor, object pTarget) { if(!pTarget) if(!(pTarget = this())) return(); return(CreateLight(LIGH, iSize, iColor, pTarget)); } global func AddLightHalf(int iSize, int iColor, object pTarget) { if(!pTarget) if(!(pTarget = this())) return(); return(CreateLight(LIGH, iSize, iColor, pTarget, "Half")); } global func AddLightCone(int iSize, int iColor, object pTarget) { if(!pTarget) if(!(pTarget = this())) return(); return(CreateLight(LGHC, iSize, iColor, pTarget)); } //Ambience-Light, Umgebungslicht, nicht sichtbar wenn keine Dunkelheit herrscht. global func AddLightAmbience(int iSize, object pTarget, string cGraphics) { if(!pTarget) if(!(pTarget = this())) return(); var light = CreateObject(LIGH,0,0,GetController(pTarget)); light->LocalN("bAmbience") = true; light->Init(iSize*5, RGBa(255,255,255,50), pTarget, cGraphics); return(light); } //Lichtblitz! global func AddLightFlash(int iSize, int iX, int iY, int iColor) { var alphamod, sizemod; CalcLight(alphamod, sizemod); var r,g,b,a; SplitRGBaValue(iColor,r,g,b,a); iColor = RGBa(r,g,b,Min(a+alphamod,255)); CreateParticle("LightFlash",iX,iY,0,0,iSize*5*sizemod/100,iColor); }
722,231
./clinfinity/Clinfinity.c4d/Effects.c4d/Light.c4d/LightCone.c4d/Script.c
/*-- Lichtkegel --*/ #strict #include LIGH // Variablen local iSizeX, iSizeY, iOffX, iOffY, iR, bDir; /* iSizeX - X-Gr÷▀e iSizeY - Y-Gr÷▀e iOffX - Verschiebung der Grafik in X-Richtung iOffY - Verschiebung der Grafik in Y-Richtung //Alle Werte in 1000/Pixel iR - Rotation bDir - Wenn true wird ist das X-Offset mit der Dir gespiegelt */ // Licht updaten... verΣndert keine Werte sondern // passt die Anzeige nur an public func Update() { ChangeSizeXY(iSizeX, iSizeY); ChangeColor(iColor); } public func ChangeSize(int iNewSize) { ChangeSizeXY(iNewSize,iNewSize); } public func ChangeSizeXY(int iNewSizeX, int iNewSizeY) { iSizeX = iNewSizeX; iSizeY = iNewSizeY; Draw(); } public func ChangeOffset(int iNewOffX, int iNewOffY, bool bNewDir) { iOffX = iNewOffX; iOffY = iNewOffY; bDir = bNewDir; Draw(); } public func ChangeR(int iNewR) { iR = -iNewR; Draw(); } public func Draw() { var dir; if(!bDir) dir = 1; else dir = 1-GetDir(GetActionTarget())*2; var alphamod, sizemod; CalcLight(alphamod, sizemod); var fsin, fcos, xoff, yoff; fsin = Sin(iR, 1000); fcos = Cos(iR, 1000); xoff = 0; yoff = +64; var width = iSizeX*sizemod/100, height = iSizeY*sizemod/100; SetObjDrawTransform( +fcos*width/1000, +fsin*height/1000, (((1000-fcos)*xoff - fsin*yoff)*height)/1000+iOffX*1000*dir, -fsin*width/1000, +fcos*height/1000, (((1000-fcos)*yoff + fsin*xoff - 64000)*height)/1000+iOffY*1000 ); }
722,232
./clinfinity/Clinfinity.c4d/Animals.c4d/Firefly.c4d/Script.c
/* Script: Firefly */ #strict 2 static const IRRL_MaxSpawnDistance = 15; static const IRRL_MaxDistance = 40; static const IRRL_ShynessDistance = 40; local attractedTo; local light; public func SpawnSwarm(int x, int y, int size, object attractedTo) { for(var i = 0; i < size; i++) { var firefly = CreateObject(IRRL, RandomX(x - IRRL_MaxSpawnDistance, x + IRRL_MaxSpawnDistance), RandomX(y - IRRL_MaxSpawnDistance, y + IRRL_MaxSpawnDistance), NO_OWNER); firefly->LocalN("attractedTo") = attractedTo; } } private func Flying() { var xdir, ydir; var awayFrom = FindObject2(Find_Distance(IRRL_ShynessDistance), Find_Category(C4D_Object), Find_OCF(OCF_HitSpeed1), Find_NoContainer()); if(awayFrom != 0) { xdir = BoundBy(GetX() - awayFrom->GetX(), -1, 1); ydir = BoundBy(GetY() - awayFrom->GetY(), -1, 1); if(xdir == 0) xdir = Random(2) * 2 - 1; if(ydir == 0) ydir = Random(2) * 2 - 1; xdir = RandomX(5 * xdir, 10 * xdir); ydir = RandomX(5 * ydir, 10 * ydir); // No check for liquids here, you can scare fireflies into those ;) SetSpeed(xdir, ydir); } else { if(Random(4)) return; if(attractedTo != 0 && ObjectDistance(attractedTo) > IRRL_MaxDistance) { xdir = BoundBy(attractedTo->GetX() - GetX(), -1, 1); ydir = BoundBy(attractedTo->GetY() - GetY(), -1, 1); xdir = RandomX(xdir, 6 * xdir); ydir = RandomX(ydir, 6 * ydir); } else { xdir = Random(13) - 6; ydir = Random(9) - 4; } if(GBackLiquid(xdir, ydir)) { SetSpeed(0, 0); } else { SetSpeed(xdir, ydir); } } } protected func Check() { // Buried or in water: Instant death if(GBackSemiSolid()) { Death(); } } protected func Initialize() { SetAction("Fly"); SetPhase(Random(6)); var lightColour = RGBa(220, 255, 200, 0); light = AddLight(40, lightColour, this); FadeIn(); var alphamod, sizemod; CalcLight(alphamod, sizemod); light->FadeIn(SetRGBaValue(lightColour, Min(60 + alphamod, 255), 0)); var time = FindObject2(Find_ID(TIME)); if(time != 0) { time->AddEventListener(this, "OnDaybreak"); } } public func OnDaybreak() { ScheduleCall(this, "StartFadeOut", RandomX(1, 150)); } public func OnFadeFinish(int targetColour) { if(GetRGBaValue(targetColour, 0) == 255) { Death(); } } private func StartFadeOut() { FadeOut(); light->FadeOut(); } public func CatchBlow() { RemoveObject(); } public func Damage() { RemoveObject(); } protected func Death() { RemoveObject(); }
722,233
./clinfinity/Clinfinity.c4f/KOTH_Skyward.c4s/Script.c
/*-- Leberwurst --*/ #strict 2 func Initialize() { // create goal var cp = CreateObject(SHIP, LandscapeWidth() / 2, LandscapeHeight() / 2, NO_OWNER); var koth = CreateObject(KOTH, 0, 0, NO_OWNER); koth->SetCP(cp); //static drafts var DraftL = CreateObject(DRFT,320, 590, NO_OWNER); DraftL -> SetPermanent(); DraftL -> SetR(20); var DraftR = CreateObject(DRFT,1500, 690, NO_OWNER); DraftR -> SetPermanent(); DraftR -> SetR(8); var DraftL2=CreateObject(DRFT, 799, 600, NO_OWNER); DraftL2 -> SetPermanent(); DraftL2 -> SetR(-15); var DraftR2=CreateObject(DRFT, 1122, 600, NO_OWNER); DraftR2 -> SetPermanent(); DraftR2 -> SetR(20); //crates on frigate CreateObject(CRAT,855,340, NO_OWNER); CreateObject(CRAT,869,340, NO_OWNER); CreateObject(CRAT,860,329, NO_OWNER); CreateObject(CRAT,987,340, NO_OWNER); CreateObject(CRAT,994,329, NO_OWNER); CreateObject(CRAT,1000,340, NO_OWNER); //drainer on frigate (no pool on deck allowed) CreateObject(DRAI, 933, 338, NO_OWNER); // steampunky flair SetGamma(RGB(15, 15, 20), RGB(118, 118, 118), RGB(210, 215, 255)); // place fog for(var i; i<160; ++i) CreateParticle("Cloud", Random(LandscapeWidth()), Random(LandscapeHeight()*2/3), RandomX(3, 9), 0, RandomX(1000, 1500), RGBa(116, 131, 145, 0)); // place decoration CreateObject(BEAM, 318, 441, NO_OWNER) -> SetAction("Right"); //beam big-Left CreateObject(BEAM, 1610, 472, NO_OWNER) -> SetAction("Left"); //beam big-right CreateObject(RUIN,863,613,NO_OWNER); // ruin in the middle //place skylands CreateObject(SKYL, 293, 500, NO_OWNER) -> SetClrModulation(RGBa(150, 180, 255, 150)); var isle2=CreateObject(SKYL, 1400, 545, NO_OWNER); isle2 -> SetClrModulation(RGBa(150, 180, 255, 155)); isle2 -> SetAction("2"); // Island Respawn PeriodicIslandRespawn(3500, 100, 400, 220, 120); // left 'home' island PeriodicIslandRespawn(3503, 1625, 440, 190, 120); // right 'home' island ScriptGo(1); } func GetStartPosition(int team) { if(team == 1) return [200, 400]; if(team == 2) return [1710, 430]; } func InitializePlayer(int plr) { CreateMatSys(plr); // fill with material var msys = GetMatSys(plr); msys->DoFill(5, WOOD); msys->DoFill(15, METL); msys->DoFill(10, ROCK); var team = GetPlayerTeam(plr); var pos = GetStartPosition(team); if(GetLength(GetPlayersByTeam(team)) == 1) { CreateStartMaterial(pos[0], pos[1], plr); } var tank = FindObject2(Find_ID(STMT), Find_Allied(plr)); tank->DoFill(300); var i = 0, clonk; while(clonk = GetCrew(plr, i++)) clonk->Enter(tank); } func CreateStartMaterial(int x, int y, int plr) { PLTF->CreatePlatform(x, y, plr); CreateConstruction(STMT, x + 10, y - 5, plr, 100); CreateObject(CATA, x + Random(20), y - 5, plr); } func Script0() { CreateParticle("Cloud", 0, Random(LandscapeHeight()*2/3), RandomX(3, 9), 0, RandomX(1000, 1500), RGBa(116, 131, 145, 0)); } func Script20() { return goto(0); }
722,234
./clinfinity/Clinfinity.c4f/KOTH_Observatory.c4s/Script.c
/*-- KOTH_Observatory --*/ #strict 2 func Initialize() { var cp = CreateObject(OBSV, 1210, 1170, NO_OWNER); cp -> SetClrModulation(RGBa(235,230,255,50)); var koth = CreateObject(KOTH, 0, 0, NO_OWNER); koth->SetCP(cp); //Mountains var MtL = CreateObject(MONT,900,1350, NO_OWNER); var MtR = CreateObject(MONT,1400,1350, NO_OWNER); //Observatory Parts var tw1 = CreateObject(TW_1,1087,825, NO_OWNER); tw1 -> SetClrModulation(RGBa(230,220,255,80)); var tw2 = CreateObject(TW_2,1019,1050, NO_OWNER); tw2 -> SetClrModulation(RGBa(230,220,255,5)); //Moon var moon = CreateObject(MOON,1337,490, NO_OWNER); moon -> SetClrModulation(RGBa(255,255,255,80)); //Trees CreateObject(TRE4,1076,905,NO_OWNER); CreateObject(TRE4,1067,926,NO_OWNER); CreateObject(TRE4,1184,917,NO_OWNER); CreateObject(TRE4,1182,904,NO_OWNER); CreateObject(TRE4,1190,918,NO_OWNER); CreateObject(TRE4,1175,922,NO_OWNER); CreateObject(TRE4,1231,926,NO_OWNER); CreateObject(TRE4,1206,925,NO_OWNER); CreateObject(TRE4,1211,905,NO_OWNER); CreateObject(TRE4,1251,921,NO_OWNER); CreateObject(TRE4,1341,922,NO_OWNER); CreateObject(TRE4,1317,920,NO_OWNER);; CreateObject(TRE4,1377,925,NO_OWNER); CreateObject(TRE4,1083,931,NO_OWNER); CreateObject(TRE4,1163,964,NO_OWNER); CreateObject(TRE4,1190,961,NO_OWNER); CreateObject(TRE4,1180,963,NO_OWNER); CreateObject(TRE4,1227,946,NO_OWNER); CreateObject(TRE4,1293,961,NO_OWNER);; CreateObject(TRE4,1264,936,NO_OWNER); CreateObject(TRE4,1291,941,NO_OWNER); CreateObject(TRE4,1340,968,NO_OWNER); CreateObject(TRE4,1345,945,NO_OWNER); CreateObject(TRE4,1313,972,NO_OWNER); CreateObject(TRE4,1372,961,NO_OWNER); CreateObject(TRE4,1392,1051,NO_OWNER); CreateObject(TRE4,1404,1076,NO_OWNER); //static Drafts var staticDraftObservatoryL=CreateObject(DRFT, 970, 1025, NO_OWNER); staticDraftObservatoryL -> SetPermanent(); var staticDraftObservatoryR=CreateObject(DRFT, 1430, 940, NO_OWNER); staticDraftObservatoryR -> SetPermanent(); // Mountain Respawn PeriodicIslandRespawn(3550, 0, 430, 570, 750); // left 'home' island PeriodicIslandRespawn(3650, 2440, 400, 630, 770); // right 'home' island ScriptGo(true); } protected func Script10(){ Message("@$Woodmessage$"); Sound("Ding"); } protected func Script60(){ Message(""); } func GetStartPosition(int team) { if(team == 1) return [200, 400]; if(team == 2) return [2240, 400]; } func InitializePlayer(int plr) { CreateMatSys(plr); // fill with material var msys = GetMatSys(plr); msys->DoFill(25, WOOD); msys->DoFill(25, METL); msys->DoFill(10, ROCK); CreateContents(FLNT, GetHiRank(plr), 3); var team = GetPlayerTeam(plr); var pos = GetStartPosition(team); if(GetLength(GetPlayersByTeam(team)) == 1) { CreateStartMaterial(pos[0], pos[1], plr); } var tank = FindObject2(Find_ID(STMT), Find_Allied(plr)); tank->DoFill(300); var i = 0, clonk; while(clonk = GetCrew(plr, i++)) clonk->Enter(tank); } func CreateStartMaterial(int x, int y, int plr) { PLTF->CreatePlatform(x, y, plr); CreateConstruction(STMT, x + 10, y - 5, plr, 100); } global func IsDay() { return false; } global func IsNight() { return true; }
722,235
./clinfinity/Clinfinity.c4f/KOTH_Observatory.c4s/Mountains.c4d/Script.c
/*-- Mountains --*/ #strict 2 func Initialize() { Local(0) = RandomX(50, 99); Local(1) = 80; }
722,236
./clinfinity/Clinfinity.c4f/KOTH_Observatory.c4s/Observatory.c4d/Script.c
/*-- Observatory --*/ #strict 2 public func SetupTime() { return 800; } // this is a control point #include L_CP local flag; public func Initialize() { SetAction("MakeSound"); flag = CreateObject(FLAG, 0, 0, NO_OWNER); flag->SetAction("FlyBase", this); } public func EnablePoint() { if(inherited(...)) SetAction("OpenCupola"); } protected func LogMsg() { Log("$PointOpen$"); Sound("Status"); } private func Captured() { flag->SetOwner(GetOwner()); return inherited(...); } public func CaptureTime() { return 400; } public func CaptureZone() { // on top of the platform return Find_InRect(-65, -150, 121, 30); }
722,237
./clinfinity/Clinfinity.c4f/KOTH_Observatory.c4s/System.c4g/TreeForeground.c
/*-- Tree4 always Foreground --*/ #strict 2 #appendto TRE4 protected func Initialize(obj){ SetCategory(C4D_Foreground, obj); }
722,238
./clinfinity/Clinfinity.c4f/DUEL_CrumblingIslands.c4s/Script.c
/*-- Crumbling Islands --*/ #strict 2 func Initialize() { //Ressource Buildings CreateConstruction(RFLN, 1040, 740, NO_OWNER, 100, 1, 0); //Flintfactory Middle CreateConstruction(RSMG, 810, 540, NO_OWNER, 100, 1, 0); //Steamgenerator Left CreateConstruction(RSMG, 1315, 545, NO_OWNER, 100, 1, 0); //Steamgenerator Left //Pipe to Steamgenerator CreateObject(PIPE, 1349, 1008, NO_OWNER); //Crumbling Islands (deco) var CIsleL = CreateObject(ISLE, 760, 810, NO_OWNER); CIsleL -> SetClrModulation(RGBa(200, 215, 255, 50)); var CIsleM = CreateObject(ISLE,1100,1000, NO_OWNER); CIsleL -> SetClrModulation(RGBa(200, 215, 255, 80)); var CIsleR = CreateObject(ISLE,1335,800, NO_OWNER); CIsleR -> SetClrModulation(RGBa(200, 215, 255, 30)); CreateObject(WTFL, 814, 698, NO_OWNER); //Waterfall SetSkyParallax(1, 20, 0, 1, 0); //Sky move with Wind //Fog CreateObject(FOG_, 400, 1050, NO_OWNER); CreateObject(FOG_, 1200, 1050, NO_OWNER); CreateObject(FOG_, 2000, 1050, NO_OWNER); //static drafts var DraftWaterfall = CreateObject(DRFT, 760, 780, NO_OWNER); DraftWaterfall -> SetPermanent(); DraftWaterfall -> SetR(-10); var MIsleL = CreateObject(DRFT, 992, 749, NO_OWNER); MIsleL -> SetPermanent(); MIsleL -> SetR(-12); var MIsleR = CreateObject(DRFT, 1095, 780, NO_OWNER); MIsleR -> SetPermanent(); MIsleR -> SetR(12); var IsleR = CreateObject(DRFT, 1310, 764, NO_OWNER); IsleR -> SetPermanent(); IsleR -> SetR(-12); var IsleM = CreateObject(DRFT, 1060, 670, NO_OWNER); IsleM -> SetPermanent(); //thousands of vines! PlaceVines(); //mass epic wood PlaceWood(); // Island Respawn PeriodicIslandRespawn(1993, 140, 750, 330, 250); // left 'home' island PeriodicIslandRespawn(2007, 1620, 730, 310, 250); // right 'home' island } func InitializePlayer(int plr) { CreateMatSys(plr); // fill with material var msys = GetMatSys(plr); msys->DoFill(4, WOOD); msys->DoFill(10, METL); msys->DoFill(7, ROCK); //Flints CreateContents(FLNT, GetHiRank(plr), 2); var team = GetPlayerTeam(plr); var pos = GetStartPosition(team); if(GetLength(GetPlayersByTeam(team)) == 1) { CreateStartMaterial(pos[0], pos[1], plr); } var tank = FindObject2(Find_ID(STMT), Find_Allied(plr)); tank->DoFill(100); var i = 0, clonk; while(clonk = GetCrew(plr, i++)) clonk->Enter(tank); } func CreateStartMaterial(int x, int y, int plr) { var pltf1 = PLTF->CreatePlatform(x, y, plr); var pltf2 = PLTF->CreatePlatform(x + 20, y, plr); PLTF->Connect(pltf1, pltf2); var team = GetPlayerTeam(plr), ox, tankX = x; if(team == 1) { tankX += 10; ox = 1; } else { tankX += 95; ox = -1; } CreateConstruction(STMT, tankX, y - 5, plr, 100); var artillery = CreateConstruction(CTW0, tankX + ox * 90, y - 5, plr, 100); artillery->ConnectCannon(CreateObject(CTW3, 0, 0, plr)); } func GetStartPosition(int team) { if(team == 1) return [300, 730]; if(team == 2) return [1800, 730]; } protected func PlaceVines() { var obj0 = CreateObject(VINE, 755, 557, NO_OWNER); obj0->SetCon(60); CreateObject(VINE, 796, 588, NO_OWNER); var obj1 = CreateObject(VINE, 786, 571, NO_OWNER); obj1->SetCon(80); var obj2 = CreateObject(VINE, 861, 584, NO_OWNER); obj2->SetCon(70); var obj3 = CreateObject(VINE, 868, 570, NO_OWNER); obj3->SetCon(60); var obj4 = CreateObject(VINE, 1289, 571, NO_OWNER); obj4->SetCon(80); var obj5 = CreateObject(VINE, 1275, 565, NO_OWNER); obj5->SetCon(50); var obj6 = CreateObject(VINE, 1281, 568, NO_OWNER); obj6->SetCon(70); var obj7 = CreateObject(VINE, 1270, 562, NO_OWNER); obj7->SetCon(40); CreateObject(VINE, 1330, 589, NO_OWNER); CreateObject(VINE, 1316, 592, NO_OWNER); var obj8 = CreateObject(VINE, 851, 602, NO_OWNER); obj8->SetCon(90); var obj9 = CreateObject(VINE, 1368, 683, NO_OWNER); obj9->SetCon(70); var obj10 = CreateObject(VINE, 1359, 720, NO_OWNER); obj10->SetCon(70); var obj11 = CreateObject(VINE, 1042, 787, NO_OWNER); obj11->SetCon(70); var obj12 = CreateObject(VINE, 182, 825, NO_OWNER); obj12->SetCon(70); var obj13 = CreateObject(VINE, 177, 825, NO_OWNER); obj13->SetCon(60); var obj14 = CreateObject(VINE, 178, 819, NO_OWNER); obj14->SetCon(60); var obj15 = CreateObject(VINE, 447, 816, NO_OWNER); obj15->SetCon(70); var obj16 = CreateObject(VINE, 451, 819, NO_OWNER); obj16->SetCon(60); var obj17 = CreateObject(VINE, 454, 817, NO_OWNER); obj17->SetCon(40); var obj18 = CreateObject(VINE, 792, 835, NO_OWNER); obj18->SetCon(80); var obj19 = CreateObject(VINE, 825, 812, NO_OWNER); obj19->SetCon(50); var obj20 = CreateObject(VINE, 820, 810, NO_OWNER); obj20->SetCon(70); var obj21 = CreateObject(VINE, 803, 829, NO_OWNER); obj21->SetCon(80); var obj22 = CreateObject(VINE, 1676, 810, NO_OWNER); obj22->SetCon(70); var obj23 = CreateObject(VINE, 1683, 810, NO_OWNER); obj23->SetCon(60); var obj24 = CreateObject(VINE, 1690, 834, NO_OWNER); obj24->SetCon(70); var obj25 = CreateObject(VINE, 1668, 808, NO_OWNER); obj25->SetCon(40); var obj26 = CreateObject(VINE, 1936, 824, NO_OWNER); obj26->SetCon(70); var obj27 = CreateObject(VINE, 1944, 809, NO_OWNER); obj27->SetCon(40); var obj28 = CreateObject(VINE, 1932, 825, NO_OWNER); obj28->SetCon(70); var obj29 = CreateObject(VINE, 1914, 846, NO_OWNER); obj29->SetCon(80); var obj30 = CreateObject(VINE, 194, 867, NO_OWNER); obj30->SetCon(70); var obj31 = CreateObject(VINE, 201, 869, NO_OWNER); obj31->SetCon(60); var obj32 = CreateObject(VINE, 212, 886, NO_OWNER); obj32->SetCon(80); var obj33 = CreateObject(VINE, 382, 879, NO_OWNER); obj33->SetCon(70); CreateObject(VINE, 380, 877, NO_OWNER); CreateObject(VINE, 393, 879, NO_OWNER); CreateObject(VINE, 400, 889, NO_OWNER); var obj34 = CreateObject(VINE, 421, 889, NO_OWNER); obj34->SetCon(70); var obj35 = CreateObject(VINE, 412, 888, NO_OWNER); obj35->SetCon(70); CreateObject(VINE, 738, 893, NO_OWNER); CreateObject(VINE, 738, 873, NO_OWNER); var obj36 = CreateObject(VINE, 1731, 886, NO_OWNER); obj36->SetCon(60); var obj37 = CreateObject(VINE, 1739, 886, NO_OWNER); obj37->SetCon(60); CreateObject(VINE, 1756, 896, NO_OWNER); var obj38 = CreateObject(VINE, 1899, 875, NO_OWNER); obj38->SetCon(70); var obj39 = CreateObject(VINE, 1889, 878, NO_OWNER); obj39->SetCon(70); CreateObject(VINE, 739, 924, NO_OWNER); var obj40 = CreateObject(VINE, 989, 917, NO_OWNER); obj40->SetCon(60); var obj41 = CreateObject(VINE, 981, 917, NO_OWNER); obj41->SetCon(50); CreateObject(VINE, 740, 955, NO_OWNER); } protected func PlaceWood() { var ids = [TRE1, TRE2, TRE3]; for(var i = 0; i <= 12; i++) { PlaceTree(ids[Random(GetLength(ids))], 0, 0, LandscapeWidth()/2, LandscapeHeight()); } for(var i = 0; i <= 12; i++) { PlaceTree(ids[Random(GetLength(ids))], LandscapeWidth()/2, 0, LandscapeWidth()/2, LandscapeHeight()); } } protected func PlaceTree(id tree, x, y, wdt, hgt) { PlaceVegetation(tree, x, y, wdt, hgt, 100000); }
722,239
./clinfinity/Clinfinity.c4f/DUEL_CrumblingIslands.c4s/Pipe.c4d/Script.c
/*-- Pipe --*/ #strict 2 local leaking; protected func Damage() { if(!leaking) { leaking = true; Sound("steam_exhaust", 0, 0, 30, 0, 1); } } protected func Leak() { if(leaking) CreateParticle("Smoke", 50, -140, 0, 50, 190, RGBa(255, 255, 255, 0)); }
722,240
./clinfinity/Clinfinity.c4f/RACE_Pilottraining.c4s/Script.c
/*--- Agility Race ---*/ #strict 2 protected func Initialize() { // ozone SetGamma(RGB(0,0,8), RGB(115,125,125), RGB(255,255,255)); // trailsign CreateObject(SIGN,150,300, NO_OWNER); // Rails CreateObject(RAIL, 30,300, NO_OWNER); CreateObject(RAIL, 90,300, NO_OWNER); CreateObject(RAIL, 120, 300, NO_OWNER); // rotate drafts for(var draft in FindObjects(Find_ID(DRFT))) { draft->SetR(Random(360)); } // Windmill var windmill = CreateObject(WMIL, 850, 50, NO_OWNER); var windmill2 = CreateObject(WMIL, 2000, 10, NO_OWNER); var pump = CreateObject(PUMP, 1260, 10, NO_OWNER); MoveToGround(windmill); MoveToGround(windmill2); MoveToGround(pump); } private func MoveToGround(object obj) { var basement = obj->LocalN("basement"); var bx, by; if(basement) { bx = basement->GetX() - obj->GetX(); by = basement->GetY() - obj->GetY(); // temporarily move basement basement->SetPosition(0, 0); } while(!obj->Stuck()) { obj->SetPosition(obj->GetX(), obj->GetY() + 1); if(obj->GetY() > LandscapeHeight()) { obj->RemoveObject(); return; } } // move basement back if(basement) basement->SetPosition(obj->GetX() + bx, obj->GetY() + by); } // -- Callbacks des Rennen-Spielziels -- // wenn diese Funktionen nicht im Szenarioscript sind // oder 0 zurⁿck geben, wird der Default-Wert verwendet // Race left -> right; additional condition: on top of the golden platform func CheckRACEGoal(int plr) { var cursor = GetCursor(plr); if(cursor && cursor->GetX() > LandscapeWidth() - GetRACEEndOffset() && cursor->GetY() < LandscapeHeight() / 2) return 1; else return -1; } // Richtung: // 1: links -> rechts // 2: rechts -> links // 3: untern -> oben // 4: oben -> unten // default: links -> rechts func GetRACEDirection() { return 1; } // Start: Anzahl an Pixeln, ab dem Rand, von dort beginnt die ZΣhlung // default: 50 px func GetRACEStartOffset() { return 180; } // Ende: Anzahl an Pixeln, ab dem Rand, bis dorthin geht die ZΣhlung // default: 50 px func GetRACEEndOffset() { return 100; } /* Spielerinitialisierung */ protected func InitializePlayer(int plr) { return JoinPlayer(plr); } private func JoinPlayer(int plr) { var clonk = GetCrew(plr); DoEnergy(100000, clonk); SetPosition(10+Random(100), LandscapeHeight()/2-15, clonk); CreateContents(LOAM, clonk); return 1; } /* Neubeitritt */ public func OnClonkDeath(object oldClonk) { var plr = oldClonk -> GetOwner(); if(GetPlayerType(plr)) { var clnk = CreateObject(AVTR, 0, 0, plr); clnk -> GrabObjectInfo(oldClonk); SelectCrew(plr, clnk, 1); Log(RndRelaunchMsg(), GetPlayerName(plr)); return JoinPlayer(plr); } } private func RndRelaunchMsg() { var n = Random(11); if (!n ) return "$MsgDeath1$"; if (!--n) return "$MsgDeath2$"; if (!--n) return "$MsgDeath3$"; if (!--n) return "$MsgDeath4$"; if (!--n) return "$MsgDeath5$"; if (!--n) return "$MsgDeath6$"; if (!--n) return "$MsgDeath7$"; if (!--n) return "$MsgDeath8$"; if (!--n) return "$MsgDeath9$"; if (!--n) return "$MsgDeath10$"; return "$MsgDeath11$"; } public func IsDraftPermanent() { return true; }
722,241
./clinfinity/Clinfinity.c4f/Tutorial_Agility.c4s/Script.c
/*-- Agility Tutorial --*/ #strict 2 // Positions for Relaunch static iPlrX, iPlrY, iCounter; func Initialize() { // Decoration CreateObject(HUT6, 36, 521, NO_OWNER); CreateObject(MUSH, 50, 235, NO_OWNER); CreateObject(MUSH, 80, 235, NO_OWNER); CreateObject(MUSH, 83, 235, NO_OWNER); CreateObject(TRE1, 44, 233, NO_OWNER); ScriptGo(true); } func InitializePlayer(int plr) { GetCrew(plr)->SetPosition(30, 220); // Message positioning //SetPlrShowControlPos(plr, SHOWCTRLPOS_TopLeft); SetTutorialMessagePos(MSG_Top | MSG_Left | MSG_WidthRel | MSG_XRel, 50, 50, 30); SavePosition(); iCounter = 0; } func Script5() { TutorialMessage(Format("$TutHelloWorld$", GetPlayerName())); } func Script15() { //SetPlrShowControl(0, "____4_678_ __________"); Sound("Ding"); TutorialMessage("$TutDoubleJump$"); } func Script35() { TutorialMessage("$TutDoubleJumpAdvise$"); SetArrow(180, 60); Sound("Ding"); } func Script40() { if(!FindObject(AVTR, 160, 50 , 30, 20)) { goto(39); return; } SavePosition(); TutorialMessage("$TutNice$"); Sound("Applause"); RemoveArrow(); } func Script50() { TutorialMessage("$TutFlyAdvise$"); SetArrow(650, 350); Sound("Ding"); } func Script60() { if(!FindObject(AVTR, 610, 340 , 60, 50)) { goto(59); return; } SavePosition(); TutorialMessage("$TutNotBad$"); RemoveArrow(); } func Script70() { TutorialMessage("$TutIntroduceDraft$"); var Draft = CreateObject(DRFT, 700, 330, NO_OWNER); Draft->SetPermanent(); Sound("Wind2"); SetArrow(790, 90); } func Script80() { if(!FindObject(AVTR, 750, 80 , 50, 25)) { goto(79); return; } SavePosition(); TutorialMessage("$TutDraftNotice$"); AddEffect("GraniteCheck", 0, 100, 5); RemoveArrow(); } global func FxGraniteCheckTimer(object target, int effectNum, int effectTime) { if(!FindObject(AVTR, 1000, 390 , 60, 30)) { var clonk = FindObject2(Find_OCF(OCF_CrewMember), Find_InRect(825, 0, 500, 400), Find_Not(Find_Or(Find_Action("Jump"), Find_Action("Tumble")))); if(clonk) clonk->Kill(); } else { ScriptGo(1); return -1; } } func Script109() { TutorialMessage("$TutGraniteIsAcid$"); ScriptGo(0); } func Script110() { SavePosition(); TutorialMessage("$TutDone$"); Sound("Applause"); GetCrew()->AddHat(HAT1); // Reward! } func Script120() { FindObject(SCRG)->Fulfill(); } func SavePosition() { // Position for Relaunch var clonk = GetCrew(); iPlrX = clonk->GetX(); iPlrY = clonk->GetY(); } func RelaunchPlayer(iPlr) { // Comment Sound("Oops"); // new Clonk var old = FindObject(AVTR); if (!old->GetAlive()) { var pClonk = CreateObject(AVTR, iPlrX, iPlrY, iPlr); pClonk->GrabObjectInfo(old); SetCursor(iPlr, pClonk); } }
722,242
./clinfinity/Clinfinity.c4f/Tutorial_Agility.c4s/ScriptGoal.c4d/Script.c
/*-- Scriptdefiniertes Spielziel --*/ #strict #include GOAL local goalFulfilled; public func IsFulfilled() { return(goalFulfilled); } public func Fulfill() { goalFulfilled = 1; } protected func Activate(iPlayer) { return(MessageWindow(GetDesc(), iPlayer)); }
722,243
./chan-sccp-b/contrib/gen_sccpconf/gen_sccpconf.c
/*! * \file gen_sccpconf.c * \brief SCCP Config Generator Class * \author Diederik de Groot <ddegroot [at] sf.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-11-17 18:10:34 +0100 (Wed, 17 Nov 2010) $ * $Revision: 2154 $ */ //#include <asterisk/paths.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <time.h> #include <sys/time.h> #include "../../src/config.h" #include "gen_sccpconf.h" #define CONFIG_TYPE_ALL 0 #define CONFIG_TYPE_DEFAULTS 1 #define CONFIG_TYPE_TEMPLATED 2 #define CONFIG_TYPE_SHORT 3 #define CONFIG_TYPE_XML 4 #define CONFIG_TYPE_MYSQL 5 #define CONFIG_TYPE_SQLITE 6 #define CONFIG_TYPE_POSTGRES 7 //#define CONFIG_TYPE_JSON 5 char *replace(const char *s, const char *old, const char *new); static int sccp_config_generate(const char *filename, size_t sizeof_filename, int config_type) { const SCCPConfigSegment *sccpConfigSegment = NULL; const SCCPConfigOption *config = NULL; long unsigned int sccp_option; long unsigned int segment; char *description; char *description_part; char name_and_value[100]; int linelen = 0; boolean_t add_primary_key = FALSE; // snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, "sccp.conf.test"); printf("info:" "Creating new config file '%s'\n", filename); FILE *f; if (!(f = fopen(filename, "w"))) { printf("error:" "Error creating new config file \n"); return 1; } char date[256] = ""; time_t t; time(&t); strncpy(date, ctime(&t), sizeof(date)); if (CONFIG_TYPE_MYSQL == config_type || CONFIG_TYPE_SQLITE == config_type || CONFIG_TYPE_POSTGRES == config_type) { int first_column_printed = 0; fprintf(f, "/*\n"); fprintf(f, " * Automatically generated configuration file\n"); fprintf(f, " * Filename: %s\n", filename); fprintf(f, " * Generator: gen_sccpconf\n"); fprintf(f, " * Creation Date: %s", date); fprintf(f, " * Version: %s\n", SCCP_VERSION); fprintf(f, " * Revision: %s\n", SCCP_REVISION); fprintf(f, " * SQLType: %s\n", (CONFIG_TYPE_MYSQL == config_type) ? "Mysql" : ((CONFIG_TYPE_SQLITE == config_type) ? "SqlLite" : "Postgresql")); fprintf(f, " */\n"); switch(config_type) { case CONFIG_TYPE_MYSQL: fprintf(f, "DROP VIEW IF EXISTS sccpdeviceconfig;\n"); fprintf(f, "DROP TABLE IF EXISTS buttonconfig;\n"); break; case CONFIG_TYPE_SQLITE: fprintf(f, "PRAGMA auto_vacuum=2;\n"); fprintf(f, "DROP VIEW IF EXISTS sccpdeviceconfig;\n"); fprintf(f, "DROP TABLE IF EXISTS buttonconfig;\n"); fprintf(f, "DROP TABLE IF EXISTS buttontype;\n"); break; case CONFIG_TYPE_POSTGRES: fprintf(f, "DROP VIEW IF EXISTS sccpdeviceconfig;\n"); fprintf(f, "DROP TABLE IF EXISTS buttonconfig;\n"); fprintf(f, "DROP TYPE IF EXISTS buttontype;\n"); break; } for (segment = SCCP_CONFIG_GLOBAL_SEGMENT; segment <= SCCP_CONFIG_SOFTKEY_SEGMENT; segment++) { sccpConfigSegment = sccp_find_segment(segment); printf("info:" "adding [%s] section\n", sccpConfigSegment->name); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- %s\n", sccpConfigSegment->name); fprintf(f, "--\n"); fprintf(f, "DROP TABLE IF EXISTS sccp%s;\n", sccpConfigSegment->name); // optional fprintf(f, "CREATE TABLE IF NOT EXISTS sccp%s (\n", sccpConfigSegment->name); config = sccpConfigSegment->config; add_primary_key = FALSE; for (sccp_option = 0; sccp_option < sccpConfigSegment->config_size; sccp_option++) { if (!strcmp(config[sccp_option].name,"name")) { add_primary_key = TRUE; } if ((config[sccp_option].flags & SCCP_CONFIG_FLAG_IGNORE & SCCP_CONFIG_FLAG_DEPRECATED & SCCP_CONFIG_FLAG_OBSOLETE) == 0) { printf("info:" "adding name: %s, default_value: %s\n", config[sccp_option].name, config[sccp_option].defaultValue); if (!strcmp(config[sccp_option].name,"button")) { // Will be replaced by view printf("info:" "skipping\n"); continue; } if (!first_column_printed) { fprintf(f, " %s", config[sccp_option].name); first_column_printed = 1; } else { fprintf(f, ",\n %s", config[sccp_option].name); } if (config[sccp_option].type) { switch (config[sccp_option].type) { case SCCP_CONFIG_DATATYPE_BOOLEAN: if (CONFIG_TYPE_MYSQL == config_type) { fprintf(f, " ENUM('yes','no')"); } else { fprintf(f, " BOOLEAN"); } if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { fprintf(f, " DEFAULT '%s'", config[sccp_option].defaultValue); } break; case SCCP_CONFIG_DATATYPE_INT: fprintf(f, " INT"); if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { fprintf(f, " DEFAULT %d", atoi(config[sccp_option].defaultValue)); } break; case SCCP_CONFIG_DATATYPE_UINT: if (CONFIG_TYPE_POSTGRES == config_type) { fprintf(f, " INT"); } else { fprintf(f, " INT UNSIGNED"); } if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { fprintf(f, " DEFAULT %d", atoi(config[sccp_option].defaultValue)); } break; case SCCP_CONFIG_DATATYPE_STRINGPTR: case SCCP_CONFIG_DATATYPE_STRING: if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { fprintf(f, " VARCHAR(%d)", strlen(config[sccp_option].defaultValue) > 45 ? (int) strlen(config[sccp_option].defaultValue) * 2 : 45); fprintf(f, " DEFAULT '%s'", config[sccp_option].defaultValue); } else { fprintf(f, " VARCHAR(%d)", 45); } break; case SCCP_CONFIG_DATATYPE_PARSER: fprintf(f, " VARCHAR(45)"); /* if (((config[sccp_option].flags & SCCP_CONFIG_FLAG_MULTI_ENTRY) == SCCP_CONFIG_FLAG_MULTI_ENTRY)) { fprintf(f, " SET(%s)\n", config[sccp_option].generic_parser); } else { fprintf(f, " ENUM(%s)", config[sccp_option].generic_parser); } */ // fprintf(f, " <generic_parser>%s</generic_parser>\n", config[sccp_option].generic_parser); break; case SCCP_CONFIG_DATATYPE_CHAR: fprintf(f, " CHAR(1)"); if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { fprintf(f, " DEFAULT '%-1s'", config[sccp_option].defaultValue); } break; } } fprintf(f, " %s", ((config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) == SCCP_CONFIG_FLAG_REQUIRED) ? "NOT NULL" : ""); if (strlen(config[sccp_option].description) != 0) { if (CONFIG_TYPE_MYSQL == config_type) { if (CONFIG_TYPE_MYSQL == config_type) { fprintf(f, " COMMENT '"); } else if (CONFIG_TYPE_SQLITE == config_type) { fprintf(f, " -- '"); } description = malloc(sizeof(char) * strlen(config[sccp_option].description)); description = strdup(config[sccp_option].description); while ((description_part = strsep(&description, "\n"))) { if (description_part && strlen(description_part) != 0) { fprintf(f, " %s ", replace(description_part, "'", "\\'")); } } fprintf(f, "'"); } } } } if (add_primary_key) { if (CONFIG_TYPE_POSTGRES == config_type) { fprintf(f, ",\n PRIMARY KEY (name)"); } else { fprintf(f, ",\n PRIMARY KEY (name ASC)"); } } if (CONFIG_TYPE_MYSQL == config_type) { fprintf(f, "\n) ENGINE=INNODB DEFAULT CHARSET=latin1;\n"); } else { fprintf(f, "\n);\n"); } first_column_printed = 0; } fprintf(f, "\n"); switch(config_type) { case CONFIG_TYPE_MYSQL: fprintf(f, "--\n"); fprintf(f, "-- Table for device's button-configuration\n"); fprintf(f, "--\n"); fprintf(f, "CREATE TABLE IF NOT EXISTS buttonconfig (\n"); fprintf(f, " device varchar(15) NOT NULL default '',\n"); fprintf(f, " instance tinyint(4) NOT NULL default '0',\n"); fprintf(f, " type enum('line','speeddial','service','feature','empty') NOT NULL default 'line',\n"); fprintf(f, " name varchar(36) default NULL,\n"); fprintf(f, " options varchar(100) default NULL,\n"); fprintf(f, " PRIMARY KEY (`device`,`instance`),\n"); fprintf(f, " KEY `device` (`device`),\n"); fprintf(f, " FOREIGN KEY (`device`) REFERENCES sccpdevice(`name`) ON DELETE CASCADE ON UPDATE CASCADE\n"); fprintf(f, ") ENGINE=INNODB DEFAULT CHARSET=latin1;\n"); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- View for merging device and button configuration\n"); fprintf(f, "--\n"); fprintf(f, "CREATE \n"); fprintf(f, "ALGORITHM = MERGE\n"); fprintf(f, "VIEW sccpdeviceconfig AS\n"); fprintf(f, " SELECT GROUP_CONCAT( CONCAT_WS( ',', buttonconfig.type, buttonconfig.name, buttonconfig.options )\n"); fprintf(f, " ORDER BY instance ASC\n"); fprintf(f, " SEPARATOR ';' ) AS button, sccpdevice.*\n"); fprintf(f, " FROM sccpdevice\n"); fprintf(f, " LEFT JOIN buttonconfig ON ( buttonconfig.device = sccpdevice.name )\n"); fprintf(f, " GROUP BY sccpdevice.name;\n"); break; case CONFIG_TYPE_SQLITE: fprintf(f, "CREATE TABLE buttontype (\n"); fprintf(f, " type varchar(9) DEFAULT NULL,\n"); fprintf(f, " PRIMARY KEY (type)\n"); fprintf(f, ");\n"); fprintf(f, "INSERT INTO buttontype (type) VALUES ('line');\n"); fprintf(f, "INSERT INTO buttontype (type) VALUES ('speeddial');\n"); fprintf(f, "INSERT INTO buttontype (type) VALUES ('service');\n"); fprintf(f, "INSERT INTO buttontype (type) VALUES ('feature');\n"); fprintf(f, "INSERT INTO buttontype (type) VALUES ('empty');\n"); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- Table with button-configuration for device\n"); fprintf(f, "--\n"); fprintf(f, "CREATE TABLE buttonconfig (\n"); fprintf(f, " device varchar(15) NOT NULL DEFAULT '',\n"); fprintf(f, " instance tinyint(4) NOT NULL DEFAULT '0',\n"); fprintf(f, " type varchar(9),\n"); fprintf(f, " name varchar(36) DEFAULT NULL,\n"); fprintf(f, " options varchar(100) DEFAULT NULL,\n"); fprintf(f, " PRIMARY KEY (device,instance),\n"); fprintf(f, " FOREIGN KEY (device) REFERENCES sccpdevice (device),\n"); fprintf(f, " FOREIGN KEY (type) REFERENCES buttontype (type) \n"); fprintf(f, ");\n"); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- View for merging device and button configuration\n"); fprintf(f, "--\n"); fprintf(f, "CREATE VIEW sccpdeviceconfig AS \n"); fprintf(f, "SELECT sccpdevice.*, \n"); fprintf(f, " group_concat(buttonconfig.type||\",\"||buttonconfig.name||\",\"||buttonconfig.options,\";\") as button \n"); fprintf(f, "FROM buttonconfig, sccpdevice \n"); fprintf(f, "WHERE buttonconfig.device=sccpdevice.name \n"); fprintf(f, "ORDER BY instance;\n"); break; case CONFIG_TYPE_POSTGRES: fprintf(f, "--\n"); fprintf(f, "-- Create buttontype\n"); fprintf(f, "--\n"); fprintf(f, "CREATE TYPE buttontype AS ENUM ('line','speeddial','service','feature','empty');\n"); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- Table with button-configuration for device\n"); fprintf(f, "--\n"); fprintf(f, "CREATE TABLE buttonconfig(\n"); fprintf(f, " device character varying(15) NOT NULL,\n"); fprintf(f, " instance integer NOT NULL DEFAULT 0,\n"); fprintf(f, " \"type\" buttontype NOT NULL DEFAULT 'line'::buttontype,\n"); fprintf(f, " \"name\" character varying(36) DEFAULT NULL::character varying,\n"); fprintf(f, " options character varying(100) DEFAULT NULL::character varying,\n"); fprintf(f, " CONSTRAINT buttonconfig_pkey PRIMARY KEY (device, instance),\n"); fprintf(f, " CONSTRAINT device FOREIGN KEY (device)\n"); fprintf(f, " REFERENCES sccpdevice (\"name\") MATCH SIMPLE\n"); fprintf(f, " ON UPDATE NO ACTION ON DELETE NO ACTION\n"); fprintf(f, ");\n"); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- textcat_column helper for sccpdeviceconfig\n"); fprintf(f, "--\n"); fprintf(f, "DROP AGGREGATE IF EXISTS textcat_column(\"text\");\n"); fprintf(f, "CREATE AGGREGATE textcat_column(\"text\") (\n"); fprintf(f, " SFUNC=textcat,\n"); fprintf(f, " STYPE=text\n"); fprintf(f, ");\n"); fprintf(f, "\n"); fprintf(f, "--\n"); fprintf(f, "-- View for device's button-configuration\n"); fprintf(f, "--\n"); fprintf(f, "CREATE VIEW sccpdeviceconfig AS\n"); fprintf(f, "SELECT \n"); fprintf(f, " (SELECT textcat_column(bc.type || ',' || bc.name || COALESCE(',' || bc.options, '') || ';') FROM (SELECT * FROM buttonconfig WHERE device=sccpdevice.name ORDER BY instance) bc ) as button, \n"); fprintf(f, " sccpdevice.*\n"); fprintf(f, "FROM sccpdevice;\n"); break; } } else if (CONFIG_TYPE_XML == config_type) { fprintf(f, "<?xml version=\"1.0\"?>\n"); fprintf(f, "<sccp>\n"); fprintf(f, " <version>%s</version>\n", SCCP_VERSION); fprintf(f, " <revision>%s</revision>\n", SCCP_REVISION); for (segment = SCCP_CONFIG_GLOBAL_SEGMENT; segment <= SCCP_CONFIG_SOFTKEY_SEGMENT; segment++) { sccpConfigSegment = sccp_find_segment(segment); printf("info:" "adding [%s] section\n", sccpConfigSegment->name); fprintf(f, " <section name=\"%s\">\n", sccpConfigSegment->name); fprintf(f, " <params>\n"); config = sccpConfigSegment->config; for (sccp_option = 0; sccp_option < sccpConfigSegment->config_size; sccp_option++) { if ((config[sccp_option].flags & SCCP_CONFIG_FLAG_IGNORE & SCCP_CONFIG_FLAG_DEPRECATED & SCCP_CONFIG_FLAG_OBSOLETE) == 0) { printf("info:" "adding name: %s, default_value: %s\n", config[sccp_option].name, config[sccp_option].defaultValue); fprintf(f, " <param name=\"%s\">\n", config[sccp_option].name); fprintf(f, " <required>%d</required>\n", ((config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) == SCCP_CONFIG_FLAG_REQUIRED) ? 1 : 0); if (((config[sccp_option].flags & SCCP_CONFIG_FLAG_MULTI_ENTRY) == SCCP_CONFIG_FLAG_MULTI_ENTRY)) { fprintf(f, " <multiple>1</multiple>\n"); } if (config[sccp_option].type) { switch (config[sccp_option].type) { case SCCP_CONFIG_DATATYPE_BOOLEAN: fprintf(f, " <type>boolean</type>\n"); break; case SCCP_CONFIG_DATATYPE_INT: fprintf(f, " <type>int</type>\n"); fprintf(f, " <size>8</size>\n"); break; case SCCP_CONFIG_DATATYPE_UINT: fprintf(f, " <type>unsigned int</type>\n"); fprintf(f, " <size>8</size>\n"); break; case SCCP_CONFIG_DATATYPE_STRING: fprintf(f, " <type>string</type>\n"); fprintf(f, " <size>45</size>\n"); break; case SCCP_CONFIG_DATATYPE_PARSER: fprintf(f, " <type>generic</type>\n"); fprintf(f, " <generic_parser>%s</generic_parser>\n", config[sccp_option].generic_parser); break; case SCCP_CONFIG_DATATYPE_STRINGPTR: fprintf(f, " <type>string</type>\n"); fprintf(f, " <size>45</size>\n"); break; case SCCP_CONFIG_DATATYPE_CHAR: fprintf(f, " <type>char</type>\n"); break; } } if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { fprintf(f, " <default>%s</default>\n", config[sccp_option].defaultValue); } if (strlen(config[sccp_option].description) != 0) { fprintf(f, " <description>"); description = malloc(sizeof(char) * strlen(config[sccp_option].description)); description = strdup(config[sccp_option].description); while ((description_part = strsep(&description, "\n"))) { if (description_part && strlen(description_part) != 0) { fprintf(f, "%s ", replace(description_part, "'", "\\'")); } } fprintf(f, "</description>\n"); } fprintf(f, " </param>\n"); } } fprintf(f, " </params>\n"); fprintf(f, " </section>\n"); } fprintf(f, "</sccp>\n"); } else { fprintf(f, ";!\n"); fprintf(f, ";! Automatically generated configuration file\n"); fprintf(f, ";! Filename: %s\n", filename); fprintf(f, ";! Generator: sccp config generate\n"); fprintf(f, ";! Creation Date: %s", date); fprintf(f, ";!\n"); fprintf(f, "\n"); for (segment = SCCP_CONFIG_GLOBAL_SEGMENT; segment <= SCCP_CONFIG_SOFTKEY_SEGMENT; segment++) { sccpConfigSegment = sccp_find_segment(segment); printf("info:" "adding [%s] section\n", sccpConfigSegment->name); switch (segment) { case SCCP_CONFIG_DEVICE_SEGMENT: if (CONFIG_TYPE_TEMPLATED == config_type) { fprintf(f, "\n;\n; %s section\n;\n[%s_template](!) ; create new template\n", sccpConfigSegment->name, sccpConfigSegment->name); } else { fprintf(f, "\n;\n; %s section\n;\n[SEP0123456789]\n", sccpConfigSegment->name); } break; case SCCP_CONFIG_LINE_SEGMENT: if (CONFIG_TYPE_TEMPLATED == config_type) { fprintf(f, "\n;\n; %s section\n;\n[%s_template](!) ; create new template\n", sccpConfigSegment->name, sccpConfigSegment->name); } else { fprintf(f, "\n;\n; %s section\n;\n[1234]\n", sccpConfigSegment->name); } break; default: fprintf(f, "\n;\n; %s section\n;\n[%s]\n", sccpConfigSegment->name, sccpConfigSegment->name); break; } config = sccpConfigSegment->config; for (sccp_option = 0; sccp_option < sccpConfigSegment->config_size; sccp_option++) { if ((config[sccp_option].flags & SCCP_CONFIG_FLAG_IGNORE & SCCP_CONFIG_FLAG_DEPRECATED & SCCP_CONFIG_FLAG_OBSOLETE) == 0) { if (config[sccp_option].name && strlen(config[sccp_option].name) != 0) { switch (config_type) { case CONFIG_TYPE_ALL: break; case CONFIG_TYPE_DEFAULTS: if ((((config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) != SCCP_CONFIG_FLAG_REQUIRED) && (!config[sccp_option].defaultValue || strlen(config[sccp_option].defaultValue) == 0)) && strcmp(config[sccp_option].name, "type")) { continue; } break; case CONFIG_TYPE_TEMPLATED: if ((!config[sccp_option].defaultValue || strlen(config[sccp_option].defaultValue) == 0) && strcmp(config[sccp_option].name, "type")) { continue; } break; case CONFIG_TYPE_SHORT: // SHORT if ((((config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) != SCCP_CONFIG_FLAG_REQUIRED) && ((!config[sccp_option].defaultValue || !strcmp(config[sccp_option].defaultValue, "(null)")) && strcmp(config[sccp_option].name, "type")))) { printf("info:" "skipping name: %s, required = %s\n", config[sccp_option].name, ((config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) != SCCP_CONFIG_FLAG_REQUIRED) ? "no" : "yes"); continue; } break; } printf("info:" "adding name: %s, default_value: %s\n", config[sccp_option].name, config[sccp_option].defaultValue); if (config[sccp_option].defaultValue && !strlen(config[sccp_option].defaultValue) == 0) { snprintf(name_and_value, sizeof(name_and_value), "%s = %s", config[sccp_option].name, config[sccp_option].defaultValue); } else { snprintf(name_and_value, sizeof(name_and_value), "%s = \"\"", config[sccp_option].name); } linelen = (int) strlen(name_and_value); fprintf(f, "%s", name_and_value); if (config_type < CONFIG_TYPE_TEMPLATED && config[sccp_option].description && strlen(config[sccp_option].description) != 0) { description = malloc(sizeof(char) * strlen(config[sccp_option].description)); description = strdup(config[sccp_option].description); while ((description_part = strsep(&description, "\n"))) { if (description_part && strlen(description_part) != 0) { fprintf(f, "%*.s ; %s%s%s\n", 81 - linelen, " ", (config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) == SCCP_CONFIG_FLAG_REQUIRED ? "(REQUIRED) " : "", ((config[sccp_option].flags & SCCP_CONFIG_FLAG_MULTI_ENTRY) == SCCP_CONFIG_FLAG_MULTI_ENTRY) ? "(MULTI-ENTRY) " : "", description_part); linelen = 0; } } } else { fprintf(f, "\n"); } } else { printf("error:" "Error creating new variable structure for %s='%s'\n", config[sccp_option].name, config[sccp_option].defaultValue); return 2; } } } printf("\n"); if (CONFIG_TYPE_TEMPLATED == config_type) { // make up two devices and two lines if (SCCP_CONFIG_DEVICE_SEGMENT == segment) { fprintf(f, "\n"); fprintf(f, "[SEP001B535CD5E4](device_template) ; use template 'device_template'\n"); fprintf(f, "description=sample1\n"); fprintf(f, "devicetype=7960\n"); fprintf(f, "button=line, 110\n"); fprintf(f, "button=line, 200@01:_SharedLine\n"); fprintf(f, "\n"); fprintf(f, "[SEP0024C4444763](device_template) ; use template 'device_template'\n"); fprintf(f, "description=sample1\n"); fprintf(f, "devicetype=7962\n"); fprintf(f, "button=line, 111\n"); fprintf(f, "button=line, 200@02:_SharedLine\n"); fprintf(f, "\n"); } if (SCCP_CONFIG_LINE_SEGMENT == segment) { fprintf(f, "\n"); fprintf(f, "[110](line_template) ; use template 'line_template'\n"); fprintf(f, "id=110\n"); fprintf(f, "label=sample_110\n"); fprintf(f, "description=sampleline_110\n"); fprintf(f, "cid_num=110\n"); fprintf(f, "cid_name=user110\n"); fprintf(f, "\n"); fprintf(f, "[111](line_template) ; use template 'line_template'\n"); fprintf(f, "id=111\n"); fprintf(f, "label=sample_111\n"); fprintf(f, "description=sampleline_111\n"); fprintf(f, "cid_num=111\n"); fprintf(f, "cid_name=user111\n"); fprintf(f, "\n"); fprintf(f, "[200](line_template) ; use template 'line_template'\n"); fprintf(f, "id=200\n"); fprintf(f, "label=sample_share\n"); fprintf(f, "description=sharedline\n"); fprintf(f, "cid_num=200\n"); fprintf(f, "cid_name=shared\n"); fprintf(f, "\n"); } } } } fclose(f); return 0; } char *replace(const char *s, const char *old, const char *new) { char *ret; int i, count = 0; size_t newlen = strlen(new); size_t oldlen = strlen(old); for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], old) == &s[i]) { count++; i += oldlen - 1; } } ret = malloc(i + count * (newlen - oldlen)); if (ret == NULL) exit(EXIT_FAILURE); i = 0; while (*s) { if (strstr(s, old) == s) { strcpy(&ret[i], new); i += newlen; s += oldlen; } else ret[i++] = *s++; } ret[i] = '\0'; return ret; } int main(int argc, char *argv[]) { char *config_file = ""; int config_type = 0; if (argc > 2) { config_file = malloc(sizeof(char *) * strlen(argv[1]) + 1); config_file = strdup(argv[1]); if (!strcasecmp(argv[2], "ALL")) { config_type = CONFIG_TYPE_ALL; } else if (!strcasecmp(argv[2], "DEFAULTS")) { config_type = CONFIG_TYPE_DEFAULTS; } else if (!strcasecmp(argv[2], "TEMPLATED")) { config_type = CONFIG_TYPE_TEMPLATED; } else if (!strcasecmp(argv[2], "SHORT")) { config_type = CONFIG_TYPE_SHORT; } else if (!strcasecmp(argv[2], "XML")) { config_type = CONFIG_TYPE_XML; } else if (!strcasecmp(argv[2], "MYSQL")) { config_type = CONFIG_TYPE_MYSQL; } else if (!strcasecmp(argv[2], "SQLITE")) { config_type = CONFIG_TYPE_SQLITE; } else if (!strcasecmp(argv[2], "POSTGRES")) { config_type = CONFIG_TYPE_POSTGRES; } else { printf("\nERROR: Unknown Type Specified: %s !!\n\n", argv[2]); goto USAGE; } } else { USAGE: printf("Usage: gen_sccpconf <config filename> <conf_type>\n"); printf(" where conf_type is one of: (ALL | DEFAULTS | TEMPLATED | SHORT | XML | MYSQL | SQLITE | POSTGRES)\n"); return 1; } return sccp_config_generate(config_file, sizeof(config_file), config_type); }
722,244
./chan-sccp-b/src/sccp_config.c
/*! * \file sccp_config.c * \brief SCCP Config Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \note To find out more about the reload function see \ref sccp_config_reload * \remarks Only methods directly related to chan-sccp configuration should be stored in this source file. * * $Date: 2010-11-17 18:10:34 +0100 (Wed, 17 Nov 2010) $ * $Revision: 2154 $ */ /*! * \section sccp_config Loading sccp.conf/realtime configuration implementation * * \subsection sccp_config_reload How was the new cli command "sccp reload" implemented * * sccp_cli.c * - new implementation of cli reload command * - checks if no other reload command is currently running * - starts loading global settings from sccp.conf (sccp_config_general) * - starts loading devices and lines from sccp.conf(sccp_config_readDevicesLines) * . * . * * sccp_config.c * - modified sccp_config_general * * - modified sccp_config_readDevicesLines * - sets pendingDelete for * - devices (via sccp_device_pre_reload), * - lines (via sccp_line_pre_reload) * - softkey (via sccp_softkey_pre_reload) * . * - calls sccp_config_buildDevice as usual * - calls sccp_config_buildDevice as usual * - find device * - or create new device * - parses sccp.conf for device * - set defaults for device if necessary using the default from globals using the same parameter name * - set pendingUpdate on device for parameters marked with SCCP_CONFIG_NEEDDEVICERESET (remove pendingDelete) * . * - calls sccp_config_buildLine as usual * - find line * - or create new line * - parses sccp.conf for line * - set defaults for line if necessary using the default from globals using the same parameter name * - set pendingUpdate on line for parameters marked with SCCP_CONFIG_NEEDDEVICERESET (remove pendingDelete) * . * - calls sccp_config_softKeySet as usual *** * - find softKeySet * - or create new softKeySet * - parses sccp.conf for softKeySet * - set pendingUpdate on softKetSet for parameters marked with SCCP_CONFIG_NEEDDEVICERESET (remove pendingDelete) * . * . * - checks pendingDelete and pendingUpdate for * - skip when call in progress * - devices (via sccp_device_post_reload), * - resets GLOB(device) if pendingUpdate * - removes GLOB(devices) with pendingDelete * . * - lines (via sccp_line_post_reload) * - resets GLOB(lines) if pendingUpdate * - removes GLOB(lines) with pendingDelete * . * - softkey (via sccp_softkey_post_reload) *** * - resets GLOB(softkeyset) if pendingUpdate *** * - removes GLOB(softkeyset) with pendingDelete *** * . * . * . * channel.c * - sccp_channel_endcall *** * - reset device if still device->pendingUpdate,line->pendingUpdate or softkeyset->pendingUpdate * . * . * * lines marked with "***" still need be implemented * */ #include <config.h> #include "common.h" #include <asterisk/paths.h> SCCP_FILE_VERSION(__FILE__, "$Revision: 2154 $") #ifndef offsetof #if defined(__GNUC__) && __GNUC__ > 3 #define offsetof(type, member) __builtin_offsetof (type, member) #else #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #endif #endif #ifndef offsetof #endif #define offsize(TYPE, MEMBER) sizeof(((TYPE *)0)->MEMBER) #define G_OBJ_REF(x) offsetof(struct sccp_global_vars,x), offsize(struct sccp_global_vars,x) #define D_OBJ_REF(x) offsetof(struct sccp_device,x), offsize(struct sccp_device,x) #define L_OBJ_REF(x) offsetof(struct sccp_line,x), offsize(struct sccp_line,x) #define S_OBJ_REF(x) offsetof(struct softKeySetConfiguration,x), offsize(struct softKeySetConfiguration,x) #define H_OBJ_REF(x) offsetof(struct sccp_hotline,x), offsize(struct sccp_hotline,x) #define BITMASK(b) (1 << ((b) % CHAR_BIT)) #define BITSLOT(b) ((b) / CHAR_BIT) #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b)) #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b)) #define BITTOGGLE(a, b) ((a)[BITSLOT(b)] ^= BITMASK(b)) /*! * \brief Enum for Config Option Types */ enum SCCPConfigOptionType { /* *INDENT-OFF* */ SCCP_CONFIG_DATATYPE_BOOLEAN = 1 << 0, SCCP_CONFIG_DATATYPE_INT = 1 << 1, SCCP_CONFIG_DATATYPE_UINT = 1 << 2, SCCP_CONFIG_DATATYPE_STRING = 1 << 3, SCCP_CONFIG_DATATYPE_PARSER = 1 << 4, SCCP_CONFIG_DATATYPE_STRINGPTR = 1 << 5, /* string pointer */ SCCP_CONFIG_DATATYPE_CHAR = 1 << 6, /* *INDENT-ON* */ }; /*! * \brief Enum for Config Option Flags */ enum SCCPConfigOptionFlag { /* *INDENT-OFF* */ SCCP_CONFIG_FLAG_IGNORE = 1 << 0, /*< ignore parameter */ SCCP_CONFIG_FLAG_NONE = 1 << 1, /*< ignore parameter */ SCCP_CONFIG_FLAG_DEPRECATED = 1 << 2, /*< parameter is deprecated and should not be used anymore, warn user and still set variable */ SCCP_CONFIG_FLAG_OBSOLETE = 1 << 3, /*< parameter is now obsolete warn user and skip */ SCCP_CONFIG_FLAG_CHANGED = 1 << 4, /*< parameter implementation has changed, warn user */ SCCP_CONFIG_FLAG_REQUIRED = 1 << 5, /*< parameter is required */ SCCP_CONFIG_FLAG_GET_DEVICE_DEFAULT = 1 << 6, /*< retrieve default value from device */ SCCP_CONFIG_FLAG_GET_GLOBAL_DEFAULT = 1 << 7, /*< retrieve default value from global */ SCCP_CONFIG_FLAG_MULTI_ENTRY = 1 << 8, /*< multi entries allowed */ /* *INDENT-ON* */ }; /*! * \brief SCCP Config Option Struct */ typedef struct SCCPConfigOption { /* *INDENT-OFF* */ const char *name; /*!< Configuration Parameter Name */ const int offset; /*!< The offset relative to the context structure where the option value is stored. */ const size_t size; /*!< Structure size */ enum SCCPConfigOptionType type; /*!< Data type */ sccp_value_changed_t(*converter_f) (void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); /*!< Conversion function */ uint32_t(*str2enumval) (const char *str); /*!< generic convertor used for parsing OptionType: SCCP_CONFIG_DATATYPE_ENUM */ const char *(*enumkeys) (void); /*!< reverse convertor used for parsing OptionType: SCCP_CONFIG_DATATYPE_ENUM, to retrieve all possible values allowed */ enum SCCPConfigOptionFlag flags; /*!< Data type */ sccp_configurationchange_t change; /*!< Does a change of this value needs a device restart */ const char *defaultValue; /*!< Default value */ const char *description; /*!< Configuration description (config file) or warning message for deprecated or obsolete values */ /* *INDENT-ON* */ } SCCPConfigOption; //converter function prototypes sccp_value_changed_t sccp_config_parse_codec_preferences(void *dest, const size_t size, const char *value, const boolean_t allow, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_allow_codec(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_disallow_codec(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_mailbox(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_tos(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_cos(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_amaflags(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_secondaryDialtoneDigits(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_variables(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_group(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_permit(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_deny(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_button(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_permithosts(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_addons(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_privacyFeature(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_earlyrtp(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_dtmfmode(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_mwilamp(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_debug(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_ipaddress(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_port(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_blindtransferindication(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_callanswerorder(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_context(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_hotline_context(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_hotline_exten(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_jbflags_enable(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_jbflags_force(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); sccp_value_changed_t sccp_config_parse_jbflags_log(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment); #include "sccp_config_entries.hh" /*! * \brief SCCP Config Option Struct */ typedef struct SCCPConfigSegment { const char *name; const sccp_config_segment_t segment; const SCCPConfigOption *config; long unsigned int config_size; } SCCPConfigSegment; /*! * \brief SCCP Config Option Struct Initialization */ static const SCCPConfigSegment sccpConfigSegments[] = { {"general", SCCP_CONFIG_GLOBAL_SEGMENT, sccpGlobalConfigOptions, ARRAY_LEN(sccpGlobalConfigOptions)}, {"device", SCCP_CONFIG_DEVICE_SEGMENT, sccpDeviceConfigOptions, ARRAY_LEN(sccpDeviceConfigOptions)}, {"line", SCCP_CONFIG_LINE_SEGMENT, sccpLineConfigOptions, ARRAY_LEN(sccpLineConfigOptions)}, {"softkey", SCCP_CONFIG_SOFTKEY_SEGMENT, sccpSoftKeyConfigOptions, ARRAY_LEN(sccpSoftKeyConfigOptions)}, }; /*! * \brief Find of SCCP Config Options */ //static const SCCPConfigOption *sccp_find_segment(const sccp_config_segment_t segment) static const SCCPConfigSegment *sccp_find_segment(const sccp_config_segment_t segment) { uint8_t i = 0; for (i = 0; i < ARRAY_LEN(sccpConfigSegments); i++) { if (sccpConfigSegments[i].segment == segment) return &sccpConfigSegments[i]; } return NULL; } /*! * \brief Find of SCCP Config Options */ static const SCCPConfigOption *sccp_find_config(const sccp_config_segment_t segment, const char *name) { long unsigned int i = 0; const SCCPConfigSegment *sccpConfigSegment = sccp_find_segment(segment); const SCCPConfigOption *config = sccpConfigSegment->config; for (i = 0; i < sccpConfigSegment->config_size; i++) { if (!strcasecmp(config[i].name, name)) return &config[i]; } return NULL; } /*! * \brief Parse SCCP Config Option Value * * \todo add errormsg return to sccpConfigOption->converter_f: so we can have a fixed format the returned errors to the user */ static sccp_configurationchange_t sccp_config_object_setValue(void *obj, const char *name, const char *value, uint8_t lineno, const sccp_config_segment_t segment, boolean_t *SetEntries) { const SCCPConfigSegment *sccpConfigSegment = sccp_find_segment(segment); const SCCPConfigOption *sccpConfigOption = sccp_find_config(segment, name); void *dst; int type; /* enum wrapper */ int flags; /* enum wrapper */ sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; /* indicates config value is changed or not */ sccp_configurationchange_t changes = SCCP_CONFIG_NOUPDATENEEDED; sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_3 "SCCP: parsing %s parameter: %s = '%s' in line %d\n", sccpConfigSegment->name, name, value, lineno); short int int8num; int int16num; long int int32num; long long int int64num; short unsigned int uint8num; unsigned int uint16num; long unsigned int uint32num; long long unsigned int uint64num; boolean_t boolean; char *str; char oldChar; if (!sccpConfigOption) { pbx_log(LOG_WARNING, "Unknown param at %s:%d:%s='%s'\n", sccpConfigSegment->name, lineno, name, value); return SCCP_CONFIG_NOUPDATENEEDED; } if (sccpConfigOption->offset <= 0) return SCCP_CONFIG_NOUPDATENEEDED; dst = ((uint8_t *) obj) + sccpConfigOption->offset; type = sccpConfigOption->type; flags = sccpConfigOption->flags; if ((flags & SCCP_CONFIG_FLAG_IGNORE) == SCCP_CONFIG_FLAG_IGNORE) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "config parameter %s='%s' in line %d ignored\n", name, value, lineno); return SCCP_CONFIG_NOUPDATENEEDED; } else if ((flags & SCCP_CONFIG_FLAG_CHANGED) == SCCP_CONFIG_FLAG_CHANGED) { pbx_log(LOG_NOTICE, "changed config param at %s='%s' in line %d\n - %s -> please check sccp.conf file\n", name, value, lineno, sccpConfigOption->description); } else if ((flags & SCCP_CONFIG_FLAG_DEPRECATED) == SCCP_CONFIG_FLAG_DEPRECATED && lineno > 0) { pbx_log(LOG_NOTICE, "deprecated config param at %s='%s' in line %d\n - %s -> using old implementation\n", name, value, lineno, sccpConfigOption->description); } else if ((flags & SCCP_CONFIG_FLAG_OBSOLETE) == SCCP_CONFIG_FLAG_OBSOLETE && lineno > 0) { pbx_log(LOG_WARNING, "obsolete config param at %s='%s' in line %d\n - %s -> param skipped\n", name, value, lineno, sccpConfigOption->description); return SCCP_CONFIG_NOUPDATENEEDED; } else if ((flags & SCCP_CONFIG_FLAG_REQUIRED) == SCCP_CONFIG_FLAG_REQUIRED) { if (NULL == value) { pbx_log(LOG_WARNING, "required config param at %s='%s' - %s\n", name, value, sccpConfigOption->description); return SCCP_CONFIG_WARNING; } } /* warn user that value is being overwritten */ switch (type) { case SCCP_CONFIG_DATATYPE_CHAR: oldChar = *(char *) dst; if (!sccp_strlen_zero(value)) { if (oldChar != value[0]) { changed = SCCP_CONFIG_CHANGE_CHANGED; *(char *) dst = value[0]; } } else { if (oldChar != '\0') { changed = SCCP_CONFIG_CHANGE_CHANGED; *(char *) dst = '\0'; } } break; case SCCP_CONFIG_DATATYPE_STRING: str = (char *) dst; if (!sccp_strlen_zero(value)) { if (strcasecmp(str, value)) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "config parameter %s '%s' != '%s'\n", name, str, value); changed = SCCP_CONFIG_CHANGE_CHANGED; pbx_copy_string(dst, value, sccpConfigOption->size); } } else if (!sccp_strlen_zero(str)) { changed = SCCP_CONFIG_CHANGE_CHANGED; pbx_copy_string(dst, "", sccpConfigOption->size); } break; case SCCP_CONFIG_DATATYPE_STRINGPTR: changed = SCCP_CONFIG_CHANGE_NOCHANGE; str = *(void **) dst; if (!sccp_strlen_zero(value)) { if (str) { if (strcasecmp(str, value)) { changed = SCCP_CONFIG_CHANGE_CHANGED; /* there is a value already, free it */ free(str); *(void **) dst = strdup(value); } } else { changed = SCCP_CONFIG_CHANGE_CHANGED; *(void **) dst = strdup(value); } } else if (!sccp_strlen_zero(str)) { changed = SCCP_CONFIG_CHANGE_CHANGED; /* there is a value already, free it */ free(str); if (value == NULL) { *(void **) dst = NULL; } else { *(void **) dst = strdup(value); } } break; case SCCP_CONFIG_DATATYPE_INT: if (sccp_strlen_zero(value)) { value = strdupa("0"); } switch (sccpConfigOption->size) { case 1: if (sscanf(value, "%hd", &int8num) == 1) { if ((*(int8_t *) dst) != int8num) { *(int8_t *) dst = int8num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; case 2: if (sscanf(value, "%d", &int16num) == 1) { if ((*(int16_t *) dst) != int16num) { *(int16_t *) dst = int16num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; case 4: if (sscanf(value, "%ld", &int32num) == 1) { if ((*(int32_t *) dst) != int32num) { *(int32_t *) dst = int32num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; case 8: if (sscanf(value, "%lld", &int64num) == 1) { if ((*(int64_t *) dst) != int64num) { *(int64_t *) dst = int64num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; } break; case SCCP_CONFIG_DATATYPE_UINT: if (sccp_strlen_zero(value)) { value = strdupa("0"); } switch (sccpConfigOption->size) { case 1: if ((!strncmp("0x", value, 2) && sscanf(value, "%hx", &uint8num)) || (sscanf(value, "%hu", &uint8num) == 1)) { if ((*(uint8_t *) dst) != uint8num) { *(uint8_t *) dst = uint8num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; case 2: if (sscanf(value, "%u", &uint16num) == 1) { if ((*(uint16_t *) dst) != uint16num) { *(uint16_t *) dst = uint16num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; case 4: if (sscanf(value, "%lu", &uint32num) == 1) { if ((*(uint32_t *) dst) != uint32num) { *(uint32_t *) dst = uint32num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; case 8: if (sscanf(value, "%llu", &uint64num) == 1) { if ((*(uint64_t *) dst) != uint64num) { *(uint64_t *) dst = uint64num; changed = SCCP_CONFIG_CHANGE_CHANGED; } } break; } break; case SCCP_CONFIG_DATATYPE_BOOLEAN: if (sccp_strlen_zero(value)) { boolean = FALSE; } else { boolean = sccp_true(value); } if (*(boolean_t *) dst != boolean) { *(boolean_t *) dst = sccp_true(value); changed = SCCP_CONFIG_CHANGE_CHANGED; } break; case SCCP_CONFIG_DATATYPE_PARSER: if (sccpConfigOption->converter_f) { changed = sccpConfigOption->converter_f(dst, sccpConfigOption->size, value, segment); } break; default: pbx_log(LOG_WARNING, "Unknown param at %s='%s'\n", name, value); return SCCP_CONFIG_NOUPDATENEEDED; } /* set changed value if changed */ if (SCCP_CONFIG_CHANGE_CHANGED == changed) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "config parameter %s='%s' in line %d changed. %s\n", name, value, lineno, SCCP_CONFIG_NEEDDEVICERESET == sccpConfigOption->change ? "(causes device reset)" : ""); /* if SetEntries is provided lookup the first offset of the struct variable we have set and note the index in SetEntries by changing the boolean_t to TRUE */ changes = sccpConfigOption->change; } if (SCCP_CONFIG_CHANGE_INVALIDVALUE != changed) { if (sccpConfigOption->offset > 0 && SetEntries != NULL) { int x; for (x = 0; x < sccpConfigSegment->config_size; x++) { if (sccpConfigOption->offset == sccpConfigSegment->config[x].offset) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCP: (sccp_config) Set Entry[%d] = TRUE for %s\n", x, sccpConfigSegment->config[x].name); SetEntries[x] = TRUE; } } } } return changes; } /*! * \brief Set SCCP obj defaults from predecessor (device / global) * * check if we can find the param name in the segment specified and retrieving its value or default value * copy the string from the defaultSegment and run through the converter again */ static void sccp_config_set_defaults(void *obj, const sccp_config_segment_t segment, const boolean_t *alreadySetEntries) { uint8_t i = 0; const SCCPConfigSegment *sccpConfigSegment = sccp_find_segment(segment); const SCCPConfigOption *sccpDstConfig = sccp_find_segment(segment)->config; const SCCPConfigOption *sccpDefaultConfigOption; sccp_device_t *my_device = NULL; sccp_line_t *my_line = NULL; sccp_device_t *ref_device = NULL; /* need to find a way to find the default device to copy */ int flags; /* enum wrapper */ int type; /* enum wrapper */ const char *value = ""; /*! \todo retrieve value from correct segment */ boolean_t valueFound = FALSE; PBX_VARIABLE_TYPE *v; uint8_t arraySize = 0; // already Set int x; boolean_t skip = FALSE; /* check if not already set using it's own parameter in the sccp.conf file */ switch (segment) { case SCCP_CONFIG_GLOBAL_SEGMENT: arraySize = ARRAY_LEN(sccpGlobalConfigOptions); sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "setting [general] defaults\n"); break; case SCCP_CONFIG_DEVICE_SEGMENT: my_device = &(*(sccp_device_t *) obj); arraySize = ARRAY_LEN(sccpDeviceConfigOptions); sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "setting device[%s] defaults\n", my_device ? my_device->id : "NULL"); break; case SCCP_CONFIG_LINE_SEGMENT: my_line = &(*(sccp_line_t *) obj); arraySize = ARRAY_LEN(sccpLineConfigOptions); sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "setting line[%s] defaults\n", my_line ? my_line->name : "NULL"); break; case SCCP_CONFIG_SOFTKEY_SEGMENT: pbx_log(LOG_ERROR, "softkey default loading not implemented yet\n"); break; } if (!GLOB(cfg)) { pbx_log(LOG_NOTICE, "GLOB(cfg) not available. Skip loading default setting.\n"); return; } /* find the defaultValue, first check the reference, if no reference is specified, us the local defaultValue */ for (i = 0; i < arraySize; i++) { /* Lookup the first offset of the struct variable we want to set default for, find the corresponding entry in the alreadySetEntries array and check the boolean flag, skip if true */ skip = FALSE; for (x = 0; x < sccpConfigSegment->config_size; x++) { if (sccpDstConfig[i].offset == sccpConfigSegment->config[x].offset && alreadySetEntries[x]) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: (sccp_config) skip setting default (SetEntry[%d] = TRUE for %s)\n", x, sccpConfigSegment->config[x].name); skip = TRUE; break; } } if (skip) { // skip default value if already set continue; } flags = sccpDstConfig[i].flags; type = sccpDstConfig[i].type; if (((flags & SCCP_CONFIG_FLAG_OBSOLETE) != SCCP_CONFIG_FLAG_OBSOLETE)) { // has not been set already and is not obsolete sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: parsing %s parameter %s looking for default (flags: %d, type: %d)\n", sccpConfigSegment->name, sccpDstConfig[i].name, flags, type); if ((flags & SCCP_CONFIG_FLAG_GET_DEVICE_DEFAULT) == SCCP_CONFIG_FLAG_GET_DEVICE_DEFAULT) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "config parameter %s refering to device default\n", sccpDstConfig[i].name); ref_device = &(*(sccp_device_t *) obj); // get value from cfg->device category valueFound = FALSE; for (v = ast_variable_browse(GLOB(cfg), (const char *) ref_device->id); v; v = v->next) { if (!strcasecmp((const char *) sccpDstConfig[i].name, v->name)) { value = v->value; if (!sccp_strlen_zero(value)) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "config parameter %s using default %s\n", sccpDstConfig[i].name, value); // get value from the config file and run through parser sccp_config_object_setValue(obj, sccpDstConfig[i].name, value, 0, segment, NULL); } valueFound = TRUE; } } if (!valueFound) { // get defaultValue from default_segment sccpDefaultConfigOption = sccp_find_config(SCCP_CONFIG_DEVICE_SEGMENT, sccpDstConfig[i].name); if (sccpDefaultConfigOption) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "config parameter %s found value:%s in device source segment\n", sccpDstConfig[i].name, value); value = sccpDefaultConfigOption->defaultValue; if (!sccp_strlen_zero(value)) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "config parameter %s using device default %s\n", sccpDstConfig[i].name, value); // get value from the config file and run through parser sccp_config_object_setValue(obj, sccpDstConfig[i].name, value, 0, segment, NULL); } } else { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "config parameter %s not found in device source segment\n", sccpDstConfig[i].name); } } } else if ((flags & SCCP_CONFIG_FLAG_GET_GLOBAL_DEFAULT) == SCCP_CONFIG_FLAG_GET_GLOBAL_DEFAULT) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "config parameter %s refering to global default\n", sccpDstConfig[i].name); // get value from cfg->general category valueFound = FALSE; for (v = ast_variable_browse(GLOB(cfg), "general"); v; v = v->next) { if (!strcasecmp(sccpDstConfig[i].name, v->name)) { value = v->value; if (!sccp_strlen_zero(value)) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "config parameter %s using global default %s\n", sccpDstConfig[i].name, value); // get value from the config file and run through parser sccp_config_object_setValue(obj, sccpDstConfig[i].name, value, 0, segment, NULL); } valueFound = TRUE; } } if (!valueFound) { // get defaultValue from default_segment sccpDefaultConfigOption = sccp_find_config(SCCP_CONFIG_GLOBAL_SEGMENT, sccpDstConfig[i].name); if (sccpDefaultConfigOption) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "config parameter %s found value:%s in global source segment\n", sccpDstConfig[i].name, value); value = sccpDefaultConfigOption->defaultValue; if (!sccp_strlen_zero(value)) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "config parameter %s using default %s\n", sccpDstConfig[i].name, value); // get value from the config file and run through parser sccp_config_object_setValue(obj, sccpDstConfig[i].name, value, 0, segment, NULL); } } else { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "config parameter %s not found in global source segment\n", sccpDstConfig[i].name); } } value = (char *) pbx_variable_retrieve(GLOB(cfg), "general", sccpDstConfig[i].name); } else { // get defaultValue from self sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "config parameter %s using local source segment default: %s -> %s\n", sccpDstConfig[i].name, value, sccpDstConfig[i].defaultValue); value = sccpDstConfig[i].defaultValue; sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "config parameter %s using default '%s'\n", sccpDstConfig[i].name, value); if (!sccp_strlen_zero(value)) { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "config parameter %s using default '%s'\n", sccpDstConfig[i].name, value); // get value from the config file and run through parser sccp_config_object_setValue(obj, sccpDstConfig[i].name, value, 0, segment, NULL); } else { sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "clearing parameter %s\n", sccpDstConfig[i].name); if (type == SCCP_CONFIG_DATATYPE_STRINGPTR || value != NULL) { sccp_config_object_setValue(obj, sccpDstConfig[i].name, "", 0, segment, NULL); } } } } } } /*! * \brief Config Converter/Parser for Debug */ sccp_value_changed_t sccp_config_parse_debug(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; uint32_t debug_new = 0; char *debug_arr[1]; debug_arr[0] = strdup(value); debug_new = sccp_parse_debugline(debug_arr, 0, 1, debug_new); if (*(uint32_t *) dest != debug_new) { *(uint32_t *) dest = debug_new; changed = SCCP_CONFIG_CHANGE_CHANGED; } sccp_free(debug_arr[0]); return changed; } /*! * \brief Config Converter/Parser for Bind Address */ sccp_value_changed_t sccp_config_parse_ipaddress(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; if (sccp_strlen_zero(value)) { value = strdupa("0.0.0.0"); } #ifdef CS_EXPERIMENTAL_NEWIP struct sockaddr_in *bindaddr_prev = &(*(struct sockaddr_in *) dest); char curval[256], *port = NULL, *host = NULL, *splitter; sccp_copy_string(curval, value, sizeof(curval)); splitter = curval; host = strsep(&splitter, ":"); port = splitter; int status; struct addrinfo hints, *res, *p; memset(&hints, 0, sizeof hints); // make sure the struct is empty hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((status = getaddrinfo(host, port, &hints, &res)) != 0) { pbx_log(LOG_WARNING, "Invalid address: %s. error: %s. SCCP disabled!\n", value, gai_strerror(status)); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } // for(p = res;p != NULL; p = p->ai_next) { // use sockaddr_storage to store multiple results p = res; if (p != NULL) { if (p->ai_family == AF_INET) { // IPv4 if (bindaddr_prev->sin_addr.s_addr != (((struct sockaddr_in *) p->ai_addr)->sin_addr).s_addr || bindaddr_prev->sin_port != ((struct sockaddr_in *) p->ai_addr)->sin_port) { bindaddr_prev->sin_family = ((struct sockaddr_in *) p->ai_addr)->sin_family; memcpy(&bindaddr_prev->sin_addr, &(((struct sockaddr_in *) p->ai_addr)->sin_addr), sizeof(struct in_addr)); bindaddr_prev->sin_port = ((struct sockaddr_in *) p->ai_addr)->sin_port; changed = SCCP_CONFIG_CHANGE_CHANGED; } // else // IPv6 // if (bindaddr_prev->sin_addr.s_addr != ((struct sockaddr_in6 *)p->ai_addr).s_addr || bindaddr_prev->sin_port != ((struct sockaddr_in6 *)p->ai_addr)->sin_port) { // bindaddr_prev->sin_family=((struct sockaddr_in6 *)p->ai_addr)->sin_family; // memcpy(&bindaddr_prev->sin_addr, &(((struct sockaddr_in6 *)p->ai_addr)->sin_addr), sizeof(struct in_addr)); // bindaddr_prev->sin_port=((struct sockaddr_in6 *)p->ai_addr)->sin_port; // changed = SCCP_CONFIG_CHANGE_CHANGED; // } } } // char ipstr[INET6_ADDRSTRLEN]; // inet_ntop(p->ai_family, &(((struct sockaddr_in *)p->ai_addr)->sin_addr), ipstr, sizeof ipstr); // pbx_log(LOG_WARNING, "host: %s, port: %d\n", ipstr, htons((((struct sockaddr_in *)p->ai_addr)->sin_port))); // } freeaddrinfo(res); // free the linked-list #else struct ast_hostent ahp; struct hostent *hp; struct sockaddr_in *bindaddr_prev = &(*(struct sockaddr_in *) dest); struct sockaddr_in *bindaddr_new = NULL; if (!(hp = pbx_gethostbyname(value, &ahp))) { pbx_log(LOG_WARNING, "Invalid address: %s. SCCP disabled\n", value); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (&bindaddr_prev->sin_addr != NULL && hp != NULL) { if ((bindaddr_new = sccp_malloc(sizeof(struct sockaddr_in)))) { memcpy(&bindaddr_new->sin_addr, hp->h_addr, sizeof(struct in_addr)); if (bindaddr_prev->sin_addr.s_addr != bindaddr_new->sin_addr.s_addr) { memcpy(&bindaddr_prev->sin_addr, hp->h_addr, sizeof(struct in_addr)); changed = SCCP_CONFIG_CHANGE_CHANGED; } sccp_free(bindaddr_new); } } else { memcpy(&bindaddr_prev->sin_addr, hp->h_addr, sizeof(struct in_addr)); changed = SCCP_CONFIG_CHANGE_CHANGED; } #endif return changed; } /*! * \brief Config Converter/Parser for Port */ sccp_value_changed_t sccp_config_parse_port(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; int new_port; struct sockaddr_in *bindaddr_prev = &(*(struct sockaddr_in *) dest); if (sscanf(value, "%i", &new_port) == 1) { if (&bindaddr_prev->sin_port != NULL) { // reload if (bindaddr_prev->sin_port != htons(new_port)) { bindaddr_prev->sin_port = htons(new_port); changed = SCCP_CONFIG_CHANGE_CHANGED; } } else { bindaddr_prev->sin_port = htons(new_port); changed = SCCP_CONFIG_CHANGE_CHANGED; } } else { pbx_log(LOG_WARNING, "Invalid port number '%s'\n", value); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } return changed; } /*! * \brief Config Converter/Parser for BlindTransferIndication */ sccp_value_changed_t sccp_config_parse_blindtransferindication(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; boolean_t blindtransferindication = *(boolean_t *) dest; if (!strcasecmp(value, "moh")) { blindtransferindication = SCCP_BLINDTRANSFER_MOH; } else if (!strcasecmp(value, "ring")) { blindtransferindication = SCCP_BLINDTRANSFER_RING; } else { pbx_log(LOG_WARNING, "Invalid blindtransferindication value, should be 'moh' or 'ring'\n"); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (*(boolean_t *) dest != blindtransferindication) { changed = SCCP_CONFIG_CHANGE_CHANGED; *(boolean_t *) dest = blindtransferindication; } return changed; } /*! * \brief Config Converter/Parser for Call Answer Order */ sccp_value_changed_t sccp_config_parse_callanswerorder(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; call_answer_order_t callanswerorder = *(call_answer_order_t *) dest; call_answer_order_t new_value; if (!strcasecmp(value, "oldestfirst")) { new_value = ANSWER_OLDEST_FIRST; } else if (!strcasecmp(value, "lastfirst")) { new_value = ANSWER_LAST_FIRST; } else { return SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (callanswerorder != new_value) { changed = SCCP_CONFIG_CHANGE_CHANGED; *(call_answer_order_t *) dest = new_value; } return changed; } /*! * \brief Config Converter/Parser for Codec Preferences * * \todo need check to see if preferred_codecs has changed * \todo do we need to reduce the preferences by the pbx -> skinny codec mapping ? */ sccp_value_changed_t sccp_config_parse_codec_preferences(void *dest, const size_t size, const char *value, const boolean_t allow, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; skinny_codec_t *preferred_codecs = &(*(skinny_codec_t *) dest); // skinny_codec_t preferred_codecs_prev[SKINNY_MAX_CAPABILITIES]; // memcpy(preferred_codecs_prev, preferred_codecs, sizeof(preferred_codecs)); if (!sccp_parse_allow_disallow(preferred_codecs, NULL, value, allow)) { changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } else if (1 == 1) { /*\todo implement check */ changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Allow Codec Preferences */ sccp_value_changed_t sccp_config_parse_allow_codec(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { return sccp_config_parse_codec_preferences(dest, size, value, TRUE, segment); } /*! * \brief Config Converter/Parser for Disallow Codec Preferences */ sccp_value_changed_t sccp_config_parse_disallow_codec(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { return sccp_config_parse_codec_preferences(dest, size, value, FALSE, segment); } /*! * \brief Config Converter/Parser for Permit IP * * \todo need check to see if ha has changed */ sccp_value_changed_t sccp_config_parse_permit(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; int error = 0; struct sccp_ha *ha = *(struct sccp_ha **) dest; if (!strcasecmp(value, "internal")) { ha = sccp_append_ha("permit", "127.0.0.0/255.0.0.0", ha, &error); ha = sccp_append_ha("permit", "10.0.0.0/255.0.0.0", ha, &error); ha = sccp_append_ha("permit", "172.16.0.0/255.224.0.0", ha, &error); ha = sccp_append_ha("permit", "192.168.0.0/255.255.0.0", ha, &error); } else { ha = sccp_append_ha("permit", value, ha, &error); } sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_3 "Permit: %s\n", value); if (!error) { *(struct sccp_ha **) dest = ha; //changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Deny IP * * \todo need check to see if ha has changed */ sccp_value_changed_t sccp_config_parse_deny(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; int error = 0; struct sccp_ha *ha = *(struct sccp_ha **) dest; ha = sccp_append_ha("deny", value, ha, &error); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_3 "Deny: %s\n", value); if (!error) { *(struct sccp_ha **) dest = ha; //changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Buttons * * \todo Build a check to see if the button has changed */ sccp_value_changed_t sccp_config_parse_button(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; char *buttonType = NULL, *buttonName = NULL, *buttonOption = NULL, *buttonArgs = NULL; char k_button[256]; char *splitter; sccp_config_buttontype_t type; unsigned i; sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_3 "Found buttonconfig: %s\n", value); sccp_copy_string(k_button, value, sizeof(k_button)); splitter = k_button; buttonType = strsep(&splitter, ","); buttonName = strsep(&splitter, ","); buttonOption = strsep(&splitter, ","); buttonArgs = splitter; for (i = 0; i < ARRAY_LEN(sccp_buttontypes) && strcasecmp(buttonType, sccp_buttontypes[i].text); ++i); if (i >= ARRAY_LEN(sccp_buttontypes)) { pbx_log(LOG_WARNING, "Unknown button type '%s'.\n", buttonType); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } type = sccp_buttontypes[i].buttontype; // sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "ButtonType: %s\n", buttonType); // sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "ButtonName: %s\n", buttonName); // sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "ButtonOption: %s\n", buttonOption); changed = sccp_config_addButton(dest, 0, type, buttonName ? pbx_strip(buttonName) : buttonType, buttonOption ? pbx_strip(buttonOption) : NULL, buttonArgs ? pbx_strip(buttonArgs) : NULL); return changed; } /*! * \brief Config Converter/Parser for Permit Hosts * * \todo maybe add new DATATYPE_LIST to add string param value to LIST_HEAD to make a generic parser * \todo need check to see if has changed */ sccp_value_changed_t sccp_config_parse_permithosts(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; // sccp_hostname_t *permithost = &(*(sccp_hostname_t *) dest); sccp_hostname_t *permithost = NULL; if ((permithost = sccp_malloc(sizeof(sccp_hostname_t)))) { if (strcasecmp(permithost->name, value)) { sccp_copy_string(permithost->name, value, sizeof(permithost->name)); SCCP_LIST_INSERT_HEAD(&(*(SCCP_LIST_HEAD (, sccp_hostname_t) *) dest), permithost, list); changed = SCCP_CONFIG_CHANGE_CHANGED; } else { sccp_free(permithost); } } else { pbx_log(LOG_WARNING, "Error getting memory to assign hostname '%s' (malloc)\n", value); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } return changed; } /*! * \brief Config Converter/Parser for addons * * \todo make more generic * \todo cleanup original implementation in sccp_utils.c */ sccp_value_changed_t sccp_config_parse_addons(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { int addon_type; sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; SCCP_LIST_HEAD (, sccp_addon_t) * addonList = dest; // checking if addontype is known if (!strcasecmp(value, "7914")) addon_type = SKINNY_DEVICETYPE_CISCO_ADDON_7914; else if (!strcasecmp(value, "7915")) addon_type = SKINNY_DEVICETYPE_CISCO_ADDON_7915_24BUTTON; else if (!strcasecmp(value, "7916")) addon_type = SKINNY_DEVICETYPE_CISCO_ADDON_7916_24BUTTON; else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Unknown addon type (%s)\n", value); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } /*!\todo check allowed addons during the registration process, so we can use skinny device type instead of user defined type -MC */ // checking if addontype is supported by devicetype // if (!((addon_type == SKINNY_DEVICETYPE_CISCO7914) && // ((!strcasecmp(d->config_type, "7960")) || // (!strcasecmp(d->config_type, "7961")) || // (!strcasecmp(d->config_type, "7962")) || // (!strcasecmp(d->config_type, "7965")) || // (!strcasecmp(d->config_type, "7970")) || (!strcasecmp(d->config_type, "7971")) || (!strcasecmp(d->config_type, "7975")))) && !((addon_type == SKINNY_DEVICETYPE_CISCO7915) && ((!strcasecmp(d->config_type, "7962")) || (!strcasecmp(d->config_type, "7965")) || (!strcasecmp(d->config_type, "7975")))) && !((addon_type == SKINNY_DEVICETYPE_CISCO7916) && ((!strcasecmp(d->config_type, "7962")) || (!strcasecmp(d->config_type, "7965")) || (!strcasecmp(d->config_type, "7975"))))) { // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Configured device (%s) does not support the specified addon type (%s)\n", d->config_type, value); // return changed; // } // add addon_type to list head sccp_addon_t *addon = sccp_malloc(sizeof(sccp_addon_t)); if (!addon) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Unable to allocate memory for a device addon\n"); return changed; } memset(addon, 0, sizeof(sccp_addon_t)); addon->type = addon_type; SCCP_LIST_INSERT_HEAD(addonList, addon, list); return SCCP_CONFIG_CHANGE_CHANGED; } /*! * \brief Config Converter/Parser for privacyFeature * * \todo malloc/calloc of privacyFeature necessary ? */ sccp_value_changed_t sccp_config_parse_privacyFeature(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; sccp_featureConfiguration_t privacyFeature; // = malloc(sizeof(sccp_featureConfiguration_t)); if (!strcasecmp(value, "full")) { privacyFeature.status = ~0; privacyFeature.enabled = TRUE; } else if (sccp_true(value) || !sccp_true(value)) { privacyFeature.status = 0; privacyFeature.enabled = sccp_true(value); } else { pbx_log(LOG_WARNING, "Invalid privacy value, should be 'full', 'on' or 'off'\n"); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (privacyFeature.status != (*(sccp_featureConfiguration_t *) dest).status || privacyFeature.enabled != (*(sccp_featureConfiguration_t *) dest).enabled) { *(sccp_featureConfiguration_t *) dest = privacyFeature; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for early RTP */ sccp_value_changed_t sccp_config_parse_earlyrtp(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; sccp_channelstate_t earlyrtp = 0; if (!strcasecmp(value, "none")) { earlyrtp = 0; } else if (!strcasecmp(value, "offhook")) { earlyrtp = SCCP_CHANNELSTATE_OFFHOOK; } else if (!strcasecmp(value, "dial")) { earlyrtp = SCCP_CHANNELSTATE_DIALING; } else if (!strcasecmp(value, "ringout")) { earlyrtp = SCCP_CHANNELSTATE_RINGOUT; } else if (!strcasecmp(value, "progress")) { earlyrtp = SCCP_CHANNELSTATE_PROGRESS; } else { pbx_log(LOG_WARNING, "Invalid earlyrtp state value, should be 'none', 'offhook', 'dial', 'ringout', 'progress'\n"); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (*(sccp_channelstate_t *) dest != earlyrtp) { *(sccp_channelstate_t *) dest = earlyrtp; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for dtmfmode */ sccp_value_changed_t sccp_config_parse_dtmfmode(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; sccp_dtmfmode_t dtmfmode = 0; if (!strcasecmp(value, "outofband")) { dtmfmode = SCCP_DTMFMODE_OUTOFBAND; } else if (!strcasecmp(value, "inband")) { dtmfmode = SCCP_DTMFMODE_INBAND; } else { pbx_log(LOG_WARNING, "Invalid dtmfmode value, should be either 'inband' or 'outofband'\n"); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (*(sccp_dtmfmode_t *) dest != dtmfmode) { *(sccp_dtmfmode_t *) dest = dtmfmode; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for mwilamp */ sccp_value_changed_t sccp_config_parse_mwilamp(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; skinny_lampmode_t mwilamp = SKINNY_LAMP_OFF; if (!strcasecmp(value, "wink")) { mwilamp = SKINNY_LAMP_WINK; } else if (!strcasecmp(value, "flash")) { mwilamp = SKINNY_LAMP_FLASH; } else if (!strcasecmp(value, "blink")) { mwilamp = SKINNY_LAMP_BLINK; } else if (!sccp_true(value)) { mwilamp = SKINNY_LAMP_OFF; } else if (sccp_true(value)) { mwilamp = SKINNY_LAMP_ON; } else { pbx_log(LOG_WARNING, "Invalid mwilamp value, should be one of 'off', 'on', 'wink', 'flash' or 'blink'\n"); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } if (*(skinny_lampmode_t *) dest != mwilamp) { *(skinny_lampmode_t *) dest = mwilamp; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Mailbox Value */ sccp_value_changed_t sccp_config_parse_mailbox(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; sccp_mailbox_t *mailbox = NULL; char *context, *mbox = NULL; SCCP_LIST_HEAD (, sccp_mailbox_t) * mailboxList = dest; mbox = context = sccp_strdupa(value); boolean_t mailbox_exists = FALSE; strsep(&context, "@"); if (sccp_strlen_zero(context)) { context = "default"; } // Check mailboxes list SCCP_LIST_TRAVERSE(mailboxList, mailbox, list) { if (sccp_strequals(mailbox->mailbox, mbox)) { mailbox_exists = TRUE; } } if ((!mailbox_exists) && (!sccp_strlen_zero(mbox))) { // Add mailbox entry mailbox = sccp_calloc(1, sizeof(*mailbox)); if (NULL != mailbox) { mailbox->mailbox = sccp_strdup(mbox); mailbox->context = sccp_strdup(context); SCCP_LIST_INSERT_TAIL(mailboxList, mailbox, list); } changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Tos Value */ sccp_value_changed_t sccp_config_parse_tos(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; unsigned int tos; if (!pbx_str2tos(value, &tos)) { /* value is tos */ } else if (sscanf(value, "%i", &tos) == 1) { tos = tos & 0xff; } else if (!strcasecmp(value, "lowdelay")) { tos = IPTOS_LOWDELAY; } else if (!strcasecmp(value, "throughput")) { tos = IPTOS_THROUGHPUT; } else if (!strcasecmp(value, "reliability")) { tos = IPTOS_RELIABILITY; #if !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(SOLARIS) } else if (!strcasecmp(value, "mincost")) { tos = IPTOS_MINCOST; #endif } else if (!strcasecmp(value, "none")) { tos = 0; } else { #if !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(SOLARIS) changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; #else changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; #endif tos = 0x68 & 0xff; } if ((*(unsigned int *) dest) != tos) { *(unsigned int *) dest = tos; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Cos Value */ sccp_value_changed_t sccp_config_parse_cos(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; unsigned int cos; if (sscanf(value, "%d", &cos) == 1) { if (cos > 7) { pbx_log(LOG_WARNING, "Invalid cos %d value, refer to QoS documentation\n", cos); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } } if ((*(unsigned int *) dest) != cos) { *(unsigned int *) dest = cos; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for AmaFlags Value */ sccp_value_changed_t sccp_config_parse_amaflags(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; int amaflags; amaflags = pbx_cdr_amaflags2int(value); if (amaflags < 0) { changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } else { if ((*(int *) dest) != amaflags) { changed = SCCP_CONFIG_CHANGE_CHANGED; *(int *) dest = amaflags; } } return changed; } /*! * \brief Config Converter/Parser for Secundairy Dialtone Digits */ sccp_value_changed_t sccp_config_parse_secondaryDialtoneDigits(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; char *str = (char *) dest; if (strlen(value) <= 9) { if (strcasecmp(str, value)) { sccp_copy_string(str, value, 9); changed = SCCP_CONFIG_CHANGE_CHANGED; } } else { changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } return changed; } sccp_value_changed_t sccp_config_parse_variables(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; boolean_t alreadyexists = FALSE; PBX_VARIABLE_TYPE *v = NULL; PBX_VARIABLE_TYPE *newvar = NULL; PBX_VARIABLE_TYPE *prevvar = *(PBX_VARIABLE_TYPE **) dest; char *varname = sccp_strdupa(value); char *varval = NULL; if (!sccp_strlen_zero(varname)) { if ((varval = strchr(varname, '='))) { *varval++ = '\0'; for (v = prevvar; v; v = v->next) { if (!strcmp(v->name, varname) && !strcmp(v->value, varval)) { // skip duplicate var alreadyexists = TRUE; } } if (!alreadyexists) { if ((newvar = ast_variable_new(varname, varval, ""))) { newvar->next = prevvar; *(PBX_VARIABLE_TYPE **) dest = newvar; } } else { *(PBX_VARIABLE_TYPE **) dest = prevvar; //changed = SCCP_CONFIG_CHANGE_CHANGED; } } else { pbx_log(LOG_ERROR, "SCCP: (sccp_config_parse_variables) Error Parsing Variables (value=%s)\n", value); changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } } return changed; } /*! * \brief Config Converter/Parser for Callgroup/Pickupgroup Values * * \todo check changes to make the function more generic */ sccp_value_changed_t sccp_config_parse_group(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; char *piece; char *c; int start = 0, finish = 0, x; sccp_group_t group = 0; if (!sccp_strlen_zero(value)) { c = sccp_strdupa(value); while ((piece = strsep(&c, ","))) { if (sscanf(piece, "%30d-%30d", &start, &finish) == 2) { /* Range */ } else if (sscanf(piece, "%30d", &start)) { /* Just one */ finish = start; } else { pbx_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", value, piece); continue; } for (x = start; x <= finish; x++) { if ((x > 63) || (x < 0)) { pbx_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x); } else { group |= ((ast_group_t) 1 << x); } } } } #if defined(HAVE_UNALIGNED_BUSERROR) // for example sparc64 sccp_group_t group_orig = 0; memcpy(&group_orig, dest, sizeof(sccp_group_t)); if (group_orig != group) { changed = SCCP_CONFIG_CHANGE_CHANGED; memcpy(dest, &group, sizeof(sccp_group_t)); } #else if ((*(sccp_group_t *) dest) != group) { changed = SCCP_CONFIG_CHANGE_CHANGED; *(sccp_group_t *) dest = group; } #endif return changed; } /*! * \brief Config Converter/Parser for Context */ sccp_value_changed_t sccp_config_parse_context(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; char *str = (char *) dest; if (strcasecmp(str, value)) { changed = SCCP_CONFIG_CHANGE_CHANGED; pbx_copy_string(dest, value, size); if (!sccp_strlen_zero(value) && !pbx_context_find((const char *) dest)) { pbx_log(LOG_WARNING, "The context '%s' you specified might not be available in the dialplan. Please check the sccp.conf\n", (char *) dest); } } else { changed = SCCP_CONFIG_CHANGE_NOCHANGE; } return changed; } /*! * \brief Config Converter/Parser for Hotline Context */ sccp_value_changed_t sccp_config_parse_hotline_context(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; sccp_hotline_t *hotline = *(sccp_hotline_t **) dest; if (strcasecmp(hotline->line->context, value)) { changed = SCCP_CONFIG_CHANGE_CHANGED; pbx_copy_string(hotline->line->context, value, size); } else { changed = SCCP_CONFIG_CHANGE_NOCHANGE; } return changed; } /*! * \brief Config Converter/Parser for Hotline Extension */ sccp_value_changed_t sccp_config_parse_hotline_exten(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; sccp_hotline_t *hotline = *(sccp_hotline_t **) dest; if (strcasecmp(hotline->exten, value)) { changed = SCCP_CONFIG_CHANGE_CHANGED; pbx_copy_string(hotline->exten, value, size); if (hotline->line) { sccp_copy_string(hotline->line->adhocNumber, value, sizeof(hotline)); } } else { changed = SCCP_CONFIG_CHANGE_NOCHANGE; } return changed; } /*! * \brief Config Converter/Parser for DND Values * \note 0/off is allow and 1/on is reject */ sccp_value_changed_t sccp_config_parse_dnd(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; uint8_t dndmode; if (!strcasecmp(value, "reject")) { dndmode = SCCP_DNDMODE_REJECT; } else if (!strcasecmp(value, "silent")) { dndmode = SCCP_DNDMODE_SILENT; } else if (!strcasecmp(value, "user")) { dndmode = SCCP_DNDMODE_USERDEFINED; } else if (!strcasecmp(value, "")) { dndmode = SCCP_DNDMODE_OFF; } else { dndmode = sccp_true(value); } if ((*(uint8_t *) dest) != dndmode) { (*(uint8_t *) dest) = dndmode; changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } /*! * \brief Config Converter/Parser for Jitter Buffer Flags */ static sccp_value_changed_t sccp_config_parse_jbflags(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment, const unsigned int flag) { sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; struct ast_jb_conf jb = *(struct ast_jb_conf *) dest; // pbx_log(LOG_WARNING,"Checking JITTERBUFFER: %d to %s\n", flag, value); if (pbx_test_flag(&jb, flag) != (unsigned) ast_true(value)) { // pbx_log(LOG_WARNING,"Setting JITTERBUFFER: %d to %s\n", flag, value); // pbx_set2_flag(&jb, ast_true(value), flag); pbx_set2_flag(&GLOB(global_jbconf), ast_true(value), flag); changed = SCCP_CONFIG_CHANGE_CHANGED; } return changed; } sccp_value_changed_t sccp_config_parse_jbflags_enable(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { return sccp_config_parse_jbflags(dest, size, value, segment, AST_JB_ENABLED); } sccp_value_changed_t sccp_config_parse_jbflags_force(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { return sccp_config_parse_jbflags(dest, size, value, segment, AST_JB_FORCED); } sccp_value_changed_t sccp_config_parse_jbflags_log(void *dest, const size_t size, const char *value, const sccp_config_segment_t segment) { return sccp_config_parse_jbflags(dest, size, value, segment, AST_JB_LOG); } /* end dyn config */ /*! * \brief add a Button to a device * \param buttonconfig_head pointer to the device->buttonconfig list * \param index button index * \param type type of button * \param name name * \param options options * \param args args * * \callgraph * \callergraph * * \lock * - device->buttonconfig * - globals * * \todo Build a check to see if the button has changed */ sccp_value_changed_t sccp_config_addButton(void *buttonconfig_head, int index, sccp_config_buttontype_t type, const char *name, const char *options, const char *args) { sccp_buttonconfig_t *config = NULL; // boolean_t is_new = FALSE; int highest_index = 0; sccp_value_changed_t changed = SCCP_CONFIG_CHANGE_NOCHANGE; // sccp_configurationchange_t changes = SCCP_CONFIG_NOUPDATENEEDED; SCCP_LIST_HEAD (, sccp_buttonconfig_t) * buttonconfigList = buttonconfig_head; sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_1 "SCCP: Loading/Checking Button Config\n"); SCCP_LIST_LOCK(buttonconfigList); SCCP_LIST_TRAVERSE(buttonconfigList, config, list) { // check if the button is to be deleted to see if we need to replace it if (index == 0 && config->pendingDelete && config->type == type) { if (config->type == EMPTY || !strcmp(config->label, name)) { sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Found Existing button at %d (Being Replaced)\n", config->index); index = config->index; break; } } highest_index = config->index; } if (index < 0) { index = highest_index + 1; config = NULL; } /* If a config at this position is not found, recreate one. */ if (!config || config->index != index) { config = sccp_calloc(1, sizeof(sccp_buttonconfig_t)); if (!config) { pbx_log(LOG_WARNING, "SCCP: sccp_config_addButton, memory allocation failed (calloc) failed\n"); return SCCP_CONFIG_CHANGE_INVALIDVALUE; } config->index = index; sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "New %s Button %s at : %d:%d\n", config_buttontype2str(type), name, index, config->index); SCCP_LIST_INSERT_TAIL(buttonconfigList, config, list); // is_new = TRUE; } else { config->pendingDelete = 0; config->pendingUpdate = 1; changed = SCCP_CONFIG_CHANGE_CHANGED; } SCCP_LIST_UNLOCK(buttonconfigList); if (type != EMPTY && (sccp_strlen_zero(name) || (type != LINE && !options))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: Faulty Button Configuration found at index: %d, type: %s, name: %s\n", config->index, config_buttontype2str(type), name); type = EMPTY; changed = SCCP_CONFIG_CHANGE_INVALIDVALUE; } switch (type) { case LINE: { struct composedId composedLineRegistrationId; memset(&composedLineRegistrationId, 0, sizeof(struct composedId)); composedLineRegistrationId = sccp_parseComposedId(name, 80); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "SCCP: ComposedId mainId: %s, subscriptionId.number: %s, subscriptionId.name: %s, subscriptionId.aux: %s\n", composedLineRegistrationId.mainId, composedLineRegistrationId.subscriptionId.number, composedLineRegistrationId.subscriptionId.name, composedLineRegistrationId.subscriptionId.aux); if (LINE == config->type && sccp_strequals(config->label, name) && sccp_strequals(config->button.line.name, composedLineRegistrationId.mainId) && sccp_strcaseequals(config->button.line.subscriptionId.number, composedLineRegistrationId.subscriptionId.number) && sccp_strequals(config->button.line.subscriptionId.name, composedLineRegistrationId.subscriptionId.name) && sccp_strequals(config->button.line.subscriptionId.aux, composedLineRegistrationId.subscriptionId.aux) ) { if (options && sccp_strequals(config->button.line.options, options)) { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } else { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } } config->type = LINE; sccp_copy_string(config->label, name, sizeof(config->label)); sccp_copy_string(config->button.line.name, composedLineRegistrationId.mainId, sizeof(config->button.line.name)); sccp_copy_string(config->button.line.subscriptionId.number, composedLineRegistrationId.subscriptionId.number, sizeof(config->button.line.subscriptionId.number)); sccp_copy_string(config->button.line.subscriptionId.name, composedLineRegistrationId.subscriptionId.name, sizeof(config->button.line.subscriptionId.name)); sccp_copy_string(config->button.line.subscriptionId.aux, composedLineRegistrationId.subscriptionId.aux, sizeof(config->button.line.subscriptionId.aux)); if (options) { sccp_copy_string(config->button.line.options, options, sizeof(config->button.line.options)); } break; } case SPEEDDIAL: /* \todo check if values change */ if (SPEEDDIAL == config->type && sccp_strequals(config->label, name) && sccp_strequals(config->button.speeddial.ext, options) ) { if (args && sccp_strequals(config->button.speeddial.hint, args)) { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } else { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } } config->type = SPEEDDIAL; sccp_copy_string(config->label, name, sizeof(config->label)); sccp_copy_string(config->button.speeddial.ext, options, sizeof(config->button.speeddial.ext)); if (args) { sccp_copy_string(config->button.speeddial.hint, args, sizeof(config->button.speeddial.hint)); } break; case SERVICE: if (SERVICE == config->type && sccp_strequals(config->label, name) && sccp_strequals(config->button.service.url, options) ) { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } /* \todo check if values change */ config->type = SERVICE; sccp_copy_string(config->label, name, sizeof(config->label)); sccp_copy_string(config->button.service.url, options, sizeof(config->button.service.url)); break; case FEATURE: if (FEATURE == config->type && sccp_strequals(config->label, name) && config->button.feature.id == sccp_featureStr2featureID(options) ) { if (args && sccp_strequals(config->button.feature.options, args)) { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } else { } } /* \todo check if values change */ config->type = FEATURE; sccp_log((DEBUGCAT_FEATURE | DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "featureID: %s\n", options); sccp_copy_string(config->label, name, sizeof(config->label)); config->button.feature.id = sccp_featureStr2featureID(options); if (args) { sccp_copy_string(config->button.feature.options, args, sizeof(config->button.feature.options)); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Arguments present on feature button: %d\n", config->instance); } sccp_log((DEBUGCAT_FEATURE | DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "Configured feature button with featureID: %s args: %s\n", options, args); break; case EMPTY: if (EMPTY == config->type) { changed = SCCP_CONFIG_CHANGE_NOCHANGE; break; } /* \todo check if values change */ config->type = EMPTY; break; } return changed; } /*! * \brief Build Line * \param l SCCP Line * \param v Asterisk Variable * \param lineName Name of line as char * \param isRealtime is Realtime as Boolean * * \callgraph * \callergraph * * \lock * - line * - see sccp_line_changed() */ static void sccp_config_buildLine(sccp_line_t * l, PBX_VARIABLE_TYPE * v, const char *lineName, boolean_t isRealtime) { sccp_configurationchange_t res = sccp_config_applyLineConfiguration(l, v); #ifdef CS_SCCP_REALTIME l->realtime = isRealtime; #endif // if (GLOB(reload_in_progress) && res == SCCP_CONFIG_NEEDDEVICERESET && l && l->pendingDelete) { if (GLOB(reload_in_progress) && res == SCCP_CONFIG_NEEDDEVICERESET && l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "%s: major changes for line '%s' detected, device reset required -> pendingUpdate=1\n", l->id, l->name); l->pendingUpdate = 1; } else { l->pendingUpdate = 0; } sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "%s: Removing pendingDelete\n", l->name); l->pendingDelete = 0; } /*! * \brief Build Device * \param d SCCP Device * \param variable Asterisk Variable * \param deviceName Name of device as char * \param isRealtime is Realtime as Boolean * * \callgraph * \callergraph * * \lock * - device * - see sccp_device_changed() */ static void sccp_config_buildDevice(sccp_device_t * d, PBX_VARIABLE_TYPE * variable, const char *deviceName, boolean_t isRealtime) { PBX_VARIABLE_TYPE *v = variable; /* apply configuration */ sccp_configurationchange_t res = sccp_config_applyDeviceConfiguration(d, v); #ifdef CS_DEVSTATE_FEATURE sccp_buttonconfig_t *config = NULL; sccp_devstate_specifier_t *dspec; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->type == FEATURE) { /* Check for the presence of a devicestate specifier and register in device list. */ if ((SCCP_FEATURE_DEVSTATE == config->button.feature.id) && (strncmp("", config->button.feature.options, 254))) { dspec = sccp_calloc(1, sizeof(sccp_devstate_specifier_t)); if (!dspec) { pbx_log(LOG_ERROR, "error while allocating memory for devicestate specifier"); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Recognized devstate feature button: %d\n", config->instance); SCCP_LIST_LOCK(&d->devstateSpecifiers); sccp_copy_string(dspec->specifier, config->button.feature.options, sizeof(config->button.feature.options)); SCCP_LIST_INSERT_TAIL(&d->devstateSpecifiers, dspec, list); SCCP_LIST_UNLOCK(&d->devstateSpecifiers); } } } } SCCP_LIST_UNLOCK(&d->buttonconfig); #endif #ifdef CS_SCCP_REALTIME d->realtime = isRealtime; #endif if (GLOB(reload_in_progress) && res == SCCP_CONFIG_NEEDDEVICERESET && d) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "%s: major changes for device detected, device reset required -> pendingUpdate=1\n", d->id); d->pendingUpdate = 1; } else { d->pendingUpdate = 0; } d->pendingDelete = 0; } /*! * \brief Get Configured Line from Asterisk Variable * \param v Asterisk Variable * \return Configured SCCP Line * \note also used by realtime functionality to line device from Asterisk Variable * * \callgraph * \callergraph * * \lock * - line->mailboxes */ sccp_configurationchange_t sccp_config_applyGlobalConfiguration(PBX_VARIABLE_TYPE * v) { sccp_configurationchange_t res = SCCP_CONFIG_NOUPDATENEEDED; boolean_t SetEntries[ARRAY_LEN(sccpGlobalConfigOptions)] = { FALSE }; for (; v; v = v->next) { res |= sccp_config_object_setValue(sccp_globals, v->name, v->value, v->lineno, SCCP_CONFIG_GLOBAL_SEGMENT, SetEntries); } sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Update Needed (%d)\n", res); sccp_config_set_defaults(sccp_globals, SCCP_CONFIG_GLOBAL_SEGMENT, SetEntries); if (GLOB(keepalive) < SCCP_MIN_KEEPALIVE) { GLOB(keepalive) = SCCP_MIN_KEEPALIVE; } return res; } /*! * \brief Parse sccp.conf and Create General Configuration * \param readingtype SCCP Reading Type * * \callgraph * \callergraph */ boolean_t sccp_config_general(sccp_readingtype_t readingtype) { PBX_VARIABLE_TYPE *v; /* Cleanup for reload */ if (GLOB(ha)) { sccp_free_ha(GLOB(ha)); GLOB(ha) = NULL; } if (GLOB(localaddr)) { sccp_free_ha(GLOB(localaddr)); GLOB(localaddr) = NULL; } if (!GLOB(cfg)) { pbx_log(LOG_WARNING, "Unable to load config file sccp.conf, SCCP disabled\n"); return FALSE; } /* read the general section */ v = ast_variable_browse(GLOB(cfg), "general"); if (!v) { pbx_log(LOG_WARNING, "Missing [general] section, SCCP disabled\n"); return FALSE; } sccp_configurationchange_t res = sccp_config_applyGlobalConfiguration(v); // sccp_config_set_defaults(sccp_globals, SCCP_CONFIG_GLOBAL_SEGMENT); if (GLOB(reload_in_progress) && res == SCCP_CONFIG_NEEDDEVICERESET) { sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "SCCP: major changes detected in globals, reset required -> pendingUpdate=1\n"); GLOB(pendingUpdate = 1); } else { GLOB(pendingUpdate = 0); } /* setup bindaddress */ if (!ntohs(GLOB(bindaddr.sin_port))) { GLOB(bindaddr.sin_port) = ntohs(DEFAULT_SCCP_PORT); } GLOB(bindaddr.sin_family) = AF_INET; /* setup hostname -> externip */ /* \todo change using singular h_addr to h_addr_list (name may resolve to multiple ip-addresses */ struct ast_hostent ahp; struct hostent *hp; if (!sccp_strlen_zero(GLOB(externhost))) { if (!(hp = pbx_gethostbyname(GLOB(externhost), &ahp))) { pbx_log(LOG_WARNING, "Invalid address resolution for externhost keyword: %s\n", GLOB(externhost)); } else { memcpy(&GLOB(externip.sin_addr), hp->h_addr, sizeof(GLOB(externip.sin_addr))); time(&GLOB(externexpire)); } } /* setup regcontext */ char newcontexts[SCCP_MAX_CONTEXT]; char oldcontexts[SCCP_MAX_CONTEXT]; char *stringp, *context, *oldregcontext; sccp_copy_string(newcontexts, GLOB(regcontext), sizeof(newcontexts)); stringp = newcontexts; sccp_copy_string(oldcontexts, GLOB(used_context), sizeof(oldcontexts)); // Initialize copy of current regcontext for later use in removing stale contexts oldregcontext = oldcontexts; cleanup_stale_contexts(stringp, oldregcontext); // Let's remove any contexts that are no longer defined in regcontext while ((context = strsep(&stringp, "&"))) { // Create contexts if they don't exist already sccp_copy_string(GLOB(used_context), context, sizeof(GLOB(used_context))); pbx_context_find_or_create(NULL, NULL, context, "SCCP"); } return TRUE; } /*! * \brief Cleanup Stale Contexts (regcontext) * \param new New Context as Character * \param old Old Context as Character */ void cleanup_stale_contexts(char *new, char *old) { char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[SCCP_MAX_CONTEXT]; while ((oldcontext = strsep(&old, "&"))) { stalecontext = '\0'; sccp_copy_string(newlist, new, sizeof(newlist)); stringp = newlist; while ((newcontext = strsep(&stringp, "&"))) { if (sccp_strequals(newcontext, oldcontext)) { /* This is not the context you're looking for */ stalecontext = '\0'; break; } else if (!sccp_strequals(newcontext, oldcontext)) { stalecontext = oldcontext; } } if (stalecontext) ast_context_destroy(ast_context_find(stalecontext), "SCCP"); } } /*! * \brief Read Lines from the Config File * * \param readingtype as SCCP Reading Type * \since 10.01.2008 - branche V3 * \author Marcello Ceschia * * \callgraph * \callergraph * * \lock * - lines * - see sccp_config_applyLineConfiguration() */ void sccp_config_readDevicesLines(sccp_readingtype_t readingtype) { // struct ast_config *cfg = NULL; char *cat = NULL; PBX_VARIABLE_TYPE *v = NULL; uint8_t device_count = 0; uint8_t line_count = 0; sccp_line_t *l = NULL; sccp_device_t *d = NULL; sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Loading Devices and Lines from config\n"); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Checking Reading Type\n"); if (readingtype == SCCP_CONFIG_READRELOAD) { sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Device Pre Reload\n"); sccp_device_pre_reload(); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Line Pre Reload\n"); sccp_line_pre_reload(); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Softkey Pre Reload\n"); sccp_softkey_pre_reload(); } if (!GLOB(cfg)) { pbx_log(LOG_NOTICE, "SCCP: (sccp_config_readDevicesLines) Unable to load config file sccp.conf, SCCP disabled\n"); return; } while ((cat = pbx_category_browse(GLOB(cfg), cat))) { const char *utype; if (!strcasecmp(cat, "general")) continue; utype = pbx_variable_retrieve(GLOB(cfg), cat, "type"); sccp_log((DEBUGCAT_CONFIG + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: (sccp_config_readDevicesLines) Reading Section Of Type %s\n", utype); if (!utype) { pbx_log(LOG_WARNING, "Section '%s' is missing a type parameter\n", cat); continue; } else if (!strcasecmp(utype, "device")) { // check minimum requirements for a device if (sccp_strlen_zero(pbx_variable_retrieve(GLOB(cfg), cat, "devicetype"))) { pbx_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sccp.conf"); continue; } else { v = ast_variable_browse(GLOB(cfg), cat); // Try to find out if we have the device already on file. // However, do not look into realtime, since // we might have been asked to create a device for realtime addition, // thus causing an infinite loop / recursion. d = sccp_device_find_byid(cat, FALSE); /* create new device with default values */ if (!d) { d = sccp_device_create(cat); // sccp_copy_string(d->id, cat, sizeof(d->id)); /* set device name */ sccp_device_addToGlobals(d); device_count++; } else { if (d->pendingDelete) { d->pendingDelete = 0; } } sccp_config_buildDevice(d, v, cat, FALSE); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_3 "found device %d: %s\n", device_count, cat); /* load saved settings from ast db */ sccp_config_restoreDeviceFeatureStatus(d); d = sccp_device_release(d); } } else if (!strcasecmp(utype, "line")) { /* check minimum requirements for a line */ if ((!(!sccp_strlen_zero(pbx_variable_retrieve(GLOB(cfg), cat, "label"))) && (!sccp_strlen_zero(pbx_variable_retrieve(GLOB(cfg), cat, "cid_name"))) && (!sccp_strlen_zero(pbx_variable_retrieve(GLOB(cfg), cat, "cid_num"))))) { pbx_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sccp.conf"); continue; } line_count++; v = ast_variable_browse(GLOB(cfg), cat); /* check if we have this line already */ SCCP_RWLIST_RDLOCK(&GLOB(lines)); if ((l = sccp_line_find_byname(cat, FALSE))) { sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_3 "found line %d: %s, do update\n", line_count, cat); sccp_config_buildLine(l, v, cat, FALSE); } else { l = sccp_line_create(cat); sccp_config_buildLine(l, v, cat, FALSE); sccp_line_addToGlobals(l); /* may find another line instance create by another thread, in that case the newly created line is going to be dropped when l is released */ } l = l ? sccp_line_release(l) : NULL; /* release either found / or newly created line. will remain retained in glob(lines) anyway. */ SCCP_RWLIST_UNLOCK(&GLOB(lines)); } else if (!strcasecmp(utype, "softkeyset")) { sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_3 "read set %s\n", cat); v = ast_variable_browse(GLOB(cfg), cat); sccp_config_softKeySet(v, cat); } else { pbx_log(LOG_WARNING, "SCCP: (sccp_config_readDevicesLines) UNKNOWN SECTION / UTYPE, type: %s\n", utype); } } #ifdef CS_SCCP_REALTIME /* reload realtime lines */ sccp_configurationchange_t res; sccp_line_t *line = NULL; SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { if ((line = sccp_line_retain(l))) { if (line->realtime == TRUE && line != GLOB(hotline)->line) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_3 "%s: reload realtime line\n", line->name); v = pbx_load_realtime(GLOB(realtimelinetable), "name", line->name, NULL); /* we did not find this line, mark it for deletion */ if (!v) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_3 "%s: realtime line not found - set pendingDelete=1\n", line->name); line->pendingDelete = 1; continue; } res = sccp_config_applyLineConfiguration(line, v); /* check if we did some changes that needs a device update */ if (GLOB(reload_in_progress) && res == SCCP_CONFIG_NEEDDEVICERESET) { line->pendingUpdate = 1; } else { line->pendingUpdate = 0; } pbx_variables_destroy(v); } line = sccp_line_release(line); } } SCCP_RWLIST_UNLOCK(&GLOB(lines)); /* finished realtime line reload */ #endif if (GLOB(reload_in_progress) && GLOB(pendingUpdate)) { sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Global param changed needing restart -> Restart all device\n"); sccp_device_t *device; SCCP_RWLIST_WRLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), device, list) { if (!device->pendingDelete && !device->pendingUpdate) { device->pendingUpdate = 1; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); } else { GLOB(pendingUpdate) = 0; } GLOB(pendingUpdate) = 0; sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Checking Reading Type\n"); if (readingtype == SCCP_CONFIG_READRELOAD) { /* IMPORTANT: The line_post_reload function may change the pendingUpdate field of * devices, so it's really important to call it *before* calling device_post_real(). */ sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Line Post Reload\n"); sccp_line_post_reload(); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Device Post Reload\n"); sccp_device_post_reload(); sccp_log((DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_2 "Softkey Post Reload\n"); sccp_softkey_post_reload(); } } /*! * \brief Get Configured Line from Asterisk Variable * \param l SCCP Line * \param v Asterisk Variable * \return Configured SCCP Line * \note also used by realtime functionality to line device from Asterisk Variable * * \callgraph * \callergraph * * \lock * - line->mailboxes */ sccp_configurationchange_t sccp_config_applyLineConfiguration(sccp_line_t * l, PBX_VARIABLE_TYPE * v) { sccp_configurationchange_t res = SCCP_CONFIG_NOUPDATENEEDED; boolean_t SetEntries[ARRAY_LEN(sccpLineConfigOptions)] = { FALSE }; if (l->pendingDelete) { /* removing variables */ if (l->variables) { pbx_variables_destroy(l->variables); l->variables = NULL; } } for (; v; v = v->next) { res |= sccp_config_object_setValue(l, v->name, v->value, v->lineno, SCCP_CONFIG_LINE_SEGMENT, SetEntries); } sccp_config_set_defaults(l, SCCP_CONFIG_LINE_SEGMENT, SetEntries); if (sccp_strlen_zero(l->id)) { sprintf(l->id, "%04d", SCCP_LIST_GETSIZE(GLOB(lines))); } return res; } /*! * \brief Apply Device Configuration from Asterisk Variable * \param d SCCP Device * \param v Asterisk Variable * \return Configured SCCP Device * \note also used by realtime functionality to line device from Asterisk Variable * \todo this function should be called sccp_config_applyDeviceConfiguration * * \callgraph * \callergraph * * \lock * - device->addons * - device->permithosts */ sccp_configurationchange_t sccp_config_applyDeviceConfiguration(sccp_device_t * d, PBX_VARIABLE_TYPE * v) { sccp_configurationchange_t res = SCCP_CONFIG_NOUPDATENEEDED; boolean_t SetEntries[ARRAY_LEN(sccpDeviceConfigOptions)] = { FALSE }; if (d->pendingDelete) { sccp_dev_clean(d, FALSE, 0); } for (; v; v = v->next) { res |= sccp_config_object_setValue(d, v->name, v->value, v->lineno, SCCP_CONFIG_DEVICE_SEGMENT, SetEntries); } sccp_config_set_defaults(d, SCCP_CONFIG_DEVICE_SEGMENT, SetEntries); if (d->keepalive < SCCP_MIN_KEEPALIVE) { d->keepalive = SCCP_MIN_KEEPALIVE; } return res; } /*! * \brief Find the Correct Config File * \return Asterisk Config Object as ast_config */ sccp_config_file_status_t sccp_config_getConfig(boolean_t force) { // struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS & CONFIG_FLAG_FILEUNCHANGED }; int res = 0; struct ast_flags config_flags = { CONFIG_FLAG_FILEUNCHANGED }; if (force) { pbx_config_destroy(GLOB(cfg)); GLOB(cfg) = NULL; pbx_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED); } if (sccp_strlen_zero(GLOB(config_file_name))) { GLOB(config_file_name) = strdup("sccp.conf"); } GLOB(cfg) = pbx_config_load(GLOB(config_file_name), "chan_sccp", config_flags); if (GLOB(cfg) == CONFIG_STATUS_FILEMISSING) { pbx_log(LOG_ERROR, "Config file '%s' not found, aborting reload.\n", GLOB(config_file_name)); GLOB(cfg) = NULL; res = CONFIG_STATUS_FILE_NOT_FOUND; goto FUNC_EXIT; } else if (GLOB(cfg) == CONFIG_STATUS_FILEINVALID) { pbx_log(LOG_ERROR, "Config file '%s' specified is not a valid config file, aborting reload.\n", GLOB(config_file_name)); GLOB(cfg) = NULL; res = CONFIG_STATUS_FILE_INVALID; goto FUNC_EXIT; } else if (GLOB(cfg) == CONFIG_STATUS_FILEUNCHANGED) { // ugly solution, but we always need to have a valid config file loaded. pbx_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED); GLOB(cfg) = pbx_config_load(GLOB(config_file_name), "chan_sccp", config_flags); if (!force) { pbx_log(LOG_NOTICE, "Config file '%s' has not changed, aborting reload.\n", GLOB(config_file_name)); res = CONFIG_STATUS_FILE_NOT_CHANGED; goto FUNC_EXIT; } else { pbx_log(LOG_NOTICE, "Config file '%s' has not changed, forcing reload.\n", GLOB(config_file_name)); } } if (GLOB(cfg) && ast_variable_browse(GLOB(cfg), "devices")) { /* Warn user when old entries exist in sccp.conf */ pbx_log(LOG_ERROR, "\n\n --> You are using an old configuration format, please update '%s'!!\n --> Loading of module chan_sccp with current sccp.conf has terminated\n --> Check http://chan-sccp-b.sourceforge.net/doc_setup.shtml for more information.\n\n", GLOB(config_file_name)); pbx_config_destroy(GLOB(cfg)); GLOB(cfg) = NULL; res = CONFIG_STATUS_FILE_OLD; goto FUNC_EXIT; } else if (!ast_variable_browse(GLOB(cfg), "general")) { pbx_log(LOG_ERROR, "Missing [general] section, SCCP disabled\n"); pbx_config_destroy(GLOB(cfg)); GLOB(cfg) = NULL; res = CONFIG_STATUS_FILE_NOT_SCCP; goto FUNC_EXIT; } pbx_log(LOG_NOTICE, "Config file '%s' loaded.\n", GLOB(config_file_name)); res = CONFIG_STATUS_FILE_OK; FUNC_EXIT: return res; } /*! * \brief Read a SoftKey configuration context * \param variable list of configuration variables * \param name name of this configuration (context) * * \callgraph * \callergraph * * \lock * - softKeySetConfig */ void sccp_config_softKeySet(PBX_VARIABLE_TYPE * variable, const char *name) { int keySetSize; sccp_softKeySetConfiguration_t *softKeySetConfiguration = NULL; int keyMode = -1; unsigned int i = 0; sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "start reading softkeyset: %s\n", name); SCCP_LIST_LOCK(&softKeySetConfig); SCCP_LIST_TRAVERSE(&softKeySetConfig, softKeySetConfiguration, list) { if (!strcasecmp(softKeySetConfiguration->name, name)) break; } SCCP_LIST_UNLOCK(&softKeySetConfig); if (!softKeySetConfiguration) { softKeySetConfiguration = sccp_calloc(1, sizeof(sccp_softKeySetConfiguration_t)); memset(softKeySetConfiguration, 0, sizeof(sccp_softKeySetConfiguration_t)); sccp_copy_string(softKeySetConfiguration->name, name, sizeof(sccp_softKeySetConfiguration_t)); softKeySetConfiguration->numberOfSoftKeySets = 0; /* add new softkexSet to list */ SCCP_LIST_LOCK(&softKeySetConfig); SCCP_LIST_INSERT_HEAD(&softKeySetConfig, softKeySetConfiguration, list); SCCP_LIST_UNLOCK(&softKeySetConfig); } while (variable) { keyMode = -1; sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "softkeyset: %s \n", variable->name); if (!strcasecmp(variable->name, "type")) { } else if (!strcasecmp(variable->name, "onhook")) { keyMode = KEYMODE_ONHOOK; } else if (!strcasecmp(variable->name, "connected")) { keyMode = KEYMODE_CONNECTED; } else if (!strcasecmp(variable->name, "onhold")) { keyMode = KEYMODE_ONHOLD; } else if (!strcasecmp(variable->name, "ringin")) { keyMode = KEYMODE_RINGIN; } else if (!strcasecmp(variable->name, "offhook")) { keyMode = KEYMODE_OFFHOOK; } else if (!strcasecmp(variable->name, "conntrans")) { keyMode = KEYMODE_CONNTRANS; } else if (!strcasecmp(variable->name, "digitsfoll")) { keyMode = KEYMODE_DIGITSFOLL; } else if (!strcasecmp(variable->name, "connconf")) { keyMode = KEYMODE_CONNCONF; } else if (!strcasecmp(variable->name, "ringout")) { keyMode = KEYMODE_RINGOUT; } else if (!strcasecmp(variable->name, "offhookfeat")) { keyMode = KEYMODE_OFFHOOKFEAT; } else if (!strcasecmp(variable->name, "onhint")) { keyMode = KEYMODE_INUSEHINT; } else { // do nothing } if (keyMode == -1) { variable = variable->next; continue; } if (softKeySetConfiguration->numberOfSoftKeySets < (keyMode + 1)) { softKeySetConfiguration->numberOfSoftKeySets = keyMode + 1; } for (i = 0; i < (sizeof(SoftKeyModes) / sizeof(softkey_modes)); i++) { if (SoftKeyModes[i].id == keyMode) { /* cleanup old value */ if (softKeySetConfiguration->modes[i].ptr) sccp_free(softKeySetConfiguration->modes[i].ptr); uint8_t *softkeyset = sccp_calloc(StationMaxSoftKeySetDefinition, sizeof(uint8_t)); keySetSize = sccp_config_readSoftSet(softkeyset, variable->value); if (keySetSize > 0) { softKeySetConfiguration->modes[i].id = keyMode; softKeySetConfiguration->modes[i].ptr = softkeyset; softKeySetConfiguration->modes[i].count = keySetSize; } else { softKeySetConfiguration->modes[i].ptr = NULL; softKeySetConfiguration->modes[i].count = 0; sccp_free(softkeyset); } } } variable = variable->next; } } /*! * \brief Read a single SoftKeyMode (configuration values) * \param softkeyset SoftKeySet * \param data configuration values * \return number of parsed softkeys */ uint8_t sccp_config_readSoftSet(uint8_t * softkeyset, const char *data) { int i = 0, j; char labels[256]; char *splitter; char *label; if (!data) return 0; strcpy(labels, data); splitter = labels; while ((label = strsep(&splitter, ",")) != NULL && (i + 1) < StationMaxSoftKeySetDefinition) { softkeyset[i++] = sccp_config_getSoftkeyLbl(label); } for (j = i + 1; j < StationMaxSoftKeySetDefinition; j++) { softkeyset[j] = SKINNY_LBL_EMPTY; } return i; } /*! * \brief Get softkey label as int * \param key configuration value * \return SoftKey label as int of SKINNY_LBL_*. returns an empty button if nothing matched */ int sccp_config_getSoftkeyLbl(char *key) { int i = 0; int size = sizeof(softKeyTemplate) / sizeof(softkeyConfigurationTemplate); for (i = 0; i < size; i++) { if (!strcasecmp(softKeyTemplate[i].configVar, key)) { return softKeyTemplate[i].softkey; } } sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "softkeybutton: %s not defined", key); return SKINNY_LBL_EMPTY; } /*! * \brief Restore feature status from ast-db * \param device device to be restored * \todo restore cfwd feature * * \callgraph * \callergraph * * \lock * - device->devstateSpecifiers */ void sccp_config_restoreDeviceFeatureStatus(sccp_device_t * device) { if (!device) return; #ifdef CS_DEVSTATE_FEATURE char buf[256] = ""; sccp_devstate_specifier_t *specifier; #endif #ifndef ASTDB_FAMILY_KEY_LEN #define ASTDB_FAMILY_KEY_LEN 256 #endif #ifndef ASTDB_RESULT_LEN #define ASTDB_RESULT_LEN 256 #endif char buffer[ASTDB_RESULT_LEN]; char timebuffer[ASTDB_RESULT_LEN]; int timeout = 0; char family[ASTDB_FAMILY_KEY_LEN]; sprintf(family, "SCCP/%s", device->id); /* dndFeature */ if (PBX(feature_getFromDatabase) (family, "dnd", buffer, sizeof(buffer))) { if (!strcasecmp(buffer, "silent")) device->dndFeature.status = SCCP_DNDMODE_SILENT; else device->dndFeature.status = SCCP_DNDMODE_REJECT; } else { device->dndFeature.status = SCCP_DNDMODE_OFF; } // /* monitorFeature */ // if (PBX(feature_getFromDatabase)(family, "monitor", buffer, sizeof(buffer))) { // device->monitorFeature.status |= SCCP_FEATURE_MONITOR_STATE_REQUESTED; // } else { // device->monitorFeature.status = 0; // } /* privacyFeature */ if (PBX(feature_getFromDatabase) (family, "privacy", buffer, sizeof(buffer))) { sscanf(buffer, "%u", (unsigned int *) &device->privacyFeature.status); } else { device->privacyFeature.status = 0; } /* Message */ if (PBX(feature_getFromDatabase) ("SCCP/message", "text", buffer, sizeof(buffer))) { if (!sccp_strlen_zero(buffer)) { if (PBX(feature_getFromDatabase) && PBX(feature_getFromDatabase) ("SCCP/message", "timeout", timebuffer, sizeof(timebuffer))) { sscanf(timebuffer, "%i", &timeout); } if (timeout) { sccp_dev_displayprinotify(device, buffer, 5, timeout); } else { sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_IDLE, buffer); } } } /* lastDialedNumber */ char lastNumber[SCCP_MAX_EXTENSION] = ""; if (PBX(feature_getFromDatabase) (family, "lastDialedNumber", lastNumber, sizeof(lastNumber))) { if (!sccp_strlen_zero(lastNumber)) { sccp_copy_string(device->lastNumber, lastNumber, sizeof(device->lastNumber)); } } /* initialize so called priority feature */ device->priFeature.status = 0x010101; device->priFeature.initialized = 0; #ifdef CS_DEVSTATE_FEATURE /* Read and initialize custom devicestate entries */ SCCP_LIST_LOCK(&device->devstateSpecifiers); SCCP_LIST_TRAVERSE(&device->devstateSpecifiers, specifier, list) { /* Check if there is already a devicestate entry */ if (PBX(feature_getFromDatabase) (devstate_db_family, specifier->specifier, buf, sizeof(buf))) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_1 "%s: Found Existing Custom Devicestate Entry: %s, state: %s\n", device->id, specifier->specifier, buf); } else { /* If not present, add a new devicestate entry. Default: NOT_INUSE */ PBX(feature_addToDatabase) (devstate_db_family, specifier->specifier, "NOT_INUSE"); sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_1 "%s: Initialized Devicestate Entry: %s\n", device->id, specifier->specifier); } /* Register as generic hint watcher */ /*! \todo Add some filtering in order to reduce number of unnecessarily triggered events. Have to work out whether filtering with AST_EVENT_IE_DEVICE matches extension or hint device name. */ snprintf(buf, 254, "Custom:%s", specifier->specifier); /* When registering for devstate events we wish to know if a single asterisk box has contributed a change even in a rig of multiple asterisk with distributed devstate. This is to enable toggling even then when otherwise the aggregate devicestate would obscure the change. However, we need to force distributed devstate even on single asterisk boxes so to get the desired events. (-DD) */ #if defined(CS_AST_HAS_EVENT) && (defined(CS_DEVICESTATE) || defined(CS_CACHEABLE_DEVICESTATE)) pbx_enable_distributed_devstate(); specifier->sub = pbx_event_subscribe(AST_EVENT_DEVICE_STATE, sccp_devstateFeatureState_cb, "devstate subscription", device, AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, buf, AST_EVENT_IE_END); #endif } SCCP_LIST_UNLOCK(&device->devstateSpecifiers); #endif } int sccp_manager_config_metadata(struct mansession *s, const struct message *m) { const SCCPConfigSegment *sccpConfigSegment = NULL; const SCCPConfigOption *config = NULL; long unsigned int sccp_option; char idtext[256]; int total = 0; int i; const char *id = astman_get_header(m, "ActionID"); const char *req_segment = astman_get_header(m, "Segment"); const char *req_option = astman_get_header(m, "Option"); char *description; char *description_part; if (strlen(req_segment) == 0) { // return all segments astman_send_listack(s, m, "List of segments will follow", "start"); for (i = 0; i < ARRAY_LEN(sccpConfigSegments); i++) { astman_append(s, "Event: SegmentEntry\r\n"); astman_append(s, "Segment: %s\r\n\r\n", sccpConfigSegments[i].name); total++; } astman_append(s, "Event: SegmentlistComplete\r\n\r\n"); } else if (strlen(req_option) == 0) { // return all options for segment astman_send_listack(s, m, "List of SegmentOptions will follow", "start"); for (i = 0; i < ARRAY_LEN(sccpConfigSegments); i++) { if (!strcasecmp(sccpConfigSegments[i].name, req_segment)) { sccpConfigSegment = &sccpConfigSegments[i]; config = sccpConfigSegment->config; for (sccp_option = 0; sccp_option < sccpConfigSegment->config_size; sccp_option++) { astman_append(s, "Event: OptionEntry\r\n"); astman_append(s, "Segment: %s\r\n", sccpConfigSegment->name); astman_append(s, "Option: %s\r\n\r\n", config[sccp_option].name); total++; } total++; } } if (0 == total) { astman_append(s, "error: segment %s not found\r\n", req_segment); } else { astman_append(s, "Event: SegmentOptionlistComplete\r\n\r\n"); } } else { // return metadata for option in segmnet astman_send_listack(s, m, "List of Option Attributes will follow", "start"); for (i = 0; i < ARRAY_LEN(sccpConfigSegments); i++) { if (!strcasecmp(sccpConfigSegments[i].name, req_segment)) { sccpConfigSegment = &sccpConfigSegments[i]; config = sccp_find_config(sccpConfigSegments[i].segment, req_option); if (config) { if ((config->flags & SCCP_CONFIG_FLAG_IGNORE) != SCCP_CONFIG_FLAG_IGNORE) { char *possible_values = NULL; astman_append(s, "Event: AttributeEntry\r\n"); astman_append(s, "Segment: %s\r\n", sccpConfigSegment->name); astman_append(s, "Option: %s\r\n", config->name); astman_append(s, "Size: %d\r\n", (int) config->size); astman_append(s, "Required: %s\r\n", ((config->flags & SCCP_CONFIG_FLAG_REQUIRED) == SCCP_CONFIG_FLAG_REQUIRED) ? "true" : "false"); astman_append(s, "Deprecated: %s\r\n", ((config->flags & SCCP_CONFIG_FLAG_DEPRECATED) == SCCP_CONFIG_FLAG_DEPRECATED) ? "true" : "false"); astman_append(s, "Obsolete: %s\r\n", ((config->flags & SCCP_CONFIG_FLAG_OBSOLETE) == SCCP_CONFIG_FLAG_OBSOLETE) ? "true" : "false"); astman_append(s, "Multientry: %s\r\n", ((config->flags & SCCP_CONFIG_FLAG_MULTI_ENTRY) == SCCP_CONFIG_FLAG_MULTI_ENTRY) ? "true" : "false"); astman_append(s, "RestartRequiredOnUpdate: %s\r\n", ((config->change & SCCP_CONFIG_NEEDDEVICERESET) == SCCP_CONFIG_NEEDDEVICERESET) ? "true" : "false"); switch (config->type) { case SCCP_CONFIG_DATATYPE_BOOLEAN: astman_append(s, "Type: BOOLEAN\r\n"); break; case SCCP_CONFIG_DATATYPE_INT: astman_append(s, "Type: INT\r\n"); break; case SCCP_CONFIG_DATATYPE_UINT: astman_append(s, "Type: UNSIGNED INT\r\n"); break; case SCCP_CONFIG_DATATYPE_STRINGPTR: case SCCP_CONFIG_DATATYPE_STRING: astman_append(s, "Type: STRING\r\n"); break; case SCCP_CONFIG_DATATYPE_PARSER: astman_append(s, "Type: PARSER\r\n"); astman_append(s, "possible_values: %s\r\n", ""); break; case SCCP_CONFIG_DATATYPE_CHAR: astman_append(s, "Type: CHAR\r\n"); break; } if (config->defaultValue && !strlen(config->defaultValue) == 0) { astman_append(s, "DefaultValue: %s\r\n", config->defaultValue); } if (strlen(config->description) != 0) { // description=malloc(sizeof(char) * strlen(config->description)); description = strdupa(config->description); astman_append(s, "Description: "); while (description && (description_part = strsep(&description, "\n"))) { astman_append(s, "%s ", description_part); } if (!sccp_strlen_zero(possible_values)) { astman_append(s, "(POSSIBLE VALUES: %s)\r\n", possible_values); } if (description_part) { sccp_free(description_part); } // sccp_free(description); } astman_append(s, "\r\n"); if (possible_values) { sccp_free(possible_values); } total++; } } else { astman_append(s, "error: option %s in segment %s not found\r\n", req_option, req_segment); total++; } } } if (0 == total) { astman_append(s, "error: segment %s not found\r\n", req_segment); total++; } else { astman_append(s, "Event: SegmentOptionAttributelistComplete\r\n\r\n"); } } snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id); astman_append(s, "EventList: Complete\r\n" "ListItems: %d\r\n" "%s" "\r\n", total, idtext); return 0; } /*! * \brief Generate default sccp.conf file * \param filename Filename * \param configType Config Type: * - 0 = templated + registered devices * - 1 = required params only * - 2 = all params * \todo Add functionality */ int sccp_config_generate(char *filename, int configType) { const SCCPConfigSegment *sccpConfigSegment = NULL; const SCCPConfigOption *config = NULL; long unsigned int sccp_option; long unsigned int segment; char *description; char *description_part; char name_and_value[100]; int linelen = 0; char fn[PATH_MAX]; snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, "sccp.conf.test"); pbx_log(LOG_NOTICE, "Creating new config file '%s'\n", fn); FILE *f; if (!(f = fopen(fn, "w"))) { pbx_log(LOG_ERROR, "Error creating new config file \n"); return 1; } char date[256] = ""; time_t t; time(&t); sccp_copy_string(date, ctime(&t), sizeof(date)); fprintf(f, ";!\n"); fprintf(f, ";! Automatically generated configuration file\n"); fprintf(f, ";! Filename: %s (%s)\n", filename, fn); fprintf(f, ";! Generator: sccp config generate\n"); fprintf(f, ";! Creation Date: %s", date); fprintf(f, ";!\n"); fprintf(f, "\n"); for (segment = SCCP_CONFIG_GLOBAL_SEGMENT; segment <= SCCP_CONFIG_SOFTKEY_SEGMENT; segment++) { sccpConfigSegment = sccp_find_segment(segment); if (configType == 0 && (segment == SCCP_CONFIG_DEVICE_SEGMENT || segment == SCCP_CONFIG_LINE_SEGMENT)) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "adding [%s] template section\n", sccpConfigSegment->name); fprintf(f, "\n;\n; %s section\n;\n[default_%s](!)\n", sccpConfigSegment->name, sccpConfigSegment->name); } else { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "adding [%s] section\n", sccpConfigSegment->name); fprintf(f, "\n;\n; %s section\n;\n[%s]\n", sccpConfigSegment->name, sccpConfigSegment->name); } config = sccpConfigSegment->config; for (sccp_option = 0; sccp_option < sccpConfigSegment->config_size; sccp_option++) { if ((config[sccp_option].flags & SCCP_CONFIG_FLAG_IGNORE & SCCP_CONFIG_FLAG_DEPRECATED & SCCP_CONFIG_FLAG_OBSOLETE) == 0) { sccp_log(DEBUGCAT_CONFIG) (VERBOSE_PREFIX_2 "adding name: %s, default_value: %s\n", config[sccp_option].name, config[sccp_option].defaultValue); if (!sccp_strlen_zero(config[sccp_option].name)) { if (!sccp_strlen_zero(config[sccp_option].defaultValue) // non empty || (configType != 2 && ((config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) != SCCP_CONFIG_FLAG_REQUIRED && sccp_strlen_zero(config[sccp_option].defaultValue))) // empty but required ) { snprintf(name_and_value, sizeof(name_and_value), "%s = %s", config[sccp_option].name, sccp_strlen_zero(config[sccp_option].defaultValue) ? "\"\"" : config[sccp_option].defaultValue); linelen = (int) strlen(name_and_value); fprintf(f, "%s", name_and_value); if (!sccp_strlen_zero(config[sccp_option].description)) { description = sccp_strdupa(config[sccp_option].description); while ((description_part = strsep(&description, "\n"))) { if (!sccp_strlen_zero(description_part)) { fprintf(f, "%*.s ; %s%s%s\n", 81 - linelen, " ", (config[sccp_option].flags & SCCP_CONFIG_FLAG_REQUIRED) == SCCP_CONFIG_FLAG_REQUIRED ? "(REQUIRED) " : "", ((config[sccp_option].flags & SCCP_CONFIG_FLAG_MULTI_ENTRY) == SCCP_CONFIG_FLAG_MULTI_ENTRY) ? "(MULTI-ENTRY)" : "", description_part); linelen = 0; } } } else { fprintf(f, "\n"); } } } else { pbx_log(LOG_ERROR, "Error creating new variable structure for %s='%s'\n", config[sccp_option].name, config[sccp_option].defaultValue); fclose(f); return 2; } } } sccp_log(DEBUGCAT_CONFIG) ("\n"); } fclose(f); return 0; };
722,245
./chan-sccp-b/src/sccp_actions.c
/*! * \file sccp_actions.c * \brief SCCP Actions Class * \author Sergio Chersovani <mlists [at] c-net.it> * \author Federico Santulli <fsantulli [at] users.sourceforge.net> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ /*! * \remarks Purpose: SCCP Actions * When to use: Only methods directly related to sccp actions should be stored in this source file. * Actions handle all the message interactions from and to SCCP phones * Relationships: Other Function wanting to communicate to phones * Phones Requesting function to be performed */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") #include <math.h> #if ASTERISK_VERSION_NUMBER < 10400 /* ! *\brief Host Access Rule Structure */ struct ast_ha { /* Host access rule */ struct in_addr netaddr; struct in_addr netmask; int sense; struct ast_ha *next; }; #endif /*! * \brief Handle Alarm * \param no_s SCCP Session = NULL * \param no_d SCCP Device = NULL * \param r SCCP MOO */ void sccp_handle_alarm(sccp_session_t * no_s, sccp_device_t * no_d, sccp_moo_t * r) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Alarm Message: Severity: %s (%d), %s [%d/%d]\n", alarm2str(letohl(r->msg.AlarmMessage.lel_alarmSeverity)), letohl(r->msg.AlarmMessage.lel_alarmSeverity), r->msg.AlarmMessage.text, letohl(r->msg.AlarmMessage.lel_parm1), letohl(r->msg.AlarmMessage.lel_parm2)); } /*! * \brief Handle Unknown Message * \param no_s SCCP Session = NULL * \param no_d SCCP Device = NULL * \param r SCCP Moo * * Interesting values for Last = * 0 Phone Load Is Rejected * 1 Phone Load TFTP Size Error * 2 Phone Load Compressor Error * 3 Phone Load Version Error * 4 Disk Full Error * 5 Checksum Error * 6 Phone Load Not Found in TFTP Server * 7 TFTP Timeout * 8 TFTP Access Error * 9 TFTP Error * 10 CCM TCP Connection timeout * 11 CCM TCP Connection Close because of bad Ack * 12 CCM Resets TCP Connection * 13 CCM Aborts TCP Connection * 14 CCM TCP Connection Closed * 15 CCM TCP Connection Closed because ICMP Unreachable * 16 CCM Rejects TCP Connection * 17 Keepalive Time Out * 18 Fail Back to Primary CCM * 20 User Resets Phone By Keypad * 21 Phone Resets because IP configuration * 22 CCM Resets Phone * 23 CCM Restarts Phone * 24 CCM Rejects Phone Registration * 25 Phone Initializes * 26 CCM TCP Connection Closed With Unknown Reason * 27 Waiting For State From CCM * 28 Waiting For Response From CCM * 29 DSP Alarm * 30 Phone Abort CCM TCP Connection * 31 File Authorization Failed */ void sccp_handle_unknown_message(sccp_session_t * no_s, sccp_device_t * no_d, sccp_moo_t * r) { uint32_t mid = letohl(r->header.lel_messageId); if ((GLOB(debug) & DEBUGCAT_MESSAGE) != 0) { // only show when debugging messages pbx_log(LOG_WARNING, "Unhandled SCCP Message: %s(0x%04X) %d bytes length\n", message2str(mid), mid, r->header.length); sccp_dump_packet((unsigned char *) &r->msg, r->header.length); } } /*! * \brief Handle Unknown Message * \param no_s SCCP Session = NULL * \param no_d SCCP Device = NULL * \param r SCCP Moo */ void sccp_handle_XMLAlarmMessage(sccp_session_t * no_s, sccp_device_t * no_d, sccp_moo_t * r) { uint32_t mid = letohl(r->header.lel_messageId); char alarmName[101]; int reasonEnum; char lastProtocolEventSent[101]; char lastProtocolEventReceived[101]; /* char *deviceName = ""; char neighborIpv4Address[15]; char neighborIpv6Address[41]; char neighborDeviceID[StationMaxNameSize]; char neighborPortID[StationMaxNameSize]; */ char *xmlData = sccp_strdupa((char *) &r->msg.RegisterMessage); char *state; char *line; for (line = strtok_r(xmlData, "\n", &state); line != NULL; line = strtok_r(NULL, "\n", &state)) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s\n", line); /* if (sscanf(line, "<String name=\"%[a-zA-Z]\">", deviceName) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Device Name: %s\n", deviceName); } */ if (sscanf(line, "<Alarm Name=\"%[a-zA-Z]\">", alarmName) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Alarm Type: %s\n", alarmName); } if (sscanf(line, "<Enum name=\"ReasonForOutOfService\">%d</Enum>>", &reasonEnum) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Reason Enum: %d\n", reasonEnum); } if (sscanf(line, "<String name=\"LastProtocolEventSent\">%[^<]</String>", lastProtocolEventSent) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Last Event Sent: %s\n", lastProtocolEventSent); } if (sscanf(line, "<String name=\"LastProtocolEventReceived\">%[^<]</String>", lastProtocolEventReceived) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Last Event Received: %s\n", lastProtocolEventReceived); } /* We might want to capture this information for later use (For example in a VideoAdvantage like project) */ /* if (sscanf(line, "<String name=\"NeighborIPv4Address\">%[^<]</String>", neighborIpv4Address) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "neighborIpv4Address: %s\n", neighborIpv4Address); } if (sscanf(line, "<String name=\"NeighborIPv6Address\">%[^<]</String>", neighborIpv6Address) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "neighborIpv6Address: %s\n", neighborIpv6Address); } if (sscanf(line, "<String name=\"NeighborDeviceID\">%[^<]</String>", neighborDeviceID) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "neighborDeviceID: %s\n", neighborDeviceID); } if (sscanf(line, "<String name=\"NeighborPortID\">%[^<]</String>", neighborPortID) == 1) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "neighborPortID: %s\n", neighborPortID); } */ } if ((GLOB(debug) & DEBUGCAT_MESSAGE) != 0) { // only show when debugging messages pbx_log(LOG_WARNING, "SCCP XMLAlarm Message: %s(0x%04X) %d bytes length\n", message2str(mid), mid, r->header.length); sccp_dump_packet((unsigned char *) &r->msg.RegisterMessage, r->header.length); } } /*! * \brief Handle Token Request * * If a fall-back server has been entered in the phones cnf.xml file and the phone has fallen back to a secundairy server * it will send a tokenreq to the primairy every so often (secundaity keep alive timeout ?). Once the primairy server sends * a token acknowledgement the switches back. * * \param s SCCP Session * \param no_d SCCP Device = NULL * \param r SCCP Moo * * \callgraph * \callergraph * * \todo Implement a decision when to send RegisterTokenAck and when to send RegisterTokenReject * If sending RegisterTokenReject what should the lel_tokenRejWaitTime (BackOff time) be */ void sccp_handle_token_request(sccp_session_t * s, sccp_device_t * no_d, sccp_moo_t * r) { sccp_device_t *device; char *deviceName = ""; uint32_t serverInstance = 0; uint32_t deviceInstance = 0; uint32_t deviceType = 0; deviceName = sccp_strdupa(r->msg.RegisterTokenRequest.sId.deviceName); serverInstance = letohl(r->msg.RegisterTokenRequest.sId.lel_instance); // should be named deviceInstance as in handle_register deviceInstance = letohl(r->msg.RegisterTokenRequest.sId.lel_instance); deviceType = letohl(r->msg.RegisterTokenRequest.lel_deviceType); // sccp_dump_packet((unsigned char *)&r->msg.RegisterTokenRequest, r->header.length); sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_2 "%s: is requesting a Token, Instance: %d, Type: %s (%d)\n", deviceName, deviceInstance, devicetype2str(deviceType), deviceType); // Search for already known devices -> Cleanup device = sccp_device_find_byid(deviceName, TRUE); if (!device && GLOB(allowAnonymous)) { device = sccp_device_createAnonymous(r->msg.RegisterMessage.sId.deviceName); sccp_config_applyDeviceConfiguration(device, NULL); sccp_config_addButton(&device->buttonconfig, 1, LINE, GLOB(hotline)->line->name, NULL, NULL); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: hotline name: %s\n", deviceName, GLOB(hotline)->line->name); device->defaultLineInstance = 1; sccp_device_addToGlobals(device); } /* no configuation for this device and no anonymous devices allowed */ if (!device) { pbx_log(LOG_NOTICE, "%s: Rejecting device: not found\n", deviceName); s = sccp_session_reject(s, "Unknown Device"); goto EXITFUNC; } s->device = sccp_session_addDevice(s, device); // retained in session device->status.token = SCCP_TOKEN_STATE_REJ; device->skinny_type = deviceType; if (device->checkACL(device) == FALSE) { pbx_log(LOG_NOTICE, "%s: Rejecting device: Ip address '%s' denied (deny + permit/permithosts).\n", r->msg.RegisterMessage.sId.deviceName, pbx_inet_ntoa(s->sin.sin_addr)); device->registrationState = SKINNY_DEVICE_RS_FAILED; s = sccp_session_reject(s, "IP Not Authorized"); goto EXITFUNC; } if (device->session && device->session != s) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: Crossover device registration!\n", device->id); device->registrationState = SKINNY_DEVICE_RS_FAILED; sccp_session_tokenReject(s, GLOB(token_backoff_time)); s = sccp_session_reject(s, "Crossover session not allowed"); device->session = sccp_session_reject(device->session, "Crossover session not allowed"); goto EXITFUNC; } /* all checks passed, assign session to device */ // device->session = s; /*Currently rejecting token until further notice */ boolean_t sendAck = FALSE; int last_digit = deviceName[strlen(deviceName)]; if (!strcasecmp("true", GLOB(token_fallback))) { /* we are the primary server */ if (serverInstance == 1) { // need to check if it gets increased by changing xml.cnf member priority ? sendAck = TRUE; } } else if (!strcasecmp("odd", GLOB(token_fallback))) { if (last_digit % 2 != 0) sendAck = TRUE; } else if (!strcasecmp("even", GLOB(token_fallback))) { if (last_digit % 2 == 0) sendAck = TRUE; } /* some test to detect active calls */ sccp_log((DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: serverInstance: %d, unknown: %d, active call? %s\n", deviceName, serverInstance, letohl(r->msg.RegisterTokenRequest.unknown), (letohl(r->msg.RegisterTokenRequest.unknown) & 0x6) ? "yes" : "no"); device->registrationState = SKINNY_DEVICE_RS_TOKEN; if (sendAck) { sccp_log((DEBUGCAT_ACTION + DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Sending phone a token acknowledgement\n", deviceName); sccp_session_tokenAck(s); } else { sccp_log((DEBUGCAT_ACTION + DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Sending phone a token rejection (sccp.conf:fallback=%s, serverInstance=%d), ask again in '%d' seconds\n", deviceName, GLOB(token_fallback), serverInstance, GLOB(token_backoff_time)); sccp_session_tokenReject(s, GLOB(token_backoff_time)); } device->status.token = (sendAck) ? SCCP_TOKEN_STATE_ACK : SCCP_TOKEN_STATE_REJ; device->registrationTime = time(0); // last time device tried sending token EXITFUNC: device = device ? sccp_device_release(device) : NULL; } /*! * \brief Handle Token Request for SPCP phones * * If a fall-back server has been entered in the phones cnf.xml file and the phone has fallen back to a secundairy server * it will send a tokenreq to the primairy every so often (secundaity keep alive timeout ?). Once the primairy server sends * a token acknowledgement the switches back. * * \param s SCCP Session * \param no_d SCCP Device = NULL * \param r SCCP Moo * * \callgraph * \callergraph * * \todo Implement a decision when to send RegisterTokenAck and when to send RegisterTokenReject * If sending RegisterTokenReject what should the lel_tokenRejWaitTime (BackOff time) be */ void sccp_handle_SPCPTokenReq(sccp_session_t * s, sccp_device_t * no_d, sccp_moo_t * r) { sccp_device_t *device = NULL; uint32_t deviceInstance = 0; uint32_t deviceType = 0; deviceInstance = letohl(r->msg.SPCPRegisterTokenRequest.sId.lel_instance); deviceType = letohl(r->msg.SPCPRegisterTokenRequest.lel_deviceType); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_2 "%s: is requestin a token, Instance: %d, Type: %s (%d)\n", r->msg.SPCPRegisterTokenRequest.sId.deviceName, deviceInstance, devicetype2str(deviceType), deviceType); /* ip address range check */ if (GLOB(ha) && !sccp_apply_ha(GLOB(ha), &s->sin)) { pbx_log(LOG_NOTICE, "%s: Rejecting device: Ip address denied\n", r->msg.SPCPRegisterTokenRequest.sId.deviceName); s = sccp_session_reject(s, "IP not authorized"); goto EXITFUNC; } // Search for already known devices device = sccp_device_find_byid(r->msg.SPCPRegisterTokenRequest.sId.deviceName, TRUE); if (device) { if (device->session && device->session != s) { device->registrationState = SKINNY_DEVICE_RS_TIMEOUT; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: Device is doing a re-registration!\n", device->id); device->session->session_stop = 1; /* do not lock session, this will produce a deadlock, just stop the thread-> everything else will be done by thread it self */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Previous Session for %s Closed!\n", device->id); } } device = device ? sccp_device_release(device) : NULL; // search for all devices including realtime device = sccp_device_find_byid(r->msg.SPCPRegisterTokenRequest.sId.deviceName, TRUE); if (!device && GLOB(allowAnonymous)) { device = sccp_device_createAnonymous(r->msg.SPCPRegisterTokenRequest.sId.deviceName); sccp_config_applyDeviceConfiguration(device, NULL); sccp_config_addButton(&device->buttonconfig, 1, LINE, GLOB(hotline)->line->name, NULL, NULL); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: hotline name: %s\n", r->msg.SPCPRegisterTokenRequest.sId.deviceName, GLOB(hotline)->line->name); device->defaultLineInstance = 1; sccp_device_addToGlobals(device); } /* no configuation for this device and no anonymous devices allowed */ if (!device) { pbx_log(LOG_NOTICE, "%s: Rejecting device: not found\n", r->msg.SPCPRegisterTokenRequest.sId.deviceName); sccp_session_tokenRejectSPCP(s, 60); s = sccp_session_reject(s, "Device not Accepted"); goto EXITFUNC; } s->protocolType = SPCP_PROTOCOL; // s->device = sccp_device_retain(device); //retained in session s->device = sccp_session_addDevice(s, device); // retained in session device->status.token = SCCP_TOKEN_STATE_REJ; device->skinny_type = deviceType; if (device->checkACL(device) == FALSE) { pbx_log(LOG_NOTICE, "%s: Rejecting device: Ip address '%s' denied (deny + permit/permithosts).\n", r->msg.SPCPRegisterTokenRequest.sId.deviceName, pbx_inet_ntoa(s->sin.sin_addr)); device->registrationState = SKINNY_DEVICE_RS_FAILED; sccp_session_tokenRejectSPCP(s, 60); s = sccp_session_reject(s, "IP Not Authorized"); goto EXITFUNC; } if (device->session && device->session != s) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: Crossover device registration!\n", device->id); device->registrationState = SKINNY_DEVICE_RS_FAILED; sccp_session_tokenRejectSPCP(s, 60); s = sccp_session_reject(s, "Crossover session not allowed"); device->session = sccp_session_reject(device->session, "Crossover session not allowed"); goto EXITFUNC; } /* all checks passed, assign session to device */ // device->session = s; device->registrationState = SKINNY_DEVICE_RS_TOKEN; device->status.token = SCCP_TOKEN_STATE_ACK; sccp_session_tokenAckSPCP(s, 65535); device->registrationTime = time(0); // last time device tried sending token EXITFUNC: device = device ? sccp_device_release(device) : NULL; } /*! * \brief Handle Device Registration * \param s SCCP Session * \param maybe_d SCCP Device * \param r SCCP Moo * * \callgraph * \callergraph */ void sccp_handle_register(sccp_session_t * s, sccp_device_t * maybe_d, sccp_moo_t * r) { sccp_device_t *device; uint8_t protocolVer = letohl(r->msg.RegisterMessage.phone_features) & SKINNY_PHONE_FEATURES_PROTOCOLVERSION; uint8_t ourMaxSupportedProtocolVersion = sccp_protocol_getMaxSupportedVersionNumber(s->protocolType); uint32_t deviceInstance = 0; uint32_t deviceType = 0; deviceInstance = letohl(r->msg.RegisterMessage.sId.lel_instance); deviceType = letohl(r->msg.RegisterMessage.lel_deviceType); sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_1 "%s: is registering, Instance: %d, Type: %s (%d), Version: %d (loadinfo '%s')\n", r->msg.RegisterMessage.sId.deviceName, deviceInstance, devicetype2str(deviceType), deviceType, protocolVer, r->msg.RegisterMessage.loadInfo); #ifdef CS_EXPERIMENTAL_NEWIP socklen_t addrlen = 0; struct sockaddr_storage *session_ss = { 0 }; struct sockaddr_storage *ss = { 0 }; char iabuf[INET6_ADDRSTRLEN]; struct sockaddr_in sin = { 0 }; if (0 != r->msg.RegisterMessage.lel_stationIpAddr) { sin.sin_family = AF_INET; memcpy(&sin.sin_addr, &r->msg.RegisterMessage.lel_stationIpAddr, 4); inet_ntop(AF_INET, &sin.sin_addr, iabuf, (socklen_t) INET_ADDRSTRLEN); sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_1 "%s: IPv4-Address: %s\n", r->msg.RegisterMessage.sId.deviceName, iabuf); ss = (struct sockaddr_storage *) &sin; } #ifdef CS_IPV6 struct sockaddr_in6 sin6 = { 0 }; if (0 != r->msg.RegisterMessage.ipv6Address) { sin6.sin6_family = AF_INET6; memcpy(&sin6.sin6_addr, &r->msg.RegisterMessage.lel_stationIpAddr, 16); inet_ntop(AF_INET6, &sin6.sin6_addr, iabuf, (socklen_t) INET6_ADDRSTRLEN); sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_1 "%s: IPv6-Address: %s\n", r->msg.RegisterMessage.sId.deviceName, iabuf); ss = (struct sockaddr_storage *) &sin6; } #endif #else s->phone_sin.sin_family = AF_INET; memcpy(&s->phone_sin.sin_addr, &r->msg.RegisterMessage.lel_stationIpAddr, 4); #endif // search for all devices including realtime if (!maybe_d) { device = sccp_device_find_byid(r->msg.RegisterMessage.sId.deviceName, TRUE); } else { device = sccp_device_retain(maybe_d); sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_1 "%s: cached device configuration\n", DEV_ID_LOG(device)); } /*! \todo We need a fix here. If deviceName was provided and specified in sccp.conf we should not continue to anonymous, * but we cannot depend on one of the standard find functions for this, because they return null in two different cases (non-existent and refcount<0). */ if (!device && GLOB(allowAnonymous)) { if (!(device = sccp_device_createAnonymous(r->msg.RegisterMessage.sId.deviceName))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: hotline device could not be created: %s\n", r->msg.RegisterMessage.sId.deviceName, GLOB(hotline)->line->name); } sccp_config_applyDeviceConfiguration(device, NULL); sccp_config_addButton(&device->buttonconfig, 1, LINE, GLOB(hotline)->line->name, NULL, NULL); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: hotline name: %s\n", r->msg.RegisterMessage.sId.deviceName, GLOB(hotline)->line->name); device->defaultLineInstance = 1; sccp_device_addToGlobals(device); } if (device) { if (device->session && device->session != s) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: Crossover device registration! Fixing up to new session\n", DEV_ID_LOG(device)); sccp_socket_stop_sessionthread(device->session, SKINNY_DEVICE_RS_FAILED); // device->session->device->registrationState = SKINNY_DEVICE_RS_FAILED; // s->device = sccp_session_addDevice(s, d); } if (!s->device || s->device != device) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: Allocating device to session (%d) %s\n", DEV_ID_LOG(device), s->fds[0].fd, pbx_inet_ntoa(s->sin.sin_addr)); s->device = sccp_session_addDevice(s, device); // replace retained in session (already connected via tokenReq before) } /* check ACLs for this device */ if (device->checkACL(device) == FALSE) { pbx_log(LOG_NOTICE, "%s: Rejecting device: Ip address '%s' denied (deny + permit/permithosts).\n", r->msg.RegisterMessage.sId.deviceName, pbx_inet_ntoa(s->sin.sin_addr)); device->registrationState = SKINNY_DEVICE_RS_FAILED; s = sccp_session_reject(s, "IP Not Authorized"); goto EXITFUNC; } } else { pbx_log(LOG_NOTICE, "%s: Rejecting device: Device Unknown \n", r->msg.RegisterMessage.sId.deviceName); s = sccp_session_reject(s, "Device Unknown"); goto EXITFUNC; } device->device_features = letohl(r->msg.RegisterMessage.phone_features); device->linesRegistered = FALSE; sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: device load_info='%s', maxbuttons='%d', supports dynamic_messages='%s', supports abbr_dial='%s'\n", r->msg.RegisterMessage.sId.deviceName, r->msg.RegisterMessage.loadInfo, r->msg.RegisterMessage.lel_maxButtons, (device->device_features & SKINNY_PHONE_FEATURES_DYNAMIC_MESSAGES) == 0 ? "no" : "yes", (device->device_features & SKINNY_PHONE_FEATURES_ABBRDIAL) == 0 ? "no" : "yes"); if (GLOB(localaddr) && sccp_apply_ha(GLOB(localaddr), &s->sin) != AST_SENSE_ALLOW) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Device is behind NAT. We will set externip or externhost for the RTP stream (%s does not fit permit/deny)\n", r->msg.RegisterMessage.sId.deviceName, pbx_inet_ntoa(s->sin.sin_addr)); device->nat = 1; } /* We should be using sockaddr_storage in sccp_socket.c so this convertion would not be necessary here */ #ifdef CS_EXPERIMENTAL_NEWIP if (AF_INET == s->sin.sin_family) { session_ss = (struct sockaddr_storage *) &s->sin; addrlen = (socklen_t) INET_ADDRSTRLEN; } #ifdef CS_IPV6 /* if (AF_INET6==s->sin6.sin6_family) { session_ss=(struct sockaddr_storage *)&s->sin6; addrlen=(socklen_t)INET6_ADDRSTRLEN; } */ #endif if (sockaddr_cmp_addr(ss, addrlen, session_ss, addrlen)) { // test to see if phone ip address differs from incoming socket ipaddress -> nat sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Auto Detected NAT. We will use externip or externhost for the RTP stream\n", r->msg.RegisterMessage.sId.deviceName); device->nat = 1; } #endif device->skinny_type = deviceType; // device->session = s; s->lastKeepAlive = time(0); device->mwilight = 0; device->protocolversion = protocolVer; device->status.token = SCCP_TOKEN_STATE_NOTOKEN; /** workaround to fix the protocol version issue for ata devices */ /* * MAC-Address : ATA00215504e821 * Protocol Version : Supported '33', In Use '17' */ if (device->skinny_type == SKINNY_DEVICETYPE_ATA188 || device->skinny_type == SKINNY_DEVICETYPE_ATA186) { device->protocolversion = SCCP_DRIVER_SUPPORTED_PROTOCOL_LOW; } device->protocol = sccp_protocol_getDeviceProtocol(device, s->protocolType); uint8_t ourProtocolCapability = sccp_protocol_getMaxSupportedVersionNumber(s->protocolType); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: asked our protocol capability (%d).\n", DEV_ID_LOG(device), ourProtocolCapability); /* we need some entropy for keepalive, to reduce the number of devices sending keepalive at one time */ device->keepaliveinterval = device->keepalive ? device->keepalive : GLOB(keepalive); device->keepaliveinterval = ((device->keepaliveinterval / 4) * 3) + (rand() % (device->keepaliveinterval / 4)) + 1; // smaller random segment, keeping keepalive toward the upperbound sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Phone protocol capability : %d\n", DEV_ID_LOG(device), protocolVer); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Our protocol capability : %d\n", DEV_ID_LOG(device), ourMaxSupportedProtocolVersion); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Joint protocol capability : %d\n", DEV_ID_LOG(device), device->protocol->version); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Ask the phone to send keepalive message every %d seconds\n", DEV_ID_LOG(device), device->keepaliveinterval); device->inuseprotocolversion = device->protocol->version; sccp_device_setIndicationProtocol(device); device->protocol->sendRegisterAck(device, device->keepaliveinterval, device->keepaliveinterval, GLOB(dateformat)); sccp_dev_set_registered(device, SKINNY_DEVICE_RS_PROGRESS); /* Ask for the capabilities of the device to proceed with registration according to sccp protocol specification 3.0 */ sccp_log((DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: (sccp_handle_register) asking for capabilities\n", DEV_ID_LOG(device)); sccp_dev_sendmsg(device, CapabilitiesReqMessage); EXITFUNC: device = device ? sccp_device_release(device) : NULL; } /*! * \brief Make Button Template for Device * \param d SCCP Device as sccp_device_t * \return Linked List of ButtonDefinitions * * \lock * - device->buttonconfig * - see sccp_line_find_byname() */ static btnlist *sccp_make_button_template(sccp_device_t * d) { int i = 0; btnlist *btn; sccp_buttonconfig_t *buttonconfig; if (!d || !&d->buttonconfig) return NULL; if (!(btn = sccp_malloc(sizeof(btnlist) * StationMaxButtonTemplateSize))) { return NULL; } memset(btn, 0, sizeof(btnlist) * StationMaxButtonTemplateSize); sccp_dev_build_buttontemplate(d, btn); uint16_t speeddialInstance = 1; /* starting instance for speeddial is 1 */ uint16_t lineInstance = 1; uint16_t serviceInstance = 1; if (!d->isAnonymous) { SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { sccp_log((DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: searching for position for button type %d\n", DEV_ID_LOG(d), buttonconfig->type); if (buttonconfig->instance > 0) continue; if (buttonconfig->type == LINE) { sccp_log((DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: searching for line position for line '%s'\n", DEV_ID_LOG(d), buttonconfig->button.line.name); } for (i = 0; i < StationMaxButtonTemplateSize; i++) { sccp_log((DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: btn[%.2d].type = %d\n", DEV_ID_LOG(d), i, btn[i].type); if (buttonconfig->type == LINE && !sccp_strlen_zero(buttonconfig->button.line.name) && (btn[i].type == SCCP_BUTTONTYPE_MULTI || btn[i].type == SCCP_BUTTONTYPE_LINE)) { btn[i].type = SKINNY_BUTTONTYPE_LINE; /* search line (create new line, if necessary (realtime)) */ /*! retains new line in btn[i].ptr, finally released in sccp_dev_clean */ if ((btn[i].ptr = sccp_line_find_byname(buttonconfig->button.line.name, TRUE))) { buttonconfig->instance = btn[i].instance = lineInstance++; } else { btn[i].type = SKINNY_BUTTONTYPE_UNDEFINED; buttonconfig->instance = btn[i].instance = 0; pbx_log(LOG_WARNING, "%s: line %s does not exists\n", DEV_ID_LOG(d), buttonconfig->button.line.name); } sccp_log((DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: add line %s on position %d\n", DEV_ID_LOG(d), buttonconfig->button.line.name, buttonconfig->instance); break; } else if (buttonconfig->type == EMPTY && (btn[i].type == SCCP_BUTTONTYPE_MULTI || btn[i].type == SCCP_BUTTONTYPE_LINE || btn[i].type == SCCP_BUTTONTYPE_SPEEDDIAL)) { btn[i].type = SKINNY_BUTTONTYPE_UNDEFINED; buttonconfig->instance = btn[i].instance = 0; break; } else if (buttonconfig->type == SERVICE && (btn[i].type == SCCP_BUTTONTYPE_MULTI)) { btn[i].type = SKINNY_BUTTONTYPE_SERVICEURL; buttonconfig->instance = btn[i].instance = serviceInstance++; break; } else if (buttonconfig->type == SPEEDDIAL && !sccp_strlen_zero(buttonconfig->label) && (btn[i].type == SCCP_BUTTONTYPE_MULTI || btn[i].type == SCCP_BUTTONTYPE_SPEEDDIAL)) { buttonconfig->instance = btn[i].instance = i + 1; if (!sccp_strlen_zero(buttonconfig->button.speeddial.hint) && btn[i].type == SCCP_BUTTONTYPE_MULTI /* we can set our feature */ ) { #ifdef CS_DYNAMIC_SPEEDDIAL if (d->inuseprotocolversion >= 15) { btn[i].type = 0x15; buttonconfig->instance = btn[i].instance = speeddialInstance++; } else { btn[i].type = SKINNY_BUTTONTYPE_LINE; buttonconfig->instance = btn[i].instance = lineInstance++;; } #else btn[i].type = SKINNY_BUTTONTYPE_LINE; buttonconfig->instance = btn[i].instance = lineInstance++;; #endif } else { btn[i].type = SKINNY_BUTTONTYPE_SPEEDDIAL; buttonconfig->instance = btn[i].instance = speeddialInstance++; } break; } else if (buttonconfig->type == FEATURE && !sccp_strlen_zero(buttonconfig->label) && (btn[i].type == SCCP_BUTTONTYPE_MULTI)) { buttonconfig->instance = btn[i].instance = speeddialInstance++; switch (buttonconfig->button.feature.id) { case SCCP_FEATURE_HOLD: btn[i].type = SKINNY_BUTTONTYPE_HOLD; break; case SCCP_FEATURE_TRANSFER: btn[i].type = SKINNY_BUTTONTYPE_TRANSFER; break; case SCCP_FEATURE_MONITOR: btn[i].type = SKINNY_BUTTONTYPE_MULTIBLINKFEATURE; break; case SCCP_FEATURE_MULTIBLINK: btn[i].type = SKINNY_BUTTONTYPE_MULTIBLINKFEATURE; break; case SCCP_FEATURE_MOBILITY: btn[i].type = SKINNY_BUTTONTYPE_MOBILITY; break; case SCCP_FEATURE_CONFERENCE: btn[i].type = SKINNY_BUTTONTYPE_CONFERENCE; break; case SCCP_FEATURE_PICKUP: btn[i].type = SKINNY_STIMULUS_GROUPCALLPICKUP; break; case SCCP_FEATURE_TEST6: btn[i].type = SKINNY_BUTTONTYPE_TEST6; break; case SCCP_FEATURE_TEST7: btn[i].type = SKINNY_BUTTONTYPE_TEST7; break; case SCCP_FEATURE_TEST8: btn[i].type = SKINNY_BUTTONTYPE_TEST8; break; case SCCP_FEATURE_TEST9: btn[i].type = SKINNY_BUTTONTYPE_TEST9; break; case SCCP_FEATURE_TESTA: btn[i].type = SKINNY_BUTTONTYPE_TESTA; break; case SCCP_FEATURE_TESTB: btn[i].type = SKINNY_BUTTONTYPE_TESTB; break; case SCCP_FEATURE_TESTC: btn[i].type = SKINNY_BUTTONTYPE_TESTC; break; case SCCP_FEATURE_TESTD: btn[i].type = SKINNY_BUTTONTYPE_TESTD; break; case SCCP_FEATURE_TESTE: btn[i].type = SKINNY_BUTTONTYPE_TESTE; break; case SCCP_FEATURE_TESTF: btn[i].type = SKINNY_BUTTONTYPE_TESTF; break; case SCCP_FEATURE_TESTG: btn[i].type = SKINNY_BUTTONTYPE_MESSAGES; break; case SCCP_FEATURE_TESTH: btn[i].type = SKINNY_BUTTONTYPE_DIRECTORY; break; case SCCP_FEATURE_TESTI: btn[i].type = SKINNY_BUTTONTYPE_TESTI; break; case SCCP_FEATURE_TESTJ: btn[i].type = SKINNY_BUTTONTYPE_APPLICATION; break; default: btn[i].type = SKINNY_BUTTONTYPE_FEATURE; break; } break; } else { continue; } sccp_log((DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "%s: Configured Phone Button [%.2d] = %s (%s)\n", d->id, buttonconfig->instance, "FEATURE", buttonconfig->label); } } SCCP_LIST_UNLOCK(&d->buttonconfig); // all non defined buttons are set to UNUSED for (i = 0; i < StationMaxButtonTemplateSize; i++) { if (btn[i].type == SCCP_BUTTONTYPE_MULTI) { btn[i].type = SKINNY_BUTTONTYPE_UNUSED; } } } else { /* reserve one line as hotline */ btn[i].type = SKINNY_BUTTONTYPE_LINE; SCCP_LIST_FIRST(&d->buttonconfig)->instance = btn[i].instance = 1; } return btn; } /*! * \brief Handle Available Lines * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \callgraph * \callergraph * * \lock * - device->buttonconfig * - see sccp_line_addDevice() * - see sccp_hint_lineStatusChanged() */ void sccp_handle_AvailableLines(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { uint8_t i = 0, line_count = 0; btnlist *btn; sccp_line_t *l = NULL; sccp_buttonconfig_t *buttonconfig = NULL; boolean_t defaultLineSet = FALSE; line_count = 0; /** \todo why do we get the message twice */ if (d->linesRegistered) return; btn = d->buttonTemplate; if (!btn) { sccp_log(DEBUGCAT_BUTTONTEMPLATE) (VERBOSE_PREFIX_3 "%s: no buttontemplate, reset device\n", DEV_ID_LOG(d)); sccp_device_sendReset(d, SKINNY_DEVICE_RESTART); return; } /* count the available lines on the phone */ for (i = 0; i < StationMaxButtonTemplateSize; i++) { if ((btn[i].type == SKINNY_BUTTONTYPE_LINE) || (btn[i].type == SCCP_BUTTONTYPE_MULTI)) line_count++; else if (btn[i].type == SKINNY_BUTTONTYPE_UNUSED) break; } sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE | DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: Phone available lines %d\n", d->id, line_count); if (d->isAnonymous == TRUE) { l = GLOB(hotline)->line; sccp_line_addDevice(l, d, 1, NULL); } else { for (i = 0; i < StationMaxButtonTemplateSize; i++) { if (btn[i].type == SKINNY_BUTTONTYPE_LINE && btn[i].ptr) { if ((l = sccp_line_retain(btn[i].ptr))) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Attaching line %s with instance %d to this device\n", d->id, l->name, btn[i].instance); SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (btn[i].instance == buttonconfig->instance && buttonconfig->type == LINE) { sccp_line_addDevice(l, d, btn[i].instance, &(buttonconfig->button.line.subscriptionId)); if (FALSE == defaultLineSet && !d->defaultLineInstance) { d->defaultLineInstance = buttonconfig->instance; defaultLineSet = TRUE; } } } SCCP_LIST_UNLOCK(&d->buttonconfig); l = sccp_line_release(l); } } } } d->linesRegistered = TRUE; } /*! * \brief Handle Accessory Status Message * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_accessorystatus_message(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { uint8_t id; uint8_t status; uint32_t unknown = 0; id = letohl(r->msg.AccessoryStatusMessage.lel_AccessoryID); status = letohl(r->msg.AccessoryStatusMessage.lel_AccessoryStatus); d->accessoryused = id; d->accessorystatus = status; unknown = letohl(r->msg.AccessoryStatusMessage.lel_unknown); switch (id) { case 1: d->accessoryStatus.headset = (status) ? TRUE : FALSE; break; case 2: d->accessoryStatus.handset = (status) ? TRUE : FALSE; break; case 3: d->accessoryStatus.speaker = (status) ? TRUE : FALSE; break; } sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Accessory '%s' is '%s' (%u)\n", DEV_ID_LOG(d), accessory2str(d->accessoryused), accessorystate2str(d->accessorystatus), unknown); } /*! * \brief Handle Device Unregister * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_unregister(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_moo_t *r1; /* we don't need to look for active channels. the phone does send unregister only when there are no channels */ REQ(r1, UnregisterAckMessage); r1->msg.UnregisterAckMessage.lel_status = SKINNY_UNREGISTERSTATUS_OK; sccp_session_send2(s, r1); // send directly to session, skipping device check sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: unregister request sent\n", DEV_ID_LOG(d)); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_NONE); } /*! * \brief Handle Button Template Request for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \warning * - device->buttonconfig is not always locked * * \lock * - device * - see sccp_make_button_template() * - see sccp_dev_send() */ void sccp_handle_button_template_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { btnlist *btn; int i; uint8_t buttonCount = 0, lastUsedButtonPosition = 0; sccp_moo_t *r1; if (d->registrationState != SKINNY_DEVICE_RS_PROGRESS && d->registrationState != SKINNY_DEVICE_RS_OK) { pbx_log(LOG_WARNING, "%s: Received a button template request from unregistered device\n", d->id); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); return; } /* pre-attach lines. We will wait for button template req if the phone does support it */ if (d->buttonTemplate) { sccp_free(d->buttonTemplate); } btn = d->buttonTemplate = sccp_make_button_template(d); if (!btn) { pbx_log(LOG_ERROR, "%s: No memory allocated for button template\n", d->id); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); return; } REQ(r1, ButtonTemplateMessage); for (i = 0; i < StationMaxButtonTemplateSize; i++) { r1->msg.ButtonTemplateMessage.definition[i].instanceNumber = btn[i].instance; if (SKINNY_BUTTONTYPE_UNUSED != btn[i].type) { //r1->msg.ButtonTemplateMessage.lel_buttonCount = i+1; buttonCount = i + 1; lastUsedButtonPosition = i; } switch (btn[i].type) { case SCCP_BUTTONTYPE_HINT: case SCCP_BUTTONTYPE_LINE: /* we do not need a line if it is not configured */ if (r1->msg.ButtonTemplateMessage.definition[i].instanceNumber == 0) { r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_UNDEFINED; } else { r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_LINE; } break; case SCCP_BUTTONTYPE_SPEEDDIAL: r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_SPEEDDIAL; break; case SKINNY_BUTTONTYPE_SERVICEURL: r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_SERVICEURL; break; case SKINNY_BUTTONTYPE_FEATURE: r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_FEATURE; break; case SCCP_BUTTONTYPE_MULTI: //r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_DISPLAY; //break; case SKINNY_BUTTONTYPE_UNUSED: r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = SKINNY_BUTTONTYPE_UNDEFINED; break; default: r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition = btn[i].type; break; } sccp_log((DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "%s: Configured Phone Button [%.2d] = %d (%d)\n", d->id, i + 1, r1->msg.ButtonTemplateMessage.definition[i].buttonDefinition, r1->msg.ButtonTemplateMessage.definition[i].instanceNumber); } r1->msg.ButtonTemplateMessage.lel_buttonOffset = 0; //r1->msg.ButtonTemplateMessage.lel_buttonCount = htolel(r1->msg.ButtonTemplateMessage.lel_buttonCount); r1->msg.ButtonTemplateMessage.lel_buttonCount = htolel(buttonCount); /* buttonCount is already in a little endian format so don't need to convert it now */ r1->msg.ButtonTemplateMessage.lel_totalButtonCount = htolel(lastUsedButtonPosition + 1); /* set speeddial for older devices like 7912 */ uint32_t speeddialInstance = 0; sccp_buttonconfig_t *config; sccp_log((DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_SPEEDDIAL)) (VERBOSE_PREFIX_3 "%s: configure unconfigured speeddialbuttons \n", d->id); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { /* we found an unconfigured speeddial */ if (config->type == SPEEDDIAL && config->instance == 0) { config->instance = speeddialInstance++; } else if (config->type == SPEEDDIAL && config->instance != 0) { speeddialInstance = config->instance; } } /* done */ sccp_dev_send(d, r1); } /*! * \brief Handle Line Number for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - device->buttonconfig */ void sccp_handle_line_number(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_line_t *l = NULL; sccp_moo_t *r1; sccp_speed_t k; sccp_buttonconfig_t *config; uint8_t lineNumber = letohl(r->msg.LineStatReqMessage.lel_lineNumber); sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "%s: Configuring line number %d\n", d->id, lineNumber); l = sccp_line_find_byid(d, lineNumber); /* if we find no regular line - it can be a speeddial with hint */ if (!l) { sccp_dev_speed_find_byindex(d, lineNumber, TRUE, &k); } REQ(r1, LineStatMessage); if (!l && !k.valid) { pbx_log(LOG_ERROR, "%s: requested a line configuration for unknown line/speeddial %d\n", DEV_ID_LOG(s->device), lineNumber); r1->msg.LineStatMessage.lel_lineNumber = htolel(lineNumber); sccp_dev_send(s->device, r1); return; } r1->msg.LineStatMessage.lel_lineNumber = htolel(lineNumber); sccp_copy_string(r1->msg.LineStatMessage.lineDirNumber, ((l) ? l->name : k.name), sizeof(r1->msg.LineStatMessage.lineDirNumber)); /* lets set the device description for the first line, so it will be display on top of device -MC */ if (lineNumber == 1) { sccp_copy_string(r1->msg.LineStatMessage.lineFullyQualifiedDisplayName, (d->description), sizeof(r1->msg.LineStatMessage.lineFullyQualifiedDisplayName)); } else { sccp_copy_string(r1->msg.LineStatMessage.lineFullyQualifiedDisplayName, ((l) ? l->description : k.name), sizeof(r1->msg.LineStatMessage.lineFullyQualifiedDisplayName)); } sccp_copy_string(r1->msg.LineStatMessage.lineDisplayName, ((l) ? l->label : k.name), sizeof(r1->msg.LineStatMessage.lineDisplayName)); sccp_dev_send(d, r1); /* force the forward status message. Some phone does not request it registering */ if (l) { sccp_dev_forward_status(l, lineNumber, d); /* set default line on device if based on "default" config option */ SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->instance == lineNumber) { if (config->type == LINE) { if (config->button.line.options && strcasestr(config->button.line.options, "default")) { d->defaultLineInstance = lineNumber; sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "set defaultLineInstance to: %u\n", lineNumber); } } break; } } SCCP_LIST_UNLOCK(&d->buttonconfig); l = sccp_line_release(l); } } /*! * \brief Handle SpeedDial Status Request for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_speed_dial_stat_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_speed_t k; sccp_moo_t *r1; int wanted = letohl(r->msg.SpeedDialStatReqMessage.lel_speedDialNumber); sccp_log((DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: Speed Dial Request for Button %d\n", DEV_ID_LOG(s->device), wanted); REQ(r1, SpeedDialStatMessage); r1->msg.SpeedDialStatMessage.lel_speedDialNumber = htolel(wanted); sccp_dev_speed_find_byindex(s->device, wanted, FALSE, &k); if (k.valid) { sccp_copy_string(r1->msg.SpeedDialStatMessage.speedDialDirNumber, k.ext, sizeof(r1->msg.SpeedDialStatMessage.speedDialDirNumber)); sccp_copy_string(r1->msg.SpeedDialStatMessage.speedDialDisplayName, k.name, sizeof(r1->msg.SpeedDialStatMessage.speedDialDisplayName)); } else { sccp_log((DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: speeddial %d unknown\n", DEV_ID_LOG(s->device), wanted); } sccp_dev_send(d, r1); } /*! * \brief Handle Stimulus for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \callgraph * \callergraph * * \lock * - channel * - device * - see sccp_device_find_index_for_line() */ void sccp_handle_stimulus(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_line_t *l = NULL; sccp_line_t *al = NULL; sccp_speed_t k; sccp_channel_t *channel = NULL, *sccp_channel_1 = NULL; uint8_t stimulus; uint8_t instance; sccp_channel_t *sccp_channel_held; sccp_channel_t *sccp_channel_ringing; stimulus = letohl(r->msg.StimulusMessage.lel_stimulus); instance = letohl(r->msg.StimulusMessage.lel_stimulusInstance); if (d->isAnonymous) { sccp_feat_adhocDial(d, GLOB(hotline)->line); /* use adhoc dial feture with hotline */ return; } sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Got stimulus=%s (%d) for instance=%d\n", d->id, stimulus2str(stimulus), stimulus, instance); if (!instance) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Instance 0 is not a valid instance. Trying the active line %d\n", d->id, instance); al = sccp_dev_get_activeline(d); if (!al) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); goto func_exit; } if (strlen(al->adhocNumber) > 0) { sccp_feat_adhocDial(d, l); goto func_exit; } // \todo set index instance = 1; } switch (stimulus) { case SKINNY_BUTTONTYPE_LASTNUMBERREDIAL: // We got a Redial Request if (sccp_strlen_zero(d->lastNumber)) goto func_exit; channel = sccp_channel_get_active(d); if (channel) { if (channel->state == SCCP_CHANNELSTATE_OFFHOOK) { sccp_copy_string(channel->dialedNumber, d->lastNumber, sizeof(d->lastNumber)); channel->scheduler.digittimeout = SCCP_SCHED_DEL(channel->scheduler.digittimeout); sccp_pbx_softswitch(channel); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Redial the number %s\n", d->id, d->lastNumber); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Redial ignored as call in progress\n", d->id); } } else { if ((l = sccp_dev_get_activeline(d))) { channel = sccp_channel_newcall(l, d, d->lastNumber, SKINNY_CALLTYPE_OUTBOUND, NULL); channel = channel ? sccp_channel_release(channel) : NULL; } } break; case SKINNY_BUTTONTYPE_LINE: // We got a Line Request l = sccp_line_find_byid(d, instance); if (!l) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: No line for instance %d. Looking for a speeddial with hint\n", d->id, instance); sccp_dev_speed_find_byindex(d, instance, TRUE, &k); if (k.valid) sccp_handle_speeddial(d, &k); else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No number assigned to speeddial %d\n", d->id, instance); goto func_exit; } if (strlen(l->adhocNumber) > 0) { sccp_feat_adhocDial(d, l); goto func_exit; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Line Key press on line %s\n", d->id, (l) ? l->name : "(nil)"); if ((channel = sccp_channel_get_active(d))) { sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: gotten active channel %d on line %s\n", d->id, channel->callid, (l) ? l->name : "(nil)"); if (channel->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Call not in progress. Closing line %s\n", d->id, (l) ? l->name : "(nil)"); sccp_channel_endcall(channel); sccp_dev_deactivate_cplane(d); goto func_exit; } else { if (sccp_channel_hold(channel)) { sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: call (%d) put on hold on line %s\n", d->id, channel->callid, l->name); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Hold failed for call (%d), line %s\n", d->id, channel->callid, l->name); } } } else { sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: no activate channel on line %d\n", d->id, instance); } if (!SCCP_RWLIST_GETSIZE(l->channels)) { sccp_channel_t *tmpChannel = NULL; sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: no activate channel on line %s\n", DEV_ID_LOG(d), (l) ? l->name : "(nil)"); sccp_dev_set_activeline(d, l); sccp_dev_set_cplane(d, instance, 1); tmpChannel = sccp_channel_newcall(l, d, NULL, SKINNY_CALLTYPE_OUTBOUND, NULL); tmpChannel = tmpChannel ? sccp_channel_release(tmpChannel) : NULL; } else if ((sccp_channel_ringing = sccp_channel_find_bystate_on_line(l, SCCP_CHANNELSTATE_RINGING))) { sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: Answering incoming/ringing line %d", d->id, instance); sccp_channel_answer(d, sccp_channel_ringing); } else if ((sccp_channel_held = sccp_channel_find_bystate_on_line(l, SCCP_CHANNELSTATE_HOLD))) { sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: Channel count on line %d = %d", d->id, instance, SCCP_RWLIST_GETSIZE(l->channels)); if (SCCP_RWLIST_GETSIZE(l->channels) == 1) { /* \todo we should lock the list here. */ channel = SCCP_LIST_FIRST(&l->channels); sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: Resume channel %d on line %d", d->id, channel->callid, instance); sccp_dev_set_activeline(d, l); sccp_channel_resume(d, channel, TRUE); sccp_dev_set_cplane(d, instance, 1); } else { sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: Switch to line %d", d->id, instance); sccp_dev_set_activeline(d, l); sccp_dev_set_cplane(d, instance, 1); } } break; case SKINNY_BUTTONTYPE_SPEEDDIAL: sccp_dev_speed_find_byindex(d, instance, FALSE, &k); if (k.valid) sccp_handle_speeddial(d, &k); else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No number assigned to speeddial %d\n", d->id, instance); break; case SKINNY_BUTTONTYPE_HOLD: /* this is the hard hold button. When we are here we are putting on hold the active_channel */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Hold/Resume Button pressed on line (%d)\n", d->id, instance); l = sccp_line_find_byid(d, instance); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line (%d) found\n", d->id, instance); l = sccp_dev_get_activeline(d); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Trying the current line\n", d->id); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line (%d) found\n", d->id, instance); goto func_exit; } instance = sccp_device_find_index_for_line(d, l->name); } if ((channel = sccp_channel_find_bystate_on_line(l, SCCP_CHANNELSTATE_CONNECTED))) { sccp_channel_hold(channel); } else if ((channel = sccp_channel_find_bystate_on_line(l, SCCP_CHANNELSTATE_HOLD))) { sccp_channel_1 = sccp_channel_get_active(d); if (sccp_channel_1) { if (sccp_channel_1->state == SCCP_CHANNELSTATE_OFFHOOK) sccp_channel_endcall(sccp_channel_1); } sccp_channel_resume(d, channel, TRUE); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No call to resume/hold found on line %d\n", d->id, instance); } break; case SKINNY_BUTTONTYPE_TRANSFER: if (!d->transfer) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Transfer disabled on device\n", d->id); break; } channel = sccp_channel_get_active(d); if (channel) { sccp_channel_transfer(channel, d); } break; case SKINNY_BUTTONTYPE_VOICEMAIL: // Get a new Line and Dial the Voicemail. sccp_feat_voicemail(d, instance); break; case SKINNY_BUTTONTYPE_CONFERENCE: pbx_log(LOG_NOTICE, "%s: Conference Button is not yet handled. working on implementation\n", d->id); break; case SKINNY_BUTTONTYPE_FEATURE: case SKINNY_BUTTONTYPE_MOBILITY: case SKINNY_BUTTONTYPE_MULTIBLINKFEATURE: case SKINNY_BUTTONTYPE_TEST6: case SKINNY_BUTTONTYPE_TEST7: case SKINNY_BUTTONTYPE_TEST8: case SKINNY_BUTTONTYPE_TEST9: case SKINNY_BUTTONTYPE_TESTA: case SKINNY_BUTTONTYPE_TESTB: case SKINNY_BUTTONTYPE_TESTC: case SKINNY_BUTTONTYPE_TESTD: case SKINNY_BUTTONTYPE_TESTE: case SKINNY_BUTTONTYPE_TESTF: case SKINNY_BUTTONTYPE_MESSAGES: case SKINNY_BUTTONTYPE_DIRECTORY: case SKINNY_BUTTONTYPE_TESTI: case SKINNY_BUTTONTYPE_APPLICATION: sccp_handle_feature_action(d, instance, TRUE); break; case SKINNY_BUTTONTYPE_FORWARDALL: // Call forward all if (!d->cfwdall) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: CFWDALL disabled on device\n", d->id); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, 0, 0, 0); goto func_exit; } l = sccp_dev_get_activeline(d); if (!l) { if (!instance) instance = 1; l = sccp_line_find_byid(d, instance); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line (%d) found\n", d->id, instance); goto func_exit; } } if (l) { sccp_feat_handle_callforward(l, d, SCCP_CFWD_ALL); } break; case SKINNY_BUTTONTYPE_FORWARDBUSY: if (!d->cfwdbusy) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: CFWDBUSY disabled on device\n", d->id); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, 0, 0, 0); goto func_exit; } l = sccp_dev_get_activeline(d); if (!l) { if (!instance) instance = 1; l = sccp_line_find_byid(d, instance); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line (%d) found\n", d->id, instance); goto func_exit; } } if (l) { sccp_feat_handle_callforward(l, d, SCCP_CFWD_BUSY); } break; case SKINNY_BUTTONTYPE_FORWARDNOANSWER: if (!d->cfwdnoanswer) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: CFWDNOANSWER disabled on device\n", d->id); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, 0, 0, 0); goto func_exit; } l = sccp_dev_get_activeline(d); if (!l) { if (!instance) instance = 1; l = sccp_line_find_byid(d, instance); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line (%d) found\n", d->id, instance); goto func_exit; } } if (l) { sccp_feat_handle_callforward(l, d, SCCP_CFWD_NOANSWER); } break; case SKINNY_BUTTONTYPE_CALLPARK: // Call parking #ifdef CS_SCCP_PARK channel = sccp_channel_get_active(d); if (!channel) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Cannot park while no calls in progress\n", d->id); goto func_exit; } sccp_channel_park(channel); #else sccp_log((DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "### Native park was not compiled in\n"); #endif break; case SKINNY_BUTTONTYPE_BLFSPEEDDIAL: //busy lamp field type speeddial sccp_dev_speed_find_byindex(d, instance, TRUE, &k); if (k.valid) sccp_handle_speeddial(d, &k); else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No number assigned to speeddial %d\n", d->id, instance); break; case SKINNY_STIMULUS_GROUPCALLPICKUP: /*!< pickup feature button */ #ifndef CS_SCCP_PICKUP sccp_log((DEBUGCAT_FEATURE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "### Native GROUP PICKUP was not compiled in\n"); #else if (d->defaultLineInstance > 0) { sccp_log((DEBUGCAT_FEATURE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "using default line with instance: %u\n", d->defaultLineInstance); /*! \todo use feature map or sccp_feat_handle_directed_pickup */ if ((l = sccp_line_find_byid(d, d->defaultLineInstance))) { //sccp_feat_handle_directed_pickup(l, d->defaultLineInstance, d); channel = sccp_channel_newcall(l, d, (char *) pbx_pickup_ext(), SKINNY_CALLTYPE_OUTBOUND, NULL); channel = channel ? sccp_channel_release(channel) : NULL; } goto func_exit; } /* no default line set, use first line */ if (!al) { al = sccp_line_find_byid(d, 1); } if (al) { /*! \todo use feature map or sccp_feat_handle_directed_pickup */ //sccp_feat_handle_directed_pickup(l, 1, d); channel = sccp_channel_newcall(al, d, (char *) pbx_pickup_ext(), SKINNY_CALLTYPE_OUTBOUND, NULL); channel = channel ? sccp_channel_release(channel) : NULL; } #endif break; default: pbx_log(LOG_NOTICE, "%s: Don't know how to deal with stimulus %d with Phonetype %s(%d) \n", d->id, stimulus, devicetype2str(d->skinny_type), d->skinny_type); break; } func_exit: channel = channel ? sccp_channel_release(channel) : NULL; al = al ? sccp_line_release(al) : NULL; l = l ? sccp_line_release(l) : NULL; } /*! * \brief Handle SpeedDial for Device * \param d SCCP Device as sccp_device_t * \param k SCCP SpeedDial as sccp_speed_t * * \lock * - channel */ void sccp_handle_speeddial(sccp_device_t * d, const sccp_speed_t * k) { sccp_channel_t *channel = NULL; sccp_line_t *l; int len; if (!k || !d || !d->session) return; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Speeddial Button (%d) pressed, configured number is (%s)\n", d->id, k->instance, k->ext); if ((channel = sccp_channel_get_active(d))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: channel state %d\n", DEV_ID_LOG(d), channel->state); // Channel already in use if ((channel->state == SCCP_CHANNELSTATE_DIALING) || (channel->state == SCCP_CHANNELSTATE_OFFHOOK)) { len = strlen(channel->dialedNumber); sccp_copy_string(channel->dialedNumber + len, k->ext, sizeof(channel->dialedNumber) - len); channel->scheduler.digittimeout = SCCP_SCHED_DEL(channel->scheduler.digittimeout); sccp_pbx_softswitch(channel); channel = sccp_channel_release(channel); return; } else if (channel->state == SCCP_CHANNELSTATE_CONNECTED || channel->state == SCCP_CHANNELSTATE_PROCEED) { // automatically put on hold sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_3 "%s: automatically put call %d on hold %d\n", DEV_ID_LOG(d), channel->callid, channel->state); sccp_channel_hold(channel); if ((l = sccp_dev_get_activeline(d))) { sccp_channel_t *tmpChannel = NULL; tmpChannel = sccp_channel_newcall(l, d, k->ext, SKINNY_CALLTYPE_OUTBOUND, NULL); tmpChannel = tmpChannel ? sccp_channel_release(tmpChannel) : NULL; l = sccp_line_release(l); } channel = sccp_channel_release(channel); return; } // Channel not in use sccp_pbx_senddigits(channel, k->ext); channel = sccp_channel_release(channel); } else { /* check Remote RINGING + gpickup */ if (d->defaultLineInstance > 0) { sccp_log((DEBUGCAT_LINE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "using default line with instance: %u", d->defaultLineInstance); l = sccp_line_find_byid(d, d->defaultLineInstance); } else { l = sccp_dev_get_activeline(d); } if (l) { channel = sccp_channel_newcall(l, d, k->ext, SKINNY_CALLTYPE_OUTBOUND, NULL); channel = channel ? sccp_channel_release(channel) : NULL; l = sccp_line_release(l); } } } /*! * \brief Handle Off Hook Event for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_offhook(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_line_t *l; sccp_channel_t *channel; if (d->isAnonymous) { sccp_feat_adhocDial(d, GLOB(hotline)->line); return; } if ((channel = sccp_channel_get_active(d))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Taken Offhook with a call (%d) in progess. Skip it!\n", d->id, channel->callid); channel = sccp_channel_release(channel); return; } /* we need this for callwaiting, hold, answer and stuff */ d->state = SCCP_DEVICESTATE_OFFHOOK; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Taken Offhook\n", d->id); /* checking for registered lines */ if (!d->configurationStatistic.numberOfLines) { pbx_log(LOG_NOTICE, "No lines registered on %s for take OffHook\n", DEV_ID_LOG(s->device)); sccp_dev_displayprompt(d, 0, 0, "No lines registered!", 0); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, 0, 0, 0); return; } /* end line check */ if ((channel = sccp_channel_find_bystate_on_device(d, SKINNY_CALLSTATE_RINGIN))) { /* Answer the ringing channel. */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Answer channel\n", d->id); sccp_channel_answer(d, channel); } else { /* use default line if it is set */ if (d && d->defaultLineInstance > 0) { sccp_log((DEBUGCAT_LINE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "using default line with instance: %u", d->defaultLineInstance); l = sccp_line_find_byid(d, d->defaultLineInstance); } else { l = sccp_dev_get_activeline(d); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Using line %s\n", d->id, l->name); if (l) { if (!sccp_strlen_zero(l->adhocNumber)) { channel = sccp_channel_newcall(l, d, l->adhocNumber, SKINNY_CALLTYPE_OUTBOUND, NULL); } else { /* make a new call with no number */ channel = sccp_channel_newcall(l, d, NULL, SKINNY_CALLTYPE_OUTBOUND, NULL); } l = sccp_line_release(l); } } channel = channel ? sccp_channel_release(channel) : NULL; } /*! * \brief Handle BackSpace Event for Device * \param d SCCP Device as sccp_device_t * \param line Line Number as uint8_t * \param callid Call ID as uint32_t */ void sccp_handle_backspace(sccp_device_t * d, uint8_t line, uint32_t callid) { sccp_moo_t *r; if (!d || !d->session) return; REQ(r, BackSpaceReqMessage); r->msg.BackSpaceReqMessage.lel_lineInstance = htolel(line); r->msg.BackSpaceReqMessage.lel_callReference = htolel(callid); sccp_dev_send(d, r); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Backspace request on line instance %u, call %u.\n", d->id, line, callid); } /*! * \brief Handle On Hook Event for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \warning * - device->buttonconfig is not always locked */ void sccp_handle_onhook(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_channel_t *channel; sccp_buttonconfig_t *buttonconfig = NULL; /* we need this for callwaiting, hold, answer and stuff */ d->state = SCCP_DEVICESTATE_ONHOOK; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: is Onhook\n", DEV_ID_LOG(d)); /* checking for registered lines */ uint8_t numberOfLines = 0; SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) numberOfLines++; } if (!numberOfLines) { pbx_log(LOG_NOTICE, "No lines registered on %s to put OnHook\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, 0, 0, "No lines registered!", 0); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, 0, 0, 0); return; } /* get the active channel */ if ((channel = sccp_channel_get_active(d))) { sccp_channel_endcall(channel); channel = sccp_channel_release(channel); } else { sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_OFF); sccp_dev_stoptone(d, 0, 0); } return; } /*! * \brief Handle On Hook Event for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * \note this is used just in protocol v3 stuff, it has been included in 0x004A AccessoryStatusMessage */ void sccp_handle_headset(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { /* * this is used just in protocol v3 stuff * it has been included in 0x004A AccessoryStatusMessage */ uint32_t headsetmode = letohl(r->msg.HeadsetStatusMessage.lel_hsMode); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Accessory '%s' is '%s' (%u)\n", DEV_ID_LOG(s->device), accessory2str(SCCP_ACCESSORY_HEADSET), accessorystate2str(headsetmode), 0); } /*! * \brief Handle Capabilities for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * */ void sccp_handle_capabilities_res(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { int i; skinny_codec_t codec; if (!d) { return; } uint8_t n = letohl(r->msg.CapabilitiesResMessage.lel_count); sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Device has %d Capabilities\n", DEV_ID_LOG(d), n); for (i = 0; i < n; i++) { codec = letohl(r->msg.CapabilitiesResMessage.caps[i].lel_payloadCapability); d->capabilities.audio[i] = codec; sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6d %-25s\n", d->id, codec, codec2str(codec)); } // if((d->preferences.audio[0] == SKINNY_CODEC_NONE)){ // prevent assignment by reversing order if ((SKINNY_CODEC_NONE == d->preferences.audio[0])) { /* we have no preferred codec, use capabilities -MC */ memcpy(&d->preferences.audio, &d->capabilities.audio, sizeof(d->preferences.audio)); } char cap_buf[512]; sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, d->capabilities.audio, ARRAY_LEN(d->capabilities.audio)); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_1 "%s: num of codecs %d, capabilities: %s\n", DEV_ID_LOG(d), (int) ARRAY_LEN(d->capabilities.audio), cap_buf); } /*! * \brief Handle Soft Key Template Request Message for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - device */ void sccp_handle_soft_key_template_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { uint8_t i; sccp_moo_t *r1; /* ok the device support the softkey map */ d->softkeysupport = 1; int arrayLen = ARRAY_LEN(softkeysmap); int dummy_len = arrayLen * (sizeof(StationSoftKeyDefinition)); int hdr_len = sizeof(r->msg.SoftKeyTemplateResMessage); int padding = ((dummy_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; /* create message */ r1 = sccp_build_packet(SoftKeyTemplateResMessage, hdr_len + dummy_len + padding); r1->msg.SoftKeyTemplateResMessage.lel_softKeyOffset = 0; for (i = 0; i < arrayLen; i++) { switch (softkeysmap[i]) { case SKINNY_LBL_EMPTY: // r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[0] = 0; // r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[1] = 0; case SKINNY_LBL_DIAL: sccp_copy_string(r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel, label2str(softkeysmap[i]), StationMaxSoftKeyLabelSize); sccp_log((DEBUGCAT_SOFTKEY | DEBUGCAT_DEVICE | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Button(%d)[%2d] = %s\n", d->id, i, i + 1, r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel); break; #ifdef CS_SCCP_CONFERENCE case SKINNY_LBL_CONFRN: case SKINNY_LBL_JOIN: case SKINNY_LBL_CONFLIST: if (d->allow_conference) { r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[0] = 128; r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[1] = softkeysmap[i]; } break; #endif default: r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[0] = 128; r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[1] = softkeysmap[i]; sccp_log((DEBUGCAT_SOFTKEY | DEBUGCAT_DEVICE | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Button(%d)[%2d] = %s\n", d->id, i, i + 1, label2str(r1->msg.SoftKeyTemplateResMessage.definition[i].softKeyLabel[1])); } r1->msg.SoftKeyTemplateResMessage.definition[i].lel_softKeyEvent = htolel(i + 1); } r1->msg.SoftKeyTemplateResMessage.lel_softKeyCount = htolel(arrayLen); r1->msg.SoftKeyTemplateResMessage.lel_totalSoftKeyCount = htolel(arrayLen); sccp_dev_send(s->device, r1); } /*! * \brief Handle Set Soft Key Request Message for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \warning * - device->buttonconfig is not always locked * * \lock * - softKeySetConfig */ void sccp_handle_soft_key_set_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { int iKeySetCount = 0; sccp_moo_t *r1; uint8_t i = 0; sccp_line_t *l; uint8_t trnsfvm = 0; uint8_t meetme = 0; #ifdef CS_SCCP_PICKUP uint8_t pickupgroup = 0; #endif /* set softkey definition */ sccp_softKeySetConfiguration_t *softkeyset; if (!sccp_strlen_zero(d->softkeyDefinition)) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: searching for softkeyset: %s!\n", d->id, d->softkeyDefinition); SCCP_LIST_LOCK(&softKeySetConfig); SCCP_LIST_TRAVERSE(&softKeySetConfig, softkeyset, list) { if (!strcasecmp(d->softkeyDefinition, softkeyset->name)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: using softkeyset: %s!\n", d->id, softkeyset->name); d->softKeyConfiguration.modes = softkeyset->modes; d->softKeyConfiguration.size = softkeyset->numberOfSoftKeySets; } } SCCP_LIST_UNLOCK(&softKeySetConfig); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: d->softkeyDefinition=%s!\n", d->id, d->softkeyDefinition); } else { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: d->softkeyDefinition is empty\n", d->id); } /* end softkey definition */ const softkey_modes *v = d->softKeyConfiguration.modes; const uint8_t v_count = d->softKeyConfiguration.size; REQ(r1, SoftKeySetResMessage); r1->msg.SoftKeySetResMessage.lel_softKeySetOffset = htolel(0); /* look for line trnsvm */ sccp_buttonconfig_t *buttonconfig; SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) { l = sccp_line_find_byname(buttonconfig->button.line.name, FALSE); if (l) { if (!sccp_strlen_zero(l->trnsfvm)) trnsfvm = 1; if (l->meetme) meetme = 1; if (!sccp_strlen_zero(l->meetmenum)) meetme = 1; #ifdef CS_SCCP_PICKUP if (l->pickupgroup) pickupgroup = 1; #endif l = sccp_line_release(l); } } } sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: softkey count: %d\n", d->id, v_count); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: TRANSFER is %s\n", d->id, (d->transfer) ? "enabled" : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: DND is %s\n", d->id, d->dndFeature.status ? dndmode2str(d->dndFeature.status) : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: PRIVATE is %s\n", d->id, d->privacyFeature.enabled ? "enabled" : "disabled"); #ifdef CS_SCCP_PARK sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: PARK is %s\n", d->id, (d->park) ? "enabled" : "disabled"); #endif sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: CFWDALL is %s\n", d->id, (d->cfwdall) ? "enabled" : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: CFWDBUSY is %s\n", d->id, (d->cfwdbusy) ? "enabled" : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: CFWDNOANSWER is %s\n", d->id, (d->cfwdnoanswer) ? "enabled" : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: TRNSFVM/IDIVERT is %s\n", d->id, (trnsfvm) ? "enabled" : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: MEETME is %s\n", d->id, (meetme) ? "enabled" : "disabled"); #ifdef CS_SCCP_PICKUP sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: PICKUPGROUP is %s\n", d->id, (pickupgroup) ? "enabled" : "disabled"); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: PICKUPEXTEN is %s\n", d->id, (d->directed_pickup) ? "enabled" : "disabled"); #endif for (i = 0; i < v_count; i++) { const uint8_t *b = v->ptr; uint8_t c, j, cp = 0; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Set[%-2d]= ", d->id, v->id); for (c = 0, cp = 0; c < v->count; c++, cp++) { r1->msg.SoftKeySetResMessage.definition[v->id].softKeyTemplateIndex[cp] = 0; /* look for the SKINNY_LBL_ number in the softkeysmap */ if ((b[c] == SKINNY_LBL_PARK) && (!d->park)) { continue; } if ((b[c] == SKINNY_LBL_TRANSFER) && (!d->transfer)) { continue; } if ((b[c] == SKINNY_LBL_DND) && (!d->dndFeature.enabled)) { continue; } if ((b[c] == SKINNY_LBL_CFWDALL) && (!d->cfwdall)) { continue; } if ((b[c] == SKINNY_LBL_CFWDBUSY) && (!d->cfwdbusy)) { continue; } if ((b[c] == SKINNY_LBL_CFWDNOANSWER) && (!d->cfwdnoanswer)) { continue; } if ((b[c] == SKINNY_LBL_TRNSFVM) && (!trnsfvm)) { continue; } if ((b[c] == SKINNY_LBL_IDIVERT) && (!trnsfvm)) { continue; } if ((b[c] == SKINNY_LBL_MEETME) && (!meetme)) { continue; } #ifndef CS_ADV_FEATURES if ((b[c] == SKINNY_LBL_BARGE)) { continue; } if ((b[c] == SKINNY_LBL_CBARGE)) { continue; } #endif #ifndef CS_SCCP_CONFERENCE if ((b[c] == SKINNY_LBL_JOIN)) { continue; } if ((b[c] == SKINNY_LBL_CONFRN)) { continue; } #endif #ifdef CS_SCCP_PICKUP if ((b[c] == SKINNY_LBL_PICKUP) && (!d->directed_pickup)) { continue; } if ((b[c] == SKINNY_LBL_GPICKUP) && (!pickupgroup)) { continue; } #endif if ((b[c] == SKINNY_LBL_PRIVATE) && (!d->privacyFeature.enabled)) { continue; } if (b[c] == SKINNY_LBL_EMPTY) { continue; } for (j = 0; j < sizeof(softkeysmap); j++) { if (b[c] == softkeysmap[j]) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) ("%-2d:%-10s ", c, label2str(softkeysmap[j])); r1->msg.SoftKeySetResMessage.definition[v->id].softKeyTemplateIndex[cp] = (j + 1); break; } } } sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) ("\n"); v++; iKeySetCount++; }; /* disable videomode and join softkey for all softkeysets */ for (i = 0; i < KEYMODE_ONHOOKSTEALABLE; i++) { sccp_softkey_setSoftkeyState(d, i, SKINNY_LBL_VIDEO_MODE, FALSE); sccp_softkey_setSoftkeyState(d, i, SKINNY_LBL_JOIN, FALSE); } sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "There are %d SoftKeySets.\n", iKeySetCount); r1->msg.SoftKeySetResMessage.lel_softKeySetCount = htolel(iKeySetCount); r1->msg.SoftKeySetResMessage.lel_totalSoftKeySetCount = htolel(iKeySetCount); // <<-- for now, but should be: iTotalKeySetCount; sccp_dev_send(d, r1); sccp_dev_set_keyset(d, 0, 0, KEYMODE_ONHOOK); } /*! * \brief Handle Dialed PhoneBook Message for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_dialedphonebook_message(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { /* this is from CCM7 dump */ sccp_moo_t *r1 = NULL; // sccp_BFLState_t state; uint32_t state; sccp_line_t *line; uint32_t unknown1 = 0; /* just 4 bits filled */ uint32_t index = 0; /* just 28 bits used */ uint32_t unknown2 = 0; /* all 32 bits used */ uint32_t lineInstance = 0; /* */ char *number; index = letohl(r->msg.DialedPhoneBookMessage.lel_NumberIndex); unknown1 = (index | 0xFFFFFFF0) ^ 0xFFFFFFF0; index = index >> 4; unknown2 = letohl(r->msg.DialedPhoneBookMessage.lel_unknown); // i don't understand this :) lineInstance = letohl(r->msg.DialedPhoneBookMessage.lel_lineinstance); number = r->msg.DialedPhoneBookMessage.phonenumber; // Sending 0x152 Ack Message. REQ(r1, DialedPhoneBookAckMessage); r1->msg.DialedPhoneBookAckMessage.lel_NumberIndex = r->msg.DialedPhoneBookMessage.lel_NumberIndex; r1->msg.DialedPhoneBookAckMessage.lel_lineinstance = r->msg.DialedPhoneBookMessage.lel_lineinstance; r1->msg.DialedPhoneBookAckMessage.lel_unknown = r->msg.DialedPhoneBookMessage.lel_unknown; r1->msg.DialedPhoneBookAckMessage.lel_unknown2 = 0; sccp_dev_send(d, r1); /* sometimes a phone sends an ' ' entry, I think we can ignore this one */ if (strlen(r->msg.DialedPhoneBookMessage.phonenumber) <= 1) { return; } line = sccp_line_find_byid(d, lineInstance); if (!line) { return; } REQ(r1, CallListStateUpdate); state = PBX(getExtensionState) (number, line->context); r1->msg.CallListStateUpdate.lel_NumberIndex = htolel(r->msg.DialedPhoneBookMessage.lel_NumberIndex); r1->msg.CallListStateUpdate.lel_lineinstance = htolel(r->msg.DialedPhoneBookMessage.lel_lineinstance); r1->msg.CallListStateUpdate.lel_state = htolel(state); sccp_dev_send(d, r1); sccp_log((DEBUGCAT_HINT | DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: send CallListStateUpdate for extension '%s', context '%s', state %d\n", DEV_ID_LOG(d), number, line->context, state); sccp_log((DEBUGCAT_HINT | DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: Device sent Dialed PhoneBook Rec.'%u' (%u) dn '%s' (0x%08X) line instance '%d'.\n", DEV_ID_LOG(d), index, unknown1, r->msg.DialedPhoneBookMessage.phonenumber, unknown2, lineInstance); line = sccp_line_release(line); } /*! * \brief Handle Time/Date Request Message for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_time_date_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { time_t timer = 0; struct tm *cmtime = NULL; char servername[StationMaxDisplayNotifySize]; sccp_moo_t *r1; if (!s) return; REQ(r1, DefineTimeDate); /* modulate the timezone by full hours only */ timer = time(0) + (d->tz_offset * 3600); cmtime = localtime(&timer); r1->msg.DefineTimeDate.lel_year = htolel(cmtime->tm_year + 1900); r1->msg.DefineTimeDate.lel_month = htolel(cmtime->tm_mon + 1); r1->msg.DefineTimeDate.lel_dayOfWeek = htolel(cmtime->tm_wday); r1->msg.DefineTimeDate.lel_day = htolel(cmtime->tm_mday); r1->msg.DefineTimeDate.lel_hour = htolel(cmtime->tm_hour); r1->msg.DefineTimeDate.lel_minute = htolel(cmtime->tm_min); r1->msg.DefineTimeDate.lel_seconds = htolel(cmtime->tm_sec); r1->msg.DefineTimeDate.lel_milliseconds = htolel(0); r1->msg.DefineTimeDate.lel_systemTime = htolel(timer); sccp_dev_send(d, r1); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: Send date/time\n", DEV_ID_LOG(d)); /* According to SCCP protocol since version 3, the first instance of asking for time and date concludes the device registration process. This is included even in the minimal subset of device registration commands. */ if (d->registrationState == SKINNY_DEVICE_RS_PROGRESS) { sccp_dev_set_registered(s->device, SKINNY_DEVICE_RS_OK); snprintf(servername, sizeof(servername), "%s %s", GLOB(servername), SKINNY_DISP_CONNECTED); sccp_dev_displaynotify(d, servername, 5); } } /*! * \brief Handle KeyPad Button for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - channel * - see sccp_device_find_index_for_line() * - see sccp_dev_displayprompt() * - see sccp_handle_dialtone() */ void sccp_handle_keypad_button(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { int digit; uint8_t lineInstance; uint32_t callid; char resp = '\0'; int len = 0; sccp_channel_t *channel = NULL; sccp_line_t *l = NULL; digit = letohl(r->msg.KeypadButtonMessage.lel_kpButton); lineInstance = letohl(r->msg.KeypadButtonMessage.lel_lineInstance); callid = letohl(r->msg.KeypadButtonMessage.lel_callReference); if (!d) { // should never be possible, d should have been retained in calling function pbx_log(LOG_NOTICE, "%s: Device sent a Keypress, but device is not specified! Exiting\n", DEV_ID_LOG(s->device)); } if (lineInstance) { l = sccp_line_find_byid(d, lineInstance); } if (callid) { if (d->active_channel && d->active_channel->callid == callid) { channel = sccp_channel_get_active(d); if (l && channel->line != l) { l = sccp_line_release(l); } if (!l) { l = channel ? sccp_line_retain(channel->line) : NULL; } } else { if (l) { channel = sccp_find_channel_on_line_byid(l, callid); } else { channel = sccp_channel_find_byid(callid); l = channel ? sccp_line_retain(channel->line) : NULL; } } } /* Old phones like 7912 never uses callid * so here we don't have a channel, this way we * should get the active channel on device */ if (!channel) { channel = sccp_channel_get_active(d); pbx_log(LOG_NOTICE, "%s: Could not find channel by callid %d on line %s with instance %d! Using active channel %d instead.\n", DEV_ID_LOG(d), callid, (l ? l->name : (channel ? channel->line->name : "Undef")), lineInstance, (channel ? channel->callid : 0)); if (channel && !l) { l = sccp_line_retain(channel->line); } } if (!channel) { pbx_log(LOG_NOTICE, "%s: Device sent a Keypress, but there is no (active) channel! Exiting\n", DEV_ID_LOG(d)); goto EXIT_FUNC; } if (!channel->owner) { pbx_log(LOG_NOTICE, "%s: Device sent a Keypress, but there is no (active) pbx channel! Exiting\n", DEV_ID_LOG(d)); sccp_channel_endcall(channel); goto EXIT_FUNC; } if (!l) { pbx_log(LOG_NOTICE, "%s: Device sent a Keypress, but there is no line specified! Exiting\n", DEV_ID_LOG(d)); goto EXIT_FUNC; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: SCCP Digit: %08x (%d) on line %s, channel %d with state: %d\n", DEV_ID_LOG(d), digit, digit, l->name, channel->callid, channel->state); if (digit == 14) { resp = '*'; } else if (digit == 15) { resp = '#'; } else if (digit >= 0 && digit <= 9) { resp = '0' + digit; } else { resp = '0' + digit; pbx_log(LOG_WARNING, "Unsupported digit %d\n", digit); } /* added PROGRESS to make sending digits possible during progress state (Pavel Troller) */ if (channel->state == SCCP_CHANNELSTATE_CONNECTED || channel->state == SCCP_CHANNELSTATE_CONNECTEDCONFERENCE || channel->state == SCCP_CHANNELSTATE_PROCEED || channel->state == SCCP_CHANNELSTATE_PROGRESS || channel->state == SCCP_CHANNELSTATE_RINGOUT) { /* we have to unlock 'cause the senddigit lock the channel */ sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_1 "%s: Sending DTMF Digit %c(%d) to %s\n", DEV_ID_LOG(d), digit, resp, l->name); sccp_pbx_senddigit(channel, resp); goto EXIT_FUNC; } if ((channel->state == SCCP_CHANNELSTATE_DIALING) || (channel->state == SCCP_CHANNELSTATE_OFFHOOK) || (channel->state == SCCP_CHANNELSTATE_GETDIGITS)) { len = strlen(channel->dialedNumber); if (len >= (SCCP_MAX_EXTENSION - 1)) { sccp_dev_displayprompt(d, lineInstance, channel->callid, "No more digits", 5); } else { // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: else state\n"); // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: GLOB(digittimeoutchar) = '%c'\n",GLOB(digittimeoutchar)); // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: resp = '%c'\n", resp); // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: GLOB(digittimeoutchar) %s resp\n", (GLOB(digittimeoutchar) == resp)?"==":"!="); /* enbloc emulation */ double max_deviation = SCCP_SIM_ENBLOC_DEVIATION; int max_time_per_digit = SCCP_SIM_ENBLOC_MAX_PER_DIGIT; double variance = 0; double std_deviation = 0; int minimum_digit_before_check = SCCP_SIM_ENBLOC_MIN_DIGIT; int lpbx_digit_usecs = 0; int number_of_digits = len; int timeout_if_enbloc = SCCP_SIM_ENBLOC_TIMEOUT; // new timeout if we have established we should enbloc dialing sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_1 "SCCP: ENBLOC_EMU digittimeout '%d' ms, sched_wait '%d' ms\n", channel->enbloc.digittimeout, PBX(sched_wait) (channel->scheduler.digittimeout)); if (GLOB(simulate_enbloc) && !channel->enbloc.deactivate && number_of_digits >= 1) { // skip the first digit (first digit had longer delay than the rest) if ((channel->enbloc.digittimeout) < (PBX(sched_wait) (channel->scheduler.digittimeout) * 1000)) { lpbx_digit_usecs = (channel->enbloc.digittimeout) - (PBX(sched_wait) (channel->scheduler.digittimeout)); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: ENBLOC EMU Cancelled (past digittimeout)\n"); channel->enbloc.deactivate = 1; } channel->enbloc.totaldigittime += lpbx_digit_usecs; channel->enbloc.totaldigittimesquared += pow(lpbx_digit_usecs, 2); sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_1 "SCCP: ENBLOC_EMU digit entry time '%d' ms, total dial time '%d' ms, number of digits: %d\n", lpbx_digit_usecs, channel->enbloc.totaldigittime, number_of_digits); if (number_of_digits >= 2) { // prevent div/0 if (number_of_digits >= minimum_digit_before_check) { // minimal number of digits before checking if (lpbx_digit_usecs < max_time_per_digit) { variance = ((double) channel->enbloc.totaldigittimesquared - (pow((double) channel->enbloc.totaldigittime, 2) / (double) number_of_digits)) / ((double) number_of_digits - 1); std_deviation = sqrt(variance); sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_1 "SCCP: ENBLOC EMU sqrt((%d-((pow(%d, 2))/%d))/%d)='%2.2f'\n", channel->enbloc.totaldigittimesquared, channel->enbloc.totaldigittime, number_of_digits, number_of_digits - 1, std_deviation); sccp_log(DEBUGCAT_ACTION) (VERBOSE_PREFIX_1 "SCCP: ENBLOC EMU totaldigittimesquared '%d', totaldigittime '%d', number_of_digits '%d', std_deviation '%2.2f', variance '%2.2f'\n", channel->enbloc.totaldigittimesquared, channel->enbloc.totaldigittime, number_of_digits, std_deviation, variance); if (std_deviation < max_deviation) { if (channel->enbloc.digittimeout > timeout_if_enbloc) { // only display message and change timeout once sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: ENBLOC EMU FAST DIAL (new timeout=2 sec)\n"); channel->enbloc.digittimeout = timeout_if_enbloc; // set new digittimeout } } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: ENBLOC EMU Cancelled (deviation from mean '%2.2f' > maximum '%2.2f')\n", std_deviation, max_deviation); channel->enbloc.deactivate = 1; } } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: ENBLOC EMU Cancelled (time per digit '%d' > maximum '%d')\n", lpbx_digit_usecs, max_time_per_digit); channel->enbloc.deactivate = 1; } } } } /* add digit to dialed number */ channel->dialedNumber[len++] = resp; channel->dialedNumber[len] = '\0'; /* removing scheduled dial */ channel->scheduler.digittimeout = SCCP_SCHED_DEL(channel->scheduler.digittimeout); // Overlap Dialing should set display too -FS if (channel->state == SCCP_CHANNELSTATE_DIALING && PBX(getChannelPbx) (channel)) { /* we shouldn't start pbx another time */ sccp_pbx_senddigit(channel, resp); goto EXIT_FUNC; } /* as we're not in overlapped mode we should add timeout again */ if ((channel->scheduler.digittimeout = sccp_sched_add(channel->enbloc.digittimeout, sccp_pbx_sched_dial, channel)) < 0) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: Unable to reschedule dialing in '%d' ms\n", channel->enbloc.digittimeout); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: reschedule dialing in '%d' ms\n", channel->enbloc.digittimeout); } #ifdef CS_SCCP_PICKUP if (!strcmp(channel->dialedNumber, pbx_pickup_ext()) && (channel->state != SCCP_CHANNELSTATE_GETDIGITS)) { /* set it to offhook state because the sccp_sk_gpickup function look for an offhook channel */ channel->state = SCCP_CHANNELSTATE_OFFHOOK; sccp_sk_gpickup(d, channel->line, lineInstance, channel); goto EXIT_FUNC; } #endif if (GLOB(digittimeoutchar) == resp) { // we dial on digit timeout char ! sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Got digit timeout char '%c', dial immediately\n", GLOB(digittimeoutchar)); channel->dialedNumber[len] = '\0'; if (channel->scheduler.digittimeout) { channel->scheduler.digittimeout = SCCP_SCHED_DEL(channel->scheduler.digittimeout); } sccp_safe_sleep(100); // we would hear last keypad stroke before starting all sccp_pbx_softswitch(channel); goto EXIT_FUNC; } if (sccp_pbx_helper(channel) == SCCP_EXTENSION_EXACTMATCH) { // we dial when helper says we have a match if (channel->scheduler.digittimeout) { channel->scheduler.digittimeout = SCCP_SCHED_DEL(channel->scheduler.digittimeout); } sccp_safe_sleep(100); // we would hear last keypad stroke before starting all sccp_pbx_softswitch(channel); // channel will be released by hangup goto EXIT_FUNC; } } } else { pbx_log(LOG_WARNING, "%s: keypad_button could not be handled correctly because of invalid state on line %s, channel: %d, state: %d\n", DEV_ID_LOG(d), l->name, channel->callid, channel->state); } sccp_handle_dialtone(channel); EXIT_FUNC: l = l ? sccp_line_release(l) : NULL; channel = channel ? sccp_channel_release(channel) : NULL; } /*! * \brief Handle DialTone Without Lock * \param channel SCCP Channel as sccp_channel_t */ void sccp_handle_dialtone(sccp_channel_t * channel) { sccp_line_t *l = NULL; sccp_device_t *d = NULL; int lenDialed = 0, lenSecDialtoneDigits = 0; uint8_t instance; uint32_t callid = 0; uint32_t secondary_dialtone_tone = 0; if (!channel) { return; } if (!(l = sccp_line_retain(channel->line))) { return; } if (!(d = sccp_channel_getDevice_retained(channel))) { return; } callid = channel->callid; lenDialed = strlen(channel->dialedNumber); instance = sccp_device_find_index_for_line(d, l->name); /* secondary dialtone check */ lenSecDialtoneDigits = strlen(l->secondary_dialtone_digits); secondary_dialtone_tone = l->secondary_dialtone_tone; /* we check dialtone just in DIALING action * otherwise, you'll get secondary dialtone also * when catching call forward number, meetme room, * etc. * */ if (channel->ss_action != SCCP_SS_DIAL) { l = sccp_line_release(l); d = sccp_device_release(d); return; } if (lenDialed == 0 && channel->state != SCCP_CHANNELSTATE_OFFHOOK) { sccp_dev_stoptone(d, instance, channel->callid); sccp_dev_starttone(d, SKINNY_TONE_INSIDEDIALTONE, instance, channel->callid, 0); } else if (lenDialed == 1) { if (channel->state != SCCP_CHANNELSTATE_DIALING) { sccp_dev_stoptone(d, instance, channel->callid); sccp_indicate(d, channel, SCCP_CHANNELSTATE_DIALING); } else { sccp_dev_stoptone(d, instance, channel->callid); } } if (d && channel && l) { if (lenSecDialtoneDigits && lenDialed == lenSecDialtoneDigits && !strncmp(channel->dialedNumber, l->secondary_dialtone_digits, lenSecDialtoneDigits)) { /* We have a secondary dialtone */ sccp_dev_starttone(d, secondary_dialtone_tone, instance, callid, 0); } else if ((lenSecDialtoneDigits) && (lenDialed == lenSecDialtoneDigits + 1 || (lenDialed > 1 && lenSecDialtoneDigits > 1 && lenDialed == lenSecDialtoneDigits - 1))) { sccp_dev_stoptone(d, instance, callid); } } l = sccp_line_release(l); d = sccp_device_release(d); } /*! * \brief Handle Soft Key Event for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_soft_key_event(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_channel_t *c = NULL; sccp_line_t *l = NULL; const sccp_softkeyMap_cb_t *softkeyMap_cb = NULL; sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Got Softkey\n", DEV_ID_LOG(d)); uint32_t event = letohl(r->msg.SoftKeyEventMessage.lel_softKeyEvent); uint32_t lineInstance = letohl(r->msg.SoftKeyEventMessage.lel_lineInstance); uint32_t callid = letohl(r->msg.SoftKeyEventMessage.lel_callReference); if (!d) { pbx_log(LOG_ERROR, "SCCP: Received Softkey Event but no device to connect it to. Exiting\n"); return; } event = softkeysmap[event - 1]; /* correct events for nokia icc client (Legacy Support -FS) */ if (d->config_type && !strcasecmp(d->config_type, "nokia-icc")) { switch (event) { case SKINNY_LBL_DIRTRFR: event = SKINNY_LBL_ENDCALL; break; } } sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Got Softkey: %s (%d) line=%d callid=%d\n", d->id, label2str(event), event, lineInstance, callid); /* we have no line and call information -> use default line */ if (!lineInstance && !callid && (event == SKINNY_LBL_NEWCALL || event == SKINNY_LBL_REDIAL)) { if (d->defaultLineInstance > 0) lineInstance = d->defaultLineInstance; else l = sccp_dev_get_activeline(d); } if (lineInstance) { l = sccp_line_find_byid(d, lineInstance); } if (l && callid) { c = sccp_find_channel_on_line_byid(l, callid); } do { softkeyMap_cb = sccp_getSoftkeyMap_by_SoftkeyEvent(event); if (!softkeyMap_cb) { pbx_log(LOG_WARNING, "Don't know how to handle keypress %d\n", event); break; } if (softkeyMap_cb->channelIsNecessary == TRUE && !c) { char buf[100]; snprintf(buf, 100, "No channel for %s!", label2str(event)); sccp_dev_displayprompt(d, lineInstance, 0, buf, 7); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, lineInstance, 0, 0); pbx_log(LOG_WARNING, "%s: Skip handling of Softkey %s (%d) line=%d callid=%d, because a channel is required, but not provided. Exiting\n", d->id, label2str(event), event, lineInstance, callid); /* disable callplane for this device */ sccp_device_sendcallstate(d, lineInstance, callid, SKINNY_CALLSTATE_ONHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_set_cplane(d, lineInstance, 0); sccp_dev_set_keyset(d, lineInstance, callid, KEYMODE_ONHOOK); break; } sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_ACTION | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Handling Softkey: %s on line: %s and channel: %s\n", d->id, label2str(event), l ? l->name : "UNDEF", c ? sccp_channel_toString(c) : "UNDEF"); softkeyMap_cb->softkeyEvent_cb(d, l, lineInstance, c); } while (FALSE); c = c ? sccp_channel_release(c) : NULL; l = l ? sccp_line_release(l) : NULL; } /*! * \brief Handle Start Media Transmission Acknowledgement for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - channel * - see sccp_channel_startmediatransmission() * - see sccp_channel_endcall() */ void sccp_handle_open_receive_channel_ack(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { struct sockaddr_in sin = { 0 }; uint32_t port = 0; uint32_t status = 0, callReference = 0, passThruPartyId = 0; sccp_channel_t *channel = NULL; char iabuf[INET6_ADDRSTRLEN]; struct sockaddr_storage ss = { 0 }; d->protocol->parseOpenReceiveChannelAck((const sccp_moo_t *) r, &status, &ss, &passThruPartyId, &callReference); /* converting back to sin/sin6 for now until all sockaddresses are stored/passed as sockaddr_storage */ if (ss.ss_family == AF_INET) { sin = *((struct sockaddr_in *) &ss); inet_ntop(AF_INET, &sin.sin_addr, iabuf, INET_ADDRSTRLEN); port = ntohs(sin.sin_port); // sccp_log(0)("SCCP: (sccp_handle_open_receive_channel_ack) IPv4 (%s:%d)\n", iabuf, port); } else { struct sockaddr_in6 sin6 = *((struct sockaddr_in6 *) &ss); inet_ntop(AF_INET6, &sin6.sin6_addr, iabuf, INET6_ADDRSTRLEN); port = ntohs(sin6.sin6_port); pbx_log(LOG_ERROR, "SCCP: IPv6 not supported at this moment (%s:%d)\n", iabuf, port); return; } if (d->nat || !d->directrtp) { memcpy(&sin.sin_addr, &s->sin.sin_addr, sizeof(sin.sin_addr)); } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Got OpenChannel ACK. Status: %d, Remote RTP/UDP '%s:%d', Type: %s, PassThruPartyId: %u, CallID: %u\n", d->id, status, iabuf, port, (d->directrtp ? "DirectRTP" : "Indirect RTP"), passThruPartyId, callReference); if (status) { // rtp error from the phone pbx_log(LOG_ERROR, "%s: (OpenReceiveChannelAck) Device returned error: %d ! No RTP stream available. Possibly all the rtp streams the phone supports have been used up. Giving up.\n", d->id, status); return; } if (d->skinny_type == SKINNY_DEVICETYPE_CISCO6911 && 0 == passThruPartyId) { passThruPartyId = 0xFFFFFFFF - callReference; sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: Dealing with 6911 which does not return a passThruPartyId, using callid: %u -> passThruPartyId %u\n", d->id, callReference, passThruPartyId); } if ((d->active_channel && d->active_channel->passthrupartyid == passThruPartyId) || !passThruPartyId) { // reduce the amount of searching by first checking active_channel channel = sccp_channel_retain(d->active_channel); } else { channel = sccp_channel_find_on_device_bypassthrupartyid(d, passThruPartyId); } if (channel) { // && sccp_channel->state != SCCP_CHANNELSTATE_DOWN) { if (channel->state == SCCP_CHANNELSTATE_INVALIDNUMBER) { pbx_log(LOG_WARNING, "%s: (OpenReceiveChannelAck) Invalid Number (%d)\n", DEV_ID_LOG(d), channel->state); channel = sccp_channel_release(channel); return; } if (channel->state == SCCP_CHANNELSTATE_DOWN) { pbx_log(LOG_WARNING, "%s: (OpenReceiveChannelAck) Channel is down. Giving up... (%d)\n", DEV_ID_LOG(d), channel->state); sccp_moo_t *r; REQ(r, CloseReceiveChannel); r->msg.CloseReceiveChannel.lel_conferenceId = htolel(callReference); r->msg.CloseReceiveChannel.lel_passThruPartyId = htolel(passThruPartyId); r->msg.CloseReceiveChannel.lel_conferenceId1 = htolel(callReference); sccp_dev_send(d, r); channel = sccp_channel_release(channel); return; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Starting Phone RTP/UDP Transmission (State: %s[%d])\n", d->id, sccp_indicate2str(channel->state), channel->state); sccp_channel_setDevice(channel, d); if (channel->rtp.audio.rtp) { sccp_channel_set_active(d, channel); //ast_rtp_set_peer(channel->rtp.audio.rtp, &sin); sccp_rtp_set_phone(channel, &channel->rtp.audio, &sin); sccp_channel_startmediatransmission(channel); /*!< Starting Media Transmission Earlier to fix 2 second delay - Copied from v2 - FS */ /* update status */ channel->rtp.audio.writeState |= SCCP_RTP_STATUS_ACTIVE; /* indicate up state only if both transmit and receive is done - this should fix the 1sek delay -MC */ if ((channel->state == SCCP_CHANNELSTATE_CONNECTED || channel->state == SCCP_CHANNELSTATE_CONNECTEDCONFERENCE) && ((channel->rtp.audio.writeState & SCCP_RTP_STATUS_ACTIVE) && (channel->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE))) { PBX(set_callstate) (channel, AST_STATE_UP); } } else { pbx_log(LOG_ERROR, "%s: (OpenReceiveChannelAck) Can't set the RTP media address to %s:%d, no asterisk rtp channel!\n", d->id, pbx_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port)); sccp_channel_endcall(channel); // FS - 350 } channel = sccp_channel_release(channel); } else { /* we successfully opened receive channel, but have no channel active -> close receive */ int callId = passThruPartyId ^ 0xFFFFFFFF; pbx_log(LOG_ERROR, "%s: (OpenReceiveChannelAck) No channel with this PassThruPartyId %u (callReference: %d, callid: %d)!\n", d->id, passThruPartyId, callReference, callId); sccp_moo_t *r; REQ(r, CloseReceiveChannel); r->msg.CloseReceiveChannel.lel_conferenceId = htolel(callId); r->msg.CloseReceiveChannel.lel_passThruPartyId = htolel(passThruPartyId); r->msg.CloseReceiveChannel.lel_conferenceId1 = htolel(callId); sccp_dev_send(d, r); } } /*! * \brief Handle Open Multi Media Receive Acknowledgement * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - channel * - see sccp_dev_send() */ void sccp_handle_OpenMultiMediaReceiveAck(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { struct sockaddr_in sin = { 0 }; struct sockaddr_storage ss = { 0 }; sccp_channel_t *channel; uint32_t status = 0, partyID = 0, passThruPartyId = 0, callReference; d->protocol->parseOpenMultiMediaReceiveChannelAck((const sccp_moo_t *) r, &status, &ss, &passThruPartyId, &callReference); /* converting back to sin/sin6 for now until all sockaddresses are stored/passed as sockaddr_storage */ if (ss.ss_family == AF_INET) { sin = *((struct sockaddr_in *) &ss); } else { pbx_log(LOG_ERROR, "SCCP: IPv6 not supported at this moment\n"); return; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Got OpenMultiMediaReceiveChannelAck. Status: %d, Remote RTP/UDP '%s:%d', Type: %s, PassThruId: %u, CallID: %u\n", d->id, status, pbx_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), (d->directrtp ? "DirectRTP" : "Indirect RTP"), partyID, callReference); if (status) { /* rtp error from the phone */ pbx_log(LOG_WARNING, "%s: Error while opening MediaTransmission (%d). Ending call\n", DEV_ID_LOG(d), status); sccp_dump_packet((unsigned char *) &r->msg, r->header.length); return; } if ((d->active_channel && d->active_channel->passthrupartyid == passThruPartyId) || !passThruPartyId) { // reduce the amount of searching by first checking active_channel channel = sccp_channel_retain(d->active_channel); } else { channel = sccp_channel_find_on_device_bypassthrupartyid(d, passThruPartyId); } /* prevent a segmentation fault on fast hangup after answer, failed voicemail for example */ if (channel) { // && sccp_channel->state != SCCP_CHANNELSTATE_DOWN) { if (channel->state == SCCP_CHANNELSTATE_INVALIDNUMBER) { channel = sccp_channel_release(channel); return; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: STARTING DEVICE RTP TRANSMISSION WITH STATE %s(%d)\n", d->id, sccp_indicate2str(channel->state), channel->state); memcpy(&channel->rtp.video.phone, &sin, sizeof(sin)); if (channel->rtp.video.rtp || sccp_rtp_createVideoServer(channel)) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Set the RTP media address to %s:%d\n", d->id, pbx_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port)); // ast_rtp_set_peer(channel->rtp.video.rtp, &sin); //sccp_rtp_set_peer(channel, &channel->rtp.video, &sin); sccp_rtp_set_phone(channel, &channel->rtp.video, &sin); channel->rtp.video.writeState |= SCCP_RTP_STATUS_ACTIVE; if ((channel->state == SCCP_CHANNELSTATE_CONNECTED) && (channel->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE) && (channel->rtp.audio.writeState & SCCP_RTP_STATUS_ACTIVE) ) { PBX(set_callstate) (channel, AST_STATE_UP); } } else { pbx_log(LOG_ERROR, "%s: Can't set the RTP media address to %s:%d, no asterisk rtp channel!\n", d->id, pbx_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port)); } sccp_moo_t *r1; r1 = sccp_build_packet(MiscellaneousCommandMessage, sizeof(r->msg.MiscellaneousCommandMessage)); r1->msg.MiscellaneousCommandMessage.lel_conferenceId = htolel(channel->callid); r1->msg.MiscellaneousCommandMessage.lel_passThruPartyId = htolel(channel->passthrupartyid); r1->msg.MiscellaneousCommandMessage.lel_callReference = htolel(channel->callid); r1->msg.MiscellaneousCommandMessage.lel_miscCommandType = htolel(1); /* videoFastUpdatePicture */ sccp_dev_send(d, r1); r1 = sccp_build_packet(Unknown_0x0141_Message, sizeof(r->msg.Unknown_0x0141_Message)); r1->msg.Unknown_0x0141_Message.lel_conferenceID = htolel(channel->callid); r1->msg.Unknown_0x0141_Message.lel_passThruPartyId = htolel(channel->passthrupartyid); r1->msg.Unknown_0x0141_Message.lel_callReference = htolel(channel->callid); r1->msg.Unknown_0x0141_Message.lel_maxBitRate = htolel(0x00000c80); sccp_dev_send(d, r1); PBX(queue_control) (channel->owner, AST_CONTROL_VIDUPDATE); channel = sccp_channel_release(channel); } else { pbx_log(LOG_ERROR, "%s: No channel with this PassThruId %u!\n", d->id, partyID); } } /*! * \brief Handle Version for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_version(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_moo_t *r1; REQ(r1, VersionMessage); sccp_copy_string(r1->msg.VersionMessage.requiredVersion, d->imageversion, sizeof(r1->msg.VersionMessage.requiredVersion)); sccp_dev_send(d, r1); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Sending version number: %s\n", d->id, d->imageversion); } #define CALC_AVG(_newval, _mean, _numval) ( ( (_mean * (_numval) ) + _newval ) / (_numval + 1)) /*! * \brief Handle Connection Statistics for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \section sccp_statistics Phone Audio Statistics * * MOS LQK = Mean Opinion Score for listening Quality (5=Excellent -> 1=BAD) * Max MOS LQK = Baseline or highest MOS LQK score observed from start of the voice stream. These codecs provide the following maximum MOS LQK score under normal conditions with no frame loss: (G.711 gives 4.5, G.729 A /AB gives 3.7) * MOS LQK Version = Version of the Cisco proprietary algorithm used to calculate MOS LQK scores. * CS = Concealement seconds * Cumulative Conceal Ratio = Total number of concealment frames divided by total number of speech frames received from start of the voice stream. * Interval Conceal Ratio = Ratio of concealment frames to speech frames in preceding 3-second interval of active speech. If using voice activity detection (VAD), a longer interval might be required to accumulate 3 seconds of active speech. * Max Conceal Ratio = Highest interval concealment ratio from start of the voice stream. * Conceal Secs = Number of seconds that have concealment events (lost frames) from the start of the voice stream (includes severely concealed seconds). * Severely Conceal Secs = Number of seconds that have more than 5 percent concealment events (lost frames) from the start of the voice stream. * Latency1 = Estimate of the network latency, expressed in milliseconds. Represents a running average of the round-trip delay, measured when RTCP receiver report blocks are received. * Max Jitter = Maximum value of instantaneous jitter, in milliseconds. * Sender Size = RTP packet size, in milliseconds, for the transmitted stream. * Rcvr Size = RTP packet size, in milliseconds, for the received stream. * Rcvr Discarded = RTP packets received from network but discarded from jitter buffers. */ void sccp_handle_ConnectionStatistics(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_call_statistics_t *last_call_stats = NULL; sccp_call_statistics_t *avg_call_stats = NULL; char QualityStats[128] = ""; if ((d = sccp_device_retain(d))) { // update last_call_statistics last_call_stats = &d->call_statistics[SCCP_CALLSTATISTIC_LAST]; strncpy(last_call_stats->type, "LAST", sizeof(last_call_stats->type)); if (letohl(r->header.lel_protocolVer < 19)) { last_call_stats->num = letohl(r->msg.ConnectionStatisticsRes.lel_CallIdentifier); last_call_stats->packets_sent = letohl(r->msg.ConnectionStatisticsRes.lel_SentPackets); last_call_stats->packets_received = letohl(r->msg.ConnectionStatisticsRes.lel_RecvdPackets); last_call_stats->packets_lost = letohl(r->msg.ConnectionStatisticsRes.lel_LostPkts); last_call_stats->jitter = letohl(r->msg.ConnectionStatisticsRes.lel_Jitter); last_call_stats->latency = letohl(r->msg.ConnectionStatisticsRes.lel_latency); sccp_copy_string(QualityStats, r->msg.ConnectionStatisticsRes.QualityStats, sizeof(QualityStats)); } else { last_call_stats->num = letohl(r->msg.ConnectionStatisticsRes_V19.lel_CallIdentifier); last_call_stats->packets_sent = letohl(r->msg.ConnectionStatisticsRes_V19.lel_SentPackets); last_call_stats->packets_received = letohl(r->msg.ConnectionStatisticsRes_V19.lel_RecvdPackets); last_call_stats->packets_lost = letohl(r->msg.ConnectionStatisticsRes_V19.lel_LostPkts); last_call_stats->jitter = letohl(r->msg.ConnectionStatisticsRes_V19.lel_Jitter); last_call_stats->latency = letohl(r->msg.ConnectionStatisticsRes_V19.lel_latency); sccp_copy_string(QualityStats, r->msg.ConnectionStatisticsRes_V19.QualityStats, sizeof(QualityStats)); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Call Statistics: CallID: %d Packets sent: %d rcvd: %d lost: %d jitter: %d latency: %d\n", d->id, last_call_stats->num, last_call_stats->packets_sent, last_call_stats->packets_received, last_call_stats->packets_lost, last_call_stats->jitter, last_call_stats->latency); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Call Quality Statistics: %s\n", d->id, QualityStats); if (!sccp_strlen_zero(QualityStats)) { sscanf(QualityStats, "MLQK=%f;MLQKav=%f;MLQKmn=%f;MLQKmx=%f;ICR=%f;CCR=%f;ICRmx=%f;CS=%d;SCS=%d;MLQKvr=%f", &last_call_stats->opinion_score_listening_quality, &last_call_stats->avg_opinion_score_listening_quality, &last_call_stats->mean_opinion_score_listening_quality, &last_call_stats->max_opinion_score_listening_quality, &last_call_stats->interval_concealement_ratio, &last_call_stats->cumulative_concealement_ratio, &last_call_stats->max_concealement_ratio, &last_call_stats->concealed_seconds, &last_call_stats->severely_concealed_seconds, &last_call_stats->variance_opinion_score_listening_quality); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: MLQK=%.4f;MLQKav=%.4f;MLQKmn=%.4f;MLQKmx=%.4f;ICR=%.4f;CCR=%.4f;ICRmx=%.4f;CS=%d;SCS=%d;MLQKvr=%.2f\n", d->id, last_call_stats->opinion_score_listening_quality, last_call_stats->avg_opinion_score_listening_quality, last_call_stats->mean_opinion_score_listening_quality, last_call_stats->max_opinion_score_listening_quality, last_call_stats->interval_concealement_ratio, last_call_stats->cumulative_concealement_ratio, last_call_stats->max_concealement_ratio, (int) last_call_stats->concealed_seconds, (int) last_call_stats->severely_concealed_seconds, last_call_stats->variance_opinion_score_listening_quality); // update avg_call_statistics avg_call_stats = &d->call_statistics[SCCP_CALLSTATISTIC_AVG]; strncpy(avg_call_stats->type, "AVG", sizeof(last_call_stats->type)); avg_call_stats->packets_sent = CALC_AVG(last_call_stats->packets_sent, avg_call_stats->packets_sent, avg_call_stats->num); avg_call_stats->packets_received = CALC_AVG(last_call_stats->packets_received, avg_call_stats->packets_received, avg_call_stats->num); avg_call_stats->packets_lost = CALC_AVG(last_call_stats->packets_lost, avg_call_stats->packets_lost, avg_call_stats->num); avg_call_stats->jitter = CALC_AVG(last_call_stats->jitter, avg_call_stats->jitter, avg_call_stats->num); avg_call_stats->latency = CALC_AVG(last_call_stats->latency, avg_call_stats->latency, avg_call_stats->num); avg_call_stats->opinion_score_listening_quality = CALC_AVG(last_call_stats->opinion_score_listening_quality, avg_call_stats->opinion_score_listening_quality, avg_call_stats->num); avg_call_stats->avg_opinion_score_listening_quality = CALC_AVG(last_call_stats->avg_opinion_score_listening_quality, avg_call_stats->avg_opinion_score_listening_quality, avg_call_stats->num); avg_call_stats->mean_opinion_score_listening_quality = CALC_AVG(last_call_stats->mean_opinion_score_listening_quality, avg_call_stats->mean_opinion_score_listening_quality, avg_call_stats->num); if (avg_call_stats->max_opinion_score_listening_quality < last_call_stats->max_opinion_score_listening_quality) avg_call_stats->max_opinion_score_listening_quality = last_call_stats->max_opinion_score_listening_quality; avg_call_stats->interval_concealement_ratio = CALC_AVG(last_call_stats->interval_concealement_ratio, avg_call_stats->interval_concealement_ratio, avg_call_stats->num); avg_call_stats->cumulative_concealement_ratio = CALC_AVG(last_call_stats->cumulative_concealement_ratio, avg_call_stats->cumulative_concealement_ratio, avg_call_stats->num); if (avg_call_stats->max_concealement_ratio < last_call_stats->max_concealement_ratio) avg_call_stats->max_concealement_ratio = last_call_stats->max_concealement_ratio; avg_call_stats->concealed_seconds = CALC_AVG(last_call_stats->concealed_seconds, avg_call_stats->concealed_seconds, avg_call_stats->num); avg_call_stats->severely_concealed_seconds = CALC_AVG(last_call_stats->severely_concealed_seconds, avg_call_stats->severely_concealed_seconds, avg_call_stats->num); avg_call_stats->variance_opinion_score_listening_quality = CALC_AVG(last_call_stats->variance_opinion_score_listening_quality, avg_call_stats->variance_opinion_score_listening_quality, avg_call_stats->num); avg_call_stats->num++; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Mean Statistics: # Calls: %d Packets sent: %d rcvd: %d lost: %d jitter: %d latency: %d\n", d->id, avg_call_stats->num, avg_call_stats->packets_sent, avg_call_stats->packets_received, avg_call_stats->packets_lost, avg_call_stats->jitter, avg_call_stats->latency); // update global_call_statistics /* avg_call_stats = &GLOB(avg_call_statistics); avg_call_stats->packets_sent = ((avg_call_stats->packets_sent * (avg_call_stats->num) ) + last_call_stats->packets_sent) / (avg_call_stats->num + 1); avg_call_stats->packets_received = ((avg_call_stats->packets_received * (avg_call_stats->num) ) + last_call_stats->packets_received) / (avg_call_stats->num + 1); avg_call_stats->packets_lost = ((avg_call_stats->packets_lost * (avg_call_stats->num) ) + last_call_stats->packets_lost) / (avg_call_stats->num + 1); avg_call_stats->jitter = ((avg_call_stats->jitter * (avg_call_stats->num) ) + last_call_stats->jitter) / (avg_call_stats->num + 1); avg_call_stats->latency = ((avg_call_stats->latency * (avg_call_stats->num) ) + last_call_stats->latency) / (avg_call_stats->num + 1); avg_call_stats->num++; */ d = sccp_device_release(d); } } /*! * \brief Handle Server Resource Message for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \todo extend ServerResMessage to be able to return multiple servers (cluster) * \todo Handle IPv6 */ void sccp_handle_ServerResMessage(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_moo_t *r1; if (!s->ourip.s_addr) { pbx_log(LOG_ERROR, "%s: Session IP Changed mid flight\n", DEV_ID_LOG(d)); return; } if (s->device && s->device->session != s) { pbx_log(LOG_ERROR, "%s: Wrong Session or Session Changed mid flight\n", DEV_ID_LOG(d)); return; } /* old protocol function replaced by the SEP file server addesses list */ sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Sending servers message\n", DEV_ID_LOG(d)); REQ(r1, ServerResMessage); sccp_copy_string(r1->msg.ServerResMessage.server[0].serverName, pbx_inet_ntoa(s->ourip), sizeof(r1->msg.ServerResMessage.server[0].serverName)); r1->msg.ServerResMessage.serverListenPort[0] = GLOB(bindaddr.sin_port); r1->msg.ServerResMessage.serverIpAddr[0] = s->ourip.s_addr; sccp_dev_send(d, r1); } /*! * \brief Handle Config Status Message for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - device * - device->buttonconfig */ void sccp_handle_ConfigStatMessage(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_moo_t *r1; sccp_buttonconfig_t *config = NULL; uint8_t lines = 0; uint8_t speeddials = 0; if (!&d->buttonconfig) return; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->type == SPEEDDIAL) speeddials++; else if (config->type == LINE) lines++; } SCCP_LIST_UNLOCK(&d->buttonconfig); REQ(r1, ConfigStatMessage); sccp_copy_string(r1->msg.ConfigStatMessage.station_identifier.deviceName, d->id, sizeof(r1->msg.ConfigStatMessage.station_identifier.deviceName)); r1->msg.ConfigStatMessage.station_identifier.lel_stationUserId = htolel(0); r1->msg.ConfigStatMessage.station_identifier.lel_stationInstance = htolel(1); r1->msg.ConfigStatMessage.lel_numberLines = htolel(lines); r1->msg.ConfigStatMessage.lel_numberSpeedDials = htolel(speeddials); sccp_dev_send(s->device, r1); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Sending ConfigStatMessage, lines %d, speeddials %d\n", DEV_ID_LOG(d), lines, speeddials); } /*! * \brief Handle Enbloc Call Messsage (Dial in one block, instead of number by number) * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \lock * - channel */ void sccp_handle_EnblocCallMessage(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_channel_t *channel = NULL; sccp_line_t *l = NULL; int len = 0; if (r && !sccp_strlen_zero(r->msg.EnblocCallMessage.calledParty)) { channel = sccp_channel_get_active(d); if (channel) { if ((channel->state == SCCP_CHANNELSTATE_DIALING) || (channel->state == SCCP_CHANNELSTATE_OFFHOOK)) { /* for anonymous devices we just want to call the extension defined in hotine->exten -> ignore dialed number -MC */ if (d->isAnonymous) { channel = sccp_channel_release(channel); return; } len = strlen(channel->dialedNumber); sccp_copy_string(channel->dialedNumber + len, r->msg.EnblocCallMessage.calledParty, sizeof(channel->dialedNumber) - len); channel->scheduler.digittimeout = SCCP_SCHED_DEL(channel->scheduler.digittimeout); sccp_pbx_softswitch(channel); channel = sccp_channel_release(channel); return; } sccp_pbx_senddigits(channel, r->msg.EnblocCallMessage.calledParty); channel = sccp_channel_release(channel); } else { // Pull up a channel l = sccp_dev_get_activeline(d); if (l) { channel = sccp_channel_newcall(l, d, r->msg.EnblocCallMessage.calledParty, SKINNY_CALLTYPE_OUTBOUND, NULL); channel = channel ? sccp_channel_release(channel) : NULL; l = sccp_line_release(l); } } } } /*! * \brief Handle Forward Status Reques for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_forward_stat_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_line_t *l; sccp_moo_t *r1 = NULL; uint32_t instance = letohl(r->msg.ForwardStatReqMessage.lel_lineNumber); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Got Forward Status Request. Line: %d\n", d->id, instance); l = sccp_line_find_byid(d, instance); if (l) { sccp_dev_forward_status(l, instance, d); l = sccp_line_release(l); } else { /* speeddial with hint. Sending empty forward message */ sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Send Forward Status. Instance: %d\n", d->id, instance); REQ(r1, ForwardStatMessage); r1->msg.ForwardStatMessage.lel_status = 0; r1->msg.ForwardStatMessage.lel_lineNumber = r->msg.ForwardStatReqMessage.lel_lineNumber; sccp_dev_send(d, r1); } } /*! * \brief Handle Feature Status Reques for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \warning * - device->buttonconfig is not always locked */ void sccp_handle_feature_stat_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_buttonconfig_t *config = NULL; int instance = letohl(r->msg.FeatureStatReqMessage.lel_featureInstance); int unknown = letohl(r->msg.FeatureStatReqMessage.lel_unknown); sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: Got Feature Status Request. Index = %d Unknown = %d \n", d->id, instance, unknown); #ifdef CS_DYNAMIC_SPEEDDIAL /* * the new speeddial style uses feature to display state * unfortunately we dont know how to handle this on other way */ sccp_speed_t k; if ((unknown == 1 && d->inuseprotocolversion >= 15)) { sccp_dev_speed_find_byindex(d, instance, TRUE, &k); if (k.valid) { sccp_moo_t *r1; REQ(r1, FeatureStatDynamicMessage); r1->msg.FeatureStatDynamicMessage.lel_instance = htolel(instance); r1->msg.FeatureStatDynamicMessage.lel_type = htolel(SKINNY_BUTTONTYPE_BLFSPEEDDIAL); r1->msg.FeatureStatDynamicMessage.lel_status = 0; sccp_copy_string(r1->msg.FeatureStatDynamicMessage.DisplayName, k.name, sizeof(r1->msg.FeatureStatDynamicMessage.DisplayName)); sccp_dev_send(d, r1); return; } } #endif SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->instance == instance && config->type == FEATURE) { sccp_feat_changed(d, NULL, config->button.feature.id); } } } /*! * \brief Handle Feature Status Request for Session * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_services_stat_req(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_moo_t *r1 = NULL; sccp_buttonconfig_t *config = NULL; int urlIndex = letohl(r->msg.ServiceURLStatReqMessage.lel_serviceURLIndex); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Got ServiceURL Status Request. Index = %d\n", d->id, urlIndex); if ((config = sccp_dev_serviceURL_find_byindex(s->device, urlIndex))) { if (d->inuseprotocolversion < 7) { REQ(r1, ServiceURLStatMessage); r1->msg.ServiceURLStatMessage.lel_serviceURLIndex = htolel(urlIndex); sccp_copy_string(r1->msg.ServiceURLStatMessage.URL, config->button.service.url, strlen(config->button.service.url) + 1); sccp_copy_string(r1->msg.ServiceURLStatMessage.label, config->label, strlen(config->label) + 1); } else { int URL_len = strlen(config->button.service.url); int label_len = strlen(config->label); int dummy_len = URL_len + label_len; int hdr_len = sizeof(r->msg.ServiceURLStatDynamicMessage) - 1; int padding = ((dummy_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 0; r1 = sccp_build_packet(ServiceURLStatDynamicMessage, hdr_len + dummy_len + padding); r1->msg.ServiceURLStatDynamicMessage.lel_serviceURLIndex = htolel(urlIndex); if (dummy_len) { char buffer[dummy_len + 2]; memset(&buffer[0], 0, dummy_len + 2); if (URL_len) memcpy(&buffer[0], config->button.service.url, URL_len); if (label_len) memcpy(&buffer[URL_len + 1], config->label, label_len); memcpy(&r1->msg.ServiceURLStatDynamicMessage.dummy, &buffer[0], dummy_len + 2); } } sccp_dev_send(d, r1); } else { sccp_log((DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: serviceURL %d not assigned\n", DEV_ID_LOG(s->device), urlIndex); } } /*! * \brief Handle Feature Action for Device * \param d SCCP Device as sccp_device_t * \param instance Instance as int * \param toggleState as boolean * * \warning * - device->buttonconfig is not always locked */ void sccp_handle_feature_action(sccp_device_t * d, int instance, boolean_t toggleState) { sccp_buttonconfig_t *config = NULL; sccp_line_t *line = NULL; sccp_callforward_t status = 0; /* state of cfwd */ uint32_t featureStat1 = 0; uint32_t featureStat2 = 0; uint32_t featureStat3 = 0; uint32_t res = 0; #ifdef CS_DEVSTATE_FEATURE char buf[254] = ""; #endif if (!d) { return; } sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: instance: %d, toggle: %s\n", d->id, instance, (toggleState) ? "yes" : "no"); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->instance == instance && config->type == FEATURE) { sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: toggle status from %d", d->id, config->button.feature.status); config->button.feature.status = (config->button.feature.status == 0) ? 1 : 0; sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 " to %d\n", config->button.feature.status); break; } } if (!config || !config->type || config->type != FEATURE) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Couldn find feature with ID = %d \n", d->id, instance); return; } /* notice: we use this function for request and changing status -> so just change state if toggleState==TRUE -MC */ char featureOption[255]; if (config->button.feature.options) { sccp_copy_string(featureOption, config->button.feature.options, sizeof(featureOption)); } sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: FeatureID = %d, Option: %s\n", d->id, config->button.feature.id, featureOption); switch (config->button.feature.id) { case SCCP_FEATURE_PRIVACY: if (!d->privacyFeature.enabled) { sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: privacy feature is disabled, ignore this change\n", d->id); break; } if (!strcasecmp(config->button.feature.options, "callpresent")) { res = d->privacyFeature.status & SCCP_PRIVACYFEATURE_CALLPRESENT; sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: device->privacyFeature.status=%d\n", d->id, d->privacyFeature.status); sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: result=%d\n", d->id, res); if (res) { /* switch off */ d->privacyFeature.status &= ~SCCP_PRIVACYFEATURE_CALLPRESENT; config->button.feature.status = 0; } else { d->privacyFeature.status |= SCCP_PRIVACYFEATURE_CALLPRESENT; config->button.feature.status = 1; } sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: device->privacyFeature.status=%d\n", d->id, d->privacyFeature.status); } else { sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: do not know how to handle %s\n", d->id, config->button.feature.options); } break; case SCCP_FEATURE_CFWDALL: status = SCCP_CFWD_NONE; // Ask for activation of the feature. if (config->button.feature.options && !sccp_strlen_zero(config->button.feature.options)) { // Now set the feature status. Note that the button status has already been toggled above. if (config->button.feature.status) { status = SCCP_CFWD_ALL; } } SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->type == LINE) { line = sccp_line_find_byname(config->button.line.name, FALSE); if (line) { sccp_line_cfwd(line, d, status, featureOption); line = sccp_line_release(line); } } } break; case SCCP_FEATURE_DND: if (!strcasecmp(config->button.feature.options, "silent")) { d->dndFeature.status = (config->button.feature.status) ? SCCP_DNDMODE_SILENT : SCCP_DNDMODE_OFF; } else if (!strcasecmp(config->button.feature.options, "busy")) { d->dndFeature.status = (config->button.feature.status) ? SCCP_DNDMODE_REJECT : SCCP_DNDMODE_OFF; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: dndmode %d is %s\n", d->id, d->dndFeature.status, (d->dndFeature.status) ? "on" : "off"); sccp_dev_check_displayprompt(d); sccp_feat_changed(d, NULL, SCCP_FEATURE_DND); break; #ifdef CS_SCCP_FEATURE_MONITOR case SCCP_FEATURE_MONITOR: if (TRUE == toggleState) { sccp_channel_t *channel = NULL; if (d->monitorFeature.status & SCCP_FEATURE_MONITOR_STATE_REQUESTED) { d->monitorFeature.status &= ~SCCP_FEATURE_MONITOR_STATE_REQUESTED; } else { d->monitorFeature.status |= SCCP_FEATURE_MONITOR_STATE_REQUESTED; } /* check if we need to start or stop monitor */ if (((d->monitorFeature.status & SCCP_FEATURE_MONITOR_STATE_REQUESTED) >> 1) == (d->monitorFeature.status & SCCP_FEATURE_MONITOR_STATE_ACTIVE)) { sccp_log(1) (VERBOSE_PREFIX_3 "%s: no need to update monitor state\n", d->id); } else { channel = sccp_channel_get_active(d); if (channel) { sccp_feat_monitor(d, channel->line, 0, channel); channel = sccp_channel_release(channel); } } sccp_log(1) (VERBOSE_PREFIX_3 "%s: set monitor state to %d\n", d->id, d->monitorFeature.status); } break; #endif #ifdef CS_DEVSTATE_FEATURE /** * Handling of custom devicestate toggle buttons. */ case SCCP_FEATURE_DEVSTATE: /* Set the appropriate devicestate, toggle it and write to the devstate astdb.. */ strncpy(buf, (config->button.feature.status) ? ("INUSE") : ("NOT_INUSE"), sizeof(buf)); res = PBX(feature_addToDatabase) (devstate_db_family, config->button.feature.options, buf); pbx_devstate_changed(pbx_devstate_val(buf), "Custom:%s", config->button.feature.options); sccp_log((DEBUGCAT_CORE | DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "%s: Feature Change DevState: '%s', State: '%s'\n", DEV_ID_LOG(d), config->button.feature.options, config->button.feature.status ? "On" : "Off"); break; #endif case SCCP_FEATURE_MULTIBLINK: featureStat1 = (d->priFeature.status & 0xf) - 1; featureStat2 = ((d->priFeature.status & 0xf00) >> 8) - 1; featureStat3 = ((d->priFeature.status & 0xf0000) >> 16) - 1; if (2 == featureStat2 && 6 == featureStat1) featureStat3 = (featureStat3 + 1) % 2; if (6 == featureStat1) featureStat2 = (featureStat2 + 1) % 3; featureStat1 = (featureStat1 + 1) % 7; d->priFeature.status = ((featureStat3 + 1) << 16) | ((featureStat2 + 1) << 8) | (featureStat1 + 1); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: priority feature status: %d, %d, %d, total: %d\n", d->id, featureStat3, featureStat2, featureStat1, d->priFeature.status); break; default: sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: unknown feature\n", d->id); break; } if (config) { sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: Got Feature Status Request. Index = %d Status: %d\n", d->id, instance, config->button.feature.status); sccp_feat_changed(d, NULL, config->button.feature.id); } return; } /*! * \brief Handle Update Capabilities Message * * This message is often used to add video and data capabilities to client. Atm we just use it for audio and video caps. * Will be better to store audio codec max packet size and video bandwidth and size. * In future we will parse also data caps to support T.38 and NSE with ATA186/188 devices. * * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \since 20090708 * \author Federico */ void sccp_handle_updatecapabilities_message(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { uint8_t audio_capability = 0, audio_codec = 0, audio_capabilities = 0; /* parsing audio caps */ audio_capabilities = letohl(r->msg.UpdateCapabilitiesMessage.lel_audioCapCount); sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Device has %d Audio Capabilities\n", DEV_ID_LOG(d), audio_capabilities); if (audio_capabilities > 0 && audio_capabilities <= SKINNY_MAX_CAPABILITIES) { for (audio_capability = 0; audio_capability < audio_capabilities; audio_capability++) { audio_codec = letohl(r->msg.UpdateCapabilitiesMessage.audioCaps[audio_capability].lel_payloadCapability); d->capabilities.audio[audio_capability] = audio_codec; /** store our audio capabilities */ sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%7d %-25s\n", DEV_ID_LOG(d), audio_codec, codec2str(audio_codec)); } } #ifdef CS_SCCP_VIDEO uint8_t video_capabilities = 0, video_capability = 0; uint8_t video_codec = 0; /* parsing video caps */ video_capabilities = letohl(r->msg.UpdateCapabilitiesMessage.lel_videoCapCount); /* enable video mode button if device has video capability */ if (video_capabilities > 0 && video_capabilities <= SKINNY_MAX_VIDEO_CAPABILITIES) { sccp_softkey_setSoftkeyState(d, KEYMODE_CONNTRANS, SKINNY_LBL_VIDEO_MODE, TRUE); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: enable video mode softkey\n", DEV_ID_LOG(d)); sccp_dev_set_message(d, "Video support enabled", 5, FALSE, TRUE); sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Device has %d Video Capabilities\n", DEV_ID_LOG(d), video_capabilities); for (video_capability = 0; video_capability < video_capabilities; video_capability++) { video_codec = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].lel_payloadCapability); d->capabilities.video[video_capability] = video_codec; /** store our video capabilities */ #if DEBUG char transmitReceiveStr[5]; sprintf(transmitReceiveStr, "%c-%c", (letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].lel_transmitOrReceive) & SKINNY_TRANSMITRECEIVE_RECEIVE) ? '<' : ' ', (letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].lel_transmitOrReceive) & SKINNY_TRANSMITRECEIVE_TRANSMIT) ? '>' : ' '); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%-3s %3d %-25s\n", DEV_ID_LOG(d), transmitReceiveStr, video_codec, codec2str(video_codec)); uint8_t video_levels = 0, video_level = 0; skinny_videoformat_t video_format = 0; video_levels = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].lel_levelPreferenceCount); for (video_level = 0; video_level < video_levels; video_level++) { video_format = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].levelPreference[video_level].format); int transmitPreference = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].levelPreference[video_level].transmitPreference); int maxBitRate = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].levelPreference[video_level].maxBitRate); int minBitRate = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].levelPreference[video_level].minBitRate); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s transmitPreference: %d\n", DEV_ID_LOG(d), "", "", transmitPreference); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s format: %d: %s\n", DEV_ID_LOG(d), "", "", video_format, videoformat2str(video_format)); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s maxBitRate: %d\n", DEV_ID_LOG(d), "", "", maxBitRate); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s minBitRate: %d\n", DEV_ID_LOG(d), "", "", minBitRate); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s %s\n", DEV_ID_LOG(d), "", "", "--"); } if (d->capabilities.video[video_capability] == SKINNY_CODEC_H264) { int h264_level = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].codec_options.h264.level); int h264_profile = letohl(r->msg.UpdateCapabilitiesMessage.videoCaps[video_capability].codec_options.h264.profile); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s level: %d\n", DEV_ID_LOG(d), "", "", h264_level); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s profile: %d\n", DEV_ID_LOG(d), "", "", h264_profile); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s %s\n", DEV_ID_LOG(d), "", "", "--"); } uint8_t video_customPictureFormat = 0, video_customPictureFormats = 0; video_customPictureFormats = letohl(r->msg.UpdateCapabilitiesMessage.customPictureFormatCount); for (video_customPictureFormat = 0; video_customPictureFormat < video_customPictureFormats; video_customPictureFormat++) { int width = letohl(r->msg.UpdateCapabilitiesMessage.customPictureFormat[video_customPictureFormat].customPictureFormatWidth); int height = letohl(r->msg.UpdateCapabilitiesMessage.customPictureFormat[video_customPictureFormat].customPictureFormatHeight); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s customPictureFormat %d: width=%d, height=%d\n", DEV_ID_LOG(d), "", "", video_customPictureFormat, width, height); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP:%6s %-5s %s\n", DEV_ID_LOG(d), "", "", "--"); } #endif } } else { sccp_softkey_setSoftkeyState(d, KEYMODE_CONNTRANS, SKINNY_LBL_VIDEO_MODE, FALSE); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: disable video mode softkey\n", DEV_ID_LOG(d)); sccp_dev_set_message(d, "Video support disabled", 5, FALSE, TRUE); } #endif } /*! * \brief Handle Keep Alive Message * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_KeepAliveMessage(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_moo_t *r1 = sccp_build_packet(KeepAliveAckMessage, 0); sccp_session_send2(s, r1); } /*! * \brief Handle Start Media Transmission Acknowledgement * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo * * \since 20090708 * \author Federico */ void sccp_handle_startmediatransmission_ack(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { struct sockaddr_in sin = { 0 }; struct sockaddr_storage ss = { 0 }; sccp_channel_t *channel = NULL; uint32_t status = 0, partyID = 0, callID = 0, callID1 = 0, passthrupartyid = 0; d->protocol->parseStartMediaTransmissionAck((const sccp_moo_t *) r, &partyID, &callID, &callID1, &status, &ss); /* converting back to sin/sin6 for now until all sockaddresses are stored/passed as sockaddr_storage */ if (ss.ss_family == AF_INET) { sin = *((struct sockaddr_in *) &ss); } else { pbx_log(LOG_ERROR, "SCCP: IPv6 not supported at this moment\n"); return; } if (partyID) passthrupartyid = partyID; if (d->skinny_type == SKINNY_DEVICETYPE_CISCO6911 && 0 == passthrupartyid) { passthrupartyid = 0xFFFFFFFF - callID1; sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: Dealing with 6911 which does not return a passthrupartyid, using callid: %u -> passthrupartyid %u\n", d->id, callID1, passthrupartyid); } if ((d->active_channel && d->active_channel->passthrupartyid == passthrupartyid) || !passthrupartyid) { channel = sccp_channel_retain(d->active_channel); } else { channel = sccp_channel_find_on_device_bypassthrupartyid(d, passthrupartyid); } if (!channel) { pbx_log(LOG_WARNING, "%s: Channel with passthrupartyid %u / callid %u / callid1 %u not found, please report this to developer\n", DEV_ID_LOG(d), partyID, callID, callID1); return; } if (status) { pbx_log(LOG_WARNING, "%s: Error while opening MediaTransmission. Ending call (status: %d)\n", DEV_ID_LOG(d), status); sccp_dump_packet((unsigned char *) &r->msg, r->header.length); if (channel->rtp.audio.writeState & SCCP_RTP_STATUS_ACTIVE) { sccp_channel_closereceivechannel(channel); } sccp_channel_endcall(channel); } else { if (channel->state != SCCP_CHANNELSTATE_DOWN) { /* update status */ channel->rtp.audio.readState &= ~SCCP_RTP_STATUS_PROGRESS; channel->rtp.audio.readState |= SCCP_RTP_STATUS_ACTIVE; /* indicate up state only if both transmit and receive is done - this should fix the 1sek delay -MC */ if ((channel->state == SCCP_CHANNELSTATE_CONNECTED) && (channel->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE) && (channel->rtp.audio.writeState & SCCP_RTP_STATUS_ACTIVE) ) { PBX(set_callstate) (channel, AST_STATE_UP); } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Got StartMediaTranmission ACK. Status: %d, Remote TCP/IP: '%s:%d', CallId %u (%u), PassThruId: %u\n", DEV_ID_LOG(d), status, pbx_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), callID, callID1, partyID); } else { pbx_log(LOG_WARNING, "%s: (sccp_handle_startmediatransmission_ack) Channel already down (%d). Hanging up\n", DEV_ID_LOG(d), channel->state); if (channel->rtp.audio.writeState & SCCP_RTP_STATUS_ACTIVE) { sccp_channel_closereceivechannel(channel); } sccp_channel_endcall(channel); } } channel = sccp_channel_release(channel); } /*! * \brief Handle Device to User Message * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_device_to_user(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { uint32_t appID; uint32_t callReference; uint32_t transactionID; uint32_t dataLength; char data[StationMaxXMLMessage]; #ifdef CS_SCCP_CONFERENCE uint32_t lineInstance; uint32_t conferenceID; uint32_t participantID; #endif appID = letohl(r->msg.DeviceToUserDataVersion1Message.lel_appID); #ifdef CS_SCCP_CONFERENCE lineInstance = letohl(r->msg.DeviceToUserDataVersion1Message.lel_lineInstance); #endif callReference = letohl(r->msg.DeviceToUserDataVersion1Message.lel_callReference); transactionID = letohl(r->msg.DeviceToUserDataVersion1Message.lel_transactionID); dataLength = letohl(r->msg.DeviceToUserDataVersion1Message.lel_dataLength); if (dataLength) { memset(data, 0, dataLength); memcpy(data, r->msg.DeviceToUserDataVersion1Message.data, dataLength); } sccp_log((DEBUGCAT_ACTION | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Handle DTU for %d '%s'\n", d->id, appID, data); if (0 != appID && 0 != callReference && 0 != transactionID) { switch (appID) { case APPID_CONFERENCE: // Handle Conference App #ifdef CS_SCCP_CONFERENCE conferenceID = lineInstance; // conferenceId is passed on via lineInstance participantID = atoi(data); // participantId is passed on in the data segment sccp_log((DEBUGCAT_ACTION | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Handle ConferenceList Info for AppID %d , CallID %d, Transaction %d, Conference %d, Participant: %d\n", d->id, appID, callReference, transactionID, conferenceID, participantID); sccp_conference_handle_device_to_user(d, callReference, transactionID, conferenceID, participantID); #endif break; case APPID_CONFERENCE_INVITE: // Handle Conference Invite #ifdef CS_SCCP_CONFERENCE conferenceID = lineInstance; // conferenceId is passed on via lineInstance participantID = atoi(data); // participantId is passed on in the data segment //phonenumber = atoi(data); sccp_log((DEBUGCAT_ACTION | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Handle ConferenceList Info for AppID %d , CallID %d, Transaction %d, Conference %d, Participant: %d\n", d->id, appID, callReference, transactionID, conferenceID, participantID); //sccp_conference_handle_device_to_user(d, callReference, transactionID, conferenceID, participantID); #endif break; case APPID_PROVISION: break; } } else { // It has data -> must be a softkey if (dataLength) { /* split data by "/" */ char str_action[10] = "", str_transactionID[10] = ""; if (sscanf(data, "%[^/]/%s", str_action, str_transactionID) > 0) { sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_MESSAGE | DEBUGCAT_ACTION)) (VERBOSE_PREFIX_3 "%s: Handle DTU Softkey Button:%s, %s\n", d->id, str_action, str_transactionID); d->dtu_softkey.action = strdup(str_action); d->dtu_softkey.transactionID = atoi(str_transactionID); } else { pbx_log(LOG_NOTICE, "%s: Failure parsing DTU Softkey Button: %s\n", d->id, data); } } } } /*! * \brief Handle Device to User Message * \param s SCCP Session * \param d SCCP Device * \param r SCCP Moo */ void sccp_handle_device_to_user_response(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { uint32_t appID; uint32_t lineInstance; uint32_t callReference; uint32_t transactionID; uint32_t dataLength; char data[StationMaxXMLMessage]; appID = letohl(r->msg.DeviceToUserDataVersion1Message.lel_appID); lineInstance = letohl(r->msg.DeviceToUserDataVersion1Message.lel_lineInstance); callReference = letohl(r->msg.DeviceToUserDataVersion1Message.lel_callReference); transactionID = letohl(r->msg.DeviceToUserDataVersion1Message.lel_transactionID); dataLength = letohl(r->msg.DeviceToUserDataVersion1Message.lel_dataLength); if (dataLength) { memset(data, 0, dataLength); memcpy(data, r->msg.DeviceToUserDataVersion1Message.data, dataLength); } sccp_log((DEBUGCAT_ACTION | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: DTU Response: AppID %d , LineInstance %d, CallID %d, Transaction %d\n", d->id, appID, lineInstance, callReference, transactionID); sccp_log((DEBUGCAT_MESSAGE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: DTU Response: Data %s\n", d->id, data); if (appID == APPID_DEVICECAPABILITIES) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Device Capabilities Response '%s'\n", d->id, data); } } /*! * \brief Handle Start Multi Media Transmission Acknowledgement * \param s SCCP Session as sccp_session_t * \param d SCCP Device as sccp_device_t * \param r SCCP Message as sccp_moo_t */ void sccp_handle_startmultimediatransmission_ack(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { struct sockaddr_in sin = { 0 }; struct sockaddr_storage ss = { 0 }; sccp_channel_t *c; uint32_t status = 0, partyID = 0, callID = 0, callID1 = 0; // sccp_dump_packet((unsigned char *)&r->msg.RegisterMessage, r->header.length); d->protocol->parseStartMultiMediaTransmissionAck((const sccp_moo_t *) r, &partyID, &callID, &callID1, &status, &ss); /* converting back to sin/sin6 for now until all sockaddresses are stored/passed as sockaddr_storage */ if (ss.ss_family == AF_INET) { sin = *((struct sockaddr_in *) &ss); } else { pbx_log(LOG_ERROR, "SCCP: IPv6 not supported at this moment\n"); return; } c = sccp_channel_find_bypassthrupartyid(partyID); if (!c) { pbx_log(LOG_WARNING, "%s: Channel with passthrupartyid %u not found, please report this to developer\n", DEV_ID_LOG(d), partyID); return; } if (status) { pbx_log(LOG_WARNING, "%s: Error while opening MediaTransmission. Ending call\n", DEV_ID_LOG(d)); sccp_channel_endcall(c); c = sccp_channel_release(c); return; } /* update status */ c->rtp.video.readState &= ~SCCP_RTP_STATUS_PROGRESS; c->rtp.video.readState |= SCCP_RTP_STATUS_ACTIVE; sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: Got StartMultiMediaTranmission ACK. Status: %d, Remote TCP/IP '%s:%d', CallId %u (%u), PassThruId: %u\n", DEV_ID_LOG(d), status, pbx_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), callID, callID1, partyID); c = sccp_channel_release(c); } /*! * \brief Handle Start Multi Media Transmission Acknowledgement * \param s SCCP Session as sccp_session_t * \param d SCCP Device as sccp_device_t * \param r SCCP Message as sccp_moo_t */ void sccp_handle_mediatransmissionfailure(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_dump_packet((unsigned char *) &r->msg.RegisterMessage, r->header.length); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: Received a MediaTranmissionFailure (not being handled fully at this moment)\n", DEV_ID_LOG(d)); } /*! * \brief Handle Miscellaneous Command Message * \param s SCCP Session as sccp_session_t * \param d SCCP Device as sccp_device_t * \param r SCCP Message as sccp_moo_t */ void sccp_handle_miscellaneousCommandMessage(sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r) { sccp_miscCommandType_t commandType; struct sockaddr_in sin = { 0 }; uint32_t partyID; sccp_channel_t *channel; partyID = letohl(r->msg.MiscellaneousCommandMessage.lel_passThruPartyId); commandType = letohl(r->msg.MiscellaneousCommandMessage.lel_miscCommandType); channel = sccp_channel_find_bypassthrupartyid(partyID); switch (commandType) { case SKINNY_MISCCOMMANDTYPE_VIDEOFREEZEPICTURE: break; case SKINNY_MISCCOMMANDTYPE_VIDEOFASTUPDATEPICTURE: memcpy(&sin.sin_addr, &r->msg.MiscellaneousCommandMessage.data.videoFastUpdatePicture.bel_remoteIpAddr, sizeof(sin.sin_addr)); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: media statistic for %s, value1: %u, value2: %u, value3: %u, value4: %u\n", channel ? channel->currentDeviceId : "--", pbx_inet_ntoa(sin.sin_addr), letohl(r->msg.MiscellaneousCommandMessage.data.videoFastUpdatePicture.lel_value1), letohl(r->msg.MiscellaneousCommandMessage.data.videoFastUpdatePicture.lel_value2), letohl(r->msg.MiscellaneousCommandMessage.data.videoFastUpdatePicture.lel_value3), letohl(r->msg.MiscellaneousCommandMessage.data.videoFastUpdatePicture.lel_value4) ); break; // case SKINNY_MISCCOMMANDTYPE_VIDEOFASTUPDATEGOB: // case SKINNY_MISCCOMMANDTYPE_VIDEOFASTUPDATEMB: // case SKINNY_MISCCOMMANDTYPE_LOSTPICTURE: // case SKINNY_MISCCOMMANDTYPE_LOSTPARTIALPICTURE: // case SKINNY_MISCCOMMANDTYPE_RECOVERYREFERENCEPICTURE: // case SKINNY_MISCCOMMANDTYPE_TEMPORALSPATIALTRADEOFF: default: break; } channel = channel ? sccp_channel_release(channel) : NULL; } // kate: indent-width 4; replace-tabs off; indent-mode cstyle; auto-insert-doxygen on; line-numbers on; tab-indents on; keep-extra-spaces off; auto-brackets on;
722,246
./chan-sccp-b/src/sccp_featureButton.c
/*! * \file sccp_featureButton.c * \brief SCCP FeatureButton Class * \author Marcello Ceschia <marcello [at] ceschia.de> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \since 2009-06-15 * * $Date$ * $Revision$ */ /*! * \remarks Purpose: SCCP FeatureButton * When to use: Only methods directly related to the phone featureButtons should be stored in this source file. * FeatureButtons are the ones at the bottom of the display, not to be confused with speeddial * buttons on the right side of the display. * Relationships: Call SCCP Features * */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /*! * \brief Feature Button Changed * * fetch the new state, and send status to device * * \param device SCCP Device * \param featureType SCCP Feature Type * * \warning * - device->buttonconfig is not always locked * * \lock * - device->buttonconfig * - see sccp_line_find_byname() * - see sccp_linedevice_find() * - see sccp_dev_send() */ void sccp_featButton_changed(sccp_device_t * device, sccp_feature_type_t featureType) { sccp_moo_t *featureMessage = NULL; sccp_buttonconfig_t *config = NULL, *buttonconfig = NULL; sccp_linedevices_t *linedevice = NULL; sccp_line_t *line; uint8_t instance = 0; uint8_t buttonID = SKINNY_BUTTONTYPE_FEATURE; // Default feature type. boolean_t lineFound = FALSE; #ifdef CS_DEVSTATE_FEATURE char buf[254] = ""; #endif if (!device) { return; } SCCP_LIST_LOCK(&device->buttonconfig); SCCP_LIST_TRAVERSE(&device->buttonconfig, config, list) { if (config->type == FEATURE && config->button.feature.id == featureType) { sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: FeatureID = %d, Option: %s\n", DEV_ID_LOG(device), config->button.feature.id, (config->button.feature.options) ? config->button.feature.options : "(none)"); instance = config->instance; switch (config->button.feature.id) { case SCCP_FEATURE_PRIVACY: if (!device->privacyFeature.enabled) { config->button.feature.status = 0; } sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: device->privacyFeature.status=%d\n", DEV_ID_LOG(device), device->privacyFeature.status); if (!strcasecmp(config->button.feature.options, "callpresent")) { uint32_t result = device->privacyFeature.status & SCCP_PRIVACYFEATURE_CALLPRESENT; sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: result is %d\n", device->id, result); config->button.feature.status = (result) ? 1 : 0; } if (!strcasecmp(config->button.feature.options, "hint")) { uint32_t result = device->privacyFeature.status & SCCP_PRIVACYFEATURE_HINT; sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: result is %d\n", device->id, result); config->button.feature.status = (result) ? 1 : 0; } break; case SCCP_FEATURE_CFWDALL: // This needs to default to FALSE so that the cfwd feature // is not being enabled unless we can ask the lines for their state. config->button.feature.status = 0; /* get current state */ SCCP_LIST_TRAVERSE(&device->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) { // Check if line and line device exists and thus forward status on that device can be checked if ((line = sccp_line_find_byname(buttonconfig->button.line.name, FALSE))) { if ((linedevice = sccp_linedevice_find(device, line))) { sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: SCCP_CFWD_ALL on line: %s is %s\n", DEV_ID_LOG(device), line->name, (linedevice->cfwdAll.enabled) ? "on" : "off"); /* set this button active, only if all lines are fwd -requesting issue #3081549 */ // Upon finding the first existing line, we need to set the feature status // to TRUE and subsequently AND that value with the forward status of each line. if (FALSE == lineFound) { lineFound = TRUE; config->button.feature.status = 1; } // Set status of feature by logical and to comply with requirement above. config->button.feature.status &= ((linedevice->cfwdAll.enabled) ? 1 : 0); // Logical and &= intended here. linedevice = sccp_linedevice_release(linedevice); } line = sccp_line_release(line); } } } buttonconfig = NULL; break; case SCCP_FEATURE_DND: if (!strcasecmp(config->button.feature.options, "silent")) { if ((device->dndFeature.enabled && device->dndFeature.status == SCCP_DNDMODE_SILENT)) { config->button.feature.status = 1; } else { config->button.feature.status = 0; } } else if (!strcasecmp(config->button.feature.options, "busy")) { if ((device->dndFeature.enabled && device->dndFeature.status == SCCP_DNDMODE_REJECT)) { config->button.feature.status = 1; } else { config->button.feature.status = 0; } } break; case SCCP_FEATURE_MONITOR: sccp_log((DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "%s: monitor feature state: %d\n", DEV_ID_LOG(device), device->monitorFeature.status); buttonID = SKINNY_BUTTONTYPE_MULTIBLINKFEATURE; switch (device->monitorFeature.status) { case SCCP_FEATURE_MONITOR_STATE_DISABLED: config->button.feature.status = 0; break; case SCCP_FEATURE_MONITOR_STATE_REQUESTED: config->button.feature.status = 131586; break; case SCCP_FEATURE_MONITOR_STATE_ACTIVE: config->button.feature.status = 131843; break; case (SCCP_FEATURE_MONITOR_STATE_REQUESTED | SCCP_FEATURE_MONITOR_STATE_ACTIVE): config->button.feature.status = 131589; break; } break; #ifdef CS_DEVSTATE_FEATURE /** Handling of custom devicestate toggle button feature */ case SCCP_FEATURE_DEVSTATE: /* we check which devicestate this button is assigned to, and fetch the respective status from the astdb. Note that this relies on the functionality of the asterisk custom devicestate module. */ if (PBX(feature_getFromDatabase) (devstate_db_family, config->button.feature.options, buf, sizeof(buf))) { sccp_log((DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "%s: devstate feature state: %s state: %s\n", DEV_ID_LOG(device), config->button.feature.options, buf); if (!strncmp("INUSE", buf, 254)) { config->button.feature.status = 1; } else { config->button.feature.status = 0; } } break; #endif case SCCP_FEATURE_HOLD: buttonID = SKINNY_BUTTONTYPE_HOLD; break; case SCCP_FEATURE_TRANSFER: buttonID = SKINNY_BUTTONTYPE_TRANSFER; break; case SCCP_FEATURE_MULTIBLINK: buttonID = SKINNY_BUTTONTYPE_MULTIBLINKFEATURE; config->button.feature.status = device->priFeature.status; break; case SCCP_FEATURE_MOBILITY: buttonID = SKINNY_BUTTONTYPE_MOBILITY; config->button.feature.status = device->mobFeature.status; break; case SCCP_FEATURE_CONFERENCE: buttonID = SKINNY_BUTTONTYPE_CONFERENCE; break; case SCCP_FEATURE_TEST6: buttonID = SKINNY_BUTTONTYPE_TEST6; break; case SCCP_FEATURE_TEST7: buttonID = SKINNY_BUTTONTYPE_TEST7; break; case SCCP_FEATURE_TEST8: buttonID = SKINNY_BUTTONTYPE_TEST8; break; case SCCP_FEATURE_TEST9: buttonID = SKINNY_BUTTONTYPE_TEST9; break; case SCCP_FEATURE_TESTA: buttonID = SKINNY_BUTTONTYPE_TESTA; break; case SCCP_FEATURE_TESTB: buttonID = SKINNY_BUTTONTYPE_TESTB; break; case SCCP_FEATURE_TESTC: buttonID = SKINNY_BUTTONTYPE_TESTC; break; case SCCP_FEATURE_TESTD: buttonID = SKINNY_BUTTONTYPE_TESTD; break; case SCCP_FEATURE_TESTE: buttonID = SKINNY_BUTTONTYPE_TESTE; break; case SCCP_FEATURE_TESTF: buttonID = SKINNY_BUTTONTYPE_TESTF; break; case SCCP_FEATURE_TESTG: buttonID = SKINNY_BUTTONTYPE_MESSAGES; break; case SCCP_FEATURE_TESTH: buttonID = SKINNY_BUTTONTYPE_DIRECTORY; break; case SCCP_FEATURE_TESTI: buttonID = SKINNY_BUTTONTYPE_TESTI; break; case SCCP_FEATURE_TESTJ: buttonID = SKINNY_BUTTONTYPE_APPLICATION; break; case SCCP_FEATURE_PICKUP: buttonID = SKINNY_STIMULUS_GROUPCALLPICKUP; break; default: break; } /* send status using new message */ if (device->inuseprotocolversion >= 15) { REQ(featureMessage, FeatureStatDynamicMessage); featureMessage->msg.FeatureStatDynamicMessage.lel_instance = htolel(instance); featureMessage->msg.FeatureStatDynamicMessage.lel_type = htolel(buttonID); featureMessage->msg.FeatureStatDynamicMessage.lel_status = htolel(config->button.feature.status); sccp_copy_string(featureMessage->msg.FeatureStatDynamicMessage.DisplayName, config->label, strlen(config->label) + 1); } else { REQ(featureMessage, FeatureStatMessage); featureMessage->msg.FeatureStatMessage.lel_featureInstance = htolel(instance); featureMessage->msg.FeatureStatMessage.lel_featureID = htolel(buttonID); featureMessage->msg.FeatureStatMessage.lel_featureStatus = htolel(config->button.feature.status); sccp_copy_string(featureMessage->msg.FeatureStatMessage.featureTextLabel, config->label, strlen(config->label) + 1); } sccp_dev_send(device, featureMessage); sccp_log((DEBUGCAT_FEATURE_BUTTON | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: (sccp_featButton_changed) Got Feature Status Request. Instance = %d Label: %s Status: %d Nota bene: Config pointer: %p\n", DEV_ID_LOG(device), instance, config->label, config->button.feature.status, config); } } SCCP_LIST_UNLOCK(&device->buttonconfig); } /*! * \brief Device State Feature CallBack * * Called when we want to return a state change of a device */ #if defined(CS_DEVSTATE_FEATURE) && defined(CS_AST_HAS_EVENT) void sccp_devstateFeatureState_cb(const struct ast_event *ast_event, void *data) { /* parse the devstate string */ /* If it is the custom family, isolate the specifier. */ sccp_device_t *device; size_t len = strlen("Custom:"); // char *sspecifier = 0; const char *dev; if (!data || !ast_event) return; dev = pbx_event_get_ie_str(ast_event, AST_EVENT_IE_DEVICE); sccp_log((DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "got device state change event from asterisk channel: %s\n", (dev) ? dev : "NULL"); device = (sccp_device_t *) data; if (!device) { sccp_log((DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "NULL device in devstate event callback.\n"); return; } if (!dev) { sccp_log((DEBUGCAT_FEATURE_BUTTON)) (VERBOSE_PREFIX_3 "NULL devstate string in devstate event callback.\n"); return; } /* Note that we update all devstate feature buttons if we receive an event for one of them, which we registered for. This will lead to unneccesary updates with multiple buttons. In the future we might need a more elegant hint-registry for this type of notification, which should be global to chan-sccp-b, not for each device. For now, this suffices. */ if (!strncasecmp(dev, "Custom:", len)) { // sspecifier = (char *)(dev + len); sccp_featButton_changed(device, SCCP_FEATURE_DEVSTATE); } } #endif
722,247
./chan-sccp-b/src/chan_sccp.c
/*! * \file chan_sccp.c * \brief An implementation of Skinny Client Control Protocol (SCCP) * \author Sergio Chersovani <mlists [at] c-net.it> * \brief Main chan_sccp Class * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \remarks Purpose: This source file should be used only for asterisk module related content. * When to use: Methods communicating to asterisk about module initialization, status, destruction * Relationships: Main hub for all other sourcefiles. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" #include <signal.h> SCCP_FILE_VERSION(__FILE__, "$Revision$") #define GENERATE_ENUM_STRINGS #include "sccp_enum_macro.h" #include "chan_sccp_enums.hh" #undef GENERATE_ENUM_STRINGS /*! * \brief Buffer for Jitterbuffer use */ #if defined(__cplusplus) || defined(c_plusplus) static ast_jb_conf default_jbconf = { flags: 0, max_size:-1, resync_threshold:-1, impl: "", #ifdef CS_AST_JB_TARGET_EXTRA target_extra:-1, #endif }; #else static struct ast_jb_conf default_jbconf = { .flags = 0, .max_size = -1, .resync_threshold = -1, .impl = "", #ifdef CS_AST_JB_TARGET_EXTRA .target_extra = -1, #endif }; #endif /*! * \brief Global null frame */ PBX_FRAME_TYPE sccp_null_frame; /*!< Asterisk Structure */ /*! * \brief Global variables */ struct sccp_global_vars *sccp_globals = 0; /*! * \brief SCCP Request Channel * \param lineName Line Name as Char * \param requestedCodec Requested Skinny Codec * \param capabilities Array of Skinny Codec Capabilities * \param capabilityLength Length of Capabilities Array * \param autoanswer_type SCCP Auto Answer Type * \param autoanswer_cause SCCP Auto Answer Cause * \param ringermode Ringer Mode * \param channel SCCP Channel * \return SCCP Channel Request Status * * \called_from_asterisk */ sccp_channel_request_status_t sccp_requestChannel(const char *lineName, skinny_codec_t requestedCodec, skinny_codec_t capabilities[], uint8_t capabilityLength, sccp_autoanswer_t autoanswer_type, uint8_t autoanswer_cause, int ringermode, sccp_channel_t ** channel) { struct composedId lineSubscriptionId; sccp_channel_t *my_sccp_channel = NULL; sccp_line_t *l = NULL; memset(&lineSubscriptionId, 0, sizeof(struct composedId)); if (!lineName) { return SCCP_REQUEST_STATUS_ERROR; } lineSubscriptionId = sccp_parseComposedId(lineName, 80); l = sccp_line_find_byname(lineSubscriptionId.mainId, FALSE); if (!l) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "SCCP/%s does not exist!\n", lineSubscriptionId.mainId); return SCCP_REQUEST_STATUS_LINEUNKNOWN; } sccp_log((DEBUGCAT_SCCP + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_1 "[SCCP] in file %s, line %d (%s)\n", __FILE__, __LINE__, __PRETTY_FUNCTION__); if (l->devices.size == 0) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "SCCP/%s isn't currently registered anywhere.\n", l->name); l = sccp_line_release(l); return SCCP_REQUEST_STATUS_LINEUNAVAIL; } sccp_log((DEBUGCAT_SCCP + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_1 "[SCCP] in file %s, line %d (%s)\n", __FILE__, __LINE__, __PRETTY_FUNCTION__); /* call forward check */ // Allocate a new SCCP channel. /* on multiline phone we set the line when answering or switching lines */ *channel = my_sccp_channel = sccp_channel_allocate(l, NULL); if (!my_sccp_channel) { l = sccp_line_release(l); return SCCP_REQUEST_STATUS_ERROR; } /* set subscriberId for individual device addressing */ if (!sccp_strlen_zero(lineSubscriptionId.subscriptionId.number)) { sccp_copy_string(my_sccp_channel->subscriptionId.number, lineSubscriptionId.subscriptionId.number, sizeof(my_sccp_channel->subscriptionId.number)); if (!sccp_strlen_zero(lineSubscriptionId.subscriptionId.name)) { sccp_copy_string(my_sccp_channel->subscriptionId.name, lineSubscriptionId.subscriptionId.name, sizeof(my_sccp_channel->subscriptionId.name)); } else { //pbx_log(LOG_NOTICE, "%s: calling subscriber id=%s\n", l->id, my_sccp_channel->subscriptionId.number); } } else { sccp_copy_string(my_sccp_channel->subscriptionId.number, l->defaultSubscriptionId.number, sizeof(my_sccp_channel->subscriptionId.number)); sccp_copy_string(my_sccp_channel->subscriptionId.name, l->defaultSubscriptionId.name, sizeof(my_sccp_channel->subscriptionId.name)); //pbx_log(LOG_NOTICE, "%s: calling all subscribers\n", l->id); } uint8_t size = (capabilityLength < sizeof(my_sccp_channel->remoteCapabilities.audio)) ? capabilityLength : sizeof(my_sccp_channel->remoteCapabilities.audio); memset(&my_sccp_channel->remoteCapabilities.audio, 0, sizeof(my_sccp_channel->remoteCapabilities.audio)); memcpy(&my_sccp_channel->remoteCapabilities.audio, capabilities, size); /** set requested codec as prefered codec */ sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "prefered audio codec (%d)\n", requestedCodec); if (requestedCodec != SKINNY_CODEC_NONE) { my_sccp_channel->preferences.audio[0] = requestedCodec; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "SCCP: prefered audio codec (%d)\n", my_sccp_channel->preferences.audio[0]); } /** done */ my_sccp_channel->autoanswer_type = autoanswer_type; my_sccp_channel->autoanswer_cause = autoanswer_cause; my_sccp_channel->ringermode = ringermode; l = sccp_line_release(l); return SCCP_REQUEST_STATUS_SUCCESS; } /*! * \brief Local Function to check for Valid Session, Message and Device * \param s SCCP Session * \param r SCCP Moo * \param msg Message * \param deviceIsNecessary Is a valid device necessary for this message to be processed, if it is, the device is retain during execution of this particular message parser * \return -1 or Device; */ inline static sccp_device_t *check_session_message_device(sccp_session_t * s, sccp_moo_t * r, const char *msg, boolean_t deviceIsNecessary) { sccp_device_t *d = NULL; if (!GLOB(module_running)) { pbx_log(LOG_ERROR, "Chan-sccp-b module is not up and running at this moment\n"); goto EXIT; } if (!s || (s->fds[0].fd < 0)) { pbx_log(LOG_ERROR, "(%s) Session no longer valid\n", msg); goto EXIT; } if (!r) { pbx_log(LOG_ERROR, "(%s) No Message Provided\n", msg); goto EXIT; } if (deviceIsNecessary && !s->device) { pbx_log(LOG_WARNING, "No valid Session Device available to handle %s for, but device is needed\n", msg); goto EXIT; } if (deviceIsNecessary && !(d = sccp_device_retain(s->device))) { pbx_log(LOG_WARNING, "Session Device vould not be retained, to handle %s for, but device is needed\n", msg); goto EXIT; } if (deviceIsNecessary && d && d->session && s != d->session) { pbx_log(LOG_WARNING, "(%s) Provided Session and Device Session are not the same. Rejecting message handling\n", msg); s = sccp_session_crossdevice_cleanup(s, d, "No Crossover Allowed -> Reset"); d = d ? sccp_device_release(d) : NULL; goto EXIT; } EXIT: if (r && (GLOB(debug) & (DEBUGCAT_MESSAGE | DEBUGCAT_ACTION)) != 0) { uint32_t mid = letohl(r->header.lel_messageId); pbx_log(LOG_NOTICE, "%s: SCCP Handle Message: %s(0x%04X) %d bytes length\n", DEV_ID_LOG(d), mid ? message2str(mid) : NULL, mid ? mid : 0, r ? r->header.length : 0); sccp_dump_packet((unsigned char *) &r->msg, r->header.length); } return d; } /*! * \brief SCCP Message Handler Callback * * Used to map SKinny Message Id's to their Handling Implementations */ struct sccp_messageMap_cb { void (*const messageHandler_cb) (sccp_session_t * s, sccp_device_t * d, sccp_moo_t * r); boolean_t deviceIsNecessary; }; typedef struct sccp_messageMap_cb sccp_messageMap_cb_t; static const struct sccp_messageMap_cb messagesCbMap[] = { [KeepAliveMessage] = {sccp_handle_KeepAliveMessage, FALSE}, // on 7985,6911 phones and tokenmsg, a KeepAliveMessage is send before register/token [OffHookMessage] = {sccp_handle_offhook, TRUE}, [OnHookMessage] = {sccp_handle_onhook, TRUE}, [SoftKeyEventMessage] = {sccp_handle_soft_key_event, TRUE}, [OpenReceiveChannelAck] = {sccp_handle_open_receive_channel_ack, TRUE}, [OpenMultiMediaReceiveChannelAckMessage] = {sccp_handle_OpenMultiMediaReceiveAck, TRUE}, [StartMediaTransmissionAck] = {sccp_handle_startmediatransmission_ack, TRUE}, [IpPortMessage] = {NULL, TRUE}, [VersionReqMessage] = {sccp_handle_version, TRUE}, [CapabilitiesResMessage] = {sccp_handle_capabilities_res, TRUE}, [ButtonTemplateReqMessage] = {sccp_handle_button_template_req, TRUE}, [SoftKeyTemplateReqMessage] = {sccp_handle_soft_key_template_req, TRUE}, [SoftKeySetReqMessage] = {sccp_handle_soft_key_set_req, TRUE}, [LineStatReqMessage] = {sccp_handle_line_number, TRUE}, [SpeedDialStatReqMessage] = {sccp_handle_speed_dial_stat_req, TRUE}, [StimulusMessage] = {sccp_handle_stimulus, TRUE}, [HeadsetStatusMessage] = {sccp_handle_headset, TRUE}, [TimeDateReqMessage] = {sccp_handle_time_date_req, TRUE}, [KeypadButtonMessage] = {sccp_handle_keypad_button, TRUE}, [ConnectionStatisticsRes] = {sccp_handle_ConnectionStatistics, TRUE}, [ServerReqMessage] = {sccp_handle_ServerResMessage, TRUE}, [ConfigStatReqMessage] = {sccp_handle_ConfigStatMessage, TRUE}, [EnblocCallMessage] = {sccp_handle_EnblocCallMessage, TRUE}, [RegisterAvailableLinesMessage] = {sccp_handle_AvailableLines, TRUE}, [ForwardStatReqMessage] = {sccp_handle_forward_stat_req, TRUE}, [FeatureStatReqMessage] = {sccp_handle_feature_stat_req, TRUE}, [ServiceURLStatReqMessage] = {sccp_handle_services_stat_req, TRUE}, [AccessoryStatusMessage] = {sccp_handle_accessorystatus_message, TRUE}, [DialedPhoneBookMessage] = {sccp_handle_dialedphonebook_message, TRUE}, [UpdateCapabilitiesMessage] = {sccp_handle_updatecapabilities_message, TRUE}, [Unknown_0x004A_Message] = {sccp_handle_unknown_message, TRUE}, [DisplayDynamicNotifyMessage] = {sccp_handle_unknown_message, TRUE}, [DisplayDynamicPriNotifyMessage] = {sccp_handle_unknown_message, TRUE}, [SpeedDialStatDynamicMessage] = {sccp_handle_speed_dial_stat_req, TRUE}, [ExtensionDeviceCaps] = {sccp_handle_unknown_message, TRUE}, [DeviceToUserDataVersion1Message] = {sccp_handle_device_to_user, TRUE}, [DeviceToUserDataResponseVersion1Message] = {sccp_handle_device_to_user_response, TRUE}, [RegisterTokenRequest] = {sccp_handle_token_request, FALSE}, [UnregisterMessage] = {sccp_handle_unregister, FALSE}, [RegisterMessage] = {sccp_handle_register, FALSE}, [AlarmMessage] = {sccp_handle_alarm, FALSE}, [XMLAlarmMessage] = {sccp_handle_XMLAlarmMessage, FALSE}, [SPCPRegisterTokenRequest] = {sccp_handle_SPCPTokenReq, FALSE}, [StartMultiMediaTransmissionAck] = {sccp_handle_startmultimediatransmission_ack, TRUE}, [MediaTransmissionFailure] = {sccp_handle_mediatransmissionfailure, TRUE}, [MiscellaneousCommandMessage] = {sccp_handle_miscellaneousCommandMessage, TRUE}, }; /*! * \brief Controller function to handle Received Messages * \param r Message as sccp_moo_t * \param s Session as sccp_session_t */ uint8_t sccp_handle_message(sccp_moo_t * r, sccp_session_t * s) { const sccp_messageMap_cb_t *messageMap_cb = NULL; uint32_t mid = 0; sccp_device_t *device = NULL; if (!s) { pbx_log(LOG_ERROR, "SCCP: (sccp_handle_message) Client does not have a session which is required. Exiting sccp_handle_message !\n"); if (r) { sccp_free(r); } return -1; } if (!r) { pbx_log(LOG_ERROR, "%s: (sccp_handle_message) No Message Specified.\n which is required, Exiting sccp_handle_message !\n", DEV_ID_LOG(s->device)); return -1; } mid = letohl(r->header.lel_messageId); /* search for message handler */ messageMap_cb = &messagesCbMap[mid]; sccp_log((DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: >> Got message %s (%x)\n", DEV_ID_LOG(s->device), message2str(mid), mid); /* we dont know how to handle event */ if (!messageMap_cb) { pbx_log(LOG_WARNING, "SCCP: Unknown Message %x. Don't know how to handle it. Skipping.\n", mid); sccp_handle_unknown_message(s, device, r); return 1; } device = check_session_message_device(s, r, message2str(mid), messageMap_cb->deviceIsNecessary); /* retained device returned */ if (messageMap_cb->messageHandler_cb && messageMap_cb->deviceIsNecessary == TRUE && !device) { pbx_log(LOG_ERROR, "SCCP: Device is required to handle this message %s(%x), but none is provided. Exiting sccp_handle_message\n", message2str(mid), mid); return 0; } if (messageMap_cb->messageHandler_cb) { messageMap_cb->messageHandler_cb(s, device, r); } s->lastKeepAlive = time(0); device = device ? sccp_device_release(device) : NULL; return 1; } /** * \brief load the configuration from sccp.conf * \todo should be pbx independent */ int load_config(void) { int oldport = ntohs(GLOB(bindaddr.sin_port)); int on = 1; /* Copy the default jb config over global_jbconf */ memcpy(&GLOB(global_jbconf), &default_jbconf, sizeof(struct ast_jb_conf)); /* Setup the monitor thread default */ #if ASTERISK_VERSION_GROUP < 110 GLOB(monitor_thread) = AST_PTHREADT_NULL; // ADDED IN SVN 414 -FS #endif GLOB(mwiMonitorThread) = AST_PTHREADT_NULL; memset(&GLOB(bindaddr), 0, sizeof(GLOB(bindaddr))); GLOB(allowAnonymous) = TRUE; #ifdef CS_SCCP_REALTIME sccp_copy_string(GLOB(realtimedevicetable), "sccpdevice", sizeof(GLOB(realtimedevicetable))); sccp_copy_string(GLOB(realtimelinetable), "sccpline", sizeof(GLOB(realtimelinetable))); #endif #if SCCP_PLATFORM_BYTE_ORDER == SCCP_LITTLE_ENDIAN sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Platform byte order : LITTLE ENDIAN\n"); #else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "Platform byte order : BIG ENDIAN\n"); #endif if (sccp_config_getConfig(TRUE) > CONFIG_STATUS_FILE_OK) { pbx_log(LOG_ERROR, "Error loading configfile !"); return FALSE; } if (!sccp_config_general(SCCP_CONFIG_READINITIAL)) { pbx_log(LOG_ERROR, "Error parsing configfile !"); return 0; } sccp_config_readDevicesLines(SCCP_CONFIG_READINITIAL); /* ok the config parse is done */ if ((GLOB(descriptor) > -1) && (ntohs(GLOB(bindaddr.sin_port)) != oldport)) { close(GLOB(descriptor)); GLOB(descriptor) = -1; } if (GLOB(descriptor) < 0) { #ifdef CS_EXPERIMENTAL_NEWIP int status; struct addrinfo hints, *res; char port_str[5] = ""; memset(&hints, 0, sizeof hints); // make sure the struct is empty hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets if (&GLOB(bindaddr.sin_addr) != NULL) { snprintf(port_str, sizeof(port_str), "%d", ntohs(GLOB(bindaddr.sin_port))); if ((status = getaddrinfo(pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), port_str, &hints, &res)) != 0) { pbx_log(LOG_WARNING, "Failed to get addressinfo for %s:%d, error: %s!\n", pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), ntohs(GLOB(bindaddr.sin_port)), gai_strerror(status)); close(GLOB(descriptor)); GLOB(descriptor) = -1; return 0; } } else { hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((status = getaddrinfo(NULL, "cisco_sccp", &hints, &res)) != 0) { pbx_log(LOG_WARNING, "Failed to get addressinfo, error: %s!\n", gai_strerror(status)); close(GLOB(descriptor)); GLOB(descriptor) = -1; return 0; } } GLOB(descriptor) = socket(res->ai_family, res->ai_socktype, res->ai_protocol); // need to add code to handle multiple interfaces (multi homed server) -> multiple socket descriptors #else GLOB(descriptor) = socket(AF_INET, SOCK_STREAM, 0); //replaced #endif on = 1; if (setsockopt(GLOB(descriptor), SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) pbx_log(LOG_WARNING, "Failed to set SCCP socket to SO_REUSEADDR mode: %s\n", strerror(errno)); if (setsockopt(GLOB(descriptor), IPPROTO_IP, IP_TOS, &GLOB(sccp_tos), sizeof(GLOB(sccp_tos))) < 0) pbx_log(LOG_WARNING, "Failed to set SCCP socket TOS to %d: %s\n", GLOB(sccp_tos), strerror(errno)); else if (GLOB(sccp_tos)) sccp_log(DEBUGCAT_SOCKET) (VERBOSE_PREFIX_1 "Using SCCP Socket ToS mark %d\n", GLOB(sccp_tos)); if (setsockopt(GLOB(descriptor), IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) pbx_log(LOG_WARNING, "Failed to set SCCP socket to TCP_NODELAY: %s\n", strerror(errno)); #if defined(linux) if (setsockopt(GLOB(descriptor), SOL_SOCKET, SO_PRIORITY, &GLOB(sccp_cos), sizeof(GLOB(sccp_cos))) < 0) pbx_log(LOG_WARNING, "Failed to set SCCP socket COS to %d: %s\n", GLOB(sccp_cos), strerror(errno)); else if (GLOB(sccp_cos)) sccp_log(DEBUGCAT_SOCKET) (VERBOSE_PREFIX_1 "Using SCCP Socket CoS mark %d\n", GLOB(sccp_cos)); #endif if (GLOB(descriptor) < 0) { pbx_log(LOG_WARNING, "Unable to create SCCP socket: %s\n", strerror(errno)); } else { #ifdef CS_EXPERIMENTAL_NEWIP if (bind(GLOB(descriptor), res->ai_addr, res->ai_addrlen) < 0) { // using addrinfo hints #else if (bind(GLOB(descriptor), (struct sockaddr *) &GLOB(bindaddr), sizeof(GLOB(bindaddr))) < 0) { //replaced #endif pbx_log(LOG_WARNING, "Failed to bind to %s:%d: %s!\n", pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), ntohs(GLOB(bindaddr.sin_port)), strerror(errno)); close(GLOB(descriptor)); GLOB(descriptor) = -1; return 0; } ast_verbose(VERBOSE_PREFIX_3 "SCCP channel driver up and running on %s:%d\n", pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), ntohs(GLOB(bindaddr.sin_port))); if (listen(GLOB(descriptor), DEFAULT_SCCP_BACKLOG)) { pbx_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n", pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), ntohs(GLOB(bindaddr.sin_port)), strerror(errno)); close(GLOB(descriptor)); GLOB(descriptor) = -1; return 0; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP listening on %s:%d\n", pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), ntohs(GLOB(bindaddr.sin_port))); GLOB(reload_in_progress) = FALSE; pbx_pthread_create(&GLOB(socket_thread), NULL, sccp_socket_thread, NULL); } #ifdef CS_EXPERIMENTAL_NEWIP freeaddrinfo(res); #endif } return 0; } /*! * \brief Add Callback Functon to PBX Scheduler * \param when number of seconds from this point in time as int * \param callback CallBack Function to be called when the time has passed * \param data Extraneous Data * \return sceduled id as int */ int sccp_sched_add(int when, sccp_sched_cb callback, const void *data) { if (!PBX(sched_add)) return 1; return PBX(sched_add) (when, callback, data); } /*! * \brief Remove Callback Functon from PBX Scheduler * \param id ID of scheduled callback as int * \return success as int */ int sccp_sched_del(int id) { if (!PBX(sched_del)) return 1; return PBX(sched_del) (id); } /*! * \brief Load the actual chan_sccp module * \return Success as int */ boolean_t sccp_prePBXLoad() { pbx_log(LOG_NOTICE, "preloading pbx module\n"); #ifdef HAVE_LIBGC GC_INIT(); (void) GC_set_warn_proc(gc_warn_handler); GC_enable(); #if DEBUG > 0 GC_find_leak = 1; #endif #endif /* make globals */ sccp_globals = (struct sccp_global_vars *) sccp_malloc(sizeof(struct sccp_global_vars)); if (!sccp_globals) { pbx_log(LOG_ERROR, "No free memory for SCCP global vars. SCCP channel type disabled\n"); return FALSE; } /* Initialize memory */ memset(&sccp_null_frame, 0, sizeof(sccp_null_frame)); memset(sccp_globals, 0, sizeof(struct sccp_global_vars)); GLOB(debug) = DEBUGCAT_CORE; // sccp_event_listeners = (struct sccp_event_subscriptions *)sccp_malloc(sizeof(struct sccp_event_subscriptions)); // memset(sccp_event_listeners, 0, sizeof(struct sccp_event_subscriptions)); // SCCP_LIST_HEAD_INIT(&sccp_event_listeners->subscriber); pbx_mutex_init(&GLOB(lock)); pbx_mutex_init(&GLOB(usecnt_lock)); #if ASTERISK_VERSION_GROUP < 110 pbx_mutex_init(&GLOB(monitor_lock)); #endif /* init refcount */ sccp_refcount_init(); SCCP_RWLIST_HEAD_INIT(&GLOB(sessions)); SCCP_RWLIST_HEAD_INIT(&GLOB(devices)); SCCP_RWLIST_HEAD_INIT(&GLOB(lines)); GLOB(general_threadpool) = sccp_threadpool_init(THREADPOOL_MIN_SIZE); sccp_event_module_start(); sccp_mwi_module_start(); sccp_hint_module_start(); sccp_manager_module_start(); #ifdef CS_SCCP_CONFERENCE sccp_conference_module_start(); #endif sccp_event_subscribe(SCCP_EVENT_FEATURE_CHANGED, sccp_device_featureChangedDisplay, TRUE); sccp_event_subscribe(SCCP_EVENT_FEATURE_CHANGED, sccp_util_featureStorageBackend, TRUE); GLOB(descriptor) = -1; GLOB(bindaddr.sin_port) = DEFAULT_SCCP_PORT; GLOB(externrefresh) = 60; GLOB(keepalive) = SCCP_KEEPALIVE; sccp_copy_string(GLOB(dateformat), "D/M/YA", sizeof(GLOB(dateformat))); sccp_copy_string(GLOB(context), "default", sizeof(GLOB(context))); sccp_copy_string(GLOB(servername), "Asterisk", sizeof(GLOB(servername))); /* Wait up to 16 seconds for first digit */ GLOB(firstdigittimeout) = 16; /* How long to wait for following digits */ GLOB(digittimeout) = 8; GLOB(debug) = 1; GLOB(sccp_tos) = (0x68 & 0xff); // AF31 GLOB(audio_tos) = (0xB8 & 0xff); // EF GLOB(video_tos) = (0x88 & 0xff); // AF41 GLOB(sccp_cos) = 4; GLOB(audio_cos) = 6; GLOB(video_cos) = 5; GLOB(echocancel) = TRUE; GLOB(silencesuppression) = TRUE; GLOB(dndmode) = SCCP_DNDMODE_REJECT; GLOB(autoanswer_tone) = SKINNY_TONE_ZIP; GLOB(remotehangup_tone) = SKINNY_TONE_ZIP; GLOB(callwaiting_tone) = SKINNY_TONE_CALLWAITINGTONE; GLOB(privacy) = TRUE; /* permit private function */ GLOB(mwilamp) = SKINNY_LAMP_ON; GLOB(protocolversion) = SCCP_DRIVER_SUPPORTED_PROTOCOL_HIGH; GLOB(amaflags) = pbx_cdr_amaflags2int("documentation"); GLOB(callanswerorder) = ANSWER_OLDEST_FIRST; GLOB(socket_thread) = AST_PTHREADT_NULL; GLOB(earlyrtp) = SCCP_CHANNELSTATE_PROGRESS; sccp_create_hotline(); return TRUE; } #if DEBUG /* * Segfault Handler * Copied from Author : Andrew Tridgell <junkcode@tridgell.net> * URL : http://www.samba.org/ftp/unpacked/junkcode/segv_handler/ */ /* static int segv_handler(int sig) { char cmd[100]; char progname[100]; char *p; int n; n = readlink("/proc/self/exe", progname, sizeof(progname)); progname[n] = 0; p = strrchr(progname, '/'); *p = 0; snprintf(cmd, sizeof(cmd), "chan-sccp-b_backtrace %d > /var/log/asterisk/chan-sccp-b_%s.%d.backtrace 2>&1", (int)getpid(), p + 1, (int)getpid()); system(cmd); signal(SIGSEGV, SIG_DFL); return 0; } static void segv_init() __attribute__ ((constructor)); void segv_init(void) { signal(SIGSEGV, (sighandler_t) segv_handler); signal(SIGBUS, (sighandler_t) segv_handler); } */ #endif boolean_t sccp_postPBX_load() { pbx_mutex_lock(&GLOB(lock)); GLOB(module_running) = TRUE; #if DEBUG // segv_init(); #endif sccp_refcount_schedule_cleanup((const void *) 0); pbx_mutex_unlock(&GLOB(lock)); return TRUE; } /*! * \brief Schedule free memory * \param ptr pointer * \return Success as int */ int sccp_sched_free(void *ptr) { if (!ptr) return -1; sccp_free(ptr); return 0; } /*! * \brief PBX Independent Function to be called before unloading the module * \return Success as int */ int sccp_preUnload(void) { pbx_mutex_lock(&GLOB(lock)); GLOB(module_running) = FALSE; pbx_mutex_unlock(&GLOB(lock)); sccp_device_t *d; sccp_line_t *l; sccp_session_t *s; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: Unloading Module\n"); sccp_event_unsubscribe(SCCP_EVENT_FEATURE_CHANGED, sccp_device_featureChangedDisplay); sccp_event_unsubscribe(SCCP_EVENT_FEATURE_CHANGED, sccp_util_featureStorageBackend); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Removing Descriptor\n"); close(GLOB(descriptor)); GLOB(descriptor) = -1; //! \todo make this pbx independend sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Hangup open channels\n"); /* removing devices */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Removing Devices\n"); SCCP_RWLIST_WRLOCK(&GLOB(devices)); while ((d = SCCP_LIST_REMOVE_HEAD(&GLOB(devices), list))) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "SCCP: Removing device %s\n", d->id); d->realtime = TRUE; /* use realtime, to fully clear the device configuration */ sccp_dev_clean(d, TRUE, 0); // performs a device reset if it has a session } if (SCCP_RWLIST_EMPTY(&GLOB(devices))) SCCP_RWLIST_HEAD_DESTROY(&GLOB(devices)); SCCP_RWLIST_UNLOCK(&GLOB(devices)); /* hotline will be removed by line removing function */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Removing Hotline\n"); sccp_line_removeFromGlobals(GLOB(hotline)->line); GLOB(hotline)->line = sccp_line_release(GLOB(hotline)->line); sccp_free(GLOB(hotline)); /* removing lines */ SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE_SAFE_BEGIN(&GLOB(lines), l, list) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "SCCP: Removing line %s\n", l->name); sccp_line_clean(l, TRUE); } SCCP_RWLIST_TRAVERSE_SAFE_END; if (SCCP_RWLIST_EMPTY(&GLOB(lines))) SCCP_RWLIST_HEAD_DESTROY(&GLOB(lines)); SCCP_RWLIST_UNLOCK(&GLOB(lines)); usleep(500); // wait for events to finalize /* removing sessions */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Removing Sessions\n"); SCCP_RWLIST_WRLOCK(&GLOB(sessions)); while ((s = SCCP_LIST_REMOVE_HEAD(&GLOB(sessions), list))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Removing session %s\n", pbx_inet_ntoa(s->sin.sin_addr)); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_NONE); } if (SCCP_LIST_EMPTY(&GLOB(sessions))) SCCP_RWLIST_HEAD_DESTROY(&GLOB(sessions)); SCCP_RWLIST_UNLOCK(&GLOB(sessions)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_2 "SCCP: Killing the socket thread\n"); sccp_globals_lock(socket_lock); if ((GLOB(socket_thread) != AST_PTHREADT_NULL) && (GLOB(socket_thread) != AST_PTHREADT_STOP)) { pthread_cancel(GLOB(socket_thread)); pthread_kill(GLOB(socket_thread), SIGURG); #ifndef HAVE_LIBGC pthread_join(GLOB(socket_thread), NULL); #endif } GLOB(socket_thread) = AST_PTHREADT_STOP; sccp_globals_unlock(socket_lock); sccp_manager_module_stop(); sccp_softkey_clear(); sccp_mutex_destroy(&GLOB(socket_lock)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_2 "SCCP: Killed the socket thread\n"); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_2 "SCCP: Removing bind\n"); if (GLOB(ha)) sccp_free_ha(GLOB(ha)); if (GLOB(localaddr)) sccp_free_ha(GLOB(localaddr)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_2 "SCCP: Removing io/sched\n"); sccp_hint_module_stop(); sccp_event_module_stop(); sccp_threadpool_destroy(GLOB(general_threadpool)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_2 "SCCP: Killed the threadpool\n"); sccp_refcount_destroy(); sccp_free(GLOB(config_file_name)); pbx_mutex_destroy(&GLOB(usecnt_lock)); pbx_mutex_destroy(&GLOB(lock)); // pbx_log(LOG_NOTICE, "SCCP chan_sccp unloaded\n"); return 0; } /*! * \brief PBX Independent Function to be called when starting module reload * \return Success as int */ int sccp_reload(void) { sccp_readingtype_t readingtype; int returnval = 0; pbx_mutex_lock(&GLOB(lock)); if (GLOB(reload_in_progress) == TRUE) { pbx_log(LOG_ERROR, "SCCP reloading already in progress.\n"); pbx_mutex_unlock(&GLOB(lock)); return 1; } sccp_config_file_status_t cfg = sccp_config_getConfig(FALSE); switch (cfg) { case CONFIG_STATUS_FILE_NOT_CHANGED: pbx_log(LOG_NOTICE, "config file '%s' has not change, skipping reload.\n", GLOB(config_file_name)); returnval = 0; break; case CONFIG_STATUS_FILE_OK: pbx_log(LOG_NOTICE, "SCCP reloading configuration.\n"); readingtype = SCCP_CONFIG_READRELOAD; GLOB(reload_in_progress) = TRUE; pbx_mutex_unlock(&GLOB(lock)); if (!sccp_config_general(readingtype)) { pbx_log(LOG_ERROR, "Unable to reload configuration.\n"); GLOB(reload_in_progress) = FALSE; pbx_mutex_unlock(&GLOB(lock)); return 2; } sccp_config_readDevicesLines(readingtype); pbx_mutex_lock(&GLOB(lock)); GLOB(reload_in_progress) = FALSE; returnval = 3; break; case CONFIG_STATUS_FILE_OLD: pbx_log(LOG_ERROR, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_log(LOG_ERROR, "\n\n --> You are using an old configuration format, please update '%s'!!\n --> Loading of module chan_sccp with current sccp.conf has terminated\n --> Check http://chan-sccp-b.sourceforge.net/doc_setup.shtml for more information.\n\n", GLOB(config_file_name)); returnval = 4; break; case CONFIG_STATUS_FILE_NOT_SCCP: pbx_log(LOG_ERROR, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_log(LOG_ERROR, "\n\n --> You are using an configuration file is not following the sccp format, please check '%s'!!\n --> Loading of module chan_sccp with current sccp.conf has terminated\n --> Check http://chan-sccp-b.sourceforge.net/doc_setup.shtml for more information.\n\n", GLOB(config_file_name)); returnval = 4; break; case CONFIG_STATUS_FILE_NOT_FOUND: pbx_log(LOG_ERROR, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_log(LOG_ERROR, "Config file '%s' not found, aborting reload.\n", GLOB(config_file_name)); returnval = 4; break; case CONFIG_STATUS_FILE_INVALID: pbx_log(LOG_ERROR, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_log(LOG_ERROR, "Config file '%s' specified is not a valid config file, aborting reload.\n", GLOB(config_file_name)); returnval = 4; break; } pbx_mutex_unlock(&GLOB(lock)); return returnval; } #ifdef CS_DEVSTATE_FEATURE const char devstate_db_family[] = "CustomDevstate"; #endif
722,248
./chan-sccp-b/src/sccp_management.c
/*! * \file sccp_management.c * \brief SCCP Management Class * \author Marcello Ceschia <marcello [at] ceschia.de> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-11-22 14:09:28 +0100 (Mon, 22 Nov 2010) $ * $Revision: 2174 $ */ #include <config.h> #ifdef CS_SCCP_MANAGER #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision: 2174 $") /* * Descriptions */ static char management_show_devices_desc[] = "Description: Lists SCCP devices in text format with details on current status.\n" "\n" "DevicelistComplete.\n" "Variables: \n" " ActionID: <id> Action ID for this transaction. Will be returned.\n"; static char management_show_lines_desc[] = "Description: Lists SCCP lines in text format with details on current status.\n" "\n" "LinelistComplete.\n" "Variables: \n" " ActionID: <id> Action ID for this transaction. Will be returned.\n"; static char management_restart_devices_desc[] = "Description: restart a given device\n" "\n" "Variables:\n" " Devicename: Name of device to restart\n"; static char management_show_device_add_line_desc[] = "Description: Lists SCCP devices in text format with details on current status.\n" "\n" "DevicelistComplete.\n" "Variables: \n" " Devicename: Name of device to restart.\n" " Linename: Name of line"; static char management_device_update_desc[] = "Description: restart a given device\n" "\n" "Variables:\n" " Devicename: Name of device\n"; static char management_device_set_dnd_desc[] = "Description: set dnd on device\n" "\n" "Variables:\n" " Devicename: Name of device\n" " DNDState: on (busy) / off / reject/ silent"; static char management_line_fwd_update_desc[] = "Description: update forward status for line\n" "\n" "Variables:\n" " Devicename: Name of device\n" " Linename: Name of line\n" " Forwardtype: type of cfwd (all | busy | noAnswer)\n" " Disable: yes Disable call forward (optional)\n" " Number: number to forward calls (optional)"; static char management_fetch_config_metadata_desc[] = "Description: fetch configuration metadata\n" "\n" "Variables:\n" " segment: Config Segment Name (if empty returns all segments).\n" " option: OptionName (if empty returns all options in sement)."; static char management_startcall_desc[] = "Description: start a new call on a device/line\n" "\n" "Variables:\n" " Devicename: Name of the Device\n" " Linename: Name of the line\n" " number: Number to call"; static char management_answercall_desc[] = "Description: answer a ringing channel\n" "\n" "Variables:\n" " Devicename: Name of the Device\n" " channelId: Id of the channel to pickup\n"; static char management_hangupcall_desc[] = "Description: hangup a channel/call\n" "\n" "Variables:\n" " channelId: Id of the Channel to hangup\n"; static char management_hold_desc[] = "Description: hold/resume a call\n" "\n" "Variables:\n" " channelId: Id of the channel to hold/unhold\n" " hold: hold=true / resume=false\n" " Devicename: Name of the Device\n" " SwapChannels: Swap channels when resuming and an active channel is present (true/false)\n"; void sccp_manager_eventListener(const sccp_event_t * event); /* * Pre Declarations */ static int sccp_manager_show_devices(struct mansession *s, const struct message *m); static int sccp_manager_show_lines(struct mansession *s, const struct message *m); static int sccp_manager_restart_device(struct mansession *s, const struct message *m); static int sccp_manager_device_add_line(struct mansession *s, const struct message *m); static int sccp_manager_device_update(struct mansession *s, const struct message *m); static int sccp_manager_device_set_dnd(struct mansession *s, const struct message *m); static int sccp_manager_line_fwd_update(struct mansession *s, const struct message *m); static int sccp_manager_startCall(struct mansession *s, const struct message *m); static int sccp_manager_answerCall(struct mansession *s, const struct message *m); static int sccp_manager_hangupCall(struct mansession *s, const struct message *m); static int sccp_manager_holdCall(struct mansession *s, const struct message *m); #if HAVE_PBX_MANAGER_HOOK_H static int sccp_asterisk_managerHookHelper(int category, const char *event, char *content); static struct manager_custom_hook sccp_manager_hook = { .file = "chan_sccp", .helper = sccp_asterisk_managerHookHelper, }; #endif /*! * \brief Register management commands */ int sccp_register_management(void) { int result = 0; /* Register manager commands */ #if ASTERISK_VERSION_NUMBER < 10600 #define _MAN_FLAGS EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG #else #define _MAN_FLAGS EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG | EVENT_FLAG_REPORTING #endif result = pbx_manager_register("SCCPListDevices", _MAN_FLAGS, sccp_manager_show_devices, "List SCCP devices (text format)", management_show_devices_desc); result |= pbx_manager_register("SCCPListLines", _MAN_FLAGS, sccp_manager_show_lines, "List SCCP lines (text format)", management_show_lines_desc); result |= pbx_manager_register("SCCPDeviceRestart", _MAN_FLAGS, sccp_manager_restart_device, "Restart a given device", management_restart_devices_desc); result |= pbx_manager_register("SCCPDeviceAddLine", _MAN_FLAGS, sccp_manager_device_add_line, "add a line to device", management_show_device_add_line_desc); result |= pbx_manager_register("SCCPDeviceUpdate", _MAN_FLAGS, sccp_manager_device_update, "add a line to device", management_device_update_desc); result |= pbx_manager_register("SCCPDeviceSetDND", _MAN_FLAGS, sccp_manager_device_set_dnd, "set dnd on device", management_device_set_dnd_desc); result |= pbx_manager_register("SCCPLineForwardUpdate", _MAN_FLAGS, sccp_manager_line_fwd_update, "set call-forward on a line", management_line_fwd_update_desc); result |= pbx_manager_register("SCCPStartCall", _MAN_FLAGS, sccp_manager_startCall, "start a new call on device", management_startcall_desc); result |= pbx_manager_register("SCCPAnswerCall", _MAN_FLAGS, sccp_manager_answerCall, "answer a ringin channel", management_answercall_desc); result |= pbx_manager_register("SCCPHangupCall", _MAN_FLAGS, sccp_manager_hangupCall, "hangup a channel", management_hangupcall_desc); result |= pbx_manager_register("SCCPHoldCall", _MAN_FLAGS, sccp_manager_holdCall, "hold/unhold a call", management_hold_desc); result |= pbx_manager_register("SCCPConfigMetaData", _MAN_FLAGS, sccp_manager_config_metadata, "retrieve config metadata", management_fetch_config_metadata_desc); #undef _MAN_FLAGS #if HAVE_PBX_MANAGER_HOOK_H ast_manager_register_hook(&sccp_manager_hook); #else #warning "manager_custom_hook not found, monitor indication does not work properly" #endif return result; } /*! * \brief Unregister management commands */ int sccp_unregister_management(void) { int result = 0; result = pbx_manager_unregister("SCCPListDevices"); result |= pbx_manager_unregister("SCCPDeviceRestart"); result |= pbx_manager_unregister("SCCPDeviceAddLine"); result |= pbx_manager_unregister("SCCPDeviceUpdate"); result |= pbx_manager_unregister("SCCPDeviceSetDND"); result |= pbx_manager_unregister("SCCPLineForwardUpdate"); result |= pbx_manager_unregister("SCCPStartCall"); result |= pbx_manager_unregister("SCCPAnswerCall"); result |= pbx_manager_unregister("SCCPHangupCall"); result |= pbx_manager_unregister("SCCPHoldCall"); result |= pbx_manager_unregister("SCCPConfigMetaData"); #if HAVE_PBX_MANAGER_HOOK_H ast_manager_unregister_hook(&sccp_manager_hook); #endif return result; } /*! * \brief starting manager-module */ void sccp_manager_module_start() { sccp_event_subscribe(SCCP_EVENT_DEVICE_ATTACHED | SCCP_EVENT_DEVICE_DETACHED | SCCP_EVENT_DEVICE_PREREGISTERED | SCCP_EVENT_DEVICE_REGISTERED | SCCP_EVENT_DEVICE_UNREGISTERED | SCCP_EVENT_FEATURE_CHANGED, sccp_manager_eventListener, TRUE); } /*! * \brief stop manager-module * * \lock * - sccp_hint_subscriptions */ void sccp_manager_module_stop() { sccp_event_unsubscribe(SCCP_EVENT_DEVICE_ATTACHED | SCCP_EVENT_DEVICE_DETACHED | SCCP_EVENT_DEVICE_PREREGISTERED | SCCP_EVENT_DEVICE_REGISTERED | SCCP_EVENT_DEVICE_UNREGISTERED, sccp_manager_eventListener); } /*! * \brief Event Listener * * Handles the manager events that need to be posted when an event happens */ void sccp_manager_eventListener(const sccp_event_t * event) { sccp_device_t *device = NULL; sccp_linedevices_t *linedevice = NULL; if (!event) return; switch (event->type) { case SCCP_EVENT_DEVICE_REGISTERED: device = event->event.deviceRegistered.device; // already retained in the event manager_event(EVENT_FLAG_CALL, "DeviceStatus", "ChannelType: SCCP\r\nChannelObjectType: Device\r\nDeviceStatus: %s\r\nSCCPDevice: %s\r\n", "REGISTERED", DEV_ID_LOG(device) ); break; case SCCP_EVENT_DEVICE_UNREGISTERED: device = event->event.deviceRegistered.device; // already retained in the event manager_event(EVENT_FLAG_CALL, "DeviceStatus", "ChannelType: SCCP\r\nChannelObjectType: Device\r\nDeviceStatus: %s\r\nSCCPDevice: %s\r\n", "UNREGISTERED", DEV_ID_LOG(device) ); break; case SCCP_EVENT_DEVICE_PREREGISTERED: device = event->event.deviceRegistered.device; // already retained in the event manager_event(EVENT_FLAG_CALL, "DeviceStatus", "ChannelType: SCCP\r\nChannelObjectType: Device\r\nDeviceStatus: %s\r\nSCCPDevice: %s\r\n", "PREREGISTERED", DEV_ID_LOG(device) ); break; case SCCP_EVENT_DEVICE_ATTACHED: device = event->event.deviceAttached.linedevice->device; // already retained in the event linedevice = event->event.deviceAttached.linedevice; // already retained in the event manager_event(EVENT_FLAG_CALL, "PeerStatus", "ChannelType: SCCP\r\nChannelObjectType: DeviceLine\r\nPeerStatus: %s\r\nSCCPDevice: %s\r\nSCCPLine: %s\r\nSCCPLineName: %s\r\nSubscriptionId: %s\r\nSubscriptionName: %s\r\n", "ATTACHED", DEV_ID_LOG(device), linedevice && linedevice->line ? linedevice->line->name : "(null)", linedevice && linedevice->line ? linedevice->line->label : "(null)", linedevice->subscriptionId.number ? linedevice->subscriptionId.number : "(null)", linedevice->subscriptionId.name ? linedevice->subscriptionId.name : "(null)"); break; case SCCP_EVENT_DEVICE_DETACHED: device = event->event.deviceAttached.linedevice->device; // already retained in the event linedevice = event->event.deviceAttached.linedevice; // already retained in the event manager_event(EVENT_FLAG_CALL, "PeerStatus", "ChannelType: SCCP\r\nChannelObjectType: DeviceLine\r\nPeerStatus: %s\r\nSCCPDevice: %s\r\nSCCPLine: %s\r\nSCCPLineName: %s\r\nSubscriptionId: %s\r\nSubscriptionName: %s\r\n", "DETACHED", DEV_ID_LOG(device), linedevice && linedevice->line ? linedevice->line->name : "(null)", linedevice && linedevice->line ? linedevice->line->label : "(null)", linedevice->subscriptionId.number ? linedevice->subscriptionId.number : "(null)", linedevice->subscriptionId.name ? linedevice->subscriptionId.name : "(null)"); break; case SCCP_EVENT_FEATURE_CHANGED: device = event->event.featureChanged.device; // already retained in the event linedevice = event->event.featureChanged.linedevice; // already retained in the event sccp_feature_type_t featureType = event->event.featureChanged.featureType; switch (featureType) { case SCCP_FEATURE_DND: manager_event(EVENT_FLAG_CALL, "DND", "ChannelType: SCCP\r\nChannelObjectType: Device\r\nFeature: %s\r\nStatus: %s\r\nSCCPDevice: %s\r\n", featureType2str(SCCP_FEATURE_DND), dndmode2str(device->dndFeature.status), DEV_ID_LOG(device) ); break; case SCCP_FEATURE_CFWDALL: case SCCP_FEATURE_CFWDBUSY: if (linedevice) { manager_event(EVENT_FLAG_CALL, "CallForward", "ChannelType: SCCP\r\nChannelObjectType: DeviceLine\r\nFeature: %s\r\nStatus: %s\r\nExtension: %s\r\nSCCPLine: %s\r\nSCCPDevice: %s\r\n", featureType2str(featureType), (SCCP_FEATURE_CFWDALL == featureType) ? ((linedevice->cfwdAll.enabled) ? "On" : "Off") : ((linedevice->cfwdBusy.enabled) ? "On" : "Off"), (SCCP_FEATURE_CFWDALL == featureType) ? ((linedevice->cfwdAll.number) ? linedevice->cfwdAll.number : "(null)") : ((linedevice->cfwdBusy.number) ? linedevice->cfwdBusy.number : "(null)"), (linedevice->line) ? linedevice->line->name : "(null)", DEV_ID_LOG(device) ); } break; case SCCP_FEATURE_CFWDNONE: manager_event(EVENT_FLAG_CALL, "CallForward", "ChannelType: SCCP\r\nChannelObjectType: DeviceLine\r\nFeature: %s\r\nStatus: Off\r\nSCCPLine: %s\r\nSCCPDevice: %s\r\n", featureType2str(featureType), (linedevice && linedevice->line) ? linedevice->line->name : "(null)", DEV_ID_LOG(device) ); break; default: break; } break; default: break; } } /*! * \brief Show Devices Command * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk * * \lock * - devices */ int sccp_manager_show_devices(struct mansession *s, const struct message *m) { const char *id = astman_get_header(m, "ActionID"); sccp_device_t *device = NULL; char idtext[256] = ""; int total = 0; struct tm *timeinfo; char regtime[25]; snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id); pbxman_send_listack(s, m, "Device status list will follow", "start"); // List the peers in separate manager events SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), device, list) { timeinfo = localtime(&device->registrationTime); strftime(regtime, sizeof(regtime), "%c", timeinfo); astman_append(s, "Event: DeviceEntry\r\n%s", idtext); astman_append(s, "ChannelType: SCCP\r\n"); astman_append(s, "ObjectId: %s\r\n", device->id); astman_append(s, "ObjectType: device\r\n"); astman_append(s, "Description: %s\r\n", device->description); astman_append(s, "IPaddress: %s\r\n", (device->session) ? pbx_inet_ntoa(device->session->sin.sin_addr) : "--"); astman_append(s, "Reg_Status: %s\r\n", registrationstate2str(device->registrationState)); astman_append(s, "Reg_Time: %s\r\n", regtime); astman_append(s, "Active: %s\r\n", (device->active_channel) ? "Yes" : "No"); astman_append(s, "NumLines: %d\r\n", device->configurationStatistic.numberOfLines); total++; } SCCP_RWLIST_UNLOCK(&GLOB(devices)); // Send final confirmation astman_append(s, "Event: SCCPListDevicesComplete\r\n" "EventList: Complete\r\n" "ListItems: %d\r\n" "\r\n", total); return 0; } /*! * \brief Show Lines Command * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk * * \lock * - lines */ int sccp_manager_show_lines(struct mansession *s, const struct message *m) { const char *id = astman_get_header(m, "ActionID"); sccp_line_t *line; char idtext[256] = ""; int total = 0; snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id); pbxman_send_listack(s, m, "Device status list will follow", "start"); /* List the peers in separate manager events */ SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), line, list) { astman_append(s, "Event: LineEntry\r\n%s", idtext); astman_append(s, "ChannelType: SCCP\r\n"); astman_append(s, "ObjectId: %s\r\n", line->id); astman_append(s, "ObjectType: line\r\n"); astman_append(s, "Name: %s\r\n", line->name); astman_append(s, "Description: %s\r\n", line->description); astman_append(s, "Num_Channels: %d\r\n", SCCP_RWLIST_GETSIZE(line->channels)); total++; } SCCP_RWLIST_UNLOCK(&GLOB(lines)); /* Send final confirmation */ astman_append(s, "Event: SCCPListLinesComplete\r\n" "EventList: Complete\r\n" "ListItems: %d\r\n" "\r\n", total); return 0; } /*! * \brief Restart Command * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ int sccp_manager_restart_device(struct mansession *s, const struct message *m) { // sccp_list_t *hintList = NULL; sccp_device_t *d = NULL; const char *deviceName = astman_get_header(m, "Devicename"); const char *type = astman_get_header(m, "Type"); pbx_log(LOG_WARNING, "Attempt to get device %s\n", deviceName); if (sccp_strlen_zero(deviceName)) { astman_send_error(s, m, "Please specify the name of device to be reset"); return 0; } pbx_log(LOG_WARNING, "Type of Restart ([quick|reset] or [full|restart]) %s\n", deviceName); if (sccp_strlen_zero(deviceName)) { pbx_log(LOG_WARNING, "Type not specified, using quick"); type = "quick"; } d = sccp_device_find_byid(deviceName, FALSE); if (!d) { astman_send_error(s, m, "Device not found"); return 0; } if (!d->session) { astman_send_error(s, m, "Device not registered"); d = sccp_device_release(d); return 0; } if (!strncasecmp(type, "full", 4) || !strncasecmp(type, "reset", 5)) { sccp_device_sendReset(d, SKINNY_DEVICE_RESET); } else { sccp_device_sendReset(d, SKINNY_DEVICE_RESTART); } astman_send_ack(s, m, "Device restarted"); //astman_append(s, "Send %s restart to device %s\r\n", type, deviceName); //astman_append(s, "\r\n"); d = sccp_device_release(d); return 0; } /*! * \brief Add Device Command * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_device_add_line(struct mansession *s, const struct message *m) { sccp_device_t *d = NULL; sccp_line_t *line = NULL; const char *deviceName = astman_get_header(m, "Devicename"); const char *lineName = astman_get_header(m, "Linename"); pbx_log(LOG_WARNING, "Attempt to get device %s\n", deviceName); if (sccp_strlen_zero(deviceName)) { astman_send_error(s, m, "Please specify the name of device"); return 0; } if (sccp_strlen_zero(lineName)) { astman_send_error(s, m, "Please specify the name of line to be added"); return 0; } d = sccp_device_find_byid(deviceName, FALSE); if (!d) { astman_send_error(s, m, "Device not found"); return 0; } line = sccp_line_find_byname(lineName, TRUE); if (!line) { astman_send_error(s, m, "Line not found"); d = sccp_device_release(d); return 0; } sccp_config_addButton(d, -1, LINE, line->name, NULL, NULL); astman_append(s, "Done\r\n"); astman_append(s, "\r\n"); line = sccp_line_release(line); d = sccp_device_release(d); return 0; } /*! * \brief Update Line Forward Command * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ int sccp_manager_line_fwd_update(struct mansession *s, const struct message *m) { sccp_line_t *line = NULL; sccp_device_t *d = NULL; sccp_linedevices_t *linedevice = NULL; const char *deviceName = astman_get_header(m, "Devicename"); const char *lineName = astman_get_header(m, "Linename"); const char *forwardType = astman_get_header(m, "Forwardtype"); const char *Disable = astman_get_header(m, "Disable"); const char *number = astman_get_header(m, "Number"); sccp_callforward_t cfwd_type = SCCP_CFWD_NONE; char cbuf[64] = ""; d = sccp_device_find_byid(deviceName, TRUE); if (!d) { pbx_log(LOG_WARNING, "%s: Device not found\n", deviceName); astman_send_error(s, m, "Device not found"); return 0; } line = sccp_line_find_byname(lineName, TRUE); if (!line) { pbx_log(LOG_WARNING, "%s: Line %s not found\n", deviceName, lineName); astman_send_error(s, m, "Line not found"); d = sccp_device_release(d); return 0; } if (line->devices.size > 1) { pbx_log(LOG_WARNING, "%s: Callforwarding on shared lines is not supported at the moment\n", deviceName); astman_send_error(s, m, "Callforwarding on shared lines is not supported at the moment"); line = sccp_line_release(line); d = sccp_device_release(d); return 0; } if (!forwardType) { pbx_log(LOG_WARNING, "%s: Forwardtype is not optional [all | busy]\n", deviceName); astman_send_error(s, m, "Forwardtype is not optional [all | busy]"); /* NoAnswer to be added later on */ line = sccp_line_release(line); d = sccp_device_release(d); return 0; } if (!Disable) { Disable = "no"; } if (line) { if ((linedevice = sccp_linedevice_find(d, line))) { if (sccp_strcaseequals("all", forwardType)) { if (sccp_strcaseequals("yes", Disable)) { linedevice->cfwdAll.enabled = 0; number = ""; } else { linedevice->cfwdAll.enabled = 1; cfwd_type = SCCP_CFWD_ALL; } sccp_copy_string(linedevice->cfwdAll.number, number, sizeof(linedevice->cfwdAll.number)); } else if (sccp_strcaseequals("busy", forwardType)) { if (sccp_strcaseequals("yes", Disable)) { linedevice->cfwdBusy.enabled = 0; number = ""; } else { linedevice->cfwdBusy.enabled = 1; cfwd_type = SCCP_CFWD_BUSY; } sccp_copy_string(linedevice->cfwdBusy.number, number, sizeof(linedevice->cfwdBusy.number)); } else if (sccp_strcaseequals("yes", Disable)) { linedevice->cfwdAll.enabled = 0; linedevice->cfwdBusy.enabled = 0; number = ""; sccp_copy_string(linedevice->cfwdAll.number, number, sizeof(linedevice->cfwdAll.number)); sccp_copy_string(linedevice->cfwdBusy.number, number, sizeof(linedevice->cfwdBusy.number)); } switch (cfwd_type) { case SCCP_CFWD_ALL: sccp_feat_changed(linedevice->device, linedevice, SCCP_FEATURE_CFWDALL); snprintf(cbuf, sizeof(cbuf), "Line %s CallForward ALL set to %s", lineName, linedevice->cfwdAll.number); break; case SCCP_CFWD_BUSY: sccp_feat_changed(linedevice->device, linedevice, SCCP_FEATURE_CFWDBUSY); snprintf(cbuf, sizeof(cbuf), "Line %s CallForward BUSY set to %s", lineName, linedevice->cfwdBusy.number); break; case SCCP_CFWD_NONE: default: sccp_feat_changed(linedevice->device, linedevice, SCCP_FEATURE_CFWDNONE); snprintf(cbuf, sizeof(cbuf), "Line %s Call Forward Disabled", lineName); break; } sccp_dev_forward_status(line, linedevice->lineInstance, linedevice->device); sccp_linedevice_release(linedevice); } else { pbx_log(LOG_WARNING, "%s: LineDevice not found for line %s (Device not registeed ?)\n", deviceName, lineName); astman_send_error(s, m, "LineDevice not found (Device not registered ?)"); line = sccp_line_release(line); d = sccp_device_release(d); return 0; } } astman_send_ack(s, m, cbuf); line = sccp_line_release(line); d = sccp_device_release(d); return 0; } /*! * \brief Update Device Command * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_device_update(struct mansession *s, const struct message *m) { sccp_device_t *d = NULL; const char *deviceName = astman_get_header(m, "Devicename"); if (sccp_strlen_zero(deviceName)) { astman_send_error(s, m, "Please specify the name of device"); return 0; } d = sccp_device_find_byid(deviceName, FALSE); if (!d) { astman_send_error(s, m, "Device not found"); return 0; } if (!d->session) { astman_send_error(s, m, "Device not active"); d = sccp_device_release(d); return 0; } sccp_handle_soft_key_template_req(d->session, d, NULL); sccp_handle_button_template_req(d->session, d, NULL); astman_send_ack(s, m, "Done"); d = sccp_device_release(d); return 0; } /*! * \brief Set DND State on Device * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_device_set_dnd(struct mansession *s, const struct message *m) { sccp_device_t *d = NULL; const char *deviceName = astman_get_header(m, "Devicename"); const char *DNDState = astman_get_header(m, "DNDState"); int prevStatus = 0; char retValStr[64] = ""; /** we need the device for resuming calls */ if (sccp_strlen_zero(deviceName)) { astman_send_error(s, m, "Devicename variable is required."); return 0; } if (sccp_strlen_zero(DNDState)) { astman_send_error(s, m, "DNDState variable is required."); return 0; } //astman_append(s, "remove channel '%s' from hold\n", channelId); if ((d = sccp_device_find_byid(deviceName, FALSE))) { if (d->dndFeature.enabled) { prevStatus = d->dndFeature.status; if (sccp_strcaseequals("on", DNDState) || sccp_strcaseequals("reject", DNDState)) { d->dndFeature.status = SCCP_DNDMODE_REJECT; } else if (sccp_strcaseequals("silent", DNDState)) { d->dndFeature.status = SCCP_DNDMODE_SILENT; } else if (sccp_strcaseequals("off", DNDState)) { d->dndFeature.status = SCCP_DNDMODE_OFF; } else { astman_send_error(s, m, "DNDState Variable has to be one of (on/off/reject/silent)."); } if (d->dndFeature.status != prevStatus) { snprintf(retValStr, sizeof(retValStr), "Device %s DND has been set to %s", d->id, dndmode2str(d->dndFeature.status)); sccp_feat_changed(d, NULL, SCCP_FEATURE_DND); sccp_dev_check_displayprompt(d); } else { snprintf(retValStr, sizeof(retValStr), "Device %s DND state unchanged", d->id); } } else { astman_send_error(s, m, "DND Feature not enabled on this device."); } d = d ? sccp_device_release(d) : NULL; } else { astman_send_error(s, m, "Device could not be found."); return 0; } astman_send_ack(s, m, retValStr); return 0; } /*! * \brief Start Call on Device, Line to Number * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_startCall(struct mansession *s, const struct message *m) { sccp_device_t *d = NULL; sccp_line_t *line = NULL; sccp_channel_t *channel = NULL; const char *deviceName = astman_get_header(m, "Devicename"); const char *lineName = astman_get_header(m, "Linename"); const char *number = astman_get_header(m, "number"); d = sccp_device_find_byid(deviceName, FALSE); if (!d) { astman_send_error(s, m, "Device not found"); return 0; } if (!lineName) { if (d && d->defaultLineInstance > 0) { line = sccp_line_find_byid(d, d->defaultLineInstance); } else { line = sccp_dev_get_activeline(d); } } else { line = sccp_line_find_byname(lineName, FALSE); } if (!line) { astman_send_error(s, m, "Line not found"); d = sccp_device_release(d); return 0; } channel = sccp_channel_newcall(line, d, sccp_strlen_zero(number) ? NULL : (char *) number, SKINNY_CALLTYPE_OUTBOUND, NULL); astman_send_ack(s, m, "Call Started"); line = sccp_line_release(line); d = sccp_device_release(d); channel = channel ? sccp_channel_release(channel) : NULL; return 0; } /*! * \brief Answer Call of ChannelId on Device * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_answerCall(struct mansession *s, const struct message *m) { sccp_device_t *d = NULL; sccp_channel_t *c = NULL; const char *deviceName = astman_get_header(m, "Devicename"); const char *channelId = astman_get_header(m, "channelId"); d = sccp_device_find_byid(deviceName, FALSE); if (!d) { astman_send_error(s, m, "Device not found"); return 0; } c = sccp_channel_find_byid(atoi(channelId)); if (!c) { astman_send_error(s, m, "Call not found\r\n"); d = sccp_device_release(d); return 0; } if (c->state != SCCP_CHANNELSTATE_RINGING) { astman_send_error(s, m, "Call is not ringin\r\n"); d = sccp_device_release(d); return 0; } astman_append(s, "Answering channel '%s'\r\n", channelId); sccp_channel_answer(d, c); astman_send_ack(s, m, "Call was Answered"); c = sccp_channel_release(c); d = sccp_device_release(d); return 0; } /*! * \brief Hangup Call of ChannelId * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_hangupCall(struct mansession *s, const struct message *m) { sccp_channel_t *c = NULL; const char *channelId = astman_get_header(m, "channelId"); c = sccp_channel_find_byid(atoi(channelId)); if (!c) { astman_send_error(s, m, "Call not found."); return 0; } //astman_append(s, "Hangup call '%s'\r\n", channelId); sccp_channel_endcall(c); astman_send_ack(s, m, "Call was hungup"); c = sccp_channel_release(c); return 0; } /*! * \brief Put ChannelId Call on Hold (on/off) * \param s Management Session * \param m Message * \return Success as int * * \called_from_asterisk */ static int sccp_manager_holdCall(struct mansession *s, const struct message *m) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; const char *channelId = astman_get_header(m, "channelId"); const char *hold = astman_get_header(m, "hold"); const char *deviceName = astman_get_header(m, "Devicename"); const char *swap = astman_get_header(m, "SwapChannels"); char *retValStr = "Channel was resumed"; boolean_t errorMessage = TRUE; c = sccp_channel_find_byid(atoi(channelId)); if (!c) { astman_send_error(s, m, "Call not found\r\n"); return 0; } if (sccp_strcaseequals("on", hold)) { /* check to see if enable hold */ sccp_channel_hold(c); retValStr = "Channel was put on hold"; errorMessage = FALSE; } else if (sccp_strcaseequals("off", hold)) { /* check to see if disable hold */ /** we need the device for resuming calls */ if (sccp_strlen_zero(deviceName)) { retValStr = "To resume a channel, you need to specify the device that resumes call using Devicename variable."; goto SEND_RESPONSE; } if ((d = sccp_device_find_byid(deviceName, FALSE))) { if (sccp_strcaseequals("yes", swap)) { sccp_channel_resume(d, c, TRUE); } else { sccp_channel_resume(d, c, FALSE); } retValStr = "Channel was resumed"; errorMessage = FALSE; } else { retValStr = "Device to hold/resume could not be found."; } } else { retValStr = "Invalid value for hold, use 'on' or 'off' only."; } SEND_RESPONSE: if (errorMessage) { astman_send_error(s, m, retValStr); } else { astman_send_ack(s, m, retValStr); } d = d ? sccp_device_release(d) : NULL; c = c ? sccp_channel_release(c) : NULL; return 0; } #if HAVE_PBX_MANAGER_HOOK_H /** * parse string from management hook to struct message * */ static void sccp_asterisk_parseStrToAstMessage(char *str, struct message *m) { int x = 0; int curlen; curlen = strlen(str); for (x = 0; x < curlen; x++) { int cr; /* set if we have \r */ if (str[x] == '\r' && x + 1 < curlen && str[x + 1] == '\n') cr = 2; /* Found. Update length to include \r\n */ else if (str[x] == '\n') cr = 1; /* also accept \n only */ else continue; /* don't keep empty lines */ if (x && m->hdrcount < ARRAY_LEN(m->headers)) { /* ... but trim \r\n and terminate the header string */ str[x] = '\0'; m->headers[m->hdrcount++] = str; } x += cr; curlen -= x; /* remaining size */ str += x; /* update pointer */ x = -1; /* reset loop */ } } /** * * * */ static int sccp_asterisk_managerHookHelper(int category, const char *event, char *content) { struct message m = { 0 }; PBX_CHANNEL_TYPE *pbxchannel = NULL; PBX_CHANNEL_TYPE *pbxBridge = NULL; sccp_channel_t *channel = NULL; sccp_device_t *d = NULL; char *str, *dupStr; if (EVENT_FLAG_CALL == category) { if (!strcasecmp("MonitorStart", event) || !strcasecmp("MonitorStop", event)) { str = dupStr = sccp_strdupa(content); /** need a dup, because converter to message structure will modify the str */ sccp_asterisk_parseStrToAstMessage(str, &m); /** convert to message structure to use the astman_get_header function */ const char *channelName = astman_get_header(&m, "Channel"); pbxchannel = pbx_channel_get_by_name(channelName); #if ASTERISK_VERSION_GROUP == 106 pbx_channel_unlock(pbxchannel); #endif if (pbxchannel && (CS_AST_CHANNEL_PVT_IS_SCCP(pbxchannel))) { channel = get_sccp_channel_from_pbx_channel(pbxchannel); } else if (pbxchannel && ((pbxBridge = pbx_channel_get_by_name(pbx_builtin_getvar_helper(pbxchannel, "BRIDGEPEER"))) != NULL) && (CS_AST_CHANNEL_PVT_IS_SCCP(pbxBridge))) { channel = get_sccp_channel_from_pbx_channel(pbxBridge); #if ASTERISK_VERSION_GROUP == 106 pbx_channel_unlock(pbxBridge); #endif } if (channel) { if ((d = sccp_channel_getDevice_retained(channel))) { if (!strcasecmp("MonitorStart", event)) { d->monitorFeature.status |= SCCP_FEATURE_MONITOR_STATE_ACTIVE; } else { d->monitorFeature.status &= ~SCCP_FEATURE_MONITOR_STATE_ACTIVE; } sccp_feat_changed(d, NULL, SCCP_FEATURE_MONITOR); d = sccp_device_release(d); } channel = sccp_channel_release(channel); } } } return 0; } #endif /* HAVE_PBX_MANAGER_HOOK_H */ #endif /* CS_SCCP_MANAGER */
722,249
./chan-sccp-b/src/sccp_indicate.c
/*! * \file sccp_indicate.c * \brief SCCP Indicate Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") static void __sccp_indicate_remote_device(sccp_device_t * device, sccp_channel_t * c, sccp_line_t * line, uint8_t state); /*! * \brief Indicate Without Lock * \param device SCCP Device * \param c *locked* SCCP Channel * \param state State as uint8_t * \param debug Debug as uint8_t * \param file File as char * \param line Line Number as int * \param file Pretty Function as char * \param pretty_function * * \callgraph * \callergraph * * \warning * - line->devices is not always locked * * \lock * - device * - see sccp_device_find_index_for_line() * - see sccp_mwi_lineStatusChangedEvent() via sccp_event_fire() */ void __sccp_indicate(sccp_device_t * device, sccp_channel_t * c, uint8_t state, uint8_t debug, char *file, int line, const char *pretty_function) { sccp_device_t *d; sccp_line_t *l; int instance; sccp_linedevices_t *linedevice; if (debug) { sccp_log((DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_1 "SCCP: [INDICATE] state '%d' in file '%s', on line %d (%s)\n", state, file, line, pretty_function); } d = (device) ? sccp_device_retain(device) : sccp_channel_getDevice_retained(c); if (!d) { sccp_log((DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_1 "SCCP: The channel %d does not have a device\n", c->callid); return; } if (!(l = sccp_line_retain(c->line))) { pbx_log(LOG_ERROR, "SCCP: The channel %d does not have a line\n", c->callid); d = sccp_device_release(d); return; } instance = sccp_device_find_index_for_line(d, l->name); linedevice = sccp_linedevice_find(d, l); /* all the check are ok. We can safely run all the dev functions with no more checks */ sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Indicate SCCP state %d (%s),channel state %d (%s) on call %s-%08x (previous channelstate %d (%s))\n", d->id, state, sccp_indicate2str(state), c->state, sccp_indicate2str(c->state), l->name, c->callid, c->previousChannelState, sccp_indicate2str(c->previousChannelState)); sccp_channel_setSkinnyCallstate(c, state); switch (state) { case SCCP_CHANNELSTATE_DOWN: //PBX(set_callstate)(c, AST_STATE_DOWN); break; case SCCP_CHANNELSTATE_OFFHOOK: if (SCCP_CHANNELSTATE_DOWN == c->previousChannelState) { // new call sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_ON); PBX(set_callstate) (c, AST_STATE_OFFHOOK); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_OFFHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_set_cplane(d, instance, 1); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_ENTER_NUMBER, 0); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_OFFHOOK); sccp_dev_starttone(d, SKINNY_TONE_INSIDEDIALTONE, instance, c->callid, 0); } else { // call pickup sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_ON); PBX(set_callstate) (c, AST_STATE_OFFHOOK); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_OFFHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_set_cplane(d, instance, 1); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_OFFHOOK); } /* for earlyrtp take a look at sccp_channel_newcall because we have no c->owner here */ break; case SCCP_CHANNELSTATE_GETDIGITS: c->state = SCCP_CHANNELSTATE_OFFHOOK; sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_ON); PBX(set_callstate) (c, AST_STATE_OFFHOOK); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_OFFHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_ENTER_NUMBER, 0); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_DIGITSFOLL); sccp_dev_set_cplane(d, instance, 1); sccp_dev_starttone(d, SKINNY_TONE_ZIPZIP, instance, c->callid, 0); /* for earlyrtp take a look at sccp_feat_handle_callforward because we have no c->owner here */ break; case SCCP_CHANNELSTATE_SPEEDDIAL: c->state = SCCP_CHANNELSTATE_OFFHOOK; /* clear all the display buffers */ sccp_dev_cleardisplaynotify(d); sccp_dev_clearprompt(d, 0, 0); sccp_dev_set_ringer(d, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_ON); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_OFFHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_ENTER_NUMBER, 0); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_OFFHOOK); sccp_dev_set_cplane(d, instance, 1); PBX(set_callstate) (c, AST_STATE_OFFHOOK); /* for earlyrtp take a look at sccp_channel_newcall because we have no c->owner here */ break; case SCCP_CHANNELSTATE_ONHOOK: c->state = SCCP_CHANNELSTATE_DOWN; PBX(set_callstate) (c, AST_STATE_DOWN); if (c == d->active_channel) { sccp_dev_stoptone(d, instance, c->callid); } sccp_dev_cleardisplaynotify(d); sccp_dev_clearprompt(d, instance, c->callid); /** if channel was answered somewhere, set state to connected before onhook -> no missedCalls entry */ if (c->answered_elsewhere) { sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_CONNECTED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_HIDDEN); } sccp_dev_set_ringer(d, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_ONHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_set_cplane(d, instance, 0); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_ONHOOK); sccp_handle_time_date_req(d->session, d, NULL); /** we need datetime on hangup for 7936 */ if (c == d->active_channel) { sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_OFF); } if (c->previousChannelState == SCCP_CHANNELSTATE_RINGING) { sccp_dev_set_ringer(d, SKINNY_RINGTYPE_OFF, instance, c->callid); } break; case SCCP_CHANNELSTATE_RINGOUT: sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_RINGOUT, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); if (!c->rtp.audio.rtp) { if (d->earlyrtp) { sccp_channel_openreceivechannel(c); } else { sccp_dev_starttone(d, (uint8_t) SKINNY_TONE_ALERTINGTONE, instance, c->callid, 0); } } sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_RINGOUT); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_RING_OUT, 0); PBX(set_callstate) (c, AST_STATE_RING); break; case SCCP_CHANNELSTATE_RINGING: sccp_dev_cleardisplaynotify(d); sccp_dev_clearprompt(d, instance, 0); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_RINGIN, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); if ((d->dndFeature.enabled && d->dndFeature.status == SCCP_DNDMODE_SILENT && c->ringermode != SKINNY_RINGTYPE_URGENT)) { sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: DND is activated on device\n", d->id); sccp_dev_set_ringer(d, SKINNY_RINGTYPE_SILENT, instance, c->callid); } else { sccp_linedevices_t *ownlinedevice; sccp_device_t *remoteDevice; SCCP_LIST_TRAVERSE(&l->devices, ownlinedevice, list) { remoteDevice = ownlinedevice->device; if (d && remoteDevice && remoteDevice == d) { sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Found matching linedevice. Aux parameter = %s\n", d->id, ownlinedevice->subscriptionId.aux); /** Check the auxiliary parameter of the linedevice to enable silent ringing for certain devices on a certain line.**/ if (0 == strncmp(ownlinedevice->subscriptionId.aux, "silent", 6)) { sccp_dev_set_ringer(d, SKINNY_RINGTYPE_SILENT, instance, c->callid); sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Forcing silent ring for specific device.\n", d->id); } else { sccp_dev_set_ringer(d, c->ringermode, instance, c->callid); sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Normal ring occurred.\n", d->id); } } } } sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_RINGIN); char prompt[100]; if (c->ringermode == SKINNY_RINGTYPE_URGENT) { snprintf(prompt, sizeof(prompt), "Urgent Call from: %s", strlen(c->callInfo.callingPartyName) ? c->callInfo.callingPartyName : c->callInfo.callingPartyNumber); } else { snprintf(prompt, sizeof(prompt), "Incoming Call from: %s", strlen(c->callInfo.callingPartyName) ? c->callInfo.callingPartyName : c->callInfo.callingPartyNumber); } sccp_dev_displayprompt(d, instance, c->callid, prompt, 0); PBX(set_callstate) (c, AST_STATE_RINGING); /*!\todo thats not the right place to update pbx state */ break; case SCCP_CHANNELSTATE_CONNECTED: d->indicate->connected(d, linedevice, c); if (!c->rtp.audio.rtp || c->previousChannelState == SCCP_CHANNELSTATE_HOLD || c->previousChannelState == SCCP_CHANNELSTATE_CALLTRANSFER || c->previousChannelState == SCCP_CHANNELSTATE_CALLCONFERENCE || c->previousChannelState == SCCP_CHANNELSTATE_OFFHOOK) { sccp_channel_openreceivechannel(c); } else if (c->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Did not reopen an RTP stream as old SCCP state was (%s)\n", d->id, sccp_indicate2str(c->previousChannelState)); } break; case SCCP_CHANNELSTATE_BUSY: if (!c->rtp.audio.rtp) { sccp_dev_starttone(d, SKINNY_TONE_LINEBUSYTONE, instance, c->callid, 0); } sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_BUSY, 0); PBX(set_callstate) (c, AST_STATE_BUSY); break; case SCCP_CHANNELSTATE_PROGRESS: /* \todo SCCP_CHANNELSTATE_PROGRESS To be checked */ sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_2 "%s: SCCP_CHANNELSTATE_PROGRESS\n", d->id); if (c->previousChannelState == SCCP_CHANNELSTATE_CONNECTED) { /** this is a bug of asterisk 1.6 (it sends progress after a call is answered then diverted to some extensions with dial app) */ sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "SCCP: Asterisk requests to change state to (Progress) after (Connected). Ignoring\n"); } else { sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "SCCP: Asterisk requests to change state to (Progress) from (%s)\n", sccp_indicate2str(c->previousChannelState)); if (!c->rtp.audio.rtp && d->earlyrtp) { sccp_channel_openreceivechannel(c); } sccp_dev_displayprompt(d, instance, c->callid, "Call Progress", 0); } break; case SCCP_CHANNELSTATE_PROCEED: if (c->previousChannelState == SCCP_CHANNELSTATE_CONNECTED) { // this is a bug of asterisk 1.6 (it sends progress after a call is answered then diverted to some extensions with dial app) sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Asterisk requests to change state to (Progress) after (Connected). Ignoring\n"); break; } sccp_dev_stoptone(d, instance, c->callid); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); /* send connected, so it is not listed as missed call */ sccp_channel_send_callinfo(d, c); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CALL_PROCEED, 0); if (!c->rtp.audio.rtp && d->earlyrtp) { sccp_channel_openreceivechannel(c); } break; case SCCP_CHANNELSTATE_HOLD: sccp_channel_closereceivechannel(c); sccp_handle_time_date_req(d->session, d, NULL); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_HOLD, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); /* send connected, so it is not listed as missed call */ sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_ONHOLD); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_HOLD, 0); sccp_channel_send_callinfo(d, c); sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_OFF); break; case SCCP_CHANNELSTATE_CONGESTION: /* it will be emulated if the rtp audio stream is open */ if (!c->rtp.audio.rtp) { sccp_dev_starttone(d, SKINNY_TONE_REORDERTONE, instance, c->callid, 0); } sccp_channel_send_callinfo(d, c); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_TEMP_FAIL, 0); break; case SCCP_CHANNELSTATE_CALLWAITING: sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "%s: SCCP_CHANNELSTATE_CALLWAITING (%s)\n", DEV_ID_LOG(d), sccp_indicate2str(c->previousChannelState)); sccp_channel_callwaiting_tone_interval(d, c); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_RINGIN, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); /* send connected, so it is not listed as missed call */ sccp_channel_send_callinfo(d, c); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CALL_WAITING, 0); sccp_dev_set_ringer(d, SKINNY_RINGTYPE_SILENT, instance, c->callid); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_RINGIN); PBX(set_callstate) (c, AST_STATE_RINGING); #ifdef CS_SCCP_CONFERENCE if (d->conferencelist_active) { sccp_conference_hide_list_ByDevice(d); } #endif break; case SCCP_CHANNELSTATE_CALLTRANSFER: sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_TRANSFER, 0); sccp_dev_set_ringer(d, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_device_sendcallstate(d, instance, c->callid, SCCP_CHANNELSTATE_CALLTRANSFER, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); break; case SCCP_CHANNELSTATE_CALLCONFERENCE: sccp_device_sendcallstate(d, instance, c->callid, SCCP_CHANNELSTATE_CALLCONFERENCE, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); break; case SCCP_CHANNELSTATE_INVALIDCONFERENCE: /*! \todo SCCP_CHANNELSTATE_INVALIDCONFERENCE To be implemented */ sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "%s: SCCP_CHANNELSTATE_INVALIDCONFERENCE (%s)\n", d->id, sccp_indicate2str(c->previousChannelState)); break; case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "%s: SCCP_CHANNELSTATE_CONNECTEDCONFERENCE (%s)\n", d->id, sccp_indicate2str(c->previousChannelState)); sccp_dev_set_ringer(d, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_ON); sccp_dev_stoptone(d, instance, c->callid); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_CONNECTED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); sccp_dev_set_cplane(d, instance, 1); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_CONNCONF); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CONNECTED, 0); if (!c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } else if (c->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Did not reopen an RTP stream as old SCCP state was (%s)\n", d->id, sccp_indicate2str(c->previousChannelState)); } break; case SCCP_CHANNELSTATE_CALLPARK: sccp_device_sendcallstate(d, instance, c->callid, SCCP_CHANNELSTATE_CALLPARK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); break; case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: sccp_dev_set_ringer(d, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_dev_clearprompt(d, instance, c->callid); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_CONNECTED, SKINNY_CALLPRIORITY_NORMAL, SKINNY_CALLINFO_VISIBILITY_DEFAULT); /** send connected, so it is not listed as missed call */ sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_CALLREMOTEMULTILINE, SKINNY_CALLPRIORITY_NORMAL, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_ONHOOKSTEALABLE); break; case SCCP_CHANNELSTATE_INVALIDNUMBER: /* this is for the earlyrtp. The 7910 does not play tones if a rtp stream is open */ sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_UNKNOWN_NUMBER, 0); if (c->rtp.audio.rtp) { sccp_channel_closereceivechannel(c); } sccp_dev_starttone(d, SKINNY_TONE_REORDERTONE, instance, c->callid, 0); break; case SCCP_CHANNELSTATE_DIALING: sccp_dev_stoptone(d, instance, c->callid); sccp_channel_send_callinfo(d, c); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_DIGITSFOLL); if (d->earlyrtp == SCCP_CHANNELSTATE_DIALING && !c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } break; case SCCP_CHANNELSTATE_DIGITSFOLL: sccp_channel_send_callinfo(d, c); sccp_dev_set_keyset(d, instance, c->callid, KEYMODE_DIGITSFOLL); break; case SCCP_CHANNELSTATE_BLINDTRANSFER: /* \todo SCCP_CHANNELSTATE_BLINDTRANSFER To be implemented */ sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "%s: SCCP_CHANNELSTATE_BLINDTRANSFER (%s)\n", d->id, sccp_indicate2str(c->previousChannelState)); break; default: /* \todo SCCP_CHANNELSTATE:default To be implemented */ sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "%s: SCCP_CHANNELSTATE:default %s (%d) -> %s (%d)\n", d->id, sccp_indicate2str(c->previousChannelState), c->previousChannelState, sccp_indicate2str(c->state), c->state); break; } /* if channel state has changed, notify the others */ if (c->state != c->previousChannelState) { /* if it is a shalred line and a state of interest */ if ((SCCP_RWLIST_GETSIZE(l->devices) > 1) && (c->state == SCCP_CHANNELSTATE_OFFHOOK || c->state == SCCP_CHANNELSTATE_DOWN || c->state == SCCP_CHANNELSTATE_ONHOOK || c->state == SCCP_CHANNELSTATE_CONNECTED || c->state == SCCP_CHANNELSTATE_HOLD) ) { /* notify all remote devices */ __sccp_indicate_remote_device(d, c, l, state); } /* notify features (sccp_feat_channelstateChanged = empty function, skipping) */ // sccp_feat_channelstateChanged(d, c); sccp_event_t event; memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_LINESTATUS_CHANGED; event.event.lineStatusChanged.line = sccp_line_retain(l); event.event.lineStatusChanged.device = sccp_device_retain(d); event.event.lineStatusChanged.state = c->state; sccp_event_fire(&event); } sccp_log((DEBUGCAT_INDICATE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Finish to indicate state SCCP (%s) on call %s-%08x\n", d->id, sccp_indicate2str(state), l->name, c->callid); d = sccp_device_release(d); l = sccp_line_release(l); linedevice = linedevice ? sccp_linedevice_release(linedevice) : linedevice; } /*! * \brief Indicate to Remote Device * \param device SCCP Device * \param c SCCP Channel * \param line SCCP Line * \param state State as int * \todo Explain Pretty Function * * \warning * - line->devices is not always locked */ static void __sccp_indicate_remote_device(sccp_device_t * device, sccp_channel_t * c, sccp_line_t * line, uint8_t state) { sccp_device_t *remoteDevice; sccp_channel_t *activeChannel; int instance; boolean_t recordAsReceivedCall = FALSE; // uint32_t privacyStatus=0; if (!c || !line) { return; } uint8_t stateVisibility = (!c->privacy) ? SKINNY_CALLINFO_VISIBILITY_DEFAULT : SKINNY_CALLINFO_VISIBILITY_HIDDEN; /** \todo move this to channel->privacy */ // if (sccp_channel_getDevic(c)) // privacyStatus = sccp_channel_getDevic(c)->privacyFeature.status & SCCP_PRIVACYFEATURE_HINT; // /* do not display private lines */ // if (state !=SCCP_CHANNELSTATE_CONNECTED && (c->privacy || privacyStatus > 0) ){ // sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "privacyStatus status is set, ignore remote devices\n"); // return; // } /* do not propagate status of hotline */ if (line == GLOB(hotline)->line) { sccp_log(DEBUGCAT_INDICATE) (VERBOSE_PREFIX_3 "SCCP: (__sccp_indicate_remote_device) I'm a hotline, do not notify me!\n"); return; } sccp_linedevices_t *linedevice; sccp_log((DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Indicate state %s (%d) on remote devices for channel %s (call %08x)\n", DEV_ID_LOG(device), sccp_indicate2str(state), state, c->designator, c->callid); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { if (!linedevice->device) { pbx_log(LOG_NOTICE, "Strange to find a linedevice (%p) here without a valid device connected to it !", linedevice); continue; } if (device && linedevice->device == device) { continue; } if ((remoteDevice = sccp_device_retain(linedevice->device))) { sccp_log((DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Indicate state %s (%d) on remote device %s for channel %s (call %08x)\n", DEV_ID_LOG(device), sccp_indicate2str(state), state, DEV_ID_LOG(remoteDevice), c->designator, c->callid); /* check if we have one part of the remote channel */ if ((activeChannel = sccp_channel_get_active(remoteDevice))) { if (sccp_strequals(PBX(getChannelLinkedId) (activeChannel), PBX(getChannelLinkedId) (c))) { stateVisibility = SKINNY_CALLINFO_VISIBILITY_HIDDEN; } activeChannel = sccp_channel_release(activeChannel); } /* done */ instance = sccp_device_find_index_for_line(remoteDevice, line->name); switch (state) { case SCCP_CHANNELSTATE_OFFHOOK: if (c->previousChannelState == SCCP_CHANNELSTATE_RINGING) { sccp_dev_set_ringer(remoteDevice, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_device_sendcallstate(remoteDevice, instance, c->callid, SKINNY_CALLSTATE_CONNECTED, SKINNY_CALLPRIORITY_NORMAL, stateVisibility); /* send connected, so it is not listed as missed call */ } break; case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: /** if channel was answered somewhere, set state to connected before onhook -> no missedCalls entry */ if (c->answered_elsewhere && recordAsReceivedCall) { pbx_log(LOG_NOTICE, "%s: call was answered elsewhere, record this as received call\n", DEV_ID_LOG(remoteDevice)); remoteDevice->indicate->offhook(remoteDevice, linedevice, c->callid); remoteDevice->indicate->connected(remoteDevice, linedevice, c); } else if (c->answered_elsewhere && !recordAsReceivedCall) { sccp_device_sendcallstate(remoteDevice, instance, c->callid, SKINNY_CALLSTATE_CONNECTED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_HIDDEN); } sccp_dev_cleardisplaynotify(remoteDevice); sccp_dev_clearprompt(remoteDevice, instance, c->callid); sccp_dev_set_ringer(remoteDevice, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_dev_set_speaker(remoteDevice, SKINNY_STATIONSPEAKER_OFF); sccp_device_sendcallstate(remoteDevice, instance, c->callid, SKINNY_CALLSTATE_ONHOOK, SKINNY_CALLPRIORITY_NORMAL, stateVisibility); sccp_dev_set_cplane(remoteDevice, linedevice->lineInstance, 1); sccp_dev_set_keyset(remoteDevice, linedevice->lineInstance, c->callid, KEYMODE_ONHOOK); break; case SCCP_CHANNELSTATE_CONNECTED: /* DD: We sometimes set the channel to offhook first before setting it to connected state. This seems to be necessary to have incoming calles logged properly. If this is done, the ringer would not get turned off on remote devices. So I removed the if clause below. Hopefully, this will not cause other calls to stop ringing if multiple calls are ringing concurrently on a shared line. */ sccp_dev_set_ringer(remoteDevice, SKINNY_RINGTYPE_OFF, instance, c->callid); sccp_dev_clearprompt(remoteDevice, instance, c->callid); sccp_device_sendcallstate(remoteDevice, instance, c->callid, SKINNY_CALLSTATE_CALLREMOTEMULTILINE, SKINNY_CALLPRIORITY_NORMAL, stateVisibility); sccp_channel_send_callinfo(remoteDevice, c); sccp_dev_set_keyset(remoteDevice, instance, c->callid, KEYMODE_ONHOOKSTEALABLE); break; case SCCP_CHANNELSTATE_HOLD: remoteDevice->indicate->remoteHold(remoteDevice, instance, c->callid, SKINNY_CALLPRIORITY_NORMAL, stateVisibility); sccp_channel_send_callinfo(remoteDevice, c); break; default: break; } //sccp_log((DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Finish Indicating state %s (%d) on remote device %s for channel %s (call %08x)\n", DEV_ID_LOG(device), sccp_indicate2str(state), state, DEV_ID_LOG(remoteDevice), c->designator, c->callid); remoteDevice = sccp_device_release(remoteDevice); } } } /*! * \brief Convert SCCP Indication/ChannelState 2 String * \param state SCCP_CHANNELSTATE_* * \return Channel State String */ const char *sccp_indicate2str(uint8_t state) { switch (state) { case SCCP_CHANNELSTATE_DOWN: return "Down"; case SCCP_CHANNELSTATE_OFFHOOK: return "OffHook"; case SCCP_CHANNELSTATE_ONHOOK: return "OnHook"; case SCCP_CHANNELSTATE_RINGOUT: return "RingOut"; case SCCP_CHANNELSTATE_RINGING: return "Ringing"; case SCCP_CHANNELSTATE_CONNECTED: return "Connected"; case SCCP_CHANNELSTATE_BUSY: return "Busy"; case SCCP_CHANNELSTATE_PROCEED: return "Proceed"; case SCCP_CHANNELSTATE_CONGESTION: return "Congestion"; case SCCP_CHANNELSTATE_HOLD: return "Hold"; case SCCP_CHANNELSTATE_CALLWAITING: return "CallWaiting"; case SCCP_CHANNELSTATE_CALLTRANSFER: return "CallTransfer"; case SCCP_CHANNELSTATE_CALLPARK: return "CallPark"; case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: return "CallRemoteMultiline"; case SCCP_CHANNELSTATE_INVALIDNUMBER: return "InvalidNumber"; case SCCP_CHANNELSTATE_DIALING: return "Dialing"; case SCCP_CHANNELSTATE_PROGRESS: return "Progress"; case SCCP_CHANNELSTATE_SPEEDDIAL: return "SpeedDial"; case SCCP_CHANNELSTATE_DIGITSFOLL: return "DigitsFoll"; case SCCP_CHANNELSTATE_INVALIDCONFERENCE: return "InvalidConf"; case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: return "ConnConf"; case SCCP_CHANNELSTATE_BLINDTRANSFER: return "BlindTransfer"; case SCCP_CHANNELSTATE_ZOMBIE: return "Zombie"; case SCCP_CHANNELSTATE_DND: return "Dnd"; default: return "Unknown"; } } /*! * \brief Convert SKINNYCall State 2 String * \param state SKINNY_CALLSTATE_* * \return Call State String */ const char *sccp_callstate2str(uint8_t state) { switch (state) { case SKINNY_CALLSTATE_OFFHOOK: return "OffHook"; case SKINNY_CALLSTATE_ONHOOK: return "OnHook"; case SKINNY_CALLSTATE_RINGOUT: return "RingOut"; case SKINNY_CALLSTATE_RINGIN: return "Ringing"; case SKINNY_CALLSTATE_CONNECTED: return "Connected"; case SKINNY_CALLSTATE_BUSY: return "Busy"; case SKINNY_CALLSTATE_PROCEED: return "Proceed"; case SKINNY_CALLSTATE_CONGESTION: return "Congestion"; case SKINNY_CALLSTATE_HOLD: return "Hold"; case SKINNY_CALLSTATE_CALLWAITING: return "CallWaiting"; case SKINNY_CALLSTATE_CALLTRANSFER: return "CallTransfer"; case SKINNY_CALLSTATE_CALLPARK: return "CallPark"; case SKINNY_CALLSTATE_CALLREMOTEMULTILINE: return "CallRemoteMultiline"; case SKINNY_CALLSTATE_INVALIDNUMBER: return "InvalidNumber"; default: return "Unknown"; } }
722,250
./chan-sccp-b/src/sccp_appfunctions.c
/*! * \file sccp_appfunctions.c * \brief SCCP application / dialplan functions Class * \author Diederik de Groot (ddegroot [at] sourceforge.net) * \date 18-03-2011 * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2011-01-12 02:42:50 +0100 (Mi, 12 Jan 2011) $ * $Revision: 2235 $ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision: 2235 $") /*! * \brief ${SCCPDEVICE()} Dialplan function - reads device data * \param chan Asterisk Channel * \param cmd Command as char * \param data Extra data as char * \param buf Buffer as chan* * \param len Lenght as size_t * \return Status as int * * \author Diederik de Groot <ddegroot@users.sourceforce.net> * \ref nf_sccp_dialplan_sccpdevice * * \called_from_asterisk * * \lock * - device->buttonconfig */ static int sccp_func_sccpdevice(PBX_CHANNEL_TYPE * chan, NEWCONST char *cmd, char *data, char *buf, size_t len) { sccp_device_t *d = NULL; char *colname; char tmp[1024] = ""; char lbuf[1024] = ""; int first = 0; if ((colname = strchr(data, ':'))) { /*! \todo Will be deprecated after 1.4 */ static int deprecation_warning = 0; *colname++ = '\0'; if (deprecation_warning++ % 10 == 0) { pbx_log(LOG_WARNING, "SCCPDEVICE(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n"); } } else if ((colname = strchr(data, ','))) { *colname++ = '\0'; } else { colname = "ip"; } if (!strncasecmp(data, "current", 7)) { sccp_channel_t *c; if (!(c = get_sccp_channel_from_pbx_channel(chan))) { /*pbx_log(LOG_WARNING, "SCCPDEVICE(): Not an SCCP channel\n"); */ return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { pbx_log(LOG_WARNING, "SCCPDEVICE(): SCCP Device not available\n"); c = sccp_channel_release(c); return -1; } c = sccp_channel_release(c); } else { if (!(d = sccp_device_find_byid(data, FALSE))) { pbx_log(LOG_WARNING, "SCCPDEVICE(): SCCP Device not available\n"); return -1; } } if (!strcasecmp(colname, "ip")) { sccp_session_t *s = d->session; if (s) { sccp_copy_string(buf, s->sin.sin_addr.s_addr ? pbx_inet_ntoa(s->sin.sin_addr) : "", len); } } else if (!strcasecmp(colname, "id")) { sccp_copy_string(buf, d->id, len); } else if (!strcasecmp(colname, "status")) { sccp_copy_string(buf, devicestate2str(d->state), len); } else if (!strcasecmp(colname, "description")) { sccp_copy_string(buf, d->description, len); } else if (!strcasecmp(colname, "config_type")) { sccp_copy_string(buf, d->config_type, len); } else if (!strcasecmp(colname, "skinny_type")) { sccp_copy_string(buf, devicetype2str(d->skinny_type), len); } else if (!strcasecmp(colname, "tz_offset")) { snprintf(buf, len, "%d", d->tz_offset); } else if (!strcasecmp(colname, "image_version")) { sccp_copy_string(buf, d->imageversion, len); } else if (!strcasecmp(colname, "accessory_status")) { sccp_copy_string(buf, accessorystate2str(d->accessorystatus), len); } else if (!strcasecmp(colname, "registration_state")) { sccp_copy_string(buf, registrationstate2str(d->registrationState), len); } else if (!strcasecmp(colname, "codecs")) { // pbx_codec_pref_string(&d->codecs, buf, sizeof(buf) - 1); sccp_multiple_codecs2str(buf, sizeof(buf) - 1, d->preferences.audio, ARRAY_LEN(d->preferences.audio)); } else if (!strcasecmp(colname, "capability")) { // pbx_getformatname_multiple(buf, len - 1, d->capability); sccp_multiple_codecs2str(buf, len - 1, d->capabilities.audio, ARRAY_LEN(d->capabilities.audio)); } else if (!strcasecmp(colname, "state")) { sccp_copy_string(buf, accessorystate2str(d->accessorystatus), len); } else if (!strcasecmp(colname, "lines_registered")) { sccp_copy_string(buf, d->linesRegistered ? "yes" : "no", len); } else if (!strcasecmp(colname, "lines_count")) { snprintf(buf, len, "%d", d->linesCount); } else if (!strcasecmp(colname, "last_number")) { sccp_copy_string(buf, d->lastNumber, len); } else if (!strcasecmp(colname, "early_rtp")) { snprintf(buf, len, "%d", d->earlyrtp); } else if (!strcasecmp(colname, "supported_protocol_version")) { snprintf(buf, len, "%d", d->protocolversion); } else if (!strcasecmp(colname, "used_protocol_version")) { snprintf(buf, len, "%d", d->inuseprotocolversion); } else if (!strcasecmp(colname, "mwi_light")) { sccp_copy_string(buf, d->mwilight ? "ON" : "OFF", len); } else if (!strcasecmp(colname, "dnd_feature")) { sccp_copy_string(buf, (d->dndFeature.enabled) ? "ON" : "OFF", len); } else if (!strcasecmp(colname, "dnd_state")) { sccp_copy_string(buf, dndmode2str(d->dndFeature.status), len); } else if (!strcasecmp(colname, "dynamic") || !strcasecmp(colname, "realtime")) { #ifdef CS_SCCP_REALTIME sccp_copy_string(buf, d->realtime ? "yes" : "no", len); #else sccp_copy_string(buf, "not supported", len); #endif } else if (!strcasecmp(colname, "active_channel")) { snprintf(buf, len, "%d", d->active_channel->callid); } else if (!strcasecmp(colname, "transfer_channel")) { snprintf(buf, len, "%d", d->transferChannels.transferee->callid); #ifdef CS_SCCP_CONFERENCE } else if (!strcasecmp(colname, "conference_id")) { snprintf(buf, len, "%d", d->conference->id); } else if (!strcasecmp(colname, "allow_conference")) { snprintf(buf, len, "%s", d->allow_conference ? "ON" : "OFF"); } else if (!strcasecmp(colname, "conf_play_general_announce")) { snprintf(buf, len, "%s", d->conf_play_general_announce ? "ON" : "OFF"); } else if (!strcasecmp(colname, "allow_conference")) { snprintf(buf, len, "%s", d->conf_play_part_announce ? "ON" : "OFF"); } else if (!strcasecmp(colname, "conf_play_part_announce")) { snprintf(buf, len, "%s", d->allow_conference ? "ON" : "OFF"); } else if (!strcasecmp(colname, "conf_mute_on_entry")) { snprintf(buf, len, "%s", d->conf_mute_on_entry ? "ON" : "OFF"); } else if (!strcasecmp(colname, "conf_music_on_hold_class")) { snprintf(buf, len, "%s", d->conf_music_on_hold_class); #endif } else if (!strcasecmp(colname, "current_line")) { sccp_copy_string(buf, d->currentLine->id ? d->currentLine->id : "", len); } else if (!strcasecmp(colname, "button_config")) { sccp_buttonconfig_t *config; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { switch (config->type) { case LINE: snprintf(tmp, sizeof(tmp), "[%d,%s,%s]", config->instance, config_buttontype2str(config->type), config->button.line.name); break; case SPEEDDIAL: snprintf(tmp, sizeof(tmp), "[%d,%s,%s,%s]", config->instance, config_buttontype2str(config->type), config->label, config->button.speeddial.ext); break; case SERVICE: snprintf(tmp, sizeof(tmp), "[%d,%s,%s,%s]", config->instance, config_buttontype2str(config->type), config->label, config->button.service.url); break; case FEATURE: snprintf(tmp, sizeof(tmp), "[%d,%s,%s,%s]", config->instance, config_buttontype2str(config->type), config->label, config->button.feature.options); break; case EMPTY: snprintf(tmp, sizeof(tmp), "[%d,%s]", config->instance, config_buttontype2str(config->type)); break; } if (first == 0) { first = 1; strcat(lbuf, tmp); } else { strcat(lbuf, ","); strcat(lbuf, tmp); } } SCCP_LIST_UNLOCK(&d->buttonconfig); snprintf(buf, len, "[ %s ]", lbuf); } else if (!strcasecmp(colname, "pending_delete")) { sccp_copy_string(buf, d->pendingDelete ? "yes" : "no", len); } else if (!strcasecmp(colname, "pending_update")) { sccp_copy_string(buf, d->pendingUpdate ? "yes" : "no", len); } else if (!strncasecmp(colname, "chanvar[", 8)) { char *chanvar = colname + 8; PBX_VARIABLE_TYPE *v; chanvar = strsep(&chanvar, "]"); for (v = d->variables; v; v = v->next) { if (!strcasecmp(v->name, chanvar)) { sccp_copy_string(buf, v->value, len); } } } else if (!strncasecmp(colname, "codec[", 6)) { char *codecnum; // int codec = 0; codecnum = colname + 6; // move past the '[' codecnum = strsep(&codecnum, "]"); // trim trailing ']' if any if (skinny_codecs[atoi(codecnum)].key) { // if ((codec = pbx_codec_pref_index(&d->codecs, atoi(codecnum)))) { // sccp_copy_string(buf, pbx_getformatname(codec), len); sccp_copy_string(buf, codec2name(atoi(codecnum)), len); } else { buf[0] = '\0'; } } else { pbx_log(LOG_WARNING, "SCCPDEVICE(%s): unknown colname: %s\n", data, colname); buf[0] = '\0'; } sccp_device_release(d); return 0; } /*! \brief Stucture to declare a dialplan function: SCCPDEVICE */ static struct pbx_custom_function sccpdevice_function = { .name = "SCCPDEVICE", .synopsis = "Retrieves information about an SCCP Device", .syntax = "Usage: SCCPDEVICE(deviceId,<option>)\n", .read = sccp_func_sccpdevice, .desc = "DeviceId = Device Identifier (i.e. SEP0123456789)\n" "Option = One of the possible options mentioned in arguments\n", #if ASTERISK_VERSION_NUMBER > 10601 .arguments = "DeviceId = Device Identifier (i.e. SEP0123456789)\n" "Option = One of these possible options:\n" "ip, id, status, description, config_type, skinny_type, tz_offset, image_version, \n" "accessory_status, registration_state, codecs, capability, state, lines_registered, \n" "lines_count, last_number, early_rtp, supported_protocol_version, used_protocol_version, \n" "mwi_light, dynamic, realtime, active_channel, transfer_channel, \n" "conference_id, allow_conference, conf_play_general_announce, allow_conference, \n" "conf_play_part_announce, conf_mute_on_entry, conf_music_on_hold_class, \n" "current_line, button_config, pending_delete, chanvar[], codec[]", #endif }; /*! * \brief ${SCCPLINE()} Dialplan function - reads sccp line data * \param chan Asterisk Channel * \param cmd Command as char * \param data Extra data as char * \param buf Buffer as chan* * \param len Lenght as size_t * \return Status as int * * \author Diederik de Groot <ddegroot@users.sourceforce.net> * \ref nf_sccp_dialplan_sccpline * * \called_from_asterisk * * \lock * - line->devices */ static int sccp_func_sccpline(PBX_CHANNEL_TYPE * chan, NEWCONST char *cmd, char *data, char *buf, size_t len) { sccp_line_t *l = NULL; sccp_channel_t *c = NULL; char *colname; char tmp[1024] = ""; char lbuf[1024] = ""; int first = 0; if ((colname = strchr(data, ':'))) { /*! \todo Will be deprecated after 1.4 */ static int deprecation_warning = 0; *colname++ = '\0'; if (deprecation_warning++ % 10 == 0) { pbx_log(LOG_WARNING, "SCCPLINE(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n"); } } else if ((colname = strchr(data, ','))) { *colname++ = '\0'; } else { colname = "id"; } if (!strncasecmp(data, "current", 7)) { if (!(c = get_sccp_channel_from_pbx_channel(chan))) { /* pbx_log(LOG_WARNING, "SCCPLINE(): Not an SCCP Channel\n"); */ return -1; } if (!c->line) { pbx_log(LOG_WARNING, "SCCPLINE(): SCCP Line not available\n"); c = sccp_channel_release(c); return -1; } l = c->line; c = sccp_channel_release(c); } else if (!strncasecmp(data, "parent", 7)) { if (!(c = get_sccp_channel_from_pbx_channel(chan))) { /* pbx_log(LOG_WARNING, "SCCPLINE(): Not an SCCP Channel\n"); */ return -1; } if (!c->parentChannel || !c->parentChannel->line) { pbx_log(LOG_WARNING, "SCCPLINE(): SCCP Line not available\n"); c = sccp_channel_release(c); return -1; } l = c->parentChannel->line; c = sccp_channel_release(c); } else { if (!(l = sccp_line_find_byname(data, TRUE))) { pbx_log(LOG_WARNING, "SCCPLINE(): SCCP Line not available\n"); return -1; } } if (!strcasecmp(colname, "id")) { sccp_copy_string(buf, l->id, len); } else if (!strcasecmp(colname, "name")) { sccp_copy_string(buf, l->name, len); } else if (!strcasecmp(colname, "description")) { sccp_copy_string(buf, l->description, len); } else if (!strcasecmp(colname, "label")) { sccp_copy_string(buf, l->label, len); } else if (!strcasecmp(colname, "vmnum")) { sccp_copy_string(buf, l->vmnum, len); } else if (!strcasecmp(colname, "trnsfvm")) { sccp_copy_string(buf, l->trnsfvm, len); } else if (!strcasecmp(colname, "meetme")) { sccp_copy_string(buf, l->meetme ? "on" : "off", len); } else if (!strcasecmp(colname, "meetmenum")) { sccp_copy_string(buf, l->meetmenum, len); } else if (!strcasecmp(colname, "meetmeopts")) { sccp_copy_string(buf, l->meetmeopts, len); } else if (!strcasecmp(colname, "context")) { sccp_copy_string(buf, l->context, len); } else if (!strcasecmp(colname, "language")) { sccp_copy_string(buf, l->language, len); } else if (!strcasecmp(colname, "accountcode")) { sccp_copy_string(buf, l->accountcode, len); } else if (!strcasecmp(colname, "musicclass")) { sccp_copy_string(buf, l->musicclass, len); } else if (!strcasecmp(colname, "amaflags")) { sccp_copy_string(buf, l->amaflags ? "yes" : "no", len); } else if (!strcasecmp(colname, "callgroup")) { pbx_print_group(buf, len, l->callgroup); } else if (!strcasecmp(colname, "pickupgroup")) { #ifdef CS_SCCP_PICKUP pbx_print_group(buf, len, l->pickupgroup); #else sccp_copy_string(buf, "not supported", len); #endif } else if (!strcasecmp(colname, "cid_name")) { sccp_copy_string(buf, l->cid_name ? l->cid_name : "<not set>", len); } else if (!strcasecmp(colname, "cid_num")) { sccp_copy_string(buf, l->cid_num ? l->cid_num : "<not set>", len); } else if (!strcasecmp(colname, "incoming_limit")) { snprintf(buf, len, "%d", l->incominglimit); } else if (!strcasecmp(colname, "channel_count")) { snprintf(buf, len, "%d", SCCP_RWLIST_GETSIZE(l->channels)); } else if (!strcasecmp(colname, "dynamic") || !strcasecmp(colname, "realtime")) { #ifdef CS_SCCP_REALTIME sccp_copy_string(buf, l->realtime ? "Yes" : "No", len); #else sccp_copy_string(buf, "not supported", len); #endif } else if (!strcasecmp(colname, "pending_delete")) { sccp_copy_string(buf, l->pendingDelete ? "yes" : "no", len); } else if (!strcasecmp(colname, "pending_update")) { sccp_copy_string(buf, l->pendingUpdate ? "yes" : "no", len); /* regexten feature -- */ } else if (!strcasecmp(colname, "regexten")) { sccp_copy_string(buf, l->regexten ? l->regexten : "Unset", len); } else if (!strcasecmp(colname, "regcontext")) { sccp_copy_string(buf, l->regcontext ? l->regcontext : "Unset", len); /* -- regexten feature */ } else if (!strcasecmp(colname, "adhoc_number")) { sccp_copy_string(buf, l->adhocNumber ? l->adhocNumber : "No", len); } else if (!strcasecmp(colname, "newmsgs")) { snprintf(buf, len, "%d", l->voicemailStatistic.newmsgs); } else if (!strcasecmp(colname, "oldmsgs")) { snprintf(buf, len, "%d", l->voicemailStatistic.oldmsgs); } else if (!strcasecmp(colname, "num_lines")) { snprintf(buf, len, "%d", l->devices.size); } else if (!strcasecmp(colname, "mailboxes")) { /*! \todo needs to be implemented, should return a comma separated list of mailboxes */ } else if (!strcasecmp(colname, "cfwd")) { sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { if (linedevice) snprintf(tmp, sizeof(tmp), "[id:%s,cfwdAll:%s,num:%s,cfwdBusy:%s,num:%s]", linedevice->device->id, linedevice->cfwdAll.enabled ? "on" : "off", linedevice->cfwdAll.number ? linedevice->cfwdAll.number : "<not set>", linedevice->cfwdBusy.enabled ? "on" : "off", linedevice->cfwdBusy.number ? linedevice->cfwdBusy.number : "<not set>"); if (first == 0) { first = 1; strcat(lbuf, tmp); } else { strcat(lbuf, ","); strcat(lbuf, tmp); } } SCCP_LIST_UNLOCK(&l->devices); snprintf(buf, len, "%s", lbuf); } else if (!strcasecmp(colname, "devices")) { sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { if (linedevice) snprintf(tmp, sizeof(tmp), "%s", linedevice->device->id); if (first == 0) { first = 1; strcat(lbuf, tmp); } else { strcat(lbuf, ","); strcat(lbuf, tmp); } } SCCP_LIST_UNLOCK(&l->devices); snprintf(buf, len, "%s", lbuf); } else if (!strncasecmp(colname, "chanvar[", 8)) { char *chanvar = colname + 8; PBX_VARIABLE_TYPE *v; chanvar = strsep(&chanvar, "]"); for (v = l->variables; v; v = v->next) { if (!strcasecmp(v->name, chanvar)) { sccp_copy_string(buf, v->value, len); } } } else { pbx_log(LOG_WARNING, "SCCPLINE(%s): unknown colname: %s\n", data, colname); buf[0] = '\0'; } sccp_line_release(l); return 0; } /*! \brief Stucture to declare a dialplan function: SCCPLINE */ static struct pbx_custom_function sccpline_function = { .name = "SCCPLINE", .synopsis = "Retrieves information about an SCCP Line", .syntax = "Usage: SCCPLINE(lineName,<option>)", .read = sccp_func_sccpline, .desc = "LineName = Name of the line to be queried.\n" "Option = One of the possible options mentioned in arguments\n", #if ASTERISK_VERSION_NUMBER > 10601 .arguments = "LineName = use on off these: 'current', 'parent', actual linename\n" "Option = One of these possible options:\n" "id, name, description, label, vmnum, trnsfvm, meetme, meetmenum, meetmeopts, context, \n" "language, accountcode, musicclass, amaflags, callgroup, pickupgroup, cid_name, cid_num, \n" "incoming_limit, channel_count, dynamic, realtime, pending_delete, pending_update, \n" "regexten, regcontext, adhoc_number, newmsgs, oldmsgs, num_lines, cfwd, devices, chanvar[]" #endif }; /*! * \brief ${SCCPCHANNEL()} Dialplan function - reads sccp line data * \param chan Asterisk Channel * \param cmd Command as char * \param data Extra data as char * \param buf Buffer as chan* * \param len Lenght as size_t * \return Status as int * * \author Diederik de Groot <ddegroot@users.sourceforce.net> * \ref nf_sccp_dialplan_sccpchannel * * \called_from_asterisk */ static int sccp_func_sccpchannel(PBX_CHANNEL_TYPE * chan, NEWCONST char *cmd, char *data, char *buf, size_t len) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; char *colname; if ((colname = strchr(data, ':'))) { /*! \todo Will be deprecated after 1.4 */ static int deprecation_warning = 0; *colname++ = '\0'; if (deprecation_warning++ % 10 == 0) { pbx_log(LOG_WARNING, "SCCPCHANNEL(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n"); } } else if ((colname = strchr(data, ','))) { *colname++ = '\0'; } else { colname = "callid"; } if (!strncasecmp(data, "current", 7)) { if (!(c = get_sccp_channel_from_pbx_channel(chan))) { return -1; /* Not a SCCP channel. */ } } else { uint32_t callid = atoi(data); if (!(c = sccp_channel_find_byid(callid))) { pbx_log(LOG_WARNING, "SCCPCHANNEL(): SCCP Channel not available\n"); return -1; } } if (!strcasecmp(colname, "callid") || !strcasecmp(colname, "id")) { snprintf(buf, len, "%d", c->callid); } else if (!strcasecmp(colname, "format")) { snprintf(buf, len, "%d", c->rtp.audio.readFormat); } else if (!strcasecmp(colname, "codecs")) { // pbx_codec_pref_string(&c->codecs, buf, sizeof(buf) - 1); sccp_copy_string(buf, codec2name(c->rtp.audio.readFormat), len); } else if (!strcasecmp(colname, "capability")) { // pbx_getformatname_multiple(buf, len - 1, c->capability); sccp_multiple_codecs2str(buf, sizeof(buf) - 1, c->capabilities.audio, ARRAY_LEN(c->capabilities.audio)); } else if (!strcasecmp(colname, "calledPartyName")) { sccp_copy_string(buf, c->callInfo.calledPartyName, len); } else if (!strcasecmp(colname, "calledPartyNumber")) { sccp_copy_string(buf, c->callInfo.calledPartyNumber, len); } else if (!strcasecmp(colname, "callingPartyName")) { sccp_copy_string(buf, c->callInfo.callingPartyName, len); } else if (!strcasecmp(colname, "callingPartyNumber")) { sccp_copy_string(buf, c->callInfo.callingPartyNumber, len); } else if (!strcasecmp(colname, "originalCallingPartyName")) { sccp_copy_string(buf, c->callInfo.originalCallingPartyName, len); } else if (!strcasecmp(colname, "originalCallingPartyNumber")) { sccp_copy_string(buf, c->callInfo.originalCallingPartyNumber, len); } else if (!strcasecmp(colname, "originalCalledPartyName")) { sccp_copy_string(buf, c->callInfo.originalCalledPartyName, len); } else if (!strcasecmp(colname, "originalCalledPartyNumber")) { sccp_copy_string(buf, c->callInfo.originalCalledPartyNumber, len); } else if (!strcasecmp(colname, "lastRedirectingPartyName")) { sccp_copy_string(buf, c->callInfo.lastRedirectingPartyName, len); } else if (!strcasecmp(colname, "lastRedirectingPartyNumber")) { sccp_copy_string(buf, c->callInfo.lastRedirectingPartyNumber, len); } else if (!strcasecmp(colname, "cgpnVoiceMailbox")) { sccp_copy_string(buf, c->callInfo.cgpnVoiceMailbox, len); } else if (!strcasecmp(colname, "cdpnVoiceMailbox")) { sccp_copy_string(buf, c->callInfo.cdpnVoiceMailbox, len); } else if (!strcasecmp(colname, "originalCdpnVoiceMailbox")) { sccp_copy_string(buf, c->callInfo.originalCdpnVoiceMailbox, len); } else if (!strcasecmp(colname, "lastRedirectingVoiceMailbox")) { sccp_copy_string(buf, c->callInfo.lastRedirectingVoiceMailbox, len); } else if (!strcasecmp(colname, "passthrupartyid")) { snprintf(buf, len, "%d", c->passthrupartyid); } else if (!strcasecmp(colname, "state")) { sccp_copy_string(buf, channelstate2str(c->state), len); } else if (!strcasecmp(colname, "previous_state")) { sccp_copy_string(buf, channelstate2str(c->previousChannelState), len); } else if (!strcasecmp(colname, "calltype")) { sccp_copy_string(buf, calltype2str(c->calltype), len); } else if (!strcasecmp(colname, "dialed_number")) { sccp_copy_string(buf, c->dialedNumber, len); } else if (!strcasecmp(colname, "device")) { sccp_copy_string(buf, c->currentDeviceId, len); } else if (!strcasecmp(colname, "line")) { sccp_copy_string(buf, c->line->name, len); } else if (!strcasecmp(colname, "answered_elsewhere")) { sccp_copy_string(buf, c->answered_elsewhere ? "yes" : "no", len); } else if (!strcasecmp(colname, "privacy")) { sccp_copy_string(buf, c->privacy ? "yes" : "no", len); } else if (!strcasecmp(colname, "ss_action")) { snprintf(buf, len, "%d", c->ss_action); // } else if (!strcasecmp(colname, "monitorEnabled")) { // sccp_copy_string(buf, c->monitorEnabled ? "yes" : "no", len); #ifdef CS_SCCP_CONFERENCE } else if (!strcasecmp(colname, "conference_id")) { snprintf(buf, len, "%d", c->conference_id); } else if (!strcasecmp(colname, "conference_participant_id")) { snprintf(buf, len, "%d", c->conference_participant_id); #endif } else if (!strcasecmp(colname, "parent")) { snprintf(buf, len, "%d", c->parentChannel->callid); } else if (!strcasecmp(colname, "bridgepeer")) { snprintf(buf, len, "%s", (c->owner && CS_AST_BRIDGED_CHANNEL(c->owner)) ? pbx_channel_name(CS_AST_BRIDGED_CHANNEL(c->owner)) : "<unknown>"); } else if (!strcasecmp(colname, "peerip")) { // NO-NAT (Ip-Address Associated with the Session->sin) if ((d = sccp_channel_getDevice_retained(c))) { ast_copy_string(buf, pbx_inet_ntoa(d->session->sin.sin_addr), len); d = sccp_device_release(d); } } else if (!strcasecmp(colname, "recvip")) { // NAT (Actual Source IP-Address Reported by the phone upon registration) if ((d = sccp_channel_getDevice_retained(c))) { ast_copy_string(buf, pbx_inet_ntoa(d->session->phone_sin.sin_addr), len); d = sccp_device_release(d); } } else if (!strncasecmp(colname, "codec[", 6)) { char *codecnum; // int codec = 0; codecnum = colname + 6; // move past the '[' codecnum = strsep(&codecnum, "]"); // trim trailing ']' if any // if ((codec = pbx_codec_pref_index(&c->codecs, atoi(codecnum)))) { // sccp_copy_string(buf, pbx_getformatname(codec), len); if (skinny_codecs[atoi(codecnum)].key) { sccp_copy_string(buf, codec2name(atoi(codecnum)), len); } else { buf[0] = '\0'; } } else { pbx_log(LOG_WARNING, "SCCPCHANNEL(%s): unknown colname: %s\n", data, colname); buf[0] = '\0'; } sccp_channel_release(c); return 0; } /*! \brief Stucture to declare a dialplan function: SCCPCHANNEL */ static struct pbx_custom_function sccpchannel_function = { .name = "SCCPCHANNEL", .synopsis = "Retrieves information about an SCCP Line", .syntax = "Usage: SCCPCHANNEL(channelId,<option>)", .read = sccp_func_sccpchannel, .desc = "ChannelId = Name of the line to be queried.\n" "Option = One of the possible options mentioned in arguments\n", #if ASTERISK_VERSION_NUMBER > 10601 .arguments = "ChannelId = use on off these: 'current', actual callid\n" "Option = One of these possible options:\n" "callid, id, format, codecs, capability, calledPartyName, calledPartyNumber, callingPartyName, \n" "callingPartyNumber, originalCallingPartyName, originalCallingPartyNumber, originalCalledPartyName, \n" "originalCalledPartyNumber, lastRedirectingPartyName, lastRedirectingPartyNumber, cgpnVoiceMailbox, \n" "cdpnVoiceMailbox, originalCdpnVoiceMailbox, lastRedirectingVoiceMailbox, passthrupartyid, state, \n" "previous_state, calltype, dialed_number, device, line, answered_elsewhere, privacy, ss_action, \n" "monitorEnabled, parent, bridgepeer, peerip, recvip, codec[]" // not implemented yet: "/*conference*/" #endif }; /*! * \brief Set the Preferred Codec for a SCCP channel via the dialplan * \param chan Asterisk Channel * \param data single codec name * \return Success as int * * \called_from_asterisk * \deprecated */ #if ASTERISK_VERSION_NUMBER >= 10800 static int sccp_app_prefcodec(PBX_CHANNEL_TYPE * chan, const char *data) #else static int sccp_app_prefcodec(PBX_CHANNEL_TYPE * chan, void *data) #endif { sccp_channel_t *c = NULL; int res; if (!(c = get_sccp_channel_from_pbx_channel(chan))) { pbx_log(LOG_WARNING, "SCCPSetCodec: Not an SCCP channel\n"); return -1; } res = sccp_channel_setPreferredCodec(c, data); c = sccp_channel_release(c); pbx_log(LOG_WARNING, "SCCPSetCodec: Is now deprecated. Please use 'Set(CHANNEL(codec)=%s)' insteadl.\n", (char *) data); return res ? 0 : -1; } /*! \brief Stucture to declare a dialplan function: SETSCCPCODEC */ static char *prefcodec_name = "SCCPSetCodec"; static char *old_prefcodec_name = "SetSCCPCodec"; static char *prefcodec_synopsis = "Sets the preferred codec for the current sccp channel (DEPRECATED use generic 'Set(CHANNEL(codec)=alaw)' instead)"; static char *prefcodec_descr = "Usage: SCCPSetCodec(codec)" "Sets the preferred codec for dialing out with the current chan_sccp channel\nDEPRECATED use generic 'Set(CHANNEL(codec)=alaw)' instead\n"; /*! * \brief Set the Name and Number of the Called Party to the Calling Phone * \param chan Asterisk Channel * \param data CallerId in format "Name" \<number\> * \return Success as int * * \called_from_asterisk */ #if ASTERISK_VERSION_NUMBER >= 10800 static int sccp_app_calledparty(PBX_CHANNEL_TYPE * chan, const char *data) #else static int sccp_app_calledparty(PBX_CHANNEL_TYPE * chan, void *data) #endif { char *text = (char *) data; char *num, *name; sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(chan))) { pbx_log(LOG_WARNING, "SCCPSetCalledParty: Not an SCCP channel\n"); return 0; } if (!text) { pbx_log(LOG_WARNING, "SCCPSetCalledParty: No CalledParty Information Provided\n"); c = sccp_channel_release(c); return 0; } pbx_callerid_parse(text, &name, &num); sccp_channel_set_calledparty(c, name, num); c = sccp_channel_release(c); return 0; } /*! \brief Stucture to declare a dialplan function: SETCALLEDPARTY */ static char *calledparty_name = "SCCPSetCalledParty"; static char *old_calledparty_name = "SetCalledParty"; static char *calledparty_synopsis = "Sets the callerid of the called party"; static char *calledparty_descr = "Usage: SCCPSetCalledParty(\"Name\" <ext>)" "Sets the name and number of the called party for use with chan_sccp\n"; /*! * \brief It allows you to send a message to the calling device. * \author Frank Segtrop <fs@matflow.net> * \param chan asterisk channel * \param data message to sent - if empty clear display * \version 20071112_1944 * * \called_from_asterisk * * \lock * - device * - see sccp_dev_displayprinotify() * - see sccp_dev_displayprompt() */ #if ASTERISK_VERSION_NUMBER >= 10800 static int sccp_app_setmessage(PBX_CHANNEL_TYPE * chan, const char *data) #else static int sccp_app_setmessage(PBX_CHANNEL_TYPE * chan, void *data) #endif { sccp_channel_t *c = NULL; sccp_device_t *d; if (!(c = get_sccp_channel_from_pbx_channel(chan))) { pbx_log(LOG_WARNING, "SCCPSetMessage: Not an SCCP channel\n"); return 0; } char *text; char *splitter = sccp_strdupa(data); int timeout = 0; text = strsep(&splitter, ","); if (splitter) { timeout = atoi(splitter); } if (!text || !(d = sccp_channel_getDevice_retained(c))) { pbx_log(LOG_WARNING, "SCCPSetMessage: Not an SCCP device or not text provided\n"); c = sccp_channel_release(c); return 0; } if (text[0] != '\0') { sccp_dev_set_message(d, text, timeout, TRUE, FALSE); } else { sccp_dev_clear_message(d, TRUE); } d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! \brief Stucture to declare a dialplan function: SETMESSAGE */ static char *setmessage_name = "SCCPSetMessage"; static char *old_setmessage_name = "SetMessage"; static char *setmessage_synopsis = "Send a Message to the current Phone"; static char *setmessage_descr = "Usage: SCCPSetMessage(\"Message\"[,timeout])\n" " Send a Message to the Calling Device (and remove after timeout, if timeout is ommited will stay until next/empty message)\n"; int sccp_register_dialplan_functions(void) { int result = 0; /* Register application functions */ result = pbx_register_application(calledparty_name, sccp_app_calledparty, calledparty_synopsis, calledparty_descr, NULL); result |= pbx_register_application(setmessage_name, sccp_app_setmessage, setmessage_synopsis, setmessage_descr, NULL); result |= pbx_register_application(prefcodec_name, sccp_app_prefcodec, prefcodec_synopsis, prefcodec_descr, NULL); /* old names */ result |= pbx_register_application(old_calledparty_name, sccp_app_calledparty, calledparty_synopsis, calledparty_descr, NULL); result |= pbx_register_application(old_setmessage_name, sccp_app_setmessage, setmessage_synopsis, setmessage_descr, NULL); result |= pbx_register_application(old_prefcodec_name, sccp_app_prefcodec, prefcodec_synopsis, prefcodec_descr, NULL); /* Register dialplan functions */ result |= pbx_custom_function_register(&sccpdevice_function, NULL); result |= pbx_custom_function_register(&sccpline_function, NULL); result |= pbx_custom_function_register(&sccpchannel_function, NULL); return result; } int sccp_unregister_dialplan_functions(void) { int result = 0; /* Unregister applications functions */ result = pbx_unregister_application(calledparty_name); result |= pbx_unregister_application(setmessage_name); result |= pbx_unregister_application(prefcodec_name); /* old names */ result |= pbx_unregister_application(old_calledparty_name); result |= pbx_unregister_application(old_setmessage_name); result |= pbx_unregister_application(old_prefcodec_name); /* Unregister dial plan functions */ result |= pbx_custom_function_unregister(&sccpdevice_function); result |= pbx_custom_function_unregister(&sccpline_function); result |= pbx_custom_function_unregister(&sccpchannel_function); return result; }
722,251
./chan-sccp-b/src/sccp_channel.c
/*! * \file sccp_channel.c * \brief SCCP Channel Class * \author Sergio Chersovani <mlists [at] c-net.it> * \date * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ /*! * \remarks Purpose: SCCP Channels * When to use: Only methods directly related to sccp channels should be stored in this source file. * Relationships: SCCP Channels connect Asterisk Channels to SCCP Lines */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") static uint32_t callCount = 1; void __sccp_channel_destroy(sccp_channel_t * channel); void sccp_channel_unsetDevice(sccp_channel_t * channel); AST_MUTEX_DEFINE_STATIC(callCountLock); /*! * \brief Private Channel Data Structure */ struct sccp_private_channel_data { sccp_device_t *device; boolean_t microphone; /*!< Flag to mute the microphone when calling a baby phone */ }; /*! * \brief Helper Function to set to FALSE * \return FALSE */ static boolean_t sccp_always_false(void) { return FALSE; } /*! * \brief Helper Function to set to TRUE * \return TRUE */ static boolean_t sccp_always_true(void) { return TRUE; } /*! * \brief Set Microphone State * \param channel SCCP Channel * \param enabled Enabled as Boolean */ static void sccp_channel_setMicrophoneState(sccp_channel_t * channel, boolean_t enabled) { #if !CS_EXPERIMENTAL sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!(c = sccp_channel_retain(channel))) { return; } if (!(d = sccp_channel_getDevice_retained(channel))) { c = sccp_channel_release(c); return; } c->privateData->microphone = enabled; switch (enabled) { case TRUE: c->isMicrophoneEnabled = sccp_always_true; if ((c->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE)) { sccp_dev_set_microphone(d, SKINNY_STATIONMIC_ON); } break; case FALSE: c->isMicrophoneEnabled = sccp_always_false; if ((c->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE)) { sccp_dev_set_microphone(d, SKINNY_STATIONMIC_OFF); } break; } d = sccp_device_release(d); c = sccp_channel_release(c); #else /* show how WITHREF / GETWITHREF would/could work */ sccp_device_t *d = NULL; WITHREF(channel) { GETWITHREF(d, channel->privateData->device) { channel->privateData->microphone = enabled; pbx_log(LOG_NOTICE, "Within retain section\n"); switch (enabled) { case TRUE: channel->isMicrophoneEnabled = sccp_always_true; if ((channel->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE)) { sccp_dev_set_microphone(d, SKINNY_STATIONMIC_ON); } break; case FALSE: channel->isMicrophoneEnabled = sccp_always_false; if ((channel->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE)) { sccp_dev_set_microphone(d, SKINNY_STATIONMIC_OFF); } break; } } } #endif } /*! * \brief Allocate SCCP Channel on Device * \param l SCCP Line * \param device SCCP Device * \return a *retained* SCCP Channel * * \callgraph * \callergraph * \lock * - callCountLock * - channel */ sccp_channel_t *sccp_channel_allocate(sccp_line_t * l, sccp_device_t * device) { /* this just allocate a sccp channel (not the asterisk channel, for that look at sccp_pbx_channel_allocate) */ sccp_channel_t *channel; char designator[CHANNEL_DESIGNATOR_SIZE]; struct sccp_private_channel_data *private_data; int callid; /* If there is no current line, then we can't make a call in, or out. */ if (!l) { pbx_log(LOG_ERROR, "SCCP: Tried to open channel on a device with no lines\n"); return NULL; } if (device && !device->session) { pbx_log(LOG_ERROR, "SCCP: Tried to open channel on device %s without a session\n", device->id); return NULL; } sccp_mutex_lock(&callCountLock); callid = callCount++; /* callcount limit should be reset at his upper limit :) */ if (callCount == 0xFFFFFFFF) callCount = 1; snprintf(designator, CHANNEL_DESIGNATOR_SIZE, "SCCP/%s-%08X", l->name, callid); sccp_mutex_unlock(&callCountLock); channel = (sccp_channel_t *) sccp_refcount_object_alloc(sizeof(sccp_channel_t), SCCP_REF_CHANNEL, designator, __sccp_channel_destroy); if (!channel) { /* error allocating memory */ pbx_log(LOG_ERROR, "%s: No memory to allocate channel on line %s\n", l->id, l->name); return NULL; } memset(channel, 0, sizeof(sccp_channel_t)); sccp_copy_string(channel->designator, designator, sizeof(channel->designator)); private_data = sccp_malloc(sizeof(struct sccp_private_channel_data)); if (!private_data) { /* error allocating memory */ pbx_log(LOG_ERROR, "%s: No memory to allocate channel private data on line %s\n", l->id, l->name); channel = sccp_channel_release(channel); return NULL; } memset(private_data, 0, sizeof(struct sccp_private_channel_data)); channel->privateData = private_data; channel->privateData->microphone = TRUE; channel->privateData->device = NULL; sccp_mutex_init(&channel->lock); sccp_mutex_lock(&channel->lock); pbx_cond_init(&channel->astStateCond, NULL); /* this is for dialing scheduler */ channel->scheduler.digittimeout = -1; channel->enbloc.digittimeout = GLOB(digittimeout) * 1000; channel->owner = NULL; /* default ringermode SKINNY_RINGTYPE_OUTSIDE. Change it with SCCPRingerMode app */ channel->ringermode = SKINNY_RINGTYPE_OUTSIDE; /* inbound for now. It will be changed later on outgoing calls */ channel->calltype = SKINNY_CALLTYPE_INBOUND; channel->answered_elsewhere = FALSE; /* by default we allow callerid presentation */ channel->callInfo.presentation = CALLERID_PRESENCE_ALLOWED; channel->callid = callid; channel->passthrupartyid = callid ^ 0xFFFFFFFF; channel->line = l; channel->peerIsSCCP = 0; channel->enbloc.digittimeout = GLOB(digittimeout) * 1000; channel->maxBitRate = 15000; if (device) { sccp_channel_setDevice(channel, device); } sccp_line_addChannel(l, channel); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: New channel number: %d on line %s\n", l->id, channel->callid, l->name); #if DEBUG channel->getDevice_retained = __sccp_channel_getDevice_retained; #else channel->getDevice_retained = sccp_channel_getDevice_retained; #endif channel->setDevice = sccp_channel_setDevice; channel->isMicrophoneEnabled = sccp_always_true; channel->setMicrophone = sccp_channel_setMicrophoneState; sccp_mutex_unlock(&channel->lock); return channel; } #if DEBUG /*! * \brief Retrieve Device from Channels->Private Channel Data * \param channel SCCP Channel * \param filename Debug Filename * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Device */ sccp_device_t *__sccp_channel_getDevice_retained(const sccp_channel_t * channel, const char *filename, int lineno, const char *func) #else /*! * \brief Retrieve Device from Channels->Private Channel Data * \param channel SCCP Channel * \return SCCP Device */ sccp_device_t *sccp_channel_getDevice_retained(const sccp_channel_t * channel) #endif { if (channel->privateData && channel->privateData->device) { #if DEBUG channel->privateData->device = sccp_refcount_retain((sccp_device_t *) channel->privateData->device, filename, lineno, func); #else channel->privateData->device = sccp_device_retain((sccp_device_t *) channel->privateData->device); #endif return (sccp_device_t *) channel->privateData->device; } else { return NULL; } } /*! * \brief unSet Device in Channels->Private Channel Data * \param channel SCCP Channel */ void sccp_channel_unsetDevice(sccp_channel_t * channel) { if (channel && channel->privateData && channel->privateData->device) { channel->privateData->device = sccp_device_release((sccp_device_t *) channel->privateData->device); memcpy(&channel->capabilities.audio, &GLOB(global_preferences), sizeof(channel->capabilities.audio)); memcpy(&channel->preferences.audio, &GLOB(global_preferences), sizeof(channel->preferences.audio)); strncpy(channel->currentDeviceId, "SCCP", sizeof(char[StationMaxDeviceNameSize])); } else { pbx_log(LOG_NOTICE, "SCCP: unsetDevice without channel->privateData->device set\n"); } } /*! * \brief Set Device in Channels->Private Channel Data * \param channel SCCP Channel * \param device SCCP Device */ void sccp_channel_setDevice(sccp_channel_t * channel, const sccp_device_t * device) { if (channel->privateData->device == device) { return; } if (NULL != channel->privateData->device) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_4 "SCCP: sccp_channel_setDevice: Auto Release was Necessary\n"); sccp_channel_unsetDevice(channel); } if (NULL != device) { channel->privateData->device = sccp_device_retain((sccp_device_t *) device); memcpy(&channel->preferences.audio, &channel->privateData->device->preferences.audio, sizeof(channel->preferences.audio)); /* our preferred codec list */ memcpy(&channel->capabilities.audio, &channel->privateData->device->capabilities.audio, sizeof(channel->capabilities.audio)); /* our capability codec list */ sccp_copy_string(channel->currentDeviceId, device->id, sizeof(char[StationMaxDeviceNameSize])); } } /*! * \brief recalculating read format for channel * \param channel a *retained* SCCP Channel */ static void sccp_channel_recalculateReadformat(sccp_channel_t * channel) { #ifndef CS_EXPERIMENTAL_RTP if (channel->rtp.audio.writeState != SCCP_RTP_STATUS_INACTIVE && channel->rtp.audio.writeFormat != SKINNY_CODEC_NONE) { //pbx_log(LOG_NOTICE, "we already have a write format, dont change codec\n"); channel->rtp.audio.readFormat = channel->rtp.audio.writeFormat; PBX(rtp_setReadFormat) (channel, channel->rtp.audio.readFormat); return; } #endif /* check if remote set a preferred format that is compatible */ if ((channel->rtp.audio.readState == SCCP_RTP_STATUS_INACTIVE) || !sccp_utils_isCodecCompatible(channel->rtp.audio.readFormat, channel->capabilities.audio, ARRAY_LEN(channel->capabilities.audio)) ) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "%s: recalculateReadformat\n", channel->currentDeviceId); channel->rtp.audio.readFormat = sccp_utils_findBestCodec(channel->preferences.audio, ARRAY_LEN(channel->preferences.audio), channel->capabilities.audio, ARRAY_LEN(channel->capabilities.audio), channel->remoteCapabilities.audio, ARRAY_LEN(channel->remoteCapabilities.audio)); if (channel->rtp.audio.readFormat == SKINNY_CODEC_NONE) { channel->rtp.audio.readFormat = SKINNY_CODEC_WIDEBAND_256K; char s1[512]; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "can not calculate readFormat, fall back to %s (%d)\n", sccp_multiple_codecs2str(s1, sizeof(s1) - 1, &channel->rtp.audio.readFormat, 1), channel->rtp.audio.readFormat); } //PBX(set_nativeAudioFormats)(channel, channel->preferences.audio, ARRAY_LEN(channel->preferences.audio)); PBX(rtp_setReadFormat) (channel, channel->rtp.audio.readFormat); } char s1[512], s2[512], s3[512], s4[512]; sccp_log((DEBUGCAT_CODEC | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, \ncapabilities: %s \npreferences: %s \nremote caps: %s \nREAD: %s\n", channel->line->name, channel->callid, sccp_multiple_codecs2str(s1, sizeof(s1) - 1, channel->capabilities.audio, ARRAY_LEN(channel->capabilities.audio)), sccp_multiple_codecs2str(s3, sizeof(s3) - 1, channel->preferences.audio, ARRAY_LEN(channel->preferences.audio)), sccp_multiple_codecs2str(s4, sizeof(s4) - 1, channel->remoteCapabilities.audio, ARRAY_LEN(channel->remoteCapabilities.audio)), sccp_multiple_codecs2str(s2, sizeof(s2) - 1, &channel->rtp.audio.readFormat, 1) ); } /*! * \brief recalculating write format for channel * \param channel a *retained* SCCP Channel */ static void sccp_channel_recalculateWriteformat(sccp_channel_t * channel) { //pbx_log(LOG_NOTICE, "writeState %d\n", channel->rtp.audio.writeState); #ifndef CS_EXPERIMENTAL_RTP if (channel->rtp.audio.readState != SCCP_RTP_STATUS_INACTIVE && channel->rtp.audio.readFormat != SKINNY_CODEC_NONE) { channel->rtp.audio.writeFormat = channel->rtp.audio.readFormat; PBX(rtp_setWriteFormat) (channel, channel->rtp.audio.writeFormat); return; } #endif /* check if remote set a preferred format that is compatible */ if ((channel->rtp.audio.writeState == SCCP_RTP_STATUS_INACTIVE) || !sccp_utils_isCodecCompatible(channel->rtp.audio.writeFormat, channel->capabilities.audio, ARRAY_LEN(channel->capabilities.audio)) ) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "%s: recalculateWriteformat\n", channel->currentDeviceId); channel->rtp.audio.writeFormat = sccp_utils_findBestCodec(channel->preferences.audio, ARRAY_LEN(channel->preferences.audio), channel->capabilities.audio, ARRAY_LEN(channel->capabilities.audio), channel->remoteCapabilities.audio, ARRAY_LEN(channel->remoteCapabilities.audio)); if (channel->rtp.audio.writeFormat == SKINNY_CODEC_NONE) { channel->rtp.audio.writeFormat = SKINNY_CODEC_WIDEBAND_256K; char s1[512]; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "can not calculate writeFormat, fall back to %s (%d)\n", sccp_multiple_codecs2str(s1, sizeof(s1) - 1, &channel->rtp.audio.writeFormat, 1), channel->rtp.audio.writeFormat); } //PBX(set_nativeAudioFormats)(channel, channel->preferences.audio, ARRAY_LEN(channel->preferences.audio)); PBX(rtp_setWriteFormat) (channel, channel->rtp.audio.writeFormat); } else { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "%s: audio.writeState already active %d\n", channel->currentDeviceId, channel->rtp.audio.writeState); } char s1[512], s2[512], s3[512], s4[512]; sccp_log((DEBUGCAT_CODEC | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, \ncapabilities: %s \npreferences: %s \nremote caps: %s \n\tWRITE: %s\n", channel->line->name, channel->callid, sccp_multiple_codecs2str(s1, sizeof(s1) - 1, channel->capabilities.audio, ARRAY_LEN(channel->capabilities.audio)), sccp_multiple_codecs2str(s3, sizeof(s3) - 1, channel->preferences.audio, ARRAY_LEN(channel->preferences.audio)), sccp_multiple_codecs2str(s4, sizeof(s4) - 1, channel->remoteCapabilities.audio, ARRAY_LEN(channel->remoteCapabilities.audio)), sccp_multiple_codecs2str(s2, sizeof(s2) - 1, &channel->rtp.audio.writeFormat, 1) ); } void sccp_channel_updateChannelDesignator(sccp_channel_t * c) { if (c) { if (c->callid) { if (c->line && c->line->name) { snprintf(c->designator, CHANNEL_DESIGNATOR_SIZE, "SCCP/%s-%08x", c->line->name, c->callid); } else { snprintf(c->designator, CHANNEL_DESIGNATOR_SIZE, "SCCP/%s-%08x", "UNDEF", c->callid); } } else { snprintf(c->designator, CHANNEL_DESIGNATOR_SIZE, "SCCP/UNDEF-UNDEF"); } sccp_refcount_updateIdentifier(c, c->designator); } } /*! * \brief Update Channel Capability * \param channel a *retained* SCCP Channel */ void sccp_channel_updateChannelCapability(sccp_channel_t * channel) { sccp_channel_recalculateReadformat(channel); sccp_channel_recalculateWriteformat(channel); } /*! * \brief Get Active Channel * \param d SCCP Device * \return SCCP Channel */ sccp_channel_t *sccp_channel_get_active(const sccp_device_t * d) { sccp_channel_t *channel; if (!d || !d->active_channel) { return NULL; } sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Getting the active channel on device.\n", d->id); if (!(channel = sccp_channel_retain(d->active_channel))) { return NULL; } if (channel->state == SCCP_CHANNELSTATE_DOWN) { channel = sccp_channel_release(channel); return NULL; } return channel; } /*! * \brief Set SCCP Channel to Active * \param d SCCP Device * \param channel SCCP Channel * * \lock * - device */ void sccp_channel_set_active(sccp_device_t * d, sccp_channel_t * channel) { sccp_device_t *device = NULL; if ((device = sccp_device_retain(d))) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Set the active channel %d on device\n", DEV_ID_LOG(d), (channel) ? channel->callid : 0); if (device->active_channel) { device->active_channel->line->statistic.numberOfActiveChannels--; device->active_channel = sccp_channel_release(device->active_channel); } if (channel) { device->active_channel = sccp_channel_retain(channel); sccp_channel_updateChannelDesignator(channel); sccp_dev_set_activeline(device, channel->line); device->active_channel->line->statistic.numberOfActiveChannels++; } device = sccp_device_release(device); } } /*! * \brief Send Call Information to Device/Channel * * Wrapper function that calls sccp_channel_send_staticCallinfo or sccp_channel_send_dynamicCallinfo * * \param device SCCP Device * \param channel SCCP Channel * * \callgraph * \callergraph * * \todo find a difference solution for sccp_conference callinfo update */ void sccp_channel_send_callinfo(const sccp_device_t * device, const sccp_channel_t * channel) { uint8_t instance = 0; if (device && channel && channel->callid) { sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: send callInfo of callid %d\n", DEV_ID_LOG(device), channel->callid); if (device->protocol && device->protocol->sendCallInfo) { instance = sccp_device_find_index_for_line(device, channel->line->name); device->protocol->sendCallInfo(device, channel, instance); } } } /*! * \brief Send Dialed Number to SCCP Channel device * \param channel SCCP Channel * * \callgraph * \callergraph */ void sccp_channel_send_callinfo2(sccp_channel_t * channel) { sccp_device_t *d = sccp_channel_getDevice_retained(channel); sccp_line_t *line = sccp_line_retain(channel->line); if (NULL != d) { sccp_channel_send_callinfo(d, channel); d = sccp_device_release(d); } else { sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { d = sccp_device_retain(linedevice->device); sccp_channel_send_callinfo(d, channel); d = sccp_device_release(d); } SCCP_LIST_UNLOCK(&line->devices); } line = line ? sccp_line_release(line) : NULL; } /*! * \brief Set Call State for SCCP Channel sccp_channel, and Send this State to SCCP Device d. * \param channel SCCP Channel * \param state channel state * * \callgraph * \callergraph */ void sccp_channel_setSkinnyCallstate(sccp_channel_t * channel, skinny_callstate_t state) { channel->previousChannelState = channel->state; channel->state = state; } /*! * \brief Set CallingParty on SCCP Channel c * \param channel SCCP Channel * * \callgraph * \callergraph */ void sccp_channel_display_callInfo(sccp_channel_t * channel) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x callInfo:\n", channel->line->name, channel->callid); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 " - calledParty: %s <%s>, valid: %s\n", (channel->callInfo.calledPartyName) ? channel->callInfo.calledPartyName : "", (channel->callInfo.calledPartyNumber) ? channel->callInfo.calledPartyNumber : "", (channel->callInfo.calledParty_valid) ? "TRUE" : "FALSE"); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 " - callingParty: %s <%s>, valid: %s\n", (channel->callInfo.callingPartyName) ? channel->callInfo.callingPartyName : "", (channel->callInfo.callingPartyNumber) ? channel->callInfo.callingPartyNumber : "", (channel->callInfo.callingParty_valid) ? "TRUE" : "FALSE"); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 " - originalCalledParty: %s <%s>, valid: %s\n", (channel->callInfo.originalCalledPartyName) ? channel->callInfo.originalCalledPartyName : "", (channel->callInfo.originalCalledPartyNumber) ? channel->callInfo.originalCalledPartyNumber : "", (channel->callInfo.originalCalledParty_valid) ? "TRUE" : "FALSE"); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 " - originalCallingParty: %s <%s>, valid: %s\n", (channel->callInfo.originalCallingPartyName) ? channel->callInfo.originalCallingPartyName : "", (channel->callInfo.originalCallingPartyNumber) ? channel->callInfo.originalCallingPartyNumber : "", (channel->callInfo.originalCallingParty_valid) ? "TRUE" : "FALSE"); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 " - lastRedirectingParty: %s <%s>, valid: %s\n", (channel->callInfo.lastRedirectingPartyName) ? channel->callInfo.lastRedirectingPartyName : "", (channel->callInfo.lastRedirectingPartyNumber) ? channel->callInfo.lastRedirectingPartyNumber : "", (channel->callInfo.lastRedirectingParty_valid) ? "TRUE" : "FALSE"); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 " - originalCalledPartyRedirectReason: %d, lastRedirectingReason: %d, CallInfo Presentation: %s\n\n", channel->callInfo.originalCdpnRedirectReason, channel->callInfo.lastRedirectingReason, channel->callInfo.presentation ? "ALLOWED" : "FORBIDDEN"); } /*! * \brief Set CallingParty on SCCP Channel c * \param channel SCCP Channel * \param name Name as char * \param number Number as char * * \callgraph * \callergraph */ void sccp_channel_set_callingparty(sccp_channel_t * channel, char *name, char *number) { if (!channel) { return; } if (name && strncmp(name, channel->callInfo.callingPartyName, StationMaxNameSize - 1)) { sccp_copy_string(channel->callInfo.callingPartyName, name, sizeof(channel->callInfo.callingPartyName)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Set callingParty Name %s on channel %d\n", channel->currentDeviceId, channel->callInfo.callingPartyName, channel->callid); } if (number && strncmp(number, channel->callInfo.callingPartyNumber, StationMaxDirnumSize - 1)) { sccp_copy_string(channel->callInfo.callingPartyNumber, number, sizeof(channel->callInfo.callingPartyNumber)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Set callingParty Number %s on channel %d\n", channel->currentDeviceId, channel->callInfo.callingPartyNumber, channel->callid); channel->callInfo.callingParty_valid = 1; } } /*! * \brief Set Original Calling Party on SCCP Channel c (Used during Forward) * \param channel SCCP Channel * \param name Name as char * \param number Number as char * \return TRUE/FALSE - TRUE if info changed * * \callgraph * \callergraph */ boolean_t sccp_channel_set_originalCallingparty(sccp_channel_t * channel, char *name, char *number) { boolean_t changed = FALSE; if (!channel) { return FALSE; } if (name && strncmp(name, channel->callInfo.originalCallingPartyName, StationMaxNameSize - 1)) { sccp_copy_string(channel->callInfo.originalCallingPartyName, name, sizeof(channel->callInfo.originalCallingPartyName)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Set original Calling Party Name %s on channel %d\n", channel->currentDeviceId, channel->callInfo.originalCallingPartyName, channel->callid); changed = TRUE; } if (number && strncmp(number, channel->callInfo.originalCallingPartyNumber, StationMaxDirnumSize - 1)) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, number, sizeof(channel->callInfo.originalCallingPartyNumber)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Set original Calling Party Number %s on channel %d\n", channel->currentDeviceId, channel->callInfo.originalCallingPartyNumber, channel->callid); changed = TRUE; channel->callInfo.originalCallingParty_valid = 1; } return changed; } /*! * \brief Set CalledParty on SCCP Channel c * \param channel SCCP Channel * \param name Called Party Name * \param number Called Party Number * * \callgraph * \callergraph */ void sccp_channel_set_calledparty(sccp_channel_t * channel, char *name, char *number) { if (!channel) { return; } if (!sccp_strlen_zero(name)) { sccp_copy_string(channel->callInfo.calledPartyName, name, sizeof(channel->callInfo.calledPartyNumber)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: (sccp_channel_set_calledparty) Set calledParty Name %s on channel %d\n", channel->currentDeviceId, channel->callInfo.calledPartyName, channel->callid); } else { channel->callInfo.calledPartyName[0] = '\0'; } if (!sccp_strlen_zero(number)) { sccp_copy_string(channel->callInfo.calledPartyNumber, number, sizeof(channel->callInfo.callingPartyNumber)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: (sccp_channel_set_calledparty) Set calledParty Number %s on channel %d\n", channel->currentDeviceId, channel->callInfo.calledPartyNumber, channel->callid); } else { channel->callInfo.calledPartyNumber[0] = '\0'; } if (!sccp_strlen_zero(channel->callInfo.calledPartyName) && !sccp_strlen_zero(channel->callInfo.calledPartyNumber)) { channel->callInfo.calledParty_valid = 1; } } /*! * \brief Set Original CalledParty on SCCP Channel c (Used during Forward) * \param channel SCCP Channel * \param name Name as char * \param number Number as char * * \callgraph * \callergraph */ boolean_t sccp_channel_set_originalCalledparty(sccp_channel_t * channel, char *name, char *number) { boolean_t changed = FALSE; if (!channel) { return FALSE; } if (name && strncmp(name, channel->callInfo.originalCalledPartyName, StationMaxNameSize - 1)) { sccp_copy_string(channel->callInfo.originalCalledPartyName, name, sizeof(channel->callInfo.originalCalledPartyName)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Set originalCalledParty Name %s on channel %d\n", channel->currentDeviceId, channel->callInfo.originalCalledPartyName, channel->callid); changed = TRUE; } if (number && strncmp(number, channel->callInfo.originalCalledPartyNumber, StationMaxDirnumSize - 1)) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, number, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Set originalCalledParty Number %s on channel %d\n", channel->currentDeviceId, channel->callInfo.originalCalledPartyNumber, channel->callid); changed = TRUE; channel->callInfo.originalCalledParty_valid = 1; } return changed; } /*! * \brief Request Call Statistics for SCCP Channel * \param channel SCCP Channel */ void sccp_channel_StatisticsRequest(sccp_channel_t * channel) { sccp_moo_t *r; sccp_device_t *d; if (!channel || !(d = sccp_channel_getDevice_retained(channel))) { return; } //TODO use protocol implementation if (d->protocol->version < 19) { REQ(r, ConnectionStatisticsReq); } else { REQ(r, ConnectionStatisticsReq_V19); } /*! \todo We need to test what we have to copy in the DirectoryNumber */ if (channel->calltype == SKINNY_CALLTYPE_OUTBOUND) sccp_copy_string(r->msg.ConnectionStatisticsReq.DirectoryNumber, channel->callInfo.calledPartyNumber, sizeof(r->msg.ConnectionStatisticsReq.DirectoryNumber)); else sccp_copy_string(r->msg.ConnectionStatisticsReq.DirectoryNumber, channel->callInfo.callingPartyNumber, sizeof(r->msg.ConnectionStatisticsReq.DirectoryNumber)); r->msg.ConnectionStatisticsReq.lel_callReference = htolel((channel) ? channel->callid : 0); r->msg.ConnectionStatisticsReq.lel_StatsProcessing = htolel(SKINNY_STATSPROCESSING_CLEAR); sccp_dev_send(d, r); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Device is Requesting CallStatisticsAndClear\n", DEV_ID_LOG(d)); d = sccp_device_release(d); } /*! * \brief Tell Device to Open a RTP Receive Channel * * At this point we choose the codec for receive channel and tell them to device. * We will get a OpenReceiveChannelAck message that includes all information. * * \param channel a locked SCCP Channel * * \lock * - see sccp_channel_updateChannelCapability() * - see sccp_channel_start_rtp() * - see sccp_device_find_index_for_line() * - see sccp_dev_starttone() * - see sccp_dev_send() */ void sccp_channel_openreceivechannel(sccp_channel_t * channel) { sccp_device_t *d = NULL; uint16_t instance; if (!channel || (!(d = sccp_channel_getDevice_retained(channel)))) { return; } /* Mute mic feature: If previously set, mute the microphone prior receiving media is already open. */ /* This must be done in this exact order to work on popular phones like the 7975. It must also be done in other places for other phones. */ if (!channel->isMicrophoneEnabled()) { sccp_dev_set_microphone(d, SKINNY_STATIONMIC_OFF); } /* calculating format at this point doesn work, because asterisk needs a nativeformat to be set before dial */ #ifdef CS_EXPERIMENTAL_CODEC sccp_channel_recalculateWriteformat(channel); #endif sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: channel %s payloadType %d\n", DEV_ID_LOG(d), PBX(getChannelName) (channel), channel->rtp.audio.writeFormat); /* create the rtp stuff. It must be create before setting the channel AST_STATE_UP. otherwise no audio will be played */ sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Ask the device to open a RTP port on channel %d. Codec: %s, echocancel: %s\n", d->id, channel->callid, codec2str(channel->rtp.audio.writeFormat), channel->line->echocancel ? "ON" : "OFF"); if (!channel->rtp.audio.rtp && !sccp_rtp_createAudioServer(channel)) { pbx_log(LOG_WARNING, "%s: Error opening RTP for channel %s-%08X\n", DEV_ID_LOG(d), channel->line->name, channel->callid); instance = sccp_device_find_index_for_line(d, channel->line->name); sccp_dev_starttone(d, SKINNY_TONE_REORDERTONE, instance, channel->callid, 0); d = sccp_device_release(d); return; } else { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Started RTP on channel %s-%08X\n", DEV_ID_LOG(d), channel->line->name, channel->callid); } if (channel->owner) { PBX(set_nativeAudioFormats) (channel, &channel->rtp.audio.writeFormat, 1); PBX(rtp_setWriteFormat) (channel, channel->rtp.audio.writeFormat); } sccp_log((DEBUGCAT_RTP | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Open receive channel with format %s[%d], payload %d, echocancel: %d, passthrupartyid: %u, callid: %u\n", DEV_ID_LOG(d), codec2str(channel->rtp.audio.writeFormat), channel->rtp.audio.writeFormat, channel->rtp.audio.writeFormat, channel->line->echocancel, channel->passthrupartyid, channel->callid); channel->rtp.audio.writeState = SCCP_RTP_STATUS_PROGRESS; d->protocol->sendOpenReceiveChannel(d, channel); #ifdef CS_SCCP_VIDEO if (sccp_device_isVideoSupported(d)) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: We can have video, try to start vrtp\n", DEV_ID_LOG(d)); if (!channel->rtp.video.rtp && !sccp_rtp_createVideoServer(channel)) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: can not start vrtp\n", DEV_ID_LOG(d)); } else { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: video rtp started\n", DEV_ID_LOG(d)); sccp_channel_startMultiMediaTransmission(channel); } } #endif d = sccp_device_release(d); } /*! * \brief Open Multi Media Channel (Video) on Channel * \param channel SCCP Channel */ void sccp_channel_openMultiMediaChannel(sccp_channel_t * channel) { uint32_t skinnyFormat; int payloadType; uint8_t lineInstance; int bitRate = 1500; sccp_device_t *d = NULL; if (!(d = channel->privateData->device)) { return; } if ((channel->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE)) { return; } if (!(d = sccp_channel_getDevice_retained(channel))) { return; } channel->rtp.video.writeState |= SCCP_RTP_STATUS_PROGRESS; skinnyFormat = channel->rtp.video.writeFormat; if (skinnyFormat == 0) { pbx_log(LOG_NOTICE, "SCCP: Unable to find skinny format for %d\n", channel->rtp.video.writeFormat); d = sccp_device_release(d); return; } payloadType = sccp_rtp_get_payloadType(&channel->rtp.video, channel->rtp.video.writeFormat); lineInstance = sccp_device_find_index_for_line(d, channel->line->name); sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Open receive multimedia channel with format %s[%d] skinnyFormat %s[%d], payload %d\n", DEV_ID_LOG(d), codec2str(channel->rtp.video.writeFormat), channel->rtp.video.writeFormat, codec2str(skinnyFormat), skinnyFormat, payloadType); d->protocol->sendOpenMultiMediaChannel(d, channel, skinnyFormat, payloadType, lineInstance, bitRate); d = sccp_device_release(d); } /*! * \brief Start Multi Media Transmission (Video) on Channel * \param channel SCCP Channel */ void sccp_channel_startMultiMediaTransmission(sccp_channel_t * channel) { int payloadType; sccp_device_t *d = NULL; struct sockaddr_in sin; struct ast_hostent ahp; struct hostent *hp; // int packetSize; channel->rtp.video.readFormat = SKINNY_CODEC_H264; //// packetSize = 3840; // packetSize = 1920; int bitRate = channel->maxBitRate; if (!channel->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: can't start vrtp media transmission, maybe channel is down %s-%08X\n", channel->currentDeviceId, channel->line->name, channel->callid); return; } if ((d = sccp_channel_getDevice_retained(channel))) { channel->preferences.video[0] = SKINNY_CODEC_H264; //channel->preferences.video[0] = SKINNY_CODEC_H263; channel->rtp.video.readFormat = sccp_utils_findBestCodec(channel->preferences.video, ARRAY_LEN(channel->preferences.video), channel->capabilities.video, ARRAY_LEN(channel->capabilities.video), channel->remoteCapabilities.video, ARRAY_LEN(channel->remoteCapabilities.video)); if (channel->rtp.video.readFormat == 0) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: fall back to h264\n", DEV_ID_LOG(d)); channel->rtp.video.readFormat = SKINNY_CODEC_H264; } /* lookup payloadType */ payloadType = sccp_rtp_get_payloadType(&channel->rtp.video, channel->rtp.video.readFormat); //! \todo handle payload error //! \todo use rtp codec map //check if bind address is an global bind address if (!channel->rtp.video.phone_remote.sin_addr.s_addr) { channel->rtp.video.phone_remote.sin_addr.s_addr = d->session->ourip.s_addr; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: using payload %d\n", DEV_ID_LOG(d), payloadType); sccp_rtp_getUs(&channel->rtp.video, &sin); if (d->nat) { if (GLOB(externip.sin_addr.s_addr)) { if (GLOB(externexpire) && (time(NULL) >= GLOB(externexpire))) { time(&GLOB(externexpire)); GLOB(externexpire) += GLOB(externrefresh); if ((hp = pbx_gethostbyname(GLOB(externhost), &ahp))) { memcpy(&GLOB(externip.sin_addr), hp->h_addr, sizeof(GLOB(externip.sin_addr))); } else pbx_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", GLOB(externhost)); } memcpy(&sin.sin_addr, &GLOB(externip.sin_addr), 4); } } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Tell device to send VRTP media to %s:%d with codec: %s(%d), payloadType %d, tos %d\n", d->id, pbx_inet_ntoa(channel->rtp.video.phone_remote.sin_addr), ntohs(channel->rtp.video.phone_remote.sin_port), codec2str(channel->rtp.video.readFormat), channel->rtp.video.readFormat, payloadType, d->audio_tos); d->protocol->sendStartMultiMediaTransmission(d, channel, payloadType, bitRate, sin); d = sccp_device_release(d); PBX(queue_control) (channel->owner, AST_CONTROL_VIDUPDATE); } } /*! * \brief Tell a Device to Start Media Transmission. * * We choose codec according to sccp_channel->format. * * \param channel SCCP Channel * \note rtp should be started before, otherwise we do not start transmission */ void sccp_channel_startmediatransmission(sccp_channel_t * channel) { sccp_device_t *d = NULL; if (!channel->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: can't start rtp media transmission, maybe channel is down %s-%08X\n", channel->currentDeviceId, channel->line->name, channel->callid); return; } if ((d = sccp_channel_getDevice_retained(channel))) { /* Mute mic feature: If previously set, mute the microphone after receiving of media is already open, but before starting to send to rtp. */ /* This must be done in this exact order to work also on newer phones like the 8945. It must also be done in other places for other phones. */ if (!channel->isMicrophoneEnabled()) { sccp_dev_set_microphone(d, SKINNY_STATIONMIC_OFF); } /*! \todo move the refreshing of the hostname->ip-address to another location (for example scheduler) to re-enable dns hostname lookup */ if (d->nat) { if (!sccp_strlen_zero(GLOB(externhost))) { pbx_log(LOG_NOTICE, "Device is behind NAT use external hostname translation: %s\n", GLOB(externhost)); struct ast_hostent ahp; struct hostent *hp; // replace us.sin_addr if we are natted if (GLOB(externip.sin_addr.s_addr)) { if (GLOB(externexpire) && (time(NULL) >= GLOB(externexpire))) { time(&GLOB(externexpire)); GLOB(externexpire) += GLOB(externrefresh); if ((hp = pbx_gethostbyname(GLOB(externhost), &ahp))) { memcpy(&GLOB(externip.sin_addr), hp->h_addr, sizeof(GLOB(externip.sin_addr))); } else { pbx_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", GLOB(externhost)); } } memcpy(&channel->rtp.audio.phone_remote.sin_addr, &GLOB(externip.sin_addr), 4); } } else if (GLOB(externip.sin_addr.s_addr)) { pbx_log(LOG_NOTICE, "Device is behind NAT use external address: %s\n", pbx_inet_ntoa(GLOB(externip.sin_addr))); memcpy(&channel->rtp.audio.phone_remote.sin_addr, &GLOB(externip.sin_addr), 4); } } else { /** \todo move this to the initial part, otherwise we overwrite direct rtp destination */ channel->rtp.audio.phone_remote.sin_addr.s_addr = d->session->ourip.s_addr; } #ifdef CS_EXPERIMENTAL_CODEC sccp_channel_recalculateReadformat(channel); #endif if (channel->owner) { PBX(set_nativeAudioFormats) (channel, &channel->rtp.audio.readFormat, 1); PBX(rtp_setReadFormat) (channel, channel->rtp.audio.readFormat); } channel->rtp.audio.readState |= SCCP_RTP_STATUS_PROGRESS; d->protocol->sendStartMediaTransmission(d, channel); char cbuf1[128] = ""; char cbuf2[128] = ""; sprintf(cbuf1, "%15s:%d", pbx_inet_ntoa(channel->rtp.audio.phone.sin_addr), ntohs(channel->rtp.audio.phone.sin_port)); sprintf(cbuf2, "%15s:%d", pbx_inet_ntoa(channel->rtp.audio.phone_remote.sin_addr), ntohs(channel->rtp.audio.phone_remote.sin_port)); sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Tell Phone to send RTP/UDP media from:%s to %s (NAT: %s)\n", DEV_ID_LOG(d), cbuf1, cbuf2, d->nat ? "yes" : "no"); sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Using codec: %s(%d), TOS %d, Silence Suppression: %s for call with PassThruId: %u and CallID: %u\n", DEV_ID_LOG(d), codec2str(channel->rtp.audio.readFormat), channel->rtp.audio.readFormat, d->audio_tos, channel->line->silencesuppression ? "ON" : "OFF", channel->passthrupartyid, channel->callid); d = sccp_device_release(d); } else { pbx_log(LOG_ERROR, "SCCP: (sccp_channel_startmediatransmission) Could not retrieve device from channel\n"); } } /*! * \brief Tell Device to Close an RTP Receive Channel and Stop Media Transmission * \param channel SCCP Channel * \note sccp_channel_stopmediatransmission is explicit call within this function! * * \lock * - channel * - see sccp_dev_send() */ void sccp_channel_closereceivechannel(sccp_channel_t * channel) { sccp_moo_t *r; sccp_device_t *d = NULL; if (!channel) { return; } if ((d = sccp_channel_getDevice_retained(channel))) { REQ(r, CloseReceiveChannel); r->msg.CloseReceiveChannel.lel_conferenceId = htolel(channel->callid); r->msg.CloseReceiveChannel.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.CloseReceiveChannel.lel_conferenceId1 = htolel(channel->callid); sccp_dev_send(d, r); sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Close receivechannel on channel %d\n", DEV_ID_LOG(d), channel->callid); } channel->rtp.audio.readState = SCCP_RTP_STATUS_INACTIVE; if (d && channel->rtp.video.rtp) { REQ(r, CloseMultiMediaReceiveChannel); r->msg.CloseMultiMediaReceiveChannel.lel_conferenceId = htolel(channel->callid); r->msg.CloseMultiMediaReceiveChannel.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.CloseMultiMediaReceiveChannel.lel_conferenceId1 = htolel(channel->callid); sccp_dev_send(d, r); } d = d ? sccp_device_release(d) : NULL; sccp_channel_stopmediatransmission(channel); } /*! * \brief Tell device to Stop Media Transmission. * * Also RTP will be Stopped/Destroyed and Call Statistic is requested. * \param channel SCCP Channel * * \lock * - channel * - see sccp_channel_stop_rtp() * - see sccp_dev_send() */ void sccp_channel_stopmediatransmission(sccp_channel_t * channel) { sccp_moo_t *r; sccp_device_t *d = NULL; if (!channel) { return; } if ((d = sccp_channel_getDevice_retained(channel))) { REQ(r, StopMediaTransmission); r->msg.StopMediaTransmission.lel_conferenceId = htolel(channel->callid); r->msg.StopMediaTransmission.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.StopMediaTransmission.lel_conferenceId1 = htolel(channel->callid); sccp_dev_send(d, r); sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Stop media transmission on channel %d\n", DEV_ID_LOG(d), channel->callid); } // stopping rtp if (channel->rtp.audio.rtp) { sccp_rtp_stop(channel); } channel->rtp.audio.readState = SCCP_RTP_STATUS_INACTIVE; // stopping vrtp if (d && channel->rtp.video.rtp) { REQ(r, StopMultiMediaTransmission); r->msg.StopMultiMediaTransmission.lel_conferenceId = htolel(channel->callid); r->msg.StopMultiMediaTransmission.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.StopMultiMediaTransmission.lel_conferenceId1 = htolel(channel->callid); sccp_dev_send(d, r); } d = d ? sccp_device_release(d) : NULL; /* requesting statistics */ sccp_channel_StatisticsRequest(channel); } /*! * \brief Hangup this channel. * \param channel *retained* SCCP Channel * * \callgraph * \callergraph * * \lock * - line->channels * - see sccp_channel_endcall() */ void sccp_channel_endcall(sccp_channel_t * channel) { sccp_device_t *d = NULL; if (!channel || !channel->line) { pbx_log(LOG_WARNING, "No channel or line or device to hangup\n"); return; } /* end all call forwarded channels (our children) */ /* should not be necessary here. Should have been handled in sccp_pbx_softswitch / sccp_pbx_answer / sccp_pbx_hangup already */ sccp_channel_t *c; SCCP_LIST_LOCK(&channel->line->channels); SCCP_LIST_TRAVERSE(&channel->line->channels, c, list) { if (c->parentChannel == channel) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Send Hangup to CallForwarding Channel %s-%08X\n", DEV_ID_LOG(d), c->line->name, c->callid); // No need to lock because sccp_channel->line->channels is already locked. sccp_channel_endcall(c); c->parentChannel = sccp_channel_release(c->parentChannel); // release from sccp_channel_forward retain } } SCCP_LIST_UNLOCK(&channel->line->channels); /* this is a station active endcall or onhook */ if ((d = sccp_channel_getDevice_retained(channel))) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_2 "%s: Ending call %d on line %s (%s)\n", DEV_ID_LOG(d), channel->callid, channel->line->name, sccp_indicate2str(channel->state)); if (channel->privateData->device) { if (GLOB(transfer_on_hangup)) { /* Complete transfer when one is in progress */ if (((channel->privateData->device->transferChannels.transferee) && (channel->privateData->device->transferChannels.transferer)) && ((channel == channel->privateData->device->transferChannels.transferee) || (channel == channel->privateData->device->transferChannels.transferer)) ) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: In the middle of a Transfer. Going to transfer completion\n", (d && d->id) ? d->id : "SCCP"); sccp_channel_transfer_complete(channel->privateData->device->transferChannels.transferer); d = sccp_device_release(d); return; } } sccp_channel_transfer_cancel(channel->privateData->device, channel); sccp_channel_transfer_release(channel->privateData->device, channel); } if (channel->owner) { PBX(requestHangup) (channel->owner); } else { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: No Asterisk channel to hangup for sccp channel %d on line %s\n", DEV_ID_LOG(d), channel->callid, channel->line->name); } sccp_log((DEBUGCAT_CORE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Call %d Ended on line %s (%s)\n", DEV_ID_LOG(d), channel->callid, channel->line->name, sccp_indicate2str(channel->state)); d = sccp_device_release(d); } else { sccp_log((DEBUGCAT_CORE | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_2 "SCCP: Ending call %d on line %s (%s)\n", channel->callid, channel->line->name, sccp_indicate2str(channel->state)); if (channel->owner) { PBX(requestHangup) (channel->owner); } else { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: No Asterisk channel to hangup for sccp channel %d on line %s\n", DEV_ID_LOG(d), channel->callid, channel->line->name); } } } /*! * \brief Allocate a new Outgoing Channel. * * \param l SCCP Line that owns this channel * \param device SCCP Device that owns this channel * \param dial Dialed Number as char * \param calltype Calltype as int * \param linkedId PBX LinkedId which unites related calls under one specific Id. * \return a *retained* SCCP Channel or NULL if something is wrong * * \callgraph * \callergraph * * \lock * - channel * - see sccp_channel_set_active() * - see sccp_indicate_nolock() */ sccp_channel_t *sccp_channel_newcall(sccp_line_t * l, sccp_device_t * device, const char *dial, uint8_t calltype, const char *linkedId) { /* handle outgoing calls */ sccp_channel_t *channel; if (!l) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if a line is not defined!\n"); return NULL; } if (!device) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if a device is not defined!\n"); return NULL; } /* look if we have a call to put on hold */ if ((channel = sccp_channel_get_active(device)) #if CS_SCCP_CONFERENCE && (NULL == channel->conference) #endif ) { /* there is an active call, let's put it on hold first */ int ret = sccp_channel_hold(channel); channel = sccp_channel_release(channel); if (!ret) return NULL; } channel = sccp_channel_allocate(l, device); if (!channel) { pbx_log(LOG_ERROR, "%s: Can't allocate SCCP channel for line %s\n", device->id, l->name); return NULL; } channel->ss_action = SCCP_SS_DIAL; /* softswitch will catch the number to be dialed */ channel->ss_data = 0; /* nothing to pass to action */ channel->calltype = calltype; sccp_channel_set_active(device, channel); /* copy the number to dial in the ast->exten */ if (dial) { sccp_copy_string(channel->dialedNumber, dial, sizeof(channel->dialedNumber)); sccp_indicate(device, channel, SCCP_CHANNELSTATE_SPEEDDIAL); } else { sccp_indicate(device, channel, SCCP_CHANNELSTATE_OFFHOOK); } /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(channel, linkedId)) { pbx_log(LOG_WARNING, "%s: Unable to allocate a new channel for line %s\n", device->id, l->name); sccp_indicate(device, channel, SCCP_CHANNELSTATE_CONGESTION); return channel; } PBX(set_callstate) (channel, AST_STATE_OFFHOOK); if (device->earlyrtp == SCCP_CHANNELSTATE_OFFHOOK && !channel->rtp.audio.rtp) { sccp_channel_openreceivechannel(channel); } if (dial) { sccp_pbx_softswitch(channel); return channel; } if ((channel->scheduler.digittimeout = sccp_sched_add(GLOB(firstdigittimeout) * 1000, sccp_pbx_sched_dial, channel)) < 0) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: Unable to schedule dialing in '%d' ms\n", GLOB(firstdigittimeout)); } return channel; } /*! * \brief Answer an Incoming Call. * \param device SCCP Device who answers * \param channel incoming *retained* SCCP channel * \todo handle codec choose * * \callgraph * \callergraph * * \lock * - line * - line->channels * - see sccp_channel_endcall() */ void sccp_channel_answer(const sccp_device_t * device, sccp_channel_t * channel) { sccp_line_t *l; skinny_codec_t preferredCodec = SKINNY_CODEC_NONE; #ifdef CS_AST_HAS_FLAG_MOH PBX_CHANNEL_TYPE *pbx_bridged_channel; #endif if (!channel || !channel->line) { pbx_log(LOG_ERROR, "SCCP: Channel %d has no line\n", (channel ? channel->callid : 0)); return; } if (!channel->owner) { pbx_log(LOG_ERROR, "SCCP: Channel %d has no owner\n", channel->callid); return; } l = sccp_line_retain(channel->line); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Answer channel %s-%08X\n", DEV_ID_LOG(device), l->name, channel->callid); if (!device) { pbx_log(LOG_ERROR, "SCCP: Channel %d has no device\n", (channel ? channel->callid : 0)); if (l) l = sccp_line_release(l); return; } /* channel was on hold, restore active -> inc. channelcount */ if (channel->state == SCCP_CHANNELSTATE_HOLD) { channel->line->statistic.numberOfActiveChannels--; } /** check if we have preferences from channel request */ preferredCodec = channel->preferences.audio[0]; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: current preferredCodec=%d\n", preferredCodec); // auto released if it was set before sccp_channel_setDevice(channel, device); /** we changed channel->preferences.audio in sccp_channel_setDevice, so push the preferred codec back to pos 1 */ if (preferredCodec != SKINNY_CODEC_NONE) { skinny_codec_t tempCodecPreferences[ARRAY_LEN(channel->preferences.audio)]; uint8_t numFoundCodecs = 1; /** we did not allow this codec in device prefence list, so do not use this as primary preferred codec */ if (!sccp_utils_isCodecCompatible(preferredCodec, channel->preferences.audio, ARRAY_LEN(channel->preferences.audio))) { numFoundCodecs = 0; } /* save original preferences */ memcpy(&tempCodecPreferences, channel->preferences.audio, sizeof(channel->preferences.audio)); channel->preferences.audio[0] = preferredCodec; memcpy(&channel->preferences.audio[numFoundCodecs], tempCodecPreferences, sizeof(skinny_codec_t) * (ARRAY_LEN(channel->preferences.audio) - numFoundCodecs)); } // //! \todo move this to openreceive- and startmediatransmission (we do calc in openreceiv and startmedia, so check if we can remove) sccp_channel_updateChannelCapability(channel); /* answering an incoming call */ /* look if we have a call to put on hold */ sccp_channel_t *sccp_channel_1; if ((sccp_channel_1 = sccp_channel_get_active(device)) != NULL) { /* If there is a ringout or offhook call, we end it so that we can answer the call. */ if (sccp_channel_1->state == SCCP_CHANNELSTATE_OFFHOOK || sccp_channel_1->state == SCCP_CHANNELSTATE_RINGOUT) { sccp_channel_endcall(sccp_channel_1); } else if (!sccp_channel_hold(sccp_channel_1)) { /* there is an active call, let's put it on hold first */ sccp_channel_1 = sccp_channel_release(sccp_channel_1); if (l) { l = sccp_line_release(l); } return; } sccp_channel_1 = sccp_channel_release(sccp_channel_1); } /* end callforwards */ sccp_channel_t *sccp_channel_2; SCCP_LIST_LOCK(&channel->line->channels); SCCP_LIST_TRAVERSE(&channel->line->channels, sccp_channel_2, list) { if (sccp_channel_2->parentChannel == channel) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: CHANNEL Hangup cfwd channel %s-%08X\n", DEV_ID_LOG(device), l->name, sccp_channel_2->callid); /* No need to lock because sccp_channel->line->channels is already locked. */ sccp_channel_endcall(sccp_channel_2); channel->answered_elsewhere = TRUE; sccp_channel_2->parentChannel = sccp_channel_release(sccp_channel_2->parentChannel); // release from sccp_channel_forward_retain } } SCCP_LIST_UNLOCK(&channel->line->channels); /* */ /** set called party name */ sccp_linedevices_t *linedevice = NULL; if ((linedevice = sccp_linedevice_find(device, channel->line))) { if (!sccp_strlen_zero(linedevice->subscriptionId.number)) { sprintf(channel->callInfo.calledPartyNumber, "%s%s", channel->line->cid_num, linedevice->subscriptionId.number); } else { sprintf(channel->callInfo.calledPartyNumber, "%s%s", channel->line->cid_num, (channel->line->defaultSubscriptionId.number) ? channel->line->defaultSubscriptionId.number : ""); } if (!sccp_strlen_zero(linedevice->subscriptionId.name)) { sprintf(channel->callInfo.calledPartyName, "%s%s", channel->line->cid_name, linedevice->subscriptionId.name); } else { sprintf(channel->callInfo.calledPartyName, "%s%s", channel->line->cid_name, (channel->line->defaultSubscriptionId.name) ? channel->line->defaultSubscriptionId.name : ""); } linedevice = sccp_linedevice_release(linedevice); } /* done */ sccp_device_t *non_const_device = sccp_device_retain((sccp_device_t *) device); if (non_const_device) { sccp_channel_set_active(non_const_device, channel); sccp_dev_set_activeline(non_const_device, channel->line); /* the old channel state could be CALLTRANSFER, so the bridged channel is on hold */ /* do we need this ? -FS */ #ifdef CS_AST_HAS_FLAG_MOH pbx_bridged_channel = CS_AST_BRIDGED_CHANNEL(channel->owner); if (pbx_bridged_channel && pbx_test_flag(pbx_channel_flags(pbx_bridged_channel), AST_FLAG_MOH)) { PBX(moh_stop) (pbx_bridged_channel); //! \todo use pbx impl pbx_clear_flag(pbx_channel_flags(pbx_bridged_channel), AST_FLAG_MOH); } #endif sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Answering channel with state '%s' (%d)\n", DEV_ID_LOG(device), pbx_state2str(pbx_channel_state(channel->owner)), pbx_channel_state(channel->owner)); PBX(queue_control) (channel->owner, AST_CONTROL_ANSWER); if (channel->state != SCCP_CHANNELSTATE_OFFHOOK) { sccp_indicate(non_const_device, channel, SCCP_CHANNELSTATE_OFFHOOK); } PBX(set_connected_line) (channel, channel->callInfo.calledPartyNumber, channel->callInfo.calledPartyName, AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER); sccp_indicate(non_const_device, channel, SCCP_CHANNELSTATE_CONNECTED); non_const_device = sccp_device_release(non_const_device); } sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Answered channel %s-%08X\n", DEV_ID_LOG(device), l->name, channel->callid); l = l ? sccp_line_release(l) : NULL; } /*! * \brief Put channel on Hold. * * \param channel *retained* SCCP Channel * \return Status as in (0 if something was wrong, otherwise 1) * * \callgraph * \callergraph * * \lock * - device */ int sccp_channel_hold(sccp_channel_t * channel) { sccp_line_t *l; sccp_device_t *d; uint16_t instance; if (!channel) { pbx_log(LOG_WARNING, "SCCP: weird error. No channel provided to put on hold\n"); return 0; } if (!(l = channel->line)) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel %d has no line attached to it\n", channel->callid); return 0; } if (!(d = sccp_channel_getDevice_retained(channel))) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel %d has no device attached to it\n", channel->callid); return 0; } if (channel->state == SCCP_CHANNELSTATE_HOLD) { pbx_log(LOG_WARNING, "SCCP: Channel already on hold\n"); d = sccp_device_release(d); return 0; } /* put on hold an active call */ if (channel->state != SCCP_CHANNELSTATE_CONNECTED && channel->state != SCCP_CHANNELSTATE_CONNECTEDCONFERENCE && channel->state != SCCP_CHANNELSTATE_PROCEED) { // TOLL FREE NUMBERS STAYS ALWAYS IN CALL PROGRESS STATE /* something wrong on the code let's notify it for a fix */ sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s can't put on hold an inactive channel %s-%08X with state %s (%d)... cancelling hold action.\n", d->id, l->name, channel->callid, sccp_indicate2str(channel->state), channel->state); /* hard button phones need it */ instance = sccp_device_find_index_for_line(d, l->name); sccp_dev_displayprompt(d, instance, channel->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); d = sccp_device_release(d); return 0; } sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Hold the channel %s-%08X\n", DEV_ID_LOG(d), l->name, channel->callid); #ifdef CS_SCCP_CONFERENCE if (d->conference) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Putting conference on hold.\n", d->id); sccp_conference_hold(d->conference); } else #endif { if (channel->owner) { PBX(queue_control_data) (channel->owner, AST_CONTROL_HOLD, S_OR(l->musicclass, NULL), !sccp_strlen_zero(l->musicclass) ? strlen(l->musicclass) + 1 : 0); } } sccp_rtp_stop(channel); sccp_channel_set_active(d, NULL); sccp_dev_set_activeline(d, NULL); sccp_indicate(d, channel, SCCP_CHANNELSTATE_HOLD); // this will also close (but not destroy) the RTP stream sccp_channel_unsetDevice(channel); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) manager_event(EVENT_FLAG_CALL, "Hold", "Status: On\r\n" "Channel: %s\r\n" "Uniqueid: %s\r\n", PBX(getChannelName) (channel), PBX(getChannelUniqueID) (channel)); #endif if (l) { l->statistic.numberOfHoldChannels++; } sccp_log((DEBUGCAT_CHANNEL + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "C partyID: %u state: %d\n", channel->passthrupartyid, channel->state); d = sccp_device_release(d); return 1; } /*! * \brief Resume a channel that is on hold. * \param device device who resumes the channel * \param channel channel * \param swap_channels Swap Channels as Boolean * \return 0 if something was wrong, otherwise 1 * * \callgraph * \callergraph * * \lock * - device * - channel * - see sccp_channel_updateChannelCapability() * - channel */ int sccp_channel_resume(sccp_device_t * device, sccp_channel_t * channel, boolean_t swap_channels) { sccp_line_t *l; sccp_device_t *d; sccp_channel_t *sccp_channel_on_hold; uint16_t instance; if (!channel || !channel->owner) { pbx_log(LOG_WARNING, "SCCP: weird error. No channel provided to resume\n"); return 0; } if (!channel || !channel->line) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel has no line on channel %d\n", channel->callid); return 0; } l = channel->line; if (!(d = sccp_device_retain(device))) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel has no device or device could not be retained on channel %d\n", channel->callid); return 0; } /* look if we have a call to put on hold */ if (swap_channels && (sccp_channel_on_hold = sccp_channel_get_active(d))) { /* there is an active call, let's put it on hold first */ if (!(sccp_channel_hold(sccp_channel_on_hold))) { pbx_log(LOG_WARNING, "SCCP: swap_channels failed to put channel %d on hold. exiting\n", sccp_channel_on_hold->callid); sccp_channel_on_hold = sccp_channel_release(sccp_channel_on_hold); d = sccp_device_release(d); return 0; } sccp_channel_on_hold = sccp_channel_release(sccp_channel_on_hold); } if (channel->state == SCCP_CHANNELSTATE_CONNECTED || channel->state == SCCP_CHANNELSTATE_PROCEED) { if (!(sccp_channel_hold(channel))) { pbx_log(LOG_WARNING, "SCCP: channel still connected before resuming, put on hold failed for channel %d. exiting\n", channel->callid); d = sccp_device_release(d); return 0; } } /* resume an active call */ if (channel->state != SCCP_CHANNELSTATE_HOLD && channel->state != SCCP_CHANNELSTATE_CALLTRANSFER && channel->state != SCCP_CHANNELSTATE_CALLCONFERENCE) { /* something wrong in the code let's notify it for a fix */ pbx_log(LOG_ERROR, "%s can't resume the channel %s-%08X. Not on hold\n", d->id, l->name, channel->callid); instance = sccp_device_find_index_for_line(d, l->name); sccp_dev_displayprompt(d, instance, channel->callid, "No active call to put on hold", 5); d = sccp_device_release(d); return 0; } /* release transfer if we are in the middle of a transfer */ sccp_channel_transfer_release(d, channel); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Resume the channel %s-%08X\n", d->id, l->name, channel->callid); l = channel->line; sccp_channel_set_active(d, channel); sccp_channel_setDevice(channel, d); #if ASTERISK_VERSION_GROUP >= 111 // update callgroup / pickupgroup ast_channel_callgroup_set(channel->owner, l->callgroup); #if CS_SCCP_PICKUP ast_channel_pickupgroup_set(channel->owner, l->pickupgroup); #endif #endif // ASTERISK_VERSION_GROUP >= 111 #ifdef CS_SCCP_CONFERENCE if (d->conference) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Conference on the channel %s-%08X\n", d->id, l->name, channel->callid); sccp_conference_resume(d->conference); } else #endif { if (channel->owner) { PBX(queue_control) (channel->owner, AST_CONTROL_UNHOLD); } } //! \todo move this to openreceive- and startmediatransmission sccp_channel_updateChannelCapability(channel); // sccp_rtp_createAudioServer(channel); channel->state = SCCP_CHANNELSTATE_HOLD; #ifdef CS_AST_CONTROL_SRCUPDATE PBX(queue_control) (channel->owner, AST_CONTROL_SRCUPDATE); // notify changes e.g codec #endif sccp_indicate(d, channel, SCCP_CHANNELSTATE_CONNECTED); // this will also reopen the RTP stream #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "Hold", "Status: Off\r\n" "Channel: %s\r\n" "Uniqueid: %s\r\n", PBX(getChannelName) (channel), PBX(getChannelUniqueID) (channel)); } #endif /* state of channel is set down from the remoteDevices, so correct channel state */ channel->state = SCCP_CHANNELSTATE_CONNECTED; if (l) { l->statistic.numberOfHoldChannels--; } /** set called party name */ sccp_linedevices_t *linedevice = NULL; if ((linedevice = sccp_linedevice_find(d, channel->line))) { if (channel->calltype == SKINNY_CALLTYPE_OUTBOUND) { if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.number)) { sprintf(channel->callInfo.callingPartyNumber, "%s%s", channel->line->cid_num, linedevice->subscriptionId.number); } else { sprintf(channel->callInfo.callingPartyNumber, "%s%s", channel->line->cid_num, (channel->line->defaultSubscriptionId.number) ? channel->line->defaultSubscriptionId.number : ""); } if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.name)) { sprintf(channel->callInfo.callingPartyName, "%s%s", channel->line->cid_name, linedevice->subscriptionId.name); } else { sprintf(channel->callInfo.callingPartyName, "%s%s", channel->line->cid_name, (channel->line->defaultSubscriptionId.name) ? channel->line->defaultSubscriptionId.name : ""); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Set callingPartyNumber '%s' callingPartyName '%s'\n", DEV_ID_LOG(d), channel->callInfo.callingPartyNumber, channel->callInfo.callingPartyName); PBX(set_connected_line) (channel, channel->callInfo.callingPartyNumber, channel->callInfo.callingPartyName, AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER); } else if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.number)) { sprintf(channel->callInfo.calledPartyNumber, "%s%s", channel->line->cid_num, linedevice->subscriptionId.number); } else { sprintf(channel->callInfo.calledPartyNumber, "%s%s", channel->line->cid_num, (channel->line->defaultSubscriptionId.number) ? channel->line->defaultSubscriptionId.number : ""); } if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.name)) { sprintf(channel->callInfo.calledPartyName, "%s%s", channel->line->cid_name, linedevice->subscriptionId.name); } else { sprintf(channel->callInfo.calledPartyName, "%s%s", channel->line->cid_name, (channel->line->defaultSubscriptionId.name) ? channel->line->defaultSubscriptionId.name : ""); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Set calledPartyNumber '%s' calledPartyName '%s'\n", DEV_ID_LOG(d), channel->callInfo.calledPartyNumber, channel->callInfo.calledPartyName); PBX(set_connected_line) (channel, channel->callInfo.calledPartyNumber, channel->callInfo.calledPartyName, AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER); } linedevice = sccp_linedevice_release(linedevice); } /* */ sccp_log((DEBUGCAT_CHANNEL + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "C partyID: %u state: %d\n", channel->passthrupartyid, channel->state); d = sccp_device_release(d); return 1; } /*! * \brief Cleanup Channel before Free. * \param channel SCCP Channel * \note we assume channel is locked * * \callgraph * \callergraph * * \lock * - device * - see sccp_device_find_selectedchannel() * - device->selectedChannels */ void sccp_channel_clean(sccp_channel_t * channel) { // sccp_line_t *l; sccp_device_t *d; sccp_selectedchannel_t *sccp_selected_channel; if (!channel) { pbx_log(LOG_ERROR, "SCCP:No channel provided to clean\n"); return; } d = sccp_channel_getDevice_retained(channel); // l = channel->line; sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Cleaning channel %08x\n", channel->callid); /* mark the channel DOWN so any pending thread will terminate */ if (channel->owner) { pbx_setstate(channel->owner, AST_STATE_DOWN); channel->owner = NULL; } /* this is in case we are destroying the session */ if (channel->state != SCCP_CHANNELSTATE_DOWN) sccp_indicate(d, channel, SCCP_CHANNELSTATE_ONHOOK); sccp_rtp_stop(channel); if (d) { /* deactive the active call if needed */ if (d->active_channel == channel) sccp_channel_set_active(d, NULL); sccp_channel_transfer_release(d, channel); #ifdef CS_SCCP_CONFERENCE if (d->conference && d->conference == channel->conference) { d->conference = sccp_refcount_release(d->conference, __FILE__, __LINE__, __PRETTY_FUNCTION__); } if (channel->conference) { channel->conference = sccp_refcount_release(channel->conference, __FILE__, __LINE__, __PRETTY_FUNCTION__); } #endif if (channel->privacy) { channel->privacy = FALSE; d->privacyFeature.status = FALSE; sccp_feat_changed(d, NULL, SCCP_FEATURE_PRIVACY); } if ((sccp_selected_channel = sccp_device_find_selectedchannel(d, channel))) { SCCP_LIST_LOCK(&d->selectedChannels); sccp_selected_channel = SCCP_LIST_REMOVE(&d->selectedChannels, sccp_selected_channel, list); SCCP_LIST_UNLOCK(&d->selectedChannels); sccp_free(sccp_selected_channel); } sccp_dev_set_activeline(d, NULL); d = sccp_device_release(d); } if (channel && channel->privateData && channel->privateData->device) { sccp_channel_unsetDevice(channel); } } /*! * \brief Destroy Channel * \param channel SCCP Channel * \note We assume channel is locked * * \callgraph * \callergraph * * \warning * - line->channels is not always locked * * \lock * - channel */ void __sccp_channel_destroy(sccp_channel_t * channel) { if (!channel) { return; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "Destroying channel %08x\n", channel->callid); if (channel->privateData) { sccp_free(channel->privateData); } sccp_mutex_destroy(&channel->lock); pbx_cond_destroy(&channel->astStateCond); return; } /*! * \brief Handle Transfer Request (Pressing the Transfer Softkey) * \param channel *retained* SCCP Channel * \param device *retained* SCCP Device * * \callgraph * \callergraph * * \lock * - device */ void sccp_channel_transfer(sccp_channel_t * channel, sccp_device_t * device) { sccp_device_t *d; sccp_channel_t *sccp_channel_new = NULL; uint8_t prev_channel_state = 0; uint32_t blindTransfer = 0; uint16_t instance; if (!channel) return; if (!(channel->line)) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel has no line on channel %d\n", channel->callid); return; } if (!(d = sccp_channel_getDevice_retained(channel))) { /* transfer was pressed on first (transferee) channel, check if is our transferee channel and continue with d <= device */ if (channel == device->transferChannels.transferee && device->transferChannels.transferer) { d = sccp_device_retain(device); } else { pbx_log(LOG_WARNING, "SCCP: weird error. The channel has no device on channel %d\n", channel->callid); return; } } if (!d->transfer || !channel->line->transfer) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Transfer disabled on device or line\n", (d && d->id) ? d->id : "SCCP"); d = sccp_device_release(d); return; } /* are we in the middle of a transfer? */ if (d->transferChannels.transferee && d->transferChannels.transferer) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: In the middle of a Transfer. Going to transfer completion\n", (d && d->id) ? d->id : "SCCP"); sccp_channel_transfer_complete(d->transferChannels.transferer); d = sccp_device_release(d); return; } /* exceptional case, we need to release half transfer before retaking, should never occur */ // if (d->transferChannels.transferee && !d->transferChannels.transferer) { // d->transferChannels.transferee = sccp_channel_release(d->transferChannels.transferee); // } if (!d->transferChannels.transferee && d->transferChannels.transferer) { d->transferChannels.transferer = sccp_channel_release(d->transferChannels.transferer); } if ((d->transferChannels.transferee = sccp_channel_retain(channel))) { /** channel to be transfered */ sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Transfer request from line channel %s-%08X\n", (d && d->id) ? d->id : "SCCP", (channel->line && channel->line->name) ? channel->line->name : "(null)", channel->callid); if (!channel->owner) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: No bridged channel to transfer on %s-%08X\n", (d && d->id) ? d->id : "SCCP", (channel->line && channel->line->name) ? channel->line->name : "(null)", channel->callid); instance = sccp_device_find_index_for_line(d, channel->line->name); sccp_dev_displayprompt(d, instance, channel->callid, SKINNY_DISP_CAN_NOT_COMPLETE_TRANSFER, 5); d->transferChannels.transferee = sccp_channel_release(d->transferChannels.transferee); d = sccp_device_release(d); return; } prev_channel_state = channel->state; if ((channel->state != SCCP_CHANNELSTATE_OFFHOOK && channel->state != SCCP_CHANNELSTATE_HOLD && channel->state != SCCP_CHANNELSTATE_CALLTRANSFER) && !sccp_channel_hold(channel)) { d->transferChannels.transferee = sccp_channel_release(d->transferChannels.transferee); d = sccp_device_release(d); return; } if (channel->state != SCCP_CHANNELSTATE_CALLTRANSFER) { sccp_indicate(d, channel, SCCP_CHANNELSTATE_CALLTRANSFER); } if ((sccp_channel_new = sccp_channel_newcall(channel->line, d, NULL, SKINNY_CALLTYPE_OUTBOUND, sccp_channel_getLinkedId(channel)))) { /* set a var for BLINDTRANSFER. It will be removed if the user manually answer the call Otherwise it is a real BLINDTRANSFER */ if (blindTransfer || (sccp_channel_new && sccp_channel_new->owner && channel->owner && CS_AST_BRIDGED_CHANNEL(channel->owner))) { //! \todo use pbx impl pbx_builtin_setvar_helper(sccp_channel_new->owner, "BLINDTRANSFER", pbx_channel_name(CS_AST_BRIDGED_CHANNEL(channel->owner))); pbx_builtin_setvar_helper(CS_AST_BRIDGED_CHANNEL(channel->owner), "BLINDTRANSFER", pbx_channel_name(sccp_channel_new->owner)); } d->transferChannels.transferer = sccp_channel_retain(sccp_channel_new); sccp_channel_new = sccp_channel_release(sccp_channel_new); } else { // giving up sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: New channel could not be created to complete transfer for %s-%08X\n", (d && d->id) ? d->id : "SCCP", (channel->line && channel->line->name) ? channel->line->name : "(null)", channel->callid); sccp_indicate(d, channel, prev_channel_state); d->transferChannels.transferee = sccp_channel_release(d->transferChannels.transferee); } } d = sccp_device_release(d); } /*! * \brief Release Transfer Variables */ void sccp_channel_transfer_release(sccp_device_t * d, sccp_channel_t * c) { if (!d | !c) { return; } if ((d->transferChannels.transferee && c == d->transferChannels.transferee) || (d->transferChannels.transferer && c == d->transferChannels.transferer)) { d->transferChannels.transferee = d->transferChannels.transferee ? sccp_channel_release(d->transferChannels.transferee) : NULL; d->transferChannels.transferer = d->transferChannels.transferer ? sccp_channel_release(d->transferChannels.transferer) : NULL; sccp_log((DEBUGCAT_CHANNEL + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: Transfer on the channel %s-%08X released\n", d->id, c->line->name, c->callid); } } /*! * \brief Cancel Transfer */ void sccp_channel_transfer_cancel(sccp_device_t * d, sccp_channel_t * c) { if (!d || !c || !d->transferChannels.transferee) { return; } /** * workaround to fix issue with 7960 and protocol version != 6 * 7960 loses callplane when cancel transfer (end call on other channel). * This script sets the hold state for transfered channel explicitly -MC */ if (d && d->transferChannels.transferee && d->transferChannels.transferee != c) { if (d->transferChannels.transferer && d->transferChannels.transferer != c) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_hangup) Denied Receipt of Transferee %d %s by the Receiving Party. Cancelling Transfer and Putting transferee channel on Hold.\n", DEV_ID_LOG(d), d->transferChannels.transferee->callid, d->transferChannels.transferee->line->name); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_hangup) Denied Receipt of Transferee %d %s by the Transfering Party. Cancelling Transfer and Putting transferee channel on Hold.\n", DEV_ID_LOG(d), d->transferChannels.transferee->callid, d->transferChannels.transferee->line->name); } sccp_rtp_stop(d->transferChannels.transferee); sccp_channel_set_active(d, NULL); sccp_dev_set_activeline(d, NULL); sccp_indicate(d, d->transferChannels.transferee, SCCP_CHANNELSTATE_HOLD); sccp_channel_setDevice(d->transferChannels.transferee, NULL); sccp_channel_transfer_release(d, d->transferChannels.transferee); } } /*! * \brief Bridge Two Channels * \param sccp_destination_local_channel Local Destination SCCP Channel * \todo Find a way solve the chan->state problem * * \callgraph * \callergraph * * \lock * - device */ void sccp_channel_transfer_complete(sccp_channel_t * sccp_destination_local_channel) { PBX_CHANNEL_TYPE *pbx_source_local_channel = NULL; PBX_CHANNEL_TYPE *pbx_source_remote_channel = NULL; PBX_CHANNEL_TYPE *pbx_destination_local_channel = NULL; PBX_CHANNEL_TYPE *pbx_destination_remote_channel = NULL; sccp_channel_t *sccp_source_local_channel; sccp_device_t *d = NULL; uint16_t instance; if (!sccp_destination_local_channel) { return; } // Obtain the device from which the transfer was initiated d = sccp_channel_getDevice_retained(sccp_destination_local_channel); if (!sccp_destination_local_channel->line || !d) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel has no line or device on channel %d\n", sccp_destination_local_channel->callid); return; } // Obtain the source channel on that device sccp_source_local_channel = sccp_channel_retain(d->transferChannels.transferee); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Complete transfer from %s-%08X\n", d->id, sccp_destination_local_channel->line->name, sccp_destination_local_channel->callid); instance = sccp_device_find_index_for_line(d, sccp_destination_local_channel->line->name); if (sccp_destination_local_channel->state != SCCP_CHANNELSTATE_RINGOUT && sccp_destination_local_channel->state != SCCP_CHANNELSTATE_CONNECTED && sccp_destination_local_channel->state != SCCP_CHANNELSTATE_PROGRESS) { pbx_log(LOG_WARNING, "SCCP: Failed to complete transfer. The channel is not ringing or connected. ChannelState: %s (%d)\n", channelstate2str(sccp_destination_local_channel->state), sccp_destination_local_channel->state); sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, instance, sccp_destination_local_channel->callid, 0); sccp_dev_displayprompt(d, instance, sccp_destination_local_channel->callid, SKINNY_DISP_CAN_NOT_COMPLETE_TRANSFER, 5); d = sccp_device_release(d); sccp_source_local_channel = sccp_channel_release(sccp_source_local_channel); return; } if (!sccp_destination_local_channel->owner || !sccp_source_local_channel || !sccp_source_local_channel->owner) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Transfer error, asterisk channel error %s-%08X and %s-%08X\n", d->id, (sccp_destination_local_channel && sccp_destination_local_channel->line && sccp_destination_local_channel->line->name) ? sccp_destination_local_channel->line->name : "(null)", (sccp_destination_local_channel && sccp_destination_local_channel->callid) ? sccp_destination_local_channel->callid : 0, (sccp_source_local_channel && sccp_source_local_channel->line && sccp_source_local_channel->line->name) ? sccp_source_local_channel->line->name : "(null)", (sccp_source_local_channel && sccp_source_local_channel->callid) ? sccp_source_local_channel->callid : 0); d = sccp_device_release(d); sccp_source_local_channel = sccp_channel_release(sccp_source_local_channel); return; } pbx_source_local_channel = sccp_source_local_channel->owner; pbx_source_remote_channel = CS_AST_BRIDGED_CHANNEL(sccp_source_local_channel->owner); pbx_destination_remote_channel = CS_AST_BRIDGED_CHANNEL(sccp_destination_local_channel->owner); pbx_destination_local_channel = sccp_destination_local_channel->owner; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: pbx_source_local_channel %s\n", d->id, pbx_source_local_channel ? pbx_channel_name(pbx_source_local_channel) : "NULL"); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: pbx_source_remote_channel %s\n\n", d->id, pbx_source_remote_channel ? pbx_channel_name(pbx_source_remote_channel) : "NULL"); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: pbx_destination_local_channel %s\n", d->id, pbx_destination_local_channel ? pbx_channel_name(pbx_destination_local_channel) : "NULL"); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: pbx_destination_remote_channel %s\n\n", d->id, pbx_destination_remote_channel ? pbx_channel_name(pbx_destination_remote_channel) : "NULL"); if (!(pbx_source_remote_channel && pbx_destination_local_channel)) { pbx_log(LOG_WARNING, "SCCP: Failed to complete transfer. Missing asterisk transferred or transferee channel\n"); sccp_dev_displayprompt(d, instance, sccp_destination_local_channel->callid, SKINNY_DISP_CAN_NOT_COMPLETE_TRANSFER, 5); d = sccp_device_release(d); sccp_source_local_channel = sccp_channel_release(sccp_source_local_channel); return; } { char *fromName = NULL; char *fromNumber = NULL; char *toName = NULL; char *toNumber = NULL; char *originalCallingPartyName = NULL; char *originalCallingPartyNumber = NULL; int connectedLineUpdateReason = (sccp_destination_local_channel->state == SCCP_CHANNELSTATE_RINGOUT) ? AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING : AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER; /* update redirecting info line for source part */ fromNumber = sccp_destination_local_channel->callInfo.callingPartyNumber; fromName = sccp_destination_local_channel->callInfo.callingPartyName; toNumber = sccp_destination_local_channel->callInfo.calledPartyNumber; toName = sccp_destination_local_channel->callInfo.calledPartyName; if (sccp_source_local_channel->calltype == SKINNY_CALLTYPE_INBOUND) { originalCallingPartyName = sccp_source_local_channel->callInfo.callingPartyName; originalCallingPartyNumber = sccp_source_local_channel->callInfo.callingPartyNumber; } else { originalCallingPartyName = sccp_source_local_channel->callInfo.calledPartyName; originalCallingPartyNumber = sccp_source_local_channel->callInfo.calledPartyNumber; } /* update our source part */ sccp_copy_string(sccp_source_local_channel->callInfo.lastRedirectingPartyName, fromName ? fromName : "", sizeof(sccp_source_local_channel->callInfo.callingPartyName)); sccp_copy_string(sccp_source_local_channel->callInfo.lastRedirectingPartyNumber, fromNumber ? fromNumber : "", sizeof(sccp_source_local_channel->callInfo.lastRedirectingPartyNumber)); sccp_source_local_channel->callInfo.lastRedirectingParty_valid = 1; sccp_channel_display_callInfo(sccp_source_local_channel); /* update our destination part */ sccp_copy_string(sccp_destination_local_channel->callInfo.lastRedirectingPartyName, fromName ? fromName : "", sizeof(sccp_destination_local_channel->callInfo.callingPartyName)); sccp_copy_string(sccp_destination_local_channel->callInfo.lastRedirectingPartyNumber, fromNumber ? fromNumber : "", sizeof(sccp_destination_local_channel->callInfo.lastRedirectingPartyNumber)); sccp_destination_local_channel->callInfo.lastRedirectingParty_valid = 1; sccp_destination_local_channel->calltype = SKINNY_CALLTYPE_FORWARD; sccp_channel_display_callInfo(sccp_destination_local_channel); /* update transferee */ PBX(set_connected_line) (sccp_source_local_channel, toNumber, toName, connectedLineUpdateReason); #if ASTERISK_VERSION_GROUP > 106 /*! \todo change to SCCP_REASON Codes, using mapping table */ if (PBX(sendRedirectedUpdate)) { PBX(sendRedirectedUpdate) (sccp_source_local_channel, fromNumber, fromName, toNumber, toName, AST_REDIRECTING_REASON_UNCONDITIONAL); } #endif /* update ringin channel directly */ PBX(set_connected_line) (sccp_destination_local_channel, originalCallingPartyNumber, originalCallingPartyName, connectedLineUpdateReason); #if ASTERISK_VERSION_GROUP > 106 /*! \todo change to SCCP_REASON Codes, using mapping table */ if (PBX(sendRedirectedUpdate)) { PBX(sendRedirectedUpdate) (sccp_destination_local_channel, fromNumber, fromName, toNumber, toName, AST_REDIRECTING_REASON_UNCONDITIONAL); } #endif } if (sccp_destination_local_channel->state == SCCP_CHANNELSTATE_RINGOUT) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Blind transfer. Signalling ringing state to %s\n", d->id, pbx_channel_name(pbx_source_remote_channel)); pbx_indicate(pbx_source_remote_channel, AST_CONTROL_RINGING); // Shouldn't this be ALERTING? sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (Ringing within Transfer %s)\n", pbx_channel_name(pbx_source_remote_channel)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (Transfer destination %s)\n", pbx_channel_name(pbx_destination_local_channel)); if (GLOB(blindtransferindication) == SCCP_BLINDTRANSFER_RING) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_transfer_complete) Send ringing indication to %s\n", pbx_channel_name(pbx_source_remote_channel)); pbx_indicate(pbx_source_remote_channel, AST_CONTROL_RINGING); } else if (GLOB(blindtransferindication) == SCCP_BLINDTRANSFER_MOH) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_transfer_complete) Started music on hold for channel %s\n", pbx_channel_name(pbx_source_remote_channel)); PBX(moh_start) (pbx_source_remote_channel, NULL, NULL); //! \todo use pbx impl } } if (pbx_channel_masquerade(pbx_destination_local_channel, pbx_source_remote_channel)) { pbx_log(LOG_WARNING, "SCCP: Failed to masquerade %s into %s\n", pbx_channel_name(pbx_destination_local_channel), pbx_channel_name(pbx_source_remote_channel)); sccp_dev_displayprompt(d, instance, sccp_destination_local_channel->callid, SKINNY_DISP_CAN_NOT_COMPLETE_TRANSFER, 5); d = sccp_device_release(d); sccp_source_local_channel = sccp_channel_release(sccp_source_local_channel); return; } if (!sccp_source_local_channel->owner) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Peer owner disappeared! Can't free ressources\n"); d = sccp_device_release(d); sccp_source_local_channel = sccp_channel_release(sccp_source_local_channel); return; } sccp_channel_transfer_release(d, d->transferChannels.transferee); if (GLOB(transfer_tone) && sccp_destination_local_channel->state == SCCP_CHANNELSTATE_CONNECTED) { /* while connected not all the tones can be played */ sccp_dev_starttone(d, GLOB(autoanswer_tone), instance, sccp_destination_local_channel->callid, 0); } d = sccp_device_release(d); sccp_source_local_channel = sccp_channel_release(sccp_source_local_channel); } /*! * \brief Reset Caller Id Presentation * \param channel SCCP Channel */ void sccp_channel_reset_calleridPresenceParameter(sccp_channel_t * channel) { channel->callInfo.presentation = CALLERID_PRESENCE_ALLOWED; if (PBX(set_callerid_presence)) { PBX(set_callerid_presence) (channel); } } /*! * \brief Set Caller Id Presentation * \param channel SCCP Channel * \param presenceParameter SCCP CallerID Presence ENUM */ void sccp_channel_set_calleridPresenceParameter(sccp_channel_t * channel, sccp_calleridpresence_t presenceParameter) { channel->callInfo.presentation = presenceParameter; if (PBX(set_callerid_presence)) { PBX(set_callerid_presence) (channel); } } /*! * \brief Forward a Channel * \param sccp_channel_parent SCCP parent channel * \param lineDevice SCCP LineDevice * \param fwdNumber fwdNumber as char * * * \callgraph * \callergraph * * \lock * - channel */ int sccp_channel_forward(sccp_channel_t * sccp_channel_parent, sccp_linedevices_t * lineDevice, char *fwdNumber) { sccp_channel_t *sccp_forwarding_channel = NULL; char dialedNumber[256]; int res = 0; if (!sccp_channel_parent) { pbx_log(LOG_ERROR, "We can not forward a call without parent channel\n"); return -1; } sccp_copy_string(dialedNumber, fwdNumber, sizeof(dialedNumber)); sccp_forwarding_channel = sccp_channel_allocate(sccp_channel_parent->line, NULL); if (!sccp_forwarding_channel) { pbx_log(LOG_ERROR, "%s: Can't allocate SCCP channel\n", lineDevice->device->id); return -1; } sccp_forwarding_channel->parentChannel = sccp_channel_retain(sccp_channel_parent); sccp_forwarding_channel->ss_action = SCCP_SS_DIAL; /* softswitch will catch the number to be dialed */ sccp_forwarding_channel->ss_data = 0; // nothing to pass to action sccp_forwarding_channel->calltype = SKINNY_CALLTYPE_OUTBOUND; /* copy the number to dial in the ast->exten */ sccp_copy_string(sccp_forwarding_channel->dialedNumber, dialedNumber, sizeof(sccp_forwarding_channel->dialedNumber)); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "Incoming: %s Forwarded By: %s Forwarded To: %s", sccp_channel_parent->callInfo.callingPartyName, lineDevice->line->cid_name, dialedNumber); /* Copy Channel Capabilities From Predecessor */ memset(&sccp_forwarding_channel->remoteCapabilities.audio, 0, sizeof(sccp_forwarding_channel->remoteCapabilities.audio)); memcpy(&sccp_forwarding_channel->remoteCapabilities.audio, sccp_channel_parent->remoteCapabilities.audio, sizeof(sccp_forwarding_channel->remoteCapabilities.audio)); memset(&sccp_forwarding_channel->preferences.audio, 0, sizeof(sccp_forwarding_channel->preferences.audio)); memcpy(&sccp_forwarding_channel->preferences.audio, sccp_channel_parent->preferences.audio, sizeof(sccp_channel_parent->preferences.audio)); /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(sccp_forwarding_channel, sccp_channel_getLinkedId(sccp_channel_parent))) { pbx_log(LOG_WARNING, "%s: Unable to allocate a new channel for line %s\n", lineDevice->device->id, sccp_forwarding_channel->line->name); sccp_line_removeChannel(sccp_forwarding_channel->line, sccp_forwarding_channel); sccp_channel_clean(sccp_forwarding_channel); // sccp_channel_destroy(sccp_forwarding_channel); res = -1; goto EXIT_FUNC; } /* Update rtp setting to match predecessor */ skinny_codec_t codecs[] = { SKINNY_CODEC_WIDEBAND_256K }; PBX(set_nativeAudioFormats) (sccp_forwarding_channel, codecs, 1); PBX(rtp_setWriteFormat) (sccp_forwarding_channel, SKINNY_CODEC_WIDEBAND_256K); PBX(rtp_setWriteFormat) (sccp_forwarding_channel, SKINNY_CODEC_WIDEBAND_256K); sccp_channel_updateChannelCapability(sccp_forwarding_channel); /* setting callerid */ if (PBX(set_callerid_number)) { PBX(set_callerid_number) (sccp_forwarding_channel, sccp_channel_parent->callInfo.callingPartyNumber); } if (PBX(set_callerid_name)) { PBX(set_callerid_name) (sccp_forwarding_channel, sccp_channel_parent->callInfo.callingPartyName); } if (PBX(set_callerid_ani)) { PBX(set_callerid_ani) (sccp_forwarding_channel, dialedNumber); } if (PBX(set_callerid_dnid)) { PBX(set_callerid_dnid) (sccp_forwarding_channel, dialedNumber); } if (PBX(set_callerid_redirectedParty)) { PBX(set_callerid_redirectedParty) (sccp_forwarding_channel, sccp_channel_parent->callInfo.calledPartyNumber, sccp_channel_parent->callInfo.calledPartyName); } if (PBX(set_callerid_redirectingParty)) { PBX(set_callerid_redirectingParty) (sccp_forwarding_channel, sccp_forwarding_channel->line->cid_num, sccp_forwarding_channel->line->cid_name); } /* dial sccp_forwarding_channel */ PBX(setChannelExten) (sccp_forwarding_channel, dialedNumber); /* \todo copy device line setvar variables from parent channel to forwarder->owner */ PBX(set_callstate) (sccp_forwarding_channel, AST_STATE_OFFHOOK); if (!sccp_strlen_zero(dialedNumber) && PBX(checkhangup) (sccp_forwarding_channel) && pbx_exists_extension(sccp_forwarding_channel->owner, sccp_forwarding_channel->line->context, dialedNumber, 1, sccp_forwarding_channel->line->cid_num)) { /* found an extension, let's dial it */ pbx_log(LOG_NOTICE, "%s: (sccp_channel_forward) channel %s-%08x is dialing number %s\n", "SCCP", sccp_forwarding_channel->line->name, sccp_forwarding_channel->callid, dialedNumber); /* Answer dialplan command works only when in RINGING OR RING ast_state */ PBX(set_callstate) (sccp_forwarding_channel, AST_STATE_RING); pbx_channel_call_forward_set(sccp_forwarding_channel->owner, dialedNumber); if (pbx_pbx_start(sccp_forwarding_channel->owner)) { pbx_log(LOG_WARNING, "%s: invalide number\n", "SCCP"); } } else { pbx_log(LOG_NOTICE, "%s: (sccp_channel_forward) channel %s-%08x cannot dial this number %s\n", "SCCP", sccp_forwarding_channel->line->name, sccp_forwarding_channel->callid, dialedNumber); sccp_channel_endcall(sccp_forwarding_channel); res = -1; goto EXIT_FUNC; } EXIT_FUNC: sccp_forwarding_channel = sccp_forwarding_channel ? sccp_channel_release(sccp_forwarding_channel) : NULL; return res; } #ifdef CS_SCCP_PARK /*! * \brief Park an SCCP Channel * \param channel SCCP Channel */ void sccp_channel_park(sccp_channel_t * channel) { sccp_parkresult_t result; if (!PBX(feature_park)) { pbx_log(LOG_WARNING, "SCCP, parking feature not implemented\n"); return; } /* let the pbx implementation do the rest */ result = PBX(feature_park) (channel); if (PARK_RESULT_SUCCESS != result) { char extstr[20]; extstr[0] = 128; extstr[1] = SKINNY_LBL_CALL_PARK; sprintf(&extstr[2], " failed"); sccp_device_t *d = sccp_channel_getDevice_retained(channel); sccp_dev_displaynotify(d, extstr, 10); d = sccp_device_release(d); } } #endif /*! * \brief Set Preferred Codec on Channel * \param c SCCP Channel * \param data Stringified Skinny Codec ShortName * \return Success as Boolean */ boolean_t sccp_channel_setPreferredCodec(sccp_channel_t * c, const void *data) { char text[64] = { '\0' }; uint64_t x; unsigned int numFoundCodecs = 0; skinny_codec_t tempCodecPreferences[ARRAY_LEN(c->preferences.audio)]; if (!data || !c) { return FALSE; } strncpy(text, data, sizeof(text) - 1); /* save original preferences */ memcpy(&tempCodecPreferences, c->preferences.audio, sizeof(c->preferences.audio)); for (x = 0; x < ARRAY_LEN(skinny_codecs) && numFoundCodecs < ARRAY_LEN(c->preferences.audio); x++) { if (!strcasecmp(skinny_codecs[x].key, text)) { c->preferences.audio[numFoundCodecs] = skinny_codecs[x].codec; numFoundCodecs++; /* we can have multiple codec versions, so dont break on this step */ //! \todo we should remove our prefs from original list -MC } } memcpy(&c->preferences.audio[numFoundCodecs], tempCodecPreferences, sizeof(skinny_codec_t) * (ARRAY_LEN(c->preferences.audio) - numFoundCodecs)); /** update capabilities if somthing changed */ if (numFoundCodecs > 0) { sccp_channel_updateChannelCapability(c); } return TRUE; } /*! * \brief Send callwaiting tone to device multiple times * \note this caused refcount / segfault issues, when channel would be lost before thread callback * \todo find another method to reimplement this. */ int sccp_channel_callwaiting_tone_interval(sccp_device_t * device, sccp_channel_t * channel) { sccp_device_t *d = NULL; sccp_channel_t *c = NULL; int res = -1; if (GLOB(callwaiting_tone)) { if ((d = sccp_device_retain(device))) { if ((c = sccp_channel_retain(channel))) { if (c->line && c->line->name) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Handle Callwaiting Tone on channel %d\n", c->callid); if (c && c->owner && (SCCP_CHANNELSTATE_CALLWAITING == c->state || SCCP_CHANNELSTATE_RINGING == c->state)) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Sending Call Waiting Tone \n", DEV_ID_LOG(d)); int instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_starttone(d, GLOB(callwaiting_tone), instance, c->callid, 0); //! \todo reimplement callwaiting_interval res = 0; } else { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_callwaiting_tone_interval)channel has been hungup or pickup up by another phone\n"); } } else { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_callwaiting_tone_interval) No valid line received to handle callwaiting\n"); } c = sccp_channel_release(channel); } else { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_callwaiting_tone_interval) No valid channel received to handle callwaiting\n"); } d = sccp_device_release(d); } else { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_callwaiting_tone_interval) No valid device received to handle callwaiting\n"); } } else { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (sccp_channel_callwaiting_tone_interval) No callwaiting_tone set\n"); } return res; } /*! * \brief Helper function to retrieve the pbx channel LinkedID */ const char *sccp_channel_getLinkedId(const sccp_channel_t * channel) { if (!PBX(getChannelLinkedId)) { return NULL; } return PBX(getChannelLinkedId) (channel); } /*=================================================================================== FIND FUNCTIONS ==============*/ /*! * \brief Find Channel by ID, using a specific line * * \callgraph * \callergraph * * \lock * - lines * - line->channels * - channel */ #if DEBUG /*! * \param l SCCP Line * \param id channel ID as int * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return *refcounted* SCCP Channel (can be null) */ sccp_channel_t *__sccp_find_channel_on_line_byid(sccp_line_t * l, uint32_t id, const char *filename, int lineno, const char *func) #else /*! * \param l SCCP Line * \param id channel ID as int * \return *refcounted* SCCP Channel (can be null) */ sccp_channel_t *sccp_find_channel_on_line_byid(sccp_line_t * l, uint32_t id) #endif { sccp_channel_t *c = NULL; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by id %u\n", id); SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "Channel %u state: %d\n", c->callid, c->state); if (c && c->callid == id && c->state != SCCP_CHANNELSTATE_DOWN) { #if DEBUG c = sccp_refcount_retain(c, filename, lineno, func); #else c = sccp_channel_retain(c); #endif sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Found channel by callid: %u\n", c->currentDeviceId, c->callid); break; } } SCCP_LIST_UNLOCK(&l->channels); return c; } /*! * \brief Find Line by ID * * \callgraph * \callergraph * * \lock * - lines * - line->channels * - channel */ #if DEBUG /*! * \param id ID as int * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return *refcounted* SCCP Channel (can be null) */ sccp_channel_t *__sccp_channel_find_byid(uint32_t id, const char *filename, int lineno, const char *func) #else /*! * \param id ID as int * \return *refcounted* SCCP Channel (can be null) */ sccp_channel_t *sccp_channel_find_byid(uint32_t id) #endif { sccp_channel_t *channel = NULL; sccp_line_t *l = NULL; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by id %u\n", id); SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { #if DEBUG channel = __sccp_find_channel_on_line_byid(l, id, filename, lineno, func); #else channel = sccp_find_channel_on_line_byid(l, id); #endif if (channel) break; } SCCP_RWLIST_UNLOCK(&GLOB(lines)); return channel; } /*! * \brief Find Channel by Pass Through Party ID * We need this to start the correct rtp stream. * \param passthrupartyid Party ID * \return *refcounted* SCCP Channel - cann bee NULL if no channel with this id was found * * \note Does check that channel state not is DOWN. * * \callgraph * \callergraph * * \lock * - lines * - line->channels * - channel */ #if DEBUG /*! * \param passthrupartyid Party ID * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return *refcounted* SCCP Channel - cann bee NULL if no channel with this id was found */ sccp_channel_t *__sccp_channel_find_bypassthrupartyid(uint32_t passthrupartyid, const char *filename, int lineno, const char *func) #else /*! * \param passthrupartyid Party ID * \return *refcounted* SCCP Channel - cann bee NULL if no channel with this id was found */ sccp_channel_t *sccp_channel_find_bypassthrupartyid(uint32_t passthrupartyid) #endif { sccp_channel_t *channel = NULL; sccp_line_t *l = NULL; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by PassThruId %u\n", passthrupartyid); SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, channel, list) { sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%u: Found channel partyID: %u state: %d\n", channel->callid, channel->passthrupartyid, channel->state); if (channel->passthrupartyid == passthrupartyid && channel->state != SCCP_CHANNELSTATE_DOWN) { #if DEBUG channel = sccp_refcount_retain(channel, filename, lineno, func); #else channel = sccp_channel_retain(channel); #endif sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Found channel for callid %u by passthrupartyid %d\n", channel->currentDeviceId, channel->callid, channel->passthrupartyid); break; } } SCCP_LIST_UNLOCK(&l->channels); if (channel) { break; } } SCCP_RWLIST_UNLOCK(&GLOB(lines)); if (!channel) ast_log(LOG_WARNING, "SCCP: Could not find active channel with Passthrupartyid %u\n", passthrupartyid); return channel; } /*! * \brief Find Channel by Pass Through Party ID on a line connected to device provided * We need this to start the correct rtp stream. * * \param d SCCP Device * \param passthrupartyid Party ID * \return *locked* SCCP Channel - can be NULL if no channel with this id was found. * * \note does not take channel state into account, this need to be asserted in the calling function * \note this is different from the sccp_channel_find_bypassthrupartyid behaviour * * \callgraph * \callergraph * * \lock * - lines * - line->channels * - channel */ #if !CS_EXPERIMENTAL // Old Version sccp_channel_t *sccp_channel_find_on_device_bypassthrupartyid(sccp_device_t * d, uint32_t passthrupartyid) { if (!d) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "SCCP: No device provided to look for %u\n", passthrupartyid); return NULL; } sccp_channel_t *c = NULL; sccp_line_t *l = NULL; sccp_buttonconfig_t *buttonconfig = NULL; boolean_t channelFound = FALSE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by PassThruId %u on device %s\n", passthrupartyid, d->id); SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) { l = sccp_line_find_byname(buttonconfig->button.line.name, FALSE); if (l) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: line: '%s'\n", DEV_ID_LOG(d), l->name); SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { //if (c->passthrupartyid == passthrupartyid && c->state != SCCP_CHANNELSTATE_DOWN) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: Found channel passthrupartyid: %u, callid: %u, state: %d on line %s\n", DEV_ID_LOG(d), c->passthrupartyid, c->callid, c->state, l->name); if (c->passthrupartyid == passthrupartyid) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: Found channel (passthrupartyid: %u, callid: %u) on line %s with state %d\n", DEV_ID_LOG(d), c->passthrupartyid, c->callid, l->name, c->state); c = sccp_channel_retain(c); channelFound = TRUE; break; } } SCCP_LIST_UNLOCK(&l->channels); l = sccp_line_release(l); if (channelFound) break; } } } if (!c || !channelFound) { ast_log(LOG_WARNING, "SCCP: Could not find active channel with Passthrupartyid %u on device %s\n", passthrupartyid, DEV_ID_LOG(d)); } return c; } #else // New Version sccp_channel_t *sccp_channel_find_on_device_bypassthrupartyid(sccp_device_t * d, uint32_t passthrupartyid) { if (!d) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "SCCP: No device provided to look for %u\n", passthrupartyid); return NULL; } btnlist *btn = d->buttonTemplate; if (!btn) { sccp_log(DEBUGCAT_BUTTONTEMPLATE) (VERBOSE_PREFIX_3 "%s: no buttontemplate, reset device\n", DEV_ID_LOG(d)); return NULL; } sccp_channel_t *c = NULL; sccp_line_t *l = NULL; int i = 0; boolean_t channelFound = FALSE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by PassThruId %u on device %s\n", passthrupartyid, d->id); for (i = 0; i < StationMaxButtonTemplateSize; i++) { if (btn[i].type == SKINNY_BUTTONTYPE_LINE && btn[i].ptr) { if ((l = sccp_line_retain(btn[i].ptr))) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: Found line: '%s'\n", DEV_ID_LOG(d), l->name); SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { //if (c->passthrupartyid == passthrupartyid && c->state != SCCP_CHANNELSTATE_DOWN) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: Found channel passthrupartyid: %u, callid: %u, state: %d on line %s\n", DEV_ID_LOG(d), c->passthrupartyid, c->callid, c->state, l->name); if (c->passthrupartyid == passthrupartyid) { sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: Found channel (passthrupartyid: %u, callid: %u) on line %s with state %d\n", DEV_ID_LOG(d), c->passthrupartyid, c->callid, l->name, c->state); c = sccp_channel_retain(c); channelFound = TRUE; break; } } SCCP_LIST_UNLOCK(&l->channels); l = sccp_line_release(l); if (channelFound) break; } } } if (!c || !channelFound) { ast_log(LOG_WARNING, "SCCP: Could not find active channel with Passthrupartyid %u on device %s\n", passthrupartyid, DEV_ID_LOG(d)); } return c; } #endif /*! * \brief Find Channel by State on Line * \return *refcounted* SCCP Channel * * \callgraph * \callergraph * * \lock * - lines * - line->channels * - channel */ #if DEBUG /*! * \param l SCCP Line * \param state State * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return *refcounted* SCCP Channel */ sccp_channel_t *__sccp_channel_find_bystate_on_line(sccp_line_t * l, uint8_t state, const char *filename, int lineno, const char *func) #else /*! * \param l SCCP Line * \param state State * \return *refcounted* SCCP Channel */ sccp_channel_t *sccp_channel_find_bystate_on_line(sccp_line_t * l, uint8_t state) #endif { sccp_channel_t *channel = NULL; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by state '%d'\n", state); SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, channel, list) { if (channel && channel->state == state) { #if DEBUG channel = sccp_refcount_retain(channel, filename, lineno, func); #else channel = sccp_channel_retain(channel); #endif sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Found channel for callid %d by state %d\n", channel->currentDeviceId, channel->callid, channel->state); break; } } SCCP_LIST_UNLOCK(&l->channels); return channel; } /*! * \brief Find Channel by State on Device * * \callgraph * \callergraph * * \warning * - device->buttonconfig is not always locked * * \lock * - device * - see sccp_line_find_byname_wo() * - line->channels * - channel */ #if DEBUG /*! * \param d SCCP Device * \param state State as int * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return *refcounted* SCCP Channel */ sccp_channel_t *__sccp_channel_find_bystate_on_device(sccp_device_t * d, uint8_t state, const char *filename, int lineno, const char *func) #else /*! * \param d SCCP Device * \param state State as int * \return *refcounted* SCCP Channel */ sccp_channel_t *sccp_channel_find_bystate_on_device(sccp_device_t * d, uint8_t state) #endif { sccp_channel_t *channel = NULL; sccp_line_t *l = NULL; sccp_buttonconfig_t *buttonconfig = NULL; boolean_t channelFound = FALSE; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Looking for channel by state '%d'\n", state); if (!(d = sccp_device_retain(d))) return NULL; SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) { l = sccp_line_find_byname(buttonconfig->button.line.name, FALSE); if (l) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_CHANNEL | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: line: '%s'\n", DEV_ID_LOG(d), l->name); SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, channel, list) { if (channel->state == state) { /* check that subscriptionId matches */ if (sccp_util_matchSubscriptionId(channel, buttonconfig->button.line.subscriptionId.number)) { #if DEBUG channel = sccp_refcount_retain(channel, filename, lineno, func); #else channel = sccp_channel_retain(channel); #endif sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_CHANNEL | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Found channel (%d)\n", DEV_ID_LOG(d), channel->callid); channelFound = TRUE; break; } else { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_CHANNEL | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Found channel (%d), but it does not match subscriptionId %s \n", DEV_ID_LOG(d), channel->callid, buttonconfig->button.line.subscriptionId.number); } } } SCCP_LIST_UNLOCK(&l->channels); l = sccp_line_release(l); if (channelFound) break; } } } d = sccp_device_release(d); return channel; } /*! * \brief Find Selected Channel by Device * \param d SCCP Device * \param channel channel * \return x SelectedChannel * * \callgraph * \callergraph * * \lock * - device->selectedChannels * * \todo Currently this returns the selectedchannel unretained ! */ sccp_selectedchannel_t *sccp_device_find_selectedchannel(sccp_device_t * d, sccp_channel_t * channel) { if (!d) return NULL; sccp_selectedchannel_t *sc = NULL; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Looking for selected channel (%d)\n", DEV_ID_LOG(d), channel->callid); SCCP_LIST_LOCK(&d->selectedChannels); SCCP_LIST_TRAVERSE(&d->selectedChannels, sc, list) { if (sc->channel == channel) { sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Found channel (%d)\n", DEV_ID_LOG(d), channel->callid); break; } } SCCP_LIST_UNLOCK(&d->selectedChannels); return sc; } /*! * \brief Count Selected Channel on Device * \param d SCCP Device * \return count Number of Selected Channels * * \lock * - device->selectedChannels */ uint8_t sccp_device_selectedchannels_count(sccp_device_t * d) { sccp_selectedchannel_t *sc = NULL; uint8_t count = 0; if (!(d = sccp_device_retain(d))) return 0; sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Looking for selected channels count\n", DEV_ID_LOG(d)); SCCP_LIST_LOCK(&d->selectedChannels); SCCP_LIST_TRAVERSE(&d->selectedChannels, sc, list) { count++; } SCCP_LIST_UNLOCK(&d->selectedChannels); return count; }
722,252
./chan-sccp-b/src/sccp_adv_features.c
/*! * \file sccp_adv_features.c * \brief SCCP Advanced Features Class * \author Sergio Chersovani <mlists [at] c-net.it> * \author Federico Santulli <fsantulli [at] users.sourceforge.net> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /*! * \brief Dummy Procedure 1 */ void dummyproc1(void) { /* this is a dummy proc */ if (0) dummyproc2(); } /*! * \brief Dummy Procedure 2 */ void dummyproc2(void) { /* this is a dummy proc */ if (0) dummyproc1(); }
722,253
./chan-sccp-b/src/sccp_device.c
/*! * \file sccp_device.c * \brief SCCP Device Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \remarks Purpose: SCCP Device * When to use: Only methods directly related to sccp devices should be stored in this source file. * Relationships: SCCP Device -> SCCP DeviceLine -> SCCP Line * SCCP Line -> SCCP ButtonConfig -> SCCP Device * * \date $Date$ * \version $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") int __sccp_device_destroy(const void *ptr); sccp_device_t *sccp_device_removeFromGlobals(sccp_device_t * device); int sccp_device_destroy(const void *ptr); /* indicate definition */ static void sccp_device_old_indicate_remoteHold(const sccp_device_t * device, uint8_t lineInstance, uint8_t callid, uint8_t callpriority, uint8_t callPrivacy); static void sccp_device_new_indicate_remoteHold(const sccp_device_t * device, uint8_t lineInstance, uint8_t callid, uint8_t callpriority, uint8_t callPrivacy); static void sccp_device_indicate_offhook(const sccp_device_t * device, sccp_linedevices_t * linedevice, uint8_t callid); static void sccp_device_indicate_connected(const sccp_device_t * device, sccp_linedevices_t * linedevice, const sccp_channel_t * channel); /* end indicate */ static sccp_push_result_t sccp_device_pushURL(const sccp_device_t * device, const char *url, uint8_t priority, uint8_t tone); static sccp_push_result_t sccp_device_pushURLNotSupported(const sccp_device_t * device, const char *url, uint8_t priority, uint8_t tone) { return SCCP_PUSH_RESULT_NOT_SUPPORTED; } static sccp_push_result_t sccp_device_pushTextMessage(const sccp_device_t * device, const char *messageText, const char *from, uint8_t priority, uint8_t tone); static sccp_push_result_t sccp_device_pushTextMessageNotSupported(const sccp_device_t * device, const char *messageText, const char *from, uint8_t priority, uint8_t tone) { return SCCP_PUSH_RESULT_NOT_SUPPORTED; } static const struct sccp_device_indication_cb sccp_device_indication_newerDevices = { .remoteHold = sccp_device_new_indicate_remoteHold, .offhook = sccp_device_indicate_offhook, .connected = sccp_device_indicate_connected, }; static const struct sccp_device_indication_cb sccp_device_indication_olderDevices = { .remoteHold = sccp_device_old_indicate_remoteHold, .offhook = sccp_device_indicate_offhook, .connected = sccp_device_indicate_connected, }; static boolean_t sccp_device_checkACLTrue(sccp_device_t * device) { return TRUE; } static boolean_t sccp_device_trueResult(void) { return TRUE; } static boolean_t sccp_device_falseResult(void) { return FALSE; } static void sccp_device_retrieveDeviceCapabilities(const sccp_device_t * device) { char *xmlStr = "<getDeviceCaps></getDeviceCaps>"; unsigned int transactionID = random(); device->protocol->sendUserToDeviceDataVersionMessage(device, APPID_DEVICECAPABILITIES, 1, 0, transactionID, xmlStr, 2); } static void sccp_device_setBackgroundImage(const sccp_device_t * device, const char *url) { char xmlStr[2048]; unsigned int transactionID = random(); if (strncmp("http://", url, strlen("http://")) != 0) { pbx_log(LOG_WARNING, "SCCP: '%s' needs to bee a valid http url\n", url ? url : ""); } memset(xmlStr, 0, sizeof(xmlStr)); strcat(xmlStr, "<setBackground>"); strcat(xmlStr, "<background>"); strcat(xmlStr, "<image>"); strcat(xmlStr, url); strcat(xmlStr, "</image>"); strcat(xmlStr, "<icon>"); strcat(xmlStr, url); strcat(xmlStr, "</icon>"); strcat(xmlStr, "</background>"); strcat(xmlStr, "</setBackground>\n\0"); device->protocol->sendUserToDeviceDataVersionMessage(device, 0, 0, 0, transactionID, xmlStr, 0); } static void sccp_device_setBackgroundImageNotSupported(const sccp_device_t * device, const char *url) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: does not support Background Image\n", device->id); } static void sccp_device_displayBackgroundImagePreview(const sccp_device_t * device, const char *url) { char xmlStr[2048]; unsigned int transactionID = random(); if (strncmp("http://", url, strlen("http://")) != 0) { pbx_log(LOG_WARNING, "SCCP: '%s' needs to bee a valid http url\n", url ? url : ""); } memset(xmlStr, 0, sizeof(xmlStr)); strcat(xmlStr, "<setBackgroundPreview>"); strcat(xmlStr, "<image>"); strcat(xmlStr, url); strcat(xmlStr, "</image>"); strcat(xmlStr, "</setBackgroundPreview>\n\0"); device->protocol->sendUserToDeviceDataVersionMessage(device, 0, 0, 0, transactionID, xmlStr, 0); } static void sccp_device_displayBackgroundImagePreviewNotSupported(const sccp_device_t * device, const char *url) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: does not support Background Image\n", device->id); } static void sccp_device_setRingtone(const sccp_device_t * device, const char *url) { char xmlStr[2048]; unsigned int transactionID = random(); if (strncmp("http://", url, strlen("http://")) != 0) { pbx_log(LOG_WARNING, "SCCP: '%s' needs to bee a valid http url\n", url ? url : ""); } memset(xmlStr, 0, sizeof(xmlStr)); strcat(xmlStr, "<setRingTone>"); strcat(xmlStr, "<ringTone>"); strcat(xmlStr, url); strcat(xmlStr, "</ringTone>"); strcat(xmlStr, "</setRingTone>\n\0"); device->protocol->sendUserToDeviceDataVersionMessage(device, 0, 0, 0, transactionID, xmlStr, 0); } static void sccp_device_setRingtoneNotSupported(const sccp_device_t * device, const char *url) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: does not support setting ringtone\n", device->id); } // static void sccp_device_startStream(const sccp_device_t *device, const char *address, uint32_t port){ // char xmlStr[2048]; // unsigned int transactionID = random(); // // // // strcat(xmlStr, "<startMedia>"); // strcat(xmlStr, "<mediaStream>"); // // strcat(xmlStr, "<onStopped></onStopped>"); //url // strcat(xmlStr, "<receiveVolume>50</receiveVolume>"); // 0-100 // strcat(xmlStr, "<type>audio</type>"); // send|receive|sendReceive // strcat(xmlStr, "<mode>sendReceive</mode>"); // send|receive|sendReceive // strcat(xmlStr, "<codec>Wideband</codec>"); // "G.711" "G.722" "G.723" "G.728" "G.729" "GSM" "Wideband" "iLBC" // strcat(xmlStr, "<address>"); // strcat(xmlStr, address); // strcat(xmlStr, "</address>"); // strcat(xmlStr, "<port>20480</port>"); // strcat(xmlStr, "</mediaStream>"); // strcat(xmlStr, "</startMedia>\n\0"); // // device->protocol->sendUserToDeviceDataVersionMessage(device, 0, 0, 0, transactionID, xmlStr, 0); // } /*! * \brief Check device ipaddress against the ip ACL (permit/deny and permithosts entries) */ static boolean_t sccp_device_checkACL(sccp_device_t * device) { struct sockaddr_in sin; boolean_t matchesACL = FALSE; /* get current socket information */ sccp_session_getSocketAddr(device, &sin); /* no permit deny information */ if (!device->ha) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: no deny/permit information for this device, allow all connections\n", device->id); return TRUE; } if (sccp_apply_ha(device->ha, &sin) != AST_SENSE_ALLOW) { // checking permithosts struct ast_str *ha_buf = pbx_str_alloca(512); sccp_print_ha(ha_buf, sizeof(ha_buf), GLOB(ha)); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: not allowed by deny/permit list (%s). Checking permithost list...\n", device->id, pbx_str_buffer(ha_buf)); struct ast_hostent ahp; struct hostent *hp; sccp_hostname_t *permithost; uint8_t i = 0; SCCP_LIST_TRAVERSE_SAFE_BEGIN(&device->permithosts, permithost, list) { if ((hp = pbx_gethostbyname(permithost->name, &ahp))) { for (i = 0; NULL != hp->h_addr_list[i]; i++) { // walk resulting ip address if (sin.sin_addr.s_addr == (*(struct in_addr *) hp->h_addr_list[i]).s_addr) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: permithost = %s match found.\n", device->id, permithost->name); matchesACL = TRUE; continue; } } } else { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: Invalid address resolution for permithost = %s (skipping permithost).\n", device->id, permithost->name); } } SCCP_LIST_TRAVERSE_SAFE_END; } else { matchesACL = TRUE; } sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: checkACL returning %s\n", device->id, matchesACL ? "TRUE" : "FALSE"); return matchesACL; } /*! * \brief run before reload is start on devices * \note See \ref sccp_config_reload * * \callgraph * \callergraph * * \lock * - devices * - device->buttonconfig */ void sccp_device_pre_reload(void) { sccp_device_t *d; sccp_buttonconfig_t *config; SCCP_RWLIST_WRLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_2 "%s: Setting Device to Pending Delete=1\n", d->id); sccp_free_ha(d->ha); d->ha = NULL; if (!d->realtime) { /* don't want to reset hotline devices. */ d->pendingDelete = 1; } d->pendingUpdate = 0; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { config->pendingDelete = 1; config->pendingUpdate = 0; } SCCP_LIST_UNLOCK(&d->buttonconfig); } SCCP_RWLIST_UNLOCK(&GLOB(devices)); } /*! * \brief Check Device Update Status * \note See \ref sccp_config_reload * \param d SCCP Device * \return Result as Boolean * * \callgraph * \callergraph * * \lock * - device * - see sccp_device_numberOfChannels() * - see sccp_device_sendReset() * - see sccp_session_close() * - device->buttonconfig */ boolean_t sccp_device_check_update(sccp_device_t * d) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "device: %s check_update, pendingUpdate: %s, pendingDelete: %s\n", d->id, d->pendingUpdate ? "TRUE" : "FALSE", d->pendingDelete ? "TRUE" : "FALSE"); boolean_t res = FALSE; if (d && (d->pendingUpdate || d->pendingDelete)) { do { if ((d = sccp_device_retain(d))) { if (sccp_device_numberOfChannels(d) > 0) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "device: %s check_update, openchannel: %d -> device restart pending.\n", d->id, sccp_device_numberOfChannels(d)); break; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "Device %s needs to be reset because of a change in sccp.conf (Update:%d, Delete:%d)\n", d->id, d->pendingUpdate, d->pendingDelete); d->pendingUpdate = 0; if (d->pendingDelete) { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Remove Device from List\n", d->id); sccp_dev_clean(d, TRUE, 0); } else { sccp_dev_clean(d, FALSE, 0); sccp_buttonconfig_t *buttonconfig; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE_SAFE_BEGIN(&d->buttonconfig, buttonconfig, list) { if (!buttonconfig->pendingDelete && !buttonconfig->pendingUpdate) continue; if (buttonconfig->pendingDelete) { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "Remove Buttonconfig for %s from List\n", d->id); SCCP_LIST_REMOVE_CURRENT(list); sccp_free(buttonconfig); } else { buttonconfig->pendingUpdate = 0; } } SCCP_LIST_TRAVERSE_SAFE_END; SCCP_LIST_UNLOCK(&d->buttonconfig); } d = sccp_device_release(d); res = TRUE; } } while (0); } return res; } /*! * \brief run after the new device config is loaded during the reload process * \note See \ref sccp_config_reload * * \callgraph * \callergraph * * \lock * - devices * - see sccp_device_check_update() */ void sccp_device_post_reload(void) { sccp_device_t *d; SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (!d->pendingDelete && !d->pendingUpdate) continue; /* Because of the previous check, the only reason that the device hasn't * been updated will be because it is currently engaged in a call. */ if (!sccp_device_check_update(d)) { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "Device %s will receive reset after current call is completed\n", d->id); } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); } /*! * \brief create a device and adding default values. * \return retained device with default/global values * * \callgraph * \callergraph */ sccp_device_t *sccp_device_create(const char *id) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "SCCP: Create Device\n"); sccp_device_t *d = (sccp_device_t *) sccp_refcount_object_alloc(sizeof(sccp_device_t), SCCP_REF_DEVICE, id, __sccp_device_destroy); if (!d) { sccp_log(0) (VERBOSE_PREFIX_3 "Unable to allocate memory for a device\n"); return NULL; } memset(d, 0, sizeof(sccp_device_t)); pbx_mutex_init(&d->lock); sccp_copy_string(d->id, id, sizeof(d->id)); SCCP_LIST_HEAD_INIT(&d->buttonconfig); SCCP_LIST_HEAD_INIT(&d->selectedChannels); SCCP_LIST_HEAD_INIT(&d->addons); #ifdef CS_DEVSTATE_FEATURE SCCP_LIST_HEAD_INIT(&d->devstateSpecifiers); #endif memset(d->softKeyConfiguration.activeMask, 0xFF, sizeof(d->softKeyConfiguration.activeMask)); d->softKeyConfiguration.modes = (softkey_modes *) SoftKeyModes; d->softKeyConfiguration.size = ARRAY_LEN(SoftKeyModes); d->state = SCCP_DEVICESTATE_ONHOOK; d->postregistration_thread = AST_PTHREADT_STOP; d->registrationState = SKINNY_DEVICE_RS_NONE; // set minimum protocol levels // d->protocolversion = SCCP_DRIVER_SUPPORTED_PROTOCOL_LOW; // d->protocol = sccp_protocol_getDeviceProtocol(d, SCCP_PROTOCOL); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "Init MessageStack\n"); /* initialize messageStack */ #ifndef SCCP_ATOMIC pbx_mutex_init(&d->messageStackLock); sccp_mutex_lock(&d->messageStackLock); #endif uint8_t i; for (i = 0; i < ARRAY_LEN(d->messageStack); i++) { d->messageStack[i] = NULL; } #ifndef SCCP_ATOMIC sccp_mutex_unlock(&d->messageStackLock); #endif // /* disable videomode and join softkey for all softkeysets */ // for (i = 0; i < KEYMODE_ONHOOKSTEALABLE; i++) { // sccp_softkey_setSoftkeyState(d, i, SKINNY_LBL_VIDEO_MODE, FALSE); // sccp_softkey_setSoftkeyState(d, i, SKINNY_LBL_JOIN, FALSE); // } d->pushURL = sccp_device_pushURLNotSupported; d->pushTextMessage = sccp_device_pushTextMessageNotSupported; d->checkACL = sccp_device_checkACL; d->hasDisplayPrompt = sccp_device_trueResult; d->setBackgroundImage = sccp_device_setBackgroundImageNotSupported; d->displayBackgroundImagePreview = sccp_device_displayBackgroundImagePreviewNotSupported; d->retrieveDeviceCapabilities = sccp_device_retrieveDeviceCapabilities; d->setRingTone = sccp_device_setRingtoneNotSupported; d->pendingUpdate = 0; d->pendingDelete = 0; return d; } /*! * \brief create an anonymous device and adding default values. * \return retained device with default/global values * * \callgraph * \callergraph */ sccp_device_t *sccp_device_createAnonymous(const char *name) { sccp_device_t *d = sccp_device_create(name); if (!d) { pbx_log(LOG_ERROR, "SCCP: sccp_device_create(%s) failed", name); return NULL; } d->realtime = TRUE; d->isAnonymous = TRUE; d->checkACL = sccp_device_checkACLTrue; return d; } /*! * \brief set type of Indicate protocol by device type */ void sccp_device_setIndicationProtocol(sccp_device_t * device) { switch (device->skinny_type) { // case SKINNY_DEVICETYPE_30SPPLUS: // case SKINNY_DEVICETYPE_30VIP: // case SKINNY_DEVICETYPE_12SPPLUS: // case SKINNY_DEVICETYPE_12SP: // case SKINNY_DEVICETYPE_12: // case SKINNY_DEVICETYPE_CISCO7902: // case SKINNY_DEVICETYPE_CISCO7912: // case SKINNY_DEVICETYPE_CISCO7911: // case SKINNY_DEVICETYPE_CISCO7906: // case SKINNY_DEVICETYPE_CISCO7905: // case SKINNY_DEVICETYPE_CISCO7931: // case SKINNY_DEVICETYPE_CISCO7935: // case SKINNY_DEVICETYPE_CISCO7936: // case SKINNY_DEVICETYPE_CISCO7937: // case SKINNY_DEVICETYPE_CISCO7910: // case SKINNY_DEVICETYPE_CISCO7940: // case SKINNY_DEVICETYPE_CISCO7960: case SKINNY_DEVICETYPE_CISCO7941: case SKINNY_DEVICETYPE_CISCO7941GE: case SKINNY_DEVICETYPE_CISCO7942: case SKINNY_DEVICETYPE_CISCO7945: // case SKINNY_DEVICETYPE_CISCO7920: case SKINNY_DEVICETYPE_CISCO7921: case SKINNY_DEVICETYPE_CISCO7925: case SKINNY_DEVICETYPE_CISCO7985: case SKINNY_DEVICETYPE_CISCO7961: case SKINNY_DEVICETYPE_CISCO7961GE: case SKINNY_DEVICETYPE_CISCO7962: case SKINNY_DEVICETYPE_CISCO7965: case SKINNY_DEVICETYPE_CISCO7970: case SKINNY_DEVICETYPE_CISCO7971: case SKINNY_DEVICETYPE_CISCO7975: case SKINNY_DEVICETYPE_CISCO_IP_COMMUNICATOR: device->indicate = &sccp_device_indication_newerDevices; break; default: device->indicate = &sccp_device_indication_olderDevices; break; } return; } /*! * \brief Add a device to the global sccp_device list * \param device SCCP Device * \return SCCP Device * * \note needs to be called with a retained device * \note adds a retained device to the list (refcount + 1) * \lock * - devices */ void sccp_device_addToGlobals(sccp_device_t * device) { if (!device) { pbx_log(LOG_ERROR, "Adding null to the global device list is not allowed!\n"); return; } device = sccp_device_retain(device); SCCP_RWLIST_WRLOCK(&GLOB(devices)); SCCP_RWLIST_INSERT_SORTALPHA(&GLOB(devices), device, list, id); SCCP_RWLIST_UNLOCK(&GLOB(devices)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "Added device '%s' (%s) to Glob(devices)\n", device->id, device->config_type); } /*! * \brief Removes a device from the global sccp_device list * \param device SCCP Device * \return device or NULL * * \note needs to be called with a retained device * \note removes the retained device withing the list (refcount - 1) * \lock * - devices */ sccp_device_t *sccp_device_removeFromGlobals(sccp_device_t * device) { if (!device) { pbx_log(LOG_ERROR, "Removing null from the global device list is not allowed!\n"); return NULL; } SCCP_RWLIST_WRLOCK(&GLOB(devices)); device = SCCP_RWLIST_REMOVE(&GLOB(devices), device, list); sccp_device_release(device); SCCP_RWLIST_UNLOCK(&GLOB(devices)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "Removed device '%s' (%s) from Glob(devices)\n", device->id, device->config_type); return device; } /*! * \brief Create a template of Buttons as Definition for a Phonetype (d->skinny_type) * \param d device * \param btn buttonlist */ void sccp_dev_build_buttontemplate(sccp_device_t * d, btnlist * btn) { uint8_t i; sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_BUTTONTEMPLATE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Building button template %s(%d), user config %s\n", d->id, devicetype2str(d->skinny_type), d->skinny_type, d->config_type); switch (d->skinny_type) { case SKINNY_DEVICETYPE_30SPPLUS: case SKINNY_DEVICETYPE_30VIP: for (i = 0; i < 4; i++) (btn++)->type = SCCP_BUTTONTYPE_LINE; for (i = 0; i < 9; i++) (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; /* Column 2 */ (btn++)->type = SKINNY_BUTTONTYPE_VOICEMAIL; (btn++)->type = SKINNY_BUTTONTYPE_FORWARDALL; (btn++)->type = SKINNY_BUTTONTYPE_CONFERENCE; (btn++)->type = SKINNY_BUTTONTYPE_CALLPARK; for (i = 0; i < 9; i++) (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; break; case SKINNY_DEVICETYPE_12SPPLUS: case SKINNY_DEVICETYPE_12SP: case SKINNY_DEVICETYPE_12: (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SKINNY_BUTTONTYPE_LASTNUMBERREDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SKINNY_BUTTONTYPE_HOLD; (btn++)->type = SKINNY_BUTTONTYPE_TRANSFER; (btn++)->type = SKINNY_BUTTONTYPE_FORWARDALL; (btn++)->type = SKINNY_BUTTONTYPE_CALLPARK; (btn++)->type = SKINNY_BUTTONTYPE_VOICEMAIL; (btn++)->type = SKINNY_BUTTONTYPE_CONFERENCE; break; case SKINNY_DEVICETYPE_CISCO7902: (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SKINNY_BUTTONTYPE_HOLD; (btn++)->type = SKINNY_BUTTONTYPE_TRANSFER; (btn++)->type = SKINNY_BUTTONTYPE_DISPLAY; (btn++)->type = SKINNY_BUTTONTYPE_VOICEMAIL; (btn++)->type = SKINNY_BUTTONTYPE_CONFERENCE; (btn++)->type = SKINNY_BUTTONTYPE_FORWARDALL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SKINNY_BUTTONTYPE_LASTNUMBERREDIAL; break; case SKINNY_DEVICETYPE_CISCO7912: case SKINNY_DEVICETYPE_CISCO7911: case SKINNY_DEVICETYPE_CISCO7906: case SKINNY_DEVICETYPE_CISCO7905: (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SKINNY_BUTTONTYPE_HOLD; for (i = 0; i < 9; i++) (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; break; case SKINNY_DEVICETYPE_CISCO7931: for (i = 0; i < 20; i++) { btn[i].type = SCCP_BUTTONTYPE_MULTI; } btn[20].type = SKINNY_BUTTONTYPE_MESSAGES; btn[20].instance = 21; btn[21].type = SKINNY_BUTTONTYPE_DIRECTORY; btn[21].instance = 22; btn[22].type = SKINNY_BUTTONTYPE_HEADSET; btn[22].instance = 23; btn[23].type = SKINNY_BUTTONTYPE_APPLICATION; btn[23].instance = 24; break; case SKINNY_DEVICETYPE_CISCO7935: case SKINNY_DEVICETYPE_CISCO7936: case SKINNY_DEVICETYPE_CISCO7937: (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SCCP_BUTTONTYPE_LINE; break; case SKINNY_DEVICETYPE_CISCO7910: (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SKINNY_BUTTONTYPE_HOLD; (btn++)->type = SKINNY_BUTTONTYPE_TRANSFER; (btn++)->type = SKINNY_BUTTONTYPE_DISPLAY; (btn++)->type = SKINNY_BUTTONTYPE_VOICEMAIL; (btn++)->type = SKINNY_BUTTONTYPE_CONFERENCE; (btn++)->type = SKINNY_BUTTONTYPE_FORWARDALL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; (btn++)->type = SKINNY_BUTTONTYPE_LASTNUMBERREDIAL; break; case SKINNY_DEVICETYPE_CISCO7940: case SKINNY_DEVICETYPE_CISCO7941: case SKINNY_DEVICETYPE_CISCO7941GE: case SKINNY_DEVICETYPE_CISCO7942: case SKINNY_DEVICETYPE_CISCO7945: /* add text message support */ d->pushTextMessage = sccp_device_pushTextMessage; d->pushURL = sccp_device_pushURL; for (i = 2 + sccp_addons_taps(d); i > 0; i--) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } break; case SKINNY_DEVICETYPE_CISCO7920: case SKINNY_DEVICETYPE_CISCO7921: case SKINNY_DEVICETYPE_CISCO7925: for (i = 0; i < 6; i++) (btn++)->type = SCCP_BUTTONTYPE_MULTI; break; case SKINNY_DEVICETYPE_CISCO7985: d->capabilities.video[0] = SKINNY_CODEC_H264; d->capabilities.video[1] = SKINNY_CODEC_H263; #ifdef CS_SCCP_VIDEO sccp_softkey_setSoftkeyState(d, KEYMODE_CONNTRANS, SKINNY_LBL_VIDEO_MODE, TRUE); #endif for (i = 0; i < 1; i++) (btn++)->type = SCCP_BUTTONTYPE_MULTI; break; case SKINNY_DEVICETYPE_CISCO7960: case SKINNY_DEVICETYPE_CISCO7961: case SKINNY_DEVICETYPE_CISCO7961GE: case SKINNY_DEVICETYPE_CISCO7962: case SKINNY_DEVICETYPE_CISCO7965: /* add text message support */ d->pushTextMessage = sccp_device_pushTextMessage; d->pushURL = sccp_device_pushURL; for (i = 6 + sccp_addons_taps(d); i > 0; i--) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } break; case SKINNY_DEVICETYPE_CISCO7970: case SKINNY_DEVICETYPE_CISCO7971: case SKINNY_DEVICETYPE_CISCO7975: case SKINNY_DEVICETYPE_CISCO_IP_COMMUNICATOR: /* the nokia icc client identifies it self as SKINNY_DEVICETYPE_CISCO7970, but it can only have one line */ if (!strcasecmp(d->config_type, "nokia-icc")) { // this is for nokia icc legacy support (Old releases) -FS (btn++)->type = SCCP_BUTTONTYPE_MULTI; } else { for (i = 8 + sccp_addons_taps(d); i > 0; i--) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } /* add text message support */ d->pushTextMessage = sccp_device_pushTextMessage; d->pushURL = sccp_device_pushURL; d->setBackgroundImage = sccp_device_setBackgroundImage; d->displayBackgroundImagePreview = sccp_device_displayBackgroundImagePreview; d->setRingTone = sccp_device_setRingtone; } break; case SKINNY_DEVICETYPE_NOKIA_ICC: (btn++)->type = SCCP_BUTTONTYPE_MULTI; break; case SKINNY_DEVICETYPE_NOKIA_E_SERIES: (btn++)->type = SCCP_BUTTONTYPE_LINE; (btn++)->type = SCCP_BUTTONTYPE_LINE; for (i = 0; i < 5; i++) (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; break; case SKINNY_DEVICETYPE_ATA186: //case SKINNY_DEVICETYPE_ATA188: (btn++)->type = SCCP_BUTTONTYPE_LINE; for (i = 0; i < 4; i++) (btn++)->type = SCCP_BUTTONTYPE_SPEEDDIAL; break; case SKINNY_DEVICETYPE_CISCO8941: case SKINNY_DEVICETYPE_CISCO8945: d->capabilities.video[0] = SKINNY_CODEC_H264; d->capabilities.video[1] = SKINNY_CODEC_H263; #ifdef CS_SCCP_VIDEO sccp_softkey_setSoftkeyState(d, KEYMODE_CONNTRANS, SKINNY_LBL_VIDEO_MODE, TRUE); #endif d->hasDisplayPrompt = sccp_device_falseResult; for (i = 0; i < 10; i++) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } (btn++)->type = SKINNY_BUTTONTYPE_CONFERENCE; (btn++)->type = SKINNY_BUTTONTYPE_HOLD; (btn++)->type = SKINNY_BUTTONTYPE_TRANSFER; (btn++)->type = SKINNY_BUTTONTYPE_LASTNUMBERREDIAL; break; case SKINNY_DEVICETYPE_SPA_521S: for (i = 0; i < 1; i++) (btn++)->type = SCCP_BUTTONTYPE_MULTI; break; case SKINNY_DEVICETYPE_SPA_525G2: for (i = 0; i < 8; i++) (btn++)->type = SCCP_BUTTONTYPE_MULTI; break; case SKINNY_DEVICETYPE_CISCO6901: case SKINNY_DEVICETYPE_CISCO6911: (btn++)->type = SCCP_BUTTONTYPE_MULTI; break; case SKINNY_DEVICETYPE_CISCO6921: for (i = 0; i < 2; i++) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } d->hasDisplayPrompt = sccp_device_falseResult; break; case SKINNY_DEVICETYPE_CISCO6941: case SKINNY_DEVICETYPE_CISCO6945: for (i = 0; i < 4; i++) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } d->hasDisplayPrompt = sccp_device_falseResult; break; case SKINNY_DEVICETYPE_CISCO6961: for (i = 0; i < 12; i++) { (btn++)->type = SCCP_BUTTONTYPE_MULTI; } d->hasDisplayPrompt = sccp_device_falseResult; break; default: /* at least one line */ (btn++)->type = SCCP_BUTTONTYPE_LINE; break; } return; } /*! * \brief Build an SCCP Message Packet * \param[in] t SCCP Message Text * \param[out] pkt_len Packet Length * \return SCCP Message */ sccp_moo_t *sccp_build_packet(sccp_message_t t, size_t pkt_len) { sccp_moo_t *r = sccp_malloc(pkt_len + SCCP_PACKET_HEADER); if (!r) { pbx_log(LOG_WARNING, "SCCP: Packet memory allocation error\n"); return NULL; } memset(r, 0, pkt_len + SCCP_PACKET_HEADER); r->header.length = htolel(pkt_len + 4); r->header.lel_messageId = htolel(t); return r; } /*! * \brief Send SCCP Message to Device * \param d SCCP Device * \param r SCCP MOO Message * \return Status as int * * \callgraph */ int sccp_dev_send(const sccp_device_t * d, sccp_moo_t * r) { int result = -1; if (d && d->session && r) { sccp_log((DEBUGCAT_MESSAGE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: >> Send message %s\n", d->id, message2str(letohl(r->header.lel_messageId))); result = sccp_session_send(d, r); } else { sccp_free(r); } return result; } /*! * \brief Send an SCCP message to a device * \param d SCCP Device * \param t SCCP Message * * \callgraph * \callergraph */ void sccp_dev_sendmsg(const sccp_device_t * d, sccp_message_t t) { if (d) sccp_session_sendmsg(d, t); } /*! * \brief Register a Device * \param d SCCP Device * \param opt Option/Registration State as int */ void sccp_dev_set_registered(sccp_device_t * d, uint8_t opt) { sccp_event_t event; sccp_moo_t *r; sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: (sccp_dev_set_registered) Setting Registered Status for Device from %s to %s\n", DEV_ID_LOG(d), registrationstate2str(d->registrationState), registrationstate2str(opt)); if (d->registrationState == opt) return; d->registrationState = opt; /* Handle registration completion. */ if (opt == SKINNY_DEVICE_RS_OK) { /* this message is mandatory to finish process */ REQ(r, SetLampMessage); if (r) { r->msg.SetLampMessage.lel_stimulus = htolel(SKINNY_STIMULUS_VOICEMAIL); r->msg.SetLampMessage.lel_stimulusInstance = 0; r->msg.SetLampMessage.lel_lampMode = (d->mwilight & ~(1 << 0)) ? htolel(d->mwilamp) : htolel(SKINNY_LAMP_OFF); // d->mwilight &= ~(1 << 0); sccp_dev_send(d, r); } if (!d->linesRegistered) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Device does not support RegisterAvailableLinesMessage, force this\n", DEV_ID_LOG(d)); sccp_handle_AvailableLines(d->session, d, NULL); d->linesRegistered = TRUE; } sccp_dev_postregistration(d); } else if (opt == SKINNY_DEVICE_RS_PROGRESS) { memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_DEVICE_PREREGISTERED; event.event.deviceRegistered.device = sccp_device_retain(d); sccp_event_fire(&event); } d->registrationTime = time(0); } /*! * \brief Sets the SCCP Device's SoftKey Mode Specified by opt * \param d SCCP Device * \param line Line as uint8_t * \param callid Call ID as uint8_t * \param softKeySetIndex SoftKeySet Index * \todo Disable DirTrfr by Default */ void sccp_dev_set_keyset(const sccp_device_t * d, uint8_t line, uint32_t callid, uint8_t softKeySetIndex) { sccp_moo_t *r; if (!d) return; if (!d->softkeysupport) return; /* the device does not support softkeys */ /*let's activate the transfer */ if (softKeySetIndex == KEYMODE_CONNECTED) softKeySetIndex = ( #if CS_SCCP_CONFERENCE (d->conference) ? KEYMODE_CONNCONF : #endif (d->transfer) ? KEYMODE_CONNTRANS : KEYMODE_CONNECTED); REQ(r, SelectSoftKeysMessage); if (!r) return; r->msg.SelectSoftKeysMessage.lel_lineInstance = htolel(line); r->msg.SelectSoftKeysMessage.lel_callReference = htolel(callid); r->msg.SelectSoftKeysMessage.lel_softKeySetIndex = htolel(softKeySetIndex); if ((softKeySetIndex == KEYMODE_ONHOOK || softKeySetIndex == KEYMODE_OFFHOOK || softKeySetIndex == KEYMODE_OFFHOOKFEAT) && (sccp_strlen_zero(d->lastNumber) #ifdef CS_ADV_FEATURES && !d->useRedialMenu #endif ) ) { sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_REDIAL, FALSE); } #if CS_SCCP_CONFERENCE if (d->allow_conference) { sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_CONFRN, TRUE); sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_CONFLIST, TRUE); sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_JOIN, TRUE); } else { sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_CONFRN, FALSE); sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_CONFLIST, FALSE); sccp_softkey_setSoftkeyState((sccp_device_t *) d, softKeySetIndex, SKINNY_LBL_JOIN, FALSE); } #endif //r->msg.SelectSoftKeysMessage.les_validKeyMask = 0xFFFFFFFF; /* htolel(65535); */ r->msg.SelectSoftKeysMessage.les_validKeyMask = htolel(d->softKeyConfiguration.activeMask[softKeySetIndex]); sccp_log((DEBUGCAT_SOFTKEY | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send softkeyset to %s(%d) on line %d and call %d\n", d->id, keymode2str(softKeySetIndex), softKeySetIndex, line, callid); sccp_dev_send(d, r); } /*! * \brief Set Ringer on Device * \param d SCCP Device * \param opt Option as uint8_t * \param lineInstance LineInstance as uint32_t * \param callid Call ID as uint32_t */ void sccp_dev_set_ringer(const sccp_device_t * d, uint8_t opt, uint8_t lineInstance, uint32_t callid) { sccp_moo_t *r; REQ(r, SetRingerMessage); if (!r) return; r->msg.SetRingerMessage.lel_ringMode = htolel(opt); /* Note that for distinctive ringing to work with the higher protocol versions the following actually needs to be set to 1 as the original comment says. Curiously, the variable is not set to 1 ... */ r->msg.SetRingerMessage.lel_unknown1 = htolel(1); /* always 1 */ r->msg.SetRingerMessage.lel_lineInstance = htolel(lineInstance); r->msg.SetRingerMessage.lel_callReference = htolel(callid); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send ringer mode %s(%d) on device\n", DEV_ID_LOG(d), ringtype2str(opt), opt); } /*! * \brief Set Speaker Status on Device * \param d SCCP Device * \param mode Speaker Mode as uint8_t */ void sccp_dev_set_speaker(const sccp_device_t * d, uint8_t mode) { sccp_moo_t *r; if (!d || !d->session) return; REQ(r, SetSpeakerModeMessage); if (!r) return; r->msg.SetSpeakerModeMessage.lel_speakerMode = htolel(mode); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send speaker mode %d\n", d->id, mode); } /*! * \brief Set Microphone Status on Device * \param d SCCP Device * \param mode Microphone Mode as uint8_t */ void sccp_dev_set_microphone(sccp_device_t * d, uint8_t mode) { sccp_moo_t *r; if (!d || !d->session) return; REQ(r, SetMicroModeMessage); if (!r) return; r->msg.SetMicroModeMessage.lel_micMode = htolel(mode); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send microphone mode %d\n", d->id, mode); } /*! * \brief Set Call Plane to Active on Line on Device * \param device SCCP Device * \param lineInstance lineInstance as unint8_t * \param status Status as int * \todo What does this function do exactly (ActivateCallPlaneMessage) ? * * \callgraph * \callergraph */ void sccp_dev_set_cplane(const sccp_device_t * device, uint8_t lineInstance, int status) { sccp_moo_t *r; if (!device) return; REQ(r, ActivateCallPlaneMessage); if (!r) return; if (status) r->msg.ActivateCallPlaneMessage.lel_lineInstance = htolel(lineInstance); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send activate call plane on line %d\n", device->id, (status) ? lineInstance : 0); } /*! * \brief Set Call Plane to In-Active on Line on Device * \param d device * \todo What does this function do exactly (DeactivateCallPlaneMessage) ? * * \callgraph * \callergraph */ void sccp_dev_deactivate_cplane(sccp_device_t * d) { if (!d) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "Null device for deactivate callplane\n"); return; } sccp_dev_sendmsg(d, DeactivateCallPlaneMessage); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send deactivate call plane\n", d->id); } /*! * \brief Send Start Tone to Device * \param d SCCP Device * \param tone Tone as uint8_t * \param line Line as uint8_t * \param callid Call ID as uint32_t * \param timeout Timeout as uint32_t */ void sccp_dev_starttone(const sccp_device_t * d, uint8_t tone, uint8_t line, uint32_t callid, uint32_t timeout) { sccp_moo_t *r; if (!d) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "Null device for device starttone\n"); return; } REQ(r, StartToneMessage); if (!r) return; r->msg.StartToneMessage.lel_tone = htolel(tone); r->msg.StartToneMessage.lel_toneTimeout = htolel(timeout); r->msg.StartToneMessage.lel_lineInstance = htolel(line); r->msg.StartToneMessage.lel_callReference = htolel(callid); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Sending tone %s (%d)\n", d->id, tone2str(tone), tone); } /*! * \brief Send Stop Tone to Device * \param d SCCP Device * \param line Line as uint8_t * \param callid Call ID as uint32_t */ void sccp_dev_stoptone(const sccp_device_t * d, uint8_t line, uint32_t callid) { sccp_moo_t *r; if (!d || !d->session) return; REQ(r, StopToneMessage); if (!r) return; r->msg.StopToneMessage.lel_lineInstance = htolel(line); r->msg.StopToneMessage.lel_callReference = htolel(callid); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Stop tone on device\n", d->id); } /*! * \brief Set Message on Display Prompt of Device * \param d SCCP Device * \param msg Msg as char * \param timeout Timeout as int * \param storedb Store in the pbx database * \param beep Beep on device when message is received * * \callgraph * \callergraph */ void sccp_dev_set_message(sccp_device_t * d, const char *msg, const int timeout, const boolean_t storedb, const boolean_t beep) { if (storedb) { char msgtimeout[10]; sprintf(msgtimeout, "%d", timeout); PBX(feature_addToDatabase) ("SCCP/message", "timeout", strdup(msgtimeout)); PBX(feature_addToDatabase) ("SCCP/message", "text", msg); } if (timeout) { sccp_dev_displayprinotify(d, msg, 5, timeout); } else { sccp_device_addMessageToStack(d, SCCP_MESSAGE_PRIORITY_IDLE, msg); } if (beep) { sccp_dev_starttone(d, SKINNY_TONE_ZIPZIP, 0, 0, 0); } } /*! * \brief Clear Message from Display Prompt of Device * \param d SCCP Device * \param cleardb Clear from the pbx database * * \callgraph * \callergraph */ void sccp_dev_clear_message(sccp_device_t * d, const boolean_t cleardb) { if (cleardb) { PBX(feature_removeTreeFromDatabase) ("SCCP/message", "timeout"); PBX(feature_removeTreeFromDatabase) ("SCCP/message", "text"); } sccp_device_clearMessageFromStack(d, SCCP_MESSAGE_PRIORITY_IDLE); // sccp_dev_clearprompt(d, 0, 0); sccp_dev_cleardisplay(d); } /*! * \brief Send Clear Prompt to Device * \param d SCCP Device * \param lineInstance LineInstance as uint8_t * \param callid Call ID uint32_t * * \callgraph * \callergraph */ void sccp_dev_clearprompt(const sccp_device_t * d, const uint8_t lineInstance, const uint32_t callid) { sccp_moo_t *r; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ REQ(r, ClearPromptStatusMessage); if (!r) return; r->msg.ClearPromptStatusMessage.lel_callReference = htolel(callid); r->msg.ClearPromptStatusMessage.lel_lineInstance = htolel(lineInstance); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Clear the status prompt on line %d and callid %d\n", d->id, lineInstance, callid); } /*! * \brief Send Display Prompt to Device * \param d SCCP Device * \param lineInstance Line instance as uint8_t * \param callid Call ID uint32_t * \param msg Msg as char * \param timeout Timeout as int * \param file Source File * \param lineno Source Line * \param pretty_function CB Function to Print * * \callgraph * \callergraph */ //void sccp_dev_displayprompt(sccp_device_t * d, uint8_t line, uint32_t callid, char *msg, int timeout) void sccp_dev_displayprompt_debug(const sccp_device_t * d, const uint8_t lineInstance, const uint32_t callid, const char *msg, const int timeout, const char *file, int lineno, const char *pretty_function) { #if DEBUG sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: ( %s:%d:%s ) sccp_dev_displayprompt '%s' for line %d (%d)\n", DEV_ID_LOG(d), file, lineno, pretty_function, msg, lineInstance, timeout); #endif if (!d || !d->session || !d->protocol || !d->skinny_type || !d->config_type) return; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ d->protocol->displayPrompt(d, lineInstance, callid, timeout, msg); } /*! * \brief Send Clear Display to Device * \param d SCCP Device * * \callgraph * \callergraph */ void sccp_dev_cleardisplay(const sccp_device_t * d) { if (!d) return; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ sccp_dev_sendmsg(d, ClearDisplay); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Clear the display\n", d->id); } /*! * \brief Send Display to Device * \param d SCCP Device * \param msg Msg as char * \param file Source File * \param lineno Source Line * \param pretty_function CB Function to Print * * \callgraph * \callergraph */ //void sccp_dev_display(sccp_device_t * d, char *msg) void sccp_dev_display_debug(const sccp_device_t * d, const char *msg, const char *file, const int lineno, const char *pretty_function) { #if DEBUG sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: ( %s:%d:%s ) sccp_dev_display '%s'\n", DEV_ID_LOG(d), file, lineno, pretty_function, msg); #endif sccp_moo_t *r; if (!d || !d->session) return; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ if (!msg || sccp_strlen_zero(msg)) return; REQ(r, DisplayTextMessage); if (!r) return; sccp_copy_string(r->msg.DisplayTextMessage.displayMessage, msg, sizeof(r->msg.DisplayTextMessage.displayMessage)); sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Display text\n", d->id); } /*! * \brief Send Clear Display Notification to Device * \param d SCCP Device * * \callgraph * \callergraph */ void sccp_dev_cleardisplaynotify(const sccp_device_t * d) { if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ sccp_dev_sendmsg(d, ClearNotifyMessage); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Clear the display notify message\n", d->id); } /*! * \brief Send Display Notification to Device * \param d SCCP Device * \param msg Msg as char * \param timeout Timeout as uint8_t * \param file Source File * \param lineno Source Line * \param pretty_function CB Function to Print * * \callgraph * \callergraph */ //void sccp_dev_displaynotify(sccp_device_t * d, char *msg, uint32_t timeout) void sccp_dev_displaynotify_debug(const sccp_device_t * d, const char *msg, uint8_t timeout, const char *file, const int lineno, const char *pretty_function) { // #if DEBUG sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: ( %s:%d:%s ) sccp_dev_displaynotify '%s' (%d)\n", DEV_ID_LOG(d), file, lineno, pretty_function, msg, timeout); // #endif if (!d || !d->session || !d->protocol || !d->skinny_type || !d->config_type) return; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ if (!msg || sccp_strlen_zero(msg)) return; d->protocol->displayNotify(d, timeout, msg); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Display notify with timeout %d\n", d->id, timeout); } /*! * \brief Send Clear Display Notification to Device * \param d SCCP Device * * \callgraph * \callergraph */ void sccp_dev_cleardisplayprinotify(const sccp_device_t * d) { if (!d || !d->session) return; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ sccp_dev_sendmsg(d, ClearPriNotifyMessage); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_MESSAGE)) (VERBOSE_PREFIX_3 "%s: Clear the display priority notify message\n", d->id); } /*! * \brief Send Display Priority Notification to Device * \param d SCCP Device * \param msg Msg as char * \param priority Priority as uint8_t * \param timeout Timeout as uint8_t * \param file Source File * \param lineno Source Line * \param pretty_function CB Function to Print * * \callgraph * \callergraph */ //void sccp_dev_displayprinotify(sccp_device_t * d, char *msg, uint32_t priority, uint32_t timeout) void sccp_dev_displayprinotify_debug(const sccp_device_t * d, const char *msg, const uint8_t priority, const uint8_t timeout, const char *file, const int lineno, const char *pretty_function) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: ( %s:%d:%s ) sccp_dev_displayprinotify '%s' (%d/%d)\n", DEV_ID_LOG(d), file, lineno, pretty_function, msg, timeout, priority); if (!d || !d->session || !d->protocol || !d->skinny_type || !d->config_type) return; if (d->skinny_type < 6 || d->skinny_type == SKINNY_DEVICETYPE_ATA186 || (!strcasecmp(d->config_type, "kirk"))) return; /* only for telecaster and new phones */ if (!msg || sccp_strlen_zero(msg)) return; d->protocol->displayPriNotify(d, priority, timeout, msg); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Display notify with timeout %d and priority %d\n", d->id, timeout, priority); } /*! * \brief Find SpeedDial by Index * \param d SCCP Device * \param instance Instance as uint8_t * \param withHint With Hint as boolean_t * \param k SCCP Speeddial (Returned by Ref) * \return Void * * \lock * - device->buttonconfig */ void sccp_dev_speed_find_byindex(sccp_device_t * d, uint16_t instance, boolean_t withHint, sccp_speed_t * k) { sccp_buttonconfig_t *config; if (!d || !d->session || instance == 0) return; memset(k, 0, sizeof(sccp_speed_t)); sccp_copy_string(k->name, "unknown speeddial", sizeof(k->name)); SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->type == SPEEDDIAL && config->instance == instance) { /* we are searching for hinted speeddials */ if (TRUE == withHint && sccp_strlen_zero(config->button.speeddial.hint)) { continue; } k->valid = TRUE; k->instance = instance; k->type = SCCP_BUTTONTYPE_SPEEDDIAL; sccp_copy_string(k->name, config->label, sizeof(k->name)); sccp_copy_string(k->ext, config->button.speeddial.ext, sizeof(k->ext)); if (!sccp_strlen_zero(config->button.speeddial.hint)) { sccp_copy_string(k->hint, config->button.speeddial.hint, sizeof(k->hint)); } } } SCCP_LIST_UNLOCK(&d->buttonconfig); } /*! * \brief Send Get Activeline to Device * \param d SCCP Device * \return SCCP Line * * \warning * - device->buttonconfig is not always locked */ sccp_line_t *sccp_dev_get_activeline(sccp_device_t * d) { sccp_buttonconfig_t *buttonconfig; if (!d || !d->session) return NULL; if (!d->currentLine) { SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) { if ((d->currentLine = sccp_line_find_byname(buttonconfig->button.line.name, FALSE))) { sccp_line_retain(d->currentLine); break; } } } if (d->currentLine) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Forcing the active line to %s from NULL\n", d->id, d->currentLine->name); return d->currentLine; } else { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: No lines\n", d->id); return NULL; } } else { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: The active line is %s\n", d->id, d->currentLine->name); return sccp_line_retain(d->currentLine); } return NULL; // never reached } /*! * \brief Set Activeline to Device * \param device SCCP Device * \param l SCCP Line * * \lock * - device */ void sccp_dev_set_activeline(sccp_device_t * device, const sccp_line_t * l) { if (!device || !device->session) return; /* nothing changed, just return */ if (l == device->currentLine) { return; } /* release old line and retain new one */ device->currentLine = device->currentLine ? sccp_line_release(device->currentLine) : NULL; device->currentLine = l ? sccp_line_retain((sccp_line_t *) l) : NULL; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Set the active line %s\n", device->id, l ? l->name : "(NULL)"); } /*! * \brief Reschedule Display Prompt Check * \param d SCCP Device * * \todo We have to decide on a standardized implementation of displayprompt to be used * For DND/Cfwd/Message/Voicemail/Private Status for Devices and Individual Lines * If necessary devicetypes could be deviced into 3-4 groups depending on their capability for displaying status the best way * * \callgraph * \callergraph */ void sccp_dev_check_displayprompt(sccp_device_t * d) { //sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE | DEBUGCAT_MESSAGE))(VERBOSE_PREFIX_1 "%s: (sccp_dev_check_displayprompt)\n", DEV_ID_LOG(d)); if (!d || !d->session) return; boolean_t message_set = FALSE; int i; if (d->hasDisplayPrompt()) { sccp_dev_clearprompt(d, 0, 0); #ifndef SCCP_ATOMIC sccp_mutex_lock(&d->messageStackLock); #endif for (i = SCCP_MAX_MESSAGESTACK - 1; i >= 0; i--) { if (d->messageStack[i] != NULL && !sccp_strlen_zero(d->messageStack[i])) { sccp_dev_displayprompt(d, 0, 0, d->messageStack[i], 0); message_set = TRUE; break; } } #ifndef SCCP_ATOMIC sccp_mutex_unlock(&d->messageStackLock); #endif } if (!message_set) { sccp_dev_displayprompt(d, 0, 0, SKINNY_DISP_YOUR_CURRENT_OPTIONS, 0); sccp_dev_set_keyset(d, 0, 0, KEYMODE_ONHOOK); /* this is for redial softkey */ } sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: Finish DisplayPrompt\n", d->id); } /*! * \brief Send forward status to a line on a device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param device SCCP Device * * \todo integration this function correctly into check sccp_dev_check_displayprompt * * \callgraph * \callergraph */ void sccp_dev_forward_status(sccp_line_t * l, uint8_t lineInstance, sccp_device_t * device) { sccp_linedevices_t *linedevice = NULL; if (!l || !device || !device->session) return; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Send Forward Status. Line: %s\n", device->id, l->name); //! \todo check for forward status during registration -MC //! \todo Needs to be revised. Does not make sense to call sccp_handle_AvailableLines from here if (device->registrationState != SKINNY_DEVICE_RS_OK) { if (!device->linesRegistered) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Device does not support RegisterAvailableLinesMessage, force this\n", DEV_ID_LOG(device)); sccp_handle_AvailableLines(device->session, device, NULL); device->linesRegistered = TRUE; } } if ((linedevice = sccp_linedevice_find(device, l))) { device->protocol->sendCallforwardMessage(device, linedevice); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Sent Forward Status. Line: %s (%d)\n", device->id, l->name, linedevice->lineInstance); sccp_linedevice_release(linedevice); } else { pbx_log(LOG_NOTICE, "%s: Device does not have line configured (no linedevice found)\n", DEV_ID_LOG(device)); } } /*! * \brief Check Ringback on Device * \param d SCCP Device * \return Result as int * * \lock * - device */ int sccp_device_check_ringback(sccp_device_t * d) { sccp_channel_t *c; if (!(d = sccp_device_retain(d))) { return 0; } d->needcheckringback = 0; if (d->state == SCCP_DEVICESTATE_OFFHOOK) { sccp_device_release(d); return 0; } c = sccp_channel_find_bystate_on_device(d, SCCP_CHANNELSTATE_CALLTRANSFER); if (!c) c = sccp_channel_find_bystate_on_device(d, SCCP_CHANNELSTATE_RINGING); if (!c) c = sccp_channel_find_bystate_on_device(d, SCCP_CHANNELSTATE_CALLWAITING); if (c) { sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGING); c = sccp_channel_release(c); return 1; } sccp_device_release(d); return 0; } /*! * \brief Handle Post Device Registration * \param data Data * * \callgraph * \callergraph * * \lock * -see sccp_hint_eventListener() via sccp_event_fire() */ void sccp_dev_postregistration(void *data) { sccp_device_t *d = data; sccp_event_t event; if (!d) return; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Device registered; performing post registration tasks...\n", d->id); // Post event to interested listeners (hints, mwi) that device was registered. memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_DEVICE_REGISTERED; event.event.deviceRegistered.device = sccp_device_retain(d); sccp_event_fire(&event); /* read status from db */ #ifndef ASTDB_FAMILY_KEY_LEN #define ASTDB_FAMILY_KEY_LEN 100 #endif #ifndef ASTDB_RESULT_LEN #define ASTDB_RESULT_LEN 80 #endif char family[ASTDB_FAMILY_KEY_LEN]; char buffer[ASTDB_RESULT_LEN] = { 0 }; sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: Getting Database Settings...\n", d->id); memset(family, 0, ASTDB_FAMILY_KEY_LEN); sprintf(family, "SCCP/%s", d->id); if (PBX(feature_getFromDatabase) (family, "dnd", buffer, sizeof(buffer)) && strcmp(buffer, "")) { sccp_config_parse_dnd(&d->dndFeature.status, sizeof(d->dndFeature.status), (const char *) buffer, SCCP_CONFIG_DEVICE_SEGMENT); sccp_feat_changed(d, NULL, SCCP_FEATURE_DND); } if (PBX(feature_getFromDatabase) (family, "privacy", buffer, sizeof(buffer)) && strcmp(buffer, "")) { d->privacyFeature.status = TRUE; sccp_feat_changed(d, NULL, SCCP_FEATURE_PRIVACY); } if (PBX(feature_getFromDatabase) (family, "monitor", buffer, sizeof(buffer)) && strcmp(buffer, "")) { sccp_feat_changed(d, NULL, SCCP_FEATURE_MONITOR); } if (d->backgroundImage) { d->setBackgroundImage(d, d->backgroundImage); } if (d->ringtone) { d->setRingTone(d, d->ringtone); } sccp_dev_check_displayprompt(d); sccp_mwi_check(d); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: Post registration process... done!\n", d->id); return; } /*! * \brief Clean Device * * clean up memory allocated by the device. * if destroy is true, device will be removed from global device list * * \param d SCCP Device * \param remove_from_global as boolean_t * \param cleanupTime Clean-up Time as uint8 * * \callgraph * \callergraph * * \lock * - devices * - see sccp_dev_set_registered() * - see sccp_hint_eventListener() via sccp_event_fire() * - device->buttonconfig * - see sccp_line_find_byname() * - see sccp_channel_endcall() * - see sccp_line_removeDevice() * - device->selectedChannels * - device->session * - device->devstateSpecifiers */ void sccp_dev_clean(sccp_device_t * d, boolean_t remove_from_global, uint8_t cleanupTime) { sccp_buttonconfig_t *config = NULL; sccp_selectedchannel_t *selectedChannel = NULL; sccp_line_t *line = NULL; sccp_channel_t *channel = NULL; sccp_event_t event; int i; #if defined(CS_DEVSTATE_FEATURE) && defined(CS_AST_HAS_EVENT) sccp_devstate_specifier_t *devstateSpecifier; #endif char family[25]; if ((d = sccp_device_retain(d))) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_1 "SCCP: Clean Device %s\n", d->id); sccp_dev_set_registered(d, SKINNY_DEVICE_RS_NONE); /* set correct register state */ if (remove_from_global) { sccp_device_removeFromGlobals(d); } d->mwilight = 0; /* reset mwi light */ d->linesRegistered = FALSE; sprintf(family, "SCCP/%s", d->id); PBX(feature_removeFromDatabase) (family, "lastDialedNumber"); if (!sccp_strlen_zero(d->lastNumber)) PBX(feature_addToDatabase) (family, "lastDialedNumber", d->lastNumber); /* cleanup dynamic allocated strings */ /** normaly we should only remove this when removing the device from globals, * in this case we can do this also when device unregistered, so we do not set this multiple times -MC */ if (d->backgroundImage) { sccp_free(d->backgroundImage); d->backgroundImage = NULL; } if (d->ringtone) { sccp_free(d->ringtone); d->ringtone = NULL; } /* hang up open channels and remove device from line */ sccp_device_t *tmpDevice = NULL; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->type == LINE) { line = sccp_line_find_byname(config->button.line.name, FALSE); if (!line) continue; SCCP_LIST_LOCK(&line->channels); SCCP_LIST_TRAVERSE(&line->channels, channel, list) { tmpDevice = sccp_channel_getDevice_retained(channel); if (tmpDevice == d) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_2 "SCCP: Hangup open channel on line %s device %s\n", line->name, d->id); sccp_channel_retain(channel); sccp_channel_endcall(channel); sccp_channel_release(channel); } tmpDevice = tmpDevice ? sccp_device_release(tmpDevice) : NULL; } SCCP_LIST_UNLOCK(&line->channels); /* remove devices from line */ sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_2 "SCCP: Remove Line %s from device %s\n", line->name, d->id); sccp_line_removeDevice(line, d); line = sccp_line_release(line); } config->instance = 0; /* reset button configuration to rebuild template on register */ } SCCP_LIST_UNLOCK(&d->buttonconfig); d->linesRegistered = FALSE; sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_2 "SCCP: Unregister Device %s\n", d->id); memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_DEVICE_UNREGISTERED; event.event.deviceRegistered.device = sccp_device_retain(d); sccp_event_fire(&event); /* cleanup statistics */ memset(&d->configurationStatistic, 0, sizeof(d->configurationStatistic)); d->mwilight = 0; /* cleanup mwi status */ d->status.token = SCCP_TOKEN_STATE_NOTOKEN; d->registrationTime = time(0); /* removing addons */ if (remove_from_global) { sccp_addons_clear(d); } /* removing selected channels */ SCCP_LIST_LOCK(&d->selectedChannels); while ((selectedChannel = SCCP_LIST_REMOVE_HEAD(&d->selectedChannels, list))) { sccp_free(selectedChannel); } SCCP_LIST_UNLOCK(&d->selectedChannels); if (d->session && d->session->device) { sccp_device_sendReset(d, SKINNY_DEVICE_RESTART); usleep(20); if (d->session) { sccp_session_removeDevice(d->session); } d->session = NULL; } /* release line references, refcounted in btnList */ if (d->buttonTemplate) { btnlist *btn = d->buttonTemplate; for (i = 0; i < StationMaxButtonTemplateSize; i++) { if ((btn[i].type == SKINNY_BUTTONTYPE_LINE) && btn[i].ptr) { btn[i].ptr = sccp_line_release(btn[i].ptr); } } sccp_free(d->buttonTemplate); d->buttonTemplate = NULL; } #if defined(CS_DEVSTATE_FEATURE) && defined(CS_AST_HAS_EVENT) /* Unregister event subscriptions originating from devstate feature */ SCCP_LIST_LOCK(&d->devstateSpecifiers); while ((devstateSpecifier = SCCP_LIST_REMOVE_HEAD(&d->devstateSpecifiers, list))) { if (devstateSpecifier->sub) { pbx_event_unsubscribe(devstateSpecifier->sub); } sccp_log(DEBUGCAT_FEATURE_BUTTON) (VERBOSE_PREFIX_1 "%s: Removed Devicestate Subscription: %s\n", d->id, devstateSpecifier->specifier); } SCCP_LIST_UNLOCK(&d->devstateSpecifiers); #endif d = sccp_device_release(d); } } /*! * \brief Free a Device as scheduled command * \param ptr SCCP Device Pointer * \return success as int * * \callgraph * \callergraph * * \called_from_asterisk * * \lock * - device * - device->buttonconfig * - device->permithosts * - device->devstateSpecifiers */ int __sccp_device_destroy(const void *ptr) { sccp_device_t *d = (sccp_device_t *) ptr; sccp_buttonconfig_t *config = NULL; sccp_hostname_t *permithost = NULL; int i; if (!d) { pbx_log(LOG_ERROR, "SCCP: Trying to destroy non-existend device\n"); return -1; } sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "%s: Destroying Device\n", d->id); sccp_mutex_lock(&d->lock); // using real device lock while using refcount /* remove button config */ /* only generated on read config, so do not remove on reset/restart */ SCCP_LIST_LOCK(&d->buttonconfig); while ((config = SCCP_LIST_REMOVE_HEAD(&d->buttonconfig, list))) { sccp_free(config); config = NULL; } SCCP_LIST_UNLOCK(&d->buttonconfig); SCCP_LIST_HEAD_DESTROY(&d->buttonconfig); /* removing permithosts */ SCCP_LIST_LOCK(&d->permithosts); while ((permithost = SCCP_LIST_REMOVE_HEAD(&d->permithosts, list))) { if (permithost) sccp_free(permithost); } SCCP_LIST_UNLOCK(&d->permithosts); SCCP_LIST_HEAD_DESTROY(&d->permithosts); #ifdef CS_DEVSTATE_FEATURE /* removing devstate_specifier */ sccp_devstate_specifier_t *devstateSpecifier; SCCP_LIST_LOCK(&d->devstateSpecifiers); while ((devstateSpecifier = SCCP_LIST_REMOVE_HEAD(&d->devstateSpecifiers, list))) { if (devstateSpecifier) sccp_free(devstateSpecifier); } SCCP_LIST_UNLOCK(&d->devstateSpecifiers); SCCP_LIST_HEAD_DESTROY(&d->devstateSpecifiers); #endif /* destroy selected channels list */ SCCP_LIST_HEAD_DESTROY(&d->selectedChannels); if (d->ha) { sccp_free_ha(d->ha); d->ha = NULL; } /* cleanup message stack */ #ifndef SCCP_ATOMIC sccp_mutex_lock(&d->messageStackLock); #endif for (i = 0; i < SCCP_MAX_MESSAGESTACK; i++) { if (d && d->messageStack && d->messageStack[i] != NULL) { sccp_free(d->messageStack[i]); } } #ifndef SCCP_ATOMIC sccp_mutex_unlock(&d->messageStackLock); pbx_mutex_destroy(&d->messageStackLock); #endif if (d->variables) { pbx_variables_destroy(d->variables); d->variables = NULL; } sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: Device Destroyed\n", d->id); sccp_mutex_unlock(&d->lock); // using real device lock while using refcount pbx_mutex_destroy(&d->lock); return 0; } /*! * \brief Free a Device as scheduled command * \param ptr SCCP Device Pointer * \return success as int * * \callgraph * \callergraph * * \called_from_asterisk * * \lock * - device * - device->buttonconfig * - device->permithosts * - device->devstateSpecifiers */ int sccp_device_destroy(const void *ptr) { sccp_device_t *d = (sccp_device_t *) ptr; sccp_device_removeFromGlobals(d); return 0; } /*! * \brief is Video Support on a Device * \param device SCCP Device * \return result as boolean_t */ boolean_t sccp_device_isVideoSupported(const sccp_device_t * device) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "%s: video support %d \n", device->id, device->capabilities.video[0]); #ifdef CS_SCCP_VIDEO if (device->capabilities.video[0] != 0) return TRUE; #endif return FALSE; } /*! * \brief Find ServiceURL by index * \param d SCCP Device * \param instance Instance as uint8_t * \return SCCP Service * * \lock * - device->buttonconfig */ sccp_buttonconfig_t *sccp_dev_serviceURL_find_byindex(sccp_device_t * d, uint16_t instance) { sccp_buttonconfig_t *config = NULL; if (!d || !d->session) return NULL; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: searching for service with instance %d\n", d->id, instance); SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { sccp_log(((DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE) + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: instance: %d buttontype: %d\n", d->id, config->instance, config->type); if (config->type == SERVICE && config->instance == instance) { sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: found service: %s\n", d->id, config->label); break; } } SCCP_LIST_UNLOCK(&d->buttonconfig); return config; } /*! * \brief Find Device by Line Index * \param d SCCP Device * \param lineName Line Name as char * \return Status as int * \note device should be locked by parent fuction * * \warning * - device->buttonconfig is not always locked */ uint8_t sccp_device_find_index_for_line(const sccp_device_t * d, const char *lineName) { sccp_buttonconfig_t *config; if (!d || !lineName) return -1; sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: sccp_device_find_index_for_line searching for %s\n", DEV_ID_LOG(d), lineName); /* device is already locked by parent function */ SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { if (config->type == LINE && (config->button.line.name) && !strcasecmp(config->button.line.name, lineName)) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: sccp_device_find_index_for_line found: %d\n", DEV_ID_LOG(d), config->instance); break; } } sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: sccp_device_find_index_for_line return: %d\n", DEV_ID_LOG(d), config ? config->instance : -2); return (config) ? config->instance : -2; } /*! * \brief Send Reset to a Device * \param d SCCP Device * \param reset_type as int * \return Status as int */ int sccp_device_sendReset(sccp_device_t * d, uint8_t reset_type) { sccp_moo_t *r; if (!d) { return 0; } REQ(r, Reset); if (!r) { return 0; } r->msg.Reset.lel_resetType = htolel(reset_type); sccp_session_send(d, r); d->pendingUpdate = 0; return 1; } /*! * \brief Send Call State to Device * \param d SCCP Device * \param instance Instance as int * \param callid Call ID as int * \param state Call State as int * \param priority Priority as skinny_callpriority_t * \param visibility Visibility as skinny_callinfo_visibility_t * * \callgraph * \callergraph */ void sccp_device_sendcallstate(const sccp_device_t * d, uint8_t instance, uint32_t callid, uint8_t state, skinny_callpriority_t priority, skinny_callinfo_visibility_t visibility) { sccp_moo_t *r; if (!d) return; REQ(r, CallStateMessage); if (!r) return; r->msg.CallStateMessage.lel_callState = htolel(state); r->msg.CallStateMessage.lel_lineInstance = htolel(instance); r->msg.CallStateMessage.lel_callReference = htolel(callid); r->msg.CallStateMessage.lel_visibility = htolel(visibility); r->msg.CallStateMessage.lel_priority = htolel(priority); /*r->msg.CallStateMessage.lel_unknown3 = htolel(2); */ sccp_dev_send(d, r); sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Send and Set the call state %s(%d) on call %d\n", d->id, sccp_callstate2str(state), state, callid); } /*! * \brief Get the number of channels that the device owns * \param device sccp device * \note device should be locked by parent functions * * \warning * - device-buttonconfig is not always locked * * \lock * - line->channels */ uint8_t sccp_device_numberOfChannels(const sccp_device_t * device) { sccp_buttonconfig_t *config; sccp_channel_t *c; sccp_line_t *l; uint8_t numberOfChannels = 0; if (!device) { sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "device is null\n"); return 0; } sccp_device_t *tmpDevice = NULL; SCCP_LIST_TRAVERSE(&device->buttonconfig, config, list) { if (config->type == LINE) { l = sccp_line_find_byname(config->button.line.name, FALSE); if (!l) continue; SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { tmpDevice = sccp_channel_getDevice_retained(c); if (tmpDevice == device) { numberOfChannels++; } tmpDevice = tmpDevice ? sccp_device_release(tmpDevice) : NULL; } SCCP_LIST_UNLOCK(&l->channels); l = sccp_line_release(l); } } return numberOfChannels; } /*! * \brief Send DTMF Tone as KeyPadButton to SCCP Device */ void sccp_dev_keypadbutton(sccp_device_t * d, char digit, uint8_t line, uint32_t callid) { sccp_moo_t *r; if (!d || !d->session) return; if (digit == '*') { digit = 0xe; /* See the definition of tone_list in chan_protocol.h for more info */ } else if (digit == '#') { digit = 0xf; } else if (digit == '0') { digit = 0xa; /* 0 is not 0 for cisco :-) */ } else { digit -= '0'; } if (digit > 16) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: SCCP phones can't play this type of dtmf. Sending it inband\n", d->id); return; } REQ(r, KeypadButtonMessage); if (!r) return; r->msg.KeypadButtonMessage.lel_kpButton = htolel(digit); r->msg.KeypadButtonMessage.lel_lineInstance = htolel(line); r->msg.KeypadButtonMessage.lel_callReference = htolel(callid); sccp_dev_send(d, r); sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: (sccp_dev_keypadbutton) Sending keypad '%02X'\n", DEV_ID_LOG(d), digit); } /*! * \brief Indicate to device that remote side has been put on hold (old). */ static void sccp_device_old_indicate_remoteHold(const sccp_device_t * device, uint8_t lineInstance, uint8_t callid, uint8_t callpriority, uint8_t callPrivacy) { sccp_device_sendcallstate(device, lineInstance, callid, SKINNY_CALLSTATE_HOLD, callpriority, callPrivacy); sccp_dev_set_keyset(device, lineInstance, callid, KEYMODE_ONHOLD); sccp_dev_displayprompt(device, lineInstance, callid, SKINNY_DISP_HOLD, 0); } /*! * \brief Indicate to device that remote side has been put on hold (new). */ static void sccp_device_new_indicate_remoteHold(const sccp_device_t * device, uint8_t lineInstance, uint8_t callid, uint8_t callpriority, uint8_t callPrivacy) { sccp_device_sendcallstate(device, lineInstance, callid, SKINNY_CALLSTATE_HOLDRED, callpriority, callPrivacy); sccp_dev_set_keyset(device, lineInstance, callid, KEYMODE_ONHOLD); sccp_dev_displayprompt(device, lineInstance, callid, SKINNY_DISP_HOLD, 0); } static void sccp_device_indicate_offhook(const sccp_device_t * device, sccp_linedevices_t * linedevice, uint8_t callid) { sccp_dev_set_speaker(device, SKINNY_STATIONSPEAKER_ON); sccp_device_sendcallstate(device, linedevice->lineInstance, callid, SKINNY_CALLSTATE_OFFHOOK, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_dev_set_cplane(device, linedevice->lineInstance, 1); sccp_dev_displayprompt(device, linedevice->lineInstance, callid, SKINNY_DISP_ENTER_NUMBER, 0); sccp_dev_set_keyset(device, linedevice->lineInstance, callid, KEYMODE_OFFHOOK); sccp_dev_starttone(device, SKINNY_TONE_INSIDEDIALTONE, linedevice->lineInstance, callid, 0); } static void sccp_device_indicate_connected(const sccp_device_t * device, sccp_linedevices_t * linedevice, const sccp_channel_t * channel) { sccp_dev_set_ringer(device, SKINNY_RINGTYPE_OFF, linedevice->lineInstance, channel->callid); sccp_dev_set_speaker(device, SKINNY_STATIONSPEAKER_ON); sccp_dev_stoptone(device, linedevice->lineInstance, channel->callid); sccp_device_sendcallstate(device, linedevice->lineInstance, channel->callid, SKINNY_CALLSTATE_CONNECTED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(device, channel); sccp_dev_set_cplane(device, linedevice->lineInstance, 1); sccp_dev_set_keyset(device, linedevice->lineInstance, channel->callid, KEYMODE_CONNECTED); sccp_dev_displayprompt(device, linedevice->lineInstance, channel->callid, SKINNY_DISP_CONNECTED, 0); } /*! * \brief Add message to the MessageStack to be shown on the Status Line of the SCCP Device */ void sccp_device_addMessageToStack(sccp_device_t * device, const uint8_t priority, const char *message) { // sccp_log((DEBUGCAT_CORE | DEBUGCAT_DEVICE | DEBUGCAT_MESSAGE))(VERBOSE_PREFIX_1 "%s: (sccp_device_addMessageToStack), '%s' at priority %d \n", DEV_ID_LOG(device), message, priority); if (ARRAY_LEN(device->messageStack) <= priority) { return; } char *newValue = NULL; char *oldValue = NULL; newValue = strdup(message); do { oldValue = device->messageStack[priority]; } while (!CAS_PTR(&device->messageStack[priority], oldValue, newValue, &device->messageStackLock)); if (oldValue) { sccp_free(oldValue); } sccp_dev_check_displayprompt(device); } /*! * \brief Remove a message from the MessageStack to be shown on the Status Line of the SCCP Device */ void sccp_device_clearMessageFromStack(sccp_device_t * device, const uint8_t priority) { if (ARRAY_LEN(device->messageStack) <= priority) { return; } char *newValue = NULL; char *oldValue = NULL; sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_4 "%s: clear message stack %d\n", DEV_ID_LOG(device), priority); do { oldValue = device->messageStack[priority]; } while (!CAS_PTR(&device->messageStack[priority], oldValue, newValue, &device->messageStackLock)); if (oldValue) { sccp_free(oldValue); sccp_dev_check_displayprompt(device); } } /*! * \brief Handle Feature Change Event for persistent feature storage * \param event SCCP Event * * \callgraph * \callergraph * * \warning * - device->buttonconfig is not always locked * - line->devices is not always locked * * \lock * - device * * \todo implement cfwd_noanswer */ void sccp_device_featureChangedDisplay(const sccp_event_t * event) { sccp_linedevices_t *linedevice = NULL; sccp_device_t *device = event->event.featureChanged.device; char tmp[256] = { 0 }; size_t len = sizeof(tmp); char *s = tmp; if (!event || !device) return; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_EVENT | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: Received Feature Change Event: %s(%d)\n", DEV_ID_LOG(device), featureType2str(event->event.featureChanged.featureType), event->event.featureChanged.featureType); switch (event->event.featureChanged.featureType) { case SCCP_FEATURE_CFWDNONE: sccp_device_clearMessageFromStack(device, SCCP_MESSAGE_PRIORITY_CFWD); break; case SCCP_FEATURE_CFWDBUSY: case SCCP_FEATURE_CFWDALL: if ((linedevice = event->event.featureChanged.linedevice)) { sccp_line_t *line = linedevice->line; uint8_t instance = linedevice->lineInstance; sccp_dev_forward_status(line, instance, device); switch (event->event.featureChanged.featureType) { case SCCP_FEATURE_CFWDALL: if (linedevice->cfwdAll.enabled) { /* build disp message string */ if (s != tmp) pbx_build_string(&s, &len, ", "); pbx_build_string(&s, &len, "%s:%s %s %s", SKINNY_DISP_CFWDALL, line->cid_num, SKINNY_DISP_FORWARDED_TO, linedevice->cfwdAll.number); } break; case SCCP_FEATURE_CFWDBUSY: if (linedevice->cfwdBusy.enabled) { /* build disp message string */ if (s != tmp) pbx_build_string(&s, &len, ", "); pbx_build_string(&s, &len, "%s:%s %s %s", SKINNY_DISP_CFWDBUSY, line->cid_num, SKINNY_DISP_FORWARDED_TO, linedevice->cfwdBusy.number); } break; default: break; } } if (strlen(tmp) > 0) { sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_CFWD, tmp); } else { sccp_device_clearMessageFromStack(device, SCCP_MESSAGE_PRIORITY_CFWD); } break; case SCCP_FEATURE_DND: if (!device->dndFeature.status) { sccp_device_clearMessageFromStack(device, SCCP_MESSAGE_PRIORITY_DND); } else { if (device->dndFeature.status == SCCP_DNDMODE_SILENT) { sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_DND, ">>> " SKINNY_DISP_DND " (Silent) <<<"); } else { sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_DND, ">>> " SKINNY_DISP_DND " (" SKINNY_DISP_BUSY ") <<<"); } } break; case SCCP_FEATURE_PRIVACY: if (TRUE == device->privacyFeature.status) { sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_PRIVACY, SKINNY_DISP_PRIVATE); } else { sccp_device_clearMessageFromStack(device, SCCP_MESSAGE_PRIORITY_PRIVACY); } break; case SCCP_FEATURE_MONITOR: if (TRUE == device->monitorFeature.status) { sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_MONITOR, SKINNY_DISP_MONITOR); } else { sccp_device_clearMessageFromStack(device, SCCP_MESSAGE_PRIORITY_MONITOR); } break; default: return; } } /*! * \brief Push a URL to an SCCP device */ static sccp_push_result_t sccp_device_pushURL(const sccp_device_t * device, const char *url, uint8_t priority, uint8_t tone) { char xmlData[512]; sprintf(xmlData, "<CiscoIPPhoneExecute><ExecuteItem Priority=\"0\"URL=\"%s\"/></CiscoIPPhoneExecute>", url); device->protocol->sendUserToDeviceDataVersionMessage(device, 0, 0, 1, 1, xmlData, priority); if (SKINNY_TONE_SILENCE != tone) { sccp_dev_starttone(device, tone, 0, 0, 0); } return SCCP_PUSH_RESULT_SUCCESS; } /*! * \brief Push a Text Message to an SCCP device */ static sccp_push_result_t sccp_device_pushTextMessage(const sccp_device_t * device, const char *messageText, const char *from, uint8_t priority, uint8_t tone) { char xmlData[1024]; sprintf(xmlData, "<CiscoIPPhoneText><Title>%s</Title><Text>%s</Text></CiscoIPPhoneText>", from ? from : "", messageText); device->protocol->sendUserToDeviceDataVersionMessage(device, 0, 0, 1, 1, xmlData, priority); if (SKINNY_TONE_SILENCE != tone) { sccp_dev_starttone(device, tone, 0, 0, 0); } return SCCP_PUSH_RESULT_SUCCESS; } /*=================================================================================== FIND FUNCTIONS ==============*/ /*! * \brief Find Device by ID * * \callgraph * \callergraph * * \lock * - devices */ #if DEBUG /*! * \param name Device ID (hostname) * \param useRealtime Use RealTime as Boolean * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Device - can bee null if device is not found */ sccp_device_t *__sccp_device_find_byid(const char *name, boolean_t useRealtime, const char *filename, int lineno, const char *func) #else /*! * \param name Device ID (hostname) * \param useRealtime Use RealTime as Boolean * \return SCCP Device - can bee null if device is not found */ sccp_device_t *sccp_device_find_byid(const char *name, boolean_t useRealtime) #endif { sccp_device_t *d = NULL; if (sccp_strlen_zero(name)) { sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "SCCP: Not allowed to search for device with name ''\n"); return NULL; } SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (d && d->id && !strcasecmp(d->id, name)) { #if DEBUG d = sccp_refcount_retain(d, filename, lineno, func); #else d = sccp_device_retain(d); #endif break; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); #ifdef CS_SCCP_REALTIME if (!d && useRealtime) d = sccp_device_find_realtime_byid(name); #endif return d; } #ifdef CS_SCCP_REALTIME /*! * \brief Find Device via RealTime * * \callgraph * \callergraph */ #if DEBUG /*! * \param name Device ID (hostname) * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Device - can bee null if device is not found */ sccp_device_t *__sccp_device_find_realtime(const char *name, const char *filename, int lineno, const char *func) #else /*! * \param name Device ID (hostname) * \return SCCP Device - can bee null if device is not found */ sccp_device_t *sccp_device_find_realtime(const char *name) #endif { sccp_device_t *d = NULL; PBX_VARIABLE_TYPE *v, *variable; if (sccp_strlen_zero(GLOB(realtimedevicetable)) || sccp_strlen_zero(name)) return NULL; if ((variable = pbx_load_realtime(GLOB(realtimedevicetable), "name", name, NULL))) { v = variable; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_REALTIME)) (VERBOSE_PREFIX_3 "SCCP: Device '%s' found in realtime table '%s'\n", name, GLOB(realtimedevicetable)); d = sccp_device_create(name); /** create new device */ if (!d) { pbx_log(LOG_ERROR, "SCCP: Unable to build realtime device '%s'\n", name); return NULL; } // sccp_copy_string(d->id, name, sizeof(d->id)); sccp_config_applyDeviceConfiguration(d, v); /** load configuration and set defaults */ sccp_config_restoreDeviceFeatureStatus(d); /** load device status from database */ sccp_device_addToGlobals(d); /** add to device to global device list */ d->realtime = TRUE; /** set device as realtime device */ pbx_variables_destroy(v); return d; } sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_REALTIME)) (VERBOSE_PREFIX_3 "SCCP: Device '%s' not found in realtime table '%s'\n", name, GLOB(realtimedevicetable)); return NULL; } #endif
722,254
./chan-sccp-b/src/sccp_hint.c
/*! * \file sccp_hint.c * \brief SCCP Hint Class * \author Marcello Ceschia < marcello.ceschia@users.sourceforge.net > * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \note For more information about how does hint update works, see \ref hint_update * \since 2009-01-16 * \remarks Purpose: SCCP Hint * When to use: Does the business of hint status * * $Date: 2011-01-04 17:29:12 +0100 (Tue, 04 Jan 2011) $ * $Revision: 2215 $ */ /*! * \section hint_update How does hint update work * * Getting hint information for display the various connected devices (e.g., 7960 or 7914) varies from PBX implementation to implementation. * In pure Asterisk and its derivatives, hint processing is needed to provide the information for the button, and can be accomplished as simply * as adding "exten => 581,hint,SCCP/581" in the default (possibly "from-internal") internal dial-plan. * Monitoring non-SCCP devices is possible by reviewing the hint status in the Asterisk CLI using the "core show hints" command. * Anything that generates a hint can be monitored using the buttons. * * \todo (Page needs to be re-written) */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision: 2215 $") /* ========================================================================================================================= Struct Definitions */ /*! *\brief SCCP Hint Subscribing Device Structure */ typedef struct sccp_hint_SubscribingDevice sccp_hint_SubscribingDevice_t; typedef struct sccp_hint_list sccp_hint_list_t; struct sccp_hint_SubscribingDevice { const sccp_device_t *device; /*!< SCCP Device */ uint8_t instance; /*!< Instance */ uint8_t positionOnDevice; /*!< Instance */ SCCP_LIST_ENTRY (sccp_hint_SubscribingDevice_t) list; /*!< Hint Subscribing Device Linked List Entry */ }; /*!< SCCP Hint Subscribing Device Structure */ /*! *\brief SCCP Hint Line State Structure */ struct sccp_hint_lineState { sccp_line_t *line; sccp_channelstate_t state; /*! * \brief Call Information Structure */ struct { char partyName[StationMaxNameSize]; /*!< Party Name */ char partyNumber[StationMaxNameSize]; /*!< Party Number */ skinny_calltype_t calltype; /*!< Skinny Call Type */ } callInfo; /*!< Call Information Structure */ SCCP_LIST_ENTRY (struct sccp_hint_lineState) list; /*!< Hint Type Linked List Entry */ }; /*! * \brief SCCP Hint List Structure */ struct sccp_hint_list { ast_mutex_t lock; /*!< Asterisk Lock */ char exten[SCCP_MAX_EXTENSION]; /*!< Extension for Hint */ char context[SCCP_MAX_CONTEXT]; /*!< Context for Hint */ char hint_dialplan[256]; /*!< e.g. IAX2/station123 */ sccp_channelstate_t currentState; /*!< current State */ sccp_channelstate_t previousState; /*!< current State */ /*! * \brief Call Information Structure */ struct { char partyNumber[StationMaxNameSize]; /*!< Calling Party Name */ char partyName[StationMaxNameSize]; /*!< Called Party Name */ skinny_calltype_t calltype; /*!< Skinny Call Type */ } callInfo; /*!< Call Information Structure */ int stateid; /*!< subscription id in asterisk */ #ifdef CS_USE_ASTERISK_DISTRIBUTED_DEVSTATE struct pbx_event_sub *device_state_sub; /*!< asterisk distributed device state subscription */ #endif SCCP_LIST_HEAD (, sccp_hint_SubscribingDevice_t) subscribers; /*!< Hint Type Subscribers Linked List Entry */ SCCP_LIST_ENTRY (sccp_hint_list_t) list; /*!< Hint Type Linked List Entry */ }; /*!< SCCP Hint List Structure */ /* ========================================================================================================================= Declarations */ static void sccp_hint_updateLineState(struct sccp_hint_lineState *lineState); static void sccp_hint_updateLineStateForSharedLine(struct sccp_hint_lineState *lineState); static void sccp_hint_updateLineStateForSingleLine(struct sccp_hint_lineState *lineState); static void sccp_hint_checkForDND(struct sccp_hint_lineState *lineState); static void sccp_hint_notifyPBX(struct sccp_hint_lineState *linestate); static sccp_hint_list_t *sccp_hint_create(char *hint_exten, char *hint_context); static void sccp_hint_notifySubscribers(sccp_hint_list_t * hint); static void sccp_hint_deviceRegistered(const sccp_device_t * device); static void sccp_hint_deviceUnRegistered(const char *deviceName); static void sccp_hint_addSubscription4Device(const sccp_device_t * device, const char *hintStr, const uint8_t instance, const uint8_t positionOnDevice); static void sccp_hint_lineStatusChanged(sccp_line_t * line, sccp_device_t * device); static void sccp_hint_handleFeatureChangeEvent(const sccp_event_t * event); static void sccp_hint_eventListener(const sccp_event_t * event); static inline boolean_t sccp_hint_isCIDavailabe(const sccp_device_t * device, const uint8_t positionOnDevice); #ifdef CS_USE_ASTERISK_DISTRIBUTED_DEVSTATE static void sccp_hint_distributed_devstate_cb(const pbx_event_t * event, void *data) { sccp_hint_list_t *hint; const char *cidName; const char *cidNumber; hint = (sccp_hint_list_t *) data; cidName = pbx_event_get_ie_str(event, AST_EVENT_IE_CEL_CIDNAME); cidNumber = pbx_event_get_ie_str(event, AST_EVENT_IE_CEL_CIDNUM); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_3 "Got new hint event %s, cidname: %s, cidnum: %s\n", hint->hint_dialplan, cidName ? cidName : "NULL", cidNumber ? cidNumber : "NULL"); if (cidName) { sccp_copy_string(hint->callInfo.partyName, cidName, sizeof(hint->callInfo.partyName)); } if (cidNumber) { sccp_copy_string(hint->callInfo.partyNumber, cidNumber, sizeof(hint->callInfo.partyNumber)); } return; } #endif #if ASTERISK_VERSION_GROUP >= 111 int sccp_hint_devstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data); #elif ASTERISK_VERSION_GROUP >= 110 int sccp_hint_devstate_cb(const char *context, const char *id, enum ast_extension_states state, void *data); #else int sccp_hint_devstate_cb(char *context, char *id, enum ast_extension_states state, void *data); #endif /* ========================================================================================================================= List Declarations */ SCCP_LIST_HEAD (, struct sccp_hint_lineState) lineStates; SCCP_LIST_HEAD (, sccp_hint_list_t) sccp_hint_subscriptions; /* ========================================================================================================================= Module Start/Stop */ /*! * \brief starting hint-module */ void sccp_hint_module_start() { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Starting hint system\n"); SCCP_LIST_HEAD_INIT(&lineStates); sccp_event_subscribe(SCCP_EVENT_DEVICE_REGISTERED | SCCP_EVENT_DEVICE_UNREGISTERED | SCCP_EVENT_DEVICE_DETACHED | SCCP_EVENT_DEVICE_ATTACHED | SCCP_EVENT_LINESTATUS_CHANGED | SCCP_EVENT_FEATURE_CHANGED, sccp_hint_eventListener, TRUE); } /*! * \brief stop hint-module * * \lock * - lineStates * - sccp_hint_subscriptions * - hint->subscribers */ void sccp_hint_module_stop() { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Stopping hint system\n"); { struct sccp_hint_lineState *lineState; SCCP_LIST_LOCK(&lineStates); while ((lineState = SCCP_LIST_REMOVE_HEAD(&lineStates, list))) { lineState->line = lineState->line ? sccp_line_release(lineState->line) : NULL; sccp_free(lineState); } SCCP_LIST_UNLOCK(&lineStates); } { sccp_hint_list_t *hint; sccp_device_t *device; sccp_hint_SubscribingDevice_t *subscriber; SCCP_LIST_LOCK(&sccp_hint_subscriptions); while ((hint = SCCP_LIST_REMOVE_HEAD(&sccp_hint_subscriptions, list))) { #ifdef CS_USE_ASTERISK_DISTRIBUTED_DEVSTATE pbx_event_unsubscribe(hint->device_state_sub); #endif ast_extension_state_del(hint->stateid, NULL); // All subscriptions that have this device should be removed, force cleanup SCCP_LIST_LOCK(&hint->subscribers); while ((subscriber = SCCP_LIST_REMOVE_HEAD(&hint->subscribers, list))) { if ((device = sccp_device_retain((sccp_device_t *) subscriber->device))) { subscriber->device = sccp_device_release(subscriber->device); device = sccp_device_release(device); sccp_free(subscriber); } } SCCP_LIST_UNLOCK(&hint->subscribers); sccp_free(hint); } SCCP_LIST_UNLOCK(&sccp_hint_subscriptions); } sccp_event_unsubscribe(SCCP_EVENT_DEVICE_REGISTERED | SCCP_EVENT_DEVICE_UNREGISTERED | SCCP_EVENT_DEVICE_DETACHED | SCCP_EVENT_DEVICE_ATTACHED | SCCP_EVENT_LINESTATUS_CHANGED, sccp_hint_eventListener); sccp_event_unsubscribe(SCCP_EVENT_FEATURE_CHANGED, sccp_hint_handleFeatureChangeEvent); } /* ========================================================================================================================= PBX Callbacks */ /*! * \brief asterisk callback for extension state changes (we subscribed with ast_extension_state_add) */ #if ASTERISK_VERSION_GROUP >= 111 /*! * \param context extension context (char *) * \param id extension (char *) * \param info ast_state_cb_info * \param data private channel data (sccp_hint_list_t *hint) as void pointer */ int sccp_hint_devstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data) #elif ASTERISK_VERSION_GROUP >= 110 /*! * \param context extension context (const char *) * \param id extension (const char *) * \param state ast_extension_state (enum) * \param data private channel data (sccp_hint_list_t *hint) as void pointer */ int sccp_hint_devstate_cb(const char *context, const char *id, enum ast_extension_states state, void *data) #else /*! * \param context extension context (char *) * \param id extension (char *) * \param state ast_extension_state (enum) * \param data private channel data (sccp_hint_list_t *hint) as void pointer */ int sccp_hint_devstate_cb(char *context, char *id, enum ast_extension_states state, void *data) #endif { sccp_hint_list_t *hint; int extensionState; char hintStr[AST_MAX_EXTENSION]; const char *cidName; // const char *cidNumber; hint = (sccp_hint_list_t *) data; ast_get_hint(hintStr, sizeof(hintStr), NULL, 0, NULL, hint->context, hint->exten); #if ASTERISK_VERSION_GROUP >= 111 extensionState = info->exten_state; #else extensionState = state; #endif cidName = hint->callInfo.partyName; // cidNumber = hint->callInfo.partyNumber; /* save previousState */ hint->previousState = hint->currentState; sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_2 "%s: (sccp_hint_devstate_cb) Got new hint event %s, state: %d (%s), cidname: %s, cidnum: %s\n", hint->exten, hint->hint_dialplan, extensionState, ast_extension_state2str(extensionState), hint->callInfo.partyName, hint->callInfo.partyNumber); switch (extensionState) { case AST_EXTENSION_REMOVED: case AST_EXTENSION_DEACTIVATED: case AST_EXTENSION_UNAVAILABLE: hint->currentState = SCCP_CHANNELSTATE_CONGESTION; break; case AST_EXTENSION_NOT_INUSE: hint->currentState = SCCP_CHANNELSTATE_ONHOOK; break; case AST_EXTENSION_INUSE: if (SCCP_CHANNELSTATE_ONHOOK == hint->previousState || SCCP_CHANNELSTATE_DOWN == hint->previousState) { hint->currentState = SCCP_CHANNELSTATE_DIALING; } else { hint->currentState = SCCP_CHANNELSTATE_CONNECTED; } break; case AST_EXTENSION_BUSY: if (cidName && !strcasecmp(cidName, "DND")) { hint->currentState = SCCP_CHANNELSTATE_DND; } else { hint->currentState = SCCP_CHANNELSTATE_BUSY; } break; case AST_EXTENSION_INUSE + AST_EXTENSION_RINGING: case AST_EXTENSION_RINGING: hint->currentState = SCCP_CHANNELSTATE_RINGING; break; case AST_EXTENSION_INUSE + AST_EXTENSION_ONHOLD: case AST_EXTENSION_ONHOLD: hint->currentState = SCCP_CHANNELSTATE_HOLD; break; } sccp_hint_notifySubscribers(hint); return 0; } /* ===================================================================================================================== SCCP Event Dispatchers */ /*! * \brief Event Listener for Hints * \param event SCCP Event * * \lock * - device * - see sccp_hint_deviceRegistered() * - see sccp_hint_deviceUnRegistered() */ void sccp_hint_eventListener(const sccp_event_t * event) { sccp_device_t *device; if (!event) return; switch (event->type) { case SCCP_EVENT_DEVICE_REGISTERED: device = event->event.deviceRegistered.device; sccp_hint_deviceRegistered(device); break; case SCCP_EVENT_DEVICE_UNREGISTERED: device = event->event.deviceRegistered.device; if (device && device->id) { char *deviceName = strdupa(device->id); sccp_hint_deviceUnRegistered(deviceName); } break; case SCCP_EVENT_DEVICE_DETACHED: sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_2 "%s: (sccp_hint_eventListener) device %s detached on line %s\n", DEV_ID_LOG(event->event.deviceAttached.linedevice->device), event->event.deviceAttached.linedevice->device->id, event->event.deviceAttached.linedevice->line->name); sccp_hint_lineStatusChanged(event->event.deviceAttached.linedevice->line, event->event.deviceAttached.linedevice->device); break; case SCCP_EVENT_DEVICE_ATTACHED: sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_2 "%s: (sccp_hint_eventListener) device %s attached on line %s\n", DEV_ID_LOG(event->event.deviceAttached.linedevice->device), event->event.deviceAttached.linedevice->device->id, event->event.deviceAttached.linedevice->line->name); sccp_hint_lineStatusChanged(event->event.deviceAttached.linedevice->line, event->event.deviceAttached.linedevice->device); break; case SCCP_EVENT_LINESTATUS_CHANGED: sccp_hint_lineStatusChanged(event->event.lineStatusChanged.line, event->event.lineStatusChanged.device); break; case SCCP_EVENT_FEATURE_CHANGED: sccp_hint_handleFeatureChangeEvent(event); break; default: break; } } /* ========================================================================================================================= Event Handlers */ /* ========================================================================================================================= Event Handlers : Device */ /*! * \brief Handle Hints for Device Register * \param device SCCP Device * * \note device locked by parent * * \warning * - device->buttonconfig is not always locked */ static void sccp_hint_deviceRegistered(const sccp_device_t * device) { sccp_buttonconfig_t *config; uint8_t positionOnDevice = 0; sccp_device_t *d = NULL; if ((d = sccp_device_retain((sccp_device_t *) device))) { SCCP_LIST_TRAVERSE(&device->buttonconfig, config, list) { positionOnDevice++; if (config->type == SPEEDDIAL) { if (sccp_strlen_zero(config->button.speeddial.hint)) { continue; } sccp_hint_addSubscription4Device(device, config->button.speeddial.hint, config->instance, positionOnDevice); } } sccp_device_release(d); } } /*! * \brief Handle Hints for Device UnRegister * \param deviceName Device as Char * * \note device locked by parent * * \lock * - device->buttonconfig * - see sccp_hint_unSubscribeHint() */ static void sccp_hint_deviceUnRegistered(const char *deviceName) { sccp_hint_list_t *hint = NULL; sccp_hint_SubscribingDevice_t *subscriber; SCCP_LIST_LOCK(&sccp_hint_subscriptions); SCCP_LIST_TRAVERSE(&sccp_hint_subscriptions, hint, list) { /* All subscriptions that have this device should be removed */ SCCP_LIST_LOCK(&hint->subscribers); SCCP_LIST_TRAVERSE_SAFE_BEGIN(&hint->subscribers, subscriber, list) { if (subscriber->device && !strcasecmp(subscriber->device->id, deviceName)) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_2 "%s: Freeing subscriber from hint exten: %s in %s\n", deviceName, hint->exten, hint->context); SCCP_LIST_REMOVE_CURRENT(list); subscriber->device = sccp_device_release(subscriber->device); sccp_free(subscriber); } } SCCP_LIST_TRAVERSE_SAFE_END; SCCP_LIST_UNLOCK(&hint->subscribers); } SCCP_LIST_UNLOCK(&sccp_hint_subscriptions); } /*! * \brief Subscribe to a Hint * \param device SCCP Device * \param hintStr Asterisk Hint Name as char * \param instance Instance as int * \param positionOnDevice button index on device (used to detect devicetype) * * \warning * - sccp_hint_subscriptions is not always locked * * \lock * - sccp_hint_subscriptions * * \note called with retained device */ static void sccp_hint_addSubscription4Device(const sccp_device_t * device, const char *hintStr, const uint8_t instance, const uint8_t positionOnDevice) { sccp_hint_list_t *hint = NULL; char buffer[256] = ""; char *splitter, *hint_exten, *hint_context; sccp_copy_string(buffer, hintStr, sizeof(buffer)); /* get exten and context */ splitter = buffer; hint_exten = strsep(&splitter, "@"); if (hint_exten) pbx_strip(hint_exten); hint_context = splitter; if (hint_context) { pbx_strip(hint_context); } else { hint_context = GLOB(context); } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_3 "%s: (sccp_hint_addSubscription4Device) Dialplan %s for exten: %s and context: %s\n", DEV_ID_LOG(device), hintStr, hint_exten, hint_context); SCCP_LIST_TRAVERSE(&sccp_hint_subscriptions, hint, list) { if (sccp_strlen(hint_exten) == sccp_strlen(hint->exten) && sccp_strlen(hint_context) == sccp_strlen(hint->context) && sccp_strequals(hint_exten, hint->exten) && sccp_strequals(hint_context, hint->context)) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_addSubscription4Device) Hint found for exten '%s@%s'\n", DEV_ID_LOG(device), hint_exten, hint_context); break; } } /* we have no hint */ if (!hint) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_addSubscription4Device) create new hint for %s@%s\n", DEV_ID_LOG(device), hint_exten, hint_context); hint = sccp_hint_create(hint_exten, hint_context); if (!hint) { pbx_log(LOG_ERROR, "%s: (sccp_hint_addSubscription4Device) hint create failed for %s@%s\n", DEV_ID_LOG(device), hint_exten, hint_context); return; } SCCP_LIST_LOCK(&sccp_hint_subscriptions); SCCP_LIST_INSERT_HEAD(&sccp_hint_subscriptions, hint, list); SCCP_LIST_UNLOCK(&sccp_hint_subscriptions); } /* add subscribing device */ sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_addSubscription4Device) create subscriber or hint: %s in %s\n", DEV_ID_LOG(device), hint->exten, hint->context); sccp_hint_SubscribingDevice_t *subscriber; subscriber = sccp_malloc(sizeof(sccp_hint_SubscribingDevice_t)); if (!subscriber) { pbx_log(LOG_ERROR, "%s: (sccp_hint_addSubscription4Device) Memory Allocation Error while creating subscriber object\n", DEV_ID_LOG(device)); return; } memset(subscriber, 0, sizeof(sccp_hint_SubscribingDevice_t)); subscriber->device = sccp_device_retain((sccp_device_t *) device); subscriber->instance = instance; subscriber->positionOnDevice = positionOnDevice; sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_addSubscription4Device) Adding subscription for hint %s@%s\n", DEV_ID_LOG(device), hint->exten, hint->context); SCCP_LIST_INSERT_HEAD(&hint->subscribers, subscriber, list); sccp_dev_set_keyset(device, subscriber->instance, 0, KEYMODE_ONHOOK); sccp_hint_notifySubscribers(hint); } /*! * \brief create a hint structure * \param hint_exten Hint Extension as char * \param hint_context Hint Context as char * \return SCCP Hint Linked List */ static sccp_hint_list_t *sccp_hint_create(char *hint_exten, char *hint_context) { sccp_hint_list_t *hint = NULL; char hint_dialplan[256] = ""; if (sccp_strlen_zero(hint_exten)) return NULL; if (sccp_strlen_zero(hint_context)) hint_context = GLOB(context); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (sccp_hint_create) Create hint for exten: %s context: %s\n", hint_exten, hint_context); pbx_get_hint(hint_dialplan, sizeof(hint_dialplan) - 1, NULL, 0, NULL, hint_context, hint_exten); // CS_AST_HAS_NEW_HINT if (sccp_strlen_zero(hint_dialplan)) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (sccp_hint_create) No hint configuration in the dialplan exten: %s and context: %s\n", hint_exten, hint_context); return NULL; } hint = sccp_malloc(sizeof(sccp_hint_list_t)); if (!hint) { pbx_log(LOG_ERROR, "SCCP: (sccp_hint_create) Memory Allocation Error while creating hint list for hint: %s@%s\n", hint_exten, hint_context); return NULL; } memset(hint, 0, sizeof(sccp_hint_list_t)); SCCP_LIST_HEAD_INIT(&hint->subscribers); sccp_mutex_init(&hint->lock); sccp_copy_string(hint->exten, hint_exten, sizeof(hint->exten)); sccp_copy_string(hint->context, hint_context, sizeof(hint->context)); sccp_copy_string(hint->hint_dialplan, hint_dialplan, sizeof(hint_dialplan)); hint->stateid = pbx_extension_state_add(hint->context, hint->exten, sccp_hint_devstate_cb, hint); #ifdef CS_USE_ASTERISK_DISTRIBUTED_DEVSTATE hint->device_state_sub = pbx_event_subscribe(AST_EVENT_DEVICE_STATE_CHANGE, sccp_hint_distributed_devstate_cb, "sccp_hint_distributed_devstate_cb", hint, AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, hint->hint_dialplan, AST_EVENT_IE_END); #endif #if ASTERISK_VERSION_GROUP >= 111 struct ast_state_cb_info info; info.exten_state = pbx_extension_state(NULL, hint->context, hint->exten); sccp_hint_devstate_cb(hint->context, hint->exten, &info, hint); #else enum ast_extension_states state = pbx_extension_state(NULL, hint->context, hint->exten); sccp_hint_devstate_cb(hint->context, hint->exten, state, hint); #endif return hint; } /* ========================================================================================================================= Event Handlers : LineState */ /*! * \brief Handle line status change * \param line SCCP Line that was changed * \param device SCCP Device who initialied the change * */ static void sccp_hint_lineStatusChanged(sccp_line_t * line, sccp_device_t * device) { struct sccp_hint_lineState *lineState = NULL; SCCP_LIST_LOCK(&lineStates); SCCP_LIST_TRAVERSE(&lineStates, lineState, list) { if (lineState->line == line) { break; } } /** create new state holder for line */ if (!lineState) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_3 "%s: (sccp_hint_lineStatusChanged) Create new hint_lineState for line: %s\n", DEV_ID_LOG(device), line->name); lineState = sccp_malloc(sizeof(struct sccp_hint_lineState)); if (!lineState) { pbx_log(LOG_ERROR, "%s: (sccp_hint_lineStatusChanged) Memory Allocation Error while creating hint-lineState object for line %s\n", DEV_ID_LOG(device), line->name); return; } memset(lineState, 0, sizeof(struct sccp_hint_lineState)); lineState->line = sccp_line_retain(line); SCCP_LIST_INSERT_HEAD(&lineStates, lineState, list); } SCCP_LIST_UNLOCK(&lineStates); if (lineState && lineState->line) { /** update line state */ sccp_hint_updateLineState(lineState); } } /*! * \brief Handle Hint Status Update * \param lineState SCCP LineState */ void sccp_hint_updateLineState(struct sccp_hint_lineState *lineState) { sccp_line_t *line = NULL; if ((line = sccp_line_retain(lineState->line))) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineState) Update Line Channel State: %s(%d)\n", line->name, channelstate2str(lineState->state), lineState->state); /* no line, or line without devices */ if (0 == line->devices.size) { lineState->state = SCCP_CHANNELSTATE_CONGESTION; lineState->callInfo.calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_copy_string(lineState->callInfo.partyName, SKINNY_DISP_TEMP_FAIL, sizeof(lineState->callInfo.partyName)); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (sccp_hint_updateLineState) 0 devices register on linename: %s\n", line->name); } else if (line->channels.size > 1) { /* line is currently shared between multiple device and has multiple concurrent calls active */ sccp_hint_updateLineStateForSharedLine(lineState); } else { /* just one device per line */ sccp_hint_updateLineStateForSingleLine(lineState); } /* push chagnes to pbx */ sccp_hint_notifyPBX(lineState); line = sccp_line_release(line); } } /*! * \brief set hint status for a line with more then one channel * \param lineState SCCP LineState */ void sccp_hint_updateLineStateForSharedLine(struct sccp_hint_lineState *lineState) { sccp_line_t *line = lineState->line; sccp_channel_t *channel = NULL; memset(lineState->callInfo.partyName, 0, sizeof(lineState->callInfo.partyName)); memset(lineState->callInfo.partyNumber, 0, sizeof(lineState->callInfo.partyNumber)); /* set default calltype = SKINNY_CALLTYPE_OUTBOUND */ lineState->callInfo.calltype = SKINNY_CALLTYPE_OUTBOUND; if (line->channels.size > 0) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineStateForSharedLine) number of active channels %d\n", line->name, line->channels.size); if (line->channels.size == 1) { SCCP_LIST_LOCK(&line->channels); channel = SCCP_LIST_FIRST(&line->channels); SCCP_LIST_UNLOCK(&line->channels); if (channel && (channel = sccp_channel_retain(channel))) { lineState->callInfo.calltype = channel->calltype; if (channel->state != SCCP_CHANNELSTATE_ONHOOK && channel->state != SCCP_CHANNELSTATE_DOWN) { lineState->state = channel->state; /* set cid name/numbe information according to the call direction */ if (SKINNY_CALLTYPE_INBOUND == channel->calltype) { sccp_copy_string(lineState->callInfo.partyName, channel->callInfo.callingPartyName, sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, channel->callInfo.callingPartyName, sizeof(lineState->callInfo.partyNumber)); } else { sccp_copy_string(lineState->callInfo.partyName, channel->callInfo.calledPartyName, sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, channel->callInfo.calledPartyNumber, sizeof(lineState->callInfo.partyNumber)); } } else { lineState->state = SCCP_CHANNELSTATE_ONHOOK; } channel = sccp_channel_release(channel); } else { lineState->state = SCCP_CHANNELSTATE_ONHOOK; } } else if (line->channels.size > 1) { /** we have multiple channels, so do not set cid information */ // sccp_copy_string(lineState->callInfo.partyName, SKINNY_DISP_IN_USE_REMOTE, sizeof(lineState->callInfo.partyName)); // sccp_copy_string(lineState->callInfo.partyNumber, SKINNY_DISP_IN_USE_REMOTE, sizeof(lineState->callInfo.partyNumber)); lineState->state = SCCP_CHANNELSTATE_CONNECTED; } } else { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineStateForSharedLine) no active channels\n", line->name); lineState->state = SCCP_CHANNELSTATE_ONHOOK; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineStateForSharedLine) Set sharedLineState to %s(%d)\n", line->name, channelstate2str(lineState->state), lineState->state); } /*! * \brief set hint status for a line with less or eq one channel * \param lineState SCCP LineState * * \lock * - hint * - see sccp_line_find_byname() */ void sccp_hint_updateLineStateForSingleLine(struct sccp_hint_lineState *lineState) { sccp_line_t *line = lineState->line; sccp_channel_t *channel = NULL; sccp_device_t *device = NULL; sccp_linedevices_t *lineDevice = NULL; uint8_t state; // boolean_t dev_privacy = FALSE; /** clear cid information */ memset(lineState->callInfo.partyName, 0, sizeof(lineState->callInfo.partyName)); memset(lineState->callInfo.partyNumber, 0, sizeof(lineState->callInfo.partyNumber)); SCCP_LIST_LOCK(&line->channels); channel = SCCP_LIST_FIRST(&line->channels); SCCP_LIST_UNLOCK(&line->channels); if (channel && (channel = sccp_channel_retain(channel))) { lineState->callInfo.calltype = channel->calltype; state = channel->state; SCCP_LIST_LOCK(&line->devices); lineDevice = SCCP_LIST_FIRST(&line->devices); SCCP_LIST_UNLOCK(&line->devices); if ((lineDevice = sccp_linedevice_retain(lineDevice))) { if ((device = sccp_device_retain(lineDevice->device))) { if (device->dndFeature.enabled && device->dndFeature.status == SCCP_DNDMODE_REJECT) { state = SCCP_CHANNELSTATE_DND; } // dev_privacy = device->privacyFeature.enabled; device = device ? sccp_device_release(device) : NULL; } lineDevice = lineDevice ? sccp_linedevice_release(lineDevice) : NULL; } switch (state) { case SCCP_CHANNELSTATE_DOWN: state = SCCP_CHANNELSTATE_ONHOOK; break; case SCCP_CHANNELSTATE_SPEEDDIAL: break; case SCCP_CHANNELSTATE_ONHOOK: break; case SCCP_CHANNELSTATE_DND: sccp_copy_string(lineState->callInfo.partyName, "DND", sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, "DND", sizeof(lineState->callInfo.partyNumber)); break; case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_RINGING: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_BUSY: case SCCP_CHANNELSTATE_HOLD: case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_CALLWAITING: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: case SCCP_CHANNELSTATE_INVALIDNUMBER: // if (dev_privacy == 0 || (dev_privacy == 1 && channel->privacy == FALSE)) { /** set cid name/number information according to the call direction */ switch (channel->calltype) { case SKINNY_CALLTYPE_INBOUND: sccp_copy_string(lineState->callInfo.partyName, channel->callInfo.callingPartyName, sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, channel->callInfo.callingPartyNumber, sizeof(lineState->callInfo.partyNumber)); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: set speeddial partyName: '%s' (callingParty)\n", line->name, channel->callInfo.callingPartyName); break; case SKINNY_CALLTYPE_OUTBOUND: sccp_copy_string(lineState->callInfo.partyName, channel->callInfo.calledPartyName, sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, channel->callInfo.calledPartyNumber, sizeof(lineState->callInfo.partyNumber)); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: set speeddial partyName: '%s' (calledParty)\n", line->name, channel->callInfo.calledPartyName); break; case SKINNY_CALLTYPE_FORWARD: sccp_copy_string(lineState->callInfo.partyName, "cfwd", sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, "cfwd", sizeof(lineState->callInfo.partyNumber)); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: set speedial partyName: cfwd\n", line->name); break; } // } break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineStateForSingleLine) partyName: %s, partyNumber: %s\n", line->name, lineState->callInfo.partyName, lineState->callInfo.partyNumber); lineState->state = state; channel = sccp_channel_release(channel); } else { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineStateForSingleLine) NO CHANNEL\n", line->name); lineState->state = SCCP_CHANNELSTATE_ONHOOK; sccp_hint_checkForDND(lineState); } // if(channel) sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_updateLineStateForSingleLine) Set singleLineState to %s(%d)\n", line->name, channelstate2str(lineState->state), lineState->state); } /* ========================================================================================================================= Event Handlers : Feature Change */ /*! * \brief Handle Feature Change Event * \param event SCCP Event * * \warning * - device->buttonconfig is not always locked */ static void sccp_hint_handleFeatureChangeEvent(const sccp_event_t * event) { sccp_buttonconfig_t *buttonconfig = NULL; sccp_device_t *d = NULL; sccp_line_t *line = NULL; switch (event->event.featureChanged.featureType) { case SCCP_FEATURE_DND: if ((d = sccp_device_retain(event->event.featureChanged.device))) { SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == LINE) { line = sccp_line_find_byname(buttonconfig->button.line.name, FALSE); if (line) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_hint_handleFeatureChangeEvent) Notify the dnd status (%s) to asterisk for line %s\n", d->id, d->dndFeature.status ? "on" : "off", line->name); sccp_hint_lineStatusChanged(line, d); line = sccp_line_release(line); } } } SCCP_LIST_UNLOCK(&d->buttonconfig); sccp_device_release(d); } break; default: break; } } static enum ast_device_state sccp_hint_hint2DeviceState(sccp_channelstate_t state) { enum ast_device_state newDeviceState = AST_DEVICE_UNKNOWN; switch (state) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: newDeviceState = AST_DEVICE_NOT_INUSE; break; case SCCP_CHANNELSTATE_RINGING: newDeviceState = AST_DEVICE_RINGING; break; case SCCP_CHANNELSTATE_HOLD: newDeviceState = AST_DEVICE_ONHOLD; break; case SCCP_CHANNELSTATE_BUSY: newDeviceState = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_DND: newDeviceState = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: newDeviceState = AST_DEVICE_UNAVAILABLE; break; case SCCP_CHANNELSTATE_INVALIDNUMBER: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_PROGRESS: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_CALLWAITING: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: newDeviceState = AST_DEVICE_INUSE; break; } return newDeviceState; } /* ========================================================================================================================= PBX Notify */ /*! * \brief Notify Asterisk of Hint State Change * \param lineState SCCP LineState */ void sccp_hint_notifyPBX(struct sccp_hint_lineState *lineState) { char channelName[100]; sccp_hint_list_t *hint = NULL; sprintf(channelName, "SCCP/%s", lineState->line->name); enum ast_device_state newDeviceState = sccp_hint_hint2DeviceState(lineState->state); enum ast_device_state oldDeviceState = AST_DEVICE_NOT_INUSE; #ifndef CS_USE_ASTERISK_DISTRIBUTED_DEVSTATE SCCP_LIST_TRAVERSE(&sccp_hint_subscriptions, hint, list) { if (!strncasecmp(channelName, hint->hint_dialplan, sizeof(channelName))) { sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: (sccp_hint_notifyPBX) %s <==> %s \n", channelName, hint->hint_dialplan); sccp_copy_string(hint->callInfo.partyName, lineState->callInfo.partyName, sizeof(hint->callInfo.partyName)); sccp_copy_string(hint->callInfo.partyNumber, lineState->callInfo.partyNumber, sizeof(hint->callInfo.partyNumber)); hint->callInfo.calltype = lineState->callInfo.calltype; oldDeviceState = sccp_hint_hint2DeviceState(hint->currentState); break; } } #endif sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_3 "SCCP: (sccp_hint_notifyPBX) Notify asterisk to set state to sccp channelstate %s (%d) => asterisk: %s (%d) on channel SCCP/%s\n", channelstate2str(lineState->state), lineState->state, pbxdevicestate2str(newDeviceState), newDeviceState, lineState->line->name); // if pbx devicestate does not change, no need to inform asterisk */ // if (hint && lineState->state == hint->currentState) { if (hint && newDeviceState == oldDeviceState) { sccp_hint_notifySubscribers(hint); /* shortcut to inform sccp subscribers about changes e.g. cid update */ } else { #ifdef CS_USE_ASTERISK_DISTRIBUTED_DEVSTATE pbx_event_t *event; event = pbx_event_new(AST_EVENT_DEVICE_STATE, AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, channelName, AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, newDeviceState, AST_EVENT_IE_CEL_CIDNAME, AST_EVENT_IE_PLTYPE_STR, lineState->callInfo.partyName, AST_EVENT_IE_CEL_CIDNUM, AST_EVENT_IE_PLTYPE_STR, lineState->callInfo.partyNumber, AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_UINT, lineState->callInfo.calltype, AST_EVENT_IE_END); pbx_event_queue_and_cache(event); sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: \n"); sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_3 "SCCP: (sccp_hint_notifyPBX!distributed) Notify asterisk to set state to sccp channelstate %s (%d) => asterisk: %s (%d) on channel SCCP/%s\n", channelstate2str(lineState->state), lineState->state, pbxdevicestate2str(newDeviceState), newDeviceState, lineState->line->name); pbx_devstate_changed_literal(newDeviceState, channelName); /* come back via pbx callback and update subscribers */ #else pbx_devstate_changed_literal(newDeviceState, channelName); /* come back via pbx callback and update subscribers */ #endif } } /* ========================================================================================================================= Subscriber Notify : Updates Speeddial */ /*! * \brief send hint status to subscriber * \param hint SCCP Hint Linked List Pointer * * \todo Check if the actual device still exists while going throughthe hint->subscribers and not pointing at rubish */ static void sccp_hint_notifySubscribers(sccp_hint_list_t * hint) { sccp_device_t *d; sccp_hint_SubscribingDevice_t *subscriber = NULL; sccp_moo_t *r; #ifdef CS_DYNAMIC_SPEEDDIAL sccp_speed_t k; char displayMessage[80]; #endif sccp_channel_t tmpChannel; if (!hint) { pbx_log(LOG_ERROR, "SCCP: (sccp_hint_notifySubscribers) no hint provided to notifySubscribers about\n"); return; } if (!&GLOB(module_running) || SCCP_REF_RUNNING != sccp_refcount_isRunning()) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_3 "%s: (sccp_hint_notifySubscribers) Skip processing hint while we are shutting down.\n", hint->exten); return; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_3 "%s: (sccp_hint_notifySubscribers) notify %u subscriber(s) of %s's state %s\n", hint->exten, SCCP_LIST_GETSIZE(hint->subscribers), (hint->hint_dialplan) ? hint->hint_dialplan : "null", channelstate2str(hint->currentState)); /* use a temporary channel as fallback for non dynamic speeddial devices */ memset(&tmpChannel, 0, sizeof(sccp_channel_t)); sccp_copy_string(tmpChannel.callInfo.callingPartyName, hint->callInfo.partyName, sizeof(tmpChannel.callInfo.callingPartyName)); sccp_copy_string(tmpChannel.callInfo.calledPartyName, hint->callInfo.partyName, sizeof(tmpChannel.callInfo.calledPartyName)); sccp_copy_string(tmpChannel.callInfo.callingPartyNumber, hint->callInfo.partyNumber, sizeof(tmpChannel.callInfo.callingPartyNumber)); sccp_copy_string(tmpChannel.callInfo.calledPartyNumber, hint->callInfo.partyNumber, sizeof(tmpChannel.callInfo.calledPartyNumber)); tmpChannel.calltype = (hint->callInfo.calltype == SKINNY_CALLTYPE_OUTBOUND) ? SKINNY_CALLTYPE_OUTBOUND : SKINNY_CALLTYPE_INBOUND; /* done */ SCCP_LIST_LOCK(&hint->subscribers); SCCP_LIST_TRAVERSE(&hint->subscribers, subscriber, list) { if ((d = sccp_device_retain((sccp_device_t *) subscriber->device))) { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_notifySubscribers) notify subscriber %s of %s's state %s (%d)\n", DEV_ID_LOG(d), d->id, (hint->hint_dialplan) ? hint->hint_dialplan : "null", channelstate2str(hint->currentState), hint->currentState); #ifdef CS_DYNAMIC_SPEEDDIAL if (d->inuseprotocolversion >= 15) { sccp_dev_speed_find_byindex((sccp_device_t *) d, subscriber->instance, TRUE, &k); REQ(r, FeatureStatDynamicMessage); if (r) { r->msg.FeatureStatDynamicMessage.lel_instance = htolel(subscriber->instance); r->msg.FeatureStatDynamicMessage.lel_type = htolel(SKINNY_BUTTONTYPE_BLFSPEEDDIAL); switch (hint->currentState) { case SCCP_CHANNELSTATE_ONHOOK: snprintf(displayMessage, sizeof(displayMessage), k.name, sizeof(displayMessage)); r->msg.FeatureStatDynamicMessage.lel_status = htolel(SKINNY_BLF_STATUS_IDLE); break; case SCCP_CHANNELSTATE_DOWN: snprintf(displayMessage, sizeof(displayMessage), k.name, sizeof(displayMessage)); r->msg.FeatureStatDynamicMessage.lel_status = htolel(SKINNY_BLF_STATUS_UNKNOWN); /* default state */ break; case SCCP_CHANNELSTATE_RINGING: if (sccp_hint_isCIDavailabe(d, subscriber->positionOnDevice) == TRUE) { if (strlen(hint->callInfo.partyName) > 0) { snprintf(displayMessage, sizeof(displayMessage), "%s %s %s", hint->callInfo.partyName, (hint->callInfo.calltype == SKINNY_CALLTYPE_OUTBOUND) ? "<-" : "->", k.name); } else if (strlen(hint->callInfo.partyNumber) > 0) { snprintf(displayMessage, sizeof(displayMessage), "%s %s %s", hint->callInfo.partyNumber, (hint->callInfo.calltype == SKINNY_CALLTYPE_OUTBOUND) ? "<-" : "->", k.name); } else { snprintf(displayMessage, sizeof(displayMessage), "%s", k.name); } } else { snprintf(displayMessage, sizeof(displayMessage), "%s", k.name); } r->msg.FeatureStatDynamicMessage.lel_status = htolel(SKINNY_BLF_STATUS_ALERTING); /* ringin */ break; case SCCP_CHANNELSTATE_DND: snprintf(displayMessage, sizeof(displayMessage), k.name, sizeof(displayMessage)); r->msg.FeatureStatDynamicMessage.lel_status = htolel(SKINNY_BLF_STATUS_DND); /* dnd */ break; case SCCP_CHANNELSTATE_CONGESTION: snprintf(displayMessage, sizeof(displayMessage), k.name, sizeof(displayMessage)); r->msg.FeatureStatDynamicMessage.lel_status = htolel(SKINNY_BLF_STATUS_UNKNOWN); /* device/line not found */ break; default: if (sccp_hint_isCIDavailabe(d, subscriber->positionOnDevice) == TRUE) { if (strlen(hint->callInfo.partyName) > 0) { snprintf(displayMessage, sizeof(displayMessage), "%s %s %s", hint->callInfo.partyName, (hint->callInfo.calltype == SKINNY_CALLTYPE_OUTBOUND) ? "<-" : "<->", k.name); } else if (strlen(hint->callInfo.partyNumber) > 0) { snprintf(displayMessage, sizeof(displayMessage), "%s %s %s", hint->callInfo.partyNumber, (hint->callInfo.calltype == SKINNY_CALLTYPE_OUTBOUND) ? "<-" : "<->", k.name); } else { snprintf(displayMessage, sizeof(displayMessage), "%s", k.name); } } else { snprintf(displayMessage, sizeof(displayMessage), "%s", k.name); } r->msg.FeatureStatDynamicMessage.lel_status = htolel(SKINNY_BLF_STATUS_INUSE); /* connected */ break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_notifySubscribers) set display name to: \"%s\"\n", DEV_ID_LOG(d), displayMessage); sccp_copy_string(r->msg.FeatureStatDynamicMessage.DisplayName, displayMessage, sizeof(r->msg.FeatureStatDynamicMessage.DisplayName)); sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_notifySubscribers) notify device: %s@%d state: %d(%d)\n", DEV_ID_LOG(d), DEV_ID_LOG(d), subscriber->instance, hint->currentState, r->msg.FeatureStatDynamicMessage.lel_status); sccp_dev_send(d, r); } else { sccp_free(r); } } else #endif { /* we have dynamic speeddial enabled, but subscriber can not handle this. We have to switch back to old hint style and send old state. */ sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_notifySubscribers) can not handle dynamic speeddial, fall back to old behavior using state %s (%d)\n", DEV_ID_LOG(d), channelstate2str(hint->currentState), hint->currentState); /* With the old hint style we should only use SCCP_CHANNELSTATE_ONHOOK and SCCP_CHANNELSTATE_CALLREMOTEMULTILINE as callstate, otherwise we get a callplane on device -> set all states except onhook to SCCP_CHANNELSTATE_CALLREMOTEMULTILINE -MC */ uint32_t iconstate = SKINNY_CALLSTATE_CALLREMOTEMULTILINE; switch (hint->currentState) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_CONGESTION: iconstate = SKINNY_CALLSTATE_ONHOOK; break; case SCCP_CHANNELSTATE_RINGING: if (d->allowRinginNotification) { iconstate = SKINNY_CALLSTATE_RINGIN; } break; case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_BUSY: case SCCP_CHANNELSTATE_HOLD: case SCCP_CHANNELSTATE_CALLWAITING: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: case SCCP_CHANNELSTATE_INVALIDNUMBER: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_PROGRESS: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_DND: iconstate = SKINNY_CALLSTATE_CALLREMOTEMULTILINE; break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "%s: (sccp_hint_notifySubscribers) setting icon to state %s (%d)\n", DEV_ID_LOG(d), channelstate2str(iconstate), iconstate); if (SCCP_CHANNELSTATE_RINGING == hint->previousState) { /* we send a congestion to the phone, so call will not be marked as missed call */ sccp_device_sendcallstate(d, subscriber->instance, 0, SCCP_CHANNELSTATE_CONGESTION, SKINNY_CALLPRIORITY_NORMAL, SKINNY_CALLINFO_VISIBILITY_HIDDEN); } sccp_device_sendcallstate(d, subscriber->instance, 0, iconstate, SKINNY_CALLPRIORITY_NORMAL, SKINNY_CALLINFO_VISIBILITY_DEFAULT); /** do not set visibility to COLLAPSED, this will hidde callInfo in state CALLREMOTEMULTILINE */ if (hint->currentState == SCCP_CHANNELSTATE_ONHOOK || hint->currentState == SCCP_CHANNELSTATE_CONGESTION) { sccp_dev_set_keyset(d, subscriber->instance, 0, KEYMODE_ONHOOK); } else { d->protocol->sendCallInfo(d, &tmpChannel, subscriber->instance); sccp_dev_set_keyset(d, subscriber->instance, 0, KEYMODE_INUSEHINT); } } d = sccp_device_release(d); } else { sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (sccp_hint_notifySubscribers) device not found/retained\n"); } } SCCP_LIST_UNLOCK(&hint->subscribers); } /* ========================================================================================================================= Helper Functions */ #ifdef CS_DYNAMIC_SPEEDDIAL /* * model information should be moved to sccp_dev_build_buttontemplate, or some other place */ static inline boolean_t sccp_hint_isCIDavailabe(const sccp_device_t * device, const uint8_t positionOnDevice) { #ifdef CS_DYNAMIC_SPEEDDIAL_CID if (positionOnDevice <= 8 && (device->skinny_type == SKINNY_DEVICETYPE_CISCO7970 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7971 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7975 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7985 || device->skinny_type == SKINNY_DEVICETYPE_CISCO_IP_COMMUNICATOR)) { return TRUE; } if (positionOnDevice <= 6 && (device->skinny_type == SKINNY_DEVICETYPE_CISCO7945 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7961 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7961GE || device->skinny_type == SKINNY_DEVICETYPE_CISCO7962 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7965)) { return TRUE; } if (positionOnDevice <= 2 && (device->skinny_type == SKINNY_DEVICETYPE_CISCO7911 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7912 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7931 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7935 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7936 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7937 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7941 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7941GE || device->skinny_type == SKINNY_DEVICETYPE_CISCO7942 || device->skinny_type == SKINNY_DEVICETYPE_CISCO7945)) { return TRUE; } #endif return FALSE; } #endif static void sccp_hint_checkForDND(struct sccp_hint_lineState *lineState) { sccp_linedevices_t *lineDevice; sccp_line_t *line = lineState->line; // if (line->devices.size > 1) { /* we have to check if all devices on this line are dnd=SCCP_DNDMODE_REJECT, otherwise do not propagate DND status */ boolean_t allDevicesInDND = TRUE; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, lineDevice, list) { if (lineDevice->device && lineDevice->device->dndFeature.status != SCCP_DNDMODE_REJECT) { allDevicesInDND = FALSE; break; } } SCCP_LIST_UNLOCK(&line->devices); if (allDevicesInDND) { lineState->state = SCCP_CHANNELSTATE_DND; } } // else { // SCCP_LIST_LOCK(&line->devices); // sccp_linedevices_t *lineDevice = SCCP_LIST_FIRST(&line->devices); // // if (lineDevice && lineDevice->device) { // if (lineDevice->device->dndFeature.enabled && lineDevice->device->dndFeature.status == SCCP_DNDMODE_REJECT) { // lineState->state = SCCP_CHANNELSTATE_DND; // } // } // SCCP_LIST_UNLOCK(&line->devices); // } if (lineState->state == SCCP_CHANNELSTATE_DND) { sccp_copy_string(lineState->callInfo.partyName, "DND", sizeof(lineState->callInfo.partyName)); sccp_copy_string(lineState->callInfo.partyNumber, "DND", sizeof(lineState->callInfo.partyNumber)); } } sccp_channelstate_t sccp_hint_getLinestate(const char *linename, const char *deviceId) { struct sccp_hint_lineState *lineState = NULL; sccp_channelstate_t state = SCCP_CHANNELSTATE_CONGESTION; SCCP_LIST_LOCK(&lineStates); SCCP_LIST_TRAVERSE(&lineStates, lineState, list) { if (sccp_strcaseequals(lineState->line->name, linename)) { state = lineState->state; break; } } SCCP_LIST_UNLOCK(&lineStates); return state; }
722,255
./chan-sccp-b/src/sccp_protocol.c
/*! * \file sccp_protocol.c * \brief SCCP Protocol implementation. * This file does the protocol implementation only. It should not be used as a controller. * \author Marcello Ceschia <marcello.ceschia [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" #define GENERATE_ENUM_STRINGS #include "sccp_enum_macro.h" #include "sccp_protocol_enums.hh" #undef GENERATE_ENUM_STRINGS /* CallInfo Message */ /* =================================================================================================================== Send Messages */ /*! * \brief Send CallInfoMessage (V3) */ static void sccp_device_sendCallinfoV3(const sccp_device_t * device, const sccp_channel_t * channel, uint8_t instance) { sccp_moo_t *r; if (!channel) { return; } REQ(r, CallInfoMessage); if (channel->callInfo.callingPartyName) { sccp_copy_string(r->msg.CallInfoMessage.callingPartyName, channel->callInfo.callingPartyName, sizeof(r->msg.CallInfoMessage.callingPartyName)); } if (channel->callInfo.callingPartyNumber) sccp_copy_string(r->msg.CallInfoMessage.callingParty, channel->callInfo.callingPartyNumber, sizeof(r->msg.CallInfoMessage.callingParty)); if (channel->callInfo.calledPartyName) sccp_copy_string(r->msg.CallInfoMessage.calledPartyName, channel->callInfo.calledPartyName, sizeof(r->msg.CallInfoMessage.calledPartyName)); if (channel->callInfo.calledPartyNumber) sccp_copy_string(r->msg.CallInfoMessage.calledParty, channel->callInfo.calledPartyNumber, sizeof(r->msg.CallInfoMessage.calledParty)); if (channel->callInfo.originalCalledPartyName) sccp_copy_string(r->msg.CallInfoMessage.originalCalledPartyName, channel->callInfo.originalCalledPartyName, sizeof(r->msg.CallInfoMessage.originalCalledPartyName)); if (channel->callInfo.originalCalledPartyNumber) sccp_copy_string(r->msg.CallInfoMessage.originalCalledParty, channel->callInfo.originalCalledPartyNumber, sizeof(r->msg.CallInfoMessage.originalCalledParty)); if (channel->callInfo.lastRedirectingPartyName) sccp_copy_string(r->msg.CallInfoMessage.lastRedirectingPartyName, channel->callInfo.lastRedirectingPartyName, sizeof(r->msg.CallInfoMessage.lastRedirectingPartyName)); if (channel->callInfo.lastRedirectingPartyNumber) sccp_copy_string(r->msg.CallInfoMessage.lastRedirectingParty, channel->callInfo.lastRedirectingPartyNumber, sizeof(r->msg.CallInfoMessage.lastRedirectingParty)); if (channel->callInfo.originalCdpnRedirectReason) r->msg.CallInfoMessage.originalCdpnRedirectReason = htolel(channel->callInfo.originalCdpnRedirectReason); if (channel->callInfo.lastRedirectingReason) r->msg.CallInfoMessage.lastRedirectingReason = htolel(channel->callInfo.lastRedirectingReason); if (channel->callInfo.cgpnVoiceMailbox) sccp_copy_string(r->msg.CallInfoMessage.cgpnVoiceMailbox, channel->callInfo.cgpnVoiceMailbox, sizeof(r->msg.CallInfoMessage.cgpnVoiceMailbox)); if (channel->callInfo.cdpnVoiceMailbox) sccp_copy_string(r->msg.CallInfoMessage.cdpnVoiceMailbox, channel->callInfo.cdpnVoiceMailbox, sizeof(r->msg.CallInfoMessage.cdpnVoiceMailbox)); if (channel->callInfo.originalCdpnVoiceMailbox) sccp_copy_string(r->msg.CallInfoMessage.originalCdpnVoiceMailbox, channel->callInfo.originalCdpnVoiceMailbox, sizeof(r->msg.CallInfoMessage.originalCdpnVoiceMailbox)); if (channel->callInfo.lastRedirectingVoiceMailbox) sccp_copy_string(r->msg.CallInfoMessage.lastRedirectingVoiceMailbox, channel->callInfo.lastRedirectingVoiceMailbox, sizeof(r->msg.CallInfoMessage.lastRedirectingVoiceMailbox)); r->msg.CallInfoMessage.lel_lineId = htolel(instance); r->msg.CallInfoMessage.lel_callRef = htolel(channel->callid); r->msg.CallInfoMessage.lel_callType = htolel(channel->calltype); r->msg.CallInfoMessage.lel_callSecurityStatus = htolel(SKINNY_CALLSECURITYSTATE_UNKNOWN); sccp_dev_send(device, r); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Send callinfo for %s channel %d on line instance %d" "\n\tcallerid: %s" "\n\tcallerName: %s\n", (device) ? device->id : "(null)", calltype2str(channel->calltype), channel->callid, instance, channel->callInfo.callingPartyNumber, channel->callInfo.callingPartyName); } /*! * \brief Send CallInfoMessage (V7) */ static void sccp_device_sendCallinfoV7(const sccp_device_t * device, const sccp_channel_t * channel, uint8_t instance) { sccp_moo_t *r; if (!channel) { return; } unsigned int dataSize = 12; const char *data[dataSize]; int data_len[dataSize]; unsigned int i = 0; int dummy_len = 0; memset(data, 0, sizeof(data)); data[0] = (strlen(channel->callInfo.callingPartyNumber) > 0) ? channel->callInfo.callingPartyNumber : NULL; data[1] = (strlen(channel->callInfo.calledPartyNumber) > 0) ? channel->callInfo.calledPartyNumber : NULL; data[2] = (strlen(channel->callInfo.originalCalledPartyNumber) > 0) ? channel->callInfo.originalCalledPartyNumber : NULL; data[3] = (strlen(channel->callInfo.lastRedirectingPartyNumber) > 0) ? channel->callInfo.lastRedirectingPartyNumber : NULL; data[4] = (strlen(channel->callInfo.cgpnVoiceMailbox) > 0) ? channel->callInfo.cgpnVoiceMailbox : NULL; data[5] = (strlen(channel->callInfo.cdpnVoiceMailbox) > 0) ? channel->callInfo.cdpnVoiceMailbox : NULL; data[6] = (strlen(channel->callInfo.originalCdpnVoiceMailbox) > 0) ? channel->callInfo.originalCdpnVoiceMailbox : NULL; data[7] = (strlen(channel->callInfo.lastRedirectingVoiceMailbox) > 0) ? channel->callInfo.lastRedirectingVoiceMailbox : NULL; data[8] = (strlen(channel->callInfo.callingPartyName) > 0) ? channel->callInfo.callingPartyName : NULL; data[9] = (strlen(channel->callInfo.calledPartyName) > 0) ? channel->callInfo.calledPartyName : NULL; data[10] = (strlen(channel->callInfo.originalCalledPartyName) > 0) ? channel->callInfo.originalCalledPartyName : NULL; data[11] = (strlen(channel->callInfo.lastRedirectingPartyName) > 0) ? channel->callInfo.lastRedirectingPartyName : NULL; for (i = 0; i < dataSize; i++) { if (data[i] != NULL) { data_len[i] = strlen(data[i]); dummy_len += data_len[i]; } else { data_len[i] = 0; //! \todo this should be 1? } } int hdr_len = sizeof(r->msg.CallInfoDynamicMessage) + (dataSize - 4); int padding = ((dummy_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; r = sccp_build_packet(CallInfoDynamicMessage, hdr_len + dummy_len + padding); r->msg.CallInfoDynamicMessage.lel_lineId = htolel(instance); r->msg.CallInfoDynamicMessage.lel_callRef = htolel(channel->callid); r->msg.CallInfoDynamicMessage.lel_callType = htolel(channel->calltype); r->msg.CallInfoDynamicMessage.partyPIRestrictionBits = 0; r->msg.CallInfoDynamicMessage.lel_callSecurityStatus = htolel(SKINNY_CALLSECURITYSTATE_NOTAUTHENTICATED); r->msg.CallInfoDynamicMessage.lel_callInstance = htolel(instance); r->msg.CallInfoDynamicMessage.lel_originalCdpnRedirectReason = htolel(channel->callInfo.originalCdpnRedirectReason); r->msg.CallInfoDynamicMessage.lel_lastRedirectingReason = htolel(channel->callInfo.lastRedirectingReason); if (dummy_len) { int bufferSize = dummy_len + ARRAY_LEN(data); char buffer[bufferSize]; memset(&buffer[0], 0, bufferSize); int pos = 0; for (i = 0; i < ARRAY_LEN(data); i++) { sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "SCCP: cid field %d, value: '%s'\n", i, (data[i]) ? data[i] : ""); if (data[i]) { memcpy(&buffer[pos], data[i], data_len[i]); pos += data_len[i] + 1; } else { pos += 1; } } memcpy(&r->msg.CallInfoDynamicMessage.dummy, &buffer[0], bufferSize); } sccp_dev_send(device, r); } /*! * \brief Send CallInfoMessage (V16) */ static void sccp_protocol_sendCallinfoV16(const sccp_device_t * device, const sccp_channel_t * channel, uint8_t instance) { sccp_moo_t *r; if (!channel) { return; } unsigned int dataSize = 16; const char *data[dataSize]; int data_len[dataSize]; unsigned int i = 0; int dummy_len = 0; memset(data, 0, sizeof(data)); data[0] = (strlen(channel->callInfo.callingPartyNumber) > 0) ? channel->callInfo.callingPartyNumber : NULL; data[1] = (strlen(channel->callInfo.originalCallingPartyNumber) > 0) ? channel->callInfo.originalCallingPartyNumber : NULL; data[2] = (strlen(channel->callInfo.calledPartyNumber) > 0) ? channel->callInfo.calledPartyNumber : NULL; data[3] = (strlen(channel->callInfo.originalCalledPartyNumber) > 0) ? channel->callInfo.originalCalledPartyNumber : NULL; data[4] = (strlen(channel->callInfo.lastRedirectingPartyNumber) > 0) ? channel->callInfo.lastRedirectingPartyNumber : NULL; data[5] = (strlen(channel->callInfo.cgpnVoiceMailbox) > 0) ? channel->callInfo.cgpnVoiceMailbox : NULL; data[6] = (strlen(channel->callInfo.cdpnVoiceMailbox) > 0) ? channel->callInfo.cdpnVoiceMailbox : NULL; data[7] = (strlen(channel->callInfo.originalCdpnVoiceMailbox) > 0) ? channel->callInfo.originalCdpnVoiceMailbox : NULL; data[8] = (strlen(channel->callInfo.lastRedirectingVoiceMailbox) > 0) ? channel->callInfo.lastRedirectingVoiceMailbox : NULL; data[9] = (strlen(channel->callInfo.callingPartyName) > 0) ? channel->callInfo.callingPartyName : NULL; data[10] = (strlen(channel->callInfo.calledPartyName) > 0) ? channel->callInfo.calledPartyName : NULL; data[11] = (strlen(channel->callInfo.originalCalledPartyName) > 0) ? channel->callInfo.originalCalledPartyName : NULL; data[12] = (strlen(channel->callInfo.lastRedirectingPartyName) > 0) ? channel->callInfo.lastRedirectingPartyName : NULL; data[13] = (strlen(channel->callInfo.originalCalledPartyName) > 0) ? channel->callInfo.originalCalledPartyName : NULL; data[14] = (strlen(channel->callInfo.cgpnVoiceMailbox) > 0) ? channel->callInfo.cgpnVoiceMailbox : NULL; data[15] = (strlen(channel->callInfo.cdpnVoiceMailbox) > 0) ? channel->callInfo.cdpnVoiceMailbox : NULL; for (i = 0; i < dataSize; i++) { if (data[i] != NULL) { data_len[i] = strlen(data[i]); dummy_len += data_len[i]; } else { data_len[i] = 0; //! \todo this should be 1? } } int hdr_len = sizeof(r->msg.CallInfoDynamicMessage) + (dataSize - 4); int padding = ((dummy_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; r = sccp_build_packet(CallInfoDynamicMessage, hdr_len + dummy_len + padding); r->msg.CallInfoDynamicMessage.lel_lineId = htolel(instance); r->msg.CallInfoDynamicMessage.lel_callRef = htolel(channel->callid); r->msg.CallInfoDynamicMessage.lel_callType = htolel(channel->calltype); r->msg.CallInfoDynamicMessage.partyPIRestrictionBits = 0; r->msg.CallInfoDynamicMessage.lel_callSecurityStatus = htolel(SKINNY_CALLSECURITYSTATE_NOTAUTHENTICATED); r->msg.CallInfoDynamicMessage.lel_callInstance = htolel(instance); r->msg.CallInfoDynamicMessage.lel_originalCdpnRedirectReason = htolel(channel->callInfo.originalCdpnRedirectReason); r->msg.CallInfoDynamicMessage.lel_lastRedirectingReason = htolel(channel->callInfo.lastRedirectingReason); if (dummy_len) { int bufferSize = dummy_len + ARRAY_LEN(data); char buffer[bufferSize]; memset(&buffer[0], 0, bufferSize); int pos = 0; for (i = 0; i < ARRAY_LEN(data); i++) { sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "SCCP: cid field %d, value: '%s'\n", i, (data[i]) ? data[i] : ""); if (data[i]) { memcpy(&buffer[pos], data[i], data_len[i]); pos += data_len[i] + 1; } else { pos += 1; } } memcpy(&r->msg.CallInfoDynamicMessage.dummy, &buffer[0], bufferSize); } sccp_dev_send(device, r); } /* done - callInfoMessage */ /* DialedNumber Message */ /*! * \brief Send DialedNumber Message (V3) */ static void sccp_protocol_sendDialedNumberV3(const sccp_device_t * device, const sccp_channel_t * channel) { sccp_moo_t *r; uint8_t instance; REQ(r, DialedNumberMessage); instance = sccp_device_find_index_for_line(device, channel->line->name); sccp_copy_string(r->msg.DialedNumberMessage.calledParty, channel->callInfo.calledPartyNumber, sizeof(r->msg.DialedNumberMessage.calledParty)); r->msg.DialedNumberMessage.lel_lineId = htolel(instance); r->msg.DialedNumberMessage.lel_callRef = htolel(channel->callid); sccp_dev_send(device, r); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Send the dialed number %s for %s channel %d\n", device->id, channel->callInfo.calledPartyNumber, calltype2str(channel->calltype), channel->callid); } /*! * \brief Send DialedNumber Message (V19) * * \todo this message is wrong, but we get 'Placed Calls' working on V >= 19 */ static void sccp_protocol_sendDialedNumberV19(const sccp_device_t * device, const sccp_channel_t * channel) { sccp_moo_t *r; uint8_t instance; REQ(r, DialedNumberMessageV19); instance = sccp_device_find_index_for_line(device, channel->line->name); sccp_copy_string(r->msg.DialedNumberMessageV19.calledParty, channel->callInfo.calledPartyNumber, sizeof(r->msg.DialedNumberMessage.calledParty)); r->msg.DialedNumberMessageV19.lel_lineId = htolel(instance); r->msg.DialedNumberMessageV19.lel_callRef = htolel(channel->callid); sccp_dev_send(device, r); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: Send the dialed number %s for %s channel %d\n", device->id, channel->callInfo.calledPartyNumber, calltype2str(channel->calltype), channel->callid); } /* done - DialedNumber Message */ /* Display Prompt Message */ /*! * \brief Send Display Prompt Message (Static) */ static void sccp_protocol_sendStaticDisplayprompt(const sccp_device_t * device, uint8_t lineInstance, uint8_t callid, uint8_t timeout, const char *message) { sccp_moo_t *r; REQ(r, DisplayPromptStatusMessage); r->msg.DisplayPromptStatusMessage.lel_messageTimeout = htolel(timeout); r->msg.DisplayPromptStatusMessage.lel_callReference = htolel(callid); r->msg.DisplayPromptStatusMessage.lel_lineInstance = htolel(lineInstance); sccp_copy_string(r->msg.DisplayPromptStatusMessage.promptMessage, message, sizeof(r->msg.DisplayPromptStatusMessage.promptMessage)); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Display prompt on line %d, callid %d, timeout %d\n", device->id, lineInstance, callid, timeout); } /*! * \brief Send Display Prompt Message (Dynamic) */ static void sccp_protocol_sendDynamicDisplayprompt(const sccp_device_t * device, uint8_t lineInstance, uint8_t callid, uint8_t timeout, const char *message) { sccp_moo_t *r; int msg_len = strlen(message); int hdr_len = sizeof(r->msg.DisplayDynamicPromptStatusMessage) - 3; int padding = ((msg_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; r = sccp_build_packet(DisplayDynamicPromptStatusMessage, hdr_len + msg_len + padding); r->msg.DisplayDynamicPromptStatusMessage.lel_messageTimeout = htolel(timeout); r->msg.DisplayDynamicPromptStatusMessage.lel_callReference = htolel(callid); r->msg.DisplayDynamicPromptStatusMessage.lel_lineInstance = htolel(lineInstance); memcpy(&r->msg.DisplayDynamicPromptStatusMessage.dummy, message, msg_len); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Display prompt on line %d, callid %d, timeout %d\n", device->id, lineInstance, callid, timeout); } /* done - display prompt */ /* Display Notify Message */ /*! * \brief Send Display Notify Message (Static) */ static void sccp_protocol_sendStaticDisplayNotify(const sccp_device_t * device, uint8_t timeout, const char *message) { sccp_moo_t *r; REQ(r, DisplayNotifyMessage); r->msg.DisplayNotifyMessage.lel_displayTimeout = htolel(timeout); sccp_copy_string(r->msg.DisplayNotifyMessage.displayMessage, message, sizeof(r->msg.DisplayNotifyMessage.displayMessage)); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Display notify timeout %d\n", device->id, timeout); } /*! * \brief Send Display Notify Message (Dynamic) */ static void sccp_protocol_sendDynamicDisplayNotify(const sccp_device_t * device, uint8_t timeout, const char *message) { sccp_moo_t *r; int msg_len = strlen(message); int hdr_len = sizeof(r->msg.DisplayDynamicNotifyMessage) - sizeof(r->msg.DisplayDynamicNotifyMessage.dummy); int padding = ((msg_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; r = sccp_build_packet(DisplayDynamicNotifyMessage, hdr_len + msg_len + padding); r->msg.DisplayDynamicNotifyMessage.lel_displayTimeout = htolel(timeout); memcpy(&r->msg.DisplayDynamicNotifyMessage.dummy, message, msg_len); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Display notify timeout %d\n", device->id, timeout); } /* done - display notify */ /* Display Priority Notify Message */ /*! * \brief Send Priority Display Notify Message (Static) */ static void sccp_protocol_sendStaticDisplayPriNotify(const sccp_device_t * device, uint8_t priority, uint8_t timeout, const char *message) { sccp_moo_t *r; REQ(r, DisplayPriNotifyMessage); r->msg.DisplayPriNotifyMessage.lel_displayTimeout = htolel(timeout); r->msg.DisplayPriNotifyMessage.lel_priority = htolel(priority); sccp_copy_string(r->msg.DisplayPriNotifyMessage.displayMessage, message, sizeof(r->msg.DisplayPriNotifyMessage.displayMessage)); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Display notify timeout %d\n", device->id, timeout); } /*! * \brief Send Priority Display Notify Message (Dynamic) */ static void sccp_protocol_sendDynamicDisplayPriNotify(const sccp_device_t * device, uint8_t priority, uint8_t timeout, const char *message) { sccp_moo_t *r; int msg_len = strlen(message); int hdr_len = sizeof(r->msg.DisplayDynamicPriNotifyMessage) - 3; int padding = ((msg_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; r = sccp_build_packet(DisplayDynamicPriNotifyMessage, hdr_len + msg_len + padding); r->msg.DisplayDynamicPriNotifyMessage.lel_displayTimeout = htolel(timeout); r->msg.DisplayDynamicPriNotifyMessage.lel_priority = htolel(priority); memcpy(&r->msg.DisplayDynamicPriNotifyMessage.dummy, message, msg_len); sccp_dev_send(device, r); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Display notify timeout %d\n", device->id, timeout); } /* done - display notify */ /* callForwardStatus Message */ /*! * \brief Send Call Forward Status Message */ static void sccp_protocol_sendCallForwardStatus(const sccp_device_t * device, const void *data) { sccp_moo_t *r; const sccp_linedevices_t *linedevice = (sccp_linedevices_t *) data; REQ(r, ForwardStatMessage); r->msg.ForwardStatMessage.lel_lineNumber = htolel(linedevice->lineInstance); r->msg.ForwardStatMessage.lel_status = (linedevice->cfwdAll.enabled || linedevice->cfwdBusy.enabled) ? htolel(1) : 0; if (linedevice->cfwdAll.enabled) { r->msg.ForwardStatMessage.lel_cfwdallstatus = htolel(1); sccp_copy_string(r->msg.ForwardStatMessage.cfwdallnumber, linedevice->cfwdAll.number, sizeof(r->msg.ForwardStatMessage.cfwdallnumber)); } if (linedevice->cfwdBusy.enabled) { r->msg.ForwardStatMessage.lel_cfwdbusystatus = htolel(1); sccp_copy_string(r->msg.ForwardStatMessage.cfwdbusynumber, linedevice->cfwdBusy.number, sizeof(r->msg.ForwardStatMessage.cfwdbusynumber)); } sccp_dev_send(device, r); } /*! * \brief Send Call Forward Status Message (V19) */ static void sccp_protocol_sendCallForwardStatusV19(const sccp_device_t * device, const void *data) { sccp_moo_t *r; const sccp_linedevices_t *linedevice = (sccp_linedevices_t *) data; REQ(r, ForwardStatMessageV19); r->msg.ForwardStatMessageV19.lel_lineNumber = htolel(linedevice->lineInstance); r->msg.ForwardStatMessageV19.lel_status = (linedevice->cfwdAll.enabled || linedevice->cfwdBusy.enabled) ? htolel(1) : 0; if (linedevice->cfwdAll.enabled) { r->msg.ForwardStatMessageV19.lel_cfwdallstatus = htolel(1); sccp_copy_string(r->msg.ForwardStatMessageV19.cfwdallnumber, linedevice->cfwdAll.number, sizeof(r->msg.ForwardStatMessageV19.cfwdallnumber)); } if (linedevice->cfwdBusy.enabled) { r->msg.ForwardStatMessageV19.lel_cfwdbusystatus = htolel(1); sccp_copy_string(r->msg.ForwardStatMessageV19.cfwdbusynumber, linedevice->cfwdBusy.number, sizeof(r->msg.ForwardStatMessageV19.cfwdbusynumber)); } r->msg.ForwardStatMessageV19.lel_unknown = 0x000000FF; sccp_dev_send(device, r); } /* done - send callForwardStatus */ /* registerAck Message */ /*! * \brief Send Register Acknowledgement Message (V3) */ static void sccp_protocol_sendRegisterAckV3(const sccp_device_t * device, uint8_t keepAliveInterval, uint8_t secondaryKeepAlive, char *dateformat) { sccp_moo_t *r; REQ(r, RegisterAckMessage); /* just for documentation */ #if 0 r->msg.RegisterAckMessage.unknown1 = 0x00; r->msg.RegisterAckMessage.unknown2 = 0x00; r->msg.RegisterAckMessage.unknown3 = 0x00; #endif r->msg.RegisterAckMessage.protocolVer = device->protocol->version; r->msg.RegisterAckMessage.lel_keepAliveInterval = htolel(keepAliveInterval); r->msg.RegisterAckMessage.lel_secondaryKeepAliveInterval = htolel(secondaryKeepAlive); memcpy(r->msg.RegisterAckMessage.dateTemplate, dateformat, sizeof(r->msg.RegisterAckMessage.dateTemplate)); sccp_dev_send(device, r); } /*! * \brief Send Register Acknowledgement Message (V4) */ static void sccp_protocol_sendRegisterAckV4(const sccp_device_t * device, uint8_t keepAliveInterval, uint8_t secondaryKeepAlive, char *dateformat) { sccp_moo_t *r; REQ(r, RegisterAckMessage); r->msg.RegisterAckMessage.unknown1 = 0x20; // 0x00; r->msg.RegisterAckMessage.unknown2 = 0x00; // 0x00; r->msg.RegisterAckMessage.unknown3 = 0xFE; // 0xFE; r->msg.RegisterAckMessage.protocolVer = device->protocol->version; r->msg.RegisterAckMessage.lel_keepAliveInterval = htolel(keepAliveInterval); r->msg.RegisterAckMessage.lel_secondaryKeepAliveInterval = htolel(secondaryKeepAlive); memcpy(r->msg.RegisterAckMessage.dateTemplate, dateformat, sizeof(r->msg.RegisterAckMessage.dateTemplate)); sccp_dev_send(device, r); } /*! * \brief Send Register Acknowledgement Message (V11) */ static void sccp_protocol_sendRegisterAckV11(const sccp_device_t * device, uint8_t keepAliveInterval, uint8_t secondaryKeepAlive, char *dateformat) { sccp_moo_t *r; REQ(r, RegisterAckMessage); r->msg.RegisterAckMessage.unknown1 = 0x20; // 0x00; r->msg.RegisterAckMessage.unknown2 = 0xF1; // 0xF1; r->msg.RegisterAckMessage.unknown3 = 0xFF; // 0xFF; r->msg.RegisterAckMessage.protocolVer = device->protocol->version; r->msg.RegisterAckMessage.lel_keepAliveInterval = htolel(keepAliveInterval); r->msg.RegisterAckMessage.lel_secondaryKeepAliveInterval = htolel(secondaryKeepAlive); memcpy(r->msg.RegisterAckMessage.dateTemplate, dateformat, sizeof(r->msg.RegisterAckMessage.dateTemplate)); sccp_dev_send(device, r); } /* done - registerACK */ /*! * \brief Send Open Receive Channel (V3) */ static void sccp_protocol_sendOpenReceiveChannelV3(const sccp_device_t * device, const sccp_channel_t * channel) { int packetSize = 20; /*! \todo calculate packetSize */ sccp_moo_t *r = sccp_build_packet(OpenReceiveChannel, sizeof(r->msg.OpenReceiveChannel.v3)); r->msg.OpenReceiveChannel.v3.lel_conferenceId = htolel(channel->callid); r->msg.OpenReceiveChannel.v3.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.OpenReceiveChannel.v3.lel_millisecondPacketSize = htolel(packetSize); r->msg.OpenReceiveChannel.v3.lel_payloadType = htolel(channel->rtp.audio.writeFormat); r->msg.OpenReceiveChannel.v3.lel_vadValue = htolel(channel->line->echocancel); r->msg.OpenReceiveChannel.v3.lel_conferenceId1 = htolel(channel->callid); r->msg.OpenReceiveChannel.v3.lel_rtptimeout = htolel(10); sccp_dev_send(device, r); } /*! * \brief Send Open Receive Channel (V17) */ static void sccp_protocol_sendOpenReceiveChannelV17(const sccp_device_t * device, const sccp_channel_t * channel) { struct sockaddr_in *them; int packetSize = 20; /*! \todo calculate packetSize */ sccp_moo_t *r = sccp_build_packet(OpenReceiveChannel, sizeof(r->msg.OpenReceiveChannel.v17)); sccp_rtp_getAudioPeer((sccp_channel_t *) channel, &them); r->msg.OpenReceiveChannel.v17.lel_conferenceId = htolel(channel->callid); r->msg.OpenReceiveChannel.v17.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.OpenReceiveChannel.v17.lel_millisecondPacketSize = htolel(packetSize); r->msg.OpenReceiveChannel.v17.lel_payloadType = htolel(channel->rtp.audio.writeFormat); r->msg.OpenReceiveChannel.v17.lel_vadValue = htolel(channel->line->echocancel); r->msg.OpenReceiveChannel.v17.lel_conferenceId1 = htolel(channel->callid); r->msg.OpenReceiveChannel.v17.lel_rtptimeout = htolel(10); r->msg.OpenReceiveChannel.v17.lel_unknown17 = htolel(4000); // if (channel->rtp.audio.phone_remote.sin_family = AF_INET) r->msg.OpenReceiveChannel.v17.lel_ipv46 = htolel(0); memcpy(&r->msg.OpenReceiveChannel.v17.bel_remoteIpAddr, &them->sin_addr, INET_ADDRSTRLEN); // } else { // r->msg.OpenReceiveChannel.v17.lel_ipv46 = htolel(1); // memcpy(&r->msg.OpenReceiveChannel.v17.bel_remoteIpAddr, &them->sin_addr, INET6_ADDRSTRLEN); // } sccp_dev_send(device, r); } /*! * \brief Send Open MultiMediaChannel Message (V3) */ static void sccp_protocol_sendOpenMultiMediaChannelV3(const sccp_device_t * device, const sccp_channel_t * channel, uint32_t skinnyFormat, int payloadType, uint8_t lineInstance, int bitRate) { sccp_moo_t *r = sccp_build_packet(OpenMultiMediaChannelMessage, sizeof(r->msg.OpenMultiMediaChannelMessage.v3)); r->msg.OpenMultiMediaChannelMessage.v3.lel_conferenceID = htolel(channel->callid); r->msg.OpenMultiMediaChannelMessage.v3.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.OpenMultiMediaChannelMessage.v3.lel_payloadCapability = htolel(skinnyFormat); r->msg.OpenMultiMediaChannelMessage.v3.lel_lineInstance = htolel(lineInstance); r->msg.OpenMultiMediaChannelMessage.v3.lel_callReference = htolel(channel->callid); r->msg.OpenMultiMediaChannelMessage.v3.lel_payloadType = htolel(payloadType); // r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.pictureFormatCount = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.pictureFormat[0].format = htolel(4); // r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.pictureFormat[0].mpi = htolel(30); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.profile = htolel(64); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.level = htolel(50); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.macroblockspersec = htolel(40500); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.macroblocksperframe = htolel(1620); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.decpicbuf = htolel(8100); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.brandcpb = htolel(10000); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.confServiceNum = htolel(channel->callid); r->msg.OpenMultiMediaChannelMessage.v3.videoParameter.bitRate = htolel(bitRate); sccp_dev_send(device, r); } /*! * \brief Send Open MultiMediaChannel Message (V17) */ static void sccp_protocol_sendOpenMultiMediaChannelV17(const sccp_device_t * device, const sccp_channel_t * channel, uint32_t skinnyFormat, int payloadType, uint8_t lineInstance, int bitRate) { sccp_moo_t *r = sccp_build_packet(OpenMultiMediaChannelMessage, sizeof(r->msg.OpenMultiMediaChannelMessage.v17)); r->msg.OpenMultiMediaChannelMessage.v17.lel_conferenceID = htolel(channel->callid); r->msg.OpenMultiMediaChannelMessage.v17.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.OpenMultiMediaChannelMessage.v17.lel_payloadCapability = htolel(skinnyFormat); r->msg.OpenMultiMediaChannelMessage.v17.lel_lineInstance = htolel(lineInstance); r->msg.OpenMultiMediaChannelMessage.v17.lel_callReference = htolel(channel->callid); r->msg.OpenMultiMediaChannelMessage.v17.lel_payloadType = htolel(payloadType); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.confServiceNum = htolel(channel->callid); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.bitRate = htolel(bitRate); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.pictureFormatCount = htolel(0); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.pictureFormat[0].format = htolel(4); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.pictureFormat[0].mpi = htolel(1); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.profile = htolel(64); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.level = htolel(50); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.macroblockspersec = htolel(40500); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.macroblocksperframe = htolel(1620); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.decpicbuf = htolel(8100); r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.brandcpb = htolel(10000); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy1 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy2 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy3 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy4 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy5 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy6 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy7 = htolel(0); // r->msg.OpenMultiMediaChannelMessage.v17.videoParameter.dummy8 = htolel(0); sccp_dev_send(device, r); } /*! * \brief Send Start MultiMedia Transmission (V3) */ static void sccp_protocol_sendStartMediaTransmissionV3(const sccp_device_t * device, const sccp_channel_t * channel) { sccp_moo_t *r = sccp_build_packet(StartMediaTransmission, sizeof(r->msg.StartMediaTransmission.v3)); int packetSize = 20; /*! \todo calculate packetSize */ r->msg.StartMediaTransmission.v3.lel_conferenceId = htolel(channel->callid); r->msg.StartMediaTransmission.v3.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.StartMediaTransmission.v3.lel_conferenceId1 = htolel(channel->callid); r->msg.StartMediaTransmission.v3.lel_millisecondPacketSize = htolel(packetSize); r->msg.StartMediaTransmission.v3.lel_payloadType = htolel(channel->rtp.audio.readFormat); r->msg.StartMediaTransmission.v3.lel_precedenceValue = htolel(device->audio_tos); r->msg.StartMediaTransmission.v3.lel_ssValue = htolel(channel->line->silencesuppression); // Silence supression r->msg.StartMediaTransmission.v3.lel_maxFramesPerPacket = htolel(0); r->msg.StartMediaTransmission.v3.lel_rtptimeout = htolel(10); r->msg.StartMediaTransmission.v3.lel_remotePortNumber = htolel(ntohs(channel->rtp.audio.phone_remote.sin_port)); memcpy(&r->msg.StartMediaTransmission.v3.bel_remoteIpAddr, &channel->rtp.audio.phone_remote.sin_addr, 4); sccp_dev_send(device, r); } /*! * \brief Send Start MultiMedia Transmission (V17) */ static void sccp_protocol_sendStartMediaTransmissionV17(const sccp_device_t * device, const sccp_channel_t * channel) { sccp_moo_t *r = sccp_build_packet(StartMediaTransmission, sizeof(r->msg.StartMediaTransmission.v17)); int packetSize = 20; /*! \todo calculate packetSize */ r->msg.StartMediaTransmission.v17.lel_conferenceId = htolel(channel->callid); r->msg.StartMediaTransmission.v17.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.StartMediaTransmission.v17.lel_conferenceId1 = htolel(channel->callid); r->msg.StartMediaTransmission.v17.lel_millisecondPacketSize = htolel(packetSize); r->msg.StartMediaTransmission.v17.lel_payloadType = htolel(channel->rtp.audio.readFormat); r->msg.StartMediaTransmission.v17.lel_precedenceValue = htolel(device->audio_tos); r->msg.StartMediaTransmission.v17.lel_ssValue = htolel(channel->line->silencesuppression); // Silence supression r->msg.StartMediaTransmission.v17.lel_maxFramesPerPacket = htolel(0); r->msg.StartMediaTransmission.v17.lel_rtptimeout = htolel(10); r->msg.StartMediaTransmission.v17.lel_remotePortNumber = htolel(ntohs(channel->rtp.audio.phone_remote.sin_port)); // if (channel->rtp.audio.phone_remote.sin_family = AF_INET) r->msg.StartMediaTransmission.v17.lel_ipv46 = htolel(0); memcpy(&r->msg.StartMediaTransmission.v17.bel_remoteIpAddr, &channel->rtp.audio.phone_remote.sin_addr, INET_ADDRSTRLEN); // } else { // r->msg.StartMediaTransmission.v17.lel_ipv46 = htolel(1); // memcpy(&r->msg.StartMediaTransmission.v17.bel_remoteIpAddr, &channel->rtp.audio.phone_remote.sin_addr, INET6_ADDRSTRLEN); // } sccp_dev_send(device, r); } /*! * \brief Send Start MultiMedia Transmission (V3) */ static void sccp_protocol_sendStartMultiMediaTransmissionV3(const sccp_device_t * device, const sccp_channel_t * channel, int payloadType, int bitRate, struct sockaddr_in sin) { sccp_moo_t *r = sccp_build_packet(StartMultiMediaTransmission, sizeof(r->msg.StartMultiMediaTransmission.v3)); r->msg.StartMultiMediaTransmission.v3.lel_conferenceID = htolel(channel->callid); r->msg.StartMultiMediaTransmission.v3.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.StartMultiMediaTransmission.v3.lel_payloadCapability = htolel(channel->rtp.video.readFormat); r->msg.StartMultiMediaTransmission.v3.lel_callReference = htolel(channel->callid); r->msg.StartMultiMediaTransmission.v3.lel_payloadType = htolel(payloadType); r->msg.StartMultiMediaTransmission.v3.lel_DSCPValue = htolel(136); r->msg.StartMultiMediaTransmission.v3.videoParameter.bitRate = htolel(bitRate); // r->msg.StartMultiMediaTransmission.v3.videoParameter.pictureFormatCount = htolel(0); // r->msg.StartMultiMediaTransmission.v3.videoParameter.pictureFormat[0].format = htolel(4); // r->msg.StartMultiMediaTransmission.v3.videoParameter.pictureFormat[0].mpi = htolel(30); r->msg.StartMultiMediaTransmission.v3.videoParameter.profile = htolel(0x40); r->msg.StartMultiMediaTransmission.v3.videoParameter.level = htolel(0x32); /* has to be >= 15 to work with 7985 */ r->msg.StartMultiMediaTransmission.v3.videoParameter.macroblockspersec = htolel(40500); r->msg.StartMultiMediaTransmission.v3.videoParameter.macroblocksperframe = htolel(1620); r->msg.StartMultiMediaTransmission.v3.videoParameter.decpicbuf = htolel(8100); r->msg.StartMultiMediaTransmission.v3.videoParameter.brandcpb = htolel(10000); r->msg.StartMultiMediaTransmission.v3.videoParameter.confServiceNum = htolel(channel->callid); r->msg.StartMultiMediaTransmission.v3.lel_remotePortNumber = htolel(ntohs(sin.sin_port)); memcpy(&r->msg.StartMultiMediaTransmission.v3.bel_remoteIpAddr, &channel->rtp.video.phone_remote.sin_addr, 4); sccp_dev_send(device, r); } /*! * \brief Send Start MultiMedia Transmission (V17) */ static void sccp_protocol_sendStartMultiMediaTransmissionV17(const sccp_device_t * device, const sccp_channel_t * channel, int payloadType, int bitRate, struct sockaddr_in sin) { sccp_moo_t *r = sccp_build_packet(StartMultiMediaTransmission, sizeof(r->msg.StartMultiMediaTransmission.v17)); r->msg.StartMultiMediaTransmission.v17.lel_conferenceID = htolel(channel->callid); r->msg.StartMultiMediaTransmission.v17.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.StartMultiMediaTransmission.v17.lel_payloadCapability = htolel(channel->rtp.video.readFormat); r->msg.StartMultiMediaTransmission.v17.lel_callReference = htolel(channel->callid); r->msg.StartMultiMediaTransmission.v17.lel_payloadType = htolel(payloadType); r->msg.StartMultiMediaTransmission.v17.lel_DSCPValue = htolel(136); r->msg.StartMultiMediaTransmission.v17.videoParameter.confServiceNum = htolel(channel->callid); r->msg.StartMultiMediaTransmission.v17.videoParameter.bitRate = htolel(bitRate); // r->msg.StartMultiMediaTransmission.v17.videoParameter.pictureFormatCount = htolel(1); // r->msg.StartMultiMediaTransmission.v17.videoParameter.pictureFormat[0].format = htolel(4); // r->msg.StartMultiMediaTransmission.v17.videoParameter.pictureFormat[0].mpi = htolel(1); r->msg.StartMultiMediaTransmission.v17.videoParameter.profile = htolel(64); r->msg.StartMultiMediaTransmission.v17.videoParameter.level = htolel(50); r->msg.StartMultiMediaTransmission.v17.videoParameter.macroblockspersec = htolel(40500); r->msg.StartMultiMediaTransmission.v17.videoParameter.macroblocksperframe = htolel(1620); r->msg.StartMultiMediaTransmission.v17.videoParameter.decpicbuf = htolel(8100); r->msg.StartMultiMediaTransmission.v17.videoParameter.brandcpb = htolel(10000); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy1 = htolel(1); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy2 = htolel(2); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy3 = htolel(3); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy4 = htolel(4); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy5 = htolel(5); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy6 = htolel(6); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy7 = htolel(7); r->msg.StartMultiMediaTransmission.v17.videoParameter.dummy8 = htolel(8); // if (channel->rtp.audio.phone_remote.sin_family = AF_INET) r->msg.StartMultiMediaTransmission.v17.lel_ipv46 = htolel(0); r->msg.StartMultiMediaTransmission.v17.lel_remotePortNumber = htolel(ntohs(sin.sin_port)); memcpy(&r->msg.StartMultiMediaTransmission.v17.bel_remoteIpAddr, &channel->rtp.video.phone_remote.sin_addr, INET_ADDRSTRLEN); // } else { // r->msg.StartMultiMediaTransmission.v17.lel_ipv46 = htolel(1); // r->msg.StartMultiMediaTransmission.v17.lel_remotePortNumber = htolel(ntohs(sin.sin_port)); // memcpy(&r->msg.StartMultiMediaTransmission.v17.bel_remoteIpAddr, &channel->rtp.video.phone_remote.sin_addr, INET6_ADDRSTRLEN); // } sccp_dev_send(device, r); } /* fastPictureUpdate */ static void sccp_protocol_sendFastPictureUpdate(const sccp_device_t * device, const sccp_channel_t * channel) { sccp_moo_t *r; REQ(r, MiscellaneousCommandMessage); r->msg.MiscellaneousCommandMessage.lel_conferenceId = htolel(channel->callid); r->msg.MiscellaneousCommandMessage.lel_passThruPartyId = htolel(channel->passthrupartyid); r->msg.MiscellaneousCommandMessage.lel_callReference = htolel(channel->callid); r->msg.MiscellaneousCommandMessage.lel_miscCommandType = htolel(SKINNY_MISCCOMMANDTYPE_VIDEOFASTUPDATEPICTURE); sccp_dev_send(device, r); } /* done - fastPictureUpdate */ /* sendUserToDeviceData Message */ /*! * \brief Send User To Device Message (V1) */ static void sccp_protocol_sendUserToDeviceDataVersion1Message(const sccp_device_t * device, uint32_t appID, uint32_t lineInstance, uint32_t callReference, uint32_t transactionID, const void *xmlData, uint8_t priority) { sccp_moo_t *r = NULL; int msg_len = strlen(xmlData); int hdr_len = sizeof(r->msg.UserToDeviceDataVersion1Message); int padding = ((msg_len + hdr_len) % 4); padding = (padding > 0) ? 4 - padding : 4; if (device->protocolversion > 17 || msg_len < StationMaxXMLMessage) { r = sccp_build_packet(UserToDeviceDataVersion1Message, hdr_len + msg_len + padding); r->msg.UserToDeviceDataVersion1Message.lel_appID = htolel(appID); r->msg.UserToDeviceDataVersion1Message.lel_lineInstance = htolel(lineInstance); r->msg.UserToDeviceDataVersion1Message.lel_callReference = htolel(callReference); r->msg.UserToDeviceDataVersion1Message.lel_transactionID = htolel(transactionID); r->msg.UserToDeviceDataVersion1Message.lel_sequenceFlag = htolel(0x0002); r->msg.UserToDeviceDataVersion1Message.lel_displayPriority = htolel(priority); r->msg.UserToDeviceDataVersion1Message.lel_dataLength = htolel(msg_len); if (msg_len) { memcpy(&r->msg.UserToDeviceDataVersion1Message.data, xmlData, msg_len); } sccp_dev_send(device, r); sccp_log(DEBUGCAT_HIGH)(VERBOSE_PREFIX_1 "%s: (sccp_protocol_sendUserToDeviceDataVersion1Message) Message sent to device (hdr_len: %d, msglen: %d, padding: %d, r-size: %d).\n", DEV_ID_LOG(device), hdr_len, msg_len, padding, hdr_len + msg_len + padding); } else { sccp_log(DEBUGCAT_CORE)(VERBOSE_PREFIX_1 "%s: (sccp_protocol_sendUserToDeviceDataVersion1Message) Message to large to send to device (hdr_len: %d, msglen: %d, padding: %d, r-size: %d). Skipping !\n", DEV_ID_LOG(device), hdr_len, msg_len, padding, hdr_len + msg_len + padding); } } /* done - sendUserToDeviceData */ /*! \todo need a protocol implementation for ConnectionStatisticsReq using Version 19 and higher */ /*! \todo need a protocol implementation for ForwardStatMessage using Version 19 and higher */ /* =================================================================================================================== Parse Received Messages */ /*! * \brief OpenReceiveChannelAck */ static void sccp_protocol_parseOpenReceiveChannelAckV3(const sccp_moo_t * r, uint32_t * status, struct sockaddr_storage *ss, uint32_t * passthrupartyid, uint32_t * callReference) { *status = letohl(r->msg.OpenReceiveChannelAck.v3.lel_status); *callReference = letohl(r->msg.OpenReceiveChannelAck.v3.lel_callReference); *passthrupartyid = letohl(r->msg.OpenReceiveChannelAck.v3.lel_passThruPartyId); ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.OpenReceiveChannelAck.v3.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.OpenReceiveChannelAck.v3.lel_portNumber)); } static void sccp_protocol_parseOpenReceiveChannelAckV17(const sccp_moo_t * r, uint32_t * status, struct sockaddr_storage *ss, uint32_t * passthrupartyid, uint32_t * callReference) { *status = letohl(r->msg.OpenReceiveChannelAck.v17.lel_status); *callReference = letohl(r->msg.OpenReceiveChannelAck.v17.lel_callReference); *passthrupartyid = letohl(r->msg.OpenReceiveChannelAck.v17.lel_passThruPartyId); if (letohl(r->msg.OpenReceiveChannelAck.v17.lel_ipv46) == 0) { // read ipv4 address ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.OpenReceiveChannelAck.v17.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.OpenReceiveChannelAck.v17.lel_portNumber)); } else { // read ipv6 address /* what to do with IPv4-mapped IPv6 addresses */ ss->ss_family = AF_INET6; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss; memcpy(&sin6->sin6_addr, &r->msg.OpenReceiveChannelAck.v17.bel_ipAddr, INET6_ADDRSTRLEN); sin6->sin6_port = htons(htolel(r->msg.OpenReceiveChannelAck.v17.lel_portNumber)); } } static void sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3(const sccp_moo_t * r, uint32_t * status, struct sockaddr_storage *ss, uint32_t * passthrupartyid, uint32_t * callReference) { *status = letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v3.lel_status); *passthrupartyid = letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v3.lel_passThruPartyId); *callReference = letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v3.lel_callReference); ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.OpenMultiMediaReceiveChannelAckMessage.v3.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.OpenMultiMediaReceiveChannelAckMessage.v3.lel_portNumber)); } static void sccp_protocol_parseOpenMultiMediaReceiveChannelAckV17(const sccp_moo_t * r, uint32_t * status, struct sockaddr_storage *ss, uint32_t * passthrupartyid, uint32_t * callReference) { *status = letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.lel_status); *passthrupartyid = letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.lel_passThruPartyId); *callReference = letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.lel_callReference); if (letohl(r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.lel_ipv46) == 0) { // read ipv4 address ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.lel_portNumber)); } else { // read ipv6 address /* what to do with IPv4-mapped IPv6 addresses */ ss->ss_family = AF_INET6; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss; memcpy(&sin6->sin6_addr, &r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.bel_ipAddr, INET6_ADDRSTRLEN); sin6->sin6_port = htons(htolel(r->msg.OpenMultiMediaReceiveChannelAckMessage.v17.lel_portNumber)); } } /*! * \brief StartMediaTransmissionAck */ static void sccp_protocol_parseStartMediaTransmissionAckV3(const sccp_moo_t * r, uint32_t * partyID, uint32_t * callID, uint32_t * callID1, uint32_t * status, struct sockaddr_storage *ss) { *partyID = letohl(r->msg.StartMediaTransmissionAck.v3.lel_passThruPartyId); *callID = letohl(r->msg.StartMediaTransmissionAck.v3.lel_callReference); *callID1 = letohl(r->msg.StartMediaTransmissionAck.v3.lel_callReference1); *status = letohl(r->msg.StartMediaTransmissionAck.v3.lel_smtStatus); ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.StartMediaTransmissionAck.v3.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.StartMediaTransmissionAck.v3.lel_portNumber)); } static void sccp_protocol_parseStartMediaTransmissionAckV17(const sccp_moo_t * r, uint32_t * partyID, uint32_t * callID, uint32_t * callID1, uint32_t * status, struct sockaddr_storage *ss) { *partyID = letohl(r->msg.StartMediaTransmissionAck.v17.lel_passThruPartyId); *callID = letohl(r->msg.StartMediaTransmissionAck.v17.lel_callReference); *callID1 = letohl(r->msg.StartMediaTransmissionAck.v17.lel_callReference1); *status = letohl(r->msg.StartMediaTransmissionAck.v17.lel_smtStatus); if (letohl(r->msg.StartMediaTransmissionAck.v17.lel_ipv46) == 0) { // read ipv4 address ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.StartMediaTransmissionAck.v17.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.StartMediaTransmissionAck.v17.lel_portNumber)); } else { // read ipv6 address /* what to do with IPv4-mapped IPv6 addresses */ ss->ss_family = AF_INET6; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss; memcpy(&sin6->sin6_addr, &r->msg.StartMediaTransmissionAck.v17.bel_ipAddr, INET6_ADDRSTRLEN); sin6->sin6_port = htons(htolel(r->msg.StartMediaTransmissionAck.v17.lel_portNumber)); } } /*! * \brief StartMultiMediaTransmissionAck */ static void sccp_protocol_parseStartMultiMediaTransmissionAckV3(const sccp_moo_t * r, uint32_t * partyID, uint32_t * callID, uint32_t * callID1, uint32_t * status, struct sockaddr_storage *ss) { *partyID = letohl(r->msg.StartMultiMediaTransmissionAck.v3.lel_passThruPartyId); *callID = letohl(r->msg.StartMultiMediaTransmissionAck.v3.lel_callReference); *callID1 = letohl(r->msg.StartMultiMediaTransmissionAck.v3.lel_callReference1); *status = letohl(r->msg.StartMultiMediaTransmissionAck.v3.lel_smtStatus); ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.StartMultiMediaTransmissionAck.v3.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.StartMultiMediaTransmissionAck.v3.lel_portNumber)); } static void sccp_protocol_parseStartMultiMediaTransmissionAckV17(const sccp_moo_t * r, uint32_t * partyID, uint32_t * callID, uint32_t * callID1, uint32_t * status, struct sockaddr_storage *ss) { *partyID = letohl(r->msg.StartMultiMediaTransmissionAck.v17.lel_passThruPartyId); *callID = letohl(r->msg.StartMultiMediaTransmissionAck.v17.lel_callReference); *callID1 = letohl(r->msg.StartMultiMediaTransmissionAck.v17.lel_callReference1); *status = letohl(r->msg.StartMultiMediaTransmissionAck.v17.lel_smtStatus); if (letohl(r->msg.StartMultiMediaTransmissionAck.v17.lel_ipv46) == 0) { // read ipv4 address ss->ss_family = AF_INET; struct sockaddr_in *sin = (struct sockaddr_in *)ss; memcpy(&sin->sin_addr, &r->msg.StartMultiMediaTransmissionAck.v17.bel_ipAddr, INET_ADDRSTRLEN); sin->sin_port = htons(htolel(r->msg.StartMultiMediaTransmissionAck.v17.lel_portNumber)); } else { // read ipv6 address /* what to do with IPv4-mapped IPv6 addresses */ ss->ss_family = AF_INET6; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss; memcpy(&sin6->sin6_addr, &r->msg.StartMultiMediaTransmissionAck.v17.bel_ipAddr, INET6_ADDRSTRLEN); sin6->sin6_port = htons(htolel(r->msg.StartMultiMediaTransmissionAck.v17.lel_portNumber)); } } /* =================================================================================================================== Map Messages to Protocol Version */ /*! * \brief SCCP Protocol Version to Message Mapping */ static const sccp_deviceProtocol_t *sccpProtocolDefinition[] = { NULL, NULL, NULL, &(sccp_deviceProtocol_t) {"SCCP", 3, sccp_device_sendCallinfoV3, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV3, sccp_protocol_sendStaticDisplayprompt, sccp_protocol_sendStaticDisplayNotify, sccp_protocol_sendStaticDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, /* default impl */ NULL, &(sccp_deviceProtocol_t) {"SCCP", 5, sccp_device_sendCallinfoV3, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV4, sccp_protocol_sendStaticDisplayprompt, sccp_protocol_sendStaticDisplayNotify, sccp_protocol_sendStaticDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, NULL, NULL, NULL, &(sccp_deviceProtocol_t) {"SCCP", 9, sccp_device_sendCallinfoV7, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV4, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, &(sccp_deviceProtocol_t) {"SCCP", 10, sccp_device_sendCallinfoV7, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV4, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, &(sccp_deviceProtocol_t) {"SCCP", 11, sccp_device_sendCallinfoV7, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, NULL, NULL, NULL, &(sccp_deviceProtocol_t) {"SCCP", 15, sccp_device_sendCallinfoV7, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV17, sccp_protocol_sendStartMultiMediaTransmissionV17, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, &(sccp_deviceProtocol_t) {"SCCP", 16, sccp_protocol_sendCallinfoV16, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV17, sccp_protocol_sendStartMultiMediaTransmissionV17, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, &(sccp_deviceProtocol_t) {"SCCP", 17, sccp_protocol_sendCallinfoV16, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV17, sccp_protocol_sendOpenMultiMediaChannelV17, sccp_protocol_sendStartMultiMediaTransmissionV17, sccp_protocol_sendStartMediaTransmissionV17, sccp_protocol_parseOpenReceiveChannelAckV17, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV17, sccp_protocol_parseStartMediaTransmissionAckV17, sccp_protocol_parseStartMultiMediaTransmissionAckV17}, NULL, &(sccp_deviceProtocol_t) {"SCCP", 19, sccp_protocol_sendCallinfoV16, sccp_protocol_sendDialedNumberV19, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatusV19, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV17, sccp_protocol_sendOpenMultiMediaChannelV17, sccp_protocol_sendStartMultiMediaTransmissionV17, sccp_protocol_sendStartMediaTransmissionV17, sccp_protocol_parseOpenReceiveChannelAckV17, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV17, sccp_protocol_parseStartMediaTransmissionAckV17, sccp_protocol_parseStartMultiMediaTransmissionAckV17}, &(sccp_deviceProtocol_t) {"SCCP", 20, sccp_protocol_sendCallinfoV16, sccp_protocol_sendDialedNumberV19, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatusV19, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV17, sccp_protocol_sendOpenMultiMediaChannelV17, sccp_protocol_sendStartMultiMediaTransmissionV17, sccp_protocol_sendStartMediaTransmissionV17, sccp_protocol_parseOpenReceiveChannelAckV17, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV17, sccp_protocol_parseStartMediaTransmissionAckV17, sccp_protocol_parseStartMultiMediaTransmissionAckV17}, NULL, &(sccp_deviceProtocol_t) {"SCCP", 22, sccp_protocol_sendCallinfoV16, sccp_protocol_sendDialedNumberV19, sccp_protocol_sendRegisterAckV11, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatusV19, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV17, sccp_protocol_sendOpenMultiMediaChannelV17, sccp_protocol_sendStartMultiMediaTransmissionV17, sccp_protocol_sendStartMediaTransmissionV17, sccp_protocol_parseOpenReceiveChannelAckV17, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV17, sccp_protocol_parseStartMediaTransmissionAckV17, sccp_protocol_parseStartMultiMediaTransmissionAckV17}, }; /*! * \brief SPCP Protocol Version to Message Mapping */ static const sccp_deviceProtocol_t *spcpProtocolDefinition[] = { &(sccp_deviceProtocol_t) {"SPCP", 0, sccp_device_sendCallinfoV3, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV4, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &(sccp_deviceProtocol_t) {"SPCP", 8, sccp_device_sendCallinfoV3, sccp_protocol_sendDialedNumberV3, sccp_protocol_sendRegisterAckV4, sccp_protocol_sendDynamicDisplayprompt, sccp_protocol_sendDynamicDisplayNotify, sccp_protocol_sendDynamicDisplayPriNotify, sccp_protocol_sendCallForwardStatus, sccp_protocol_sendUserToDeviceDataVersion1Message, sccp_protocol_sendFastPictureUpdate, sccp_protocol_sendOpenReceiveChannelV3, sccp_protocol_sendOpenMultiMediaChannelV3, sccp_protocol_sendStartMultiMediaTransmissionV3, sccp_protocol_sendStartMediaTransmissionV3, sccp_protocol_parseOpenReceiveChannelAckV3, sccp_protocol_parseOpenMultiMediaReceiveChannelAckV3, sccp_protocol_parseStartMediaTransmissionAckV3, sccp_protocol_parseStartMultiMediaTransmissionAckV3}, }; /*! * \brief Get Maximum Supported Version Number by Protocol Type */ uint8_t sccp_protocol_getMaxSupportedVersionNumber(int type) { switch (type) { case SCCP_PROTOCOL: return ARRAY_LEN(sccpProtocolDefinition) - 1; case SPCP_PROTOCOL: return ARRAY_LEN(spcpProtocolDefinition) - 1; default: return 0; } } /*! * \brief Get Maximum Possible Protocol Supported by Device */ const sccp_deviceProtocol_t *sccp_protocol_getDeviceProtocol(const sccp_device_t * device, int type) { uint8_t i; uint8_t version = device->protocolversion; const sccp_deviceProtocol_t **protocolDef; size_t protocolArraySize; uint8_t returnProtocol; sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "SCCP: searching for our capability for device protocol version %d\n", version); if (type == SCCP_PROTOCOL) { protocolArraySize = ARRAY_LEN(sccpProtocolDefinition); protocolDef = sccpProtocolDefinition; returnProtocol = 3; // setting minimally returned protocol sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "SCCP: searching for our capability for device protocol SCCP\n"); } else { protocolArraySize = ARRAY_LEN(spcpProtocolDefinition); protocolDef = spcpProtocolDefinition; returnProtocol = 0; sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "SCCP: searching for our capability for device protocol SPCP\n"); } for (i = (protocolArraySize - 1); i > 0; i--) { if (protocolDef[i] != NULL && version >= protocolDef[i]->version) { sccp_log(DEBUGCAT_DEVICE) (VERBOSE_PREFIX_3 "%s: found protocol version '%d' at %d\n", protocolDef[i]->name, protocolDef[i]->version, i); returnProtocol = i; break; } } return protocolDef[returnProtocol]; }
722,256
./chan-sccp-b/src/sccp_utils.c
/*! * \file sccp_utils.c * \brief SCCP Utils Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /*! * \brief Print out a messagebuffer * \param messagebuffer Pointer to Message Buffer as char * \param len Lenght as Int */ void sccp_dump_packet(unsigned char *messagebuffer, int len) { static const int numcolumns = 16; // number output columns if (len <= 0 || !messagebuffer) { // safe quard sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: messagebuffer is not valid. exiting sccp_dump_packet\n"); return; } int col = 0; int cur = 0; int hexcolumnlength = 0; const char *hex = "0123456789ABCDEF"; char hexout[(numcolumns * 3) + (numcolumns / 8) + 1]; // 3 char per hex value + grouping + endofline char *hexptr; char chrout[numcolumns + 1]; char *chrptr; do { memset(hexout, 0, sizeof(hexout)); memset(chrout, 0, sizeof(chrout)); hexptr = hexout; chrptr = chrout; for (col = 0; col < numcolumns && (cur + col) < len; col++) { *hexptr++ = hex[(*messagebuffer >> 4) & 0xF]; // lookup first part of hex value and add to hexptr *hexptr++ = hex[(*messagebuffer) & 0xF]; // lookup second part of a hex value and add to hexptr *hexptr++ = ' '; // add space to hexptr if ((col + 1) % 8 == 0) { *hexptr++ = ' '; // group by blocks of eight } *chrptr++ = isprint(*messagebuffer) ? *messagebuffer : '.'; // add character or . to chrptr messagebuffer += 1; // instead *messagebuffer++ to circumvent unused warning } hexcolumnlength = (numcolumns * 3) + (numcolumns / 8) - 1; // numcolums + block spaces - 1 sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "%08X - %-*.*s - %s\n", cur, hexcolumnlength, hexcolumnlength, hexout, chrout); cur += col; } while (cur < (len - 1)); } /*! * \brief Add Host to the Permithost Linked List * \param d SCCP Device * \param config_string as Character * * \warning * - device->permithosts is not always locked */ void sccp_permithost_addnew(sccp_device_t * d, const char *config_string) { sccp_hostname_t *permithost; if ((permithost = sccp_malloc(sizeof(sccp_hostname_t)))) { sccp_copy_string(permithost->name, config_string, sizeof(permithost->name)); SCCP_LIST_INSERT_HEAD(&d->permithosts, permithost, list); } else { pbx_log(LOG_WARNING, "Error adding the permithost = %s to the list\n", config_string); } } /*! * \brief Return Number of Buttons on AddOn Device * \param d SCCP Device * \return taps (Number of Buttons on AddOn Device) * * \lock * - device->addons */ int sccp_addons_taps(sccp_device_t * d) { sccp_addon_t *cur = NULL; int taps = 0; if (!strcasecmp(d->config_type, "7914")) return 28; // on compatibility mode it returns 28 taps for a double 7914 addon SCCP_LIST_LOCK(&d->addons); SCCP_LIST_TRAVERSE(&d->addons, cur, list) { if (cur->type == SKINNY_DEVICETYPE_CISCO_ADDON_7914) taps += 14; if (cur->type == SKINNY_DEVICETYPE_CISCO_ADDON_7915_12BUTTON || cur->type == SKINNY_DEVICETYPE_CISCO_ADDON_7916_12BUTTON) taps += 12; if (cur->type == SKINNY_DEVICETYPE_CISCO_ADDON_7915_24BUTTON || cur->type == SKINNY_DEVICETYPE_CISCO_ADDON_7916_24BUTTON) taps += 24; sccp_log((DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Found (%d) taps on device addon (%d)\n", (d->id ? d->id : "SCCP"), taps, cur->type); } SCCP_LIST_UNLOCK(&d->addons); return taps; } /*! * \brief Clear all Addons from AddOn Linked List * \param d SCCP Device */ void sccp_addons_clear(sccp_device_t * d) { sccp_addon_t *addon; if (!d) return; // while ((AST_LIST_REMOVE_HEAD(&d->addons, list))) ; while ((addon = SCCP_LIST_REMOVE_HEAD(&d->addons, list))) { sccp_free(addon); } d->addons.first = NULL; d->addons.last = NULL; } /*! * \brief Return AddOn Linked List * \param d SCCP Device * \return addons_list */ char *sccp_addons_list(sccp_device_t * d) { char *addons_list = NULL; return addons_list; } /*! * \brief Put SCCP into Safe Sleep for [num] milli_seconds * \param ms MilliSeconds */ void sccp_safe_sleep(int ms) { struct timeval start = pbx_tvnow(); usleep(1); while (ast_tvdiff_ms(pbx_tvnow(), start) < ms) { usleep(1); } } /*! * \brief Notify asterisk for new state * \param channel SCCP Channel * \param state New State - type of AST_STATE_* */ void sccp_pbx_setcallstate(sccp_channel_t * channel, int state) { if (channel) { if (channel->owner) { pbx_setstate(channel->owner, state); // pbx_cond_wait(&channel->astStateCond, &channel->lock); sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Set asterisk state %s (%d) for call %d\n", channel->currentDeviceId, pbx_state2str(state), state, channel->callid); } } } /*! * \brief Clean Asterisk Database Entries in the "SCCP" Family * * \lock * - devices */ void sccp_dev_dbclean() { struct ast_db_entry *entry = NULL; sccp_device_t *d; char key[256]; //! \todo write an pbx implementation for that //entry = PBX(feature_getFromDatabase)tree("SCCP", NULL); while (entry) { sscanf(entry->key, "/SCCP/%s", key); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_REALTIME)) (VERBOSE_PREFIX_3 "SCCP: Looking for '%s' in the devices list\n", key); if ((strlen(key) == 15) && (!strncmp(key, "SEP", 3) || !strncmp(key, "ATA", 3) || !strncmp(key, "VGC", 3) || !strncmp(key, "AN", 2) || !strncmp(key, "SKIGW", 5))) { SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (d->id && !strcasecmp(d->id, key)) { break; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); if (!d) { PBX(feature_removeFromDatabase) ("SCCP", key); sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_REALTIME)) (VERBOSE_PREFIX_3 "SCCP: device '%s' removed from asterisk database\n", entry->key); } } entry = entry->next; } if (entry) pbx_db_freetree(entry); } gcc_inline const char *message2str(sccp_message_t type) { /* sccp_protocol.h */ return sccp_messagetypes[type].text; } gcc_inline size_t message2size(sccp_message_t type) { /* sccp_protocol.h */ return sccp_messagetypes[type].size; } gcc_inline const char *pbxdevicestate2str(uint32_t value) { /* pbx_impl/ast/ast.h */ _ARR2STR(pbx_devicestates, devicestate, value, text); } gcc_inline const char *extensionstatus2str(uint32_t value) { /* pbx_impl/ast/ast.h */ _ARR2STR(sccp_extension_states, extension_state, value, text); } gcc_inline const char *label2str(uint16_t value) { /* sccp_labels.h */ _ARR2STR(skinny_labels, label, value, text); } gcc_inline const char *codec2str(skinny_codec_t value) { /* sccp_protocol.h */ _ARR2STR(skinny_codecs, codec, value, text); } gcc_inline int codec2payload(skinny_codec_t value) { /* sccp_protocol.h */ _ARR2INT(skinny_codecs, codec, value, rtp_payload_type); } gcc_inline const char *codec2key(skinny_codec_t value) { /* sccp_protocol.h */ _ARR2STR(skinny_codecs, codec, value, key); } gcc_inline const char *codec2name(skinny_codec_t value) { /* sccp_protocol.h */ _ARR2STR(skinny_codecs, codec, value, name); } gcc_inline const char *featureType2str(sccp_feature_type_t value) { /* chan_sccp.h */ _ARR2STR(sccp_feature_types, featureType, value, text); } gcc_inline uint32_t debugcat2int(const char *str) { /* chan_sccp.h */ _STRARR2INT(sccp_debug_categories, key, str, category); } /*! * \brief Retrieve the string of format numbers and names from an array of formats * Buffer needs to be declared and freed afterwards * \param buf Buffer as char array * \param size Size of Buffer * \param codecs Array of Skinny Codecs * \param length Max Length */ char *sccp_multiple_codecs2str(char *buf, size_t size, skinny_codec_t * codecs, int length) { int x; unsigned len; char *start, *end = buf; if (!size) return buf; snprintf(end, size, "("); len = strlen(end); end += len; size -= len; start = end; for (x = 0; x < length; x++) { if (codecs[x] == 0) continue; snprintf(end, size, "%s, ", codec2name(codecs[x])); len = strlen(end); end += len; size -= len; } if (start == end) pbx_copy_string(start, "nothing)", size); else if (size > 2) { *(end - 2) = ')'; *(end - 1) = '\0'; } return buf; } void skinny_codec_pref_remove(skinny_codec_t * skinny_codec_prefs, skinny_codec_t skinny_codec); /*! * \brief Remove Codec from Skinny Codec Preferences */ void skinny_codec_pref_remove(skinny_codec_t * skinny_codec_prefs, skinny_codec_t skinny_codec) { skinny_codec_t *old_skinny_codec_prefs = { 0 }; int x, y = 0; if (ARRAY_LEN(skinny_codec_prefs)) return; memcpy(old_skinny_codec_prefs, skinny_codec_prefs, sizeof(skinny_codec_t)); memset(skinny_codec_prefs, 0, SKINNY_MAX_CAPABILITIES); for (x = 0; x < SKINNY_MAX_CAPABILITIES; x++) { // if not found element copy to new array if (SKINNY_CODEC_NONE == old_skinny_codec_prefs[x]) break; if (old_skinny_codec_prefs[x] != skinny_codec) { // sccp_log(DEBUGCAT_CODEC)(VERBOSE_PREFIX_1 "re-adding codec '%d' at pos %d\n", old_skinny_codec_prefs[x], y); skinny_codec_prefs[y++] = old_skinny_codec_prefs[x]; } else { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_1 "found codec '%d' at pos %d, skipping\n", skinny_codec, x); } } } /*! * \brief Append Codec to Skinny Codec Preferences */ static int skinny_codec_pref_append(skinny_codec_t * skinny_codec_pref, skinny_codec_t skinny_codec) { int x = 0; skinny_codec_pref_remove(skinny_codec_pref, skinny_codec); for (x = 0; x < SKINNY_MAX_CAPABILITIES; x++) { if (SKINNY_CODEC_NONE == skinny_codec_pref[x]) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_1 "adding codec '%d' as pos %d\n", skinny_codec, x); skinny_codec_pref[x] = skinny_codec; return x; } } return -1; } /*! * \brief Parse Skinny Codec Allow / Disallow Config Lines */ int sccp_parse_allow_disallow(skinny_codec_t * skinny_codec_prefs, skinny_codec_t * skinny_codec_mask, const char *list, int allowing) { int all; unsigned int x; // unsigned int y; int errors = 0; char *parse = NULL, *this = NULL; boolean_t found = FALSE; // boolean_t mapped = FALSE; skinny_codec_t codec; parse = sccp_strdupa(list); while ((this = strsep(&parse, ","))) { all = strcasecmp(this, "all") ? 0 : 1; if (all && !allowing) { // disallowing all memset(skinny_codec_prefs, 0, SKINNY_MAX_CAPABILITIES); break; } for (x = 0; x < ARRAY_LEN(skinny_codecs); x++) { if (all || !strcasecmp(skinny_codecs[x].key, this)) { codec = skinny_codecs[x].codec; found = TRUE; if (skinny_codec_mask) { if (allowing) *skinny_codec_mask |= codec; else *skinny_codec_mask &= ~codec; } if (skinny_codec_prefs) { if (strcasecmp(this, "all")) { if (allowing) { // sccp_log(DEBUGCAT_CODEC)(VERBOSE_PREFIX_1 "adding codec '%s'\n", this); skinny_codec_pref_append(skinny_codec_prefs, codec); } else { // sccp_log(DEBUGCAT_CODEC)(VERBOSE_PREFIX_1 "removing codec '%s'\n", this); skinny_codec_pref_remove(skinny_codec_prefs, codec); } } } } } if (!found) { pbx_log(LOG_WARNING, "Cannot %s unknown codec '%s'\n", allowing ? "allow" : "disallow", this); errors++; continue; } } return errors; } /*! * \brief Check if Skinny Codec is compatible with Skinny Capabilities Array */ boolean_t sccp_utils_isCodecCompatible(skinny_codec_t codec, const skinny_codec_t capabilities[], uint8_t length) { uint8_t i; for (i = 0; i < length; i++) { if (capabilities[i] == codec) { return TRUE; } } return FALSE; } #ifndef CS_AST_HAS_STRINGS /*! * \brief Asterisk Skip Blanks * \param str as Character * \return String without Blanks */ char *pbx_skip_blanks(char *str) { while (*str && *str < 33) str++; return str; } /*! * \brief Asterisk Trim Blanks * Remove Blanks from the begining and end of a string * \param str as Character * \return String without Beginning or Ending Blanks */ char *pbx_trim_blanks(char *str) { char *work = str; if (work) { work += strlen(work) - 1; while ((work >= str) && *work < 33) *(work--) = '\0'; } return str; } /*! * \brief Asterisk Non Blanks * \param str as Character * \return Only the Non Blank Characters */ char *pbx_skip_nonblanks(char *str) { while (*str && *str > 32) str++; return str; } /*! * \brief Asterisk Strip * \param s as Character * \return String without all Blanks */ char *pbx_strip(char *s) { s = pbx_skip_blanks(s); if (s) pbx_trim_blanks(s); return s; } #endif #ifndef CS_AST_HAS_APP_SEPARATE_ARGS /*! * \brief Seperate App Args * \param buf Buffer as Char * \param delim Delimiter as Char * \param array Array as Char Array * \param arraylen Array Length as Int * \return argc Unsigned Int */ unsigned int sccp_app_separate_args(char *buf, char delim, char **array, int arraylen) { int argc; char *scan; int paren = 0; if (!buf || !array || !arraylen) return 0; memset(array, 0, arraylen * sizeof(*array)); scan = buf; for (argc = 0; *scan && (argc < arraylen - 1); argc++) { array[argc] = scan; for (; *scan; scan++) { if (*scan == '(') paren++; else if (*scan == ')') { if (paren) paren--; } else if ((*scan == delim) && !paren) { *scan++ = '\0'; break; } } } if (*scan) array[argc++] = scan; return argc; } #endif /*! * \brief get the SoftKeyIndex for a given SoftKeyLabel on specified keymode * \param d SCCP Device * \param keymode KeyMode as Unsigned Int * \param softkey SoftKey as Unsigned Int * \return Result as int * * \todo implement function for finding index of given SoftKey */ int sccp_softkeyindex_find_label(sccp_device_t * d, unsigned int keymode, unsigned int softkey) { return -1; } /*! * \brief This is used on device reconnect attempt * \param sin Socket Address In * \return SCCP Device * * \lock * - devices */ //sccp_device_t *sccp_device_find_byipaddress(unsigned long s_addr) sccp_device_t *sccp_device_find_byipaddress(struct sockaddr_in sin) { sccp_device_t *d = NULL; SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (d->session && d->session->sin.sin_addr.s_addr == sin.sin_addr.s_addr && d->session->sin.sin_port == d->session->sin.sin_port) { d = sccp_device_retain(d); break; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); return d; } /*! * \brief convert Feature String 2 Feature ID * \param str Feature Str as char * \return Feature Type */ sccp_feature_type_t sccp_featureStr2featureID(const char *const str) { if (!str) return SCCP_FEATURE_UNKNOWN; uint32_t i; for (i = 0; i < ARRAY_LEN(sccp_feature_types); i++) { if (!strcasecmp(sccp_feature_types[i].text, str)) { return sccp_feature_types[i].featureType; } } return SCCP_FEATURE_UNKNOWN; } /*! * \brief Handle Feature Change Event for persistent feature storage * \param event SCCP Event * * \callgraph * \callergraph * * \warning * - device->buttonconfig is not always locked * - line->devices is not always locked * * \lock * - device */ void sccp_util_featureStorageBackend(const sccp_event_t * event) { char family[25]; char cfwdLineStore[60]; sccp_linedevices_t *linedevice = NULL; sccp_device_t *device = event->event.featureChanged.device; if (!event || !device) { return; } sccp_log((DEBUGCAT_EVENT | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: StorageBackend got Feature Change Event: %s(%d)\n", DEV_ID_LOG(device), featureType2str(event->event.featureChanged.featureType), event->event.featureChanged.featureType); sprintf(family, "SCCP/%s", device->id); switch (event->event.featureChanged.featureType) { case SCCP_FEATURE_CFWDNONE: case SCCP_FEATURE_CFWDBUSY: case SCCP_FEATURE_CFWDALL: if ((linedevice = event->event.featureChanged.linedevice)) { sccp_line_t *line = linedevice->line; uint8_t instance = linedevice->lineInstance; sccp_dev_forward_status(line, instance, device); sprintf(cfwdLineStore, "%s/%s", family, line->name); switch (event->event.featureChanged.featureType) { case SCCP_FEATURE_CFWDALL: if (linedevice->cfwdAll.enabled) { PBX(feature_addToDatabase) (cfwdLineStore, "cfwdAll", linedevice->cfwdAll.number); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: db put %s\n", DEV_ID_LOG(device), cfwdLineStore); } else { PBX(feature_removeFromDatabase) (cfwdLineStore, "cfwdAll"); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: db clear %s\n", DEV_ID_LOG(device), cfwdLineStore); } break; case SCCP_FEATURE_CFWDBUSY: if (linedevice->cfwdBusy.enabled) { PBX(feature_addToDatabase) (cfwdLineStore, "cfwdBusy", linedevice->cfwdBusy.number); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: db put %s\n", DEV_ID_LOG(device), cfwdLineStore); } else { PBX(feature_removeFromDatabase) (cfwdLineStore, "cfwdBusy"); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: db clear %s\n", DEV_ID_LOG(device), cfwdLineStore); } break; case SCCP_FEATURE_CFWDNONE: PBX(feature_removeFromDatabase) (cfwdLineStore, "cfwdAll"); PBX(feature_removeFromDatabase) (cfwdLineStore, "cfwdBusy"); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: cfwd cleared from db\n", DEV_ID_LOG(device)); default: break; } } break; case SCCP_FEATURE_DND: // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: change dnd to %s\n", DEV_ID_LOG(device), device->dndFeature.status ? "on" : "off"); if (device->dndFeature.previousStatus != device->dndFeature.status) { if (!device->dndFeature.status) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: change dnd to off\n", DEV_ID_LOG(device)); PBX(feature_removeFromDatabase) (family, "dnd"); } else { if (device->dndFeature.status == SCCP_DNDMODE_SILENT) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: change dnd to silent\n", DEV_ID_LOG(device)); PBX(feature_addToDatabase) (family, "dnd", "silent"); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: change dnd to reject\n", DEV_ID_LOG(device)); PBX(feature_addToDatabase) (family, "dnd", "reject"); } } device->dndFeature.previousStatus = device->dndFeature.status; } break; case SCCP_FEATURE_PRIVACY: if (device->privacyFeature.previousStatus != device->privacyFeature.status) { if (!device->privacyFeature.status) { PBX(feature_removeFromDatabase) (family, "privacy"); } else { char data[256]; sprintf(data, "%d", device->privacyFeature.status); PBX(feature_addToDatabase) (family, "privacy", data); } device->privacyFeature.status = device->privacyFeature.status; } break; case SCCP_FEATURE_MONITOR: if (device->monitorFeature.previousStatus != device->monitorFeature.status) { if (!device->monitorFeature.status) { PBX(feature_removeFromDatabase) (family, "monitor"); } else { PBX(feature_addToDatabase) (family, "monitor", "on"); } device->monitorFeature.previousStatus = device->monitorFeature.status; } break; default: return; } } /*! * \brief Parse Composed ID * \param labelString LabelString as string * \param maxLength Maximum Length as unsigned int * * \callgraph * \callergraph */ struct composedId sccp_parseComposedId(const char *labelString, unsigned int maxLength) { const char *stringIterator = 0; uint32_t i = 0; boolean_t endDetected = FALSE; int state = 0; struct composedId id; assert(0 != labelString); memset(&id, 0, sizeof(id)); for (stringIterator = labelString; stringIterator < labelString + maxLength && !endDetected; stringIterator++) { switch (state) { case 0: // parsing of main id assert(i < sizeof(id.mainId)); switch (*stringIterator) { case '\0': endDetected = TRUE; id.mainId[i] = '\0'; break; case '@': id.mainId[i] = '\0'; i = 0; state = 1; break; case '!': id.mainId[i] = '\0'; i = 0; state = 3; break; default: id.mainId[i] = *stringIterator; i++; break; } break; case 1: // parsing of sub id number assert(i < sizeof(id.subscriptionId.number)); switch (*stringIterator) { case '\0': endDetected = TRUE; id.subscriptionId.number[i] = '\0'; break; case ':': id.subscriptionId.number[i] = '\0'; i = 0; state = 2; break; case '!': id.subscriptionId.number[i] = '\0'; i = 0; state = 3; break; default: id.subscriptionId.number[i] = *stringIterator; i++; break; } break; case 2: // parsing of sub id name assert(i < sizeof(id.subscriptionId.name)); switch (*stringIterator) { case '\0': endDetected = TRUE; id.subscriptionId.name[i] = '\0'; break; case '!': id.subscriptionId.name[i] = '\0'; i = 0; state = 3; break; default: id.subscriptionId.name[i] = *stringIterator; i++; break; } break; case 3: // parsing of auxiliary parameter assert(i < sizeof(id.subscriptionId.name)); switch (*stringIterator) { case '\0': endDetected = TRUE; id.subscriptionId.aux[i] = '\0'; break; default: id.subscriptionId.aux[i] = *stringIterator; i++; break; } break; default: assert(FALSE); } } return id; } /*! * \brief Match Subscription ID * \param channel SCCP Channel * \param subscriptionIdNum Subscription ID Number for linedevice * \return result as boolean * * \callgraph * \callergraph */ boolean_t sccp_util_matchSubscriptionId(const sccp_channel_t * channel, const char *subscriptionIdNum) { boolean_t result = TRUE; boolean_t filterPhones = FALSE; /* Determine if the phones registered on the shared line shall be filtered at all: only if a non-trivial subscription id is specified with the calling channel, which is not the default subscription id of the shared line denoting all devices, the phones are addressed individually. (-DD) */ filterPhones = FALSE; /* set the default to call all phones */ /* First condition: Non-trivial subscriptionId specified for matching in call. */ if (strlen(channel->subscriptionId.number) != 0) { /* Second condition: SubscriptionId does not match default subscriptionId of line. */ if (0 != strncasecmp(channel->subscriptionId.number, channel->line->defaultSubscriptionId.number, strlen(channel->subscriptionId.number))) { filterPhones = TRUE; } } if (FALSE == filterPhones) { /* Accept phone for calling if all phones shall be called. */ result = TRUE; } else if (0 != strlen(subscriptionIdNum) /* We already know that we won't search for a trivial subscriptionId. */ &&0 != strncasecmp(channel->subscriptionId.number, subscriptionIdNum, strlen(channel->subscriptionId.number))) { /* Do the match! */ result = FALSE; } #if 0 pbx_log(LOG_NOTICE, "sccp_channel->subscriptionId.number=%s, length=%d\n", channel->subscriptionId.number, strlen(channel->subscriptionId.number)); pbx_log(LOG_NOTICE, "subscriptionIdNum=%s, length=%d\n", subscriptionIdNum ? subscriptionIdNum : "NULL", subscriptionIdNum ? strlen(subscriptionIdNum) : -1); pbx_log(LOG_NOTICE, "sccp_util_matchSubscriptionId: sccp_channel->subscriptionId.number=%s, SubscriptionId=%s\n", (channel->subscriptionId.number) ? channel->subscriptionId.number : "NULL", (subscriptionIdNum) ? subscriptionIdNum : "NULL"); pbx_log(LOG_NOTICE, "sccp_util_matchSubscriptionId: result: %d\n", result); #endif return result; } /*! * \brief Parse a debug categories line to debug int * \param arguments Array of Arguments * \param startat Start Point in the Arguments Array * \param argc Count of Arguments * \param new_debug_value as uint32_t * \return new_debug_value as uint32_t */ int32_t sccp_parse_debugline(char *arguments[], int startat, int argc, int32_t new_debug_value) { int argi; int32_t i; char *argument = ""; char *token = ""; const char delimiters[] = " ,\t"; boolean_t subtract = 0; if (sscanf((char *) arguments[startat], "%d", &new_debug_value) != 1) { for (argi = startat; argi < argc; argi++) { argument = (char *) arguments[argi]; if (!strncmp(argument, "none", 4)) { new_debug_value = 0; break; } else if (!strncmp(argument, "no", 2)) { subtract = 1; } else if (!strncmp(argument, "all", 3)) { new_debug_value = 0; for (i = 0; i < ARRAY_LEN(sccp_debug_categories); i++) { if (!subtract) { new_debug_value += sccp_debug_categories[i].category; } } } else { // parse comma separated debug_var token = strtok(argument, delimiters); while (token != NULL) { // match debug level name to enum for (i = 0; i < ARRAY_LEN(sccp_debug_categories); i++) { if (strcasecmp(token, sccp_debug_categories[i].key) == 0) { if (subtract) { if ((new_debug_value & sccp_debug_categories[i].category) == sccp_debug_categories[i].category) { new_debug_value -= sccp_debug_categories[i].category; } } else { if ((new_debug_value & sccp_debug_categories[i].category) != sccp_debug_categories[i].category) { new_debug_value += sccp_debug_categories[i].category; } } } } token = strtok(NULL, delimiters); } } } } return new_debug_value; } /*! * \brief Write the current debug value to debug categories * \param debugvalue DebugValue as uint32_t * \return string containing list of categories comma seperated (you need to free it) */ char *sccp_get_debugcategories(int32_t debugvalue) { int32_t i; char *res = NULL; char *tmpres = NULL; const char *sep = ","; size_t size = 0; for (i = 0; i < ARRAY_LEN(sccp_debug_categories); ++i) { if ((debugvalue & sccp_debug_categories[i].category) == sccp_debug_categories[i].category) { size_t new_size = size; new_size += strlen(sccp_debug_categories[i].key) + sizeof(sep) + 1; tmpres = sccp_realloc(res, new_size); if (tmpres == NULL) { pbx_log(LOG_ERROR, "Memory Allocation Error\n"); sccp_free(res); return NULL; } res = tmpres; if (size == 0) { strcpy(res, sccp_debug_categories[i].key); } else { strcat(res, sep); strcat(res, sccp_debug_categories[i].key); } size = new_size; } } return res; } /*! * \brief create a LineStatDynamicMessage * \param lineInstance the line instance * \param dirNum the dirNum (e.g. line->cid_num) * \param fqdn line description (top right o the first line) * \param lineDisplayName label on the display * \return LineStatDynamicMessage as sccp_moo_t * * * \callgraph * \callergraph */ sccp_moo_t *sccp_utils_buildLineStatDynamicMessage(uint32_t lineInstance, const char *dirNum, const char *fqdn, const char *lineDisplayName) { sccp_moo_t *r1 = NULL; int dirNum_len = (dirNum != NULL) ? strlen(dirNum) : 0; int FQDN_len = (fqdn != NULL) ? strlen(fqdn) : 0; int lineDisplayName_len = (lineDisplayName != NULL) ? strlen(lineDisplayName) : 0; int dummy_len = dirNum_len + FQDN_len + lineDisplayName_len; int hdr_len = 8 - 1; int padding = 4; /* after each string + 1 */ int size = hdr_len + dummy_len + padding; /* message size must be muliple of 4 */ if ((size % 4) > 0) { size = size + (4 - (size % 4)); } r1 = sccp_build_packet(LineStatDynamicMessage, size); r1->msg.LineStatDynamicMessage.lel_lineNumber = htolel(lineInstance); r1->msg.LineStatDynamicMessage.lel_lineType = htolel(0x0f); if (dummy_len) { char buffer[dummy_len + padding]; memset(&buffer[0], 0, sizeof(buffer)); if (dirNum_len) memcpy(&buffer[0], dirNum, dirNum_len); if (FQDN_len) memcpy(&buffer[dirNum_len + 1], fqdn, FQDN_len); if (lineDisplayName_len) memcpy(&buffer[dirNum_len + FQDN_len + 2], lineDisplayName, lineDisplayName_len); memcpy(&r1->msg.LineStatDynamicMessage.dummy, &buffer[0], sizeof(buffer)); } return r1; } #ifdef HAVE_LIBGC /*! * \brief Verbose Logging Hanler for the GC Garbage Collector */ void gc_warn_handler(char *msg, GC_word p) { pbx_log(LOG_ERROR, "LIBGC: WARNING"); pbx_log(LOG_ERROR, msg, (unsigned long) p); } #endif /*! * \brief Compare the information of two socket with one another * \param s0 Socket Information * \param s1 Socket Information * \return success as int * * \retval 0 on diff * \retval 1 on equal */ int socket_equals(struct sockaddr_in *s0, struct sockaddr_in *s1) { if (s0->sin_addr.s_addr != s1->sin_addr.s_addr || s0->sin_port != s1->sin_port || s0->sin_family != s1->sin_family) { return 0; } return 1; } /*! * \brief SCCP version of strlen_zero * \param data String to be checked * \return zerolength as boolean * * \retval FALSE on non zero length * \retval TRUE on zero length */ gcc_inline boolean_t sccp_strlen_zero(const char *data) { if (!data || (*data == '\0')) { return TRUE; } return FALSE; } /*! * \brief SCCP version of strlen * \param data String to be checked * \return length as int */ gcc_inline size_t sccp_strlen(const char *data) { if (!data || (*data == '\0')) { return 0; } return strlen(data); } /*! * \brief SCCP version of strequals * \note Takes into account zero length strings, if both strings are zero length returns TRUE * \param data1 String to be checked * \param data2 String to be checked * \return !strcmp as boolean_t * * \retval booleant_t on !strcmp * \retval TRUE on both zero length * \retval FALSE on one of the the parameters being zero length */ gcc_inline boolean_t sccp_strequals(const char *data1, const char *data2) { if (sccp_strlen_zero(data1) && sccp_strlen_zero(data2)) { return TRUE; } else if (!sccp_strlen_zero(data1) && !sccp_strlen_zero(data2)) { return !strcmp(data1, data2); } return FALSE; } /*! * \brief SCCP version of strcaseequals * \note Takes into account zero length strings, if both strings are zero length returns TRUE * \param data1 String to be checked * \param data2 String to be checked * \return !strcasecmp as boolean_t * * \retval boolean_t on strcaseequals * \retval TRUE on both zero length * \retval FALSE on one of the the parameters being zero length */ gcc_inline boolean_t sccp_strcaseequals(const char *data1, const char *data2) { if (sccp_strlen_zero(data1) && sccp_strlen_zero(data2)) { return TRUE; } else if (!sccp_strlen_zero(data1) && !sccp_strlen_zero(data2)) { return !strcasecmp(data1, data2); } return FALSE; } int sccp_strIsNumeric(const char *s) { if (*s) { char c; while ((c = *s++)) { if (!isdigit(c)) return 0; } return 1; } return 0; } /*! * \brief Find the best codec match Between Preferences, Capabilities and RemotePeerCapabilities * * Returns: * - Best Match If Found * - If not it returns the first jointCapability * - Else SKINNY_CODEC_NONE */ skinny_codec_t sccp_utils_findBestCodec(const skinny_codec_t ourPreferences[], int pLength, const skinny_codec_t ourCapabilities[], int cLength, const skinny_codec_t remotePeerCapabilities[], int rLength) { uint8_t r, c, p; skinny_codec_t firstJointCapability = SKINNY_CODEC_NONE; /*!< used to get a default value */ sccp_log((DEBUGCAT_CODEC + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "pLength %d, cLength: %d, rLength: %d\n", pLength, cLength, rLength); /** check if we have a preference codec list */ if (pLength == 0 || ourPreferences[0] == SKINNY_CODEC_NONE) { /* using remote capabilities to */ sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "We got an empty preference codec list (exiting)\n"); return SKINNY_CODEC_NONE; } /* iterate over our codec preferences */ for (p = 0; p < pLength; p++) { if (ourPreferences[p] == SKINNY_CODEC_NONE) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "no more preferences at position %d\n", p); break; } /* no more preferences */ sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "preference: %d(%s)\n", ourPreferences[p], codec2name(ourPreferences[p])); /* check if we are capable to handle this codec */ for (c = 0; c < cLength; c++) { if (ourCapabilities[c] == SKINNY_CODEC_NONE) { /* we reached the end of valide codecs, because we found the first NONE codec */ break; } sccp_log((DEBUGCAT_CODEC + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "preference: %d(%s), capability: %d(%s)\n", ourPreferences[p], codec2name(ourPreferences[p]), ourCapabilities[c], codec2name(ourCapabilities[c])); /* we have no capabilities from the remote party, use the best codec from ourPreferences */ if (ourPreferences[p] == ourCapabilities[c]) { if (firstJointCapability == SKINNY_CODEC_NONE) { firstJointCapability = ourPreferences[p]; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "found first firstJointCapability %d(%s)\n", firstJointCapability, codec2name(firstJointCapability)); } if (rLength == 0 || remotePeerCapabilities[0] == SKINNY_CODEC_NONE) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "Empty remote Capabilities, using bestCodec from firstJointCapability %d(%s)\n", firstJointCapability, codec2name(firstJointCapability)); return firstJointCapability; } else { /* using capabilities from remote party, that matches our preferences & capabilities */ for (r = 0; r < rLength; r++) { if (remotePeerCapabilities[r] == SKINNY_CODEC_NONE) { break; } sccp_log((DEBUGCAT_CODEC + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "preference: %d(%s), capability: %d(%s), remoteCapability: " UI64FMT "(%s)\n", ourPreferences[p], codec2name(ourPreferences[p]), ourCapabilities[c], codec2name(ourCapabilities[c]), (ULONG) remotePeerCapabilities[r], codec2name(remotePeerCapabilities[r])); if (ourPreferences[p] == remotePeerCapabilities[r]) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "found bestCodec as joint capability with remote peer %d(%s)\n", ourPreferences[p], codec2name(ourPreferences[p])); return ourPreferences[p]; } } } } } } if (firstJointCapability != SKINNY_CODEC_NONE) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "did not find joint capability with remote device, using first joint capability %d(%s)\n", firstJointCapability, codec2name(firstJointCapability)); return firstJointCapability; } sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "no joint capability with preference codec list\n"); return 0; } /*! * \brief Free a list of Host Access Rules * \param ha The head of the list of HAs to free * \retval void */ void sccp_free_ha(struct sccp_ha *ha) { struct sccp_ha *hal; while (ha) { hal = ha; ha = ha->next; sccp_free(hal); } } /*! * \brief Apply a set of rules to a given IP address * * \param ha The head of the list of host access rules to follow * \param sin A sockaddr_in whose address is considered when matching rules * \retval AST_SENSE_ALLOW The IP address passes our ACL * \retval AST_SENSE_DENY The IP address fails our ACL */ int sccp_apply_ha(struct sccp_ha *ha, struct sockaddr_in *sin) { /* Start optimistic */ int res = AST_SENSE_DENY; while (ha) { /* For each rule, if this address and the netmask = the net address apply the current rule */ if ((sin->sin_addr.s_addr & ha->netmask.s_addr) == ha->netaddr.s_addr) { res = ha->sense; } ha = ha->next; } return res; } /*! * \brief Add a new rule to a list of HAs * * \param sense Either "permit" or "deny" (Actually any 'p' word will result * in permission, and any other word will result in denial) * \param stuff The IP address and subnet mask, separated with a '/'. The subnet * mask can either be in dotted-decimal format or in CIDR notation (i.e. 0-32). * \param path The head of the HA list to which we wish to append our new rule. If * NULL is passed, then the new rule will become the head of the list * \param[out] error The integer error points to will be set non-zero if an error occurs * \return The head of the HA list */ struct sccp_ha *sccp_append_ha(const char *sense, const char *stuff, struct sccp_ha *path, int *error) { struct sccp_ha *ha; char *nm; struct sccp_ha *prev = NULL; struct sccp_ha *ret; int x; char *tmp = sccp_strdupa(stuff); ret = path; while (path) { prev = path; path = path->next; } if (!(ha = sccp_calloc(1, sizeof(*ha)))) { if (error) { *error = 1; } return ret; } sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "start parsing ha sense: %s, stuff: %s \n", sense, stuff); if (!(nm = strchr(tmp, '/'))) { /* assume /32. Yes, htonl does not do anything for this particular mask but we better use it to show we remember about byte order */ ha->netmask.s_addr = htonl(0xFFFFFFFF); } else { *nm = '\0'; nm++; if (!strchr(nm, '.')) { if ((sscanf(nm, "%30d", &x) == 1) && (x >= 0) && (x <= 32)) { if (x == 0) { /* This is special-cased to prevent unpredictable * behavior of shifting left 32 bits */ ha->netmask.s_addr = 0; } else { ha->netmask.s_addr = htonl(0xFFFFFFFF << (32 - x)); } } else { sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_1 "Invalid CIDR in %s\n", stuff); sccp_free(ha); if (error) { *error = 1; } return ret; } } else if (!inet_aton(nm, &ha->netmask)) { sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_1 "Invalid mask in %s\n", stuff); sccp_free(ha); if (error) { *error = 1; } return ret; } } if (!inet_aton(tmp, &ha->netaddr)) { sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_1 "Invalid IP address in %s\n", stuff); sccp_free(ha); if (error) { *error = 1; } return ret; } ha->netaddr.s_addr &= ha->netmask.s_addr; ha->sense = strncasecmp(sense, "p", 1) ? AST_SENSE_DENY : AST_SENSE_ALLOW; ha->next = NULL; if (prev) { prev->next = ha; } else { ret = ha; } return ret; } void sccp_print_ha(struct ast_str *buf, int buflen, struct sccp_ha *path) { char str1[INET_ADDRSTRLEN]; char str2[INET_ADDRSTRLEN]; while (path) { inet_ntop(AF_INET, &path->netaddr.s_addr, str1, INET_ADDRSTRLEN); inet_ntop(AF_INET, &path->netmask.s_addr, str2, INET_ADDRSTRLEN); pbx_str_append(&buf, buflen, "%s:%s/%s,", AST_SENSE_DENY == path->sense ? "deny" : "permit", str1, str2); path = path->next; } } /*! * \brief Yields string representation from channel (for debug). * \param c SCCP channel * \return string constant (on the heap!) */ const char *sccp_channel_toString(sccp_channel_t * c) { if (c && c->designator) return (const char *) c->designator; else return ""; } /*! * \brief Print Group * \param buf Buf as char * \param buflen Buffer Lendth as int * \param group Group as sccp_group_t * \return Result as char */ void sccp_print_group(struct ast_str *buf, int buflen, sccp_group_t group) { unsigned int i; int first = 1; uint8_t max = (sizeof(sccp_group_t) * 8) - 1; if (!group) return; for (i = 0; i <= max; i++) { if (group & ((sccp_group_t) 1 << i)) { if (!first) { pbx_str_append(&buf, buflen, ","); } else { first = 0; } pbx_str_append(&buf, buflen, "%d", i); } } return; } /*! * \brief Compare two socket addressed with each other */ int sockaddr_cmp_addr(struct sockaddr_storage *addr1, socklen_t len1, struct sockaddr_storage *addr2, socklen_t len2) { struct sockaddr_in *p1_in = (struct sockaddr_in *) addr1; struct sockaddr_in *p2_in = (struct sockaddr_in *) addr2; struct sockaddr_in6 *p1_in6 = (struct sockaddr_in6 *) addr1; struct sockaddr_in6 *p2_in6 = (struct sockaddr_in6 *) addr2; if (len1 < len2) return -1; if (len1 > len2) return 1; if (p1_in->sin_family < p2_in->sin_family) return -1; if (p1_in->sin_family > p2_in->sin_family) return 1; /* compare ip4 */ if (p1_in->sin_family == AF_INET) { return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_ADDRSTRLEN); } else if (p1_in6->sin6_family == AF_INET6) { return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr, INET6_ADDRSTRLEN); } else { /* unknown type, compare for sanity. */ return memcmp(addr1, addr2, len1); } } int sccp_strversioncmp(const char *s1, const char *s2) { static const char *digits = "0123456789"; int ret, lz1, lz2; size_t p1, p2; p1 = strcspn(s1, digits); p2 = strcspn(s2, digits); while (p1 == p2 && s1[p1] != '\0' && s2[p2] != '\0') { /* Different prefix */ if ((ret = strncmp(s1, s2, p1)) != 0) return ret; s1 += p1; s2 += p2; lz1 = lz2 = 0; if (*s1 == '0') lz1 = 1; if (*s2 == '0') lz2 = 1; if (lz1 > lz2) return -1; else if (lz1 < lz2) return 1; else if (lz1 == 1) { /* * If the common prefix for s1 and s2 consists only of zeros, then the * "longer" number has to compare less. Otherwise the comparison needs * to be numerical (just fallthrough). See */ while (*s1 == '0' && *s2 == '0') { ++s1; ++s2; } p1 = strspn(s1, digits); p2 = strspn(s2, digits); /* Catch empty strings */ if (p1 == 0 && p2 > 0) return 1; else if (p2 == 0 && p1 > 0) return -1; /* Prefixes are not same */ if (*s1 != *s2 && *s1 != '0' && *s2 != '0') { if (p1 < p2) return 1; else if (p1 > p2) return -1; } else { if (p1 < p2) ret = strncmp(s1, s2, p1); else if (p1 > p2) ret = strncmp(s1, s2, p2); if (ret != 0) return ret; } } p1 = strspn(s1, digits); p2 = strspn(s2, digits); if (p1 < p2) return -1; else if (p1 > p2) return 1; else if ((ret = strncmp(s1, s2, p1)) != 0) return ret; /* Numbers are equal or not present, try with next ones. */ s1 += p1; s2 += p2; p1 = strcspn(s1, digits); p2 = strcspn(s2, digits); } return strcmp(s1, s2); }
722,257
./chan-sccp-b/src/sccp_refcount.c
/*! * \file sccp_refcount.c * \brief SCCP Refcount Class * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ /*! * \section sccp_refcount Reference Counted Objects * * We started using refcounting in V4.0 to prevent possible deadlock situations where the would not even have to occur. Up till now we had been using lock to prevent objects * from vanishing instead of preventing modification. As a rule there will be at most be one thread modifying a device, line, channel object in such a significant manner * the session thread the device and associated line/channel belongs too). * * In this regard locking was not necessary and could be replaced by a method to prevent vanishing objects and preventing dereferencing null pointers, leading to segmentation faults. * To solve that we opted to implement reference counting. Reference counting has a number of rules that need to be followed at any and all times for it to work: * * - Rule 1: During the initial creation / allocation of a refcounted object the refcount is set to 1. Example: * \code * channel = (sccp_channel_t *) sccp_refcount_object_alloc(sizeof(sccp_channel_t), "channel", c->id, __sccp_channel_destroy); * \endcode * * - Rule 2: Function that <b><em>return an object</em></b> (e.g. sccp_device, sccp_line, sccp_channel, sccp_event, sccp_linedevice), need to do so <b><em>with</em></b> a retained objects. * This happens when a object is created and returned to a calling function for example. * * - Rule 3: Functins that <b><em>receive an object pointer reference</em></b> via a function call expect the object <b><em>is being retained</em></b> in the calling function, during the time the called function lasts. * The object can <b><em>only</em></b> be released by the calling function not the called function, * * - Rule 4: When releasing an object the pointer we had toward the object should be nullified immediatly, either of these solutions is possible: * \code * d = sccp_device_release(d); // sccp_release always returns NULL * \endcode * or * \code * sccp_device_release(d); * d = NULL; * \endcode * * - Rule 5: You <b><em>cannnot</em></b> use free a refcounted object. Destruction of the refcounted object and subsequent freeing of the occupied memory is performed by the sccp_release * when the number of reference reaches 0. To finalize the use of a refcounted object just release the object one final time, to negate the initial refcount of 1 during creation. * . * These rules need to followed to the letter ! */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") #define SCCP_HASH_PRIME 563 #define SCCP_SIMPLE_HASH(_a) (((unsigned long)(_a)) % SCCP_HASH_PRIME) #define SCCP_LIVE_MARKER 13 #define REF_FILE "/tmp/sccp_refs" enum sccp_refcount_runstate runState = SCCP_REF_STOPPED; struct sccp_refcount_obj_info { int (*destructor) (const void *ptr); char datatype[StationMaxDeviceNameSize]; sccp_debug_category_t debugcat; } obj_info[] = { /* *INDENT-OFF* */ [SCCP_REF_DEVICE] = {NULL, "device", DEBUGCAT_DEVICE}, [SCCP_REF_LINE] = {NULL, "line", DEBUGCAT_LINE}, [SCCP_REF_CHANNEL] = {NULL, "channel", DEBUGCAT_CHANNEL}, [SCCP_REF_LINEDEVICE] = {NULL, "linedevice", DEBUGCAT_LINE}, [SCCP_REF_EVENT] = {NULL, "event", DEBUGCAT_EVENT}, [SCCP_REF_TEST] = {NULL, "test", DEBUGCAT_HIGH}, [SCCP_REF_CONFERENCE] = {NULL, "conference", DEBUGCAT_CONFERENCE}, [SCCP_REF_PARTICIPANT] = {NULL, "participant", DEBUGCAT_CONFERENCE}, /* *INDENT-ON* */ }; #ifdef SCCP_ATOMIC #define obj_lock NULL #else #define obj_lock &obj->lock #endif struct refcount_object { #ifndef SCCP_ATOMIC ast_mutex_t lock; #endif volatile CAS32_TYPE refcount; enum sccp_refcounted_types type; char identifier[REFCOUNT_INDENTIFIER_SIZE]; int alive; size_t len; SCCP_RWLIST_ENTRY (RefCountedObject) list; unsigned char data[0]; }; ast_rwlock_t objectslock; // general lock to modify hash table entries static struct refcount_objentry { SCCP_RWLIST_HEAD (, RefCountedObject) refCountedObjects; //!< one rwlock per hash table entry, used to modify list } *objects[SCCP_HASH_PRIME]; //!< objects hash table void sccp_refcount_init(void) { sccp_log((DEBUGCAT_REFCOUNT | DEBUGCAT_HIGH)) ("SCCP: (Refcount) init\n"); pbx_rwlock_init_notracking(&objectslock); // No tracking to safe cpu cycles runState = SCCP_REF_RUNNING; } void sccp_refcount_destroy(void) { int x; RefCountedObject *obj; pbx_log(LOG_NOTICE, "SCCP: (Refcount) destroying...\n"); runState = SCCP_REF_STOPPED; sched_yield(); //make sure all other threads can finish their work first. // cleanup if necessary, if everything is well, this should not be necessary ast_rwlock_wrlock(&objectslock); for (x = 0; x < SCCP_HASH_PRIME; x++) { if (objects[x]) { SCCP_RWLIST_WRLOCK(&(objects[x])->refCountedObjects); while ((obj = SCCP_RWLIST_REMOVE_HEAD(&(objects[x])->refCountedObjects, list))) { pbx_log(LOG_NOTICE, "Cleaning up [%3d]=type:%17s, id:%25s, ptr:%15p, refcount:%4d, alive:%4s, size:%4d\n", x, (obj_info[obj->type]).datatype, obj->identifier, obj, (int) obj->refcount, SCCP_LIVE_MARKER == obj->alive ? "yes" : "no", (int) obj->len); if ((&obj_info[obj->type])->destructor) (&obj_info[obj->type])->destructor(obj->data); #ifndef SCCP_ATOMIC ast_mutex_destroy(&obj->lock); #endif memset(obj, 0, sizeof(RefCountedObject)); sccp_free(obj); obj = NULL; } SCCP_RWLIST_UNLOCK(&(objects[x])->refCountedObjects); SCCP_RWLIST_HEAD_DESTROY(&(objects[x])->refCountedObjects); } } ast_rwlock_unlock(&objectslock); pbx_rwlock_destroy(&objectslock); runState = SCCP_REF_DESTROYED; } int sccp_refcount_isRunning(void) { return runState; } // not really needed any more int sccp_refcount_schedule_cleanup(const void *data) { return 0; } void *sccp_refcount_object_alloc(size_t size, enum sccp_refcounted_types type, const char *identifier, void *destructor) { RefCountedObject *obj; void *ptr = NULL; int hash; if (!(obj = calloc(1, size + sizeof(*obj)))) { ast_log(LOG_ERROR, "SCCP: (sccp_refcount_object_alloc) Memory allocation failure (obj)"); return NULL; } if (!(&obj_info[type])->destructor) { (&obj_info[type])->destructor = destructor; } // initialize object obj->len = size; obj->type = type; obj->refcount = 1; #ifndef SCCP_ATOMIC ast_mutex_init(&obj->lock); #endif sccp_copy_string(obj->identifier, identifier, sizeof(obj->identifier)); // generate hash ptr = obj->data; hash = SCCP_SIMPLE_HASH(ptr); if (!objects[hash]) { // create new hashtable head when necessary (should this possibly be moved to refcount_init, to avoid raceconditions ?) ast_rwlock_wrlock(&objectslock); if (!objects[hash]) { // check again after getting the lock, to see if another thread did not create the head already if (!(objects[hash] = malloc(sizeof(struct refcount_objentry)))) { ast_log(LOG_ERROR, "SCCP: (sccp_refcount_object_alloc) Memory allocation failure (hashtable)"); free(obj); obj = NULL; ast_rwlock_unlock(&objectslock); return NULL; } SCCP_RWLIST_HEAD_INIT(&(objects[hash])->refCountedObjects); } ast_rwlock_unlock(&objectslock); } // add object to hash table SCCP_RWLIST_WRLOCK(&(objects[hash])->refCountedObjects); SCCP_RWLIST_INSERT_HEAD(&(objects[hash])->refCountedObjects, obj, list); SCCP_RWLIST_UNLOCK(&(objects[hash])->refCountedObjects); sccp_log(DEBUGCAT_REFCOUNT) (VERBOSE_PREFIX_1 "SCCP: (alloc_obj) Creating new %s %s (%p) inside %p at hash: %d\n", (&obj_info[obj->type])->datatype, identifier, ptr, obj, hash); obj->alive = SCCP_LIVE_MARKER; #if CS_REFCOUNT_DEBUG FILE *refo = fopen(REF_FILE, "a"); if (refo) { fprintf(refo, "%p =1 %s:%d:%s (allocate new %s, len: %d, destructor: %p) [%p]\n", obj, __FILE__, __LINE__, __PRETTY_FUNCTION__, (&obj_info[obj->type])->datatype, (int) obj->len, (&obj_info[type])->destructor, ptr); fclose(refo); } #endif memset(ptr, 0, size); return ptr; } #if CS_REFCOUNT_DEBUG int __sccp_refcount_debug(void *ptr, RefCountedObject * obj, int delta, const char *file, int line, const char *func) { if (ptr == NULL) { FILE *refo = fopen(REF_FILE, "a"); if (refo) { fprintf(refo, "%p **PTR IS NULL !!** %s:%d:%s\n", ptr, file, line, func); fclose(refo); } // ast_assert(0); return -1; } if (obj == NULL) { FILE *refo = fopen(REF_FILE, "a"); if (refo) { fprintf(refo, "%p **OBJ ALREADY DESTROYED !!** %s:%d:%s\n", ptr, file, line, func); fclose(refo); } // ast_assert(0); return -1; } if (delta == 0 && obj->alive != SCCP_LIVE_MARKER) { FILE *refo = fopen(REF_FILE, "a"); if (refo) { fprintf(refo, "%p **OBJ Already destroyed and Declared DEAD !!** %s:%d:%s (%s:%s) [@%d] [%p]\n", ptr, file, line, func, (&obj_info[obj->type])->datatype, obj->identifier, obj->refcount, ptr); fclose(refo); } // ast_assert(0); return -1; } if (delta != 0) { FILE *refo = fopen(REF_FILE, "a"); if (refo) { fprintf(refo, "%p %s%d %s:%d:%s (%s:%s) [@%d] [%p]\n", obj, (delta < 0 ? "" : "+"), delta, file, line, func, (&obj_info[obj->type])->datatype, obj->identifier, obj->refcount, ptr); fclose(refo); } } if (obj->refcount + delta == 0 && (&obj_info[obj->type])->destructor != NULL) { FILE *refo = fopen(REF_FILE, "a"); if (refo) { fprintf(refo, "%p **call destructor** %s:%d:%s (%s:%s)\n", ptr, file, line, func, (&obj_info[obj->type])->datatype, obj->identifier); fclose(refo); } } return 0; } #endif static inline RefCountedObject *find_obj(const void *ptr, const char *filename, int lineno, const char *func) { RefCountedObject *obj = NULL; boolean_t found = FALSE; if (!ptr) return NULL; int hash = SCCP_SIMPLE_HASH(ptr); if (objects[hash]) { SCCP_RWLIST_RDLOCK(&(objects[hash])->refCountedObjects); SCCP_RWLIST_TRAVERSE(&(objects[hash])->refCountedObjects, obj, list) { if (obj->data == ptr) { if (SCCP_LIVE_MARKER == obj->alive) { found = TRUE; } else { #if CS_REFCOUNT_DEBUG __sccp_refcount_debug((void *) ptr, obj, 0, filename, lineno, func); #endif sccp_log(DEBUGCAT_REFCOUNT) (VERBOSE_PREFIX_1 "SCCP: (find_obj) %p Already declared dead (hash: %d)\n", obj, hash); } break; } } SCCP_RWLIST_UNLOCK(&(objects[hash])->refCountedObjects); } return found ? obj : NULL; } static inline void remove_obj(const void *ptr) { RefCountedObject *obj = NULL; if (!ptr) return; int hash = SCCP_SIMPLE_HASH(ptr); sccp_log(DEBUGCAT_REFCOUNT) (VERBOSE_PREFIX_1 "SCCP: (release) Removing %p from hash table at hash: %d\n", ptr, hash); if (objects[hash]) { SCCP_RWLIST_WRLOCK(&(objects[hash])->refCountedObjects); SCCP_RWLIST_TRAVERSE_SAFE_BEGIN(&(objects[hash])->refCountedObjects, obj, list) { if (obj->data == ptr) { SCCP_RWLIST_REMOVE_CURRENT(list); break; } } SCCP_RWLIST_TRAVERSE_SAFE_END; SCCP_RWLIST_UNLOCK(&(objects[hash])->refCountedObjects); } if (obj) { sched_yield(); // make sure all other threads can finish their work first. // should resolve lockless refcount SMP issues // BTW we are not allowed to sleep whilst haveing a reference // fire destructor sccp_log(DEBUGCAT_REFCOUNT) (VERBOSE_PREFIX_1 "SCCP: (release) Destroying %p at hash: %d\n", obj, hash); if ((&obj_info[obj->type])->destructor) (&obj_info[obj->type])->destructor(ptr); memset(obj, 0, sizeof(RefCountedObject)); sccp_free(obj); obj = NULL; } } #include <asterisk/cli.h> void sccp_refcount_print_hashtable(int fd) { int x, prev = 0; RefCountedObject *obj = NULL; pbx_cli(fd, "+==============================================================================================+\n"); pbx_cli(fd, "| %5s | %17s | %25s | %15s | %4s | %4s | %4s |\n", "hash", "type", "id", "ptr", "refc", "live", "size"); pbx_cli(fd, "|==============================================================================================|\n"); ast_rwlock_rdlock(&objectslock); for (x = 0; x < SCCP_HASH_PRIME; x++) { if (objects[x] && &(objects[x])->refCountedObjects) { SCCP_RWLIST_RDLOCK(&(objects[x])->refCountedObjects); SCCP_RWLIST_TRAVERSE(&(objects[x])->refCountedObjects, obj, list) { if (prev == x) { pbx_cli(fd, "| +-> "); } else { pbx_cli(fd, "| [%3d] ", x); } pbx_cli(fd, "| %17s | %25s | %15p | %4d | %4s | %4d |\n", (obj_info[obj->type]).datatype, obj->identifier, obj, (int) obj->refcount, SCCP_LIVE_MARKER == obj->alive ? "yes" : "no", (int) obj->len); prev = x; } SCCP_RWLIST_UNLOCK(&(objects[x])->refCountedObjects); } } ast_rwlock_unlock(&objectslock); pbx_cli(fd, "+==============================================================================================+\n"); } void sccp_refcount_updateIdentifier(void *ptr, char *identifier) { RefCountedObject *obj = NULL; if ((obj = find_obj(ptr, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { sccp_copy_string(obj->identifier, identifier, sizeof(obj->identifier)); } else { ast_log(LOG_ERROR, "SCCP: (updateIdentifief) Refcount Object %p could not be found\n", ptr); } } inline void *sccp_refcount_retain(void *ptr, const char *filename, int lineno, const char *func) { RefCountedObject *obj = NULL; volatile int refcountval; int newrefcountval; if ((obj = find_obj(ptr, filename, lineno, func))) { #if CS_REFCOUNT_DEBUG __sccp_refcount_debug(ptr, obj, 1, filename, lineno, func); #endif refcountval = ATOMIC_INCR((&obj->refcount), 1, &obj->lock); newrefcountval = refcountval + 1; if ((sccp_globals->debug & (((&obj_info[obj->type])->debugcat + DEBUGCAT_REFCOUNT))) == ((&obj_info[obj->type])->debugcat + DEBUGCAT_REFCOUNT)) { ast_log(__LOG_VERBOSE, __FILE__, 0, "", " %-15.15s:%-4.4d (%-25.25s) %*.*s> %*s refcount increased %.2d +> %.2d for %10s: %s (%p)\n", filename, lineno, func, refcountval, refcountval, "--------------------", 20 - refcountval, " ", refcountval, newrefcountval, (&obj_info[obj->type])->datatype, obj->identifier, obj); } return obj->data; } else { #if CS_REFCOUNT_DEBUG __sccp_refcount_debug((void *) ptr, NULL, 1, filename, lineno, func); #endif ast_log(__LOG_VERBOSE, __FILE__, 0, "retain", "SCCP: (%-15.15s:%-4.4d (%-25.25s)) ALARM !! trying to retain a %s: %s (%p) with invalid memory reference! this should never happen !\n", filename, lineno, func, (obj && (&obj_info[obj->type])->datatype) ? (&obj_info[obj->type])->datatype : "UNREF", (obj && obj->identifier) ? obj->identifier : "UNREF", obj); ast_log(LOG_ERROR, "SCCP: (release) Refcount Object %p could not be found (Major Logic Error). Please report to developers\n", ptr); return NULL; } } inline void *sccp_refcount_release(const void *ptr, const char *filename, int lineno, const char *func) { RefCountedObject *obj = NULL; volatile int refcountval; int newrefcountval; if ((obj = find_obj(ptr, filename, lineno, func))) { #if CS_REFCOUNT_DEBUG __sccp_refcount_debug((void *) ptr, obj, -1, filename, lineno, func); #endif refcountval = ATOMIC_DECR((&obj->refcount), 1, &obj->lock); newrefcountval = refcountval - 1; if (newrefcountval == 0) { ATOMIC_DECR(&obj->alive, SCCP_LIVE_MARKER, &obj->lock); sccp_log(DEBUGCAT_REFCOUNT) (VERBOSE_PREFIX_1 "SCCP: %-15.15s:%-4.4d (%-25.25s) (release) Finalizing %p (%p)\n", filename, lineno, func, obj, ptr); remove_obj(ptr); } else { if ((sccp_globals->debug & (((&obj_info[obj->type])->debugcat + DEBUGCAT_REFCOUNT))) == ((&obj_info[obj->type])->debugcat + DEBUGCAT_REFCOUNT)) { ast_log(__LOG_VERBOSE, __FILE__, 0, "", " %-15.15s:%-4.4d (%-25.25s) <%*.*s %*s refcount decreased %.2d <- %.2d for %10s: %s (%p)\n", filename, lineno, func, newrefcountval, newrefcountval, "--------------------", 20 - newrefcountval, " ", newrefcountval, refcountval, (&obj_info[obj->type])->datatype, obj->identifier, obj); } } } else { #if CS_REFCOUNT_DEBUG __sccp_refcount_debug((void *) ptr, NULL, -1, filename, lineno, func); #endif ast_log(__LOG_VERBOSE, __FILE__, 0, "release", "SCCP (%-15.15s:%-4.4d (%-25.25s)) ALARM !! trying to release a %s: %s (%p) with invalid memory reference! this should never happen !\n", filename, lineno, func, (obj && (&obj_info[obj->type])->datatype) ? (&obj_info[obj->type])->datatype : "UNREF", (obj && obj->identifier) ? obj->identifier : "UNREF", obj); ast_log(LOG_ERROR, "SCCP: (release) Refcount Object %p could not be found (Major Logic Error). Please report to developers\n", ptr); } return NULL; }
722,258
./chan-sccp-b/src/sccp_socket.c
/*! * \file sccp_socket.c * \brief SCCP Socket Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" #include <signal.h> SCCP_FILE_VERSION(__FILE__, "$Revision$") #include <sys/ioctl.h> #ifdef SOLARIS #include <sys/filio.h> // provides FIONREAD on SOLARIS #endif #ifndef CS_USE_POLL_COMPAT #include <poll.h> #include <sys/poll.h> #else #define AST_POLL_COMPAT 1 #include <asterisk/poll-compat.h> #endif #ifdef pbx_poll #define sccp_socket_poll pbx_poll #else #define sccp_socket_poll poll #endif sccp_session_t *sccp_session_findByDevice(const sccp_device_t * device); void destroy_session(sccp_session_t * s, uint8_t cleanupTime); void sccp_session_close(sccp_session_t * s); void sccp_socket_device_thread_exit(void *session); void *sccp_socket_device_thread(void *session); static sccp_moo_t *sccp_process_data(sccp_session_t * s); boolean_t socket_is_IPv6(struct sockaddr_storage *socketStorage) { return (socketStorage->ss_family == AF_INET6) ? TRUE : FALSE; } boolean_t socket_is_mapped_ipv4(struct sockaddr_storage *socketStorage) { const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) socketStorage; return IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr); } /*! * \brief Exchange Socket Addres Information from them to us */ static int sccp_socket_getOurAddressfor(struct in_addr *them, struct in_addr *us) { int s; struct sockaddr_in sin; socklen_t slen; if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { return -1; } sin.sin_family = AF_INET; sin.sin_port = GLOB(bindaddr.sin_port); sin.sin_addr = *them; if (connect(s, (struct sockaddr *) &sin, sizeof(sin))) { return -1; } slen = sizeof(sin); if (getsockname(s, (struct sockaddr *) &sin, &slen)) { close(s); return -1; } close(s); // *us = sin.sin_addr; memcpy(us, &sin.sin_addr, sizeof(struct in_addr)); return 0; } void sccp_socket_stop_sessionthread(sccp_session_t * session, uint8_t newRegistrationState) { sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_2 "%s: Stopping Session Thread\n", DEV_ID_LOG(session->device)); if (!session) { pbx_log(LOG_NOTICE, "SCCP: session already terminated\n"); return; } session->session_stop = 1; if (session->device) { session->device->registrationState = newRegistrationState; } if (AST_PTHREADT_NULL != session->session_thread) { shutdown(session->fds[0].fd, SHUT_RD); // this will also wake up poll // which is waiting for a read event and close down the thread nicely } } /*! * \brief Read Data From Socket * \param s SCCP Session * * \lock * - session */ static int sccp_read_data(sccp_session_t * s) { if (!s || s->session_stop) { return 0; } int16_t readlen = 0; char input[SCCP_MAX_PACKET]; readlen = read(s->fds[0].fd, input, sizeof(input)); if (readlen <= 0) { if (readlen < 0 && (errno == EINTR || errno == EAGAIN)) { pbx_log(LOG_WARNING, "SCCP: Come back later (EAGAIN): %s\n", strerror(errno)); } else { /* (readlen==0 || errno == ECONNRESET || errno == ETIMEDOUT) */ sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: device closed connection or network unreachable. closing connection.\n", DEV_ID_LOG(s->device)); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); } return 0; } else { /* move s->buffer content to the beginning */ memcpy(s->buffer + s->buffer_size, input, readlen); s->buffer_size += readlen; } return readlen; } /*! * \brief Find Session in Globals Lists * \param s SCCP Session * \return boolean * * \lock * - session */ static boolean_t sccp_session_findBySession(sccp_session_t * s) { sccp_session_t *session; boolean_t res = FALSE; SCCP_RWLIST_WRLOCK(&GLOB(sessions)); SCCP_RWLIST_TRAVERSE(&GLOB(sessions), session, list) { if (session == s) { res = TRUE; break; } } SCCP_RWLIST_UNLOCK(&GLOB(sessions)); return res; } /*! * \brief Add a session to the global sccp_sessions list * \param s SCCP Session * \return boolean * * \lock * - session */ static boolean_t sccp_session_addToGlobals(sccp_session_t * s) { boolean_t res = FALSE; if (s) { if (!sccp_session_findBySession(s)) {; SCCP_RWLIST_WRLOCK(&GLOB(sessions)); SCCP_LIST_INSERT_HEAD(&GLOB(sessions), s, list); res = TRUE; SCCP_RWLIST_UNLOCK(&GLOB(sessions)); } } return res; } /*! * \brief Removes a session from the global sccp_sessions list * \param s SCCP Session * \return boolean * * \lock * - sessions */ static boolean_t sccp_session_removeFromGlobals(sccp_session_t * s) { sccp_session_t *session; boolean_t res = FALSE; if (s) { SCCP_RWLIST_WRLOCK(&GLOB(sessions)); SCCP_RWLIST_TRAVERSE_SAFE_BEGIN(&GLOB(sessions), session, list) { if (session == s) { SCCP_LIST_REMOVE_CURRENT(list); res = TRUE; break; } } SCCP_RWLIST_TRAVERSE_SAFE_END; SCCP_RWLIST_UNLOCK(&GLOB(sessions)); } return res; } /*! * \brief Retain device pointer in session. Replace existing pointer if necessary * \param session SCCP Session * \param device SCCP Device */ sccp_device_t *sccp_session_addDevice(sccp_session_t * session, sccp_device_t * device) { if (session && device && session->device != device) { sccp_session_lock(session); if (session->device) { sccp_device_t *remdevice = sccp_device_retain(session->device); sccp_session_removeDevice(session); remdevice = sccp_device_release(remdevice); } if ((session->device = sccp_device_retain(device))) { session->device->session = session; } sccp_session_unlock(session); } return (session && session->device) ? session->device : NULL; } /*! * \brief Release device pointer from session * \param session SCCP Session */ sccp_device_t *sccp_session_removeDevice(sccp_session_t * session) { if (session && session->device) { if (session->device->session && session->device->session != session) { // cleanup previous/crossover session sccp_session_removeFromGlobals(session->device->session); } sccp_session_lock(session); session->device->registrationState = SKINNY_DEVICE_RS_NONE; session->device->session = NULL; session->device = sccp_device_release(session->device); sccp_session_unlock(session); } return NULL; } /*! * \brief Socket Session Close * \param s SCCP Session * * \callgraph * \callergraph * * \lock * - see sccp_hint_eventListener() via sccp_event_fire() * - session */ void sccp_session_close(sccp_session_t * s) { sccp_session_lock(s); s->session_stop = 1; if (s->fds[0].fd > 0) { close(s->fds[0].fd); s->fds[0].fd = -1; } sccp_session_unlock(s); sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "%s: Old session marked down\n", DEV_ID_LOG(s->device)); } /*! * \brief Destroy Socket Session * \param s SCCP Session * \param cleanupTime Cleanup Time as uint8_t, Max time before device cleanup starts * * \callgraph * \callergraph * * \lock * - sessions * - device */ void destroy_session(sccp_session_t * s, uint8_t cleanupTime) { sccp_device_t *d = NULL; boolean_t found_in_list = FALSE; if (!s) { return; } found_in_list = sccp_session_removeFromGlobals(s); if (!found_in_list) { sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "%s: Session could not be found in GLOB(session) %s\n", DEV_ID_LOG(s->device), pbx_inet_ntoa(s->sin.sin_addr)); } /* cleanup device if this session is not a crossover session */ if (s->device && (d = sccp_device_retain(s->device))) { sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "%s: Destroy Device Session %s\n", DEV_ID_LOG(s->device), pbx_inet_ntoa(s->sin.sin_addr)); d->registrationState = SKINNY_DEVICE_RS_NONE; d->needcheckringback = 0; sccp_dev_clean(d, (d->realtime) ? TRUE : FALSE, cleanupTime); sccp_device_release(d); } sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "SCCP: Destroy Session %s\n", pbx_inet_ntoa(s->sin.sin_addr)); /* closing fd's */ sccp_session_lock(s); if (s->fds[0].fd > 0) { close(s->fds[0].fd); s->fds[0].fd = -1; } /* freeing buffers */ if (s->buffer) { sccp_free(s->buffer); } sccp_session_unlock(s); /* destroying mutex and cleaning the session */ sccp_mutex_destroy(&s->lock); sccp_free(s); s = NULL; } /*! * \brief Socket Device Thread Exit * \param session SCCP Session * * \callgraph * \callergraph */ void sccp_socket_device_thread_exit(void *session) { sccp_session_t *s = (sccp_session_t *) session; sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "%s: cleanup session\n", DEV_ID_LOG(s->device)); sccp_session_close(s); s->session_thread = AST_PTHREADT_NULL; destroy_session(s, 10); } /*! * \brief Socket Device Thread * \param session SCCP Session * * \callgraph * \callergraph */ void *sccp_socket_device_thread(void *session) { sccp_session_t *s = (sccp_session_t *) session; uint8_t keepaliveAdditionalTimePercent = 10; int res; double maxWaitTime; int pollTimeout; sccp_moo_t *m; pthread_cleanup_push(sccp_socket_device_thread_exit, session); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); /* we increase additionalTime for wireless/slower devices */ if (s->device && (s->device->skinny_type == SKINNY_DEVICETYPE_CISCO7920 || s->device->skinny_type == SKINNY_DEVICETYPE_CISCO7921 || s->device->skinny_type == SKINNY_DEVICETYPE_CISCO7925 || s->device->skinny_type == SKINNY_DEVICETYPE_CISCO7975 || s->device->skinny_type == SKINNY_DEVICETYPE_CISCO7970 || s->device->skinny_type == SKINNY_DEVICETYPE_CISCO6911) ) { keepaliveAdditionalTimePercent += 10; } while (s->fds[0].fd > 0 && !s->session_stop) { /* create cancellation point */ pthread_testcancel(); if (s->device) { pbx_mutex_lock(&GLOB(lock)); if (GLOB(reload_in_progress) == FALSE && s && s->device && (!(s->device->pendingUpdate == FALSE && s->device->pendingDelete == FALSE))) { sccp_device_check_update(s->device); } pbx_mutex_unlock(&GLOB(lock)); } /* calculate poll timout using keepalive interval */ maxWaitTime = (s->device) ? s->device->keepalive : GLOB(keepalive); maxWaitTime += (maxWaitTime / 100) * keepaliveAdditionalTimePercent; pollTimeout = maxWaitTime * 1000; sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "%s: set poll timeout %d/%d for session %d\n", DEV_ID_LOG(s->device), (int) maxWaitTime, pollTimeout / 1000, s->fds[0].fd); pthread_testcancel(); /* poll is also a cancellation point */ res = sccp_socket_poll(s->fds, 1, pollTimeout); pthread_testcancel(); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); if (-1 == res) { /* poll data processing */ if (errno > 0 && (errno != EAGAIN) && (errno != EINTR)) { pbx_log(LOG_ERROR, "%s: poll() returned %d. errno: %s, (ip-address: %s)\n", DEV_ID_LOG(s->device), errno, strerror(errno), pbx_inet_ntoa(s->sin.sin_addr)); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); break; } } else if (0 == res) { /* poll timeout */ sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "%s: Poll Timeout.\n", DEV_ID_LOG(s->device)); if (((int) time(0) > ((int) s->lastKeepAlive + (int) maxWaitTime))) { ast_log(LOG_NOTICE, "%s: Closing session because connection timed out after %d seconds (timeout: %d).\n", DEV_ID_LOG(s->device), (int) maxWaitTime, pollTimeout); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_TIMEOUT); break; } } else if (res > 0) { /* poll data processing */ if (s->fds[0].revents & POLLIN || s->fds[0].revents & POLLPRI) { /* POLLIN | POLLPRI */ /* we have new data -> continue */ sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "%s: Session New Data Arriving\n", DEV_ID_LOG(s->device)); if (sccp_read_data(s) >= SCCP_PACKET_HEADER) { while ((m = sccp_process_data(s))) { if (!sccp_handle_message(m, s)) { if (s->device) { sccp_device_sendReset(s->device, SKINNY_DEVICE_RESTART); } sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); sccp_free(m); break; } sccp_free(m); s->lastKeepAlive = time(0); } } } else { /* POLLHUP / POLLERR */ pbx_log(LOG_NOTICE, "%s: Closing session because we received POLLPRI/POLLHUP/POLLERR\n", DEV_ID_LOG(s->device)); sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); break; } } else { /* poll returned invalid res */ sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_2 "%s: Poll Returned invalid result: %d.\n", DEV_ID_LOG(s->device), res); } pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); } sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "%s: Exiting sccp_socket device thread\n", DEV_ID_LOG(s->device)); pthread_cleanup_pop(1); return NULL; } /*! * \brief Socket Accept Connection * * \lock * - sessions */ static void sccp_accept_connection(void) { /* called without GLOB(sessions_lock) */ struct sockaddr_in incoming; sccp_session_t *s; int new_socket; socklen_t length = (socklen_t) (sizeof(struct sockaddr_in)); int on = 1; if ((new_socket = accept(GLOB(descriptor), (struct sockaddr *) &incoming, &length)) < 0) { pbx_log(LOG_ERROR, "Error accepting new socket %s\n", strerror(errno)); return; } // if (setsockopt(new_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) { // pbx_log(LOG_WARNING, "Failed to set SCCP socket to SO_REUSEADDR mode: %s\n", strerror(errno)); // } if (setsockopt(new_socket, IPPROTO_IP, IP_TOS, &GLOB(sccp_tos), sizeof(GLOB(sccp_tos))) < 0) { pbx_log(LOG_WARNING, "Failed to set SCCP socket TOS to %d: %s\n", GLOB(sccp_tos), strerror(errno)); } if (setsockopt(new_socket, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) { pbx_log(LOG_WARNING, "Failed to set SCCP socket to TCP_NODELAY: %s\n", strerror(errno)); } #if defined(linux) if (setsockopt(new_socket, SOL_SOCKET, SO_PRIORITY, &GLOB(sccp_cos), sizeof(GLOB(sccp_cos))) < 0) { pbx_log(LOG_WARNING, "Failed to set SCCP socket COS to %d: %s\n", GLOB(sccp_cos), strerror(errno)); } #endif s = sccp_malloc(sizeof(struct sccp_session)); memset(s, 0, sizeof(sccp_session_t)); memcpy(&s->sin, &incoming, sizeof(s->sin)); sccp_mutex_init(&s->lock); sccp_session_lock(s); s->fds[0].events = POLLIN | POLLPRI; s->fds[0].revents = 0; s->fds[0].fd = new_socket; if (!GLOB(ha)) { pbx_log(LOG_NOTICE, "No global ha list\n"); } /* check ip address against global permit/deny ACL */ if (GLOB(ha) && sccp_apply_ha(GLOB(ha), &s->sin) != AST_SENSE_ALLOW) { struct ast_str *buf = pbx_str_alloca(512); sccp_print_ha(buf, sizeof(buf), GLOB(ha)); sccp_log(0) ("SCCP: Rejecting Connection: Ip-address '%s' denied. Check general deny/permit settings (%s).\n", pbx_inet_ntoa(s->sin.sin_addr), pbx_str_buffer(buf)); pbx_log(LOG_WARNING, "SCCP: Rejecting Connection: Ip-address '%s' denied. Check general deny/permit settings (%s).\n", pbx_inet_ntoa(s->sin.sin_addr), pbx_str_buffer(buf)); sccp_session_reject(s, "Device ip not authorized"); sccp_session_unlock(s); destroy_session(s, 0); return; } sccp_session_addToGlobals(s); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "SCCP: Accepted connection from %s\n", pbx_inet_ntoa(s->sin.sin_addr)); /** set default handler for registration to sccp */ s->protocolType = SCCP_PROTOCOL; s->lastKeepAlive = time(0); s->buffer = calloc(1, SCCP_MAX_PACKET * 2); /* maximum buffer size has to be more than one maximum packet */ s->buffer_size = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Accepted connection from %s\n", pbx_inet_ntoa(s->sin.sin_addr)); if (GLOB(bindaddr.sin_addr.s_addr) == INADDR_ANY) { sccp_socket_getOurAddressfor(&incoming.sin_addr, &s->ourip); } else { memcpy(&s->ourip, &GLOB(bindaddr.sin_addr.s_addr), sizeof(s->ourip)); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Using ip %s\n", pbx_inet_ntoa(s->ourip)); size_t stacksize = 0; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pbx_pthread_create(&s->session_thread, &attr, sccp_socket_device_thread, s); if (!pthread_attr_getstacksize(&attr, &stacksize)) { sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: Using %d memory for this thread\n", (int) stacksize); } sccp_session_unlock(s); } /*! * \brief Socket Process Data * \param s SCCP Session * \note Called with mutex lock */ static sccp_moo_t *sccp_process_data(sccp_session_t * s) { sccp_header_t header = { 0 }; uint32_t packetSize = 0; uint32_t messageId = 0; uint32_t newPacketSize = 0; uint32_t mooMessageSize = 0; sccp_moo_t *msg = NULL; if (!s || s->buffer_size < SCCP_PACKET_HEADER) { return NULL; /* Not enough data to even read the packet lenght */ } memcpy(&header, s->buffer, SCCP_PACKET_HEADER); messageId = letohl(header.lel_messageId); packetSize = letohl(header.length); packetSize += 8; /* SCCP_PACKET_HEADER - sizeof(packetSize); */ if (packetSize > s->buffer_size) { return NULL; /* Not enough data, yet. */ } /* copy the first full message we can find out of s->buffer */ newPacketSize = packetSize; mooMessageSize = message2size(messageId); if (newPacketSize > SCCP_MAX_PACKET) { /* Make sure we don't read bigger then SCCP_MAX_PACKET */ pbx_log(LOG_NOTICE, "SCCP: Oversize packet mid: %d, our packet size: %d, phone packet size: %d, max packat size: %d (Expect Problems. Report to Developers)\n", messageId, newPacketSize, packetSize, (uint32_t) SCCP_MAX_PACKET); newPacketSize = SCCP_MAX_PACKET; } else if (newPacketSize < mooMessageSize) { /* Make sure we allocate enough to cover sccp_moo_t */ sccp_log((DEBUGCAT_SOCKET + DEBUGCAT_HIGH)) ("SCCP: Undersized message: %s (%02X), message size: %d, phone packet size: %d\n", message2str(messageId), messageId, mooMessageSize, newPacketSize); newPacketSize = mooMessageSize; } if ((msg = sccp_calloc(1, newPacketSize)) == NULL) { /* Only calloc what we need */ pbx_log(LOG_ERROR, "SCCP: unable to allocate %d bytes for a new skinny packet (Expect Dissaster)\n", newPacketSize); return NULL; } memcpy(msg, s->buffer, packetSize); /* Copy packetSize from the buffer */ msg->header.length = letohl(msg->header.length); /* replace msg->length (network conversion) */ sccp_log(DEBUGCAT_HIGH) ("SCCP: packet message: %s (%02X), phone packet size: %d, new packet size: %d, sccp message_size: %d\n", message2str(messageId), messageId, packetSize, newPacketSize, mooMessageSize); /* move s->buffer content to the beginning */ s->buffer_size -= packetSize; memmove(s->buffer, (s->buffer + packetSize), s->buffer_size); /* return the message */ return msg; } /*! * \brief Socket Thread * \param ignore None * * \lock * - sessions * - globals * - see sccp_device_check_update() * - see sccp_socket_poll() * - see sccp_session_close() * - see destroy_session() * - see sccp_read_data() * - see sccp_process_data() * - see sccp_handle_message() * - see sccp_device_sendReset() */ void *sccp_socket_thread(void *ignore) { struct pollfd fds[1]; fds[0].events = POLLIN | POLLPRI; fds[0].revents = 0; int res; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); while (GLOB(descriptor) > -1) { fds[0].fd = GLOB(descriptor); res = sccp_socket_poll(fds, 1, SCCP_SOCKET_ACCEPT_TIMEOUT); if (res < 0) { if (errno == EINTR || errno == EAGAIN) { pbx_log(LOG_ERROR, "SCCP poll() returned %d. errno: %d (%s) -- ignoring.\n", res, errno, strerror(errno)); } else { pbx_log(LOG_ERROR, "SCCP poll() returned %d. errno: %d (%s)\n", res, errno, strerror(errno)); } } else if (res == 0) { // poll timeout } else { if (GLOB(module_running)) { sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "SCCP: Accept Connection\n"); sccp_accept_connection(); } } } sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "SCCP: Exit from the socket thread\n"); return NULL; } /*! * \brief Socket Send Message * \param device SCCP Device * \param t SCCP Message */ void sccp_session_sendmsg(const sccp_device_t * device, sccp_message_t t) { if (!device || !device->session) { sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "SCCP: (sccp_session_sendmsg) No device available to send message to\n"); return; } sccp_moo_t *r = sccp_build_packet(t, 0); if (r) { sccp_session_send(device, r); } } /*! * \brief Socket Send * \param device SCCP Device * \param r Message Data Structure (sccp_moo_t) * \return SCCP Session Send */ int sccp_session_send(const sccp_device_t * device, sccp_moo_t * r) { sccp_session_t *s = sccp_session_findByDevice(device); if (s && !s->session_stop) { return sccp_session_send2(s, r); } else { return -1; } } /*! * \brief Socket Send Message * \param s Session SCCP Session (can't be null) * \param r Message SCCP Moo Message (will be freed) * \return Result as Int * * \lock * - session */ int sccp_session_send2(sccp_session_t * s, sccp_moo_t * r) { ssize_t res = 0; uint32_t msgid = letohl(r->header.lel_messageId); ssize_t bytesSent; ssize_t bufLen; uint8_t *bufAddr; unsigned int try, maxTries;; if (s && s->session_stop) { return -1; } if (!s || s->fds[0].fd <= 0) { sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "SCCP: Tried to send packet over DOWN device.\n"); if (s) { sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); } sccp_free(r); r = NULL; return -1; } if (msgid == KeepAliveAckMessage || msgid == RegisterAckMessage || msgid == UnregisterAckMessage) { r->header.lel_protocolVer = 0; } else if (s->device && s->device->inuseprotocolversion >= 17) { r->header.lel_protocolVer = htolel(0x11); /* we should always send 0x11 */ } else { r->header.lel_protocolVer = 0; } try = 0; maxTries = 500; /* arbitrairy number of tries */ bytesSent = 0; bufAddr = ((uint8_t *) r); bufLen = (ssize_t) (letohl(r->header.length) + 8); do { try++; ast_mutex_lock(&s->write_lock); /* prevent two threads writing at the same time. That should happen in a synchronized way */ res = write(s->fds[0].fd, bufAddr + bytesSent, bufLen - bytesSent); ast_mutex_unlock(&s->write_lock); if (res < 0) { if (errno == EINTR || errno == EAGAIN) { usleep(200); /* back off to give network/other threads some time */ continue; } pbx_log(LOG_ERROR, "%s: write returned %d (error: '%s (%d)'). Sent %d of %d for Message: '%s' with total length %d \n", DEV_ID_LOG(s->device), (int) res, strerror(errno), errno, (int) bytesSent, (int) bufLen, message2str(letohl(r->header.lel_messageId)), letohl(r->header.length) ); if (s) { sccp_socket_stop_sessionthread(s, SKINNY_DEVICE_RS_FAILED); } res = -1; break; } bytesSent += res; } while (bytesSent < bufLen && try < maxTries && s && !s->session_stop && s->fds[0].fd > 0); sccp_free(r); r = NULL; if (bytesSent < bufLen) { ast_log(LOG_ERROR, "%s: Could only send %d of %d bytes!\n", DEV_ID_LOG(s->device), (int) bytesSent, (int) bufLen); res = -1; } return res; } /*! * \brief Find session for device * \param device SCCP Device * \return SCCP Session * * \lock * - sessions */ sccp_session_t *sccp_session_findByDevice(const sccp_device_t * device) { if (!device) { sccp_log((DEBUGCAT_SOCKET)) (VERBOSE_PREFIX_3 "SCCP: (sccp_session_find) No device available to find session\n"); return NULL; } return device->session; } static sccp_session_t *sccp_session_findSessionForDevice(const sccp_device_t * device) { sccp_session_t *session; SCCP_LIST_TRAVERSE_SAFE_BEGIN(&GLOB(sessions), session, list) { if (session->device == device) { break; } } SCCP_LIST_TRAVERSE_SAFE_END; return session; } /*! * \brief Send a Reject Message to Device. * \param session SCCP Session Pointer * \param message Message as char (reason of rejection) */ sccp_session_t *sccp_session_reject(sccp_session_t * session, char *message) { sccp_moo_t *r; REQ(r, RegisterRejectMessage); sccp_copy_string(r->msg.RegisterRejectMessage.text, message, sizeof(r->msg.RegisterRejectMessage.text)); sccp_session_send2(session, r); /* if we reject the connection during accept connection, thread is not ready */ sccp_socket_stop_sessionthread(session, SKINNY_DEVICE_RS_FAILED); return NULL; } /*! * \brief Send a Reject Message to Device. * \param session SCCP Session Pointer * \param device SCCP Device Pointer * \param message Message as char (reason of rejection) */ sccp_session_t *sccp_session_crossdevice_cleanup(sccp_session_t * session, sccp_device_t * device, char *message) { sccp_dev_displayprinotify(device, message, 0, 2); sccp_device_sendReset(device, SKINNY_DEVICE_RESTART); /* if we reject the connection during accept connection, thread is not ready */ sccp_socket_stop_sessionthread(session, SKINNY_DEVICE_RS_NONE); return NULL; } /*! * \brief Send a Reject Message to Device. * \param session SCCP Session Pointer * \param backoff_time Time to Backoff before retrying TokenSend */ void sccp_session_tokenReject(sccp_session_t * session, uint32_t backoff_time) { sccp_moo_t *r; REQ(r, RegisterTokenReject); r->msg.RegisterTokenReject.lel_tokenRejWaitTime = htolel(backoff_time); sccp_session_send2(session, r); } /*! * \brief Send a token acknowledgement. * \param session SCCP Session Pointer */ void sccp_session_tokenAck(sccp_session_t * session) { sccp_moo_t *r; REQ(r, RegisterTokenAck); sccp_session_send2(session, r); } /*! * \brief Send an Reject Message to the SPCP Device. * \param session SCCP Session Pointer * \param features Phone Features as Uint32_t */ void sccp_session_tokenRejectSPCP(sccp_session_t * session, uint32_t features) { sccp_moo_t *r; REQ(r, SPCPRegisterTokenReject); r->msg.SPCPRegisterTokenReject.lel_features = htolel(features); sccp_session_send2(session, r); } /*! * \brief Send a token acknowledgement to the SPCP Device. * \param session SCCP Session Pointer * \param features Phone Features as Uint32_t */ void sccp_session_tokenAckSPCP(sccp_session_t * session, uint32_t features) { sccp_moo_t *r; REQ(r, SPCPRegisterTokenAck); r->msg.SPCPRegisterTokenAck.lel_features = htolel(features); sccp_session_send2(session, r); } /*! * \brief Get the in_addr for Specific Device. * \param device SCCP Device Pointer (can be null) * \param type Type in {AF_INET, AF_INET6} * \return In Address as Structure */ struct in_addr *sccp_session_getINaddr(sccp_device_t * device, int type) { sccp_session_t *s = sccp_session_findByDevice(device); if (!s) { return NULL; } switch (type) { case AF_INET: return &s->sin.sin_addr; case AF_INET6: //return &s->sin6.sin6_addr; return NULL; default: return NULL; } } void sccp_session_getSocketAddr(const sccp_device_t * device, struct sockaddr_in *sin) { sccp_session_t *s = sccp_session_findSessionForDevice(device); if (!s) { return; } memcpy(sin, &s->sin, sizeof(struct sockaddr_in)); }
722,259
./chan-sccp-b/src/sccp_conference.c
/*! * \file sccp_conference.c * \brief SCCP Conference for asterisk 10 * \author Marcello Ceschia <marcelloceschia [at] users.sorceforge.net> * \note Reworked, but based on chan_sccp code. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" #include <asterisk/say.h> #ifdef CS_SCCP_CONFERENCE #include "asterisk/bridging.h" #include "asterisk/bridging_features.h" #ifdef HAVE_PBX_BRIDGING_ROLES_H #include "asterisk/bridging_roles.h" #endif #define sccp_conference_release(x) (sccp_conference_t *)sccp_refcount_release(x, __FILE__, __LINE__, __PRETTY_FUNCTION__) #define sccp_conference_retain(x) (sccp_conference_t *)sccp_refcount_retain(x, __FILE__, __LINE__, __PRETTY_FUNCTION__) #define sccp_participant_release(x) (sccp_conference_participant_t *)sccp_refcount_release(x, __FILE__, __LINE__, __PRETTY_FUNCTION__) #define sccp_participant_retain(x) (sccp_conference_participant_t *)sccp_refcount_retain(x, __FILE__, __LINE__, __PRETTY_FUNCTION__) SCCP_FILE_VERSION(__FILE__, "$Revision$") static int lastConferenceID = 99; static const uint32_t appID = APPID_CONFERENCE; SCCP_LIST_HEAD (, sccp_conference_t) conferences; /*!< our list of conferences */ static void *sccp_conference_thread(void *data); void sccp_conference_update_callInfo(sccp_channel_t * channel, PBX_CHANNEL_TYPE * pbxChannel); void __sccp_conference_addParticipant(sccp_conference_t * conference, sccp_channel_t * participantChannel); int playback_to_channel(sccp_conference_participant_t * participant, const char *filename, int say_number); int playback_to_conference(sccp_conference_t * conference, const char *filename, int say_number); sccp_conference_t *sccp_conference_findByID(uint32_t identifier); sccp_conference_participant_t *sccp_conference_participant_findByID(sccp_conference_t * conference, uint32_t identifier); sccp_conference_participant_t *sccp_conference_participant_findByChannel(sccp_conference_t * conference, sccp_channel_t * channel); sccp_conference_participant_t *sccp_conference_participant_findByDevice(sccp_conference_t * conference, sccp_device_t * device); sccp_conference_participant_t *sccp_conference_participant_findByPBXChannel(sccp_conference_t * conference, PBX_CHANNEL_TYPE * channel); void sccp_conference_play_music_on_hold_to_participant(sccp_conference_t * conference, sccp_conference_participant_t * participant, boolean_t start); static sccp_conference_participant_t *sccp_conference_createParticipant(sccp_conference_t * conference); static void sccp_conference_addParticipant_toList(sccp_conference_t * conference, sccp_conference_participant_t * participant); void pbx_builtin_setvar_int_helper(PBX_CHANNEL_TYPE * channel, const char *var_name, int intvalue); static void sccp_conference_connect_bridge_channels_to_participants(sccp_conference_t * conference); static void sccp_conference_update_conflist(sccp_conference_t * conference); void __sccp_conference_hide_list(sccp_conference_participant_t * participant); void sccp_conference_promote_demote_participant(sccp_conference_t * conference, sccp_conference_participant_t * participant, sccp_conference_participant_t * moderator); void sccp_conference_invite_participant(sccp_conference_t * conference, sccp_conference_participant_t * moderator); /*! * \brief Start Conference Module */ void sccp_conference_module_start(void) { SCCP_LIST_HEAD_INIT(&conferences); } /* * \brief Cleanup after conference refcount goes to zero (refcount destroy) */ static void __sccp_conference_destroy(sccp_conference_t * conference) { if (!conference) { return; } if (conference->playback_channel) { sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Destroying conference playback channel\n", conference->id); PBX_CHANNEL_TYPE *underlying_channel = pbx_channel_tech(conference->playback_channel)->bridged_channel(conference->playback_channel, NULL); pbx_hangup(underlying_channel); pbx_hangup(conference->playback_channel); conference->playback_channel = NULL; } sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Destroying conference\n", conference->id); sccp_free(conference->linkedid); pbx_bridge_destroy(conference->bridge); SCCP_LIST_HEAD_DESTROY(&conference->participants); pbx_mutex_destroy(&conference->playback_lock); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_USER, "SCCPConfEnd", "ConfId: %d\r\n", conference->id); } #endif return; } /* * \brief Cleanup after participant refcount goes to zero (refcount destroy) */ static void __sccp_conference_participant_destroy(sccp_conference_participant_t * participant) { sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Destroying participant %d %p\n", participant->conference->id, participant->id, participant); if (participant->isModerator && participant->conference) { participant->conference->num_moderators--; } pbx_bridge_features_cleanup(&participant->features); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfLeave", "ConfId: %d\r\n" "PartId: %d\r\n" "Channel: %s\r\n" "Uniqueid: %s\r\n", participant->conference ? participant->conference->id : -1, participant->id, participant->channel ? PBX(getChannelName) (participant->channel) : "NULL", participant->channel ? PBX(getChannelUniqueID) (participant->channel) : "NULL"); } #endif if (participant->channel) { participant->channel->conference_id = 0; participant->channel->conference_participant_id = 0; participant->channel->conference = participant->channel->conference ? sccp_conference_release(participant->channel->conference) : NULL; participant->channel = sccp_channel_release(participant->channel); } if (participant->device) { participant->device->conferencelist_active = FALSE; participant->device->conference = participant->device->conference ? sccp_conference_release(participant->device->conference) : NULL; participant->device = sccp_device_release(participant->device); } participant->conference = participant->conference ? sccp_conference_release(participant->conference) : NULL; return; } /* ============================================================================================================================ Conference Functions === */ /*! * \brief Create a new conference on sccp_channel_t */ sccp_conference_t *sccp_conference_create(sccp_device_t * device, sccp_channel_t * channel) { sccp_conference_t *conference = NULL; char conferenceIdentifier[REFCOUNT_INDENTIFIER_SIZE]; int conferenceID = ++lastConferenceID; uint32_t bridgeCapabilities; sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCP: Creating new conference SCCPCONF/%04d\n", conferenceID); /** create conference */ snprintf(conferenceIdentifier, REFCOUNT_INDENTIFIER_SIZE, "SCCPCONF/%04d", conferenceID); conference = (sccp_conference_t *) sccp_refcount_object_alloc(sizeof(sccp_conference_t), SCCP_REF_CONFERENCE, conferenceIdentifier, __sccp_conference_destroy); if (NULL == conference) { pbx_log(LOG_ERROR, "SCCPCONF/%04d: cannot alloc memory for new conference.\n", conferenceID); return NULL; } /** initialize new conference */ memset(conference, 0, sizeof(sccp_conference_t)); conference->id = conferenceID; conference->finishing = FALSE; conference->isLocked = FALSE; conference->isOnHold = FALSE; conference->linkedid = strdup(PBX(getChannelLinkedId) (channel)); conference->mute_on_entry = device->conf_mute_on_entry; conference->playback_announcements = device->conf_play_general_announce; sccp_copy_string(conference->playback_language, pbx_channel_language(channel->owner), sizeof(conference->playback_language)); SCCP_LIST_HEAD_INIT(&conference->participants); // bridgeCapabilities = AST_BRIDGE_CAPABILITY_1TO1MIX; /* bridge_multiplexed */ bridgeCapabilities = AST_BRIDGE_CAPABILITY_MULTIMIX; /* bridge_softmix */ #ifdef CS_BRIDGE_CAPABILITY_MULTITHREADED bridgeCapabilities |= AST_BRIDGE_CAPABILITY_MULTITHREADED; /* bridge_softmix */ #endif #ifdef CS_SCCP_VIDEO bridgeCapabilities |= AST_BRIDGE_CAPABILITY_VIDEO; #endif /* using the SMART flag results in issues when removing forgeign participant, because it try to create a new conference and merge into it. Which seems to be more complex then necessary */ conference->bridge = pbx_bridge_new(bridgeCapabilities, 0); /* pbx_bridge_set_internal_sample_rate(conference_bridge->bridge, auto); pbx_bridge_set_mixing_interval(conference->bridge,40); */ SCCP_LIST_LOCK(&conferences); if ((conference = sccp_conference_retain(conference))) { SCCP_LIST_INSERT_HEAD(&conferences, conference, list); } SCCP_LIST_UNLOCK(&conferences); /* init playback lock */ pbx_mutex_init(&conference->playback_lock); /* create new conference moderator channel */ sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCP: Adding moderator channel to SCCPCONF/%04d\n", conferenceID); sccp_conference_participant_t *participant = sccp_conference_createParticipant(conference); if (participant) { conference->num_moderators++; participant->channel = sccp_channel_retain(channel); participant->device = sccp_device_retain(device); participant->conferenceBridgePeer = channel->owner; if (pbx_pthread_create_background(&participant->joinThread, NULL, sccp_conference_thread, participant) < 0) { PBX(requestHangup) (channel->owner); return NULL; } sccp_conference_addParticipant_toList(conference, participant); participant->channel->conference = sccp_conference_retain(conference); participant->channel->conference_id = conference->id; participant->channel->conference_participant_id = participant->id; participant->playback_announcements = device->conf_play_part_announce; PBX(setChannelLinkedId) (participant->channel, conference->linkedid); sccp_conference_update_callInfo(channel, participant->conferenceBridgePeer); participant->isModerator = TRUE; device->conferencelist_active = TRUE; // Activate conflist sccp_softkey_setSoftkeyState(device, KEYMODE_CONNCONF, SKINNY_LBL_JOIN, TRUE); sccp_softkey_setSoftkeyState(device, KEYMODE_CONNTRANS, SKINNY_LBL_JOIN, TRUE); pbx_builtin_setvar_int_helper(channel->owner, "__SCCP_CONFERENCE_ID", conference->id); pbx_builtin_setvar_int_helper(channel->owner, "__SCCP_CONFERENCE_PARTICIPANT_ID", participant->id); sccp_indicate(device, channel, SCCP_CHANNELSTATE_CONNECTEDCONFERENCE); sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Added Moderator %d (Channel: %s)\n", conference->id, participant->id, pbx_channel_name(participant->conferenceBridgePeer)); } /** we return the pointer, so do not release conference (should be retained in d->conference or rather l->conference/c->conference. d->conference limits us to one conference per phone */ #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_USER, "SCCPConfStart", "ConfId: %d\r\n" "SCCPDevice: %s\r\n", conferenceID, DEV_ID_LOG(device)); } #endif conference = sccp_conference_retain(conference); // return retained return conference; } /*! * \brief Generic Function to create a new participant */ static sccp_conference_participant_t *sccp_conference_createParticipant(sccp_conference_t * conference) { if (!conference) { pbx_log(LOG_ERROR, "SCCPCONF: no conference / participantChannel provided.\n"); return NULL; } sccp_conference_participant_t *participant = NULL; int participantID = conference->participants.size + 1; char participantIdentifier[REFCOUNT_INDENTIFIER_SIZE]; sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Creating new conference-participant %d\n", conference->id, participantID); snprintf(participantIdentifier, REFCOUNT_INDENTIFIER_SIZE, "SCCPCONF/%04d/PART/%04d", conference->id, participantID); participant = (sccp_conference_participant_t *) sccp_refcount_object_alloc(sizeof(sccp_conference_participant_t), SCCP_REF_PARTICIPANT, participantIdentifier, __sccp_conference_participant_destroy); if (!participant) { pbx_log(LOG_ERROR, "SCCPCONF/%04d: cannot alloc memory for new conference participant.\n", conference->id); participant = sccp_participant_release(participant); return NULL; } pbx_bridge_features_init(&participant->features); participant->id = participantID; participant->conference = sccp_conference_retain(conference); participant->conferenceBridgePeer = NULL; participant->playback_announcements = conference->playback_announcements; // default participant->onMusicOnHold = FALSE; return participant; } static void sccp_conference_connect_bridge_channels_to_participants(sccp_conference_t * conference) { struct ast_bridge *bridge = conference->bridge; struct ast_bridge_channel *bridge_channel = NULL; sccp_conference_participant_t *participant = NULL; #ifndef CS_BRIDGE_BASE_NEW sccp_log((DEBUGCAT_HIGH | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Searching Bridge Channel(num_channels: %d).\n", conference->id, conference->bridge->num); #else sccp_log((DEBUGCAT_HIGH | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Searching Bridge Channel(num_channels: %d).\n", conference->id, conference->bridge->num_channels); #endif ao2_lock(bridge); AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) { sccp_log((DEBUGCAT_HIGH | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Bridge Channel %p.\n", conference->id, bridge_channel); if ((participant = sccp_conference_participant_findByPBXChannel(conference, bridge_channel->chan))) { if (conference->mute_on_entry) { participant->features.mute = 1; } sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Connecting Bridge Channel %p to Participant %d.\n", conference->id, bridge_channel, participant->id); participant->bridge_channel = bridge_channel; participant = sccp_participant_release(participant); } } ao2_unlock(bridge); } /*! * \brief Allocate a temp channel(participant->conferenceBridgePeer) to take the place of the participant_ast_channel in the old channel bridge (masquerade). * The resulting "bridge-free" participant_ast_channel can then be inserted into the conference * The temp channel will be hungup */ static boolean_t sccp_conference_masqueradeChannel(PBX_CHANNEL_TYPE * participant_ast_channel, sccp_conference_t * conference, sccp_conference_participant_t * participant) { if (participant) { if (!(PBX(allocTempPBXChannel) (participant_ast_channel, &participant->conferenceBridgePeer))) { pbx_log(LOG_ERROR, "SCCPCONF/%04d: Creation of Temp Channel Failed. Exiting.\n", conference->id); return FALSE; } if (!PBX(masqueradeHelper) (participant_ast_channel, participant->conferenceBridgePeer)) { pbx_log(LOG_ERROR, "SCCPCONF/%04d: Failed to Masquerade TempChannel.\n", conference->id); PBX(requestHangup) (participant->conferenceBridgePeer); //participant_ast_channel = pbx_channel_unref(participant_ast_channel); return FALSE; } if (pbx_pthread_create_background(&participant->joinThread, NULL, sccp_conference_thread, participant) < 0) { PBX(requestHangup) (participant->conferenceBridgePeer); return FALSE; } sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Added Participant %d (Channel: %s)\n", conference->id, participant->id, pbx_channel_name(participant->conferenceBridgePeer)); return TRUE; } return FALSE; } /*! * \brief Add the Participant to conference->participants */ static void sccp_conference_addParticipant_toList(sccp_conference_t * conference, sccp_conference_participant_t * participant) { // add to participant list sccp_conference_participant_t *tmpParticipant = NULL; SCCP_LIST_LOCK(&conference->participants); if ((tmpParticipant = sccp_participant_retain(participant))) { SCCP_LIST_INSERT_TAIL(&conference->participants, tmpParticipant, list); } SCCP_LIST_UNLOCK(&conference->participants); } /*! * \brief Update the callinfo on the sccp channel */ void sccp_conference_update_callInfo(sccp_channel_t * channel, PBX_CHANNEL_TYPE * pbxChannel) { char confstr[StationMaxNameSize] = ""; snprintf(confstr, StationMaxNameSize, "Conference %d", channel->conference_id); switch (channel->calltype) { case SKINNY_CALLTYPE_INBOUND: sccp_copy_string(channel->callInfo.originalCallingPartyName, channel->callInfo.callingPartyName, sizeof(channel->callInfo.originalCallingPartyName)); channel->callInfo.originalCallingParty_valid = 1; sccp_copy_string(channel->callInfo.callingPartyName, confstr, sizeof(channel->callInfo.callingPartyName)); channel->callInfo.callingParty_valid = 1; break; case SKINNY_CALLTYPE_OUTBOUND: case SKINNY_CALLTYPE_FORWARD: sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.calledPartyName, sizeof(channel->callInfo.originalCallingPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.calledPartyName, confstr, sizeof(channel->callInfo.calledPartyName)); channel->callInfo.calledParty_valid = 1; break; } /* this is just a workaround to update sip and other channels also -MC */ /** @todo we should fix this workaround -MC */ #if ASTERISK_VERSION_GROUP > 106 struct ast_party_connected_line connected; struct ast_set_party_connected_line update_connected; memset(&update_connected, 0, sizeof(update_connected)); ast_party_connected_line_init(&connected); update_connected.id.number = 1; connected.id.number.valid = 1; connected.id.number.str = confstr; connected.id.number.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; update_connected.id.name = 1; connected.id.name.valid = 1; connected.id.name.str = confstr; connected.id.name.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; #if ASTERISK_VERSION_GROUP > 110 ast_set_party_id_all(&update_connected.priv); #endif connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER; if (pbxChannel) { ast_channel_set_connected_line(pbxChannel, &connected, &update_connected); } #endif PBX(set_connected_line) (channel, confstr, confstr, AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER); } /*! * \brief Used to set the ConferenceId and ParticipantId on the pbx channel for outside use * \todo Has to be moved to pbx_impl */ void pbx_builtin_setvar_int_helper(PBX_CHANNEL_TYPE * channel, const char *var_name, int intvalue) { char valuestr[8] = ""; snprintf(valuestr, 8, "%d", intvalue); pbx_builtin_setvar_helper(channel, var_name, valuestr); } /*! * \brief Take the channel bridge peer and add it to the conference. (used for the bridge peer channels which are on hold on the moderators phone) */ #if HAVE_PBX_CEL_H #include <asterisk/cel.h> #endif void sccp_conference_addParticipatingChannel(sccp_conference_t * conference, sccp_channel_t * originalSCCPChannel, PBX_CHANNEL_TYPE * pbxChannel) { sccp_channel_t *channel = NULL; if (!conference->isLocked) { sccp_conference_participant_t *participant = sccp_conference_createParticipant(conference); if (participant) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Adding participant %d (Channel %s)\n", conference->id, participant->id, pbx_channel_name(pbxChannel)); sccp_device_t *device = NULL; sccp_conference_update_callInfo(originalSCCPChannel, pbxChannel); // Update CallerId on originalChannel before masquerade // if peer is sccp then retain peer_sccp_channel channel = get_sccp_channel_from_pbx_channel(pbxChannel); if (channel && (device = sccp_channel_getDevice_retained(channel))) { participant->playback_announcements = device->conf_play_part_announce; PBX(setChannelLinkedId) (channel, conference->linkedid); } else { participant->playback_announcements = conference->playback_announcements; } if (sccp_conference_masqueradeChannel(pbxChannel, conference, participant)) { sccp_conference_addParticipant_toList(conference, participant); if (channel && device) { // SCCP Channel participant->channel = sccp_channel_retain(channel); participant->device = sccp_device_retain(device); participant->channel->conference = sccp_conference_retain(conference); participant->channel->conference_id = conference->id; participant->channel->conference_participant_id = participant->id; participant->playback_announcements = device->conf_play_part_announce; sccp_indicate(device, channel, SCCP_CHANNELSTATE_CONNECTEDCONFERENCE); // device->conferencelist_active = TRUE; // Activate conflist on all sccp participants } else { // PBX Channel PBX(setPBXChannelLinkedId) (participant->conferenceBridgePeer, conference->linkedid); } pbx_builtin_setvar_int_helper(participant->conferenceBridgePeer, "__SCCP_CONFERENCE_ID", conference->id); pbx_builtin_setvar_int_helper(participant->conferenceBridgePeer, "__SCCP_CONFERENCE_PARTICIPANT_ID", participant->id); #if ASTERISK_VERSION_GROUP>106 pbx_indicate(participant->conferenceBridgePeer, AST_CONTROL_CONNECTED_LINE); #endif } else { // Masq Error channel = channel ? sccp_channel_release(channel) : NULL; participant = sccp_participant_release(participant); } channel = channel ? sccp_channel_release(channel) : NULL; device = device ? sccp_device_release(device) : NULL; } } else { sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Conference is locked. Participant Denied.\n", conference->id); if (pbxChannel) { pbx_stream_and_wait(pbxChannel, "conf-locked", ""); } } } /*! * \brief Remove a specific participant from a conference */ static void sccp_conference_removeParticipant(sccp_conference_t * conference, sccp_conference_participant_t * participant) { sccp_conference_participant_t *tmp_participant = NULL; sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Removing Participant %d.\n", conference->id, participant->id); SCCP_LIST_LOCK(&conference->participants); tmp_participant = SCCP_LIST_REMOVE(&conference->participants, participant, list); tmp_participant = sccp_participant_release(tmp_participant); SCCP_LIST_UNLOCK(&conference->participants); /* if last moderator is leaving, end conference */ if (participant->isModerator && conference->num_moderators == 1 && !conference->finishing) { sccp_conference_end(conference); } else if (!participant->isModerator && !conference->finishing) { playback_to_conference(conference, NULL, participant->id); playback_to_conference(conference, "conf-hasleft", -1); } sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Hanging up Participant %d (Channel: %s)\n", conference->id, participant->id, pbx_channel_name(participant->conferenceBridgePeer)); pbx_clear_flag(pbx_channel_flags(participant->conferenceBridgePeer), AST_FLAG_BLOCKING); pbx_hangup(participant->conferenceBridgePeer); participant = sccp_participant_release(participant); /* Conference end if the number of participants == 1 */ if (SCCP_LIST_GETSIZE(conference->participants) == 1 && !conference->finishing) { sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: There are no conference participants left, Ending conference.\n", conference->id); sccp_conference_end(conference); } sccp_conference_update_conflist(conference); } /*! * \brief Every participant is running one of the threads as long as they are joined to the conference * When the thread is cancelled they will clean-up after them selves using the removeParticipant function */ static void *sccp_conference_thread(void *data) { sccp_conference_participant_t *participant = NULL; /** cast data to conference_participant */ participant = (sccp_conference_participant_t *) data; if ((participant = sccp_participant_retain(participant))) { sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: entering join thread.\n", participant->conference->id); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfEntered", "ConfId: %d\r\n" "PartId: %d\r\n" "Channel: %s\r\n" "Uniqueid: %s\r\n", participant->conference->id, participant->id, participant->channel ? PBX(getChannelName) (participant->channel) : "NULL", participant->channel ? PBX(getChannelUniqueID) (participant->channel) : "NULL"); } #endif // Join the bridge sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Entering pbx_bridge_join: %s as %d\n", participant->conference->id, pbx_channel_name(participant->conferenceBridgePeer), participant->id); pbx_bridge_join(participant->conference->bridge, participant->conferenceBridgePeer, NULL, &participant->features, NULL); sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Leaving pbx_bridge_join: %s as %d\n", participant->conference->id, pbx_channel_name(participant->conferenceBridgePeer), participant->id); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfLeft", "ConfId: %d\r\n" "PartId: %d\r\n" "Channel: %s\r\n" "Uniqueid: %s\r\n", participant->conference->id, participant->id, participant->channel ? PBX(getChannelName) (participant->channel) : "NULL", participant->channel ? PBX(getChannelUniqueID) (participant->channel) : "NULL"); } #endif if (participant->channel && participant->device) { __sccp_conference_hide_list(participant); } participant->pendingRemoval = TRUE; sccp_conference_removeParticipant(participant->conference, participant); participant->joinThread = AST_PTHREADT_NULL; participant = sccp_participant_release(participant); } return NULL; } /*! * \brief This function is called when the minimal number of occupants of a confernce is reached or when the last moderator hangs-up */ void sccp_conference_start(sccp_conference_t * conference) { sccp_conference_update_conflist(conference); //playback_to_conference(conference, "conf-enteringno", -1); //playback_to_conference(conference, NULL, conference->id); playback_to_conference(conference, "conf-placeintoconf", -1); sccp_conference_connect_bridge_channels_to_participants(conference); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfStarted", "ConfId: %d\r\n", conference->id); } #endif } void sccp_conference_update(sccp_conference_t * conference) { sccp_conference_update_conflist(conference); sccp_conference_connect_bridge_channels_to_participants(conference); } /*! * \brief This function is called when the minimal number of occupants of a confernce is reached or when the last moderator hangs-up */ void sccp_conference_end(sccp_conference_t * conference) { sccp_conference_participant_t *participant = NULL; sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Ending Conference.\n", conference->id); SCCP_LIST_LOCK(&conferences); conference->finishing = TRUE; SCCP_LIST_UNLOCK(&conferences); playback_to_conference(conference, "conf-leaderhasleft", -1); /* remove remaining participants / moderators */ SCCP_LIST_LOCK(&conference->participants); if (SCCP_LIST_GETSIZE(conference->participants) > 0) { // remove the participants first SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (!participant->isModerator) { pbx_bridge_remove(participant->conference->bridge, participant->conferenceBridgePeer); } } // and then remove the moderators SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->isModerator) { pbx_bridge_remove(participant->conference->bridge, participant->conferenceBridgePeer); } } } SCCP_LIST_UNLOCK(&conference->participants); /* remove conference */ sccp_conference_t *tmp_conference = NULL; SCCP_LIST_LOCK(&conferences); tmp_conference = SCCP_LIST_REMOVE(&conferences, conference, list); tmp_conference = sccp_conference_release(tmp_conference); SCCP_LIST_UNLOCK(&conferences); sccp_log((DEBUGCAT_CORE | DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Conference Ended.\n", conference->id); conference = sccp_conference_release(conference); } /* ========================================================================================================================== Conference Hold/Resume === */ /*! * \brief Handle putting on hold a conference */ void sccp_conference_hold(sccp_conference_t * conference) { sccp_conference_participant_t *participant = NULL; sccp_log(DEBUGCAT_CONFERENCE) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Putting conference on hold.\n", conference->id); if (!conference) { return; } /* play music on hold to participants, if there is no moderator, currently active to the conference */ if (!conference->isOnHold && conference->num_moderators == 1) { SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->isModerator == FALSE) { sccp_conference_play_music_on_hold_to_participant(conference, participant, TRUE); } } SCCP_LIST_UNLOCK(&conference->participants); conference->isOnHold = TRUE; } } /*! * \brief Handle resuming a conference */ void sccp_conference_resume(sccp_conference_t * conference) { sccp_conference_participant_t *participant = NULL; sccp_log(DEBUGCAT_CONFERENCE) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Resuming conference.\n", conference->id); if (!conference) { return; } /* stop play music on hold to participants. */ if (conference->isOnHold) { SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->isModerator == FALSE) { sccp_conference_play_music_on_hold_to_participant(conference, participant, FALSE); } } SCCP_LIST_UNLOCK(&conference->participants); conference->isOnHold = TRUE; } } /* =============================================================================================================== Playback to Conference/Participant === */ /*! * \brief This helper-function is used to playback either a file or number sequence */ static int stream_and_wait(PBX_CHANNEL_TYPE * playback_channel, const char *filename, int say_number) { if (!sccp_strlen_zero(filename) && !pbx_fileexists(filename, NULL, NULL)) { pbx_log(LOG_WARNING, "File %s does not exists in any format\n", !sccp_strlen_zero(filename) ? filename : "<unknown>"); return 0; } if (playback_channel) { if (!sccp_strlen_zero(filename)) { sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "Playing '%s' to Conference\n", filename); pbx_stream_and_wait(playback_channel, filename, ""); } else if (say_number >= 0) { sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "Saying '%d' to Conference\n", say_number); pbx_say_number(playback_channel, say_number, "", pbx_channel_language(playback_channel), NULL); } } return 1; } /*! * \brief This function is used to playback either a file or number sequence to a specific participant only */ int playback_to_channel(sccp_conference_participant_t * participant, const char *filename, int say_number) { int res = 0; if (!participant->playback_announcements) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Playback for participant %d suppressed\n", participant->conference->id, participant->id); return 1; } if (participant->bridge_channel) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Playback %s %d for participant %d\n", participant->conference->id, filename, say_number, participant->id); participant->bridge_channel->suspended = 1; ast_bridge_change_state(participant->bridge_channel, AST_BRIDGE_CHANNEL_STATE_WAIT); if (stream_and_wait(participant->bridge_channel->chan, filename, say_number)) { res = 1; } else { pbx_log(LOG_WARNING, "Failed to play %s or '%d'!\n", filename, say_number); } participant->bridge_channel->suspended = 0; ast_bridge_change_state(participant->bridge_channel, AST_BRIDGE_CHANNEL_STATE_WAIT); } else { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: No bridge channel for playback\n", participant->conference->id); } return res; } /*! * \brief This function is used to playback either a file or number sequence to all conference participants. Used for announcing * The playback channel is created once, and imparted on the conference when necessary on follow-up calls */ int playback_to_conference(sccp_conference_t * conference, const char *filename, int say_number) { PBX_CHANNEL_TYPE *underlying_channel; int res = 0; if (!conference->playback_announcements) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Playback on conference suppressed\n", conference->id); return 1; } pbx_mutex_lock(&conference->playback_lock); if (!sccp_strlen_zero(filename) && !pbx_fileexists(filename, NULL, NULL)) { pbx_log(LOG_WARNING, "File %s does not exists in any format\n", !sccp_strlen_zero(filename) ? filename : "<unknown>"); return 0; } if (!(conference->playback_channel)) { if (!(conference->playback_channel = PBX(requestForeignChannel) ("Bridge", AST_FORMAT_SLINEAR, NULL, ""))) { pbx_mutex_unlock(&conference->playback_lock); return 0; } if (!sccp_strlen_zero(conference->playback_language)) { PBX(set_language) (conference->playback_channel, conference->playback_language); } pbx_channel_set_bridge(conference->playback_channel, conference->bridge); if (ast_call(conference->playback_channel, "", 0)) { pbx_hangup(conference->playback_channel); conference->playback_channel = NULL; pbx_mutex_unlock(&conference->playback_lock); return 0; } sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Created Playback Channel\n", conference->id); underlying_channel = pbx_channel_tech(conference->playback_channel)->bridged_channel(conference->playback_channel, NULL); // Update CDR to prevent nasty ast warning when hanging up this channel (confbridge does not set the cdr correctly) pbx_cdr_start(pbx_channel_cdr(conference->playback_channel)); #if ASTERISK_VERSION_GROUP < 110 conference->playback_channel->cdr->answer = ast_tvnow(); underlying_channel->cdr->answer = ast_tvnow(); #endif pbx_cdr_update(conference->playback_channel); } else { /* Channel was already available so we just need to add it back into the bridge */ underlying_channel = pbx_channel_tech(conference->playback_channel)->bridged_channel(conference->playback_channel, NULL); sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Attaching '%s' to Conference\n", conference->id, pbx_channel_name(underlying_channel)); pbx_bridge_impart(conference->bridge, underlying_channel, NULL, NULL, 0); } if (!stream_and_wait(conference->playback_channel, filename, say_number)) { ast_log(LOG_WARNING, "Failed to play %s or '%d'!\n", filename, say_number); } else { res = 1; } sccp_log((DEBUGCAT_CONFERENCE + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Detaching '%s' from Conference\n", conference->id, pbx_channel_name(underlying_channel)); pbx_bridge_depart(conference->bridge, underlying_channel); pbx_mutex_unlock(&conference->playback_lock); return res; } /* ============================================================================================================================= List Find Functions === */ /*! * \brief Find conference by ID */ sccp_conference_t *sccp_conference_findByID(uint32_t identifier) { sccp_conference_t *conference = NULL; if (identifier == 0) { return NULL; } SCCP_LIST_LOCK(&conferences); SCCP_LIST_TRAVERSE(&conferences, conference, list) { if (conference->id == identifier) { conference = sccp_conference_retain(conference); break; } } SCCP_LIST_UNLOCK(&conferences); return conference; } /*! * \brief Find participant by ID */ sccp_conference_participant_t *sccp_conference_participant_findByID(sccp_conference_t * conference, uint32_t identifier) { sccp_conference_participant_t *participant = NULL; if (!conference || identifier == 0) { return NULL; } SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->id == identifier) { participant = sccp_participant_retain(participant); break; } } SCCP_LIST_UNLOCK(&conference->participants); return participant; } /*! * \brief Find participant by sccp channel */ sccp_conference_participant_t *sccp_conference_participant_findByChannel(sccp_conference_t * conference, sccp_channel_t * channel) { sccp_conference_participant_t *participant = NULL; if (!conference || !channel) { return NULL; } SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->channel == channel) { participant = sccp_participant_retain(participant); break; } } SCCP_LIST_UNLOCK(&conference->participants); return participant; } /*! * \brief Find participant by sccp device */ sccp_conference_participant_t *sccp_conference_participant_findByDevice(sccp_conference_t * conference, sccp_device_t * device) { sccp_conference_participant_t *participant = NULL; if (!conference || !device) { return NULL; } SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->device == device) { participant = sccp_participant_retain(participant); break; } } SCCP_LIST_UNLOCK(&conference->participants); return participant; } /*! * \brief Find participant by PBX channel */ sccp_conference_participant_t *sccp_conference_participant_findByPBXChannel(sccp_conference_t * conference, PBX_CHANNEL_TYPE * channel) { sccp_conference_participant_t *participant = NULL; if (!conference || !channel) { return NULL; } SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->conferenceBridgePeer == channel) { participant = sccp_participant_retain(participant); break; } } SCCP_LIST_UNLOCK(&conference->participants); return participant; } /* ======================================================================================================================== ConfList (XML) Functions === */ /*! * \brief Show ConfList * * Cisco URL reference * UserData:INTEGER:STRING * UserDataSoftKey:STRING:INTEGER:STRING * UserCallDataSoftKey:STRING:INTEGER0:INTEGER1:INTEGER2:INTEGER3:STRING * UserCallData:INTEGER0:INTEGER1:INTEGER2:INTEGER3:STRING */ void sccp_conference_show_list(sccp_conference_t * conference, sccp_channel_t * c) { int use_icon = 0; sccp_conference_participant_t *participant = NULL; sccp_channel_t *channel = NULL; if (!conference) { pbx_log(LOG_WARNING, "SCCPCONF: No conference available to display list for\n"); goto exit_function; } if (!(channel = sccp_channel_retain(c))) { // only send this list to sccp phones pbx_log(LOG_WARNING, "SCCPCONF/%04d: No channel available to display conferencelist for\n", conference->id); goto exit_function; } if (!(participant = sccp_conference_participant_findByChannel(conference, channel))) { pbx_log(LOG_WARNING, "SCCPCONF/%04d: Channel %s is not a participant in this conference\n", conference->id, pbx_channel_name(channel->owner)); goto exit_function; } if (conference->participants.size < 1) { pbx_log(LOG_WARNING, "SCCPCONF/%04d: Conference does not have enough participants\n", conference->id); goto exit_function; } if (participant->device) { participant->device->conferencelist_active = TRUE; if (!participant->callReference) { participant->callReference = channel->callid; participant->lineInstance = conference->id; #if ASTERISK_VERSION_NUMBER >= 10400 participant->transactionID = pbx_random() % 1000; #else participant->transactionID = random() % 1000; #endif } char xmlStr[2048] = ""; char xmlTmp[512] = ""; // sprintf(xmlTmp, "<CiscoIPPhoneIconMenu appId=\"%d\" onAppFocusLost=\"\" onAppFocusGained=\"\" onAppClosed=\"\">", appID); if (participant->device->protocolversion >= 17) { sprintf(xmlTmp, "<CiscoIPPhoneIconFileMenu appId=\"%d\">", appID); strcat(xmlStr, xmlTmp); if (conference->isLocked) { sprintf(xmlTmp, "<Title IconIndex=\"5\">Conference %d</Title>\n", conference->id); } else { sprintf(xmlTmp, "<Title IconIndex=\"4\">Conference %d</Title>\n", conference->id); } strcat(xmlStr, xmlTmp); } else { sprintf(xmlTmp, "<CiscoIPPhoneIconMenu>"); strcat(xmlStr, xmlTmp); sprintf(xmlTmp, "<Title>Conference %d</Title>\n", conference->id); strcat(xmlStr, xmlTmp); } strcat(xmlStr, "<Prompt>Make Your Selection</Prompt>\n"); // MenuItems sccp_conference_participant_t *part = NULL; SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, part, list) { if (part->pendingRemoval) continue; strcat(xmlStr, "<MenuItem>"); if (part->isModerator) use_icon = 0; else use_icon = 2; if (part->features.mute) { ++use_icon; } strcat(xmlStr, "<IconIndex>"); sprintf(xmlTmp, "%d", use_icon); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</IconIndex>"); strcat(xmlStr, "<Name>"); if (part->channel != NULL) { switch (part->channel->calltype) { case SKINNY_CALLTYPE_INBOUND: sprintf(xmlTmp, "%d:%s (%s)", part->id, part->channel->callInfo.calledPartyName, part->channel->callInfo.calledPartyNumber); break; case SKINNY_CALLTYPE_OUTBOUND: sprintf(xmlTmp, "%d:%s (%s)", part->id, part->channel->callInfo.callingPartyName, part->channel->callInfo.callingPartyNumber); break; case SKINNY_CALLTYPE_FORWARD: sprintf(xmlTmp, "%d:%s (%s)", part->id, part->channel->callInfo.originalCallingPartyName, part->channel->callInfo.originalCallingPartyName); break; } strcat(xmlStr, xmlTmp); } else { // Asterisk Channel #if ASTERISK_VERSION_GROUP > 110 sprintf(xmlTmp, "%d:%s (%s)", part->id, ast_channel_caller(part->conferenceBridgePeer)->id.name.str, ast_channel_caller(part->conferenceBridgePeer)->id.number.str); #elif ASTERISK_VERSION_GROUP > 106 sprintf(xmlTmp, "%d:%s (%s)", part->id, part->conferenceBridgePeer->caller.id.name.str, part->conferenceBridgePeer->caller.id.number.str); #else sprintf(xmlTmp, "%d:%s (%s)", part->id, part->conferenceBridgePeer->cid.cid_name, part->conferenceBridgePeer->cid.cid_num); #endif strcat(xmlStr, xmlTmp); } strcat(xmlStr, "</Name>"); sprintf(xmlTmp, "<URL>UserCallData:%d:%d:%d:%d:%d</URL>", appID, participant->lineInstance, participant->callReference, participant->transactionID, part->id); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</MenuItem>\n"); } SCCP_LIST_UNLOCK(&conference->participants); // SoftKeys if (participant->isModerator) { strcat(xmlStr, "<SoftKeyItem>"); strcat(xmlStr, "<Name>EndConf</Name>"); strcat(xmlStr, "<Position>1</Position>"); // sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:ENDCONF/%d/%d/%d/</URL>", 1, appID, participant->lineInstance, participant->transactionID); sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:ENDCONF/%d</URL>", 1, participant->transactionID); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</SoftKeyItem>\n"); strcat(xmlStr, "<SoftKeyItem>"); strcat(xmlStr, "<Name>Mute</Name>"); strcat(xmlStr, "<Position>2</Position>"); // sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:MUTE/%d/%d/%d/</URL>", 2, appID, participant->lineInstance, participant->transactionID); sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:MUTE/%d</URL>", 2, participant->transactionID); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</SoftKeyItem>\n"); strcat(xmlStr, "<SoftKeyItem>"); strcat(xmlStr, "<Name>Kick</Name>"); strcat(xmlStr, "<Position>3</Position>"); // sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:KICK/%d/%d/%d/</URL>", 3, appID, participant->lineInstance, participant->transactionID); sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:KICK/%d</URL>", 3, participant->transactionID); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</SoftKeyItem>\n"); } strcat(xmlStr, "<SoftKeyItem>"); strcat(xmlStr, "<Name>Exit</Name>"); strcat(xmlStr, "<Position>4</Position>"); strcat(xmlStr, "<URL>SoftKey:Exit</URL>"); strcat(xmlStr, "</SoftKeyItem>\n"); if (participant->isModerator) { strcat(xmlStr, "<SoftKeyItem>"); strcat(xmlStr, "<Name>Moderate</Name>"); strcat(xmlStr, "<Position>5</Position>"); sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:MODERATE/%d/%d/%d/</URL>", 1, appID, participant->lineInstance, participant->transactionID); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</SoftKeyItem>\n"); #if CS_EXPERIMENTAL strcat(xmlStr, "<SoftKeyItem>"); strcat(xmlStr, "<Name>Invite</Name>"); strcat(xmlStr, "<Position>6</Position>"); sprintf(xmlTmp, "<URL>UserDataSoftKey:Select:%d:INVITE/%d/%d/%d/</URL>", 1, appID, participant->lineInstance, participant->transactionID); strcat(xmlStr, xmlTmp); strcat(xmlStr, "</SoftKeyItem>\n"); #endif } // CiscoIPPhoneIconMenu Icons if (participant->device->protocolversion >= 17) { strcat(xmlStr, "<IconItem><Index>0</Index><URL>Resource:Icon.Connected</URL></IconItem>"); // moderator strcat(xmlStr, "<IconItem><Index>1</Index><URL>Resource:AnimatedIcon.Hold</URL></IconItem>"); // muted moderator strcat(xmlStr, "<IconItem><Index>2</Index><URL>Resource:AnimatedIcon.StreamRxTx</URL></IconItem>"); // participant strcat(xmlStr, "<IconItem><Index>3</Index><URL>Resource:AnimatedIcon.Hold</URL></IconItem>"); // muted participant strcat(xmlStr, "<IconItem><Index>4</Index><URL>Resource:Icon.Speaker</URL></IconItem>"); // unlocked conference strcat(xmlStr, "<IconItem><Index>5</Index><URL>Resource:Icon.SecureCall</URL></IconItem>\n"); // locked conference } else { strcat(xmlStr, "<IconItem><Index>0</Index><Height>10</Height><Width>16</Width><Depth>2</Depth><Data>000F0000C03F3000C03FF000C03FF003000FF00FFCFFF30FFCFFF303CC3FF300CC3F330000000000</Data></IconItem>"); // moderator strcat(xmlStr, "<IconItem><Index>1</Index><Height>10</Height><Width>16</Width><Depth>2</Depth><Data>000F0000C03FF03CC03FF03CC03FF03C000FF03CFCFFF33CFCFFF33CCC3FF33CCC3FF33C00000000</Data></IconItem>"); // muted moderator strcat(xmlStr, "<IconItem><Index>2</Index><Height>10</Height><Width>16</Width><Depth>2</Depth><Data>000F0000C0303000C030F000C030F003000FF00FFCF0F30F0C00F303CC30F300CC30330000000000</Data></IconItem>"); // participant strcat(xmlStr, "<IconItem><Index>3</Index><Height>10</Height><Width>16</Width><Depth>2</Depth><Data>000F0000C030F03CC030F03CC030F03C000FF03CFCF0F33C0C00F33CCC30F33CCC30F33C00000000</Data></IconItem>\n"); // muted participant } if (participant->device->protocolversion >= 17) { strcat(xmlStr, "</CiscoIPPhoneIconFileMenu>\n"); } else { strcat(xmlStr, "</CiscoIPPhoneIconMenu>\n"); } sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: ShowList appID %d, lineInstance %d, callReference %d, transactionID %d\n", conference->id, appID, participant->callReference, participant->lineInstance, participant->transactionID); sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: XML-message:\n%s\n", conference->id, xmlStr); participant->device->protocol->sendUserToDeviceDataVersionMessage(participant->device, appID, participant->callReference, participant->lineInstance, participant->transactionID, xmlStr, 2); } exit_function: participant = participant ? sccp_participant_release(participant) : NULL; channel = channel ? sccp_channel_release(channel) : NULL; } /*! * \brief Hide ConfList */ void __sccp_conference_hide_list(sccp_conference_participant_t * participant) { if (participant->channel && participant->device) { if (participant->device->conferencelist_active) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: Hide Conf List for participant: %d\n", participant->conference->id, participant->id); char *data = "<CiscoIPPhoneExecute><ExecuteItem Priority=\"0\" URL=\"App:Close:0\"/></CiscoIPPhoneExecute>"; participant->device->protocol->sendUserToDeviceDataVersionMessage(participant->device, appID, participant->callReference, participant->lineInstance, participant->transactionID, data, 2); participant->device->conferencelist_active = FALSE; } } } void sccp_conference_hide_list_ByDevice(sccp_device_t * device) { sccp_conference_t *conference = NULL; sccp_conference_participant_t *participant = NULL; SCCP_LIST_LOCK(&conferences); SCCP_LIST_TRAVERSE(&conferences, conference, list) { if (device && (participant = sccp_conference_participant_findByDevice(conference, device))) { if (participant->channel && participant->device) { __sccp_conference_hide_list(participant); } participant = sccp_participant_release(participant); } } SCCP_LIST_UNLOCK(&conferences); } /*! * \brief Update ConfList on all phones displaying the list */ static void sccp_conference_update_conflist(sccp_conference_t * conference) { sccp_conference_participant_t *participant = NULL; if (!conference) { return; } SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { if (participant->channel && participant->device && participant->device->conferencelist_active) { sccp_conference_show_list(conference, participant->channel); } } SCCP_LIST_UNLOCK(&conference->participants); } /*! * \brief Handle ButtonPresses from ConfList */ void sccp_conference_handle_device_to_user(sccp_device_t * d, uint32_t callReference, uint32_t transactionID, uint32_t conferenceID, uint32_t participantID) { sccp_conference_t *conference = NULL; sccp_conference_participant_t *participant = NULL; sccp_conference_participant_t *moderator = NULL; if (d && d->dtu_softkey.transactionID == transactionID) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_4 "%s: Handle DTU SoftKey Button Press for CallID %d, Transaction %d, Conference %d, Participant:%d, Action %s\n", d->id, callReference, transactionID, conferenceID, participantID, d->dtu_softkey.action); if (!(conference = sccp_conference_findByID(conferenceID))) { pbx_log(LOG_WARNING, "%s: Conference not found\n", DEV_ID_LOG(d)); goto EXIT; } if (!(participant = sccp_conference_participant_findByID(conference, participantID))) { pbx_log(LOG_WARNING, "SCCPCONF/%04d: %s: Participant not found\n", conference->id, DEV_ID_LOG(d)); goto EXIT; } if (!(moderator = sccp_conference_participant_findByDevice(conference, d))) { pbx_log(LOG_WARNING, "SCCPCONF/%04d: %s: Moderator not found\n", conference->id, DEV_ID_LOG(d)); goto EXIT; } sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: DTU Softkey Executing Action %s (%s)\n", conference->id, d->dtu_softkey.action, DEV_ID_LOG(d)); if (!strcmp(d->dtu_softkey.action, "ENDCONF")) { sccp_conference_end(conference); } else if (!strcmp(d->dtu_softkey.action, "MUTE")) { sccp_conference_toggle_mute_participant(conference, participant); } else if (!strcmp(d->dtu_softkey.action, "KICK")) { if (participant->isModerator) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Since wenn du we kick ourselves ? You've got issues! (%s)\n", conference->id, DEV_ID_LOG(d)); sccp_dev_set_message(d, "cannot kick yourself", 5, FALSE, FALSE); } else { sccp_conference_kick_participant(conference, participant); } } else if (!strcmp(d->dtu_softkey.action, "EXIT")) { d->conferencelist_active = FALSE; #if CS_EXPERIMENTAL } else if (!strcmp(d->dtu_softkey.action, "INVITE")) { sccp_conference_invite_participant(conference, moderator); #endif } else if (!strcmp(d->dtu_softkey.action, "MODERATE")) { sccp_conference_promote_demote_participant(conference, participant, moderator); } } else { pbx_log(LOG_WARNING, "%s: DTU TransactionID does not match or device not found (%d)\n", DEV_ID_LOG(d), transactionID); } EXIT: /* reset softkey state for next button press */ if (d) { if (d->dtu_softkey.action) { sccp_free(d->dtu_softkey.action); } d->dtu_softkey.transactionID = 0; } participant = participant ? sccp_participant_release(participant) : NULL; conference = conference ? sccp_conference_release(conference) : NULL; moderator = moderator ? sccp_participant_release(moderator) : NULL; } /*! * \brief Kick Participant out of the conference */ void sccp_conference_kick_participant(sccp_conference_t * conference, sccp_conference_participant_t * participant) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Kick Participant %d\n", conference->id, participant->id); participant->pendingRemoval = TRUE; playback_to_channel(participant, "conf-kicked", -1); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfParticipantKicked", "ConfId: %d\r\n" "PartId: %d\r\n", conference->id, participant->id); } #endif pbx_bridge_remove(participant->conference->bridge, participant->conferenceBridgePeer); } /*! * \brief Toggle Conference Lock */ void sccp_conference_toggle_lock_conference(sccp_conference_t * conference, sccp_conference_participant_t * participant) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Toggle Conference Lock\n", conference->id); conference->isLocked = (!conference->isLocked ? 1 : 0); playback_to_channel(participant, (conference->isLocked ? "conf-lockednow" : "conf-unlockednow"), -1); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfLock", "ConfId: %d\r\n" "Enabled: %s\r\n", conference->id, conference->isLocked ? "Yes" : "No"); } #endif sccp_conference_update_conflist(conference); } /*! * \brief Toggle Participant Mute Status */ void sccp_conference_toggle_mute_participant(sccp_conference_t * conference, sccp_conference_participant_t * participant) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Mute Participant %d\n", conference->id, participant->id); if (!participant->features.mute) { participant->features.mute = 1; playback_to_channel(participant, "conf-muted", -1); // if (participant->channel) { // participant->channel->setMicrophone(participant->channel, FALSE); // } } else { participant->features.mute = 0; playback_to_channel(participant, "conf-unmuted", -1); // if (participant->channel) { // participant->channel->setMicrophone(participant->channel, TRUE); // } } if (participant->channel && participant->device) { sccp_dev_set_message(participant->device, participant->features.mute ? "You are muted" : "You are unmuted", 5, FALSE, FALSE); } #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfParticipantMute", "ConfId: %d\r\n" "PartId: %d\r\n" "Mute: %s\r\n", conference->id, participant->id, participant->features.mute ? "Yes" : "No"); } #endif sccp_conference_update_conflist(conference); } /*! * \brief Toggle Music on Hold to a specific participant */ void sccp_conference_play_music_on_hold_to_participant(sccp_conference_t * conference, sccp_conference_participant_t * participant, boolean_t start) { sccp_log((DEBUGCAT_CONFERENCE)) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Play Music on hold to Participant %d\n", conference->id, participant->id); if (!participant->channel || !participant->device) { return; } if (start) { if (participant->onMusicOnHold == FALSE) { if (!sccp_strlen_zero(participant->device->conf_music_on_hold_class)) { PBX(moh_start) (participant->conferenceBridgePeer, participant->device->conf_music_on_hold_class, NULL); participant->onMusicOnHold = TRUE; //pbx_set_flag(participant->conferenceBridgePeer, AST_FLAG_MOH); } else { sccp_conference_toggle_mute_participant(conference, participant); } } } else { if (!sccp_strlen_zero(participant->device->conf_music_on_hold_class)) { if (!ast_bridge_suspend(conference->bridge, participant->conferenceBridgePeer)) { PBX(moh_stop) (participant->conferenceBridgePeer); //pbx_clear_flag(participant->conferenceBridgePeer, AST_FLAG_MOH); ast_bridge_unsuspend(conference->bridge, participant->conferenceBridgePeer); participant->onMusicOnHold = FALSE; } } else { sccp_conference_toggle_mute_participant(conference, participant); } } sccp_conference_update_conflist(conference); } /*! * \brief Promote Participant to Moderator * * paramater moderator can be provided as NULL (cli/ami actions) */ void sccp_conference_promote_demote_participant(sccp_conference_t * conference, sccp_conference_participant_t * participant, sccp_conference_participant_t * moderator) { if (participant->device && participant->channel) { if (!participant->isModerator) { // promote participant->isModerator = TRUE; conference->num_moderators++; participant->device->conferencelist_active = TRUE; participant->device->conference = sccp_conference_retain(conference); sccp_softkey_setSoftkeyState(participant->device, KEYMODE_CONNCONF, SKINNY_LBL_JOIN, TRUE); sccp_softkey_setSoftkeyState(participant->device, KEYMODE_CONNTRANS, SKINNY_LBL_JOIN, TRUE); sccp_indicate(participant->device, participant->channel, SCCP_CHANNELSTATE_CONNECTEDCONFERENCE); } else { if (conference->num_moderators > 1) { // demote participant->isModerator = FALSE; conference->num_moderators++; participant->device->conference = sccp_conference_release(participant->device->conference); sccp_softkey_setSoftkeyState(participant->device, KEYMODE_CONNCONF, SKINNY_LBL_JOIN, FALSE); sccp_softkey_setSoftkeyState(participant->device, KEYMODE_CONNTRANS, SKINNY_LBL_JOIN, FALSE); sccp_indicate(participant->device, participant->channel, SCCP_CHANNELSTATE_CONNECTED); } else { sccp_log(DEBUGCAT_CONFERENCE) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Not enough moderators left in the conference. Promote someone else first.\n", conference->id); if (moderator) { sccp_dev_set_message(moderator->device, "Promote someone first", 5, FALSE, FALSE); } } } sccp_dev_set_message(participant->device, participant->isModerator ? "You have been Promoted" : "You have been Demoted", 5, FALSE, FALSE); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_CALL, "SCCPConfParticipantPromotion", "ConfId: %d\r\n" "PartId: %d\r\n" "Moderator: %s\r\n", conference->id, participant->id, participant->isModerator ? "Yes" : "No"); } #endif } else { sccp_log(DEBUGCAT_CONFERENCE) (VERBOSE_PREFIX_3 "SCCPCONF/%04d: Only SCCP Channels can be moderators\n", conference->id); if (moderator) { sccp_dev_set_message(moderator->device, "Only sccp phones can be moderator", 5, FALSE, FALSE); } } sccp_conference_update_conflist(conference); } /*! * \brief Invite a new participant (XML function) * usage: enter a phone number via conflist menu, number will be dialed and included into the conference without any further action * * \todo To Be Implemented * * Cisco URL reference * UserData:INTEGER:STRING * UserDataSoftKey:STRING:INTEGER:STRING * UserCallDataSoftKey:STRING:INTEGER0:INTEGER1:INTEGER2:INTEGER3:STRING * UserCallData:INTEGER0:INTEGER1:INTEGER2:INTEGER3:STRING */ void sccp_conference_invite_participant(sccp_conference_t * conference, sccp_conference_participant_t * moderator) { //sccp_channel_t *channel = NULL; char xmlStr[2048] = ""; char xmlTmp[512] = ""; if (!conference) { pbx_log(LOG_WARNING, "SCCPCONF: No conference\n"); return; } if (!moderator) { pbx_log(LOG_WARNING, "SCCPCONF/%04d: No moderator\n", conference->id); return; } if (conference->isLocked) { pbx_log(LOG_WARNING, "SCCPCONF/%04d: Conference is currently locked\n", conference->id); if (moderator->device) { sccp_dev_set_message(moderator->device, "Conference is locked", 5, FALSE, FALSE); } return; } if (moderator->channel && moderator->device) { if (moderator->device->protocolversion >= 17) { sprintf(xmlTmp, "<CiscoIPPhoneInput appId=\"%d\">\n", appID); } else { sprintf(xmlTmp, "<CiscoIPPhoneInput>\n"); } strcat(xmlStr, xmlTmp); sprintf(xmlTmp, "<Title>Conference %d Invite</Title>\n", conference->id); strcat(xmlStr, "<Prompt>Enter the phone number to invite</Prompt>\n"); // sprintf(xmlTmp, "<URL>UserCallData:%d:%d:%d:%d:%d</URL>\n", APPID_CONFERENCE_INVITE, moderator->lineInstance, moderator->callReference, moderator->transactionID, moderator->id); // sprintf(xmlTmp, "<URL>UserCallData:%d:%d:%d:%d</URL>\n", APPID_CONFERENCE_INVITE, moderator->lineInstance, moderator->callReference, moderator->transactionID); sprintf(xmlTmp, "<URL>UserData:%d:%s</URL>\n", appID, "invite"); strcat(xmlStr, xmlTmp); strcat(xmlStr, "<InputItem>\n"); strcat(xmlStr, " <DisplayName>Phone Number</DisplayName>\n"); strcat(xmlStr, " <QueryStringParam>NUMBER</QueryStringParam>\n"); strcat(xmlStr, " <InputFlags>T</InputFlags>\n"); strcat(xmlStr, "</InputItem>\n"); // SoftKeys // strcat(xmlStr, "<SoftKeyItem>\n"); // strcat(xmlStr, " <Name>Exit</Name>\n"); // strcat(xmlStr, " <Position>4</Position>\n"); // strcat(xmlStr, " <URL>SoftKey:Exit</URL>\n"); // strcat(xmlStr, "</SoftKeyItem>\n"); strcat(xmlStr, "</CiscoIPPhoneInput>\n"); sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: ShowList appID %d, lineInstance %d, callReference %d, transactionID %d\n", conference->id, appID, moderator->callReference, moderator->lineInstance, moderator->transactionID); sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "SCCPCONF/%04d: XML-message:\n%s\n", conference->id, xmlStr); moderator->device->protocol->sendUserToDeviceDataVersionMessage(moderator->device, APPID_CONFERENCE_INVITE, moderator->callReference, moderator->lineInstance, moderator->transactionID, xmlStr, 2); } } /* =================================================================================================================================== CLI Functions === */ #include <asterisk/cli.h> /*! * \brief Complete Conference * \param line Line as char * \param word Word as char * \param pos Pos as int * \param state State as int * \return Result as char * * \called_from_asterisk * * \lock * - lines */ char *sccp_complete_conference(OLDCONST char *line, OLDCONST char *word, int pos, int state) { sccp_conference_t *conference = NULL; sccp_conference_participant_t *participant = NULL; int conference_id = 0; int wordlen = strlen(word), which = 0, i = 0; char *ret = NULL; char tmpname[20]; char *actions[5] = { "EndConf", "Kick", "Mute", "Invite", "Moderate" }; switch (pos) { case 2: // action for (i = 0; i < ARRAY_LEN(actions); i++) { if (!strncasecmp(word, actions[i], wordlen) && ++which > state) { return strdup(actions[i]); } } break; case 3: // conferenceid SCCP_LIST_LOCK(&conferences); SCCP_LIST_TRAVERSE(&conferences, conference, list) { snprintf(tmpname, sizeof(tmpname), "%d", conference->id); if (!strncasecmp(word, tmpname, wordlen) && ++which > state) { ret = strdup(tmpname); break; } } SCCP_LIST_UNLOCK(&conferences); break; case 4: // participantid if (sscanf(line, "sccp conference %s %d", tmpname, &conference_id) > 0) { if ((conference = sccp_conference_findByID(conference_id))) { SCCP_LIST_LOCK(&conference->participants); SCCP_LIST_TRAVERSE(&conference->participants, participant, list) { snprintf(tmpname, sizeof(tmpname), "%d", participant->id); if (!strncasecmp(word, tmpname, wordlen) && ++which > state) { ret = strdup(tmpname); break; } } SCCP_LIST_UNLOCK(&conference->participants); conference = sccp_conference_release(conference); } } break; default: break; } return ret; } /*! * \brief List Conferences * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ int sccp_cli_show_conferences(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { int local_total = 0; sccp_conference_t *conference = NULL; // table definition #define CLI_AMI_TABLE_NAME Conferences #define CLI_AMI_TABLE_PER_ENTRY_NAME Conference // #define CLI_AMI_TABLE_LIST_ITER_TYPE sccp_conference_t #define CLI_AMI_TABLE_LIST_ITER_HEAD &conferences #define CLI_AMI_TABLE_LIST_ITER_VAR conference #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 3, conference->id) \ CLI_AMI_TABLE_FIELD(Participants, d, 12, conference->participants.size) \ CLI_AMI_TABLE_FIELD(Moderator, d, 12, conference->num_moderators) \ CLI_AMI_TABLE_FIELD(Announce, s, 12, conference->playback_announcements ? "Yes" : "No") \ CLI_AMI_TABLE_FIELD(MuteOnEntry, s, 12, conference->mute_on_entry ? "Yes" : "No") \ #include "sccp_cli_table.h" if (s) *total = local_total; return RESULT_SUCCESS; } /*! * \brief Show Conference Participants * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ int sccp_cli_show_conference(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_conference_t *conference = NULL; int local_total = 0; int confid = 0; if (argc < 4 || argc > 5 || sccp_strlen_zero(argv[3])) { pbx_log(LOG_WARNING, "At least ConferenceId needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "At least ConferenceId needs to be supplied\n %s", ""); return RESULT_FAILURE; } if (!sccp_strIsNumeric(argv[3]) || (confid = atoi(argv[3])) <= 0) { pbx_log(LOG_WARNING, "At least a valid ConferenceId needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "At least valid ConferenceId needs to be supplied\n %s", ""); return RESULT_FAILURE; } if ((conference = sccp_conference_findByID(confid))) { sccp_conference_participant_t *participant = NULL; if (!s) { CLI_AMI_OUTPUT(fd, s, "\n--- SCCP conference ----------------------------------------------------------------------------------\n"); } else { astman_send_listack(s, m, argv[0], "start"); CLI_AMI_OUTPUT_PARAM("Event", CLI_AMI_LIST_WIDTH, "%s", argv[0]); } CLI_AMI_OUTPUT_PARAM("ConfId", CLI_AMI_LIST_WIDTH, "%d", conference->id); #define CLI_AMI_TABLE_NAME Participants #define CLI_AMI_TABLE_PER_ENTRY_NAME Participant #define CLI_AMI_TABLE_LIST_ITER_HEAD &conference->participants #define CLI_AMI_TABLE_LIST_ITER_VAR participant #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 3, participant->id) \ CLI_AMI_TABLE_FIELD(ChannelName, s, 20, participant->conferenceBridgePeer ? pbx_channel_name(participant->conferenceBridgePeer) : "NULL") \ CLI_AMI_TABLE_FIELD(Moderator, s, 11, participant->isModerator ? "Yes" : "No") \ CLI_AMI_TABLE_FIELD(Muted, s, 5, participant->features.mute ? "Yes" : "No") \ CLI_AMI_TABLE_FIELD(Announce, s, 8, participant->playback_announcements ? "Yes" : "No") \ #include "sccp_cli_table.h" conference = sccp_conference_release(conference); } else { pbx_log(LOG_WARNING, "At least a valid ConferenceId needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "At least valid ConferenceId needs to be supplied\n %s", ""); return RESULT_FAILURE; } if (s) *total = local_total; return RESULT_SUCCESS; } /*! * \brief Conference End * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ int sccp_cli_conference_action(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { int confid = 0, partid = 0; int local_total = 0; sccp_conference_t *conference = NULL; sccp_conference_participant_t *participant = NULL; int res = RESULT_SUCCESS; sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "Conference Action:%s, Conference %s, Participant %s\n", argv[2], argv[3], argc >= 5 ? argv[4] : ""); if (argc < 4 || argc > 5) return RESULT_SHOWUSAGE; if (sccp_strlen_zero(argv[2]) || sccp_strlen_zero(argv[3])) return RESULT_SHOWUSAGE; if (sccp_strIsNumeric(argv[3]) && (confid = atoi(argv[3])) > 0) { if ((conference = sccp_conference_findByID(confid))) { if (!strncasecmp(argv[2], "EndConf", 7)) { // EndConf Action sccp_conference_end(conference); } else if (argc >= 5) { if (sccp_strIsNumeric(argv[4]) && (partid = atoi(argv[4])) > 0) { if ((participant = sccp_conference_participant_findByID(conference, partid))) { if (!strncasecmp(argv[2], "Kick", 4)) { // Kick Action sccp_conference_kick_participant(conference, participant); } else if (!strncasecmp(argv[2], "Mute", 4)) { // Mute Action sccp_conference_toggle_mute_participant(conference, participant); } else if (!strncasecmp(argv[2], "Invite", 5)) { // Invite Action sccp_conference_invite_participant(conference, participant); } else if (!strncasecmp(argv[2], "Moderate", 8)) { // Moderate Action sccp_conference_promote_demote_participant(conference, participant, NULL); } else { pbx_log(LOG_WARNING, "Unknown Action %s\n", argv[2]); CLI_AMI_ERROR(fd, s, m, "Unknown Action\n %s", argv[2]); res = RESULT_FAILURE; } participant = sccp_participant_release(participant); } else { pbx_log(LOG_WARNING, "Participant %s not found in conference %s\n", argv[4], argv[3]); CLI_AMI_ERROR(fd, s, m, "Participant %s not found in conference\n", argv[4]); res = RESULT_FAILURE; } } else { pbx_log(LOG_WARNING, "At least a valid ParticipantId needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "At least valid ParticipantId needs to be supplied\n %s", ""); res = RESULT_FAILURE; } } else { pbx_log(LOG_WARNING, "Not enough parameters provided for action %s\n", argv[2]); CLI_AMI_ERROR(fd, s, m, "Not enough parameters provided for action %s\n", argv[2]); res = RESULT_FAILURE; } conference = sccp_conference_release(conference); } else { pbx_log(LOG_WARNING, "Conference %s not found\n", argv[3]); CLI_AMI_ERROR(fd, s, m, "Conference %s not found\n", argv[3]); res = RESULT_FAILURE; } } else { pbx_log(LOG_WARNING, "At least a valid ConferenceId needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "At least valid ConferenceId needs to be supplied\n %s", ""); return RESULT_FAILURE; } if (s) *total = local_total; return res; } #endif // kate: indent-width 8; replace-tabs off; indent-mode cstyle; auto-insert-doxygen on; line-numbers on; tab-indents on; keep-extra-spaces off; auto-brackets off;
722,260
./chan-sccp-b/src/sccp_rtp.c
/*! * \file sccp_rtp.c * \brief SCCP RTP Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /*! * \brief create a new rtp server for audio data * \param c SCCP Channel */ int sccp_rtp_createAudioServer(const sccp_channel_t * c) { boolean_t rtpResult = FALSE; sccp_device_t *device = NULL; if (!c) return -1; if (c->rtp.audio.rtp) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "we already have a rtp server, we use this one\n"); return TRUE; } if (PBX(rtp_audio_create)) { rtpResult = (boolean_t) PBX(rtp_audio_create) ((sccp_channel_t *) c); } else { pbx_log(LOG_ERROR, "we should start our own rtp server, but we dont have one\n"); } if (!sccp_rtp_getUs(&c->rtp.audio, &((sccp_channel_t *) c)->rtp.audio.phone_remote)) { pbx_log(LOG_WARNING, "%s: Did not get our rtp part\n", c->currentDeviceId); } device = sccp_channel_getDevice_retained(c); //struct sockaddr_in us; // PBX(rtp_setPeer) (&c->rtp.audio, &c->rtp.audio.phone, device ? device->nat : 0); device = device ? sccp_device_release(device) : NULL; return rtpResult; } /*! * \brief create a new rtp server for video data * \param c SCCP Channel */ int sccp_rtp_createVideoServer(const sccp_channel_t * c) { boolean_t rtpResult = FALSE; if (!c) return FALSE; if (c->rtp.video.rtp) { pbx_log(LOG_ERROR, "we already have a rtp server, why dont we use this?\n"); return TRUE; } if (PBX(rtp_video_create)) { rtpResult = (boolean_t) PBX(rtp_video_create) ((sccp_channel_t *) c); } else { pbx_log(LOG_ERROR, "we should start our own rtp server, but we dont have one\n"); } if (!sccp_rtp_getUs(&c->rtp.video, &((sccp_channel_t *) c)->rtp.video.phone_remote)) { pbx_log(LOG_WARNING, "%s: Did not get our rtp part\n", c->currentDeviceId); } return rtpResult; } /*! * \brief Stop an RTP Source. * \param c SCCP Channel */ void sccp_rtp_stop(sccp_channel_t * c) { if (!c) return; if (PBX(rtp_stop)) { PBX(rtp_stop) (c); } else { pbx_log(LOG_ERROR, "no pbx function to stop rtp\n"); } } /*! * \brief set the address the phone should send rtp media. * \param c SCCP Channel * \param rtp SCCP RTP * \param new_peer socket info to remote device */ void sccp_rtp_set_peer(sccp_channel_t * c, struct sccp_rtp *rtp, struct sockaddr_in *new_peer) { /* validate socket */ if (new_peer->sin_port == 0) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "%s: ( sccp_rtp_set_peer ) remote information are invalid, dont change anything\n", c->currentDeviceId); return; } /* check if we have new infos */ if (socket_equals(new_peer, &c->rtp.audio.phone_remote)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "%s: (sccp_rtp_set_peer) remote information are equal to the current one, ignore change\n", c->currentDeviceId); return; } memcpy(&c->rtp.audio.phone_remote, new_peer, sizeof(c->rtp.audio.phone_remote)); pbx_log(LOG_NOTICE, "%s: ( sccp_rtp_set_peer ) Set remote address to %s:%d\n", c->currentDeviceId, pbx_inet_ntoa(new_peer->sin_addr), ntohs(new_peer->sin_port)); if (c->rtp.audio.readState & SCCP_RTP_STATUS_ACTIVE) { /* Shutdown any early-media or previous media on re-invite */ /*! \todo we should wait for the acknowledgement to get back. We don't have a function/procedure in place to do this at this moment in time (sccp_dev_send_wait) */ sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "%s: (sccp_rtp_set_peer) Stop media transmission on channel %d\n", c->currentDeviceId, c->callid); sccp_channel_stopmediatransmission(c); sccp_channel_startmediatransmission(c); } } /*! * \brief set the address where the phone should send rtp media. * \param c SCCP Channel * \param rtp SCCP RTP * \param new_peer socket info to remote device */ void sccp_rtp_set_phone(sccp_channel_t * c, struct sccp_rtp *rtp, struct sockaddr_in *new_peer) { sccp_device_t *device; /* validate socket */ if (new_peer->sin_port == 0) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "%s: (sccp_rtp_set_phone) remote information are invalid, dont change anything\n", c->currentDeviceId); return; } if ((device = sccp_channel_getDevice_retained(c))) { /* check if we have new infos */ /*! \todo if we enable this, we get an audio issue when resume on the same device, so we need to force asterisk to update -MC */ /* if (socket_equals(new_peer, &c->rtp.audio.phone)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "%s: (sccp_rtp_set_phone) remote information are equal to the current one, ignore change\n", c->currentDeviceId); //return; } */ memcpy(&rtp->phone, new_peer, sizeof(rtp->phone)); //update pbx if (PBX(rtp_setPeer)) { PBX(rtp_setPeer) (rtp, new_peer, device->nat); } char cbuf1[128] = ""; char cbuf2[128] = ""; sprintf(cbuf1, "%15s:%d", pbx_inet_ntoa(rtp->phone_remote.sin_addr), ntohs(rtp->phone_remote.sin_port)); sprintf(cbuf2, "%15s:%d", pbx_inet_ntoa(rtp->phone.sin_addr), ntohs(rtp->phone.sin_port)); sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Tell PBX to send RTP/UDP media from:%s to %s (NAT: %s)\n", DEV_ID_LOG(device), cbuf1, cbuf2, device->nat ? "yes" : "no"); device = sccp_device_release(device); } } /*! * \brief Get Audio Peer RTP Information */ sccp_rtp_info_t sccp_rtp_getAudioPeerInfo(const sccp_channel_t * c, struct sccp_rtp **rtp) { sccp_device_t *device = NULL; sccp_rtp_info_t result = SCCP_RTP_INFO_NORTP; device = sccp_channel_getDevice_retained(c); if (!device) { return SCCP_RTP_INFO_NORTP; } *rtp = &(((sccp_channel_t *) c)->rtp.audio); result = SCCP_RTP_INFO_AVAILABLE; if (device->directrtp && !device->nat) { result |= SCCP_RTP_INFO_ALLOW_DIRECTRTP; } device = device ? sccp_device_release(device) : NULL; return result; } /*! * \brief Get Video Peer RTP Information */ sccp_rtp_info_t sccp_rtp_getVideoPeerInfo(const sccp_channel_t * c, struct sccp_rtp ** rtp) { sccp_rtp_info_t result = SCCP_RTP_INFO_NORTP; sccp_device_t *device = NULL; device = sccp_channel_getDevice_retained(c); if (!device) { return SCCP_RTP_INFO_NORTP; } *rtp = &(((sccp_channel_t *) c)->rtp.video); result = SCCP_RTP_INFO_AVAILABLE; device = device ? sccp_device_release(device) : NULL; return result; } /*! * \brief Get Payload Type */ uint8_t sccp_rtp_get_payloadType(const struct sccp_rtp * rtp, skinny_codec_t codec) { if (PBX(rtp_get_payloadType)) { return PBX(rtp_get_payloadType) (rtp, codec); } else { return 97; } } /*! * \brief Get Sample Rate */ uint8_t sccp_rtp_get_sampleRate(skinny_codec_t codec) { if (PBX(rtp_get_sampleRate)) { return PBX(rtp_get_sampleRate) (codec); } else { return (uint8_t) 3840; } } /*! * \brief Destroy RTP Source. * \param c SCCP Channel */ void sccp_rtp_destroy(sccp_channel_t * c) { sccp_line_t *l = NULL; l = c->line; if (c->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: destroying phone media transmission on channel %s-%08X\n", c->currentDeviceId, l ? l->name : "(null)", c->callid); PBX(rtp_destroy) (c->rtp.audio.rtp); c->rtp.audio.rtp = NULL; } if (c->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: destroying video media transmission on channel %s-%08X\n", c->currentDeviceId, l ? l->name : "(null)", c->callid); PBX(rtp_destroy) (c->rtp.video.rtp); c->rtp.video.rtp = NULL; } } /*! * \brief Get Audio Peer */ boolean_t sccp_rtp_getAudioPeer(sccp_channel_t * c, struct sockaddr_in **new_peer) { *new_peer = &c->rtp.audio.phone_remote; return TRUE; } /*! * \brief Get Video Peer */ boolean_t sccp_rtp_getVideoPeer(sccp_channel_t * c, struct sockaddr_in **new_peer) { *new_peer = &c->rtp.audio.phone_remote; return TRUE; } /*! * \brief Retrieve Phone Socket Information */ boolean_t sccp_rtp_getUs(const struct sccp_rtp *rtp, struct sockaddr_in *us) { if (rtp->rtp) { PBX(rtp_getUs) (rtp->rtp, us); return TRUE; } else { us = (struct sockaddr_in *) &rtp->phone_remote; // return FALSE; return TRUE; } } /*! * \brief Retrieve Phone Socket Information */ boolean_t sccp_rtp_getPeer(const struct sccp_rtp *rtp, struct sockaddr_in *them) { if (rtp->rtp) { PBX(rtp_getPeer) (rtp->rtp, them); return TRUE; } else { return FALSE; } }
722,261
./chan-sccp-b/src/sccp_line.c
/*! * \file sccp_line.c * \brief SCCP Line * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") static void regcontext_exten(sccp_line_t * l, struct subscriptionId *subscriptionId, int onoff); int __sccp_line_destroy(const void *ptr); int __sccp_lineDevice_destroy(const void *ptr); void sccp_line_delete_nolock(sccp_line_t * l); int sccp_line_destroy(const void *ptr); /*! * \brief run before reload is start on lines * \note See \ref sccp_config_reload * * \callgraph * \callergraph * * \lock * - lines */ void sccp_line_pre_reload(void) { sccp_line_t *l; sccp_linedevices_t *linedevice; SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { if (GLOB(hotline)->line == l) { /* always remove hotline from linedevice */ SCCP_LIST_TRAVERSE_SAFE_BEGIN(&l->devices, linedevice, list) { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Removing Hotline from Device\n", linedevice->device->id); linedevice->device->isAnonymous = FALSE; sccp_line_removeDevice(linedevice->line, linedevice->device); } SCCP_LIST_TRAVERSE_SAFE_END; } else { /* Don't want to include the hotline line */ #ifdef CS_SCCP_REALTIME if (l->realtime == FALSE) #endif { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Setting Line to Pending Delete=1\n", l->name); l->pendingDelete = 1; } } l->pendingUpdate = 0; } SCCP_RWLIST_UNLOCK(&GLOB(lines)); } /*! * \brief run after the new line config is loaded during the reload process * \note See \ref sccp_config_reload * \todo to be implemented correctly (***) * * \callgraph * \callergraph * * \lock * - lines * - line * - line->devices * - device * - see sccp_line_clean() */ void sccp_line_post_reload(void) { sccp_line_t *l; sccp_linedevices_t *linedevice; SCCP_RWLIST_TRAVERSE_SAFE_BEGIN(&GLOB(lines), l, list) { if (!l->pendingDelete && !l->pendingUpdate) continue; if ((l = sccp_line_retain(l))) { SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { linedevice->device->pendingUpdate = 1; } SCCP_LIST_UNLOCK(&l->devices); if (l->pendingDelete) { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Deleting Line (post_reload)\n", l->name); sccp_line_clean(l, TRUE); } else { sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Cleaning Line (post_reload)\n", l->name); sccp_line_clean(l, FALSE); } l = sccp_line_release(l); } } SCCP_RWLIST_TRAVERSE_SAFE_END; } /*! * \brief Build Default SCCP Line. * * Creates an SCCP Line with default/global values * * \return Default SCCP Line * * \callgraph * \callergraph */ sccp_line_t *sccp_line_create(const char *name) { sccp_line_t *l = (sccp_line_t *) sccp_refcount_object_alloc(sizeof(sccp_line_t), SCCP_REF_LINE, name, __sccp_line_destroy); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Unable to allocate memory for a line\n"); return NULL; } memset(l, 0, sizeof(sccp_line_t)); pbx_mutex_init(&l->lock); sccp_copy_string(l->name, name, sizeof(l->name)); SCCP_LIST_HEAD_INIT(&l->channels); SCCP_LIST_HEAD_INIT(&l->devices); SCCP_LIST_HEAD_INIT(&l->mailboxes); return l; } /*! * Add a line to global line list. * \param line line pointer * \since 20091202 - MC * * \note needs to be called with a retained line * \note adds a retained line to the list (refcount + 1) * \lock * - lines * - see sccp_mwi_linecreatedEvent() via sccp_event_fire() */ void sccp_line_addToGlobals(sccp_line_t * line) { sccp_line_t *l = NULL; while (!SCCP_RWLIST_TRYWRLOCK(&GLOB(lines))) { /* Upgrading to wrlock if possible */ usleep(100); /* backoff on failure */ } if ((l = sccp_line_retain(line))) { /* add to list */ l = sccp_line_retain(l); /* add retained line to the list */ SCCP_RWLIST_INSERT_SORTALPHA(&GLOB(lines), l, list, cid_num); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Added line '%s' to Glob(lines)\n", l->name); /* emit event */ sccp_event_t event; memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_LINE_CREATED; event.event.lineCreated.line = sccp_line_retain(l); sccp_event_fire(&event); l = sccp_line_release(l); } else { pbx_log(LOG_ERROR, "Adding null to global line list is not allowed!\n"); } SCCP_RWLIST_UNLOCK(&GLOB(lines)); } /*! * Remove a line from the global line list. * \param line SCCP line pointer * * \note needs to be called with a retained line * \note removes the retained line withing the list (refcount - 1) * \lock * - lines * - see sccp_mwi_linecreatedEvent() via sccp_event_fire() */ sccp_line_t *sccp_line_removeFromGlobals(sccp_line_t * line) { sccp_line_t *removed_line = NULL; if (!line) { pbx_log(LOG_ERROR, "Removing null from global line list is not allowed!\n"); return NULL; } // SCCP_RWLIST_WRLOCK(&GLOB(lines)); while (!SCCP_RWLIST_TRYWRLOCK(&GLOB(lines))) { /* Upgrading to wrlock if possible */ usleep(100); /* backoff on failure */ } removed_line = SCCP_RWLIST_REMOVE(&GLOB(lines), line, list); SCCP_RWLIST_UNLOCK(&GLOB(lines)); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Removed line '%s' from Glob(lines)\n", removed_line->name); /* not sure if we should fire an event like this ? */ /* sccp_event_t event; memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_LINE_DELETED; event.event.lineCreated.line = sccp_line_retain(line); sccp_event_fire(&event); */ if (removed_line) { sccp_line_release(removed_line); } return removed_line; } /*! * \brief create a hotline * * \lock * - lines */ void *sccp_create_hotline(void) { sccp_line_t *hotline; GLOB(hotline) = (sccp_hotline_t *) sccp_malloc(sizeof(sccp_hotline_t)); if (!GLOB(hotline)) { pbx_log(LOG_ERROR, "Error allocating memory for GLOB(hotline)"); return FALSE; } memset(GLOB(hotline), 0, sizeof(sccp_hotline_t)); SCCP_RWLIST_RDLOCK(&GLOB(lines)); hotline = sccp_line_create("Hotline"); #ifdef CS_SCCP_REALTIME hotline->realtime = TRUE; #endif if (hotline) { sccp_copy_string(hotline->cid_name, "hotline", sizeof(hotline->cid_name)); sccp_copy_string(hotline->cid_num, "hotline", sizeof(hotline->cid_name)); sccp_copy_string(hotline->context, "default", sizeof(hotline->context)); sccp_copy_string(hotline->label, "hotline", sizeof(hotline->label)); sccp_copy_string(hotline->adhocNumber, "111", sizeof(hotline->adhocNumber)); //sccp_copy_string(hotline->mailbox, "hotline", sizeof(hotline->mailbox)); sccp_copy_string(GLOB(hotline)->exten, "111", sizeof(GLOB(hotline)->exten)); GLOB(hotline)->line = sccp_line_retain(hotline); sccp_line_addToGlobals(hotline); // can return previous line on doubles sccp_line_release(hotline); } SCCP_RWLIST_UNLOCK(&GLOB(lines)); return NULL; } /*! * \brief Kill all Channels of a specific Line * \param l SCCP Line * \note Should be Called with a lock on l->lock * * \callgraph * \callergraph * * \lock * - line->channels * - see sccp_channel_endcall(); */ void sccp_line_kill_channels(sccp_line_t * l) { sccp_channel_t *c; if (!l) return; // SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE_SAFE_BEGIN(&l->channels, c, list) { if ((sccp_channel_retain(c))) { sccp_channel_endcall(c); sccp_channel_release(c); } } SCCP_LIST_TRAVERSE_SAFE_END; // SCCP_LIST_UNLOCK(&l->channels); } /*! * \brief Clean Line * * clean up memory allocated by the line. * if destroy is true, line will be removed from global device list * * \param l SCCP Line * \param remove_from_global as boolean_t * * \todo integrate sccp_line_clean and sccp_line_delete_nolock into sccp_line_delete * * \callgraph * \callergraph * * \lock * - lines * - see sccp_line_kill_channels() * - line->devices * - see sccp_line_destroy() */ void sccp_line_clean(sccp_line_t * l, boolean_t remove_from_global) { sccp_line_kill_channels(l); sccp_line_removeDevice(l, NULL); // removing all devices from this line. if (remove_from_global) { sccp_line_destroy(l); } } /*! * \brief Free a Line as scheduled command * \param ptr SCCP Line Pointer * \return success as int * * \callgraph * \callergraph * * \lock * - line * - see sccp_mwi_unsubscribeMailbox() */ int __sccp_line_destroy(const void *ptr) { sccp_line_t *l = (sccp_line_t *) ptr; sccp_log((DEBUGCAT_LINE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "%s: Line FREE\n", l->name); sccp_mutex_lock(&l->lock); // cleanup linedevices sccp_line_removeDevice(l, NULL); if (SCCP_LIST_EMPTY(&l->devices)) SCCP_LIST_HEAD_DESTROY(&l->devices); // cleanup mailboxes if (l->trnsfvm) { sccp_free(l->trnsfvm); } sccp_mailbox_t *mailbox = NULL; SCCP_LIST_LOCK(&l->mailboxes); while ((mailbox = SCCP_LIST_REMOVE_HEAD(&l->mailboxes, list))) { if (!mailbox) break; sccp_mwi_unsubscribeMailbox(&mailbox); if (mailbox->mailbox) sccp_free(mailbox->mailbox); if (mailbox->context) sccp_free(mailbox->context); sccp_free(mailbox); } SCCP_LIST_UNLOCK(&l->mailboxes); if (SCCP_LIST_EMPTY(&l->mailboxes)) { SCCP_LIST_HEAD_DESTROY(&l->mailboxes); } // cleanup channels sccp_channel_t *c = NULL; SCCP_LIST_LOCK(&l->channels); while ((c = SCCP_LIST_REMOVE_HEAD(&l->channels, list))) { sccp_channel_endcall(c); sccp_channel_release(c); // release channel retain in list } SCCP_LIST_UNLOCK(&l->channels); if (SCCP_LIST_EMPTY(&l->channels)) { SCCP_LIST_HEAD_DESTROY(&l->channels); } // cleanup variables if (l->variables) { pbx_variables_destroy(l->variables); l->variables = NULL; } sccp_mutex_unlock(&l->lock); pbx_mutex_destroy(&l->lock); return 0; } /*! * \brief Free a Line as scheduled command * \param ptr SCCP Line Pointer * \return success as int * * \callgraph * \callergraph * * \lock * - line * - see sccp_mwi_unsubscribeMailbox() */ int __sccp_lineDevice_destroy(const void *ptr) { sccp_linedevices_t *linedevice = (sccp_linedevices_t *) ptr; sccp_log((DEBUGCAT_DEVICE | DEBUGCAT_LINE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "%s: LineDevice FREE %p\n", DEV_ID_LOG(linedevice->device), linedevice); if (linedevice->line) linedevice->line = sccp_line_release(linedevice->line); if (linedevice->device) linedevice->device = sccp_device_release(linedevice->device); return 0; } /*! * \brief Free a Line as scheduled command * \param ptr SCCP Line Pointer * \return success as int * * \callgraph * \callergraph * * \lock * - line * - see sccp_mwi_unsubscribeMailbox() */ int sccp_line_destroy(const void *ptr) { sccp_line_t *l = (sccp_line_t *) ptr; sccp_line_removeFromGlobals(l); // final release return 0; } /*! * \brief Delete an SCCP line * \param l SCCP Line * \note Should be Called without a lock on l->lock */ void sccp_line_delete_nolock(sccp_line_t * l) { sccp_line_clean(l, TRUE); } /*! * \brief Set a Call Forward on a specific Line * \param line SCCP Line * \param device device that requested the forward * \param type Call Forward Type as uint8_t * \param number Number to which should be forwarded * \todo we should check, that extension is reachable on line * * \callgraph * \callergraph * * \lock * - line->devices * - see sccp_feat_changed() * * \todo implement cfwd_noanswer */ void sccp_line_cfwd(sccp_line_t * line, sccp_device_t * device, sccp_callforward_t type, char *number) { sccp_linedevices_t *linedevice = NULL; if (!line || !device) return; if ((linedevice = sccp_linedevice_find(device, line))) { if (type == SCCP_CFWD_NONE) { linedevice->cfwdAll.enabled = 0; linedevice->cfwdBusy.enabled = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Call Forward disabled on line %s\n", DEV_ID_LOG(device), line->name); } else { if (!number || sccp_strlen_zero(number)) { linedevice->cfwdAll.enabled = 0; linedevice->cfwdBusy.enabled = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Call Forward to an empty number. Invalid\n", DEV_ID_LOG(device)); } else { switch (type) { case SCCP_CFWD_ALL: linedevice->cfwdAll.enabled = 1; sccp_copy_string(linedevice->cfwdAll.number, number, sizeof(linedevice->cfwdAll.number)); break; case SCCP_CFWD_BUSY: linedevice->cfwdBusy.enabled = 1; sccp_copy_string(linedevice->cfwdBusy.number, number, sizeof(linedevice->cfwdBusy.number)); break; default: linedevice->cfwdAll.enabled = 0; linedevice->cfwdBusy.enabled = 0; } sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Call Forward enabled on line %s to number %s\n", DEV_ID_LOG(device), line->name, number); } } sccp_dev_starttone(linedevice->device, SKINNY_TONE_ZIPZIP, 0, 0, 0); sccp_feat_changed(linedevice->device, linedevice, SCCP_FEATURE_CFWDALL); sccp_dev_forward_status(linedevice->line, linedevice->lineInstance, device); linedevice = sccp_linedevice_release(linedevice); } else { pbx_log(LOG_ERROR, "%s: Device does not have line configured (linedevice not found)\n", DEV_ID_LOG(device)); } } /*! * \brief Attach a Device to a line * \param l SCCP Line * \param device SCCP Device * \param lineInstance lineInstance as uint8_t * \param subscriptionId Subscription ID for addressing individual devices on the line * * \lock * - line->devices * - see register_exten() * - line * - see sccp_feat_changed() * - see sccp_dev_forward_status() via sccp_event_fire() * - see sccp_mwi_deviceAttachedEvent() via sccp_event_fire */ void sccp_line_addDevice(sccp_line_t * l, sccp_device_t * device, uint8_t lineInstance, struct subscriptionId *subscriptionId) { sccp_linedevices_t *linedevice = NULL; if (!device || !l) { pbx_log(LOG_ERROR, "SCCP: sccp_line_addDevice: No line or device provided\n"); return; } if ((linedevice = sccp_linedevice_find(device, l))) { sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "%s: device already registered for line '%s'\n", DEV_ID_LOG(device), l->name); sccp_linedevice_release(linedevice); // early exit return; } if (!(device = sccp_device_retain(device))) { pbx_log(LOG_ERROR, "SCCP: sccp_line_addDevice: Device could not be retained for line : %s\n", l ? l->name : "UNDEF"); return; } if (!(l = sccp_line_retain(l))) { pbx_log(LOG_ERROR, "%s: sccp_line_addDevice: Line could not be retained\n", DEV_ID_LOG(device)); device = sccp_device_release(device); return; } sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "%s: add device to line %s\n", DEV_ID_LOG(device), l->name); char ld_id[REFCOUNT_INDENTIFIER_SIZE]; snprintf(ld_id, REFCOUNT_INDENTIFIER_SIZE, "%s/%s", device->id, l->name); linedevice = (sccp_linedevices_t *) sccp_refcount_object_alloc(sizeof(sccp_linedevices_t), SCCP_REF_LINEDEVICE, ld_id, __sccp_lineDevice_destroy); memset(linedevice, 0, sizeof(sccp_linedevices_t)); linedevice->device = sccp_device_retain(device); linedevice->line = sccp_line_retain(l); linedevice->lineInstance = lineInstance; if (NULL != subscriptionId) { sccp_copy_string(linedevice->subscriptionId.name, subscriptionId->name, sizeof(linedevice->subscriptionId.name)); sccp_copy_string(linedevice->subscriptionId.number, subscriptionId->number, sizeof(linedevice->subscriptionId.number)); sccp_copy_string(linedevice->subscriptionId.aux, subscriptionId->aux, sizeof(linedevice->subscriptionId.aux)); } SCCP_LIST_LOCK(&l->devices); SCCP_LIST_INSERT_HEAD(&l->devices, linedevice, list); SCCP_LIST_UNLOCK(&l->devices); linedevice->line->statistic.numberOfActiveDevices++; linedevice->device->configurationStatistic.numberOfLines++; /* read cfwd status from db */ #ifndef ASTDB_FAMILY_KEY_LEN #define ASTDB_FAMILY_KEY_LEN 100 #endif #ifndef ASTDB_RESULT_LEN #define ASTDB_RESULT_LEN 80 #endif char family[ASTDB_FAMILY_KEY_LEN]; char buffer[ASTDB_RESULT_LEN]; memset(family, 0, ASTDB_FAMILY_KEY_LEN); sprintf(family, "SCCP/%s/%s", device->id, l->name); if (PBX(feature_getFromDatabase) (family, "cfwdAll", buffer, sizeof(buffer)) && strcmp(buffer, "")) { linedevice->cfwdAll.enabled = TRUE; sccp_copy_string(linedevice->cfwdAll.number, buffer, sizeof(linedevice->cfwdAll.number)); sccp_feat_changed(device, linedevice, SCCP_FEATURE_CFWDALL); } if (PBX(feature_getFromDatabase) (family, "cfwdBusy", buffer, sizeof(buffer)) && strcmp(buffer, "")) { linedevice->cfwdBusy.enabled = TRUE; sccp_copy_string(linedevice->cfwdBusy.number, buffer, sizeof(linedevice->cfwdAll.number)); sccp_feat_changed(device, linedevice, SCCP_FEATURE_CFWDBUSY); } if (linedevice->cfwdAll.enabled || linedevice->cfwdBusy.enabled) { sccp_dev_forward_status(l, lineInstance, device); } // fire event for new device sccp_event_t event; memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_DEVICE_ATTACHED; event.event.deviceAttached.linedevice = sccp_linedevice_retain(linedevice); sccp_event_fire(&event); regcontext_exten(l, &(linedevice->subscriptionId), 1); sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "%s: added linedevice: %p with device: %s\n", l->name, linedevice, DEV_ID_LOG(device)); l = sccp_line_release(l); device = sccp_device_release(device); } /*! * \brief Remove a Device from a Line * * Fire SCCP_EVENT_DEVICE_DETACHED event after removing device. * * \param l SCCP Line * \param device SCCP Device * * \note device can be NULL, mening remove all device from this line * * \lock * - line * - line->devices * - see unregister_exten() * - see sccp_hint_eventListener() via sccp_event_fire() */ void sccp_line_removeDevice(sccp_line_t * l, sccp_device_t * device) { sccp_linedevices_t *linedevice; if (!l) { return; } sccp_log((DEBUGCAT_HIGH + DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: remove device from line %s\n", DEV_ID_LOG(device), l->name); SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE_SAFE_BEGIN(&l->devices, linedevice, list) { if (device == NULL || linedevice->device == device) { regcontext_exten(l, &(linedevice->subscriptionId), 0); SCCP_LIST_REMOVE_CURRENT(list); l->statistic.numberOfActiveDevices--; sccp_event_t event; memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_DEVICE_DETACHED; event.event.deviceAttached.linedevice = sccp_linedevice_retain(linedevice); sccp_event_fire(&event); sccp_linedevice_release(linedevice); } } SCCP_LIST_TRAVERSE_SAFE_END; SCCP_LIST_UNLOCK(&l->devices); } /*! * \brief Add a Channel to a Line * * \param l SCCP Line * \param channel SCCP Channel * * \warning * - line->channels is not always locked * * \lock * - line */ void sccp_line_addChannel(sccp_line_t * l, sccp_channel_t * channel) { if (!l || !channel) return; if ((l = sccp_line_retain(l))) { l->statistic.numberOfActiveChannels++; SCCP_LIST_LOCK(&l->channels); if ((channel = sccp_channel_retain(channel))) { // Add into list retained sccp_channel_updateChannelDesignator(channel); sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_1 "SCCP: Adding channel %d to line %s\n", channel->callid, l->name); if (GLOB(callanswerorder) == ANSWER_OLDEST_FIRST) SCCP_LIST_INSERT_TAIL(&l->channels, channel, list); else SCCP_LIST_INSERT_HEAD(&l->channels, channel, list); } SCCP_LIST_UNLOCK(&l->channels); l = sccp_line_release(l); } } /*! * \brief Remove a Channel from a Line * * \param l SCCP Line * \param c SCCP Channel * * \warning * - line->channels is not always locked * * \lock * - line */ void sccp_line_removeChannel(sccp_line_t * l, sccp_channel_t * c) { sccp_channel_t *channel; if (!l || !c) return; if ((l = sccp_line_retain(l))) { SCCP_LIST_LOCK(&l->channels); if ((channel = SCCP_LIST_REMOVE(&l->channels, c, list))) { sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_1 "SCCP: Removing channel %d from line %s\n", channel->callid, l->name); l->statistic.numberOfActiveChannels--; channel = sccp_channel_release(channel); // Remove retain from list } SCCP_LIST_UNLOCK(&l->channels); l = sccp_line_release(l); } } /*! * \brief Register Extension to Asterisk regextension * \param l SCCP Line * \param subscriptionId subscriptionId * \param onoff On/Off as int * \note used for DUNDi Discovery \ref DUNDi */ static void regcontext_exten(sccp_line_t * l, struct subscriptionId *subscriptionId, int onoff) { char multi[256] = ""; char *stringp, *ext = "", *context = ""; // char extension[AST_MAX_CONTEXT]=""; // char name[AST_MAX_CONTEXT]=""; struct pbx_context *con; struct pbx_find_info q = {.stacklen = 0 }; if (sccp_strlen_zero(GLOB(regcontext))) { return; } sccp_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi)); stringp = multi; while ((ext = strsep(&stringp, "&"))) { if ((context = strchr(ext, '@'))) { *context++ = '\0'; /* split ext@context */ if (!pbx_context_find(context)) { pbx_log(LOG_WARNING, "Context specified in regcontext=%s (sccp.conf) must exist\n", context); continue; } } else { context = GLOB(regcontext); } con = pbx_context_find_or_create(NULL, NULL, context, "SCCP"); /* make sure the context exists */ if (con) { if (onoff) { /* register */ if (!pbx_exists_extension(NULL, context, ext, 1, NULL) && pbx_add_extension(context, 0, ext, 1, NULL, NULL, "Noop", sccp_strdup(l->name), sccp_free_ptr, "SCCP")) { sccp_log((DEBUGCAT_LINE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Registered RegContext: %s, Extension: %s, Line: %s\n", context, ext, l->name); } /* register extension + subscriptionId */ /* if (subscriptionId && subscriptionId->number && !sccp_strlen_zero(subscriptionId->number) && !sccp_strlen_zero(subscriptionId->name)) { snprintf(extension, sizeof(extension), "%s@%s", ext, subscriptionId->number); snprintf(name, sizeof(name), "%s%s", l->name, subscriptionId->name); if (!pbx_exists_extension(NULL, context, extension, 2, NULL) && pbx_add_extension(context, 0, extension, 2, NULL, NULL, "Noop", sccp_strdup(name), sccp_free_ptr, "SCCP")) { sccp_log((DEBUGCAT_LINE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Registered RegContext: %s, Extension: %s, Line: %s\n", context, extension, name); } } */ } else { /* un-register */ if (l->devices.size == 1) { // only remove entry if it is the last one (shared line) if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) { ast_context_remove_extension(context, ext, 1, NULL); sccp_log((DEBUGCAT_LINE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Unregistered RegContext: %s, Extension: %s\n", context, ext); } } /* unregister extension + subscriptionId */ /* if (subscriptionId && subscriptionId->number && !sccp_strlen_zero(subscriptionId->number) && !sccp_strlen_zero(subscriptionId->name)) { snprintf(extension, sizeof(extension), "%s@%s", ext, subscriptionId->number); // if (pbx_exists_extension(NULL, context, extension, 2, NULL)) { if (pbx_find_extension(NULL, NULL, &q, context, extension, 2, NULL, "", E_MATCH)) { ast_context_remove_extension(context, extension, 2, NULL); sccp_log((DEBUGCAT_LINE | DEBUGCAT_CONFIG)) (VERBOSE_PREFIX_1 "Unregistered RegContext: %s, Extension: %s\n", context, extension); } } */ } } else { pbx_log(LOG_ERROR, "SCCP: context '%s' does not exist and could not be created\n", context); } } } /*! * \brief check the DND status for single/shared lines * On shared line we will return dnd status if all devices in dnd only. * single line signaling dnd if device is set to dnd * * \param line SCCP Line (locked) */ sccp_channelstate_t sccp_line_getDNDChannelState(sccp_line_t * line) { sccp_linedevices_t *lineDevice = NULL; sccp_channelstate_t state = SCCP_CHANNELSTATE_CONGESTION; if (!line) { pbx_log(LOG_WARNING, "SCCP: (sccp_hint_getDNDState) Either no hint or line provided\n"); return state; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (sccp_hint_getDNDState) line: %s\n", line->name); if (line->devices.size > 1) { /* we have to check if all devices on this line are dnd=SCCP_DNDMODE_REJECT, otherwise do not propagate DND status */ boolean_t allDevicesInDND = TRUE; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, lineDevice, list) { if (lineDevice->device->dndFeature.status != SCCP_DNDMODE_REJECT) { allDevicesInDND = FALSE; break; } } SCCP_LIST_UNLOCK(&line->devices); if (allDevicesInDND) { state = SCCP_CHANNELSTATE_DND; } } else { sccp_linedevices_t *lineDevice = SCCP_LIST_FIRST(&line->devices); if (lineDevice) { if (lineDevice->device->dndFeature.enabled && lineDevice->device->dndFeature.status == SCCP_DNDMODE_REJECT) { state = SCCP_CHANNELSTATE_DND; } } } // if(line->devices.size > 1) return state; } /*=================================================================================== FIND FUNCTIONS ==============*/ /*! * \brief Find Line by Name * * \callgraph * \callergraph * * \lock * - lines */ #if DEBUG /*! * \param name Line Name * \param useRealtime Use Realtime as Boolean * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Line */ sccp_line_t *__sccp_line_find_byname(const char *name, uint8_t useRealtime, const char *filename, int lineno, const char *func) #else /*! * \param name Line Name * \param useRealtime Use Realtime as Boolean * \return SCCP Line */ sccp_line_t *sccp_line_find_byname(const char *name, uint8_t useRealtime) #endif { sccp_line_t *l = NULL; // sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "SCCP: Looking for line '%s'\n", name); if (sccp_strlen_zero(name)) { sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "SCCP: Not allowed to search for line with name ''\n"); return NULL; } SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { if (l && l->name && !strcasecmp(l->name, name)) { #if DEBUG l = sccp_refcount_retain(l, filename, lineno, func); #else l = sccp_line_retain(l); #endif break; } } #ifdef CS_SCCP_REALTIME if (!l && useRealtime) { l = sccp_line_find_realtime_byname(name); /* already retained */ } #endif SCCP_RWLIST_UNLOCK(&GLOB(lines)); if (!l) { sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "SCCP: Line '%s' not found.\n", name); return NULL; } // sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: Found line '%s'\n", "SCCP", l->name); return l; } #ifdef CS_SCCP_REALTIME /*! * \brief Find Line via Realtime * * \callgraph * \callergraph */ #if DEBUG /*! * \param name Line Name * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Line */ sccp_line_t *__sccp_line_find_realtime_byname(const char *name, const char *filename, int lineno, const char *func) #else /*! * \param name Line Name * \return SCCP Line */ sccp_line_t *sccp_line_find_realtime_byname(const char *name) #endif { sccp_line_t *l = NULL; PBX_VARIABLE_TYPE *v, *variable; if (sccp_strlen_zero(GLOB(realtimelinetable)) || sccp_strlen_zero(name)) { return NULL; } if (sccp_strlen_zero(name)) { sccp_log((DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "SCCP: Not allowed to search for line with name ''\n"); return NULL; } if ((variable = pbx_load_realtime(GLOB(realtimelinetable), "name", name, NULL))) { v = variable; sccp_log((DEBUGCAT_LINE | DEBUGCAT_REALTIME)) (VERBOSE_PREFIX_3 "SCCP: Line '%s' found in realtime table '%s'\n", name, GLOB(realtimelinetable)); sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_4 "SCCP: creating realtime line '%s'\n", name); l = sccp_line_create(name); /* already retained */ sccp_config_applyLineConfiguration(l, variable); l->realtime = TRUE; sccp_line_addToGlobals(l); // can return previous instance on doubles pbx_variables_destroy(v); if (!l) { pbx_log(LOG_ERROR, "SCCP: Unable to build realtime line '%s'\n", name); } return l; } sccp_log((DEBUGCAT_LINE | DEBUGCAT_REALTIME)) (VERBOSE_PREFIX_3 "SCCP: Line '%s' not found in realtime table '%s'\n", name, GLOB(realtimelinetable)); return NULL; } #endif /*! * \brief Find Line by Instance on device * * \todo No ID Specified only instance, should this function be renamed ? * * \callgraph * \callergraph * * \lock * - device->buttonconfig * - see sccp_line_find_byname_wo() */ #if DEBUG /*! * \param d SCCP Device * \param instance line instance as int * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Line (can be null) */ sccp_line_t *__sccp_line_find_byid(sccp_device_t * d, uint16_t instance, const char *filename, int lineno, const char *func) #else /*! * \param d SCCP Device * \param instance line instance as int * \return SCCP Line (can be null) */ sccp_line_t *sccp_line_find_byid(sccp_device_t * d, uint16_t instance) #endif { sccp_line_t *l = NULL; sccp_buttonconfig_t *config; sccp_log((DEBUGCAT_LINE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Looking for line with instance %d.\n", DEV_ID_LOG(d), instance); if (!d || instance == 0) return NULL; SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, config, list) { sccp_log((DEBUGCAT_LINE | DEBUGCAT_DEVICE | DEBUGCAT_BUTTONTEMPLATE)) (VERBOSE_PREFIX_3 "%s: button instance %d, type: %d\n", DEV_ID_LOG(d), config->instance, config->type); if (config && config->type == LINE && config->instance == instance && !sccp_strlen_zero(config->button.line.name)) { #if DEBUG l = __sccp_line_find_byname(config->button.line.name, TRUE, filename, lineno, func); #else l = sccp_line_find_byname(config->button.line.name, TRUE); #endif break; } } SCCP_LIST_UNLOCK(&d->buttonconfig); if (!l) { sccp_log((DEBUGCAT_LINE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: No line found with instance %d.\n", DEV_ID_LOG(d), instance); return NULL; } sccp_log((DEBUGCAT_LINE | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: Found line %s\n", "SCCP", l->name); return l; } /*! * \brief Get Device Configuration * \param device SCCP Device * \param line SCCP Line * \param filename Debug FileName * \param lineno Debug LineNumber * \param func Debug Function Name * \return SCCP Line Devices * * \callgraph * \callergraph * * \warning * - line->devices is not always locked */ sccp_linedevices_t *__sccp_linedevice_find(const sccp_device_t * device, const sccp_line_t * line, const char *filename, int lineno, const char *func) { if (!line) { pbx_log(LOG_NOTICE, "%s: [%s:%d]->linedevice_find: No line provided to search in\n", DEV_ID_LOG(device), filename, lineno); return NULL; } if (!device) { pbx_log(LOG_NOTICE, "SCCP: [%s:%d]->linedevice_find: No device provided to search for (line: %s)\n", filename, lineno, line ? line->name : "UNDEF"); return NULL; } sccp_linedevices_t *linedevice = NULL; sccp_linedevices_t *ld = NULL; SCCP_LIST_LOCK(&((sccp_line_t *) line)->devices); SCCP_LIST_TRAVERSE(&((sccp_line_t *) line)->devices, linedevice, list) { sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "linedevice %p for device %s line %s\n", linedevice, DEV_ID_LOG(linedevice->device), linedevice->line->name); if (device == linedevice->device) { ld = sccp_linedevice_retain(linedevice); sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "%s: found linedevice for line %s. Returning linedevice %p\n", DEV_ID_LOG(device), ld->line->name, ld); break; } } SCCP_LIST_UNLOCK(&((sccp_line_t *) line)->devices); if (!ld) { sccp_log(DEBUGCAT_LINE) (VERBOSE_PREFIX_3 "%s: [%s:%d]->linedevice_find: linedevice for line %s could not be found. Returning NULL\n", DEV_ID_LOG(device), filename, lineno, line->name); } return ld; }
722,262
./chan-sccp-b/src/sccp_softkeys.c
/*! * \file sccp_softkeys.c * \brief SCCP SoftKeys Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /* private prototypes */ void sccp_sk_videomode(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c); /* done */ /*! * \brief Global list of softkeys */ struct softKeySetConfigList softKeySetConfig; /*!< List of SoftKeySets */ /*! * \brief Softkey Pre Reload * * \lock * - softKeySetConfig */ void sccp_softkey_pre_reload(void) { // sccp_softKeySetConfiguration_t *k; // uint8_t i; // // SCCP_LIST_LOCK(&softKeySetConfig); // while ((k = SCCP_LIST_REMOVE_HEAD(&softKeySetConfig, list))) { // sccp_log((DEBUGCAT_CONFIG | DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "Setting SoftkeySetConfig to Pending Delete=1\n"); // for (i = 0; i < (sizeof(SoftKeyModes) / sizeof(softkey_modes)); i++) { // if(k->modes[i].ptr) // sccp_free(k->modes[i].ptr); // } // sccp_free(k); // } // SCCP_LIST_UNLOCK(&softKeySetConfig); } /*! * \brief Softkey Post Reload */ void sccp_softkey_post_reload(void) { } void sccp_softkey_clear() { sccp_softKeySetConfiguration_t *k; uint8_t i; SCCP_LIST_LOCK(&softKeySetConfig); while ((k = SCCP_LIST_REMOVE_HEAD(&softKeySetConfig, list))) { for (i = 0; i < (sizeof(SoftKeyModes) / sizeof(softkey_modes)); i++) { if (k->modes[i].ptr) sccp_free(k->modes[i].ptr); } sccp_free(k); } SCCP_LIST_UNLOCK(&softKeySetConfig); } /*! * \brief Softkey Function Callback by SKINNY LABEL */ static const struct sccp_softkeyMap_cb softkeyCbMap[] = { {SKINNY_LBL_NEWCALL, sccp_sk_newcall, FALSE}, {SKINNY_LBL_REDIAL, sccp_sk_redial, FALSE}, {SKINNY_LBL_MEETME, sccp_sk_meetme, TRUE}, {SKINNY_LBL_BARGE, sccp_sk_barge, TRUE}, {SKINNY_LBL_CBARGE, sccp_sk_cbarge, TRUE}, {SKINNY_LBL_HOLD, sccp_sk_hold, TRUE}, {SKINNY_LBL_TRANSFER, sccp_sk_transfer, TRUE}, {SKINNY_LBL_CFWDALL, sccp_sk_cfwdall, FALSE}, {SKINNY_LBL_CFWDBUSY, sccp_sk_cfwdbusy, FALSE}, {SKINNY_LBL_CFWDNOANSWER, sccp_sk_cfwdnoanswer, FALSE}, {SKINNY_LBL_BACKSPACE, sccp_sk_backspace, TRUE}, {SKINNY_LBL_ENDCALL, sccp_sk_endcall, TRUE}, {SKINNY_LBL_RESUME, sccp_sk_resume, TRUE}, {SKINNY_LBL_ANSWER, sccp_sk_answer, TRUE}, {SKINNY_LBL_TRNSFVM, sccp_sk_trnsfvm, TRUE}, {SKINNY_LBL_IDIVERT, sccp_sk_trnsfvm, TRUE}, {SKINNY_LBL_DND, sccp_sk_dnd, FALSE}, {SKINNY_LBL_DIRTRFR, sccp_sk_dirtrfr, TRUE}, {SKINNY_LBL_SELECT, sccp_sk_select, TRUE}, {SKINNY_LBL_PRIVATE, sccp_sk_private, TRUE}, {SKINNY_LBL_MONITOR, sccp_feat_monitor, TRUE}, {SKINNY_LBL_INTRCPT, sccp_sk_resume, TRUE}, {SKINNY_LBL_DIAL, sccp_sk_dial, TRUE}, {SKINNY_LBL_VIDEO_MODE, sccp_sk_videomode, TRUE}, #ifdef CS_SCCP_PARK {SKINNY_LBL_PARK, sccp_sk_park, TRUE}, #endif #ifdef CS_SCCP_PICKUP {SKINNY_LBL_PICKUP, sccp_sk_pickup, FALSE}, {SKINNY_LBL_GPICKUP, sccp_sk_gpickup, FALSE}, #endif #ifdef CS_SCCP_CONFERENCE {SKINNY_LBL_CONFRN, sccp_sk_conference, TRUE}, {SKINNY_LBL_JOIN, sccp_sk_join, TRUE}, {SKINNY_LBL_CONFLIST, sccp_sk_conflist, TRUE}, #endif }; /*! * \brief Get SoftkeyMap by Event */ const sccp_softkeyMap_cb_t *sccp_getSoftkeyMap_by_SoftkeyEvent(uint32_t event) { uint8_t i; for (i = 0; i < ARRAY_LEN(softkeyCbMap); i++) { if (softkeyCbMap[i].event == event) { return &softkeyCbMap[i]; } } return NULL; } /*! * \brief Enable or Disable one softkey on a specific softKeySet * \param device SCCP Device () * \param softKeySet SoftkeySet \see SoftKeyModes * \param softKey softkey e.g. SKINNY_LBL_REDIAL * \param enable enabled or disabled * */ void sccp_softkey_setSoftkeyState(sccp_device_t * device, uint8_t softKeySet, uint8_t softKey, boolean_t enable) { uint8_t i; /* find softkey */ for (i = 0; i < device->softKeyConfiguration.modes[softKeySet].count; i++) { if (device->softKeyConfiguration.modes[softKeySet].ptr[i] == softKey) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: found softkey '%s' at %d\n", DEV_ID_LOG(device), label2str(device->softKeyConfiguration.modes[softKeySet].ptr[i]), i); if (enable) { device->softKeyConfiguration.activeMask[softKeySet] |= (1 << i); } else { device->softKeyConfiguration.activeMask[softKeySet] &= (~(1 << i)); } } } return; } /*! * \brief Forces Dialling before timeout * \n Usage: \ref sccp_sk_dial * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_dial(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Dial Pressed\n", DEV_ID_LOG(d)); if (c) { // Handle termination of dialling if in appropriate state. /* Only handle this in DIALING state. AFAIK GETDIGITS is used only for call forward and related input functions. (-DD) */ if (c->ss_action == SCCP_SS_GETFORWARDEXTEN) { c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_pbx_softswitch(c); } else if (c->state == SCCP_CHANNELSTATE_DIALING) { c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_pbx_softswitch(c); } } } /*! * \brief Start/Stop VideoMode * \n Usage: \ref sccp_sk_videomode * \param device SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param channel SCCP Channel * * \todo Add doxygen entry for sccp_sk_videomode * \todo Implement stopping video transmission */ void sccp_sk_videomode(sccp_device_t * device, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * channel) { #ifdef CS_SCCP_VIDEO if (sccp_device_isVideoSupported(device)) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: We can have video, try to start vrtp\n", DEV_ID_LOG(device)); if (!channel->rtp.video.rtp && !sccp_rtp_createVideoServer(channel)) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: can not start vrtp\n", DEV_ID_LOG(device)); } else { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: vrtp started\n", DEV_ID_LOG(device)); sccp_channel_startMultiMediaTransmission(channel); } } #endif } /*! * \brief Redial last Dialed Number by this Device * \n Usage: \ref sk_redial * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \lock * - channel */ void sccp_sk_redial(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Redial Pressed\n", DEV_ID_LOG(d)); #ifdef CS_ADV_FEATURES if (d->useRedialMenu) { char *data = "<CiscoIPPhoneExecute><ExecuteItem Priority=\"0\" URL=\"Key:Directories\"/><ExecuteItem Priority=\"0\" URL=\"Key:KeyPad3\"/></CiscoIPPhoneExecute>"; d->protocol->sendUserToDeviceDataVersionMessage(d, 0, lineInstance, 0, 0, data, 0); return; } #endif if (sccp_strlen_zero(d->lastNumber)) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: No number to redial\n", d->id); return; } if (c) { if (c->state == SCCP_CHANNELSTATE_OFFHOOK) { /* we have a offhook channel */ sccp_copy_string(c->dialedNumber, d->lastNumber, sizeof(c->dialedNumber)); sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Get ready to redial number %s\n", d->id, d->lastNumber); // c->digittimeout = time(0)+1; c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_pbx_softswitch(c); } /* here's a KEYMODE error. nothing to do */ return; } else { if (!l) { l = sccp_dev_get_activeline(d); c = sccp_channel_newcall(l, d, d->lastNumber, SKINNY_CALLTYPE_OUTBOUND, NULL); c = c ? sccp_channel_release(c) : NULL; l = sccp_line_release(l); } else { c = sccp_channel_newcall(l, d, d->lastNumber, SKINNY_CALLTYPE_OUTBOUND, NULL); c = c ? sccp_channel_release(c) : NULL; } } } /*! * \brief Initiate a New Call * \n Usage: \ref sk_newcall * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_newcall(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { char *adhocNumber = NULL; sccp_speed_t k; sccp_line_t *line = NULL; uint8_t instance = l ? sccp_device_find_index_for_line(d, l->name) : 0; /*!< we use this instance, do determine if this should be a speeddial or a linerequest */ sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey NewCall Pressed\n", DEV_ID_LOG(d)); if (!l || instance != lineInstance) { /* handle dummy speeddial */ sccp_dev_speed_find_byindex(d, lineInstance, TRUE, &k); if (strlen(k.ext) > 0) { adhocNumber = k.ext; } line = l; /*!< use l as line to dialout */ /* use default line if it is set */ if (!line && d && d->defaultLineInstance > 0) { sccp_log((DEBUGCAT_SOFTKEY | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "using default line with instance: %u", d->defaultLineInstance); line = sccp_line_find_byid(d, d->defaultLineInstance); } } else { line = sccp_line_retain(l); } if (!line && d && d->currentLine) line = sccp_dev_get_activeline(d); if (!line) { sccp_dev_starttone(d, SKINNY_TONE_ZIPZIP, 0, 0, 1); sccp_dev_displayprompt(d, 0, 0, "No line available", 5); } else { if (!adhocNumber && (strlen(line->adhocNumber) > 0)) { adhocNumber = line->adhocNumber; } if (adhocNumber) { c = sccp_channel_newcall(line, d, adhocNumber, SKINNY_CALLTYPE_OUTBOUND, NULL); c = c ? sccp_channel_release(c) : NULL; } else { c = sccp_channel_newcall(line, d, NULL, SKINNY_CALLTYPE_OUTBOUND, NULL); c = c ? sccp_channel_release(c) : NULL; } line = sccp_line_release(line); } } /*! * \brief Hold Call on Current Line * \n Usage: \ref sk_hold * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_hold(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Hold Pressed\n", DEV_ID_LOG(d)); if (!c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: No call to put on hold, check your softkeyset, hold should not be available in this situation.\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, 0, 0, "No call to put on hold.", 5); return; } sccp_channel_hold(c); } /*! * \brief Resume Call on Current Line * \n Usage: \ref sk_resume * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_resume(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Resume Pressed\n", DEV_ID_LOG(d)); if (!c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: No call to resume. Ignoring\n", d->id); return; } sccp_channel_resume(d, c, TRUE); } /*! * \brief Transfer Call on Current Line * \n Usage: \ref sk_transfer * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \todo discus Marcello's transfer experiment * * \lock * - device->selectedChannels * - device->buttonconfig * - see sccp_line_find_byname() * - line->channels */ void sccp_sk_transfer(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_channel_transfer(c, d); } /*! * \brief End Call on Current Line * \n Usage: \ref sk_endcall * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_endcall(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey EndCall Pressed\n", DEV_ID_LOG(d)); if (!c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Endcall with no call in progress\n", d->id); return; } sccp_channel_endcall(c); } /*! * \brief Set DND on Current Line if Line is Active otherwise set on Device * \n Usage: \ref sk_dnd * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \todo The line param is not used */ void sccp_sk_dnd(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { if (!d) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: sccp_sk_dnd function called without specifying a device\n"); return; } sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey DND Pressed (Current Status: %s, Feature enabled: %s)\n", DEV_ID_LOG(d), dndmode2str(d->dndFeature.status), d->dndFeature.enabled ? "YES" : "NO"); if (!d->dndFeature.enabled) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: SoftKey DND Feature disabled\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, 0, 0, SKINNY_DISP_DND " " SKINNY_DISP_SERVICE_IS_NOT_ACTIVE, 10); return; } if (!strcasecmp(d->dndFeature.configOptions, "reject")) { /* config is set to: dnd=reject */ if (d->dndFeature.status == SCCP_DNDMODE_OFF) d->dndFeature.status = SCCP_DNDMODE_REJECT; else d->dndFeature.status = SCCP_DNDMODE_OFF; } else if (!strcasecmp(d->dndFeature.configOptions, "silent")) { /* config is set to: dnd=silent */ if (d->dndFeature.status == SCCP_DNDMODE_OFF) d->dndFeature.status = SCCP_DNDMODE_SILENT; else d->dndFeature.status = SCCP_DNDMODE_OFF; } else { /* for all other config us the toggle mode */ switch (d->dndFeature.status) { case SCCP_DNDMODE_OFF: d->dndFeature.status = SCCP_DNDMODE_REJECT; break; case SCCP_DNDMODE_REJECT: d->dndFeature.status = SCCP_DNDMODE_SILENT; break; case SCCP_DNDMODE_SILENT: d->dndFeature.status = SCCP_DNDMODE_OFF; break; default: d->dndFeature.status = SCCP_DNDMODE_OFF; break; } } sccp_feat_changed(d, NULL, SCCP_FEATURE_DND); /* notify the modules the the DND-feature changed state */ sccp_dev_check_displayprompt(d); /*! \todo we should use the feature changed event to check displayprompt */ sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey DND Pressed (New Status: %s, Feature enabled: %s)\n", DEV_ID_LOG(d), dndmode2str(d->dndFeature.status), d->dndFeature.enabled ? "YES" : "NO"); } /*! * \brief BackSpace Last Entered Number * \n Usage: \ref sk_backspace * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \lock * - channel * - see sccp_handle_dialtone_nolock() */ void sccp_sk_backspace(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Backspace Pressed\n", DEV_ID_LOG(d)); int len; if ((c->state != SCCP_CHANNELSTATE_DIALING) && (c->state != SCCP_CHANNELSTATE_DIGITSFOLL) && (c->state != SCCP_CHANNELSTATE_OFFHOOK)) { return; } len = strlen(c->dialedNumber); /* we have no number, so nothing to process */ if (!len) { return; } if (len > 1) { c->dialedNumber[len - 1] = '\0'; /* removing scheduled dial */ c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); /* rescheduling dial timeout (one digit) */ if ((c->scheduler.digittimeout = sccp_sched_add(GLOB(digittimeout) * 1000, sccp_pbx_sched_dial, c)) < 0) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: (sccp_sk_backspace) Unable to reschedule dialing in '%d' s\n", GLOB(digittimeout)); } } else if (len == 1) { c->dialedNumber[len - 1] = '\0'; /* removing scheduled dial */ c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); /* rescheduling dial timeout (no digits) */ if ((c->scheduler.digittimeout = sccp_sched_add(GLOB(firstdigittimeout) * 1000, sccp_pbx_sched_dial, c)) < 0) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: (sccp_sk_backspace) Unable to reschedule dialing in '%d' s\n", GLOB(firstdigittimeout)); } } // sccp_log((DEBUGCAT_SOFTKEY))(VERBOSE_PREFIX_3 "%s: backspacing dial number %s\n", c->device->id, c->dialedNumber); sccp_handle_dialtone(c); sccp_handle_backspace(d, lineInstance, c->callid); } /*! * \brief Answer Incoming Call * \n Usage: \ref sk_answer * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_answer(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { if (!c) { if (l) ast_log(LOG_WARNING, "%s: (sccp_sk_answer) Pressed the answer key without any channel on line %s\n", d->id, l->name); return; } sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Answer Pressed, instance: %d\n", DEV_ID_LOG(d), lineInstance); if (c->owner) pbx_channel_lock(c->owner); sccp_channel_answer(d, c); if (c->owner) pbx_channel_unlock(c->owner); } /*! * \brief Bridge two selected channels * \n Usage: \ref sk_dirtrfr * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \lock * - line->channels * - device->selectedChannels * - device->selectedChannels * - device */ void sccp_sk_dirtrfr(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Direct Transfer Pressed\n", DEV_ID_LOG(d)); sccp_selectedchannel_t *x; sccp_channel_t *chan1 = NULL, *chan2 = NULL, *tmp = NULL; if (!(d = sccp_device_retain(d))) return; if ((sccp_device_selectedchannels_count(d)) != 2) { if (SCCP_RWLIST_GETSIZE(l->channels) == 2) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Automatically select the two current channels\n", d->id); SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { x = sccp_malloc(sizeof(sccp_selectedchannel_t)); if (x != NULL) { x->channel = c; SCCP_LIST_LOCK(&d->selectedChannels); SCCP_LIST_INSERT_HEAD(&d->selectedChannels, x, list); SCCP_LIST_UNLOCK(&d->selectedChannels); } } SCCP_LIST_UNLOCK(&l->channels); } else if (SCCP_RWLIST_GETSIZE(l->channels) < 2) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: Not enough channels to transfer\n", d->id); sccp_dev_displayprompt(d, lineInstance, c->callid, "Not enough calls to trnsf", 5); // sccp_dev_displayprompt(d, 0, 0, SKINNY_DISP_CAN_NOT_COMPLETE_TRANSFER, 5); return; } else { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: More than 2 channels to transfer, please use softkey select\n", d->id); sccp_dev_displayprompt(d, lineInstance, c->callid, "More than 2 calls, use " SKINNY_DISP_SELECT, 5); // sccp_dev_displayprompt(d, 0, 0, SKINNY_DISP_CAN_NOT_COMPLETE_TRANSFER, 5); return; } } SCCP_LIST_LOCK(&d->selectedChannels); x = SCCP_LIST_FIRST(&d->selectedChannels); chan1 = sccp_channel_retain(x->channel); chan2 = SCCP_LIST_NEXT(x, list)->channel; chan2 = sccp_channel_retain(chan2); SCCP_LIST_UNLOCK(&d->selectedChannels); if (chan1 && chan2) { //for using the sccp_channel_transfer_complete function //chan2 must be in RINGOUT or CONNECTED state sccp_dev_displayprompt(d, 0, 0, SKINNY_DISP_CALL_TRANSFER, 5); sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_sk_dirtrfr) First Channel Status (%d), Second Channel Status (%d)\n", DEV_ID_LOG(d), chan1->state, chan2->state); if (chan2->state != SCCP_CHANNELSTATE_CONNECTED && chan1->state == SCCP_CHANNELSTATE_CONNECTED) { tmp = chan1; chan1 = chan2; chan2 = tmp; } else if (chan1->state == SCCP_CHANNELSTATE_HOLD && chan2->state == SCCP_CHANNELSTATE_HOLD) { //resume chan2 if both channels are on hold sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_sk_dirtrfr) Resuming Second Channel (%d)\n", DEV_ID_LOG(d), chan2->state); sccp_channel_resume(d, chan2, TRUE); sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_sk_dirtrfr) Resumed Second Channel (%d)\n", DEV_ID_LOG(d), chan2->state); } sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_sk_dirtrfr) First Channel Status (%d), Second Channel Status (%d)\n", DEV_ID_LOG(d), chan1->state, chan2->state); d->transferChannels.transferee = sccp_channel_retain(chan1); d->transferChannels.transferer = sccp_channel_retain(chan2); sccp_channel_transfer_complete(chan2); chan1 = sccp_channel_release(chan1); chan2 = sccp_channel_release(chan2); } d = sccp_device_release(d); } /*! * \brief Select a Line for further processing by for example DirTrfr * \n Usage: \ref sk_select * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \lock * - device->selectedChannels */ void sccp_sk_select(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Select Pressed\n", DEV_ID_LOG(d)); sccp_selectedchannel_t *x = NULL; sccp_moo_t *r1; uint8_t numSelectedChannels = 0, status = 0; if (!d) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "SCCP: (sccp_sk_select) Can't select a channel without a device\n"); return; } if (!c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_sk_select) No channel to be selected\n", DEV_ID_LOG(d)); return; } if ((x = sccp_device_find_selectedchannel(d, c))) { SCCP_LIST_LOCK(&d->selectedChannels); x = SCCP_LIST_REMOVE(&d->selectedChannels, x, list); SCCP_LIST_UNLOCK(&d->selectedChannels); sccp_free(x); } else { x = sccp_malloc(sizeof(sccp_selectedchannel_t)); if (x != NULL) { x->channel = c; SCCP_LIST_LOCK(&d->selectedChannels); SCCP_LIST_INSERT_HEAD(&d->selectedChannels, x, list); SCCP_LIST_UNLOCK(&d->selectedChannels); status = 1; } } numSelectedChannels = sccp_device_selectedchannels_count(d); sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: (sccp_sk_select) '%d' channels selected\n", DEV_ID_LOG(d), numSelectedChannels); REQ(r1, CallSelectStatMessage); r1->msg.CallSelectStatMessage.lel_status = htolel(status); r1->msg.CallSelectStatMessage.lel_lineInstance = htolel(lineInstance); r1->msg.CallSelectStatMessage.lel_callReference = htolel(c->callid); sccp_dev_send(d, r1); } /*! * \brief Set Call Forward All on Current Line * \n Usage: \ref sk_cfwdall * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_cfwdall(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_line_t *line = NULL; sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Call Forward All Pressed, line: %s, instance: %d, channel: %d\n", DEV_ID_LOG(d), l ? l->name : "(NULL)", lineInstance, c ? c->callid : -1); if (!l && d) { if (d->defaultLineInstance > 0) { line = sccp_line_find_byid(d, d->defaultLineInstance); } if (!line) { line = sccp_dev_get_activeline(d); } if (!line) { line = sccp_line_find_byid(d, 1); } } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_callforward(line, d, SCCP_CFWD_ALL); line = sccp_line_release(line); } else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", DEV_ID_LOG(d)); } /*! * \brief Set Call Forward when Busy on Current Line * \n Usage: \ref sk_cfwdbusy * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_cfwdbusy(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_line_t *line = NULL; sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Call Forward Busy Pressed\n", DEV_ID_LOG(d)); if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_callforward(line, d, SCCP_CFWD_BUSY); line = sccp_line_release(line); } else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); } /*! * \brief Set Call Forward when No Answer on Current Line * \n Usage: \ref sk_cfwdnoanswer * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_cfwdnoanswer(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_line_t *line = NULL; sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Call Forward NoAnswer Pressed\n", DEV_ID_LOG(d)); if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_callforward(line, d, SCCP_CFWD_NOANSWER); line = sccp_line_release(line); } else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); /* sccp_log((DEBUGCAT_SOFTKEY))(VERBOSE_PREFIX_3 "### CFwdNoAnswer Softkey pressed - NOT SUPPORTED\n"); */ } /*! * \brief Park Call on Current Line * \n Usage: \ref sk_park * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_park(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Park Pressed\n", DEV_ID_LOG(d)); #ifdef CS_SCCP_PARK sccp_channel_park(c); #else sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "### Native park was not compiled in\n"); #endif } /*! * \brief Transfer to VoiceMail on Current Line * \n Usage: \ref sk_transfer * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_trnsfvm(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Transfer Voicemail Pressed\n", DEV_ID_LOG(d)); sccp_feat_idivert(d, l, c); } /*! * \brief Initiate Private Call on Current Line * \n Usage: \ref sk_private * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * * \lock * - channel * - see sccp_dev_displayprompt() */ void sccp_sk_private(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { if (!d) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: sccp_sk_private function called without specifying a device\n"); return; } sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Private Pressed\n", DEV_ID_LOG(d)); if (!d->privacyFeature.enabled) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: private function is not active on this device\n", d->id); sccp_dev_displayprompt(d, lineInstance, 0, "PRIVATE function is not active", 5); return; } if (!c) { sccp_dev_displayprompt(d, lineInstance, 0, "PRIVATE with no channel active", 5); return; } c->privacy = (c->privacy) ? FALSE : TRUE; // d->privacyFeature.status = c->privacy; // should not be activeted on softkey // sccp_feat_changed(d, NULL, SCCP_FEATURE_PRIVACY); if (c->privacy) { sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_PRIVATE, 0); c->callInfo.presentation = 0; } else { sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_ENTER_NUMBER, 1); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Private %s on call %d\n", d->id, c->privacy ? "enabled" : "disabled", c->callid); } /*! * \brief Put Current Line into Conference * \n Usage: \ref sk_conference * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others */ void sccp_sk_conference(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Conference Pressed\n", DEV_ID_LOG(d)); #ifdef CS_SCCP_CONFERENCE sccp_feat_handle_conference(d, l, lineInstance, c); #else sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "### Conference was not compiled in\n"); #endif } /*! * \brief Show Participant List of Current Conference * \n Usage: \ref sk_conflist * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \todo Conferencing option is under development. */ void sccp_sk_conflist(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Conflist Pressed\n", DEV_ID_LOG(d)); sccp_feat_conflist(d, l, lineInstance, c); } /*! * \brief Join Current Line to Conference * \n Usage: \ref sk_join * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \todo Conferencing option needs to be build and implemented */ void sccp_sk_join(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Join Pressed\n", DEV_ID_LOG(d)); sccp_feat_join(d, l, lineInstance, c); } /*! * \brief Barge into Call on the Current Line * \n Usage: \ref sk_barge * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_barge(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_line_t *line = NULL; sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Barge Pressed\n", DEV_ID_LOG(d)); if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_barge(line, lineInstance, d); line = sccp_line_release(line); } else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); } /*! * \brief Barge into Call on the Current Line * \n Usage: \ref sk_cbarge * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_cbarge(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_line_t *line = NULL; sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey cBarge Pressed\n", DEV_ID_LOG(d)); if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_cbarge(line, lineInstance, d); line = sccp_line_release(line); } else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); } /*! * \brief Put Current Line in to Meetme Conference * \n Usage: \ref sk_meetme * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others */ void sccp_sk_meetme(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_line_t *line = NULL; sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Meetme Pressed\n", DEV_ID_LOG(d)); if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_meetme(line, lineInstance, d); line = sccp_line_release(line); } else sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); } /*! * \brief Pickup Parked Call * \n Usage: \ref sk_pickup * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_pickup(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Pickup Pressed\n", DEV_ID_LOG(d)); #ifndef CS_SCCP_PICKUP sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "### Native EXTENSION PICKUP was not compiled in\n"); #else sccp_line_t *line = NULL; if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_handle_directed_pickup(line, lineInstance, d); line = sccp_line_release(line); if (c && c->scheduler.digittimeout) c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); } #endif } /*! * \brief Pickup Ringing Line from Pickup Group * \n Usage: \ref sk_gpickup * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel */ void sccp_sk_gpickup(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: SoftKey Group Pickup Pressed\n", DEV_ID_LOG(d)); #ifndef CS_SCCP_PICKUP sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "### Native GROUP PICKUP was not compiled in\n"); #else sccp_line_t *line = NULL; if (!l && d) { line = sccp_line_find_byid(d, 1); } else { line = sccp_line_retain(l); } if (line) { sccp_feat_grouppickup(line, d); line = sccp_line_release(line); if (c && c->scheduler.digittimeout) c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line found\n", d->id); } #endif } /*! * \brief sets a SoftKey to a specified status (on/off) * * \param d SCCP Device * \param l active line * \param lineInstance lineInstance as uint8_t * \param c active channel * \param keymode int of KEYMODE_* * \param softkeyindex index of the SoftKey to set * \param status 0 for off otherwise on * * \todo use SoftKeyLabel instead of softkeyindex */ void sccp_sk_set_keystate(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c, unsigned int keymode, unsigned int softkeyindex, unsigned int status) { sccp_moo_t *r; uint32_t mask, validKeyMask; unsigned i; if (!l || !c || !d || !d->session) return; REQ(r, SelectSoftKeysMessage); r->msg.SelectSoftKeysMessage.lel_lineInstance = htolel(lineInstance); r->msg.SelectSoftKeysMessage.lel_callReference = htolel(c->callid); r->msg.SelectSoftKeysMessage.lel_softKeySetIndex = htolel(keymode); //r->msg.SelectSoftKeysMessage.les_validKeyMask = 0xFFFFFFFF; /* htolel(65535); */ validKeyMask = 0xFFFFFFFF; mask = 1; for (i = 1; i <= softkeyindex; i++) { mask = (mask << 1); } if (status == 0) //disable softkey mask = ~(validKeyMask & mask); else mask = validKeyMask | mask; r->msg.SelectSoftKeysMessage.les_validKeyMask = htolel(mask); sccp_log((DEBUGCAT_SOFTKEY)) (VERBOSE_PREFIX_3 "%s: Send softkeyset to %s(%d) on line %d and call %d\n", d->id, keymode2str(5), 5, lineInstance, c->callid); sccp_dev_send(d, r); }
722,263
./chan-sccp-b/src/sccp_cli.c
/*! * \file sccp_cli.c * \brief SCCP CLI Class * \author Sergio Chersovani <mlists [at] c-net.it> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ /*! * \remarks Purpose: SCCP CLI * When to use: Only methods directly related to the asterisk cli interface should be stored in this source file. * Relationships: Calls ??? */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") #include <asterisk/cli.h> typedef enum sccp_cli_completer { SCCP_CLI_NULL_COMPLETER, SCCP_CLI_DEVICE_COMPLETER, SCCP_CLI_CONNECTED_DEVICE_COMPLETER, SCCP_CLI_LINE_COMPLETER, SCCP_CLI_CONNECTED_LINE_COMPLETER, SCCP_CLI_CHANNEL_COMPLETER, SCCP_CLI_CONFERENCE_COMPLETER, SCCP_CLI_DEBUG_COMPLETER, SCCP_CLI_SET_COMPLETER, } sccp_cli_completer_t; static char *sccp_exec_completer(sccp_cli_completer_t completer, OLDCONST char *line, OLDCONST char *word, int pos, int state); /* --- CLI Tab Completion ---------------------------------------------------------------------------------------------- */ /*! * \brief Complete Device * \param line Line as char * \param word Word as char * \param pos Pos as int * \param state State as int * \return Result as char * * \called_from_asterisk * * \lock * - devices */ static char *sccp_complete_device(OLDCONST char *line, OLDCONST char *word, int pos, int state) { sccp_device_t *d; int wordlen = strlen(word), which = 0; char *ret = NULL; SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (!strncasecmp(word, d->id, wordlen) && ++which > state) { ret = strdup(d->id); break; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); return ret; } static char *sccp_complete_connected_device(OLDCONST char *line, OLDCONST char *word, int pos, int state) { sccp_device_t *d; int wordlen = strlen(word), which = 0; char *ret = NULL; SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (!strncasecmp(word, d->id, wordlen) && d->registrationState != SKINNY_DEVICE_RS_NONE && ++which > state) { ret = strdup(d->id); break; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); return ret; } /*! * \brief Complete Line * \param line Line as char * \param word Word as char * \param pos Pos as int * \param state State as int * \return Result as char * * \called_from_asterisk * * \lock * - lines */ static char *sccp_complete_line(OLDCONST char *line, OLDCONST char *word, int pos, int state) { sccp_line_t *l; int wordlen = strlen(word), which = 0; char *ret = NULL; SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { if (!strncasecmp(word, l->name, wordlen) && ++which > state) { ret = strdup(l->name); break; } } SCCP_RWLIST_UNLOCK(&GLOB(lines)); return ret; } static char *sccp_complete_connected_line(OLDCONST char *line, OLDCONST char *word, int pos, int state) { sccp_line_t *l; int wordlen = strlen(word), which = 0; char *ret = NULL; SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { if (!strncasecmp(word, l->name, wordlen) && SCCP_LIST_GETSIZE(&l->devices) > 0 && ++which > state) { ret = strdup(l->name); break; } } SCCP_RWLIST_UNLOCK(&GLOB(lines)); return ret; } /*! * \brief Complete Channel * \param line Line as char * \param word Word as char * \param pos Pos as int * \param state State as int * \return Result as char * * \called_from_asterisk * * \lock * - lines */ static char *sccp_complete_channel(OLDCONST char *line, OLDCONST char *word, int pos, int state) { sccp_line_t *l; sccp_channel_t *c; int wordlen = strlen(word), which = 0; char *ret = NULL; char tmpname[20]; SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { snprintf(tmpname, sizeof(tmpname), "SCCP/%s-%08x", l->name, c->callid); if (!strncasecmp(word, tmpname, wordlen) && ++which > state) { ret = strdup(tmpname); break; } } SCCP_LIST_UNLOCK(&l->channels); } SCCP_RWLIST_UNLOCK(&GLOB(lines)); return ret; } /*! * \brief Complete Debug * \param line Line as char * \param word Word as char * \param pos Pos as int * \param state State as int * \return Result as char * * \called_from_asterisk */ static char *sccp_complete_debug(OLDCONST char *line, OLDCONST char *word, int pos, int state) { uint8_t i; int wordlen = strlen(word); int which = 0; char *ret = NULL; boolean_t debugno = 0; char *extra_cmds[3] = { "no", "none", "all" }; // check if the sccp debug line contains no before the categories if (!strncasecmp(line, "sccp debug no ", strlen("sccp debug no "))) { debugno = 1; } // check extra_cmd for (i = 0; i < ARRAY_LEN(extra_cmds); i++) { if (!strncasecmp(word, extra_cmds[i], wordlen)) { // skip "no" and "none" if in debugno mode if (debugno && !strncasecmp("no", extra_cmds[i], strlen("no"))) continue; if (++which > state) return strdup(extra_cmds[i]); } } // check categories for (i = 0; i < ARRAY_LEN(sccp_debug_categories); i++) { // if in debugno mode if (debugno) { // then skip the categories which are not currently active if ((GLOB(debug) & sccp_debug_categories[i].category) != sccp_debug_categories[i].category) continue; } else { // not debugno then skip the categories which are already active if ((GLOB(debug) & sccp_debug_categories[i].category) == sccp_debug_categories[i].category) continue; } // find a match with partial category if (!strncasecmp(word, sccp_debug_categories[i].key, wordlen)) { if (++which > state) return strdup(sccp_debug_categories[i].key); } } return ret; } /*! * \brief Complete Debug * \param line Line as char * \param word Word as char * \param pos Pos as int * \param state State as int * \return Result as char * * \called_from_asterisk */ static char *sccp_complete_set(OLDCONST char *line, OLDCONST char *word, int pos, int state) { uint8_t i; sccp_device_t *d; sccp_channel_t *c; sccp_line_t *l; int wordlen = strlen(word), which = 0; char tmpname[80]; char *ret = NULL; char *types[] = { "device", "channel", "line"}; char *properties_channel[] = { "hold"}; char *properties_device[] = { "ringtone", "backgroundImage"}; char *values_hold[] = { "on", "off"}; switch (pos) { case 2: // type for (i = 0; i < ARRAY_LEN(types); i++) { if (!strncasecmp(word, types[i], wordlen) && ++which > state) { return strdup(types[i]); } } break; case 3: // device / channel / line if( strstr(line, "device") != NULL ){ SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { if (!strncasecmp(word, d->id, wordlen) && ++which > state) { ret = strdup(d->id); break; } } SCCP_RWLIST_UNLOCK(&GLOB(devices)); } else if( strstr(line, "channel") != NULL ){ SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, c, list) { snprintf(tmpname, sizeof(tmpname), "SCCP/%s-%08x", l->name, c->callid); if (!strncasecmp(word, tmpname, wordlen) && ++which > state) { ret = strdup(tmpname); break; } } SCCP_LIST_UNLOCK(&l->channels); } SCCP_RWLIST_UNLOCK(&GLOB(lines)); } break; case 4: // properties if( strstr(line, "device") != NULL ){ for (i = 0; i < ARRAY_LEN(properties_device); i++) { if (!strncasecmp(word, properties_device[i], wordlen) && ++which > state) { return strdup(properties_device[i]); } } } else if( strstr(line, "channel") != NULL ){ for (i = 0; i < ARRAY_LEN(properties_channel); i++) { if (!strncasecmp(word, properties_channel[i], wordlen) && ++which > state) { return strdup(properties_channel[i]); } } } break; case 5: // values_hold if( strstr(line, "channel") != NULL && strstr(line, "hold") != NULL ){ for (i = 0; i < ARRAY_LEN(values_hold); i++) { if (!strncasecmp(word, values_hold[i], wordlen) && ++which > state) { return strdup(values_hold[i]); } } } break; default: break; } return ret; } static char *sccp_exec_completer(sccp_cli_completer_t completer, OLDCONST char *line, OLDCONST char *word, int pos, int state) { switch (completer) { case SCCP_CLI_NULL_COMPLETER: return NULL; break; case SCCP_CLI_DEVICE_COMPLETER: return sccp_complete_device(line, word, pos, state); break; case SCCP_CLI_CONNECTED_DEVICE_COMPLETER: return sccp_complete_connected_device(line, word, pos, state); break; case SCCP_CLI_LINE_COMPLETER: return sccp_complete_line(line, word, pos, state); break; case SCCP_CLI_CONNECTED_LINE_COMPLETER: return sccp_complete_connected_line(line, word, pos, state); break; case SCCP_CLI_CHANNEL_COMPLETER: return sccp_complete_channel(line, word, pos, state); break; case SCCP_CLI_CONFERENCE_COMPLETER: #ifdef CS_SCCP_CONFERENCE return sccp_complete_conference(line, word, pos, state); #endif break; case SCCP_CLI_DEBUG_COMPLETER: return sccp_complete_debug(line, word, pos, state); break; case SCCP_CLI_SET_COMPLETER: return sccp_complete_set(line, word, pos, state); break; } return NULL; } /* --- Support Functions ---------------------------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------------------------------------SHOW GLOBALS- */ /*! * \brief Show Globals * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - globals */ //static int sccp_show_globals(int fd, int argc, char *argv[]) static int sccp_show_globals(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { char pref_buf[256]; struct ast_str *callgroup_buf = pbx_str_alloca(512); #ifdef CS_SCCP_PICKUP struct ast_str *pickupgroup_buf = pbx_str_alloca(512); #endif struct ast_str *ha_buf = pbx_str_alloca(512); char *debugcategories; int local_total = 0; const char *actionid = ""; sccp_globals_lock(lock); sccp_multiple_codecs2str(pref_buf, sizeof(pref_buf) - 1, GLOB(global_preferences), ARRAY_LEN(GLOB(global_preferences))); debugcategories = sccp_get_debugcategories(GLOB(debug)); sccp_print_ha(ha_buf, sizeof(ha_buf), GLOB(ha)); if (!s) { CLI_AMI_OUTPUT(fd, s, "\n--- SCCP channel driver global settings ----------------------------------------------------------------------------------\n"); } else { astman_send_listack(s, m, argv[0], "start"); CLI_AMI_OUTPUT_PARAM("Event", CLI_AMI_LIST_WIDTH, "%s", "SCCPGlobalSettings"); actionid = astman_get_header(m, "ActionID"); if (!pbx_strlen_zero(actionid)) { astman_append(s, "ActionID: %s\r\n", actionid); } astman_append(s, "\r\n"); } CLI_AMI_OUTPUT_PARAM("Config File", CLI_AMI_LIST_WIDTH, "%s", GLOB(config_file_name)); #if SCCP_PLATFORM_BYTE_ORDER == SCCP_LITTLE_ENDIAN CLI_AMI_OUTPUT_PARAM("Platform byte order", CLI_AMI_LIST_WIDTH, "%s", "LITTLE ENDIAN"); #else CLI_AMI_OUTPUT_PARAM("Platform byte order", CLI_AMI_LIST_WIDTH, "%s", "BIG ENDIAN"); #endif // CLI_AMI_OUTPUT_PARAM("Protocol Version", CLI_AMI_LIST_WIDTH, "%d", GLOB(protocolversion)); CLI_AMI_OUTPUT_PARAM("Server Name", CLI_AMI_LIST_WIDTH, "%s", GLOB(servername)); CLI_AMI_OUTPUT_PARAM("Bind Address", CLI_AMI_LIST_WIDTH, "%s:%d", pbx_inet_ntoa(GLOB(bindaddr.sin_addr)), ntohs(GLOB(bindaddr.sin_port))); CLI_AMI_OUTPUT_BOOL("Nat", CLI_AMI_LIST_WIDTH, GLOB(nat)); CLI_AMI_OUTPUT_PARAM("Extern Hostname", CLI_AMI_LIST_WIDTH, "%s", GLOB(externhost)); CLI_AMI_OUTPUT_PARAM("Extern Host Refresh", CLI_AMI_LIST_WIDTH, "%d", GLOB(externrefresh)); CLI_AMI_OUTPUT_PARAM("Extern IP", CLI_AMI_LIST_WIDTH, "%s:%d", pbx_inet_ntoa(GLOB(externip.sin_addr)), ntohs(GLOB(externip.sin_port))); CLI_AMI_OUTPUT_PARAM("Deny/Permit", CLI_AMI_LIST_WIDTH, "%s", pbx_str_buffer(ha_buf)); CLI_AMI_OUTPUT_BOOL("Direct RTP", CLI_AMI_LIST_WIDTH, GLOB(directrtp)); CLI_AMI_OUTPUT_PARAM("Keepalive", CLI_AMI_LIST_WIDTH, "%d", GLOB(keepalive)); CLI_AMI_OUTPUT_PARAM("Debug", CLI_AMI_LIST_WIDTH, "(%d) %s", GLOB(debug), debugcategories); CLI_AMI_OUTPUT_PARAM("Date format", CLI_AMI_LIST_WIDTH, "%s", GLOB(dateformat)); CLI_AMI_OUTPUT_PARAM("First digit timeout", CLI_AMI_LIST_WIDTH, "%d", GLOB(firstdigittimeout)); CLI_AMI_OUTPUT_PARAM("Digit timeout", CLI_AMI_LIST_WIDTH, "%d", GLOB(digittimeout)); CLI_AMI_OUTPUT_PARAM("Digit timeout char", CLI_AMI_LIST_WIDTH, "%c", GLOB(digittimeoutchar)); CLI_AMI_OUTPUT_PARAM("SCCP tos (signaling)", CLI_AMI_LIST_WIDTH, "%d", GLOB(sccp_tos)); CLI_AMI_OUTPUT_PARAM("SCCP cos (signaling)", CLI_AMI_LIST_WIDTH, "%d", GLOB(sccp_cos)); CLI_AMI_OUTPUT_PARAM("AUDIO tos (rtp)", CLI_AMI_LIST_WIDTH, "%d", GLOB(audio_tos)); CLI_AMI_OUTPUT_PARAM("AUDIO cos (rtp)", CLI_AMI_LIST_WIDTH, "%d", GLOB(audio_cos)); CLI_AMI_OUTPUT_PARAM("VIDEO tos (vrtp)", CLI_AMI_LIST_WIDTH, "%d", GLOB(video_tos)); CLI_AMI_OUTPUT_PARAM("VIDEO cos (vrtp)", CLI_AMI_LIST_WIDTH, "%d", GLOB(video_cos)); CLI_AMI_OUTPUT_PARAM("Context", CLI_AMI_LIST_WIDTH, "%s (%s)", GLOB(context), pbx_context_find(GLOB(context)) ? "exists" : "does not exist !!"); CLI_AMI_OUTPUT_PARAM("Language", CLI_AMI_LIST_WIDTH, "%s", GLOB(language)); CLI_AMI_OUTPUT_PARAM("Accountcode", CLI_AMI_LIST_WIDTH, "%s", GLOB(accountcode)); CLI_AMI_OUTPUT_PARAM("Musicclass", CLI_AMI_LIST_WIDTH, "%s", GLOB(musicclass)); CLI_AMI_OUTPUT_PARAM("AMA flags", CLI_AMI_LIST_WIDTH, "%d (%s)", GLOB(amaflags), pbx_cdr_flags2str(GLOB(amaflags))); sccp_print_group(callgroup_buf, sizeof(callgroup_buf), GLOB(callgroup)); CLI_AMI_OUTPUT_PARAM("Callgroup", CLI_AMI_LIST_WIDTH, "%s", callgroup_buf ? pbx_str_buffer(callgroup_buf) : ""); #ifdef CS_SCCP_PICKUP sccp_print_group(pickupgroup_buf, sizeof(pickupgroup_buf), GLOB(pickupgroup)); CLI_AMI_OUTPUT_PARAM("Pickupgroup", CLI_AMI_LIST_WIDTH, "%s", pickupgroup_buf ? pbx_str_buffer(pickupgroup_buf) : ""); CLI_AMI_OUTPUT_BOOL("Pickup Mode Answer ", CLI_AMI_LIST_WIDTH, GLOB(directed_pickup_modeanswer)); #endif CLI_AMI_OUTPUT_PARAM("Codecs preference", CLI_AMI_LIST_WIDTH, "%s", pref_buf); CLI_AMI_OUTPUT_BOOL("CFWDALL ", CLI_AMI_LIST_WIDTH, GLOB(cfwdall)); CLI_AMI_OUTPUT_BOOL("CFWBUSY ", CLI_AMI_LIST_WIDTH, GLOB(cfwdbusy)); CLI_AMI_OUTPUT_BOOL("CFWNOANSWER ", CLI_AMI_LIST_WIDTH, GLOB(cfwdnoanswer)); #ifdef CS_MANAGER_EVENTS CLI_AMI_OUTPUT_BOOL("Call Events", CLI_AMI_LIST_WIDTH, GLOB(callevents)); #else CLI_AMI_OUTPUT_BOOL("Call Events", CLI_AMI_LIST_WIDTH, FALSE); #endif CLI_AMI_OUTPUT_PARAM("DND", CLI_AMI_LIST_WIDTH, "%s", GLOB(dndmode) ? dndmode2str(GLOB(dndmode)) : "Disabled"); #ifdef CS_SCCP_PARK CLI_AMI_OUTPUT_BOOL("Park", CLI_AMI_LIST_WIDTH, FALSE); #else CLI_AMI_OUTPUT_BOOL("Park", CLI_AMI_LIST_WIDTH, FALSE); #endif CLI_AMI_OUTPUT_BOOL("Private softkey", CLI_AMI_LIST_WIDTH, GLOB(privacy)); CLI_AMI_OUTPUT_BOOL("Echo cancel", CLI_AMI_LIST_WIDTH, GLOB(echocancel)); CLI_AMI_OUTPUT_BOOL("Silence suppression", CLI_AMI_LIST_WIDTH, GLOB(silencesuppression)); CLI_AMI_OUTPUT_BOOL("Trust phone ip (deprecated)", CLI_AMI_LIST_WIDTH, GLOB(trustphoneip)); CLI_AMI_OUTPUT_PARAM("Early RTP", CLI_AMI_LIST_WIDTH, "%s (%s)", GLOB(earlyrtp) ? "Yes" : "No", GLOB(earlyrtp) ? sccp_indicate2str(GLOB(earlyrtp)) : "none"); CLI_AMI_OUTPUT_PARAM("AutoAnswer ringtime", CLI_AMI_LIST_WIDTH, "%d", GLOB(autoanswer_ring_time)); CLI_AMI_OUTPUT_PARAM("AutoAnswer tone", CLI_AMI_LIST_WIDTH, "%d", GLOB(autoanswer_tone)); CLI_AMI_OUTPUT_PARAM("RemoteHangup tone", CLI_AMI_LIST_WIDTH, "%d", GLOB(remotehangup_tone)); CLI_AMI_OUTPUT_PARAM("Transfer tone", CLI_AMI_LIST_WIDTH, "%d", GLOB(transfer_tone)); CLI_AMI_OUTPUT_BOOL("Transfer on hangup", CLI_AMI_LIST_WIDTH, GLOB(transfer_on_hangup)); CLI_AMI_OUTPUT_PARAM("Callwaiting tone", CLI_AMI_LIST_WIDTH, "%d", GLOB(callwaiting_tone)); CLI_AMI_OUTPUT_PARAM("Callwaiting interval", CLI_AMI_LIST_WIDTH, "%d", GLOB(callwaiting_interval)); CLI_AMI_OUTPUT_PARAM("Registration Context", CLI_AMI_LIST_WIDTH, "%s", GLOB(regcontext) ? GLOB(regcontext) : "Unset"); CLI_AMI_OUTPUT_BOOL("Jitterbuffer enabled ", CLI_AMI_LIST_WIDTH, pbx_test_flag(&GLOB(global_jbconf), AST_JB_ENABLED)); CLI_AMI_OUTPUT_BOOL("Jitterbuffer forced ", CLI_AMI_LIST_WIDTH, pbx_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)); CLI_AMI_OUTPUT_PARAM("Jitterbuffer max size", CLI_AMI_LIST_WIDTH, "%ld", GLOB(global_jbconf).max_size); CLI_AMI_OUTPUT_PARAM("Jitterbuffer resync", CLI_AMI_LIST_WIDTH, "%ld", GLOB(global_jbconf).resync_threshold); CLI_AMI_OUTPUT_PARAM("Jitterbuffer impl", CLI_AMI_LIST_WIDTH, "%s", GLOB(global_jbconf).impl); CLI_AMI_OUTPUT_BOOL("Jitterbuffer log ", CLI_AMI_LIST_WIDTH, pbx_test_flag(&GLOB(global_jbconf), AST_JB_LOG)); #ifdef CS_AST_JB_TARGET_EXTRA CLI_AMI_OUTPUT_PARAM("Jitterbuf target extra", CLI_AMI_LIST_WIDTH, "%ld", GLOB(global_jbconf).target_extra); #endif CLI_AMI_OUTPUT_PARAM("Token FallBack", CLI_AMI_LIST_WIDTH, "%s", GLOB(token_fallback)); CLI_AMI_OUTPUT_PARAM("Token Backoff-Time", CLI_AMI_LIST_WIDTH, "%d", GLOB(token_backoff_time)); CLI_AMI_OUTPUT_BOOL("Hotline_Enabled", CLI_AMI_LIST_WIDTH, GLOB(allowAnonymous)); CLI_AMI_OUTPUT_PARAM("Hotline_Context", CLI_AMI_LIST_WIDTH, "%s", GLOB(hotline->line->context)); CLI_AMI_OUTPUT_PARAM("Hotline_Exten", CLI_AMI_LIST_WIDTH, "%s", GLOB(hotline->exten)); CLI_AMI_OUTPUT_PARAM("Threadpool Size", CLI_AMI_LIST_WIDTH, "%d/%d", sccp_threadpool_jobqueue_count(GLOB(general_threadpool)), sccp_threadpool_thread_count(GLOB(general_threadpool))); sccp_free(debugcategories); sccp_globals_unlock(lock); if (s) { *total = local_total; astman_append(s, "\r\n"); } return RESULT_SUCCESS; } static char cli_globals_usage[] = "Usage: sccp show globals\n" " Lists global settings for the SCCP subsystem.\n"; static char ami_globals_usage[] = "Usage: SCCPShowGlobals\n" " Lists global settings for the SCCP subsystem.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "globals" #define AMI_COMMAND "SCCPShowGlobals" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_globals, sccp_show_globals, "List defined SCCP global settings", cli_globals_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------SHOW DEVICES- */ /*! * \brief Show Devices * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - devices */ //static int sccp_show_devices(int fd, int argc, char *argv[]) static int sccp_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { struct tm *timeinfo; char regtime[25]; int local_total = 0; sccp_device_t *d; // table definition #define CLI_AMI_TABLE_NAME Devices #define CLI_AMI_TABLE_PER_ENTRY_NAME Device #define CLI_AMI_TABLE_LIST_ITER_TYPE sccp_device_t #define CLI_AMI_TABLE_LIST_ITER_HEAD &GLOB(devices) #define CLI_AMI_TABLE_LIST_ITER_VAR list_dev #define CLI_AMI_TABLE_LIST_LOCK SCCP_RWLIST_RDLOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_RWLIST_TRAVERSE #define CLI_AMI_TABLE_BEFORE_ITERATION \ if ((d = sccp_device_retain(list_dev))) { \ timeinfo = localtime(&d->registrationTime); \ strftime(regtime, sizeof(regtime), "%c ", timeinfo); #define CLI_AMI_TABLE_AFTER_ITERATION \ sccp_device_release(d); \ } //#define CLI_AMI_TABLE_BEFORE_ITERATION timeinfo = localtime(&d->registrationTime); strftime(regtime, sizeof(regtime), "%c ", timeinfo); #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_RWLIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Name, s, 40, d->description) \ CLI_AMI_TABLE_FIELD(Address, s, 20, (d->session) ? pbx_inet_ntoa(d->session->sin.sin_addr) : "--") \ CLI_AMI_TABLE_FIELD(Mac, s, 16, d->id) \ CLI_AMI_TABLE_FIELD(RegState, s, 10, registrationstate2str(d->registrationState)) \ CLI_AMI_TABLE_FIELD(Token, s, 5, d->status.token ? ((d->status.token == SCCP_TOKEN_STATE_ACK) ? "Ack" : "Rej") : "None") \ CLI_AMI_TABLE_FIELD(RegTime, s, 25, regtime) \ CLI_AMI_TABLE_FIELD(Act, s, 3, (d->active_channel) ? "Yes" : "No") \ CLI_AMI_TABLE_FIELD(Lines, d, 5, d->configurationStatistic.numberOfLines) #include "sccp_cli_table.h" // end of table definition if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_devices_usage[] = "Usage: sccp show devices\n" " Lists defined SCCP devices.\n"; static char ami_devices_usage[] = "Usage: SCCPShowDevices\n" "Lists defined SCCP devices.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "devices" #define AMI_COMMAND "SCCPShowDevices" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_devices, sccp_show_devices, "List defined SCCP devices", cli_devices_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------SHOW DEVICE- */ /*! * \brief Show Device * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \warning * - device->buttonconfig is not always locked * * \lock * - device * - device->buttonconfig */ static int sccp_show_device(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_device_t *d; sccp_line_t *l; char pref_buf[256]; char cap_buf[512]; struct ast_str *ha_buf = pbx_str_alloca(512); PBX_VARIABLE_TYPE *v = NULL; sccp_linedevices_t *linedevice = NULL; int local_total = 0; const char *actionid = ""; const char *dev; if (argc < 4) { pbx_log(LOG_WARNING, "DeviceName needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "DeviceName needs to be supplied %s\n", ""); } dev = sccp_strdupa(argv[3]); if (pbx_strlen_zero(dev)) { pbx_log(LOG_WARNING, "DeviceName needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "DeviceName needs to be supplied %s\n", ""); } d = sccp_device_find_byid(dev, FALSE); if (!d) { pbx_log(LOG_WARNING, "Failed to get device %s\n", dev); CLI_AMI_ERROR(fd, s, m, "Can't find settings for device %s\n", dev); } sccp_multiple_codecs2str(pref_buf, sizeof(pref_buf) - 1, d->preferences.audio, ARRAY_LEN(d->preferences.audio)); sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, d->capabilities.audio, ARRAY_LEN(d->capabilities.audio)); sccp_print_ha(ha_buf, sizeof(ha_buf), d->ha); if (!s) { CLI_AMI_OUTPUT(fd, s, "\n--- SCCP channel driver device settings ----------------------------------------------------------------------------------\n"); } else { astman_send_listack(s, m, argv[0], "start"); CLI_AMI_OUTPUT_PARAM("Event", CLI_AMI_LIST_WIDTH, "%s", "SCCPShowDevice"); actionid = astman_get_header(m, "ActionID"); if (!pbx_strlen_zero(actionid)) { astman_append(s, "ActionID: %s\r\n", actionid); } astman_append(s, "\r\n"); } /* *INDENT-OFF* */ CLI_AMI_OUTPUT_PARAM("MAC-Address", CLI_AMI_LIST_WIDTH, "%s", d->id); CLI_AMI_OUTPUT_PARAM("Protocol Version", CLI_AMI_LIST_WIDTH, "Supported '%d', In Use '%d'", d->protocolversion, d->inuseprotocolversion); CLI_AMI_OUTPUT_PARAM("Protocol In Use", CLI_AMI_LIST_WIDTH, "%s Version %d", d->protocol ? d->protocol->name : "NONE", d->protocol ? d->protocol->version : 0); CLI_AMI_OUTPUT_PARAM("Tokenstate", CLI_AMI_LIST_WIDTH, "%s", d->status.token ? ((d->status.token == SCCP_TOKEN_STATE_ACK) ? "Token acknowledged" : "Token rejected") : "no token requested"); CLI_AMI_OUTPUT_PARAM("Keepalive", CLI_AMI_LIST_WIDTH, "%d", d->keepalive); CLI_AMI_OUTPUT_PARAM("Registration state", CLI_AMI_LIST_WIDTH, "%s(%d)", registrationstate2str(d->registrationState), d->registrationState); CLI_AMI_OUTPUT_PARAM("State", CLI_AMI_LIST_WIDTH, "%s(%d)", devicestate2str(d->state), d->state); CLI_AMI_OUTPUT_PARAM("MWI light", CLI_AMI_LIST_WIDTH, "%s(%d)", lampmode2str(d->mwilamp), d->mwilamp); CLI_AMI_OUTPUT_BOOL("MWI handset light", CLI_AMI_LIST_WIDTH, d->mwilight); CLI_AMI_OUTPUT_PARAM("Description", CLI_AMI_LIST_WIDTH, "%s", d->description); CLI_AMI_OUTPUT_PARAM("Config Phone Type", CLI_AMI_LIST_WIDTH, "%s", d->config_type); CLI_AMI_OUTPUT_PARAM("Skinny Phone Type", CLI_AMI_LIST_WIDTH, "%s(%d)", devicetype2str(d->skinny_type), d->skinny_type); CLI_AMI_OUTPUT_YES_NO("Softkey support", CLI_AMI_LIST_WIDTH, d->softkeysupport); CLI_AMI_OUTPUT_PARAM("Softkeyset", CLI_AMI_LIST_WIDTH, "%s", d->softkeyDefinition); CLI_AMI_OUTPUT_YES_NO("BTemplate support", CLI_AMI_LIST_WIDTH, d->buttonTemplate); CLI_AMI_OUTPUT_YES_NO("linesRegistered", CLI_AMI_LIST_WIDTH, d->linesRegistered); CLI_AMI_OUTPUT_PARAM("Image Version", CLI_AMI_LIST_WIDTH, "%s", d->imageversion); CLI_AMI_OUTPUT_PARAM("Timezone Offset", CLI_AMI_LIST_WIDTH, "%d", d->tz_offset); CLI_AMI_OUTPUT_PARAM("Capabilities", CLI_AMI_LIST_WIDTH, "%s", cap_buf); CLI_AMI_OUTPUT_PARAM("Codecs preference", CLI_AMI_LIST_WIDTH, "%s", pref_buf); CLI_AMI_OUTPUT_PARAM("Audio TOS", CLI_AMI_LIST_WIDTH, "%d", d->audio_tos); CLI_AMI_OUTPUT_PARAM("Audio COS", CLI_AMI_LIST_WIDTH, "%d", d->audio_cos); CLI_AMI_OUTPUT_PARAM("Video TOS", CLI_AMI_LIST_WIDTH, "%d", d->video_tos); CLI_AMI_OUTPUT_PARAM("Video COS", CLI_AMI_LIST_WIDTH, "%d", d->video_cos); CLI_AMI_OUTPUT_YES_NO("DND Feature enabled", CLI_AMI_LIST_WIDTH, d->dndFeature.enabled); CLI_AMI_OUTPUT_PARAM("DND Status", CLI_AMI_LIST_WIDTH, "%s", (d->dndFeature.status) ? dndmode2str(d->dndFeature.status) : "Disabled"); CLI_AMI_OUTPUT_BOOL("Can Transfer", CLI_AMI_LIST_WIDTH, d->transfer); CLI_AMI_OUTPUT_BOOL("Can Park", CLI_AMI_LIST_WIDTH, d->park); CLI_AMI_OUTPUT_BOOL("Can CFWDALL", CLI_AMI_LIST_WIDTH, d->cfwdall); CLI_AMI_OUTPUT_BOOL("Can CFWBUSY", CLI_AMI_LIST_WIDTH, d->cfwdbusy); CLI_AMI_OUTPUT_BOOL("Can CFWNOANSWER", CLI_AMI_LIST_WIDTH, d->cfwdnoanswer); CLI_AMI_OUTPUT_YES_NO("Allow ringin notification (e)", CLI_AMI_LIST_WIDTH, d->allowRinginNotification); CLI_AMI_OUTPUT_BOOL("Private softkey", CLI_AMI_LIST_WIDTH, d->privacyFeature.enabled); CLI_AMI_OUTPUT_PARAM("Dtmf mode", CLI_AMI_LIST_WIDTH, "%s", (d->dtmfmode) ? "Out-of-Band" : "In-Band"); CLI_AMI_OUTPUT_PARAM("digit timeout", CLI_AMI_LIST_WIDTH, "%d", d->digittimeout); CLI_AMI_OUTPUT_BOOL("Nat", CLI_AMI_LIST_WIDTH, d->nat); CLI_AMI_OUTPUT_YES_NO("Videosupport?", CLI_AMI_LIST_WIDTH, sccp_device_isVideoSupported(d)); CLI_AMI_OUTPUT_BOOL("Direct RTP", CLI_AMI_LIST_WIDTH, d->directrtp); CLI_AMI_OUTPUT_BOOL("Trust phone ip (deprecated)", CLI_AMI_LIST_WIDTH, d->trustphoneip); CLI_AMI_OUTPUT_PARAM("Bind Address", CLI_AMI_LIST_WIDTH, "%s:%d", (d->session) ? pbx_inet_ntoa(d->session->sin.sin_addr) : "???.???.???.???", (d->session) ? ntohs(d->session->sin.sin_port) : 0); CLI_AMI_OUTPUT_PARAM("Server Address", CLI_AMI_LIST_WIDTH, "%s", (d->session) ? ast_inet_ntoa(d->session->ourip) : "???.???.???.???"); CLI_AMI_OUTPUT_PARAM("Deny/Permit", CLI_AMI_LIST_WIDTH, "%s", pbx_str_buffer(ha_buf)); CLI_AMI_OUTPUT_PARAM("Early RTP", CLI_AMI_LIST_WIDTH, "%s (%s)", d->earlyrtp ? "Yes" : "No", d->earlyrtp ? sccp_indicate2str(d->earlyrtp) : "none"); CLI_AMI_OUTPUT_PARAM("Device State (Acc.)", CLI_AMI_LIST_WIDTH, "%s", accessorystate2str(d->accessorystatus)); CLI_AMI_OUTPUT_PARAM("Last Used Accessory", CLI_AMI_LIST_WIDTH, "%s", accessory2str(d->accessoryused)); CLI_AMI_OUTPUT_PARAM("Last dialed number", CLI_AMI_LIST_WIDTH, "%s", d->lastNumber); CLI_AMI_OUTPUT_PARAM("Default line instance", CLI_AMI_LIST_WIDTH, "%d", d->defaultLineInstance); CLI_AMI_OUTPUT_PARAM("Custom Background Image", CLI_AMI_LIST_WIDTH, "%s", d->backgroundImage ? d->backgroundImage : "---"); CLI_AMI_OUTPUT_PARAM("Custom Ring Tone", CLI_AMI_LIST_WIDTH, "%s", d->ringtone ? d->ringtone : "---"); #ifdef CS_ADV_FEATURES CLI_AMI_OUTPUT_BOOL("Use Placed Calls", CLI_AMI_LIST_WIDTH, d->useRedialMenu); #endif CLI_AMI_OUTPUT_BOOL("PendingUpdate", CLI_AMI_LIST_WIDTH, d->pendingUpdate); CLI_AMI_OUTPUT_BOOL("PendingDelete", CLI_AMI_LIST_WIDTH, d->pendingDelete); #ifdef CS_SCCP_PICKUP CLI_AMI_OUTPUT_BOOL("Directed Pickup", CLI_AMI_LIST_WIDTH, d->directed_pickup); CLI_AMI_OUTPUT_PARAM("Pickup Context", CLI_AMI_LIST_WIDTH, "%s (%s)", d->directed_pickup_context, pbx_context_find(d->directed_pickup_context) ? "exists" : "does not exist !!"); CLI_AMI_OUTPUT_BOOL("Pickup Mode Answer", CLI_AMI_LIST_WIDTH, d->directed_pickup_modeanswer); #endif #ifdef CS_CONFERENCE CLI_AMI_OUTPUT_BOOL("allow_conference", CLI_AMI_LIST_WIDTH, d->allow_conference); CLI_AMI_OUTPUT_BOOL("conf_play_general_announce", CLI_AMI_LIST_WIDTH, d->conf_play_general_announce); CLI_AMI_OUTPUT_BOOL("conf_play_part_announce", CLI_AMI_LIST_WIDTH, d->conf_play_part_announce); CLI_AMI_OUTPUT_BOOL("conf_mute_on_entry", CLI_AMI_LIST_WIDTH, d->conf_mute_on_entry); CLI_AMI_OUTPUT_PARAM("conf_music_on_hold_class",CLI_AMI_LIST_WIDTH, d->conf_music_on_hold_class); #endif /* *INDENT-ON* */ if (SCCP_LIST_FIRST(&d->buttonconfig)) { // BUTTONS #define CLI_AMI_TABLE_NAME Buttons #define CLI_AMI_TABLE_PER_ENTRY_NAME Button #define CLI_AMI_TABLE_LIST_ITER_TYPE sccp_buttonconfig_t #define CLI_AMI_TABLE_LIST_ITER_HEAD &d->buttonconfig #define CLI_AMI_TABLE_LIST_ITER_VAR buttonconfig #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 4, buttonconfig->instance) \ CLI_AMI_TABLE_FIELD(TypeStr, s, 30, config_buttontype2str(buttonconfig->type)) \ CLI_AMI_TABLE_FIELD(Type, d, 24, buttonconfig->type) \ CLI_AMI_TABLE_FIELD(pendUpdt, s, 8, buttonconfig->pendingUpdate ? "Yes" : "No") \ CLI_AMI_TABLE_FIELD(pendDel, s, 8, buttonconfig->pendingUpdate ? "Yes" : "No") \ CLI_AMI_TABLE_FIELD(Default, s, 9, (0!=buttonconfig->instance && d->defaultLineInstance == buttonconfig->instance && LINE==buttonconfig->type) ? "Yes" : "No") #include "sccp_cli_table.h" // LINES #define CLI_AMI_TABLE_NAME Lines #define CLI_AMI_TABLE_PER_ENTRY_NAME Line #define CLI_AMI_TABLE_LIST_ITER_HEAD &d->buttonconfig #define CLI_AMI_TABLE_LIST_ITER_VAR buttonconfig #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_BEFORE_ITERATION \ if (buttonconfig->type == LINE) { \ l = sccp_line_find_byname(buttonconfig->button.line.name, FALSE); \ if (l) { \ linedevice = sccp_linedevice_find(d, l); #define CLI_AMI_TABLE_AFTER_ITERATION \ linedevice = linedevice ? sccp_linedevice_release(linedevice) : NULL; \ sccp_line_release(l); \ } \ } #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 4, buttonconfig->instance) \ CLI_AMI_TABLE_FIELD(Name, s, 23, l->name) \ CLI_AMI_TABLE_FIELD(Suffix, s, 6, buttonconfig->button.line.subscriptionId.number) \ CLI_AMI_TABLE_FIELD(Label, s, 24, l->label) \ CLI_AMI_TABLE_FIELD(CfwdType, s, 10, (linedevice && linedevice->cfwdAll.enabled ? "All" : (linedevice && linedevice->cfwdBusy.enabled ? "Busy" : "None"))) \ CLI_AMI_TABLE_FIELD(CfwdNumber, s, 16, (linedevice && linedevice->cfwdAll.enabled ? linedevice->cfwdAll.number : (linedevice && linedevice->cfwdBusy.enabled ? linedevice->cfwdBusy.number : ""))) #include "sccp_cli_table.h" // SPEEDDIALS #define CLI_AMI_TABLE_NAME Speeddials #define CLI_AMI_TABLE_PER_ENTRY_NAME Speeddial #define CLI_AMI_TABLE_LIST_ITER_HEAD &d->buttonconfig #define CLI_AMI_TABLE_LIST_ITER_VAR buttonconfig #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_BEFORE_ITERATION \ if (buttonconfig->type == SPEEDDIAL) { #define CLI_AMI_TABLE_AFTER_ITERATION \ } #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 4, buttonconfig->instance) \ CLI_AMI_TABLE_FIELD(Name, s, 23, buttonconfig->label) \ CLI_AMI_TABLE_FIELD(Number, s, 31, buttonconfig->button.speeddial.ext) \ CLI_AMI_TABLE_FIELD(Hint, s, 27, buttonconfig->button.speeddial.hint) // CLI_AMI_TABLE_FIELD(HintStatus, s, 20, ast_extension_state2str(ast_extension_state())) #include "sccp_cli_table.h" // FEATURES #define CLI_AMI_TABLE_NAME Features #define CLI_AMI_TABLE_PER_ENTRY_NAME Feature #define CLI_AMI_TABLE_LIST_ITER_HEAD &d->buttonconfig #define CLI_AMI_TABLE_LIST_ITER_VAR buttonconfig #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_BEFORE_ITERATION \ if (buttonconfig->type == FEATURE) { #define CLI_AMI_TABLE_AFTER_ITERATION \ } #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 4, buttonconfig->instance) \ CLI_AMI_TABLE_FIELD(Name, s, 23, buttonconfig->label) \ CLI_AMI_TABLE_FIELD(Options, s, 31, buttonconfig->button.feature.options) \ CLI_AMI_TABLE_FIELD(Status, d, 27, buttonconfig->button.feature.status) #include "sccp_cli_table.h" // SERVICEURL #define CLI_AMI_TABLE_NAME ServiceURLs #define CLI_AMI_TABLE_PER_ENTRY_NAME ServiceURL #define CLI_AMI_TABLE_LIST_ITER_HEAD &d->buttonconfig #define CLI_AMI_TABLE_LIST_ITER_VAR buttonconfig #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_BEFORE_ITERATION \ if (buttonconfig->type == SERVICE) { #define CLI_AMI_TABLE_AFTER_ITERATION \ } #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Id, d, 4, buttonconfig->instance) \ CLI_AMI_TABLE_FIELD(Name, s, 23, buttonconfig->label) \ CLI_AMI_TABLE_FIELD(URL, s, 59, buttonconfig->button.service.url) #include "sccp_cli_table.h" } if (d->variables) { // SERVICEURL #define CLI_AMI_TABLE_NAME Variables #define CLI_AMI_TABLE_PER_ENTRY_NAME Variable #define CLI_AMI_TABLE_ITERATOR for(v = d->variables;v;v = v->next) #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Name, s, 28, v->name) \ CLI_AMI_TABLE_FIELD(Value, s, 59, v->value) #include "sccp_cli_table.h" } sccp_call_statistics_type_t callstattype; sccp_call_statistics_t *stats = NULL; #define CLI_AMI_TABLE_NAME CallStatistics #define CLI_AMI_TABLE_PER_ENTRY_NAME Statistics #define CLI_AMI_TABLE_ITERATOR for(callstattype = SCCP_CALLSTATISTIC_LAST; callstattype <= SCCP_CALLSTATISTIC_AVG; callstattype++) #define CLI_AMI_TABLE_BEFORE_ITERATION stats = &d->call_statistics[callstattype]; #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Type, s, 8, stats->type ? stats->type : "UNDEF") \ CLI_AMI_TABLE_FIELD(Calls, d, 8, stats->num) \ CLI_AMI_TABLE_FIELD(PcktSnd, d, 8, stats->packets_sent) \ CLI_AMI_TABLE_FIELD(PcktRcvd, d, 8, stats->packets_received) \ CLI_AMI_TABLE_FIELD(Lost, d, 8, stats->packets_lost) \ CLI_AMI_TABLE_FIELD(Jitter, d, 8, stats->jitter) \ CLI_AMI_TABLE_FIELD(Latency, d, 8, stats->latency) \ CLI_AMI_TABLE_FIELD(Quality, f, 8, stats->opinion_score_listening_quality) \ CLI_AMI_TABLE_FIELD(avgQual, f, 8, stats->avg_opinion_score_listening_quality) \ CLI_AMI_TABLE_FIELD(meanQual, f, 8, stats->mean_opinion_score_listening_quality) \ CLI_AMI_TABLE_FIELD(maxQual, f, 8, stats->max_opinion_score_listening_quality) \ CLI_AMI_TABLE_FIELD(rConceal, f, 8, stats->cumulative_concealement_ratio) \ CLI_AMI_TABLE_FIELD(sConceal, d, 8, stats->concealed_seconds) #include "sccp_cli_table.h" sccp_device_release(d); if (s) { *total = local_total; astman_append(s, "\r\n"); } return RESULT_SUCCESS; } static char cli_device_usage[] = "Usage: sccp show device <deviceId>\n" " Lists device settings for the SCCP subsystem.\n"; static char ami_device_usage[] = "Usage: SCCPShowDevice\n" "Lists device settings for the SCCP subsystem.\n\n" "PARAMS: DeviceName\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "device" #define CLI_COMPLETE SCCP_CLI_DEVICE_COMPLETER #define AMI_COMMAND "SCCPShowDevice" #define CLI_AMI_PARAMS "DeviceName" CLI_AMI_ENTRY(show_device, sccp_show_device, "Lists device settings", cli_device_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ---------------------------------------------------------------------------------------------------------SHOW LINES- */ /*! * \brief Show Lines * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - lines * - devices */ //static int sccp_show_lines(int fd, int argc, char *argv[]) static int sccp_show_lines(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_line_t *l = NULL; sccp_channel_t *channel = NULL; sccp_device_t *d = NULL; boolean_t found_linedevice; char cap_buf[512]; PBX_VARIABLE_TYPE *v = NULL; int local_total = 0; const char *actionid = ""; if (!s) { pbx_cli(fd, "\n+--- Lines ---------------------------------------------------------------------------------------------------------------------------+\n"); pbx_cli(fd, "| %-13s %-9s %-30s %-16s %-4s %-4s %-49s |\n", "Ext", "Suffix", "Label", "Device", "MWI", "Chs", "Active Channel"); pbx_cli(fd, "+ ============= ========= ============================== ================ ==== ==== ================================================= +\n"); } else { astman_append(s, "Event: TableStart\r\n"); local_total++; astman_append(s, "TableName: Lines\r\n"); local_total++; actionid = astman_get_header(m, "ActionID"); if (!pbx_strlen_zero(actionid)) { astman_append(s, "ActionID: %s\r\n", actionid); } astman_append(s, "\r\n"); } SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { channel = NULL; // \todo handle shared line d = NULL; #if 0 // never gonna happen because of line above if (d) { sccp_device_retain(d); channel = d->active_channel; sccp_device_release(d); } #endif if (!channel || (channel->line != l)) channel = NULL; memset(&cap_buf, 0, sizeof(cap_buf)); if (channel && channel->owner) { pbx_getformatname_multiple(cap_buf, sizeof(cap_buf), pbx_channel_nativeformats(channel->owner)); } sccp_linedevices_t *linedevice; found_linedevice = 0; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { if ((d = sccp_device_retain(linedevice->device))) { if (!s) { pbx_cli(fd, "| %-13s %-9s %-30s %-16s %-4s %-4d %-10s %-10s %-16s %-10s |\n", !found_linedevice ? l->name : " +--", linedevice->subscriptionId.number, l->label, (d) ? d->id : "--", (l->voicemailStatistic.newmsgs) ? "ON" : "OFF", SCCP_RWLIST_GETSIZE(l->channels), (channel) ? sccp_indicate2str(channel->state) : "--", (channel) ? calltype2str(channel->calltype) : "", (channel) ? ((channel->calltype == SKINNY_CALLTYPE_OUTBOUND) ? channel->callInfo.calledPartyName : channel->callInfo.callingPartyName) : "", cap_buf); } else { astman_append(s, "Event: LineEntry\r\n"); astman_append(s, "ChannelType: SCCP\r\n"); astman_append(s, "ChannelObjectType: Line\r\n"); astman_append(s, "Exten: %s\r\n", l->name); astman_append(s, "SubscriptionNumber: %s\r\n", linedevice->subscriptionId.number); astman_append(s, "Device: %s\r\n", (d) ? d->id : "--"); astman_append(s, "MWI: %s\r\n", (l->voicemailStatistic.newmsgs) ? "ON" : "OFF"); astman_append(s, "ActiveChannels: %d\r\n", SCCP_RWLIST_GETSIZE(l->channels)); astman_append(s, "ChannelState: %s\r\n", (channel) ? sccp_indicate2str(channel->state) : "--"); astman_append(s, "CallType: %s\r\n", (channel) ? calltype2str(channel->calltype) : ""); astman_append(s, "PartyName: %s\r\n", (channel) ? ((channel->calltype == SKINNY_CALLTYPE_OUTBOUND) ? channel->callInfo.calledPartyName : channel->callInfo.callingPartyName) : ""); astman_append(s, "Capabilities: %s\r\n", cap_buf); astman_append(s, "\r\n"); } found_linedevice = 1; d = sccp_device_release(d); } } SCCP_LIST_UNLOCK(&l->devices); if (found_linedevice == 0) { if (!s) { pbx_cli(fd, "| %-13s %-9s %-30s %-16s %-4s %-4d %-10s %-10s %-16s %-10s |\n", l->name, "", l->label, "--", (l->voicemailStatistic.newmsgs) ? "ON" : "OFF", SCCP_RWLIST_GETSIZE(l->channels), (channel) ? sccp_indicate2str(channel->state) : "--", (channel) ? calltype2str(channel->calltype) : "", (channel) ? ((channel->calltype == SKINNY_CALLTYPE_OUTBOUND) ? channel->callInfo.calledPartyName : channel->callInfo.callingPartyName) : "", cap_buf); } else { astman_append(s, "Event: LineEntry\r\n"); astman_append(s, "ChannelType: SCCP\r\n"); astman_append(s, "ChannelObjectType: Line\r\n"); astman_append(s, "Exten: %s\r\n", l->name); astman_append(s, "Label: %s\r\n", l->label); astman_append(s, "Device: %s\r\n", "(null)"); astman_append(s, "MWI: %s\r\n", (l->voicemailStatistic.newmsgs) ? "ON" : "OFF"); astman_append(s, "\r\n"); } } if (!s) { for (v = l->variables; v; v = v->next) pbx_cli(fd, "| %-13s %-9s %-30s = %-74.74s |\n", "", "Variable:", v->name, v->value); if (strcmp(l->defaultSubscriptionId.number, "") || strcmp(l->defaultSubscriptionId.name, "")) pbx_cli(fd, "| %-13s %-9s %-30s %-76.76s |\n", "", "SubscrId:", l->defaultSubscriptionId.number, l->defaultSubscriptionId.name); } } if (!s) { pbx_cli(fd, "+-------------------------------------------------------------------------------------------------------------------------------------+\n"); } else { astman_append(s, "Event: TableEnd\r\n"); local_total++; astman_append(s, "TableName: Lines\r\n"); local_total++; if (!pbx_strlen_zero(actionid)) { astman_append(s, "ActionID: %s\r\n", actionid); local_total++; } astman_append(s, "\r\n"); local_total++; } SCCP_RWLIST_UNLOCK(&GLOB(lines)); if (s) { *total = local_total; astman_append(s, "\r\n"); } return RESULT_SUCCESS; } static char cli_lines_usage[] = "Usage: sccp show lines\n" " Lists all lines known to the SCCP subsystem.\n"; static char ami_lines_usage[] = "Usage: SCCPShowLines\n" "Lists all lines known to the SCCP subsystem\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "lines" #define AMI_COMMAND "SCCPShowLines" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_lines, sccp_show_lines, "List defined SCCP Lines", cli_lines_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -----------------------------------------------------------------------------------------------------------SHOW LINE- */ /*! * \brief Show Line * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - line * - line->devices */ //static int sccp_show_line(int fd, int argc, char *argv[]) static int sccp_show_line(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_line_t *l; sccp_linedevices_t *linedevice; sccp_mailbox_t *mailbox; PBX_VARIABLE_TYPE *v = NULL; struct ast_str *callgroup_buf = pbx_str_alloca(512); #ifdef CS_SCCP_PICKUP struct ast_str *pickupgroup_buf = pbx_str_alloca(512); #endif int local_total = 0; const char *line; if (argc < 4) { pbx_log(LOG_WARNING, "LineName needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "LineName needs to be supplied %s\n", ""); } line = sccp_strdupa(argv[3]); l = sccp_line_find_byname(line, FALSE); if (!l) { pbx_log(LOG_WARNING, "Failed to get line %s\n", line); CLI_AMI_ERROR(fd, s, m, "Can't find settings for line %s\n", line); } if (!s) { CLI_AMI_OUTPUT(fd, s, "\n--- SCCP channel driver line settings ------------------------------------------------------------------------------------\n"); } else { astman_send_listack(s, m, argv[0], "start"); CLI_AMI_OUTPUT_PARAM("Event", CLI_AMI_LIST_WIDTH, "%s", argv[0]); } CLI_AMI_OUTPUT_PARAM("Name", CLI_AMI_LIST_WIDTH, "%s", l->name ? l->name : "<not set>"); CLI_AMI_OUTPUT_PARAM("Description", CLI_AMI_LIST_WIDTH, "%s", l->description ? l->description : "<not set>"); CLI_AMI_OUTPUT_PARAM("Label", CLI_AMI_LIST_WIDTH, "%s", l->label ? l->label : "<not set>"); CLI_AMI_OUTPUT_PARAM("ID", CLI_AMI_LIST_WIDTH, "%s", l->id ? l->id : "<not set>"); CLI_AMI_OUTPUT_PARAM("Pin", CLI_AMI_LIST_WIDTH, "%s", l->pin ? l->pin : "<not set>"); CLI_AMI_OUTPUT_PARAM("VoiceMail number", CLI_AMI_LIST_WIDTH, "%s", l->vmnum ? l->vmnum : "<not set>"); CLI_AMI_OUTPUT_PARAM("Transfer to Voicemail", CLI_AMI_LIST_WIDTH, "%s", l->trnsfvm ? l->trnsfvm : "No"); CLI_AMI_OUTPUT_BOOL("MeetMe enabled", CLI_AMI_LIST_WIDTH, l->meetme); CLI_AMI_OUTPUT_PARAM("MeetMe number", CLI_AMI_LIST_WIDTH, "%s", l->meetmenum); CLI_AMI_OUTPUT_PARAM("MeetMe Options", CLI_AMI_LIST_WIDTH, "%s", l->meetmeopts); CLI_AMI_OUTPUT_PARAM("Context", CLI_AMI_LIST_WIDTH, "%s (%s)", l->context ? l->context : "<not set>", pbx_context_find(l->context) ? "exists" : "does not exist !!"); CLI_AMI_OUTPUT_PARAM("Language", CLI_AMI_LIST_WIDTH, "%s", l->language ? l->language : "<not set>"); CLI_AMI_OUTPUT_PARAM("Account Code", CLI_AMI_LIST_WIDTH, "%s", l->accountcode ? l->accountcode : "<not set>"); CLI_AMI_OUTPUT_PARAM("Musicclass", CLI_AMI_LIST_WIDTH, "%s", l->musicclass ? l->musicclass : "<not set>"); CLI_AMI_OUTPUT_PARAM("AmaFlags", CLI_AMI_LIST_WIDTH, "%d", l->amaflags); sccp_print_group(callgroup_buf, sizeof(callgroup_buf), l->callgroup); CLI_AMI_OUTPUT_PARAM("Call Group", CLI_AMI_LIST_WIDTH, "%s", callgroup_buf ? pbx_str_buffer(callgroup_buf) : ""); #ifdef CS_SCCP_PICKUP sccp_print_group(pickupgroup_buf, sizeof(pickupgroup_buf), l->pickupgroup); CLI_AMI_OUTPUT_PARAM("Pickup Group", CLI_AMI_LIST_WIDTH, "%s", pickupgroup_buf ? pbx_str_buffer(pickupgroup_buf) : ""); #endif CLI_AMI_OUTPUT_PARAM("Caller ID name", CLI_AMI_LIST_WIDTH, "%s", l->cid_name ? l->cid_name : "<not set>"); CLI_AMI_OUTPUT_PARAM("Caller ID number", CLI_AMI_LIST_WIDTH, "%s", l->cid_num ? l->cid_num : "<not set>"); CLI_AMI_OUTPUT_PARAM("Incoming Calls limit", CLI_AMI_LIST_WIDTH, "%d", l->incominglimit); CLI_AMI_OUTPUT_PARAM("Active Channel Count", CLI_AMI_LIST_WIDTH, "%d", SCCP_RWLIST_GETSIZE(l->channels)); CLI_AMI_OUTPUT_PARAM("Sec. Dialtone Digits", CLI_AMI_LIST_WIDTH, "%s", l->secondary_dialtone_digits ? l->secondary_dialtone_digits : "<not set>"); CLI_AMI_OUTPUT_PARAM("Sec. Dialtone", CLI_AMI_LIST_WIDTH, "0x%02x", l->secondary_dialtone_tone); CLI_AMI_OUTPUT_BOOL("Echo Cancellation", CLI_AMI_LIST_WIDTH, l->echocancel); CLI_AMI_OUTPUT_BOOL("Silence Suppression", CLI_AMI_LIST_WIDTH, l->silencesuppression); CLI_AMI_OUTPUT_BOOL("Can Transfer", CLI_AMI_LIST_WIDTH, l->transfer); CLI_AMI_OUTPUT_PARAM("Can DND", CLI_AMI_LIST_WIDTH, "%s", (l->dndmode) ? dndmode2str(l->dndmode) : "Disabled"); #ifdef CS_SCCP_REALTIME CLI_AMI_OUTPUT_BOOL("Is Realtime Line", CLI_AMI_LIST_WIDTH, l->realtime); #endif CLI_AMI_OUTPUT_BOOL("Pending Delete", CLI_AMI_LIST_WIDTH, l->pendingUpdate); CLI_AMI_OUTPUT_BOOL("Pending Update", CLI_AMI_LIST_WIDTH, l->pendingDelete); CLI_AMI_OUTPUT_PARAM("Registration Extension", CLI_AMI_LIST_WIDTH, "%s", l->regexten ? l->regexten : "Unset"); CLI_AMI_OUTPUT_PARAM("Registration Context", CLI_AMI_LIST_WIDTH, "%s", l->regcontext ? l->regcontext : "Unset"); CLI_AMI_OUTPUT_BOOL("Adhoc Number Assigned", CLI_AMI_LIST_WIDTH, l->adhocNumber ? l->adhocNumber : "No"); CLI_AMI_OUTPUT_PARAM("Message Waiting New.", CLI_AMI_LIST_WIDTH, "%i", l->voicemailStatistic.newmsgs); CLI_AMI_OUTPUT_PARAM("Message Waiting Old.", CLI_AMI_LIST_WIDTH, "%i", l->voicemailStatistic.oldmsgs); // Line attached to these devices #define CLI_AMI_TABLE_NAME AttachedDevices #define CLI_AMI_TABLE_PER_ENTRY_NAME Device #define CLI_AMI_TABLE_LIST_ITER_HEAD &l->devices #define CLI_AMI_TABLE_LIST_ITER_VAR linedevice #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Device, s, 15, linedevice->device->id) \ CLI_AMI_TABLE_FIELD(CfwdType, s, 8, linedevice->cfwdAll.enabled ? "All" : (linedevice->cfwdBusy.enabled ? "Busy" : "")) \ CLI_AMI_TABLE_FIELD(CfwdNumber, s, 20, linedevice->cfwdAll.enabled ? linedevice->cfwdAll.number : (linedevice->cfwdBusy.enabled ? linedevice->cfwdBusy.number : "")) #include "sccp_cli_table.h" // Mailboxes connected to this line #define CLI_AMI_TABLE_NAME Mailboxes #define CLI_AMI_TABLE_PER_ENTRY_NAME Mailbox #define CLI_AMI_TABLE_LIST_ITER_HEAD &l->mailboxes #define CLI_AMI_TABLE_LIST_ITER_VAR mailbox #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(mailbox, s, 15, mailbox->mailbox) \ CLI_AMI_TABLE_FIELD(context, s, 15, mailbox->context) #include "sccp_cli_table.h" if (l->variables) { // SERVICEURL #define CLI_AMI_TABLE_NAME Variables #define CLI_AMI_TABLE_PER_ENTRY_NAME Variable #define CLI_AMI_TABLE_ITERATOR for(v = l->variables;v;v = v->next) #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Name, s, 15, v->name) \ CLI_AMI_TABLE_FIELD(Value, s, 29, v->value) #include "sccp_cli_table.h" } sccp_line_release(l); if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_line_usage[] = "Usage: sccp show line <lineId>\n" " List defined SCCP line settings.\n"; static char ami_line_usage[] = "Usage: SCCPShowLine\n" "List defined SCCP line settings.\n\n" "PARAMS: LineName\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "line" #define CLI_COMPLETE SCCP_CLI_LINE_COMPLETER #define AMI_COMMAND "SCCPShowLine" #define CLI_AMI_PARAMS "LineName" CLI_AMI_ENTRY(show_line, sccp_show_line, "List defined SCCP line settings", cli_line_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------SHOW CHANNELS- */ /*! * \brief Show Channels * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - lines * - line * - line->channels */ //static int sccp_show_channels(int fd, int argc, char *argv[]) static int sccp_show_channels(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_channel_t *channel; sccp_line_t *l; sccp_device_t *d; int local_total = 0; char tmpname[20]; #define CLI_AMI_TABLE_NAME Channels #define CLI_AMI_TABLE_PER_ENTRY_NAME Channel #define CLI_AMI_TABLE_LIST_ITER_HEAD &GLOB(lines) #define CLI_AMI_TABLE_LIST_ITER_VAR l #define CLI_AMI_TABLE_LIST_LOCK SCCP_RWLIST_RDLOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_RWLIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_RWLIST_UNLOCK #define CLI_AMI_TABLE_BEFORE_ITERATION \ l = sccp_line_retain(l); \ SCCP_LIST_LOCK(&l->channels); \ SCCP_LIST_TRAVERSE(&l->channels, channel, list) { \ d = sccp_channel_getDevice_retained(channel); \ if (channel->conference_id) { \ snprintf(tmpname, sizeof(tmpname), "SCCPCONF/%03d/%03d", channel->conference_id, channel->conference_participant_id); \ } else { \ snprintf(tmpname, sizeof(tmpname), "SCCP/%s-%08x", l->name, channel->callid); \ } #define CLI_AMI_TABLE_AFTER_ITERATION \ if (d) \ sccp_device_release(d); \ } \ SCCP_LIST_UNLOCK(&l->channels); \ sccp_line_release(l); #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(ID, d, 5, channel->callid) \ CLI_AMI_TABLE_FIELD(PBX, s, 20, strdupa(tmpname)) \ CLI_AMI_TABLE_FIELD(Line, s, 10, channel->line->name) \ CLI_AMI_TABLE_FIELD(Device, s, 16, d ? d->id : "(unknown)") \ CLI_AMI_TABLE_FIELD(DeviceDescr, s, 32, d ? d->description : "(unknown)") \ CLI_AMI_TABLE_FIELD(NumCalled, s, 10, channel->callInfo.calledPartyNumber) \ CLI_AMI_TABLE_FIELD(PBX State, s, 10, (channel->owner) ? pbx_state2str(PBX(getChannelState)(channel)) : "(none)") \ CLI_AMI_TABLE_FIELD(SCCP State, s, 10, sccp_indicate2str(channel->state)) \ CLI_AMI_TABLE_FIELD(ReadCodec, s, 10, codec2name(channel->rtp.audio.readFormat)) \ CLI_AMI_TABLE_FIELD(WriteCodec, s, 10, codec2name(channel->rtp.audio.writeFormat)) #include "sccp_cli_table.h" if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_channels_usage[] = "Usage: sccp show channels\n" " Lists active channels for the SCCP subsystem.\n"; static char ami_channels_usage[] = "Usage: SCCPShowChannels\n" "Lists active channels for the SCCP subsystem.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "channels" #define AMI_COMMAND "SCCPShowChannels" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_channels, sccp_show_channels, "Lists active SCCP channels", cli_channels_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -------------------------------------------------------------------------------------------------------SHOW SESSIONS- */ /*! * \brief Show Sessions * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - sessions * - session * - device * - session */ //static int sccp_show_sessions(int fd, int argc, char *argv[]) static int sccp_show_sessions(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_device_t *d = NULL; int local_total = 0; #define CLI_AMI_TABLE_NAME Sessions #define CLI_AMI_TABLE_PER_ENTRY_NAME Session #define CLI_AMI_TABLE_LIST_ITER_HEAD &GLOB(sessions) #define CLI_AMI_TABLE_LIST_ITER_TYPE sccp_session_t #define CLI_AMI_TABLE_LIST_ITER_VAR session #define CLI_AMI_TABLE_LIST_LOCK SCCP_RWLIST_RDLOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_RWLIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_RWLIST_UNLOCK #define CLI_AMI_TABLE_BEFORE_ITERATION \ sccp_session_lock(session); \ if (session->device && (d = sccp_device_retain(session->device))) { \ #define CLI_AMI_TABLE_AFTER_ITERATION \ d = sccp_device_release(d); \ }; \ sccp_session_unlock(session); \ #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Socket, d, 10, session->fds[0].fd) \ CLI_AMI_TABLE_FIELD(IP, s, CLI_AMI_LIST_WIDTH, pbx_inet_ntoa(session->sin.sin_addr)) \ CLI_AMI_TABLE_FIELD(Port, d, 5, session->sin.sin_port) \ CLI_AMI_TABLE_FIELD(KA, d, 4, (uint32_t) (time(0) - session->lastKeepAlive)) \ CLI_AMI_TABLE_FIELD(KAI, d, 4, d->keepaliveinterval) \ CLI_AMI_TABLE_FIELD(Device, s, 15, (d) ? d->id : "--") \ CLI_AMI_TABLE_FIELD(State, s, 14, (d) ? devicestate2str(d->state) : "--") \ CLI_AMI_TABLE_FIELD(Type, s, 15, (d) ? devicetype2str(d->skinny_type) : "--") \ CLI_AMI_TABLE_FIELD(RegState, s, 10, (d) ? registrationstate2str(d->registrationState) : "--") \ CLI_AMI_TABLE_FIELD(Token, s, 10, (d && d->status.token ) ? (SCCP_TOKEN_STATE_ACK == d->status.token ? "Ack" : (SCCP_TOKEN_STATE_REJ == d->status.token ? "Reject" : "--")) : "--") #include "sccp_cli_table.h" if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_sessions_usage[] = "Usage: sccp show sessions\n" " Show All SCCP Sessions.\n"; static char ami_sessions_usage[] = "Usage: SCCPShowSessions\n" "Show All SCCP Sessions.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "sessions" #define AMI_COMMAND "SCCPShowSessions" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_sessions, sccp_show_sessions, "Show all SCCP sessions", cli_sessions_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ---------------------------------------------------------------------------------------------SHOW_MWI_SUBSCRIPTIONS- */ // sccp_show_mwi_subscriptions implementation moved to sccp_mwi.c, because of access to private struct static char cli_mwi_subscriptions_usage[] = "Usage: sccp show mwi subscriptions\n" " Show All SCCP MWI Subscriptions.\n"; static char ami_mwi_subscriptions_usage[] = "Usage: SCCPShowMWISubscriptions\n" "Show All SCCP MWI Subscriptions.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "mwi", "subscriptions" #define AMI_COMMAND "SCCPShowMWISubscriptions" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_mwi_subscriptions, sccp_show_mwi_subscriptions, "Show all SCCP MWI subscriptions", cli_mwi_subscriptions_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #if defined(DEBUG) || defined(CS_EXPERIMENTAL) /* ---------------------------------------------------------------------------------------------CONFERENCE FUNCTIONS- */ #ifdef CS_SCCP_CONFERENCE static char cli_conferences_usage[] = "Usage: sccp show conferences\n" " Lists running SCCP conferences.\n"; static char ami_conferences_usage[] = "Usage: SCCPShowConferences\n" "Lists running SCCP conferences.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "conferences" #define AMI_COMMAND "SCCPShowConferences" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_conferences, sccp_cli_show_conferences, "List running SCCP Conferences", cli_conferences_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ static char cli_conference_usage[] = "Usage: sccp show conference\n" " Lists running SCCP conference.\n"; static char ami_conference_usage[] = "Usage: SCCPShowConference\n" "Lists running SCCP conference.\n\n" "PARAMS: ConferenceId\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "conference" #define AMI_COMMAND "SCCPShowConference" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_conference, sccp_cli_show_conference, "List running SCCP Conference", cli_conference_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ static char cli_conference_action_usage[] = "Usage: sccp conference [conference_id]\n" " Conference [EndConf | Kick | Mute | Invite | Moderate] [conference_id] [participant_id].\n"; static char ami_conference_action_usage[] = "Usage: SCCPConference [conference id]\n" "Conference Actions.\n\n" "PARAMS: \n" " Action: [EndConf | Kick | Mute | Invite | Moderate]\n" " ConferenceId\n" " ParticipantId\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "conference" //#define CLI_COMPLETE SCCP_CLI_CONFERENCE_COMPLETER #define CLI_COMPLETE SCCP_CLI_CONFERENCE_COMPLETER #define AMI_COMMAND "SCCPConference" #define CLI_AMI_PARAMS "Action","ConferenceId","ParticipantId" CLI_AMI_ENTRY(conference_action, sccp_cli_conference_action, "Conference Action", cli_conference_action_usage, TRUE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #endif /* -------------------------------------------------------------------------------------------------------TEST MESSAGE- */ #define NUM_LOOPS 20 #define NUM_OBJECTS 100 #ifdef CS_EXPERIMENTAL struct refcount_test { int id; int loop; unsigned int threadid; char *test; } *object[NUM_OBJECTS]; static void sccp_cli_refcount_test_destroy(struct refcount_test *obj) { sccp_log(0) ("TEST: Destroyed %d, thread: %d\n", obj->id, (unsigned int) pthread_self()); sccp_free(object[obj->id]->test); object[obj->id]->test = NULL; }; static void *sccp_cli_refcount_test_thread(void *data) { boolean_t working = *(boolean_t *) data; struct refcount_test *obj = NULL, *obj1 = NULL; int test, loop; int random_object; if (working) { // CORRECT for (loop = 0; loop < NUM_LOOPS; loop++) { for (test = 0; test < NUM_OBJECTS; test++) { random_object = rand() % NUM_OBJECTS; sccp_log(0) ("TEST: retain/release %d, loop: %d, thread: %d\n", random_object, loop, (unsigned int) pthread_self()); if ((obj = sccp_refcount_retain(object[random_object], __FILE__, __LINE__, __PRETTY_FUNCTION__))) { usleep(random_object % 10); if ((obj1 = sccp_refcount_retain(obj, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { usleep(random_object % 10); obj1 = sccp_refcount_release(obj1, __FILE__, __LINE__, __PRETTY_FUNCTION__); } obj = sccp_refcount_release(obj, __FILE__, __LINE__, __PRETTY_FUNCTION__); } } } } else { // FALSE for (loop = 0; loop < NUM_LOOPS; loop++) { for (test = 0; test < NUM_OBJECTS; test++) { random_object = rand() % NUM_OBJECTS; sccp_log(0) ("TEST: retain/release %d, loop: %d, thread: %d\n", random_object, loop, (unsigned int) pthread_self()); if ((obj = sccp_refcount_retain(object[random_object], __FILE__, __LINE__, __PRETTY_FUNCTION__))) { usleep(random_object % 10); if ((obj = sccp_refcount_retain(obj, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { usleep(random_object % 10); obj = sccp_refcount_release(obj, __FILE__, __LINE__, __PRETTY_FUNCTION__); // obj will be NULL after releasing } obj = sccp_refcount_release(obj, __FILE__, __LINE__, __PRETTY_FUNCTION__); } } } } return NULL; } static void *sccp_cli_threadpool_test_thread(void *data) { int loop; // int num_loops=rand(); int num_loops = 1000; sccp_log(0) (VERBOSE_PREFIX_4 "Running work: %d, loops: %d\n", (unsigned int) pthread_self(), num_loops); for (loop = 0; loop < num_loops; loop++) { usleep(1); } sccp_log(0) (VERBOSE_PREFIX_4 "Thread: %d Done\n", (unsigned int) pthread_self()); return 0; } static void sccp_update_statusbar(const sccp_device_t * d, const char *msg, const uint8_t priority, const uint8_t timeout, uint8_t level, boolean_t clear, const uint8_t lineInstance, const uint32_t callid) { sccp_moo_t *r; if (!d || !d->protocol) { return; } switch (level) { case 0: if (!clear) { REQ(r, DisplayTextMessage); sccp_copy_string(r->msg.DisplayTextMessage.displayMessage, msg, sizeof(r->msg.DisplayTextMessage.displayMessage)); sccp_dev_send(d, r); } else { sccp_dev_sendmsg(d, ClearDisplay); } case 1: if (!clear) { d->protocol->displayNotify(d, timeout, msg); } else { sccp_dev_sendmsg(d, ClearNotifyMessage); } case 2: if (!clear) { d->protocol->displayPriNotify(d, priority, timeout, msg); } else { REQ(r, ClearPriNotifyMessage); r->msg.ClearPriNotifyMessage.lel_priority = htolel(priority); sccp_dev_send(d, r); } case 3: if (!clear) { d->protocol->displayPrompt(d, lineInstance, callid, timeout, msg); } else { REQ(r, ClearPromptStatusMessage); r->msg.ClearPromptStatusMessage.lel_callReference = htolel(callid); r->msg.ClearPromptStatusMessage.lel_lineInstance = htolel(lineInstance); sccp_dev_send(d, r); } } } #endif /*! * \brief Test Message * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_test_message(int fd, int argc, char *argv[]) { if (argc < 4) return RESULT_SHOWUSAGE; if (sccp_strlen_zero(argv[3])) return RESULT_SHOWUSAGE; #ifdef CS_EXPERIMENTAL // OpenReceiveChannel TEST if (!strcasecmp(argv[3], "openreceivechannel")) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "Testing re-Sending OpenReceiveChannel to change Payloads on the fly!!\n"); sccp_moo_t *r1; sccp_moo_t *r2; int packetSize = 20; /*! \todo calculate packetSize */ sccp_device_t *d = NULL; sccp_line_t *l = NULL; sccp_channel_t *channel = NULL; SCCP_RWLIST_RDLOCK(&GLOB(lines)); SCCP_RWLIST_TRAVERSE(&GLOB(lines), l, list) { SCCP_LIST_TRAVERSE(&l->channels, channel, list) { d = sccp_channel_getDevice_retained(channel); sccp_channel_retain(channel); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "Sending OpenReceiveChannel and changing payloadType to 8\n"); REQ(r1, OpenReceiveChannel); r1->msg.OpenReceiveChannel.v17.lel_conferenceId = htolel(channel->callid); r1->msg.OpenReceiveChannel.v17.lel_passThruPartyId = htolel(channel->passthrupartyid); r1->msg.OpenReceiveChannel.v17.lel_millisecondPacketSize = htolel(packetSize); r1->msg.OpenReceiveChannel.v17.lel_payloadType = htolel(8); r1->msg.OpenReceiveChannel.v17.lel_vadValue = htolel(channel->line->echocancel); r1->msg.OpenReceiveChannel.v17.lel_conferenceId1 = htolel(channel->callid); r1->msg.OpenReceiveChannel.v17.lel_rtptimeout = htolel(10); sccp_dev_send(d, r1); // sleep(1); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "Sending OpenReceiveChannel and changing payloadType to 4\n"); REQ(r2, OpenReceiveChannel); r2->msg.OpenReceiveChannel.v17.lel_conferenceId = htolel(channel->callid); r2->msg.OpenReceiveChannel.v17.lel_passThruPartyId = htolel(channel->passthrupartyid); r2->msg.OpenReceiveChannel.v17.lel_millisecondPacketSize = htolel(packetSize); r2->msg.OpenReceiveChannel.v17.lel_payloadType = htolel(4); r2->msg.OpenReceiveChannel.v17.lel_vadValue = htolel(channel->line->echocancel); r2->msg.OpenReceiveChannel.v17.lel_conferenceId1 = htolel(channel->callid); r2->msg.OpenReceiveChannel.v17.lel_rtptimeout = htolel(10); sccp_dev_send(d, r2); sccp_channel_release(channel); sccp_device_release(d); } sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "Testing re-Sending OpenReceiveChannel. It WORKS !\n"); } SCCP_RWLIST_UNLOCK(&GLOB(lines)); return RESULT_SUCCESS; } // SpeedDialStatDynamicMessage = 0x0149, if (!strcasecmp(argv[3], "speeddialstatdynamic")) { sccp_device_t *d = NULL; sccp_buttonconfig_t *buttonconfig = NULL; uint8_t instance = 0; uint8_t buttonID = SKINNY_BUTTONTYPE_SPEEDDIAL; uint32_t state = 66306; // 0, 66306, 131589, sccp_moo_t *r1; if (argc < 5) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_2 "Device Not specified\n"); return RESULT_FAILURE; } if ((d = sccp_device_find_byid(argv[4], FALSE))) { instance = atoi(argv[5]); SCCP_LIST_LOCK(&d->buttonconfig); SCCP_LIST_TRAVERSE(&d->buttonconfig, buttonconfig, list) { if (buttonconfig->type == SPEEDDIAL) { instance = buttonconfig->instance; REQ(r1, SpeedDialStatDynamicMessage); r1->msg.SpeedDialStatDynamicMessage.lel_instance = htolel(instance); r1->msg.SpeedDialStatDynamicMessage.lel_type = htolel(buttonID); r1->msg.SpeedDialStatDynamicMessage.lel_status = htolel(state ? state : 0); sccp_copy_string(r1->msg.SpeedDialStatDynamicMessage.DisplayName, "NEW TEXT", strlen("NEW_TEXT") + 1); sccp_dev_send(d, r1); } } SCCP_LIST_UNLOCK(&d->buttonconfig); } return RESULT_SUCCESS; } if (!strcasecmp(argv[3], "refcount")) { int thread; boolean_t working = TRUE; int num_threads = (argc == 5) ? atoi(argv[4]) : 4; if (argc == 6 && !strcmp(argv[5], "fail")) { working = FALSE; } pthread_t t; int test; char id[23]; for (test = 0; test < NUM_OBJECTS; test++) { snprintf(id, sizeof(id), "%d/%d", test, (unsigned int) pthread_self()); object[test] = (struct refcount_test *) sccp_refcount_object_alloc(sizeof(struct refcount_test), SCCP_REF_TEST, id, sccp_cli_refcount_test_destroy); object[test]->id = test; object[test]->threadid = (unsigned int) pthread_self(); object[test]->test = strdup(id); sccp_log(0) ("TEST: Created %d\n", object[test]->id); } sccp_refcount_print_hashtable(fd); sleep(3); for (thread = 0; thread < num_threads; thread++) { pbx_pthread_create(&t, NULL, sccp_cli_refcount_test_thread, &working); } pthread_join(t, NULL); sleep(3); for (test = 0; test < NUM_OBJECTS; test++) { if (object[test]) { sccp_log(0) ("TEST: Final Release %d, thread: %d\n", object[test]->id, (unsigned int) pthread_self()); sccp_refcount_release(object[test], __FILE__, __LINE__, __PRETTY_FUNCTION__); } } sleep(1); sccp_refcount_print_hashtable(fd); return RESULT_SUCCESS; } if (!strcasecmp(argv[3], "threadpool")) { int work; int num_work = (argc == 5) ? atoi(argv[4]) : 4; for (work = 0; work < num_work; work++) { if (!sccp_threadpool_add_work(GLOB(general_threadpool), (void *) sccp_cli_threadpool_test_thread, (void *) &work)) { pbx_log(LOG_ERROR, "Could not add work to threadpool\n"); } } return RESULT_SUCCESS; } if (!strcasecmp(argv[3], "hint")) { int state = (argc == 6) ? atoi(argv[5]) : 0; pbx_devstate_changed(state, "SCCP/%s", argv[4]); pbx_log(LOG_NOTICE, "Hint %s Set NewState: %d\n", argv[4], state); return RESULT_SUCCESS; } if (!strcasecmp(argv[3], "permit")) { /* WIP */ struct ast_str *buf = pbx_str_alloca(512); //struct sccp_ha *path; //sccp_append_ha(const char *sense, const char *stuff, struct sccp_ha *path, int *error) sccp_print_ha(buf, sizeof(buf), GLOB(ha)); pbx_log(LOG_NOTICE, "%s: HA Buffer: %s\n", argv[4], pbx_str_buffer(buf)); return RESULT_SUCCESS; } if (!strcasecmp(argv[3], "retrieveDeviceCapabilities")) { /* WIP */ sccp_device_t *d = NULL; d = sccp_device_find_byid(argv[4], FALSE); if (d) { d->retrieveDeviceCapabilities(d); pbx_log(LOG_NOTICE, "%s: Done\n", d->id); d = sccp_device_release(d); } return RESULT_SUCCESS; } if (!strcasecmp(argv[3], "StatusBar")) { /* WIP */ sccp_device_t *d = NULL; d = sccp_device_find_byid(argv[4], FALSE); if (d) { //sccp_update_statusbar(d, *msg, priority, timeout, level, clear, lineInstance, callid) pbx_log(LOG_NOTICE, "%s: Base\n", d->id); sccp_update_statusbar(d, "BASE", 0, 0, 0, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Clear Base\n", d->id); sccp_update_statusbar(d, "", 0, 0, 0, TRUE, 0, 0); sleep(1); /* Level 1 */ pbx_log(LOG_NOTICE, "%s: Base\n", d->id); sccp_update_statusbar(d, "BASE", 0, 0, 0, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Level 1\n", d->id); sccp_update_statusbar(d, "LEVEL 1", 0, 0, 1, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to BASE\n", d->id); sccp_update_statusbar(d, "", 0, 0, 1, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Clear Base\n", d->id); sccp_update_statusbar(d, "", 0, 0, 0, TRUE, 0, 0); sleep(1); /* Level 2 */ pbx_log(LOG_NOTICE, "%s: Base\n", d->id); sccp_update_statusbar(d, "BASE", 0, 0, 0, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Level 1\n", d->id); sccp_update_statusbar(d, "LEVEL 1", 0, 0, 1, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Level 2, Prio 1\n", d->id); sccp_update_statusbar(d, "Level 2, Prio 1", 1, 3, 2, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Level 2, Prio 4\n", d->id); sccp_update_statusbar(d, "Level 2, Prio 4", 4, 3, 2, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to Level 2, Prio 4\n", d->id); sccp_update_statusbar(d, "", 4, 0, 2, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to Level 1\n", d->id); sccp_update_statusbar(d, "", 1, 0, 2, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to Base\n", d->id); sccp_update_statusbar(d, "", 0, 0, 1, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Clear Base\n", d->id); sccp_update_statusbar(d, "", 0, 0, 0, TRUE, 0, 0); sleep(1); /* Level 3 */ /* pbx_log(LOG_NOTICE, "%s: Level 1\n", d->id); sccp_update_statusbar(d, "LEVEL 1", 0, 0, 1, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Level 2\n", d->id); sccp_update_statusbar(d, "Level 2", 0, 0, 2, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Level 3\n", d->id); sccp_update_statusbar(d, "Level 2", 0, 0, 3, FALSE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to Level 2\n", d->id); sccp_update_statusbar(d, "", 0, 0, 3, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to Level 1\n", d->id); sccp_update_statusbar(d, "", 0, 0, 2, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Back to Base\n", d->id); sccp_update_statusbar(d, "", 0, 0, 1, TRUE, 0, 0); sleep(1); pbx_log(LOG_NOTICE, "%s: Clear Base\n", d->id); sccp_update_statusbar(d, "", 0, 0, 0, TRUE, 0, 0); sleep(1);*/ d = sccp_device_release(d); } return RESULT_SUCCESS; } #endif return RESULT_FAILURE; } static char cli_test_message_usage[] = "Usage: sccp test message [message_name]\n" " Test message [message_name].\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "test", "message" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_test_message, sccp_test_message, "Test a Message", cli_test_message_usage, FALSE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ------------------------------------------------------------------------------------------------------- REFCOUNT - */ /*! * \brief Print Refcount Hash Table * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_show_refcount(int fd, int argc, char *argv[]) { if (argc < 3) return RESULT_SHOWUSAGE; sccp_refcount_print_hashtable(fd); return RESULT_SUCCESS; } static char cli_show_refcount_usage[] = "Usage: sccp show refcount [sortorder]\n" " Show Refcount Hash Table. sortorder can be hash or type\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "refcount" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_show_refcount, sccp_show_refcount, "Test a Message", cli_show_refcount_usage, FALSE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #endif //defined(DEBUG) || defined(CS_EXPERIMENTAL) /* --------------------------------------------------------------------------------------------------SHOW_SOKFTKEYSETS- */ /*! * \brief Show Sessions * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - softKeySetConfig */ //static int sccp_show_softkeysets(int fd, int argc, char *argv[]) static int sccp_show_softkeysets(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { uint8_t i = 0; uint8_t v_count = 0; uint8_t c = 0; int local_total = 0; #define CLI_AMI_TABLE_NAME SoftKeySets #define CLI_AMI_TABLE_PER_ENTRY_NAME SoftKeySet #define CLI_AMI_TABLE_LIST_ITER_HEAD &softKeySetConfig #define CLI_AMI_TABLE_LIST_ITER_TYPE sccp_softKeySetConfiguration_t #define CLI_AMI_TABLE_LIST_ITER_VAR softkeyset #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_BEFORE_ITERATION \ v_count = sizeof(softkeyset->modes) / sizeof(softkey_modes); \ for (i = 0; i < v_count; i++) { \ const uint8_t *b = softkeyset->modes[i].ptr; \ for (c = 0; c < softkeyset->modes[i].count; c++) { #define CLI_AMI_TABLE_AFTER_ITERATION \ } \ } #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Set, s, 15, softkeyset->name) \ CLI_AMI_TABLE_FIELD(Mode, s, 12, keymode2str(i)) \ CLI_AMI_TABLE_FIELD(Description, s, 40, keymode2str(i)) \ CLI_AMI_TABLE_FIELD(LblID, d, 5, c) \ CLI_AMI_TABLE_FIELD(Label, s, 15, label2str(b[c])) #include "sccp_cli_table.h" if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_show_softkeysets_usage[] = "Usage: sccp show softkeysets\n" " Show the configured SoftKeySets.\n"; static char ami_show_softkeysets_usage[] = "Usage: SCCPShowSoftkeySets\n" "Show All SCCP Softkey Sets.\n\n" "PARAMS: None\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "softkeyssets" #define AMI_COMMAND "SCCPShowSoftkeySets" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "" CLI_AMI_ENTRY(show_softkeysets, sccp_show_softkeysets, "Show configured SoftKeySets", cli_show_softkeysets_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -----------------------------------------------------------------------------------------------------MESSAGE DEVICES- */ /*! * \brief Message Devices * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - devices * - see sccp_dev_displaynotify() * - see sccp_dev_starttone() */ //static int sccp_message_devices(int fd, int argc, char *argv[]) static int sccp_message_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_device_t *d; int timeout = 0; boolean_t beep = FALSE; int local_total = 0; if (argc < 4) { pbx_log(LOG_WARNING, "MessageText needs to be supplied\n"); CLI_AMI_ERROR(fd, s, m, "MessageText needs to be supplied %s\n", ""); } // const char *messagetext = astman_get_header(m, "MessageText"); // if (sccp_strlen_zero(messagetext)) { if (sccp_strlen_zero(argv[3])) { pbx_log(LOG_WARNING, "MessageText cannot be empty\n"); CLI_AMI_ERROR(fd, s, m, "messagetext cannot be empty, '%s'\n", argv[3]); } if (argc > 4) { if (!strcmp(argv[4], "beep")) { beep = TRUE; sscanf(argv[5], "%d", &timeout); } sscanf(argv[4], "%d", &timeout); } sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Sending message '%s' to all devices (beep: %d, timeout: %d)\n", argv[3], beep, timeout); SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { sccp_dev_set_message(d, argv[3], timeout, FALSE, beep); // sccp_dev_set_message(d, messagetext, timeout, FALSE, beep); } SCCP_RWLIST_UNLOCK(&GLOB(devices)); if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_message_devices_usage[] = "Usage: sccp message devices <message text> [beep] [timeout]\n" " Send a message to all SCCP Devices + phone beep + timeout.\n"; static char ami_message_devices_usage[] = "Usage: SCCPMessageDevices\n" "Show All SCCP Softkey Sets.\n\n" "PARAMS: MessageText, Beep, Timeout\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "message", "devices" #define AMI_COMMAND "SCCPMessageDevices" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER #define CLI_AMI_PARAMS "MessageText", "Beep", "Timeout" CLI_AMI_ENTRY(message_devices, sccp_message_devices, "Send a message to all SCCP devices", cli_message_devices_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -----------------------------------------------------------------------------------------------------MESSAGE DEVICE- */ /*! * \brief Message Device * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \todo TO BE IMPLEMENTED: sccp message device */ static int sccp_message_device(int fd, int argc, char *argv[]) { sccp_device_t *d; int timeout = 10; boolean_t beep = FALSE; if (argc < 4) return RESULT_SHOWUSAGE; if (sccp_strlen_zero(argv[3])) return RESULT_SHOWUSAGE; if (argc > 5) { if (!strcmp(argv[5], "beep")) { beep = TRUE; sscanf(argv[6], "%d", &timeout); } sscanf(argv[5], "%d", &timeout); } if ((d = sccp_device_find_byid(argv[3], FALSE))) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Sending message '%s' to %s (beep: %d, timeout: %d)\n", argv[3], d->id, beep, timeout); sccp_dev_set_message(d, argv[4], timeout, FALSE, beep); d = sccp_device_release(d); return RESULT_SUCCESS; } else { ast_cli(fd, "Device not found!\n"); return RESULT_FAILURE; } } static char message_device_usage[] = "Usage: sccp message device <deviceId> <message text> [beep] [timeout]\n" " Send a message to an SCCP Device + phone beep + timeout.\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "message", "device" #define CLI_COMPLETE SCCP_CLI_DEVICE_COMPLETER CLI_ENTRY(cli_message_device, sccp_message_device, "Send a message to SCCP Device", message_device_usage, FALSE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ------------------------------------------------------------------------------------------------------SYSTEM MESSAGE- */ /*! * \brief System Message * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_system_message(int fd, int argc, char *argv[]) { int res; sccp_device_t *d; int timeout = 0; boolean_t beep = FALSE; if (argc == 3) { SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { sccp_dev_clear_message(d, TRUE); } SCCP_RWLIST_UNLOCK(&GLOB(devices)); ast_cli(fd, "Message Cleared\n"); return RESULT_SUCCESS; } if (argc < 4 || argc > 6) return RESULT_SHOWUSAGE; if (sccp_strlen_zero(argv[3])) return RESULT_SHOWUSAGE; res = PBX(feature_addToDatabase) ("SCCP/message", "text", argv[3]); if (!res) { ast_cli(fd, "Failed to store the SCCP system message text\n"); } else { sccp_log(DEBUGCAT_CLI) (VERBOSE_PREFIX_3 "SCCP system message text stored successfully\n"); } if (argc > 4) { if (!strcmp(argv[4], "beep")) { beep = TRUE; sscanf(argv[5], "%d", &timeout); } sscanf(argv[4], "%d", &timeout); } else { timeout = 0; } if (!res) { ast_cli(fd, "Failed to store the SCCP system message timeout\n"); } else { sccp_log(DEBUGCAT_CLI) (VERBOSE_PREFIX_3 "SCCP system message timeout stored successfully\n"); } sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Sending system message '%s' to all devices (beep: %d, timeout: %d)\n", argv[3], beep, timeout); SCCP_RWLIST_RDLOCK(&GLOB(devices)); SCCP_RWLIST_TRAVERSE(&GLOB(devices), d, list) { sccp_dev_set_message(d, argv[3], timeout, TRUE, beep); } SCCP_RWLIST_UNLOCK(&GLOB(devices)); return RESULT_SUCCESS; } static char system_message_usage[] = "Usage: sccp system message <message text> [beep] [timeout]\n" " The default optional timeout is 0 (forever)\n" " Example: sccp system message \"The boss is gone. Let's have some fun!\" 10\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "system", "message" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_system_message, sccp_system_message, "Send a system wide message to all SCCP Devices", system_message_usage, FALSE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -----------------------------------------------------------------------------------------------------DND DEVICE- */ /*! * \brief Message Device * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - device * - see sccp_sk_dnd() */ static int sccp_dnd_device(int fd, int argc, char *argv[]) { sccp_device_t *d = NULL; if (argc < 3) return RESULT_SHOWUSAGE; if ((d = sccp_device_find_byid(argv[3], TRUE))) { sccp_sk_dnd(d, NULL, 0, NULL); d = sccp_device_release(d); } else { pbx_cli(fd, "Can't find device %s\n", argv[3]); return RESULT_SUCCESS; } return RESULT_SUCCESS; } static char dnd_device_usage[] = "Usage: sccp dnd <deviceId>\n" " Send a dnd to an SCCP Device.\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "dnd", "device" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER CLI_ENTRY(cli_dnd_device, sccp_dnd_device, "Send a dnd to SCCP Device", dnd_device_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------REMOVE_LINE_FROM_DEVICE- */ /*! * \brief Remove Line From Device * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \todo TO BE IMPLEMENTED: sccp message device */ static int sccp_remove_line_from_device(int fd, int argc, char *argv[]) { pbx_cli(fd, "Command has not been fully implemented yet!\n"); return RESULT_FAILURE; } static char remove_line_from_device_usage[] = "Usage: sccp remove line <deviceID> <lineID>\n" " Remove a line from device.\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "remove", "line" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER, SCCP_CLI_CONNECTED_LINE_COMPLETER CLI_ENTRY(cli_remove_line_from_device, sccp_remove_line_from_device, "Remove a line from device", remove_line_from_device_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -------------------------------------------------------------------------------------------------ADD_LINE_TO_DEVICE- */ /*! * \brief Add Line To Device * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_add_line_to_device(int fd, int argc, char *argv[]) { sccp_device_t *d; sccp_line_t *l; if (argc < 5) return RESULT_SHOWUSAGE; if (sccp_strlen_zero(argv[4])) return RESULT_SHOWUSAGE; if ((d = sccp_device_find_byid(argv[3], FALSE))) { l = sccp_line_find_byname(argv[4], FALSE); if (!l) { pbx_log(LOG_ERROR, "Error: Line %s not found\n", argv[4]); return RESULT_FAILURE; } sccp_config_addButton(d, -1, LINE, l->name, NULL, NULL); l = sccp_line_release(l); d = sccp_device_release(d); } else { pbx_log(LOG_ERROR, "Error: Device %s not found\n", argv[3]); return RESULT_FAILURE; } pbx_cli(fd, "Line %s has been added to device %s\n", l->name, d->id); return RESULT_SUCCESS; } static char add_line_to_device_usage[] = "Usage: sccp add line <deviceID> <lineID>\n" " Add a line to a device.\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "add", "line" #define CLI_COMPLETE SCCP_CLI_DEVICE_COMPLETER, SCCP_CLI_CONNECTED_LINE_COMPLETER CLI_ENTRY(cli_add_line_to_device, sccp_add_line_to_device, "Add a line to a device", add_line_to_device_usage, FALSE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ------------------------------------------------------------------------------------------------------------DO DEBUG- */ /*! * \brief Do Debug * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_do_debug(int fd, int argc, char *argv[]) { int32_t new_debug = GLOB(debug); if (argc > 2) { new_debug = sccp_parse_debugline(argv, 2, argc, new_debug); } char *debugcategories = sccp_get_debugcategories(new_debug); if (argc > 2) pbx_cli(fd, "SCCP new debug status: (%d -> %d) %s\n", GLOB(debug), new_debug, debugcategories); else pbx_cli(fd, "SCCP debug status: (%d) %s\n", GLOB(debug), debugcategories); sccp_free(debugcategories); GLOB(debug) = new_debug; return RESULT_SUCCESS; } static char do_debug_usage[] = "Usage: SCCP debug [no] <level or categories>\n" " Where categories is one or more (separated by commas) of:\n" " core, sccp, hint, rtp, device, line, action, channel, cli, config, feature, feature_button, softkey,\n" " indicate, pbx, socket, mwi, event, adv_feature, conference, buttontemplate, speeddial, codec, realtime,\n" " lock, newcode, high\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "debug" #define CLI_COMPLETE SCCP_CLI_DEBUG_COMPLETER CLI_ENTRY(cli_do_debug, sccp_do_debug, "Set SCCP Debugging Types", do_debug_usage, TRUE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ------------------------------------------------------------------------------------------------------------NO DEBUG- */ /*! * \brief No Debug * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_no_debug(int fd, int argc, char *argv[]) { if (argc < 3) return RESULT_SHOWUSAGE; GLOB(debug) = 0; pbx_cli(fd, "SCCP Debugging Disabled\n"); return RESULT_SUCCESS; } static char no_debug_usage[] = "Usage: SCCP no debug\n" " Disables dumping of SCCP packets for debugging purposes\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "no", "debug" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_no_debug, sccp_no_debug, "Set SCCP Debugging Types", no_debug_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------------RELOAD- */ /*! * \brief Do Reload * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - globals * * \note To find out more about the reload function see \ref sccp_config_reload */ static int sccp_cli_reload(int fd, int argc, char *argv[]) { sccp_readingtype_t readingtype; boolean_t force_reload = FALSE; int returnval = RESULT_SUCCESS; if (argc < 2 || argc > 3) return RESULT_SHOWUSAGE; pbx_mutex_lock(&GLOB(lock)); if (GLOB(reload_in_progress) == TRUE) { pbx_cli(fd, "SCCP reloading already in progress.\n"); pbx_mutex_unlock(&GLOB(lock)); return RESULT_FAILURE; } if (argc > 2) { if (sccp_strequals("force", argv[2])) {\ pbx_cli(fd, "Force Reading Config file '%s'\n", GLOB(config_file_name)); force_reload=TRUE; } else { pbx_cli(fd, "Using config file '%s' (previous config file: '%s')\n", argv[2], GLOB(config_file_name)); if (!sccp_strequals(GLOB(config_file_name), argv[2])) { force_reload=TRUE; } if (GLOB(config_file_name)) { sccp_free(GLOB(config_file_name)); } GLOB(config_file_name) = sccp_strdup(argv[2]); } } sccp_config_file_status_t cfg = sccp_config_getConfig(force_reload); switch (cfg) { case CONFIG_STATUS_FILE_NOT_CHANGED: // if (!force_reload) { pbx_cli(fd, "config file '%s' has not change, skipping reload.\n", GLOB(config_file_name)); returnval = RESULT_SUCCESS; break; // } /* fall through */ case CONFIG_STATUS_FILE_OK: if (GLOB(cfg)) { pbx_cli(fd, "SCCP reloading configuration. %p\n", GLOB(cfg)); readingtype = SCCP_CONFIG_READRELOAD; GLOB(reload_in_progress) = TRUE; pbx_mutex_unlock(&GLOB(lock)); if (!sccp_config_general(readingtype)) { pbx_cli(fd, "Unable to reload configuration.\n"); GLOB(reload_in_progress) = FALSE; pbx_mutex_unlock(&GLOB(lock)); return RESULT_FAILURE; } sccp_config_readDevicesLines(readingtype); pbx_mutex_lock(&GLOB(lock)); GLOB(reload_in_progress) = FALSE; returnval = RESULT_SUCCESS; } break; case CONFIG_STATUS_FILE_OLD: pbx_cli(fd, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_cli(fd, "\n\n --> You are using an old configuration format, please update '%s'!!\n --> Loading of module chan_sccp with current sccp.conf has terminated\n --> Check http://chan-sccp-b.sourceforge.net/doc_setup.shtml for more information.\n\n", GLOB(config_file_name)); returnval = RESULT_FAILURE; break; case CONFIG_STATUS_FILE_NOT_SCCP: pbx_cli(fd, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_cli(fd, "\n\n --> You are using an configuration file is not following the sccp format, please check '%s'!!\n --> Loading of module chan_sccp with current sccp.conf has terminated\n --> Check http://chan-sccp-b.sourceforge.net/doc_setup.shtml for more information.\n\n", GLOB(config_file_name)); returnval = RESULT_FAILURE; break; case CONFIG_STATUS_FILE_NOT_FOUND: pbx_cli(fd, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_cli(fd, "Config file '%s' not found, aborting reload.\n", GLOB(config_file_name)); returnval = RESULT_FAILURE; break; case CONFIG_STATUS_FILE_INVALID: pbx_cli(fd, "Error reloading from '%s'\n", GLOB(config_file_name)); pbx_cli(fd, "Config file '%s' specified is not a valid config file, aborting reload.\n", GLOB(config_file_name)); returnval = RESULT_FAILURE; break; } pbx_mutex_unlock(&GLOB(lock)); return returnval; } static char reload_usage[] = "Usage: SCCP reload [force|filename]\n" " Reloads SCCP configuration from sccp.conf or optional [force|filename]\n" " (It will send a reset to all device which have changed (when they have an active channel reset will be postponed until device goes onhook))\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "reload" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_reload, sccp_cli_reload, "Reload the SCCP configuration", reload_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /*! * \brief Generare sccp.conf * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_cli_config_generate(int fd, int argc, char *argv[]) { #ifdef CS_EXPERIMENTAL int returnval = RESULT_SUCCESS; char *config_file = "sccp.conf.test"; if (argc < 2 || argc > 4) return RESULT_SHOWUSAGE; pbx_cli(fd, "SCCP: Creating config file.\n"); if (argc > 3) { pbx_cli(fd, "Using config file '%s'\n", argv[3]); config_file = sccp_strdupa(argv[3]); } if (sccp_config_generate(config_file, 0)) { pbx_cli(fd, "SCCP generated. saving '%s'...\n", config_file); } else { pbx_cli(fd, "SCCP generation failed.\n"); returnval = RESULT_FAILURE; } return returnval; #else pbx_cli(fd, "online SCCP config generate not implemented yet! use gen_sccpconf from contrib for now.\n"); return RESULT_FAILURE; #endif } static char config_generate_usage[] = "Usage: SCCP config generate [filename]\n" " Generates a new sccp.conf if none exists. Either creating sccp.conf or [filename] if specified\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "config", "generate" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_config_generate, sccp_cli_config_generate, "Generate a SCCP configuration file", config_generate_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -------------------------------------------------------------------------------------------------------SHOW VERSION- */ /*! * \brief Show Version * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_show_version(int fd, int argc, char *argv[]) { pbx_cli(fd, "Skinny Client Control Protocol (SCCP). Release: %s %s - %s (built by '%s' on '%s')\n", SCCP_VERSION, SCCP_BRANCH, SCCP_REVISION, BUILD_USER, BUILD_DATE); return RESULT_SUCCESS; } static char show_version_usage[] = "Usage: SCCP show version\n" " Show SCCP version details\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "show", "version" #define CLI_COMPLETE SCCP_CLI_NULL_COMPLETER CLI_ENTRY(cli_show_version, sccp_show_version, "Show SCCP version details", show_version_usage, FALSE) #undef CLI_COMPLETE #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -------------------------------------------------------------------------------------------------------RESET_RESTART- */ /*! * \brief Reset/Restart * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - devices in sccp_device_find_byid() * - device */ static int sccp_reset_restart(int fd, int argc, char *argv[]) { sccp_device_t *d; boolean_t restart = TRUE; if (argc < 3 || argc > 4) return RESULT_SHOWUSAGE; if (!strcasecmp(argv[1], "reset")) { if (argc == 4) { if (strcasecmp(argv[3], "restart")) return RESULT_SHOWUSAGE; restart = TRUE; } else restart = FALSE; } else if (argc != 3) return RESULT_SHOWUSAGE; pbx_cli(fd, VERBOSE_PREFIX_2 "%s: %s request sent to the device\n", argv[2], argv[1]); d = sccp_device_find_byid(argv[2], FALSE); if (!d) { pbx_cli(fd, "Can't find device %s\n", argv[2]); return RESULT_FAILURE; } if (!d->session || d->registrationState != SKINNY_DEVICE_RS_OK) { pbx_cli(fd, "%s: device not registered\n", argv[2]); d = sccp_device_release(d); return RESULT_FAILURE; } /* sccp_device_clean will check active channels */ /* \todo implement a check for active channels before sending reset */ //if (d->channelCount > 0) { // pbx_cli(fd, "%s: unable to %s device with active channels. Hangup first\n", argv[2], (!strcasecmp(argv[1], "reset")) ? "reset" : "restart"); // return RESULT_SUCCESS; //} if (!restart) sccp_device_sendReset(d, SKINNY_DEVICE_RESET); else sccp_device_sendReset(d, SKINNY_DEVICE_RESTART); pthread_cancel(d->session->session_thread); d = sccp_device_release(d); return RESULT_SUCCESS; } /* --------------------------------------------------------------------------------------------------------------RESET- */ static char reset_usage[] = "Usage: SCCP reset\n" " sccp reset <deviceId> [restart]\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "reset" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER CLI_ENTRY(cli_reset, sccp_reset_restart, "Show SCCP version details", reset_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* -------------------------------------------------------------------------------------------------------------RESTART- */ static char restart_usage[] = "Usage: SCCP restart\n" " sccp restart <deviceId>\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "restart" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER CLI_ENTRY(cli_restart, sccp_reset_restart, "Restart an SCCP device", restart_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ----------------------------------------------------------------------------------------------------------UNREGISTER- */ /*! * \brief Unregister * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - device */ static int sccp_unregister(int fd, int argc, char *argv[]) { sccp_moo_t *r; sccp_device_t *d; if (argc != 3) return RESULT_SHOWUSAGE; pbx_cli(fd, "%s: %s request sent to the device\n", argv[2], argv[1]); d = sccp_device_find_byid(argv[2], FALSE); if (!d) { pbx_cli(fd, "Can't find device %s\n", argv[2]); return RESULT_FAILURE; } if (!d->session) { pbx_cli(fd, "%s: device not registered\n", argv[2]); sccp_device_release(d); return RESULT_FAILURE; } pbx_cli(fd, "%s: Turn off the monitored line lamps to permit the %s\n", argv[2], argv[1]); REQ(r, RegisterRejectMessage); strncpy(r->msg.RegisterRejectMessage.text, "Unregister user request", StationMaxDisplayTextSize); sccp_dev_send(d, r); d = sccp_device_release(d); return RESULT_SUCCESS; } static char unregister_usage[] = "Usage: SCCP unregister <deviceId>\n" " Unregister an SCCP device\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "unregister" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER CLI_ENTRY(cli_unregister, sccp_unregister, "Unregister an SCCP device", unregister_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------------START CALL- */ /*! * \brief Start Call * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ static int sccp_start_call(int fd, int argc, char *argv[]) { sccp_device_t *d; sccp_channel_t *channel = NULL; sccp_line_t *line = NULL; if (argc < 3) { pbx_cli(fd, "argc is less then 2: %d\n", argc); return RESULT_SHOWUSAGE; } if (pbx_strlen_zero(argv[2])) { pbx_cli(fd, "string length of argv[2] is zero\n"); return RESULT_SHOWUSAGE; } d = sccp_device_find_byid(argv[2], FALSE); if (!d) { pbx_cli(fd, "Can't find settings for device %s\n", argv[2]); return RESULT_FAILURE; } if (d && d->defaultLineInstance > 0) { line = sccp_line_find_byid(d, d->defaultLineInstance); } else { line = sccp_dev_get_activeline(d); } if (!line) { pbx_cli(fd, "Can't find line for device %s\n", argv[2]); d = sccp_device_release(d); return RESULT_FAILURE; } pbx_cli(fd, "Starting Call for Device: %s\n", argv[2]); channel = sccp_channel_newcall(line, d, argv[3], SKINNY_CALLTYPE_OUTBOUND, NULL); line = sccp_line_release(line); d = sccp_device_release(d); channel = channel ? sccp_channel_release(channel) : NULL; return RESULT_SUCCESS; } static char start_call_usage[] = "Usage: sccp call <deviceId> <phone_number>\n" "Call number <number> using device <deviceId>\nIf number is ommitted, device will go off-Hook.\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "call" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER CLI_ENTRY(cli_start_call, sccp_start_call, "Call Number via Device", start_call_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------------SET HOLD- */ /*! * \brief Set Channel on Hold * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - channel */ static int sccp_set_object(int fd, int argc, char *argv[]) { sccp_channel_t *c = NULL; sccp_device_t *device = NULL; PBX_VARIABLE_TYPE variable; int res; if (argc < 5) return RESULT_SHOWUSAGE; if (pbx_strlen_zero(argv[3]) || pbx_strlen_zero(argv[4])) return RESULT_SHOWUSAGE; if (!strcmp("channel", argv[2])) { // sccp set channel SCCP/test-123 hold on if (!strncasecmp("SCCP/", argv[3], 5)) { int line, channel; sscanf(argv[3], "SCCP/%d-%d", &line, &channel); c = sccp_channel_find_byid(channel); } else { c = sccp_channel_find_byid(atoi(argv[3])); } if (!c) { pbx_cli(fd, "Can't find channel for ID %s\n", argv[3]); return RESULT_FAILURE; } if (!strcmp("hold", argv[4]) ){ if (!strcmp("on", argv[5])) { /* check to see if enable hold */ pbx_cli(fd, "PLACING CHANNEL %s ON HOLD\n", argv[3]); sccp_channel_hold(c); } else if (!strcmp("off", argv[5])) { /* check to see if disable hold */ pbx_cli(fd, "PLACING CHANNEL %s OFF HOLD\n", argv[3]); sccp_device_t *d = sccp_channel_getDevice_retained(c); sccp_channel_resume(d, c, FALSE); d = sccp_device_release(d); } else { /* wrong parameter value */ c = sccp_channel_release(c); return RESULT_SHOWUSAGE; } } c = sccp_channel_release(c); } else if (!strcmp("device", argv[2])) { // sccp set device SEP00000 ringtone http://1234 if (argc < 6){ return RESULT_SHOWUSAGE; } if (pbx_strlen_zero(argv[3]) || pbx_strlen_zero(argv[4]) || pbx_strlen_zero(argv[5])) return RESULT_SHOWUSAGE; } char *dev = sccp_strdupa(argv[3]); if (pbx_strlen_zero(dev)) { pbx_log(LOG_WARNING, "DeviceName needs to be supplied\n"); // CLI_AMI_ERROR(fd, s, m, "DeviceName needs to be supplied %s\n", ""); } device = sccp_device_find_byid(dev, FALSE); if (!device) { pbx_log(LOG_WARNING, "Failed to get device %s\n", dev); // CLI_AMI_ERROR(fd, s, m, "Can't find settings for device %s\n", dev); return RESULT_FAILURE; } if(!strcmp("ringtone", argv[4])){ device->setRingTone(device, argv[5]); } else if(!strcmp("backgroundImage", argv[4])){ device->setBackgroundImage(device, argv[5]); } else { variable.name = argv[4]; variable.value = argv[5]; variable.next = NULL; variable.file = "cli"; variable.lineno = 0; res = sccp_config_applyDeviceConfiguration(device, &variable); if (res & SCCP_CONFIG_NEEDDEVICERESET){ device->pendingUpdate = 1; } } device = device ? sccp_device_release(device) : NULL; return RESULT_SUCCESS; } static char set_hold_usage[] = "Usage: sccp set [hold|device] <channelId> <on/off>\n" "Set a channel to hold/unhold\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "set" #define CLI_COMPLETE SCCP_CLI_SET_COMPLETER CLI_ENTRY(cli_set_hold, sccp_set_object, "Set channel|device to hold/unhold", set_hold_usage, TRUE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------------REMOTE ANSWER- */ /*! * \brief Answer a Remote Channel * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - channel */ static int sccp_remote_answer(int fd, int argc, char *argv[]) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (argc < 3) return RESULT_SHOWUSAGE; if (pbx_strlen_zero(argv[2])) return RESULT_SHOWUSAGE; if (!strncasecmp("SCCP/", argv[2], 5)) { int line, channel; sscanf(argv[2], "SCCP/%d-%d", &line, &channel); c = sccp_channel_find_byid(channel); } else { c = sccp_channel_find_byid(atoi(argv[2])); } if (!c) { pbx_cli(fd, "Can't find channel for ID %s\n", argv[2]); return RESULT_FAILURE; } else { pbx_cli(fd, "ANSWERING CHANNEL %s \n", argv[2]); if ((d = sccp_channel_getDevice_retained(c))) { sccp_channel_answer(d, c); d = sccp_device_release(d); } if (c->owner) { PBX(queue_control) (c->owner, AST_CONTROL_ANSWER); } c = sccp_channel_release(c); return RESULT_SUCCESS; } } static char remote_answer_usage[] = "Usage: sccp answer <channelId>\n" "Answer a ringing/incoming channel\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "answer" #define CLI_COMPLETE SCCP_CLI_CHANNEL_COMPLETER CLI_ENTRY(cli_remote_answer, sccp_remote_answer, "Answer a ringing/incoming channel", remote_answer_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --------------------------------------------------------------------------------------------------------------END CALL- */ /*! * \brief End a Call (on a Channel) * \param fd Fd as int * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - channel */ static int sccp_end_call(int fd, int argc, char *argv[]) { sccp_channel_t *c = NULL; if (argc < 3) return RESULT_SHOWUSAGE; if (pbx_strlen_zero(argv[2])) return RESULT_SHOWUSAGE; if (!strncasecmp("SCCP/", argv[2], 5)) { int line, channel; sscanf(argv[2], "SCCP/%d-%d", &line, &channel); c = sccp_channel_find_byid(channel); } else { c = sccp_channel_find_byid(atoi(argv[2])); } if (!c) { pbx_cli(fd, "Can't find channel for ID %s\n", argv[2]); return RESULT_FAILURE; } pbx_cli(fd, "ENDING CALL ON CHANNEL %s \n", argv[2]); sccp_channel_endcall(c); c = sccp_channel_release(c); return RESULT_SUCCESS; } static char end_call_usage[] = "Usage: sccp onhook <channelId>\n" "Hangup a channel\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "onhook" #define CLI_COMPLETE SCCP_CLI_CHANNEL_COMPLETER CLI_ENTRY(cli_end_call, sccp_end_call, "Hangup a channel", end_call_usage, FALSE) #undef CLI_COMMAND #undef CLI_COMPLETE #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* ---------------------------------------------------------------------------------------------------------------------- TOKEN - */ /*! * \brief Send Token Ack to device(s) * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk * * \lock * - channel */ static int sccp_tokenack(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_device_t *d; int local_total = 0; const char *dev; if (argc < 3 || sccp_strlen_zero(argv[2])) { return RESULT_SHOWUSAGE; } dev = sccp_strdupa(argv[2]); d = sccp_device_find_byid(dev, FALSE); if (!d) { pbx_log(LOG_WARNING, "Failed to get device %s\n", dev); CLI_AMI_ERROR(fd, s, m, "Can't find settings for device %s\n", dev); } if (d->status.token != SCCP_TOKEN_STATE_REJ && d->session) { pbx_log(LOG_WARNING, "%s: We need to have received a token request before we can acknowledge it\n", dev); CLI_AMI_ERROR(fd, s, m, "%s: We need to have received a token request before we can acknowledge it\n", dev); } else { if (d->session) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Sending phone a token acknowledgement\n", dev); sccp_session_tokenAck(d->session); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Phone not connected to this server (no valid session)\n", dev); } } sccp_device_release(d); if (s) *total = local_total; return RESULT_SUCCESS; } static char cli_tokenack_usage[] = "Usage: sccp tokenack <deviceId>\n" "Send Token Acknowlegde. Makes a phone switch servers on demand (used in clustering)\n"; static char ami_tokenack_usage[] = "Usage: SCCPTokenAck\n" "Send Token Acknowledge to device. Makes a phone switch servers on demand (used in clustering)\n\n" "PARAMS: DeviceName\n"; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CLI_COMMAND "sccp", "tokenack" #define CLI_COMPLETE SCCP_CLI_CONNECTED_DEVICE_COMPLETER #define AMI_COMMAND "SCCPTokenAck" #define CLI_AMI_PARAMS "DeviceName" CLI_AMI_ENTRY(tokenack, sccp_tokenack, "Send TokenAck", cli_tokenack_usage, FALSE) #undef CLI_AMI_PARAMS #undef CLI_COMPLETE #undef AMI_COMMAND #undef CLI_COMMAND #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /* --- Register Cli Entries-------------------------------------------------------------------------------------------- */ /*! * \brief Asterisk Cli Entry * * structure for cli functions including short description. * * \return Result as struct * \todo add short description */ static struct pbx_cli_entry cli_entries[] = { AST_CLI_DEFINE(cli_show_globals, "Show SCCP global settings."), AST_CLI_DEFINE(cli_show_devices, "Show all SCCP Devices."), AST_CLI_DEFINE(cli_show_device, "Show an SCCP Device"), AST_CLI_DEFINE(cli_show_lines, "Show All SCCP Lines."), AST_CLI_DEFINE(cli_show_line, "Show an SCCP Line."), AST_CLI_DEFINE(cli_show_channels, "Show all SCCP channels."), AST_CLI_DEFINE(cli_show_version, "SCCP show version."), AST_CLI_DEFINE(cli_show_mwi_subscriptions, "Show all mwi subscriptions"), AST_CLI_DEFINE(cli_show_softkeysets, "Show all mwi configured SoftKeySets"), AST_CLI_DEFINE(cli_unregister, "Unregister an SCCP device"), AST_CLI_DEFINE(cli_system_message, "Set the SCCP system message."), AST_CLI_DEFINE(cli_message_devices, "Send a message to all SCCP Devices."), AST_CLI_DEFINE(cli_message_device, "Send a message to an SCCP Device."), AST_CLI_DEFINE(cli_remove_line_from_device, "Remove a line from a device."), AST_CLI_DEFINE(cli_add_line_to_device, "Add a line to a device."), AST_CLI_DEFINE(cli_show_sessions, "Show All SCCP Sessions."), AST_CLI_DEFINE(cli_dnd_device, "Set DND on a device"), AST_CLI_DEFINE(cli_do_debug, "Enable SCCP debugging."), AST_CLI_DEFINE(cli_no_debug, "Disable SCCP debugging."), AST_CLI_DEFINE(cli_config_generate, "SCCP generate config file."), AST_CLI_DEFINE(cli_reload, "SCCP module reload."), AST_CLI_DEFINE(cli_restart, "Restart an SCCP device"), AST_CLI_DEFINE(cli_reset, "Reset an SCCP Device"), AST_CLI_DEFINE(cli_start_call, "Start a Call."), AST_CLI_DEFINE(cli_end_call, "End a Call."), AST_CLI_DEFINE(cli_set_hold, "Place call on hold."), AST_CLI_DEFINE(cli_remote_answer, "Remotely answer a call."), #if defined(DEBUG) || defined(CS_EXPERIMENTAL) AST_CLI_DEFINE(cli_test_message, "Test message."), AST_CLI_DEFINE(cli_show_refcount, "Test message."), #endif AST_CLI_DEFINE(cli_tokenack, "Send Token Acknowledgement."), #ifdef CS_SCCP_CONFERENCE AST_CLI_DEFINE(cli_show_conferences, "Show running SCCP Conferences."), AST_CLI_DEFINE(cli_show_conference, "Show SCCP Conference Info."), AST_CLI_DEFINE(cli_conference_action, "Conference Actions.") #endif }; /*! * register CLI functions from asterisk */ void sccp_register_cli(void) { int i, res = 0; for (i = 0; i < ARRAY_LEN(cli_entries); i++) { sccp_log(DEBUGCAT_CLI) (VERBOSE_PREFIX_2 "Cli registered action %s\n", (cli_entries + i)->_full_cmd); res |= pbx_cli_register(cli_entries + i); } #if ASTERISK_VERSION_NUMBER < 10600 #define _MAN_COM_FLAGS EVENT_FLAG_SYSTEM | EVENT_FLAG_COMMAND #define _MAN_REP_FLAGS EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG #else #define _MAN_COM_FLAGS EVENT_FLAG_SYSTEM | EVENT_FLAG_COMMAND #define _MAN_REP_FLAGS EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG | EVENT_FLAG_REPORTING #endif pbx_manager_register("SCCPShowGlobals", _MAN_REP_FLAGS, manager_show_globals, "show globals setting", ami_globals_usage); pbx_manager_register("SCCPShowDevices", _MAN_REP_FLAGS, manager_show_devices, "show devices", ami_devices_usage); pbx_manager_register("SCCPShowDevice", _MAN_REP_FLAGS, manager_show_device, "show device settings", ami_device_usage); pbx_manager_register("SCCPShowLines", _MAN_REP_FLAGS, manager_show_lines, "show lines", ami_lines_usage); pbx_manager_register("SCCPShowLine", _MAN_REP_FLAGS, manager_show_line, "show line", ami_line_usage); pbx_manager_register("SCCPShowChannels", _MAN_REP_FLAGS, manager_show_channels, "show channels", ami_channels_usage); pbx_manager_register("SCCPShowSessions", _MAN_REP_FLAGS, manager_show_sessions, "show sessions", ami_sessions_usage); pbx_manager_register("SCCPShowMWISubscriptions", _MAN_REP_FLAGS, manager_show_mwi_subscriptions, "show sessions", ami_mwi_subscriptions_usage); pbx_manager_register("SCCPShowSoftkeySets", _MAN_REP_FLAGS, manager_show_softkeysets, "show softkey sets", ami_show_softkeysets_usage); pbx_manager_register("SCCPMessageDevices", _MAN_REP_FLAGS, manager_message_devices, "message devices", ami_message_devices_usage); pbx_manager_register("SCCPTokenAck", _MAN_REP_FLAGS, manager_tokenack, "send tokenack", ami_tokenack_usage); #ifdef CS_SCCP_CONFERENCE pbx_manager_register("SCCPShowConferences", _MAN_REP_FLAGS, manager_show_conferences, "show conferences", ami_conferences_usage); pbx_manager_register("SCCPShowConference", _MAN_REP_FLAGS, manager_show_conference, "show conference", ami_conference_usage); pbx_manager_register("SCCPConference", _MAN_REP_FLAGS, manager_conference_action, "conference actions", ami_conference_action_usage); #endif } /*! * unregister CLI functions from asterisk */ void sccp_unregister_cli(void) { int i, res = 0; for (i = 0; i < ARRAY_LEN(cli_entries); i++) { sccp_log(DEBUGCAT_CLI) (VERBOSE_PREFIX_2 "Cli unregistered action %s\n", (cli_entries + i)->_full_cmd); res |= pbx_cli_unregister(cli_entries + i); } pbx_manager_unregister("SCCPShowGlobals"); pbx_manager_unregister("SCCPShowDevice"); pbx_manager_unregister("SCCPShowDevices"); pbx_manager_unregister("SCCPShowLines"); pbx_manager_unregister("SCCPShowLine"); pbx_manager_unregister("SCCPShowChannels"); pbx_manager_unregister("SCCPShowSessions"); pbx_manager_unregister("SCCPShowMWISubscriptions"); pbx_manager_unregister("SCCPShowSoftkeySets"); pbx_manager_unregister("SCCPMessageDevices"); pbx_manager_unregister("SCCPTokenAck"); #ifdef CS_SCCP_CONFERENCE pbx_manager_unregister("SCCPShowConferences"); pbx_manager_unregister("SCCPShowConference"); pbx_manager_unregister("SCCPConference"); #endif }
722,264
./chan-sccp-b/src/sccp_lock.c
/*! * \file sccp_lock.c * \brief SCCP Lock Class * \author Federico Santulli <fsantulli [at] users.sourceforge.net> * \note Mutex lock code derived from Asterisk 1.4 * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") #ifdef CS_AST_DEBUG_CHANNEL_LOCKS #define CS_LOCKS_DEBUG_ALL /*! * \brief Mutex Unlock AST MUTEX (and print debugging output) * \param mutex Mutex as ast_mutex_t * \param itemnametolock Item-Name to Lock as char * \param filename FileName as char * \param lineno LineNumber as int * \param func Function as char * \return Result as int * * \note You need to enable DEBUG__LOCKS for this function */ int __sccp_mutex_unlock(ast_mutex_t * p_mutex, const char *itemnametolock, const char *filename, int lineno, const char *func) { int res = 0; #ifdef CS_LOCKS_DEBUG_ALL if (strncasecmp(filename, "sccp_socket.c", 13)) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: Unlocking %s\n", filename, lineno, func, itemnametolock); #endif if (!p_mutex) { sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: Unlocking non-existing mutex\n", filename, lineno, func); return 0; } #ifdef CS_AST_DEBUG_THREADS res = __pbx_pthread_mutex_unlock(filename, lineno, func, itemnametolock, p_mutex); #else res = pbx_mutex_unlock(p_mutex); #endif #ifdef CS_LOCKS_DEBUG_ALL #ifdef CS_AST_DEBUG_THREADS int count = 0; #ifndef CS_AST_LOCK_TRACK if ((count = p_mutex->reentrancy)) { #else if ((count = p_mutex->track.reentrancy)) { #endif if (strncasecmp(filename, "sccp_socket", 11)) { sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s now have %d locks (recursive)\n", filename, lineno, func, itemnametolock, count); } } #endif #endif #ifdef CS_LOCKS_DEBUG_ALL if (!res) { if (strncasecmp(filename, "sccp_socket.c", 13)) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s was unlocked\n", filename, lineno, func, itemnametolock); } #endif if (res == EINVAL) { sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s had no lock by this thread. Failed unlocking\n", filename, lineno, func, itemnametolock); } if (res == EPERM) { /* We had no lock, so okay any way */ sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s was not locked at all \n", filename, lineno, func, itemnametolock); res = 0; } return res; } /*! * \brief Mutex Lock (and print debugging output) * \param mutex Mutex as ast_mutex_t * \param itemnametolock Item-Name to Lock as char * \param filename FileName as char * \param lineno LineNumber as int * \param func Function as char * \return Result as int * \note You need to enable DEBUG__LOCKS for this function */ int __sccp_mutex_lock(ast_mutex_t * p_mutex, const char *itemnametolock, const char *filename, int lineno, const char *func) { int res; #ifdef CS_LOCKS_DEBUG_ALL if (strncasecmp(filename, "sccp_socket.c", 13)) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: Locking %s\n", filename, lineno, func, itemnametolock); #endif #ifdef CS_AST_DEBUG_THREADS res = __pbx_pthread_mutex_lock(filename, lineno, func, itemnametolock, p_mutex); #else res = pbx_mutex_lock(p_mutex); #endif #ifdef CS_LOCKS_DEBUG_ALL #ifdef CS_AST_DEBUG_THREADS int count = 0; #ifndef CS_AST_LOCK_TRACK if ((count = p_mutex->reentrancy)) { #else if ((count = p_mutex->track.reentrancy)) { #endif if (strncasecmp(filename, "sccp_socket", 11)) { sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s now have %d locks (recursive)\n", filename, lineno, func, itemnametolock, count); } } #endif #endif #ifdef CS_LOCKS_DEBUG_ALL if (!res) { if (strncasecmp(filename, "sccp_socket.c", 13)) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s was locked\n", filename, lineno, func, itemnametolock); } #endif if (res == EDEADLK) { /* We had no lock, so okey any way */ sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s was not locked by us. Lock would cause deadlock.\n", filename, lineno, func, itemnametolock); } if (res == EINVAL) { sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s lock failed. No mutex.\n", filename, lineno, func, itemnametolock); } return res; } /*! * \brief Try to get a Lock (and print debugging output) * \param mutex Mutex as ast_mutex_t * \param itemnametolock Item-Name to Lock as char * \param filename FileName as char * \param lineno LineNumber as int * \param func Function as char * \return Result as int * \note You need to enable DEBUG__LOCKS for this function */ int __sccp_mutex_trylock(ast_mutex_t * p_mutex, const char *itemnametolock, const char *filename, int lineno, const char *func) { int res; #ifdef CS_LOCKS_DEBUG_ALL if (strncasecmp(filename, "sccp_socket.c", 13)) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: Trying to lock %s\n", filename, lineno, func, itemnametolock); #endif #ifdef CS_AST_DEBUG_THREADS res = __pbx_pthread_mutex_trylock(filename, lineno, func, itemnametolock, p_mutex); #else res = pbx_mutex_trylock(p_mutex); #endif #ifdef CS_LOCKS_DEBUG_ALL #ifdef CS_AST_DEBUG_THREADS int count = 0; #ifndef CS_AST_LOCK_TRACK if ((count = p_mutex->reentrancy)) { #else if ((count = p_mutex->track.reentrancy)) { #endif if (strncasecmp(filename, "sccp_socket", 11)) { sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s now have %d locks (recursive)\n", filename, lineno, func, itemnametolock, count); } } #endif #endif #ifdef CS_LOCKS_DEBUG_ALL if (!res) { if (strncasecmp(filename, "sccp_socket", 11)) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s was locked\n", filename, lineno, func, itemnametolock); } #endif if (res == EBUSY) { /* We failed to lock */ sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s failed to lock. Not waiting around...\n", filename, lineno, func, itemnametolock); } if (res == EDEADLK) { /* We had no lock, so okey any way */ sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s was not locked. Lock would cause deadlock.\n", filename, lineno, func, itemnametolock); } if (res == EINVAL) sccp_log((DEBUGCAT_LOCK)) (VERBOSE_PREFIX_3 "::::==== %s line %d (%s) SCCP_MUTEX: %s lock failed. No mutex.\n", filename, lineno, func, itemnametolock); return res; } #endif
722,265
./chan-sccp-b/src/sccp_threadpool.c
/*! * \file sccp_threadpool.c * \brief SCCP Threadpool Class * \author Diederik de Groot < ddegroot@users.sourceforge.net > * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \note Based on the work of Johan Hanssen Seferidis * Library providing a threading pool where you can add work. * \since 2009-01-16 * \remarks Purpose: SCCP Hint * When to use: Does the business of hint status * * $Date: 2011-01-04 17:29:12 +0100 (Tue, 04 Jan 2011) $ * $Revision: 2215 $ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision: 2215 $") #include "sccp_threadpool.h" #include <signal.h> #undef pthread_create #if defined(__GNUC__) && __GNUC__ > 3 && defined(HAVE_SYS_INFO_H) #include <sys/sysinfo.h> // to retrieve processor info #endif #define SEMAPHORE_LOCKED (0) #define SEMAPHORE_UNLOCKED (1) void sccp_threadpool_grow(sccp_threadpool_t * tp_p, int amount); void sccp_threadpool_shrink(sccp_threadpool_t * tp_p, int amount); typedef struct sccp_threadpool_thread sccp_threadpool_thread_t; struct sccp_threadpool_thread { pthread_t thread; int die; sccp_threadpool_t *tp_p; SCCP_LIST_ENTRY (sccp_threadpool_thread_t) list; }; /* The threadpool */ struct sccp_threadpool { // pthread_t *threads; /*!< pointer to threads' ID */ // int threadsN; /*!< amount of threads */ SCCP_LIST_HEAD (, sccp_threadpool_job_t) jobs; SCCP_LIST_HEAD (, sccp_threadpool_thread_t) threads; ast_cond_t work; ast_cond_t exit; time_t last_size_check; /*!< Time since last size check */ time_t last_resize; /*!< Time since last resize */ int job_high_water_mark; /*!< Highest number of jobs outstanding since last resize check */ }; /* * Fast reminders: * * tp = threadpool * sccp_threadpool = threadpool * sccp_threadpool_t = threadpool type * tp_p = threadpool pointer * sem = semaphore * xN = x can be any string. N stands for amount * */ static volatile int sccp_threadpool_shuttingdown = 0; /* Initialise thread pool */ sccp_threadpool_t *sccp_threadpool_init(int threadsN) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Starting Threadpool\n"); sccp_threadpool_t *tp_p; #if defined(__GNUC__) && __GNUC__ > 3 && defined(HAVE_SYS_INFO_H) threadsN = get_nprocs_conf(); // get current number of active processors #endif if (!threadsN || threadsN < THREADPOOL_MIN_SIZE) threadsN = THREADPOOL_MIN_SIZE; if (threadsN > THREADPOOL_MAX_SIZE) threadsN = THREADPOOL_MAX_SIZE; /* Make new thread pool */ tp_p = (sccp_threadpool_t *) malloc(sizeof(sccp_threadpool_t)); /* MALLOC thread pool */ if (tp_p == NULL) { pbx_log(LOG_ERROR, "sccp_threadpool_init(): Could not allocate memory for thread pool\n"); return NULL; } /* initialize the thread pool */ SCCP_LIST_HEAD_INIT(&tp_p->threads); /* Initialise the job queue */ SCCP_LIST_HEAD_INIT(&tp_p->jobs); tp_p->last_size_check = time(0); tp_p->job_high_water_mark = 0; tp_p->last_resize = time(0); /* Initialise Condition */ ast_cond_init(&(tp_p->work), NULL); ast_cond_init(&(tp_p->exit), NULL); /* Make threads in pool */ SCCP_LIST_LOCK(&(tp_p->threads)); sccp_threadpool_grow(tp_p, threadsN); SCCP_LIST_UNLOCK(&(tp_p->threads)); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Threadpool Started\n"); return tp_p; } // sccp_threadpool_grow needs to be called with locked &(tp_p->threads)->lock void sccp_threadpool_grow(sccp_threadpool_t * tp_p, int amount) { pthread_attr_t attr; sccp_threadpool_thread_t *tp_thread; int t; if (tp_p && !sccp_threadpool_shuttingdown) { for (t = 0; t < amount; t++) { tp_thread = malloc(sizeof(sccp_threadpool_thread_t)); if (tp_thread == NULL) { pbx_log(LOG_ERROR, "sccp_threadpool_init(): Could not allocate memory for thread\n"); return; } tp_thread->die = 0; tp_thread->tp_p = tp_p; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); SCCP_LIST_INSERT_HEAD(&(tp_p->threads), tp_thread, list); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Create thread %d in pool \n", t); pbx_pthread_create(&(tp_thread->thread), &attr, (void *) sccp_threadpool_thread_do, (void *) tp_thread); ast_cond_broadcast(&(tp_p->work)); } } } // sccp_threadpool_shrink needs to be called with locked &(tp_p->threads)->lock void sccp_threadpool_shrink(sccp_threadpool_t * tp_p, int amount) { sccp_threadpool_thread_t *tp_thread; int t; if (tp_p && !sccp_threadpool_shuttingdown) { for (t = 0; t < amount; t++) { tp_thread = SCCP_LIST_FIRST(&(tp_p->threads)); tp_thread->die = 1; sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Sending die signal to thread %d in pool \n", (unsigned int) tp_thread->thread); // wake up all threads ast_cond_broadcast(&(tp_p->work)); } } } /* check threadpool size (increase/decrease if necessary) */ static void sccp_threadpool_check_size(sccp_threadpool_t * tp_p) { if (tp_p && !sccp_threadpool_shuttingdown) { sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_check_resize) in thread: %d\n", (unsigned int) pthread_self()); SCCP_LIST_LOCK(&(tp_p->threads)); { if (SCCP_LIST_GETSIZE(tp_p->jobs) > (SCCP_LIST_GETSIZE(tp_p->threads) * 2) && SCCP_LIST_GETSIZE(tp_p->threads) < THREADPOOL_MAX_SIZE) { // increase sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Add new thread to threadpool %p\n", tp_p); sccp_threadpool_grow(tp_p, 1); tp_p->last_resize = time(0); } else if (((time(0) - tp_p->last_resize) > THREADPOOL_RESIZE_INTERVAL * 3) && // wait a little longer to decrease (SCCP_LIST_GETSIZE(tp_p->threads) > THREADPOOL_MIN_SIZE && SCCP_LIST_GETSIZE(tp_p->jobs) < (SCCP_LIST_GETSIZE(tp_p->threads) / 2))) { // decrease sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Remove thread %d from threadpool %p\n", SCCP_LIST_GETSIZE(tp_p->threads) - 1, tp_p); // kill last thread only if it is not executed by itself sccp_threadpool_shrink(tp_p, 1); tp_p->last_resize = time(0); } tp_p->last_size_check = time(0); tp_p->job_high_water_mark = SCCP_LIST_GETSIZE(tp_p->jobs); sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_check_resize) Number of threads: %d, job_high_water_mark: %d\n", SCCP_LIST_GETSIZE(tp_p->threads), tp_p->job_high_water_mark); } SCCP_LIST_UNLOCK(&(tp_p->threads)); } } void sccp_threadpool_thread_end(void *p) { sccp_threadpool_thread_t *tp_thread = (sccp_threadpool_thread_t *) p; sccp_threadpool_thread_t *res = NULL; sccp_threadpool_t *tp_p = tp_thread->tp_p; SCCP_LIST_LOCK(&(tp_p->threads)); res = SCCP_LIST_REMOVE(&(tp_p->threads), tp_thread, list); SCCP_LIST_UNLOCK(&(tp_p->threads)); ast_cond_signal(&(tp_p->exit)); if (res) free(res); } /* What each individual thread is doing */ void sccp_threadpool_thread_do(void *p) { sccp_threadpool_thread_t *tp_thread = (sccp_threadpool_thread_t *) p; sccp_threadpool_t *tp_p = tp_thread->tp_p; uint threadid = (unsigned int) pthread_self(); pthread_cleanup_push(sccp_threadpool_thread_end, tp_thread); int jobs = 0, threads = 0; sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Starting Threadpool JobQueue\n"); while (1) { pthread_testcancel(); jobs = SCCP_LIST_GETSIZE(tp_p->jobs); threads = SCCP_LIST_GETSIZE(tp_p->threads); sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_thread_do) num_jobs: %d, threadid: %d, num_threads: %d\n", jobs, threadid, threads); SCCP_LIST_LOCK(&(tp_p->jobs)); /* LOCK */ while (SCCP_LIST_GETSIZE(tp_p->jobs) == 0 && !tp_thread->die) { if (tp_thread->die && SCCP_LIST_GETSIZE(tp_p->jobs) == 0) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "JobQueue Die. Exiting thread %d...\n", threadid); SCCP_LIST_UNLOCK(&(tp_p->jobs)); pthread_exit(0); } sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_thread_do) Thread %d Waiting for New Work Condition\n", threadid); ast_cond_wait(&(tp_p->work), &(tp_p->jobs.lock)); } if (tp_thread->die && SCCP_LIST_GETSIZE(tp_p->jobs) == 0) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "JobQueue Die. Exiting thread %d...\n", threadid); SCCP_LIST_UNLOCK(&(tp_p->jobs)); pthread_exit(0); } sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_thread_do) Let's work. num_jobs: %d, threadid: %d, num_threads: %d\n", jobs, threadid, threads); { /* Read job from queue and execute it */ void *(*func_buff) (void *arg) = NULL; void *arg_buff = NULL; sccp_threadpool_job_t *job; if ((job = SCCP_LIST_REMOVE_HEAD(&(tp_p->jobs), list))) { func_buff = job->function; arg_buff = job->arg; } SCCP_LIST_UNLOCK(&(tp_p->jobs)); sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_thread_do) executing %p in threadid: %d\n", job, threadid); if (job) { func_buff(arg_buff); /* run function */ free(job); /* DEALLOC job */ } // check number of threads in threadpool if ((time(0) - tp_p->last_size_check) > THREADPOOL_RESIZE_INTERVAL) { sccp_threadpool_check_size(tp_p); /* Check Resizing */ } } } sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "JobQueue Exiting Thread...\n"); pthread_cleanup_pop(1); return; } /* Add work to the thread pool */ int sccp_threadpool_add_work(sccp_threadpool_t * tp_p, void *(*function_p) (void *), void *arg_p) { // prevent new work while shutting down if (!sccp_threadpool_shuttingdown) { sccp_threadpool_job_t *newJob; newJob = (sccp_threadpool_job_t *) malloc(sizeof(sccp_threadpool_job_t)); /* MALLOC job */ if (newJob == NULL) { pbx_log(LOG_ERROR, "sccp_threadpool_add_work(): Could not allocate memory for new job\n"); exit(1); } /* add function and argument */ newJob->function = function_p; newJob->arg = arg_p; /* add job to queue */ sccp_threadpool_jobqueue_add(tp_p, newJob); return 1; } else { pbx_log(LOG_ERROR, "sccp_threadpool_add_work(): Threadpool shutting down, denying new work\n"); return 0; } } /* Destroy the threadpool */ void sccp_threadpool_destroy(sccp_threadpool_t * tp_p) { sccp_threadpool_thread_t *tp_thread = NULL; sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Destroying Threadpool %p with %d jobs\n", tp_p, SCCP_LIST_GETSIZE(tp_p->jobs)); // After this point, no new jobs can be added SCCP_LIST_LOCK(&(tp_p->jobs)); sccp_threadpool_shuttingdown = 1; SCCP_LIST_UNLOCK(&(tp_p->jobs)); // shutdown is a kind of work too SCCP_LIST_LOCK(&(tp_p->threads)); SCCP_LIST_TRAVERSE(&(tp_p->threads), tp_thread, list) { tp_thread->die = 1; ast_cond_broadcast(&(tp_p->work)); } SCCP_LIST_UNLOCK(&(tp_p->threads)); // wake up jobs untill jobqueue is empty, before shutting down, to make sure all jobs have been processed ast_cond_broadcast(&(tp_p->work)); // wait for all threads to exit if (SCCP_LIST_GETSIZE(tp_p->threads) != 0) { struct timespec ts; struct timeval tp; int counter = 0; SCCP_LIST_LOCK(&(tp_p->threads)); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Waiting for threadpool to wind down. please stand by...\n"); while (SCCP_LIST_GETSIZE(tp_p->threads) != 0 && counter++ < THREADPOOL_MAX_SIZE) { gettimeofday(&tp, NULL); ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; ts.tv_sec += 1; // wait max 2 second ast_cond_broadcast(&(tp_p->work)); ast_cond_timedwait(&tp_p->exit, &(tp_p->threads.lock), &ts); } /* Make sure threads have finished (should never have to execute) */ if (SCCP_LIST_GETSIZE(tp_p->threads) != 0) { while ((tp_thread = SCCP_LIST_REMOVE_HEAD(&(tp_p->threads), list))) { pbx_log(LOG_ERROR, "Forcing Destroy of thread %p\n", tp_thread); pthread_cancel(tp_thread->thread); pthread_kill(tp_thread->thread, SIGURG); pthread_join(tp_thread->thread, NULL); } } SCCP_LIST_UNLOCK(&(tp_p->threads)); } /* Dealloc */ ast_cond_destroy(&(tp_p->work)); /* Remove Condition */ ast_cond_destroy(&(tp_p->exit)); /* Remove Condition */ SCCP_LIST_HEAD_DESTROY(&(tp_p->jobs)); SCCP_LIST_HEAD_DESTROY(&(tp_p->threads)); free(tp_p); /* DEALLOC thread pool */ sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "Threadpool Ended\n"); } int sccp_threadpool_thread_count(sccp_threadpool_t * tp_p) { return SCCP_LIST_GETSIZE(tp_p->threads); } /* =================== JOB QUEUE OPERATIONS ===================== */ /* Add job to queue */ void sccp_threadpool_jobqueue_add(sccp_threadpool_t * tp_p, sccp_threadpool_job_t * newjob_p) { if (!tp_p) { pbx_log(LOG_ERROR, "(sccp_threadpool_jobqueue_add) no tp_p\n"); sccp_free(newjob_p); return; } sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_jobqueue_add) tp_p: %p, jobCount: %d\n", tp_p, SCCP_LIST_GETSIZE(tp_p->jobs)); SCCP_LIST_LOCK(&(tp_p->jobs)); if (sccp_threadpool_shuttingdown) { pbx_log(LOG_ERROR, "(sccp_threadpool_jobqueue_add) shutting down\n"); SCCP_LIST_UNLOCK(&(tp_p->jobs)); sccp_free(newjob_p); return; } SCCP_LIST_INSERT_TAIL(&(tp_p->jobs), newjob_p, list); SCCP_LIST_UNLOCK(&(tp_p->jobs)); if (SCCP_LIST_GETSIZE(tp_p->jobs) > tp_p->job_high_water_mark) { tp_p->job_high_water_mark = SCCP_LIST_GETSIZE(tp_p->jobs); } ast_cond_signal(&(tp_p->work)); } int sccp_threadpool_jobqueue_count(sccp_threadpool_t * tp_p) { sccp_log(DEBUGCAT_THPOOL) (VERBOSE_PREFIX_3 "(sccp_threadpool_jobqueue_count) tp_p: %p, jobCount: %d\n", tp_p, SCCP_LIST_GETSIZE(tp_p->jobs)); return SCCP_LIST_GETSIZE(tp_p->jobs); }
722,266
./chan-sccp-b/src/sccp_event.c
/*! * \file sccp_event.c * \brief SCCP Event Class * \author Marcello Ceschia <marcello [at] ceschia.de> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \since 2009-09-02 * * $Date$ * $Revision$ */ /*! * \remarks Purpose: SCCP Event * When to use: Only methods directly related to sccp events should be stored in this source file. * Relationships: SCCP Hint */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") #define GENERATE_ENUM_STRINGS #include "sccp_enum_macro.h" #include "sccp_event_enums.hh" #undef GENERATE_ENUM_STRINGS void sccp_event_destroy(sccp_event_t * event); /*! * \brief SCCP Event Listeners Structure */ struct sccp_event_aSyncEventProcessorThreadArg { const struct sccp_event_subscriptions *subscribers; sccp_event_t *event; }; struct sccp_event_subscriptions { int syncSize; sccp_event_subscriber_t *sync; int aSyncSize; sccp_event_subscriber_t *async; }; struct sccp_event_subscriptions subscriptions[NUMBER_OF_EVENT_TYPES]; boolean_t sccp_event_running = FALSE; void sccp_event_destroy(sccp_event_t * event) { // pbx_log(LOG_NOTICE, "destroy event - %p type: %d: releasing held object references\n", event, event->type); switch (event->type) { case SCCP_EVENT_DEVICE_REGISTERED: case SCCP_EVENT_DEVICE_UNREGISTERED: case SCCP_EVENT_DEVICE_PREREGISTERED: event->event.deviceRegistered.device = sccp_device_release(event->event.deviceRegistered.device); break; case SCCP_EVENT_LINE_CREATED: event->event.lineCreated.line = sccp_line_release(event->event.lineCreated.line); break; case SCCP_EVENT_DEVICE_ATTACHED: case SCCP_EVENT_DEVICE_DETACHED: //event->event.deviceAttached.linedevice = (event->event.deviceAttached.linedevice); event->event.deviceAttached.linedevice = sccp_linedevice_release(event->event.deviceAttached.linedevice); break; case SCCP_EVENT_FEATURE_CHANGED: event->event.featureChanged.device = sccp_device_release(event->event.featureChanged.device); event->event.featureChanged.linedevice = event->event.featureChanged.linedevice ? sccp_linedevice_release(event->event.featureChanged.linedevice) : NULL; break; case SCCP_EVENT_LINESTATUS_CHANGED: event->event.lineStatusChanged.line = sccp_line_release(event->event.lineStatusChanged.line); event->event.lineStatusChanged.device = event->event.lineStatusChanged.device ? sccp_device_release(event->event.lineStatusChanged.device) : NULL; break; case SCCP_EVENT_LINE_CHANGED: case SCCP_EVENT_LINE_DELETED: break; } // pbx_log(LOG_NOTICE, "Event destroyed- %p type: %d\n", event, event->type); } static void *sccp_event_processor(void *data) { struct sccp_event_aSyncEventProcessorThreadArg *args; const struct sccp_event_subscriptions *subscribers; sccp_event_t *event; int n; args = data; subscribers = args->subscribers; event = args->event; sccp_log(DEBUGCAT_EVENT) (VERBOSE_PREFIX_3 "Processing Asynchronous Event %p of Type %s\n", event, event_type2str(event->type)); if ((event = sccp_event_retain(event))) { for (n = 0; n < subscribers->aSyncSize && sccp_event_running; n++) { if (subscribers->async[n].callback_function != NULL) { sccp_log(DEBUGCAT_EVENT) (VERBOSE_PREFIX_3 "Processing Event %p of Type %s: %p (%d)\n", event, event_type2str(event->type), subscribers->async[n].callback_function, n); subscribers->async[n].callback_function((const sccp_event_t *) event); } } sccp_event_release(event); } else { sccp_log(DEBUGCAT_EVENT) (VERBOSE_PREFIX_3 "Could not retain event\n"); } sccp_event_release(args->event); sccp_free(data); return NULL; } void sccp_event_module_start(void) { int i; if (!sccp_event_running) { for (i = 0; i < NUMBER_OF_EVENT_TYPES; i++) { subscriptions[i].async = (sccp_event_subscriber_t *) malloc(sizeof(sccp_event_subscriber_t)); subscriptions[i].sync = (sccp_event_subscriber_t *) malloc(sizeof(sccp_event_subscriber_t)); } sccp_event_running = TRUE; } } void sccp_event_module_stop(void) { int i; if (sccp_event_running) { sccp_event_running = FALSE; for (i = 0; i < NUMBER_OF_EVENT_TYPES; i++) { subscriptions[i].aSyncSize = 0; subscriptions[i].syncSize = 0; } usleep(20); // arbitairy time for other threads to finish their business for (i = 0; i < NUMBER_OF_EVENT_TYPES; i++) { free(subscriptions[i].async); free(subscriptions[i].sync); } } } /*! * \brief Subscribe to an Event * \param eventType SCCP Event Type * \param cb SCCP Event Call Back Function * \param allowASyncExecution Handle Event Asynchronously (Boolean) * * \warning * - sccp_event_listeners->subscriber is not always locked */ void sccp_event_subscribe(sccp_event_type_t eventType, sccp_event_callback_t cb, boolean_t allowASyncExecution) { int i, n, size; for (i = 0, n = 1 << i; i < NUMBER_OF_EVENT_TYPES && sccp_event_running; i++, n = 1 << i) { if (eventType & n) { if (allowASyncExecution) { size = subscriptions[i].aSyncSize; if (size) { subscriptions[i].async = (sccp_event_subscriber_t *) realloc(subscriptions[i].async, (size + 1) * sizeof(sccp_event_subscriber_t)); } subscriptions[i].async[size].callback_function = cb; subscriptions[i].async[size].eventType = eventType; subscriptions[i].aSyncSize++; } else { size = subscriptions[i].syncSize; if (size) { subscriptions[i].sync = (sccp_event_subscriber_t *) realloc(subscriptions[i].async, (size + 1) * sizeof(sccp_event_subscriber_t)); } subscriptions[i].sync[size].callback_function = cb; subscriptions[i].sync[size].eventType = eventType; subscriptions[i].syncSize++; } } } } /*! * \brief unSubscribe from an Event * \param eventType SCCP Event Type * \param cb SCCP Event Call Back Function */ void sccp_event_unsubscribe(sccp_event_type_t eventType, sccp_event_callback_t cb) { int i, n, x; for (i = 0, n = 1 << i; i < NUMBER_OF_EVENT_TYPES; i++, n = 1 << i) { if (eventType & n) { for (x = 0; x < subscriptions[i].aSyncSize; x++) { if (subscriptions[i].async[x].callback_function == cb) { subscriptions[i].async[x].callback_function = (void *) NULL; subscriptions[i].async[x].eventType = 0; } } for (x = 0; x < subscriptions[i].syncSize; x++) { if (subscriptions[i].sync[x].callback_function == cb) { subscriptions[i].sync[x].callback_function = (void *) NULL; subscriptions[i].sync[x].eventType = 0; } } } } } /*! * \brief Fire an Event * \param event SCCP Event * \note event will be freed after event is fired * * \warning * - sccp_event_listeners->subscriber is not always locked */ void sccp_event_fire(const sccp_event_t * event) { if (event == NULL || SCCP_REF_RUNNING != sccp_refcount_isRunning() || !sccp_event_running) return; sccp_event_t *e = (sccp_event_t *) sccp_refcount_object_alloc(sizeof(sccp_event_t), SCCP_REF_EVENT, event_type2str(event->type), sccp_event_destroy); if (!e) { pbx_log(LOG_ERROR, "%p: Memory Allocation Error while creating sccp_event e. Exiting\n", event); return; } // memcpy(e, event, sizeof(sccp_event_t)); e->type = event->type; sccp_log(DEBUGCAT_EVENT) (VERBOSE_PREFIX_3 "Handling Event %p of Type %s\n", event, event_type2str(e->type)); /* update refcount */ switch (e->type) { case SCCP_EVENT_DEVICE_REGISTERED: case SCCP_EVENT_DEVICE_UNREGISTERED: case SCCP_EVENT_DEVICE_PREREGISTERED: e->event.deviceRegistered.device = event->event.deviceRegistered.device; break; case SCCP_EVENT_LINE_CREATED: e->event.lineCreated.line = event->event.lineCreated.line; break; case SCCP_EVENT_DEVICE_ATTACHED: case SCCP_EVENT_DEVICE_DETACHED: e->event.deviceAttached.linedevice = event->event.deviceAttached.linedevice; break; case SCCP_EVENT_FEATURE_CHANGED: e->event.featureChanged.device = event->event.featureChanged.device; e->event.featureChanged.linedevice = event->event.featureChanged.linedevice; e->event.featureChanged.featureType = event->event.featureChanged.featureType; break; case SCCP_EVENT_LINESTATUS_CHANGED: e->event.lineStatusChanged.line = event->event.lineStatusChanged.line; e->event.lineStatusChanged.device = event->event.lineStatusChanged.device; e->event.lineStatusChanged.state = event->event.lineStatusChanged.state; break; case SCCP_EVENT_LINE_CHANGED: case SCCP_EVENT_LINE_DELETED: break; } /* search for position in array */ int i, n; sccp_event_type_t eventType = event->type; for (i = 0, n = 1 << i; i < NUMBER_OF_EVENT_TYPES; i++, n = 1 << i) { if (eventType & n) { break; } } // pthread_attr_t tattr; // pthread_t tid; /* start async thread if nessesary */ if (GLOB(module_running)) { if (subscriptions[i].aSyncSize > 0 && sccp_event_running) { /* create thread for async subscribers */ struct sccp_event_aSyncEventProcessorThreadArg *arg = malloc(sizeof(struct sccp_event_aSyncEventProcessorThreadArg)); if (!arg) { pbx_log(LOG_ERROR, "%p: Memory Allocation Error while creating sccp_event_aSyncEventProcessorThreadArg. Skipping\n", event); } else { arg->subscribers = &subscriptions[i]; arg->event = sccp_event_retain(e); /* initialized with default attributes */ if (arg->event != NULL) { sccp_log(DEBUGCAT_EVENT) (VERBOSE_PREFIX_3 "Adding work to threadpool for event: %p, type: %s\n", event, event_type2str(event->type)); if (!sccp_threadpool_add_work(GLOB(general_threadpool), (void *) sccp_event_processor, (void *) arg)) { pbx_log(LOG_ERROR, "Could not add work to threadpool for event: %p, type: %s for processing\n", event, event_type2str(event->type)); arg->event = sccp_event_release(arg->event); sccp_free(arg); } } else { pbx_log(LOG_ERROR, "Could not retain e: %p, type: %s for processing\n", e, event_type2str(event->type)); sccp_free(arg); } } } /* execute sync subscribers */ if ((e = sccp_event_retain(e))) { for (n = 0; n < subscriptions[i].syncSize && sccp_event_running; n++) { if (subscriptions[i].sync[n].callback_function != NULL) { subscriptions[i].sync[n].callback_function((const sccp_event_t *) e); } } sccp_event_release(e); } else { pbx_log(LOG_ERROR, "Could not retain e: %p, type: %s for processing\n", e, event_type2str(event->type)); } } else { // we are unloading. switching to synchonous mode for everything sccp_log(DEBUGCAT_EVENT) (VERBOSE_PREFIX_3 "Handling Event %p of Type %s in Forced Synchronous Mode\n", event, event_type2str(e->type)); if ((e = sccp_event_retain(e))) { for (n = 0; n < subscriptions[i].syncSize && sccp_event_running; n++) { if (subscriptions[i].sync[n].callback_function != NULL) { subscriptions[i].sync[n].callback_function((const sccp_event_t *) e); } } for (n = 0; n < subscriptions[i].aSyncSize && sccp_event_running; n++) { if (subscriptions[i].async[n].callback_function != NULL) { subscriptions[i].async[n].callback_function((const sccp_event_t *) e); } } sccp_event_release(e); } else { pbx_log(LOG_ERROR, "Could not retain e: %p, type: %s for processing\n", e, event_type2str(event->type)); } } sccp_event_release(e); }
722,267
./chan-sccp-b/src/sccp_mwi.c
/*! * \file sccp_mwi.c * \brief SCCP Message Waiting Indicator Class * \author Marcello Ceschia <marcello.ceschia [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") #ifndef CS_AST_HAS_EVENT #define SCCP_MWI_CHECK_INTERVAL 30 #endif void sccp_mwi_checkLine(sccp_line_t * line); void sccp_mwi_setMWILineStatus(sccp_device_t * d, sccp_line_t * l); void sccp_mwi_linecreatedEvent(const sccp_event_t * event); void sccp_mwi_deviceAttachedEvent(const sccp_event_t * event); void sccp_mwi_addMailboxSubscription(char *mailbox, char *context, sccp_line_t * line); void sccp_mwi_lineStatusChangedEvent(const sccp_event_t * event); SCCP_LIST_HEAD (, sccp_mailbox_subscriber_list_t) sccp_mailbox_subscriptions; /*! * start mwi module. */ void sccp_mwi_module_start(void) { /* */ SCCP_LIST_HEAD_INIT(&sccp_mailbox_subscriptions); sccp_event_subscribe(SCCP_EVENT_LINE_CREATED, sccp_mwi_linecreatedEvent, TRUE); sccp_event_subscribe(SCCP_EVENT_DEVICE_ATTACHED, sccp_mwi_deviceAttachedEvent, TRUE); sccp_event_subscribe(SCCP_EVENT_LINESTATUS_CHANGED, sccp_mwi_lineStatusChangedEvent, FALSE); } /*! * \brief Stop MWI Monitor * * \lock * - sccp_mailbox_subscriptions */ void sccp_mwi_module_stop() { sccp_mailbox_subscriber_list_t *subscription = NULL; sccp_mailboxLine_t *sccp_mailboxLine = NULL; SCCP_LIST_LOCK(&sccp_mailbox_subscriptions); while ((subscription = SCCP_LIST_REMOVE_HEAD(&sccp_mailbox_subscriptions, list))) { /* removing lines */ SCCP_LIST_LOCK(&subscription->sccp_mailboxLine); while ((sccp_mailboxLine = SCCP_LIST_REMOVE_HEAD(&subscription->sccp_mailboxLine, list))) { sccp_free(sccp_mailboxLine); } SCCP_LIST_UNLOCK(&subscription->sccp_mailboxLine); SCCP_LIST_HEAD_DESTROY(&subscription->sccp_mailboxLine); #ifdef CS_AST_HAS_EVENT /* unsubscribe asterisk event */ if (subscription->event_sub) { pbx_event_unsubscribe(subscription->event_sub); } #else subscription->schedUpdate = SCCP_SCHED_DEL(subscription->schedUpdate); #endif sccp_free(subscription); } SCCP_LIST_UNLOCK(&sccp_mailbox_subscriptions); SCCP_LIST_HEAD_DESTROY(&sccp_mailbox_subscriptions); sccp_event_unsubscribe(SCCP_EVENT_LINE_CREATED, sccp_mwi_linecreatedEvent); sccp_event_unsubscribe(SCCP_EVENT_DEVICE_ATTACHED, sccp_mwi_deviceAttachedEvent); sccp_event_unsubscribe(SCCP_EVENT_LINESTATUS_CHANGED, sccp_mwi_lineStatusChangedEvent); } /*! * \brief Generic update mwi count * \param subscription Pointer to a mailbox subscription * * \lock * - subscription->sccp_mailboxLine * - line * - line->devices is not always locked * - see sccp_mwi_setMWILineStatus() */ static void sccp_mwi_updatecount(sccp_mailbox_subscriber_list_t * subscription) { sccp_mailboxLine_t *mailboxLine = NULL; sccp_line_t *line = NULL; SCCP_LIST_LOCK(&subscription->sccp_mailboxLine); SCCP_LIST_TRAVERSE(&subscription->sccp_mailboxLine, mailboxLine, list) { if ((line = sccp_line_retain(mailboxLine->line))) { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_4 "line: %s\n", line->name); sccp_linedevices_t *lineDevice = NULL; /* update statistics for line */ line->voicemailStatistic.oldmsgs -= subscription->previousVoicemailStatistic.oldmsgs; line->voicemailStatistic.newmsgs -= subscription->previousVoicemailStatistic.newmsgs; line->voicemailStatistic.oldmsgs += subscription->currentVoicemailStatistic.oldmsgs; line->voicemailStatistic.newmsgs += subscription->currentVoicemailStatistic.newmsgs; /* done */ /* notify each device on line */ SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, lineDevice, list) { if (lineDevice && lineDevice->device) { sccp_mwi_setMWILineStatus(lineDevice->device, line); } else { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_4 "error: null line device.\n"); } } SCCP_LIST_UNLOCK(&line->devices); sccp_line_release(line); } } SCCP_LIST_UNLOCK(&subscription->sccp_mailboxLine); } #ifdef CS_AST_HAS_EVENT /*! * \brief Receive MWI Event from Asterisk * \param event Asterisk Event * \param data Asterisk Data * */ void sccp_mwi_event(const struct ast_event *event, void *data) { sccp_mailbox_subscriber_list_t *subscription = data; pbx_log(LOG_NOTICE, "Got mwi-event\n"); if (!subscription || !event) return; sccp_log((DEBUGCAT_MWI)) (VERBOSE_PREFIX_3 "Received PBX mwi event for %s@%s\n", (subscription->mailbox) ? subscription->mailbox : "NULL", (subscription->context) ? subscription->context : "NULL"); /* for calculation store previous voicemail counts */ subscription->previousVoicemailStatistic.newmsgs = subscription->currentVoicemailStatistic.newmsgs; subscription->previousVoicemailStatistic.oldmsgs = subscription->currentVoicemailStatistic.oldmsgs; subscription->currentVoicemailStatistic.newmsgs = pbx_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS); subscription->currentVoicemailStatistic.oldmsgs = pbx_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS); if (subscription->previousVoicemailStatistic.newmsgs != subscription->currentVoicemailStatistic.newmsgs) { sccp_mwi_updatecount(subscription); } } #else /*! * \brief MWI Progress * \param ptr Pointer to Mailbox Subscriber list Entry * \note only used for asterisk version without mwi event (scheduled check) * * \warning * - line->devices is not always locked * * \called_from_asterisk * * \lock * - subscription->sccp_mailboxLine * - line * - see sccp_mwi_setMWILineStatus() */ int sccp_mwi_checksubscription(const void *ptr) { sccp_mailbox_subscriber_list_t *subscription = (sccp_mailbox_subscriber_list_t *) ptr; if (!subscription) return -1; subscription->previousVoicemailStatistic.newmsgs = subscription->currentVoicemailStatistic.newmsgs; subscription->previousVoicemailStatistic.oldmsgs = subscription->currentVoicemailStatistic.oldmsgs; char buffer[512]; sprintf(buffer, "%s@%s", subscription->mailbox, subscription->context); sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_4 "SCCP: ckecking mailbox: %s\n", buffer); pbx_app_inboxcount(buffer, &subscription->currentVoicemailStatistic.newmsgs, &subscription->currentVoicemailStatistic.oldmsgs); /* update devices if something changed */ if (subscription->previousVoicemailStatistic.newmsgs != subscription->currentVoicemailStatistic.newmsgs) { sccp_mwi_updatecount(subscription); } /* reschedule my self */ if ((subscription->schedUpdate = sccp_sched_add(SCCP_MWI_CHECK_INTERVAL * 1000, sccp_mwi_checksubscription, subscription)) < 0) { pbx_log(LOG_ERROR, "Error creating mailbox subscription.\n"); } return 0; } #endif /*! * \brief Remove Mailbox Subscription * \param mailbox SCCP Mailbox * \todo Implement sccp_mwi_unsubscribeMailbox ( \todo Marcello) */ void sccp_mwi_unsubscribeMailbox(sccp_mailbox_t ** mailbox) { // \todo implement sccp_mwi_unsubscribeMailbox return; } /*! * \brief Device Attached Event * \param event SCCP Event * * \lock * - device */ void sccp_mwi_deviceAttachedEvent(const sccp_event_t * event) { if (!event) return; sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_1 "SCCP: (mwi_deviceAttachedEvent) Get deviceAttachedEvent\n"); sccp_line_t *line = event->event.deviceAttached.linedevice->line; sccp_device_t *device = event->event.deviceAttached.linedevice->device; if (!line || !(device = sccp_device_retain(device))) { pbx_log(LOG_ERROR, "get deviceAttachedEvent where one parameter is missing. device: %s, line: %s\n", DEV_ID_LOG(device), (line) ? line->name : "null"); return; } device->voicemailStatistic.oldmsgs += line->voicemailStatistic.oldmsgs; device->voicemailStatistic.newmsgs += line->voicemailStatistic.newmsgs; sccp_mwi_setMWILineStatus(device, line); /* set mwi-line-status */ device = sccp_device_release(device); } /*! * \brief Line Status Changed Event * \param event SCCP Event * * \lock * - see sccp_mwi_check() */ void sccp_mwi_lineStatusChangedEvent(const sccp_event_t * event) { if (!event) return; sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_1 "SCCP: (mwi_lineStatusChangedEvent) Get lineStatusChangedEvent\n"); sccp_device_t *device = event->event.lineStatusChanged.device; if (!device) return; sccp_mwi_check(device); } /*! * \brief Line Created Event * \param event SCCP Event * * \warning * - line->mailboxes is not always locked */ void sccp_mwi_linecreatedEvent(const sccp_event_t * event) { if (!event) return; sccp_mailbox_t *mailbox; sccp_line_t *line = event->event.lineCreated.line; sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_1 "SCCP: (mwi_linecreatedEvent) Get linecreatedEvent\n"); if (!line) { pbx_log(LOG_ERROR, "Get linecreatedEvent, but line not set\n"); return; } if (line && (&line->mailboxes) != NULL) { SCCP_LIST_TRAVERSE(&line->mailboxes, mailbox, list) { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_1 "line: '%s' mailbox: %s@%s\n", line->name, mailbox->mailbox, mailbox->context); sccp_mwi_addMailboxSubscription(mailbox->mailbox, mailbox->context, line); } } return; } /*! * \brief Add Mailbox Subscription * \param mailbox Mailbox as char * \param context Mailbox Context * \param line SCCP Line * * \warning * - subscription->sccp_mailboxLine is not always locked * * \lock * - sccp_mailbox_subscriptions * - subscription->sccp_mailboxLine */ void sccp_mwi_addMailboxSubscription(char *mailbox, char *context, sccp_line_t * line) { sccp_mailbox_subscriber_list_t *subscription = NULL; sccp_mailboxLine_t *mailboxLine = NULL; SCCP_LIST_LOCK(&sccp_mailbox_subscriptions); SCCP_LIST_TRAVERSE(&sccp_mailbox_subscriptions, subscription, list) { if (strlen(mailbox) == strlen(subscription->mailbox) && strlen(context) == strlen(subscription->context) && !strcmp(mailbox, subscription->mailbox) && !strcmp(context, subscription->context)) { break; } } SCCP_LIST_UNLOCK(&sccp_mailbox_subscriptions); if (!subscription) { subscription = sccp_malloc(sizeof(sccp_mailbox_subscriber_list_t)); if (!subscription) { pbx_log(LOG_ERROR, "SCCP: (mwi_addMailboxSubscription) Error allocating memory for sccp_mwi_addMailboxSubscription"); return; } memset(subscription, 0, sizeof(sccp_mailbox_subscriber_list_t)); SCCP_LIST_HEAD_INIT(&subscription->sccp_mailboxLine); sccp_copy_string(subscription->mailbox, mailbox, sizeof(subscription->mailbox)); sccp_copy_string(subscription->context, context, sizeof(subscription->context)); sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "SCCP: (mwi_addMailboxSubscription) create subscription for: %s@%s\n", subscription->mailbox, subscription->context); SCCP_LIST_LOCK(&sccp_mailbox_subscriptions); SCCP_LIST_INSERT_HEAD(&sccp_mailbox_subscriptions, subscription, list); SCCP_LIST_UNLOCK(&sccp_mailbox_subscriptions); /* get initial value */ #ifdef CS_AST_HAS_EVENT struct ast_event *event = ast_event_get_cached(AST_EVENT_MWI, AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, subscription->mailbox, AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, subscription->context, AST_EVENT_IE_END); if (event) { subscription->currentVoicemailStatistic.newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS); subscription->currentVoicemailStatistic.oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS); ast_event_destroy(event); } else #endif { /* Fall back on checking the mailbox directly */ char buffer[512]; sprintf(buffer, "%s@%s", subscription->mailbox, subscription->context); pbx_app_inboxcount(buffer, &subscription->currentVoicemailStatistic.newmsgs, &subscription->currentVoicemailStatistic.oldmsgs); } #ifdef CS_AST_HAS_EVENT /* register asterisk event */ //struct pbx_event_sub *pbx_event_subscribe(enum ast_event_type event_type, ast_event_cb_t cb, char *description, void *userdata, ...); #if ASTERISK_VERSION_NUMBER >= 10800 subscription->event_sub = pbx_event_subscribe(AST_EVENT_MWI, sccp_mwi_event, "mailbox subscription", subscription, AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, subscription->mailbox, AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, subscription->context, AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS, AST_EVENT_IE_END); #else subscription->event_sub = pbx_event_subscribe(AST_EVENT_MWI, sccp_mwi_event, subscription, AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, subscription->mailbox, AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, subscription->context, AST_EVENT_IE_END); #endif if (!subscription->event_sub) { pbx_log(LOG_ERROR, "SCCP: PBX MWI event could not be subscribed to for mailbox %s@%s\n", subscription->mailbox, subscription->context); } #else if ((subscription->schedUpdate = sccp_sched_add(SCCP_MWI_CHECK_INTERVAL * 1000, sccp_mwi_checksubscription, subscription)) < 0) { pbx_log(LOG_ERROR, "SCCP: (mwi_addMailboxSubscription) Error creating mailbox subscription.\n"); } #endif } /* we already have this subscription */ SCCP_LIST_TRAVERSE(&subscription->sccp_mailboxLine, mailboxLine, list) { if (line == mailboxLine->line) break; } if (!mailboxLine) { mailboxLine = sccp_malloc(sizeof(sccp_mailboxLine_t)); if (!mailboxLine) { pbx_log(LOG_ERROR, "SCCP: (mwi_addMailboxSubscription) Error allocating memory for mailboxLine"); return; } memset(mailboxLine, 0, sizeof(sccp_mailboxLine_t)); mailboxLine->line = line; line->voicemailStatistic.newmsgs = subscription->currentVoicemailStatistic.newmsgs; line->voicemailStatistic.oldmsgs = subscription->currentVoicemailStatistic.oldmsgs; SCCP_LIST_LOCK(&subscription->sccp_mailboxLine); SCCP_LIST_INSERT_HEAD(&subscription->sccp_mailboxLine, mailboxLine, list); SCCP_LIST_UNLOCK(&subscription->sccp_mailboxLine); } } /*! * \brief Check Line for MWI Status * \param line SCCP Line * * \lock * - line->mailboxes */ void sccp_mwi_checkLine(sccp_line_t * line) { sccp_mailbox_t *mailbox = NULL; char buffer[512]; SCCP_LIST_LOCK(&line->mailboxes); SCCP_LIST_TRAVERSE(&line->mailboxes, mailbox, list) { sprintf(buffer, "%s@%s", mailbox->mailbox, mailbox->context); sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "SCCP: (mwi_checkLine) Line: %s, Mailbox: %s\n", line->name, buffer); if (!sccp_strlen_zero(buffer)) { #ifdef CS_AST_HAS_NEW_VOICEMAIL pbx_app_inboxcount(buffer, &line->voicemailStatistic.newmsgs, &line->voicemailStatistic.oldmsgs); #else if (pbx_app_has_voicemail(buffer)) { line->voicemailStatistic.newmsgs = 1; } #endif sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "SCCP: (mwi_checkLine) Line: %s, Mailbox: %s inbox: %d/%d\n", line->name, buffer, line->voicemailStatistic.newmsgs, line->voicemailStatistic.oldmsgs); } } SCCP_LIST_UNLOCK(&line->mailboxes); } /*! * \brief Set MWI Line Status * \param d SCCP Device * \param l SCCP Line * * \lock * - device * - see sccp_device_find_index_for_line() * - see sccp_dev_send() * - see sccp_mwi_check() */ void sccp_mwi_setMWILineStatus(sccp_device_t * d, sccp_line_t * l) { sccp_moo_t *r; int instance = 0; uint8_t status = 0; uint32_t mask; uint32_t newState = 0; if (!(d = sccp_device_retain(d))) return; /* when l is defined we are switching on/off the button icon */ if (l) { instance = sccp_device_find_index_for_line(d, l->name); status = l->voicemailStatistic.newmsgs ? 1 : 0; } mask = 1 << instance; newState = d->mwilight; /* update status */ if (status) { /* activate */ newState |= mask; } else { /* deactivate */ newState &= ~mask; } /* check if we need to update line status */ if ((d->mwilight & ~(1 << 0)) != (newState & ~(1 << 0))) { d->mwilight = newState; REQ(r, SetLampMessage); r->msg.SetLampMessage.lel_stimulus = htolel(SKINNY_STIMULUS_VOICEMAIL); r->msg.SetLampMessage.lel_stimulusInstance = htolel(instance); r->msg.SetLampMessage.lel_lampMode = (d->mwilight & ~(1 << 0)) ? htolel(d->mwilamp) : htolel(SKINNY_LAMP_OFF); sccp_dev_send(d, r); sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: (mwi_setMWILineStatus) Turn %s the MWI on line (%s)%d\n", DEV_ID_LOG(d), (mask > 0) ? "ON" : "OFF", (l ? l->name : "unknown"), instance); } else { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: (mwi_setMWILineStatus) Device already knows status %s on line %s (%d)\n", DEV_ID_LOG(d), (newState & ~(1 << 0)) ? "ON" : "OFF", (l ? l->name : "unknown"), instance); } sccp_mwi_check(d); sccp_device_release(d); } /*! * \brief Check MWI Status for Device * \param device SCCP Device * \note called by lineStatusChange * * \lock * - device->buttonconfig * - see sccp_line_find_byname() * - line->channels * - device * - device->buttonconfig * - see sccp_line_find_byname() * - see sccp_dev_send() * - see sccp_dev_check_displayprompt() */ void sccp_mwi_check(sccp_device_t * device) { sccp_buttonconfig_t *config = NULL; sccp_line_t *line = NULL; sccp_channel_t *c = NULL; sccp_moo_t *r = NULL; uint8_t status; uint32_t mask; uint32_t oldmsgs = 0, newmsgs = 0; /* check if we have an active channel */ boolean_t hasActiveChannel = FALSE, hasRinginChannel = FALSE; if (!(device = sccp_device_retain(device))) { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "SCCP: (mwi_check) called with NULL device!\n"); return; } /* for each line, check if there is an active call */ sccp_device_t *tmpDevice = NULL; SCCP_LIST_LOCK(&device->buttonconfig); SCCP_LIST_TRAVERSE(&device->buttonconfig, config, list) { if (config->type == LINE) { line = sccp_line_find_byname(config->button.line.name, FALSE); if (!line) { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: NULL line retrieved from buttonconfig!\n", DEV_ID_LOG(device)); continue; } SCCP_LIST_LOCK(&line->channels); SCCP_LIST_TRAVERSE(&line->channels, c, list) { tmpDevice = sccp_channel_getDevice_retained(c); if (tmpDevice == device) { // We have a channel belonging to our device (no remote shared line channel) if (c->state != SCCP_CHANNELSTATE_ONHOOK && c->state != SCCP_CHANNELSTATE_DOWN) { hasActiveChannel = TRUE; } if (c->state == SCCP_CHANNELSTATE_RINGING) { hasRinginChannel = TRUE; } } tmpDevice = tmpDevice ? sccp_device_release(tmpDevice) : NULL; } /* pre-collect number of voicemails on device to be set later */ oldmsgs += line->voicemailStatistic.oldmsgs; newmsgs += line->voicemailStatistic.newmsgs; sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: (mwi_check) line %s voicemail count %d new/%d old\n", DEV_ID_LOG(device), line->name, line->voicemailStatistic.newmsgs, line->voicemailStatistic.oldmsgs); SCCP_LIST_UNLOCK(&line->channels); line = sccp_line_release(line); } } SCCP_LIST_UNLOCK(&device->buttonconfig); /* disable mwi light if we have an active channel, but no ringin */ if (hasActiveChannel && !hasRinginChannel && !device->mwioncall) { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: we have an active channel, disable mwi light\n", DEV_ID_LOG(device)); if (device->mwilight & (1 << 0)) { // Set the MWI light to off only if it is already on. device->mwilight &= ~(1 << 0); /* set mwi light for device to off */ REQ(r, SetLampMessage); r->msg.SetLampMessage.lel_stimulus = htolel(SKINNY_STIMULUS_VOICEMAIL); r->msg.SetLampMessage.lel_stimulusInstance = 0; r->msg.SetLampMessage.lel_lampMode = htolel(SKINNY_LAMP_OFF); sccp_dev_send(device, r); sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: Turn %s the MWI on line (%s) %d\n", DEV_ID_LOG(device), "OFF", "unknown", 0); } else { sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: MWI already %s on line (%s) %d\n", DEV_ID_LOG(device), "OFF", "unknown", 0); } device = sccp_device_release(device); return; // <---- This return must be outside the inner if } /* Note: We must return the function before this point unless we want to turn the MWI on during a call! */ /* This is taken care of by the previous block of code. */ device->voicemailStatistic.newmsgs = oldmsgs; device->voicemailStatistic.oldmsgs = newmsgs; /* set mwi light */ mask = device->mwilight & ~(1 << 0); /* status without mwi light for device (1<<0) */ status = (mask > 0) ? 1 : 0; if ((device->mwilight & (1 << 0)) != status) { /* status needs update */ if (status) { device->mwilight |= (1 << 0); /* activate */ } else { device->mwilight &= ~(1 << 0); /* deactivate */ } REQ(r, SetLampMessage); r->msg.SetLampMessage.lel_stimulus = htolel(SKINNY_STIMULUS_VOICEMAIL); //r->msg.SetLampMessage.lel_stimulusInstance = 0; r->msg.SetLampMessage.lel_lampMode = htolel((device->mwilight) ? device->mwilamp : SKINNY_LAMP_OFF); sccp_dev_send(device, r); sccp_log(DEBUGCAT_MWI) (VERBOSE_PREFIX_3 "%s: Turn %s the MWI light (newmsgs: %d->%d)\n", DEV_ID_LOG(device), (device->mwilight & (1 << 0)) ? "ON" : "OFF", newmsgs, device->voicemailStatistic.newmsgs); } /* we should check the display only once, maybe we need a priority stack -MC */ if (newmsgs > 0) { char buffer[StationMaxDisplayTextSize]; sprintf(buffer, "%s: (%d/%d)", SKINNY_DISP_YOU_HAVE_VOICEMAIL, newmsgs, oldmsgs); sccp_device_addMessageToStack(device, SCCP_MESSAGE_PRIORITY_VOICEMAIL, buffer); } else { sccp_device_clearMessageFromStack(device, SCCP_MESSAGE_PRIORITY_VOICEMAIL); } device = sccp_device_release(device); } /*! * \brief Show MWI Subscriptions * \param fd Fd as int * \param total Total number of lines as int * \param s AMI Session * \param m Message * \param argc Argc as int * \param argv[] Argv[] as char * \return Result as int * * \called_from_asterisk */ #include <asterisk/cli.h> int sccp_show_mwi_subscriptions(int fd, int *total, struct mansession *s, const struct message *m, int argc, char *argv[]) { sccp_line_t *line = NULL; sccp_mailboxLine_t *mailboxLine = NULL; char linebuf[31] = ""; int local_total = 0; #define CLI_AMI_TABLE_NAME MWI_Subscriptions #define CLI_AMI_TABLE_PER_ENTRY_NAME Mailbox_Subscriber #define CLI_AMI_TABLE_LIST_ITER_HEAD &sccp_mailbox_subscriptions #define CLI_AMI_TABLE_LIST_ITER_TYPE sccp_mailbox_subscriber_list_t #define CLI_AMI_TABLE_LIST_ITER_VAR subscription #define CLI_AMI_TABLE_LIST_LOCK SCCP_LIST_LOCK #define CLI_AMI_TABLE_LIST_ITERATOR SCCP_LIST_TRAVERSE #define CLI_AMI_TABLE_LIST_UNLOCK SCCP_LIST_UNLOCK #define CLI_AMI_TABLE_BEFORE_ITERATION \ SCCP_LIST_TRAVERSE(&subscription->sccp_mailboxLine, mailboxLine, list) { \ line = mailboxLine->line; \ snprintf(linebuf,sizeof(linebuf),"%30s",line->name); \ } #ifdef CS_AST_HAS_EVENT #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Mailbox, s, 10, subscription->mailbox) \ CLI_AMI_TABLE_FIELD(LineName, s, 30, linebuf) \ CLI_AMI_TABLE_FIELD(Context, s, 15, subscription->context) \ CLI_AMI_TABLE_FIELD(New, d, 3, subscription->currentVoicemailStatistic.newmsgs)\ CLI_AMI_TABLE_FIELD(Old, d, 3, subscription->currentVoicemailStatistic.oldmsgs)\ CLI_AMI_TABLE_FIELD(Sub, s, 3, subscription->event_sub ? "YES" : "NO") #include "sccp_cli_table.h" #else #define CLI_AMI_TABLE_FIELDS \ CLI_AMI_TABLE_FIELD(Mailbox, s, 10, subscription->mailbox) \ CLI_AMI_TABLE_FIELD(LineName, s, 30, linebuf) \ CLI_AMI_TABLE_FIELD(Context, s, 15, subscription->context) \ CLI_AMI_TABLE_FIELD(New, d, 3, subscription->currentVoicemailStatistic.newmsgs)\ CLI_AMI_TABLE_FIELD(Old, d, 3, subscription->currentVoicemailStatistic.oldmsgs) #include "sccp_cli_table.h" #endif if (s) { *total = local_total; } return RESULT_SUCCESS; }
722,268
./chan-sccp-b/src/sccp_features.c
/*! * \file sccp_features.c * \brief SCCP Features Class * \author Federico Santulli <fsantulli [at] users.sourceforge.net > * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * \since 2009-01-16 * * $Date$ * $Revision$ */ /*! * \remarks Purpose: SCCP Features * When to use: Only methods directly related to handling phone features should be stored in this source file. * Phone Features are Capabilities of the phone, like: * - CallForwarding * - Dialing * - Changing to Do Not Disturb(DND) Status * Relationships: These Features are called by FeatureButtons. Features can in turn call on Actions. * */ #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /*! * \brief Handle Call Forwarding * \param l SCCP Line * \param device SCCP Device * \param type CallForward Type (NONE, ALL, BUSY, NOANSWER) as SCCP_CFWD_* * \return SCCP Channel * * \callgraph * \callergraph * * \lock * - channel * - see sccp_channel_set_active() * - see sccp_indicate_nolock() */ void sccp_feat_handle_callforward(sccp_line_t * l, sccp_device_t * device, sccp_callforward_t type) { sccp_channel_t *c = NULL; sccp_linedevices_t *linedevice = NULL; if (!l) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if line is not specified!\n"); return; } if (!device) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if device is not specified!\n"); return; } linedevice = sccp_linedevice_find(device, l); if (!linedevice) { pbx_log(LOG_ERROR, "%s: Device does not have line configured \n", DEV_ID_LOG(device)); return; } /* if call forward is active and you asked about the same call forward maybe you would disable */ if ((linedevice->cfwdAll.enabled && type == SCCP_CFWD_ALL) || (linedevice->cfwdBusy.enabled && type == SCCP_CFWD_BUSY)) { sccp_line_cfwd(l, device, SCCP_CFWD_NONE, NULL); goto EXIT; } else { if (type == SCCP_CFWD_NOANSWER) { sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "### CFwdNoAnswer NOT SUPPORTED\n"); sccp_dev_displayprompt(device, 0, 0, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); goto EXIT; } } /* look if we have a call */ if ((c = sccp_channel_get_active(device))) { if (c->ss_action == SCCP_SS_GETFORWARDEXTEN) { // we have a channel, checking if if (c->state == SCCP_CHANNELSTATE_RINGOUT || c->state == SCCP_CHANNELSTATE_CONNECTED || c->state == SCCP_CHANNELSTATE_PROCEED || c->state == SCCP_CHANNELSTATE_BUSY || c->state == SCCP_CHANNELSTATE_CONGESTION) { if (c->calltype == SKINNY_CALLTYPE_OUTBOUND) { pbx_log(LOG_ERROR, "%s: 1\n", DEV_ID_LOG(device)); // if we have an outbound call, we can set callforward to dialed number -FS if (c->dialedNumber && !sccp_strlen_zero(c->dialedNumber)) { // checking if we have a number ! pbx_log(LOG_ERROR, "%s: 2\n", DEV_ID_LOG(device)); sccp_line_cfwd(l, device, type, c->dialedNumber); // we are on call, so no tone has been played until now :) //sccp_dev_starttone(device, SKINNY_TONE_ZIPZIP, instance, 0, 0); sccp_channel_endcall(c); goto EXIT; } } else if (c->owner && ast_bridged_channel(c->owner)) { // check if we have an ast channel to get callerid from // if we have an incoming or forwarded call, let's get number from callerid :) -FS char *number = NULL; pbx_log(LOG_ERROR, "%s: 3\n", DEV_ID_LOG(device)); if (PBX(get_callerid_name)) PBX(get_callerid_number) (c, &number); if (number) { sccp_line_cfwd(l, device, type, number); pbx_log(LOG_ERROR, "%s: 4\n", DEV_ID_LOG(device)); // we are on call, so no tone has been played until now :) sccp_dev_starttone(device, SKINNY_TONE_ZIPZIP, linedevice->lineInstance, 0, 0); sccp_channel_endcall(c); sccp_free(number); goto EXIT; } // if we where here it's cause there is no number in callerid,, so put call on hold and ask for a call forward number :) -FS if (!sccp_channel_hold(c)) { // if can't hold it means there is no active call, so return as we're already waiting a number to dial sccp_dev_displayprompt(device, 0, 0, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); goto EXIT; } } } else if (c->state == SCCP_CHANNELSTATE_OFFHOOK && sccp_strlen_zero(c->dialedNumber)) { pbx_log(LOG_ERROR, "%s: 5\n", DEV_ID_LOG(device)); // we are dialing but without entering a number :D -FS sccp_dev_stoptone(device, linedevice->lineInstance, (c && c->callid) ? c->callid : 0); // changing SS_DIALING mode to SS_GETFORWARDEXTEN c->ss_action = SCCP_SS_GETFORWARDEXTEN; /* Simpleswitch will catch a number to be dialed */ c->ss_data = type; /* this should be found in thread */ // changing channelstate to GETDIGITS sccp_indicate(device, c, SCCP_CHANNELSTATE_GETDIGITS); goto EXIT; } else { // we cannot allocate a channel, or ask an extension to pickup. sccp_dev_displayprompt(device, 0, 0, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); goto EXIT; } } else { /* see case for channel */ } } if (!c) { // if we where here there is no call in progress, so we should allocate a channel. c = sccp_channel_allocate(l, device); if (!c) { pbx_log(LOG_ERROR, "%s: Can't allocate SCCP channel for line %s\n", DEV_ID_LOG(device), l->name); goto EXIT; } sccp_channel_set_active(device, c); if (!sccp_pbx_channel_allocate(c, NULL)) { pbx_log(LOG_WARNING, "%s: (handle_callforward) Unable to allocate a new channel for line %s\n", DEV_ID_LOG(device), l->name); sccp_indicate(device, c, SCCP_CHANNELSTATE_CONGESTION); // implicitly retained device by sccp_action goto EXIT; } } else { if (c->state == SCCP_CHANNELSTATE_OFFHOOK) { /** we just opened a channel for cfwd, switch ss_action = SCCP_SS_GETFORWARDEXTEN */ c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); // we are dialing but without entering a number :D -FS sccp_dev_stoptone(device, linedevice->lineInstance, c->callid); } else { // other call in progress, put on hold int ret = sccp_channel_hold(c); if (!ret) { pbx_log(LOG_ERROR, "%s: Active call '%d' could not be put on hold\n", DEV_ID_LOG(device), c->callid); goto EXIT; } } } c->ss_action = SCCP_SS_GETFORWARDEXTEN; /* Simpleswitch will catch a number to be dialed */ c->ss_data = type; /* this should be found in thread */ c->calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_indicate(device, c, SCCP_CHANNELSTATE_GETDIGITS); sccp_dev_displayprompt(device, linedevice->lineInstance, c->callid, "Enter number to cfwd", 0); PBX(set_callstate) (c, AST_STATE_OFFHOOK); if (device->earlyrtp == SCCP_CHANNELSTATE_OFFHOOK && !c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } EXIT: linedevice = linedevice ? sccp_linedevice_release(linedevice) : NULL; c = c ? sccp_channel_release(c) : NULL; } #ifdef CS_SCCP_PICKUP /*! * \brief Handle Direct Pickup of Line * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param d SCCP Device * \return SCCP Channel * * \lock * - channel * - see sccp_channel_set_active() * - see sccp_indicate_nolock() */ void sccp_feat_handle_directed_pickup(sccp_line_t * l, uint8_t lineInstance, sccp_device_t * d) { sccp_channel_t *c; if (!l || !d || strlen(d->id) < 3) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if line or device are not defined!\n"); return; } /* look if we have a call */ if ((c = sccp_channel_get_active(d))) { // we have a channel, checking if if (c->state == SCCP_CHANNELSTATE_OFFHOOK && (!c->dialedNumber || (c->dialedNumber && sccp_strlen_zero(c->dialedNumber)))) { // we are dialing but without entering a number :D -FS sccp_dev_stoptone(d, lineInstance, (c && c->callid) ? c->callid : 0); // changing SS_DIALING mode to SS_GETFORWARDEXTEN c->ss_action = SCCP_SS_GETPICKUPEXTEN; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* this should be found in thread */ // changing channelstate to GETDIGITS sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); c = sccp_channel_release(c); return; } else { /* there is an active call, let's put it on hold first */ if (!sccp_channel_hold(c)) { c = sccp_channel_release(c); return; } } c = sccp_channel_release(c); } c = sccp_channel_allocate(l, d); if (!c) { pbx_log(LOG_ERROR, "%s: (handle_directed_pickup) Can't allocate SCCP channel for line %s\n", d->id, l->name); return; } c->ss_action = SCCP_SS_GETPICKUPEXTEN; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* not needed here */ c->calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_channel_set_active(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(c, NULL)) { pbx_log(LOG_WARNING, "%s: (handle_directed_pickup) Unable to allocate a new channel for line %s\n", d->id, l->name); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); c = sccp_channel_release(c); return; } PBX(set_callstate) (c, AST_STATE_OFFHOOK); if (d->earlyrtp == SCCP_CHANNELSTATE_OFFHOOK && !c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } c = sccp_channel_release(c); } #endif #ifdef CS_SCCP_PICKUP /*! * \brief Handle Direct Pickup of Extension * \param c *locked* SCCP Channel * \param exten Extension as char * \return Success as int * * \lock * - asterisk channel * - device */ int sccp_feat_directed_pickup(sccp_channel_t * c, char *exten) { int res = -1; #if CS_AST_DO_PICKUP PBX_CHANNEL_TYPE *target = NULL; /* potential pickup target */ PBX_CHANNEL_TYPE *original = NULL; /* destination */ PBX_CHANNEL_TYPE *tmp = NULL; const char *ringermode = NULL; sccp_device_t *d; char *context; char *name = NULL; char *number = NULL; sccp_channel_t *tmpChannel; if (!PBX(findPickupChannelByExtenLocked)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) findPickupChannelByExtenLocked not implemented for this asterisk version\n"); return -1; } if (sccp_strlen_zero(exten)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) zero exten\n"); return -1; } if (!c || !c->owner) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) no channel\n"); return -1; } original = c->owner; if (!c->line || !(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) no device\n"); return -1; } /* copying extension into our buffer */ if ((context = strchr(exten, '@'))) { *context++ = '\0'; } else { if (!sccp_strlen_zero(d->directed_pickup_context)) { context = (char *) strdup(d->directed_pickup_context); } else { context = (char *) pbx_channel_context(original); } } target = PBX(findPickupChannelByExtenLocked) (original, exten, context); if (target) { tmp = (CS_AST_BRIDGED_CHANNEL(target) ? CS_AST_BRIDGED_CHANNEL(target) : target); /* fixup callinfo */ tmpChannel = CS_AST_CHANNEL_PVT(target); if (tmpChannel) { if (PBX(get_callerid_name)) PBX(get_callerid_name) (tmpChannel, &name); if (PBX(get_callerid_number)) PBX(get_callerid_number) (tmpChannel, &number); } pbx_log(LOG_NOTICE, "SCCP: (directed_pickup) %s callerid is ('%s'-'%s')\n", pbx_channel_name(tmp), name ? name : "", number ? number : ""); tmp = NULL; res = 0; if (d->directed_pickup_modeanswer) { if ((res = ast_answer(c->owner))) { // \todo: remove res in this line: Although the value stored to 'res' is used in the enclosing expression, the value is never actually read from 'res' sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) Unable to answer '%s'\n", PBX(getChannelName) (c)); res = -1; } else if ((res = PBX(queue_control) (c->owner, AST_CONTROL_ANSWER))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) Unable to queue answer on '%s'\n", PBX(getChannelName) (c)); res = -1; } } if (res == 0) { SCCP_SCHED_DEL(c->scheduler.digittimeout); c->calltype = SKINNY_CALLTYPE_INBOUND; c->state = SCCP_CHANNELSTATE_PROCEED; c->answered_elsewhere = TRUE; res = ast_do_pickup(c->owner, target); if (!res) { /* directed pickup succeeded */ sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: (directed_pickup) pickup succeeded on callid: %d\n", DEV_ID_LOG(d), c->callid); sccp_rtp_stop(c); /* stop previous audio */ pbx_channel_set_hangupcause(original, AST_CAUSE_ANSWERED_ELSEWHERE); pbx_hangup(original); /* hangup masqueraded zombie channel */ pbx_channel_set_hangupcause(c->owner, AST_CAUSE_NORMAL_CLEARING); /* reset picked up channel */ sccp_channel_setDevice(c, d); sccp_channel_set_active(d, c); sccp_channel_updateChannelCapability(c); if (d->directed_pickup_modeanswer) { sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTED); } else { uint8_t instance; instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_stoptone(d, instance, c->callid); sccp_dev_set_speaker(d, SKINNY_STATIONSPEAKER_OFF); sccp_channel_set_active(d, NULL); c->ringermode = SKINNY_RINGTYPE_OUTSIDE; // default ring ringermode = pbx_builtin_getvar_helper(c->owner, "ALERT_INFO"); if (ringermode && !sccp_strlen_zero(ringermode)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Found ALERT_INFO=%s\n", ringermode); if (strcasecmp(ringermode, "inside") == 0) c->ringermode = SKINNY_RINGTYPE_INSIDE; else if (strcasecmp(ringermode, "feature") == 0) c->ringermode = SKINNY_RINGTYPE_FEATURE; else if (strcasecmp(ringermode, "silent") == 0) c->ringermode = SKINNY_RINGTYPE_SILENT; else if (strcasecmp(ringermode, "urgent") == 0) c->ringermode = SKINNY_RINGTYPE_URGENT; } sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGING); } } } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) Giving Up\n"); } target = pbx_channel_unref(target); pbx_channel_unlock(target); } else { pbx_channel_unlock(target); } if (!res) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) Exten '%s@'%s' Picked up Succesfully\n", exten, context); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (directed_pickup) Failed to pickup up Exten '%s@'%s'\n", exten, context); } d = sccp_device_release(d); #endif return res; } /*! * \brief Handle Group Pickup Feature * \param l SCCP Line * \param d SCCP Device * \return Success as int * * \todo backport from trunk * * \lock * - asterisk channel * - channel * - see sccp_indicate_nolock() * - see sccp_device_find_index_for_line() * - see sccp_dev_stoptone() * - see sccp_dev_set_speaker() * - device * - see sccp_indicate_nolock() * * \todo Fix callerid setting before calling ast_pickup_call */ int sccp_feat_grouppickup(sccp_line_t * l, sccp_device_t * d) { int res = 0; PBX_CHANNEL_TYPE *dest = NULL; sccp_channel_t *c; if (!l || !d || !d->id || sccp_strlen_zero(d->id)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (grouppickup) no line or device\n"); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) starting grouppickup\n", DEV_ID_LOG(d)); if (!l->pickupgroup) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) pickupgroup not configured in sccp.conf\n", d->id); return -1; } if (!PBX(feature_pickup)) { pbx_log(LOG_ERROR, "%s: (grouppickup) GPickup feature not implemented\n", d->id); } /* create channel for pickup */ if ((c = sccp_channel_find_bystate_on_line(l, SCCP_CHANNELSTATE_OFFHOOK)) && !pbx_test_flag(pbx_channel_flags(c->owner), AST_FLAG_ZOMBIE)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) Already offhook, reusing callid %d\n", d->id, c->callid); dest = c->owner; } else { /* emulate a new call so we end up in the same state as when a new call has been started */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) Starting new channel\n", d->id); c = sccp_channel_newcall(l, d, NULL, SKINNY_CALLTYPE_OUTBOUND, NULL); dest = c->owner; } /* prepare for call pickup */ SCCP_SCHED_DEL(c->scheduler.digittimeout); c->calltype = SKINNY_CALLTYPE_INBOUND; c->state = SCCP_CHANNELSTATE_PROCEED; c->answered_elsewhere = TRUE; res = pbx_pickup_call(dest); /* Should be replaced with a PBX(feature_pickup) call, which could give information back why the pickup failed (elsewhere or no match) */ if (!res) { /* gpickup succeeded */ sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) pickup succeeded on callid: %d\n", DEV_ID_LOG(d), c->callid); sccp_rtp_stop(c); /* stop previous audio */ pbx_channel_set_hangupcause(dest, AST_CAUSE_ANSWERED_ELSEWHERE); pbx_hangup(dest); /* hangup masqueraded zombie channel */ pbx_channel_set_hangupcause(c->owner, AST_CAUSE_NORMAL_CLEARING); sccp_channel_setDevice(c, d); sccp_channel_set_active(d, c); sccp_channel_updateChannelCapability(c); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTED); /* connect calls - reinstate audio */ } else { /* call pickup failed, restore previous situation */ c->answered_elsewhere = FALSE; /* send gpickup failure */ sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) pickup failed (someone else picked it up already or not in the correct callgroup)\n", DEV_ID_LOG(d)); int instance = sccp_device_find_index_for_line(d, l->name); sccp_dev_set_message(d, "Pickup Failed", 5, FALSE, TRUE); /* use messageStack */ sccp_dev_starttone(d, SKINNY_TONE_BEEPBONK, instance, c->callid, 2); sleep(1); /* give a little time for tone to get delivered, before hanging up */ /* hangup */ pbx_channel_set_hangupcause(c->owner, AST_CAUSE_CALL_REJECTED); pbx_hangup(c->owner); } c = sccp_channel_release(c); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (grouppickup) finished (%d)\n", DEV_ID_LOG(d), res); return res; } #endif // CS_SCCP_PICKUP /*! * \brief Update Caller ID * \param c SCCP Channel * * \callgraph * \callergraph */ void sccp_feat_updatecid(sccp_channel_t * c) { char *name = NULL, *number = NULL; if (!c || !c->owner) return; if (!c->calltype == SKINNY_CALLTYPE_OUTBOUND) { if (!ast_bridged_channel(c->owner)) { return; } } if (PBX(get_callerid_name)) PBX(get_callerid_name) (c, &name); if (PBX(get_callerid_number)) PBX(get_callerid_number) (c, &number); sccp_channel_set_callingparty(c, name, number); if (name) sccp_free(name); if (number) sccp_free(number); } /*! * \brief Handle VoiceMail * \param d SCCP Device * \param lineInstance LineInstance as uint8_t * * \lock * - channel * - see sccp_dev_displayprompt() */ void sccp_feat_voicemail(sccp_device_t * d, uint8_t lineInstance) { sccp_channel_t *c; sccp_line_t *l; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Voicemail Button pressed on line (%d)\n", d->id, lineInstance); if ((c = sccp_channel_get_active(d))) { if (!c->line || sccp_strlen_zero(c->line->vmnum)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No voicemail number configured on line %d\n", d->id, lineInstance); c = sccp_channel_release(c); return; } if (c->state == SCCP_CHANNELSTATE_OFFHOOK || c->state == SCCP_CHANNELSTATE_DIALING) { sccp_copy_string(c->dialedNumber, c->line->vmnum, sizeof(c->dialedNumber)); c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_pbx_softswitch(c); c = sccp_channel_release(c); return; } sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); c = sccp_channel_release(c); return; } if (!lineInstance) { if (d->defaultLineInstance) lineInstance = d->defaultLineInstance; else lineInstance = 1; } l = sccp_line_find_byid(d, lineInstance); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line with instance %d found.\n", d->id, lineInstance); //TODO workaround to solve the voicemail button issue with old hint style and speeddials before first line -MC if (d->defaultLineInstance) { l = sccp_line_find_byid(d, d->defaultLineInstance); } } if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No line with defaultLineInstance %d found. Not Dialing Voicemail Extension.\n", d->id, d->defaultLineInstance); return; } if (!sccp_strlen_zero(l->vmnum)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Dialing voicemail %s\n", d->id, l->vmnum); c = sccp_channel_newcall(l, d, l->vmnum, SKINNY_CALLTYPE_OUTBOUND, NULL); } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No voicemail number configured on line %d\n", d->id, lineInstance); } c = c ? sccp_channel_release(c) : NULL; l = sccp_line_release(l); } /*! * \brief Handle Divert/Transfer Call to VoiceMail * \param d SCCP Device * \param l SCCP Line * \param c SCCP Channel */ void sccp_feat_idivert(sccp_device_t * d, sccp_line_t * l, sccp_channel_t * c) { int instance; if (!l) { sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: TRANSVM pressed but no line found\n", d->id); sccp_dev_displayprompt(d, 0, 0, "No line found to transfer", 5); return; } if (!l->trnsfvm) { sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: TRANSVM pressed but not configured in sccp.conf\n", d->id); return; } if (!c || !c->owner) { sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: TRANSVM with no channel active\n", d->id); sccp_dev_displayprompt(d, 0, 0, "TRANSVM with no channel active", 5); return; } if (c->state != SCCP_CHANNELSTATE_RINGING && c->state != SCCP_CHANNELSTATE_CALLWAITING) { sccp_log((DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: TRANSVM pressed in no ringing state\n", d->id); return; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: TRANSVM to %s\n", d->id, l->trnsfvm); PBX(setChannelCallForward) (c, l->trnsfvm); instance = sccp_device_find_index_for_line(d, l->name); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); /* send connected, so it is not listed as missed call */ pbx_setstate(c->owner, AST_STATE_BUSY); PBX(queue_control) (c->owner, AST_CONTROL_BUSY); } /*! * \brief Handle 3-Way Phone Based Conferencing on a Device * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \return SCCP Channel * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others * * \lock * - channel * - see sccp_indicate_nolock() * - channel * - see sccp_channel_set_active() * - see sccp_indicate_nolock() * - see sccp_pbx_channel_allocate() * - see sccp_channel_openreceivechannel() */ void sccp_feat_handle_conference(sccp_device_t * d, sccp_line_t * l, uint8_t lineInstance, sccp_channel_t * c) { #ifdef CS_SCCP_CONFERENCE if (!l || !d || !d->id || sccp_strlen_zero(d->id)) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if line or device are not defined!\n"); return; } if (!d->allow_conference) { sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); pbx_log(LOG_NOTICE, "%s: conference not enabled\n", DEV_ID_LOG(d)); return; } /* look if we have a call */ if ((c = sccp_channel_get_active(d))) { if (!sccp_channel_hold(c)) { sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_TEMP_FAIL, 5); c = sccp_channel_release(c); return; } c = sccp_channel_release(c); } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Allocating new channel for conference\n"); if ((c = sccp_channel_allocate(l, d))) { c->ss_action = SCCP_SS_GETCONFERENCEROOM; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* not needed here */ c->calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_channel_set_active(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(c, NULL)) { pbx_log(LOG_WARNING, "%s: (sccp_feat_handle_conference) Unable to allocate a new channel for line %s\n", d->id, l->name); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); c = sccp_channel_release(c); return; } PBX(set_callstate) (c, AST_STATE_OFFHOOK); /* removing scheduled dial */ c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_pbx_softswitch(c); c = sccp_channel_release(c); } else { pbx_log(LOG_ERROR, "%s: (sccp_feat_handle_conference) Can't allocate SCCP channel for line %s\n", DEV_ID_LOG(d), l->name); return; } #endif } /*! * \brief Handle Conference * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \return Success as int * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others * * \lock * - device->selectedChannels * - see sccp_conference_addParticipant() * - device->buttonconfig * - see sccp_line_find_byname() * - line->channels * - see sccp_conference_addParticipant() */ void sccp_feat_conference_start(sccp_device_t * d, sccp_line_t * l, const uint32_t lineInstance, sccp_channel_t * c) { #ifdef CS_SCCP_CONFERENCE sccp_channel_t *channel = NULL; sccp_selectedchannel_t *selectedChannel = NULL; boolean_t selectedFound = FALSE; PBX_CHANNEL_TYPE *bridged_channel = NULL; if (!(d = sccp_device_retain(d)) || !c) { return; } uint8_t num = sccp_device_numberOfChannels(d); int instance = sccp_device_find_index_for_line(d, l->name); sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: sccp_device_numberOfChannels %d.\n", DEV_ID_LOG(d), num); if (d->conference /* && num > 3 */ ) { /* if we have selected channels, add this to conference */ SCCP_LIST_LOCK(&d->selectedChannels); SCCP_LIST_TRAVERSE(&d->selectedChannels, selectedChannel, list) { selectedFound = TRUE; if (NULL != selectedChannel->channel && selectedChannel->channel != c) { if (channel != d->active_channel) { if ((bridged_channel = CS_AST_BRIDGED_CHANNEL(channel->owner))) { sccp_conference_addParticipatingChannel(d->conference, c, bridged_channel); } else { pbx_log(LOG_ERROR, "%s: sccp conference: bridgedchannel for channel %s could not be found\n", DEV_ID_LOG(d), pbx_channel_name(channel->owner)); } } } } SCCP_LIST_UNLOCK(&d->selectedChannels); /* If no calls were selected, add all calls to the conference, across all lines. */ if (FALSE == selectedFound) { // all channels on this phone sccp_line_t *line = NULL; uint8_t i = 0; for (i = 0; i < StationMaxButtonTemplateSize; i++) { if (d->buttonTemplate[i].type == SKINNY_BUTTONTYPE_LINE && d->buttonTemplate[i].ptr) { if ((line = sccp_line_retain(d->buttonTemplate[i].ptr))) { SCCP_LIST_LOCK(&line->channels); SCCP_LIST_TRAVERSE(&line->channels, channel, list) { if (channel != d->active_channel) { if ((bridged_channel = CS_AST_BRIDGED_CHANNEL(channel->owner))) { sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: sccp conference: channel %s, state: %s.\n", DEV_ID_LOG(d), pbx_channel_name(bridged_channel), channelstate2str(channel->state)); sccp_conference_addParticipatingChannel(d->conference, c, bridged_channel); } else { pbx_log(LOG_ERROR, "%s: sccp conference: bridgedchannel for channel %s could not be found\n", DEV_ID_LOG(d), pbx_channel_name(channel->owner)); } } } SCCP_LIST_UNLOCK(&line->channels); line = sccp_line_release(line); } } } } sccp_conference_start(d->conference); } else { sccp_dev_displayprompt(d, instance, c->callid, "Error creating conf", 5); pbx_log(LOG_NOTICE, "%s: conference could not be created\n", DEV_ID_LOG(d)); } d = d ? sccp_device_release(d) : NULL; #else sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: conference not enabled\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); #endif } /*! * \brief Handle Join a Conference * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others */ void sccp_feat_join(sccp_device_t * d, sccp_line_t * l, uint8_t lineInstance, sccp_channel_t * c) { #if CS_SCCP_CONFERENCE sccp_channel_t *channel = NULL; PBX_CHANNEL_TYPE *bridged_channel = NULL; if (!c) return; if ((d = sccp_device_retain(d))) { if (!d->allow_conference) { sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); pbx_log(LOG_NOTICE, "%s: conference not enabled\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, lineInstance, c->callid, "conference not allowed", 5); } else if (!d->conference) { pbx_log(LOG_NOTICE, "%s: There is currently no active conference on this device. Start Conference First.\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, lineInstance, c->callid, "No Conference to Join", 5); } else if (!d->active_channel) { pbx_log(LOG_NOTICE, "%s: No active channel on device to join to the conference.\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, lineInstance, c->callid, "No Active Channel", 5); } else if (d->active_channel->conference) { pbx_log(LOG_NOTICE, "%s: Channel is already part of a conference.\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, lineInstance, c->callid, "Already in Conference", 5); } else { channel = d->active_channel; pbx_log(LOG_NOTICE, "%s: Joining new participant to conference %d.\n", DEV_ID_LOG(d), d->conference->id); sccp_channel_hold(channel); if ((bridged_channel = CS_AST_BRIDGED_CHANNEL(channel->owner))) { sccp_log((DEBUGCAT_CONFERENCE | DEBUGCAT_FEATURE)) (VERBOSE_PREFIX_3 "%s: sccp conference: channel %s, state: %s.\n", DEV_ID_LOG(d), pbx_channel_name(bridged_channel), channelstate2str(channel->state)); sccp_conference_addParticipatingChannel(d->conference, channel, bridged_channel); } else { pbx_log(LOG_ERROR, "%s: sccp conference: bridgedchannel for channel %s could not be found\n", DEV_ID_LOG(d), pbx_channel_name(channel->owner)); } sccp_channel_t *mod_chan = NULL; SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, mod_chan, list) { if (d->conference == mod_chan->conference) { sccp_channel_resume(d, mod_chan, FALSE); sccp_feat_conflist(d, mod_chan->line, 0, mod_chan); break; } } SCCP_LIST_UNLOCK(&l->channels); sccp_conference_update(d->conference); } d = sccp_device_release(d); } #else pbx_log(LOG_NOTICE, "%s: conference not enabled\n", DEV_ID_LOG(d)); sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); #endif } /*! * \brief Handle Conference List * \param d SCCP Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param c SCCP Channel * \return Success as int */ void sccp_feat_conflist(sccp_device_t * d, sccp_line_t * l, uint8_t lineInstance, sccp_channel_t * c) { if (d) { #ifdef CS_SCCP_CONFERENCE if (!d->allow_conference) { sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); pbx_log(LOG_NOTICE, "%s: conference not enabled\n", DEV_ID_LOG(d)); return; } sccp_conference_show_list(c->conference, c); #else sccp_dev_displayprompt(d, lineInstance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); #endif } } /*! * \brief Handle 3-Way Phone Based Conferencing on a Device * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param d SCCP Device * \return SCCP Channel * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others * * \lock * - channel * - see sccp_indicate_nolock() * - channel * - see sccp_channel_set_active() * - see sccp_indicate_nolock() * - see sccp_pbx_channel_allocate() * - see sccp_channel_openreceivechannel() */ void sccp_feat_handle_meetme(sccp_line_t * l, uint8_t lineInstance, sccp_device_t * d) { sccp_channel_t *c; if (!l || !d || !d->id || sccp_strlen_zero(d->id)) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if line or device are not defined!\n"); return; } /* look if we have a call */ if ((c = sccp_channel_get_active(d))) { // we have a channel, checking if if (c->state == SCCP_CHANNELSTATE_OFFHOOK && (!c->dialedNumber || (c->dialedNumber && sccp_strlen_zero(c->dialedNumber)))) { // we are dialing but without entering a number :D -FS sccp_dev_stoptone(d, lineInstance, (c && c->callid) ? c->callid : 0); // changing SS_DIALING mode to SS_GETFORWARDEXTEN c->ss_action = SCCP_SS_GETMEETMEROOM; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* this should be found in thread */ // changing channelstate to GETDIGITS sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); c = sccp_channel_release(c); return; /* there is an active call, let's put it on hold first */ } else if (!sccp_channel_hold(c)) { c = sccp_channel_release(c); return; } c = sccp_channel_release(c); } c = sccp_channel_allocate(l, d); if (!c) { pbx_log(LOG_ERROR, "%s: (handle_meetme) Can't allocate SCCP channel for line %s\n", DEV_ID_LOG(d), l->name); return; } c->ss_action = SCCP_SS_GETMEETMEROOM; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* not needed here */ c->calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_channel_set_active(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(c, NULL)) { pbx_log(LOG_WARNING, "%s: (handle_meetme) Unable to allocate a new channel for line %s\n", d->id, l->name); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); c = sccp_channel_release(c); return; } PBX(set_callstate) (c, AST_STATE_OFFHOOK); if (d->earlyrtp == SCCP_CHANNELSTATE_OFFHOOK && !c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } /* removing scheduled dial */ c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); if (!(c->scheduler.digittimeout = sccp_sched_add(GLOB(firstdigittimeout) * 1000, sccp_pbx_sched_dial, c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Unable to schedule dialing in '%d' ms\n", GLOB(firstdigittimeout)); } c = sccp_channel_release(c); } /*! * \brief SCCP Meetme Application Config Structure */ struct meetmeAppConfig { char *appName; char *defaultMeetmeOption; } meetmeApps[] = { /* *INDENT-OFF* */ {"MeetMe", "qd"}, {"ConfBridge", "Mac"}, {"Konference", "MTV"} /* *INDENT-ON* */ }; /*! * \brief a Meetme Application Thread * \param data Data * \author Federico Santulli * * \lock * - channel * - see sccp_indicate_nolock() * - see sccp_channel_set_calledparty() * - see sccp_channel_setSkinnyCallstate() * - see sccp_channel_send_callinfo() * - see sccp_indicate_nolock() */ static void *sccp_feat_meetme_thread(void *data) { sccp_channel_t *c = data; sccp_device_t *d = NULL; struct meetmeAppConfig *app = NULL; char ext[SCCP_MAX_EXTENSION]; char context[SCCP_MAX_CONTEXT]; char meetmeopts[SCCP_MAX_CONTEXT]; #if ASTERISK_VERSION_NUMBER >= 10600 #define SCCP_CONF_SPACER ',' #endif #if ASTERISK_VERSION_NUMBER >= 10400 && ASTERISK_VERSION_NUMBER < 10600 #define SCCP_CONF_SPACER '|' #endif #if ASTERISK_VERSION_NUMBER >= 10400 unsigned int eid = pbx_random(); #else unsigned int eid = random(); #define SCCP_CONF_SPACER '|' #endif if (!c || !(d = sccp_channel_getDevice_retained(c))) { pbx_log(LOG_NOTICE, "SCCP: no channel or device provided for meetme feature. exiting\n"); return NULL; } /* searching for meetme app */ uint32_t i; for (i = 0; i < sizeof(meetmeApps) / sizeof(struct meetmeAppConfig); i++) { if (pbx_findapp(meetmeApps[i].appName)) { app = &(meetmeApps[i]); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: using '%s' for meetme\n", meetmeApps[i].appName); break; } } /* finish searching for meetme app */ if (!app) { // \todo: remove res in this line: Although the value stored to 'res' is used in the enclosing expression, the value is never actually read from 'res' pbx_log(LOG_WARNING, "SCCP: No MeetMe application available!\n"); c = sccp_channel_retain(c); sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_channel_set_calledparty(c, SKINNY_DISP_CONFERENCE, c->dialedNumber); sccp_channel_setSkinnyCallstate(c, SKINNY_CALLSTATE_PROCEED); sccp_channel_send_callinfo(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDCONFERENCE); c = sccp_channel_release(c); d = sccp_device_release(d); return NULL; } // SKINNY_DISP_CAN_NOT_COMPLETE_CONFERENCE if (c && c->owner) { if (!pbx_channel_context(c->owner) || sccp_strlen_zero(pbx_channel_context(c->owner))) { d = sccp_device_release(d); return NULL; } /* replaced by meetmeopts in global, device, line */ // snprintf(meetmeopts, sizeof(meetmeopts), "%s%c%s", c->dialedNumber, SCCP_CONF_SPACER, (c->line->meetmeopts&& !sccp_strlen_zero(c->line->meetmeopts)) ? c->line->meetmeopts : "qd"); if (!sccp_strlen_zero(c->line->meetmeopts)) { snprintf(meetmeopts, sizeof(meetmeopts), "%s%c%s", c->dialedNumber, SCCP_CONF_SPACER, c->line->meetmeopts); } else if (!sccp_strlen_zero(d->meetmeopts)) { snprintf(meetmeopts, sizeof(meetmeopts), "%s%c%s", c->dialedNumber, SCCP_CONF_SPACER, d->meetmeopts); } else if (!sccp_strlen_zero(GLOB(meetmeopts))) { snprintf(meetmeopts, sizeof(meetmeopts), "%s%c%s", c->dialedNumber, SCCP_CONF_SPACER, GLOB(meetmeopts)); } else { snprintf(meetmeopts, sizeof(meetmeopts), "%s%c%s", c->dialedNumber, SCCP_CONF_SPACER, app->defaultMeetmeOption); } sccp_copy_string(context, pbx_channel_context(c->owner), sizeof(context)); snprintf(ext, sizeof(ext), "sccp_meetme_temp_conference_%ud", eid); if (!pbx_exists_extension(NULL, context, ext, 1, NULL)) { pbx_add_extension(context, 1, ext, 1, NULL, NULL, app->appName, meetmeopts, NULL, "sccp_feat_meetme_thread"); pbx_log(LOG_WARNING, "SCCP: create extension exten => %s,%d,%s(%s)\n", ext, 1, app->appName, meetmeopts); } // sccp_copy_string(c->owner->exten, ext, sizeof(c->owner->exten)); PBX(setChannelExten) (c, ext); c = sccp_channel_retain(c); sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_channel_set_calledparty(c, SKINNY_DISP_CONFERENCE, c->dialedNumber); sccp_channel_setSkinnyCallstate(c, SKINNY_CALLSTATE_PROCEED); sccp_channel_send_callinfo(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTEDCONFERENCE); if (pbx_pbx_run(c->owner)) { sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDCONFERENCE); pbx_log(LOG_WARNING, "SCCP: SCCP_CHANNELSTATE_INVALIDCONFERENCE\n"); } c = sccp_channel_release(c); ast_context_remove_extension(context, ext, 1, NULL); } d = sccp_device_release(d); return NULL; } /*! * \brief Start a Meetme Application Thread * \param c SCCP Channel * \author Federico Santulli */ void sccp_feat_meetme_start(sccp_channel_t * c) { #if CS_EXPERIMENTAL sccp_threadpool_add_work(GLOB(general_threadpool), (void *) sccp_feat_meetme_thread, (void *) c); #else pthread_attr_t attr; pthread_t t; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (pbx_pthread_create(&t, &attr, sccp_feat_meetme_thread, c) < 0) { pbx_log(LOG_WARNING, "SCCP: Cannot create a MeetMe thread (%s).\n", strerror(errno)); } pthread_attr_destroy(&attr); #endif } /*! * \brief Handle Barging into a Call * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param d SCCP Device * \return SCCP Channel * * \lock * - channel * - see sccp_indicate_nolock() */ void sccp_feat_handle_barge(sccp_line_t * l, uint8_t lineInstance, sccp_device_t * d) { sccp_channel_t *c; if (!l || !d || !d->id || sccp_strlen_zero(d->id)) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if line or device are not defined!\n"); return; } /* look if we have a call */ if ((c = sccp_channel_get_active(d))) { // we have a channel, checking if if (c->state == SCCP_CHANNELSTATE_OFFHOOK && (!c->dialedNumber || (c->dialedNumber && sccp_strlen_zero(c->dialedNumber)))) { // we are dialing but without entering a number :D -FS sccp_dev_stoptone(d, lineInstance, (c && c->callid) ? c->callid : 0); // changing SS_DIALING mode to SS_GETFORWARDEXTEN c->ss_action = SCCP_SS_GETBARGEEXTEN; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* this should be found in thread */ // changing channelstate to GETDIGITS sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); c = sccp_channel_release(c); return; } else if (!sccp_channel_hold(c)) { /* there is an active call, let's put it on hold first */ c = sccp_channel_release(c); return; } c = sccp_channel_release(c); } c = sccp_channel_allocate(l, d); if (!c) { pbx_log(LOG_ERROR, "%s: (handle_barge) Can't allocate SCCP channel for line %s\n", d->id, l->name); return; } c->ss_action = SCCP_SS_GETBARGEEXTEN; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* not needed here */ c->calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_channel_set_active(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(c, NULL)) { pbx_log(LOG_WARNING, "%s: (handle_barge) Unable to allocate a new channel for line %s\n", d->id, l->name); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); c = sccp_channel_release(c); return; } PBX(set_callstate) (c, AST_STATE_OFFHOOK); if (d->earlyrtp == SCCP_CHANNELSTATE_OFFHOOK && !c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } c = sccp_channel_release(c); } /*! * \brief Barging into a Call Feature * \param c SCCP Channel * \param exten Extention as char * \return Success as int */ int sccp_feat_barge(sccp_channel_t * c, char *exten) { /* sorry but this is private code -FS */ sccp_device_t *d = NULL; if (!c || !(d = sccp_channel_getDevice_retained(c))) return -1; uint8_t instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); d = sccp_device_release(d); return 1; } /*! * \brief Handle Barging into a Conference * \param l SCCP Line * \param lineInstance lineInstance as uint8_t * \param d SCCP Device * \return SCCP Channel * \todo Conferencing option needs to be build and implemented * Using and External Conference Application Instead of Meetme makes it possible to use app_Conference, app_MeetMe, app_Konference and/or others * * \lock * - channel * - see sccp_indicate_nolock() * - channel * - see sccp_channel_set_active() * - see sccp_indicate_nolock() */ void sccp_feat_handle_cbarge(sccp_line_t * l, uint8_t lineInstance, sccp_device_t * d) { sccp_channel_t *c; if (!l || !d || strlen(d->id) < 3) { pbx_log(LOG_ERROR, "SCCP: Can't allocate SCCP channel if line or device are not defined!\n"); return; } /* look if we have a call */ if ((c = sccp_channel_get_active(d))) { // we have a channel, checking if if (c->state == SCCP_CHANNELSTATE_OFFHOOK && (!c->dialedNumber || (c->dialedNumber && sccp_strlen_zero(c->dialedNumber)))) { // we are dialing but without entering a number :D -FS sccp_dev_stoptone(d, lineInstance, (c && c->callid) ? c->callid : 0); // changing SS_DIALING mode to SS_GETFORWARDEXTEN c->ss_action = SCCP_SS_GETCBARGEROOM; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* this should be found in thread */ // changing channelstate to GETDIGITS sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); c = sccp_channel_release(c); return; } else { /* there is an active call, let's put it on hold first */ if (!sccp_channel_hold(c)) { c = sccp_channel_release(c); return; } } c = sccp_channel_release(c); } c = sccp_channel_allocate(l, d); if (!c) { pbx_log(LOG_ERROR, "%s: (handle_cbarge) Can't allocate SCCP channel for line %s\n", d->id, l->name); return; } c->ss_action = SCCP_SS_GETCBARGEROOM; /* Simpleswitch will catch a number to be dialed */ c->ss_data = 0; /* not needed here */ c->calltype = SKINNY_CALLTYPE_OUTBOUND; sccp_channel_set_active(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_GETDIGITS); /* ok the number exist. allocate the asterisk channel */ if (!sccp_pbx_channel_allocate(c, NULL)) { pbx_log(LOG_WARNING, "%s: (handle_cbarge) Unable to allocate a new channel for line %s\n", d->id, l->name); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); c = sccp_channel_release(c); return; } PBX(set_callstate) (c, AST_STATE_OFFHOOK); if (d->earlyrtp == SCCP_CHANNELSTATE_OFFHOOK && !c->rtp.audio.rtp) { sccp_channel_openreceivechannel(c); } c = sccp_channel_release(c); } /*! * \brief Barging into a Conference Feature * \param c SCCP Channel * \param conferencenum Conference Number as char * \return Success as int */ int sccp_feat_cbarge(sccp_channel_t * c, char *conferencenum) { /* sorry but this is private code -FS */ sccp_device_t *d = NULL; if (!c || !(d = sccp_channel_getDevice_retained(c))) return -1; uint8_t instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_KEY_IS_NOT_ACTIVE, 5); d = sccp_device_release(d); return 1; } /*! * \brief Hotline Feature * * Setting the hotline Feature on a device, will make it connect to a predefined extension as soon as the Receiver * is picked up or the "New Call" Button is pressed. No number has to be given. * * \param d SCCP Device * \param line SCCP Line * * \lock * - channel */ void sccp_feat_adhocDial(sccp_device_t * d, sccp_line_t * line) { sccp_channel_t *c = NULL; if (!d || !d->session || !line) return; sccp_log((DEBUGCAT_FEATURE | DEBUGCAT_LINE)) (VERBOSE_PREFIX_3 "%s: handling hotline\n", d->id); if ((c = sccp_channel_get_active(d))) { if ((c->state == SCCP_CHANNELSTATE_DIALING) || (c->state == SCCP_CHANNELSTATE_OFFHOOK)) { sccp_copy_string(c->dialedNumber, line->adhocNumber, sizeof(c->dialedNumber)); c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_pbx_softswitch(c); c = sccp_channel_release(c); return; } sccp_pbx_senddigits(c, line->adhocNumber); } else { // Pull up a channel if (GLOB(hotline)->line) { c = sccp_channel_newcall(line, d, line->adhocNumber, SKINNY_CALLTYPE_OUTBOUND, NULL); } } c = c ? sccp_channel_release(c) : NULL; } /*! * \brief Handler to Notify Features have Changed * \param device SCCP Device * \param linedevice SCCP LineDevice * \param featureType SCCP Feature Type * * \lock * - see sccp_hint_handleFeatureChangeEvent() via sccp_event_fire() * - see sccp_util_handleFeatureChangeEvent() via sccp_event_fire() */ void sccp_feat_changed(sccp_device_t * device, sccp_linedevices_t * linedevice, sccp_feature_type_t featureType) { if (device) { sccp_featButton_changed(device, featureType); sccp_event_t event; memset(&event, 0, sizeof(sccp_event_t)); event.type = SCCP_EVENT_FEATURE_CHANGED; event.event.featureChanged.device = sccp_device_retain(device); event.event.featureChanged.linedevice = linedevice ? sccp_linedevice_retain(linedevice) : NULL; event.event.featureChanged.featureType = featureType; sccp_event_fire(&event); } } /*! * \brief Handler to Notify Channel State has Changed * \param device SCCP Device * \param channel SCCP Channel */ void sccp_feat_channelstateChanged(sccp_device_t * device, sccp_channel_t * channel) { uint8_t state; if (!channel || !device) return; state = channel->state; switch (state) { case SCCP_CHANNELSTATE_CONNECTED: /* We must update the status here. Not change it. (DD) */ /* if (device->monitorFeature.enabled && device->monitorFeature.status != channel->monitorEnabled) { sccp_feat_monitor(device, channel); } */ break; case SCCP_CHANNELSTATE_DOWN: // case SCCP_CHANNELSTATE_ONHOOK: // case SCCP_CHANNELSTATE_BUSY: // case SCCP_CHANNELSTATE_CONGESTION: // case SCCP_CHANNELSTATE_INVALIDNUMBER: // case SCCP_CHANNELSTATE_ZOMBIE: /* \todo: In the event a call is terminated, the channel monitor should be turned off (it implicitly is by ending the call), and the feature button should be reset to disabled state. */ // device->monitorFeature.status = 0; // sccp_feat_changed(device, NULL, SCCP_FEATURE_MONITOR); break; default: break; } } /*! * \brief Feature Monitor * \param device SCCP Device * \param line SCCP Line * \param lineInstance LineInstance as uint32_t * \param channel SCCP Channel */ void sccp_feat_monitor(sccp_device_t * device, sccp_line_t * line, const uint32_t lineInstance, sccp_channel_t * channel) { PBX(feature_monitor) (channel); }
722,269
./chan-sccp-b/src/sccp_pbx.c
/*! * \file sccp_pbx.c * \brief SCCP PBX Asterisk Wrapper Class * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date$ * $Revision$ */ #ifndef __PBX_IMPL_C #define __PBX_IMPL_C #include <config.h> #include "common.h" SCCP_FILE_VERSION(__FILE__, "$Revision$") /*! * \brief SCCP Structure to pass data to the pbx answer thread */ struct sccp_answer_conveyor_struct { uint32_t callid; sccp_linedevices_t *linedevice; }; /*! * \brief Call Auto Answer Thead * \param data Data * * The Auto Answer thread is started by ref sccp_pbx_call if necessary */ static void *sccp_pbx_call_autoanswer_thread(void *data) { struct sccp_answer_conveyor_struct *conveyor = data; sccp_channel_t *c = NULL; sccp_device_t *device = NULL; int instance = 0; sleep(GLOB(autoanswer_ring_time)); pthread_testcancel(); if (!conveyor) { return NULL; } if (!conveyor->linedevice) { goto FINAL; } if (!(device = sccp_device_retain(conveyor->linedevice->device))) { goto FINAL; } if (!(c = sccp_channel_find_byid(conveyor->callid))) { goto FINAL; } if (c->state != SCCP_CHANNELSTATE_RINGING) { goto FINAL; } sccp_channel_answer(device, c); if (GLOB(autoanswer_tone) != SKINNY_TONE_SILENCE && GLOB(autoanswer_tone) != SKINNY_TONE_NOTONE) { instance = sccp_device_find_index_for_line(device, c->line->name); sccp_dev_starttone(device, GLOB(autoanswer_tone), instance, c->callid, 0); } if (c->autoanswer_type == SCCP_AUTOANSWER_1W) { sccp_dev_set_microphone(device, SKINNY_STATIONMIC_OFF); } FINAL: c = c ? sccp_channel_release(c) : NULL; device = device ? sccp_device_release(device) : NULL; conveyor->linedevice = conveyor->linedevice ? sccp_linedevice_release(conveyor->linedevice) : NULL; // retained in calling thread, final release here sccp_free(conveyor); return NULL; } /*! * \brief Incoming Calls by Asterisk SCCP_Request * \param c SCCP Channel * \param dest Destination as char * \param timeout Timeout after which incoming call is cancelled as int * \return Success as int * * \todo reimplement DNDMODES, ringermode=urgent, autoanswer * * \callgraph * \callergraph * * \called_from_asterisk * * \lock * - line * - line->devices * - line * - line->devices * - see sccp_device_sendcallstate() * - see sccp_channel_send_callinfo() * - see sccp_channel_forward() * - see sccp_util_matchSubscriptionId() * - see sccp_channel_get_active() * - see sccp_indicate_lock() * * \note called with c retained */ int sccp_pbx_call(sccp_channel_t * c, char *dest, int timeout) { sccp_line_t *l; sccp_channel_t *active_channel = NULL; char *cid_name = NULL; char *cid_number = NULL; char suffixedNumber[255] = { '\0' }; /*!< For saving the digittimeoutchar to the logs */ boolean_t hasSession = FALSE; l = sccp_line_retain(c->line); if (l) { sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { assert(linedevice->device); if (linedevice->device->session) hasSession = TRUE; } SCCP_LIST_UNLOCK(&l->devices); if (!hasSession) { pbx_log(LOG_WARNING, "SCCP: weird error. The channel %d has no device connected to this line or device has no valid session\n", (c ? c->callid : 0)); if (l) l = sccp_line_release(l); return -1; } } else { pbx_log(LOG_WARNING, "SCCP: weird error. The channel %d has no line\n", (c ? c->callid : 0)); if (l) l = sccp_line_release(l); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Asterisk request to call %s\n", l->name, PBX(getChannelName) (c)); /* if incoming call limit is reached send BUSY */ if (SCCP_RWLIST_GETSIZE(l->channels) > l->incominglimit) { /* >= just to be sure :-) */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "Incoming calls limit (%d) reached on SCCP/%s... sending busy\n", l->incominglimit, l->name); l = sccp_line_release(l); pbx_setstate(c->owner, AST_STATE_BUSY); PBX(queue_control) (c->owner, AST_CONTROL_BUSY); return 0; } /* Reinstated this call instead of the following lines */ if (strlen(c->callInfo.callingPartyName) > 0) { cid_name = strdup(c->callInfo.callingPartyName); } if (strlen(c->callInfo.callingPartyNumber) > 0) { cid_number = strdup(c->callInfo.callingPartyNumber); } //! \todo implement dnid, ani, ani2 and rdnis sccp_log(DEBUGCAT_PBX) (VERBOSE_PREFIX_3 "SCCP: (sccp_pbx_call) asterisk callerid='%s <%s>'\n", (cid_number) ? cid_number : "", (cid_name) ? cid_name : ""); /* Set the channel callingParty Name and Number, called Party Name and Number, original CalledParty Name and Number, Presentation */ if (GLOB(recorddigittimeoutchar)) { /* The hack to add the # at the end of the incoming number is only applied for numbers beginning with a 0, which is appropriate for Germany and other countries using similar numbering plan. The option should be generalized, moved to the dialplan, or otherwise be replaced. */ /* Also, we require an option whether to add the timeout suffix to certain enbloc dialed numbers (such as via 7970 enbloc dialing) if they match a certain pattern. This would help users dial from call history lists on other phones, which do not have enbloc dialing, when using shared lines. */ if (NULL != cid_number && strlen(cid_number) > 0 && strlen(cid_number) < sizeof(suffixedNumber) - 2 && '0' == cid_number[0]) { strncpy(suffixedNumber, cid_number, strlen(cid_number)); suffixedNumber[strlen(cid_number) + 0] = '#'; suffixedNumber[strlen(cid_number) + 1] = '\0'; sccp_channel_set_callingparty(c, cid_name, suffixedNumber); } else { sccp_channel_set_callingparty(c, cid_name, cid_number); } } else { sccp_channel_set_callingparty(c, cid_name, cid_number); } /* Set the channel calledParty Name and Number 7910 compatibility */ sccp_channel_set_calledparty(c, l->cid_name, l->cid_num); PBX(set_connected_line) (c, c->callInfo.calledPartyNumber, c->callInfo.calledPartyName, AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN); //! \todo implement dnid, ani, ani2 and rdnis if (PBX(get_callerid_presence)) { sccp_channel_set_calleridPresenceParameter(c, PBX(get_callerid_presence) (c)); } sccp_channel_display_callInfo(c); if (!c->ringermode) { c->ringermode = SKINNY_RINGTYPE_OUTSIDE; } boolean_t isRinging = FALSE; boolean_t hasDNDParticipant = FALSE; sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { assert(linedevice->device); /* do we have cfwd enabled? */ if (linedevice->cfwdAll.enabled) { pbx_log(LOG_NOTICE, "%s: initialize cfwd for line %s\n", linedevice->device->id, l->name); if (sccp_channel_forward(c, linedevice, linedevice->cfwdAll.number) == 0) { sccp_device_sendcallstate(linedevice->device, linedevice->lineInstance, c->callid, SKINNY_CALLSTATE_INTERCOMONEWAY, SKINNY_CALLPRIORITY_NORMAL, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(linedevice->device, c); #ifdef CS_EXPERIMENTAL if (sccp_strlen_zero(pbx_builtin_getvar_helper(c->owner, "FORWARDER_FOR"))) { struct ast_var_t *variables; const char *var, *val; char mask[25]; ast_channel_lock(c->owner); sprintf(mask, "SCCP::%d", c->callid); AST_LIST_TRAVERSE(pbx_channel_varshead(c->owner), variables, entries) { if ((var = ast_var_name(variables)) && (val = ast_var_value(variables)) && (!strcmp("LINKID", var)) && (strcmp(mask, val))) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_1 "SCCP: LINKID %s\n", val); pbx_builtin_setvar_helper(c->owner, "__FORWARDER_FOR", val); } } ast_channel_unlock(c->owner); } #endif isRinging = TRUE; } continue; } if (!linedevice->device->session) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: line device has no session\n", DEV_ID_LOG(linedevice->device)); continue; } /* check if c->subscriptionId.number is matching deviceSubscriptionID */ /* This means that we call only those devices on a shared line which match the specified subscription id in the dial parameters. */ if (!sccp_util_matchSubscriptionId(c, linedevice->subscriptionId.number)) { sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: device does not match subscriptionId.number c->subscriptionId.number: '%s', deviceSubscriptionID: '%s'\n", DEV_ID_LOG(linedevice->device), c->subscriptionId.number, linedevice->subscriptionId.number); continue; } if ((active_channel = sccp_channel_get_active(linedevice->device))) { sccp_indicate(linedevice->device, c, SCCP_CHANNELSTATE_CALLWAITING); isRinging = TRUE; active_channel = sccp_channel_release(active_channel); } else { /** check if ringermode is not urgent and device enabled dnd in reject mode */ if (SKINNY_RINGTYPE_URGENT != c->ringermode && linedevice->device->dndFeature.enabled && linedevice->device->dndFeature.status == SCCP_DNDMODE_REJECT) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: DND active on line %s, returning Busy\n", linedevice->device->id, linedevice->line->name); hasDNDParticipant = TRUE; continue; } sccp_indicate(linedevice->device, c, SCCP_CHANNELSTATE_RINGING); isRinging = TRUE; if (c->autoanswer_type) { struct sccp_answer_conveyor_struct *conveyor = sccp_calloc(1, sizeof(struct sccp_answer_conveyor_struct)); if (conveyor) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Running the autoanswer thread on %s\n", DEV_ID_LOG(linedevice->device), PBX(getChannelName) (c)); conveyor->callid = c->callid; conveyor->linedevice = sccp_linedevice_retain(linedevice); #if !CS_EXPERIMENTAL /* new default */ sccp_threadpool_add_work(GLOB(general_threadpool), (void *) sccp_pbx_call_autoanswer_thread, (void *) conveyor); #else pthread_t t; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (pbx_pthread_create(&t, &attr, sccp_pbx_call_autoanswer_thread, conveyor)) { pbx_log(LOG_WARNING, "%s: Unable to create switch thread for channel (%s-%08x) %s\n", DEV_ID_LOG(linedevice->device), l->name, c->callid, strerror(errno)); sccp_free(conveyor); } pthread_detach(t); pthread_attr_destroy(&attr); #endif } } } } SCCP_LIST_UNLOCK(&l->devices); if (isRinging) { sccp_channel_setSkinnyCallstate(c, SKINNY_CALLSTATE_RINGIN); PBX(queue_control) (c->owner, AST_CONTROL_RINGING); } else if (hasDNDParticipant) { pbx_setstate(c->owner, AST_STATE_BUSY); PBX(queue_control) (c->owner, AST_CONTROL_BUSY); } else { PBX(queue_control) (c->owner, AST_CONTROL_CONGESTION); } if (cid_name) free(cid_name); if (cid_number) free(cid_number); /** * workaround to fix: * [Jun 21 08:44:15] WARNING[21040]: channel.c:4934 ast_write: Codec mismatch on channel SCCP/109-0000000a setting write format to slin16 from ulaw native formats 0x0 (nothing) * */ PBX(rtp_setWriteFormat) (c, SKINNY_CODEC_WIDEBAND_256K); PBX(rtp_setReadFormat) (c, SKINNY_CODEC_WIDEBAND_256K); l = sccp_line_release(l); return isRinging != TRUE; } /*! * \brief Handle Hangup Request by Asterisk * \param c SCCP Channel * \return Success as int * * \callgraph * \callergraph * * \called_from_asterisk via sccp_wrapper_asterisk.._hangup * * \note sccp_channel should be retained in calling function */ int sccp_pbx_hangup(sccp_channel_t * c) { sccp_line_t *l = NULL; sccp_device_t *d = NULL; /* here the ast channel is locked */ //sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk request to hangup channel %s\n", PBX(getChannelName)(c)); sccp_mutex_lock(&GLOB(usecnt_lock)); GLOB(usecnt)--; sccp_mutex_unlock(&GLOB(usecnt_lock)); pbx_update_use_count(); if (!(c = sccp_channel_retain(c))) { sccp_log((DEBUGCAT_PBX + DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Asked to hangup channel. SCCP channel already deleted\n"); return -1; } d = sccp_channel_getDevice_retained(c); if (d && c->state != SCCP_CHANNELSTATE_DOWN && SKINNY_DEVICE_RS_OK == d->registrationState) { //if (GLOB(remotehangup_tone) && d && d->state == SCCP_DEVICESTATE_OFFHOOK && c == sccp_channel_get_active_nolock(d)) /* Caused active channels never to be full released */ if (GLOB(remotehangup_tone) && d && d->state == SCCP_DEVICESTATE_OFFHOOK && c == d->active_channel) { sccp_dev_starttone(d, GLOB(remotehangup_tone), 0, 0, 10); } sccp_indicate(d, c, SCCP_CHANNELSTATE_ONHOOK); } l = sccp_line_retain(c->line); #ifdef CS_SCCP_CONFERENCE if (c && c->conference) { c->conference = sccp_refcount_release(c->conference, __FILE__, __LINE__, __PRETTY_FUNCTION__); } if (d && d->conference) { d->conference = sccp_refcount_release(d->conference, __FILE__, __LINE__, __PRETTY_FUNCTION__); } #endif // CS_SCCP_CONFERENCE if (c->rtp.audio.rtp || c->rtp.video.rtp) { if (d && SKINNY_DEVICE_RS_OK == d->registrationState) { sccp_channel_closereceivechannel(c); } sccp_rtp_destroy(c); } // removing scheduled dialing c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Current channel %s-%08x state %s(%d)\n", (d) ? DEV_ID_LOG(d) : "(null)", l ? l->name : "(null)", c->callid, sccp_indicate2str(c->state), c->state); /* end callforwards */ sccp_channel_t *channel; SCCP_LIST_LOCK(&l->channels); SCCP_LIST_TRAVERSE(&l->channels, channel, list) { if (channel->parentChannel == c) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: PBX Hangup cfwd channel %s-%08X\n", DEV_ID_LOG(d), l->name, channel->callid); /* No need to lock because c->line->channels is already locked. */ sccp_channel_endcall(channel); channel->parentChannel = sccp_channel_release(channel->parentChannel); // release from sccp_channel_forward_retain } } SCCP_LIST_UNLOCK(&l->channels); /* done - end callforwards */ /* cancel transfer if in progress */ sccp_channel_transfer_cancel(d, c); /* remove call from transferee, transferer */ sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { sccp_device_t *tmpDevice = NULL; if ((tmpDevice = sccp_device_retain(linedevice->device))) { sccp_channel_transfer_release(tmpDevice, c); sccp_device_release(tmpDevice); } } SCCP_LIST_UNLOCK(&l->devices); /* done - remove call from transferee, transferer */ sccp_line_removeChannel(l, c); if (!d) { /* channel is not answered, just ringin over all devices */ /* find the first the device on which it is registered and hangup that one (__sccp_indicate_remote_device will do the rest) */ sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { if (linedevice->device && SKINNY_DEVICE_RS_OK == linedevice->device->registrationState) { d = sccp_device_retain(linedevice->device); break; } } SCCP_LIST_UNLOCK(&l->devices); } else { d->monitorFeature.status &= ~SCCP_FEATURE_MONITOR_STATE_ACTIVE; sccp_log(DEBUGCAT_PBX) (VERBOSE_PREFIX_3 "%s: Reset monitor state after hangup\n", DEV_ID_LOG(d)); sccp_feat_changed(d, NULL, SCCP_FEATURE_MONITOR); } // else if (SKINNY_DEVICE_RS_OK != d->registrationState) { // c->state = SCCP_CHANNELSTATE_DOWN; // device is reregistering // } else { // /* // * Really neccessary? // * Test for 7910 (to remove the following line) // * (-DD) // */ // sccp_channel_send_callinfo(d, c); // sccp_pbx_needcheckringback(d); // sccp_dev_check_displayprompt(d); // } sccp_indicate(d, c, SCCP_CHANNELSTATE_ONHOOK); sccp_channel_clean(c); d = d ? sccp_device_release(d) : NULL; l = l ? sccp_line_release(l) : NULL; c = c ? sccp_channel_release(c) : NULL; return 0; } /*! * \brief Thread to check Device Ring Back * * The Auto Answer thread is started by ref sccp_pbx_needcheckringback if necessary * * \param d SCCP Device * * \lock * - device->session */ void sccp_pbx_needcheckringback(sccp_device_t * d) { if (d && d->session) { sccp_session_lock(d->session); d->session->needcheckringback = 1; sccp_session_unlock(d->session); } } /*! * \brief Answer an Asterisk Channel * \note we have no bridged channel at this point * * \param channel SCCCP channel * \return Success as int * * \callgraph * \callergraph * * \called_from_asterisk * * \todo masquarade does not succeed when forwarding to a dialplan extension which starts with PLAYBACK (Is this still the case, i think this might have been resolved ?? - DdG -) */ int sccp_pbx_answer(sccp_channel_t * channel) { sccp_channel_t *c = NULL; int res = 0; sccp_log((DEBUGCAT_PBX | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "SCCP: sccp_pbx_answer\n"); /* \todo perhaps we should lock channel here. */ if (!(c = sccp_channel_retain(channel))) return -1; sccp_log((DEBUGCAT_PBX | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: sccp_pbx_answer checking parent channel\n", c->currentDeviceId); if (c->parentChannel) { // containing a retained channel, final release at the end /* we are a forwarded call, bridge me with my parent */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_3 "%s: bridge me with my parent's channel %s\n", c->currentDeviceId, PBX(getChannelName) (c)); PBX_CHANNEL_TYPE *br = NULL, *astForwardedChannel = c->parentChannel->owner; if (PBX(getChannelAppl) (c)) { sccp_log((DEBUGCAT_PBX + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_answer) %s bridging to dialplan application %s\n", c->currentDeviceId, PBX(getChannelName) (c), PBX(getChannelAppl) (c)); } /* at this point we do not have a pointer to ou bridge channel so we search for it -MC */ const char *bridgePeerChannelName = pbx_builtin_getvar_helper(c->owner, "BRIDGEPEER"); if (!sccp_strlen_zero(bridgePeerChannelName)) { sccp_log((DEBUGCAT_PBX + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer) searching for bridgepeer by name: %s\n", bridgePeerChannelName); PBX(getChannelByName) (bridgePeerChannelName, &br); } /* did we find our bridge */ pbx_log(LOG_NOTICE, "SCCP: bridge: %s\n", (br) ? pbx_channel_name(br) : " -- no bridgepeer found -- "); if (br) { /* set the channel and the bridge to state UP to fix problem with fast pickup / autoanswer */ pbx_setstate(c->owner, AST_STATE_UP); pbx_setstate(br, AST_STATE_UP); sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer) Going to Masquerade %s into %s\n", pbx_channel_name(br), pbx_channel_name(astForwardedChannel)); if (!pbx_channel_masquerade(astForwardedChannel, br)) { sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer) Masqueraded into %s\n", pbx_channel_name(astForwardedChannel)); sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) bridged. channel state: ast %s\n", pbx_state2str(pbx_channel_state(c->owner))); sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) bridged. channel state: astForwardedChannel %s\n", pbx_state2str(pbx_channel_state(astForwardedChannel))); sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) bridged. channel state: br %s\n", pbx_state2str(pbx_channel_state(br))); sccp_log((DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) ============================================== \n"); #if ASTERISK_VERSION_GROUP > 106 // pbx_indicate(c->owner, AST_CONTROL_REDIRECTING); // hangling should be implemented in pbx_impl like connectedline pbx_indicate(br, AST_CONTROL_CONNECTED_LINE); #endif } else { pbx_log(LOG_ERROR, "(sccp_pbx_answer) Failed to masquerade bridge into forwarded channel\n"); res = -1; } } else { /* we have no bridge and can not make a masquerade -> end call */ sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) no bridge. channel state: ast %s\n", pbx_state2str(pbx_channel_state(c->owner))); sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) no bridge. channel state: astForwardedChannel %s\n", pbx_state2str(pbx_channel_state(astForwardedChannel))); sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_4 "(sccp_pbx_answer: call forward) ============================================== \n"); if (pbx_channel_state(c->owner) == AST_STATE_RING && pbx_channel_state(astForwardedChannel) == AST_STATE_DOWN && PBX(getChannelPbx) (c)) { sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_4 "SCCP: Receiver Hungup: (hasPBX: %s)\n", PBX(getChannelPbx) (c) ? "yes" : "no"); pbx_channel_set_hangupcause(astForwardedChannel, AST_CAUSE_CALL_REJECTED); pbx_queue_hangup(astForwardedChannel); } else { pbx_log(LOG_ERROR, "%s: We did not find bridge channel for call forwarding call. Hangup\n", c->currentDeviceId); pbx_channel_set_hangupcause(astForwardedChannel, AST_CAUSE_REQUESTED_CHAN_UNAVAIL); pbx_queue_hangup(astForwardedChannel); sccp_channel_endcall(c); res = -1; } } c->parentChannel = sccp_channel_release(c->parentChannel); // release parentChannel from sccp_channel_forward_retain // FINISH } else { sccp_device_t *d = NULL; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_answer) Outgoing call %s has been answered on %s@%s\n", c->currentDeviceId, PBX(getChannelName) (c), c->line->name, c->currentDeviceId); sccp_channel_updateChannelCapability(c); /*! \todo This seems like brute force, and doesn't seem to be of much use. However, I want it to be remebered as I have forgotten what my actual motivation was for writing this strange code. (-DD) */ if ((d = sccp_channel_getDevice_retained(c))) { sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_indicate(d, c, SCCP_CHANNELSTATE_PROCEED); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTED); /** check for monitor request */ if (d && (d->monitorFeature.status & SCCP_FEATURE_MONITOR_STATE_REQUESTED) && !(d->monitorFeature.status & SCCP_FEATURE_MONITOR_STATE_ACTIVE)) { pbx_log(LOG_NOTICE, "%s: request monitor\n", d->id); sccp_feat_monitor(d, c->line, 0, c); } d = sccp_device_release(d); } if (c->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE) { PBX(queue_control) (c->owner, AST_CONTROL_VIDUPDATE); } // FINISH } //FINISH: c = sccp_channel_release(c); return res; } /*! * \brief Allocate an Asterisk Channel * \param c SCCP Channel * \param linkedId PBX LinkedId which unites related calls under one particular id * \return 1 on Success as uint8_t * * \callgraph * \callergraph * * \lock * - line->devices * - channel * - line * - see sccp_channel_updateChannelCapability() * - usecnt_lock */ uint8_t sccp_pbx_channel_allocate(sccp_channel_t * c, const char *linkedId) { PBX_CHANNEL_TYPE *tmp; if (!(c = sccp_channel_retain(c))) { return -1; } sccp_line_t *l = sccp_line_retain(c->line); sccp_device_t *d = NULL; #ifndef CS_AST_CHANNEL_HAS_CID char cidtmp[256]; memset(&cidtmp, 0, sizeof(cidtmp)); #endif // CS_AST_CHANNEL_HAS_CID sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: try to allocate channel \n"); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: Line: %s\n", l->name); if (!l) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Unable to allocate asterisk channel %s\n", l->name); pbx_log(LOG_ERROR, "SCCP: Unable to allocate asterisk channel\n"); sccp_channel_release(c); return 0; } // /* Don't hold a sccp pvt lock while we allocate a channel */ if ((d = sccp_channel_getDevice_retained(c))) { sccp_linedevices_t *linedevice; SCCP_LIST_LOCK(&l->devices); SCCP_LIST_TRAVERSE(&l->devices, linedevice, list) { if (linedevice->device == d) break; } SCCP_LIST_UNLOCK(&l->devices); switch (c->calltype) { case SKINNY_CALLTYPE_INBOUND: /* append subscriptionId to cid */ if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.number)) { sprintf(c->callInfo.calledPartyNumber, "%s%s", l->cid_num, linedevice->subscriptionId.number); } else { sprintf(c->callInfo.calledPartyNumber, "%s%s", l->cid_num, (l->defaultSubscriptionId.number) ? l->defaultSubscriptionId.number : ""); } if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.name)) { sprintf(c->callInfo.calledPartyName, "%s%s", l->cid_name, linedevice->subscriptionId.name); } else { sprintf(c->callInfo.calledPartyName, "%s%s", l->cid_name, (l->defaultSubscriptionId.name) ? l->defaultSubscriptionId.name : ""); } break; case SKINNY_CALLTYPE_FORWARD: case SKINNY_CALLTYPE_OUTBOUND: /* append subscriptionId to cid */ if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.number)) { sprintf(c->callInfo.callingPartyNumber, "%s%s", l->cid_num, linedevice->subscriptionId.number); } else { sprintf(c->callInfo.callingPartyNumber, "%s%s", l->cid_num, (l->defaultSubscriptionId.number) ? l->defaultSubscriptionId.number : ""); } if (linedevice && !sccp_strlen_zero(linedevice->subscriptionId.name)) { sprintf(c->callInfo.callingPartyName, "%s%s", l->cid_name, linedevice->subscriptionId.name); } else { sprintf(c->callInfo.callingPartyName, "%s%s", l->cid_name, (l->defaultSubscriptionId.name) ? l->defaultSubscriptionId.name : ""); } break; } } else { switch (c->calltype) { case SKINNY_CALLTYPE_INBOUND: sprintf(c->callInfo.calledPartyNumber, "%s%s", l->cid_num, (l->defaultSubscriptionId.number) ? l->defaultSubscriptionId.number : ""); sprintf(c->callInfo.calledPartyName, "%s%s", l->cid_name, (l->defaultSubscriptionId.name) ? l->defaultSubscriptionId.name : ""); break; case SKINNY_CALLTYPE_FORWARD: case SKINNY_CALLTYPE_OUTBOUND: sprintf(c->callInfo.callingPartyNumber, "%s%s", l->cid_num, (l->defaultSubscriptionId.number) ? l->defaultSubscriptionId.number : ""); sprintf(c->callInfo.callingPartyName, "%s%s", l->cid_name, (l->defaultSubscriptionId.name) ? l->defaultSubscriptionId.name : ""); break; } } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: cid_num: \"%s\"\n", c->callInfo.callingPartyNumber); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: cid_name: \"%s\"\n", c->callInfo.callingPartyName); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: accountcode: \"%s\"\n", l->accountcode); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: exten: \"%s\"\n", c->dialedNumber); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: context: \"%s\"\n", l->context); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: amaflags: \"%d\"\n", l->amaflags); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: chan/call: \"%s-%08x\"\n", l->name, c->callid); /* This should definitely fix CDR */ // tmp = pbx_channel_alloc(1, AST_STATE_DOWN, c->callInfo.callingPartyNumber, c->callInfo.callingPartyName, l->accountcode, c->dialedNumber, l->context, l->amaflags, "SCCP/%s-%08x", l->name, c->callid); PBX(alloc_pbxChannel) (c, &tmp, linkedId); if (!tmp) { pbx_log(LOG_ERROR, "%s: Unable to allocate asterisk channel on line %s\n", l->id, l->name); c = sccp_channel_release(c); l = l ? sccp_line_release(l) : NULL; d = d ? sccp_device_release(d) : NULL; return 0; } sccp_channel_updateChannelCapability(c); PBX(set_nativeAudioFormats) (c, c->preferences.audio, 1); //! \todo check locking /* \todo we should remove this shit. */ char tmpName[StationMaxNameSize]; snprintf(tmpName, sizeof(tmpName), "SCCP/%s-%08x", l->name, c->callid); PBX(setChannelName) (c, tmpName); pbx_jb_configure(tmp, &GLOB(global_jbconf)); // \todo: Bridge? // \todo: Transfer? sccp_mutex_lock(&GLOB(usecnt_lock)); GLOB(usecnt)++; sccp_mutex_unlock(&GLOB(usecnt_lock)); pbx_update_use_count(); if (PBX(set_callerid_number)) PBX(set_callerid_number) (c, c->callInfo.callingPartyNumber); if (PBX(set_callerid_name)) PBX(set_callerid_name) (c, c->callInfo.callingPartyName); /* asterisk needs the native formats bevore dialout, otherwise the next channel gets the whole AUDIO_MASK as requested format * chan_sip dont like this do sdp processing */ // PBX(set_nativeAudioFormats)(c, c->preferences.audio, ARRAY_LEN(c->preferences.audio)); // export sccp informations in asterisk dialplan if (d) { pbx_builtin_setvar_helper(tmp, "SCCP_DEVICE_MAC", d->id); pbx_builtin_setvar_helper(tmp, "SCCP_DEVICE_IP", pbx_inet_ntoa(d->session->sin.sin_addr)); pbx_builtin_setvar_helper(tmp, "SCCP_DEVICE_TYPE", devicetype2str(d->skinny_type)); } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Allocated asterisk channel %s-%d\n", (l) ? l->id : "(null)", (l) ? l->name : "(null)", c->callid); c = sccp_channel_release(c); l = l ? sccp_line_release(l) : NULL; d = d ? sccp_device_release(d) : NULL; return 1; } /*! * \brief Schedule Asterisk Dial * \param data Data as constant * \return Success as int * * \called_from_asterisk */ int sccp_pbx_sched_dial(const void *data) { sccp_channel_t *c = NULL; if ((c = sccp_channel_retain((sccp_channel_t *) data))) { if (c->owner && !PBX(getChannelPbx) (c)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: Timeout for call '%d'. Going to dial '%s'\n", c->callid, c->dialedNumber); sccp_pbx_softswitch(c); } c = sccp_channel_release(c); } return 0; } /*! * \brief Asterisk Helper * \param c SCCP Channel as sccp_channel_t * \return Success as int */ sccp_extension_status_t sccp_pbx_helper(sccp_channel_t * c) { sccp_extension_status_t extensionStatus; sccp_device_t *d = NULL; if (!sccp_strlen_zero(c->dialedNumber)) { if (GLOB(recorddigittimeoutchar) && GLOB(digittimeoutchar) == c->dialedNumber[strlen(c->dialedNumber) - 1]) { /* we finished dialing with digit timeout char */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: We finished dialing with digit timeout char %s\n", c->dialedNumber); return SCCP_EXTENSION_EXACTMATCH; } } if ((c->ss_action != SCCP_SS_GETCBARGEROOM) && (c->ss_action != SCCP_SS_GETMEETMEROOM) #ifdef CS_SCCP_CONFERENCE && (c->ss_action != SCCP_SS_GETCONFERENCEROOM) #endif ) { //! \todo check overlap feature status -MC extensionStatus = PBX(extension_status) (c); if ((d = sccp_channel_getDevice_retained(c))) { if (((d->overlapFeature.enabled && !extensionStatus) || (!d->overlapFeature.enabled && !extensionStatus)) && ((d->overlapFeature.enabled && !extensionStatus) || (!d->overlapFeature.enabled && !extensionStatus))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: %s Matches More\n", c->dialedNumber); d = sccp_device_release(d); return SCCP_EXTENSION_MATCHMORE; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: %s Match %s\n", c->dialedNumber, extensionStatus == SCCP_EXTENSION_EXACTMATCH ? "Exactly" : "More"); d = sccp_device_release(d); } return extensionStatus; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "SCCP: %s Does Exists\n", c->dialedNumber); return SCCP_EXTENSION_NOTEXISTS; } /*! * \brief Handle Soft Switch * \param channel SCCP Channel as sccp_channel_t * \todo clarify Soft Switch Function * * \lock * - channel * - see sccp_pbx_senddigits() * - see sccp_channel_set_calledparty() * - see sccp_indicate_nolock() * - channel * - see sccp_line_cfwd() * - see sccp_indicate_nolock() * - see sccp_device_sendcallstate() * - see sccp_channel_send_callinfo() * - see sccp_dev_clearprompt() * - see sccp_dev_displayprompt() * - see sccp_feat_meetme_start() * - see PBX(set_callstate)() * - see pbx_pbx_start() * - see sccp_indicate_nolock() * - see manager_event() */ void *sccp_pbx_softswitch(sccp_channel_t * channel) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; sccp_line_t *l = NULL; PBX_CHANNEL_TYPE *pbx_channel = NULL; PBX_VARIABLE_TYPE *v = NULL; if (!(c = sccp_channel_retain(channel))) { pbx_log(LOG_ERROR, "SCCP: (sccp_pbx_softswitch) No <channel> available. Returning from dial thread.\n"); goto EXIT_FUNC; } /* Reset Enbloc Dial Emulation */ c->enbloc.deactivate = 0; c->enbloc.totaldigittime = 0; c->enbloc.totaldigittimesquared = 0; c->enbloc.digittimeout = GLOB(digittimeout) * 1000; /* prevent softswitch from being executed twice (Pavel Troller / 15-Oct-2010) */ if (PBX(getChannelPbx) (c)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (sccp_pbx_softswitch) PBX structure already exists. Dialing instead of starting.\n"); /* If there are any digits, send them instead of starting the PBX */ if (!sccp_strlen_zero(c->dialedNumber)) { sccp_pbx_senddigits(c, c->dialedNumber); sccp_channel_set_calledparty(c, "", c->dialedNumber); if ((d = sccp_channel_getDevice_retained(c))) { sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); d = sccp_device_release(d); } } goto EXIT_FUNC; } if (c->owner) { pbx_channel = ast_channel_ref(c->owner); } /* removing scheduled dialing */ c->scheduler.digittimeout = SCCP_SCHED_DEL(c->scheduler.digittimeout); /* we should just process outbound calls, let's check calltype */ if (c->calltype != SKINNY_CALLTYPE_OUTBOUND) { pbx_log(LOG_ERROR, "SCCP: (sccp_pbx_softswitch) This function is for outbound calls only. Exiting\n"); goto EXIT_FUNC; } /* assume d is the channel's device */ /* does it exists ? */ if (!(d = sccp_channel_getDevice_retained(c))) { pbx_log(LOG_ERROR, "SCCP: (sccp_pbx_softswitch) No <device> available. Returning from dial thread. Exiting\n"); goto EXIT_FUNC; } /* we don't need to check for a device type but just if the device has an id, otherwise back home -FS */ if (!d->id || sccp_strlen_zero(d->id)) { pbx_log(LOG_ERROR, "SCCP: (sccp_pbx_softswitch) No <device> identifier available. Returning from dial thread. Exiting\n"); goto EXIT_FUNC; } if (!(l = sccp_line_retain(c->line))) { pbx_log(LOG_ERROR, "SCCP: (sccp_pbx_softswitch) No <line> available. Returning from dial thread. Exiting\n"); if (pbx_channel) { PBX(requestHangup) (pbx_channel); } goto EXIT_FUNC; } uint8_t instance = sccp_device_find_index_for_line(d, l->name); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) New call on line %s\n", DEV_ID_LOG(d), l->name); /* assign callerid name and number */ //sccp_channel_set_callingparty(c, l->cid_name, l->cid_num); // we use shortenedNumber but why ??? // If the timeout digit has been used to terminate the number // and this digit shall be included in the phone call history etc (recorddigittimeoutchar is true) // we still need to dial the number without the timeout char in the pbx // so that we don't dial strange extensions with a trailing characters. char shortenedNumber[256] = { '\0' }; sccp_copy_string(shortenedNumber, c->dialedNumber, sizeof(shortenedNumber)); unsigned int len = strlen(shortenedNumber); assert(strlen(c->dialedNumber) == len); if (len > 0 && GLOB(digittimeoutchar) == shortenedNumber[len - 1]) { shortenedNumber[len - 1] = '\0'; // If we don't record the timeoutchar in the logs, we remove it from the sccp channel structure // Later, the channel dialed number is used for directories, etc., // and the shortened number is used for dialing the actual call via asterisk pbx. if (!GLOB(recorddigittimeoutchar)) { c->dialedNumber[len - 1] = '\0'; } } /* This will choose what to do */ switch (c->ss_action) { case SCCP_SS_GETFORWARDEXTEN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Get Forward Extension\n", d->id); if (!sccp_strlen_zero(shortenedNumber)) { sccp_line_cfwd(l, d, c->ss_data, shortenedNumber); } sccp_channel_endcall(c); goto EXIT_FUNC; // leave simple switch without dial #ifdef CS_SCCP_PICKUP case SCCP_SS_GETPICKUPEXTEN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Get Pickup Extension\n", d->id); // like we're dialing but we're not :) sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); sccp_dev_clearprompt(d, instance, c->callid); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CALL_PROCEED, 0); if (!sccp_strlen_zero(shortenedNumber)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: (sccp_pbx_softswitch) Asterisk request to pickup exten '%s'\n", shortenedNumber); if (sccp_feat_directed_pickup(c, shortenedNumber)) { sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDNUMBER); } } else { // without a number we can also close the call. Isn't it true ? sccp_channel_endcall(c); } goto EXIT_FUNC; // leave simpleswitch without dial #endif // CS_SCCP_PICKUP #ifdef CS_SCCP_CONFERENCE case SCCP_SS_GETCONFERENCEROOM: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Conference request\n", d->id); if (c->owner && !pbx_check_hangup(c->owner)) { sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_setSkinnyCallstate(c, SKINNY_CALLSTATE_PROCEED); PBX(set_callstate) (channel, AST_STATE_UP); if (!d->conference) { d->conference = sccp_conference_create(d, c); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTEDCONFERENCE); } else { pbx_log(LOG_NOTICE, "%s: There is already a conference running on this device.\n", DEV_ID_LOG(d)); sccp_channel_endcall(c); goto EXIT_FUNC; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Start Conference\n", d->id); sccp_feat_conference_start(d, l, instance, c); } goto EXIT_FUNC; #endif case SCCP_SS_GETMEETMEROOM: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Meetme request\n", d->id); if (!sccp_strlen_zero(shortenedNumber) && !sccp_strlen_zero(c->line->meetmenum)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Meetme request for room '%s' on extension '%s'\n", d->id, shortenedNumber, c->line->meetmenum); if (c->owner && !pbx_check_hangup(c->owner)) pbx_builtin_setvar_helper(c->owner, "SCCP_MEETME_ROOM", shortenedNumber); sccp_copy_string(shortenedNumber, c->line->meetmenum, sizeof(shortenedNumber)); //sccp_copy_string(c->dialedNumber, SKINNY_DISP_CONFERENCE, sizeof(c->dialedNumber)); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Start Meetme Thread\n", d->id); sccp_feat_meetme_start(c); /* Copied from Federico Santulli */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Meetme Thread Started\n", d->id); goto EXIT_FUNC; } else { // without a number we can also close the call. Isn't it true ? sccp_channel_endcall(c); goto EXIT_FUNC; } break; case SCCP_SS_GETBARGEEXTEN: // like we're dialing but we're not :) sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Get Barge Extension\n", d->id); sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); sccp_dev_clearprompt(d, instance, c->callid); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CALL_PROCEED, 0); if (!sccp_strlen_zero(shortenedNumber)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Device request to barge exten '%s'\n", d->id, shortenedNumber); if (sccp_feat_barge(c, shortenedNumber)) { sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDNUMBER); } } else { // without a number we can also close the call. Isn't it true ? sccp_channel_endcall(c); } goto EXIT_FUNC; // leave simpleswitch without dial case SCCP_SS_GETCBARGEROOM: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Get Conference Barge Extension\n", d->id); // like we're dialing but we're not :) sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); sccp_dev_clearprompt(d, instance, c->callid); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CALL_PROCEED, 0); if (!sccp_strlen_zero(shortenedNumber)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Device request to barge conference '%s'\n", d->id, shortenedNumber); if (sccp_feat_cbarge(c, shortenedNumber)) { sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDNUMBER); } } else { // without a number we can also close the call. Isn't it true ? sccp_channel_endcall(c); } goto EXIT_FUNC; // leave simpleswitch without dial case SCCP_SS_DIAL: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: (sccp_pbx_softswitch) Dial Extension\n", d->id); break; } /* set private variable */ if (pbx_channel && !pbx_check_hangup(pbx_channel)) { sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "SCCP: (sccp_pbx_softswitch) set variable SKINNY_PRIVATE to: %s\n", c->privacy ? "1" : "0"); if (c->privacy) { //pbx_channel->cid.cid_pres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; sccp_channel_set_calleridPresenceParameter(c, CALLERID_PRESENCE_FORBIDDEN); } uint32_t result = d->privacyFeature.status & SCCP_PRIVACYFEATURE_CALLPRESENT; result |= c->privacy; if (d->privacyFeature.enabled && result) { sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "SCCP: (sccp_pbx_softswitch) set variable SKINNY_PRIVATE to: %s\n", "1"); pbx_builtin_setvar_helper(pbx_channel, "SKINNY_PRIVATE", "1"); } else { sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "SCCP: (sccp_pbx_softswitch) set variable SKINNY_PRIVATE to: %s\n", "0"); pbx_builtin_setvar_helper(pbx_channel, "SKINNY_PRIVATE", "0"); } } /* set devicevariables */ v = ((d) ? d->variables : NULL); while (pbx_channel && !pbx_check_hangup(pbx_channel) && d && v) { pbx_builtin_setvar_helper(pbx_channel, v->name, v->value); v = v->next; } /* set linevariables */ v = ((l) ? l->variables : NULL); while (pbx_channel && !pbx_check_hangup(pbx_channel) && l && v) { pbx_builtin_setvar_helper(pbx_channel, v->name, v->value); v = v->next; } PBX(setChannelExten) (c, shortenedNumber); sccp_copy_string(d->lastNumber, c->dialedNumber, sizeof(d->lastNumber)); sccp_softkey_setSoftkeyState(d, KEYMODE_ONHOOK, SKINNY_LBL_REDIAL, TRUE); /** enable redial key */ sccp_channel_set_calledparty(c, "", shortenedNumber); /* The 7961 seems to need the dialing callstate to record its directories information. */ sccp_indicate(d, c, SCCP_CHANNELSTATE_DIALING); /* proceed call state is needed to display the called number. The phone will not display callinfo in offhook state */ sccp_device_sendcallstate(d, instance, c->callid, SKINNY_CALLSTATE_PROCEED, SKINNY_CALLPRIORITY_LOW, SKINNY_CALLINFO_VISIBILITY_DEFAULT); sccp_channel_send_callinfo(d, c); sccp_dev_clearprompt(d, instance, c->callid); sccp_dev_displayprompt(d, instance, c->callid, SKINNY_DISP_CALL_PROCEED, 0); /*! \todo DdG: Extra wait time is incurred when checking pbx_exists_extension, when a wrong number is dialed. storing extension_exists status for sccp_log use */ int extension_exists = SCCP_EXTENSION_NOTEXISTS; if (!sccp_strlen_zero(shortenedNumber) && (pbx_channel && !pbx_check_hangup(pbx_channel)) /* && (extension_exists = pbx_exists_extension(pbx_channel, pbx_channel_context(pbx_channel), shortenedNumber, 1, l->cid_num)) */ && ((extension_exists = PBX(extension_status(c)) != SCCP_EXTENSION_NOTEXISTS)) ) { /* found an extension, let's dial it */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_1 "%s: (sccp_pbx_softswitch) channel %s-%08x is dialing number %s\n", DEV_ID_LOG(d), l->name, c->callid, shortenedNumber); /* Answer dialplan command works only when in RINGING OR RING ast_state */ PBX(set_callstate) (c, AST_STATE_RING); int8_t pbxStartResult = pbx_pbx_start(pbx_channel); /* \todo replace AST_PBX enum using pbx_impl wrapper enum */ switch (pbxStartResult) { case AST_PBX_FAILED: pbx_log(LOG_ERROR, "%s: (sccp_pbx_softswitch) channel %s-%08x failed to start new thread to dial %s\n", DEV_ID_LOG(d), l->name, c->callid, shortenedNumber); /* \todo change indicate to something more suitable */ sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDNUMBER); break; case AST_PBX_CALL_LIMIT: pbx_log(LOG_WARNING, "%s: (sccp_pbx_softswitch) call limit reached for channel %s-%08x failed to start new thread to dial %s\n", DEV_ID_LOG(d), l->name, c->callid, shortenedNumber); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); break; default: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "%s: (sccp_pbx_softswitch) pbx started\n", DEV_ID_LOG(d)); #ifdef CS_MANAGER_EVENTS if (GLOB(callevents)) { manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate", "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSCCPdevice: %s\r\nSCCPline: %s\r\nSCCPcallid: %s\r\n", (pbx_channel) ? pbx_channel_name(pbx_channel) : "(null)", (pbx_channel) ? pbx_channel_uniqueid(pbx_channel) : "(null)", "SCCP", (d) ? DEV_ID_LOG(d) : "(null)", (l && l->name) ? l->name : "(null)", (c && c->callid) ? (char *) &c->callid : "(null)"); } #endif break; } } else { sccp_log(DEBUGCAT_PBX) (VERBOSE_PREFIX_1 "%s: (sccp_pbx_softswitch) channel %s-%08x shortenedNumber: %s, pbx_check_hangup(chan): %d, extension exists: %s\n", DEV_ID_LOG(d), l->name, c->callid, shortenedNumber, pbx_check_hangup(pbx_channel), (extension_exists != SCCP_EXTENSION_NOTEXISTS) ? "TRUE" : "FALSE"); pbx_log(LOG_NOTICE, "%s: Call from '%s' to extension '%s', rejected because the extension could not be found in context '%s'\n", DEV_ID_LOG(d), l->name, shortenedNumber, pbx_channel_context(pbx_channel)); /* timeout and no extension match */ sccp_indicate(d, c, SCCP_CHANNELSTATE_INVALIDNUMBER); } sccp_log((DEBUGCAT_PBX | DEBUGCAT_DEVICE)) (VERBOSE_PREFIX_1 "%s: (sccp_pbx_softswitch) quit\n", DEV_ID_LOG(d)); EXIT_FUNC: if (pbx_channel) { ast_channel_unref(pbx_channel); } l = l ? sccp_line_release(l) : NULL; c = c ? sccp_channel_release(c) : NULL; d = d ? sccp_device_release(d) : NULL; return NULL; } /*! * \brief Send Digit to Asterisk * \param c SCCP Channel * \param digit Digit as char */ void sccp_pbx_senddigit(sccp_channel_t * c, char digit) { if (PBX(send_digit)) PBX(send_digit) (c, digit); } /*! * \brief Send Multiple Digits to Asterisk * \param c SCCP Channel * \param digits Multiple Digits as char */ void sccp_pbx_senddigits(sccp_channel_t * c, const char *digits) { if (PBX(send_digits)) PBX(send_digits) (c, digits); } /*! * \brief Handle Dialplan Transfer * * This will allow asterisk to transfer an SCCP Channel via the dialplan transfer function * * \param ast Asterisk Channel * \param dest Destination as char * * \return result as int * * \test Dialplan Transfer Needs to be tested * \todo pbx_transfer needs to be implemented correctly * * \called_from_asterisk */ int sccp_pbx_transfer(PBX_CHANNEL_TYPE * ast, const char *dest) { int res = 0; sccp_channel_t *c; if (dest == NULL) { /* functions below do not take a NULL */ dest = ""; return -1; } c = get_sccp_channel_from_pbx_channel(ast); if (!c) { return -1; } /* sccp_device_t *d; sccp_channel_t *newcall; */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_1 "Transferring '%s' to '%s'\n", PBX(getChannelName) (c), dest); if (pbx_channel_state(ast) == AST_STATE_RING) { //! \todo Blindtransfer needs to be implemented correctly /* res = sccp_blindxfer(p, dest); */ res = -1; } else { //! \todo Transfer needs to be implemented correctly /* res=sccp_channel_transfer(p,dest); */ res = -1; } c = sccp_channel_release(c); return res; } /** * \brief Get Peer Codec Capabilies * \param channel SCCP Channel * \param capabilities Codec Capabilities * * \note Variable capabilities will be malloced by function, caller must destroy this later */ /* int sccp_pbx_getPeerCodecCapabilities(sccp_channel_t * channel, void **capabilities) { // sccp_channel_t *peer; PBX(getPeerCodecCapabilities) (channel, capabilities); return 1; } */ #endif
722,270
./chan-sccp-b/src/pbx_impl/pbx_impl.c
/*! * \file pbx_impl.c * \brief SCCP PBX Asterisk Wrapper Class * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #ifndef __PBX_IMPL_C #define __PBX_IMPL_C #include <config.h> #include "../common.h" SCCP_FILE_VERSION(__FILE__, "$Revision: 2278 $") #endif
722,271
./chan-sccp-b/src/pbx_impl/ast/ast106.c
/*! * \file ast106.c * \brief SCCP PBX Asterisk Wrapper Class * \author Marcello Ceshia * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #include <config.h> #include "../../common.h" #include "ast106.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include <asterisk/sched.h> #include <asterisk/netsock.h> #define new avoid_cxx_new_keyword #include <asterisk/rtp.h> #undef new #ifndef CS_AST_RTP_INSTANCE_NEW #define ast_rtp_instance_read(_x, _y) ast_rtp_read(_x) #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif struct sched_context *sched = 0; struct io_context *io = 0; #define SCCP_AST_LINKEDID_HELPER "LINKEDID" //static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_request(const char *type, format_t format, const PBX_CHANNEL_TYPE * requestor, void *data, int *cause); static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_request(const char *type, int format, void *data, int *cause); static int sccp_wrapper_asterisk16_call(PBX_CHANNEL_TYPE * chan, char *addr, int timeout); static int sccp_wrapper_asterisk16_answer(PBX_CHANNEL_TYPE * chan); static PBX_FRAME_TYPE *sccp_wrapper_asterisk16_rtp_read(PBX_CHANNEL_TYPE * ast); static int sccp_wrapper_asterisk16_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame); static int sccp_wrapper_asterisk16_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen); static int sccp_wrapper_asterisk16_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan); static enum ast_bridge_result sccp_wrapper_asterisk16_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms); static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text); static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit); static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration); static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen); int sccp_wrapper_asterisk16_hangup(PBX_CHANNEL_TYPE * ast_channel); boolean_t sccp_wrapper_asterisk16_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId); int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control); int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen); boolean_t sccp_asterisk_getForwarderPeerChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel); static int sccp_wrapper_asterisk16_devicestate(void *data); PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context); #if defined(__cplusplus) || defined(c_plusplus) /*! * \brief SCCP Tech Structure */ static struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, description: "Skinny Client Control Protocol (SCCP)", capabilities: AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_SLINEAR16 | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A | AST_FORMAT_H264 | AST_FORMAT_H263_PLUS, properties: AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, requester: sccp_wrapper_asterisk16_request, devicestate: sccp_wrapper_asterisk16_devicestate, send_digit_begin: sccp_wrapper_recvdigit_begin, send_digit_end: sccp_wrapper_recvdigit_end, call: sccp_wrapper_asterisk16_call, hangup: sccp_wrapper_asterisk16_hangup, answer: sccp_wrapper_asterisk16_answer, read: sccp_wrapper_asterisk16_rtp_read, write: sccp_wrapper_asterisk16_rtp_write, send_text: sccp_pbx_sendtext, send_image: NULL, send_html: sccp_pbx_sendHTML, exception: NULL, bridge: sccp_wrapper_asterisk16_rtpBridge, early_bridge: NULL, indicate: sccp_wrapper_asterisk16_indicate, fixup: sccp_wrapper_asterisk16_fixup, setoption: NULL, queryoption: NULL, transfer: NULL, write_video: sccp_wrapper_asterisk16_rtp_write, write_text: NULL, bridged_channel: NULL, func_channel_read: sccp_wrapper_asterisk_channel_read, func_channel_write: sccp_asterisk_pbx_fktChannelWrite, get_base_channel: NULL, set_base_channel: NULL, /* *INDENT-ON* */ }; #else /*! * \brief SCCP Tech Structure */ const struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .description = "Skinny Client Control Protocol (SCCP)", // we could use the skinny_codec = ast_codec mapping here to generate the list of capabilities .capabilities = AST_FORMAT_SLINEAR16 | AST_FORMAT_SLINEAR | AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A, .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, .requester = sccp_wrapper_asterisk16_request, .devicestate = sccp_wrapper_asterisk16_devicestate, .call = sccp_wrapper_asterisk16_call, .hangup = sccp_wrapper_asterisk16_hangup, .answer = sccp_wrapper_asterisk16_answer, .read = sccp_wrapper_asterisk16_rtp_read, .write = sccp_wrapper_asterisk16_rtp_write, .write_video = sccp_wrapper_asterisk16_rtp_write, .indicate = sccp_wrapper_asterisk16_indicate, .fixup = sccp_wrapper_asterisk16_fixup, .transfer = sccp_pbx_transfer, .bridge = sccp_wrapper_asterisk16_rtpBridge, //.early_bridge = ast_rtp_early_bridge, //.bridged_channel = .send_text = sccp_pbx_sendtext, .send_html = sccp_pbx_sendHTML, //.send_html = //.send_image = .func_channel_read = sccp_wrapper_asterisk_channel_read, .func_channel_write = sccp_asterisk_pbx_fktChannelWrite, .send_digit_begin = sccp_wrapper_recvdigit_begin, .send_digit_end = sccp_wrapper_recvdigit_end, //.write_text = //.write_video = //.cc_callback = // ccss, new >1.6.0 //.exception = // new >1.6.0 // .setoption = sccp_wrapper_asterisk16_setOption, //.queryoption = // new >1.6.0 //.get_pvt_uniqueid = sccp_pbx_get_callid, // new >1.6.0 //.get_base_channel = //.set_base_channel = /* *INDENT-ON* */ }; #endif static int sccp_wrapper_asterisk16_devicestate(void *data) { int res = AST_DEVICE_UNKNOWN; char *lineName = (char *) data; char *deviceId = NULL; sccp_channelstate_t state; if ((deviceId = strchr(lineName, '@'))) { *deviceId = '\0'; deviceId++; } state = sccp_hint_getLinestate(lineName, deviceId); switch (state) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: res = AST_DEVICE_NOT_INUSE; break; case SCCP_CHANNELSTATE_RINGING: #ifdef CS_AST_DEVICE_RINGING res = AST_DEVICE_RINGING; break; #endif case SCCP_CHANNELSTATE_HOLD: res = AST_DEVICE_INUSE; break; case SCCP_CHANNELSTATE_INVALIDNUMBER: res = AST_DEVICE_INVALID; break; case SCCP_CHANNELSTATE_BUSY: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_DND: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: res = AST_DEVICE_UNAVAILABLE; break; case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_PROGRESS: #ifdef CS_AST_DEVICE_RINGING res = AST_DEVICE_RINGING; break; #endif case SCCP_CHANNELSTATE_CALLWAITING: case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: res = AST_DEVICE_INUSE; break; } sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: (sccp_asterisk_devicestate) PBX requests state for '%s' - state %s\n", (char *) lineName, ast_devstate2str(res)); return res; } /*! * \brief Convert an array of skinny_codecs (enum) to ast_codec_prefs * * \param skinny_codecs Array of Skinny Codecs * \param astCodecPref Array of PBX Codec Preferences * * \return bit array fmt/Format of ast_format_type (int) * * \todo check bitwise operator (not sure) - DdG */ int skinny_codecs2pbx_codec_pref(skinny_codec_t * skinny_codecs, struct ast_codec_pref *astCodecPref) { uint32_t i; int res_codec = 0; for (i = 1; i < SKINNY_MAX_CAPABILITIES; i++) { if (skinny_codecs[i]) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "adding codec to ast_codec_pref\n"); res_codec |= ast_codec_pref_append(astCodecPref, skinny_codec2pbx_codec(skinny_codecs[i])); } } return res_codec; } static boolean_t sccp_wrapper_asterisk16_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); #define RTP_NEW_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_new_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } #define RTP_CHANGE_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_change_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } static void get_skinnyFormats(format_t format, skinny_codec_t codecs[], size_t size) { unsigned int x; unsigned len = 0; if (!size) return; for (x = 0; x < ARRAY_LEN(skinny2pbx_codec_maps) && len <= size; x++) { if (skinny2pbx_codec_maps[x].pbx_codec & format) { codecs[len++] = skinny2pbx_codec_maps[x].skinny_codec; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "map ast codec " UI64FMT " to %d\n", (ULONG) (skinny2pbx_codec_maps[x].pbx_codec & format), skinny2pbx_codec_maps[x].skinny_codec); } } } /*************************************************************************************************************** CODEC **/ /*! \brief Get the name of a format * \note replacement for ast_getformatname * \param format id of format * \return A static string containing the name of the format or "unknown" if unknown. */ char *pbx_getformatname(format_t format) { return ast_getformatname(format); } /*! * \brief Get the names of a set of formats * \note replacement for ast_getformatname_multiple * \param buf a buffer for the output string * \param size size of buf (bytes) * \param format the format (combined IDs of codecs) * Prints a list of readable codec names corresponding to "format". * ex: for format=AST_FORMAT_GSM|AST_FORMAT_SPEEX|AST_FORMAT_ILBC it will return "0x602 (GSM|SPEEX|ILBC)" * \return The return value is buf. */ char *pbx_getformatname_multiple(char *buf, size_t size, format_t format) { return ast_getformatname_multiple(buf, size, format & AST_FORMAT_AUDIO_MASK); } /*! * \brief start monitoring thread of chan_sccp * \param data * * \lock * - monitor_lock */ void *sccp_do_monitor(void *data) { int res; /* This thread monitors all the interfaces which are not yet in use (and thus do not have a separate thread) indefinitely */ /* From here on out, we die whenever asked */ for (;;) { pthread_testcancel(); /* Wait for sched or io */ res = ast_sched_wait(sched); if ((res < 0) || (res > 1000)) { res = 1000; } res = ast_io_wait(io, res); if (res > 20) { ast_debug(1, "SCCP: ast_io_wait ran %d all at once\n", res); } ast_mutex_lock(&GLOB(monitor_lock)); res = ast_sched_runq(sched); if (res >= 20) { ast_debug(1, "SCCP: ast_sched_runq ran %d all at once\n", res); } ast_mutex_unlock(&GLOB(monitor_lock)); if (GLOB(monitor_thread) == AST_PTHREADT_STOP) { return 0; } } /* Never reached */ return NULL; } /*! * \brief Read from an Asterisk Channel * \param ast Asterisk Channel as ast_channel * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static PBX_FRAME_TYPE *sccp_wrapper_asterisk16_rtp_read(PBX_CHANNEL_TYPE * ast) { sccp_channel_t *c = NULL; PBX_FRAME_TYPE *frame = NULL; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) { // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return &ast_null_frame; } if (!c->rtp.audio.rtp) { // c = sccp_channel_release(c); return &ast_null_frame; } switch (ast->fdno) { case 0: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 0); /* RTP Audio */ break; case 1: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 1); /* RTCP Control Channel */ break; #ifdef CS_SCCP_VIDEO case 2: frame = ast_rtp_instance_read(c->rtp.video.rtp, 0); /* RTP Video */ break; case 3: frame = ast_rtp_instance_read(c->rtp.video.rtp, 1); /* RTCP Control Channel for video */ break; #endif default: break; } if (!frame) { pbx_log(LOG_WARNING, "%s: error reading frame == NULL\n", c->currentDeviceId); // c = sccp_channel_release(c); return &ast_null_frame; } else { //sccp_log((DEBUGCAT_CORE))(VERBOSE_PREFIX_3 "%s: read format: ast->fdno: %d, frametype: %d, %s(%d)\n", DEV_ID_LOG(c->device), ast->fdno, frame->frametype, pbx_getformatname(frame->subclass), frame->subclass); if (frame->frametype == AST_FRAME_VOICE) { #ifdef CS_SCCP_CONFERENCE if (c->conference && ast->readformat == AST_FORMAT_SLINEAR) { ast_set_read_format(ast, AST_FORMAT_SLINEAR); } #endif } } // c = sccp_channel_release(c); return frame; } static int sccp_wrapper_asterisk16_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { /* handle forwarded channel indications */ if (c->parentChannel) { PBX_CHANNEL_TYPE *bridgePeer; sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: forwarding indication %d to parentChannel %s (FORWARDED_FOR: %s)\n", ind, c->parentChannel->owner->name, pbx_builtin_getvar_helper(c->parentChannel->owner, "FORWARDER_FOR")); if (sccp_asterisk_getForwarderPeerChannel(c->parentChannel, &bridgePeer)) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: forwarding indication %d to caller %s\n", ind, bridgePeer->name); res = sccp_wrapper_asterisk16_indicate(bridgePeer, ind, data, datalen); ast_channel_unlock(bridgePeer); } else { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: cannot forward indication %d. bridgePeer not found\n", ind); } } else { ast_log(LOG_WARNING, "SCCP: (sccp_wrapper_asterisk16_indicate) Could not find device to handle indication, giving up.\n"); res = -1; } d = sccp_device_release(d); c = sccp_channel_release(c); return res; } if (c->state == SCCP_CHANNELSTATE_DOWN) { c = sccp_channel_release(c); d = sccp_device_release(d); return -1; } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Asterisk indicate '%d' condition on channel %s\n", (char *) c->currentDeviceId, ind, ast->name); /* when the rtp media stream is open we will let asterisk emulate the tones */ res = (((c->rtp.audio.readState != SCCP_RTP_STATUS_INACTIVE) || (d && d->earlyrtp)) ? -1 : 0); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: readStat: %d\n", (char *) c->currentDeviceId, c->rtp.audio.readState); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: res: %d\n", (char *) c->currentDeviceId, res); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: rtp?: %s\n", (char *) c->currentDeviceId, (c->rtp.audio.rtp) ? "yes" : "no"); switch (ind) { case AST_CONTROL_RINGING: if (SKINNY_CALLTYPE_OUTBOUND == c->calltype) { // Allow signalling of RINGOUT only on outbound calls. // Otherwise, there are some issues with late arrival of ringing // indications on ISDN calls (chan_lcr, chan_dahdi) (-DD). sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGOUT); } break; case AST_CONTROL_BUSY: sccp_indicate(d, c, SCCP_CHANNELSTATE_BUSY); break; case AST_CONTROL_CONGESTION: sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); break; case AST_CONTROL_PROGRESS: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROGRESS); res = -1; break; case AST_CONTROL_PROCEEDING: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROCEED); res = -1; break; case AST_CONTROL_SRCCHANGE: if (c->rtp.audio.rtp) ast_rtp_new_source(c->rtp.audio.rtp); res = 0; break; case AST_CONTROL_SRCUPDATE: /* Source media has changed. */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Source UPDATE request\n"); if (c->rtp.audio.rtp) { ast_rtp_change_source(c->rtp.audio.rtp); } res = 0; break; /* when the bridged channel hold/unhold the call we are notified here */ case AST_CONTROL_HOLD: sccp_asterisk_moh_start(ast, (const char *) data, c->musicclass); res = 0; break; case AST_CONTROL_UNHOLD: sccp_asterisk_moh_stop(ast); if (c->rtp.audio.rtp) { ast_rtp_new_source(c->rtp.audio.rtp); } res = 0; break; case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ if (c->rtp.video.rtp && d && sccp_device_isVideoSupported(d)) { d->protocol->sendFastPictureUpdate(d, c); res = 0; } else res = -1; break; #ifdef CS_AST_CONTROL_INCOMPLETE case AST_CONTROL_INCOMPLETE: /*!< Indication that the extension dialed is incomplete */ /* \todo implement dial continuation by: * - display message incomplete number * - adding time to channel->scheduler.digittimeout * - rescheduling sccp_pbx_sched_dial */ #ifdef CS_EXPERIMENTAL if (c->scheduler.digittimeout) { SCCP_SCHED_DEL(c->scheduler.digittimeout); } sccp_indicate(d, c, SCCP_CHANNELSTATE_DIGITSFOLL); c->scheduler.digittimeout = PBX(sched_add) (c->enbloc.digittimeout, sccp_pbx_sched_dial, c); #endif res = 0; break; #endif case -1: // Asterisk prod the channel res = -1; break; default: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Don't know how to indicate condition %d\n", ind); res = -1; } //ast_cond_signal(&c->astStateCond); d = sccp_device_release(d); c = sccp_channel_release(c); sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: send asterisk result %d\n", res); return res; } /*! * \brief Write to an Asterisk Channel * \param ast Channel as ast_channel * \param frame Frame as ast_frame * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static int sccp_wrapper_asterisk16_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame) { int res = 0; sccp_channel_t *c = NULL; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) { // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return -1; } switch (frame->frametype) { case AST_FRAME_VOICE: // checking for samples to transmit if (!frame->samples) { if (strcasecmp(frame->src, "ast_prod")) { pbx_log(LOG_ERROR, "%s: Asked to transmit frame type %d with no samples.\n", c->currentDeviceId, (int) frame->frametype); } else { // frame->samples == 0 when frame_src is ast_prod sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Asterisk prodded channel %s.\n", c->currentDeviceId, ast->name); if (c->parentChannel) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: forwarding prodding to parentChannel %s\n", c->parentChannel->owner->name); sccp_wrapper_asterisk16_rtp_write(c->parentChannel->owner, frame); } } } else if (!(frame->subclass & ast->nativeformats)) { // char s1[512], s2[512], s3[512]; // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "%s: Asked to transmit frame type %d, while native formats are %s(%lu) read/write = %s(%lu)/%s(%lu)\n", c->currentDeviceId, frame->subclass, pbx_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats), ast->nativeformats, pbx_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat), (uint64_t)ast->readformat, pbx_getformatname_multiple(s3, sizeof(s3) - 1, (uint64_t)ast->writeformat), (uint64_t)ast->writeformat); // //! \todo correct debugging // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "%s: Asked to transmit frame type %d, while native formats are %s(%lu) read/write = %s(%lu)/%s(%lu)\n", c->currentDeviceId, (int)frame->frametype, pbx_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats), ast->nativeformats, pbx_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat), (uint64_t)ast->readformat, pbx_getformatname_multiple(s3, sizeof(s3) - 1, (uint64_t)ast->writeformat), (uint64_t)ast->writeformat); //return -1; } #if 0 if ((ast->rawwriteformat = ast->writeformat) && ast->writetrans) { ast_translator_free_path(ast->writetrans); ast->writetrans = NULL; ast_set_write_format(ast, frame->subclass); } #endif if (c->rtp.audio.rtp) { res = ast_rtp_write(c->rtp.audio.rtp, frame); } break; case AST_FRAME_IMAGE: case AST_FRAME_VIDEO: #ifdef CS_SCCP_VIDEO if (c->rtp.video.writeState == SCCP_RTP_STATUS_INACTIVE && c->rtp.video.rtp && c->state != SCCP_CHANNELSTATE_HOLD) { int codec = pbx_codec2skinny_codec((frame->subclass & AST_FORMAT_VIDEO_MASK)); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: got video frame %d\n", c->currentDeviceId, codec); if (0 != codec) { c->rtp.video.writeFormat = codec; sccp_channel_openMultiMediaChannel(c); } } if (c->rtp.video.rtp && (c->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE) != 0) { res = ast_rtp_write(c->rtp.video.rtp, frame); } #endif break; case AST_FRAME_TEXT: case AST_FRAME_MODEM: default: pbx_log(LOG_WARNING, "%s: Can't send %d type frames with SCCP write on channel %s\n", c->currentDeviceId, frame->frametype, ast->name); break; } // c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk16_sendDigits(const sccp_channel_t * channel, const char *digits) { if (!channel || !channel->owner) { pbx_log(LOG_WARNING, "No channel to send digits to\n"); return 0; } PBX_CHANNEL_TYPE *pbx_channel = channel->owner; int i; PBX_FRAME_TYPE f; f = ast_null_frame; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digits '%s'\n", (char *) channel->currentDeviceId, digits); // We don't just call sccp_pbx_senddigit due to potential overhead, and issues with locking f.src = "SCCP"; // CS_AST_NEW_FRAME_STRUCT // f.frametype = AST_FRAME_DTMF_BEGIN; // ast_queue_frame(pbx_channel, &f); for (i = 0; digits[i] != '\0'; i++) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digit %c\n", (char *) channel->currentDeviceId, digits[i]); f.frametype = AST_FRAME_DTMF_END; // Sending only the dmtf will force asterisk to start with DTMF_BEGIN and schedule the DTMF_END f.subclass = digits[i]; // f.samples = SCCP_MIN_DTMF_DURATION * 8; f.len = SCCP_MIN_DTMF_DURATION; f.src = "SEND DIGIT"; ast_queue_frame(pbx_channel, &f); } return 1; } static int sccp_wrapper_asterisk16_sendDigit(const sccp_channel_t * channel, const char digit) { char digits[3] = "\0\0"; digits[0] = digit; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: got a single digit '%c' -> '%s'\n", channel->currentDeviceId, digit, digits); return sccp_wrapper_asterisk16_sendDigits(channel, digits); } static void sccp_wrapper_asterisk16_setCalleridPresence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (CALLERID_PRESENCE_FORBIDDEN == channel->callInfo.presentation) { pbx_channel->cid.cid_pres |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; } } static int sccp_wrapper_asterisk16_setNativeAudioFormats(const sccp_channel_t * channel, skinny_codec_t codec[], int length) { //#ifdef CS_EXPERIMENTAL format_t new_nativeformats = 0; int i; ast_debug(10, "%s: set native Formats length: %d\n", (char *) channel->currentDeviceId, length); for (i = 0; i < length; i++) { new_nativeformats |= skinny_codec2pbx_codec(codec[i]); ast_debug(10, "%s: set native Formats to %d, skinny: %d\n", (char *) channel->currentDeviceId, (int) channel->owner->nativeformats, codec[i]); } if (channel->owner->nativeformats != new_nativeformats) { channel->owner->nativeformats = new_nativeformats; char codecs[512]; sccp_multiple_codecs2str(codecs, sizeof(codecs) - 1, codec, length); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_2 "%s: updated native Formats to %d, length: %d, skinny: [%s]\n", (char *) channel->currentDeviceId, (int) channel->owner->nativeformats, length, codecs); } //#else // channel->owner->nativeformats = skinny_codec2pbx_codec(codec[0]); //#endif return 1; } static int sccp_wrapper_asterisk16_setNativeVideoFormats(const sccp_channel_t * channel, uint32_t formats) { return 1; } boolean_t sccp_wrapper_asterisk16_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId) { sccp_line_t *line = NULL; (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); if ((*pbx_channel) == NULL) { return FALSE; } if (!channel || !channel->line) { return FALSE; } line = channel->line; (*pbx_channel)->tech = &sccp_tech; (*pbx_channel)->tech_pvt = sccp_channel_retain(channel); memset((*pbx_channel)->exten, 0, sizeof((*pbx_channel)->exten)); sccp_copy_string((*pbx_channel)->context, line->context, sizeof((*pbx_channel)->context)); if (!sccp_strlen_zero(line->language)) ast_string_field_set((*pbx_channel), language, line->language); if (!sccp_strlen_zero(line->accountcode)) ast_string_field_set((*pbx_channel), accountcode, line->accountcode); if (!sccp_strlen_zero(line->musicclass)) ast_string_field_set((*pbx_channel), musicclass, line->musicclass); if (line->amaflags) (*pbx_channel)->amaflags = line->amaflags; if (line->callgroup) (*pbx_channel)->callgroup = line->callgroup; #if CS_SCCP_PICKUP if (line->pickupgroup) (*pbx_channel)->pickupgroup = line->pickupgroup; #endif (*pbx_channel)->priority = 1; (*pbx_channel)->adsicpe = AST_ADSI_UNAVAILABLE; /** the the tonezone using language information */ if (!sccp_strlen_zero(line->language) && ast_get_indication_zone(line->language)) { (*pbx_channel)->zone = ast_get_indication_zone(line->language); /* this will core asterisk on hangup */ } /* create/set linkid */ char linkedid[50]; sprintf(linkedid, "SCCP::%-10d", channel->callid); if (PBX(setChannelLinkedId)) PBX(setChannelLinkedId) (channel, linkedid); /* done */ channel->owner = (*pbx_channel); return TRUE; } static boolean_t sccp_wrapper_asterisk16_masqueradeHelper(PBX_CHANNEL_TYPE * pbxChannel, PBX_CHANNEL_TYPE * pbxTmpChannel) { pbx_moh_stop(pbxChannel); const char *context; const char *exten; int priority; pbx_moh_stop(pbxChannel); ast_channel_lock(pbxChannel); context = ast_strdupa(pbxChannel->context); exten = ast_strdupa(pbxChannel->exten); priority = pbxChannel->priority; pbx_channel_unlock(pbxChannel); /* in older versions we need explicit locking, around the masqueration */ pbx_channel_lock(pbxChannel); if (pbx_channel_masquerade(pbxTmpChannel, pbxChannel)) { return FALSE; } pbx_channel_lock(pbxTmpChannel); pbx_do_masquerade(pbxTmpChannel); pbx_channel_unlock(pbxTmpChannel); pbx_channel_set_hangupcause(pbxChannel, AST_CAUSE_NORMAL_UNSPECIFIED); pbx_channel_unlock(pbxChannel); /* when returning from bridge, the channel will continue at the next priority */ ast_explicit_goto(pbxTmpChannel, context, exten, priority + 1); return TRUE; } static boolean_t sccp_wrapper_asterisk16_allocTempPBXChannel(PBX_CHANNEL_TYPE * pbxSrcChannel, PBX_CHANNEL_TYPE ** pbxDstChannel) { if (!pbxSrcChannel) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) no pbx channel provided\n"); return FALSE; } (*pbxDstChannel) = ast_channel_alloc(0, pbxSrcChannel->_state, 0, 0, pbxSrcChannel->accountcode, pbxSrcChannel->exten, pbxSrcChannel->context, pbxSrcChannel->amaflags, "TMP/%s", pbxSrcChannel->name); if ((*pbxDstChannel) == NULL) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) create pbx channel failed\n"); return FALSE; } (*pbxDstChannel)->writeformat = pbxSrcChannel->writeformat; (*pbxDstChannel)->readformat = pbxSrcChannel->readformat; pbx_builtin_setvar_helper(*pbxDstChannel, "__" SCCP_AST_LINKEDID_HELPER, pbx_builtin_getvar_helper(pbxSrcChannel, SCCP_AST_LINKEDID_HELPER)); return TRUE; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_requestForeignChannel(const char *type, pbx_format_type format, const PBX_CHANNEL_TYPE * requestor, void *data) { PBX_CHANNEL_TYPE *chan; int cause; if (!(chan = ast_request(type, format, data, &cause))) { pbx_log(LOG_ERROR, "SCCP: Requested channel could not be created, cause: %d", cause); return NULL; } return chan; } int sccp_wrapper_asterisk16_hangup(PBX_CHANNEL_TYPE * ast_channel) { sccp_channel_t *c; int res = 1; if ((c = get_sccp_channel_from_pbx_channel(ast_channel))) { if (ast_test_flag(ast_channel, AST_FLAG_ANSWERED_ELSEWHERE) || ast_channel->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: This call was answered elsewhere\n"); c->answered_elsewhere = TRUE; } res = sccp_pbx_hangup(c); sccp_channel_release(c); } ast_channel->tech_pvt = NULL; c = c ? sccp_channel_release(c) : NULL; ast_channel = pbx_channel_unref(ast_channel); return res; } /*! * \brief Parking Thread Arguments Structure */ struct parkingThreadArg { PBX_CHANNEL_TYPE *bridgedChannel; PBX_CHANNEL_TYPE *hostChannel; const sccp_device_t *device; }; /*! * \brief Channel Park Thread * This thread doing the park magic and sends an displaynotify with the park position to the initial device (@see struct parkingThreadArg) * * \param data struct parkingThreadArg with host and bridged channel together with initial device */ static void *sccp_wrapper_asterisk16_park_thread(void *data) { struct parkingThreadArg *arg; PBX_FRAME_TYPE *f; char extstr[20]; int ext; int res; arg = (struct parkingThreadArg *) data; f = ast_read(arg->bridgedChannel); if (f) ast_frfree(f); res = ast_park_call(arg->bridgedChannel, arg->hostChannel, 0, &ext); if (!res) { extstr[0] = 128; extstr[1] = SKINNY_LBL_CALL_PARK_AT; sprintf(&extstr[2], " %d", ext); sccp_dev_displaynotify((sccp_device_t *) arg->device, extstr, 10); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Parked channel %s on %d\n", DEV_ID_LOG(arg->device), arg->bridgedChannel->name, ext); } ast_hangup(arg->hostChannel); ast_free(arg); return NULL; } /*! * \brief Park the bridge channel of hostChannel * This function prepares the host and the bridged channel to be ready for parking. * It clones the pbx channel of both sides forward them to the park_thread * * \param hostChannel initial channel that request the parking * \todo we have a codec issue after unpark a call * \todo copy connected line info * */ static sccp_parkresult_t sccp_wrapper_asterisk16_park(const sccp_channel_t * hostChannel) { pthread_t th; struct parkingThreadArg *arg; PBX_CHANNEL_TYPE *pbx_bridgedChannelClone, *pbx_hostChannelClone; PBX_CHANNEL_TYPE *bridgedChannel = NULL; bridgedChannel = ast_bridged_channel(hostChannel->owner); if (!bridgedChannel) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX channel for parking"); return PARK_RESULT_FAIL; } pbx_bridgedChannelClone = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, hostChannel->owner->accountcode, bridgedChannel->exten, bridgedChannel->context, bridgedChannel->amaflags, "Parking/%s", bridgedChannel->name); pbx_hostChannelClone = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, hostChannel->owner->accountcode, hostChannel->owner->exten, hostChannel->owner->context, hostChannel->owner->amaflags, "SCCP/%s", hostChannel->owner->name); if (pbx_hostChannelClone && pbx_bridgedChannelClone) { /* restore codecs for bridged channel */ pbx_bridgedChannelClone->readformat = bridgedChannel->readformat; pbx_bridgedChannelClone->writeformat = bridgedChannel->writeformat; pbx_bridgedChannelClone->nativeformats = bridgedChannel->nativeformats; ast_channel_masquerade(pbx_bridgedChannelClone, bridgedChannel); /* restore context data */ ast_copy_string(pbx_bridgedChannelClone->context, bridgedChannel->context, sizeof(pbx_bridgedChannelClone->context)); ast_copy_string(pbx_bridgedChannelClone->exten, bridgedChannel->exten, sizeof(pbx_bridgedChannelClone->exten)); pbx_bridgedChannelClone->priority = bridgedChannel->priority; /* restore codecs for host channel */ /* We need to clone the host part, for playing back the announcement */ pbx_hostChannelClone->readformat = hostChannel->owner->readformat; pbx_hostChannelClone->writeformat = hostChannel->owner->writeformat; pbx_hostChannelClone->nativeformats = hostChannel->owner->nativeformats; ast_channel_masquerade(pbx_hostChannelClone, hostChannel->owner); /* restore context data */ ast_copy_string(pbx_hostChannelClone->context, hostChannel->owner->context, sizeof(pbx_hostChannelClone->context)); ast_copy_string(pbx_hostChannelClone->exten, hostChannel->owner->exten, sizeof(pbx_hostChannelClone->exten)); pbx_hostChannelClone->priority = hostChannel->owner->priority; /* start cloning */ if (ast_do_masquerade(pbx_hostChannelClone)) { pbx_log(LOG_ERROR, "while doing masquerade\n"); ast_hangup(pbx_hostChannelClone); return PARK_RESULT_FAIL; } } else { if (pbx_bridgedChannelClone) ast_hangup(pbx_bridgedChannelClone); if (pbx_hostChannelClone) ast_hangup(pbx_hostChannelClone); return PARK_RESULT_FAIL; } if (!(arg = (struct parkingThreadArg *) ast_calloc(1, sizeof(struct parkingThreadArg)))) { return PARK_RESULT_FAIL; } arg->bridgedChannel = pbx_bridgedChannelClone; arg->hostChannel = pbx_hostChannelClone; if ((arg->device = sccp_channel_getDevice_retained(hostChannel))) { if (!ast_pthread_create_detached_background(&th, NULL, sccp_wrapper_asterisk16_park_thread, arg)) { return PARK_RESULT_SUCCESS; } arg->device = sccp_device_release(arg->device); } return PARK_RESULT_FAIL; } #if !CS_AST_DO_PICKUP static const struct ast_datastore_info pickup_active = { .type = "pickup-active", }; static int ast_do_pickup(PBX_CHANNEL_TYPE * chan, PBX_CHANNEL_TYPE * target) { const char *chan_name; /*!< A masquerade changes channel names. */ const char *target_name; /*!< A masquerade changes channel names. */ char *target_cid_name = NULL, *target_cid_number = NULL, *target_cid_ani = NULL; sccp_channel_t *c = get_sccp_channel_from_pbx_channel(target); int res = -1; target_name = sccp_strdupa(target->name); ast_debug(1, "Call pickup on '%s' by '%s'\n", target_name, chan->name); /* Mark the target to block any call pickup race. */ #if ASTERISK_VERSION_NUMBER > 10600 struct ast_datastore *ds_pickup; ds_pickup = ast_datastore_alloc(&pickup_active, NULL); if (!ds_pickup) { pbx_log(LOG_WARNING, "Unable to create channel datastore on '%s' for call pickup\n", target_name); return -1; } ast_channel_datastore_add(target, ds_pickup); #endif /* store callerid info to local variables */ if (c) { if (target->cid.cid_name) target_cid_name = strdup(target->cid.cid_name); if (target->cid.cid_num) target_cid_number = strdup(target->cid.cid_num); if (target->cid.cid_ani) target_cid_ani = strdup(target->cid.cid_ani); } // copy codec information target->nativeformats = chan->nativeformats; target->rawwriteformat = chan->rawwriteformat; target->writeformat = chan->writeformat; target->readformat = chan->readformat; target->writetrans = chan->writetrans; ast_set_write_format(target, chan->rawwriteformat); ast_channel_unlock(target); /* The pickup race is avoided so we do not need the lock anymore. */ ast_channel_lock(chan); chan_name = sccp_strdupa(chan->name); /* exchange callerid info */ if (c) { if (chan && !sccp_strlen_zero(chan->cid.cid_name)) sccp_copy_string(c->callInfo.originalCalledPartyName, chan->cid.cid_name, sizeof(c->callInfo.originalCalledPartyName)); if (chan && !sccp_strlen_zero(chan->cid.cid_num)) sccp_copy_string(c->callInfo.originalCalledPartyNumber, chan->cid.cid_num, sizeof(c->callInfo.originalCalledPartyNumber)); if (!sccp_strlen_zero(target_cid_name)) { sccp_copy_string(c->callInfo.calledPartyName, target_cid_name, sizeof(c->callInfo.callingPartyName)); sccp_free(target_cid_name); } if (!sccp_strlen_zero(target_cid_number)) { sccp_copy_string(c->callInfo.calledPartyNumber, target_cid_number, sizeof(c->callInfo.callingPartyNumber)); sccp_free(target_cid_number); } /* we use the chan->cid.cid_name to do the magic */ if (!sccp_strlen_zero(target_cid_ani)) { sccp_copy_string(c->callInfo.callingPartyNumber, target_cid_ani, sizeof(c->callInfo.callingPartyNumber)); sccp_copy_string(c->callInfo.callingPartyName, target_cid_ani, sizeof(c->callInfo.callingPartyName)); sccp_free(target_cid_ani); } } ast_channel_unlock(chan); if (ast_answer(chan)) { pbx_log(LOG_WARNING, "Unable to answer '%s'\n", chan_name); goto pickup_failed; } if (sccp_asterisk_queue_control(chan, AST_CONTROL_ANSWER)) { pbx_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan_name); goto pickup_failed; } /* setting this flag to generate a reason header in the cancel message to the ringing channel */ ast_set_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE); if (ast_channel_masquerade(target, chan)) { pbx_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan_name, target_name); goto pickup_failed; } /* Do the masquerade manually to make sure that it is completed. */ ast_do_masquerade(target); res = 0; pickup_failed: ast_channel_lock(target); #if ASTERISK_VERSION_NUMBER > 10600 if (!ast_channel_datastore_remove(target, ds_pickup)) { ast_datastore_free(ds_pickup); } #endif return res; } #endif /*! * \brief Pickup asterisk channel target using chan * * \param chan initial channel that request the parking * \param target Channel t park to */ static boolean_t sccp_wrapper_asterisk16_pickupChannel(const sccp_channel_t * chan, PBX_CHANNEL_TYPE * target) { boolean_t result; result = ast_do_pickup(chan->owner, target) ? FALSE : TRUE; return result; } static uint8_t sccp_wrapper_asterisk16_get_payloadType(const struct sccp_rtp *rtp, skinny_codec_t codec) { uint32_t astCodec; int payload; astCodec = skinny_codec2pbx_codec(codec); payload = ast_rtp_lookup_code(rtp->rtp, 1, astCodec); return payload; } static int sccp_wrapper_asterisk16_get_sampleRate(skinny_codec_t codec) { #if ASTERISK_VERSION_NUMBER > 10601 uint32_t astCodec; astCodec = skinny_codec2pbx_codec(codec); return ast_rtp_lookup_sample_rate(1, astCodec); #else uint32_t i; for (i = 1; i < ARRAY_LEN(skinny_codecs); i++) { if (skinny_codecs[i].codec == codec) { return skinny_codecs[i].sample_rate; } } return 8000; #endif } static sccp_extension_status_t sccp_wrapper_asterisk16_extensionStatus(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (!pbx_channel || !pbx_channel->context) { pbx_log(LOG_ERROR, "%s: (extension_status) Either no pbx_channel or no valid context provided to lookup number\n", channel->designator); return SCCP_EXTENSION_NOTEXISTS; } int ignore_pat = ast_ignore_pattern(pbx_channel->context, channel->dialedNumber); int ext_exist = ast_exists_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); int ext_canmatch = ast_canmatch_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); int ext_matchmore = ast_matchmore_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "+=sccp extension matcher says==================+\n" VERBOSE_PREFIX_2 "|ignore |exists |can match |match more|\n" VERBOSE_PREFIX_2 "|%3s |%3s |%3s |%3s |\n" VERBOSE_PREFIX_2 "+==============================================+\n", ignore_pat ? "yes" : "no", ext_exist ? "yes" : "no", ext_canmatch ? "yes" : "no", ext_matchmore ? "yes" : "no"); if (ignore_pat) { return SCCP_EXTENSION_NOTEXISTS; } else if (ext_exist) { if (ext_canmatch && !ext_matchmore) { return SCCP_EXTENSION_EXACTMATCH; } else { return SCCP_EXTENSION_MATCHMORE; } } return SCCP_EXTENSION_NOTEXISTS; } //static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_request(const char *type, format_t format, const PBX_CHANNEL_TYPE * requestor, void *data, int *cause) static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_request(const char *type, int format, void *data, int *cause) { sccp_channel_request_status_t requestStatus; sccp_channel_t *channel = NULL; skinny_codec_t audioCapabilities[SKINNY_MAX_CAPABILITIES]; skinny_codec_t videoCapabilities[SKINNY_MAX_CAPABILITIES]; memset(&audioCapabilities, 0, sizeof(audioCapabilities)); memset(&videoCapabilities, 0, sizeof(videoCapabilities)); //! \todo parse request char *lineName; skinny_codec_t codec = SKINNY_CODEC_G711_ULAW_64K; sccp_autoanswer_t autoanswer_type = SCCP_AUTOANSWER_NONE; uint8_t autoanswer_cause = AST_CAUSE_NOTDEFINED; int ringermode = 0; *cause = AST_CAUSE_NOTDEFINED; if (!type) { pbx_log(LOG_NOTICE, "Attempt to call with unspecified type of channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } if (!data) { pbx_log(LOG_NOTICE, "Attempt to call SCCP/ failed\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } /* we leave the data unchanged */ lineName = strdup((const char *) data); /* parsing options string */ char *options = NULL; int optc = 0; char *optv[2]; int opti = 0; if ((options = strchr(lineName, '/'))) { *options = '\0'; options++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked us to create a channel with type=%s, format=" UI64FMT ", lineName=%s, options=%s\n", type, (uint64_t) format, lineName, (options) ? options : ""); /* get ringer mode from ALERT_INFO */ /* requestor is not available in asterisk 1.6 */ /* const char *alert_info = NULL; if(requestor){ alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *)requestor, "_ALERT_INFO"); if(!alert_info){ alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *)requestor, "__ALERT_INFO"); } } if (alert_info && !sccp_strlen_zero(alert_info)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Found ALERT_INFO=%s\n", alert_info); if (strcasecmp(alert_info, "inside") == 0) ringermode = SKINNY_RINGTYPE_INSIDE; else if (strcasecmp(alert_info, "feature") == 0) ringermode = SKINNY_RINGTYPE_FEATURE; else if (strcasecmp(alert_info, "silent") == 0) ringermode = SKINNY_RINGTYPE_SILENT; else if (strcasecmp(alert_info, "urgent") == 0) ringermode = SKINNY_RINGTYPE_URGENT; } */ /* done ALERT_INFO parsing */ /* parse options */ if (options && (optc = sccp_app_separate_args(options, '/', optv, sizeof(optv) / sizeof(optv[0])))) { pbx_log(LOG_NOTICE, "parse options\n"); for (opti = 0; opti < optc; opti++) { pbx_log(LOG_NOTICE, "parse option '%s'\n", optv[opti]); if (!strncasecmp(optv[opti], "aa", 2)) { /* let's use the old style auto answer aa1w and aa2w */ if (!strncasecmp(optv[opti], "aa1w", 4)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa2w", 4)) { autoanswer_type = SCCP_AUTOANSWER_2W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa=", 3)) { optv[opti] += 3; pbx_log(LOG_NOTICE, "parsing aa\n"); if (!strncasecmp(optv[opti], "1w", 2)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 2; } else if (!strncasecmp(optv[opti], "2w", 2)) { autoanswer_type = SCCP_AUTOANSWER_2W; pbx_log(LOG_NOTICE, "set aa to 2w\n"); optv[opti] += 2; } } /* since the pbx ignores autoanswer_cause unless SCCP_RWLIST_GETSIZE(l->channels) > 1, it is safe to set it if provided */ if (!sccp_strlen_zero(optv[opti]) && (autoanswer_cause)) { if (!strcasecmp(optv[opti], "b")) autoanswer_cause = AST_CAUSE_BUSY; else if (!strcasecmp(optv[opti], "u")) autoanswer_cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; else if (!strcasecmp(optv[opti], "c")) autoanswer_cause = AST_CAUSE_CONGESTION; } if (autoanswer_cause) *cause = autoanswer_cause; /* check for ringer options */ } else if (!strncasecmp(optv[opti], "ringer=", 7)) { optv[opti] += 7; if (!strcasecmp(optv[opti], "inside")) ringermode = SKINNY_RINGTYPE_INSIDE; else if (!strcasecmp(optv[opti], "outside")) ringermode = SKINNY_RINGTYPE_OUTSIDE; else if (!strcasecmp(optv[opti], "feature")) ringermode = SKINNY_RINGTYPE_FEATURE; else if (!strcasecmp(optv[opti], "silent")) ringermode = SKINNY_RINGTYPE_SILENT; else if (!strcasecmp(optv[opti], "urgent")) ringermode = SKINNY_RINGTYPE_URGENT; else ringermode = SKINNY_RINGTYPE_OUTSIDE; } else { pbx_log(LOG_WARNING, "Wrong option %s\n", optv[opti]); } } } /** getting remote capabilities */ char cap_buf[512]; /* audio capabilities */ const struct ast_channel_tech *tech_pvt = ast_get_channel_tech(type); if (format) { get_skinnyFormats(format & AST_FORMAT_AUDIO_MASK, audioCapabilities, ARRAY_LEN(audioCapabilities)); get_skinnyFormats(format & AST_FORMAT_VIDEO_MASK, videoCapabilities, ARRAY_LEN(videoCapabilities)); } else { get_skinnyFormats(tech_pvt->capabilities & AST_FORMAT_AUDIO_MASK, audioCapabilities, ARRAY_LEN(audioCapabilities)); get_skinnyFormats(tech_pvt->capabilities & AST_FORMAT_VIDEO_MASK, videoCapabilities, ARRAY_LEN(videoCapabilities)); } sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, audioCapabilities, ARRAY_LEN(audioCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote audio caps: %s\n", cap_buf); sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, videoCapabilities, ARRAY_LEN(videoCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote video caps: %s\n", cap_buf); /** done */ /** get requested format */ codec = pbx_codec2skinny_codec(format); requestStatus = sccp_requestChannel(lineName, codec, audioCapabilities, ARRAY_LEN(audioCapabilities), autoanswer_type, autoanswer_cause, ringermode, &channel); switch (requestStatus) { case SCCP_REQUEST_STATUS_SUCCESS: // everything is fine break; case SCCP_REQUEST_STATUS_LINEUNKNOWN: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s Unknown -> Not Successfull\n", lineName); *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER; goto EXITFUNC; case SCCP_REQUEST_STATUS_LINEUNAVAIL: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s not currently registered -> Try again later\n", lineName); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; case SCCP_REQUEST_STATUS_ERROR: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; default: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; } if (!sccp_pbx_channel_allocate(channel, NULL)) { //! \todo handle error in more detail, cleanup sccp channel pbx_log(LOG_WARNING, "SCCP: Unable to allocate channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; } PBX_CHANNEL_TYPE *requestor = channel->owner; // set calling party sccp_channel_set_callingparty(channel, requestor->cid.cid_name, requestor->cid.cid_num); sccp_channel_set_originalCalledparty(channel, NULL, requestor->cid.cid_dnid); EXITFUNC: if (lineName) sccp_free(lineName); sccp_restart_monitor(); sccp_channel_release(channel); return (channel && channel->owner) ? channel->owner : NULL; } /* * \brief get callerid_name from pbx * \param sccp_channle Asterisk Channel * \param cid name result * \return parse result */ static int sccp_wrapper_asterisk16_callerid_name(const sccp_channel_t * channel, char **cid_name) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->cid.cid_name && strlen(pbx_chan->cid.cid_name) > 0) { *cid_name = strdup(pbx_chan->cid.cid_name); return 1; } return 0; } /* * \brief get callerid_name from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk16_callerid_number(const sccp_channel_t * channel, char **cid_number) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->cid.cid_num && strlen(pbx_chan->cid.cid_num) > 0) { *cid_number = strdup(pbx_chan->cid.cid_num); return 1; } return 0; } /* * \brief get callerid_ton from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk16_callerid_ton(const sccp_channel_t * channel, char **cid_ton) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; return pbx_chan->cid.cid_ton; } /* * \brief get callerid_ani from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk16_callerid_ani(const sccp_channel_t * channel, char **cid_ani) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->cid.cid_ani && strlen(pbx_chan->cid.cid_ani) > 0) { *cid_ani = strdup(pbx_chan->cid.cid_ani); return 1; } return 0; } /* * \brief get callerid_dnid from pbx (Destination ID) * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk16_callerid_dnid(const sccp_channel_t * channel, char **cid_dnid) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->cid.cid_dnid && strlen(pbx_chan->cid.cid_dnid) > 0) { *cid_dnid = strdup(pbx_chan->cid.cid_dnid); return 1; } return 0; } /* * \brief get callerid_rdnis from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk16_callerid_rdnis(const sccp_channel_t * channel, char **cid_rdnis) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->cid.cid_rdnis && strlen(pbx_chan->cid.cid_rdnis) > 0) { *cid_rdnis = strdup(pbx_chan->cid.cid_rdnis); return 1; } return 0; } /* * \brief get callerid_presence from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk16_callerid_presence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; // return pbx_chan->cid.cid_pres; if (pbx_chan->cid.cid_pres) { return CALLERID_PRESENCE_ALLOWED; } return CALLERID_PRESENCE_FORBIDDEN; } static int sccp_wrapper_asterisk16_call(PBX_CHANNEL_TYPE * ast, char *dest, int timeout) { sccp_channel_t *c = NULL; struct varshead *headp; struct ast_var_t *current; int res = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk request to call %s (dest:%s, timeout: %d)\n", pbx_channel_name(ast), dest, timeout); if (!sccp_strlen_zero(pbx_channel_call_forward(ast))) { PBX(queue_control) (ast, -1); /* Prod Channel if in the middle of a call_forward instead of proceed */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Forwarding Call to '%s'\n", pbx_channel_call_forward(ast)); return 0; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { pbx_log(LOG_WARNING, "SCCP: Asterisk request to call %s on channel: %s, but we don't have this channel!\n", dest, pbx_channel_name(ast)); return -1; } /* Check whether there is MaxCallBR variables */ headp = &ast->varshead; //ast_log(LOG_NOTICE, "SCCP: search for varibles!\n"); AST_LIST_TRAVERSE(headp, current, entries) { //ast_log(LOG_NOTICE, "var: name: %s, value: %s\n", ast_var_name(current), ast_var_value(current)); if (!strcasecmp(ast_var_name(current), "__MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } else if (!strcasecmp(ast_var_name(current), "MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } } char *cid_name = NULL; char *cid_number = NULL; sccp_wrapper_asterisk16_callerid_name(c, &cid_name); sccp_wrapper_asterisk16_callerid_number(c, &cid_number); sccp_channel_set_callingparty(c, cid_name, cid_number); if (cid_name) { free(cid_name); } if (cid_number) { free(cid_number); } res = sccp_pbx_call(c, dest, timeout); c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk16_answer(PBX_CHANNEL_TYPE * chan) { //! \todo change this handling and split pbx and sccp handling -MC int res = -1; sccp_channel_t *channel = NULL; if ((channel = get_sccp_channel_from_pbx_channel(chan))) { res = sccp_pbx_answer(channel); channel = sccp_channel_release(channel); } return res; } /** * * \todo update remote capabilities after fixup */ static int sccp_wrapper_asterisk16_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: we got a fixup request for %s\n", newchan->name); sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(newchan))) { pbx_log(LOG_WARNING, "sccp_pbx_fixup(old: %s(%p), new: %s(%p)). no SCCP channel to fix\n", oldchan->name, (void *) oldchan, newchan->name, (void *) newchan); return -1; } c->owner = newchan; c = sccp_channel_release(c); return 0; } static enum ast_bridge_result sccp_wrapper_asterisk16_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms) { enum ast_bridge_result res; int new_flags = flags; /* \note temporarily marked out until we figure out how to get directrtp back on track - DdG */ sccp_channel_t *sc0, *sc1; if ((sc0 = get_sccp_channel_from_pbx_channel(c0)) && (sc1 = get_sccp_channel_from_pbx_channel(c1))) { // Switch off DTMF between SCCP phones new_flags &= !AST_BRIDGE_DTMF_CHANNEL_0; new_flags &= !AST_BRIDGE_DTMF_CHANNEL_1; if (GLOB(directrtp)) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } else { sccp_device_t *d0 = sccp_channel_getDevice_retained(sc0); if (d0) { sccp_device_t *d1 = sccp_channel_getDevice_retained(sc1); if (d1) { if (d0->directrtp && d1->directrtp) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } d1 = sccp_device_release(d1); } d0 = sccp_device_release(d0); } } sc0->peerIsSCCP = TRUE; sc1->peerIsSCCP = TRUE; // SCCP Key handle direction to asterisk is still to be implemented here // sccp_pbx_senddigit sc0 = sccp_channel_release(sc0); sc1 = sccp_channel_release(sc1); } else { // Switch on DTMF between differing channels ast_channel_undefer_dtmf(c0); ast_channel_undefer_dtmf(c1); } res = ast_rtp_bridge(c0, c1, new_flags, fo, rc, timeoutms); switch (res) { case AST_BRIDGE_COMPLETE: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Complete\n", c0->name, c1->name); break; case AST_BRIDGE_FAILED: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed\n", c0->name, c1->name); break; case AST_BRIDGE_FAILED_NOWARN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed NoWarn\n", c0->name, c1->name); break; case AST_BRIDGE_RETRY: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed Retry\n", c0->name, c1->name); break; } /*! \todo Implement callback function queue upon completion */ return res; } static enum ast_rtp_get_result sccp_wrapper_asterisk16_get_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_get_result res = AST_RTP_TRY_NATIVE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", ast->name); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GET_FAILED; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GET_FAILED; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GET_FAILED; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GET_FAILED; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", ast->name); return AST_RTP_TRY_PARTIAL; } return res; } static int sccp_wrapper_asterisk16_set_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE * rtp, PBX_RTP_TYPE * vrtp, PBX_RTP_TYPE * trtp, int codecs, int nat_active) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; struct sockaddr_in them; sccp_log((DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) format: %d\n", (int) codecs); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: __FILE__\n"); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO PVT\n"); return -1; } if (!c->line) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO LINE\n"); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO DEVICE\n"); return -1; } if (!d->directrtp) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) Direct RTP disabled\n"); d = sccp_device_release(d); return -1; } if (rtp) { ast_rtp_get_peer(rtp, &them); } else { if (ast->_state != AST_STATE_UP) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Early RTP stage, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } else { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Native Bridge Break, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } } /* Need a return here to break the bridge */ d = sccp_device_release(d); return 0; } static enum ast_rtp_get_result sccp_wrapper_asterisk16_get_vrtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_get_result res = AST_RTP_TRY_NATIVE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", ast->name); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GET_FAILED; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); //! \todo should this not be getVideoPeerInfo if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GET_FAILED; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GET_FAILED; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_TRY_PARTIAL; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", ast->name); return AST_RTP_TRY_PARTIAL; } return res; } static int sccp_wrapper_asterisk16_getCodec(PBX_CHANNEL_TYPE * ast) { format_t format = AST_FORMAT_ULAW; sccp_channel_t *channel; if (!(channel = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP | DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (getCodec) NO PVT\n"); return format; } ast_debug(10, "asterisk requests format for channel %s, readFormat: %s(%d)\n", ast->name, codec2str(channel->rtp.audio.readFormat), channel->rtp.audio.readFormat); if (channel->remoteCapabilities.audio) return skinny_codecs2pbx_codecs(channel->remoteCapabilities.audio); else return skinny_codecs2pbx_codecs(channel->capabilities.audio); } static int sccp_wrapper_asterisk16_rtp_stop(sccp_channel_t * channel) { if (channel->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping phone media transmission on channel %08X\n", channel->callid); ast_rtp_stop(channel->rtp.audio.rtp); } if (channel->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping video media transmission on channel %08X\n", channel->callid); ast_rtp_stop(channel->rtp.video.rtp); } return 0; } static boolean_t sccp_wrapper_asterisk16_create_audio_rtp(sccp_channel_t * c) { sccp_session_t *s = NULL; sccp_device_t *d = NULL; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating rtp server connection on %s\n", DEV_ID_LOG(d), pbx_inet_ntoa(s->ourip)); c->rtp.audio.rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, s->ourip); if (!c->rtp.audio.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: rtp server created\n", DEV_ID_LOG(d)); if (c->owner) { ast_channel_set_fd(c->owner, 0, ast_rtp_fd(c->rtp.audio.rtp)); ast_channel_set_fd(c->owner, 1, ast_rtcp_fd(c->rtp.audio.rtp)); ast_queue_frame(c->owner, &ast_null_frame); } ast_rtp_setqos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk16_create_video_rtp(sccp_channel_t * c) { sccp_session_t *s = NULL; sccp_device_t *d = NULL; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating vrtp server connection at %s\n", DEV_ID_LOG(d), pbx_inet_ntoa(s->ourip)); c->rtp.video.rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, s->ourip); if (!c->rtp.video.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: vrtp created\n", DEV_ID_LOG(d)); if (c->owner) { ast_channel_set_fd(c->owner, 2, ast_rtp_fd(c->rtp.video.rtp)); ast_channel_set_fd(c->owner, 3, ast_rtcp_fd(c->rtp.video.rtp)); ast_queue_frame(c->owner, &ast_null_frame); } ast_rtp_setqos(c->rtp.video.rtp, d->video_tos, d->video_cos, "SCCP VRTP"); d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk16_destroyRTP(PBX_RTP_TYPE * rtp) { ast_rtp_destroy(rtp); return (!rtp) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk16_checkHangup(const sccp_channel_t * channel) { int res; res = ast_check_hangup(channel->owner); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk16_rtpGetPeer(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { // ast_rtp_get_them(rtp, address); ast_rtp_get_peer(rtp, address); return TRUE; } static boolean_t sccp_wrapper_asterisk16_rtpGetUs(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { ast_rtp_get_us(rtp, address); return TRUE; } static boolean_t sccp_wrapper_asterisk16_getChannelByName(const char *name, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *ast_channel = NULL; sccp_log((DEBUGCAT_PBX + DEBUGCAT_HIGH)) (VERBOSE_PREFIX_4 "(PBX(getChannelByName)) searching for channel with identification %s\n", name); while ((ast_channel = pbx_channel_walk_locked(ast_channel)) != NULL) { if (strlen(ast_channel->name) == strlen(name) && !strncmp(ast_channel->name, name, strlen(ast_channel->name))) { *pbx_channel = ast_channel; pbx_channel_unlock(ast_channel); return TRUE; } pbx_channel_unlock(ast_channel); } return FALSE; /* PBX_CHANNEL_TYPE *ast = ast_get_channel_by_name_locked(name); if (!ast) return FALSE; *pbx_channel = ast; ast_channel_unlock(ast); return TRUE; */ } static int sccp_wrapper_asterisk16_rtp_set_peer(const struct sccp_rtp *rtp, const struct sockaddr_in *new_peer, int nat_active) { struct sockaddr_in peer; memcpy(&peer.sin_addr, &new_peer->sin_addr, sizeof(peer.sin_addr)); peer.sin_port = new_peer->sin_port; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Tell asterisk to send rtp media to %s:%d\n", ast_inet_ntoa(peer.sin_addr), ntohs(peer.sin_port)); ast_rtp_set_peer(rtp->rtp, &peer); if (nat_active) ast_rtp_setnat(rtp->rtp, 1); return TRUE; } static boolean_t sccp_wrapper_asterisk16_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec) { channel->owner->rawwriteformat = skinny_codec2pbx_codec(codec); channel->owner->nativeformats |= channel->owner->rawwriteformat; #ifndef CS_EXPERIMENTAL_CODEC if (!channel->owner->writeformat) { channel->owner->writeformat = channel->owner->rawwriteformat; } if (channel->owner->writetrans) { ast_translator_free_path(channel->owner->writetrans); channel->owner->writetrans = NULL; } #endif ast_set_write_format(channel->owner, channel->owner->rawwriteformat); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "write native: %d\n", (int) channel->owner->rawwriteformat); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "write: %d\n", (int) channel->owner->writeformat); #ifdef CS_EXPERIMENTAL_CODEC PBX_CHANNEL_TYPE *bridge; if (PBX(getRemoteChannel) (channel, &bridge)) { channel->owner->writeformat = 0; bridge->readformat = 0; ast_channel_make_compatible(bridge, channel->owner); } else { ast_set_write_format(channel->owner, channel->owner->rawwriteformat); } #else channel->owner->nativeformats = channel->owner->rawwriteformat; ast_set_write_format(channel->owner, channel->owner->writeformat); #endif return TRUE; } static boolean_t sccp_wrapper_asterisk16_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec) { channel->owner->rawreadformat = skinny_codec2pbx_codec(codec); channel->owner->nativeformats = channel->owner->rawreadformat; #ifndef CS_EXPERIMENTAL_CODEC if (!channel->owner->readformat) { channel->owner->readformat = channel->owner->rawreadformat; } if (channel->owner->readtrans) { ast_translator_free_path(channel->owner->readtrans); channel->owner->readtrans = NULL; } #endif sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "read native: %d\n", (int) channel->owner->rawreadformat); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "read: %d\n", (int) channel->owner->readformat); #ifdef CS_EXPERIMENTAL_CODEC PBX_CHANNEL_TYPE *bridge; if (PBX(getRemoteChannel) (channel, &bridge)) { channel->owner->readformat = 0; bridge->writeformat = 0; ast_channel_make_compatible(channel->owner, bridge); } else { ast_set_read_format(channel->owner, channel->owner->rawreadformat); } #else channel->owner->nativeformats = channel->owner->rawreadformat; ast_set_read_format(channel->owner, channel->owner->readformat); #endif return TRUE; } static void sccp_wrapper_asterisk16_setCalleridName(const sccp_channel_t * channel, const char *name) { if (channel->owner->cid.cid_name) { ast_free(channel->owner->cid.cid_name); } channel->owner->cid.cid_name = ast_strdup(name); } static void sccp_wrapper_asterisk16_setCalleridNumber(const sccp_channel_t * channel, const char *number) { if (channel->owner->cid.cid_num) { ast_free(channel->owner->cid.cid_num); } channel->owner->cid.cid_num = ast_strdup(number); } /* ANI=Automatic Number Identification => Calling Party DNIS/DNID=Dialed Number Identification Service RDNIS=Redirected Dialed Number Identification Service */ static void sccp_wrapper_asterisk16_setRedirectingParty(const sccp_channel_t * channel, const char *number, const char *name) { // set redirecting party if (channel->owner->cid.cid_rdnis) { ast_free(channel->owner->cid.cid_rdnis); } channel->owner->cid.cid_rdnis = ast_strdup(number); // set number dialed originaly if (channel->owner->cid.cid_dnid) { ast_free(channel->owner->cid.cid_dnid); } if (channel->owner->cid.cid_num) { channel->owner->cid.cid_dnid = ast_strdup(channel->owner->cid.cid_num); } } static void sccp_wrapper_asterisk16_setRedirectedParty(const sccp_channel_t * channel, const char *number, const char *name) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "sccp_wrapper_asterisk16_setRedirectedParty Not Implemented\n"); /*!< \todo set RedirectedParty using ast_callerid */ /* if (number) { channel->owner->redirecting.to.number.valid = 1; ast_party_number_free(&channel->owner->redirecting.to.number); channel->owner->redirecting.to.number.str = ast_strdup(number); } if (name) { channel->owner->redirecting.to.name.valid = 1; ast_party_name_free(&channel->owner->redirecting.to.name); channel->owner->redirecting.to.name.str = ast_strdup(name); } */ } static void sccp_wrapper_asterisk16_updateConnectedLine(const sccp_channel_t * channel, const char *number, const char *name, uint8_t reason) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "sccp_wrapper_asterisk16_updateConnectedLine Not Implemented\n"); /* struct ast_party_connected_line connected; struct ast_set_party_connected_line update_connected; memset(&update_connected, 0, sizeof(update_connected)); if (number) { update_connected.id.number = 1; connected.id.number.valid = 1; connected.id.number.str = (char *)number; connected.id.number.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (name) { update_connected.id.name = 1; connected.id.name.valid = 1; connected.id.name.str = (char *)name; connected.id.name.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } connected.id.tag = NULL; connected.source = reason; ast_channel_queue_connected_line_update(channel->owner, &connected, &update_connected); */ } static int sccp_wrapper_asterisk16_sched_add(int when, sccp_sched_cb callback, const void *data) { if (sched) return ast_sched_add(sched, when, callback, data); return FALSE; } static long sccp_wrapper_asterisk16_sched_when(int id) { if (sched) return ast_sched_when(sched, id); return FALSE; } static int sccp_wrapper_asterisk16_sched_wait(int id) { if (sched) return ast_sched_wait(sched); return FALSE; } static int sccp_wrapper_asterisk16_sched_del(int id) { if (sched) return ast_sched_del(sched, id); return FALSE; } static int sccp_wrapper_asterisk16_setCallState(const sccp_channel_t * channel, int state) { sccp_pbx_setcallstate((sccp_channel_t *) channel, state); //! \todo implement correct return value (take into account negative deadlock prevention) return 0; } static void sccp_wrapper_asterisk_set_pbxchannel_linkedid(PBX_CHANNEL_TYPE * pbx_channel, const char *new_linkedid) { if (pbx_channel) { pbx_builtin_setvar_helper(pbx_channel, "__" SCCP_AST_LINKEDID_HELPER, new_linkedid); } } #define DECLARE_PBX_CHANNEL_STRGET(_field) \ static const char *sccp_wrapper_asterisk_get_channel_##_field(const sccp_channel_t * channel) \ { \ static const char *empty_channel_##_field = "--no-channel-" #_field "--"; \ if (channel->owner) { \ return channel->owner->_field; \ } \ return empty_channel_##_field; \ }; #define DECLARE_PBX_CHANNEL_STRSET(_field) \ static void sccp_wrapper_asterisk_set_channel_##_field(const sccp_channel_t * channel, const char * _field) \ { \ if (channel->owner) { \ sccp_copy_string(channel->owner->_field, _field, sizeof(channel->owner->_field)); \ } \ }; DECLARE_PBX_CHANNEL_STRGET(name) DECLARE_PBX_CHANNEL_STRGET(uniqueid) DECLARE_PBX_CHANNEL_STRGET(appl) DECLARE_PBX_CHANNEL_STRGET(exten) DECLARE_PBX_CHANNEL_STRSET(exten) DECLARE_PBX_CHANNEL_STRGET(context) DECLARE_PBX_CHANNEL_STRSET(context) DECLARE_PBX_CHANNEL_STRGET(macroexten) DECLARE_PBX_CHANNEL_STRSET(macroexten) DECLARE_PBX_CHANNEL_STRGET(macrocontext) DECLARE_PBX_CHANNEL_STRSET(macrocontext) DECLARE_PBX_CHANNEL_STRGET(call_forward) static const char *sccp_wrapper_asterisk_get_channel_linkedid(const sccp_channel_t * channel) { static const char *emptyLinkedId = "--no-linkedid--"; if (channel->owner) { if (pbx_builtin_getvar_helper(channel->owner, SCCP_AST_LINKEDID_HELPER)) { return pbx_builtin_getvar_helper(channel->owner, SCCP_AST_LINKEDID_HELPER); } } return emptyLinkedId; } static void sccp_wrapper_asterisk_set_channel_linkedid(const sccp_channel_t * channel, const char *new_linkedid) { if (channel->owner) { sccp_wrapper_asterisk_set_pbxchannel_linkedid(channel->owner, new_linkedid); } } static void sccp_wrapper_asterisk_set_channel_name(const sccp_channel_t * channel, const char *new_name) { if (channel->owner) { pbx_string_field_set(channel->owner, name, new_name); } } static void sccp_wrapper_asterisk_set_channel_call_forward(const sccp_channel_t * channel, const char *new_call_forward) { if (channel->owner) { pbx_string_field_set(channel->owner, call_forward, new_call_forward); } } static enum ast_channel_state sccp_wrapper_asterisk_get_channel_state(const sccp_channel_t * channel) { if (channel->owner) { return channel->owner->_state; } return 0; } static const struct ast_pbx *sccp_wrapper_asterisk_get_channel_pbx(const sccp_channel_t * channel) { if (channel->owner) { return channel->owner->pbx; } return NULL; } static void sccp_wrapper_asterisk_set_channel_tech_pvt(const sccp_channel_t * channel) { if (channel->owner) { // channel->owner->tech_pvt = sccp_channel_retain((sccp_channel_t * )channel); } } /*! * \brief Find Asterisk/PBX channel by linkedid * * \param ast pbx channel * \param data linkId as void * * * \return int * * \todo I don't understand what this functions returns */ static int pbx_find_channel_by_linkedid(PBX_CHANNEL_TYPE * ast, void *data) { if (!data) return 0; char *linkedId = data; if (!ast->masq && sccp_strequals(pbx_builtin_getvar_helper(ast, SCCP_AST_LINKEDID_HELPER), linkedId)) { sccp_log((DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "SCCP: peer name: %s, linkId: %s\n", ast->name ? ast->name : "(null)", linkedId); // return !ast->pbx && (!strcasecmp(refLinkId, linkId)) && !ast->masq; return 1; } else { return 0; } } static boolean_t sccp_asterisk_getRemoteChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *remotePeer = ast_channel_search_locked(pbx_find_channel_by_linkedid, (void *) sccp_wrapper_asterisk_get_channel_linkedid(channel)); if (remotePeer) { *pbx_channel = remotePeer; return TRUE; } return FALSE; } static int pbx_find_forward_originator_channel_by_linkedid(PBX_CHANNEL_TYPE * ast, void *data) { if (!data) return 0; PBX_CHANNEL_TYPE *refAstChannel = data; if (ast == refAstChannel) { // skip own channel return 0; } if (!ast->masq && sccp_strequals(pbx_builtin_getvar_helper(refAstChannel, SCCP_AST_LINKEDID_HELPER), pbx_builtin_getvar_helper(ast, SCCP_AST_LINKEDID_HELPER))) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: peer name: %s\n", ast->name ? ast->name : "(null)"); return 1; } else { return 0; } } boolean_t sccp_asterisk_getForwarderPeerChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *remotePeer = ast_channel_search_locked(pbx_find_forward_originator_channel_by_linkedid, (void *) channel->owner); if (remotePeer) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: found peer name: %s\n", remotePeer->name ? remotePeer->name : "(null)"); *pbx_channel = remotePeer; return TRUE; } return FALSE; } /*! * \brief Send Text to Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param text Text to be send as char * \return Succes as int * * \called_from_asterisk */ static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; uint8_t instance; if (!ast) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX CHANNEL to send text to\n"); return -1; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send text to (%s)\n", ast->name); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send text to (%s)\n", ast->name); c = sccp_channel_release(c); return -1; } if (!text || sccp_strlen_zero(text)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No text to send to %s\n", d->id, ast->name); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Sending text %s on %s\n", d->id, text, ast->name); instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, (char *) text, 10); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! * \brief Receive First Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit First Digit as char * \return Always Return -1 as int * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit) { return -1; } /*! * \brief Receive Last Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit Last Digit as char * \param duration Duration as int * \return boolean * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send digit to (%s)\n", ast->name); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send digit to (%s)\n", ast->name); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked to send dtmf '%d' to channel %s. Trying to send it %s\n", digit, ast->name, (d->dtmfmode) ? "outofband" : "inband"); if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Can't send the dtmf '%d' %c to a not connected channel %s\n", d->id, digit, digit, ast->name); d = sccp_device_release(d); return -1; } sccp_dev_keypadbutton(d, digit, sccp_device_find_index_for_line(d, c->line->name), c->callid); d = sccp_device_release(d); return -1; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_findChannelWithCallback(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data, boolean_t lock) { PBX_CHANNEL_TYPE *remotePeer; if (!lock) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "requesting channel search without intermediate locking, but no implementation for this (yet)\n"); } remotePeer = ast_channel_search_locked(found_cb, data); return remotePeer; } static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!datalen || sccp_strlen_zero(data) || !(!strncmp(data, "http://", 7) || !strncmp(data, "file://", 7) || !strncmp(data, "ftp://", 6))) { pbx_log(LOG_NOTICE, "SCCP: Received a non valid URL\n"); return -1; } struct ast_frame fr; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { #if DEBUG if (!(d = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { #else if (!(d = c->getDevice_retained(c))) { #endif c = sccp_channel_release(c); return -1; } memset(&fr, 0, sizeof(fr)); fr.frametype = AST_FRAME_HTML; #if CS_AST_NEW_FRAME_STRUCT fr.data.ptr = (char *) data; #else fr.data = (char *) data; #endif fr.src = "SCCP Send URL"; fr.datalen = datalen; sccp_push_result_t pushResult = d->pushURL(d, data, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { fr.subclass = AST_HTML_LDCOMPLETE; } else { fr.subclass = AST_HTML_NOSUPPORT; } ast_queue_frame(ast, ast_frisolate(&fr)); d = sccp_device_release(d); c = sccp_channel_release(c); } return 0; } /*! * \brief Queue a control frame * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type */ int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass = control }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Queue a control frame with payload * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type * \param data Payload * \param datalen Payload Length */ int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen) { #if CS_AST_NEW_FRAME_STRUCT struct ast_frame f = { AST_FRAME_CONTROL,.subclass = control,.data.ptr = (void *) data,.datalen = datalen }; #else struct ast_frame f = { AST_FRAME_CONTROL,.subclass = control,.data = (void *) data,.datalen = datalen }; #endif return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Get Hint Extension State and return the matching Busy Lamp Field State */ static skinny_busylampfield_state_t sccp_wrapper_asterisk106_getExtensionState(const char *extension, const char *context) { skinny_busylampfield_state_t result = SKINNY_BLF_STATUS_UNKNOWN; if (sccp_strlen_zero(extension) || sccp_strlen_zero(context)) { pbx_log(LOG_ERROR, "SCCP: PBX(getExtensionState): Either extension:'%s' or context:;%s' provided is empty\n", extension, context); return result; } int state = ast_extension_state(NULL, context, extension); switch (state) { case AST_EXTENSION_REMOVED: case AST_EXTENSION_DEACTIVATED: case AST_EXTENSION_UNAVAILABLE: result = SKINNY_BLF_STATUS_UNKNOWN; break; case AST_EXTENSION_NOT_INUSE: result = SKINNY_BLF_STATUS_IDLE; break; case AST_EXTENSION_INUSE: case AST_EXTENSION_ONHOLD: case AST_EXTENSION_ONHOLD + AST_EXTENSION_INUSE: case AST_EXTENSION_BUSY: result = SKINNY_BLF_STATUS_INUSE; break; case AST_EXTENSION_RINGING + AST_EXTENSION_INUSE: case AST_EXTENSION_RINGING: result = SKINNY_BLF_STATUS_ALERTING; break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (getExtensionState) extension: %s@%s, extension_state: '%s (%d)' -> blf state '%d'\n", extension, context, ast_extension_state2str(state), state, result); return result; } /*! * \brief using RTP Glue Engine */ #if defined(__cplusplus) || defined(c_plusplus) struct ast_rtp_protocol sccp_rtp = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .get_rtp_info = sccp_wrapper_asterisk16_get_rtp_peer, .get_vrtp_info = sccp_wrapper_asterisk16_get_vrtp_peer, .set_rtp_peer = sccp_wrapper_asterisk16_set_rtp_peer, .get_codec = sccp_wrapper_asterisk16_getCodec, /* *INDENT-ON* */ }; #else struct ast_rtp_protocol sccp_rtp = { .type = SCCP_TECHTYPE_STR, .get_rtp_info = sccp_wrapper_asterisk16_get_rtp_peer, .get_vrtp_info = sccp_wrapper_asterisk16_get_vrtp_peer, .set_rtp_peer = sccp_wrapper_asterisk16_set_rtp_peer, .get_codec = sccp_wrapper_asterisk16_getCodec, }; #endif #ifdef HAVE_PBX_MESSAGE_H #include "asterisk/message.h" static int sccp_asterisk_message_send(const struct ast_msg *msg, const char *to, const char *from) { char *lineName; sccp_line_t *line; const char *messageText = ast_msg_get_body(msg); int res = -1; lineName = (char *) sccp_strdupa(to); if (strchr(lineName, '@')) { strsep(&lineName, "@"); } else { strsep(&lineName, ":"); } if (sccp_strlen_zero(lineName)) { pbx_log(LOG_WARNING, "MESSAGE(to) is invalid for SCCP - '%s'\n", to); return -1; } line = sccp_line_find_byname(lineName, FALSE); if (!line) { pbx_log(LOG_WARNING, "line '%s' not found\n", lineName); return -1; } /** \todo move this to line implementation */ sccp_linedevices_t *linedevice; sccp_push_result_t pushResult; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { pushResult = linedevice->device->pushTextMessage(linedevice->device, messageText, from, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { res = 0; } } SCCP_LIST_UNLOCK(&line->devices); return res; } #if defined(__cplusplus) || defined(c_plusplus) static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ name: "sccp", msg_send:sccp_asterisk_message_send, /* *INDENT-ON* */ }; #else static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ .name = "sccp", .msg_send = sccp_asterisk_message_send, /* *INDENT-ON* */ }; #endif #endif boolean_t sccp_wrapper_asterisk_setLanguage(PBX_CHANNEL_TYPE * pbxChannel, const char *newLanguage) { ast_string_field_set(pbxChannel, language, newLanguage); return TRUE; } #if defined(__cplusplus) || defined(c_plusplus) sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ alloc_pbxChannel: sccp_wrapper_asterisk16_allocPBXChannel, set_callstate: sccp_wrapper_asterisk16_setCallState, checkhangup: sccp_wrapper_asterisk16_checkHangup, hangup: NULL, requestHangup: sccp_wrapper_asterisk_requestHangup, forceHangup: sccp_wrapper_asterisk_forceHangup, extension_status: sccp_wrapper_asterisk16_extensionStatus, setPBXChannelLinkedId: sccp_wrapper_asterisk_set_pbxchannel_linkedid, /** get channel by name */ getChannelByName: sccp_wrapper_asterisk16_getChannelByName, getRemoteChannel: sccp_asterisk_getRemoteChannel, getChannelByCallback: NULL, getChannelLinkedId: sccp_wrapper_asterisk_get_channel_linkedid, setChannelLinkedId: sccp_wrapper_asterisk_set_channel_linkedid, getChannelName: sccp_wrapper_asterisk_get_channel_name, setChannelName: sccp_wrapper_asterisk_set_channel_name, getChannelUniqueID: sccp_wrapper_asterisk_get_channel_uniqueid, getChannelExten: sccp_wrapper_asterisk_get_channel_exten, setChannelExten: sccp_wrapper_asterisk_set_channel_exten, getChannelContext: sccp_wrapper_asterisk_get_channel_context, setChannelContext: sccp_wrapper_asterisk_set_channel_context, getChannelMacroExten: sccp_wrapper_asterisk_get_channel_macroexten, setChannelMacroExten: sccp_wrapper_asterisk_set_channel_macroexten, getChannelMacroContext: sccp_wrapper_asterisk_get_channel_macrocontext, setChannelMacroContext: sccp_wrapper_asterisk_set_channel_macrocontext, getChannelCallForward: sccp_wrapper_asterisk_get_channel_call_forward, setChannelCallForward: sccp_wrapper_asterisk_set_channel_call_forward, getChannelAppl: sccp_wrapper_asterisk_get_channel_appl, getChannelState: sccp_wrapper_asterisk_get_channel_state, getChannelPbx: sccp_wrapper_asterisk_get_channel_pbx, setChannelTechPVT: sccp_wrapper_asterisk_set_channel_tech_pvt, set_nativeAudioFormats: sccp_wrapper_asterisk16_setNativeAudioFormats, set_nativeVideoFormats: sccp_wrapper_asterisk16_setNativeVideoFormats, getPeerCodecCapabilities: NULL, send_digit: sccp_wrapper_asterisk16_sendDigit, send_digits: sccp_wrapper_asterisk16_sendDigits, sched_add: sccp_wrapper_asterisk16_sched_add, sched_del: sccp_wrapper_asterisk16_sched_del, sched_when: sccp_wrapper_asterisk16_sched_when, sched_wait: sccp_wrapper_asterisk16_sched_wait, /* rtp */ rtp_getPeer: sccp_wrapper_asterisk16_rtpGetPeer, rtp_getUs: sccp_wrapper_asterisk16_rtpGetUs, rtp_setPeer: sccp_wrapper_asterisk16_rtp_set_peer, rtp_setWriteFormat: sccp_wrapper_asterisk16_setWriteFormat, rtp_setReadFormat: sccp_wrapper_asterisk16_setReadFormat, rtp_destroy: sccp_wrapper_asterisk16_destroyRTP, rtp_stop: sccp_wrapper_asterisk16_rtp_stop, rtp_codec: NULL, rtp_audio_create: sccp_wrapper_asterisk16_create_audio_rtp, rtp_video_create: sccp_wrapper_asterisk16_create_video_rtp, rtp_get_payloadType: sccp_wrapper_asterisk16_get_payloadType, rtp_get_sampleRate: sccp_wrapper_asterisk16_get_sampleRate, rtp_bridgePeers: NULL, /* callerid */ get_callerid_name: sccp_wrapper_asterisk16_callerid_name, get_callerid_number: sccp_wrapper_asterisk16_callerid_number, get_callerid_ton: sccp_wrapper_asterisk16_callerid_ton, get_callerid_ani: sccp_wrapper_asterisk16_callerid_ani, get_callerid_subaddr: NULL, get_callerid_dnid: sccp_wrapper_asterisk16_callerid_dnid, get_callerid_rdnis: sccp_wrapper_asterisk16_callerid_rdnis, get_callerid_presence: sccp_wrapper_asterisk16_callerid_presence, set_callerid_name: sccp_wrapper_asterisk16_setCalleridName, set_callerid_number: sccp_wrapper_asterisk16_setCalleridNumber, set_callerid_ani: NULL, set_callerid_dnid: NULL, set_callerid_redirectingParty: sccp_wrapper_asterisk16_setRedirectingParty, set_callerid_redirectedParty: sccp_wrapper_asterisk16_setRedirectedParty, set_callerid_presence: sccp_wrapper_asterisk16_setCalleridPresence, set_connected_line: sccp_wrapper_asterisk16_updateConnectedLine, sendRedirectedUpdate: sccp_asterisk_sendRedirectedUpdate, /* feature section */ feature_park: sccp_wrapper_asterisk16_park, feature_stopMusicOnHold: NULL, feature_addToDatabase: sccp_asterisk_addToDatabase, feature_getFromDatabase: sccp_asterisk_getFromDatabase, feature_removeFromDatabase: sccp_asterisk_removeFromDatabase, feature_removeTreeFromDatabase: sccp_asterisk_removeTreeFromDatabase, feature_monitor: sccp_wrapper_asterisk_featureMonitor, getFeatureExtension: NULL, feature_pickup: sccp_wrapper_asterisk16_pickupChannel, eventSubscribe: NULL, findChannelByCallback: sccp_wrapper_asterisk16_findChannelWithCallback, moh_start: sccp_asterisk_moh_start, moh_stop: sccp_asterisk_moh_stop, queue_control: sccp_asterisk_queue_control, queue_control_data: sccp_asterisk_queue_control_data, allocTempPBXChannel: sccp_wrapper_asterisk16_allocTempPBXChannel, masqueradeHelper: sccp_wrapper_asterisk16_masqueradeHelper, requestForeignChannel: sccp_wrapper_asterisk16_requestForeignChannel, set_language: sccp_wrapper_asterisk_setLanguage, getExtensionState: sccp_wrapper_asterisk106_getExtensionState, findPickupChannelByExtenLocked: sccp_wrapper_asterisk16_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #else /*! * \brief SCCP - PBX Callback Functions * (Decoupling Tight Dependencies on Asterisk Functions) */ struct sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ /* channel */ .alloc_pbxChannel = sccp_wrapper_asterisk16_allocPBXChannel, .requestHangup = sccp_wrapper_asterisk_requestHangup, .forceHangup = sccp_wrapper_asterisk_forceHangup, .extension_status = sccp_wrapper_asterisk16_extensionStatus, .setPBXChannelLinkedId = sccp_wrapper_asterisk_set_pbxchannel_linkedid, .getChannelByName = sccp_wrapper_asterisk16_getChannelByName, .getChannelLinkedId = sccp_wrapper_asterisk_get_channel_linkedid, .setChannelLinkedId = sccp_wrapper_asterisk_set_channel_linkedid, .getChannelName = sccp_wrapper_asterisk_get_channel_name, .setChannelName = sccp_wrapper_asterisk_set_channel_name, .getChannelUniqueID = sccp_wrapper_asterisk_get_channel_uniqueid, .getChannelExten = sccp_wrapper_asterisk_get_channel_exten, .setChannelExten = sccp_wrapper_asterisk_set_channel_exten, .getChannelContext = sccp_wrapper_asterisk_get_channel_context, .setChannelContext = sccp_wrapper_asterisk_set_channel_context, .getChannelMacroExten = sccp_wrapper_asterisk_get_channel_macroexten, .setChannelMacroExten = sccp_wrapper_asterisk_set_channel_macroexten, .getChannelMacroContext = sccp_wrapper_asterisk_get_channel_macrocontext, .setChannelMacroContext = sccp_wrapper_asterisk_set_channel_macrocontext, .getChannelCallForward = sccp_wrapper_asterisk_get_channel_call_forward, .setChannelCallForward = sccp_wrapper_asterisk_set_channel_call_forward, .getChannelAppl = sccp_wrapper_asterisk_get_channel_appl, .getChannelState = sccp_wrapper_asterisk_get_channel_state, .getChannelPbx = sccp_wrapper_asterisk_get_channel_pbx, .setChannelTechPVT = sccp_wrapper_asterisk_set_channel_tech_pvt, .getRemoteChannel = sccp_asterisk_getRemoteChannel, .checkhangup = sccp_wrapper_asterisk16_checkHangup, /* digits */ .send_digits = sccp_wrapper_asterisk16_sendDigits, .send_digit = sccp_wrapper_asterisk16_sendDigit, /* schedulers */ .sched_add = sccp_wrapper_asterisk16_sched_add, .sched_del = sccp_wrapper_asterisk16_sched_del, .sched_when = sccp_wrapper_asterisk16_sched_when, .sched_wait = sccp_wrapper_asterisk16_sched_wait, /* callstate / indicate */ .set_callstate = sccp_wrapper_asterisk16_setCallState, /* codecs */ .set_nativeAudioFormats = sccp_wrapper_asterisk16_setNativeAudioFormats, .set_nativeVideoFormats = sccp_wrapper_asterisk16_setNativeVideoFormats, /* rtp */ .rtp_getPeer = sccp_wrapper_asterisk16_rtpGetPeer, .rtp_getUs = sccp_wrapper_asterisk16_rtpGetUs, .rtp_stop = sccp_wrapper_asterisk16_rtp_stop, .rtp_audio_create = sccp_wrapper_asterisk16_create_audio_rtp, .rtp_video_create = sccp_wrapper_asterisk16_create_video_rtp, .rtp_get_payloadType = sccp_wrapper_asterisk16_get_payloadType, .rtp_get_sampleRate = sccp_wrapper_asterisk16_get_sampleRate, .rtp_destroy = sccp_wrapper_asterisk16_destroyRTP, .rtp_setWriteFormat = sccp_wrapper_asterisk16_setWriteFormat, .rtp_setReadFormat = sccp_wrapper_asterisk16_setReadFormat, .rtp_setPeer = sccp_wrapper_asterisk16_rtp_set_peer, /* callerid */ .get_callerid_name = sccp_wrapper_asterisk16_callerid_name, .get_callerid_number = sccp_wrapper_asterisk16_callerid_number, .get_callerid_ton = sccp_wrapper_asterisk16_callerid_ton, .get_callerid_ani = sccp_wrapper_asterisk16_callerid_ani, .get_callerid_subaddr = NULL, .get_callerid_dnid = sccp_wrapper_asterisk16_callerid_dnid, .get_callerid_rdnis = sccp_wrapper_asterisk16_callerid_rdnis, .get_callerid_presence = sccp_wrapper_asterisk16_callerid_presence, .set_callerid_name = sccp_wrapper_asterisk16_setCalleridName, //! \todo implement callback .set_callerid_number = sccp_wrapper_asterisk16_setCalleridNumber, //! \todo implement callback .set_callerid_dnid = NULL, //! \todo implement callback .set_callerid_redirectingParty = sccp_wrapper_asterisk16_setRedirectingParty, .set_callerid_redirectedParty = sccp_wrapper_asterisk16_setRedirectedParty, .set_callerid_presence = sccp_wrapper_asterisk16_setCalleridPresence, .set_connected_line = sccp_wrapper_asterisk16_updateConnectedLine, .sendRedirectedUpdate = sccp_asterisk_sendRedirectedUpdate, /* database */ .feature_addToDatabase = sccp_asterisk_addToDatabase, .feature_getFromDatabase = sccp_asterisk_getFromDatabase, .feature_removeFromDatabase = sccp_asterisk_removeFromDatabase, .feature_removeTreeFromDatabase = sccp_asterisk_removeTreeFromDatabase, .feature_monitor = sccp_wrapper_asterisk_featureMonitor, .feature_park = sccp_wrapper_asterisk16_park, .feature_pickup = sccp_wrapper_asterisk16_pickupChannel, .findChannelByCallback = sccp_wrapper_asterisk16_findChannelWithCallback, .moh_start = sccp_asterisk_moh_start, .moh_stop = sccp_asterisk_moh_stop, .queue_control = sccp_asterisk_queue_control, .queue_control_data = sccp_asterisk_queue_control_data, .allocTempPBXChannel = sccp_wrapper_asterisk16_allocTempPBXChannel, .masqueradeHelper = sccp_wrapper_asterisk16_masqueradeHelper, .requestForeignChannel = sccp_wrapper_asterisk16_requestForeignChannel, .set_language = sccp_wrapper_asterisk_setLanguage, .getExtensionState = sccp_wrapper_asterisk106_getExtensionState, .findPickupChannelByExtenLocked = sccp_wrapper_asterisk16_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #endif #if defined(__cplusplus) || defined(c_plusplus) static ast_module_load_result load_module(void) #else static int load_module(void) #endif { boolean_t res; /* check for existance of chan_skinny */ if (ast_module_check("chan_skinny.so")) { pbx_log(LOG_ERROR, "Chan_skinny is loaded. Please check modules.conf and remove chan_skinny before loading chan_sccp.\n"); return AST_MODULE_LOAD_DECLINE; } sched = sched_context_create(); if (!sched) { pbx_log(LOG_WARNING, "Unable to create schedule context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } /* make globals */ res = sccp_prePBXLoad(); if (!res) { return AST_MODULE_LOAD_DECLINE; } io = io_context_create(); if (!io) { pbx_log(LOG_WARNING, "Unable to create I/O context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } //! \todo how can we handle this in a pbx independent way? if (!load_config()) { if (ast_channel_register(&sccp_tech)) { pbx_log(LOG_ERROR, "Unable to register channel class SCCP\n"); return AST_MODULE_LOAD_FAILURE; } } #ifdef HAVE_PBX_MESSAGE_H if (ast_msg_tech_register(&sccp_msg_tech)) { /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */ pbx_log(LOG_WARNING, "Unable to register message interface\n"); } #endif ast_rtp_proto_register(&sccp_rtp); sccp_register_management(); sccp_register_cli(); sccp_register_dialplan_functions(); /* And start the monitor for the first time */ sccp_restart_monitor(); sccp_postPBX_load(); return AST_MODULE_LOAD_SUCCESS; } int sccp_restart_monitor() { /* If we're supposed to be stopped -- stay stopped */ if (GLOB(monitor_thread) == AST_PTHREADT_STOP) return 0; ast_mutex_lock(&GLOB(monitor_lock)); if (GLOB(monitor_thread) == pthread_self()) { ast_mutex_unlock(&GLOB(monitor_lock)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SCCP)) (VERBOSE_PREFIX_3 "SCCP: (sccp_restart_monitor) Cannot kill myself\n"); return -1; } if (GLOB(monitor_thread) != AST_PTHREADT_NULL) { /* Wake up the thread */ pthread_kill(GLOB(monitor_thread), SIGURG); } else { /* Start a new monitor */ if (ast_pthread_create_background(&GLOB(monitor_thread), NULL, sccp_do_monitor, NULL) < 0) { ast_mutex_unlock(&GLOB(monitor_lock)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SCCP)) (VERBOSE_PREFIX_3 "SCCP: (sccp_restart_monitor) Unable to start monitor thread.\n"); return -1; } } ast_mutex_unlock(&GLOB(monitor_lock)); return 0; } static int unload_module(void) { sccp_preUnload(); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP RTP protocol\n"); ast_rtp_proto_unregister(&sccp_rtp); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP Channel Tech\n"); ast_channel_unregister(&sccp_tech); sccp_unregister_dialplan_functions(); sccp_unregister_cli(); sccp_mwi_module_stop(); #ifdef CS_SCCP_MANAGER sccp_unregister_management(); #endif #ifdef HAVE_PBX_MESSAGE_H ast_msg_tech_unregister(&sccp_msg_tech); #endif sccp_globals_lock(monitor_lock); if ((GLOB(monitor_thread) != AST_PTHREADT_NULL) && (GLOB(monitor_thread) != AST_PTHREADT_STOP)) { pthread_cancel(GLOB(monitor_thread)); pthread_kill(GLOB(monitor_thread), SIGURG); #ifndef HAVE_LIBGC pthread_join(GLOB(monitor_thread), NULL); #endif } GLOB(monitor_thread) = AST_PTHREADT_STOP; if (io) { io_context_destroy(io); io = NULL; } while (SCCP_REF_DESTROYED != sccp_refcount_isRunning()) { usleep(SCCP_TIME_TO_KEEP_REFCOUNTEDOBJECT); // give enough time for all schedules to end and refcounted object to be cleanup completely } if (sched) { pbx_log(LOG_NOTICE, "Cleaning up scheduled items:\n"); int scheduled_items = 0; ast_sched_dump(sched); while ((scheduled_items = ast_sched_runq(sched))) { pbx_log(LOG_NOTICE, "Cleaning up %d scheduled items... please wait\n", scheduled_items); usleep(ast_sched_wait(sched)); } sched = NULL; } sccp_globals_unlock(monitor_lock); sccp_mutex_destroy(&GLOB(monitor_lock)); sccp_free(sccp_globals); pbx_log(LOG_NOTICE, "Running Cleanup\n"); #ifdef HAVE_LIBGC // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Collect a little:%d\n",GC_collect_a_little()); // CHECK_LEAKS(); // GC_gcollect(); #endif pbx_log(LOG_NOTICE, "Module chan_sccp unloaded\n"); return 0; } #if ASTERSIK_VERSION_NUMBER > 10601 static int module_reload(void) { sccp_reload(); return 0; } #endif #if defined(__cplusplus) || defined(c_plusplus) static struct ast_module_info __mod_info = { NULL, load_module, module_reload, unload_module, NULL, NULL, AST_MODULE, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)", ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, AST_BUILDOPT_SUM, AST_MODPRI_CHANNEL_DRIVER, NULL, }; static void __attribute__ ((constructor)) __reg_module(void) { ast_module_register(&__mod_info); } static void __attribute__ ((destructor)) __unreg_module(void) { ast_module_unregister(&__mod_info); } static const __attribute__ ((unused)) struct ast_module_info *ast_module_info = &__mod_info; #else #if ASTERISK_VERSION_NUMBER > 10601 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)",.load = load_module,.unload = unload_module,); #else AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "')"); #endif #endif PBX_CHANNEL_TYPE *sccp_search_remotepeer_locked(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data) { PBX_CHANNEL_TYPE *remotePeer; remotePeer = ast_channel_search_locked(found_cb, data); return remotePeer; } /* sccp_wrapper_asterisk16_findPickupChannelByExtenLocked helper functions */ /* Helper function that determines whether a channel is capable of being picked up */ static int can_pickup(struct ast_channel *chan) { if (!chan->pbx && !chan->masq && !ast_test_flag(chan, AST_FLAG_ZOMBIE) && (chan->_state == AST_STATE_RINGING || chan->_state == AST_STATE_RING || chan->_state == AST_STATE_DOWN)) { return 1; } return 0; } struct pickup_criteria { const char *exten; const char *context; struct ast_channel *chan; }; static int sccp_find_pbxchannel_by_exten(PBX_CHANNEL_TYPE * c, void *data) { struct pickup_criteria *info = data; return (!strcasecmp(c->macroexten, info->exten) || !strcasecmp(c->exten, info->exten)) && !strcasecmp(c->dialcontext, info->context) && (info->chan != c) && can_pickup(c); } /* end sccp_wrapper_asterisk16_findPickupChannelByExtenLocked helper functions */ PBX_CHANNEL_TYPE *sccp_wrapper_asterisk16_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context) { struct ast_channel *target = NULL; /*!< Potential pickup target */ struct pickup_criteria search = { .exten = exten, .context = context, .chan = chan, }; target = ast_channel_search_locked(sccp_find_pbxchannel_by_exten, &search); return target; }
722,272
./chan-sccp-b/src/pbx_impl/ast/ast110.c
/*! * \file ast110.c * \brief SCCP PBX Asterisk Wrapper Class * \author Marcello Ceshia * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #include <config.h> #include "../../common.h" #include "ast110.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include <asterisk/sched.h> #include <asterisk/netsock2.h> #include <asterisk/format.h> #include <asterisk/cel.h> #define new avoid_cxx_new_keyword #include <asterisk/rtp_engine.h> #undef new #if defined(__cplusplus) || defined(c_plusplus) } #endif struct ast_sched_context *sched = 0; struct io_context *io = 0; struct ast_format slinFormat = { AST_FORMAT_SLINEAR, {{0}, 0} }; static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk110_request(const char *type, struct ast_format_cap *format, const PBX_CHANNEL_TYPE * requestor, void *data, int *cause); static int sccp_wrapper_asterisk110_call(PBX_CHANNEL_TYPE * chan, char *addr, int timeout); static int sccp_wrapper_asterisk110_answer(PBX_CHANNEL_TYPE * chan); static PBX_FRAME_TYPE *sccp_wrapper_asterisk110_rtp_read(PBX_CHANNEL_TYPE * ast); static int sccp_wrapper_asterisk110_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame); static int sccp_wrapper_asterisk110_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen); static int sccp_wrapper_asterisk110_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan); static enum ast_bridge_result sccp_wrapper_asterisk110_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms); static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text); static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit); static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration); static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen); int sccp_wrapper_asterisk110_hangup(PBX_CHANNEL_TYPE * ast_channel); boolean_t sccp_wrapper_asterisk110_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId); int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control); int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen); static int sccp_wrapper_asterisk110_devicestate(void *data); PBX_CHANNEL_TYPE *sccp_wrapper_asterisk110_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context); skinny_codec_t sccp_asterisk10_getSkinnyFormatSingle(struct ast_format_cap *ast_format_capability) { struct ast_format tmp_fmt; uint8_t i; skinny_codec_t codec = SKINNY_CODEC_NONE; ast_format_cap_iter_start(ast_format_capability); while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) { for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == tmp_fmt.id) { codec = skinny2pbx_codec_maps[i].skinny_codec; break; } } if (codec != SKINNY_CODEC_NONE) { break; } } ast_format_cap_iter_end(ast_format_capability); return codec; } static uint8_t sccp_asterisk10_getSkinnyFormatMultiple(struct ast_format_cap *ast_format_capability, skinny_codec_t codec[], int length) { struct ast_format tmp_fmt; uint8_t i; uint8_t position = 0; ast_format_cap_iter_start(ast_format_capability); while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt) && position < length) { for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == tmp_fmt.id) { codec[position++] = skinny2pbx_codec_maps[i].skinny_codec; break; } } } ast_format_cap_iter_end(ast_format_capability); return position; } #if defined(__cplusplus) || defined(c_plusplus) /*! * \brief SCCP Tech Structure */ static struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, description: "Skinny Client Control Protocol (SCCP)", // capabilities: AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_SLINEAR16 | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A | AST_FORMAT_H264 | AST_FORMAT_H263_PLUS, properties: AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, requester: sccp_wrapper_asterisk110_request, devicestate: sccp_wrapper_asterisk110_devicestate, send_digit_begin: sccp_wrapper_recvdigit_begin, send_digit_end: sccp_wrapper_recvdigit_end, call: sccp_wrapper_asterisk110_call, hangup: sccp_wrapper_asterisk110_hangup, answer: sccp_wrapper_asterisk110_answer, read: sccp_wrapper_asterisk110_rtp_read, write: sccp_wrapper_asterisk110_rtp_write, send_text: sccp_pbx_sendtext, send_image: NULL, send_html: sccp_pbx_sendHTML, exception: NULL, bridge: sccp_wrapper_asterisk110_rtpBridge, early_bridge: NULL, indicate: sccp_wrapper_asterisk110_indicate, fixup: sccp_wrapper_asterisk110_fixup, setoption: NULL, queryoption: NULL, transfer: NULL, write_video: sccp_wrapper_asterisk110_rtp_write, write_text: NULL, bridged_channel: NULL, func_channel_read: sccp_wrapper_asterisk_channel_read, func_channel_write: sccp_asterisk_pbx_fktChannelWrite, get_base_channel: NULL, set_base_channel: NULL /* *INDENT-ON* */ }; #else /*! * \brief SCCP Tech Structure */ struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .description = "Skinny Client Control Protocol (SCCP)", // we could use the skinny_codec = ast_codec mapping here to generate the list of capabilities // .capabilities = AST_FORMAT_SLINEAR16 | AST_FORMAT_SLINEAR | AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A, .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, .requester = sccp_wrapper_asterisk110_request, .devicestate = sccp_wrapper_asterisk110_devicestate, .call = sccp_wrapper_asterisk110_call, .hangup = sccp_wrapper_asterisk110_hangup, .answer = sccp_wrapper_asterisk110_answer, .read = sccp_wrapper_asterisk110_rtp_read, .write = sccp_wrapper_asterisk110_rtp_write, .write_video = sccp_wrapper_asterisk110_rtp_write, .indicate = sccp_wrapper_asterisk110_indicate, .fixup = sccp_wrapper_asterisk110_fixup, .transfer = sccp_pbx_transfer, .bridge = sccp_wrapper_asterisk110_rtpBridge, //.early_bridge = ast_rtp_early_bridge, //.bridged_channel = .send_text = sccp_pbx_sendtext, .send_html = sccp_pbx_sendHTML, //.send_html = //.send_image = .func_channel_read = sccp_wrapper_asterisk_channel_read, .func_channel_write = sccp_asterisk_pbx_fktChannelWrite, .send_digit_begin = sccp_wrapper_recvdigit_begin, .send_digit_end = sccp_wrapper_recvdigit_end, //.write_text = //.write_video = //.cc_callback = // ccss, new >1.6.0 //.exception = // new >1.6.0 // .setoption = sccp_wrapper_asterisk110_setOption, //.queryoption = // new >1.6.0 //.get_pvt_uniqueid = sccp_pbx_get_callid, // new >1.6.0 //.get_base_channel = //.set_base_channel = /* *INDENT-ON* */ }; #endif static int sccp_wrapper_asterisk110_devicestate(void *data) { int res = AST_DEVICE_UNKNOWN; char *lineName = (char *) data; char *deviceId = NULL; sccp_channelstate_t state; if ((deviceId = strchr(lineName, '@'))) { *deviceId = '\0'; deviceId++; } state = sccp_hint_getLinestate(lineName, deviceId); switch (state) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: res = AST_DEVICE_NOT_INUSE; break; case SCCP_CHANNELSTATE_RINGING: res = AST_DEVICE_RINGING; break; case SCCP_CHANNELSTATE_HOLD: res = AST_DEVICE_ONHOLD; break; case SCCP_CHANNELSTATE_INVALIDNUMBER: res = AST_DEVICE_INVALID; break; case SCCP_CHANNELSTATE_BUSY: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_DND: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: res = AST_DEVICE_UNAVAILABLE; break; case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_PROGRESS: case SCCP_CHANNELSTATE_CALLWAITING: res = AST_DEVICE_RINGINUSE; break; case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: res = AST_DEVICE_INUSE; break; } sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: (sccp_asterisk_devicestate) PBX requests state for '%s' - state %s\n", (char *) lineName, ast_devstate2str(res)); return res; } /*! * \brief Convert an array of skinny_codecs (enum) to ast_codec_prefs * * \param skinny_codecs Array of Skinny Codecs * \param astCodecPref Array of PBX Codec Preferences * * \return bit array fmt/Format of ast_format_type (int) * * \todo check bitwise operator (not sure) - DdG */ int skinny_codecs2pbx_codec_pref(skinny_codec_t * skinny_codecs, struct ast_codec_pref *astCodecPref) { struct ast_format *dst = NULL; uint32_t codec = skinny_codecs2pbx_codecs(skinny_codecs); // convert to bitfield dst = ast_format_from_old_bitfield(dst, codec); // convert bitfield to ast_format return ast_codec_pref_append(astCodecPref, dst); // return ast_codec_pref } static boolean_t sccp_wrapper_asterisk110_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); #define RTP_NEW_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_new_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } #define RTP_CHANGE_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_change_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } // static void get_skinnyFormats(struct ast_format_cap *format, skinny_codec_t codecs[], size_t size) // { // unsigned int x; // unsigned len = 0; // // size_t f_len; // struct ast_format tmp_fmt; // const struct ast_format_list *f_list = ast_format_list_get(&f_len); // // if (!size) { // f_list = ast_format_list_destroy(f_list); // return; // } // // for (x = 0; x < ARRAY_LEN(skinny2pbx_codec_maps) && len <= size; x++) { // ast_format_copy(&tmp_fmt, &f_list[x].format); // if (ast_format_cap_iscompatible(format, &tmp_fmt)) { // if (skinny2pbx_codec_maps[x].pbx_codec == ((uint) tmp_fmt.id)) { // codecs[len++] = skinny2pbx_codec_maps[x].skinny_codec; // } // } // } // f_list = ast_format_list_destroy(f_list); // } /*************************************************************************************************************** CODEC **/ /*! \brief Get the name of a format * \note replacement for ast_getformatname * \param format id of format * \return A static string containing the name of the format or "unknown" if unknown. */ const char *pbx_getformatname(const struct ast_format *format) { return ast_getformatname(format); } /*! * \brief Get the names of a set of formats * \note replacement for ast_getformatname_multiple * \param buf a buffer for the output string * \param size size of buf (bytes) * \param format the format (combined IDs of codecs) * Prints a list of readable codec names corresponding to "format". * ex: for format=AST_FORMAT_GSM|AST_FORMAT_SPEEX|AST_FORMAT_ILBC it will return "0x602 (GSM|SPEEX|ILBC)" * \return The return value is buf. */ char *pbx_getformatname_multiple(char *buf, size_t size, struct ast_format_cap *format) { return ast_getformatname_multiple(buf, size, format); } /*! * \brief Read from an Asterisk Channel * \param ast Asterisk Channel as ast_channel * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static PBX_FRAME_TYPE *sccp_wrapper_asterisk110_rtp_read(PBX_CHANNEL_TYPE * ast) { sccp_channel_t *c = NULL; PBX_FRAME_TYPE *frame = NULL; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) { // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return &ast_null_frame; } if (!c->rtp.audio.rtp) { // c = sccp_channel_release(c); return &ast_null_frame; } switch (ast->fdno) { case 0: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 0); /* RTP Audio */ break; case 1: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 1); /* RTCP Control Channel */ break; #ifdef CS_SCCP_VIDEO case 2: frame = ast_rtp_instance_read(c->rtp.video.rtp, 0); /* RTP Video */ break; case 3: frame = ast_rtp_instance_read(c->rtp.video.rtp, 1); /* RTCP Control Channel for video */ break; #endif default: break; } if (!frame) { pbx_log(LOG_WARNING, "%s: error reading frame == NULL\n", c->currentDeviceId); // c = sccp_channel_release(c); return &ast_null_frame; } else { //sccp_log((DEBUGCAT_CORE))(VERBOSE_PREFIX_3 "%s: read format: ast->fdno: %d, frametype: %d, %s(%d)\n", DEV_ID_LOG(c->device), ast->fdno, frame->frametype, pbx_getformatname(frame->subclass), frame->subclass); if (frame->frametype == AST_FRAME_VOICE) { #ifdef CS_SCCP_CONFERENCE if (c->conference && (!ast_format_is_slinear(&ast->readformat))) { ast_set_read_format(ast, &slinFormat); } else #endif if (ast_format_cmp(&frame->subclass.format, &ast->rawreadformat) == AST_FORMAT_CMP_NOT_EQUAL) { ast_set_read_format_by_id(ast, frame->subclass.format.id); } } } // // c = sccp_channel_release(c); return frame; } /*! * \brief Find Asterisk/PBX channel by linkid * * \param ast pbx channel * \param data linkId as void * * * \return int * * \todo I don't understand what this functions returns */ static int pbx_find_channel_by_linkid(PBX_CHANNEL_TYPE * ast, const void *data) { const char *linkId = (char *) data; if (!data) return 0; return !ast->pbx && ast->linkedid && (!strcasecmp(ast->linkedid, linkId)) && !ast->masq; } /*! * \brief Update Connected Line * \param channel Asterisk Channel as ast_channel * \param data Asterisk Data * \param datalen Asterisk Data Length */ static void sccp_wrapper_asterisk110_connectedline(sccp_channel_t * channel, const void *data, size_t datalen) { PBX_CHANNEL_TYPE *ast = channel->owner; sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: Got connected line update, connected.id.number=%s, connected.id.name=%s, reason=%d\n", pbx_channel_name(ast), ast->connected.id.number.str ? ast->connected.id.number.str : "(nil)", ast->connected.id.name.str ? ast->connected.id.name.str : "(nil)", ast->connected.source); // sccp_channel_display_callInfo(channel); /* set the original calling/called party if the reason is a transfer */ if (ast->connected.source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER || ast->connected.source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING) { if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Destination\n"); if (ast->connected.id.number.str && !sccp_strlen_zero(ast->connected.id.number.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, ast->connected.id.number.str, sizeof(channel->callInfo.originalCallingPartyNumber)); channel->callInfo.originalCallingParty_valid = 1; } if (ast->connected.id.name.str && !sccp_strlen_zero(ast->connected.id.name.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyName, ast->connected.id.name.str, sizeof(channel->callInfo.originalCallingPartyName)); } if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.callingPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } else { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Transferee\n"); if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyNumber)); sccp_copy_string(channel->callInfo.originalCallingPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyName)); channel->callInfo.originalCallingParty_valid = 1; } if (channel->callInfo.calledParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.calledPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } channel->callInfo.originalCdpnRedirectReason = channel->callInfo.lastRedirectingReason; channel->callInfo.lastRedirectingReason = 0; // need to figure out these codes } if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { if (ast->connected.id.number.str && !sccp_strlen_zero(ast->connected.id.number.str)) sccp_copy_string(channel->callInfo.callingPartyNumber, ast->connected.id.number.str, sizeof(channel->callInfo.callingPartyNumber)); if (ast->connected.id.name.str && !sccp_strlen_zero(ast->connected.id.name.str)) sccp_copy_string(channel->callInfo.callingPartyName, ast->connected.id.name.str, sizeof(channel->callInfo.callingPartyName)); } else { if (ast->connected.id.number.str && !sccp_strlen_zero(ast->connected.id.number.str)) sccp_copy_string(channel->callInfo.calledPartyNumber, ast->connected.id.number.str, sizeof(channel->callInfo.calledPartyNumber)); if (ast->connected.id.name.str && !sccp_strlen_zero(ast->connected.id.name.str)) sccp_copy_string(channel->callInfo.calledPartyName, ast->connected.id.name.str, sizeof(channel->callInfo.calledPartyName)); } sccp_channel_display_callInfo(channel); sccp_channel_send_callinfo2(channel); } static int sccp_wrapper_asterisk110_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { switch (ind) { case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk110_connectedline(c, data, datalen); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); res = 0; break; default: res = -1; break; } c = sccp_channel_release(c); return res; } if (c->state == SCCP_CHANNELSTATE_DOWN) { c = sccp_channel_release(c); d = sccp_device_release(d); return -1; } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Asterisk indicate '%d' condition on channel %s\n", DEV_ID_LOG(d), ind, ast->name); /* when the rtp media stream is open we will let asterisk emulate the tones */ res = (((c->rtp.audio.readState != SCCP_RTP_STATUS_INACTIVE) || (d && d->earlyrtp)) ? -1 : 0); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: readStat: %d\n", DEV_ID_LOG(d), c->rtp.audio.readState); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: res: %d\n", DEV_ID_LOG(d), res); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: rtp?: %s\n", DEV_ID_LOG(d), (c->rtp.audio.rtp) ? "yes" : "no"); switch (ind) { case AST_CONTROL_RINGING: if (SKINNY_CALLTYPE_OUTBOUND == c->calltype) { // Allow signalling of RINGOUT only on outbound calls. // Otherwise, there are some issues with late arrival of ringing // indications on ISDN calls (chan_lcr, chan_dahdi) (-DD). sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGOUT); struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; /*! \todo handle multiple remotePeers i.e. DIAL(SCCP/400&SIP/300), find smallest common codecs, what order to use ? */ PBX_CHANNEL_TYPE *remotePeer; for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { if (pbx_find_channel_by_linkid(remotePeer, (void *) ast->linkedid)) { char buf[512]; sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(remotePeer); if (remoteSccpChannel) { sccp_multiple_codecs2str(buf, sizeof(buf) - 1, remoteSccpChannel->preferences.audio, ARRAY_LEN(remoteSccpChannel->preferences.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote preferences: %s\n", buf); uint8_t x, y, z; z = 0; for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { c->remoteCapabilities.audio[z++] = remoteSccpChannel->preferences.audio[x]; break; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote nativeformats: %s\n", pbx_getformatname_multiple(buf, sizeof(buf) - 1, remotePeer->nativeformats)); sccp_asterisk10_getSkinnyFormatMultiple(remotePeer->nativeformats, c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); } sccp_multiple_codecs2str(buf, sizeof(buf) - 1, c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote caps: %s\n", buf); remotePeer = ast_channel_unref(remotePeer); break; } } ast_channel_iterator_destroy(iterator); } break; case AST_CONTROL_BUSY: sccp_indicate(d, c, SCCP_CHANNELSTATE_BUSY); break; case AST_CONTROL_CONGESTION: sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); break; case AST_CONTROL_PROGRESS: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROGRESS); res = -1; break; case AST_CONTROL_PROCEEDING: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROCEED); res = -1; break; case AST_CONTROL_SRCCHANGE: if (c->rtp.audio.rtp) ast_rtp_instance_change_source(c->rtp.audio.rtp); res = 0; break; case AST_CONTROL_SRCUPDATE: /* Source media has changed. */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Source UPDATE request\n"); if (c->rtp.audio.rtp) { ast_rtp_instance_change_source(c->rtp.audio.rtp); } /** this is a dirty workaround to fix audio issue while pickup a parked call * reason: asterisk do not indicate connected if we dial to a parked extension * -MC */ if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: force CONNECT\n"); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTED); } res = 0; break; /* when the bridged channel hold/unhold the call we are notified here */ case AST_CONTROL_HOLD: sccp_asterisk_moh_start(ast, (const char *) data, c->musicclass); res = 0; break; case AST_CONTROL_UNHOLD: sccp_asterisk_moh_stop(ast); if (c->rtp.audio.rtp) { ast_rtp_instance_update_source(c->rtp.audio.rtp); } res = 0; break; case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk110_connectedline(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ if (c->rtp.video.rtp && d && sccp_device_isVideoSupported(d)) { d->protocol->sendFastPictureUpdate(d, c); res = 0; } else res = -1; break; #ifdef CS_AST_CONTROL_INCOMPLETE case AST_CONTROL_INCOMPLETE: /*!< Indication that the extension dialed is incomplete */ /* \todo implement dial continuation by: * - display message incomplete number * - adding time to channel->scheduler.digittimeout * - rescheduling sccp_pbx_sched_dial */ #ifdef CS_EXPERIMENTAL if (c->scheduler.digittimeout) { SCCP_SCHED_DEL(c->scheduler.digittimeout); } sccp_indicate(d, c, SCCP_CHANNELSTATE_DIGITSFOLL); c->scheduler.digittimeout = PBX(sched_add) (c->enbloc.digittimeout, sccp_pbx_sched_dial, c); #endif res = 0; break; #endif case -1: // Asterisk prod the channel res = -1; break; default: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Don't know how to indicate condition %d\n", ind); res = -1; } //ast_cond_signal(&c->astStateCond); d = sccp_device_release(d); c = sccp_channel_release(c); sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: send asterisk result %d\n", res); return res; } /*! * \brief Write to an Asterisk Channel * \param ast Channel as ast_channel * \param frame Frame as ast_frame * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static int sccp_wrapper_asterisk110_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame) { sccp_channel_t *c = NULL; int res = 0; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) { // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return -1; } switch (frame->frametype) { case AST_FRAME_VOICE: // checking for samples to transmit if (!frame->samples) { if (strcasecmp(frame->src, "ast_prod")) { pbx_log(LOG_ERROR, "%s: Asked to transmit frame type %d with no samples.\n", c->currentDeviceId, (int) frame->frametype); } else { // frame->samples == 0 when frame_src is ast_prod sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Asterisk prodded channel %s.\n", c->currentDeviceId, ast->name); } } if (c->rtp.audio.rtp) { res = ast_rtp_instance_write(c->rtp.audio.rtp, frame); } break; case AST_FRAME_IMAGE: case AST_FRAME_VIDEO: #ifdef CS_SCCP_VIDEO if (c->rtp.video.writeState == SCCP_RTP_STATUS_INACTIVE && c->rtp.video.rtp && c->state != SCCP_CHANNELSTATE_HOLD // && (c->device->capability & frame->subclass) ) { // int codec = pbx_codec2skinny_codec((frame->subclass.codec & AST_FORMAT_VIDEO_MASK)); int codec = pbx_codec2skinny_codec((frame->frametype == AST_FRAME_VIDEO)); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: got video frame %d\n", c->currentDeviceId, codec); if (0 != codec) { c->rtp.video.writeFormat = codec; sccp_channel_openMultiMediaChannel(c); } } if (c->rtp.video.rtp && (c->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE) != 0) { res = ast_rtp_instance_write(c->rtp.video.rtp, frame); } #endif break; case AST_FRAME_TEXT: case AST_FRAME_MODEM: default: pbx_log(LOG_WARNING, "%s: Can't send %d type frames with SCCP write on channel %s\n", c->currentDeviceId, frame->frametype, ast->name); break; } // c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk110_sendDigits(const sccp_channel_t * channel, const char *digits) { if (!channel || !channel->owner) { pbx_log(LOG_WARNING, "No channel to send digits to\n"); return 0; } PBX_CHANNEL_TYPE *pbx_channel = channel->owner; int i; PBX_FRAME_TYPE f; f = ast_null_frame; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digits '%s'\n", (char *) channel->currentDeviceId, digits); // We don't just call sccp_pbx_senddigit due to potential overhead, and issues with locking f.src = "SCCP"; // CS_AST_NEW_FRAME_STRUCT // f.frametype = AST_FRAME_DTMF_BEGIN; // ast_queue_frame(pbx_channel, &f); for (i = 0; digits[i] != '\0'; i++) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digit %c\n", (char *) channel->currentDeviceId, digits[i]); f.frametype = AST_FRAME_DTMF_END; // Sending only the dmtf will force asterisk to start with DTMF_BEGIN and schedule the DTMF_END f.subclass.integer = digits[i]; // f.samples = SCCP_MIN_DTMF_DURATION * 8; f.len = SCCP_MIN_DTMF_DURATION; f.src = "SEND DIGIT"; ast_queue_frame(pbx_channel, &f); } return 1; } static int sccp_wrapper_asterisk110_sendDigit(const sccp_channel_t * channel, const char digit) { char digits[3] = "\0\0"; digits[0] = digit; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: got a single digit '%c' -> '%s'\n", channel->currentDeviceId, digit, digits); return sccp_wrapper_asterisk110_sendDigits(channel, digits); } static void sccp_wrapper_asterisk110_setCalleridPresence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (CALLERID_PRESENCE_FORBIDDEN == channel->callInfo.presentation) { pbx_channel->caller.id.name.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; pbx_channel->caller.id.number.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; } } static int sccp_wrapper_asterisk110_setNativeAudioFormats(const sccp_channel_t * channel, skinny_codec_t codec[], int length) { struct ast_format fmt; int i; ast_debug(10, "%s: set native Formats length: %d\n", (char *) channel->currentDeviceId, length); ast_format_cap_remove_bytype(channel->owner->nativeformats, AST_FORMAT_TYPE_AUDIO); for (i = 0; i < length; i++) { ast_format_set(&fmt, skinny_codec2pbx_codec(codec[i]), 0); ast_format_cap_add(channel->owner->nativeformats, &fmt); } return 1; } static int sccp_wrapper_asterisk110_setNativeVideoFormats(const sccp_channel_t * channel, uint32_t formats) { return 1; } boolean_t sccp_wrapper_asterisk110_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId) { sccp_line_t *line = NULL; (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, linkedId, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); if ((*pbx_channel) == NULL) { return FALSE; } if (!channel || !channel->line) { return FALSE; } line = channel->line; (*pbx_channel)->tech = &sccp_tech; (*pbx_channel)->tech_pvt = sccp_channel_retain(channel); memset((*pbx_channel)->exten, 0, sizeof((*pbx_channel)->exten)); sccp_copy_string((*pbx_channel)->context, line->context, sizeof((*pbx_channel)->context)); if (!sccp_strlen_zero(line->language)) ast_string_field_set((*pbx_channel), language, line->language); if (!sccp_strlen_zero(line->accountcode)) ast_string_field_set((*pbx_channel), accountcode, line->accountcode); if (!sccp_strlen_zero(line->musicclass)) ast_string_field_set((*pbx_channel), musicclass, line->musicclass); if (line->amaflags) (*pbx_channel)->amaflags = line->amaflags; if (line->callgroup) (*pbx_channel)->callgroup = line->callgroup; #if CS_SCCP_PICKUP if (line->pickupgroup) (*pbx_channel)->pickupgroup = line->pickupgroup; #endif (*pbx_channel)->priority = 1; (*pbx_channel)->adsicpe = AST_ADSI_UNAVAILABLE; /** the the tonezone using language information */ if (!sccp_strlen_zero(line->language) && ast_get_indication_zone(line->language)) { (*pbx_channel)->zone = ast_get_indication_zone(line->language); /* this will core asterisk on hangup */ } ast_module_ref(ast_module_info->self); channel->owner = ast_channel_ref((*pbx_channel)); return TRUE; } static boolean_t sccp_wrapper_asterisk110_masqueradeHelper(PBX_CHANNEL_TYPE * pbxChannel, PBX_CHANNEL_TYPE * pbxTmpChannel) { pbx_moh_stop(pbxChannel); // Masquerade setup and execution must be done without any channel locks held if (pbx_channel_masquerade(pbxTmpChannel, pbxChannel)) { return FALSE; } //pbxTmpChannel->_state = AST_STATE_UP; pbx_do_masquerade(pbxTmpChannel); // when returning from bridge, the channel will continue at the next priority // ast_explicit_goto(pbxTmpChannel, pbx_channel_context(pbxTmpChannel), pbx_channel_exten(pbxTmpChannel), pbx_channel_priority(pbxTmpChannel) + 1); return TRUE; } static boolean_t sccp_wrapper_asterisk110_allocTempPBXChannel(PBX_CHANNEL_TYPE * pbxSrcChannel, PBX_CHANNEL_TYPE ** pbxDstChannel) { struct ast_format tmpfmt; if (!pbxSrcChannel) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) no pbx channel provided\n"); return FALSE; } (*pbxDstChannel) = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, pbxSrcChannel->accountcode, pbxSrcChannel->exten, pbxSrcChannel->context, pbxSrcChannel->linkedid, pbxSrcChannel->amaflags, "TMP/%s", pbxSrcChannel->name); if ((*pbxDstChannel) == NULL) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) create pbx channel failed\n"); return FALSE; } ast_channel_lock(pbxSrcChannel); if (ast_format_cap_is_empty(pbxSrcChannel->nativeformats)) { ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0); } else { ast_best_codec(pbxSrcChannel->nativeformats, &tmpfmt); } ast_format_cap_add((*pbxDstChannel)->nativeformats, &tmpfmt); ast_set_read_format((*pbxDstChannel), &tmpfmt); ast_set_write_format((*pbxDstChannel), &tmpfmt); sccp_copy_string((*pbxDstChannel)->context, pbxSrcChannel->context, sizeof((*pbxDstChannel)->context)); sccp_copy_string((*pbxDstChannel)->exten, pbxSrcChannel->exten, sizeof((*pbxDstChannel)->exten)); (*pbxDstChannel)->priority = pbxSrcChannel->priority; ast_channel_unlock(pbxSrcChannel); return TRUE; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk110_requestForeignChannel(const char *type, pbx_format_type format, const PBX_CHANNEL_TYPE * requestor, void *data) { PBX_CHANNEL_TYPE *chan; int cause; struct ast_format_cap *cap; struct ast_format tmpfmt; if (!(cap = ast_format_cap_alloc_nolock())) { return 0; } ast_format_cap_add(cap, ast_format_set(&tmpfmt, format, 0)); if (!(chan = ast_request(type, cap, NULL, "", &cause))) { pbx_log(LOG_ERROR, "SCCP: Requested channel could not be created, cause: %d\n", cause); cap = ast_format_cap_destroy(cap); return NULL; } cap = ast_format_cap_destroy(cap); return chan; } int sccp_wrapper_asterisk110_hangup(PBX_CHANNEL_TYPE * ast_channel) { sccp_channel_t *c = NULL; PBX_CHANNEL_TYPE *channel_owner = NULL; int res = -1; if ((c = get_sccp_channel_from_pbx_channel(ast_channel))) { channel_owner = c->owner; if (ast_test_flag(ast_channel, AST_FLAG_ANSWERED_ELSEWHERE) || ast_channel->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: This call was answered elsewhere\n"); c->answered_elsewhere = TRUE; } res = sccp_pbx_hangup(c); c->owner = NULL; if (0 == res) { sccp_channel_release(c); //this only releases the get_sccp_channel_from_pbx_channel } } //after this moment c might have gone already ast_channel->tech_pvt = NULL; c = c ? sccp_channel_release(c) : NULL; if (channel_owner) { channel_owner = ast_channel_unref(channel_owner); } ast_module_unref(ast_module_info->self); return res; } /*! * \brief Park the bridge channel of hostChannel * This function prepares the host and the bridged channel to be ready for parking. * It clones the pbx channel of both sides forward them to the park_thread * * \param hostChannel initial channel that request the parking * \todo we have a codec issue after unpark a call * \todo copy connected line info * */ static sccp_parkresult_t sccp_wrapper_asterisk110_park(const sccp_channel_t * hostChannel) { int extout; char extstr[20]; sccp_device_t *device; sccp_parkresult_t res = PARK_RESULT_FAIL; PBX_CHANNEL_TYPE *bridgedChannel = NULL; memset(extstr, 0, sizeof(extstr)); extstr[0] = 128; extstr[1] = SKINNY_LBL_CALL_PARK_AT; bridgedChannel = ast_bridged_channel(hostChannel->owner); device = sccp_channel_getDevice_retained(hostChannel); ast_channel_lock(hostChannel->owner); /* we have to lock our channel, otherwise asterisk crashes internally */ if (!ast_masq_park_call(bridgedChannel, hostChannel->owner, 0, &extout)) { sprintf(&extstr[2], " %d", extout); sccp_dev_displayprinotify(device, extstr, 1, 10); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Parked channel %s on %d\n", DEV_ID_LOG(device), bridgedChannel->name, extout); res = PARK_RESULT_SUCCESS; } ast_channel_unlock(hostChannel->owner); device = sccp_device_release(device); return res; } static boolean_t sccp_asterisk110_getFeatureExtension(const sccp_channel_t * channel, char **extension) { struct ast_call_feature *feat; ast_rdlock_call_features(); feat = ast_find_call_feature("automon"); if (feat) { *extension = strdup(feat->exten); } ast_unlock_call_features(); return feat ? TRUE : FALSE; } /*! * \brief Pickup asterisk channel target using chan * * \param chan initial channel that request the parking * \param target Channel t park to */ static boolean_t sccp_wrapper_asterisk110_pickupChannel(const sccp_channel_t * chan, PBX_CHANNEL_TYPE * target) { boolean_t result; result = ast_do_pickup(chan->owner, target) ? FALSE : TRUE; return result; } static uint8_t sccp_wrapper_asterisk110_get_payloadType(const struct sccp_rtp *rtp, skinny_codec_t codec) { struct ast_format astCodec; int payload; ast_format_set(&astCodec, skinny_codec2pbx_codec(codec), 0); payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(rtp->rtp), 1, &astCodec, 0); return payload; } static int sccp_wrapper_asterisk110_get_sampleRate(skinny_codec_t codec) { struct ast_format astCodec; ast_format_set(&astCodec, skinny_codec2pbx_codec(codec), 0); return ast_rtp_lookup_sample_rate2(1, &astCodec, 0); } static sccp_extension_status_t sccp_wrapper_asterisk110_extensionStatus(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (!pbx_channel || !pbx_channel->context) { pbx_log(LOG_ERROR, "%s: (extension_status) Either no pbx_channel or no valid context provided to lookup number\n", channel->designator); return SCCP_EXTENSION_NOTEXISTS; } int ignore_pat = ast_ignore_pattern(pbx_channel->context, channel->dialedNumber); int ext_exist = ast_exists_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); int ext_canmatch = ast_canmatch_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); int ext_matchmore = ast_matchmore_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "+=sccp extension matcher says==================+\n" VERBOSE_PREFIX_2 "|ignore |exists |can match |match more|\n" VERBOSE_PREFIX_2 "|%3s |%3s |%3s |%3s |\n" VERBOSE_PREFIX_2 "+==============================================+\n", ignore_pat ? "yes" : "no", ext_exist ? "yes" : "no", ext_canmatch ? "yes" : "no", ext_matchmore ? "yes" : "no"); if (ignore_pat) { return SCCP_EXTENSION_NOTEXISTS; } else if (ext_exist) { if (ext_canmatch && !ext_matchmore) { return SCCP_EXTENSION_EXACTMATCH; } else { return SCCP_EXTENSION_MATCHMORE; } } return SCCP_EXTENSION_NOTEXISTS; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk110_request(const char *type, struct ast_format_cap *format, const PBX_CHANNEL_TYPE * requestor, void *data, int *cause) { PBX_CHANNEL_TYPE *result_ast_channel = NULL; sccp_channel_request_status_t requestStatus; sccp_channel_t *channel = NULL; skinny_codec_t audioCapabilities[SKINNY_MAX_CAPABILITIES]; skinny_codec_t videoCapabilities[SKINNY_MAX_CAPABILITIES]; memset(&audioCapabilities, 0, sizeof(audioCapabilities)); memset(&videoCapabilities, 0, sizeof(videoCapabilities)); //! \todo parse request char *lineName; skinny_codec_t codec = SKINNY_CODEC_G711_ULAW_64K; sccp_autoanswer_t autoanswer_type = SCCP_AUTOANSWER_NONE; uint8_t autoanswer_cause = AST_CAUSE_NOTDEFINED; int ringermode = 0; *cause = AST_CAUSE_NOTDEFINED; if (!type) { pbx_log(LOG_NOTICE, "Attempt to call with unspecified type of channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } if (!data) { pbx_log(LOG_NOTICE, "Attempt to call SCCP/ failed\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } /* we leave the data unchanged */ lineName = strdupa((const char *) data); /* parsing options string */ char *options = NULL; int optc = 0; char *optv[2]; int opti = 0; if ((options = strchr(lineName, '/'))) { *options = '\0'; options++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked us to create a channel with type=%s, format=" UI64FMT " lineName=%s, options=%s\n", type, (uint64_t) ast_format_cap_to_old_bitfield(format), lineName, (options) ? options : ""); /* get ringer mode from ALERT_INFO */ const char *alert_info = NULL; if (requestor) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "_ALERT_INFO"); if (!alert_info) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "__ALERT_INFO"); } } if (alert_info && !sccp_strlen_zero(alert_info)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Found ALERT_INFO=%s\n", alert_info); if (strcasecmp(alert_info, "inside") == 0) ringermode = SKINNY_RINGTYPE_INSIDE; else if (strcasecmp(alert_info, "feature") == 0) ringermode = SKINNY_RINGTYPE_FEATURE; else if (strcasecmp(alert_info, "silent") == 0) ringermode = SKINNY_RINGTYPE_SILENT; else if (strcasecmp(alert_info, "urgent") == 0) ringermode = SKINNY_RINGTYPE_URGENT; } /* done ALERT_INFO parsing */ /* parse options */ if (options && (optc = sccp_app_separate_args(options, '/', optv, sizeof(optv) / sizeof(optv[0])))) { pbx_log(LOG_NOTICE, "parse options\n"); for (opti = 0; opti < optc; opti++) { pbx_log(LOG_NOTICE, "parse option '%s'\n", optv[opti]); if (!strncasecmp(optv[opti], "aa", 2)) { /* let's use the old style auto answer aa1w and aa2w */ if (!strncasecmp(optv[opti], "aa1w", 4)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa2w", 4)) { autoanswer_type = SCCP_AUTOANSWER_2W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa=", 3)) { optv[opti] += 3; pbx_log(LOG_NOTICE, "parsing aa\n"); if (!strncasecmp(optv[opti], "1w", 2)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 2; } else if (!strncasecmp(optv[opti], "2w", 2)) { autoanswer_type = SCCP_AUTOANSWER_2W; pbx_log(LOG_NOTICE, "set aa to 2w\n"); optv[opti] += 2; } } /* since the pbx ignores autoanswer_cause unless SCCP_RWLIST_GETSIZE(l->channels) > 1, it is safe to set it if provided */ if (!sccp_strlen_zero(optv[opti]) && (autoanswer_cause)) { if (!strcasecmp(optv[opti], "b")) autoanswer_cause = AST_CAUSE_BUSY; else if (!strcasecmp(optv[opti], "u")) autoanswer_cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; else if (!strcasecmp(optv[opti], "c")) autoanswer_cause = AST_CAUSE_CONGESTION; } if (autoanswer_cause) *cause = autoanswer_cause; /* check for ringer options */ } else if (!strncasecmp(optv[opti], "ringer=", 7)) { optv[opti] += 7; if (!strcasecmp(optv[opti], "inside")) ringermode = SKINNY_RINGTYPE_INSIDE; else if (!strcasecmp(optv[opti], "outside")) ringermode = SKINNY_RINGTYPE_OUTSIDE; else if (!strcasecmp(optv[opti], "feature")) ringermode = SKINNY_RINGTYPE_FEATURE; else if (!strcasecmp(optv[opti], "silent")) ringermode = SKINNY_RINGTYPE_SILENT; else if (!strcasecmp(optv[opti], "urgent")) ringermode = SKINNY_RINGTYPE_URGENT; else ringermode = SKINNY_RINGTYPE_OUTSIDE; } else { pbx_log(LOG_WARNING, "Wrong option %s\n", optv[opti]); } } } /** getting remote capabilities */ char cap_buf[512]; /* audio capabilities */ if (requestor) { sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(requestor); if (remoteSccpChannel) { uint8_t x, y, z; z = 0; /* shrink audioCapabilities to remote preferred/capable format */ for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { audioCapabilities[z++] = remoteSccpChannel->preferences.audio[x]; break; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_asterisk10_getSkinnyFormatMultiple(requestor->nativeformats, audioCapabilities, ARRAY_LEN(audioCapabilities)); // replace AUDIO_MASK with AST_FORMAT_TYPE_AUDIO check } /* video capabilities */ sccp_asterisk10_getSkinnyFormatMultiple(requestor->nativeformats, videoCapabilities, ARRAY_LEN(videoCapabilities)); //replace AUDIO_MASK with AST_FORMAT_TYPE_AUDIO check } sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, audioCapabilities, ARRAY_LEN(audioCapabilities)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote audio caps: %s\n", cap_buf); sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, videoCapabilities, ARRAY_LEN(videoCapabilities)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote video caps: %s\n", cap_buf); /** done */ /** get requested format */ // codec = pbx_codec2skinny_codec(ast_format_cap_to_old_bitfield(format)); codec = sccp_asterisk10_getSkinnyFormatSingle(format); /* get requested format */ { struct ast_format tmpfmt; ast_format_cap_iter_start(format); while (!(ast_format_cap_iter_next(format, &tmpfmt))) { if (AST_FORMAT_GET_TYPE(tmpfmt.id) == AST_FORMAT_TYPE_AUDIO) { codec = pbx_codec2skinny_codec(tmpfmt.id); break; } } ast_format_cap_iter_end(format); } requestStatus = sccp_requestChannel(lineName, codec, audioCapabilities, ARRAY_LEN(audioCapabilities), autoanswer_type, autoanswer_cause, ringermode, &channel); switch (requestStatus) { case SCCP_REQUEST_STATUS_SUCCESS: // everything is fine break; case SCCP_REQUEST_STATUS_LINEUNKNOWN: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s Unknown -> Not Successfull\n", lineName); *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER; goto EXITFUNC; case SCCP_REQUEST_STATUS_LINEUNAVAIL: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s not currently registered -> Try again later\n", lineName); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; case SCCP_REQUEST_STATUS_ERROR: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; default: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; } if (!sccp_pbx_channel_allocate(channel, requestor ? requestor->linkedid : NULL)) { //! \todo handle error in more detail, cleanup sccp channel pbx_log(LOG_WARNING, "SCCP: Unable to allocate channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; } if (requestor) { /* set calling party */ sccp_channel_set_callingparty(channel, requestor->caller.id.name.str, requestor->caller.id.number.str); sccp_channel_set_originalCalledparty(channel, requestor->redirecting.from.name.str, requestor->redirecting.from.number.str); if (requestor->linkedid) { ast_string_field_set(channel->owner, linkedid, requestor->linkedid); } } EXITFUNC: if (channel) { result_ast_channel = channel->owner; sccp_channel_release(channel); } return result_ast_channel; } static int sccp_wrapper_asterisk110_call(PBX_CHANNEL_TYPE * ast, char *dest, int timeout) { sccp_channel_t *c = NULL; struct varshead *headp; struct ast_var_t *current; int res = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk request to call %s (dest:%s, timeout: %d)\n", pbx_channel_name(ast), dest, timeout); if (!sccp_strlen_zero(pbx_channel_call_forward(ast))) { PBX(queue_control) (ast, -1); /* Prod Channel if in the middle of a call_forward instead of proceed */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Forwarding Call to '%s'\n", pbx_channel_call_forward(ast)); return 0; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { pbx_log(LOG_WARNING, "SCCP: Asterisk request to call %s on channel: %s, but we don't have this channel!\n", dest, pbx_channel_name(ast)); return -1; } /* Check whether there is MaxCallBR variables */ headp = &ast->varshead; AST_LIST_TRAVERSE(headp, current, entries) { if (!strcasecmp(ast_var_name(current), "__MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } else if (!strcasecmp(ast_var_name(current), "MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } } res = sccp_pbx_call(c, dest, timeout); c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk110_answer(PBX_CHANNEL_TYPE * chan) { //! \todo change this handling and split pbx and sccp handling -MC int res = -1; sccp_channel_t *channel = NULL; if ((channel = get_sccp_channel_from_pbx_channel(chan))) { res = sccp_pbx_answer(channel); channel = sccp_channel_release(channel); } return res; } /** * * \todo update remote capabilities after fixup */ static int sccp_wrapper_asterisk110_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: we got a fixup request for %s\n", newchan->name); sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(newchan))) { pbx_log(LOG_WARNING, "sccp_pbx_fixup(old: %s(%p), new: %s(%p)). no SCCP channel to fix\n", oldchan->name, (void *) oldchan, newchan->name, (void *) newchan); return -1; } c->owner = newchan; c->owner = ast_channel_ref(c->owner); oldchan = ast_channel_unref(oldchan); c = sccp_channel_release(c); return 0; } static enum ast_bridge_result sccp_wrapper_asterisk110_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms) { enum ast_bridge_result res; int new_flags = flags; /* \note temporarily marked out until we figure out how to get directrtp back on track - DdG */ sccp_channel_t *sc0, *sc1; if ((sc0 = get_sccp_channel_from_pbx_channel(c0)) && (sc1 = get_sccp_channel_from_pbx_channel(c1))) { // Switch off DTMF between SCCP phones new_flags &= !AST_BRIDGE_DTMF_CHANNEL_0; new_flags &= !AST_BRIDGE_DTMF_CHANNEL_1; if (GLOB(directrtp)) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } else { sccp_device_t *d0 = sccp_channel_getDevice_retained(sc0); if (d0) { sccp_device_t *d1 = sccp_channel_getDevice_retained(sc1); if (d1) { if (d0->directrtp && d1->directrtp) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } d1 = sccp_device_release(d1); } d0 = sccp_device_release(d0); } } sc0->peerIsSCCP = TRUE; sc1->peerIsSCCP = TRUE; // SCCP Key handle direction to asterisk is still to be implemented here // sccp_pbx_senddigit sc0 = sccp_channel_release(sc0); sc1 = sccp_channel_release(sc1); } else { // Switch on DTMF between differing channels ast_channel_undefer_dtmf(c0); ast_channel_undefer_dtmf(c1); } //res = ast_rtp_bridge(c0, c1, new_flags, fo, rc, timeoutms); res = ast_rtp_instance_bridge(c0, c1, new_flags, fo, rc, timeoutms); switch (res) { case AST_BRIDGE_COMPLETE: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Complete\n", c0->name, c1->name); break; case AST_BRIDGE_FAILED: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed\n", c0->name, c1->name); break; case AST_BRIDGE_FAILED_NOWARN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed NoWarn\n", c0->name, c1->name); break; case AST_BRIDGE_RETRY: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed Retry\n", c0->name, c1->name); break; } /*! \todo Implement callback function queue upon completion */ return res; } static enum ast_rtp_glue_result sccp_wrapper_asterisk110_get_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", ast->name); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_FORBID; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", ast->name); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static int sccp_wrapper_asterisk110_set_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE * rtp, PBX_RTP_TYPE * vrtp, PBX_RTP_TYPE * trtp, const struct ast_format_cap *codecs, int nat_active) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; struct ast_sockaddr them; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: __FILE__\n"); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO PVT\n"); return -1; } if (!c->line) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO LINE\n"); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO DEVICE\n"); return -1; } if (!d->directrtp) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) Direct RTP disabled\n"); d = sccp_device_release(d); return -1; } if (rtp) { ast_rtp_instance_get_remote_address(rtp, &them); //sccp_rtp_set_peer(c, &them); /*! \todo convert struct ast_sockaddr -> struct sockaddr_in */ } else { if (ast->_state != AST_STATE_UP) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Early RTP stage, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } else { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Native Bridge Break, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } } /* Need a return here to break the bridge */ d = sccp_device_release(d); return 0; } static enum ast_rtp_glue_result sccp_wrapper_asterisk110_get_vrtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", ast->name); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); //! \todo should this not be getVideoPeerInfo if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_FORBID; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", ast->name); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static void sccp_wrapper_asterisk110_getCodec(PBX_CHANNEL_TYPE * ast, struct ast_format_cap *result) { uint8_t i; struct ast_format fmt; sccp_channel_t *channel; if (!(channel = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP | DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (getCodec) NO PVT\n"); return; } ast_debug(10, "asterisk requests format for channel %s, readFormat: %s(%d)\n", ast->name, codec2str(channel->rtp.audio.readFormat), channel->rtp.audio.readFormat); for (i = 0; i < ARRAY_LEN(channel->preferences.audio); i++) { ast_format_set(&fmt, skinny_codec2pbx_codec(channel->preferences.audio[i]), 0); ast_format_cap_add(result, &fmt); } return; } /* * \brief get callerid_name from pbx * \param sccp_channle Asterisk Channel * \param cid name result * \return parse result */ static int sccp_wrapper_asterisk110_callerid_name(const sccp_channel_t * channel, char **cid_name) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.name.str && strlen(pbx_chan->caller.id.name.str) > 0) { *cid_name = strdup(pbx_chan->caller.id.name.str); return 1; } return 0; } /* * \brief get callerid_name from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_number(const sccp_channel_t * channel, char **cid_number) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.number.str && strlen(pbx_chan->caller.id.number.str) > 0) { *cid_number = strdup(pbx_chan->caller.id.number.str); return 1; } return 0; } /* * \brief get callerid_ton from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_ton(const sccp_channel_t * channel, char **cid_ton) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.number.valid) { return pbx_chan->caller.ani.number.plan; } return 0; } /* * \brief get callerid_ani from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_ani(const sccp_channel_t * channel, char **cid_ani) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.ani.number.valid && pbx_chan->caller.ani.number.str && strlen(pbx_chan->caller.ani.number.str) > 0) { *cid_ani = strdup(pbx_chan->caller.ani.number.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_subaddr(const sccp_channel_t * channel, char **cid_subaddr) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.subaddress.valid && pbx_chan->caller.id.subaddress.str && strlen(pbx_chan->caller.id.subaddress.str) > 0) { *cid_subaddr = strdup(pbx_chan->caller.id.subaddress.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx (Destination ID) * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_dnid(const sccp_channel_t * channel, char **cid_dnid) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->dialed.number.str && strlen(pbx_chan->dialed.number.str) > 0) { *cid_dnid = strdup(pbx_chan->dialed.number.str); return 1; } return 0; } /* * \brief get callerid_rdnis from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_rdnis(const sccp_channel_t * channel, char **cid_rdnis) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->redirecting.from.number.valid && pbx_chan->redirecting.from.number.str && strlen(pbx_chan->redirecting.from.number.str) > 0) { *cid_rdnis = strdup(pbx_chan->redirecting.from.number.str); return 1; } return 0; } /* * \brief get callerid_presence from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk110_callerid_presence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; // if (pbx_chan->caller.id.number.presentation) { // return pbx_chan->caller.id.number.presentation; // } // return 0; if ((ast_party_id_presentation(&pbx_chan->caller.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) { return CALLERID_PRESENCE_ALLOWED; } return CALLERID_PRESENCE_FORBIDDEN; } static int sccp_wrapper_asterisk110_rtp_stop(sccp_channel_t * channel) { if (channel->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping phone media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.audio.rtp); } if (channel->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping video media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.video.rtp); } return 0; } static boolean_t sccp_wrapper_asterisk110_create_audio_rtp(sccp_channel_t * c) { sccp_session_t *s = NULL; sccp_device_t *d = NULL; struct ast_sockaddr sock; // struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; if (GLOB(bindaddr.sin_addr.s_addr) == INADDR_ANY) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = GLOB(bindaddr.sin_port); sin.sin_addr = s->ourip; /* sccp_socket_getOurAddressfor(s->sin.sin_addr, sin.sin_addr); */// maybe we should use this opertunity to check the connected ip-address again ast_sockaddr_from_sin(&sock, &sin); } else { ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating rtp server connection on %s\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock)); c->rtp.audio.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.audio.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: rtp server created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_RTCP, 1); if (SCCP_DTMFMODE_INBAND == d->dtmfmode) { ast_rtp_instance_dtmf_mode_set(c->rtp.audio.rtp, AST_RTP_DTMF_MODE_INBAND); } else { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF, 1); ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, 1); } ast_channel_set_fd(c->owner, 0, ast_rtp_instance_fd(c->rtp.audio.rtp, 0)); ast_channel_set_fd(c->owner, 1, ast_rtp_instance_fd(c->rtp.audio.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } //FIXME skinny_codecs2pbx_codec_pref does not work with ast >= 1.10 // memset(&astCodecPref, 0, sizeof(astCodecPref)); // if (skinny_codecs2pbx_codec_pref(c->preferences.audio, &astCodecPref)) { // ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); // } // char pref_buf[128]; // ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); // sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pref: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.audio.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add audio codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_AUDIO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "audio", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk110_create_video_rtp(sccp_channel_t * c) { sccp_session_t *s; sccp_device_t *d = NULL; struct ast_sockaddr sock; // struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating vrtp server connection at %s\n", DEV_ID_LOG(d), pbx_inet_ntoa(s->ourip)); ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); c->rtp.video.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.video.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: vrtp created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.video.rtp, AST_RTP_PROPERTY_RTCP, 1); ast_channel_set_fd(c->owner, 2, ast_rtp_instance_fd(c->rtp.video.rtp, 0)); ast_channel_set_fd(c->owner, 3, ast_rtp_instance_fd(c->rtp.video.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } //FIXME skinny_codecs2pbx_codec_pref does not work with ast >= 1.10 // memset(&astCodecPref, 0, sizeof(astCodecPref)); // if (skinny_codecs2pbx_codec_pref(c->preferences.video, &astCodecPref)) { // ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); // } //char pref_buf[128]; //ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); //sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pef: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.video.rtp, d->video_tos, d->video_cos, "SCCP VRTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.video.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add video codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_VIDEO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "video", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk110_destroyRTP(PBX_RTP_TYPE * rtp) { int res; res = ast_rtp_instance_destroy(rtp); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk110_checkHangup(const sccp_channel_t * channel) { int res; res = ast_check_hangup(channel->owner); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk110_rtpGetPeer(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_remote_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk110_rtpGetUs(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_local_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk110_getChannelByName(const char *name, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *ast = ast_channel_get_by_name(name); if (!ast) return FALSE; *pbx_channel = ast; return TRUE; } static int sccp_wrapper_asterisk110_rtp_set_peer(const struct sccp_rtp *rtp, const struct sockaddr_in *new_peer, int nat_active) { struct ast_sockaddr ast_sockaddr_dest; struct ast_sockaddr ast_sockaddr_source; int res; ((struct sockaddr_in *) new_peer)->sin_family = AF_INET; ast_sockaddr_from_sin(&ast_sockaddr_dest, new_peer); ast_sockaddr_set_port(&ast_sockaddr_dest, ntohs(new_peer->sin_port)); res = ast_rtp_instance_set_remote_address(rtp->rtp, &ast_sockaddr_dest); ast_rtp_instance_get_local_address(rtp->rtp, &ast_sockaddr_source); // sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "SCCP: Tell PBX to send RTP/UDP media from '%s:%d' to '%s:%d' (NAT: %s)\n", ast_sockaddr_stringify_host(&ast_sockaddr_source), ast_sockaddr_port(&ast_sockaddr_source), ast_sockaddr_stringify_host(&ast_sockaddr_dest), ast_sockaddr_port(&ast_sockaddr_dest), nat_active ? "yes" : "no"); if (nat_active) { ast_rtp_instance_set_prop(rtp->rtp, AST_RTP_PROPERTY_NAT, 1); } return res; } static boolean_t sccp_wrapper_asterisk110_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec) { //! \todo possibly needs to be synced to ast108 if (!channel) return FALSE; struct ast_format fmt; ast_format_set(&fmt, skinny_codec2pbx_codec(codec), 0); ast_format_copy(&channel->owner->writeformat, &fmt); ast_format_copy(&channel->owner->rawwriteformat, &fmt); if (0 != channel->rtp.audio.rtp) ast_rtp_instance_set_write_format(channel->rtp.audio.rtp, &fmt); return TRUE; } static boolean_t sccp_wrapper_asterisk110_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec) { //! \todo possibly needs to be synced to ast108 if (!channel) return FALSE; struct ast_format fmt; ast_format_set(&fmt, skinny_codec2pbx_codec(codec), 0); ast_format_copy(&channel->owner->readformat, &fmt); ast_format_copy(&channel->owner->rawreadformat, &fmt); if (0 != channel->rtp.audio.rtp) ast_rtp_instance_set_read_format(channel->rtp.audio.rtp, &fmt); return TRUE; } static void sccp_wrapper_asterisk110_setCalleridName(const sccp_channel_t * channel, const char *name) { if (name) { channel->owner->caller.id.name.valid = 1; ast_party_name_free(&channel->owner->caller.id.name); channel->owner->caller.id.name.str = ast_strdup(name); } } static void sccp_wrapper_asterisk110_setCalleridNumber(const sccp_channel_t * channel, const char *number) { if (number) { channel->owner->caller.id.number.valid = 1; ast_party_number_free(&channel->owner->caller.id.number); channel->owner->caller.id.number.str = ast_strdup(number); } } static void sccp_wrapper_asterisk110_setRedirectingParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { ast_party_number_free(&channel->owner->redirecting.from.number); channel->owner->redirecting.from.number.str = ast_strdup(number); channel->owner->redirecting.from.number.valid = 1; } if (name) { ast_party_name_free(&channel->owner->redirecting.from.name); channel->owner->redirecting.from.name.str = ast_strdup(name); channel->owner->redirecting.from.name.valid = 1; } } static void sccp_wrapper_asterisk110_setRedirectedParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { channel->owner->redirecting.to.number.valid = 1; ast_party_number_free(&channel->owner->redirecting.to.number); channel->owner->redirecting.to.number.str = ast_strdup(number); } if (name) { channel->owner->redirecting.to.name.valid = 1; ast_party_name_free(&channel->owner->redirecting.to.name); channel->owner->redirecting.to.name.str = ast_strdup(name); } } static void sccp_wrapper_asterisk110_updateConnectedLine(const sccp_channel_t * channel, const char *number, const char *name, uint8_t reason) { struct ast_party_connected_line connected; struct ast_set_party_connected_line update_connected; memset(&update_connected, 0, sizeof(update_connected)); if (number) { update_connected.id.number = 1; connected.id.number.valid = 1; connected.id.number.str = (char *) number; connected.id.number.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (name) { update_connected.id.name = 1; connected.id.name.valid = 1; connected.id.name.str = (char *) name; connected.id.name.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } connected.id.tag = NULL; connected.source = reason; ast_channel_queue_connected_line_update(channel->owner, &connected, &update_connected); } static int sccp_wrapper_asterisk110_sched_add(int when, sccp_sched_cb callback, const void *data) { if (sched) return ast_sched_add(sched, when, callback, data); return FALSE; } static long sccp_wrapper_asterisk110_sched_when(int id) { if (sched) return ast_sched_when(sched, id); return FALSE; } static int sccp_wrapper_asterisk110_sched_wait(int id) { if (sched) return ast_sched_wait(sched); return FALSE; } static int sccp_wrapper_asterisk110_sched_del(int id) { if (sched) return ast_sched_del(sched, id); return FALSE; } static int sccp_wrapper_asterisk110_setCallState(const sccp_channel_t * channel, int state) { sccp_pbx_setcallstate((sccp_channel_t *) channel, state); //! \todo implement correct return value (take into account negative deadlock prevention) return 0; } static boolean_t sccp_asterisk_getRemoteChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *remotePeer; struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { if (pbx_find_channel_by_linkid(remotePeer, (void *) channel->owner->linkedid)) { break; } } ast_channel_iterator_destroy(iterator); if (remotePeer) { *pbx_channel = remotePeer; remotePeer = ast_channel_unref(remotePeer); return TRUE; } return FALSE; } /*! * \brief Send Text to Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param text Text to be send as char * \return Succes as int * * \called_from_asterisk */ static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; uint8_t instance; if (!ast) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX CHANNEL to send text to\n"); return -1; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send text to (%s)\n", ast->name); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send text to (%s)\n", ast->name); c = sccp_channel_release(c); return -1; } if (!text || sccp_strlen_zero(text)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No text to send to %s\n", d->id, ast->name); d = sccp_device_release(d); return 0; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Sending text %s on %s\n", d->id, text, ast->name); instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, (char *) text, 10); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! * \brief Receive First Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit First Digit as char * \return Always Return -1 as int * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit) { return -1; } /*! * \brief Receive Last Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit Last Digit as char * \param duration Duration as int * \return boolean * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send digit to (%s)\n", ast->name); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send digit to (%s)\n", ast->name); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked to send dtmf '%d' to channel %s. Trying to send it %s\n", digit, ast->name, (d->dtmfmode) ? "outofband" : "inband"); if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Can't send the dtmf '%d' %c to a not connected channel %s\n", d->id, digit, digit, ast->name); d = sccp_device_release(d); return -1; } sccp_dev_keypadbutton(d, digit, sccp_device_find_index_for_line(d, c->line->name), c->callid); d = sccp_device_release(d); return -1; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk110_findChannelWithCallback(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data, boolean_t lock) { PBX_CHANNEL_TYPE *remotePeer; struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); if (!lock) { ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; } for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { if (found_cb(remotePeer, data)) { ast_channel_lock(remotePeer); break; } } ast_channel_iterator_destroy(iterator); return remotePeer; } /*! \brief Set an option on a asterisk channel */ #if 0 static int sccp_wrapper_asterisk110_setOption(PBX_CHANNEL_TYPE * ast, int option, void *data, int datalen) { int res = -1; sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: channel: %s(%s) setOption: %d\n", c->currentDeviceId, sccp_channel_toString(c), ast->name, option); //! if AST_OPTION_FORMAT_READ / AST_OPTION_FORMAT_WRITE are available we might be indication that we can do transcoding (channel.c:set_format). Correct ? */ switch (option) { case AST_OPTION_FORMAT_READ: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_read_format(c->rtp.audio.rtp, (struct ast_format *) data); } //sccp_wrapper_asterisk110_setReadFormat(c, (struct ast_format *) data); break; case AST_OPTION_FORMAT_WRITE: if (c->rtp.audio.rtp) { //res = ast_rtp_instance_set_write_format(c->rtp.audio.rtp, (struct ast_format *) data); } //sccp_wrapper_asterisk110_setWriteFormat(c, (struct ast_format *) data); break; case AST_OPTION_MAKE_COMPATIBLE: if (c->rtp.audio.rtp) { //res = ast_rtp_instance_make_compatible(ast, c->rtp.audio.rtp, (PBX_CHANNEL_TYPE *) data); } break; case AST_OPTION_DIGIT_DETECT: case AST_OPTION_SECURE_SIGNALING: case AST_OPTION_SECURE_MEDIA: res = -1; break; default: break; } c = sccp_channel_release(c); } return res; } #endif static void sccp_wrapper_asterisk_set_pbxchannel_linkedid(PBX_CHANNEL_TYPE * pbx_channel, const char *new_linkedid) { if (pbx_channel) { if (!strcmp(pbx_channel->linkedid, new_linkedid)) { return; } ast_cel_check_retire_linkedid(pbx_channel); ast_string_field_set(pbx_channel, linkedid, new_linkedid); ast_cel_linkedid_ref(new_linkedid); } }; #define DECLARE_PBX_CHANNEL_STRGET(_field) \ static const char *sccp_wrapper_asterisk_get_channel_##_field(const sccp_channel_t * channel) \ { \ static const char *empty_channel_##_field = "--no-channel-" #_field "--"; \ if (channel->owner) { \ return channel->owner->_field; \ } \ return empty_channel_##_field; \ }; #define DECLARE_PBX_CHANNEL_STRSET(_field) \ static void sccp_wrapper_asterisk_set_channel_##_field(const sccp_channel_t * channel, const char * _field) \ { \ if (channel->owner) { \ sccp_copy_string(channel->owner->_field, _field, sizeof(channel->owner->_field)); \ } \ }; DECLARE_PBX_CHANNEL_STRGET(name) DECLARE_PBX_CHANNEL_STRGET(uniqueid) DECLARE_PBX_CHANNEL_STRGET(appl) DECLARE_PBX_CHANNEL_STRGET(linkedid) DECLARE_PBX_CHANNEL_STRGET(exten) DECLARE_PBX_CHANNEL_STRSET(exten) DECLARE_PBX_CHANNEL_STRGET(context) DECLARE_PBX_CHANNEL_STRSET(context) DECLARE_PBX_CHANNEL_STRGET(macroexten) DECLARE_PBX_CHANNEL_STRSET(macroexten) DECLARE_PBX_CHANNEL_STRGET(macrocontext) DECLARE_PBX_CHANNEL_STRSET(macrocontext) DECLARE_PBX_CHANNEL_STRGET(call_forward) static void sccp_wrapper_asterisk_set_channel_linkedid(const sccp_channel_t * channel, const char *new_linkedid) { if (channel->owner) { sccp_wrapper_asterisk_set_pbxchannel_linkedid(channel->owner, new_linkedid); } }; static void sccp_wrapper_asterisk_set_channel_name(const sccp_channel_t * channel, const char *new_name) { if (channel->owner) { pbx_string_field_build(channel->owner, name, "%s", new_name); } }; static void sccp_wrapper_asterisk_set_channel_call_forward(const sccp_channel_t * channel, const char *new_call_forward) { if (channel->owner) { pbx_string_field_set(channel->owner, call_forward, new_call_forward); } } static enum ast_channel_state sccp_wrapper_asterisk_get_channel_state(const sccp_channel_t * channel) { if (channel->owner) { return channel->owner->_state; } return 0; } static const struct ast_pbx *sccp_wrapper_asterisk_get_channel_pbx(const sccp_channel_t * channel) { if (channel->owner) { return channel->owner->pbx; } return NULL; } static void sccp_wrapper_asterisk_set_channel_tech_pvt(const sccp_channel_t * channel) { if (channel->owner) { // channel->owner->tech_pvt = (void *)channel; } } static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!datalen || sccp_strlen_zero(data) || !(!strncmp(data, "http://", 7) || !strncmp(data, "file://", 7) || !strncmp(data, "ftp://", 6))) { pbx_log(LOG_NOTICE, "SCCP: Received a non valid URL\n"); return -1; } struct ast_frame fr; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { #if DEBUG if (!(d = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { #else if (!(d = c->getDevice_retained(c))) { #endif c = sccp_channel_release(c); return -1; } memset(&fr, 0, sizeof(fr)); fr.frametype = AST_FRAME_HTML; fr.data.ptr = (char *) data; fr.src = "SCCP Send URL"; fr.datalen = datalen; sccp_push_result_t pushResult = d->pushURL(d, data, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { fr.subclass.integer = AST_HTML_LDCOMPLETE; } else { fr.subclass.integer = AST_HTML_NOSUPPORT; } ast_queue_frame(ast, ast_frisolate(&fr)); d = sccp_device_release(d); c = sccp_channel_release(c); } return 0; } /*! * \brief Queue a control frame * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type */ int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Queue a control frame with payload * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type * \param data Payload * \param datalen Payload Length */ int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control,.data.ptr = (void *) data,.datalen = datalen }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Get Hint Extension State and return the matching Busy Lamp Field State */ static skinny_busylampfield_state_t sccp_wrapper_asterisk110_getExtensionState(const char *extension, const char *context) { skinny_busylampfield_state_t result = SKINNY_BLF_STATUS_UNKNOWN; if (sccp_strlen_zero(extension) || sccp_strlen_zero(context)) { pbx_log(LOG_ERROR, "SCCP: PBX(getExtensionState): Either extension:'%s' or context:;%s' provided is empty\n", extension, context); return result; } int state = ast_extension_state(NULL, context, extension); switch (state) { case AST_EXTENSION_REMOVED: case AST_EXTENSION_DEACTIVATED: case AST_EXTENSION_UNAVAILABLE: result = SKINNY_BLF_STATUS_UNKNOWN; break; case AST_EXTENSION_NOT_INUSE: result = SKINNY_BLF_STATUS_IDLE; break; case AST_EXTENSION_INUSE: case AST_EXTENSION_ONHOLD: case AST_EXTENSION_ONHOLD + AST_EXTENSION_INUSE: case AST_EXTENSION_BUSY: result = SKINNY_BLF_STATUS_INUSE; break; case AST_EXTENSION_RINGING + AST_EXTENSION_INUSE: case AST_EXTENSION_RINGING: result = SKINNY_BLF_STATUS_ALERTING; break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (getExtensionState) extension: %s@%s, extension_state: '%s (%d)' -> blf state '%d'\n", extension, context, ast_extension_state2str(state), state, result); return result; } /*! * \brief using RTP Glue Engine */ #if defined(__cplusplus) || defined(c_plusplus) struct ast_rtp_glue sccp_rtp = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, mod: NULL, get_rtp_info:sccp_wrapper_asterisk110_get_rtp_peer, get_vrtp_info:sccp_wrapper_asterisk110_get_vrtp_peer, get_trtp_info:NULL, update_peer:sccp_wrapper_asterisk110_set_rtp_peer, get_codec:sccp_wrapper_asterisk110_getCodec, /* *INDENT-ON* */ }; #else struct ast_rtp_glue sccp_rtp = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .get_rtp_info = sccp_wrapper_asterisk110_get_rtp_peer, .get_vrtp_info = sccp_wrapper_asterisk110_get_vrtp_peer, .update_peer = sccp_wrapper_asterisk110_set_rtp_peer, .get_codec = sccp_wrapper_asterisk110_getCodec, /* *INDENT-ON* */ }; #endif #ifdef HAVE_PBX_MESSAGE_H #include "asterisk/message.h" static int sccp_asterisk_message_send(const struct ast_msg *msg, const char *to, const char *from) { char *lineName; sccp_line_t *line; const char *messageText = ast_msg_get_body(msg); int res = -1; lineName = (char *) sccp_strdupa(to); if (strchr(lineName, '@')) { strsep(&lineName, "@"); } else { strsep(&lineName, ":"); } if (sccp_strlen_zero(lineName)) { pbx_log(LOG_WARNING, "MESSAGE(to) is invalid for SCCP - '%s'\n", to); return -1; } line = sccp_line_find_byname(lineName, FALSE); if (!line) { pbx_log(LOG_WARNING, "line '%s' not found\n", lineName); return -1; } /** \todo move this to line implementation */ sccp_linedevices_t *linedevice; sccp_push_result_t pushResult; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { pushResult = linedevice->device->pushTextMessage(linedevice->device, messageText, from, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { res = 0; } } SCCP_LIST_UNLOCK(&line->devices); return res; } #if defined(__cplusplus) || defined(c_plusplus) static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ name: "sccp", msg_send:sccp_asterisk_message_send, /* *INDENT-ON* */ }; #else static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ .name = "sccp", .msg_send = sccp_asterisk_message_send, /* *INDENT-ON* */ }; #endif #endif boolean_t sccp_wrapper_asterisk_setLanguage(PBX_CHANNEL_TYPE * pbxChannel, const char *newLanguage) { ast_string_field_set(pbxChannel, language, newLanguage); return TRUE; } #if defined(__cplusplus) || defined(c_plusplus) sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ alloc_pbxChannel: sccp_wrapper_asterisk110_allocPBXChannel, set_callstate: sccp_wrapper_asterisk110_setCallState, checkhangup: sccp_wrapper_asterisk110_checkHangup, hangup: NULL, requestHangup: sccp_wrapper_asterisk_requestHangup, forceHangup: sccp_wrapper_asterisk_forceHangup, extension_status: sccp_wrapper_asterisk110_extensionStatus, setPBXChannelLinkedId: sccp_wrapper_asterisk_set_pbxchannel_linkedid, /** get channel by name */ getChannelByName: sccp_wrapper_asterisk110_getChannelByName, getRemoteChannel: sccp_asterisk_getRemoteChannel, getChannelByCallback: NULL, getChannelLinkedId: sccp_wrapper_asterisk_get_channel_linkedid, setChannelLinkedId: sccp_wrapper_asterisk_set_channel_linkedid, getChannelName: sccp_wrapper_asterisk_get_channel_name, getChannelUniqueID: sccp_wrapper_asterisk_get_channel_uniqueid, getChannelExten: sccp_wrapper_asterisk_get_channel_exten, setChannelExten: sccp_wrapper_asterisk_set_channel_exten, getChannelContext: sccp_wrapper_asterisk_get_channel_context, setChannelContext: sccp_wrapper_asterisk_set_channel_context, getChannelMacroExten: sccp_wrapper_asterisk_get_channel_macroexten, setChannelMacroExten: sccp_wrapper_asterisk_set_channel_macroexten, getChannelMacroContext: sccp_wrapper_asterisk_get_channel_macrocontext, setChannelMacroContext: sccp_wrapper_asterisk_set_channel_macrocontext, getChannelCallForward: sccp_wrapper_asterisk_get_channel_call_forward, setChannelCallForward: sccp_wrapper_asterisk_set_channel_call_forward, getChannelAppl: sccp_wrapper_asterisk_get_channel_appl, getChannelState: sccp_wrapper_asterisk_get_channel_state, getChannelPbx: sccp_wrapper_asterisk_get_channel_pbx, setChannelTechPVT: sccp_wrapper_asterisk_set_channel_tech_pvt, set_nativeAudioFormats: sccp_wrapper_asterisk110_setNativeAudioFormats, set_nativeVideoFormats: sccp_wrapper_asterisk110_setNativeVideoFormats, getPeerCodecCapabilities: NULL, send_digit: sccp_wrapper_asterisk110_sendDigit, send_digits: sccp_wrapper_asterisk110_sendDigits, sched_add: sccp_wrapper_asterisk110_sched_add, sched_del: sccp_wrapper_asterisk110_sched_del, sched_when: sccp_wrapper_asterisk110_sched_when, sched_wait: sccp_wrapper_asterisk110_sched_wait, /* rtp */ rtp_getPeer: sccp_wrapper_asterisk110_rtpGetPeer, rtp_getUs: sccp_wrapper_asterisk110_rtpGetUs, rtp_setPeer: sccp_wrapper_asterisk110_rtp_set_peer, rtp_setWriteFormat: sccp_wrapper_asterisk110_setWriteFormat, rtp_setReadFormat: sccp_wrapper_asterisk110_setReadFormat, rtp_destroy: sccp_wrapper_asterisk110_destroyRTP, rtp_stop: sccp_wrapper_asterisk110_rtp_stop, rtp_codec: NULL, rtp_audio_create: sccp_wrapper_asterisk110_create_audio_rtp, rtp_video_create: sccp_wrapper_asterisk110_create_video_rtp, rtp_get_payloadType: sccp_wrapper_asterisk110_get_payloadType, rtp_get_sampleRate: sccp_wrapper_asterisk110_get_sampleRate, rtp_bridgePeers: NULL, /* callerid */ get_callerid_name: sccp_wrapper_asterisk110_callerid_name, get_callerid_number: sccp_wrapper_asterisk110_callerid_number, get_callerid_ton: sccp_wrapper_asterisk110_callerid_ton, get_callerid_ani: sccp_wrapper_asterisk110_callerid_ani, get_callerid_subaddr: sccp_wrapper_asterisk110_callerid_subaddr, get_callerid_dnid: sccp_wrapper_asterisk110_callerid_dnid, get_callerid_rdnis: sccp_wrapper_asterisk110_callerid_rdnis, get_callerid_presence: sccp_wrapper_asterisk110_callerid_presence, set_callerid_name: sccp_wrapper_asterisk110_setCalleridName, set_callerid_number: sccp_wrapper_asterisk110_setCalleridNumber, set_callerid_ani: NULL, set_callerid_dnid: NULL, set_callerid_redirectingParty: sccp_wrapper_asterisk110_setRedirectingParty, set_callerid_redirectedParty: sccp_wrapper_asterisk110_setRedirectedParty, set_callerid_presence: sccp_wrapper_asterisk110_setCalleridPresence, set_connected_line: sccp_wrapper_asterisk110_updateConnectedLine, sendRedirectedUpdate: sccp_asterisk_sendRedirectedUpdate, /* feature section */ feature_park: sccp_wrapper_asterisk110_park, feature_stopMusicOnHold: NULL, feature_addToDatabase: sccp_asterisk_addToDatabase, feature_getFromDatabase: sccp_asterisk_getFromDatabase, feature_removeFromDatabase: sccp_asterisk_removeFromDatabase, feature_removeTreeFromDatabase: sccp_asterisk_removeTreeFromDatabase, feature_monitor: sccp_wrapper_asterisk_featureMonitor, getFeatureExtension: sccp_asterisk110_getFeatureExtension, feature_pickup: sccp_wrapper_asterisk110_pickupChannel, eventSubscribe: NULL, findChannelByCallback: sccp_wrapper_asterisk110_findChannelWithCallback, moh_start: sccp_asterisk_moh_start, moh_stop: sccp_asterisk_moh_stop, queue_control: sccp_asterisk_queue_control, queue_control_data: sccp_asterisk_queue_control_data, allocTempPBXChannel: sccp_wrapper_asterisk110_allocTempPBXChannel, masqueradeHelper: sccp_wrapper_asterisk110_masqueradeHelper, requestForeignChannel: sccp_wrapper_asterisk110_requestForeignChannel, set_language: sccp_wrapper_asterisk_setLanguage, getExtensionState: sccp_wrapper_asterisk110_getExtensionState, findPickupChannelByExtenLocked: sccp_wrapper_asterisk110_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #else /*! * \brief SCCP - PBX Callback Functions * (Decoupling Tight Dependencies on Asterisk Functions) */ struct sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ /* channel */ .alloc_pbxChannel = sccp_wrapper_asterisk110_allocPBXChannel, .requestHangup = sccp_wrapper_asterisk_requestHangup, .forceHangup = sccp_wrapper_asterisk_forceHangup, .extension_status = sccp_wrapper_asterisk110_extensionStatus, .setPBXChannelLinkedId = sccp_wrapper_asterisk_set_pbxchannel_linkedid, .getChannelByName = sccp_wrapper_asterisk110_getChannelByName, .getChannelLinkedId = sccp_wrapper_asterisk_get_channel_linkedid, .setChannelLinkedId = sccp_wrapper_asterisk_set_channel_linkedid, .getChannelName = sccp_wrapper_asterisk_get_channel_name, .setChannelName = sccp_wrapper_asterisk_set_channel_name, .getChannelUniqueID = sccp_wrapper_asterisk_get_channel_uniqueid, .getChannelExten = sccp_wrapper_asterisk_get_channel_exten, .setChannelExten = sccp_wrapper_asterisk_set_channel_exten, .getChannelContext = sccp_wrapper_asterisk_get_channel_context, .setChannelContext = sccp_wrapper_asterisk_set_channel_context, .getChannelMacroExten = sccp_wrapper_asterisk_get_channel_macroexten, .setChannelMacroExten = sccp_wrapper_asterisk_set_channel_macroexten, .getChannelMacroContext = sccp_wrapper_asterisk_get_channel_macrocontext, .setChannelMacroContext = sccp_wrapper_asterisk_set_channel_macrocontext, .getChannelCallForward = sccp_wrapper_asterisk_get_channel_call_forward, .setChannelCallForward = sccp_wrapper_asterisk_set_channel_call_forward, .getChannelAppl = sccp_wrapper_asterisk_get_channel_appl, .getChannelState = sccp_wrapper_asterisk_get_channel_state, .getChannelPbx = sccp_wrapper_asterisk_get_channel_pbx, .setChannelTechPVT = sccp_wrapper_asterisk_set_channel_tech_pvt, .getRemoteChannel = sccp_asterisk_getRemoteChannel, .checkhangup = sccp_wrapper_asterisk110_checkHangup, /* digits */ .send_digits = sccp_wrapper_asterisk110_sendDigits, .send_digit = sccp_wrapper_asterisk110_sendDigit, /* schedulers */ .sched_add = sccp_wrapper_asterisk110_sched_add, .sched_del = sccp_wrapper_asterisk110_sched_del, .sched_when = sccp_wrapper_asterisk110_sched_when, .sched_wait = sccp_wrapper_asterisk110_sched_wait, /* callstate / indicate */ .set_callstate = sccp_wrapper_asterisk110_setCallState, /* codecs */ .set_nativeAudioFormats = sccp_wrapper_asterisk110_setNativeAudioFormats, .set_nativeVideoFormats = sccp_wrapper_asterisk110_setNativeVideoFormats, /* rtp */ .rtp_getPeer = sccp_wrapper_asterisk110_rtpGetPeer, .rtp_getUs = sccp_wrapper_asterisk110_rtpGetUs, .rtp_stop = sccp_wrapper_asterisk110_rtp_stop, .rtp_audio_create = sccp_wrapper_asterisk110_create_audio_rtp, .rtp_video_create = sccp_wrapper_asterisk110_create_video_rtp, .rtp_get_payloadType = sccp_wrapper_asterisk110_get_payloadType, .rtp_get_sampleRate = sccp_wrapper_asterisk110_get_sampleRate, .rtp_destroy = sccp_wrapper_asterisk110_destroyRTP, .rtp_setWriteFormat = sccp_wrapper_asterisk110_setWriteFormat, .rtp_setReadFormat = sccp_wrapper_asterisk110_setReadFormat, .rtp_setPeer = sccp_wrapper_asterisk110_rtp_set_peer, /* callerid */ .get_callerid_name = sccp_wrapper_asterisk110_callerid_name, .get_callerid_number = sccp_wrapper_asterisk110_callerid_number, .get_callerid_ton = sccp_wrapper_asterisk110_callerid_ton, .get_callerid_ani = sccp_wrapper_asterisk110_callerid_ani, .get_callerid_subaddr = sccp_wrapper_asterisk110_callerid_subaddr, .get_callerid_dnid = sccp_wrapper_asterisk110_callerid_dnid, .get_callerid_rdnis = sccp_wrapper_asterisk110_callerid_rdnis, .get_callerid_presence = sccp_wrapper_asterisk110_callerid_presence, .set_callerid_name = sccp_wrapper_asterisk110_setCalleridName, //! \todo implement callback .set_callerid_number = sccp_wrapper_asterisk110_setCalleridNumber, //! \todo implement callback .set_callerid_dnid = NULL, //! \todo implement callback .set_callerid_redirectingParty = sccp_wrapper_asterisk110_setRedirectingParty, .set_callerid_redirectedParty = sccp_wrapper_asterisk110_setRedirectedParty, .set_callerid_presence = sccp_wrapper_asterisk110_setCalleridPresence, .set_connected_line = sccp_wrapper_asterisk110_updateConnectedLine, .sendRedirectedUpdate = sccp_asterisk_sendRedirectedUpdate, /* database */ .feature_addToDatabase = sccp_asterisk_addToDatabase, .feature_getFromDatabase = sccp_asterisk_getFromDatabase, .feature_removeFromDatabase = sccp_asterisk_removeFromDatabase, .feature_removeTreeFromDatabase = sccp_asterisk_removeTreeFromDatabase, .feature_monitor = sccp_wrapper_asterisk_featureMonitor, .feature_park = sccp_wrapper_asterisk110_park, .getFeatureExtension = sccp_asterisk110_getFeatureExtension, .feature_pickup = sccp_wrapper_asterisk110_pickupChannel, .findChannelByCallback = sccp_wrapper_asterisk110_findChannelWithCallback, .moh_start = sccp_asterisk_moh_start, .moh_stop = sccp_asterisk_moh_stop, .queue_control = sccp_asterisk_queue_control, .queue_control_data = sccp_asterisk_queue_control_data, .allocTempPBXChannel = sccp_wrapper_asterisk110_allocTempPBXChannel, .masqueradeHelper = sccp_wrapper_asterisk110_masqueradeHelper, .requestForeignChannel = sccp_wrapper_asterisk110_requestForeignChannel, .set_language = sccp_wrapper_asterisk_setLanguage, .getExtensionState = sccp_wrapper_asterisk110_getExtensionState, .findPickupChannelByExtenLocked = sccp_wrapper_asterisk110_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #endif #if defined(__cplusplus) || defined(c_plusplus) static ast_module_load_result load_module(void) #else static int load_module(void) #endif { boolean_t res; /* check for existance of chan_skinny */ if (ast_module_check("chan_skinny.so")) { pbx_log(LOG_ERROR, "Chan_skinny is loaded. Please check modules.conf and remove chan_skinny before loading chan_sccp.\n"); return AST_MODULE_LOAD_DECLINE; } sched = ast_sched_context_create(); if (!sched) { pbx_log(LOG_WARNING, "Unable to create schedule context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } if (ast_sched_start_thread(sched)) { ast_sched_context_destroy(sched); sched = NULL; return AST_MODULE_LOAD_FAILURE; } /* make globals */ res = sccp_prePBXLoad(); if (!res) { return AST_MODULE_LOAD_DECLINE; } sccp_tech.capabilities = ast_format_cap_alloc(); ast_format_cap_add_all_by_type(sccp_tech.capabilities, AST_FORMAT_TYPE_AUDIO); io = io_context_create(); if (!io) { pbx_log(LOG_WARNING, "Unable to create I/O context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } //! \todo how can we handle this in a pbx independent way? if (!load_config()) { if (ast_channel_register(&sccp_tech)) { pbx_log(LOG_ERROR, "Unable to register channel class SCCP\n"); return AST_MODULE_LOAD_FAILURE; } } #ifdef HAVE_PBX_MESSAGE_H if (ast_msg_tech_register(&sccp_msg_tech)) { /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */ pbx_log(LOG_WARNING, "Unable to register message interface\n"); } #endif ast_rtp_glue_register(&sccp_rtp); sccp_register_management(); sccp_register_cli(); sccp_register_dialplan_functions(); sccp_postPBX_load(); return AST_MODULE_LOAD_SUCCESS; } static int unload_module(void) { sccp_preUnload(); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP RTP protocol\n"); ast_rtp_glue_unregister(&sccp_rtp); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP Channel Tech\n"); ast_channel_unregister(&sccp_tech); sccp_unregister_dialplan_functions(); sccp_unregister_cli(); sccp_mwi_module_stop(); #ifdef CS_SCCP_MANAGER sccp_unregister_management(); #endif #ifdef HAVE_PBX_MESSAGE_H ast_msg_tech_unregister(&sccp_msg_tech); #endif if (io) { io_context_destroy(io); io = NULL; } while (SCCP_REF_DESTROYED != sccp_refcount_isRunning()) { usleep(SCCP_TIME_TO_KEEP_REFCOUNTEDOBJECT); // give enough time for all schedules to end and refcounted object to be cleanup completely } if (sched) { pbx_log(LOG_NOTICE, "Cleaning up scheduled items:\n"); int scheduled_items = 0; ast_sched_dump(sched); while ((scheduled_items = ast_sched_runq(sched))) { pbx_log(LOG_NOTICE, "Cleaning up %d scheduled items... please wait\n", scheduled_items); usleep(ast_sched_wait(sched)); } ast_sched_context_destroy(sched); sched = NULL; } sccp_free(sccp_globals); pbx_log(LOG_NOTICE, "Running Cleanup\n"); #ifdef HAVE_LIBGC // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Collect a little:%d\n",GC_collect_a_little()); // CHECK_LEAKS(); // GC_gcollect(); #endif pbx_log(LOG_NOTICE, "Module chan_sccp unloaded\n"); return 0; } static int module_reload(void) { sccp_reload(); return 0; } #if defined(__cplusplus) || defined(c_plusplus) static struct ast_module_info __mod_info = { NULL, load_module, module_reload, unload_module, NULL, NULL, AST_MODULE, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)", ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, AST_BUILDOPT_SUM, AST_MODPRI_CHANNEL_DRIVER, NULL, }; static void __attribute__ ((constructor)) __reg_module(void) { ast_module_register(&__mod_info); } static void __attribute__ ((destructor)) __unreg_module(void) { ast_module_unregister(&__mod_info); } static const __attribute__ ((unused)) struct ast_module_info *ast_module_info = &__mod_info; #else AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Skinny Client Control Protocol (SCCP). SCCP-Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)",.load = load_module,.unload = unload_module,.reload = module_reload,.load_pri = AST_MODPRI_DEFAULT,.nonoptreq = "res_rtp_asterisk,chan_local",); #endif PBX_CHANNEL_TYPE *sccp_search_remotepeer_locked(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data) { PBX_CHANNEL_TYPE *remotePeer; struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { if (found_cb(remotePeer, data)) { ast_channel_lock(remotePeer); break; } } ast_channel_iterator_destroy(iterator); return remotePeer; } PBX_CHANNEL_TYPE *sccp_wrapper_asterisk110_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context) { struct ast_channel *target = NULL; /*!< Potential pickup target */ struct ast_channel_iterator *iter; if (!(iter = ast_channel_iterator_by_exten_new(exten, context))) { return NULL; } while ((target = ast_channel_iterator_next(iter))) { ast_channel_lock(target); if ((chan != target) && ast_can_pickup(target)) { ast_log(LOG_NOTICE, "%s pickup by %s\n", target->name, chan->name); break; } ast_channel_unlock(target); target = ast_channel_unref(target); } ast_channel_iterator_destroy(iter); return target; }
722,273
./chan-sccp-b/src/pbx_impl/ast/ast111.c
/*! * \file ast111.c * \brief SCCP PBX Asterisk Wrapper Class * \author Marcello Ceshia * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #include <config.h> #include "../../common.h" #include "ast111.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include <asterisk/sched.h> #include <asterisk/netsock2.h> #include <asterisk/cel.h> #define new avoid_cxx_new_keyword #include <asterisk/rtp_engine.h> #undef new #if defined(__cplusplus) || defined(c_plusplus) } #endif struct ast_sched_context *sched = 0; struct io_context *io = 0; struct ast_format slinFormat = { AST_FORMAT_SLINEAR, {{0}, 0} }; static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_request(const char *type, struct ast_format_cap *format, const PBX_CHANNEL_TYPE * requestor, const char *dest, int *cause); static int sccp_wrapper_asterisk111_call(PBX_CHANNEL_TYPE * chan, const char *addr, int timeout); static int sccp_wrapper_asterisk111_answer(PBX_CHANNEL_TYPE * chan); static PBX_FRAME_TYPE *sccp_wrapper_asterisk111_rtp_read(PBX_CHANNEL_TYPE * ast); static int sccp_wrapper_asterisk111_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame); static int sccp_wrapper_asterisk111_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen); static int sccp_wrapper_asterisk111_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan); #ifdef CS_AST_RTP_INSTANCE_BRIDGE static enum ast_bridge_result sccp_wrapper_asterisk111_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms); #endif static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text); static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit); static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration); static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen); int sccp_wrapper_asterisk111_hangup(PBX_CHANNEL_TYPE * ast_channel); boolean_t sccp_wrapper_asterisk111_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId); int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control); int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen); static int sccp_wrapper_asterisk111_devicestate(const char *data); static boolean_t sccp_wrapper_asterisk111_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec); static boolean_t sccp_wrapper_asterisk111_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context); static inline skinny_codec_t sccp_asterisk11_getSkinnyFormatSingle(struct ast_format_cap *ast_format_capability) { struct ast_format tmp_fmt; uint8_t i; skinny_codec_t codec = SKINNY_CODEC_NONE; ast_format_cap_iter_start(ast_format_capability); while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) { for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == tmp_fmt.id) { codec = skinny2pbx_codec_maps[i].skinny_codec; break; } } if (codec != SKINNY_CODEC_NONE) { break; } } ast_format_cap_iter_end(ast_format_capability); return codec; } static uint8_t sccp_asterisk11_getSkinnyFormatMultiple(struct ast_format_cap *ast_format_capability, skinny_codec_t codec[], int length) { struct ast_format tmp_fmt; uint8_t i; uint8_t position = 0; ast_format_cap_iter_start(ast_format_capability); while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt) && position < length) { for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == tmp_fmt.id) { codec[position++] = skinny2pbx_codec_maps[i].skinny_codec; break; } } } ast_format_cap_iter_end(ast_format_capability); return position; } #if defined(__cplusplus) || defined(c_plusplus) /*! * \brief SCCP Tech Structure */ static struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, description: "Skinny Client Control Protocol (SCCP)", // capabilities: AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_SLINEAR16 | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A | AST_FORMAT_H264 | AST_FORMAT_H263_PLUS, properties: AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, requester: sccp_wrapper_asterisk111_request, devicestate: sccp_wrapper_asterisk111_devicestate, send_digit_begin: sccp_wrapper_recvdigit_begin, send_digit_end: sccp_wrapper_recvdigit_end, call: sccp_wrapper_asterisk111_call, hangup: sccp_wrapper_asterisk111_hangup, answer: sccp_wrapper_asterisk111_answer, read: sccp_wrapper_asterisk111_rtp_read, write: sccp_wrapper_asterisk111_rtp_write, send_text: sccp_pbx_sendtext, send_image: NULL, send_html: sccp_pbx_sendHTML, exception: NULL, bridge: sccp_wrapper_asterisk111_rtpBridge, early_bridge: NULL, indicate: sccp_wrapper_asterisk111_indicate, fixup: sccp_wrapper_asterisk111_fixup, setoption: NULL, queryoption: NULL, transfer: NULL, write_video: sccp_wrapper_asterisk111_rtp_write, write_text: NULL, bridged_channel: NULL, func_channel_read: sccp_wrapper_asterisk_channel_read, func_channel_write: sccp_asterisk_pbx_fktChannelWrite, get_base_channel: NULL, set_base_channel: NULL, /* *INDENT-ON* */ }; #else /*! * \brief SCCP Tech Structure */ struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .description = "Skinny Client Control Protocol (SCCP)", // we could use the skinny_codec = ast_codec mapping here to generate the list of capabilities // .capabilities = AST_FORMAT_SLINEAR16 | AST_FORMAT_SLINEAR | AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A, .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, .requester = sccp_wrapper_asterisk111_request, .devicestate = sccp_wrapper_asterisk111_devicestate, .call = sccp_wrapper_asterisk111_call, .hangup = sccp_wrapper_asterisk111_hangup, .answer = sccp_wrapper_asterisk111_answer, .read = sccp_wrapper_asterisk111_rtp_read, .write = sccp_wrapper_asterisk111_rtp_write, .write_video = sccp_wrapper_asterisk111_rtp_write, .indicate = sccp_wrapper_asterisk111_indicate, .fixup = sccp_wrapper_asterisk111_fixup, .transfer = sccp_pbx_transfer, #ifdef CS_AST_RTP_INSTANCE_BRIDGE .bridge = sccp_wrapper_asterisk111_rtpBridge, #endif //.early_bridge = ast_rtp_early_bridge, //.bridged_channel = .send_text = sccp_pbx_sendtext, .send_html = sccp_pbx_sendHTML, //.send_image = .func_channel_read = sccp_wrapper_asterisk_channel_read, .func_channel_write = sccp_asterisk_pbx_fktChannelWrite, .send_digit_begin = sccp_wrapper_recvdigit_begin, .send_digit_end = sccp_wrapper_recvdigit_end, //.write_text = //.write_video = //.cc_callback = // ccss, new >1.6.0 //.exception = // new >1.6.0 //.setoption = sccp_wrapper_asterisk111_setOption, //.queryoption = // new >1.6.0 //.get_pvt_uniqueid = sccp_pbx_get_callid, // new >1.6.0 //.get_base_channel = //.set_base_channel = /* *INDENT-ON* */ }; #endif static int sccp_wrapper_asterisk111_devicestate(const char *data) { int res = AST_DEVICE_UNKNOWN; char *lineName = (char *) data; char *deviceId = NULL; sccp_channelstate_t state; if ((deviceId = strchr(lineName, '@'))) { *deviceId = '\0'; deviceId++; } state = sccp_hint_getLinestate(lineName, deviceId); switch (state) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: res = AST_DEVICE_NOT_INUSE; break; case SCCP_CHANNELSTATE_RINGING: res = AST_DEVICE_RINGING; break; case SCCP_CHANNELSTATE_HOLD: res = AST_DEVICE_ONHOLD; break; case SCCP_CHANNELSTATE_INVALIDNUMBER: res = AST_DEVICE_INVALID; break; case SCCP_CHANNELSTATE_BUSY: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_DND: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: res = AST_DEVICE_UNAVAILABLE; break; case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_PROGRESS: case SCCP_CHANNELSTATE_CALLWAITING: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: res = AST_DEVICE_INUSE; break; } sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: (sccp_asterisk_devicestate) PBX requests state for '%s' - state %s\n", (char *) lineName, ast_devstate2str(res)); return res; } /*! * \brief Convert an array of skinny_codecs (enum) to ast_codec_prefs * * \param skinny_codecs Array of Skinny Codecs * \param astCodecPref Array of PBX Codec Preferences * * \return bit array fmt/Format of ast_format_type (int) * * \todo check bitwise operator (not sure) - DdG */ int skinny_codecs2pbx_codec_pref(skinny_codec_t * skinny_codecs, struct ast_codec_pref *astCodecPref) { struct ast_format dst; uint32_t codec = skinny_codecs2pbx_codecs(skinny_codecs); // convert to bitfield ast_format_from_old_bitfield(&dst, codec); return ast_codec_pref_append(astCodecPref, &dst); // return ast_codec_pref } static boolean_t sccp_wrapper_asterisk111_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); #define RTP_NEW_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_new_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } #define RTP_CHANGE_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_change_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } // static void get_skinnyFormats(struct ast_format_cap *format, skinny_codec_t codecs[], size_t size) // { // unsigned int x; // unsigned len = 0; // // size_t f_len; // struct ast_format tmp_fmt; // const struct ast_format_list *f_list = ast_format_list_get(&f_len); // // if (!size) { // f_list = ast_format_list_destroy(f_list); // return; // } // // for (x = 0; x < ARRAY_LEN(skinny2pbx_codec_maps) && len <= size; x++) { // ast_format_copy(&tmp_fmt, &f_list[x].format); // if (ast_format_cap_iscompatible(format, &tmp_fmt)) { // if (skinny2pbx_codec_maps[x].pbx_codec == ((uint) tmp_fmt.id)) { // codecs[len++] = skinny2pbx_codec_maps[x].skinny_codec; // } // } // } // f_list = ast_format_list_destroy(f_list); // } /*************************************************************************************************************** CODEC **/ /*! \brief Get the name of a format * \note replacement for ast_getformatname * \param format id of format * \return A static string containing the name of the format or "unknown" if unknown. */ const char *pbx_getformatname(const struct ast_format *format) { return ast_getformatname(format); } /*! * \brief Get the names of a set of formats * \note replacement for ast_getformatname_multiple * \param buf a buffer for the output string * \param size size of buf (bytes) * \param format the format (combined IDs of codecs) * Prints a list of readable codec names corresponding to "format". * ex: for format=AST_FORMAT_GSM|AST_FORMAT_SPEEX|AST_FORMAT_ILBC it will return "0x602 (GSM|SPEEX|ILBC)" * \return The return value is buf. */ char *pbx_getformatname_multiple(char *buf, size_t size, struct ast_format_cap *format) { return ast_getformatname_multiple(buf, size, format); } /*! * \brief Read from an Asterisk Channel * \param ast Asterisk Channel as ast_channel * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static PBX_FRAME_TYPE *sccp_wrapper_asterisk111_rtp_read(PBX_CHANNEL_TYPE * ast) { sccp_channel_t *c = NULL; PBX_FRAME_TYPE *frame = &ast_null_frame; if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained pbx_log(LOG_ERROR, "SCCP: (rtp_read) no channel pvt\n"); goto EXIT_FUNC; } if (!c->rtp.audio.rtp) { pbx_log(LOG_NOTICE, "SCCP: (rtp_read) no rtp stream yet. skip\n"); goto EXIT_FUNC; } switch (ast_channel_fdno(ast)) { case 0: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 0); /* RTP Audio */ break; case 1: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 1); /* RTCP Control Channel */ break; #ifdef CS_SCCP_VIDEO case 2: frame = ast_rtp_instance_read(c->rtp.video.rtp, 0); /* RTP Video */ break; case 3: frame = ast_rtp_instance_read(c->rtp.video.rtp, 1); /* RTCP Control Channel for video */ break; #endif default: break; } //sccp_log((DEBUGCAT_CORE))(VERBOSE_PREFIX_3 "%s: read format: ast->fdno: %d, frametype: %d, %s(%d)\n", DEV_ID_LOG(c->device), ast_channel_fdno(ast), frame->frametype, pbx_getformatname(frame->subclass), frame->subclass); if (frame->frametype == AST_FRAME_VOICE) { #ifdef CS_SCCP_CONFERENCE if (c->conference && (!ast_format_is_slinear(ast_channel_readformat(ast)))) { ast_set_read_format(ast, &slinFormat); } #endif } EXIT_FUNC: return frame; } /*! * \brief Find Asterisk/PBX channel by linkid * * \param ast pbx channel * \param data linkId as void * * * \return int * * \todo I don't understand what this functions returns */ static int pbx_find_channel_by_linkid(PBX_CHANNEL_TYPE * ast, const void *data) { const char *linkedId = (char *) data; if (!linkedId) { return 0; } return !pbx_channel_pbx(ast) && ast_channel_linkedid(ast) && (!strcasecmp(ast_channel_linkedid(ast), linkedId)) && !pbx_channel_masq(ast); } /*! * \brief Update Connected Line * \param channel Asterisk Channel as ast_channel * \param data Asterisk Data * \param datalen Asterisk Data Length */ static void sccp_wrapper_asterisk111_connectedline(sccp_channel_t * channel, const void *data, size_t datalen) { PBX_CHANNEL_TYPE *ast = channel->owner; sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: Got connected line update, connected.id.number=%s, connected.id.name=%s, reason=%d\n", pbx_channel_name(ast), ast_channel_connected(ast)->id.number.str ? ast_channel_connected(ast)->id.number.str : "(nil)", ast_channel_connected(ast)->id.name.str ? ast_channel_connected(ast)->id.name.str : "(nil)", ast_channel_connected(ast)->source); // sccp_channel_display_callInfo(channel); /* set the original calling/called party if the reason is a transfer */ if (ast_channel_connected(ast)->source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER || ast_channel_connected(ast)->source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING) { if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Destination\n"); if (ast_channel_connected(ast)->id.number.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.number.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, ast_channel_connected(ast)->id.number.str, sizeof(channel->callInfo.originalCallingPartyNumber)); channel->callInfo.originalCallingParty_valid = 1; } if (ast_channel_connected(ast)->id.name.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.name.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyName, ast_channel_connected(ast)->id.name.str, sizeof(channel->callInfo.originalCallingPartyName)); } if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.callingPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } else { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Transferee\n"); if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyNumber)); sccp_copy_string(channel->callInfo.originalCallingPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyName)); channel->callInfo.originalCallingParty_valid = 1; } if (channel->callInfo.calledParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.calledPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } channel->callInfo.originalCdpnRedirectReason = channel->callInfo.lastRedirectingReason; channel->callInfo.lastRedirectingReason = 0; // need to figure out these codes } if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { if (ast_channel_connected(ast)->id.number.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.number.str)) { sccp_copy_string(channel->callInfo.callingPartyNumber, ast_channel_connected(ast)->id.number.str, sizeof(channel->callInfo.callingPartyNumber)); channel->callInfo.callingParty_valid = 1; } if (ast_channel_connected(ast)->id.name.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.name.str)) { sccp_copy_string(channel->callInfo.callingPartyName, ast_channel_connected(ast)->id.name.str, sizeof(channel->callInfo.callingPartyName)); } } else { if (ast_channel_connected(ast)->id.number.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.number.str)) { sccp_copy_string(channel->callInfo.calledPartyNumber, ast_channel_connected(ast)->id.number.str, sizeof(channel->callInfo.calledPartyNumber)); channel->callInfo.callingParty_valid = 1; } if (ast_channel_connected(ast)->id.name.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.name.str)) { sccp_copy_string(channel->callInfo.calledPartyName, ast_channel_connected(ast)->id.name.str, sizeof(channel->callInfo.calledPartyName)); } } sccp_channel_display_callInfo(channel); sccp_channel_send_callinfo2(channel); } static int sccp_wrapper_asterisk111_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { switch (ind) { case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk111_connectedline(c, data, datalen); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); res = 0; break; default: res = -1; break; } c = sccp_channel_release(c); return res; } if (c->state == SCCP_CHANNELSTATE_DOWN) { c = sccp_channel_release(c); d = d ? sccp_device_release(d) : NULL; return -1; } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Asterisk indicate '%d' condition on channel %s\n", DEV_ID_LOG(d), ind, pbx_channel_name(ast)); /* when the rtp media stream is open we will let asterisk emulate the tones */ res = (((c->rtp.audio.readState != SCCP_RTP_STATUS_INACTIVE) || (d && d->earlyrtp)) ? -1 : 0); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: readStat: %d\n", DEV_ID_LOG(d), c->rtp.audio.readState); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: res: %d\n", DEV_ID_LOG(d), res); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: rtp?: %s\n", DEV_ID_LOG(d), (c->rtp.audio.rtp) ? "yes" : "no"); switch (ind) { case AST_CONTROL_RINGING: if (SKINNY_CALLTYPE_OUTBOUND == c->calltype) { // Allow signalling of RINGOUT only on outbound calls. // Otherwise, there are some issues with late arrival of ringing // indications on ISDN calls (chan_lcr, chan_dahdi) (-DD). sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGOUT); struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; /*! \todo handle multiple remotePeers i.e. DIAL(SCCP/400&SIP/300), find smallest common codecs, what order to use ? */ PBX_CHANNEL_TYPE *remotePeer; for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { if (pbx_find_channel_by_linkid(remotePeer, (void *) ast_channel_linkedid(ast))) { char buf[512]; sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(remotePeer); if (remoteSccpChannel) { sccp_multiple_codecs2str(buf, sizeof(buf) - 1, remoteSccpChannel->preferences.audio, ARRAY_LEN(remoteSccpChannel->preferences.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote preferences: %s\n", buf); uint8_t x, y, z; z = 0; for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { c->remoteCapabilities.audio[z++] = remoteSccpChannel->preferences.audio[x]; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote nativeformats: %s\n", pbx_getformatname_multiple(buf, sizeof(buf) - 1, ast_channel_nativeformats(remotePeer))); sccp_asterisk11_getSkinnyFormatMultiple(ast_channel_nativeformats(remotePeer), c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); } sccp_multiple_codecs2str(buf, sizeof(buf) - 1, c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote caps: %s\n", buf); ast_channel_unref(remotePeer); break; } } ast_channel_iterator_destroy(iterator); } break; case AST_CONTROL_BUSY: sccp_indicate(d, c, SCCP_CHANNELSTATE_BUSY); break; case AST_CONTROL_CONGESTION: sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); break; case AST_CONTROL_PROGRESS: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROGRESS); res = -1; break; case AST_CONTROL_PROCEEDING: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROCEED); res = -1; break; case AST_CONTROL_SRCCHANGE: if (c->rtp.audio.rtp) ast_rtp_instance_change_source(c->rtp.audio.rtp); res = 0; break; case AST_CONTROL_SRCUPDATE: /* Source media has changed. */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Source UPDATE request\n"); if (c->rtp.audio.rtp) { ast_rtp_instance_change_source(c->rtp.audio.rtp); } res = 0; break; /* when the bridged channel hold/unhold the call we are notified here */ case AST_CONTROL_HOLD: sccp_asterisk_moh_start(ast, (const char *) data, c->musicclass); res = 0; break; case AST_CONTROL_UNHOLD: sccp_asterisk_moh_stop(ast); if (c->rtp.audio.rtp) { ast_rtp_instance_update_source(c->rtp.audio.rtp); } res = 0; break; case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk111_connectedline(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ if (c->rtp.video.rtp && d && sccp_device_isVideoSupported(d)) { d->protocol->sendFastPictureUpdate(d, c); res = 0; } else res = -1; break; #ifdef CS_AST_CONTROL_INCOMPLETE case AST_CONTROL_INCOMPLETE: /*!< Indication that the extension dialed is incomplete */ /* \todo implement dial continuation by: * - display message incomplete number * - adding time to channel->scheduler.digittimeout * - rescheduling sccp_pbx_sched_dial */ #ifdef CS_EXPERIMENTAL if (c->scheduler.digittimeout) { SCCP_SCHED_DEL(c->scheduler.digittimeout); } sccp_indicate(d, c, SCCP_CHANNELSTATE_DIGITSFOLL); c->scheduler.digittimeout = PBX(sched_add) (c->enbloc.digittimeout, sccp_pbx_sched_dial, c); #endif res = 0; break; #endif case -1: // Asterisk prod the channel res = -1; break; case AST_CONTROL_PVT_CAUSE_CODE: res = -1; /* Tell asterisk to provide inband signalling */ default: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Don't know how to indicate condition %d\n", ind); res = -1; } //ast_cond_signal(&c->astStateCond); d = sccp_device_release(d); c = sccp_channel_release(c); sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP (pbx_indicate): send asterisk result %d\n", res); return res; } /*! * \brief Write to an Asterisk Channel * \param ast Channel as ast_channel * \param frame Frame as ast_frame * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static int sccp_wrapper_asterisk111_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame) { sccp_channel_t *c = NULL; #ifdef CS_SCCP_VIDEO sccp_device_t *device; #endif int res = 0; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) { // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return -1; } switch (frame->frametype) { case AST_FRAME_VOICE: // checking for samples to transmit if (!frame->samples) { if (strcasecmp(frame->src, "ast_prod")) { pbx_log(LOG_ERROR, "%s: Asked to transmit frame type %d with no samples.\n", c->currentDeviceId, (int) frame->frametype); } else { // frame->samples == 0 when frame_src is ast_prod sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Asterisk prodded channel %s.\n", c->currentDeviceId, pbx_channel_name(ast)); } } if (c->rtp.audio.rtp) { res = ast_rtp_instance_write(c->rtp.audio.rtp, frame); } break; case AST_FRAME_IMAGE: case AST_FRAME_VIDEO: #ifdef CS_SCCP_VIDEO #if DEBUG device = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__); #else device = c->getDevice_retained(c); #endif if (c->rtp.video.writeState == SCCP_RTP_STATUS_INACTIVE && c->rtp.video.rtp && device && c->state != SCCP_CHANNELSTATE_HOLD) { // int codec = pbx_codec2skinny_codec((frame->subclass.codec & AST_FORMAT_VIDEO_MASK)); int codec = pbx_codec2skinny_codec(frame->subclass.format.id); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: got video frame %d\n", c->currentDeviceId, codec); if (0 != codec) { c->rtp.video.writeFormat = codec; sccp_channel_openMultiMediaChannel(c); } } if (c->rtp.video.rtp && (c->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE) != 0) { res = ast_rtp_instance_write(c->rtp.video.rtp, frame); } device = device ? sccp_device_release(device) : NULL; #endif break; case AST_FRAME_TEXT: case AST_FRAME_MODEM: default: pbx_log(LOG_WARNING, "%s: Can't send %d type frames with SCCP write on channel %s\n", c->currentDeviceId, frame->frametype, pbx_channel_name(ast)); break; } // c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk111_sendDigits(const sccp_channel_t * channel, const char *digits) { if (!channel || !channel->owner) { pbx_log(LOG_WARNING, "No channel to send digits to\n"); return 0; } PBX_CHANNEL_TYPE *pbx_channel = channel->owner; int i; PBX_FRAME_TYPE f; f = ast_null_frame; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digits '%s'\n", (char *) channel->currentDeviceId, digits); // We don't just call sccp_pbx_senddigit due to potential overhead, and issues with locking f.src = "SCCP"; // CS_AST_NEW_FRAME_STRUCT // f.frametype = AST_FRAME_DTMF_BEGIN; // ast_queue_frame(pbx_channel, &f); for (i = 0; digits[i] != '\0'; i++) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digit %c\n", (char *) channel->currentDeviceId, digits[i]); f.frametype = AST_FRAME_DTMF_END; // Sending only the dmtf will force asterisk to start with DTMF_BEGIN and schedule the DTMF_END f.subclass.integer = digits[i]; // f.samples = SCCP_MIN_DTMF_DURATION * 8; f.len = SCCP_MIN_DTMF_DURATION; f.src = "SEND DIGIT"; ast_queue_frame(pbx_channel, &f); } return 1; } static int sccp_wrapper_asterisk111_sendDigit(const sccp_channel_t * channel, const char digit) { char digits[3] = "\0\0"; digits[0] = digit; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: got a single digit '%c' -> '%s'\n", channel->currentDeviceId, digit, digits); return sccp_wrapper_asterisk111_sendDigits(channel, digits); } static void sccp_wrapper_asterisk111_setCalleridPresence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (CALLERID_PRESENCE_FORBIDDEN == channel->callInfo.presentation) { ast_channel_caller(pbx_channel)->id.name.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; ast_channel_caller(pbx_channel)->id.number.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; } } static int sccp_wrapper_asterisk111_setNativeAudioFormats(const sccp_channel_t * channel, skinny_codec_t codec[], int length) { struct ast_format fmt; int i; #ifndef CS_EXPERIMENTAL_CODEC length = 1; //set only one codec #endif ast_debug(10, "%s: set native Formats length: %d\n", (char *) channel->currentDeviceId, length); ast_format_cap_remove_bytype(ast_channel_nativeformats(channel->owner), AST_FORMAT_TYPE_AUDIO); for (i = 0; i < length; i++) { ast_format_set(&fmt, skinny_codec2pbx_codec(codec[i]), 0); ast_format_cap_add(ast_channel_nativeformats(channel->owner), &fmt); } return 1; } static int sccp_wrapper_asterisk111_setNativeVideoFormats(const sccp_channel_t * channel, uint32_t formats) { return 1; } boolean_t sccp_wrapper_asterisk111_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId) { sccp_line_t *line = NULL; (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, linkedId, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); // (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, NULL, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); if ((*pbx_channel) == NULL) { return FALSE; } line = channel->line; ast_channel_tech_set((*pbx_channel), &sccp_tech); ast_channel_tech_pvt_set((*pbx_channel), sccp_channel_retain(channel)); ast_channel_context_set(*pbx_channel, line->context); ast_channel_exten_set(*pbx_channel, ""); if (!sccp_strlen_zero(line->language)) { ast_channel_language_set((*pbx_channel), line->language); } if (!sccp_strlen_zero(line->accountcode)) { ast_channel_accountcode_set((*pbx_channel), line->accountcode); } if (!sccp_strlen_zero(line->musicclass)) { ast_channel_musicclass_set((*pbx_channel), line->musicclass); } if (line->amaflags) { ast_channel_amaflags_set(*pbx_channel, line->amaflags); } if (line->callgroup) { ast_channel_callgroup_set(*pbx_channel, line->callgroup); } ast_channel_callgroup_set(*pbx_channel, line->callgroup); // needed for ast_pickup_call #if CS_SCCP_PICKUP if (line->pickupgroup) { ast_channel_pickupgroup_set(*pbx_channel, line->pickupgroup); } #endif ast_channel_priority_set((*pbx_channel), 1); ast_channel_adsicpe_set((*pbx_channel), AST_ADSI_UNAVAILABLE); /** the the tonezone using language information */ if (!sccp_strlen_zero(line->language) && ast_get_indication_zone(line->language)) { ast_channel_zone_set((*pbx_channel), ast_get_indication_zone(line->language)); /* this will core asterisk on hangup */ } ast_module_ref(ast_module_info->self); channel->owner = ast_channel_ref((*pbx_channel)); /* DdG: if we don't unref on hangup, we should not be taking the reference either. It will hinder module unload ? */ return TRUE; } static boolean_t sccp_wrapper_asterisk111_masqueradeHelper(PBX_CHANNEL_TYPE * pbxChannel, PBX_CHANNEL_TYPE * pbxTmpChannel) { pbx_moh_stop(pbxChannel); // Masquerade setup and execution must be done without any channel locks held if (pbx_channel_masquerade(pbxTmpChannel, pbxChannel)) { return FALSE; } //ast_channel_state_set(pbxTmpChannel, AST_STATE_UP); pbx_do_masquerade(pbxTmpChannel); // when returning from bridge, the channel will continue at the next priority // ast_explicit_goto(pbxTmpChannel, pbx_channel_context(pbxTmpChannel), pbx_channel_exten(pbxTmpChannel), pbx_channel_priority(pbxTmpChannel) + 1); return TRUE; } static boolean_t sccp_wrapper_asterisk111_allocTempPBXChannel(PBX_CHANNEL_TYPE * pbxSrcChannel, PBX_CHANNEL_TYPE ** pbxDstChannel) { struct ast_format tmpfmt; if (!pbxSrcChannel) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) no pbx channel provided\n"); return FALSE; } (*pbxDstChannel) = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(pbxSrcChannel), pbx_channel_exten(pbxSrcChannel), pbx_channel_context(pbxSrcChannel), ast_channel_linkedid(pbxSrcChannel), ast_channel_amaflags(pbxSrcChannel), "TMP/%s", ast_channel_name(pbxSrcChannel)); if ((*pbxDstChannel) == NULL) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) create pbx channel failed\n"); return FALSE; } ast_channel_lock(pbxSrcChannel); if (ast_format_cap_is_empty(pbx_channel_nativeformats(pbxSrcChannel))) { ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0); } else { ast_best_codec(pbx_channel_nativeformats(pbxSrcChannel), &tmpfmt); } ast_format_cap_add(ast_channel_nativeformats(*pbxDstChannel), &tmpfmt); ast_set_read_format((*pbxDstChannel), &tmpfmt); ast_set_write_format((*pbxDstChannel), &tmpfmt); ast_channel_context_set((*pbxDstChannel), ast_channel_context(pbxSrcChannel)); ast_channel_exten_set((*pbxDstChannel), ast_channel_exten(pbxSrcChannel)); ast_channel_priority_set((*pbxDstChannel), ast_channel_priority(pbxSrcChannel)); ast_channel_unlock(pbxSrcChannel); return TRUE; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_requestForeignChannel(const char *type, pbx_format_type format, const PBX_CHANNEL_TYPE * requestor, void *data) { PBX_CHANNEL_TYPE *chan; int cause; struct ast_format_cap *cap; struct ast_format tmpfmt; if (!(cap = ast_format_cap_alloc_nolock())) { return 0; } ast_format_cap_add(cap, ast_format_set(&tmpfmt, format, 0)); if (!(chan = ast_request(type, cap, NULL, "", &cause))) { pbx_log(LOG_ERROR, "SCCP: Requested channel could not be created, cause: %d\n", cause); cap = ast_format_cap_destroy(cap); return NULL; } cap = ast_format_cap_destroy(cap); return chan; } int sccp_wrapper_asterisk111_hangup(PBX_CHANNEL_TYPE * ast_channel) { sccp_channel_t *c; PBX_CHANNEL_TYPE *channel_owner = NULL; int res = -1; if ((c = get_sccp_channel_from_pbx_channel(ast_channel))) { channel_owner = c->owner; if (pbx_channel_hangupcause(ast_channel) == AST_CAUSE_ANSWERED_ELSEWHERE) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: This call was answered elsewhere\n"); c->answered_elsewhere = TRUE; } res = sccp_pbx_hangup(c); c->owner = NULL; if (0 == res) { sccp_channel_release(c); //this only releases the get_sccp_channel_from_pbx_channel } } //after this moment c might have gone already ast_channel_tech_pvt_set(ast_channel, NULL); c = c ? sccp_channel_release(c) : NULL; if (channel_owner) { channel_owner = ast_channel_unref(channel_owner); } ast_module_unref(ast_module_info->self); return res; } /*! * \brief Parking Thread Arguments Structure */ /*! * \brief Park the bridge channel of hostChannel * This function prepares the host and the bridged channel to be ready for parking. * It clones the pbx channel of both sides forward them to the park_thread * * \param hostChannel initial channel that request the parking * \todo we have a codec issue after unpark a call * \todo copy connected line info * */ static sccp_parkresult_t sccp_wrapper_asterisk111_park(const sccp_channel_t * hostChannel) { int extout; char extstr[20]; sccp_device_t *device; sccp_parkresult_t res = PARK_RESULT_FAIL; PBX_CHANNEL_TYPE *bridgedChannel = NULL; memset(extstr, 0, sizeof(extstr)); extstr[0] = 128; extstr[1] = SKINNY_LBL_CALL_PARK_AT; bridgedChannel = ast_bridged_channel(hostChannel->owner); device = sccp_channel_getDevice_retained(hostChannel); ast_channel_lock(hostChannel->owner); /* we have to lock our channel, otherwise asterisk crashes internally */ if (!ast_masq_park_call(bridgedChannel, hostChannel->owner, 0, &extout)) { sprintf(&extstr[2], " %d", extout); sccp_dev_displayprinotify(device, extstr, 1, 10); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Parked channel %s on %d\n", DEV_ID_LOG(device), ast_channel_name(bridgedChannel), extout); res = PARK_RESULT_SUCCESS; } ast_channel_unlock(hostChannel->owner); device = sccp_device_release(device); return res; } static boolean_t sccp_wrapper_asterisk111_getFeatureExtension(const sccp_channel_t * channel, char **extension) { struct ast_call_feature *feat; ast_rdlock_call_features(); feat = ast_find_call_feature("automon"); if (feat) { *extension = strdup(feat->exten); } ast_unlock_call_features(); return feat ? TRUE : FALSE; } /*! * \brief Pickup asterisk channel target using chan * * \param chan initial channel that request the parking * \param target Channel t park to * */ static boolean_t sccp_wrapper_asterisk111_pickupChannel(const sccp_channel_t * chan, PBX_CHANNEL_TYPE * target) { boolean_t result; PBX_CHANNEL_TYPE *ref; ref = ast_channel_ref(chan->owner); result = ast_do_pickup(chan->owner, target) ? FALSE : TRUE; if (result) { ((sccp_channel_t *) chan)->owner = ast_channel_ref(target); ast_hangup(ref); } ref = ast_channel_unref(chan->owner); return result; } static uint8_t sccp_wrapper_asterisk111_get_payloadType(const struct sccp_rtp *rtp, skinny_codec_t codec) { struct ast_format astCodec; int payload; ast_format_set(&astCodec, skinny_codec2pbx_codec(codec), 0); payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(rtp->rtp), 1, &astCodec, 0); return payload; } static int sccp_wrapper_asterisk111_get_sampleRate(skinny_codec_t codec) { struct ast_format astCodec; ast_format_set(&astCodec, skinny_codec2pbx_codec(codec), 0); return ast_rtp_lookup_sample_rate2(1, &astCodec, 0); } static sccp_extension_status_t sccp_wrapper_asterisk111_extensionStatus(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (!pbx_channel || !pbx_channel_context(pbx_channel)) { pbx_log(LOG_ERROR, "%s: (extension_status) Either no pbx_channel or no valid context provided to lookup number\n", channel->designator); return SCCP_EXTENSION_NOTEXISTS; } int ignore_pat = ast_ignore_pattern(pbx_channel_context(pbx_channel), channel->dialedNumber); int ext_exist = ast_exists_extension(pbx_channel, pbx_channel_context(pbx_channel), channel->dialedNumber, 1, channel->line->cid_num); int ext_canmatch = ast_canmatch_extension(pbx_channel, pbx_channel_context(pbx_channel), channel->dialedNumber, 1, channel->line->cid_num); int ext_matchmore = ast_matchmore_extension(pbx_channel, pbx_channel_context(pbx_channel), channel->dialedNumber, 1, channel->line->cid_num); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "+=sccp extension matcher says==================+\n" VERBOSE_PREFIX_2 "|ignore |exists |can match |match more|\n" VERBOSE_PREFIX_2 "|%3s |%3s |%3s |%3s |\n" VERBOSE_PREFIX_2 "+==============================================+\n", ignore_pat ? "yes" : "no", ext_exist ? "yes" : "no", ext_canmatch ? "yes" : "no", ext_matchmore ? "yes" : "no"); if (ignore_pat) { return SCCP_EXTENSION_NOTEXISTS; } else if (ext_exist) { if (ext_canmatch && !ext_matchmore) { return SCCP_EXTENSION_EXACTMATCH; } else { return SCCP_EXTENSION_MATCHMORE; } } return SCCP_EXTENSION_NOTEXISTS; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_request(const char *type, struct ast_format_cap *format, const PBX_CHANNEL_TYPE * requestor, const char *dest, int *cause) { sccp_channel_request_status_t requestStatus; PBX_CHANNEL_TYPE *result_ast_channel = NULL; sccp_channel_t *channel = NULL; const char *linkedId = NULL; skinny_codec_t audioCapabilities[SKINNY_MAX_CAPABILITIES]; skinny_codec_t videoCapabilities[SKINNY_MAX_CAPABILITIES]; memset(&audioCapabilities, 0, sizeof(audioCapabilities)); memset(&videoCapabilities, 0, sizeof(videoCapabilities)); //! \todo parse request char *lineName; skinny_codec_t codec = SKINNY_CODEC_G711_ULAW_64K; sccp_autoanswer_t autoanswer_type = SCCP_AUTOANSWER_NONE; uint8_t autoanswer_cause = AST_CAUSE_NOTDEFINED; int ringermode = 0; *cause = AST_CAUSE_NOTDEFINED; if (!type) { pbx_log(LOG_NOTICE, "Attempt to call with unspecified type of channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } if (!dest) { pbx_log(LOG_NOTICE, "Attempt to call SCCP/ failed\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } /* we leave the data unchanged */ lineName = strdupa((const char *) dest); /* parsing options string */ char *options = NULL; int optc = 0; char *optv[2]; int opti = 0; if ((options = strchr(lineName, '/'))) { *options = '\0'; options++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked us to create a channel with type=%s, format=" UI64FMT ", lineName=%s, options=%s\n", type, (uint64_t) ast_format_cap_to_old_bitfield(format), lineName, (options) ? options : ""); /* get ringer mode from ALERT_INFO */ const char *alert_info = NULL; if (requestor) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "_ALERT_INFO"); if (!alert_info) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "__ALERT_INFO"); } } if (alert_info && !sccp_strlen_zero(alert_info)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Found ALERT_INFO=%s\n", alert_info); if (strcasecmp(alert_info, "inside") == 0) ringermode = SKINNY_RINGTYPE_INSIDE; else if (strcasecmp(alert_info, "feature") == 0) ringermode = SKINNY_RINGTYPE_FEATURE; else if (strcasecmp(alert_info, "silent") == 0) ringermode = SKINNY_RINGTYPE_SILENT; else if (strcasecmp(alert_info, "urgent") == 0) ringermode = SKINNY_RINGTYPE_URGENT; } /* done ALERT_INFO parsing */ /* parse options */ if (options && (optc = sccp_app_separate_args(options, '/', optv, sizeof(optv) / sizeof(optv[0])))) { pbx_log(LOG_NOTICE, "parse options\n"); for (opti = 0; opti < optc; opti++) { pbx_log(LOG_NOTICE, "parse option '%s'\n", optv[opti]); if (!strncasecmp(optv[opti], "aa", 2)) { /* let's use the old style auto answer aa1w and aa2w */ if (!strncasecmp(optv[opti], "aa1w", 4)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa2w", 4)) { autoanswer_type = SCCP_AUTOANSWER_2W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa=", 3)) { optv[opti] += 3; pbx_log(LOG_NOTICE, "parsing aa\n"); if (!strncasecmp(optv[opti], "1w", 2)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 2; } else if (!strncasecmp(optv[opti], "2w", 2)) { autoanswer_type = SCCP_AUTOANSWER_2W; pbx_log(LOG_NOTICE, "set aa to 2w\n"); optv[opti] += 2; } } /* since the pbx ignores autoanswer_cause unless SCCP_RWLIST_GETSIZE(l->channels) > 1, it is safe to set it if provided */ if (!sccp_strlen_zero(optv[opti]) && (autoanswer_cause)) { if (!strcasecmp(optv[opti], "b")) autoanswer_cause = AST_CAUSE_BUSY; else if (!strcasecmp(optv[opti], "u")) autoanswer_cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; else if (!strcasecmp(optv[opti], "c")) autoanswer_cause = AST_CAUSE_CONGESTION; } if (autoanswer_cause) *cause = autoanswer_cause; /* check for ringer options */ } else if (!strncasecmp(optv[opti], "ringer=", 7)) { optv[opti] += 7; if (!strcasecmp(optv[opti], "inside")) ringermode = SKINNY_RINGTYPE_INSIDE; else if (!strcasecmp(optv[opti], "outside")) ringermode = SKINNY_RINGTYPE_OUTSIDE; else if (!strcasecmp(optv[opti], "feature")) ringermode = SKINNY_RINGTYPE_FEATURE; else if (!strcasecmp(optv[opti], "silent")) ringermode = SKINNY_RINGTYPE_SILENT; else if (!strcasecmp(optv[opti], "urgent")) ringermode = SKINNY_RINGTYPE_URGENT; else ringermode = SKINNY_RINGTYPE_OUTSIDE; } else { pbx_log(LOG_WARNING, "Wrong option %s\n", optv[opti]); } } } /** getting remote capabilities */ char cap_buf[512]; /* audio capabilities */ if (requestor) { sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(requestor); if (remoteSccpChannel) { uint8_t x, y, z; z = 0; /* shrink audioCapabilities to remote preferred/capable format */ for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { audioCapabilities[z++] = remoteSccpChannel->preferences.audio[x]; break; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_asterisk11_getSkinnyFormatMultiple(ast_channel_nativeformats(requestor), audioCapabilities, ARRAY_LEN(audioCapabilities)); // replace AUDIO_MASK with AST_FORMAT_TYPE_AUDIO check } /* video capabilities */ sccp_asterisk11_getSkinnyFormatMultiple(ast_channel_nativeformats(requestor), videoCapabilities, ARRAY_LEN(videoCapabilities)); //replace AUDIO_MASK with AST_FORMAT_TYPE_AUDIO check } sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, audioCapabilities, ARRAY_LEN(audioCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote audio caps: %s\n", cap_buf); sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, videoCapabilities, ARRAY_LEN(videoCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote video caps: %s\n", cap_buf); /** done */ /** get requested format */ // codec = pbx_codec2skinny_codec(ast_format_cap_to_old_bitfield(format)); codec = sccp_asterisk11_getSkinnyFormatSingle(format); requestStatus = sccp_requestChannel(lineName, codec, audioCapabilities, ARRAY_LEN(audioCapabilities), autoanswer_type, autoanswer_cause, ringermode, &channel); switch (requestStatus) { case SCCP_REQUEST_STATUS_SUCCESS: // everything is fine break; case SCCP_REQUEST_STATUS_LINEUNKNOWN: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s Unknown -> Not Successfull\n", lineName); *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER; goto EXITFUNC; case SCCP_REQUEST_STATUS_LINEUNAVAIL: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s not currently registered -> Try again later\n", lineName); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; case SCCP_REQUEST_STATUS_ERROR: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; default: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; } if (requestor) { linkedId = ast_channel_linkedid(requestor); } if (!sccp_pbx_channel_allocate(channel, linkedId)) { //! \todo handle error in more detail, cleanup sccp channel pbx_log(LOG_WARNING, "SCCP: Unable to allocate channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; } if (requestor) { /* set calling party */ sccp_channel_set_callingparty(channel, (char *) ast_channel_caller((PBX_CHANNEL_TYPE *) requestor)->id.name.str, (char *) ast_channel_caller((PBX_CHANNEL_TYPE *) requestor)->id.number.str); sccp_channel_set_originalCalledparty(channel, (char *) ast_channel_redirecting((PBX_CHANNEL_TYPE *) requestor)->orig.name.str, (char *) ast_channel_redirecting((PBX_CHANNEL_TYPE *) requestor)->orig.number.str); if (ast_channel_linkedid(requestor)) { ast_channel_linkedid_set(channel->owner, ast_channel_linkedid(requestor)); } } /** workaround for asterisk console log flooded channel.c:5080 ast_write: Codec mismatch on channel SCCP/xxx-0000002d setting write format to g722 from unknown native formats (nothing) */ skinny_codec_t codecs[] = { SKINNY_CODEC_WIDEBAND_256K }; sccp_wrapper_asterisk111_setNativeAudioFormats(channel, codecs, 1); sccp_wrapper_asterisk111_setReadFormat(channel, SKINNY_CODEC_WIDEBAND_256K); sccp_wrapper_asterisk111_setWriteFormat(channel, SKINNY_CODEC_WIDEBAND_256K); /** done */ EXITFUNC: if (channel) { result_ast_channel = channel->owner; sccp_channel_release(channel); } return result_ast_channel; } static int sccp_wrapper_asterisk111_call(PBX_CHANNEL_TYPE * ast, const char *dest, int timeout) { sccp_channel_t *c = NULL; struct varshead *headp; struct ast_var_t *current; int res = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk request to call %s (dest:%s, timeout: %d)\n", pbx_channel_name(ast), dest, timeout); if (!sccp_strlen_zero(pbx_channel_call_forward(ast))) { PBX(queue_control) (ast, -1); /* Prod Channel if in the middle of a call_forward instead of proceed */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Forwarding Call to '%s'\n", pbx_channel_call_forward(ast)); return 0; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { pbx_log(LOG_WARNING, "SCCP: Asterisk request to call %s on channel: %s, but we don't have this channel!\n", dest, pbx_channel_name(ast)); return -1; } /* Check whether there is MaxCallBR variables */ headp = ast_channel_varshead(ast); //ast_log(LOG_NOTICE, "SCCP: search for varibles!\n"); AST_LIST_TRAVERSE(headp, current, entries) { //ast_log(LOG_NOTICE, "var: name: %s, value: %s\n", ast_var_name(current), ast_var_value(current)); if (!strcasecmp(ast_var_name(current), "__MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } else if (!strcasecmp(ast_var_name(current), "MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } } res = sccp_pbx_call(c, (char *) dest, timeout); c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk111_answer(PBX_CHANNEL_TYPE * chan) { //! \todo change this handling and split pbx and sccp handling -MC int res = -1; sccp_channel_t *channel = NULL; if ((channel = get_sccp_channel_from_pbx_channel(chan))) { res = sccp_pbx_answer(channel); channel = sccp_channel_release(channel); } return res; } /** * * \todo update remote capabilities after fixup */ static int sccp_wrapper_asterisk111_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: we got a fixup request for %s\n", ast_channel_name(newchan)); sccp_channel_t *c = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(newchan))) { pbx_log(LOG_WARNING, "sccp_pbx_fixup(old: %s(%p), new: %s(%p)). no SCCP channel to fix\n", ast_channel_name(oldchan), (void *) oldchan, ast_channel_name(newchan), (void *) newchan); res = -1; } else { if (c->owner != oldchan) { ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, c->owner); res = -1; } else { c->owner = ast_channel_ref(newchan); if (!sccp_strlen_zero(c->line->language)) { ast_channel_language_set(newchan, c->line->language); } ast_channel_unref(oldchan); //! \todo force update of rtp_peer for directrtp // sccp_wrapper_asterisk111_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0); //! \todo update remote capabilities after fixup } c = sccp_channel_release(c); } return res; } #ifdef CS_AST_RTP_INSTANCE_BRIDGE static enum ast_bridge_result sccp_wrapper_asterisk111_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms) { enum ast_bridge_result res; int new_flags = flags; /* \note temporarily marked out until we figure out how to get directrtp back on track - DdG */ sccp_channel_t *sc0 = NULL, *sc1 = NULL; if ((sc0 = get_sccp_channel_from_pbx_channel(c0)) && (sc1 = get_sccp_channel_from_pbx_channel(c1))) { // Switch off DTMF between SCCP phones new_flags &= !AST_BRIDGE_DTMF_CHANNEL_0; new_flags &= !AST_BRIDGE_DTMF_CHANNEL_1; if (GLOB(directrtp)) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } else { sccp_device_t *d0 = sccp_channel_getDevice_retained(sc0); if (d0) { sccp_device_t *d1 = sccp_channel_getDevice_retained(sc1); if (d1) { if (d0->directrtp && d1->directrtp) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } d1 = sccp_device_release(d1); } d0 = sccp_device_release(d0); } } sc0->peerIsSCCP = TRUE; sc1->peerIsSCCP = TRUE; // SCCP Key handle direction to asterisk is still to be implemented here // sccp_pbx_senddigit } else { // Switch on DTMF between differing channels ast_channel_undefer_dtmf(c0); ast_channel_undefer_dtmf(c1); } sc0 = sc0 ? sccp_channel_release(sc0) : NULL; sc1 = sc1 ? sccp_channel_release(sc1) : NULL; //res = ast_rtp_bridge(c0, c1, new_flags, fo, rc, timeoutms); res = ast_rtp_instance_bridge(c0, c1, new_flags, fo, rc, timeoutms); switch (res) { case AST_BRIDGE_COMPLETE: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Complete\n", ast_channel_name(c0), ast_channel_name(c1)); break; case AST_BRIDGE_FAILED: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed\n", ast_channel_name(c0), ast_channel_name(c1)); break; case AST_BRIDGE_FAILED_NOWARN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed NoWarn\n", ast_channel_name(c0), ast_channel_name(c1)); break; case AST_BRIDGE_RETRY: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed Retry\n", ast_channel_name(c0), ast_channel_name(c1)); break; } /*! \todo Implement callback function queue upon completion */ return res; } #endif static enum ast_rtp_glue_result sccp_wrapper_asterisk111_get_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", pbx_channel_name(ast)); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; ao2_ref(*rtp, +1); if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( wrapper_asterisk111_get_rtp_peer ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_LOCAL; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( wrapper_asterisk111_get_rtp_peer ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", pbx_channel_name(ast)); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static int sccp_wrapper_asterisk111_set_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE * rtp, PBX_RTP_TYPE * vrtp, PBX_RTP_TYPE * trtp, const struct ast_format_cap *codecs, int nat_active) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int result = 0; do { if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO PVT\n"); result = -1; break; } if (!c->line) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO LINE\n"); result = -1; break; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO DEVICE\n"); result = -1; break; } if (!rtp) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) RTP not ready\n"); result = 0; break; } // if (!d->directrtp || d->nat) { struct ast_sockaddr us_tmp; struct sockaddr_in us = { 0, }; // sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) %s, use local part\n", d->directrtp ? "direct media disabled" : "NATed device"); ast_rtp_instance_get_local_address(rtp, &us_tmp); ast_sockaddr_to_sin(&us_tmp, &us); us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->session->ourip.s_addr; sccp_rtp_set_peer(c, &c->rtp.audio, &us); // } else { // struct ast_sockaddr them_tmp; // struct sockaddr_in them = { 0, }; // // ast_rtp_instance_get_remote_address(rtp, &them_tmp); // ast_sockaddr_to_sin(&them_tmp, &them); // sccp_rtp_set_peer(c, &c->rtp.audio, &them); // } if (ast_channel_state(ast) != AST_STATE_UP) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Early RTP stage, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } else { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Native Bridge Break, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } } while (0); /* Need a return here to break the bridge */ d = d ? sccp_device_release(d) : NULL; return result; } static enum ast_rtp_glue_result sccp_wrapper_asterisk111_get_vrtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", pbx_channel_name(ast)); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); //! \todo should this not be getVideoPeerInfo if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_FORBID; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", pbx_channel_name(ast)); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static void sccp_wrapper_asterisk111_getCodec(PBX_CHANNEL_TYPE * ast, struct ast_format_cap *result) { uint8_t i; struct ast_format fmt; sccp_channel_t *channel; if (!(channel = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP | DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (getCodec) NO PVT\n"); return; } ast_debug(10, "asterisk requests format for channel %s, readFormat: %s(%d)\n", pbx_channel_name(ast), codec2str(channel->rtp.audio.readFormat), channel->rtp.audio.readFormat); for (i = 0; i < ARRAY_LEN(channel->preferences.audio); i++) { ast_format_set(&fmt, skinny_codec2pbx_codec(channel->preferences.audio[i]), 0); ast_format_cap_add(result, &fmt); } return; } /* * \brief get callerid_name from pbx * \param sccp_channle Asterisk Channel * \param cid name result * \return parse result */ static int sccp_wrapper_asterisk111_callerid_name(const sccp_channel_t * channel, char **cid_name) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.name.str && strlen(ast_channel_caller(pbx_chan)->id.name.str) > 0) { *cid_name = strdup(ast_channel_caller(pbx_chan)->id.name.str); return 1; } return 0; } /* * \brief get callerid_name from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_number(const sccp_channel_t * channel, char **cid_number) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.number.str && strlen(ast_channel_caller(pbx_chan)->id.number.str) > 0) { *cid_number = strdup(ast_channel_caller(pbx_chan)->id.number.str); return 1; } return 0; } /* * \brief get callerid_ton from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_ton(const sccp_channel_t * channel, char **cid_ton) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.number.valid) { return ast_channel_caller(pbx_chan)->ani.number.plan; } return 0; } /* * \brief get callerid_ani from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_ani(const sccp_channel_t * channel, char **cid_ani) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->ani.number.valid && ast_channel_caller(pbx_chan)->ani.number.str && strlen(ast_channel_caller(pbx_chan)->ani.number.str) > 0) { *cid_ani = strdup(ast_channel_caller(pbx_chan)->ani.number.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_subaddr(const sccp_channel_t * channel, char **cid_subaddr) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.subaddress.valid && ast_channel_caller(pbx_chan)->id.subaddress.str && strlen(ast_channel_caller(pbx_chan)->id.subaddress.str) > 0) { *cid_subaddr = strdup(ast_channel_caller(pbx_chan)->id.subaddress.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx (Destination ID) * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_dnid(const sccp_channel_t * channel, char **cid_dnid) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_dialed(pbx_chan)->number.str && strlen(ast_channel_dialed(pbx_chan)->number.str) > 0) { *cid_dnid = strdup(ast_channel_dialed(pbx_chan)->number.str); return 1; } return 0; } /* * \brief get callerid_rdnis from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_rdnis(const sccp_channel_t * channel, char **cid_rdnis) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_redirecting(pbx_chan)->from.number.valid && ast_channel_redirecting(pbx_chan)->from.number.str && strlen(ast_channel_redirecting(pbx_chan)->from.number.str) > 0) { *cid_rdnis = strdup(ast_channel_redirecting(pbx_chan)->from.number.str); return 1; } return 0; } /* * \brief get callerid_presence from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_presence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; // if (ast_channel_caller(pbx_chan)->id.number.valid) { // return ast_channel_caller(pbx_chan)->id.number.presentation; // } // return 0; if ((ast_party_id_presentation(&ast_channel_caller(pbx_chan)->id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) { return CALLERID_PRESENCE_ALLOWED; } return CALLERID_PRESENCE_FORBIDDEN; } static int sccp_wrapper_asterisk111_rtp_stop(sccp_channel_t * channel) { if (channel->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping phone media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.audio.rtp); } if (channel->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping video media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.video.rtp); } return 0; } static boolean_t sccp_wrapper_asterisk111_create_audio_rtp(sccp_channel_t * c) { sccp_session_t *s = NULL; sccp_device_t *d = NULL; struct ast_sockaddr sock; // struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; if (GLOB(bindaddr.sin_addr.s_addr) == INADDR_ANY) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = GLOB(bindaddr.sin_port); sin.sin_addr = s->ourip; /* sccp_socket_getOurAddressfor(s->sin.sin_addr, sin.sin_addr); */// maybe we should use this opertunity to check the connected ip-address again ast_sockaddr_from_sin(&sock, &sin); } else { ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating rtp server connection on %s\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock)); c->rtp.audio.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.audio.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: rtp server created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_RTCP, 1); if (SCCP_DTMFMODE_INBAND == d->dtmfmode) { ast_rtp_instance_dtmf_mode_set(c->rtp.audio.rtp, AST_RTP_DTMF_MODE_INBAND); } else { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF, 1); ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, 1); } ast_channel_set_fd(c->owner, 0, ast_rtp_instance_fd(c->rtp.audio.rtp, 0)); ast_channel_set_fd(c->owner, 1, ast_rtp_instance_fd(c->rtp.audio.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } // memset(&astCodecPref, 0, sizeof(astCodecPref)); // if (skinny_codecs2pbx_codec_pref(c->preferences.audio, &astCodecPref)) { // ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); // } // char pref_buf[128]; // ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); // sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pref: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); ast_rtp_instance_set_qos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.audio.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add audio codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_AUDIO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "audio", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk111_create_video_rtp(sccp_channel_t * c) { sccp_session_t *s; sccp_device_t *d = NULL; struct ast_sockaddr sock; struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating vrtp server connection at %s\n", DEV_ID_LOG(d), pbx_inet_ntoa(s->ourip)); ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); c->rtp.video.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.video.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: vrtp created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.video.rtp, AST_RTP_PROPERTY_RTCP, 1); ast_channel_set_fd(c->owner, 2, ast_rtp_instance_fd(c->rtp.video.rtp, 0)); ast_channel_set_fd(c->owner, 3, ast_rtp_instance_fd(c->rtp.video.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } memset(&astCodecPref, 0, sizeof(astCodecPref)); if (skinny_codecs2pbx_codec_pref(c->preferences.video, &astCodecPref)) { ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); } //char pref_buf[128]; //ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); //sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pef: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.video.rtp, d->video_tos, d->video_cos, "SCCP VRTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.video.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add video codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_VIDEO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "video", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk111_destroyRTP(PBX_RTP_TYPE * rtp) { int res; res = ast_rtp_instance_destroy(rtp); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk111_checkHangup(const sccp_channel_t * channel) { int res; res = ast_check_hangup(channel->owner); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk111_rtpGetPeer(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_remote_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk111_rtpGetUs(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_local_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk111_getChannelByName(const char *name, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *ast = ast_channel_get_by_name(name); if (!ast) return FALSE; *pbx_channel = ast; return TRUE; } static int sccp_wrapper_asterisk111_rtp_set_peer(const struct sccp_rtp *rtp, const struct sockaddr_in *new_peer, int nat_active) { struct ast_sockaddr ast_sockaddr_dest; struct ast_sockaddr ast_sockaddr_source; int res; ((struct sockaddr_in *) new_peer)->sin_family = AF_INET; ast_sockaddr_from_sin(&ast_sockaddr_dest, new_peer); ast_sockaddr_set_port(&ast_sockaddr_dest, ntohs(new_peer->sin_port)); res = ast_rtp_instance_set_remote_address(rtp->rtp, &ast_sockaddr_dest); ast_rtp_instance_get_local_address(rtp->rtp, &ast_sockaddr_source); // sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "SCCP: Tell PBX to send RTP/UDP media from '%s:%d' to '%s:%d' (NAT: %s)\n", ast_sockaddr_stringify_host(&ast_sockaddr_source), ast_sockaddr_port(&ast_sockaddr_source), ast_sockaddr_stringify_host(&ast_sockaddr_dest), ast_sockaddr_port(&ast_sockaddr_dest), nat_active ? "yes" : "no"); if (nat_active) { ast_rtp_instance_set_prop(rtp->rtp, AST_RTP_PROPERTY_NAT, 1); } return res; } static boolean_t sccp_wrapper_asterisk111_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec) { //! \todo possibly needs to be synced to ast108 if (!channel) return FALSE; struct ast_format tmp_format; struct ast_format_cap *cap = ast_format_cap_alloc_nolock(); ast_format_set(&tmp_format, skinny_codec2pbx_codec(codec), 0); ast_format_cap_add(cap, &tmp_format); ast_set_write_format_from_cap(channel->owner, cap); ast_format_cap_destroy(cap); if (NULL != channel->rtp.audio.rtp) { ast_rtp_instance_set_write_format(channel->rtp.audio.rtp, &tmp_format); } return TRUE; } static boolean_t sccp_wrapper_asterisk111_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec) { //! \todo possibly needs to be synced to ast108 if (!channel) return FALSE; struct ast_format tmp_format; struct ast_format_cap *cap = ast_format_cap_alloc_nolock(); ast_format_set(&tmp_format, skinny_codec2pbx_codec(codec), 0); ast_format_cap_add(cap, &tmp_format); ast_set_read_format_from_cap(channel->owner, cap); ast_format_cap_destroy(cap); if (NULL != channel->rtp.audio.rtp) { ast_rtp_instance_set_read_format(channel->rtp.audio.rtp, &tmp_format); } return TRUE; } static void sccp_wrapper_asterisk111_setCalleridName(const sccp_channel_t * channel, const char *name) { if (name) { ast_party_name_free(&ast_channel_caller(channel->owner)->id.name); ast_channel_caller(channel->owner)->id.name.str = ast_strdup(name); ast_channel_caller(channel->owner)->id.name.valid = 1; } } static void sccp_wrapper_asterisk111_setCalleridNumber(const sccp_channel_t * channel, const char *number) { if (number) { ast_party_number_free(&ast_channel_caller(channel->owner)->id.number); ast_channel_caller(channel->owner)->id.number.str = ast_strdup(number); ast_channel_caller(channel->owner)->id.number.valid = 1; } } static void sccp_wrapper_asterisk111_setRedirectingParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { ast_party_number_free(&ast_channel_redirecting(channel->owner)->from.number); ast_channel_redirecting(channel->owner)->from.number.str = ast_strdup(number); ast_channel_redirecting(channel->owner)->from.number.valid = 1; } if (name) { ast_party_name_free(&ast_channel_redirecting(channel->owner)->from.name); ast_channel_redirecting(channel->owner)->from.name.str = ast_strdup(name); ast_channel_redirecting(channel->owner)->from.name.valid = 1; } } static void sccp_wrapper_asterisk111_setRedirectedParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { ast_party_number_free(&ast_channel_redirecting(channel->owner)->to.number); ast_channel_redirecting(channel->owner)->to.number.str = ast_strdup(number); ast_channel_redirecting(channel->owner)->to.number.valid = 1; } if (name) { ast_party_name_free(&ast_channel_redirecting(channel->owner)->to.name); ast_channel_redirecting(channel->owner)->to.name.str = ast_strdup(name); ast_channel_redirecting(channel->owner)->to.name.valid = 1; } } static void sccp_wrapper_asterisk111_updateConnectedLine(const sccp_channel_t * channel, const char *number, const char *name, uint8_t reason) { struct ast_party_connected_line connected; struct ast_set_party_connected_line update_connected; memset(&update_connected, 0, sizeof(update_connected)); ast_party_connected_line_init(&connected); if (number) { update_connected.id.number = 1; connected.id.number.valid = 1; connected.id.number.str = (char *) number; connected.id.number.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (name) { update_connected.id.name = 1; connected.id.name.valid = 1; connected.id.name.str = (char *) name; connected.id.name.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (update_connected.id.number || update_connected.id.name) { ast_set_party_id_all(&update_connected.priv); // connected.id.tag = NULL; connected.source = reason; ast_channel_queue_connected_line_update(channel->owner, &connected, &update_connected); sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "SCCP: do connected line for line '%s', name: %s ,num: %s\n", pbx_channel_name(channel->owner), name ? name : "(NULL)", number ? number : "(NULL)"); } } /* // moved to ast.c static void sccp_wrapper_asterisk111_sendRedirectedUpdate(const sccp_channel_t * channel, const char *fromNumber, const char *fromName, const char *toNumber, const char *toName, uint8_t reason){ struct ast_party_redirecting redirecting; struct ast_set_party_redirecting update_redirecting; ast_party_redirecting_init(&redirecting); memset(&update_redirecting, 0, sizeof(update_redirecting)); // update redirecting info line for source part if(fromNumber){ update_redirecting.from.number = 1; redirecting.from.number.valid = 1; redirecting.from.number.str = strdupa(fromNumber); } if(fromName){ update_redirecting.from.name = 1; redirecting.from.name.valid = 1; redirecting.from.name.str = strdupa(fromName); } if(toNumber){ update_redirecting.to.number = 1; redirecting.to.number.valid = 1; redirecting.to.number.str = strdupa(toNumber); } if(toName){ update_redirecting.to.name = 1; redirecting.to.name.valid = 1; redirecting.to.name.str = strdupa(toName); } ast_channel_queue_redirecting_update(channel->owner, &redirecting, &update_redirecting); } */ static int sccp_wrapper_asterisk111_sched_add(int when, sccp_sched_cb callback, const void *data) { if (sched) return ast_sched_add(sched, when, callback, data); return FALSE; } static long sccp_wrapper_asterisk111_sched_when(int id) { if (sched) return ast_sched_when(sched, id); return FALSE; } static int sccp_wrapper_asterisk111_sched_wait(int id) { if (sched) return ast_sched_wait(sched); return FALSE; } static int sccp_wrapper_asterisk111_sched_del(int id) { if (sched) return ast_sched_del(sched, id); return FALSE; } static int sccp_wrapper_asterisk111_setCallState(const sccp_channel_t * channel, int state) { sccp_pbx_setcallstate((sccp_channel_t *) channel, state); return 0; } static boolean_t sccp_asterisk_getRemoteChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *remotePeer = NULL; // struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); // // ((struct ao2_iterator *)iterator)->flags |= AO2_ITERATOR_DONTLOCK; // // for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { // if (pbx_find_channel_by_linkid(remotePeer, (void *)ast_channel_linkedid(channel->owner))) { // break; // } // } // // while(!(remotePeer = ast_channel_iterator_next(iterator) ){ // ast_channel_unref(remotePeer); // } // // ast_channel_iterator_destroy(iterator); // // if (remotePeer) { // *pbx_channel = remotePeer; // remotePeer = ast_channel_unref(remotePeer); // should we be releasing th referenec here, it has not been taken explicitly. // return TRUE; // } *pbx_channel = remotePeer; return FALSE; } /*! * \brief Send Text to Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param text Text to be send as char * \return Succes as int * * \called_from_asterisk */ static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; uint8_t instance; if (!ast) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX CHANNEL to send text to\n"); return -1; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send text to (%s)\n", pbx_channel_name(ast)); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send text to (%s)\n", pbx_channel_name(ast)); c = sccp_channel_release(c); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Sending text %s on %s\n", d->id, text, pbx_channel_name(ast)); instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, (char *) text, 10); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! * \brief Receive First Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit First Digit as char * \return Always Return -1 as int * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit) { return -1; } /*! * \brief Receive Last Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit Last Digit as char * \param duration Duration as int * \return boolean * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send digit to (%s)\n", pbx_channel_name(ast)); return -1; } do { if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send digit to (%s)\n", pbx_channel_name(ast)); break; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked to send dtmf '%d' to channel %s. Trying to send it %s\n", digit, pbx_channel_name(ast), (d->dtmfmode) ? "outofband" : "inband"); if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Can't send the dtmf '%d' %c to a not connected channel %s\n", d->id, digit, digit, pbx_channel_name(ast)); break; } sccp_dev_keypadbutton(d, digit, sccp_device_find_index_for_line(d, c->line->name), c->callid); } while (0); d = d ? sccp_device_release(d) : NULL; c = c ? sccp_channel_release(c) : NULL; return -1; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_findChannelWithCallback(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data, boolean_t lock) { PBX_CHANNEL_TYPE *remotePeer = NULL; // struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); // // if (!lock) { // ((struct ao2_iterator *)iterator)->flags |= AO2_ITERATOR_DONTLOCK; // } // // for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { // // if (found_cb(remotePeer, data)) { // // ast_channel_lock(remotePeer); // ast_channel_unref(remotePeer); // break; // } // // } // ast_channel_iterator_destroy(iterator); return remotePeer; } /*! \brief Set an option on a asterisk channel */ #if 0 static int sccp_wrapper_asterisk111_setOption(PBX_CHANNEL_TYPE * ast, int option, void *data, int datalen) { int res = -1; sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: channel: %s(%s) setOption: %d\n", c->currentDeviceId, sccp_channel_toString(c), pbx_channel_name(ast), option); //! if AST_OPTION_FORMAT_READ / AST_OPTION_FORMAT_WRITE are available we might be indication that we can do transcoding (channel.c:set_format). Correct ? */ switch (option) { case AST_OPTION_FORMAT_READ: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_read_format(c->rtp.audio.rtp, (struct ast_format *) data); } //sccp_wrapper_asterisk111_setReadFormat(c, (struct ast_format *) data); break; case AST_OPTION_FORMAT_WRITE: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_write_format(c->rtp.audio.rtp, (struct ast_format *) data); } //sccp_wrapper_asterisk111_setWriteFormat(c, (struct ast_format *) data); break; case AST_OPTION_MAKE_COMPATIBLE: if (c->rtp.audio.rtp) { res = ast_rtp_instance_make_compatible(ast, c->rtp.audio.rtp, (PBX_CHANNEL_TYPE *) data); } break; case AST_OPTION_DIGIT_DETECT: case AST_OPTION_SECURE_SIGNALING: case AST_OPTION_SECURE_MEDIA: res = -1; break; default: break; } c = sccp_channel_release(c); } return res; } #endif static void sccp_wrapper_asterisk_set_pbxchannel_linkedid(PBX_CHANNEL_TYPE * pbx_channel, const char *new_linkedid) { if (pbx_channel) { if (!strcmp(ast_channel_linkedid(pbx_channel), new_linkedid)) { return; } ast_cel_check_retire_linkedid(pbx_channel); ast_channel_linkedid_set(pbx_channel, new_linkedid); ast_cel_linkedid_ref(new_linkedid); } }; #define DECLARE_PBX_CHANNEL_STRGET(_field) \ static const char *sccp_wrapper_asterisk_get_channel_##_field(const sccp_channel_t * channel) \ { \ static const char *empty_channel_##_field = "--no-channel" #_field "--"; \ if (channel->owner) { \ return ast_channel_##_field(channel->owner); \ } \ return empty_channel_##_field; \ }; #define DECLARE_PBX_CHANNEL_STRSET(_field) \ static void sccp_wrapper_asterisk_set_channel_##_field(const sccp_channel_t * channel, const char * _field) \ { \ if (channel->owner) { \ ast_channel_##_field##_set(channel->owner, _field); \ } \ }; DECLARE_PBX_CHANNEL_STRGET(name) DECLARE_PBX_CHANNEL_STRSET(name) DECLARE_PBX_CHANNEL_STRGET(uniqueid) DECLARE_PBX_CHANNEL_STRGET(appl) DECLARE_PBX_CHANNEL_STRGET(exten) DECLARE_PBX_CHANNEL_STRSET(exten) DECLARE_PBX_CHANNEL_STRGET(linkedid) DECLARE_PBX_CHANNEL_STRGET(context) DECLARE_PBX_CHANNEL_STRSET(context) DECLARE_PBX_CHANNEL_STRGET(macroexten) DECLARE_PBX_CHANNEL_STRSET(macroexten) DECLARE_PBX_CHANNEL_STRGET(macrocontext) DECLARE_PBX_CHANNEL_STRSET(macrocontext) DECLARE_PBX_CHANNEL_STRGET(call_forward) DECLARE_PBX_CHANNEL_STRSET(call_forward) static void sccp_wrapper_asterisk_set_channel_linkedid(const sccp_channel_t * channel, const char *new_linkedid) { if (channel->owner) { sccp_wrapper_asterisk_set_pbxchannel_linkedid(channel->owner, new_linkedid); } }; static enum ast_channel_state sccp_wrapper_asterisk_get_channel_state(const sccp_channel_t * channel) { if (channel->owner) { return ast_channel_state(channel->owner); } return 0; } static const struct ast_pbx *sccp_wrapper_asterisk_get_channel_pbx(const sccp_channel_t * channel) { if (channel->owner) { return ast_channel_pbx(channel->owner); } return NULL; } static void sccp_wrapper_asterisk_set_channel_tech_pvt(const sccp_channel_t * channel) { if (channel->owner) { ast_channel_tech_pvt_set(channel->owner, (void *) channel); } } static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!datalen || sccp_strlen_zero(data) || !(!strncmp(data, "http://", 7) || !strncmp(data, "file://", 7) || !strncmp(data, "ftp://", 6))) { pbx_log(LOG_NOTICE, "SCCP: Received a non valid URL\n"); return -1; } struct ast_frame fr; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { #if DEBUG if (!(d = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { #else if (!(d = c->getDevice_retained(c))) { #endif c = sccp_channel_release(c); return -1; } memset(&fr, 0, sizeof(fr)); fr.frametype = AST_FRAME_HTML; fr.data.ptr = (char *) data; fr.src = "SCCP Send URL"; fr.datalen = datalen; sccp_push_result_t pushResult = d->pushURL(d, data, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { fr.subclass.integer = AST_HTML_LDCOMPLETE; } else { fr.subclass.integer = AST_HTML_NOSUPPORT; } ast_queue_frame(ast, ast_frisolate(&fr)); d = sccp_device_release(d); c = sccp_channel_release(c); } return 0; } /*! * \brief Queue a control frame * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type */ int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Queue a control frame with payload * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type * \param data Payload * \param datalen Payload Length */ int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control,.data.ptr = (void *) data,.datalen = datalen }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Get Hint Extension State and return the matching Busy Lamp Field State */ static skinny_busylampfield_state_t sccp_wrapper_asterisk111_getExtensionState(const char *extension, const char *context) { skinny_busylampfield_state_t result = SKINNY_BLF_STATUS_UNKNOWN; if (sccp_strlen_zero(extension) || sccp_strlen_zero(context)) { pbx_log(LOG_ERROR, "SCCP: PBX(getExtensionState): Either extension:'%s' or context:;%s' provided is empty\n", extension, context); return result; } int state = ast_extension_state(NULL, context, extension); switch (state) { case AST_EXTENSION_REMOVED: case AST_EXTENSION_DEACTIVATED: case AST_EXTENSION_UNAVAILABLE: result = SKINNY_BLF_STATUS_UNKNOWN; break; case AST_EXTENSION_NOT_INUSE: result = SKINNY_BLF_STATUS_IDLE; break; case AST_EXTENSION_INUSE: case AST_EXTENSION_ONHOLD: case AST_EXTENSION_ONHOLD + AST_EXTENSION_INUSE: case AST_EXTENSION_BUSY: result = SKINNY_BLF_STATUS_INUSE; break; case AST_EXTENSION_RINGING + AST_EXTENSION_INUSE: case AST_EXTENSION_RINGING: result = SKINNY_BLF_STATUS_ALERTING; break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (getExtensionState) extension: %s@%s, extension_state: '%s (%d)' -> blf state '%d'\n", extension, context, ast_extension_state2str(state), state, result); return result; } /*! * \brief using RTP Glue Engine */ #if defined(__cplusplus) || defined(c_plusplus) struct ast_rtp_glue sccp_rtp = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, mod: NULL, get_rtp_info:sccp_wrapper_asterisk111_get_rtp_peer, get_vrtp_info:sccp_wrapper_asterisk111_get_vrtp_peer, get_trtp_info:NULL, update_peer:sccp_wrapper_asterisk111_set_rtp_peer, get_codec:sccp_wrapper_asterisk111_getCodec, /* *INDENT-ON* */ }; #else struct ast_rtp_glue sccp_rtp = { .type = SCCP_TECHTYPE_STR, .get_rtp_info = sccp_wrapper_asterisk111_get_rtp_peer, .get_vrtp_info = sccp_wrapper_asterisk111_get_vrtp_peer, .update_peer = sccp_wrapper_asterisk111_set_rtp_peer, .get_codec = sccp_wrapper_asterisk111_getCodec, }; #endif #ifdef HAVE_PBX_MESSAGE_H #include "asterisk/message.h" static int sccp_asterisk_message_send(const struct ast_msg *msg, const char *to, const char *from) { char *lineName; sccp_line_t *line; const char *messageText = ast_msg_get_body(msg); int res = -1; lineName = (char *) sccp_strdupa(to); if (strchr(lineName, '@')) { strsep(&lineName, "@"); } else { strsep(&lineName, ":"); } if (sccp_strlen_zero(lineName)) { pbx_log(LOG_WARNING, "MESSAGE(to) is invalid for SCCP - '%s'\n", to); return -1; } line = sccp_line_find_byname(lineName, FALSE); if (!line) { pbx_log(LOG_WARNING, "line '%s' not found\n", lineName); return -1; } /** \todo move this to line implementation */ sccp_linedevices_t *linedevice; sccp_push_result_t pushResult; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { pushResult = linedevice->device->pushTextMessage(linedevice->device, messageText, from, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { res = 0; } } SCCP_LIST_UNLOCK(&line->devices); return res; } #if defined(__cplusplus) || defined(c_plusplus) static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ name: "sccp", msg_send:sccp_asterisk_message_send, /* *INDENT-ON* */ }; #else static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ .name = "sccp", .msg_send = sccp_asterisk_message_send, /* *INDENT-ON* */ }; #endif #endif /*! * \brief pbx_manager_register * * \note this functions needs to be defined here, because it depends on the static declaration of ast_module_info->self */ int pbx_manager_register(const char *action, int authority, int (*func) (struct mansession * s, const struct message * m), const char *synopsis, const char *description) { return ast_manager_register2(action, authority, func, ast_module_info->self, synopsis, description); } boolean_t sccp_wrapper_asterisk111_setLanguage(PBX_CHANNEL_TYPE * pbxChannel, const char *language) { ast_channel_language_set(pbxChannel, language); return TRUE; } #if defined(__cplusplus) || defined(c_plusplus) sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ alloc_pbxChannel: sccp_wrapper_asterisk111_allocPBXChannel, set_callstate: sccp_wrapper_asterisk111_setCallState, checkhangup: sccp_wrapper_asterisk111_checkHangup, hangup: NULL, requestHangup: sccp_wrapper_asterisk_requestHangup, forceHangup: sccp_wrapper_asterisk_forceHangup, extension_status: sccp_wrapper_asterisk111_extensionStatus, setPBXChannelLinkedId: sccp_wrapper_asterisk_set_pbxchannel_linkedid, /** get channel by name */ getChannelByName: sccp_wrapper_asterisk111_getChannelByName, getRemoteChannel: sccp_asterisk_getRemoteChannel, getChannelByCallback: NULL, getChannelLinkedId: sccp_wrapper_asterisk_get_channel_linkedid, setChannelLinkedId: sccp_wrapper_asterisk_set_channel_linkedid, getChannelName: sccp_wrapper_asterisk_get_channel_name, getChannelUniqueID: sccp_wrapper_asterisk_get_channel_uniqueid, getChannelExten: sccp_wrapper_asterisk_get_channel_exten, setChannelExten: sccp_wrapper_asterisk_set_channel_exten, getChannelContext: sccp_wrapper_asterisk_get_channel_context, setChannelContext: sccp_wrapper_asterisk_set_channel_context, getChannelMacroExten: sccp_wrapper_asterisk_get_channel_macroexten, setChannelMacroExten: sccp_wrapper_asterisk_set_channel_macroexten, getChannelMacroContext: sccp_wrapper_asterisk_get_channel_macrocontext, setChannelMacroContext: sccp_wrapper_asterisk_set_channel_macrocontext, getChannelCallForward: sccp_wrapper_asterisk_get_channel_call_forward, setChannelCallForward: sccp_wrapper_asterisk_set_channel_call_forward, getChannelAppl: sccp_wrapper_asterisk_get_channel_appl, getChannelState: sccp_wrapper_asterisk_get_channel_state, getChannelPbx: sccp_wrapper_asterisk_get_channel_pbx, setChannelTechPVT: sccp_wrapper_asterisk_set_channel_tech_pvt, set_nativeAudioFormats: sccp_wrapper_asterisk111_setNativeAudioFormats, set_nativeVideoFormats: sccp_wrapper_asterisk111_setNativeVideoFormats, getPeerCodecCapabilities: NULL, send_digit: sccp_wrapper_asterisk111_sendDigit, send_digits: sccp_wrapper_asterisk111_sendDigits, sched_add: sccp_wrapper_asterisk111_sched_add, sched_del: sccp_wrapper_asterisk111_sched_del, sched_when: sccp_wrapper_asterisk111_sched_when, sched_wait: sccp_wrapper_asterisk111_sched_wait, /* rtp */ rtp_getPeer: sccp_wrapper_asterisk111_rtpGetPeer, rtp_getUs: sccp_wrapper_asterisk111_rtpGetUs, rtp_setPeer: sccp_wrapper_asterisk111_rtp_set_peer, rtp_setWriteFormat: sccp_wrapper_asterisk111_setWriteFormat, rtp_setReadFormat: sccp_wrapper_asterisk111_setReadFormat, rtp_destroy: sccp_wrapper_asterisk111_destroyRTP, rtp_stop: sccp_wrapper_asterisk111_rtp_stop, rtp_codec: NULL, rtp_audio_create: sccp_wrapper_asterisk111_create_audio_rtp, rtp_video_create: sccp_wrapper_asterisk111_create_video_rtp, rtp_get_payloadType: sccp_wrapper_asterisk111_get_payloadType, rtp_get_sampleRate: sccp_wrapper_asterisk111_get_sampleRate, rtp_bridgePeers: NULL, /* callerid */ get_callerid_name: sccp_wrapper_asterisk111_callerid_name, get_callerid_number: sccp_wrapper_asterisk111_callerid_number, get_callerid_ton: sccp_wrapper_asterisk111_callerid_ton, get_callerid_ani: sccp_wrapper_asterisk111_callerid_ani, get_callerid_subaddr: sccp_wrapper_asterisk111_callerid_subaddr, get_callerid_dnid: sccp_wrapper_asterisk111_callerid_dnid, get_callerid_rdnis: sccp_wrapper_asterisk111_callerid_rdnis, get_callerid_presence: sccp_wrapper_asterisk111_callerid_presence, set_callerid_name: sccp_wrapper_asterisk111_setCalleridName, set_callerid_number: sccp_wrapper_asterisk111_setCalleridNumber, set_callerid_ani: NULL, set_callerid_dnid: NULL, set_callerid_redirectingParty: sccp_wrapper_asterisk111_setRedirectingParty, set_callerid_redirectedParty: sccp_wrapper_asterisk111_setRedirectedParty, set_callerid_presence: sccp_wrapper_asterisk111_setCalleridPresence, set_connected_line: sccp_wrapper_asterisk111_updateConnectedLine, // sendRedirectedUpdate: sccp_wrapper_asterisk111_sendRedirectedUpdate, sendRedirectedUpdate: sccp_asterisk_sendRedirectedUpdate, /* feature section */ feature_park: sccp_wrapper_asterisk111_park, feature_stopMusicOnHold: NULL, feature_addToDatabase: sccp_asterisk_addToDatabase, feature_getFromDatabase: sccp_asterisk_getFromDatabase, feature_removeFromDatabase: sccp_asterisk_removeFromDatabase, feature_removeTreeFromDatabase: sccp_asterisk_removeTreeFromDatabase, feature_monitor: sccp_wrapper_asterisk_featureMonitor, getFeatureExtension: sccp_wrapper_asterisk111_getFeatureExtension, feature_pickup: sccp_wrapper_asterisk111_pickupChannel, eventSubscribe: NULL, findChannelByCallback: sccp_wrapper_asterisk111_findChannelWithCallback, moh_start: sccp_asterisk_moh_start, moh_stop: sccp_asterisk_moh_stop, queue_control: sccp_asterisk_queue_control, queue_control_data: sccp_asterisk_queue_control_data, allocTempPBXChannel: sccp_wrapper_asterisk111_allocTempPBXChannel, masqueradeHelper: sccp_wrapper_asterisk111_masqueradeHelper, requestForeignChannel: sccp_wrapper_asterisk111_requestForeignChannel, set_language: sccp_wrapper_asterisk111_setLanguage, getExtensionState: sccp_wrapper_asterisk111_getExtensionState, findPickupChannelByExtenLocked: sccp_wrapper_asterisk111_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #else /*! * \brief SCCP - PBX Callback Functions * (Decoupling Tight Dependencies on Asterisk Functions) */ struct sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ /* channel */ .alloc_pbxChannel = sccp_wrapper_asterisk111_allocPBXChannel, .requestHangup = sccp_wrapper_asterisk_requestHangup, .forceHangup = sccp_wrapper_asterisk_forceHangup, .extension_status = sccp_wrapper_asterisk111_extensionStatus, .setPBXChannelLinkedId = sccp_wrapper_asterisk_set_pbxchannel_linkedid, .getChannelByName = sccp_wrapper_asterisk111_getChannelByName, .getChannelLinkedId = sccp_wrapper_asterisk_get_channel_linkedid, .setChannelLinkedId = sccp_wrapper_asterisk_set_channel_linkedid, .getChannelName = sccp_wrapper_asterisk_get_channel_name, .setChannelName = sccp_wrapper_asterisk_set_channel_name, .getChannelUniqueID = sccp_wrapper_asterisk_get_channel_uniqueid, .getChannelExten = sccp_wrapper_asterisk_get_channel_exten, .setChannelExten = sccp_wrapper_asterisk_set_channel_exten, .getChannelContext = sccp_wrapper_asterisk_get_channel_context, .setChannelContext = sccp_wrapper_asterisk_set_channel_context, .getChannelMacroExten = sccp_wrapper_asterisk_get_channel_macroexten, .setChannelMacroExten = sccp_wrapper_asterisk_set_channel_macroexten, .getChannelMacroContext = sccp_wrapper_asterisk_get_channel_macrocontext, .setChannelMacroContext = sccp_wrapper_asterisk_set_channel_macrocontext, .getChannelCallForward = sccp_wrapper_asterisk_get_channel_call_forward, .setChannelCallForward = sccp_wrapper_asterisk_set_channel_call_forward, .getChannelAppl = sccp_wrapper_asterisk_get_channel_appl, .getChannelState = sccp_wrapper_asterisk_get_channel_state, .getChannelPbx = sccp_wrapper_asterisk_get_channel_pbx, .setChannelTechPVT = sccp_wrapper_asterisk_set_channel_tech_pvt, .getRemoteChannel = sccp_asterisk_getRemoteChannel, .checkhangup = sccp_wrapper_asterisk111_checkHangup, /* digits */ .send_digits = sccp_wrapper_asterisk111_sendDigits, .send_digit = sccp_wrapper_asterisk111_sendDigit, /* schedulers */ .sched_add = sccp_wrapper_asterisk111_sched_add, .sched_del = sccp_wrapper_asterisk111_sched_del, .sched_when = sccp_wrapper_asterisk111_sched_when, .sched_wait = sccp_wrapper_asterisk111_sched_wait, /* callstate / indicate */ .set_callstate = sccp_wrapper_asterisk111_setCallState, /* codecs */ .set_nativeAudioFormats = sccp_wrapper_asterisk111_setNativeAudioFormats, .set_nativeVideoFormats = sccp_wrapper_asterisk111_setNativeVideoFormats, /* rtp */ .rtp_getPeer = sccp_wrapper_asterisk111_rtpGetPeer, .rtp_getUs = sccp_wrapper_asterisk111_rtpGetUs, .rtp_stop = sccp_wrapper_asterisk111_rtp_stop, .rtp_audio_create = sccp_wrapper_asterisk111_create_audio_rtp, .rtp_video_create = sccp_wrapper_asterisk111_create_video_rtp, .rtp_get_payloadType = sccp_wrapper_asterisk111_get_payloadType, .rtp_get_sampleRate = sccp_wrapper_asterisk111_get_sampleRate, .rtp_destroy = sccp_wrapper_asterisk111_destroyRTP, .rtp_setWriteFormat = sccp_wrapper_asterisk111_setWriteFormat, .rtp_setReadFormat = sccp_wrapper_asterisk111_setReadFormat, .rtp_setPeer = sccp_wrapper_asterisk111_rtp_set_peer, /* callerid */ .get_callerid_name = sccp_wrapper_asterisk111_callerid_name, .get_callerid_number = sccp_wrapper_asterisk111_callerid_number, .get_callerid_ton = sccp_wrapper_asterisk111_callerid_ton, .get_callerid_ani = sccp_wrapper_asterisk111_callerid_ani, .get_callerid_subaddr = sccp_wrapper_asterisk111_callerid_subaddr, .get_callerid_dnid = sccp_wrapper_asterisk111_callerid_dnid, .get_callerid_rdnis = sccp_wrapper_asterisk111_callerid_rdnis, .get_callerid_presence = sccp_wrapper_asterisk111_callerid_presence, .set_callerid_name = sccp_wrapper_asterisk111_setCalleridName, //! \todo implement callback .set_callerid_number = sccp_wrapper_asterisk111_setCalleridNumber, //! \todo implement callback .set_callerid_dnid = NULL, //! \todo implement callback .set_callerid_redirectingParty = sccp_wrapper_asterisk111_setRedirectingParty, .set_callerid_redirectedParty = sccp_wrapper_asterisk111_setRedirectedParty, .set_callerid_presence = sccp_wrapper_asterisk111_setCalleridPresence, .set_connected_line = sccp_wrapper_asterisk111_updateConnectedLine, // .sendRedirectedUpdate = sccp_wrapper_asterisk111_sendRedirectedUpdate, .sendRedirectedUpdate = sccp_asterisk_sendRedirectedUpdate, /* database */ .feature_addToDatabase = sccp_asterisk_addToDatabase, .feature_getFromDatabase = sccp_asterisk_getFromDatabase, .feature_removeFromDatabase = sccp_asterisk_removeFromDatabase, .feature_removeTreeFromDatabase = sccp_asterisk_removeTreeFromDatabase, .feature_monitor = sccp_wrapper_asterisk_featureMonitor, .feature_park = sccp_wrapper_asterisk111_park, .getFeatureExtension = sccp_wrapper_asterisk111_getFeatureExtension, .feature_pickup = sccp_wrapper_asterisk111_pickupChannel, .findChannelByCallback = sccp_wrapper_asterisk111_findChannelWithCallback, .moh_start = sccp_asterisk_moh_start, .moh_stop = sccp_asterisk_moh_stop, .queue_control = sccp_asterisk_queue_control, .queue_control_data = sccp_asterisk_queue_control_data, .allocTempPBXChannel = sccp_wrapper_asterisk111_allocTempPBXChannel, .masqueradeHelper = sccp_wrapper_asterisk111_masqueradeHelper, .requestForeignChannel = sccp_wrapper_asterisk111_requestForeignChannel, .set_language = sccp_wrapper_asterisk111_setLanguage, .getExtensionState = sccp_wrapper_asterisk111_getExtensionState, .findPickupChannelByExtenLocked = sccp_wrapper_asterisk111_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #endif #if defined(__cplusplus) || defined(c_plusplus) static ast_module_load_result load_module(void) #else static int load_module(void) #endif { boolean_t res; /* check for existance of chan_skinny */ if (ast_module_check("chan_skinny.so")) { pbx_log(LOG_ERROR, "Chan_skinny is loaded. Please check modules.conf and remove chan_skinny before loading chan_sccp.\n"); return AST_MODULE_LOAD_DECLINE; } sched = ast_sched_context_create(); if (!sched) { pbx_log(LOG_WARNING, "Unable to create schedule context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } if (ast_sched_start_thread(sched)) { ast_sched_context_destroy(sched); sched = NULL; return AST_MODULE_LOAD_FAILURE; } /* make globals */ res = sccp_prePBXLoad(); if (!res) { return AST_MODULE_LOAD_DECLINE; } sccp_tech.capabilities = ast_format_cap_alloc(); ast_format_cap_add_all_by_type(sccp_tech.capabilities, AST_FORMAT_TYPE_AUDIO); io = io_context_create(); if (!io) { pbx_log(LOG_WARNING, "Unable to create I/O context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } //! \todo how can we handle this in a pbx independent way? if (!load_config()) { if (ast_channel_register(&sccp_tech)) { pbx_log(LOG_ERROR, "Unable to register channel class SCCP\n"); return AST_MODULE_LOAD_FAILURE; } } #ifdef HAVE_PBX_MESSAGE_H if (ast_msg_tech_register(&sccp_msg_tech)) { /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */ pbx_log(LOG_WARNING, "Unable to register message interface\n"); } #endif // ast_rtp_glue_register(&sccp_rtp); sccp_register_management(); sccp_register_cli(); sccp_register_dialplan_functions(); sccp_postPBX_load(); return AST_MODULE_LOAD_SUCCESS; } static int unload_module(void) { sccp_preUnload(); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP RTP protocol\n"); // ast_rtp_glue_unregister(&sccp_rtp); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP Channel Tech\n"); ast_channel_unregister(&sccp_tech); sccp_unregister_dialplan_functions(); sccp_unregister_cli(); sccp_mwi_module_stop(); #ifdef CS_SCCP_MANAGER sccp_unregister_management(); #endif #ifdef HAVE_PBX_MESSAGE_H ast_msg_tech_unregister(&sccp_msg_tech); #endif if (io) { io_context_destroy(io); io = NULL; } while (SCCP_REF_DESTROYED != sccp_refcount_isRunning()) { usleep(SCCP_TIME_TO_KEEP_REFCOUNTEDOBJECT); // give enough time for all schedules to end and refcounted object to be cleanup completely } if (sched) { pbx_log(LOG_NOTICE, "Cleaning up scheduled items:\n"); int scheduled_items = 0; ast_sched_dump(sched); while ((scheduled_items = ast_sched_runq(sched))) { pbx_log(LOG_NOTICE, "Cleaning up %d scheduled items... please wait\n", scheduled_items); usleep(ast_sched_wait(sched)); } ast_sched_context_destroy(sched); sched = NULL; } sccp_free(sccp_globals); pbx_log(LOG_NOTICE, "Running Cleanup\n"); #ifdef HAVE_LIBGC // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Collect a little:%d\n",GC_collect_a_little()); // CHECK_LEAKS(); // GC_gcollect(); #endif pbx_log(LOG_NOTICE, "Module chan_sccp unloaded\n"); return 0; } static int module_reload(void) { sccp_reload(); return 0; } #if defined(__cplusplus) || defined(c_plusplus) static struct ast_module_info __mod_info = { NULL, load_module, module_reload, unload_module, NULL, NULL, AST_MODULE, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)", ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, AST_BUILDOPT_SUM, AST_MODPRI_CHANNEL_DRIVER, NULL, }; static void __attribute__ ((constructor)) __reg_module(void) { ast_module_register(&__mod_info); } static void __attribute__ ((destructor)) __unreg_module(void) { ast_module_unregister(&__mod_info); } static const __attribute__ ((unused)) struct ast_module_info *ast_module_info = &__mod_info; #else AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Skinny Client Control Protocol (SCCP). SCCP-Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "')",.load = load_module,.unload = unload_module,.reload = module_reload,.load_pri = AST_MODPRI_DEFAULT,.nonoptreq = "chan_local" /* dependence on res_rtp_asterisk makes us unload to late */ /* .nonoptreq = "res_rtp_asterisk,chan_local" */ ); #endif PBX_CHANNEL_TYPE *sccp_search_remotepeer_locked(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data) { PBX_CHANNEL_TYPE *remotePeer = NULL; // struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); // // ((struct ao2_iterator *)iterator)->flags |= AO2_ITERATOR_DONTLOCK; // // for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { // // if (found_cb(remotePeer, data)) { // // ast_channel_lock(remotePeer); // ast_channel_unref(remotePeer); // break; // } // // } // ast_channel_iterator_destroy(iterator); return remotePeer; } PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context) { struct ast_channel *target = NULL; /*!< Potential pickup target */ struct ast_channel_iterator *iter; if (!(iter = ast_channel_iterator_by_exten_new(exten, context))) { return NULL; } while ((target = ast_channel_iterator_next(iter))) { ast_channel_lock(target); if ((chan != target) && ast_can_pickup(target)) { ast_log(LOG_NOTICE, "%s pickup by %s\n", ast_channel_name(target), ast_channel_name(chan)); break; } ast_channel_unlock(target); target = ast_channel_unref(target); } ast_channel_iterator_destroy(iter); return target; }
722,274
./chan-sccp-b/src/pbx_impl/ast/ast.c
/*! * \file ast.c * \brief SCCP PBX Asterisk Wrapper Class * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note Reworked, but based on chan_sccp code. * The original chan_sccp driver that was made by Zozo which itself was derived from the chan_skinny driver. * Modified by Jan Czmok and Julien Goodwin * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #include <config.h> #include "../../common.h" SCCP_FILE_VERSION(__FILE__, "$Revision: 2269 $") /* * \brief itterate through locked pbx channels * \note replacement for ast_channel_walk_locked * \param ast_chan Asterisk Channel * \return ast_chan Locked Asterisk Channel * * \todo implement pbx_channel_walk_locked or replace * \deprecated */ PBX_CHANNEL_TYPE *pbx_channel_walk_locked(PBX_CHANNEL_TYPE * target) { #if ASTERISK_VERSION_NUMBER >= 10800 struct ast_channel_iterator *iter = ast_channel_iterator_all_new(); PBX_CHANNEL_TYPE *res = NULL; PBX_CHANNEL_TYPE *tmp = NULL; /* no target given, so just start iteration */ if (!target) { tmp = ast_channel_iterator_next(iter); } else { /* search for our target channel and use the next iteration value */ while ((tmp = ast_channel_iterator_next(iter)) != NULL) { if (tmp == target) { tmp = ast_channel_iterator_next(iter); break; } } } if (tmp) { res = tmp; tmp = ast_channel_unref(tmp); ast_channel_lock(res); } ast_channel_iterator_destroy(iter); return res; #else return ast_channel_walk_locked(target); #endif } /* * \brief iterate through locked pbx channels and search using specified match function * \param is_match match function * \param data paremeter data for match function * \return pbx_channel Locked Asterisk Channel * * \deprecated */ PBX_CHANNEL_TYPE *pbx_channel_search_locked(int (*is_match) (PBX_CHANNEL_TYPE *, void *), void *data) { //#ifdef ast_channel_search_locked #if ASTERISK_VERSION_NUMBER < 10800 return ast_channel_search_locked(is_match, data); #else boolean_t matched = FALSE; PBX_CHANNEL_TYPE *pbx_channel = NULL; PBX_CHANNEL_TYPE *tmp = NULL; struct ast_channel_iterator *iter = NULL; if (!(iter = ast_channel_iterator_all_new())) { return NULL; } for (; iter && (tmp = ast_channel_iterator_next(iter)); tmp = ast_channel_unref(tmp)) { pbx_channel_lock(tmp); if (is_match(tmp, data)) { matched = TRUE; break; } pbx_channel_unlock(tmp); } if (iter) { ast_channel_iterator_destroy(iter); } if (matched) { pbx_channel = tmp; tmp = ast_channel_unref(tmp); return pbx_channel; } else { return NULL; } #endif } /************************************************************************************************************** CONFIG **/ /* * \brief Add a new rule to a list of HAs * \note replacement for ast_append_ha * \param sense Sense / Key * \param stuff Value / Stuff to Add * \param path list of HAs * \param error Error as int * \return The head of the HA list * * \deprecated */ struct ast_ha *pbx_append_ha(NEWCONST char *sense, const char *stuff, struct ast_ha *path, int *error) { #if ASTERISK_VERSION_NUMBER < 10600 return ast_append_ha(sense, stuff, path); #else return ast_append_ha(sense, stuff, path, error); #endif // ASTERISK_VERSION_NUMBER } /* * \brief Register a new context * \note replacement for ast_context_find_or_create * * This will first search for a context with your name. If it exists already, it will not * create a new one. If it does not exist, it will create a new one with the given name * and registrar. * * \param extcontexts pointer to the ast_context structure pointer * \param name name of the new context * \param registrar registrar of the context * \return NULL on failure, and an ast_context structure on success */ struct ast_context *pbx_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar) { #if ASTERISK_VERSION_NUMBER < 10600 return ast_context_find_or_create(extcontexts, name, registrar); #else return ast_context_find_or_create(extcontexts, exttable, name, registrar); #endif // ASTERISK_VERSION_NUMBER } /*! * \brief Load a config file * * \param filename path of file to open. If no preceding '/' character, * path is considered relative to AST_CONFIG_DIR * \param who_asked The module which is making this request. * \param flags Optional flags: * CONFIG_FLAG_WITHCOMMENTS - load the file with comments intact; * CONFIG_FLAG_FILEUNCHANGED - check the file mtime and return CONFIG_STATUS_FILEUNCHANGED if the mtime is the same; or * CONFIG_FLAG_NOCACHE - don't cache file mtime (main purpose of this option is to save memory on temporary files). * * \details * Create a config structure from a given configuration file. * * \return an ast_config data structure on success * \retval NULL on error */ struct ast_config *pbx_config_load(const char *filename, const char *who_asked, struct ast_flags flags) { #if ASTERISK_VERSION_NUMBER < 10600 return ast_config_load(filename); #else return ast_config_load2(filename, who_asked, flags); #endif // ASTERISK_VERSION_NUMBER } /*! * \brief Get/Create new config variable * \note replacement for ast_variable_new * \param v Variable Name as char * \return The return value is struct ast_variable. */ PBX_VARIABLE_TYPE *pbx_variable_new(PBX_VARIABLE_TYPE * v) { #if ASTERISK_VERSION_NUMBER >= 10600 return ast_variable_new(v->name, v->value, v->file); #else return ast_variable_new(v->name, v->value); #endif // ASTERISK_VERSION_NUMBER } /******************************************************************************************************** NET / SOCKET **/ /* * \brief thread-safe replacement for inet_ntoa() * \note replacement for ast_pbx_inet_ntoa * \param ia In Address / Source Address * \return Address as char */ const char *pbx_inet_ntoa(struct in_addr ia) { #if ASTERISK_VERSION_NUMBER < 10400 char iabuf[INET_ADDRSTRLEN]; return ast_inet_ntoa(iabuf, sizeof(iabuf), ia); #else return ast_inet_ntoa(ia); #endif // ASTERISK_VERSION_NUMBER } #if ASTERISK_VERSION_NUMBER < 10400 /* BackPort of ast_str2cos & ast_str2cos for asterisk 1.2 */ struct dscp_codepoint { char *name; unsigned int space; }; static const struct dscp_codepoint dscp_pool1[] = { {"CS0", 0x00}, {"CS1", 0x08}, {"CS2", 0x10}, {"CS3", 0x18}, {"CS4", 0x20}, {"CS5", 0x28}, {"CS6", 0x30}, {"CS7", 0x38}, {"AF11", 0x0A}, {"AF12", 0x0C}, {"AF13", 0x0E}, {"AF21", 0x12}, {"AF22", 0x14}, {"AF23", 0x16}, {"AF31", 0x1A}, {"AF32", 0x1C}, {"AF33", 0x1E}, {"AF41", 0x22}, {"AF42", 0x24}, {"AF43", 0x26}, {"EF", 0x2E}, }; int pbx_str2tos(const char *value, unsigned int *tos) { int fval; unsigned int x; if (sscanf(value, "%30i", &fval) == 1) { *tos = fval & 0xFF; return 0; } for (x = 0; x < ARRAY_LEN(dscp_pool1); x++) { if (!strcasecmp(value, dscp_pool1[x].name)) { *tos = dscp_pool1[x].space << 2; return 0; } } return -1; } #else int pbx_str2tos(const char *value, unsigned int *tos) { return ast_str2tos(value, tos); } #endif // ASTERISK_VERSION_NUMBER #if ASTERISK_VERSION_NUMBER < 10600 int pbx_str2cos(const char *value, unsigned int *cos) { int fval; if (sscanf(value, "%30d", &fval) == 1) { if (fval < 8) { *cos = fval; return 0; } } return -1; } #else int pbx_str2cos(const char *value, unsigned int *cos) { return ast_str2cos(value, cos); } #endif // ASTERISK_VERSION_NUMBER /************************************************************************************************************* GENERAL **/ /*! * \brief Simply remove extension from context * \note replacement for ast_context_remove_extension * * \param context context to remove extension from * \param extension which extension to remove * \param priority priority of extension to remove (0 to remove all) * \param registrar registrar of the extension * * This function removes an extension from a given context. * * \retval 0 on success * \retval -1 on failure * * @{ */ int pbx_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar) { #if ASTERISK_VERSION_NUMBER >= 10600 struct pbx_find_info q = {.stacklen = 0 }; if (pbx_find_extension(NULL, NULL, &q, context, extension, 1, NULL, "", E_MATCH)) { return ast_context_remove_extension(context, extension, priority, registrar); } else { return -1; } #else return ast_context_remove_extension(context, extension, priority, registrar); #endif // ASTERISK_VERSION_NUMBER } /*! * \brief Send ack in manager list transaction * \note replacement for astman_send_listack * \param s Management Session * \param m Management Message * \param msg Message * \param listflag List Flag */ void pbxman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag) { #if ASTERISK_VERSION_NUMBER < 10600 astman_send_ack(s, m, msg); #else astman_send_listack(s, m, msg, listflag); #endif // ASTERISK_VERSION_NUMBER } /****************************************************************************************************** CODEC / FORMAT **/ /*! * \brief Convert a ast_codec (fmt) to a skinny codec (enum) * * \param fmt Format as ast_format_type * * \return skinny_codec */ skinny_codec_t pbx_codec2skinny_codec(ast_format_type fmt) { uint32_t i; for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == (uint64_t) fmt) { return skinny2pbx_codec_maps[i].skinny_codec; } } return 0; } /*! * \brief Convert a skinny_codec (enum) to an ast_codec (fmt) * * \param codec Skinny Codec (enum) * * \return fmt Format as ast_format_type */ ast_format_type skinny_codec2pbx_codec(skinny_codec_t codec) { uint32_t i; for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].skinny_codec == codec) { return skinny2pbx_codec_maps[i].pbx_codec; } } return 0; } /*! * \brief Convert an array of skinny_codecs (enum) to a bit array of ast_codecs (fmt) * * \param skinny_codecs Array of Skinny Codecs * * \return bit array fmt/Format of ast_format_type (int) * * \todo check bitwise operator (not sure) - DdG */ int skinny_codecs2pbx_codecs(skinny_codec_t * skinny_codecs) { uint32_t i; int res_codec = 0; for (i = 1; i < SKINNY_MAX_CAPABILITIES; i++) { res_codec |= skinny_codec2pbx_codec(skinny_codecs[i]); } return res_codec; } #if DEBUG /*! * \brief Retrieve the SCCP Channel from an Asterisk Channel * * \param pbx_channel PBX Channel * \param filename Debug Filename * \param lineno Debug Line Number * \param func Debug Function Name * \return SCCP Channel on Success or Null on Fail * * \todo this code is not pbx independent */ sccp_channel_t *__get_sccp_channel_from_pbx_channel(const PBX_CHANNEL_TYPE * pbx_channel, const char *filename, int lineno, const char *func) #else /*! * \brief Retrieve the SCCP Channel from an Asterisk Channel * * \param pbx_channel PBX Channel * \return SCCP Channel on Success or Null on Fail * * \todo this code is not pbx independent */ sccp_channel_t *get_sccp_channel_from_pbx_channel(const PBX_CHANNEL_TYPE * pbx_channel) #endif { sccp_channel_t *c = NULL; if (pbx_channel && CS_AST_CHANNEL_PVT(pbx_channel) && CS_AST_CHANNEL_PVT_CMP_TYPE(pbx_channel, "SCCP")) { if ((c = CS_AST_CHANNEL_PVT(pbx_channel))) { #if DEBUG return sccp_refcount_retain(c, filename, lineno, func); #else return sccp_channel_retain(c); #endif } else { pbx_log(LOG_ERROR, "Channel is not a valid SCCP Channel\n"); return NULL; } } else { return NULL; } } int sccp_wrapper_asterisk_forceHangup(PBX_CHANNEL_TYPE * ast_channel, pbx_hangup_type_t pbx_hangup_type) { int tries = 0; if (!ast_channel) { pbx_log(LOG_NOTICE, "no channel to hangup provided. exiting hangup\n"); return FALSE; } if (pbx_test_flag(pbx_channel_flags(ast_channel), AST_FLAG_ZOMBIE)) { pbx_log(LOG_NOTICE, "%s: channel is a zombie. exiting hangup\n", pbx_channel_name(ast_channel) ? pbx_channel_name(ast_channel) : "--"); return FALSE; } if (pbx_test_flag(pbx_channel_flags(ast_channel), AST_FLAG_BLOCKING)) { // wait for blocker before issuing softhangup while (!pbx_channel_blocker(ast_channel) && tries < 50) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (requestHangup) Blocker set but no blocker found yet, waiting...!\n"); usleep(50); tries++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send ast_softhangup_nolock (blocker: %s)\n", pbx_channel_name(ast_channel), pbx_channel_blockproc(ast_channel)); ast_softhangup_nolock(ast_channel, AST_SOFTHANGUP_DEV); return TRUE; } if (pbx_channel_softhangup(ast_channel) != 0) { if (AST_STATE_DOWN == pbx_channel_state(ast_channel)) { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: channel is already being hungup. exiting hangup\n", pbx_channel_name(ast_channel)); return FALSE; } else { sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: channel is already being hungup. forcing queued_hangup.\n", pbx_channel_name(ast_channel)); pbx_hangup_type = PBX_QUEUED_HANGUP; pbx_log(LOG_NOTICE, "set to PBX_QUEUED_HANGUP\n"); } } /* check for briged pbx_channel */ PBX_CHANNEL_TYPE *pbx_bridged_channel = NULL; if ((pbx_bridged_channel = CS_AST_BRIDGED_CHANNEL(ast_channel))) { if (pbx_channel_softhangup(pbx_bridged_channel) != 0) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: bridge peer: %s is already hanging up. exiting hangup.\n", pbx_channel_name(ast_channel), pbx_channel_name(pbx_bridged_channel)); return FALSE; } } switch (pbx_hangup_type) { case PBX_HARD_HANGUP: sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send hard ast_hangup\n", pbx_channel_name(ast_channel)); ast_indicate(ast_channel, -1); ast_hangup(ast_channel); break; case PBX_SOFT_HANGUP: // wait for blocker before issuing softhangup while (!pbx_channel_blocker(ast_channel) && tries < 50) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (requestHangup) Blocker set but no blocker found yet, waiting...!\n"); usleep(50); tries++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send ast_softhangup_nolock (blocker: %s)\n", pbx_channel_name(ast_channel), pbx_channel_blockproc(ast_channel)); ast_softhangup_nolock(ast_channel, AST_SOFTHANGUP_DEV); break; case PBX_QUEUED_HANGUP: sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send ast_queue_hangup\n", pbx_channel_name(ast_channel)); #if ASTERISK_VERSION_NUMBER < 10601 pbx_channel_setwhentohangup_tv(ast_channel, 0); #else pbx_channel_setwhentohangup_tv(ast_channel, ast_tvnow()); #endif // ast_channel->_state=AST_STATE_DOWN; ast_queue_hangup(ast_channel); break; } return TRUE; } int sccp_wrapper_asterisk_requestHangup(PBX_CHANNEL_TYPE * ast_channel) { if (!ast_channel) { pbx_log(LOG_NOTICE, "channel to hangup is NULL\n"); return FALSE; } if ((pbx_channel_softhangup(ast_channel) & AST_SOFTHANGUP_APPUNLOAD) != 0) { pbx_channel_set_hangupcause(ast_channel, AST_CAUSE_CHANNEL_UNACCEPTABLE); ast_softhangup(ast_channel, AST_SOFTHANGUP_APPUNLOAD); sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_3 "%s: send softhangup appunload\n", pbx_channel_name(ast_channel)); return TRUE; } sccp_channel_t *sccp_channel = get_sccp_channel_from_pbx_channel(ast_channel); sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "hangup %s: hasPbx %s; ast state: %s, sccp state: %s, blocking: %s, already being hungup: %s, hangupcause: %d\n", pbx_channel_name(ast_channel), pbx_channel_pbx(ast_channel) ? "yes" : "no", pbx_state2str(pbx_channel_state(ast_channel)), sccp_channel ? sccp_indicate2str(sccp_channel->state) : "--", pbx_test_flag(pbx_channel_flags(ast_channel), AST_FLAG_BLOCKING) ? "yes" : "no", pbx_channel_softhangup(ast_channel) ? "yes" : "no", pbx_channel_hangupcause(ast_channel) ); if (pbx_test_flag(pbx_channel_flags(ast_channel), AST_FLAG_BLOCKING)) { // wait for blocker before issuing softhangup int tries = 0; while (!pbx_channel_blocker(ast_channel) && tries < 50) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: (requestHangup) Blocker set but no blocker found yet, waiting...!\n"); usleep(50); tries++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send ast_softhangup_nolock (blocker: %s)\n", pbx_channel_name(ast_channel), pbx_channel_blockproc(ast_channel)); ast_softhangup_nolock(ast_channel, AST_SOFTHANGUP_DEV); } else if (AST_STATE_UP == pbx_channel_state(ast_channel) || pbx_channel_pbx(ast_channel)) { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send ast_queue_hangup\n", pbx_channel_name(ast_channel)); #if ASTERISK_VERSION_NUMBER < 10601 pbx_channel_setwhentohangup_tv(ast_channel, 0); #else pbx_channel_setwhentohangup_tv(ast_channel, ast_tvnow()); #endif ast_queue_hangup(ast_channel); } else { sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "%s: send hard ast_hangup\n", pbx_channel_name(ast_channel)); ast_hangup(ast_channel); // ast_queue_hangup(ast_channel); } sccp_channel = sccp_channel ? sccp_channel_release(sccp_channel) : NULL; return TRUE; } int sccp_asterisk_pbx_fktChannelWrite(PBX_CHANNEL_TYPE * ast, const char *funcname, char *args, const char *value) { sccp_channel_t *c; boolean_t res = TRUE; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { pbx_log(LOG_ERROR, "This function requires a valid SCCP channel\n"); return -1; } else { if (!strcasecmp(args, "MaxCallBR")) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: set max call bitrate to %s\n", (char *) c->currentDeviceId, value); if (sscanf(value, "%ud", &c->maxBitRate)) { pbx_builtin_setvar_helper(ast, "_MaxCallBR", value); res = TRUE; } else { res = FALSE; } } else if (!strcasecmp(args, "codec")) { res = sccp_channel_setPreferredCodec(c, value); } else if (!strcasecmp(args, "microphone")) { if (!value || sccp_strlen_zero(value) || !sccp_true(value)) { c->setMicrophone(c, FALSE); } else { c->setMicrophone(c, TRUE); } } else { res = FALSE; } c = sccp_channel_release(c); } return res ? 0 : -1; } /***** database *****/ boolean_t sccp_asterisk_addToDatabase(const char *family, const char *key, const char *value) { int res; if (sccp_strlen_zero(family) || sccp_strlen_zero(key) || sccp_strlen_zero(value)) return FALSE; res = ast_db_put(family, key, value); return (!res) ? TRUE : FALSE; } boolean_t sccp_asterisk_getFromDatabase(const char *family, const char *key, char *out, int outlen) { int res; if (sccp_strlen_zero(family) || sccp_strlen_zero(key)) return FALSE; res = ast_db_get(family, key, out, outlen); return (!res) ? TRUE : FALSE; } boolean_t sccp_asterisk_removeFromDatabase(const char *family, const char *key) { int res; if (sccp_strlen_zero(family) || sccp_strlen_zero(key)) return FALSE; res = ast_db_del(family, key); return (!res) ? TRUE : FALSE; } boolean_t sccp_asterisk_removeTreeFromDatabase(const char *family, const char *key) { int res; if (sccp_strlen_zero(family) || sccp_strlen_zero(key)) return FALSE; res = ast_db_deltree(family, key); return (!res) ? TRUE : FALSE; } /* end - database */ /*! * \brief Turn on music on hold on a given channel * \note replacement for ast_moh_start * * \param pbx_channel The channel structure that will get music on hold * \param mclass The class to use if the musicclass is not currently set on * the channel structure. * \param interpclass The class to use if the musicclass is not currently set on * the channel structure or in the mclass argument. * * \retval Zero on success * \retval non-zero on failure */ int sccp_asterisk_moh_start(PBX_CHANNEL_TYPE * pbx_channel, const char *mclass, const char *interpclass) { if (!ast_test_flag(pbx_channel_flags(pbx_channel), AST_FLAG_MOH)) { pbx_set_flag(pbx_channel_flags(pbx_channel), AST_FLAG_MOH); return ast_moh_start((PBX_CHANNEL_TYPE *) pbx_channel, mclass, interpclass); } else { return 0; } } void sccp_asterisk_moh_stop(PBX_CHANNEL_TYPE * pbx_channel) { if (ast_test_flag(pbx_channel_flags(pbx_channel), AST_FLAG_MOH)) { pbx_clear_flag(pbx_channel_flags(pbx_channel), AST_FLAG_MOH); ast_moh_stop((PBX_CHANNEL_TYPE *) pbx_channel); } } void sccp_asterisk_redirectedUpdate(sccp_channel_t * channel, const void *data, size_t datalen) { PBX_CHANNEL_TYPE *ast = channel->owner; #if ASTERISK_VERSION_GROUP >106 struct ast_party_id redirecting_from = pbx_channel_redirecting_effective_from(ast); struct ast_party_id redirecting_to = pbx_channel_redirecting_effective_to(ast); sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: Got redirecting update. From %s<%s>; To %s<%s>\n", pbx_channel_name(ast), (redirecting_from.name.valid && redirecting_from.name.str) ? redirecting_from.name.str : "", (redirecting_from.number.valid && redirecting_from.number.str) ? redirecting_from.number.str : "", (redirecting_to.name.valid && redirecting_to.name.str) ? redirecting_to.name.str : "", (redirecting_to.number.valid && redirecting_to.number.str) ? redirecting_to.number.str : ""); if (redirecting_from.name.valid && redirecting_from.name.str) { sccp_copy_string(channel->callInfo.lastRedirectingPartyName, redirecting_from.name.str, sizeof(channel->callInfo.callingPartyName)); } sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, (redirecting_from.number.valid && redirecting_from.number.str) ? redirecting_from.number.str : "", sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; #else sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, ast->cid.cid_rdnis ? ast->cid.cid_rdnis : "", sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; #endif sccp_channel_send_callinfo2(channel); } void sccp_asterisk_sendRedirectedUpdate(const sccp_channel_t * channel, const char *fromNumber, const char *fromName, const char *toNumber, const char *toName, uint8_t reason) { #if ASTERISK_VERSION_GROUP >106 struct ast_party_redirecting redirecting; struct ast_set_party_redirecting update_redirecting; ast_party_redirecting_init(&redirecting); memset(&update_redirecting, 0, sizeof(update_redirecting)); /* update redirecting info line for source part */ if (fromNumber) { update_redirecting.from.number = 1; redirecting.from.number.valid = 1; redirecting.from.number.str = strdupa(fromNumber); } if (fromName) { update_redirecting.from.name = 1; redirecting.from.name.valid = 1; redirecting.from.name.str = strdupa(fromName); } if (toNumber) { update_redirecting.to.number = 1; redirecting.to.number.valid = 1; redirecting.to.number.str = strdupa(toNumber); } if (toName) { update_redirecting.to.name = 1; redirecting.to.name.valid = 1; redirecting.to.name.str = strdupa(toName); } ast_channel_queue_redirecting_update(channel->owner, &redirecting, &update_redirecting); #else // set redirecting party (forwarder) if (fromNumber) { if (channel->owner->cid.cid_rdnis) { ast_free(channel->owner->cid.cid_rdnis); } channel->owner->cid.cid_rdnis = ast_strdup(fromNumber); } // where is the call going to now if (toNumber) { if (channel->owner->cid.cid_dnid) { ast_free(channel->owner->cid.cid_dnid); } channel->owner->cid.cid_dnid = ast_strdup(toNumber); } #endif } /*! * \brief ACF Channel Read callback * * \param ast Asterisk Channel * \param funcname functionname as const char * * \param args arguments as char * * \param buf buffer as char * * \param buflen bufferlenght as size_t * \return result as int * * \called_from_asterisk * * \test ACF Channel Read Needs to be tested */ int sccp_wrapper_asterisk_channel_read(PBX_CHANNEL_TYPE * ast, NEWCONST char *funcname, char *args, char *buf, size_t buflen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int res = 0; if (!ast || !CS_AST_CHANNEL_PVT_IS_SCCP(ast)) { pbx_log(LOG_ERROR, "This function requires a valid SCCP channel\n"); return -1; } if ((c = get_sccp_channel_from_pbx_channel(ast))) { if ((d = sccp_channel_getDevice_retained(c))) { if (!strcasecmp(args, "peerip")) { ast_copy_string(buf, pbx_inet_ntoa(d->session->sin.sin_addr), buflen); } else if (!strcasecmp(args, "recvip")) { ast_copy_string(buf, pbx_inet_ntoa(d->session->phone_sin.sin_addr), buflen); } else if (!strcasecmp(args, "useragent")) { sccp_copy_string(buf, devicetype2str(d->skinny_type), buflen); } else if (!strcasecmp(args, "from")) { sccp_copy_string(buf, (char *) d->id, buflen); } else { res = -1; } d = sccp_device_release(d); } else { res = -1; } c = sccp_channel_release(c); } else { res = -1; } return res; } boolean_t sccp_wrapper_asterisk_featureMonitor(const sccp_channel_t * channel) { struct ast_call_feature *feature = ast_find_call_feature("automon"); if (feature) { feature->operation(channel->owner, channel->owner, NULL, "*1", 0, NULL); return TRUE; } return FALSE; } // kate: indent-width 4; replace-tabs off; indent-mode cstyle; auto-insert-doxygen on; line-numbers on; tab-indents on; keep-extra-spaces off;
722,275
./chan-sccp-b/src/pbx_impl/ast/astTrunk.c
/*! * \file astTrunk.c * \brief SCCP PBX Asterisk Wrapper Class * \author Marcello Ceshia * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #include <config.h> #include "../../common.h" #include "astTrunk.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include <asterisk/sched.h> #include <asterisk/netsock2.h> #include <asterisk/cel.h> #define new avoid_cxx_new_keyword #include <asterisk/rtp_engine.h> #undef new #if defined(__cplusplus) || defined(c_plusplus) } #endif struct ast_sched_context *sched = 0; struct io_context *io = 0; struct ast_format slinFormat = { AST_FORMAT_SLINEAR, {{0}, 0} }; static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_request(const char *type, struct ast_format_cap *format, const PBX_CHANNEL_TYPE * requestor, const char *dest, int *cause); static int sccp_wrapper_asterisk111_call(PBX_CHANNEL_TYPE * chan, const char *addr, int timeout); static int sccp_wrapper_asterisk111_answer(PBX_CHANNEL_TYPE * chan); static PBX_FRAME_TYPE *sccp_wrapper_asterisk111_rtp_read(PBX_CHANNEL_TYPE * ast); static int sccp_wrapper_asterisk111_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame); static int sccp_wrapper_asterisk111_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen); static int sccp_wrapper_asterisk111_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan); #ifdef CS_AST_RTP_INSTANCE_BRIDGE static enum ast_bridge_result sccp_wrapper_asterisk111_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms); #endif static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text); static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit); static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration); static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen); int sccp_wrapper_asterisk111_hangup(PBX_CHANNEL_TYPE * ast_channel); boolean_t sccp_wrapper_asterisk111_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId); int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control); int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen); static int sccp_wrapper_asterisk111_devicestate(const char *data); static boolean_t sccp_wrapper_asterisk111_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec); static boolean_t sccp_wrapper_asterisk111_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context); static inline skinny_codec_t sccp_asterisk11_getSkinnyFormatSingle(struct ast_format_cap *ast_format_capability) { struct ast_format tmp_fmt; uint8_t i; skinny_codec_t codec = SKINNY_CODEC_NONE; ast_format_cap_iter_start(ast_format_capability); while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt)) { for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == tmp_fmt.id) { codec = skinny2pbx_codec_maps[i].skinny_codec; break; } } if (codec != SKINNY_CODEC_NONE) { break; } } ast_format_cap_iter_end(ast_format_capability); return codec; } static uint8_t sccp_asterisk11_getSkinnyFormatMultiple(struct ast_format_cap *ast_format_capability, skinny_codec_t codec[], int length) { struct ast_format tmp_fmt; uint8_t i; uint8_t position = 0; ast_format_cap_iter_start(ast_format_capability); while (!ast_format_cap_iter_next(ast_format_capability, &tmp_fmt) && position < length) { for (i = 1; i < ARRAY_LEN(skinny2pbx_codec_maps); i++) { if (skinny2pbx_codec_maps[i].pbx_codec == tmp_fmt.id) { codec[position++] = skinny2pbx_codec_maps[i].skinny_codec; break; } } } ast_format_cap_iter_end(ast_format_capability); return position; } #if defined(__cplusplus) || defined(c_plusplus) /*! * \brief SCCP Tech Structure */ static struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, description: "Skinny Client Control Protocol (SCCP)", // capabilities: AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_SLINEAR16 | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A | AST_FORMAT_H264 | AST_FORMAT_H263_PLUS, properties: AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, requester: sccp_wrapper_asterisk111_request, devicestate: sccp_wrapper_asterisk111_devicestate, send_digit_begin: sccp_wrapper_recvdigit_begin, send_digit_end: sccp_wrapper_recvdigit_end, call: sccp_wrapper_asterisk111_call, hangup: sccp_wrapper_asterisk111_hangup, answer: sccp_wrapper_asterisk111_answer, read: sccp_wrapper_asterisk111_rtp_read, write: sccp_wrapper_asterisk111_rtp_write, send_text: sccp_pbx_sendtext, send_image: NULL, send_html: sccp_pbx_sendHTML, exception: NULL, bridge: sccp_wrapper_asterisk111_rtpBridge, early_bridge: NULL, indicate: sccp_wrapper_asterisk111_indicate, fixup: sccp_wrapper_asterisk111_fixup, setoption: NULL, queryoption: NULL, transfer: NULL, write_video: sccp_wrapper_asterisk111_rtp_write, write_text: NULL, bridged_channel: NULL, func_channel_read: sccp_wrapper_asterisk_channel_read, func_channel_write: sccp_asterisk_pbx_fktChannelWrite, get_base_channel: NULL, set_base_channel: NULL, /* *INDENT-ON* */ }; #else /*! * \brief SCCP Tech Structure */ struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .description = "Skinny Client Control Protocol (SCCP)", // we could use the skinny_codec = ast_codec mapping here to generate the list of capabilities // .capabilities = AST_FORMAT_SLINEAR16 | AST_FORMAT_SLINEAR | AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A, .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, .requester = sccp_wrapper_asterisk111_request, .devicestate = sccp_wrapper_asterisk111_devicestate, .call = sccp_wrapper_asterisk111_call, .hangup = sccp_wrapper_asterisk111_hangup, .answer = sccp_wrapper_asterisk111_answer, .read = sccp_wrapper_asterisk111_rtp_read, .write = sccp_wrapper_asterisk111_rtp_write, .write_video = sccp_wrapper_asterisk111_rtp_write, .indicate = sccp_wrapper_asterisk111_indicate, .fixup = sccp_wrapper_asterisk111_fixup, .transfer = sccp_pbx_transfer, #ifdef CS_AST_RTP_INSTANCE_BRIDGE .bridge = sccp_wrapper_asterisk111_rtpBridge, #endif //.early_bridge = ast_rtp_early_bridge, //.bridged_channel = .send_text = sccp_pbx_sendtext, .send_html = sccp_pbx_sendHTML, //.send_image = .func_channel_read = sccp_wrapper_asterisk_channel_read, .func_channel_write = sccp_asterisk_pbx_fktChannelWrite, .send_digit_begin = sccp_wrapper_recvdigit_begin, .send_digit_end = sccp_wrapper_recvdigit_end, //.write_text = //.write_video = //.cc_callback = // ccss, new >1.6.0 //.exception = // new >1.6.0 //.setoption = sccp_wrapper_asterisk111_setOption, //.queryoption = // new >1.6.0 //.get_pvt_uniqueid = sccp_pbx_get_callid, // new >1.6.0 //.get_base_channel = //.set_base_channel = /* *INDENT-ON* */ }; #endif static int sccp_wrapper_asterisk111_devicestate(const char *data) { int res = AST_DEVICE_UNKNOWN; char *lineName = (char *) data; char *deviceId = NULL; sccp_channelstate_t state; if ((deviceId = strchr(lineName, '@'))) { *deviceId = '\0'; deviceId++; } state = sccp_hint_getLinestate(lineName, deviceId); switch (state) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: res = AST_DEVICE_NOT_INUSE; break; case SCCP_CHANNELSTATE_RINGING: res = AST_DEVICE_RINGING; break; case SCCP_CHANNELSTATE_HOLD: res = AST_DEVICE_ONHOLD; break; case SCCP_CHANNELSTATE_INVALIDNUMBER: res = AST_DEVICE_INVALID; break; case SCCP_CHANNELSTATE_BUSY: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_DND: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: res = AST_DEVICE_UNAVAILABLE; break; case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_PROGRESS: case SCCP_CHANNELSTATE_CALLWAITING: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: res = AST_DEVICE_INUSE; break; } sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: (sccp_asterisk_devicestate) PBX requests state for '%s' - state %s\n", (char *) lineName, ast_devstate2str(res)); return res; } /*! * \brief Convert an array of skinny_codecs (enum) to ast_codec_prefs * * \param skinny_codecs Array of Skinny Codecs * \param astCodecPref Array of PBX Codec Preferences * * \return bit array fmt/Format of ast_format_type (int) * * \todo check bitwise operator (not sure) - DdG */ int skinny_codecs2pbx_codec_pref(skinny_codec_t * skinny_codecs, struct ast_codec_pref *astCodecPref) { struct ast_format dst; uint32_t codec = skinny_codecs2pbx_codecs(skinny_codecs); // convert to bitfield ast_format_from_old_bitfield(&dst, codec); return ast_codec_pref_append(astCodecPref, &dst); // return ast_codec_pref } static boolean_t sccp_wrapper_asterisk111_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); #define RTP_NEW_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_new_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } #define RTP_CHANGE_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_change_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } // static void get_skinnyFormats(struct ast_format_cap *format, skinny_codec_t codecs[], size_t size) // { // unsigned int x; // unsigned len = 0; // // size_t f_len; // struct ast_format tmp_fmt; // const struct ast_format_list *f_list = ast_format_list_get(&f_len); // // if (!size) { // f_list = ast_format_list_destroy(f_list); // return; // } // // for (x = 0; x < ARRAY_LEN(skinny2pbx_codec_maps) && len <= size; x++) { // ast_format_copy(&tmp_fmt, &f_list[x].format); // if (ast_format_cap_iscompatible(format, &tmp_fmt)) { // if (skinny2pbx_codec_maps[x].pbx_codec == ((uint) tmp_fmt.id)) { // codecs[len++] = skinny2pbx_codec_maps[x].skinny_codec; // } // } // } // f_list = ast_format_list_destroy(f_list); // } /*************************************************************************************************************** CODEC **/ /*! \brief Get the name of a format * \note replacement for ast_getformatname * \param format id of format * \return A static string containing the name of the format or "unknown" if unknown. */ const char *pbx_getformatname(const struct ast_format *format) { return ast_getformatname(format); } /*! * \brief Get the names of a set of formats * \note replacement for ast_getformatname_multiple * \param buf a buffer for the output string * \param size size of buf (bytes) * \param format the format (combined IDs of codecs) * Prints a list of readable codec names corresponding to "format". * ex: for format=AST_FORMAT_GSM|AST_FORMAT_SPEEX|AST_FORMAT_ILBC it will return "0x602 (GSM|SPEEX|ILBC)" * \return The return value is buf. */ char *pbx_getformatname_multiple(char *buf, size_t size, struct ast_format_cap *format) { return ast_getformatname_multiple(buf, size, format); } /*! * \brief Read from an Asterisk Channel * \param ast Asterisk Channel as ast_channel * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static PBX_FRAME_TYPE *sccp_wrapper_asterisk111_rtp_read(PBX_CHANNEL_TYPE * ast) { sccp_channel_t *c = NULL; PBX_FRAME_TYPE *frame = &ast_null_frame; if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained pbx_log(LOG_ERROR, "SCCP: (rtp_read) no channel pvt\n"); goto EXIT_FUNC; } if (!c->rtp.audio.rtp) { pbx_log(LOG_NOTICE, "SCCP: (rtp_read) no rtp stream yet. skip\n"); goto EXIT_FUNC; } switch (ast_channel_fdno(ast)) { case 0: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 0); /* RTP Audio */ break; case 1: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 1); /* RTCP Control Channel */ break; #ifdef CS_SCCP_VIDEO case 2: frame = ast_rtp_instance_read(c->rtp.video.rtp, 0); /* RTP Video */ break; case 3: frame = ast_rtp_instance_read(c->rtp.video.rtp, 1); /* RTCP Control Channel for video */ break; #endif default: break; } //sccp_log((DEBUGCAT_CORE))(VERBOSE_PREFIX_3 "%s: read format: ast->fdno: %d, frametype: %d, %s(%d)\n", DEV_ID_LOG(c->device), ast_channel_fdno(ast), frame->frametype, pbx_getformatname(frame->subclass), frame->subclass); if (frame->frametype == AST_FRAME_VOICE) { #ifdef CS_SCCP_CONFERENCE if (c->conference && (!ast_format_is_slinear(ast_channel_readformat(ast)))) { ast_set_read_format(ast, &slinFormat); } #endif } EXIT_FUNC: return frame; } /*! * \brief Find Asterisk/PBX channel by linkid * * \param ast pbx channel * \param data linkId as void * * * \return int * * \todo I don't understand what this functions returns */ static int pbx_find_channel_by_linkid(PBX_CHANNEL_TYPE * ast, const void *data) { const char *linkedId = (char *) data; if (!linkedId) { return 0; } return !pbx_channel_pbx(ast) && ast_channel_linkedid(ast) && (!strcasecmp(ast_channel_linkedid(ast), linkedId)) && !pbx_channel_masq(ast); } /*! * \brief Update Connected Line * \param channel Asterisk Channel as ast_channel * \param data Asterisk Data * \param datalen Asterisk Data Length */ static void sccp_wrapper_asterisk111_connectedline(sccp_channel_t * channel, const void *data, size_t datalen) { PBX_CHANNEL_TYPE *ast = channel->owner; sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: Got connected line update, connected.id.number=%s, connected.id.name=%s, reason=%d\n", pbx_channel_name(ast), ast_channel_connected(ast)->id.number.str ? ast_channel_connected(ast)->id.number.str : "(nil)", ast_channel_connected(ast)->id.name.str ? ast_channel_connected(ast)->id.name.str : "(nil)", ast_channel_connected(ast)->source); // sccp_channel_display_callInfo(channel); /* set the original calling/called party if the reason is a transfer */ if (ast_channel_connected(ast)->source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER || ast_channel_connected(ast)->source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING) { if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Destination\n"); if (ast_channel_connected(ast)->id.number.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.number.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, ast_channel_connected(ast)->id.number.str, sizeof(channel->callInfo.originalCallingPartyNumber)); channel->callInfo.originalCallingParty_valid = 1; } if (ast_channel_connected(ast)->id.name.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.name.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyName, ast_channel_connected(ast)->id.name.str, sizeof(channel->callInfo.originalCallingPartyName)); } if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.callingPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } else { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Transferee\n"); if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyNumber)); sccp_copy_string(channel->callInfo.originalCallingPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyName)); channel->callInfo.originalCallingParty_valid = 1; } if (channel->callInfo.calledParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.calledPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } channel->callInfo.originalCdpnRedirectReason = channel->callInfo.lastRedirectingReason; channel->callInfo.lastRedirectingReason = 0; // need to figure out these codes } if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { if (ast_channel_connected(ast)->id.number.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.number.str)) { sccp_copy_string(channel->callInfo.callingPartyNumber, ast_channel_connected(ast)->id.number.str, sizeof(channel->callInfo.callingPartyNumber)); channel->callInfo.callingParty_valid = 1; } if (ast_channel_connected(ast)->id.name.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.name.str)) { sccp_copy_string(channel->callInfo.callingPartyName, ast_channel_connected(ast)->id.name.str, sizeof(channel->callInfo.callingPartyName)); } } else { if (ast_channel_connected(ast)->id.number.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.number.str)) { sccp_copy_string(channel->callInfo.calledPartyNumber, ast_channel_connected(ast)->id.number.str, sizeof(channel->callInfo.calledPartyNumber)); channel->callInfo.callingParty_valid = 1; } if (ast_channel_connected(ast)->id.name.str && !sccp_strlen_zero(ast_channel_connected(ast)->id.name.str)) { sccp_copy_string(channel->callInfo.calledPartyName, ast_channel_connected(ast)->id.name.str, sizeof(channel->callInfo.calledPartyName)); } } sccp_channel_display_callInfo(channel); sccp_channel_send_callinfo2(channel); } static int sccp_wrapper_asterisk111_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { switch (ind) { case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk111_connectedline(c, data, datalen); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); res = 0; break; default: res = -1; break; } c = sccp_channel_release(c); return res; } if (c->state == SCCP_CHANNELSTATE_DOWN) { c = sccp_channel_release(c); d = d ? sccp_device_release(d) : NULL; return -1; } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Asterisk indicate '%d' condition on channel %s\n", DEV_ID_LOG(d), ind, pbx_channel_name(ast)); /* when the rtp media stream is open we will let asterisk emulate the tones */ res = (((c->rtp.audio.readState != SCCP_RTP_STATUS_INACTIVE) || (d && d->earlyrtp)) ? -1 : 0); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: readStat: %d\n", DEV_ID_LOG(d), c->rtp.audio.readState); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: res: %d\n", DEV_ID_LOG(d), res); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: rtp?: %s\n", DEV_ID_LOG(d), (c->rtp.audio.rtp) ? "yes" : "no"); switch (ind) { case AST_CONTROL_RINGING: if (SKINNY_CALLTYPE_OUTBOUND == c->calltype) { // Allow signalling of RINGOUT only on outbound calls. // Otherwise, there are some issues with late arrival of ringing // indications on ISDN calls (chan_lcr, chan_dahdi) (-DD). sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGOUT); struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; /*! \todo handle multiple remotePeers i.e. DIAL(SCCP/400&SIP/300), find smallest common codecs, what order to use ? */ PBX_CHANNEL_TYPE *remotePeer; for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { if (pbx_find_channel_by_linkid(remotePeer, (void *) ast_channel_linkedid(ast))) { char buf[512]; sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(remotePeer); if (remoteSccpChannel) { sccp_multiple_codecs2str(buf, sizeof(buf) - 1, remoteSccpChannel->preferences.audio, ARRAY_LEN(remoteSccpChannel->preferences.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote preferences: %s\n", buf); uint8_t x, y, z; z = 0; for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { c->remoteCapabilities.audio[z++] = remoteSccpChannel->preferences.audio[x]; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote nativeformats: %s\n", pbx_getformatname_multiple(buf, sizeof(buf) - 1, ast_channel_nativeformats(remotePeer))); sccp_asterisk11_getSkinnyFormatMultiple(ast_channel_nativeformats(remotePeer), c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); } sccp_multiple_codecs2str(buf, sizeof(buf) - 1, c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote caps: %s\n", buf); ast_channel_unref(remotePeer); break; } } ast_channel_iterator_destroy(iterator); } break; case AST_CONTROL_BUSY: sccp_indicate(d, c, SCCP_CHANNELSTATE_BUSY); break; case AST_CONTROL_CONGESTION: sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); break; case AST_CONTROL_PROGRESS: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROGRESS); res = -1; break; case AST_CONTROL_PROCEEDING: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROCEED); res = -1; break; case AST_CONTROL_SRCCHANGE: if (c->rtp.audio.rtp) ast_rtp_instance_change_source(c->rtp.audio.rtp); res = 0; break; case AST_CONTROL_SRCUPDATE: /* Source media has changed. */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Source UPDATE request\n"); if (c->rtp.audio.rtp) { ast_rtp_instance_change_source(c->rtp.audio.rtp); } res = 0; break; /* when the bridged channel hold/unhold the call we are notified here */ case AST_CONTROL_HOLD: sccp_asterisk_moh_start(ast, (const char *) data, c->musicclass); res = 0; break; case AST_CONTROL_UNHOLD: sccp_asterisk_moh_stop(ast); if (c->rtp.audio.rtp) { ast_rtp_instance_update_source(c->rtp.audio.rtp); } res = 0; break; case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk111_connectedline(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ if (c->rtp.video.rtp && d && sccp_device_isVideoSupported(d)) { d->protocol->sendFastPictureUpdate(d, c); res = 0; } else res = -1; break; #ifdef CS_AST_CONTROL_INCOMPLETE case AST_CONTROL_INCOMPLETE: /*!< Indication that the extension dialed is incomplete */ /* \todo implement dial continuation by: * - display message incomplete number * - adding time to channel->scheduler.digittimeout * - rescheduling sccp_pbx_sched_dial */ #ifdef CS_EXPERIMENTAL if (c->scheduler.digittimeout) { SCCP_SCHED_DEL(c->scheduler.digittimeout); } sccp_indicate(d, c, SCCP_CHANNELSTATE_DIGITSFOLL); c->scheduler.digittimeout = PBX(sched_add) (c->enbloc.digittimeout, sccp_pbx_sched_dial, c); #endif res = 0; break; #endif case -1: // Asterisk prod the channel res = -1; break; case AST_CONTROL_PVT_CAUSE_CODE: res = -1; /* Tell asterisk to provide inband signalling */ default: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Don't know how to indicate condition %d\n", ind); res = -1; } //ast_cond_signal(&c->astStateCond); d = sccp_device_release(d); c = sccp_channel_release(c); sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP (pbx_indicate): send asterisk result %d\n", res); return res; } /*! * \brief Write to an Asterisk Channel * \param ast Channel as ast_channel * \param frame Frame as ast_frame * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static int sccp_wrapper_asterisk111_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame) { sccp_channel_t *c = NULL; #ifdef CS_SCCP_VIDEO sccp_device_t *device; #endif int res = 0; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) { // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return -1; } switch (frame->frametype) { case AST_FRAME_VOICE: // checking for samples to transmit if (!frame->samples) { if (strcasecmp(frame->src, "ast_prod")) { pbx_log(LOG_ERROR, "%s: Asked to transmit frame type %d with no samples.\n", c->currentDeviceId, (int) frame->frametype); } else { // frame->samples == 0 when frame_src is ast_prod sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Asterisk prodded channel %s.\n", c->currentDeviceId, pbx_channel_name(ast)); } } if (c->rtp.audio.rtp) { res = ast_rtp_instance_write(c->rtp.audio.rtp, frame); } break; case AST_FRAME_IMAGE: case AST_FRAME_VIDEO: #ifdef CS_SCCP_VIDEO #if DEBUG device = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__); #else device = c->getDevice_retained(c); #endif if (c->rtp.video.writeState == SCCP_RTP_STATUS_INACTIVE && c->rtp.video.rtp && device && c->state != SCCP_CHANNELSTATE_HOLD) { // int codec = pbx_codec2skinny_codec((frame->subclass.codec & AST_FORMAT_VIDEO_MASK)); int codec = pbx_codec2skinny_codec(frame->subclass.format.id); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: got video frame %d\n", c->currentDeviceId, codec); if (0 != codec) { c->rtp.video.writeFormat = codec; sccp_channel_openMultiMediaChannel(c); } } if (c->rtp.video.rtp && (c->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE) != 0) { res = ast_rtp_instance_write(c->rtp.video.rtp, frame); } device = device ? sccp_device_release(device) : NULL; #endif break; case AST_FRAME_TEXT: case AST_FRAME_MODEM: default: pbx_log(LOG_WARNING, "%s: Can't send %d type frames with SCCP write on channel %s\n", c->currentDeviceId, frame->frametype, pbx_channel_name(ast)); break; } // c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk111_sendDigits(const sccp_channel_t * channel, const char *digits) { if (!channel || !channel->owner) { pbx_log(LOG_WARNING, "No channel to send digits to\n"); return 0; } PBX_CHANNEL_TYPE *pbx_channel = channel->owner; int i; PBX_FRAME_TYPE f; f = ast_null_frame; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digits '%s'\n", (char *) channel->currentDeviceId, digits); // We don't just call sccp_pbx_senddigit due to potential overhead, and issues with locking f.src = "SCCP"; // CS_AST_NEW_FRAME_STRUCT // f.frametype = AST_FRAME_DTMF_BEGIN; // ast_queue_frame(pbx_channel, &f); for (i = 0; digits[i] != '\0'; i++) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digit %c\n", (char *) channel->currentDeviceId, digits[i]); f.frametype = AST_FRAME_DTMF_END; // Sending only the dmtf will force asterisk to start with DTMF_BEGIN and schedule the DTMF_END f.subclass.integer = digits[i]; // f.samples = SCCP_MIN_DTMF_DURATION * 8; f.len = SCCP_MIN_DTMF_DURATION; f.src = "SEND DIGIT"; ast_queue_frame(pbx_channel, &f); } return 1; } static int sccp_wrapper_asterisk111_sendDigit(const sccp_channel_t * channel, const char digit) { char digits[3] = "\0\0"; digits[0] = digit; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: got a single digit '%c' -> '%s'\n", channel->currentDeviceId, digit, digits); return sccp_wrapper_asterisk111_sendDigits(channel, digits); } static void sccp_wrapper_asterisk111_setCalleridPresence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (CALLERID_PRESENCE_FORBIDDEN == channel->callInfo.presentation) { ast_channel_caller(pbx_channel)->id.name.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; ast_channel_caller(pbx_channel)->id.number.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; } } static int sccp_wrapper_asterisk111_setNativeAudioFormats(const sccp_channel_t * channel, skinny_codec_t codec[], int length) { struct ast_format fmt; int i; #ifndef CS_EXPERIMENTAL_CODEC length = 1; //set only one codec #endif ast_debug(10, "%s: set native Formats length: %d\n", (char *) channel->currentDeviceId, length); ast_format_cap_remove_bytype(ast_channel_nativeformats(channel->owner), AST_FORMAT_TYPE_AUDIO); for (i = 0; i < length; i++) { ast_format_set(&fmt, skinny_codec2pbx_codec(codec[i]), 0); ast_format_cap_add(ast_channel_nativeformats(channel->owner), &fmt); } return 1; } static int sccp_wrapper_asterisk111_setNativeVideoFormats(const sccp_channel_t * channel, uint32_t formats) { return 1; } boolean_t sccp_wrapper_asterisk111_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId) { sccp_line_t *line = NULL; (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, linkedId, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); // (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, NULL, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); if ((*pbx_channel) == NULL) { return FALSE; } line = channel->line; ast_channel_tech_set((*pbx_channel), &sccp_tech); ast_channel_tech_pvt_set((*pbx_channel), sccp_channel_retain(channel)); ast_channel_context_set(*pbx_channel, line->context); ast_channel_exten_set(*pbx_channel, ""); if (!sccp_strlen_zero(line->language)) { ast_channel_language_set((*pbx_channel), line->language); } if (!sccp_strlen_zero(line->accountcode)) { ast_channel_accountcode_set((*pbx_channel), line->accountcode); } if (!sccp_strlen_zero(line->musicclass)) { ast_channel_musicclass_set((*pbx_channel), line->musicclass); } if (line->amaflags) { ast_channel_amaflags_set(*pbx_channel, line->amaflags); } if (line->callgroup) { ast_channel_callgroup_set(*pbx_channel, line->callgroup); } ast_channel_callgroup_set(*pbx_channel, line->callgroup); // needed for ast_pickup_call #if CS_SCCP_PICKUP if (line->pickupgroup) { ast_channel_pickupgroup_set(*pbx_channel, line->pickupgroup); } #endif ast_channel_priority_set((*pbx_channel), 1); ast_channel_adsicpe_set((*pbx_channel), AST_ADSI_UNAVAILABLE); /** the the tonezone using language information */ if (!sccp_strlen_zero(line->language) && ast_get_indication_zone(line->language)) { ast_channel_zone_set((*pbx_channel), ast_get_indication_zone(line->language)); /* this will core asterisk on hangup */ } ast_module_ref(ast_module_info->self); channel->owner = ast_channel_ref((*pbx_channel)); /* DdG: if we don't unref on hangup, we should not be taking the reference either. It will hinder module unload ? */ return TRUE; } static boolean_t sccp_wrapper_asterisk111_masqueradeHelper(PBX_CHANNEL_TYPE * pbxChannel, PBX_CHANNEL_TYPE * pbxTmpChannel) { pbx_moh_stop(pbxChannel); // Masquerade setup and execution must be done without any channel locks held if (pbx_channel_masquerade(pbxTmpChannel, pbxChannel)) { return FALSE; } //ast_channel_state_set(pbxTmpChannel, AST_STATE_UP); pbx_do_masquerade(pbxTmpChannel); // when returning from bridge, the channel will continue at the next priority // ast_explicit_goto(pbxTmpChannel, pbx_channel_context(pbxTmpChannel), pbx_channel_exten(pbxTmpChannel), pbx_channel_priority(pbxTmpChannel) + 1); return TRUE; } static boolean_t sccp_wrapper_asterisk111_allocTempPBXChannel(PBX_CHANNEL_TYPE * pbxSrcChannel, PBX_CHANNEL_TYPE ** pbxDstChannel) { struct ast_format tmpfmt; if (!pbxSrcChannel) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) no pbx channel provided\n"); return FALSE; } (*pbxDstChannel) = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(pbxSrcChannel), pbx_channel_exten(pbxSrcChannel), pbx_channel_context(pbxSrcChannel), ast_channel_linkedid(pbxSrcChannel), ast_channel_amaflags(pbxSrcChannel), "TMP/%s", ast_channel_name(pbxSrcChannel)); if ((*pbxDstChannel) == NULL) { pbx_log(LOG_ERROR, "SCCP: (alloc_conferenceTempPBXChannel) create pbx channel failed\n"); return FALSE; } ast_channel_lock(pbxSrcChannel); if (ast_format_cap_is_empty(pbx_channel_nativeformats(pbxSrcChannel))) { ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0); } else { ast_best_codec(pbx_channel_nativeformats(pbxSrcChannel), &tmpfmt); } ast_format_cap_add(ast_channel_nativeformats(*pbxDstChannel), &tmpfmt); ast_set_read_format((*pbxDstChannel), &tmpfmt); ast_set_write_format((*pbxDstChannel), &tmpfmt); ast_channel_context_set((*pbxDstChannel), ast_channel_context(pbxSrcChannel)); ast_channel_exten_set((*pbxDstChannel), ast_channel_exten(pbxSrcChannel)); ast_channel_priority_set((*pbxDstChannel), ast_channel_priority(pbxSrcChannel)); ast_channel_unlock(pbxSrcChannel); return TRUE; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_requestForeignChannel(const char *type, pbx_format_type format, const PBX_CHANNEL_TYPE * requestor, void *data) { PBX_CHANNEL_TYPE *chan; int cause; struct ast_format_cap *cap; struct ast_format tmpfmt; if (!(cap = ast_format_cap_alloc_nolock())) { return 0; } ast_format_cap_add(cap, ast_format_set(&tmpfmt, format, 0)); if (!(chan = ast_request(type, cap, NULL, "", &cause))) { pbx_log(LOG_ERROR, "SCCP: Requested channel could not be created, cause: %d\n", cause); cap = ast_format_cap_destroy(cap); return NULL; } cap = ast_format_cap_destroy(cap); return chan; } int sccp_wrapper_asterisk111_hangup(PBX_CHANNEL_TYPE * ast_channel) { sccp_channel_t *c; PBX_CHANNEL_TYPE *channel_owner = NULL; int res = -1; if ((c = get_sccp_channel_from_pbx_channel(ast_channel))) { channel_owner = c->owner; if (pbx_channel_hangupcause(ast_channel) == AST_CAUSE_ANSWERED_ELSEWHERE) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: This call was answered elsewhere\n"); c->answered_elsewhere = TRUE; } res = sccp_pbx_hangup(c); c->owner = NULL; if (0 == res) { sccp_channel_release(c); //this only releases the get_sccp_channel_from_pbx_channel } } //after this moment c might have gone already ast_channel_tech_pvt_set(ast_channel, NULL); c = c ? sccp_channel_release(c) : NULL; if (channel_owner) { channel_owner = ast_channel_unref(channel_owner); } ast_module_unref(ast_module_info->self); return res; } /*! * \brief Parking Thread Arguments Structure */ /*! * \brief Park the bridge channel of hostChannel * This function prepares the host and the bridged channel to be ready for parking. * It clones the pbx channel of both sides forward them to the park_thread * * \param hostChannel initial channel that request the parking * \todo we have a codec issue after unpark a call * \todo copy connected line info * */ static sccp_parkresult_t sccp_wrapper_asterisk111_park(const sccp_channel_t * hostChannel) { int extout; char extstr[20]; sccp_device_t *device; sccp_parkresult_t res = PARK_RESULT_FAIL; PBX_CHANNEL_TYPE *bridgedChannel = NULL; memset(extstr, 0, sizeof(extstr)); extstr[0] = 128; extstr[1] = SKINNY_LBL_CALL_PARK_AT; bridgedChannel = ast_bridged_channel(hostChannel->owner); device = sccp_channel_getDevice_retained(hostChannel); ast_channel_lock(hostChannel->owner); /* we have to lock our channel, otherwise asterisk crashes internally */ if (!ast_masq_park_call(bridgedChannel, hostChannel->owner, 0, &extout)) { sprintf(&extstr[2], " %d", extout); sccp_dev_displayprinotify(device, extstr, 1, 10); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Parked channel %s on %d\n", DEV_ID_LOG(device), ast_channel_name(bridgedChannel), extout); res = PARK_RESULT_SUCCESS; } ast_channel_unlock(hostChannel->owner); device = sccp_device_release(device); return res; } static boolean_t sccp_wrapper_asterisk111_getFeatureExtension(const sccp_channel_t * channel, char **extension) { struct ast_call_feature *feat; ast_rdlock_call_features(); feat = ast_find_call_feature("automon"); if (feat) { *extension = strdup(feat->exten); } ast_unlock_call_features(); return feat ? TRUE : FALSE; } /*! * \brief Pickup asterisk channel target using chan * * \param chan initial channel that request the parking * \param target Channel t park to * */ static boolean_t sccp_wrapper_asterisk111_pickupChannel(const sccp_channel_t * chan, PBX_CHANNEL_TYPE * target) { boolean_t result; PBX_CHANNEL_TYPE *ref; ref = ast_channel_ref(chan->owner); result = ast_do_pickup(chan->owner, target) ? FALSE : TRUE; if (result) { ((sccp_channel_t *) chan)->owner = ast_channel_ref(target); ast_hangup(ref); } ref = ast_channel_unref(chan->owner); return result; } static uint8_t sccp_wrapper_asterisk111_get_payloadType(const struct sccp_rtp *rtp, skinny_codec_t codec) { struct ast_format astCodec; int payload; ast_format_set(&astCodec, skinny_codec2pbx_codec(codec), 0); payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(rtp->rtp), 1, &astCodec, 0); return payload; } static int sccp_wrapper_asterisk111_get_sampleRate(skinny_codec_t codec) { struct ast_format astCodec; ast_format_set(&astCodec, skinny_codec2pbx_codec(codec), 0); return ast_rtp_lookup_sample_rate2(1, &astCodec, 0); } static sccp_extension_status_t sccp_wrapper_asterisk111_extensionStatus(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (!pbx_channel || !pbx_channel_context(pbx_channel)) { pbx_log(LOG_ERROR, "%s: (extension_status) Either no pbx_channel or no valid context provided to lookup number\n", channel->designator); return SCCP_EXTENSION_NOTEXISTS; } int ignore_pat = ast_ignore_pattern(pbx_channel_context(pbx_channel), channel->dialedNumber); int ext_exist = ast_exists_extension(pbx_channel, pbx_channel_context(pbx_channel), channel->dialedNumber, 1, channel->line->cid_num); int ext_canmatch = ast_canmatch_extension(pbx_channel, pbx_channel_context(pbx_channel), channel->dialedNumber, 1, channel->line->cid_num); int ext_matchmore = ast_matchmore_extension(pbx_channel, pbx_channel_context(pbx_channel), channel->dialedNumber, 1, channel->line->cid_num); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "+=sccp extension matcher says==================+\n" VERBOSE_PREFIX_2 "|ignore |exists |can match |match more|\n" VERBOSE_PREFIX_2 "|%3s |%3s |%3s |%3s |\n" VERBOSE_PREFIX_2 "+==============================================+\n", ignore_pat ? "yes" : "no", ext_exist ? "yes" : "no", ext_canmatch ? "yes" : "no", ext_matchmore ? "yes" : "no"); if (ignore_pat) { return SCCP_EXTENSION_NOTEXISTS; } else if (ext_exist) { if (ext_canmatch && !ext_matchmore) { return SCCP_EXTENSION_EXACTMATCH; } else { return SCCP_EXTENSION_MATCHMORE; } } return SCCP_EXTENSION_NOTEXISTS; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_request(const char *type, struct ast_format_cap *format, const PBX_CHANNEL_TYPE * requestor, const char *dest, int *cause) { sccp_channel_request_status_t requestStatus; PBX_CHANNEL_TYPE *result_ast_channel = NULL; sccp_channel_t *channel = NULL; const char *linkedId = NULL; skinny_codec_t audioCapabilities[SKINNY_MAX_CAPABILITIES]; skinny_codec_t videoCapabilities[SKINNY_MAX_CAPABILITIES]; memset(&audioCapabilities, 0, sizeof(audioCapabilities)); memset(&videoCapabilities, 0, sizeof(videoCapabilities)); //! \todo parse request char *lineName; skinny_codec_t codec = SKINNY_CODEC_G711_ULAW_64K; sccp_autoanswer_t autoanswer_type = SCCP_AUTOANSWER_NONE; uint8_t autoanswer_cause = AST_CAUSE_NOTDEFINED; int ringermode = 0; *cause = AST_CAUSE_NOTDEFINED; if (!type) { pbx_log(LOG_NOTICE, "Attempt to call with unspecified type of channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } if (!dest) { pbx_log(LOG_NOTICE, "Attempt to call SCCP/ failed\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } /* we leave the data unchanged */ lineName = strdupa((const char *) dest); /* parsing options string */ char *options = NULL; int optc = 0; char *optv[2]; int opti = 0; if ((options = strchr(lineName, '/'))) { *options = '\0'; options++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked us to create a channel with type=%s, format=" UI64FMT ", lineName=%s, options=%s\n", type, (uint64_t) ast_format_cap_to_old_bitfield(format), lineName, (options) ? options : ""); /* get ringer mode from ALERT_INFO */ const char *alert_info = NULL; if (requestor) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "_ALERT_INFO"); if (!alert_info) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "__ALERT_INFO"); } } if (alert_info && !sccp_strlen_zero(alert_info)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Found ALERT_INFO=%s\n", alert_info); if (strcasecmp(alert_info, "inside") == 0) ringermode = SKINNY_RINGTYPE_INSIDE; else if (strcasecmp(alert_info, "feature") == 0) ringermode = SKINNY_RINGTYPE_FEATURE; else if (strcasecmp(alert_info, "silent") == 0) ringermode = SKINNY_RINGTYPE_SILENT; else if (strcasecmp(alert_info, "urgent") == 0) ringermode = SKINNY_RINGTYPE_URGENT; } /* done ALERT_INFO parsing */ /* parse options */ if (options && (optc = sccp_app_separate_args(options, '/', optv, sizeof(optv) / sizeof(optv[0])))) { pbx_log(LOG_NOTICE, "parse options\n"); for (opti = 0; opti < optc; opti++) { pbx_log(LOG_NOTICE, "parse option '%s'\n", optv[opti]); if (!strncasecmp(optv[opti], "aa", 2)) { /* let's use the old style auto answer aa1w and aa2w */ if (!strncasecmp(optv[opti], "aa1w", 4)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa2w", 4)) { autoanswer_type = SCCP_AUTOANSWER_2W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa=", 3)) { optv[opti] += 3; pbx_log(LOG_NOTICE, "parsing aa\n"); if (!strncasecmp(optv[opti], "1w", 2)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 2; } else if (!strncasecmp(optv[opti], "2w", 2)) { autoanswer_type = SCCP_AUTOANSWER_2W; pbx_log(LOG_NOTICE, "set aa to 2w\n"); optv[opti] += 2; } } /* since the pbx ignores autoanswer_cause unless SCCP_RWLIST_GETSIZE(l->channels) > 1, it is safe to set it if provided */ if (!sccp_strlen_zero(optv[opti]) && (autoanswer_cause)) { if (!strcasecmp(optv[opti], "b")) autoanswer_cause = AST_CAUSE_BUSY; else if (!strcasecmp(optv[opti], "u")) autoanswer_cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; else if (!strcasecmp(optv[opti], "c")) autoanswer_cause = AST_CAUSE_CONGESTION; } if (autoanswer_cause) *cause = autoanswer_cause; /* check for ringer options */ } else if (!strncasecmp(optv[opti], "ringer=", 7)) { optv[opti] += 7; if (!strcasecmp(optv[opti], "inside")) ringermode = SKINNY_RINGTYPE_INSIDE; else if (!strcasecmp(optv[opti], "outside")) ringermode = SKINNY_RINGTYPE_OUTSIDE; else if (!strcasecmp(optv[opti], "feature")) ringermode = SKINNY_RINGTYPE_FEATURE; else if (!strcasecmp(optv[opti], "silent")) ringermode = SKINNY_RINGTYPE_SILENT; else if (!strcasecmp(optv[opti], "urgent")) ringermode = SKINNY_RINGTYPE_URGENT; else ringermode = SKINNY_RINGTYPE_OUTSIDE; } else { pbx_log(LOG_WARNING, "Wrong option %s\n", optv[opti]); } } } /** getting remote capabilities */ char cap_buf[512]; /* audio capabilities */ if (requestor) { sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(requestor); if (remoteSccpChannel) { uint8_t x, y, z; z = 0; /* shrink audioCapabilities to remote preferred/capable format */ for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { audioCapabilities[z++] = remoteSccpChannel->preferences.audio[x]; break; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_asterisk11_getSkinnyFormatMultiple(ast_channel_nativeformats(requestor), audioCapabilities, ARRAY_LEN(audioCapabilities)); // replace AUDIO_MASK with AST_FORMAT_TYPE_AUDIO check } /* video capabilities */ sccp_asterisk11_getSkinnyFormatMultiple(ast_channel_nativeformats(requestor), videoCapabilities, ARRAY_LEN(videoCapabilities)); //replace AUDIO_MASK with AST_FORMAT_TYPE_AUDIO check } sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, audioCapabilities, ARRAY_LEN(audioCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote audio caps: %s\n", cap_buf); sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, videoCapabilities, ARRAY_LEN(videoCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote video caps: %s\n", cap_buf); /** done */ /** get requested format */ // codec = pbx_codec2skinny_codec(ast_format_cap_to_old_bitfield(format)); codec = sccp_asterisk11_getSkinnyFormatSingle(format); requestStatus = sccp_requestChannel(lineName, codec, audioCapabilities, ARRAY_LEN(audioCapabilities), autoanswer_type, autoanswer_cause, ringermode, &channel); switch (requestStatus) { case SCCP_REQUEST_STATUS_SUCCESS: // everything is fine break; case SCCP_REQUEST_STATUS_LINEUNKNOWN: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s Unknown -> Not Successfull\n", lineName); *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER; goto EXITFUNC; case SCCP_REQUEST_STATUS_LINEUNAVAIL: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s not currently registered -> Try again later\n", lineName); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; case SCCP_REQUEST_STATUS_ERROR: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; default: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; } if (requestor) { linkedId = ast_channel_linkedid(requestor); } if (!sccp_pbx_channel_allocate(channel, linkedId)) { //! \todo handle error in more detail, cleanup sccp channel pbx_log(LOG_WARNING, "SCCP: Unable to allocate channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; } if (requestor) { /* set calling party */ sccp_channel_set_callingparty(channel, (char *) ast_channel_caller((PBX_CHANNEL_TYPE *) requestor)->id.name.str, (char *) ast_channel_caller((PBX_CHANNEL_TYPE *) requestor)->id.number.str); sccp_channel_set_originalCalledparty(channel, (char *) ast_channel_redirecting((PBX_CHANNEL_TYPE *) requestor)->orig.name.str, (char *) ast_channel_redirecting((PBX_CHANNEL_TYPE *) requestor)->orig.number.str); if (ast_channel_linkedid(requestor)) { ast_channel_linkedid_set(channel->owner, ast_channel_linkedid(requestor)); } } /** workaround for asterisk console log flooded channel.c:5080 ast_write: Codec mismatch on channel SCCP/xxx-0000002d setting write format to g722 from unknown native formats (nothing) */ skinny_codec_t codecs[] = { SKINNY_CODEC_WIDEBAND_256K }; sccp_wrapper_asterisk111_setNativeAudioFormats(channel, codecs, 1); sccp_wrapper_asterisk111_setReadFormat(channel, SKINNY_CODEC_WIDEBAND_256K); sccp_wrapper_asterisk111_setWriteFormat(channel, SKINNY_CODEC_WIDEBAND_256K); /** done */ EXITFUNC: if (channel) { result_ast_channel = channel->owner; sccp_channel_release(channel); } return result_ast_channel; } static int sccp_wrapper_asterisk111_call(PBX_CHANNEL_TYPE * ast, const char *dest, int timeout) { sccp_channel_t *c = NULL; struct varshead *headp; struct ast_var_t *current; int res = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk request to call %s (dest:%s, timeout: %d)\n", pbx_channel_name(ast), dest, timeout); if (!sccp_strlen_zero(pbx_channel_call_forward(ast))) { PBX(queue_control) (ast, -1); /* Prod Channel if in the middle of a call_forward instead of proceed */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Forwarding Call to '%s'\n", pbx_channel_call_forward(ast)); return 0; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { pbx_log(LOG_WARNING, "SCCP: Asterisk request to call %s on channel: %s, but we don't have this channel!\n", dest, pbx_channel_name(ast)); return -1; } /* Check whether there is MaxCallBR variables */ headp = ast_channel_varshead(ast); //ast_log(LOG_NOTICE, "SCCP: search for varibles!\n"); AST_LIST_TRAVERSE(headp, current, entries) { //ast_log(LOG_NOTICE, "var: name: %s, value: %s\n", ast_var_name(current), ast_var_value(current)); if (!strcasecmp(ast_var_name(current), "__MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } else if (!strcasecmp(ast_var_name(current), "MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } } res = sccp_pbx_call(c, (char *) dest, timeout); c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk111_answer(PBX_CHANNEL_TYPE * chan) { //! \todo change this handling and split pbx and sccp handling -MC int res = -1; sccp_channel_t *channel = NULL; if ((channel = get_sccp_channel_from_pbx_channel(chan))) { res = sccp_pbx_answer(channel); channel = sccp_channel_release(channel); } return res; } /** * * \todo update remote capabilities after fixup */ static int sccp_wrapper_asterisk111_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: we got a fixup request for %s\n", ast_channel_name(newchan)); sccp_channel_t *c = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(newchan))) { pbx_log(LOG_WARNING, "sccp_pbx_fixup(old: %s(%p), new: %s(%p)). no SCCP channel to fix\n", ast_channel_name(oldchan), (void *) oldchan, ast_channel_name(newchan), (void *) newchan); res = -1; } else { if (c->owner != oldchan) { ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, c->owner); res = -1; } else { c->owner = ast_channel_ref(newchan); if (!sccp_strlen_zero(c->line->language)) { ast_channel_language_set(newchan, c->line->language); } ast_channel_unref(oldchan); //! \todo force update of rtp_peer for directrtp // sccp_wrapper_asterisk111_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0); //! \todo update remote capabilities after fixup } c = sccp_channel_release(c); } return res; } #ifdef CS_AST_RTP_INSTANCE_BRIDGE static enum ast_bridge_result sccp_wrapper_asterisk111_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms) { enum ast_bridge_result res; int new_flags = flags; /* \note temporarily marked out until we figure out how to get directrtp back on track - DdG */ sccp_channel_t *sc0 = NULL, *sc1 = NULL; if ((sc0 = get_sccp_channel_from_pbx_channel(c0)) && (sc1 = get_sccp_channel_from_pbx_channel(c1))) { // Switch off DTMF between SCCP phones new_flags &= !AST_BRIDGE_DTMF_CHANNEL_0; new_flags &= !AST_BRIDGE_DTMF_CHANNEL_1; if (GLOB(directrtp)) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } else { sccp_device_t *d0 = sccp_channel_getDevice_retained(sc0); if (d0) { sccp_device_t *d1 = sccp_channel_getDevice_retained(sc1); if (d1) { if (d0->directrtp && d1->directrtp) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } d1 = sccp_device_release(d1); } d0 = sccp_device_release(d0); } } sc0->peerIsSCCP = TRUE; sc1->peerIsSCCP = TRUE; // SCCP Key handle direction to asterisk is still to be implemented here // sccp_pbx_senddigit } else { // Switch on DTMF between differing channels ast_channel_undefer_dtmf(c0); ast_channel_undefer_dtmf(c1); } sc0 = sc0 ? sccp_channel_release(sc0) : NULL; sc1 = sc1 ? sccp_channel_release(sc1) : NULL; //res = ast_rtp_bridge(c0, c1, new_flags, fo, rc, timeoutms); res = ast_rtp_instance_bridge(c0, c1, new_flags, fo, rc, timeoutms); switch (res) { case AST_BRIDGE_COMPLETE: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Complete\n", ast_channel_name(c0), ast_channel_name(c1)); break; case AST_BRIDGE_FAILED: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed\n", ast_channel_name(c0), ast_channel_name(c1)); break; case AST_BRIDGE_FAILED_NOWARN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed NoWarn\n", ast_channel_name(c0), ast_channel_name(c1)); break; case AST_BRIDGE_RETRY: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed Retry\n", ast_channel_name(c0), ast_channel_name(c1)); break; } /*! \todo Implement callback function queue upon completion */ return res; } #endif static enum ast_rtp_glue_result sccp_wrapper_asterisk111_get_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", pbx_channel_name(ast)); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; ao2_ref(*rtp, +1); if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( wrapper_asterisk111_get_rtp_peer ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_LOCAL; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( wrapper_asterisk111_get_rtp_peer ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", pbx_channel_name(ast)); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static int sccp_wrapper_asterisk111_set_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE * rtp, PBX_RTP_TYPE * vrtp, PBX_RTP_TYPE * trtp, const struct ast_format_cap *codecs, int nat_active) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int result = 0; do { if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO PVT\n"); result = -1; break; } if (!c->line) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO LINE\n"); result = -1; break; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO DEVICE\n"); result = -1; break; } if (!rtp) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) RTP not ready\n"); result = 0; break; } // if (!d->directrtp || d->nat) { struct ast_sockaddr us_tmp; struct sockaddr_in us = { 0, }; // sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) %s, use local part\n", d->directrtp ? "direct media disabled" : "NATed device"); ast_rtp_instance_get_local_address(rtp, &us_tmp); ast_sockaddr_to_sin(&us_tmp, &us); us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->session->ourip.s_addr; sccp_rtp_set_peer(c, &c->rtp.audio, &us); // } else { // struct ast_sockaddr them_tmp; // struct sockaddr_in them = { 0, }; // // ast_rtp_instance_get_remote_address(rtp, &them_tmp); // ast_sockaddr_to_sin(&them_tmp, &them); // sccp_rtp_set_peer(c, &c->rtp.audio, &them); // } if (ast_channel_state(ast) != AST_STATE_UP) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Early RTP stage, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } else { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Native Bridge Break, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } } while (0); /* Need a return here to break the bridge */ d = d ? sccp_device_release(d) : NULL; return result; } static enum ast_rtp_glue_result sccp_wrapper_asterisk111_get_vrtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", pbx_channel_name(ast)); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); //! \todo should this not be getVideoPeerInfo if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_FORBID; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", pbx_channel_name(ast)); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static void sccp_wrapper_asterisk111_getCodec(PBX_CHANNEL_TYPE * ast, struct ast_format_cap *result) { uint8_t i; struct ast_format fmt; sccp_channel_t *channel; if (!(channel = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP | DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (getCodec) NO PVT\n"); return; } ast_debug(10, "asterisk requests format for channel %s, readFormat: %s(%d)\n", pbx_channel_name(ast), codec2str(channel->rtp.audio.readFormat), channel->rtp.audio.readFormat); for (i = 0; i < ARRAY_LEN(channel->preferences.audio); i++) { ast_format_set(&fmt, skinny_codec2pbx_codec(channel->preferences.audio[i]), 0); ast_format_cap_add(result, &fmt); } return; } /* * \brief get callerid_name from pbx * \param sccp_channle Asterisk Channel * \param cid name result * \return parse result */ static int sccp_wrapper_asterisk111_callerid_name(const sccp_channel_t * channel, char **cid_name) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.name.str && strlen(ast_channel_caller(pbx_chan)->id.name.str) > 0) { *cid_name = strdup(ast_channel_caller(pbx_chan)->id.name.str); return 1; } return 0; } /* * \brief get callerid_name from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_number(const sccp_channel_t * channel, char **cid_number) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.number.str && strlen(ast_channel_caller(pbx_chan)->id.number.str) > 0) { *cid_number = strdup(ast_channel_caller(pbx_chan)->id.number.str); return 1; } return 0; } /* * \brief get callerid_ton from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_ton(const sccp_channel_t * channel, char **cid_ton) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.number.valid) { return ast_channel_caller(pbx_chan)->ani.number.plan; } return 0; } /* * \brief get callerid_ani from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_ani(const sccp_channel_t * channel, char **cid_ani) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->ani.number.valid && ast_channel_caller(pbx_chan)->ani.number.str && strlen(ast_channel_caller(pbx_chan)->ani.number.str) > 0) { *cid_ani = strdup(ast_channel_caller(pbx_chan)->ani.number.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_subaddr(const sccp_channel_t * channel, char **cid_subaddr) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_caller(pbx_chan)->id.subaddress.valid && ast_channel_caller(pbx_chan)->id.subaddress.str && strlen(ast_channel_caller(pbx_chan)->id.subaddress.str) > 0) { *cid_subaddr = strdup(ast_channel_caller(pbx_chan)->id.subaddress.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx (Destination ID) * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_dnid(const sccp_channel_t * channel, char **cid_dnid) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_dialed(pbx_chan)->number.str && strlen(ast_channel_dialed(pbx_chan)->number.str) > 0) { *cid_dnid = strdup(ast_channel_dialed(pbx_chan)->number.str); return 1; } return 0; } /* * \brief get callerid_rdnis from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_rdnis(const sccp_channel_t * channel, char **cid_rdnis) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (ast_channel_redirecting(pbx_chan)->from.number.valid && ast_channel_redirecting(pbx_chan)->from.number.str && strlen(ast_channel_redirecting(pbx_chan)->from.number.str) > 0) { *cid_rdnis = strdup(ast_channel_redirecting(pbx_chan)->from.number.str); return 1; } return 0; } /* * \brief get callerid_presence from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk111_callerid_presence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; // if (ast_channel_caller(pbx_chan)->id.number.valid) { // return ast_channel_caller(pbx_chan)->id.number.presentation; // } // return 0; if ((ast_party_id_presentation(&ast_channel_caller(pbx_chan)->id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) { return CALLERID_PRESENCE_ALLOWED; } return CALLERID_PRESENCE_FORBIDDEN; } static int sccp_wrapper_asterisk111_rtp_stop(sccp_channel_t * channel) { if (channel->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping phone media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.audio.rtp); } if (channel->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping video media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.video.rtp); } return 0; } static boolean_t sccp_wrapper_asterisk111_create_audio_rtp(sccp_channel_t * c) { sccp_session_t *s = NULL; sccp_device_t *d = NULL; struct ast_sockaddr sock; // struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; if (GLOB(bindaddr.sin_addr.s_addr) == INADDR_ANY) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = GLOB(bindaddr.sin_port); sin.sin_addr = s->ourip; /* sccp_socket_getOurAddressfor(s->sin.sin_addr, sin.sin_addr); */// maybe we should use this opertunity to check the connected ip-address again ast_sockaddr_from_sin(&sock, &sin); } else { ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating rtp server connection on %s\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock)); c->rtp.audio.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.audio.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: rtp server created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_RTCP, 1); if (SCCP_DTMFMODE_INBAND == d->dtmfmode) { ast_rtp_instance_dtmf_mode_set(c->rtp.audio.rtp, AST_RTP_DTMF_MODE_INBAND); } else { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF, 1); ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, 1); } ast_channel_set_fd(c->owner, 0, ast_rtp_instance_fd(c->rtp.audio.rtp, 0)); ast_channel_set_fd(c->owner, 1, ast_rtp_instance_fd(c->rtp.audio.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } // memset(&astCodecPref, 0, sizeof(astCodecPref)); // if (skinny_codecs2pbx_codec_pref(c->preferences.audio, &astCodecPref)) { // ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); // } // char pref_buf[128]; // ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); // sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pref: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); ast_rtp_instance_set_qos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.audio.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add audio codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_AUDIO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "audio", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk111_create_video_rtp(sccp_channel_t * c) { sccp_session_t *s; sccp_device_t *d = NULL; struct ast_sockaddr sock; struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating vrtp server connection at %s\n", DEV_ID_LOG(d), pbx_inet_ntoa(s->ourip)); ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); c->rtp.video.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.video.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: vrtp created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.video.rtp, AST_RTP_PROPERTY_RTCP, 1); ast_channel_set_fd(c->owner, 2, ast_rtp_instance_fd(c->rtp.video.rtp, 0)); ast_channel_set_fd(c->owner, 3, ast_rtp_instance_fd(c->rtp.video.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } memset(&astCodecPref, 0, sizeof(astCodecPref)); if (skinny_codecs2pbx_codec_pref(c->preferences.video, &astCodecPref)) { ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); } //char pref_buf[128]; //ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); //sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pef: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.video.rtp, d->video_tos, d->video_cos, "SCCP VRTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.video.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add video codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_VIDEO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "video", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk111_destroyRTP(PBX_RTP_TYPE * rtp) { int res; res = ast_rtp_instance_destroy(rtp); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk111_checkHangup(const sccp_channel_t * channel) { int res; res = ast_check_hangup(channel->owner); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk111_rtpGetPeer(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_remote_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk111_rtpGetUs(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_local_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk111_getChannelByName(const char *name, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *ast = ast_channel_get_by_name(name); if (!ast) return FALSE; *pbx_channel = ast; return TRUE; } static int sccp_wrapper_asterisk111_rtp_set_peer(const struct sccp_rtp *rtp, const struct sockaddr_in *new_peer, int nat_active) { struct ast_sockaddr ast_sockaddr_dest; struct ast_sockaddr ast_sockaddr_source; int res; ((struct sockaddr_in *) new_peer)->sin_family = AF_INET; ast_sockaddr_from_sin(&ast_sockaddr_dest, new_peer); ast_sockaddr_set_port(&ast_sockaddr_dest, ntohs(new_peer->sin_port)); res = ast_rtp_instance_set_remote_address(rtp->rtp, &ast_sockaddr_dest); ast_rtp_instance_get_local_address(rtp->rtp, &ast_sockaddr_source); // sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "SCCP: Tell PBX to send RTP/UDP media from '%s:%d' to '%s:%d' (NAT: %s)\n", ast_sockaddr_stringify_host(&ast_sockaddr_source), ast_sockaddr_port(&ast_sockaddr_source), ast_sockaddr_stringify_host(&ast_sockaddr_dest), ast_sockaddr_port(&ast_sockaddr_dest), nat_active ? "yes" : "no"); if (nat_active) { ast_rtp_instance_set_prop(rtp->rtp, AST_RTP_PROPERTY_NAT, 1); } return res; } static boolean_t sccp_wrapper_asterisk111_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec) { //! \todo possibly needs to be synced to ast108 if (!channel) return FALSE; struct ast_format tmp_format; struct ast_format_cap *cap = ast_format_cap_alloc_nolock(); ast_format_set(&tmp_format, skinny_codec2pbx_codec(codec), 0); ast_format_cap_add(cap, &tmp_format); ast_set_write_format_from_cap(channel->owner, cap); ast_format_cap_destroy(cap); if (NULL != channel->rtp.audio.rtp) { ast_rtp_instance_set_write_format(channel->rtp.audio.rtp, &tmp_format); } return TRUE; } static boolean_t sccp_wrapper_asterisk111_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec) { //! \todo possibly needs to be synced to ast108 if (!channel) return FALSE; struct ast_format tmp_format; struct ast_format_cap *cap = ast_format_cap_alloc_nolock(); ast_format_set(&tmp_format, skinny_codec2pbx_codec(codec), 0); ast_format_cap_add(cap, &tmp_format); ast_set_read_format_from_cap(channel->owner, cap); ast_format_cap_destroy(cap); if (NULL != channel->rtp.audio.rtp) { ast_rtp_instance_set_read_format(channel->rtp.audio.rtp, &tmp_format); } return TRUE; } static void sccp_wrapper_asterisk111_setCalleridName(const sccp_channel_t * channel, const char *name) { if (name) { ast_party_name_free(&ast_channel_caller(channel->owner)->id.name); ast_channel_caller(channel->owner)->id.name.str = ast_strdup(name); ast_channel_caller(channel->owner)->id.name.valid = 1; } } static void sccp_wrapper_asterisk111_setCalleridNumber(const sccp_channel_t * channel, const char *number) { if (number) { ast_party_number_free(&ast_channel_caller(channel->owner)->id.number); ast_channel_caller(channel->owner)->id.number.str = ast_strdup(number); ast_channel_caller(channel->owner)->id.number.valid = 1; } } static void sccp_wrapper_asterisk111_setRedirectingParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { ast_party_number_free(&ast_channel_redirecting(channel->owner)->from.number); ast_channel_redirecting(channel->owner)->from.number.str = ast_strdup(number); ast_channel_redirecting(channel->owner)->from.number.valid = 1; } if (name) { ast_party_name_free(&ast_channel_redirecting(channel->owner)->from.name); ast_channel_redirecting(channel->owner)->from.name.str = ast_strdup(name); ast_channel_redirecting(channel->owner)->from.name.valid = 1; } } static void sccp_wrapper_asterisk111_setRedirectedParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { ast_party_number_free(&ast_channel_redirecting(channel->owner)->to.number); ast_channel_redirecting(channel->owner)->to.number.str = ast_strdup(number); ast_channel_redirecting(channel->owner)->to.number.valid = 1; } if (name) { ast_party_name_free(&ast_channel_redirecting(channel->owner)->to.name); ast_channel_redirecting(channel->owner)->to.name.str = ast_strdup(name); ast_channel_redirecting(channel->owner)->to.name.valid = 1; } } static void sccp_wrapper_asterisk111_updateConnectedLine(const sccp_channel_t * channel, const char *number, const char *name, uint8_t reason) { struct ast_party_connected_line connected; struct ast_set_party_connected_line update_connected; memset(&update_connected, 0, sizeof(update_connected)); ast_party_connected_line_init(&connected); if (number) { update_connected.id.number = 1; connected.id.number.valid = 1; connected.id.number.str = (char *) number; connected.id.number.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (name) { update_connected.id.name = 1; connected.id.name.valid = 1; connected.id.name.str = (char *) name; connected.id.name.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (update_connected.id.number || update_connected.id.name) { ast_set_party_id_all(&update_connected.priv); // connected.id.tag = NULL; connected.source = reason; ast_channel_queue_connected_line_update(channel->owner, &connected, &update_connected); sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "SCCP: do connected line for line '%s', name: %s ,num: %s\n", pbx_channel_name(channel->owner), name ? name : "(NULL)", number ? number : "(NULL)"); } } /* // moved to ast.c static void sccp_wrapper_asterisk111_sendRedirectedUpdate(const sccp_channel_t * channel, const char *fromNumber, const char *fromName, const char *toNumber, const char *toName, uint8_t reason){ struct ast_party_redirecting redirecting; struct ast_set_party_redirecting update_redirecting; ast_party_redirecting_init(&redirecting); memset(&update_redirecting, 0, sizeof(update_redirecting)); // update redirecting info line for source part if(fromNumber){ update_redirecting.from.number = 1; redirecting.from.number.valid = 1; redirecting.from.number.str = strdupa(fromNumber); } if(fromName){ update_redirecting.from.name = 1; redirecting.from.name.valid = 1; redirecting.from.name.str = strdupa(fromName); } if(toNumber){ update_redirecting.to.number = 1; redirecting.to.number.valid = 1; redirecting.to.number.str = strdupa(toNumber); } if(toName){ update_redirecting.to.name = 1; redirecting.to.name.valid = 1; redirecting.to.name.str = strdupa(toName); } ast_channel_queue_redirecting_update(channel->owner, &redirecting, &update_redirecting); } */ static int sccp_wrapper_asterisk111_sched_add(int when, sccp_sched_cb callback, const void *data) { if (sched) return ast_sched_add(sched, when, callback, data); return FALSE; } static long sccp_wrapper_asterisk111_sched_when(int id) { if (sched) return ast_sched_when(sched, id); return FALSE; } static int sccp_wrapper_asterisk111_sched_wait(int id) { if (sched) return ast_sched_wait(sched); return FALSE; } static int sccp_wrapper_asterisk111_sched_del(int id) { if (sched) return ast_sched_del(sched, id); return FALSE; } static int sccp_wrapper_asterisk111_setCallState(const sccp_channel_t * channel, int state) { sccp_pbx_setcallstate((sccp_channel_t *) channel, state); return 0; } static boolean_t sccp_asterisk_getRemoteChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *remotePeer = NULL; // struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); // // ((struct ao2_iterator *)iterator)->flags |= AO2_ITERATOR_DONTLOCK; // // for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { // if (pbx_find_channel_by_linkid(remotePeer, (void *)ast_channel_linkedid(channel->owner))) { // break; // } // } // // while(!(remotePeer = ast_channel_iterator_next(iterator) ){ // ast_channel_unref(remotePeer); // } // // ast_channel_iterator_destroy(iterator); // // if (remotePeer) { // *pbx_channel = remotePeer; // remotePeer = ast_channel_unref(remotePeer); // should we be releasing th referenec here, it has not been taken explicitly. // return TRUE; // } *pbx_channel = remotePeer; return FALSE; } /*! * \brief Send Text to Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param text Text to be send as char * \return Succes as int * * \called_from_asterisk */ static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; uint8_t instance; if (!ast) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX CHANNEL to send text to\n"); return -1; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send text to (%s)\n", pbx_channel_name(ast)); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send text to (%s)\n", pbx_channel_name(ast)); c = sccp_channel_release(c); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Sending text %s on %s\n", d->id, text, pbx_channel_name(ast)); instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, (char *) text, 10); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! * \brief Receive First Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit First Digit as char * \return Always Return -1 as int * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit) { return -1; } /*! * \brief Receive Last Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit Last Digit as char * \param duration Duration as int * \return boolean * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send digit to (%s)\n", pbx_channel_name(ast)); return -1; } do { if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send digit to (%s)\n", pbx_channel_name(ast)); break; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked to send dtmf '%d' to channel %s. Trying to send it %s\n", digit, pbx_channel_name(ast), (d->dtmfmode) ? "outofband" : "inband"); if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Can't send the dtmf '%d' %c to a not connected channel %s\n", d->id, digit, digit, pbx_channel_name(ast)); break; } sccp_dev_keypadbutton(d, digit, sccp_device_find_index_for_line(d, c->line->name), c->callid); } while (0); d = d ? sccp_device_release(d) : NULL; c = c ? sccp_channel_release(c) : NULL; return -1; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_findChannelWithCallback(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data, boolean_t lock) { PBX_CHANNEL_TYPE *remotePeer = NULL; // struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); // // if (!lock) { // ((struct ao2_iterator *)iterator)->flags |= AO2_ITERATOR_DONTLOCK; // } // // for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { // // if (found_cb(remotePeer, data)) { // // ast_channel_lock(remotePeer); // ast_channel_unref(remotePeer); // break; // } // // } // ast_channel_iterator_destroy(iterator); return remotePeer; } /*! \brief Set an option on a asterisk channel */ #if 0 static int sccp_wrapper_asterisk111_setOption(PBX_CHANNEL_TYPE * ast, int option, void *data, int datalen) { int res = -1; sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: channel: %s(%s) setOption: %d\n", c->currentDeviceId, sccp_channel_toString(c), pbx_channel_name(ast), option); //! if AST_OPTION_FORMAT_READ / AST_OPTION_FORMAT_WRITE are available we might be indication that we can do transcoding (channel.c:set_format). Correct ? */ switch (option) { case AST_OPTION_FORMAT_READ: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_read_format(c->rtp.audio.rtp, (struct ast_format *) data); } //sccp_wrapper_asterisk111_setReadFormat(c, (struct ast_format *) data); break; case AST_OPTION_FORMAT_WRITE: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_write_format(c->rtp.audio.rtp, (struct ast_format *) data); } //sccp_wrapper_asterisk111_setWriteFormat(c, (struct ast_format *) data); break; case AST_OPTION_MAKE_COMPATIBLE: if (c->rtp.audio.rtp) { res = ast_rtp_instance_make_compatible(ast, c->rtp.audio.rtp, (PBX_CHANNEL_TYPE *) data); } break; case AST_OPTION_DIGIT_DETECT: case AST_OPTION_SECURE_SIGNALING: case AST_OPTION_SECURE_MEDIA: res = -1; break; default: break; } c = sccp_channel_release(c); } return res; } #endif static void sccp_wrapper_asterisk_set_pbxchannel_linkedid(PBX_CHANNEL_TYPE * pbx_channel, const char *new_linkedid) { if (pbx_channel) { if (!strcmp(ast_channel_linkedid(pbx_channel), new_linkedid)) { return; } ast_cel_check_retire_linkedid(pbx_channel); ast_channel_linkedid_set(pbx_channel, new_linkedid); ast_cel_linkedid_ref(new_linkedid); } }; #define DECLARE_PBX_CHANNEL_STRGET(_field) \ static const char *sccp_wrapper_asterisk_get_channel_##_field(const sccp_channel_t * channel) \ { \ static const char *empty_channel_##_field = "--no-channel" #_field "--"; \ if (channel->owner) { \ return ast_channel_##_field(channel->owner); \ } \ return empty_channel_##_field; \ }; #define DECLARE_PBX_CHANNEL_STRSET(_field) \ static void sccp_wrapper_asterisk_set_channel_##_field(const sccp_channel_t * channel, const char * _field) \ { \ if (channel->owner) { \ ast_channel_##_field##_set(channel->owner, _field); \ } \ }; DECLARE_PBX_CHANNEL_STRGET(name) DECLARE_PBX_CHANNEL_STRSET(name) DECLARE_PBX_CHANNEL_STRGET(uniqueid) DECLARE_PBX_CHANNEL_STRGET(appl) DECLARE_PBX_CHANNEL_STRGET(exten) DECLARE_PBX_CHANNEL_STRSET(exten) DECLARE_PBX_CHANNEL_STRGET(linkedid) DECLARE_PBX_CHANNEL_STRGET(context) DECLARE_PBX_CHANNEL_STRSET(context) DECLARE_PBX_CHANNEL_STRGET(macroexten) DECLARE_PBX_CHANNEL_STRSET(macroexten) DECLARE_PBX_CHANNEL_STRGET(macrocontext) DECLARE_PBX_CHANNEL_STRSET(macrocontext) DECLARE_PBX_CHANNEL_STRGET(call_forward) DECLARE_PBX_CHANNEL_STRSET(call_forward) static void sccp_wrapper_asterisk_set_channel_linkedid(const sccp_channel_t * channel, const char *new_linkedid) { if (channel->owner) { sccp_wrapper_asterisk_set_pbxchannel_linkedid(channel->owner, new_linkedid); } }; static enum ast_channel_state sccp_wrapper_asterisk_get_channel_state(const sccp_channel_t * channel) { if (channel->owner) { return ast_channel_state(channel->owner); } return 0; } static const struct ast_pbx *sccp_wrapper_asterisk_get_channel_pbx(const sccp_channel_t * channel) { if (channel->owner) { return ast_channel_pbx(channel->owner); } return NULL; } static void sccp_wrapper_asterisk_set_channel_tech_pvt(const sccp_channel_t * channel) { if (channel->owner) { ast_channel_tech_pvt_set(channel->owner, (void *) channel); } } static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!datalen || sccp_strlen_zero(data) || !(!strncmp(data, "http://", 7) || !strncmp(data, "file://", 7) || !strncmp(data, "ftp://", 6))) { pbx_log(LOG_NOTICE, "SCCP: Received a non valid URL\n"); return -1; } struct ast_frame fr; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { #if DEBUG if (!(d = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { #else if (!(d = c->getDevice_retained(c))) { #endif c = sccp_channel_release(c); return -1; } memset(&fr, 0, sizeof(fr)); fr.frametype = AST_FRAME_HTML; fr.data.ptr = (char *) data; fr.src = "SCCP Send URL"; fr.datalen = datalen; sccp_push_result_t pushResult = d->pushURL(d, data, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { fr.subclass.integer = AST_HTML_LDCOMPLETE; } else { fr.subclass.integer = AST_HTML_NOSUPPORT; } ast_queue_frame(ast, ast_frisolate(&fr)); d = sccp_device_release(d); c = sccp_channel_release(c); } return 0; } /*! * \brief Queue a control frame * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type */ int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Queue a control frame with payload * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type * \param data Payload * \param datalen Payload Length */ int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control,.data.ptr = (void *) data,.datalen = datalen }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Get Hint Extension State and return the matching Busy Lamp Field State */ static skinny_busylampfield_state_t sccp_wrapper_asterisk111_getExtensionState(const char *extension, const char *context) { skinny_busylampfield_state_t result = SKINNY_BLF_STATUS_UNKNOWN; if (sccp_strlen_zero(extension) || sccp_strlen_zero(context)) { pbx_log(LOG_ERROR, "SCCP: PBX(getExtensionState): Either extension:'%s' or context:;%s' provided is empty\n", extension, context); return result; } int state = ast_extension_state(NULL, context, extension); switch (state) { case AST_EXTENSION_REMOVED: case AST_EXTENSION_DEACTIVATED: case AST_EXTENSION_UNAVAILABLE: result = SKINNY_BLF_STATUS_UNKNOWN; break; case AST_EXTENSION_NOT_INUSE: result = SKINNY_BLF_STATUS_IDLE; break; case AST_EXTENSION_INUSE: case AST_EXTENSION_ONHOLD: case AST_EXTENSION_ONHOLD + AST_EXTENSION_INUSE: case AST_EXTENSION_BUSY: result = SKINNY_BLF_STATUS_INUSE; break; case AST_EXTENSION_RINGING + AST_EXTENSION_INUSE: case AST_EXTENSION_RINGING: result = SKINNY_BLF_STATUS_ALERTING; break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (getExtensionState) extension: %s@%s, extension_state: '%s (%d)' -> blf state '%d'\n", extension, context, ast_extension_state2str(state), state, result); return result; } /*! * \brief using RTP Glue Engine */ #if defined(__cplusplus) || defined(c_plusplus) struct ast_rtp_glue sccp_rtp = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, mod: NULL, get_rtp_info:sccp_wrapper_asterisk111_get_rtp_peer, get_vrtp_info:sccp_wrapper_asterisk111_get_vrtp_peer, get_trtp_info:NULL, update_peer:sccp_wrapper_asterisk111_set_rtp_peer, get_codec:sccp_wrapper_asterisk111_getCodec, /* *INDENT-ON* */ }; #else struct ast_rtp_glue sccp_rtp = { .type = SCCP_TECHTYPE_STR, .get_rtp_info = sccp_wrapper_asterisk111_get_rtp_peer, .get_vrtp_info = sccp_wrapper_asterisk111_get_vrtp_peer, .update_peer = sccp_wrapper_asterisk111_set_rtp_peer, .get_codec = sccp_wrapper_asterisk111_getCodec, }; #endif #ifdef HAVE_PBX_MESSAGE_H #include "asterisk/message.h" static int sccp_asterisk_message_send(const struct ast_msg *msg, const char *to, const char *from) { char *lineName; sccp_line_t *line; const char *messageText = ast_msg_get_body(msg); int res = -1; lineName = (char *) sccp_strdupa(to); if (strchr(lineName, '@')) { strsep(&lineName, "@"); } else { strsep(&lineName, ":"); } if (sccp_strlen_zero(lineName)) { pbx_log(LOG_WARNING, "MESSAGE(to) is invalid for SCCP - '%s'\n", to); return -1; } line = sccp_line_find_byname(lineName, FALSE); if (!line) { pbx_log(LOG_WARNING, "line '%s' not found\n", lineName); return -1; } /** \todo move this to line implementation */ sccp_linedevices_t *linedevice; sccp_push_result_t pushResult; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { pushResult = linedevice->device->pushTextMessage(linedevice->device, messageText, from, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { res = 0; } } SCCP_LIST_UNLOCK(&line->devices); return res; } #if defined(__cplusplus) || defined(c_plusplus) static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ name: "sccp", msg_send:sccp_asterisk_message_send, /* *INDENT-ON* */ }; #else static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ .name = "sccp", .msg_send = sccp_asterisk_message_send, /* *INDENT-ON* */ }; #endif #endif /*! * \brief pbx_manager_register * * \note this functions needs to be defined here, because it depends on the static declaration of ast_module_info->self */ int pbx_manager_register(const char *action, int authority, int (*func) (struct mansession * s, const struct message * m), const char *synopsis, const char *description) { return ast_manager_register2(action, authority, func, ast_module_info->self, synopsis, description); } boolean_t sccp_wrapper_asterisk111_setLanguage(PBX_CHANNEL_TYPE * pbxChannel, const char *language) { ast_channel_language_set(pbxChannel, language); return TRUE; } #if defined(__cplusplus) || defined(c_plusplus) sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ alloc_pbxChannel: sccp_wrapper_asterisk111_allocPBXChannel, set_callstate: sccp_wrapper_asterisk111_setCallState, checkhangup: sccp_wrapper_asterisk111_checkHangup, hangup: NULL, requestHangup: sccp_wrapper_asterisk_requestHangup, forceHangup: sccp_wrapper_asterisk_forceHangup, extension_status: sccp_wrapper_asterisk111_extensionStatus, setPBXChannelLinkedId: sccp_wrapper_asterisk_set_pbxchannel_linkedid, /** get channel by name */ getChannelByName: sccp_wrapper_asterisk111_getChannelByName, getRemoteChannel: sccp_asterisk_getRemoteChannel, getChannelByCallback: NULL, getChannelLinkedId: sccp_wrapper_asterisk_get_channel_linkedid, setChannelLinkedId: sccp_wrapper_asterisk_set_channel_linkedid, getChannelName: sccp_wrapper_asterisk_get_channel_name, getChannelUniqueID: sccp_wrapper_asterisk_get_channel_uniqueid, getChannelExten: sccp_wrapper_asterisk_get_channel_exten, setChannelExten: sccp_wrapper_asterisk_set_channel_exten, getChannelContext: sccp_wrapper_asterisk_get_channel_context, setChannelContext: sccp_wrapper_asterisk_set_channel_context, getChannelMacroExten: sccp_wrapper_asterisk_get_channel_macroexten, setChannelMacroExten: sccp_wrapper_asterisk_set_channel_macroexten, getChannelMacroContext: sccp_wrapper_asterisk_get_channel_macrocontext, setChannelMacroContext: sccp_wrapper_asterisk_set_channel_macrocontext, getChannelCallForward: sccp_wrapper_asterisk_get_channel_call_forward, setChannelCallForward: sccp_wrapper_asterisk_set_channel_call_forward, getChannelAppl: sccp_wrapper_asterisk_get_channel_appl, getChannelState: sccp_wrapper_asterisk_get_channel_state, getChannelPbx: sccp_wrapper_asterisk_get_channel_pbx, setChannelTechPVT: sccp_wrapper_asterisk_set_channel_tech_pvt, set_nativeAudioFormats: sccp_wrapper_asterisk111_setNativeAudioFormats, set_nativeVideoFormats: sccp_wrapper_asterisk111_setNativeVideoFormats, getPeerCodecCapabilities: NULL, send_digit: sccp_wrapper_asterisk111_sendDigit, send_digits: sccp_wrapper_asterisk111_sendDigits, sched_add: sccp_wrapper_asterisk111_sched_add, sched_del: sccp_wrapper_asterisk111_sched_del, sched_when: sccp_wrapper_asterisk111_sched_when, sched_wait: sccp_wrapper_asterisk111_sched_wait, /* rtp */ rtp_getPeer: sccp_wrapper_asterisk111_rtpGetPeer, rtp_getUs: sccp_wrapper_asterisk111_rtpGetUs, rtp_setPeer: sccp_wrapper_asterisk111_rtp_set_peer, rtp_setWriteFormat: sccp_wrapper_asterisk111_setWriteFormat, rtp_setReadFormat: sccp_wrapper_asterisk111_setReadFormat, rtp_destroy: sccp_wrapper_asterisk111_destroyRTP, rtp_stop: sccp_wrapper_asterisk111_rtp_stop, rtp_codec: NULL, rtp_audio_create: sccp_wrapper_asterisk111_create_audio_rtp, rtp_video_create: sccp_wrapper_asterisk111_create_video_rtp, rtp_get_payloadType: sccp_wrapper_asterisk111_get_payloadType, rtp_get_sampleRate: sccp_wrapper_asterisk111_get_sampleRate, rtp_bridgePeers: NULL, /* callerid */ get_callerid_name: sccp_wrapper_asterisk111_callerid_name, get_callerid_number: sccp_wrapper_asterisk111_callerid_number, get_callerid_ton: sccp_wrapper_asterisk111_callerid_ton, get_callerid_ani: sccp_wrapper_asterisk111_callerid_ani, get_callerid_subaddr: sccp_wrapper_asterisk111_callerid_subaddr, get_callerid_dnid: sccp_wrapper_asterisk111_callerid_dnid, get_callerid_rdnis: sccp_wrapper_asterisk111_callerid_rdnis, get_callerid_presence: sccp_wrapper_asterisk111_callerid_presence, set_callerid_name: sccp_wrapper_asterisk111_setCalleridName, set_callerid_number: sccp_wrapper_asterisk111_setCalleridNumber, set_callerid_ani: NULL, set_callerid_dnid: NULL, set_callerid_redirectingParty: sccp_wrapper_asterisk111_setRedirectingParty, set_callerid_redirectedParty: sccp_wrapper_asterisk111_setRedirectedParty, set_callerid_presence: sccp_wrapper_asterisk111_setCalleridPresence, set_connected_line: sccp_wrapper_asterisk111_updateConnectedLine, // sendRedirectedUpdate: sccp_wrapper_asterisk111_sendRedirectedUpdate, sendRedirectedUpdate: sccp_asterisk_sendRedirectedUpdate, /* feature section */ feature_park: sccp_wrapper_asterisk111_park, feature_stopMusicOnHold: NULL, feature_addToDatabase: sccp_asterisk_addToDatabase, feature_getFromDatabase: sccp_asterisk_getFromDatabase, feature_removeFromDatabase: sccp_asterisk_removeFromDatabase, feature_removeTreeFromDatabase: sccp_asterisk_removeTreeFromDatabase, feature_monitor: sccp_wrapper_asterisk_featureMonitor, getFeatureExtension: sccp_wrapper_asterisk111_getFeatureExtension, feature_pickup: sccp_wrapper_asterisk111_pickupChannel, eventSubscribe: NULL, findChannelByCallback: sccp_wrapper_asterisk111_findChannelWithCallback, moh_start: sccp_asterisk_moh_start, moh_stop: sccp_asterisk_moh_stop, queue_control: sccp_asterisk_queue_control, queue_control_data: sccp_asterisk_queue_control_data, allocTempPBXChannel: sccp_wrapper_asterisk111_allocTempPBXChannel, masqueradeHelper: sccp_wrapper_asterisk111_masqueradeHelper, requestForeignChannel: sccp_wrapper_asterisk111_requestForeignChannel, set_language: sccp_wrapper_asterisk111_setLanguage, getExtensionState: sccp_wrapper_asterisk111_getExtensionState, findPickupChannelByExtenLocked: sccp_wrapper_asterisk111_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #else /*! * \brief SCCP - PBX Callback Functions * (Decoupling Tight Dependencies on Asterisk Functions) */ struct sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ /* channel */ .alloc_pbxChannel = sccp_wrapper_asterisk111_allocPBXChannel, .requestHangup = sccp_wrapper_asterisk_requestHangup, .forceHangup = sccp_wrapper_asterisk_forceHangup, .extension_status = sccp_wrapper_asterisk111_extensionStatus, .setPBXChannelLinkedId = sccp_wrapper_asterisk_set_pbxchannel_linkedid, .getChannelByName = sccp_wrapper_asterisk111_getChannelByName, .getChannelLinkedId = sccp_wrapper_asterisk_get_channel_linkedid, .setChannelLinkedId = sccp_wrapper_asterisk_set_channel_linkedid, .getChannelName = sccp_wrapper_asterisk_get_channel_name, .setChannelName = sccp_wrapper_asterisk_set_channel_name, .getChannelUniqueID = sccp_wrapper_asterisk_get_channel_uniqueid, .getChannelExten = sccp_wrapper_asterisk_get_channel_exten, .setChannelExten = sccp_wrapper_asterisk_set_channel_exten, .getChannelContext = sccp_wrapper_asterisk_get_channel_context, .setChannelContext = sccp_wrapper_asterisk_set_channel_context, .getChannelMacroExten = sccp_wrapper_asterisk_get_channel_macroexten, .setChannelMacroExten = sccp_wrapper_asterisk_set_channel_macroexten, .getChannelMacroContext = sccp_wrapper_asterisk_get_channel_macrocontext, .setChannelMacroContext = sccp_wrapper_asterisk_set_channel_macrocontext, .getChannelCallForward = sccp_wrapper_asterisk_get_channel_call_forward, .setChannelCallForward = sccp_wrapper_asterisk_set_channel_call_forward, .getChannelAppl = sccp_wrapper_asterisk_get_channel_appl, .getChannelState = sccp_wrapper_asterisk_get_channel_state, .getChannelPbx = sccp_wrapper_asterisk_get_channel_pbx, .setChannelTechPVT = sccp_wrapper_asterisk_set_channel_tech_pvt, .getRemoteChannel = sccp_asterisk_getRemoteChannel, .checkhangup = sccp_wrapper_asterisk111_checkHangup, /* digits */ .send_digits = sccp_wrapper_asterisk111_sendDigits, .send_digit = sccp_wrapper_asterisk111_sendDigit, /* schedulers */ .sched_add = sccp_wrapper_asterisk111_sched_add, .sched_del = sccp_wrapper_asterisk111_sched_del, .sched_when = sccp_wrapper_asterisk111_sched_when, .sched_wait = sccp_wrapper_asterisk111_sched_wait, /* callstate / indicate */ .set_callstate = sccp_wrapper_asterisk111_setCallState, /* codecs */ .set_nativeAudioFormats = sccp_wrapper_asterisk111_setNativeAudioFormats, .set_nativeVideoFormats = sccp_wrapper_asterisk111_setNativeVideoFormats, /* rtp */ .rtp_getPeer = sccp_wrapper_asterisk111_rtpGetPeer, .rtp_getUs = sccp_wrapper_asterisk111_rtpGetUs, .rtp_stop = sccp_wrapper_asterisk111_rtp_stop, .rtp_audio_create = sccp_wrapper_asterisk111_create_audio_rtp, .rtp_video_create = sccp_wrapper_asterisk111_create_video_rtp, .rtp_get_payloadType = sccp_wrapper_asterisk111_get_payloadType, .rtp_get_sampleRate = sccp_wrapper_asterisk111_get_sampleRate, .rtp_destroy = sccp_wrapper_asterisk111_destroyRTP, .rtp_setWriteFormat = sccp_wrapper_asterisk111_setWriteFormat, .rtp_setReadFormat = sccp_wrapper_asterisk111_setReadFormat, .rtp_setPeer = sccp_wrapper_asterisk111_rtp_set_peer, /* callerid */ .get_callerid_name = sccp_wrapper_asterisk111_callerid_name, .get_callerid_number = sccp_wrapper_asterisk111_callerid_number, .get_callerid_ton = sccp_wrapper_asterisk111_callerid_ton, .get_callerid_ani = sccp_wrapper_asterisk111_callerid_ani, .get_callerid_subaddr = sccp_wrapper_asterisk111_callerid_subaddr, .get_callerid_dnid = sccp_wrapper_asterisk111_callerid_dnid, .get_callerid_rdnis = sccp_wrapper_asterisk111_callerid_rdnis, .get_callerid_presence = sccp_wrapper_asterisk111_callerid_presence, .set_callerid_name = sccp_wrapper_asterisk111_setCalleridName, //! \todo implement callback .set_callerid_number = sccp_wrapper_asterisk111_setCalleridNumber, //! \todo implement callback .set_callerid_dnid = NULL, //! \todo implement callback .set_callerid_redirectingParty = sccp_wrapper_asterisk111_setRedirectingParty, .set_callerid_redirectedParty = sccp_wrapper_asterisk111_setRedirectedParty, .set_callerid_presence = sccp_wrapper_asterisk111_setCalleridPresence, .set_connected_line = sccp_wrapper_asterisk111_updateConnectedLine, // .sendRedirectedUpdate = sccp_wrapper_asterisk111_sendRedirectedUpdate, .sendRedirectedUpdate = sccp_asterisk_sendRedirectedUpdate, /* database */ .feature_addToDatabase = sccp_asterisk_addToDatabase, .feature_getFromDatabase = sccp_asterisk_getFromDatabase, .feature_removeFromDatabase = sccp_asterisk_removeFromDatabase, .feature_removeTreeFromDatabase = sccp_asterisk_removeTreeFromDatabase, .feature_monitor = sccp_wrapper_asterisk_featureMonitor, .feature_park = sccp_wrapper_asterisk111_park, .getFeatureExtension = sccp_wrapper_asterisk111_getFeatureExtension, .feature_pickup = sccp_wrapper_asterisk111_pickupChannel, .findChannelByCallback = sccp_wrapper_asterisk111_findChannelWithCallback, .moh_start = sccp_asterisk_moh_start, .moh_stop = sccp_asterisk_moh_stop, .queue_control = sccp_asterisk_queue_control, .queue_control_data = sccp_asterisk_queue_control_data, .allocTempPBXChannel = sccp_wrapper_asterisk111_allocTempPBXChannel, .masqueradeHelper = sccp_wrapper_asterisk111_masqueradeHelper, .requestForeignChannel = sccp_wrapper_asterisk111_requestForeignChannel, .set_language = sccp_wrapper_asterisk111_setLanguage, .getExtensionState = sccp_wrapper_asterisk111_getExtensionState, .findPickupChannelByExtenLocked = sccp_wrapper_asterisk111_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #endif #if defined(__cplusplus) || defined(c_plusplus) static ast_module_load_result load_module(void) #else static int load_module(void) #endif { boolean_t res; /* check for existance of chan_skinny */ if (ast_module_check("chan_skinny.so")) { pbx_log(LOG_ERROR, "Chan_skinny is loaded. Please check modules.conf and remove chan_skinny before loading chan_sccp.\n"); return AST_MODULE_LOAD_DECLINE; } sched = ast_sched_context_create(); if (!sched) { pbx_log(LOG_WARNING, "Unable to create schedule context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } if (ast_sched_start_thread(sched)) { ast_sched_context_destroy(sched); sched = NULL; return AST_MODULE_LOAD_FAILURE; } /* make globals */ res = sccp_prePBXLoad(); if (!res) { return AST_MODULE_LOAD_DECLINE; } sccp_tech.capabilities = ast_format_cap_alloc(); ast_format_cap_add_all_by_type(sccp_tech.capabilities, AST_FORMAT_TYPE_AUDIO); io = io_context_create(); if (!io) { pbx_log(LOG_WARNING, "Unable to create I/O context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } //! \todo how can we handle this in a pbx independent way? if (!load_config()) { if (ast_channel_register(&sccp_tech)) { pbx_log(LOG_ERROR, "Unable to register channel class SCCP\n"); return AST_MODULE_LOAD_FAILURE; } } #ifdef HAVE_PBX_MESSAGE_H if (ast_msg_tech_register(&sccp_msg_tech)) { /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */ pbx_log(LOG_WARNING, "Unable to register message interface\n"); } #endif // ast_rtp_glue_register(&sccp_rtp); sccp_register_management(); sccp_register_cli(); sccp_register_dialplan_functions(); sccp_postPBX_load(); return AST_MODULE_LOAD_SUCCESS; } static int unload_module(void) { sccp_preUnload(); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP RTP protocol\n"); // ast_rtp_glue_unregister(&sccp_rtp); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP Channel Tech\n"); ast_channel_unregister(&sccp_tech); sccp_unregister_dialplan_functions(); sccp_unregister_cli(); sccp_mwi_module_stop(); #ifdef CS_SCCP_MANAGER sccp_unregister_management(); #endif #ifdef HAVE_PBX_MESSAGE_H ast_msg_tech_unregister(&sccp_msg_tech); #endif if (io) { io_context_destroy(io); io = NULL; } while (SCCP_REF_DESTROYED != sccp_refcount_isRunning()) { usleep(SCCP_TIME_TO_KEEP_REFCOUNTEDOBJECT); // give enough time for all schedules to end and refcounted object to be cleanup completely } if (sched) { pbx_log(LOG_NOTICE, "Cleaning up scheduled items:\n"); int scheduled_items = 0; ast_sched_dump(sched); while ((scheduled_items = ast_sched_runq(sched))) { pbx_log(LOG_NOTICE, "Cleaning up %d scheduled items... please wait\n", scheduled_items); usleep(ast_sched_wait(sched)); } ast_sched_context_destroy(sched); sched = NULL; } sccp_free(sccp_globals); pbx_log(LOG_NOTICE, "Running Cleanup\n"); #ifdef HAVE_LIBGC // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Collect a little:%d\n",GC_collect_a_little()); // CHECK_LEAKS(); // GC_gcollect(); #endif pbx_log(LOG_NOTICE, "Module chan_sccp unloaded\n"); return 0; } static int module_reload(void) { sccp_reload(); return 0; } #if defined(__cplusplus) || defined(c_plusplus) static struct ast_module_info __mod_info = { NULL, load_module, module_reload, unload_module, NULL, NULL, AST_MODULE, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)", ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, AST_BUILDOPT_SUM, AST_MODPRI_CHANNEL_DRIVER, NULL, }; static void __attribute__ ((constructor)) __reg_module(void) { ast_module_register(&__mod_info); } static void __attribute__ ((destructor)) __unreg_module(void) { ast_module_unregister(&__mod_info); } static const __attribute__ ((unused)) struct ast_module_info *ast_module_info = &__mod_info; #else AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Skinny Client Control Protocol (SCCP). SCCP-Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "')",.load = load_module,.unload = unload_module,.reload = module_reload,.load_pri = AST_MODPRI_DEFAULT,.nonoptreq = "chan_local" /* dependence on res_rtp_asterisk makes us unload to late */ /* .nonoptreq = "res_rtp_asterisk,chan_local" */ ); #endif PBX_CHANNEL_TYPE *sccp_search_remotepeer_locked(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data) { PBX_CHANNEL_TYPE *remotePeer = NULL; // struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); // // ((struct ao2_iterator *)iterator)->flags |= AO2_ITERATOR_DONTLOCK; // // for (; (remotePeer = ast_channel_iterator_next(iterator)); remotePeer = ast_channel_unref(remotePeer)) { // // if (found_cb(remotePeer, data)) { // // ast_channel_lock(remotePeer); // ast_channel_unref(remotePeer); // break; // } // // } // ast_channel_iterator_destroy(iterator); return remotePeer; } PBX_CHANNEL_TYPE *sccp_wrapper_asterisk111_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context) { struct ast_channel *target = NULL; /*!< Potential pickup target */ struct ast_channel_iterator *iter; if (!(iter = ast_channel_iterator_by_exten_new(exten, context))) { return NULL; } while ((target = ast_channel_iterator_next(iter))) { ast_channel_lock(target); if ((chan != target) && ast_can_pickup(target)) { ast_log(LOG_NOTICE, "%s pickup by %s\n", ast_channel_name(target), ast_channel_name(chan)); break; } ast_channel_unlock(target); target = ast_channel_unref(target); } ast_channel_iterator_destroy(iter); return target; }
722,276
./chan-sccp-b/src/pbx_impl/ast/ast108.c
/*! * \file ast108.c * \brief SCCP PBX Asterisk Wrapper Class * \author Marcello Ceshia * \author Diederik de Groot <ddegroot [at] users.sourceforge.net> * \note This program is free software and may be modified and distributed under the terms of the GNU Public License. * See the LICENSE file at the top of the source tree. * * $Date: 2010-10-23 20:04:30 +0200 (Sat, 23 Oct 2010) $ * $Revision: 2044 $ */ #include <config.h> #include "../../common.h" #include "ast108.h" #include <signal.h> #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #include <asterisk/sched.h> #include <asterisk/netsock2.h> #if HAVE_PBX_CEL_H #include <asterisk/cel.h> #endif #define new avoid_cxx_new_keyword #include <asterisk/rtp_engine.h> #undef new #if defined(__cplusplus) || defined(c_plusplus) } #endif #undef HAVE_PBX_MESSAGE_H struct sched_context *sched = 0; struct io_context *io = 0; static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk18_request(const char *type, format_t format, const PBX_CHANNEL_TYPE * requestor, void *data, int *cause); static int sccp_wrapper_asterisk18_call(PBX_CHANNEL_TYPE * chan, char *addr, int timeout); static int sccp_wrapper_asterisk18_answer(PBX_CHANNEL_TYPE * chan); static PBX_FRAME_TYPE *sccp_wrapper_asterisk18_rtp_read(PBX_CHANNEL_TYPE * ast); static int sccp_wrapper_asterisk18_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame); static int sccp_wrapper_asterisk18_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen); static int sccp_wrapper_asterisk18_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan); static enum ast_bridge_result sccp_wrapper_asterisk18_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms); static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text); static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit); static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration); static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen); int sccp_wrapper_asterisk18_hangup(PBX_CHANNEL_TYPE * ast_channel); boolean_t sccp_wrapper_asterisk18_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId); static boolean_t sccp_wrapper_asterisk18_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec); //static int sccp_wrapper_asterisk18_setOption(PBX_CHANNEL_TYPE *ast, int option, void *data, int datalen); int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control); int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen); static int sccp_wrapper_asterisk18_devicestate(void *data); PBX_CHANNEL_TYPE *sccp_wrapper_asterisk18_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context); #if defined(__cplusplus) || defined(c_plusplus) /*! * \brief SCCP Tech Structure */ static struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, description: "Skinny Client Control Protocol (SCCP)", capabilities: AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_SLINEAR16 | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A | AST_FORMAT_H264 | AST_FORMAT_H263_PLUS, properties: AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, requester: sccp_wrapper_asterisk18_request, devicestate: sccp_wrapper_asterisk18_devicestate, send_digit_begin: sccp_wrapper_recvdigit_begin, send_digit_end: sccp_wrapper_recvdigit_end, call: sccp_wrapper_asterisk18_call, hangup: sccp_wrapper_asterisk18_hangup, answer: sccp_wrapper_asterisk18_answer, read: sccp_wrapper_asterisk18_rtp_read, write: sccp_wrapper_asterisk18_rtp_write, send_text: sccp_pbx_sendtext, send_image: NULL, send_html: sccp_pbx_sendHTML, exception: NULL, bridge: sccp_wrapper_asterisk18_rtpBridge, early_bridge: NULL, indicate: sccp_wrapper_asterisk18_indicate, fixup: sccp_wrapper_asterisk18_fixup, setoption: NULL, queryoption: NULL, transfer: NULL, write_video: sccp_wrapper_asterisk18_rtp_write, write_text: NULL, bridged_channel: NULL, func_channel_read: sccp_wrapper_asterisk_channel_read, func_channel_write: sccp_asterisk_pbx_fktChannelWrite, get_base_channel: NULL, set_base_channel: NULL, // setoption: sccp_wrapper_asterisk18_setOption, /* *INDENT-ON* */ }; #else /*! * \brief SCCP Tech Structure */ const struct ast_channel_tech sccp_tech = { /* *INDENT-OFF* */ .type = SCCP_TECHTYPE_STR, .description = "Skinny Client Control Protocol (SCCP)", // we could use the skinny_codec = ast_codec mapping here to generate the list of capabilities .capabilities = AST_FORMAT_SLINEAR16 | AST_FORMAT_SLINEAR | AST_FORMAT_ALAW | AST_FORMAT_ULAW | AST_FORMAT_GSM | AST_FORMAT_G723_1 | AST_FORMAT_G729A, .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER, .requester = sccp_wrapper_asterisk18_request, .devicestate = sccp_wrapper_asterisk18_devicestate, .call = sccp_wrapper_asterisk18_call, .hangup = sccp_wrapper_asterisk18_hangup, .answer = sccp_wrapper_asterisk18_answer, .read = sccp_wrapper_asterisk18_rtp_read, .write = sccp_wrapper_asterisk18_rtp_write, .write_video = sccp_wrapper_asterisk18_rtp_write, .indicate = sccp_wrapper_asterisk18_indicate, .fixup = sccp_wrapper_asterisk18_fixup, .transfer = sccp_pbx_transfer, .bridge = sccp_wrapper_asterisk18_rtpBridge, //.early_bridge = ast_rtp_early_bridge, //.bridged_channel = .send_text = sccp_pbx_sendtext, .send_html = sccp_pbx_sendHTML, //.send_image = .func_channel_read = sccp_wrapper_asterisk_channel_read, .func_channel_write = sccp_asterisk_pbx_fktChannelWrite, .send_digit_begin = sccp_wrapper_recvdigit_begin, .send_digit_end = sccp_wrapper_recvdigit_end, //.write_text = //.write_video = //.cc_callback = // ccss, new >1.6.0 //.exception = // new >1.6.0 // .setoption = sccp_wrapper_asterisk18_setOption, //.queryoption = // new >1.6.0 //.get_pvt_uniqueid = sccp_pbx_get_callid, // new >1.6.0 //.get_base_channel = //.set_base_channel = /* *INDENT-ON* */ }; #endif static int sccp_wrapper_asterisk18_devicestate(void *data) { int res = AST_DEVICE_UNKNOWN; char *lineName = (char *) data; char *deviceId = NULL; sccp_channelstate_t state; if ((deviceId = strchr(lineName, '@'))) { *deviceId = '\0'; deviceId++; } state = sccp_hint_getLinestate(lineName, deviceId); switch (state) { case SCCP_CHANNELSTATE_DOWN: case SCCP_CHANNELSTATE_ONHOOK: res = AST_DEVICE_NOT_INUSE; break; case SCCP_CHANNELSTATE_RINGING: res = AST_DEVICE_RINGING; break; case SCCP_CHANNELSTATE_HOLD: res = AST_DEVICE_ONHOLD; break; case SCCP_CHANNELSTATE_INVALIDNUMBER: res = AST_DEVICE_INVALID; break; case SCCP_CHANNELSTATE_BUSY: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_DND: res = AST_DEVICE_BUSY; break; case SCCP_CHANNELSTATE_CONGESTION: case SCCP_CHANNELSTATE_ZOMBIE: case SCCP_CHANNELSTATE_SPEEDDIAL: case SCCP_CHANNELSTATE_INVALIDCONFERENCE: res = AST_DEVICE_UNAVAILABLE; break; case SCCP_CHANNELSTATE_RINGOUT: case SCCP_CHANNELSTATE_DIALING: case SCCP_CHANNELSTATE_DIGITSFOLL: case SCCP_CHANNELSTATE_PROGRESS: case SCCP_CHANNELSTATE_CALLWAITING: res = AST_DEVICE_RINGINUSE; break; case SCCP_CHANNELSTATE_CONNECTEDCONFERENCE: case SCCP_CHANNELSTATE_OFFHOOK: case SCCP_CHANNELSTATE_GETDIGITS: case SCCP_CHANNELSTATE_CONNECTED: case SCCP_CHANNELSTATE_PROCEED: case SCCP_CHANNELSTATE_BLINDTRANSFER: case SCCP_CHANNELSTATE_CALLTRANSFER: case SCCP_CHANNELSTATE_CALLCONFERENCE: case SCCP_CHANNELSTATE_CALLPARK: case SCCP_CHANNELSTATE_CALLREMOTEMULTILINE: res = AST_DEVICE_INUSE; break; } sccp_log((DEBUGCAT_HINT)) (VERBOSE_PREFIX_4 "SCCP: (sccp_asterisk_devicestate) PBX requests state for '%s' - state %s\n", (char *) lineName, ast_devstate2str(res)); return res; } /*! * \brief Convert an array of skinny_codecs (enum) to ast_codec_prefs * * \param skinny_codecs Array of Skinny Codecs * \param astCodecPref Array of PBX Codec Preferences * * \return bit array fmt/Format of ast_format_type (int) * * \todo check bitwise operator (not sure) - DdG */ int skinny_codecs2pbx_codec_pref(skinny_codec_t * skinny_codecs, struct ast_codec_pref *astCodecPref) { uint32_t i; int res_codec = 0; for (i = 1; i < SKINNY_MAX_CAPABILITIES; i++) { if (skinny_codecs[i]) { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "adding codec to ast_codec_pref\n"); res_codec |= ast_codec_pref_append(astCodecPref, skinny_codec2pbx_codec(skinny_codecs[i])); } } return res_codec; } static boolean_t sccp_wrapper_asterisk18_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec); #define RTP_NEW_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_new_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } #define RTP_CHANGE_SOURCE(_c,_log) \ if(c->rtp.audio.rtp) { \ ast_rtp_change_source(c->rtp.audio.rtp); \ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE))(VERBOSE_PREFIX_3 "SCCP: " #_log "\n"); \ } static void get_skinnyFormats(format_t format, skinny_codec_t codecs[], size_t size) { unsigned int x; unsigned len = 0; if (!size) return; for (x = 0; x < ARRAY_LEN(skinny2pbx_codec_maps) && len <= size; x++) { if (skinny2pbx_codec_maps[x].pbx_codec & format) { codecs[len++] = skinny2pbx_codec_maps[x].skinny_codec; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "map ast codec " UI64FMT " to %d\n", (ULONG) (skinny2pbx_codec_maps[x].pbx_codec & format), skinny2pbx_codec_maps[x].skinny_codec); } } } /*! \brief Get the name of a format * \note replacement for ast_getformatname * \param format id of format * \return A static string containing the name of the format or "unknown" if unknown. */ char *pbx_getformatname(format_t format) { return ast_getformatname(format); } /*! * \brief Get the names of a set of formats * \note replacement for ast_getformatname_multiple * \param buf a buffer for the output string * \param size size of buf (bytes) * \param format the format (combined IDs of codecs) * Prints a list of readable codec names corresponding to "format". * ex: for format=AST_FORMAT_GSM|AST_FORMAT_SPEEX|AST_FORMAT_ILBC it will return "0x602 (GSM|SPEEX|ILBC)" * \return The return value is buf. */ char *pbx_getformatname_multiple(char *buf, size_t size, format_t format) { return ast_getformatname_multiple(buf, size, format & AST_FORMAT_AUDIO_MASK); } /*! * \brief start monitoring thread of chan_sccp * \param data * * \lock * - monitor_lock */ void *sccp_do_monitor(void *data) { int res; /* This thread monitors all the interfaces which are not yet in use (and thus do not have a separate thread) indefinitely */ /* From here on out, we die whenever asked */ for (;;) { pthread_testcancel(); /* Wait for sched or io */ res = ast_sched_wait(sched); if ((res < 0) || (res > 1000)) { res = 1000; } res = ast_io_wait(io, res); if (res > 20) { ast_debug(1, "SCCP: ast_io_wait ran %d all at once\n", res); } ast_mutex_lock(&GLOB(monitor_lock)); res = ast_sched_runq(sched); if (res >= 20) { ast_debug(1, "SCCP: ast_sched_runq ran %d all at once\n", res); } ast_mutex_unlock(&GLOB(monitor_lock)); if (GLOB(monitor_thread) == AST_PTHREADT_STOP) { return 0; } } /* Never reached */ return NULL; } /*! * \brief Read from an Asterisk Channel * \param ast Asterisk Channel as ast_channel * * \called_from_asterisk * * \note not following the refcount rules... channel is already retained */ static PBX_FRAME_TYPE *sccp_wrapper_asterisk18_rtp_read(PBX_CHANNEL_TYPE * ast) { sccp_channel_t *c = NULL; PBX_FRAME_TYPE *frame = NULL; if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return &ast_null_frame; } if (!c->rtp.audio.rtp) { return &ast_null_frame; } switch (ast->fdno) { case 0: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 0); /* RTP Audio */ break; case 1: frame = ast_rtp_instance_read(c->rtp.audio.rtp, 1); /* RTCP Control Channel */ break; #ifdef CS_SCCP_VIDEO case 2: frame = ast_rtp_instance_read(c->rtp.video.rtp, 0); /* RTP Video */ break; case 3: frame = ast_rtp_instance_read(c->rtp.video.rtp, 1); /* RTCP Control Channel for video */ break; #endif default: frame = &ast_null_frame; break; } if (frame->frametype == AST_FRAME_VOICE) { #ifdef CS_SCCP_CONFERENCE if (c->conference && (AST_FORMAT_SLINEAR != ast->readformat)) { ast_set_read_format(ast, AST_FORMAT_SLINEAR); } else #endif { if (!(frame->subclass.codec & (ast->rawreadformat & AST_FORMAT_AUDIO_MASK))) { //sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Channel %s changed format from %s(%d) to %s(%d)\n", DEV_ID_LOG(c->device), ast->name, pbx_getformatname(ast->nativeformats), ast->nativeformats, pbx_getformatname(frame->subclass), frame->subclass); #ifndef CS_EXPERIMENTAL_CODEC sccp_wrapper_asterisk18_setReadFormat(c, c->rtp.audio.readFormat); #endif } if (frame->subclass.codec != (ast->nativeformats & AST_FORMAT_AUDIO_MASK)) { if (!(frame->subclass.codec & skinny_codecs2pbx_codecs(c->capabilities.audio))) { ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n", ast_getformatname(frame->subclass.codec), ast->name); return &ast_null_frame; } ast_debug(1, "SCCP: format changed to %s\n", ast_getformatname(frame->subclass.codec)); ast->nativeformats = (ast->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | frame->subclass.codec; ast_set_read_format(ast, ast->readformat); ast_set_write_format(ast, ast->writeformat); } } } return frame; } /*! * \brief Find Asterisk/PBX channel by linkid * * \param ast pbx channel * \param data linkId as void * * * \return int * * \todo I don't understand what this functions returns */ static int pbx_find_channel_by_linkid(PBX_CHANNEL_TYPE * ast, const void *data) { const char *linkId = (char *) data; if (!data) return 0; return !ast->pbx && ast->linkedid && (!strcasecmp(ast->linkedid, linkId)) && !ast->masq; } /*! * \brief Update Connected Line * \param channel Asterisk Channel as ast_channel * \param data Asterisk Data * \param datalen Asterisk Data Length */ static void sccp_wrapper_asterisk18_connectedline(sccp_channel_t * channel, const void *data, size_t datalen) { PBX_CHANNEL_TYPE *ast = channel->owner; sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_3 "%s: Got connected line update, connected.id.number=%s, connected.id.name=%s, reason=%d\n", pbx_channel_name(ast), ast->connected.id.number.str ? ast->connected.id.number.str : "(nil)", ast->connected.id.name.str ? ast->connected.id.name.str : "(nil)", ast->connected.source); // sccp_channel_display_callInfo(channel); /* set the original calling/called party if the reason is a transfer */ if (ast->connected.source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER || ast->connected.source == AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER_ALERTING) { if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Destination\n"); if (ast->connected.id.number.str && !sccp_strlen_zero(ast->connected.id.number.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, ast->connected.id.number.str, sizeof(channel->callInfo.originalCallingPartyNumber)); channel->callInfo.originalCallingParty_valid = 1; } if (ast->connected.id.name.str && !sccp_strlen_zero(ast->connected.id.name.str)) { sccp_copy_string(channel->callInfo.originalCallingPartyName, ast->connected.id.name.str, sizeof(channel->callInfo.originalCallingPartyName)); } if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.callingPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } else { sccp_log(DEBUGCAT_CHANNEL)("SCCP: (connectedline) Transferee\n"); if (channel->callInfo.callingParty_valid) { sccp_copy_string(channel->callInfo.originalCallingPartyNumber, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyNumber)); sccp_copy_string(channel->callInfo.originalCallingPartyName, channel->callInfo.callingPartyNumber, sizeof(channel->callInfo.originalCallingPartyName)); channel->callInfo.originalCallingParty_valid = 1; } if (channel->callInfo.calledParty_valid) { sccp_copy_string(channel->callInfo.originalCalledPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyNumber)); sccp_copy_string(channel->callInfo.originalCalledPartyName, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.originalCalledPartyName)); channel->callInfo.originalCalledParty_valid = 1; sccp_copy_string(channel->callInfo.lastRedirectingPartyName, channel->callInfo.calledPartyName, sizeof(channel->callInfo.lastRedirectingPartyName)); sccp_copy_string(channel->callInfo.lastRedirectingPartyNumber, channel->callInfo.calledPartyNumber, sizeof(channel->callInfo.lastRedirectingPartyNumber)); channel->callInfo.lastRedirectingParty_valid = 1; } } channel->callInfo.originalCdpnRedirectReason = channel->callInfo.lastRedirectingReason; channel->callInfo.lastRedirectingReason = 0; // need to figure out these codes } if (channel->calltype == SKINNY_CALLTYPE_INBOUND) { if (ast->connected.id.number.str && !sccp_strlen_zero(ast->connected.id.number.str)) sccp_copy_string(channel->callInfo.callingPartyNumber, ast->connected.id.number.str, sizeof(channel->callInfo.callingPartyNumber)); if (ast->connected.id.name.str && !sccp_strlen_zero(ast->connected.id.name.str)) sccp_copy_string(channel->callInfo.callingPartyName, ast->connected.id.name.str, sizeof(channel->callInfo.callingPartyName)); } else { if (ast->connected.id.number.str && !sccp_strlen_zero(ast->connected.id.number.str)) sccp_copy_string(channel->callInfo.calledPartyNumber, ast->connected.id.number.str, sizeof(channel->callInfo.calledPartyNumber)); if (ast->connected.id.name.str && !sccp_strlen_zero(ast->connected.id.name.str)) sccp_copy_string(channel->callInfo.calledPartyName, ast->connected.id.name.str, sizeof(channel->callInfo.calledPartyName)); } sccp_channel_display_callInfo(channel); sccp_channel_send_callinfo2(channel); } static int sccp_wrapper_asterisk18_indicate(PBX_CHANNEL_TYPE * ast, int ind, const void *data, size_t datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(ast))) return -1; if (!(d = sccp_channel_getDevice_retained(c))) { switch (ind) { case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk18_connectedline(c, data, datalen); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); res = 0; break; default: res = -1; break; } c = sccp_channel_release(c); return res; } if (c->state == SCCP_CHANNELSTATE_DOWN) { c = sccp_channel_release(c); d = sccp_device_release(d); return -1; } sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: Asterisk indicate '%d' condition on channel %s\n", DEV_ID_LOG(d), ind, ast->name); /* when the rtp media stream is open we will let asterisk emulate the tones */ res = (((c->rtp.audio.readState != SCCP_RTP_STATUS_INACTIVE) || (d && d->earlyrtp)) ? -1 : 0); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: readState: %d\n", DEV_ID_LOG(d), c->rtp.audio.readState); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: res: %d\n", DEV_ID_LOG(d), res); sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "%s: rtp?: %s\n", DEV_ID_LOG(d), (c->rtp.audio.rtp) ? "yes" : "no"); switch (ind) { case AST_CONTROL_RINGING: if (SKINNY_CALLTYPE_OUTBOUND == c->calltype) { // Allow signalling of RINGOUT only on outbound calls. // Otherwise, there are some issues with late arrival of ringing // indications on ISDN calls (chan_lcr, chan_dahdi) (-DD). sccp_indicate(d, c, SCCP_CHANNELSTATE_RINGOUT); struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; /*! \todo handle multiple remotePeers i.e. DIAL(SCCP/400&SIP/300), find smallest common codecs, what order to use ? */ PBX_CHANNEL_TYPE *remotePeer; for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { if (pbx_find_channel_by_linkid(remotePeer, (void *) ast->linkedid)) { char buf[512]; sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(remotePeer); if (remoteSccpChannel) { sccp_multiple_codecs2str(buf, sizeof(buf) - 1, remoteSccpChannel->preferences.audio, ARRAY_LEN(remoteSccpChannel->preferences.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote preferences: %s\n", buf); uint8_t x, y, z; z = 0; for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { c->remoteCapabilities.audio[z++] = remoteSccpChannel->preferences.audio[x]; break; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote nativeformats: %s\n", pbx_getformatname_multiple(buf, sizeof(buf) - 1, remotePeer->nativeformats)); get_skinnyFormats(remotePeer->nativeformats, c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); } sccp_multiple_codecs2str(buf, sizeof(buf) - 1, c->remoteCapabilities.audio, ARRAY_LEN(c->remoteCapabilities.audio)); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote caps: %s\n", buf); ast_channel_unref(remotePeer); break; } } ast_channel_iterator_destroy(iterator); } break; case AST_CONTROL_BUSY: sccp_indicate(d, c, SCCP_CHANNELSTATE_BUSY); break; case AST_CONTROL_CONGESTION: sccp_indicate(d, c, SCCP_CHANNELSTATE_CONGESTION); break; case AST_CONTROL_PROGRESS: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROGRESS); res = -1; break; case AST_CONTROL_PROCEEDING: sccp_indicate(d, c, SCCP_CHANNELSTATE_PROCEED); res = -1; break; case AST_CONTROL_SRCCHANGE: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Source CHANGE request\n"); if (c->rtp.audio.rtp) ast_rtp_instance_change_source(c->rtp.audio.rtp); res = 0; break; case AST_CONTROL_SRCUPDATE: /* Source media has changed. */ sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Source UPDATE request\n"); if (c->rtp.audio.rtp) ast_rtp_instance_update_source(c->rtp.audio.rtp); sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP:c->state: %d\n", c->state); if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: force CONNECT (AST_CONTROL_SRCUPDATE)\n"); sccp_indicate(d, c, SCCP_CHANNELSTATE_CONNECTED); } res = 0; break; /* when the bridged channel hold/unhold the call we are notified here */ case AST_CONTROL_HOLD: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: HOLD request\n"); sccp_asterisk_moh_start(ast, (const char *) data, c->musicclass); if (c->rtp.audio.rtp) { ast_rtp_instance_update_source(c->rtp.audio.rtp); } res = 0; break; case AST_CONTROL_UNHOLD: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: UNHOLD request\n"); sccp_asterisk_moh_stop(ast); if (c->rtp.audio.rtp) { ast_rtp_instance_update_source(c->rtp.audio.rtp); } res = 0; break; case AST_CONTROL_CONNECTED_LINE: sccp_wrapper_asterisk18_connectedline(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_REDIRECTING: sccp_asterisk_redirectedUpdate(c, data, datalen); sccp_indicate(d, c, c->state); res = 0; break; case AST_CONTROL_VIDUPDATE: /* Request a video frame update */ #ifdef CS_SCCP_VIDEO if (c->rtp.video.rtp && d && sccp_device_isVideoSupported(d)) { d->protocol->sendFastPictureUpdate(d, c); res = 0; } else #endif { res = -1; } break; #ifdef CS_AST_CONTROL_INCOMPLETE case AST_CONTROL_INCOMPLETE: /*!< Indication that the extension dialed is incomplete */ /* \todo implement dial continuation by: * - display message incomplete number * - adding time to channel->scheduler.digittimeout * - rescheduling sccp_pbx_sched_dial */ #ifdef CS_EXPERIMENTAL if (c->scheduler.digittimeout) { SCCP_SCHED_DEL(c->scheduler.digittimeout); } sccp_indicate(d, c, SCCP_CHANNELSTATE_DIGITSFOLL); c->scheduler.digittimeout = PBX(sched_add) (c->enbloc.digittimeout, sccp_pbx_sched_dial, c); #endif res = 0; break; #endif #ifdef CS_EXPERIMENTAL case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */ break; #endif case -1: // Asterisk prod the channel res = -1; break; default: sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: Don't know how to indicate condition %d\n", ind); res = -1; } //ast_cond_signal(&c->astStateCond); d = sccp_device_release(d); c = sccp_channel_release(c); sccp_log((DEBUGCAT_PBX | DEBUGCAT_INDICATE)) (VERBOSE_PREFIX_3 "SCCP: send asterisk result %d\n", res); return res; } /*! * \brief Write to an Asterisk Channel * \param ast Channel as ast_channel * \param frame Frame as ast_frame * * \called_from_asterisk * * \note // not following the refcount rules... channel is already retained */ static int sccp_wrapper_asterisk18_rtp_write(PBX_CHANNEL_TYPE * ast, PBX_FRAME_TYPE * frame) { int res = 0; sccp_channel_t *c = NULL; // if (!(c = get_sccp_channel_from_pbx_channel(ast))) // not following the refcount rules... channel is already retained if (!(c = CS_AST_CHANNEL_PVT(ast))) { // not following the refcount rules... channel is already retained return -1; } if (c) { switch (frame->frametype) { case AST_FRAME_VOICE: // checking for samples to transmit if (!frame->samples) { if (strcasecmp(frame->src, "ast_prod")) { pbx_log(LOG_ERROR, "%s: Asked to transmit frame type %d with no samples.\n", (char *) c->currentDeviceId, (int) frame->frametype); } else { sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Asterisk prodded channel %s.\n", (char *) c->currentDeviceId, ast->name); } } //CODEC_TRANSLATION_FIX_AFTER_MOH if (frame->subclass.codec != ast->rawwriteformat) { /* asterisk channel.c:4911 temporary fix */ if ((!(frame->subclass.codec & ast->nativeformats)) && (ast->writeformat != frame->subclass.codec)) { char s1[512], s2[512], s3[512]; sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_2 "%s: Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n -> Forcing writeformat to %s to fix this issue.\n", c->currentDeviceId, ast_getformatname(frame->subclass.codec), ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK), ast_getformatname_multiple(s2, sizeof(s2), ast->readformat), ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat), ast_getformatname(frame->subclass.codec)); ast_set_write_format(ast, frame->subclass.codec); } frame = (ast->writetrans) ? ast_translate(ast->writetrans, frame, 0) : frame; } //CODEC_TRANSLATION_FIX_AFTER_MOH if (c->rtp.audio.rtp && frame) { res = ast_rtp_instance_write(c->rtp.audio.rtp, frame); } break; case AST_FRAME_IMAGE: case AST_FRAME_VIDEO: #ifdef CS_SCCP_VIDEO if (c->rtp.video.writeState == SCCP_RTP_STATUS_INACTIVE && c->rtp.video.rtp && c->state != SCCP_CHANNELSTATE_HOLD // && (c->device->capability & frame->subclass) ) { int codec = pbx_codec2skinny_codec((frame->subclass.codec & AST_FORMAT_VIDEO_MASK)); sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_3 "%s: got video frame %d\n", (char *) c->currentDeviceId, codec); if (0 != codec) { c->rtp.video.writeFormat = codec; sccp_channel_openMultiMediaChannel(c); } } if (c->rtp.video.rtp && frame && (c->rtp.video.writeState & SCCP_RTP_STATUS_ACTIVE) != 0) { res = ast_rtp_instance_write(c->rtp.video.rtp, frame); } #endif break; case AST_FRAME_TEXT: case AST_FRAME_MODEM: default: pbx_log(LOG_WARNING, "%s: Can't send %d type frames with SCCP write on channel %s\n", (char *) c->currentDeviceId, frame->frametype, ast->name); break; } } // c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk18_sendDigits(const sccp_channel_t * channel, const char *digits) { if (!channel || !channel->owner) { pbx_log(LOG_WARNING, "No channel to send digits to\n"); return 0; } PBX_CHANNEL_TYPE *pbx_channel = channel->owner; int i; PBX_FRAME_TYPE f; f = ast_null_frame; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digits '%s'\n", (char *) channel->currentDeviceId, digits); // We don't just call sccp_pbx_senddigit due to potential overhead, and issues with locking f.src = "SCCP"; // CS_AST_NEW_FRAME_STRUCT // f.frametype = AST_FRAME_DTMF_BEGIN; // ast_queue_frame(pbx_channel, &f); for (i = 0; digits[i] != '\0'; i++) { sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: Sending digit %c\n", (char *) channel->currentDeviceId, digits[i]); f.frametype = AST_FRAME_DTMF_END; // Sending only the dmtf will force asterisk to start with DTMF_BEGIN and schedule the DTMF_END f.subclass.integer = digits[i]; // f.samples = SCCP_MIN_DTMF_DURATION * 8; f.len = SCCP_MIN_DTMF_DURATION; f.src = "SEND DIGIT"; ast_queue_frame(pbx_channel, &f); } return 1; } static int sccp_wrapper_asterisk18_sendDigit(const sccp_channel_t * channel, const char digit) { char digits[3] = "\0\0"; digits[0] = digit; sccp_log((DEBUGCAT_PBX | DEBUGCAT_CHANNEL)) (VERBOSE_PREFIX_3 "%s: got a single digit '%c' -> '%s'\n", channel->currentDeviceId, digit, digits); return sccp_wrapper_asterisk18_sendDigits(channel, digits); } static void sccp_wrapper_asterisk18_setCalleridPresence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (CALLERID_PRESENCE_FORBIDDEN == channel->callInfo.presentation) { pbx_channel->caller.id.name.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; pbx_channel->caller.id.number.presentation |= AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED; } } static int sccp_wrapper_asterisk18_setNativeAudioFormats(const sccp_channel_t * channel, skinny_codec_t codec[], int length) { format_t new_nativeformats = 0; int i; ast_debug(10, "%s: set native Formats length: %d\n", (char *) channel->currentDeviceId, length); for (i = 0; i < length; i++) { new_nativeformats |= skinny_codec2pbx_codec(codec[i]); ast_debug(10, "%s: set native Formats to %d, skinny: %d\n", (char *) channel->currentDeviceId, (int) channel->owner->nativeformats, codec[i]); } if (channel->owner->nativeformats != new_nativeformats) { channel->owner->nativeformats = new_nativeformats; char codecs[512]; sccp_multiple_codecs2str(codecs, sizeof(codecs) - 1, codec, length); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_2 "%s: updated native Formats to %d, length: %d, skinny: [%s]\n", (char *) channel->currentDeviceId, (int) channel->owner->nativeformats, length, codecs); } return 1; } static int sccp_wrapper_asterisk18_setNativeVideoFormats(const sccp_channel_t * channel, uint32_t formats) { return 1; } boolean_t sccp_wrapper_asterisk18_allocPBXChannel(sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel, const char *linkedId) { sccp_line_t *line = NULL; (*pbx_channel) = ast_channel_alloc(0, AST_STATE_DOWN, channel->line->cid_num, channel->line->cid_name, channel->line->accountcode, channel->dialedNumber, channel->line->context, linkedId, channel->line->amaflags, "SCCP/%s-%08X", channel->line->name, channel->callid); if ((*pbx_channel) == NULL) { return FALSE; } if (!channel || !channel->line) { return FALSE; } line = channel->line; (*pbx_channel)->tech = &sccp_tech; (*pbx_channel)->tech_pvt = sccp_channel_retain(channel); memset((*pbx_channel)->exten, 0, sizeof((*pbx_channel)->exten)); sccp_copy_string((*pbx_channel)->context, line->context, sizeof((*pbx_channel)->context)); if (!sccp_strlen_zero(line->language)) ast_string_field_set((*pbx_channel), language, line->language); if (!sccp_strlen_zero(line->accountcode)) ast_string_field_set((*pbx_channel), accountcode, line->accountcode); if (!sccp_strlen_zero(line->musicclass)) ast_string_field_set((*pbx_channel), musicclass, line->musicclass); if (line->amaflags) (*pbx_channel)->amaflags = line->amaflags; if (line->callgroup) (*pbx_channel)->callgroup = line->callgroup; #if CS_SCCP_PICKUP if (line->pickupgroup) (*pbx_channel)->pickupgroup = line->pickupgroup; #endif (*pbx_channel)->priority = 1; (*pbx_channel)->adsicpe = AST_ADSI_UNAVAILABLE; /** the the tonezone using language information */ if (!sccp_strlen_zero(line->language) && ast_get_indication_zone(line->language)) { (*pbx_channel)->zone = ast_get_indication_zone(line->language); /* this will core asterisk on hangup */ } ast_module_ref(ast_module_info->self); channel->owner = ast_channel_ref((*pbx_channel)); return TRUE; } static boolean_t sccp_wrapper_asterisk18_masqueradeHelper(PBX_CHANNEL_TYPE * pbxChannel, PBX_CHANNEL_TYPE * pbxTmpChannel) { const char *context; const char *exten; int priority; pbx_moh_stop(pbxChannel); ast_channel_lock_both(pbxChannel, pbxTmpChannel); context = ast_strdupa(pbxChannel->context); exten = ast_strdupa(pbxChannel->exten); priority = pbxChannel->priority; pbx_channel_unlock(pbxChannel); pbx_channel_unlock(pbxTmpChannel); /* in older versions we need explicit locking, around the masqueration */ pbx_channel_lock(pbxChannel); if (pbx_channel_masquerade(pbxTmpChannel, pbxChannel)) { return FALSE; } pbx_channel_lock(pbxTmpChannel); pbx_do_masquerade(pbxTmpChannel); pbx_channel_unlock(pbxTmpChannel); pbx_channel_set_hangupcause(pbxChannel, AST_CAUSE_NORMAL_UNSPECIFIED); pbx_channel_unlock(pbxChannel); /* when returning from bridge, the channel will continue at the next priority */ ast_explicit_goto(pbxTmpChannel, context, exten, priority + 1); return TRUE; } static boolean_t sccp_wrapper_asterisk18_allocTempPBXChannel(PBX_CHANNEL_TYPE * pbxSrcChannel, PBX_CHANNEL_TYPE ** pbxDstChannel) { if (!pbxSrcChannel) { pbx_log(LOG_ERROR, "SCCP: (alloc_TempPBXChannel) no pbx channel provided\n"); return FALSE; } (*pbxDstChannel) = ast_channel_alloc(0, pbxSrcChannel->_state, 0, 0, pbxSrcChannel->accountcode, pbxSrcChannel->exten, pbxSrcChannel->context, pbxSrcChannel->linkedid, pbxSrcChannel->amaflags, "TMP/%s", pbxSrcChannel->name); if ((*pbxDstChannel) == NULL) { pbx_log(LOG_ERROR, "SCCP: (alloc_TempPBXChannel) create pbx channel failed\n"); return FALSE; } (*pbxDstChannel)->writeformat = pbxSrcChannel->writeformat; (*pbxDstChannel)->readformat = pbxSrcChannel->readformat; return TRUE; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk18_requestForeignChannel(const char *type, pbx_format_type format, const PBX_CHANNEL_TYPE * requestor, void *data) { PBX_CHANNEL_TYPE *chan; int cause; if (!(chan = ast_request(type, format, requestor, data, &cause))) { pbx_log(LOG_ERROR, "SCCP: Requested channel could not be created, cause: %d", cause); return NULL; } return chan; } int sccp_wrapper_asterisk18_hangup(PBX_CHANNEL_TYPE * ast_channel) { sccp_channel_t *c; PBX_CHANNEL_TYPE *channel_owner = NULL; int res = -1; if ((c = get_sccp_channel_from_pbx_channel(ast_channel))) { channel_owner = c->owner; if (ast_test_flag(ast_channel, AST_FLAG_ANSWERED_ELSEWHERE) || ast_channel->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: This call was answered elsewhere\n"); c->answered_elsewhere = TRUE; } res = sccp_pbx_hangup(c); c->owner = NULL; if (0 == res) { sccp_channel_release(c); //this only releases the get_sccp_channel_from_pbx_channel } } //after this moment c might have gone already ast_channel->tech_pvt = NULL; c = c ? sccp_channel_release(c) : NULL; if (channel_owner) { channel_owner = ast_channel_unref(channel_owner); } ast_module_unref(ast_module_info->self); return res; } /*! * \brief Parking Thread Arguments Structure */ struct parkingThreadArg { PBX_CHANNEL_TYPE *bridgedChannel; PBX_CHANNEL_TYPE *hostChannel; const sccp_device_t *device; }; /*! * \brief Channel Park Thread * This thread doing the park magic and sends an displaynotify with the park position to the initial device (@see struct parkingThreadArg) * * \param data struct parkingThreadArg with host and bridged channel together with initial device */ static void *sccp_wrapper_asterisk18_park_thread(void *data) { struct parkingThreadArg *arg; PBX_FRAME_TYPE *f; char extstr[20]; int ext; int res; arg = (struct parkingThreadArg *) data; f = ast_read(arg->bridgedChannel); if (f) ast_frfree(f); res = ast_park_call(arg->bridgedChannel, arg->hostChannel, 0, "", &ext); if (!res) { extstr[0] = 128; extstr[1] = SKINNY_LBL_CALL_PARK_AT; sprintf(&extstr[2], " %d", ext); sccp_dev_displaynotify((sccp_device_t *) arg->device, extstr, 10); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Parked channel %s on %d\n", DEV_ID_LOG(arg->device), arg->bridgedChannel->name, ext); } ast_hangup(arg->hostChannel); ast_free(arg); return NULL; } /*! * \brief Park the bridge channel of hostChannel * This function prepares the host and the bridged channel to be ready for parking. * It clones the pbx channel of both sides forward them to the park_thread * * \param hostChannel initial channel that request the parking * \todo we have a codec issue after unpark a call * \todo copy connected line info * */ static sccp_parkresult_t sccp_wrapper_asterisk18_park(const sccp_channel_t * hostChannel) { pthread_t th; struct parkingThreadArg *arg; PBX_CHANNEL_TYPE *pbx_bridgedChannelClone, *pbx_hostChannelClone; PBX_CHANNEL_TYPE *bridgedChannel = NULL; bridgedChannel = ast_bridged_channel(hostChannel->owner); if (!bridgedChannel) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX channel for parking"); return PARK_RESULT_FAIL; } pbx_bridgedChannelClone = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, hostChannel->owner->accountcode, bridgedChannel->exten, bridgedChannel->context, bridgedChannel->linkedid, bridgedChannel->amaflags, "Parking/%s", bridgedChannel->name); pbx_hostChannelClone = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, hostChannel->owner->accountcode, hostChannel->owner->exten, hostChannel->owner->context, hostChannel->owner->linkedid, hostChannel->owner->amaflags, "SCCP/%s", hostChannel->owner->name); if (pbx_hostChannelClone && pbx_bridgedChannelClone) { /* restore codecs for bridged channel */ pbx_bridgedChannelClone->readformat = bridgedChannel->readformat; pbx_bridgedChannelClone->writeformat = bridgedChannel->writeformat; pbx_bridgedChannelClone->nativeformats = bridgedChannel->nativeformats; ast_channel_masquerade(pbx_bridgedChannelClone, bridgedChannel); /* restore context data */ ast_copy_string(pbx_bridgedChannelClone->context, bridgedChannel->context, sizeof(pbx_bridgedChannelClone->context)); ast_copy_string(pbx_bridgedChannelClone->exten, bridgedChannel->exten, sizeof(pbx_bridgedChannelClone->exten)); pbx_bridgedChannelClone->priority = bridgedChannel->priority; /* restore codecs for host channel */ /* We need to clone the host part, for playing back the announcement */ pbx_hostChannelClone->readformat = hostChannel->owner->readformat; pbx_hostChannelClone->writeformat = hostChannel->owner->writeformat; pbx_hostChannelClone->nativeformats = hostChannel->owner->nativeformats; ast_channel_masquerade(pbx_hostChannelClone, hostChannel->owner); /* restore context data */ ast_copy_string(pbx_hostChannelClone->context, hostChannel->owner->context, sizeof(pbx_hostChannelClone->context)); ast_copy_string(pbx_hostChannelClone->exten, hostChannel->owner->exten, sizeof(pbx_hostChannelClone->exten)); pbx_hostChannelClone->priority = hostChannel->owner->priority; /* start cloning */ if (ast_do_masquerade(pbx_hostChannelClone)) { pbx_log(LOG_ERROR, "while doing masquerade\n"); ast_hangup(pbx_hostChannelClone); return PARK_RESULT_FAIL; } } else { if (pbx_bridgedChannelClone) ast_hangup(pbx_bridgedChannelClone); if (pbx_hostChannelClone) ast_hangup(pbx_hostChannelClone); return PARK_RESULT_FAIL; } if (!(arg = (struct parkingThreadArg *) ast_calloc(1, sizeof(struct parkingThreadArg)))) { return PARK_RESULT_FAIL; } arg->bridgedChannel = pbx_bridgedChannelClone; arg->hostChannel = pbx_hostChannelClone; if ((arg->device = sccp_channel_getDevice_retained(hostChannel))) { if (!ast_pthread_create_detached_background(&th, NULL, sccp_wrapper_asterisk18_park_thread, arg)) { return PARK_RESULT_SUCCESS; } arg->device = sccp_device_release(arg->device); } sccp_free(arg); return PARK_RESULT_FAIL; } static boolean_t sccp_wrapper_asterisk18_getFeatureExtension(const sccp_channel_t * channel, char **extension) { struct ast_call_feature *feat; ast_rdlock_call_features(); feat = ast_find_call_feature("automon"); if (feat) { *extension = strdup(feat->exten); } ast_unlock_call_features(); return feat ? TRUE : FALSE; } #if !CS_AST_DO_PICKUP static const struct ast_datastore_info pickup_active = { .type = "pickup-active", }; static int ast_do_pickup(PBX_CHANNEL_TYPE * chan, PBX_CHANNEL_TYPE * target) { struct ast_party_connected_line connected_caller; PBX_CHANNEL_TYPE *chans[2] = { chan, target }; struct ast_datastore *ds_pickup; const char *chan_name; /*!< A masquerade changes channel names. */ const char *target_name; /*!< A masquerade changes channel names. */ int res = -1; target_name = sccp_strdupa(target->name); ast_debug(1, "Call pickup on '%s' by '%s'\n", target_name, chan->name); /* Mark the target to block any call pickup race. */ ds_pickup = ast_datastore_alloc(&pickup_active, NULL); if (!ds_pickup) { pbx_log(LOG_WARNING, "Unable to create channel datastore on '%s' for call pickup\n", target_name); return -1; } ast_channel_datastore_add(target, ds_pickup); ast_party_connected_line_init(&connected_caller); ast_party_connected_line_copy(&connected_caller, &target->connected); ast_channel_unlock(target); /* The pickup race is avoided so we do not need the lock anymore. */ connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER; if (ast_channel_connected_line_macro(NULL, chan, &connected_caller, 0, 0)) { ast_channel_update_connected_line(chan, &connected_caller, NULL); } ast_party_connected_line_free(&connected_caller); ast_channel_lock(chan); chan_name = sccp_strdupa(chan->name); ast_connected_line_copy_from_caller(&connected_caller, &chan->caller); ast_channel_unlock(chan); connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER; ast_channel_queue_connected_line_update(chan, &connected_caller, NULL); ast_party_connected_line_free(&connected_caller); // ast_cel_report_event(target, AST_CEL_PICKUP, NULL, NULL, chan); if (ast_answer(chan)) { pbx_log(LOG_WARNING, "Unable to answer '%s'\n", chan_name); goto pickup_failed; } if (sccp_asterisk_queue_control(chan, AST_CONTROL_ANSWER)) { pbx_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan_name); goto pickup_failed; } /* setting this flag to generate a reason header in the cancel message to the ringing channel */ ast_set_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE); if (ast_channel_masquerade(target, chan)) { pbx_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan_name, target_name); goto pickup_failed; } /* If you want UniqueIDs, set channelvars in manager.conf to CHANNEL(uniqueid) */ ast_manager_event_multichan(EVENT_FLAG_CALL, "Pickup", 2, chans, "Channel: %s\r\n" "TargetChannel: %s\r\n", chan_name, target_name); /* Do the masquerade manually to make sure that it is completed. */ ast_do_masquerade(target); res = 0; pickup_failed: ast_channel_lock(target); if (!ast_channel_datastore_remove(target, ds_pickup)) { ast_datastore_free(ds_pickup); } return res; } #endif /*! * \brief Pickup asterisk channel target using chan * * \param chan initial channel that request the parking * \param target Channel t park to */ static boolean_t sccp_wrapper_asterisk18_pickupChannel(const sccp_channel_t * chan, PBX_CHANNEL_TYPE * target) { boolean_t result = FALSE; PBX_CHANNEL_TYPE *ref; ref = ast_channel_ref(chan->owner); result = ast_do_pickup(chan->owner, target) ? FALSE : TRUE; if (result) { ((sccp_channel_t *) chan)->owner = ast_channel_ref(target); ast_hangup(ref); } ref = ast_channel_unref(chan->owner); return result; } static uint8_t sccp_wrapper_asterisk18_get_payloadType(const struct sccp_rtp *rtp, skinny_codec_t codec) { uint32_t astCodec; int payload; astCodec = skinny_codec2pbx_codec(codec); payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(rtp->rtp), 1, astCodec); return payload; } static int sccp_wrapper_asterisk18_get_sampleRate(skinny_codec_t codec) { uint32_t astCodec; astCodec = skinny_codec2pbx_codec(codec); return ast_rtp_lookup_sample_rate2(1, astCodec); } static sccp_extension_status_t sccp_wrapper_asterisk18_extensionStatus(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_channel = channel->owner; if (!pbx_channel || !pbx_channel->context) { pbx_log(LOG_ERROR, "%s: (extension_status) Either no pbx_channel or no valid context provided to lookup number\n", channel->designator); return SCCP_EXTENSION_NOTEXISTS; } int ignore_pat = ast_ignore_pattern(pbx_channel->context, channel->dialedNumber); int ext_exist = ast_exists_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); int ext_canmatch = ast_canmatch_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); int ext_matchmore = ast_matchmore_extension(pbx_channel, pbx_channel->context, channel->dialedNumber, 1, channel->line->cid_num); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "+=sccp extension matcher says==================+\n" VERBOSE_PREFIX_2 "|ignore |exists |can match |match more|\n" VERBOSE_PREFIX_2 "|%3s |%3s |%3s |%3s |\n" VERBOSE_PREFIX_2 "+==============================================+\n", ignore_pat ? "yes" : "no", ext_exist ? "yes" : "no", ext_canmatch ? "yes" : "no", ext_matchmore ? "yes" : "no"); if (ignore_pat) { return SCCP_EXTENSION_NOTEXISTS; } else if (ext_exist) { if (ext_canmatch && !ext_matchmore) { return SCCP_EXTENSION_EXACTMATCH; } else { return SCCP_EXTENSION_MATCHMORE; } } return SCCP_EXTENSION_NOTEXISTS; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk18_request(const char *type, format_t format, const PBX_CHANNEL_TYPE * requestor, void *data, int *cause) { PBX_CHANNEL_TYPE *result_ast_channel = NULL; sccp_channel_request_status_t requestStatus; sccp_channel_t *channel = NULL; skinny_codec_t audioCapabilities[SKINNY_MAX_CAPABILITIES]; skinny_codec_t videoCapabilities[SKINNY_MAX_CAPABILITIES]; memset(&audioCapabilities, 0, sizeof(audioCapabilities)); memset(&videoCapabilities, 0, sizeof(videoCapabilities)); //! \todo parse request char *lineName; skinny_codec_t codec = SKINNY_CODEC_G711_ULAW_64K; sccp_autoanswer_t autoanswer_type = SCCP_AUTOANSWER_NONE; uint8_t autoanswer_cause = AST_CAUSE_NOTDEFINED; int ringermode = 0; *cause = AST_CAUSE_NOTDEFINED; if (!type) { pbx_log(LOG_NOTICE, "Attempt to call with unspecified type of channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } if (!data) { pbx_log(LOG_NOTICE, "Attempt to call SCCP/ failed\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; return NULL; } /* we leave the data unchanged */ lineName = strdupa((const char *) data); /* parsing options string */ char *options = NULL; int optc = 0; char *optv[2]; int opti = 0; if ((options = strchr(lineName, '/'))) { *options = '\0'; options++; } sccp_log(DEBUGCAT_CHANNEL) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked us to create a channel with type=%s, format=" UI64FMT ", lineName=%s, options=%s\n", type, (uint64_t) format, lineName, (options) ? options : ""); /* get ringer mode from ALERT_INFO */ const char *alert_info = NULL; if (requestor) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "_ALERT_INFO"); if (!alert_info) { alert_info = pbx_builtin_getvar_helper((PBX_CHANNEL_TYPE *) requestor, "__ALERT_INFO"); } } if (alert_info && !sccp_strlen_zero(alert_info)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Found ALERT_INFO=%s\n", alert_info); if (strcasecmp(alert_info, "inside") == 0) ringermode = SKINNY_RINGTYPE_INSIDE; else if (strcasecmp(alert_info, "feature") == 0) ringermode = SKINNY_RINGTYPE_FEATURE; else if (strcasecmp(alert_info, "silent") == 0) ringermode = SKINNY_RINGTYPE_SILENT; else if (strcasecmp(alert_info, "urgent") == 0) ringermode = SKINNY_RINGTYPE_URGENT; } /* done ALERT_INFO parsing */ /* parse options */ if (options && (optc = sccp_app_separate_args(options, '/', optv, sizeof(optv) / sizeof(optv[0])))) { pbx_log(LOG_NOTICE, "parse options\n"); for (opti = 0; opti < optc; opti++) { pbx_log(LOG_NOTICE, "parse option '%s'\n", optv[opti]); if (!strncasecmp(optv[opti], "aa", 2)) { /* let's use the old style auto answer aa1w and aa2w */ if (!strncasecmp(optv[opti], "aa1w", 4)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa2w", 4)) { autoanswer_type = SCCP_AUTOANSWER_2W; optv[opti] += 4; } else if (!strncasecmp(optv[opti], "aa=", 3)) { optv[opti] += 3; pbx_log(LOG_NOTICE, "parsing aa\n"); if (!strncasecmp(optv[opti], "1w", 2)) { autoanswer_type = SCCP_AUTOANSWER_1W; optv[opti] += 2; } else if (!strncasecmp(optv[opti], "2w", 2)) { autoanswer_type = SCCP_AUTOANSWER_2W; pbx_log(LOG_NOTICE, "set aa to 2w\n"); optv[opti] += 2; } } /* since the pbx ignores autoanswer_cause unless SCCP_RWLIST_GETSIZE(l->channels) > 1, it is safe to set it if provided */ if (!sccp_strlen_zero(optv[opti]) && (autoanswer_cause)) { if (!strcasecmp(optv[opti], "b")) autoanswer_cause = AST_CAUSE_BUSY; else if (!strcasecmp(optv[opti], "u")) autoanswer_cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; else if (!strcasecmp(optv[opti], "c")) autoanswer_cause = AST_CAUSE_CONGESTION; } if (autoanswer_cause) *cause = autoanswer_cause; /* check for ringer options */ } else if (!strncasecmp(optv[opti], "ringer=", 7)) { optv[opti] += 7; if (!strcasecmp(optv[opti], "inside")) ringermode = SKINNY_RINGTYPE_INSIDE; else if (!strcasecmp(optv[opti], "outside")) ringermode = SKINNY_RINGTYPE_OUTSIDE; else if (!strcasecmp(optv[opti], "feature")) ringermode = SKINNY_RINGTYPE_FEATURE; else if (!strcasecmp(optv[opti], "silent")) ringermode = SKINNY_RINGTYPE_SILENT; else if (!strcasecmp(optv[opti], "urgent")) ringermode = SKINNY_RINGTYPE_URGENT; else ringermode = SKINNY_RINGTYPE_OUTSIDE; } else { pbx_log(LOG_WARNING, "Wrong option %s\n", optv[opti]); } } } /** getting remote capabilities */ char cap_buf[512]; /* audio capabilities */ if (requestor) { sccp_channel_t *remoteSccpChannel = get_sccp_channel_from_pbx_channel(requestor); if (remoteSccpChannel) { uint8_t x, y, z; z = 0; /* shrink audioCapabilities to remote preferred/capable format */ for (x = 0; x < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->preferences.audio[x] != 0; x++) { for (y = 0; y < SKINNY_MAX_CAPABILITIES && remoteSccpChannel->capabilities.audio[y] != 0; y++) { if (remoteSccpChannel->preferences.audio[x] == remoteSccpChannel->capabilities.audio[y]) { audioCapabilities[z++] = remoteSccpChannel->preferences.audio[x]; break; } } } remoteSccpChannel = sccp_channel_release(remoteSccpChannel); } else { get_skinnyFormats(requestor->nativeformats & AST_FORMAT_AUDIO_MASK, audioCapabilities, ARRAY_LEN(audioCapabilities)); } /* video capabilities */ get_skinnyFormats(requestor->nativeformats & AST_FORMAT_VIDEO_MASK, videoCapabilities, ARRAY_LEN(videoCapabilities)); } sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, audioCapabilities, ARRAY_LEN(audioCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote audio caps: %s\n", cap_buf); sccp_multiple_codecs2str(cap_buf, sizeof(cap_buf) - 1, videoCapabilities, ARRAY_LEN(videoCapabilities)); // sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_4 "remote video caps: %s\n", cap_buf); /** done */ /** get requested format */ codec = pbx_codec2skinny_codec(format); requestStatus = sccp_requestChannel(lineName, codec, audioCapabilities, ARRAY_LEN(audioCapabilities), autoanswer_type, autoanswer_cause, ringermode, &channel); switch (requestStatus) { case SCCP_REQUEST_STATUS_SUCCESS: // everything is fine break; case SCCP_REQUEST_STATUS_LINEUNKNOWN: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s Unknown -> Not Successfull\n", lineName); *cause = AST_CAUSE_DESTINATION_OUT_OF_ORDER; goto EXITFUNC; case SCCP_REQUEST_STATUS_LINEUNAVAIL: sccp_log(DEBUGCAT_CORE) (VERBOSE_PREFIX_4 "SCCP: sccp_requestChannel returned Line %s not currently registered -> Try again later\n", lineName); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; case SCCP_REQUEST_STATUS_ERROR: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; default: pbx_log(LOG_ERROR, "SCCP: sccp_requestChannel returned Status Error for lineName: %s\n", lineName); *cause = AST_CAUSE_UNALLOCATED; goto EXITFUNC; } if (!sccp_pbx_channel_allocate(channel, requestor ? requestor->linkedid : NULL)) { //! \todo handle error in more detail, cleanup sccp channel pbx_log(LOG_WARNING, "SCCP: Unable to allocate channel\n"); *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL; goto EXITFUNC; } if (requestor) { /* set calling party */ sccp_channel_set_callingparty(channel, requestor->caller.id.name.str, requestor->caller.id.number.str); sccp_channel_set_originalCalledparty(channel, requestor->redirecting.from.name.str, requestor->redirecting.from.number.str); } EXITFUNC: sccp_restart_monitor(); if (channel) { result_ast_channel = channel->owner; sccp_channel_release(channel); } return result_ast_channel; } static int sccp_wrapper_asterisk18_call(PBX_CHANNEL_TYPE * ast, char *dest, int timeout) { sccp_channel_t *c = NULL; struct varshead *headp; struct ast_var_t *current; int res = 0; sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk request to call %s (dest:%s, timeout: %d)\n", pbx_channel_name(ast), dest, timeout); if (!sccp_strlen_zero(pbx_channel_call_forward(ast))) { PBX(queue_control) (ast, -1); /* Prod Channel if in the middle of a call_forward instead of proceed */ sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Forwarding Call to '%s'\n", pbx_channel_call_forward(ast)); return 0; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { pbx_log(LOG_WARNING, "SCCP: Asterisk request to call %s on channel: %s, but we don't have this channel!\n", dest, pbx_channel_name(ast)); return -1; } /* Check whether there is MaxCallBR variables */ headp = &ast->varshead; //ast_log(LOG_NOTICE, "SCCP: search for varibles!\n"); AST_LIST_TRAVERSE(headp, current, entries) { //ast_log(LOG_NOTICE, "var: name: %s, value: %s\n", ast_var_name(current), ast_var_value(current)); if (!strcasecmp(ast_var_name(current), "__MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } else if (!strcasecmp(ast_var_name(current), "MaxCallBR")) { sccp_asterisk_pbx_fktChannelWrite(ast, "CHANNEL", "MaxCallBR", ast_var_value(current)); } } res = sccp_pbx_call(c, dest, timeout); c = sccp_channel_release(c); return res; } static int sccp_wrapper_asterisk18_answer(PBX_CHANNEL_TYPE * chan) { //! \todo change this handling and split pbx and sccp handling -MC int res = -1; sccp_channel_t *channel = NULL; if ((channel = get_sccp_channel_from_pbx_channel(chan))) { res = sccp_pbx_answer(channel); channel = sccp_channel_release(channel); } return res; } /** * * \todo update remote capabilities after fixup */ static int sccp_wrapper_asterisk18_fixup(PBX_CHANNEL_TYPE * oldchan, PBX_CHANNEL_TYPE * newchan) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: we got a fixup request for %s\n", newchan->name); sccp_channel_t *c = NULL; int res = 0; if (!(c = get_sccp_channel_from_pbx_channel(newchan))) { pbx_log(LOG_WARNING, "sccp_pbx_fixup(old: %s(%p), new: %s(%p)). no SCCP channel to fix\n", oldchan->name, (void *) oldchan, newchan->name, (void *) newchan); return -1; } else { if (c->owner != oldchan) { ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, c->owner); res = -1; } else { c->owner = ast_channel_ref(newchan); if (!sccp_strlen_zero(c->line->language)) { ast_string_field_set(newchan, language, c->line->language); } ast_channel_unref(oldchan); //! \todo force update of rtp_peer for directrtp // sccp_wrapper_asterisk18_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0); //! \todo update remote capabilities after fixup } c = sccp_channel_release(c); } return res; } static enum ast_bridge_result sccp_wrapper_asterisk18_rtpBridge(PBX_CHANNEL_TYPE * c0, PBX_CHANNEL_TYPE * c1, int flags, PBX_FRAME_TYPE ** fo, PBX_CHANNEL_TYPE ** rc, int timeoutms) { enum ast_bridge_result res; int new_flags = flags; /* \note temporarily marked out until we figure out how to get directrtp back on track - DdG */ sccp_channel_t *sc0, *sc1; sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridging chan %s and chan %s\n", c0->name, c1->name); if ((sc0 = get_sccp_channel_from_pbx_channel(c0)) && (sc1 = get_sccp_channel_from_pbx_channel(c1))) { // Switch off DTMF between SCCP phones new_flags &= !AST_BRIDGE_DTMF_CHANNEL_0; new_flags &= !AST_BRIDGE_DTMF_CHANNEL_1; if (GLOB(directrtp)) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } else { sccp_device_t *d0 = sccp_channel_getDevice_retained(sc0); if (d0) { sccp_device_t *d1 = sccp_channel_getDevice_retained(sc1); if (d1) { if (d0->directrtp && d1->directrtp) { ast_channel_defer_dtmf(c0); ast_channel_defer_dtmf(c1); } d1 = sccp_device_release(d1); } d0 = sccp_device_release(d0); } } sc0->peerIsSCCP = TRUE; sc1->peerIsSCCP = TRUE; // SCCP Key handle direction to asterisk is still to be implemented here // sccp_pbx_senddigit sc0 = sccp_channel_release(sc0); sc1 = sccp_channel_release(sc1); } else { // Switch on DTMF between differing channels ast_channel_undefer_dtmf(c0); ast_channel_undefer_dtmf(c1); } res = ast_rtp_instance_bridge(c0, c1, new_flags, fo, rc, timeoutms); switch (res) { case AST_BRIDGE_COMPLETE: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Complete\n", c0->name, c1->name); break; case AST_BRIDGE_FAILED: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed\n", c0->name, c1->name); break; case AST_BRIDGE_FAILED_NOWARN: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed NoWarn\n", c0->name, c1->name); break; case AST_BRIDGE_RETRY: sccp_log((DEBUGCAT_PBX)) (VERBOSE_PREFIX_1 "SCCP: Bridge chan %s and chan %s: Failed Retry\n", c0->name, c1->name); break; } /*! \todo Implement callback function queue upon completion */ return res; } static enum ast_rtp_glue_result sccp_wrapper_asterisk18_get_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", ast->name); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_FORBID; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", ast->name); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static int sccp_wrapper_asterisk18_set_rtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE * rtp, PBX_RTP_TYPE * vrtp, PBX_RTP_TYPE * trtp, format_t codecs, int nat_active) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; int result = 0; sccp_log((DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) format: %d\n", (int) codecs); sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: __FILE__\n"); do { if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO PVT\n"); result = -1; break; } if (!c->line) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO LINE\n"); result = -1; break; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_set_rtp_peer) NO DEVICE\n"); result = -1; break; } if (!d->directrtp) { // in-direct rtp struct ast_sockaddr us_tmp; struct sockaddr_in us = { 0, }; ast_rtp_instance_get_local_address(rtp, &us_tmp); ast_sockaddr_to_sin(&us_tmp, &us); us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->session->ourip.s_addr; sccp_rtp_set_peer(c, &c->rtp.audio, &us); /* } else { // direct rtp struct ast_sockaddr them_tmp; struct sockaddr_in them = { 0, }; ast_rtp_instance_get_remote_address(rtp, &them_tmp); ast_sockaddr_to_sin(&them_tmp, &them); sccp_rtp_set_peer(c, &c->rtp.audio, &them); */ } if (ast->_state != AST_STATE_UP) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Early RTP stage, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } else { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_2 "SCCP: (sccp_channel_set_rtp_peer) Native Bridge Break, codecs=%lu, nat=%d\n", (long unsigned int) codecs, d->nat); } } while (0); /* Need a return here to break the bridge */ d = d ? sccp_device_release(d) : NULL; return result; } static enum ast_rtp_glue_result sccp_wrapper_asterisk18_get_vrtp_peer(PBX_CHANNEL_TYPE * ast, PBX_RTP_TYPE ** rtp) { sccp_channel_t *c = NULL; sccp_rtp_info_t rtpInfo; struct sccp_rtp *audioRTP = NULL; enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE; sccp_log((DEBUGCAT_CHANNEL | DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) Asterisk requested RTP peer for channel %s\n", ast->name); if (!(c = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: (sccp_channel_get_rtp_peer) NO PVT\n"); return AST_RTP_GLUE_RESULT_FORBID; } rtpInfo = sccp_rtp_getAudioPeerInfo(c, &audioRTP); //! \todo should this not be getVideoPeerInfo if (rtpInfo == SCCP_RTP_INFO_NORTP) { return AST_RTP_GLUE_RESULT_FORBID; } *rtp = audioRTP->rtp; if (!*rtp) return AST_RTP_GLUE_RESULT_FORBID; #ifdef HAVE_PBX_RTP_ENGINE_H ao2_ref(*rtp, +1); #endif if (ast_test_flag(&GLOB(global_jbconf), AST_JB_FORCED)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) JitterBuffer is Forced. AST_RTP_GET_FAILED\n"); return AST_RTP_GLUE_RESULT_FORBID; } if (!(rtpInfo & SCCP_RTP_INFO_ALLOW_DIRECTRTP)) { sccp_log((DEBUGCAT_RTP)) (VERBOSE_PREFIX_1 "SCCP: ( __PRETTY_FUNCTION__ ) Direct RTP disabled -> Using AST_RTP_TRY_PARTIAL for channel %s\n", ast->name); return AST_RTP_GLUE_RESULT_LOCAL; } return res; } static format_t sccp_wrapper_asterisk18_getCodec(PBX_CHANNEL_TYPE * ast) { format_t format = AST_FORMAT_ULAW; sccp_channel_t *channel; if (!(channel = CS_AST_CHANNEL_PVT(ast))) { sccp_log((DEBUGCAT_RTP | DEBUGCAT_CODEC)) (VERBOSE_PREFIX_1 "SCCP: (getCodec) NO PVT\n"); return format; } ast_debug(10, "asterisk requests format for channel %s, readFormat: %s(%d)\n", ast->name, codec2str(channel->rtp.audio.readFormat), channel->rtp.audio.readFormat); if (channel->remoteCapabilities.audio) return skinny_codecs2pbx_codecs(channel->remoteCapabilities.audio); else return skinny_codecs2pbx_codecs(channel->capabilities.audio); } /* * \brief get callerid_name from pbx * \param sccp_channle Asterisk Channel * \param cid name result * \return parse result * * caller.id.name.str * caller.id.name.char_set * caller.id.name.presentation * caller.id.name.valid * caller.id.number.str * caller.id.number.plan * caller.id.number.presentation * caller.id.number.valid * caller.id.subaddress.str * caller.id.subaddress.type * caller.id.subaddress.odd_even_indicator * caller.id.subaddress.valid * caller.ani.* * caller.ani2 */ static int sccp_wrapper_asterisk18_callerid_name(const sccp_channel_t * channel, char **cid_name) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.name.valid && pbx_chan->caller.id.name.str && strlen(pbx_chan->caller.id.name.str) > 0) { *cid_name = strdup(pbx_chan->caller.id.name.str); return 1; } return 0; } /* * \brief get callerid_name from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number * * caller.id.name.str * caller.id.name.char_set * caller.id.name.presentation * caller.id.name.valid * caller.id.number.str * caller.id.number.plan * caller.id.number.presentation * caller.id.number.valid * caller.id.subaddress.str * caller.id.subaddress.type * caller.id.subaddress.odd_even_indicator * caller.id.subaddress.valid * caller.ani.* * caller.ani2 */ static int sccp_wrapper_asterisk18_callerid_number(const sccp_channel_t * channel, char **cid_number) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.number.valid && pbx_chan->caller.id.number.str && strlen(pbx_chan->caller.id.number.str) > 0) { *cid_number = strdup(pbx_chan->caller.id.number.str); return 1; } return 0; } /* * \brief get callerid_ton from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk18_callerid_ton(const sccp_channel_t * channel, char **cid_ton) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.number.valid) { return pbx_chan->caller.ani.number.plan; } return 0; } /* * \brief get callerid_ani from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number * * caller.id.name.* * caller.id.number.* * caller.id.subaddress.* * caller.ani.name.str * caller.ani.name.char_set * caller.ani.name.presentation * caller.ani.name.valid * caller.ani.number.str * caller.ani.number.plan * caller.ani.number.presentation * caller.ani.number.valid * caller.ani.subaddr.str * caller.ani.subaddr.type * caller.ani.subaddr.odd_even_indicator * caller.ani.subaddr.valid * caller.ani2 */ static int sccp_wrapper_asterisk18_callerid_ani(const sccp_channel_t * channel, char **cid_ani) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.ani.number.valid && pbx_chan->caller.ani.number.str && strlen(pbx_chan->caller.ani.number.str) > 0) { *cid_ani = strdup(pbx_chan->caller.ani.number.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number * * caller.id.subaddress.str * caller.id.subaddress.type * caller.id.subaddress.odd_even_indicator * caller.id.subaddress.valid */ static int sccp_wrapper_asterisk18_callerid_subaddr(const sccp_channel_t * channel, char **cid_subaddr) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->caller.id.subaddress.valid && pbx_chan->caller.id.subaddress.str && strlen(pbx_chan->caller.id.subaddress.str) > 0) { *cid_subaddr = strdup(pbx_chan->caller.id.subaddress.str); return 1; } return 0; } /* * \brief get callerid_dnid from pbx (Destination ID) * \param ast_chan Asterisk Channel * \return char * with the caller number * * dialed.number.str * dialed.number.plan * dialed.subaddress.str * dialed.subaddress.type * dialed.subaddress.odd_even_indicator * dialed.subaddress.valid * dialed.transit_network_select */ static int sccp_wrapper_asterisk18_callerid_dnid(const sccp_channel_t * channel, char **cid_dnid) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->dialed.number.str && strlen(pbx_chan->dialed.number.str) > 0) { *cid_dnid = strdup(pbx_chan->dialed.number.str); return 1; } return 0; } /* * \brief get callerid_rdnis from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number * * redirecting.from.name.str * redirecting.from.name.char_set * redirecting.from.name.presentation * redirecting.from.name.valid * redirecting.from.number.str * redirecting.from.number.char_set * redirecting.from.number.presentation * redirecting.from.number.valid * redirecting.from.subaddress.str * redirecting.from.subaddress.type * redirecting.from.subaddress.odd_even_indicator * redirecting.from.subaddress.valid * redirecting.to.name.str * redirecting.to.name.char_set * redirecting.to.name.presentation * redirecting.to.name.valid * redirecting.to.number.str * redirecting.to.number.char_set * redirecting.to.number.presentation * redirecting.to.number.valid * redirecting.to.subaddress.str * redirecting.to.subaddress.type * redirecting.to.subaddress.odd_even_indicator * redirecting.to.subaddress.valid */ static int sccp_wrapper_asterisk18_callerid_rdnis(const sccp_channel_t * channel, char **cid_rdnis) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; if (pbx_chan->redirecting.from.number.valid && pbx_chan->redirecting.from.number.str && strlen(pbx_chan->redirecting.from.number.str) > 0) { *cid_rdnis = strdup(pbx_chan->redirecting.from.number.str); return 1; } return 0; } /* * \brief get callerid_presence from pbx * \param ast_chan Asterisk Channel * \return char * with the caller number */ static int sccp_wrapper_asterisk18_callerid_presence(const sccp_channel_t * channel) { PBX_CHANNEL_TYPE *pbx_chan = channel->owner; // if (pbx_chan->caller.id.number.presentation) { // return pbx_chan->caller.id.number.presentation; // } // return 0; if ((ast_party_id_presentation(&pbx_chan->caller.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) { return CALLERID_PRESENCE_ALLOWED; } return CALLERID_PRESENCE_FORBIDDEN; } static int sccp_wrapper_asterisk18_rtp_stop(sccp_channel_t * channel) { if (channel->rtp.audio.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping phone media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.audio.rtp); } if (channel->rtp.video.rtp) { sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "Stopping video media transmission on channel %08X\n", channel->callid); ast_rtp_instance_stop(channel->rtp.video.rtp); } return 0; } static boolean_t sccp_wrapper_asterisk18_create_audio_rtp(sccp_channel_t * c) { sccp_session_t *s = NULL; sccp_device_t *d = NULL; struct ast_sockaddr sock; struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; if (GLOB(bindaddr.sin_addr.s_addr) == INADDR_ANY) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = GLOB(bindaddr.sin_port); sin.sin_addr = s->ourip; /* sccp_socket_getOurAddressfor(s->sin.sin_addr, sin.sin_addr); */// maybe we should use this opertunity to check the connected ip-address again ast_sockaddr_from_sin(&sock, &sin); } else { ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating rtp server connection on %s\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock)); c->rtp.audio.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.audio.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: rtp server created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_RTCP, 1); if (SCCP_DTMFMODE_INBAND == d->dtmfmode) { ast_rtp_instance_dtmf_mode_set(c->rtp.audio.rtp, AST_RTP_DTMF_MODE_INBAND); } else { ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF, 1); ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, 1); } ast_channel_set_fd(c->owner, 0, ast_rtp_instance_fd(c->rtp.audio.rtp, 0)); ast_channel_set_fd(c->owner, 1, ast_rtp_instance_fd(c->rtp.audio.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); ast_rtp_instance_set_prop(c->rtp.audio.rtp, AST_RTP_PROPERTY_NAT, d->nat); } memset(&astCodecPref, 0, sizeof(astCodecPref)); if (skinny_codecs2pbx_codec_pref(c->preferences.audio, &astCodecPref)) { ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); } //char pref_buf[128]; // ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); // sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pref: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.audio.rtp, d->audio_tos, d->audio_cos, "SCCP RTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.audio.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add audio codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_AUDIO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "audio", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk18_create_video_rtp(sccp_channel_t * c) { sccp_session_t *s; sccp_device_t *d = NULL; struct ast_sockaddr sock; struct ast_codec_pref astCodecPref; if (!c) return FALSE; if (!(d = sccp_channel_getDevice_retained(c))) return FALSE; s = d->session; sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: Creating vrtp server connection at %s\n", DEV_ID_LOG(d), pbx_inet_ntoa(s->ourip)); ast_sockaddr_from_sin(&sock, &GLOB(bindaddr)); c->rtp.video.rtp = ast_rtp_instance_new("asterisk", sched, &sock, NULL); if (!c->rtp.video.rtp) { d = sccp_device_release(d); return FALSE; } sccp_log(DEBUGCAT_RTP) (VERBOSE_PREFIX_3 "%s: vrtp created at %s:%d\n", DEV_ID_LOG(d), ast_sockaddr_stringify_host(&sock), ast_sockaddr_port(&sock)); if (c->owner) { ast_rtp_instance_set_prop(c->rtp.video.rtp, AST_RTP_PROPERTY_RTCP, 1); ast_channel_set_fd(c->owner, 2, ast_rtp_instance_fd(c->rtp.video.rtp, 0)); ast_channel_set_fd(c->owner, 3, ast_rtp_instance_fd(c->rtp.video.rtp, 1)); ast_queue_frame(c->owner, &ast_null_frame); } memset(&astCodecPref, 0, sizeof(astCodecPref)); if (skinny_codecs2pbx_codec_pref(c->preferences.video, &astCodecPref)) { ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(c->rtp.audio.rtp), c->rtp.audio.rtp, &astCodecPref); } //char pref_buf[128]; //ast_codec_pref_string((struct ast_codec_pref *)&c->codecs, pref_buf, sizeof(pref_buf) - 1); //sccp_log(2) (VERBOSE_PREFIX_3 "SCCP: SCCP/%s-%08x, set pef: %s\n", c->line->name, c->callid, pref_buf); ast_rtp_instance_set_qos(c->rtp.video.rtp, d->video_tos, d->video_cos, "SCCP VRTP"); /* add payload mapping for skinny codecs */ uint8_t i; struct ast_rtp_codecs *codecs = ast_rtp_instance_get_codecs(c->rtp.video.rtp); for (i = 0; i < ARRAY_LEN(skinny_codecs); i++) { /* add video codecs only */ if (skinny_codecs[i].mimesubtype && skinny_codecs[i].codec_type == SKINNY_CODEC_TYPE_VIDEO) { ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL, skinny_codecs[i].codec, "video", (char *) skinny_codecs[i].mimesubtype, (enum ast_rtp_options) 0, skinny_codecs[i].sample_rate); } } d = sccp_device_release(d); return TRUE; } static boolean_t sccp_wrapper_asterisk18_destroyRTP(PBX_RTP_TYPE * rtp) { int res; res = ast_rtp_instance_destroy(rtp); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk18_checkHangup(const sccp_channel_t * channel) { int res; res = ast_check_hangup(channel->owner); return (!res) ? TRUE : FALSE; } static boolean_t sccp_wrapper_asterisk18_rtpGetPeer(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_remote_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk18_rtpGetUs(PBX_RTP_TYPE * rtp, struct sockaddr_in *address) { struct ast_sockaddr addr; ast_rtp_instance_get_local_address(rtp, &addr); ast_sockaddr_to_sin(&addr, address); return TRUE; } static boolean_t sccp_wrapper_asterisk18_getChannelByName(const char *name, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *ast = ast_channel_get_by_name(name); if (!ast) return FALSE; *pbx_channel = ast; return TRUE; } static int sccp_wrapper_asterisk18_rtp_set_peer(const struct sccp_rtp *rtp, const struct sockaddr_in *new_peer, int nat_active) { struct ast_sockaddr ast_sockaddr_dest; struct ast_sockaddr ast_sockaddr_source; int res; ((struct sockaddr_in *) new_peer)->sin_family = AF_INET; ast_sockaddr_from_sin(&ast_sockaddr_dest, new_peer); ast_sockaddr_set_port(&ast_sockaddr_dest, ntohs(new_peer->sin_port)); res = ast_rtp_instance_set_remote_address(rtp->rtp, &ast_sockaddr_dest); ast_rtp_instance_get_local_address(rtp->rtp, &ast_sockaddr_source); // sccp_log(DEBUGCAT_HIGH) (VERBOSE_PREFIX_3 "SCCP: Tell PBX to send RTP/UDP media from '%s:%d' to '%s:%d' (NAT: %s)\n", ast_sockaddr_stringify_host(&ast_sockaddr_source), ast_sockaddr_port(&ast_sockaddr_source), ast_sockaddr_stringify_host(&ast_sockaddr_dest), ast_sockaddr_port(&ast_sockaddr_dest), nat_active ? "yes" : "no"); if (nat_active) { ast_rtp_instance_set_prop(rtp->rtp, AST_RTP_PROPERTY_NAT, 1); } return res; } static boolean_t sccp_wrapper_asterisk18_setWriteFormat(const sccp_channel_t * channel, skinny_codec_t codec) { channel->owner->rawwriteformat = skinny_codec2pbx_codec(codec); channel->owner->nativeformats |= channel->owner->rawwriteformat; #ifndef CS_EXPERIMENTAL_CODEC if (!channel->owner->writeformat) { channel->owner->writeformat = channel->owner->rawwriteformat; } if (channel->owner->writetrans) { ast_translator_free_path(channel->owner->writetrans); channel->owner->writetrans = NULL; } #endif ast_set_write_format(channel->owner, channel->owner->rawwriteformat); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "write native: %d\n", (int) channel->owner->rawwriteformat); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "write: %d\n", (int) channel->owner->writeformat); #ifdef CS_EXPERIMENTAL_CODEC PBX_CHANNEL_TYPE *bridge; if (PBX(getRemoteChannel) (channel, &bridge)) { // pbx_log(LOG_NOTICE, "Bridge found\n"); channel->owner->writeformat = 0; bridge->readformat = 0; // if(bridge->readtrans){ // ast_translator_free_path(bridge->readtrans); // bridge->readtrans = NULL; // } ast_channel_make_compatible(bridge, channel->owner); } else { ast_set_write_format(channel->owner, channel->owner->rawwriteformat); } #else channel->owner->nativeformats = channel->owner->rawwriteformat; ast_set_write_format(channel->owner, channel->owner->writeformat); #endif return TRUE; } static boolean_t sccp_wrapper_asterisk18_setReadFormat(const sccp_channel_t * channel, skinny_codec_t codec) { channel->owner->rawreadformat = skinny_codec2pbx_codec(codec); channel->owner->nativeformats = channel->owner->rawreadformat; #ifndef CS_EXPERIMENTAL_CODEC if (!channel->owner->readformat) { channel->owner->readformat = channel->owner->rawreadformat; } if (channel->owner->readtrans) { ast_translator_free_path(channel->owner->readtrans); channel->owner->readtrans = NULL; } #endif sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "read native: %d\n", (int) channel->owner->rawreadformat); sccp_log(DEBUGCAT_CODEC) (VERBOSE_PREFIX_3 "read: %d\n", (int) channel->owner->readformat); #ifdef CS_EXPERIMENTAL_CODEC PBX_CHANNEL_TYPE *bridge; if (PBX(getRemoteChannel) (channel, &bridge)) { // pbx_log(LOG_NOTICE, "Bridge found\n"); channel->owner->readformat = 0; bridge->writeformat = 0; // if(bridge->writetrans){ // ast_translator_free_path(bridge->writetrans); // bridge->writetrans = NULL; // } ast_channel_make_compatible(channel->owner, bridge); } else { ast_set_read_format(channel->owner, channel->owner->rawreadformat); } #else channel->owner->nativeformats = channel->owner->rawreadformat; ast_set_read_format(channel->owner, channel->owner->readformat); #endif return TRUE; } static void sccp_wrapper_asterisk18_setCalleridName(const sccp_channel_t * channel, const char *name) { if (name) { channel->owner->caller.id.name.valid = 1; ast_party_name_free(&channel->owner->caller.id.name); channel->owner->caller.id.name.str = ast_strdup(name); } } static void sccp_wrapper_asterisk18_setCalleridNumber(const sccp_channel_t * channel, const char *number) { if (number) { channel->owner->caller.id.number.valid = 1; ast_party_number_free(&channel->owner->caller.id.number); channel->owner->caller.id.number.str = ast_strdup(number); } } static void sccp_wrapper_asterisk18_setRedirectingParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { ast_party_number_free(&channel->owner->redirecting.from.number); channel->owner->redirecting.from.number.str = ast_strdup(number); channel->owner->redirecting.from.number.valid = 1; } if (name) { ast_party_name_free(&channel->owner->redirecting.from.name); channel->owner->redirecting.from.name.str = ast_strdup(name); channel->owner->redirecting.from.name.valid = 1; } } static void sccp_wrapper_asterisk18_setRedirectedParty(const sccp_channel_t * channel, const char *number, const char *name) { if (number) { channel->owner->redirecting.to.number.valid = 1; ast_party_number_free(&channel->owner->redirecting.to.number); channel->owner->redirecting.to.number.str = ast_strdup(number); } if (name) { channel->owner->redirecting.to.name.valid = 1; ast_party_name_free(&channel->owner->redirecting.to.name); channel->owner->redirecting.to.name.str = ast_strdup(name); } } static void sccp_wrapper_asterisk18_updateConnectedLine(const sccp_channel_t * channel, const char *number, const char *name, uint8_t reason) { struct ast_party_connected_line connected; struct ast_set_party_connected_line update_connected; memset(&update_connected, 0, sizeof(update_connected)); if (number) { update_connected.id.number = 1; connected.id.number.valid = 1; connected.id.number.str = (char *) number; connected.id.number.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } if (name) { update_connected.id.name = 1; connected.id.name.valid = 1; connected.id.name.str = (char *) name; connected.id.name.presentation = AST_PRES_ALLOWED_NETWORK_NUMBER; } connected.id.tag = NULL; connected.source = reason; ast_channel_queue_connected_line_update(channel->owner, &connected, &update_connected); } static int sccp_wrapper_asterisk18_sched_add(int when, sccp_sched_cb callback, const void *data) { if (sched) return ast_sched_add(sched, when, callback, data); return FALSE; } static long sccp_wrapper_asterisk18_sched_when(int id) { if (sched) return ast_sched_when(sched, id); return FALSE; } static int sccp_wrapper_asterisk18_sched_wait(int id) { if (sched) return ast_sched_wait(sched); return FALSE; } static int sccp_wrapper_asterisk18_sched_del(int id) { if (sched) return ast_sched_del(sched, id); return FALSE; } static int sccp_wrapper_asterisk18_setCallState(const sccp_channel_t * channel, int state) { sccp_pbx_setcallstate((sccp_channel_t *) channel, state); //! \todo implement correct return value (take into account negative deadlock prevention) return 0; } static boolean_t sccp_asterisk_getRemoteChannel(const sccp_channel_t * channel, PBX_CHANNEL_TYPE ** pbx_channel) { PBX_CHANNEL_TYPE *remotePeer; struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { if (pbx_find_channel_by_linkid(remotePeer, (void *) channel->owner->linkedid)) { break; } } ast_channel_iterator_destroy(iterator); if (remotePeer) { *pbx_channel = remotePeer; ast_channel_unref(remotePeer); return TRUE; } return FALSE; } /*! * \brief Send Text to Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param text Text to be send as char * \return Succes as int * * \called_from_asterisk */ static int sccp_pbx_sendtext(PBX_CHANNEL_TYPE * ast, const char *text) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; uint8_t instance; if (!ast) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No PBX CHANNEL to send text to\n"); return -1; } if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send text to (%s)\n", ast->name); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send text to (%s)\n", ast->name); c = sccp_channel_release(c); return -1; } if (!text || sccp_strlen_zero(text)) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: No text to send to %s\n", d->id, ast->name); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Sending text %s on %s\n", d->id, text, ast->name); instance = sccp_device_find_index_for_line(d, c->line->name); sccp_dev_displayprompt(d, instance, c->callid, (char *) text, 10); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! * \brief Receive First Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit First Digit as char * \return Always Return -1 as int * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_begin(PBX_CHANNEL_TYPE * ast, char digit) { return -1; } /*! * \brief Receive Last Digit from Asterisk Channel * \param ast Asterisk Channel as ast_channel * \param digit Last Digit as char * \param duration Duration as int * \return boolean * * \called_from_asterisk */ static int sccp_wrapper_recvdigit_end(PBX_CHANNEL_TYPE * ast, char digit, unsigned int duration) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP CHANNEL to send digit to (%s)\n", ast->name); return -1; } if (!(d = sccp_channel_getDevice_retained(c))) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: No SCCP DEVICE to send digit to (%s)\n", ast->name); c = sccp_channel_release(c); return -1; } sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "SCCP: Asterisk asked to send dtmf '%d' to channel %s. Trying to send it %s\n", digit, ast->name, (d->dtmfmode) ? "outofband" : "inband"); if (c->state != SCCP_CHANNELSTATE_CONNECTED) { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_3 "%s: Can't send the dtmf '%d' %c to a not connected channel %s\n", d->id, digit, digit, ast->name); d = sccp_device_release(d); c = sccp_channel_release(c); return -1; } sccp_dev_keypadbutton(d, digit, sccp_device_find_index_for_line(d, c->line->name), c->callid); d = sccp_device_release(d); c = sccp_channel_release(c); return -1; } static PBX_CHANNEL_TYPE *sccp_wrapper_asterisk18_findChannelWithCallback(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data, boolean_t lock) { PBX_CHANNEL_TYPE *remotePeer; struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); if (!lock) { ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; } for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { if (found_cb(remotePeer, data)) { ast_channel_lock(remotePeer); ast_channel_unref(remotePeer); break; } } ast_channel_iterator_destroy(iterator); return remotePeer; } /*! \brief Set an option on a asterisk channel */ #if 0 static int sccp_wrapper_asterisk18_setOption(PBX_CHANNEL_TYPE * ast, int option, void *data, int datalen) { int res = -1; sccp_channel_t *c = NULL; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } else { sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "%s: channel: %s(%s) setOption: %d\n", c->currentDeviceId, sccp_channel_toString(c), ast->name, option); //! if AST_OPTION_FORMAT_READ / AST_OPTION_FORMAT_WRITE are available we might be indication that we can do transcoding (channel.c:set_format). Correct ? */ switch (option) { case AST_OPTION_FORMAT_READ: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_read_format(c->rtp.audio.rtp, *(int *) data); } break; case AST_OPTION_FORMAT_WRITE: if (c->rtp.audio.rtp) { res = ast_rtp_instance_set_write_format(c->rtp.audio.rtp, *(int *) data); } break; case AST_OPTION_MAKE_COMPATIBLE: if (c->rtp.audio.rtp) { res = ast_rtp_instance_make_compatible(ast, c->rtp.audio.rtp, (PBX_CHANNEL_TYPE *) data); } break; case AST_OPTION_DIGIT_DETECT: case AST_OPTION_SECURE_SIGNALING: case AST_OPTION_SECURE_MEDIA: res = -1; break; default: break; } c = sccp_channel_release(c); } return res; } #endif static void sccp_wrapper_asterisk_set_pbxchannel_linkedid(PBX_CHANNEL_TYPE * pbx_channel, const char *new_linkedid) { if (pbx_channel) { if (!strcmp(pbx_channel->linkedid, new_linkedid)) { return; } #if HAVE_PBX_CEL_H ast_cel_check_retire_linkedid(pbx_channel); #endif ast_string_field_set(pbx_channel, linkedid, new_linkedid); } } #define DECLARE_PBX_CHANNEL_STRGET(_field) \ static const char *sccp_wrapper_asterisk_get_channel_##_field(const sccp_channel_t * channel) \ { \ static const char *empty_channel_##_field = "--no-channel-" #_field "--"; \ if (channel->owner) { \ return channel->owner->_field; \ } \ return empty_channel_##_field; \ }; #define DECLARE_PBX_CHANNEL_STRSET(_field) \ static void sccp_wrapper_asterisk_set_channel_##_field(const sccp_channel_t * channel, const char * _field) \ { \ if (channel->owner) { \ sccp_copy_string(channel->owner->_field, _field, sizeof(channel->owner->_field)); \ } \ }; DECLARE_PBX_CHANNEL_STRGET(name) DECLARE_PBX_CHANNEL_STRGET(uniqueid) DECLARE_PBX_CHANNEL_STRGET(appl) DECLARE_PBX_CHANNEL_STRGET(linkedid) DECLARE_PBX_CHANNEL_STRGET(exten) DECLARE_PBX_CHANNEL_STRSET(exten) DECLARE_PBX_CHANNEL_STRGET(context) DECLARE_PBX_CHANNEL_STRSET(context) DECLARE_PBX_CHANNEL_STRGET(macroexten) DECLARE_PBX_CHANNEL_STRSET(macroexten) DECLARE_PBX_CHANNEL_STRGET(macrocontext) DECLARE_PBX_CHANNEL_STRSET(macrocontext) DECLARE_PBX_CHANNEL_STRGET(call_forward) static void sccp_wrapper_asterisk_set_channel_linkedid(const sccp_channel_t * channel, const char *new_linkedid) { if (channel->owner) { sccp_wrapper_asterisk_set_pbxchannel_linkedid(channel->owner, new_linkedid); } } static void sccp_wrapper_asterisk_set_channel_call_forward(const sccp_channel_t * channel, const char *new_call_forward) { if (channel->owner) { pbx_string_field_set(channel->owner, call_forward, new_call_forward); } } static void sccp_wrapper_asterisk_set_channel_name(const sccp_channel_t * channel, const char *new_name) { if (channel->owner) { pbx_string_field_set(channel->owner, name, new_name); } } static enum ast_channel_state sccp_wrapper_asterisk_get_channel_state(const sccp_channel_t * channel) { if (channel->owner) { return channel->owner->_state; } return 0; } static const struct ast_pbx *sccp_wrapper_asterisk_get_channel_pbx(const sccp_channel_t * channel) { if (channel->owner) { return channel->owner->pbx; } return NULL; } static void sccp_wrapper_asterisk_set_channel_tech_pvt(const sccp_channel_t * channel) { if (channel->owner) { // channel->owner->tech_pvt = channel; } } static int sccp_pbx_sendHTML(PBX_CHANNEL_TYPE * ast, int subclass, const char *data, int datalen) { sccp_channel_t *c = NULL; sccp_device_t *d = NULL; if (!datalen || sccp_strlen_zero(data) || !(!strncmp(data, "http://", 7) || !strncmp(data, "file://", 7) || !strncmp(data, "ftp://", 6))) { pbx_log(LOG_NOTICE, "SCCP: Received a non valid URL\n"); return -1; } struct ast_frame fr; if (!(c = get_sccp_channel_from_pbx_channel(ast))) { return -1; } #if DEBUG if (!(d = c->getDevice_retained(c, __FILE__, __LINE__, __PRETTY_FUNCTION__))) { #else if (!(d = c->getDevice_retained(c))) { #endif c = sccp_channel_release(c); return -1; } memset(&fr, 0, sizeof(fr)); fr.frametype = AST_FRAME_HTML; fr.data.ptr = (char *) data; fr.src = "SCCP Send URL"; fr.datalen = datalen; sccp_push_result_t pushResult = d->pushURL(d, data, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { fr.subclass.integer = AST_HTML_LDCOMPLETE; } else { fr.subclass.integer = AST_HTML_NOSUPPORT; } ast_queue_frame(ast, ast_frisolate(&fr)); d = sccp_device_release(d); c = sccp_channel_release(c); return 0; } /*! * \brief Queue a control frame * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type */ int sccp_asterisk_queue_control(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Queue a control frame with payload * \param pbx_channel PBX Channel * \param control as Asterisk Control Frame Type * \param data Payload * \param datalen Payload Length */ int sccp_asterisk_queue_control_data(const PBX_CHANNEL_TYPE * pbx_channel, enum ast_control_frame_type control, const void *data, size_t datalen) { struct ast_frame f = { AST_FRAME_CONTROL,.subclass.integer = control,.data.ptr = (void *) data,.datalen = datalen }; return ast_queue_frame((PBX_CHANNEL_TYPE *) pbx_channel, &f); } /*! * \brief Get Hint Extension State and return the matching Busy Lamp Field State */ static skinny_busylampfield_state_t sccp_wrapper_asterisk108_getExtensionState(const char *extension, const char *context) { skinny_busylampfield_state_t result = SKINNY_BLF_STATUS_UNKNOWN; if (sccp_strlen_zero(extension) || sccp_strlen_zero(context)) { pbx_log(LOG_ERROR, "SCCP: PBX(getExtensionState): Either extension:'%s' or context:;%s' provided is empty\n", extension, context); return result; } int state = ast_extension_state(NULL, context, extension); switch (state) { case AST_EXTENSION_REMOVED: case AST_EXTENSION_DEACTIVATED: case AST_EXTENSION_UNAVAILABLE: result = SKINNY_BLF_STATUS_UNKNOWN; break; case AST_EXTENSION_NOT_INUSE: result = SKINNY_BLF_STATUS_IDLE; break; case AST_EXTENSION_INUSE: case AST_EXTENSION_ONHOLD: case AST_EXTENSION_ONHOLD + AST_EXTENSION_INUSE: case AST_EXTENSION_BUSY: result = SKINNY_BLF_STATUS_INUSE; break; case AST_EXTENSION_RINGING + AST_EXTENSION_INUSE: case AST_EXTENSION_RINGING: result = SKINNY_BLF_STATUS_ALERTING; break; } sccp_log(DEBUGCAT_HINT) (VERBOSE_PREFIX_4 "SCCP: (getExtensionState) extension: %s@%s, extension_state: '%s (%d)' -> blf state '%d'\n", extension, context, ast_extension_state2str(state), state, result); return result; } #if defined(__cplusplus) || defined(c_plusplus) struct ast_rtp_glue sccp_rtp = { /* *INDENT-OFF* */ type: SCCP_TECHTYPE_STR, mod: NULL, get_rtp_info: sccp_wrapper_asterisk18_get_rtp_peer, get_vrtp_info: sccp_wrapper_asterisk18_get_vrtp_peer, get_trtp_info: NULL, update_peer: sccp_wrapper_asterisk18_set_rtp_peer, get_codec: sccp_wrapper_asterisk18_getCodec, /* *INDENT-ON* */ }; #else /*! * \brief using RTP Glue Engine */ struct ast_rtp_glue sccp_rtp = { .type = SCCP_TECHTYPE_STR, .get_rtp_info = sccp_wrapper_asterisk18_get_rtp_peer, .get_vrtp_info = sccp_wrapper_asterisk18_get_vrtp_peer, .update_peer = sccp_wrapper_asterisk18_set_rtp_peer, .get_codec = sccp_wrapper_asterisk18_getCodec, }; #endif #ifdef HAVE_PBX_MESSAGE_H #include "asterisk/message.h" static int sccp_asterisk_message_send(const struct ast_msg *msg, const char *to, const char *from) { char *lineName; sccp_line_t *line; const char *messageText = ast_msg_get_body(msg); int res = -1; lineName = (char *) sccp_strdupa(to); if (strchr(lineName, '@')) { strsep(&lineName, "@"); } else { strsep(&lineName, ":"); } if (sccp_strlen_zero(lineName)) { pbx_log(LOG_WARNING, "MESSAGE(to) is invalid for SCCP - '%s'\n", to); return -1; } line = sccp_line_find_byname(lineName, FALSE); if (!line) { pbx_log(LOG_WARNING, "line '%s' not found\n", lineName); return -1; } /** \todo move this to line implementation */ sccp_linedevices_t *linedevice; sccp_push_result_t pushResult; SCCP_LIST_LOCK(&line->devices); SCCP_LIST_TRAVERSE(&line->devices, linedevice, list) { pushResult = linedevice->device->pushTextMessage(linedevice->device, messageText, from, 1, SKINNY_TONE_ZIP); if (SCCP_PUSH_RESULT_SUCCESS == pushResult) { res = 0; } } SCCP_LIST_UNLOCK(&line->devices); return res; } #if defined(__cplusplus) || defined(c_plusplus) static const struct ast_msg_tech sccp_msg_tech = { /* *INDENT-OFF* */ name: "sccp", msg_send: sccp_asterisk_message_send, /* *INDENT-ON* */ }; #else static const struct ast_msg_tech sccp_msg_tech = { .name = "sccp", .msg_send = sccp_asterisk_message_send, }; #endif #endif boolean_t sccp_wrapper_asterisk_setLanguage(PBX_CHANNEL_TYPE * pbxChannel, const char *newLanguage) { ast_string_field_set(pbxChannel, language, newLanguage); return TRUE; } #if defined(__cplusplus) || defined(c_plusplus) sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ alloc_pbxChannel: sccp_wrapper_asterisk18_allocPBXChannel, set_callstate: sccp_wrapper_asterisk18_setCallState, checkhangup: sccp_wrapper_asterisk18_checkHangup, hangup: NULL, requestHangup: sccp_wrapper_asterisk_requestHangup, forceHangup: sccp_wrapper_asterisk_forceHangup, extension_status: sccp_wrapper_asterisk18_extensionStatus, setPBXChannelLinkedId: sccp_wrapper_asterisk_set_pbxchannel_linkedid, /** get channel by name */ getChannelByName: sccp_wrapper_asterisk18_getChannelByName, getRemoteChannel: sccp_asterisk_getRemoteChannel, getChannelByCallback: NULL, getChannelLinkedId: sccp_wrapper_asterisk_get_channel_linkedid, setChannelLinkedId: sccp_wrapper_asterisk_set_channel_linkedid, getChannelName: sccp_wrapper_asterisk_get_channel_name, setChannelName: sccp_wrapper_asterisk_set_channel_name, getChannelUniqueID: sccp_wrapper_asterisk_get_channel_uniqueid, getChannelExten: sccp_wrapper_asterisk_get_channel_exten, setChannelExten: sccp_wrapper_asterisk_set_channel_exten, getChannelContext: sccp_wrapper_asterisk_get_channel_context, setChannelContext: sccp_wrapper_asterisk_set_channel_context, getChannelMacroExten: sccp_wrapper_asterisk_get_channel_macroexten, setChannelMacroExten: sccp_wrapper_asterisk_set_channel_macroexten, getChannelMacroContext: sccp_wrapper_asterisk_get_channel_macrocontext, setChannelMacroContext: sccp_wrapper_asterisk_set_channel_macrocontext, getChannelCallForward: sccp_wrapper_asterisk_get_channel_call_forward, setChannelCallForward: sccp_wrapper_asterisk_set_channel_call_forward, getChannelAppl: sccp_wrapper_asterisk_get_channel_appl, getChannelState: sccp_wrapper_asterisk_get_channel_state, getChannelPbx: sccp_wrapper_asterisk_get_channel_pbx, setChannelTechPVT: sccp_wrapper_asterisk_set_channel_tech_pvt, set_nativeAudioFormats: sccp_wrapper_asterisk18_setNativeAudioFormats, set_nativeVideoFormats: sccp_wrapper_asterisk18_setNativeVideoFormats, getPeerCodecCapabilities: NULL, send_digit: sccp_wrapper_asterisk18_sendDigit, send_digits: sccp_wrapper_asterisk18_sendDigits, sched_add: sccp_wrapper_asterisk18_sched_add, sched_del: sccp_wrapper_asterisk18_sched_del, sched_when: sccp_wrapper_asterisk18_sched_when, sched_wait: sccp_wrapper_asterisk18_sched_wait, /* rtp */ rtp_getPeer: sccp_wrapper_asterisk18_rtpGetPeer, rtp_getUs: sccp_wrapper_asterisk18_rtpGetUs, rtp_setPeer: sccp_wrapper_asterisk18_rtp_set_peer, rtp_setWriteFormat: sccp_wrapper_asterisk18_setWriteFormat, rtp_setReadFormat: sccp_wrapper_asterisk18_setReadFormat, rtp_destroy: sccp_wrapper_asterisk18_destroyRTP, rtp_stop: sccp_wrapper_asterisk18_rtp_stop, rtp_codec: NULL, rtp_audio_create: sccp_wrapper_asterisk18_create_audio_rtp, rtp_video_create: sccp_wrapper_asterisk18_create_video_rtp, rtp_get_payloadType: sccp_wrapper_asterisk18_get_payloadType, rtp_get_sampleRate: sccp_wrapper_asterisk18_get_sampleRate, rtp_bridgePeers: NULL, /* callerid */ get_callerid_name: sccp_wrapper_asterisk18_callerid_name, get_callerid_number: sccp_wrapper_asterisk18_callerid_number, get_callerid_ton: sccp_wrapper_asterisk18_callerid_ton, get_callerid_ani: sccp_wrapper_asterisk18_callerid_ani, get_callerid_subaddr: sccp_wrapper_asterisk18_callerid_subaddr, get_callerid_dnid: sccp_wrapper_asterisk18_callerid_dnid, get_callerid_rdnis: sccp_wrapper_asterisk18_callerid_rdnis, get_callerid_presence: sccp_wrapper_asterisk18_callerid_presence, set_callerid_name: sccp_wrapper_asterisk18_setCalleridName, set_callerid_number: sccp_wrapper_asterisk18_setCalleridNumber, set_callerid_ani: NULL, set_callerid_dnid: NULL, set_callerid_redirectingParty: sccp_wrapper_asterisk18_setRedirectingParty, set_callerid_redirectedParty: sccp_wrapper_asterisk18_setRedirectedParty, set_callerid_presence: sccp_wrapper_asterisk18_setCalleridPresence, set_connected_line: sccp_wrapper_asterisk18_updateConnectedLine, sendRedirectedUpdate: sccp_asterisk_sendRedirectedUpdate, /* feature section */ feature_park: sccp_wrapper_asterisk18_park, feature_stopMusicOnHold: NULL, feature_addToDatabase: sccp_asterisk_addToDatabase, feature_getFromDatabase: sccp_asterisk_getFromDatabase, feature_removeFromDatabase: sccp_asterisk_removeFromDatabase, feature_removeTreeFromDatabase: sccp_asterisk_removeTreeFromDatabase, feature_monitor: sccp_wrapper_asterisk_featureMonitor, getFeatureExtension: sccp_wrapper_asterisk18_getFeatureExtension, feature_pickup: sccp_wrapper_asterisk18_pickupChannel, eventSubscribe: NULL, findChannelByCallback: sccp_wrapper_asterisk18_findChannelWithCallback, moh_start: sccp_asterisk_moh_start, moh_stop: sccp_asterisk_moh_stop, queue_control: sccp_asterisk_queue_control, queue_control_data: sccp_asterisk_queue_control_data, allocTempPBXChannel: sccp_wrapper_asterisk18_allocTempPBXChannel, masqueradeHelper: sccp_wrapper_asterisk18_masqueradeHelper, requestForeignChannel: sccp_wrapper_asterisk18_requestForeignChannel, set_language: sccp_wrapper_asterisk_setLanguage, getExtensionState: sccp_wrapper_asterisk108_getExtensionState, findPickupChannelByExtenLocked: sccp_wrapper_asterisk18_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #else /*! * \brief SCCP - PBX Callback Functions * (Decoupling Tight Dependencies on Asterisk Functions) */ struct sccp_pbx_cb sccp_pbx = { /* *INDENT-OFF* */ /* channel */ .alloc_pbxChannel = sccp_wrapper_asterisk18_allocPBXChannel, .requestHangup = sccp_wrapper_asterisk_requestHangup, .forceHangup = sccp_wrapper_asterisk_forceHangup, .extension_status = sccp_wrapper_asterisk18_extensionStatus, .setPBXChannelLinkedId = sccp_wrapper_asterisk_set_pbxchannel_linkedid, .getChannelByName = sccp_wrapper_asterisk18_getChannelByName, .getChannelLinkedId = sccp_wrapper_asterisk_get_channel_linkedid, .setChannelLinkedId = sccp_wrapper_asterisk_set_channel_linkedid, .getChannelName = sccp_wrapper_asterisk_get_channel_name, .setChannelName = sccp_wrapper_asterisk_set_channel_name, .getChannelUniqueID = sccp_wrapper_asterisk_get_channel_uniqueid, .getChannelExten = sccp_wrapper_asterisk_get_channel_exten, .setChannelExten = sccp_wrapper_asterisk_set_channel_exten, .getChannelContext = sccp_wrapper_asterisk_get_channel_context, .setChannelContext = sccp_wrapper_asterisk_set_channel_context, .getChannelMacroExten = sccp_wrapper_asterisk_get_channel_macroexten, .setChannelMacroExten = sccp_wrapper_asterisk_set_channel_macroexten, .getChannelMacroContext = sccp_wrapper_asterisk_get_channel_macrocontext, .setChannelMacroContext = sccp_wrapper_asterisk_set_channel_macrocontext, .getChannelCallForward = sccp_wrapper_asterisk_get_channel_call_forward, .setChannelCallForward = sccp_wrapper_asterisk_set_channel_call_forward, .getChannelAppl = sccp_wrapper_asterisk_get_channel_appl, .getChannelState = sccp_wrapper_asterisk_get_channel_state, .getChannelPbx = sccp_wrapper_asterisk_get_channel_pbx, .setChannelTechPVT = sccp_wrapper_asterisk_set_channel_tech_pvt, .getRemoteChannel = sccp_asterisk_getRemoteChannel, .checkhangup = sccp_wrapper_asterisk18_checkHangup, /* digits */ .send_digits = sccp_wrapper_asterisk18_sendDigits, .send_digit = sccp_wrapper_asterisk18_sendDigit, /* schedulers */ .sched_add = sccp_wrapper_asterisk18_sched_add, .sched_del = sccp_wrapper_asterisk18_sched_del, .sched_when = sccp_wrapper_asterisk18_sched_when, .sched_wait = sccp_wrapper_asterisk18_sched_wait, /* callstate / indicate */ .set_callstate = sccp_wrapper_asterisk18_setCallState, /* codecs */ .set_nativeAudioFormats = sccp_wrapper_asterisk18_setNativeAudioFormats, .set_nativeVideoFormats = sccp_wrapper_asterisk18_setNativeVideoFormats, /* rtp */ .rtp_getPeer = sccp_wrapper_asterisk18_rtpGetPeer, .rtp_getUs = sccp_wrapper_asterisk18_rtpGetUs, .rtp_stop = sccp_wrapper_asterisk18_rtp_stop, .rtp_audio_create = sccp_wrapper_asterisk18_create_audio_rtp, .rtp_video_create = sccp_wrapper_asterisk18_create_video_rtp, .rtp_get_payloadType = sccp_wrapper_asterisk18_get_payloadType, .rtp_get_sampleRate = sccp_wrapper_asterisk18_get_sampleRate, .rtp_destroy = sccp_wrapper_asterisk18_destroyRTP, .rtp_setWriteFormat = sccp_wrapper_asterisk18_setWriteFormat, .rtp_setReadFormat = sccp_wrapper_asterisk18_setReadFormat, .rtp_setPeer = sccp_wrapper_asterisk18_rtp_set_peer, /* callerid */ .get_callerid_name = sccp_wrapper_asterisk18_callerid_name, .get_callerid_number = sccp_wrapper_asterisk18_callerid_number, .get_callerid_ton = sccp_wrapper_asterisk18_callerid_ton, .get_callerid_ani = sccp_wrapper_asterisk18_callerid_ani, .get_callerid_subaddr = sccp_wrapper_asterisk18_callerid_subaddr, .get_callerid_dnid = sccp_wrapper_asterisk18_callerid_dnid, .get_callerid_rdnis = sccp_wrapper_asterisk18_callerid_rdnis, .get_callerid_presence = sccp_wrapper_asterisk18_callerid_presence, .set_callerid_name = sccp_wrapper_asterisk18_setCalleridName, //! \todo implement callback .set_callerid_number = sccp_wrapper_asterisk18_setCalleridNumber, //! \todo implement callback .set_callerid_dnid = NULL, //! \todo implement callback .set_callerid_redirectingParty = sccp_wrapper_asterisk18_setRedirectingParty, .set_callerid_redirectedParty = sccp_wrapper_asterisk18_setRedirectedParty, .set_callerid_presence = sccp_wrapper_asterisk18_setCalleridPresence, .set_connected_line = sccp_wrapper_asterisk18_updateConnectedLine, .sendRedirectedUpdate = sccp_asterisk_sendRedirectedUpdate, /* database */ .feature_addToDatabase = sccp_asterisk_addToDatabase, .feature_getFromDatabase = sccp_asterisk_getFromDatabase, .feature_removeFromDatabase = sccp_asterisk_removeFromDatabase, .feature_removeTreeFromDatabase = sccp_asterisk_removeTreeFromDatabase, .feature_park = sccp_wrapper_asterisk18_park, .feature_monitor = sccp_wrapper_asterisk_featureMonitor, .getFeatureExtension = sccp_wrapper_asterisk18_getFeatureExtension, .feature_pickup = sccp_wrapper_asterisk18_pickupChannel, .findChannelByCallback = sccp_wrapper_asterisk18_findChannelWithCallback, .moh_start = sccp_asterisk_moh_start, .moh_stop = sccp_asterisk_moh_stop, .queue_control = sccp_asterisk_queue_control, .queue_control_data = sccp_asterisk_queue_control_data, .allocTempPBXChannel = sccp_wrapper_asterisk18_allocTempPBXChannel, .masqueradeHelper = sccp_wrapper_asterisk18_masqueradeHelper, .requestForeignChannel = sccp_wrapper_asterisk18_requestForeignChannel, .set_language = sccp_wrapper_asterisk_setLanguage, .getExtensionState = sccp_wrapper_asterisk108_getExtensionState, .findPickupChannelByExtenLocked = sccp_wrapper_asterisk18_findPickupChannelByExtenLocked, /* *INDENT-ON* */ }; #endif #if defined(__cplusplus) || defined(c_plusplus) static ast_module_load_result load_module(void) #else static int load_module(void) #endif { boolean_t res; /* check for existance of chan_skinny */ if (ast_module_check("chan_skinny.so")) { pbx_log(LOG_ERROR, "Chan_skinny is loaded. Please check modules.conf and remove chan_skinny before loading chan_sccp.\n"); return AST_MODULE_LOAD_DECLINE; } sched = sched_context_create(); if (!sched) { pbx_log(LOG_WARNING, "Unable to create schedule context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } /* make globals */ res = sccp_prePBXLoad(); if (!res) { return AST_MODULE_LOAD_DECLINE; } io = io_context_create(); if (!io) { pbx_log(LOG_WARNING, "Unable to create I/O context. SCCP channel type disabled\n"); return AST_MODULE_LOAD_FAILURE; } //! \todo how can we handle this in a pbx independent way? if (!load_config()) { if (ast_channel_register(&sccp_tech)) { pbx_log(LOG_ERROR, "Unable to register channel class SCCP\n"); return AST_MODULE_LOAD_FAILURE; } } #ifdef HAVE_PBX_MESSAGE_H if (ast_msg_tech_register(&sccp_msg_tech)) { /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */ pbx_log(LOG_WARNING, "Unable to register message interface\n"); } #endif // ast_enable_distributed_devstate(); // ast_rtp_glue_register(&sccp_rtp); sccp_register_management(); sccp_register_cli(); sccp_register_dialplan_functions(); /* And start the monitor for the first time */ sccp_restart_monitor(); sccp_postPBX_load(); return AST_MODULE_LOAD_SUCCESS; } int sccp_restart_monitor() { /* If we're supposed to be stopped -- stay stopped */ if (GLOB(monitor_thread) == AST_PTHREADT_STOP) return 0; ast_mutex_lock(&GLOB(monitor_lock)); if (GLOB(monitor_thread) == pthread_self()) { ast_mutex_unlock(&GLOB(monitor_lock)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SCCP)) (VERBOSE_PREFIX_3 "SCCP: (sccp_restart_monitor) Cannot kill myself\n"); return -1; } if (GLOB(monitor_thread) != AST_PTHREADT_NULL) { /* Wake up the thread */ pthread_kill(GLOB(monitor_thread), SIGURG); } else { /* Start a new monitor */ if (ast_pthread_create_background(&GLOB(monitor_thread), NULL, sccp_do_monitor, NULL) < 0) { ast_mutex_unlock(&GLOB(monitor_lock)); sccp_log((DEBUGCAT_CORE | DEBUGCAT_SCCP)) (VERBOSE_PREFIX_3 "SCCP: (sccp_restart_monitor) Unable to start monitor thread.\n"); return -1; } } ast_mutex_unlock(&GLOB(monitor_lock)); return 0; } static int unload_module(void) { sccp_preUnload(); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP RTP protocol\n"); // ast_rtp_glue_unregister(&sccp_rtp); sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Unregister SCCP Channel Tech\n"); ast_channel_unregister(&sccp_tech); sccp_unregister_dialplan_functions(); sccp_unregister_cli(); sccp_mwi_module_stop(); #ifdef CS_SCCP_MANAGER sccp_unregister_management(); #endif #ifdef HAVE_PBX_MESSAGE_H ast_msg_tech_unregister(&sccp_msg_tech); #endif sccp_globals_lock(monitor_lock); if ((GLOB(monitor_thread) != AST_PTHREADT_NULL) && (GLOB(monitor_thread) != AST_PTHREADT_STOP)) { pthread_cancel(GLOB(monitor_thread)); pthread_kill(GLOB(monitor_thread), SIGURG); #ifndef HAVE_LIBGC pthread_join(GLOB(monitor_thread), NULL); #endif } GLOB(monitor_thread) = AST_PTHREADT_STOP; if (io) { io_context_destroy(io); io = NULL; } while (SCCP_REF_DESTROYED != sccp_refcount_isRunning()) { usleep(SCCP_TIME_TO_KEEP_REFCOUNTEDOBJECT); // give enough time for all schedules to end and refcounted object to be cleanup completely } if (sched) { pbx_log(LOG_NOTICE, "Cleaning up scheduled items:\n"); int scheduled_items = 0; ast_sched_dump(sched); while ((scheduled_items = ast_sched_runq(sched))) { pbx_log(LOG_NOTICE, "Cleaning up %d scheduled items... please wait\n", scheduled_items); usleep(ast_sched_wait(sched)); } sched_context_destroy(sched); sched = NULL; } sccp_globals_unlock(monitor_lock); sccp_mutex_destroy(&GLOB(monitor_lock)); sccp_free(sccp_globals); pbx_log(LOG_NOTICE, "Running Cleanup\n"); #ifdef HAVE_LIBGC // sccp_log((DEBUGCAT_CORE)) (VERBOSE_PREFIX_2 "SCCP: Collect a little:%d\n",GC_collect_a_little()); // CHECK_LEAKS(); // GC_gcollect(); #endif pbx_log(LOG_NOTICE, "Module chan_sccp unloaded\n"); return 0; } static int module_reload(void) { sccp_reload(); return 0; } #if defined(__cplusplus) || defined(c_plusplus) static struct ast_module_info __mod_info = { NULL, load_module, module_reload, unload_module, NULL, NULL, AST_MODULE, "Skinny Client Control Protocol (SCCP). Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)", ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, AST_BUILDOPT_SUM, AST_MODPRI_CHANNEL_DRIVER, NULL, }; static void __attribute__ ((constructor)) __reg_module(void) { ast_module_register(&__mod_info); } static void __attribute__ ((destructor)) __unreg_module(void) { ast_module_unregister(&__mod_info); } static const __attribute__ ((unused)) struct ast_module_info *ast_module_info = &__mod_info; #else AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Skinny Client Control Protocol (SCCP). SCCP-Release: " SCCP_VERSION " " SCCP_BRANCH " (built by '" BUILD_USER "' on '" BUILD_DATE "', NULL)",.load = load_module,.unload = unload_module,.reload = module_reload,.load_pri = AST_MODPRI_DEFAULT,.nonoptreq = "res_rtp_asterisk,chan_local",); #endif PBX_CHANNEL_TYPE *sccp_search_remotepeer_locked(int (*const found_cb) (PBX_CHANNEL_TYPE * c, void *data), void *data) { PBX_CHANNEL_TYPE *remotePeer; struct ast_channel_iterator *iterator = ast_channel_iterator_all_new(); ((struct ao2_iterator *) iterator)->flags |= AO2_ITERATOR_DONTLOCK; for (; (remotePeer = ast_channel_iterator_next(iterator)); ast_channel_unref(remotePeer)) { if (found_cb(remotePeer, data)) { ast_channel_lock(remotePeer); ast_channel_unref(remotePeer); break; } } ast_channel_iterator_destroy(iterator); return remotePeer; } PBX_CHANNEL_TYPE *sccp_wrapper_asterisk18_findPickupChannelByExtenLocked(PBX_CHANNEL_TYPE * chan, const char *exten, const char *context) { struct ast_channel *target = NULL; /*!< Potential pickup target */ struct ast_channel_iterator *iter; if (!(iter = ast_channel_iterator_by_exten_new(exten, context))) { return NULL; } while ((target = ast_channel_iterator_next(iter))) { ast_channel_lock(target); if ((chan != target) && ast_can_pickup(target)) { ast_log(LOG_NOTICE, "%s pickup by %s\n", target->name, chan->name); break; } ast_channel_unlock(target); target = ast_channel_unref(target); } ast_channel_iterator_destroy(iter); return target; }
722,277
./kerberos-android-ndk/jni/kerberosapp.c
/* * kerberosapp.c * * Copyright (C) 2012 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * Original source developed by yaSSL (http://www.yassl.com) * */ #include <stdio.h> #include <stdlib.h> #include "edu_mit_kerberos_KerberosAppActivity.h" #include "kerberosapp.h" /* Global JNI Variables */ JavaVM* cached_jvm; jobject cached_obj; /* * Generate NULL-terminated argv array from a string. * Note: argv begins with command name, and is * NULL terminated (thus the +2) */ void generateArgv(char* input, int argc, char** argv) { int i; char* tmp; LOGI("Entered generateArgv"); for(i = 0; i < argc+2; i++) { if(i == 0) { /* add command name */ argv[i] = (char*)malloc(5*sizeof(char*)); strcpy(argv[i], "kinit"); } else if (i == argc+1) /* add NULL termination */ argv[i] = NULL; else if (i == 1) { tmp = strtok(input, " "); argv[i] = (char*)malloc((strlen(tmp)+1)*sizeof(char*)); strcpy(argv[i], tmp); } else { tmp = strtok(NULL, " "); argv[i] = (char*)malloc((strlen(tmp)+1)*sizeof(char*)); strcpy(argv[i], tmp); } } return; } /* * Free argv array. */ void releaseArgv(int argc, char** argv) { int i; for (i = 0; i < argc; i++){ free(argv[i]); } free(argv); } /* * Get the current JNIEnv pointer from global JavaVM. */ JNIEnv* GetJNIEnv(JavaVM *jvm) { JNIEnv *env; int status; status = (*jvm)->GetEnv(jvm, (void **) &env, JNI_VERSION_1_6); if (status < 0) { LOGI("Unable to get JNIEnv pointer from JavaVM"); return NULL; } return env; } /* * Is called automatically when library is loaded. */ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { JNIEnv* env; LOGI("Loaded libkerberosapp"); if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) return -1; /* Cache our JavaVM pointer */ cached_jvm = jvm; return JNI_VERSION_1_6; } /* * Is called automatically when library is unloaded. */ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, void *reserved) { JNIEnv *env; if( (env = GetJNIEnv(jvm)) == NULL) { return; } (*env)->DeleteGlobalRef(env, cached_obj); return; } /* * Class: edu_mit_kerberos_KerberosAppActivity * Method: nativeSetKRB5CCNAME * Signature: (Ljava/lang/String)I * * Set the KRB5CCNAME environment variable to point to our desired * ticket cache. * */ JNIEXPORT jint JNICALL Java_edu_mit_kerberos_KerberosAppActivity_nativeSetKRB5CCNAME (JNIEnv* env, jobject obj, jstring argString) { jboolean isCopy; int ret; const char *args; /* Get original KRB5CCNAME path string from Java */ args = (*env)->GetStringUTFChars(env, argString, &isCopy); ret = setenv("KRB5CCNAME", args, 1); /* free argString */ (*env)->ReleaseStringUTFChars(env, argString, args); return ret; } /* * Class: edu_mit_kerberos_KerberosAppActivity * Method: nativeSetKRB5CONFIG * Signature: (Ljava/lang/String)I * * Set the KRB5_CONFIG environment variable to point to our desired * Kerberos configuration file. * */ JNIEXPORT jint JNICALL Java_edu_mit_kerberos_KerberosAppActivity_nativeSetKRB5CONFIG (JNIEnv* env, jobject obj, jstring argString) { jboolean isCopy; int ret; const char *args; /* Get original KRB5_CONFIG path string from Java */ args = (*env)->GetStringUTFChars(env, argString, &isCopy); ret = setenv("KRB5_CONFIG", args, 1); /* free argString */ (*env)->ReleaseStringUTFChars(env, argString, args); return ret; } /* * Class: edu_mit_kerberos_KerberosAppActivity * Method: nativeKinit * Signature: (Ljava/lang/String;I)I * * Wrapper around native kinit application * */ JNIEXPORT jint JNICALL Java_edu_mit_kerberos_KerberosAppActivity_nativeKinit (JNIEnv* env, jobject obj, jstring argString, jint argCount) { jboolean isCopy; int ret; int numArgs = (int) argCount; const char *args; char *args_copy; char **argv = (char**)malloc((numArgs+2) * sizeof(char*)); /* Cache a reference to the calling object */ cached_obj = (*env)->NewGlobalRef(env, obj); /* get original argv string from Java */ args = (*env)->GetStringUTFChars(env, argString, &isCopy); /* make a copy of argString to use with strtok */ args_copy = malloc(strlen(args) + 1); strcpy(args_copy, args); /* free argString */ (*env)->ReleaseStringUTFChars(env, argString, args); /* generate argv list */ generateArgv(args_copy, numArgs, argv); /* run kinit */ ret = kinit_driver(env, obj, numArgs+1, argv); free(args_copy); releaseArgv(numArgs+1, argv); if(ret == 1) return 1; return 0; } /* * Class: edu_mit_kerberos_KerberosAppActivity * Method: nativeKlist * Signature: (Ljava/lang/String;I)I * * Wrapper around native klist application * */ JNIEXPORT jint JNICALL Java_edu_mit_kerberos_KerberosAppActivity_nativeKlist (JNIEnv* env, jobject obj, jstring argString, jint argCount) { jboolean isCopy; int ret; int numArgs = (int) argCount; const char *args; char *args_copy; char **argv = (char**)malloc((numArgs+2) * sizeof(char*)); /* Cache a reference to the calling object */ cached_obj = (*env)->NewGlobalRef(env, obj); /* get original argv string from Java */ args = (*env)->GetStringUTFChars(env, argString, &isCopy); /* make a copy of argString to use with strtok */ args_copy = malloc(strlen(args) + 1); strcpy(args_copy, args); /* free argString */ (*env)->ReleaseStringUTFChars(env, argString, args); /* generate argv list */ generateArgv(args_copy, numArgs, argv); /* run kinit */ ret = klist_driver(env, obj, numArgs+1, argv); free(args_copy); releaseArgv(numArgs+1, argv); if(ret == 1) return 1; return 0; } /* * Class: edu_mit_kerberos_KerberosAppActivity * Method: nativeKvno * Signature: (Ljava/lang/String;I)I * * Wrapper around native kvno application * */ JNIEXPORT jint JNICALL Java_edu_mit_kerberos_KerberosAppActivity_nativeKvno (JNIEnv* env, jobject obj, jstring argString, jint argCount) { jboolean isCopy; int ret; int numArgs = (int) argCount; const char *args; char *args_copy; char **argv = (char**)malloc((numArgs+2) * sizeof(char*)); /* Cache a reference to the calling object */ cached_obj = (*env)->NewGlobalRef(env, obj); /* get original argv string from Java */ args = (*env)->GetStringUTFChars(env, argString, &isCopy); /* make a copy of argString to use with strtok */ args_copy = malloc(strlen(args) + 1); strcpy(args_copy, args); /* free argString */ (*env)->ReleaseStringUTFChars(env, argString, args); /* generate argv list */ generateArgv(args_copy, numArgs, argv); /* run kinit */ ret = kvno_driver(env, obj, numArgs+1, argv); free(args_copy); releaseArgv(numArgs+1, argv); if(ret == 1) return 1; return 0; } /* * Class: edu_mit_kerberos_KerberosAppActivity * Method: nativeKdestroy * Signature: (Ljava/lang/String;I)I * * Wrapper around native kdestroy application * */ JNIEXPORT jint JNICALL Java_edu_mit_kerberos_KerberosAppActivity_nativeKdestroy (JNIEnv* env, jobject obj, jstring argString, jint argCount) { jboolean isCopy; int ret; int numArgs = (int) argCount; const char *args; char *args_copy; char **argv = (char**)malloc((numArgs+2) * sizeof(char*)); /* Cache a reference to the calling object */ cached_obj = (*env)->NewGlobalRef(env, obj); /* get original argv string from Java */ args = (*env)->GetStringUTFChars(env, argString, &isCopy); /* make a copy of argString to use with strtok */ args_copy = malloc(strlen(args) + 1); strcpy(args_copy, args); /* free argString */ (*env)->ReleaseStringUTFChars(env, argString, args); /* generate argv list */ generateArgv(args_copy, numArgs, argv); /* run kdestroy */ ret = kdestroy_driver(env, obj, numArgs+1, argv); free(args_copy); releaseArgv(numArgs+1, argv); if(ret == 1) return 1; return 0; } /* * Android log function, printf-style. * Logs input string to GUI TextView. */ void androidPrint(const char* format, ...) { va_list args; char appendString[4096]; va_start(args, format); vsnprintf(appendString, sizeof(appendString), format, args); appendText(appendString); va_end(args); } /* * Android error log function, replaces com_err calls */ void androidError(const char* progname, errcode_t code, const char* format, ...) { va_list args; char errString[4096] = "Error "; va_start(args, format); vsnprintf(errString+6, sizeof(errString), format, args); strcat(errString, "\n"); appendText(errString); va_end(args); } /* * Appends text to Java TextView. * * Note: Set jni_env, class_obj before calling. * Return: 0 (success), 1 (failure) */ int appendText(char* input) { JNIEnv* env; jclass cls; /* edu.mit.kerberos.KerberosApp */ jmethodID mid; /* edu.mit.kerberos.KerberosApp.appendText() */ jstring javaOutput; /* text to append */ env = GetJNIEnv(cached_jvm); cls = (*env)->GetObjectClass(env, cached_obj); mid = (*env)->GetMethodID(env, cls, "appendText", "(Ljava/lang/String;)V"); if (mid == 0) { LOGI("Unable to find Java appendText method"); return 1; } else { javaOutput = (*env)->NewStringUTF(env, input); if (env == NULL || cached_obj == NULL || mid == NULL || javaOutput == NULL) { LOGI("We have a null variable in native code"); return 1; } (*env)->CallVoidMethod(env, cached_obj, mid, javaOutput); } return 0; }
722,278
./kerberos-android-ndk/jni/kdestroy/kdestroy.c
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* clients/kdestroy/kdestroy.c - Destroy contents of credential cache */ /* * Copyright 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #include "k5-platform.h" #include <krb5.h> #include <com_err.h> #include <string.h> #include <stdio.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef _WIN32 #include <getopt.h> #endif #ifdef __STDC__ #define BELL_CHAR '\a' #else #define BELL_CHAR '\007' #endif #ifdef ANDROID #include "kerberosapp.h" static JNIEnv* jni_env; static jobject class_obj; #else #define log(...) fprintf(stderr, __VA_ARGS__) #endif /* ANDROID */ extern int optind; extern char *optarg; #ifndef _WIN32 #define GET_PROGNAME(x) (strrchr((x), '/') ? strrchr((x), '/')+1 : (x)) #else #define GET_PROGNAME(x) max(max(strrchr((x), '/'), strrchr((x), '\\')) + 1,(x)) #endif #ifdef ANDROID static char *progname; #else char *progname; #endif static void usage() { #define KRB_AVAIL_STRING(x) ((x)?"available":"not available") fprintf(stderr, _("Usage: %s [-A] [-q] [-c cache_name]\n"), progname); fprintf(stderr, _("\t-A destroy all credential caches in collection\n")); fprintf(stderr, _("\t-q quiet mode\n")); fprintf(stderr, _("\t-c specify name of credentials cache\n")); exit(2); } #ifdef ANDROID int kdestroy_driver(env, obj, argc, argv) JNIEnv* env; jobject obj; int argc; char **argv; { krb5_context kcontext; krb5_error_code retval; int c; krb5_ccache cache = NULL; krb5_cccol_cursor cursor; char *cache_name = NULL; int code = 0; int errflg = 0; int quiet = 0; int all = 0; /* save JNI environment */ jni_env = GetJNIEnv(cached_jvm); class_obj = obj; /* reset getopt() */ optind = 1; LOGI("Entered kdestroy_driver"); #else int main(argc, argv) int argc; char **argv; { krb5_context kcontext; krb5_error_code retval; int c; krb5_ccache cache = NULL; krb5_cccol_cursor cursor; char *cache_name = NULL; int code = 0; int errflg = 0; int quiet = 0; int all = 0; #endif setlocale(LC_MESSAGES, ""); progname = GET_PROGNAME(argv[0]); while ((c = getopt(argc, argv, "54Aqc:")) != -1) { switch (c) { case 'A': all = 1; break; case 'q': quiet = 1; break; case 'c': if (cache_name) { fprintf(stderr, _("Only one -c option allowed\n")); errflg++; } else { cache_name = optarg; } break; case '4': fprintf(stderr, _("Kerberos 4 is no longer supported\n")); exit(3); break; case '5': break; case '?': default: errflg++; break; } } if (optind != argc) errflg++; if (errflg) { usage(); } retval = krb5_init_context(&kcontext); if (retval) { com_err(progname, retval, _("while initializing krb5")); exit(1); } if (all) { code = krb5_cccol_cursor_new(kcontext, &cursor); if (code) { com_err(progname, code, _("while listing credential caches")); exit(1); } while ((code = krb5_cccol_cursor_next(kcontext, cursor, &cache)) == 0 && cache != NULL) { code = krb5_cc_get_full_name(kcontext, cache, &cache_name); if (code) { com_err(progname, code, _("composing ccache name")); exit(1); } code = krb5_cc_destroy(kcontext, cache); if (code && code != KRB5_FCC_NOFILE) { com_err(progname, code, _("while destroying cache %s"), cache_name); } krb5_free_string(kcontext, cache_name); } krb5_cccol_cursor_free(kcontext, &cursor); return 0; } if (cache_name) { code = krb5_cc_resolve (kcontext, cache_name, &cache); if (code != 0) { com_err(progname, code, _("while resolving %s"), cache_name); exit(1); } } else { code = krb5_cc_default(kcontext, &cache); if (code) { com_err(progname, code, _("while getting default ccache")); exit(1); } } code = krb5_cc_destroy (kcontext, cache); if (code != 0) { com_err (progname, code, _("while destroying cache")); if (code != KRB5_FCC_NOFILE) { if (quiet) fprintf(stderr, _("Ticket cache NOT destroyed!\n")); else { fprintf(stderr, _("Ticket cache %cNOT%c destroyed!\n"), BELL_CHAR, BELL_CHAR); } errflg = 1; } } return errflg; }
722,279
./kerberos-android-ndk/jni/kinit/kinit.c
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * clients/kinit/kinit.c * * Copyright 1990, 2008 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * Initialize a credentials cache. * */ #include "autoconf.h" #include "k5-platform.h" /* for asprintf */ #include <krb5.h> #include "extern.h" #include <string.h> #include <stdio.h> #include <time.h> #include <errno.h> #include <com_err.h> #ifdef ANDROID #include "kerberosapp.h" static JNIEnv* jni_env; static jobject class_obj; #else #define log(...) fprintf(stderr, __VA_ARGS__) #endif /* ANDROID */ #ifdef GETOPT_LONG #include <getopt.h> #else #ifdef HAVE_UNISTD_H #include <unistd.h> #ifdef sun /* SunOS4 unistd didn't declare these; okay to make unconditional? */ extern int optind; extern char *optarg; #endif /* sun */ #else extern int optind; extern char *optarg; extern int getopt(); #endif /* HAVE_UNISTD_H */ #endif /* GETOPT_LONG */ #ifndef _WIN32 #define GET_PROGNAME(x) (strrchr((x), '/') ? strrchr((x), '/')+1 : (x)) #else #define GET_PROGNAME(x) max(max(strrchr((x), '/'), strrchr((x), '\\')) + 1,(x)) #endif #ifdef HAVE_PWD_H #include <pwd.h> static char * get_name_from_os() { struct passwd *pw; if ((pw = getpwuid((int) getuid()))) return pw->pw_name; return 0; } #else /* HAVE_PWD_H */ #ifdef _WIN32 static char * get_name_from_os() { static char name[1024]; DWORD name_size = sizeof(name); if (GetUserName(name, &name_size)) { name[sizeof(name)-1] = 0; /* Just to be extra safe */ return name; } else { return 0; } } #else /* _WIN32 */ static char * get_name_from_os() { return 0; } #endif /* _WIN32 */ #endif /* HAVE_PWD_H */ static char *progname; typedef enum { INIT_PW, INIT_KT, RENEW, VALIDATE } action_type; struct k_opts { /* in seconds */ krb5_deltat starttime; krb5_deltat lifetime; krb5_deltat rlife; int forwardable; int proxiable; int anonymous; int addresses; int not_forwardable; int not_proxiable; int no_addresses; int verbose; char* principal_name; char* service_name; char* keytab_name; char* k5_cache_name; char *armor_ccache; action_type action; int num_pa_opts; krb5_gic_opt_pa_data *pa_opts; int canonicalize; int enterprise; }; struct k5_data { krb5_context ctx; krb5_ccache cc; krb5_principal me; char* name; }; #ifdef GETOPT_LONG /* if struct[2] == NULL, then long_getopt acts as if the short flag struct[3] was specified. If struct[2] != NULL, then struct[3] is stored in *(struct[2]), the array index which was specified is stored in *index, and long_getopt() returns 0. */ struct option long_options[] = { { "noforwardable", 0, NULL, 'F' }, { "noproxiable", 0, NULL, 'P' }, { "addresses", 0, NULL, 'a'}, { "forwardable", 0, NULL, 'f' }, { "proxiable", 0, NULL, 'p' }, { "noaddresses", 0, NULL, 'A' }, { "canonicalize", 0, NULL, 'C' }, { "enterprise", 0, NULL, 'E' }, { NULL, 0, NULL, 0 } }; #define GETOPT(argc, argv, str) getopt_long(argc, argv, str, long_options, 0) #else #define GETOPT(argc, argv, str) getopt(argc, argv, str) #endif static void usage() { #define USAGE_BREAK "\n\t" #ifdef GETOPT_LONG #define USAGE_LONG_FORWARDABLE " | --forwardable | --noforwardable" #define USAGE_LONG_PROXIABLE " | --proxiable | --noproxiable" #define USAGE_LONG_ADDRESSES " | --addresses | --noaddresses" #define USAGE_LONG_CANONICALIZE " | --canonicalize" #define USAGE_LONG_ENTERPRISE " | --enterprise" #define USAGE_BREAK_LONG USAGE_BREAK #else #define USAGE_LONG_FORWARDABLE "" #define USAGE_LONG_PROXIABLE "" #define USAGE_LONG_ADDRESSES "" #define USAGE_LONG_CANONICALIZE "" #define USAGE_LONG_ENTERPRISE "" #define USAGE_BREAK_LONG "" #endif fprintf(stderr, "Usage: %s [-V] " "[-l lifetime] [-s start_time] " USAGE_BREAK "[-r renewable_life] " "[-f | -F" USAGE_LONG_FORWARDABLE "] " USAGE_BREAK_LONG "[-p | -P" USAGE_LONG_PROXIABLE "] " USAGE_BREAK_LONG "-n " "[-a | -A" USAGE_LONG_ADDRESSES "] " USAGE_BREAK_LONG "[-C" USAGE_LONG_CANONICALIZE "] " USAGE_BREAK "[-E" USAGE_LONG_ENTERPRISE "] " USAGE_BREAK "[-v] [-R] " "[-k [-t keytab_file]] " "[-c cachename] " USAGE_BREAK "[-S service_name] [-T ticket_armor_cache]" USAGE_BREAK "[-X <attribute>[=<value>]] [principal]" "\n\n", progname); fprintf(stderr, " options:"); fprintf(stderr, "\t-V verbose\n"); fprintf(stderr, "\t-l lifetime\n"); fprintf(stderr, "\t-s start time\n"); fprintf(stderr, "\t-r renewable lifetime\n"); fprintf(stderr, "\t-f forwardable\n"); fprintf(stderr, "\t-F not forwardable\n"); fprintf(stderr, "\t-p proxiable\n"); fprintf(stderr, "\t-P not proxiable\n"); fprintf(stderr, "\t-n anonymous\n"); fprintf(stderr, "\t-a include addresses\n"); fprintf(stderr, "\t-A do not include addresses\n"); fprintf(stderr, "\t-v validate\n"); fprintf(stderr, "\t-R renew\n"); fprintf(stderr, "\t-C canonicalize\n"); fprintf(stderr, "\t-E client is enterprise principal name\n"); fprintf(stderr, "\t-k use keytab\n"); fprintf(stderr, "\t-t filename of keytab to use\n"); fprintf(stderr, "\t-c Kerberos 5 cache name\n"); fprintf(stderr, "\t-S service\n"); fprintf(stderr, "\t-T armor credential cache\n"); fprintf(stderr, "\t-X <attribute>[=<value>]\n"); exit(2); } static krb5_context errctx; static void extended_com_err_fn (const char *myprog, errcode_t code, const char *fmt, va_list args) { const char *emsg; emsg = krb5_get_error_message (errctx, code); fprintf (stderr, "%s: %s ", myprog, emsg); krb5_free_error_message (errctx, emsg); vfprintf (stderr, fmt, args); fprintf (stderr, "\n"); } static int add_preauth_opt(struct k_opts *opts, char *av) { char *sep, *v; krb5_gic_opt_pa_data *p, *x; if (opts->num_pa_opts == 0) { opts->pa_opts = malloc(sizeof(krb5_gic_opt_pa_data)); if (opts->pa_opts == NULL) return ENOMEM; } else { size_t newsize = (opts->num_pa_opts + 1) * sizeof(krb5_gic_opt_pa_data); x = realloc(opts->pa_opts, newsize); if (x == NULL) return ENOMEM; opts->pa_opts = x; } p = &opts->pa_opts[opts->num_pa_opts]; sep = strchr(av, '='); if (sep) { *sep = '\0'; v = ++sep; p->value = v; } else { p->value = "yes"; } p->attr = av; opts->num_pa_opts++; return 0; } static char * parse_options(argc, argv, opts) int argc; char **argv; struct k_opts* opts; { krb5_error_code code; int errflg = 0; int i; while ((i = GETOPT(argc, argv, "r:fpFPn54aAVl:s:c:kt:T:RS:vX:CE")) != -1) { switch (i) { case 'V': opts->verbose = 1; break; case 'l': /* Lifetime */ code = krb5_string_to_deltat(optarg, &opts->lifetime); if (code != 0 || opts->lifetime == 0) { log("Bad lifetime value %s\n", optarg); errflg++; } break; case 'r': /* Renewable Time */ code = krb5_string_to_deltat(optarg, &opts->rlife); if (code != 0 || opts->rlife == 0) { log("Bad lifetime value %s\n", optarg); errflg++; } break; case 'f': opts->forwardable = 1; break; case 'F': opts->not_forwardable = 1; break; case 'p': opts->proxiable = 1; break; case 'P': opts->not_proxiable = 1; break; case 'n': opts->anonymous = 1; break; case 'a': opts->addresses = 1; break; case 'A': opts->no_addresses = 1; break; case 's': code = krb5_string_to_deltat(optarg, &opts->starttime); if (code != 0 || opts->starttime == 0) { krb5_timestamp abs_starttime; code = krb5_string_to_timestamp(optarg, &abs_starttime); if (code != 0 || abs_starttime == 0) { log("Bad start time value %s\n", optarg); errflg++; } else { opts->starttime = abs_starttime - time(0); } } break; case 'S': opts->service_name = optarg; break; case 'k': opts->action = INIT_KT; break; case 't': if (opts->keytab_name) { log("Only one -t option allowed.\n"); errflg++; } else { opts->keytab_name = optarg; } break; case 'T': if (opts->armor_ccache) { log("Only one armor_ccache\n"); errflg++; } else opts->armor_ccache = optarg; break; case 'R': opts->action = RENEW; break; case 'v': opts->action = VALIDATE; break; case 'c': if (opts->k5_cache_name) { log("Only one -c option allowed\n"); errflg++; } else { opts->k5_cache_name = optarg; } break; case 'X': code = add_preauth_opt(opts, optarg); if (code) { com_err(progname, code, "while adding preauth option"); errflg++; } break; case 'C': opts->canonicalize = 1; break; case 'E': opts->enterprise = 1; break; case '4': log("Kerberos 4 is no longer supported\n"); exit(3); break; case '5': break; default: errflg++; break; } } if (opts->forwardable && opts->not_forwardable) { log("Only one of -f and -F allowed\n"); errflg++; } if (opts->proxiable && opts->not_proxiable) { log("Only one of -p and -P allowed\n"); errflg++; } if (opts->addresses && opts->no_addresses) { log("Only one of -a and -A allowed\n"); errflg++; } if (argc - optind > 1) { log("Extra arguments (starting with \"%s\").\n", argv[optind+1]); errflg++; } if (errflg) { usage(); } opts->principal_name = (optind == argc-1) ? argv[optind] : 0; return opts->principal_name; } static int k5_begin(opts, k5) struct k_opts* opts; struct k5_data* k5; { krb5_error_code code = 0; int flags = opts->enterprise ? KRB5_PRINCIPAL_PARSE_ENTERPRISE : 0; code = krb5_init_context(&k5->ctx); if (code) { com_err(progname, code, "while initializing Kerberos 5 library"); return 0; } errctx = k5->ctx; if (opts->k5_cache_name) { code = krb5_cc_resolve(k5->ctx, opts->k5_cache_name, &k5->cc); if (code != 0) { com_err(progname, code, "resolving ccache %s", opts->k5_cache_name); return 0; } if (opts->verbose) { log("Using specified cache: %s\n", opts->k5_cache_name); } } else { if ((code = krb5_cc_default(k5->ctx, &k5->cc))) { com_err(progname, code, "while getting default ccache"); return 0; } if (opts->verbose) { log("Using default cache: %s\n", krb5_cc_get_name(k5->ctx, k5->cc)); } } if (opts->principal_name) { /* Use specified name */ if ((code = krb5_parse_name_flags(k5->ctx, opts->principal_name, flags, &k5->me))) { com_err(progname, code, "when parsing name %s", opts->principal_name); return 0; } } else { /* No principal name specified */ if (opts->anonymous) { char *defrealm; code = krb5_get_default_realm(k5->ctx, &defrealm); if (code) { com_err(progname, code, "while getting default realm"); return 0; } code = krb5_build_principal_ext(k5->ctx, &k5->me, strlen(defrealm), defrealm, strlen(KRB5_WELLKNOWN_NAMESTR), KRB5_WELLKNOWN_NAMESTR, strlen(KRB5_ANONYMOUS_PRINCSTR), KRB5_ANONYMOUS_PRINCSTR, 0); krb5_free_default_realm(k5->ctx, defrealm); if (code) { com_err(progname, code, "while building principal"); return 0; } } else { if (opts->action == INIT_KT) { /* Use the default host/service name */ code = krb5_sname_to_principal(k5->ctx, NULL, NULL, KRB5_NT_SRV_HST, &k5->me); if (code) { com_err(progname, code, "when creating default server principal name"); return 0; } if (k5->me->realm.data[0] == 0) { code = krb5_unparse_name(k5->ctx, k5->me, &k5->name); if (code == 0) { com_err(progname, KRB5_ERR_HOST_REALM_UNKNOWN, "(principal %s)", k5->name); } else { com_err(progname, KRB5_ERR_HOST_REALM_UNKNOWN, "for local services"); } return 0; } } else { /* Get default principal from cache if one exists */ code = krb5_cc_get_principal(k5->ctx, k5->cc, &k5->me); if (code) { char *name = get_name_from_os(); if (!name) { log("Unable to identify user\n"); return 0; } if ((code = krb5_parse_name_flags(k5->ctx, name, flags, &k5->me))) { com_err(progname, code, "when parsing name %s", name); return 0; } } } } } code = krb5_unparse_name(k5->ctx, k5->me, &k5->name); if (code) { com_err(progname, code, "when unparsing name"); return 0; } if (opts->verbose) log("Using principal: %s\n", k5->name); opts->principal_name = k5->name; return 1; } static void k5_end(k5) struct k5_data* k5; { if (k5->name) krb5_free_unparsed_name(k5->ctx, k5->name); if (k5->me) krb5_free_principal(k5->ctx, k5->me); if (k5->cc) krb5_cc_close(k5->ctx, k5->cc); if (k5->ctx) krb5_free_context(k5->ctx); errctx = NULL; memset(k5, 0, sizeof(*k5)); } static krb5_error_code KRB5_CALLCONV kinit_prompter( krb5_context ctx, void *data, const char *name, const char *banner, int num_prompts, krb5_prompt prompts[] ) { #ifndef ANDROID krb5_error_code rc = krb5_prompter_posix(ctx, data, name, banner, num_prompts, prompts); return rc; #else // Credit: Caleb Callaway //ref: http://www.iam.ubc.ca/guides/javatut99/native1.1/implementing/method.html //ref: http://stackoverflow.com/questions/992836/how-to-access-the-java-method-in-a-c-application //ref: http://docs.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html#wp9502 //ref: http://java.sun.com/docs/books/jni/html/objtypes.html#4013 jstring name_string; jstring banner_string; jstring prompt_text; jboolean is_hidden; jobjectArray prompt_array; jclass prompt_class; jmethodID prompt_constructor_id; jobject prompt; jclass calling_class; jmethodID prompter_method_id; jobjectArray result_array; jstring result; const char * native_result; int i; name_string = (*jni_env)->NewStringUTF(jni_env, name); banner_string = (*jni_env)->NewStringUTF(jni_env, banner); prompt_class = (*jni_env)->FindClass(jni_env, "edu/mit/kerberos/Prompt"); prompt_constructor_id = (*jni_env)->GetMethodID(jni_env, prompt_class, "<init>", "(Ljava/lang/String;Z)V"); prompt_array = (*jni_env)->NewObjectArray(jni_env, num_prompts, prompt_class, NULL); for(i = 0; i < num_prompts; i++) { prompt_text = (*jni_env)->NewStringUTF(jni_env, prompts[i].prompt); is_hidden = (jboolean)prompts[i].hidden; prompt = (*jni_env)->NewObject(jni_env, prompt_class, prompt_constructor_id, prompt_text, is_hidden); (*jni_env)->SetObjectArrayElement(jni_env, prompt_array, i, prompt); } calling_class = (*jni_env)->GetObjectClass(jni_env, class_obj); prompter_method_id = (*jni_env)->GetMethodID(jni_env, calling_class, "kinitPrompter", "(Ljava/lang/String;Ljava/lang/String;[Ledu/mit/kerberos/Prompt;)[Ljava/lang/String;"); // make the call result_array = (*jni_env)->CallObjectMethod(jni_env, class_obj, prompter_method_id, name_string, banner_string, prompt_array); if (result_array == NULL) return KRB5_LIBOS_CANTREADPWD; for(i = 0; i < num_prompts; i++) { result = (jstring)(*jni_env)->GetObjectArrayElement(jni_env, result_array, i); if (result == NULL) { log("Null result from Java prompter at index %i", i); return KRB5_LIBOS_CANTREADPWD; } native_result = (*jni_env)->GetStringUTFChars(jni_env, result, NULL); if (native_result == NULL) { log("Null result getting native representation of index %i", i); return KRB5_LIBOS_CANTREADPWD; } // construct result snprintf(prompts[i].reply->data, prompts[i].reply->length, "%s", native_result); prompts[i].reply->length = strlen(native_result); // snprintf duplicates the string, so it is safe to release here (*jni_env)->ReleaseStringUTFChars(jni_env, result, native_result); } return 0; #endif /* ANDROID */ } static int k5_kinit(opts, k5) struct k_opts* opts; struct k5_data* k5; { int notix = 1; krb5_keytab keytab = 0; krb5_creds my_creds; krb5_error_code code = 0; krb5_get_init_creds_opt *options = NULL; int i; memset(&my_creds, 0, sizeof(my_creds)); code = krb5_get_init_creds_opt_alloc(k5->ctx, &options); if (code) goto cleanup; /* From this point on, we can goto cleanup because my_creds is initialized. */ if (opts->lifetime) krb5_get_init_creds_opt_set_tkt_life(options, opts->lifetime); if (opts->rlife) krb5_get_init_creds_opt_set_renew_life(options, opts->rlife); if (opts->forwardable) krb5_get_init_creds_opt_set_forwardable(options, 1); if (opts->not_forwardable) krb5_get_init_creds_opt_set_forwardable(options, 0); if (opts->proxiable) krb5_get_init_creds_opt_set_proxiable(options, 1); if (opts->not_proxiable) krb5_get_init_creds_opt_set_proxiable(options, 0); if (opts->canonicalize) krb5_get_init_creds_opt_set_canonicalize(options, 1); if (opts->anonymous) krb5_get_init_creds_opt_set_anonymous(options, 1); if (opts->addresses) { krb5_address **addresses = NULL; code = krb5_os_localaddr(k5->ctx, &addresses); if (code != 0) { com_err(progname, code, "getting local addresses"); goto cleanup; } krb5_get_init_creds_opt_set_address_list(options, addresses); } if (opts->no_addresses) krb5_get_init_creds_opt_set_address_list(options, NULL); if (opts->armor_ccache) krb5_get_init_creds_opt_set_fast_ccache_name(k5->ctx, options, opts->armor_ccache); if ((opts->action == INIT_KT) && opts->keytab_name) { #ifndef _WIN32 if (strncmp(opts->keytab_name, "KDB:", 3) == 0) { code = kinit_kdb_init(&k5->ctx, krb5_princ_realm(k5->ctx, k5->me)->data); if (code != 0) { com_err(progname, code, "while setting up KDB keytab for realm %s", krb5_princ_realm(k5->ctx, k5->me)->data); goto cleanup; } } #endif code = krb5_kt_resolve(k5->ctx, opts->keytab_name, &keytab); if (code != 0) { com_err(progname, code, "resolving keytab %s", opts->keytab_name); goto cleanup; } if (opts->verbose) log("Using keytab: %s\n", opts->keytab_name); } for (i = 0; i < opts->num_pa_opts; i++) { code = krb5_get_init_creds_opt_set_pa(k5->ctx, options, opts->pa_opts[i].attr, opts->pa_opts[i].value); if (code != 0) { com_err(progname, code, "while setting '%s'='%s'", opts->pa_opts[i].attr, opts->pa_opts[i].value); goto cleanup; } if (opts->verbose) { log("PA Option %s = %s\n", opts->pa_opts[i].attr, opts->pa_opts[i].value); } } code = krb5_get_init_creds_opt_set_out_ccache(k5->ctx, options, k5->cc); if (code) goto cleanup; switch (opts->action) { case INIT_PW: code = krb5_get_init_creds_password(k5->ctx, &my_creds, k5->me, 0, kinit_prompter, 0, opts->starttime, opts->service_name, options); break; case INIT_KT: code = krb5_get_init_creds_keytab(k5->ctx, &my_creds, k5->me, keytab, opts->starttime, opts->service_name, options); break; case VALIDATE: code = krb5_get_validated_creds(k5->ctx, &my_creds, k5->me, k5->cc, opts->service_name); break; case RENEW: code = krb5_get_renewed_creds(k5->ctx, &my_creds, k5->me, k5->cc, opts->service_name); break; } if (code) { char *doing = 0; switch (opts->action) { case INIT_PW: case INIT_KT: doing = "getting initial credentials"; break; case VALIDATE: doing = "validating credentials"; break; case RENEW: doing = "renewing credentials"; break; } if (code == KRB5KRB_AP_ERR_BAD_INTEGRITY) log("%s: Password incorrect while %s\n", progname, doing); else com_err(progname, code, "while %s", doing); goto cleanup; } if ((opts->action != INIT_PW) && (opts->action != INIT_KT)) { code = krb5_cc_initialize(k5->ctx, k5->cc, opts->canonicalize ? my_creds.client : k5->me); if (code) { com_err(progname, code, "when initializing cache %s", opts->k5_cache_name?opts->k5_cache_name:""); goto cleanup; } if (opts->verbose) log("Initialized cache\n"); code = krb5_cc_store_cred(k5->ctx, k5->cc, &my_creds); if (code) { com_err(progname, code, "while storing credentials"); goto cleanup; } if (opts->verbose) log("Stored credentials\n"); } notix = 0; cleanup: if (options) krb5_get_init_creds_opt_free(k5->ctx, options); if (my_creds.client == k5->me) { my_creds.client = 0; } if (opts->pa_opts) { free(opts->pa_opts); opts->pa_opts = NULL; opts->num_pa_opts = 0; } krb5_free_cred_contents(k5->ctx, &my_creds); if (keytab) krb5_kt_close(k5->ctx, keytab); return notix?0:1; } #ifndef ANDROID int main(argc, argv) int argc; char **argv; { struct k_opts opts; struct k5_data k5; int authed_k5 = 0; progname = GET_PROGNAME(argv[0]); /* Ensure we can be driven from a pipe */ if(!isatty(fileno(stdin))) setvbuf(stdin, 0, _IONBF, 0); if(!isatty(fileno(stdout))) setvbuf(stdout, 0, _IONBF, 0); if(!isatty(fileno(stderr))) setvbuf(stderr, 0, _IONBF, 0); memset(&opts, 0, sizeof(opts)); opts.action = INIT_PW; memset(&k5, 0, sizeof(k5)); set_com_err_hook (extended_com_err_fn); parse_options(argc, argv, &opts); if (k5_begin(&opts, &k5)) authed_k5 = k5_kinit(&opts, &k5); if (authed_k5 && opts.verbose) log("Authenticated to Kerberos v5\n"); k5_end(&k5); if (!authed_k5) exit(1); return 0; } #else /* ANDROID */ int kinit_driver(env, obj, argc, argv) JNIEnv* env; jobject obj; int argc; char **argv; { struct k_opts opts; struct k5_data k5; int authed_k5 = 0; /* save JNI environment */ jni_env = env; class_obj = obj; /* reset getopt() */ optind = 1; setlocale(LC_MESSAGES, ""); progname = GET_PROGNAME(argv[0]); /* Ensure we can be driven from a pipe */ if(!isatty(fileno(stdin))) setvbuf(stdin, 0, _IONBF, 0); if(!isatty(fileno(stdout))) setvbuf(stdout, 0, _IONBF, 0); if(!isatty(fileno(stderr))) setvbuf(stderr, 0, _IONBF, 0); memset(&opts, 0, sizeof(opts)); opts.action = INIT_PW; memset(&k5, 0, sizeof(k5)); set_com_err_hook (extended_com_err_fn); parse_options(argc, argv, &opts); if (k5_begin(&opts, &k5)) authed_k5 = k5_kinit(&opts, &k5); if (authed_k5 && opts.verbose) log("Authenticated to Kerberos v5\n"); k5_end(&k5); if (!authed_k5) return 1; return 0; } #endif /* ANDROID */
722,280
./kerberos-android-ndk/jni/kinit/kinit_kdb.c
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* clients/kinit/kinit_kdb.c */ /* * Copyright (C) 2010 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /** * @file kinit_kdb.c * Operations to open the KDB and make the KDB key table available * for kinit. */ #include <k5-int.h> #include <kadm5/admin.h> #include <kdb_kt.h> #include "extern.h" /** Server handle */ static void *server_handle; /** * @internal Initialize KDB for given realm * @param context pointer to context that will be re-initialized * @@param realm name of realm to initialize */ krb5_error_code kinit_kdb_init(krb5_context *pcontext, char *realm) { kadm5_config_params config; krb5_error_code retval = 0; if (*pcontext) { krb5_free_context(*pcontext); *pcontext = NULL; } memset(&config, 0, sizeof config); retval = kadm5_init_krb5_context(pcontext); if (retval) return retval; config.mask = KADM5_CONFIG_REALM; config.realm = realm; retval = kadm5_init(*pcontext, "kinit", NULL /*pass*/, "kinit", &config, KADM5_STRUCT_VERSION, KADM5_API_VERSION_3, NULL, &server_handle); if (retval) return retval; retval = krb5_kt_register(*pcontext, &krb5_kt_kdb_ops); return retval; }
722,281
./kerberos-android-ndk/jni/klist/klist.c
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * clients/klist/klist.c * * Copyright 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * * List out the contents of your credential cache or keytab. */ #include "autoconf.h" #include <krb5.h> #include <com_err.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <string.h> #include <stdio.h> #include <time.h> /* Need definition of INET6 before network headers, for IRIX. */ #if defined(HAVE_ARPA_INET_H) #include <arpa/inet.h> #endif #ifndef _WIN32 #define GET_PROGNAME(x) (strrchr((x), '/') ? strrchr((x), '/')+1 : (x)) #else #define GET_PROGNAME(x) max(max(strrchr((x), '/'), strrchr((x), '\\')) + 1,(x)) #endif #ifndef _WIN32 #include <sys/socket.h> #include <netdb.h> #endif #ifdef ANDROID #include "kerberosapp.h" static JNIEnv* jni_env; static jobject class_obj; #else #define log(...) fprintf(stderr, __VA_ARGS__) #endif /* ANDROID */ extern int optind; int show_flags = 0, show_time = 0, status_only = 0, show_keys = 0; int show_etype = 0, show_addresses = 0, no_resolve = 0, print_version = 0; int show_adtype = 0; char *defname; char *progname; krb5_int32 now; unsigned int timestamp_width; krb5_context kcontext; char * etype_string (krb5_enctype ); void show_credential (krb5_creds *); void do_ccache (char *); void do_keytab (char *); void printtime (time_t); void one_addr (krb5_address *); void fillit (FILE *, unsigned int, int); #define DEFAULT 0 #define CCACHE 1 #define KEYTAB 2 static void usage() { #define KRB_AVAIL_STRING(x) ((x)?"available":"not available") fprintf(stderr, "Usage: %s [-e] [-V] [[-c] [-d] [-f] [-s] [-a [-n]]] %s", progname, "[-k [-t] [-K]] [name]\n"); fprintf(stderr, "\t-c specifies credentials cache\n"); fprintf(stderr, "\t-k specifies keytab\n"); fprintf(stderr, "\t (Default is credentials cache)\n"); fprintf(stderr, "\t-e shows the encryption type\n"); fprintf(stderr, "\t-V shows the Kerberos version and exits\n"); fprintf(stderr, "\toptions for credential caches:\n"); fprintf(stderr, "\t\t-d shows the submitted authorization data types\n"); fprintf(stderr, "\t\t-f shows credentials flags\n"); fprintf(stderr, "\t\t-s sets exit status based on valid tgt existence\n"); fprintf(stderr, "\t\t-a displays the address list\n"); fprintf(stderr, "\t\t\t-n do not reverse-resolve\n"); fprintf(stderr, "\toptions for keytabs:\n"); fprintf(stderr, "\t\t-t shows keytab entry timestamps\n"); fprintf(stderr, "\t\t-K shows keytab entry DES keys\n"); exit(1); } #ifdef ANDROID int klist_driver(env, obj, argc, argv) JNIEnv* env; jobject obj; int argc; char **argv; { int c; char *name; int mode; /* save JNI environment */ jni_env = GetJNIEnv(cached_jvm); class_obj = obj; /* reset getopt() */ optind = 1; LOGI("Entered klist_driver"); #else int main(argc, argv) int argc; char **argv; { int c; char *name; int mode; #endif /* ANDROID */ progname = GET_PROGNAME(argv[0]); name = NULL; mode = DEFAULT; /* V=version so v can be used for verbose later if desired. */ while ((c = getopt(argc, argv, "dfetKsnack45V")) != -1) { switch (c) { case 'd': show_adtype = 1; break; case 'f': show_flags = 1; break; case 'e': show_etype = 1; break; case 't': show_time = 1; break; case 'K': show_keys = 1; break; case 's': status_only = 1; break; case 'n': no_resolve = 1; break; case 'a': show_addresses = 1; break; case 'c': if (mode != DEFAULT) usage(); mode = CCACHE; break; case 'k': if (mode != DEFAULT) usage(); mode = KEYTAB; break; case '4': log("Kerberos 4 is no longer supported\n"); exit(3); break; case '5': break; case 'V': print_version = 1; break; default: usage(); break; } } if (no_resolve && !show_addresses) usage(); if (mode == DEFAULT || mode == CCACHE) { if (show_time || show_keys) usage(); } else { if (show_flags || status_only || show_addresses) usage(); } if (argc - optind > 1) { log("Extra arguments (starting with \"%s\").\n", argv[optind+1]); usage(); } if (print_version) { #ifdef _WIN32 /* No access to autoconf vars; fix somehow. */ printf("Kerberos for Windows\n"); #else log("%s version %s\n", PACKAGE_NAME, PACKAGE_VERSION); #endif exit(0); } name = (optind == argc-1) ? argv[optind] : 0; now = time(0); { char tmp[BUFSIZ]; if (!krb5_timestamp_to_sfstring(now, tmp, 20, (char *) NULL) || !krb5_timestamp_to_sfstring(now, tmp, sizeof(tmp), (char *) NULL)) timestamp_width = (int) strlen(tmp); else timestamp_width = 15; } { krb5_error_code retval; retval = krb5_init_context(&kcontext); if (retval) { com_err(progname, retval, "while initializing krb5"); #ifdef ANDROID return 1; #else exit(1); #endif } if (mode == DEFAULT || mode == CCACHE) do_ccache(name); else do_keytab(name); } return 0; } void do_keytab(name) char *name; { krb5_keytab kt; krb5_keytab_entry entry; krb5_kt_cursor cursor; char buf[BUFSIZ]; /* hopefully large enough for any type */ char *pname; int code; if (name == NULL) { if ((code = krb5_kt_default(kcontext, &kt))) { com_err(progname, code, "while getting default keytab"); exit(1); } } else { if ((code = krb5_kt_resolve(kcontext, name, &kt))) { com_err(progname, code, "while resolving keytab %s", name); exit(1); } } if ((code = krb5_kt_get_name(kcontext, kt, buf, BUFSIZ))) { com_err(progname, code, "while getting keytab name"); exit(1); } log("Keytab name: %s\n", buf); if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) { com_err(progname, code, "while starting keytab scan"); exit(1); } if (show_time) { log("KVNO Timestamp"); fillit(stdout, timestamp_width - sizeof("Timestamp") + 2, (int) ' '); log("Principal\n"); log("---- "); fillit(stdout, timestamp_width, (int) '-'); log(" "); fillit(stdout, 78 - timestamp_width - sizeof("KVNO"), (int) '-'); log("\n"); } else { log("KVNO Principal\n"); log("---- --------------------------------------------------------------------------\n"); } while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) { if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) { com_err(progname, code, "while unparsing principal name"); exit(1); } log("%4d ", entry.vno); if (show_time) { printtime(entry.timestamp); log(" "); } log("%s", pname); if (show_etype) log(" (%s) " , etype_string(entry.key.enctype)); if (show_keys) { log(" (0x"); { unsigned int i; for (i = 0; i < entry.key.length; i++) log("%02x", entry.key.contents[i]); } log(")"); } log("\n"); krb5_free_unparsed_name(kcontext, pname); } if (code && code != KRB5_KT_END) { com_err(progname, code, "while scanning keytab"); exit(1); } if ((code = krb5_kt_end_seq_get(kcontext, kt, &cursor))) { com_err(progname, code, "while ending keytab scan"); exit(1); } exit(0); } void do_ccache(name) char *name; { krb5_ccache cache = NULL; krb5_cc_cursor cur; krb5_creds creds; krb5_principal princ; krb5_flags flags; krb5_error_code code; int exit_status = 0; if (status_only) /* exit_status is set back to 0 if a valid tgt is found */ exit_status = 1; if (name == NULL) { if ((code = krb5_cc_default(kcontext, &cache))) { if (!status_only) com_err(progname, code, "while getting default ccache"); exit(1); } } else { if ((code = krb5_cc_resolve(kcontext, name, &cache))) { if (!status_only) com_err(progname, code, "while resolving ccache %s", name); exit(1); } } flags = 0; /* turns off OPENCLOSE mode */ if ((code = krb5_cc_set_flags(kcontext, cache, flags))) { if (code == KRB5_FCC_NOFILE) { if (!status_only) { com_err(progname, code, "(ticket cache %s:%s)", krb5_cc_get_type(kcontext, cache), krb5_cc_get_name(kcontext, cache)); #ifdef KRB5_KRB4_COMPAT if (name == NULL) do_v4_ccache(0); #endif } } else { if (!status_only) com_err(progname, code, "while setting cache flags (ticket cache %s:%s)", krb5_cc_get_type(kcontext, cache), krb5_cc_get_name(kcontext, cache)); } #ifdef ANDROID return; #else exit(1); #endif } if ((code = krb5_cc_get_principal(kcontext, cache, &princ))) { if (!status_only) com_err(progname, code, "while retrieving principal name"); exit(1); } if ((code = krb5_unparse_name(kcontext, princ, &defname))) { if (!status_only) com_err(progname, code, "while unparsing principal name"); exit(1); } if (!status_only) { #ifdef ANDROID log("Ticket cache: %s:%s\nDefault principal: %s", #else log("Ticket cache: %s:%s\nDefault principal: %s\n\n", #endif krb5_cc_get_type(kcontext, cache), krb5_cc_get_name(kcontext, cache), defname); fputs("Valid starting", stdout); fillit(stdout, timestamp_width - sizeof("Valid starting") + 3, (int) ' '); fputs("Expires", stdout); fillit(stdout, timestamp_width - sizeof("Expires") + 3, (int) ' '); fputs("Service principal\n", stdout); } if ((code = krb5_cc_start_seq_get(kcontext, cache, &cur))) { if (!status_only) com_err(progname, code, "while starting to retrieve tickets"); exit(1); } while (!(code = krb5_cc_next_cred(kcontext, cache, &cur, &creds))) { if (krb5_is_config_principal(kcontext, creds.server)) continue; if (status_only) { if (exit_status && creds.server->length == 2 && strcmp(creds.server->realm.data, princ->realm.data) == 0 && strcmp((char *)creds.server->data[0].data, "krbtgt") == 0 && strcmp((char *)creds.server->data[1].data, princ->realm.data) == 0 && creds.times.endtime > now) exit_status = 0; } else { show_credential(&creds); } krb5_free_cred_contents(kcontext, &creds); } if (code == KRB5_CC_END) { if ((code = krb5_cc_end_seq_get(kcontext, cache, &cur))) { if (!status_only){ com_err(progname, code, "while finishing ticket retrieval"); } exit(1); } flags = KRB5_TC_OPENCLOSE; /* turns on OPENCLOSE mode */ if ((code = krb5_cc_set_flags(kcontext, cache, flags))) { if (!status_only){ com_err(progname, code, "while closing ccache"); } #ifdef ANDROID return; #else exit(1); #endif /* ANDROID */ } #ifdef KRB5_KRB4_COMPAT if (name == NULL && !status_only) do_v4_ccache(0); #endif #ifdef ANDROID return; #else exit(exit_status); #endif /* ANDROID */ } else { if (!status_only){ com_err(progname, code, "while retrieving a ticket"); } #ifdef ANDROID return; #else exit(1); #endif /* ANDROID */ } } char * etype_string(enctype) krb5_enctype enctype; { static char buf[100]; krb5_error_code retval; if ((retval = krb5_enctype_to_name(enctype, FALSE, buf, sizeof(buf)))) { /* XXX if there's an error != EINVAL, I should probably report it */ snprintf(buf, sizeof(buf), "etype %d", enctype); } return buf; } static char * flags_string(cred) register krb5_creds *cred; { static char buf[32]; int i = 0; if (cred->ticket_flags & TKT_FLG_FORWARDABLE) buf[i++] = 'F'; if (cred->ticket_flags & TKT_FLG_FORWARDED) buf[i++] = 'f'; if (cred->ticket_flags & TKT_FLG_PROXIABLE) buf[i++] = 'P'; if (cred->ticket_flags & TKT_FLG_PROXY) buf[i++] = 'p'; if (cred->ticket_flags & TKT_FLG_MAY_POSTDATE) buf[i++] = 'D'; if (cred->ticket_flags & TKT_FLG_POSTDATED) buf[i++] = 'd'; if (cred->ticket_flags & TKT_FLG_INVALID) buf[i++] = 'i'; if (cred->ticket_flags & TKT_FLG_RENEWABLE) buf[i++] = 'R'; if (cred->ticket_flags & TKT_FLG_INITIAL) buf[i++] = 'I'; if (cred->ticket_flags & TKT_FLG_HW_AUTH) buf[i++] = 'H'; if (cred->ticket_flags & TKT_FLG_PRE_AUTH) buf[i++] = 'A'; if (cred->ticket_flags & TKT_FLG_TRANSIT_POLICY_CHECKED) buf[i++] = 'T'; if (cred->ticket_flags & TKT_FLG_OK_AS_DELEGATE) buf[i++] = 'O'; /* D/d are taken. Use short strings? */ if (cred->ticket_flags & TKT_FLG_ANONYMOUS) buf[i++] = 'a'; buf[i] = '\0'; return(buf); } void printtime(tv) time_t tv; { char timestring[BUFSIZ]; char fill; fill = ' '; if (!krb5_timestamp_to_sfstring((krb5_timestamp) tv, timestring, timestamp_width+1, &fill)) { log("%s", timestring); LOGI("%s", timestring); } } void show_credential(cred) register krb5_creds * cred; { krb5_error_code retval; krb5_ticket *tkt; char *name, *sname, *flags; int extra_field = 0; retval = krb5_unparse_name(kcontext, cred->client, &name); if (retval) { com_err(progname, retval, "while unparsing client name"); return; } retval = krb5_unparse_name(kcontext, cred->server, &sname); if (retval) { com_err(progname, retval, "while unparsing server name"); krb5_free_unparsed_name(kcontext, name); return; } if (!cred->times.starttime) cred->times.starttime = cred->times.authtime; #ifdef ANDROID log("\n\nValid Starting: \n"); #endif printtime(cred->times.starttime); putchar(' '); putchar(' '); #ifdef ANDROID log("\nExpires: \n"); #endif printtime(cred->times.endtime); putchar(' '); putchar(' '); #ifdef ANDROID log("\nService Principal:\n"); #endif log("%s\n", sname); if (strcmp(name, defname)) { log("\tfor client %s", name); extra_field++; } if (cred->times.renew_till) { if (!extra_field) fputs("\t",stdout); else fputs(", ",stdout); fputs("renew until ", stdout); #ifdef ANDROID log("renew until: \n"); #endif printtime(cred->times.renew_till); extra_field += 2; } if (extra_field > 3) { fputs("\n", stdout); extra_field = 0; } if (show_flags) { flags = flags_string(cred); if (flags && *flags) { if (!extra_field) fputs("\t",stdout); else fputs(", ",stdout); log("Flags: %s", flags); extra_field++; } } if (extra_field > 2) { fputs("\n", stdout); extra_field = 0; } if (show_etype) { retval = krb5_decode_ticket(&cred->ticket, &tkt); if (retval) goto err_tkt; if (!extra_field) fputs("\t",stdout); else fputs(", ",stdout); log("Etype (skey, tkt): %s, ", etype_string(cred->keyblock.enctype)); log("%s ", etype_string(tkt->enc_part.enctype)); extra_field++; err_tkt: if (tkt != NULL) krb5_free_ticket(kcontext, tkt); } if (show_adtype) { int i; if (cred->authdata != NULL) { if (!extra_field) fputs("\t",stdout); else fputs(", ",stdout); log("AD types: "); for (i = 0; cred->authdata[i] != NULL; i++) { if (i) log(", "); log("%d", cred->authdata[i]->ad_type); } extra_field++; } } /* if any additional info was printed, extra_field is non-zero */ if (extra_field) putchar('\n'); if (show_addresses) { if (!cred->addresses || !cred->addresses[0]) { log("\tAddresses: (none)\n"); } else { int i; log("\tAddresses: "); one_addr(cred->addresses[0]); for (i=1; cred->addresses[i]; i++) { log(", "); one_addr(cred->addresses[i]); } log("\n"); } } krb5_free_unparsed_name(kcontext, name); krb5_free_unparsed_name(kcontext, sname); } #include "port-sockets.h" #include "socket-utils.h" /* for ss2sin etc */ #include "fake-addrinfo.h" void one_addr(a) krb5_address *a; { struct sockaddr_storage ss; int err; char namebuf[NI_MAXHOST]; memset (&ss, 0, sizeof (ss)); switch (a->addrtype) { case ADDRTYPE_INET: if (a->length != 4) { broken: log("broken address (type %d length %d)", a->addrtype, a->length); return; } { struct sockaddr_in *sinp = ss2sin (&ss); sinp->sin_family = AF_INET; #ifdef HAVE_SA_LEN sinp->sin_len = sizeof (struct sockaddr_in); #endif memcpy (&sinp->sin_addr, a->contents, 4); } break; #ifdef KRB5_USE_INET6 case ADDRTYPE_INET6: if (a->length != 16) goto broken; { struct sockaddr_in6 *sin6p = ss2sin6 (&ss); sin6p->sin6_family = AF_INET6; #ifdef HAVE_SA_LEN sin6p->sin6_len = sizeof (struct sockaddr_in6); #endif memcpy (&sin6p->sin6_addr, a->contents, 16); } break; #endif default: log("unknown addrtype %d", a->addrtype); return; } namebuf[0] = 0; err = getnameinfo (ss2sa (&ss), socklen (ss2sa (&ss)), namebuf, sizeof (namebuf), 0, 0, no_resolve ? NI_NUMERICHOST : 0U); if (err) { log("unprintable address (type %d, error %d %s)", a->addrtype, err, gai_strerror (err)); return; } log("%s", namebuf); } void fillit(f, num, c) FILE *f; unsigned int num; int c; { unsigned int i; for (i=0; i<num; i++) fputc(c, f); }
722,282
./kerberos-android-ndk/jni/kvno/kvno.c
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 1998 by the FundsXpress, INC. * * All rights reserved. * * Export of this software from the United States of America may require * a specific license from the United States Government. It is the * responsibility of any person or organization contemplating export to * obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of FundsXpress. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. FundsXpress makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <stdio.h> #include <stdlib.h> #include "k5-platform.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef _WIN32 #include <getopt.h> #endif #include <string.h> #ifdef ANDROID #include "kerberosapp.h" static JNIEnv* jni_env; static jobject class_obj; #else #define log(...) fprintf(stderr, __VA_ARGS__) #endif /* ANDROID */ extern int optind; extern char *optarg; static char *prog; static void xusage() { fprintf(stderr, _("usage: %s [-C] [-u] [-c ccache] [-e etype]\n"), prog); fprintf(stderr, _("\t[-k keytab] [-S sname] [-U for_user [-P]]\n")); fprintf(stderr, _("\tservice1 service2 ...\n")); exit(1); } int quiet = 0; static void do_v5_kvno (int argc, char *argv[], char *ccachestr, char *etypestr, char *keytab_name, char *sname, int canon, int unknown, char *for_user, int proxy); #include <com_err.h> static void extended_com_err_fn (const char *, errcode_t, const char *, va_list); #ifdef ANDROID int kvno_driver(JNIEnv* env, jobject obj, int argc, char *argv[]) { int option; char *etypestr = NULL, *ccachestr = NULL, *keytab_name = NULL; char *sname = NULL, *for_user = NULL; int canon = 0, unknown = 0, proxy = 0; /* save JNI environment */ jni_env = GetJNIEnv(cached_jvm); class_obj = obj; /* reset getopt() */ optind = 1; LOGI("Entered kvno_driver"); #else int main(int argc, char *argv[]) { int option; char *etypestr = NULL, *ccachestr = NULL, *keytab_name = NULL; char *sname = NULL, *for_user = NULL; int canon = 0, unknown = 0, proxy = 0; #endif /* ANDROID */ setlocale(LC_MESSAGES, ""); set_com_err_hook (extended_com_err_fn); prog = strrchr(argv[0], '/'); prog = prog ? (prog + 1) : argv[0]; while ((option = getopt(argc, argv, "uCc:e:hk:qPS:U:")) != -1) { switch (option) { case 'C': canon = 1; break; case 'c': ccachestr = optarg; break; case 'e': etypestr = optarg; break; case 'h': xusage(); break; case 'k': keytab_name = optarg; break; case 'q': quiet = 1; break; case 'P': proxy = 1; /* S4U2Proxy - constrained delegation */ break; case 'S': sname = optarg; if (unknown == 1){ fprintf(stderr, _("Options -u and -S are mutually exclusive\n")); xusage(); } break; case 'u': unknown = 1; if (sname){ fprintf(stderr, _("Options -u and -S are mutually exclusive\n")); xusage(); } break; case 'U': for_user = optarg; /* S4U2Self - protocol transition */ break; default: xusage(); break; } } if (proxy) { if (keytab_name == NULL) { fprintf(stderr, _("Option -P (constrained delegation) " "requires keytab to be specified\n")); xusage(); } else if (for_user == NULL) { fprintf(stderr, _("Option -P (constrained delegation) requires " "option -U (protocol transition)\n")); xusage(); } } if ((argc - optind) < 1) xusage(); do_v5_kvno(argc - optind, argv + optind, ccachestr, etypestr, keytab_name, sname, canon, unknown, for_user, proxy); return 0; } #include <k5-int.h> static krb5_context context; static void extended_com_err_fn (const char *myprog, errcode_t code, const char *fmt, va_list args) { const char *emsg; emsg = krb5_get_error_message (context, code); fprintf (stderr, "%s: %s ", myprog, emsg); krb5_free_error_message (context, emsg); vfprintf (stderr, fmt, args); fprintf (stderr, "\n"); } static void do_v5_kvno (int count, char *names[], char * ccachestr, char *etypestr, char *keytab_name, char *sname, int canon, int unknown, char *for_user, int proxy) { krb5_error_code ret; int i, errors; krb5_enctype etype; krb5_ccache ccache; krb5_principal me; krb5_creds in_creds; krb5_keytab keytab = NULL; krb5_principal for_user_princ = NULL; krb5_flags options; ret = krb5_init_context(&context); if (ret) { com_err(prog, ret, _("while initializing krb5 library")); #ifdef ANDROID return; #else exit(1); #endif } if (etypestr) { ret = krb5_string_to_enctype(etypestr, &etype); if (ret) { com_err(prog, ret, _("while converting etype")); #ifdef ANDROID return; #else exit(1); #endif } } else { etype = 0; } if (ccachestr) ret = krb5_cc_resolve(context, ccachestr, &ccache); else ret = krb5_cc_default(context, &ccache); if (ret) { com_err(prog, ret, _("while opening ccache")); #ifdef ANDROID return; #else exit(1); #endif } if (keytab_name) { ret = krb5_kt_resolve(context, keytab_name, &keytab); if (ret) { com_err(prog, ret, _("resolving keytab %s"), keytab_name); #ifdef ANDROID return; #else exit(1); #endif } } if (for_user) { ret = krb5_parse_name_flags(context, for_user, KRB5_PRINCIPAL_PARSE_ENTERPRISE, &for_user_princ); if (ret) { com_err(prog, ret, _("while parsing principal name %s"), for_user); #ifdef ANDROID return; #else exit(1); #endif } } ret = krb5_cc_get_principal(context, ccache, &me); if (ret) { com_err(prog, ret, _("while getting client principal name")); #ifdef ANDROID return; #else exit(1); #endif } errors = 0; options = 0; if (canon) options |= KRB5_GC_CANONICALIZE; for (i = 0; i < count; i++) { krb5_principal server = NULL; krb5_ticket *ticket = NULL; krb5_creds *out_creds = NULL; char *princ = NULL; memset(&in_creds, 0, sizeof(in_creds)); if (sname != NULL) { ret = krb5_sname_to_principal(context, names[i], sname, KRB5_NT_SRV_HST, &server); } else { ret = krb5_parse_name(context, names[i], &server); } if (ret) { if (!quiet) { com_err(prog, ret, _("while parsing principal name %s"), names[i]); } goto error; } if (unknown == 1) { krb5_princ_type(context, server) = KRB5_NT_UNKNOWN; } ret = krb5_unparse_name(context, server, &princ); if (ret) { com_err(prog, ret, _("while formatting parsed principal name for " "'%s'"), names[i]); goto error; } in_creds.keyblock.enctype = etype; if (for_user) { if (!proxy && !krb5_principal_compare(context, me, server)) { com_err(prog, EINVAL, _("client and server principal names must match")); goto error; } in_creds.client = for_user_princ; in_creds.server = me; ret = krb5_get_credentials_for_user(context, options, ccache, &in_creds, NULL, &out_creds); } else { in_creds.client = me; in_creds.server = server; ret = krb5_get_credentials(context, options, ccache, &in_creds, &out_creds); } if (ret) { com_err(prog, ret, _("while getting credentials for %s"), princ); goto error; } /* we need a native ticket */ ret = krb5_decode_ticket(&out_creds->ticket, &ticket); if (ret) { com_err(prog, ret, _("while decoding ticket for %s"), princ); goto error; } if (keytab) { ret = krb5_server_decrypt_ticket_keytab(context, keytab, ticket); if (ret) { if (!quiet) { fprintf(stderr, "%s: kvno = %d, keytab entry invalid\n", princ, ticket->enc_part.kvno); } com_err(prog, ret, _("while decrypting ticket for %s"), princ); goto error; } if (!quiet) { printf(_("%s: kvno = %d, keytab entry valid\n"), princ, ticket->enc_part.kvno); } if (proxy) { krb5_free_creds(context, out_creds); out_creds = NULL; in_creds.client = ticket->enc_part2->client; in_creds.server = server; ret = krb5_get_credentials_for_proxy(context, KRB5_GC_CANONICALIZE, ccache, &in_creds, ticket, &out_creds); if (ret) { com_err(prog, ret, _("%s: constrained delegation failed"), princ); goto error; } } } else { if (!quiet) printf(_("%s: kvno = %d\n"), princ, ticket->enc_part.kvno); } continue; error: if (server != NULL) krb5_free_principal(context, server); if (ticket != NULL) krb5_free_ticket(context, ticket); if (out_creds != NULL) krb5_free_creds(context, out_creds); if (princ != NULL) krb5_free_unparsed_name(context, princ); errors++; } if (keytab) krb5_kt_close(context, keytab); krb5_free_principal(context, me); krb5_free_principal(context, for_user_princ); krb5_cc_close(context, ccache); krb5_free_context(context); #ifdef ANDROID return; #else if (errors) exit(1); exit(0); #endif /* ANDROID */ }
722,283
./automatonbrain/jni/decoder-jni.c
#include <jni.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> #include <stdbool.h> #include <android/bitmap.h> AVCodecContext *pCodecCtx; // FFMPEG codec context AVCodec *pCodec; // Pointer to FFMPEG codec (H264) AVFrame *pFrame; // Used in the decoding process struct SwsContext *convertCtx; // Used in the scaling/conversion process AVPacket avpkt; // Used in the decoding process int temp; // Various uses bool Java_se_forskningsavd_automatonbrain_Decoder_init(JNIEnv* env, jobject thiz) { avcodec_init(); avcodec_register_all(); pCodecCtx = avcodec_alloc_context(); pCodec = avcodec_find_decoder( CODEC_ID_H264 ); av_init_packet( &avpkt ); if( !pCodec ) { return false; //printf( "RoboCortex [error]: Unable to initialize decoder\n" ); //exit( EXIT_DECODER ); } avcodec_open( pCodecCtx, pCodec ); // Allocate decoder frame pFrame = avcodec_alloc_frame(); return true; } bool Java_se_forskningsavd_automatonbrain_Decoder_decode(JNIEnv *env, jobject thiz, jbyteArray frame, jobject bitmap) { AndroidBitmapInfo bitmapInfo; if (AndroidBitmap_getInfo(env, bitmap, &bitmapInfo) != 0) { return false; } uint8_t *dest_data = 0; //TODO avpkt.data = (*env)->GetByteArrayElements(env, frame, 0); avpkt.size = (*env)->GetArrayLength(env, frame); avpkt.flags = AV_PKT_FLAG_KEY; int len = avcodec_decode_video2( pCodecCtx, pFrame, &temp, &avpkt ); (*env)->ReleaseByteArrayElements(env, frame, avpkt.data, JNI_ABORT); if (len < 0 ) { return false; //printf( "RoboCortex [info]: Decoding error (packet loss)\n" ); } else { void *bitmapData; AndroidBitmap_lockPixels(env, bitmap, &bitmapData); const uint8_t * data[1] = { bitmapData }; int linesize[1] = { bitmapInfo.stride }; // Create scaling & color-space conversion context convertCtx = sws_getContext( pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, bitmapInfo.width, bitmapInfo.height, PIX_FMT_BGRA, SWS_AREA, NULL, NULL, NULL); // Scale and convert the frame sws_scale( convertCtx, (const uint8_t**) pFrame->data, pFrame->linesize, 0, pCodecCtx->height, (uint8_t * const*) data, linesize ); // Cleanup sws_freeContext( convertCtx ); // AndroidBitmap_unlockPixels(env, bitmap); } return true; }
722,284
./robotis_cm9_series/cm-9_ide/processing-head/libraries/DynamixelPro/utility/dxl_pro.c
/* * dxl_pro.c * * Created on: 2013. 4. 25. * Author: ROBOTIS,.LTD. */ #include <string.h> #include "dxl_pro.h" /* gbpRxBuffer gbDXLWritePointer extern uint32 Dummy(uint32 tmp); extern void uDelay(uint32 uTime); extern void nDelay(uint32 nTime);*/ #ifdef CM9_DEBUG void PrintBufferEx(byte *bpPrintBuffer, byte bLength) { byte bCount; if(bLength == 0) { if(gbpTxBufferEx[2] == BROADCAST_ID) { TxDStringC("\r\n No Data[at Broadcast ID 0xFE]"); } else { TxDStringC("\r\n No Data(Check ID, Operating Mode, Baud rate)");//TxDString("\r\n No Data(Check ID, Operating Mode, Baud rate)"); } } for(bCount = 0; bCount < bLength; bCount++) { TxDHex8C(bpPrintBuffer[bCount]); TxDByteC(' '); } TxDStringC(" LEN:");//("(LEN:") TxDHex8C(bLength); TxDStringC("\r\n"); } #endif uint32 dxl_get_baudrate(int baudnum) { if(baudnum >= 2400) return baudnum; switch(baudnum) { case 0: return 2400; case 1: return 57600; case 2: return 115200; case 3: return 1000000; case 4: return 2000000; case 5: return 3000000; case 6: return 4000000; case 7: return 4500000; case 8: return 10500000; default: return 57600; } } unsigned short update_crc(unsigned short crc_accum, unsigned char *data_blk_ptr, unsigned short data_blk_size) { unsigned short i, j; unsigned short crc_table[256] = {0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011, 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022, 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072, 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041, 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2, 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1, 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1, 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082, 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192, 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1, 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1, 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2, 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151, 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162, 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132, 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101, 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312, 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321, 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371, 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342, 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1, 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2, 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2, 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381, 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291, 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2, 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2, 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1, 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252, 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261, 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231, 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202 }; for(j = 0; j < data_blk_size; j++) { i = ((unsigned short)(crc_accum >> 8) ^ *data_blk_ptr++) & 0xFF; crc_accum = (crc_accum << 8) ^ crc_table[i]; } return crc_accum; } void dxl_add_stuffing(unsigned char * packet) { int i = 0, index = 0; int packet_length_in = DXL_MAKEWORD(packet[PKT_LENGTH_L], packet[PKT_LENGTH_H]); int packet_length_out = packet_length_in; unsigned char temp[MAXNUM_TXPACKET] = {0}; memcpy(temp, packet, PKT_LENGTH_H + 1); // FF FF FD XX ID LEN_L LEN_H index = PKT_INSTRUCTION; for( i = 0; i < packet_length_in - 2; i++) // except CRC { temp[index++] = packet[i+PKT_INSTRUCTION]; if(packet[i+PKT_INSTRUCTION] == 0xFD && packet[i+PKT_INSTRUCTION-1] == 0xFF && packet[i+PKT_INSTRUCTION-2] == 0xFF) { // FF FF FD temp[index++] = 0xFD; packet_length_out++; } } temp[index++] = packet[PKT_INSTRUCTION+packet_length_in-2]; temp[index++] = packet[PKT_INSTRUCTION+packet_length_in-1]; // if(packet_length_in != packet_length_out) //packet = (unsigned char*)realloc(packet, index * sizeof(unsigned char)); memcpy(packet, temp, index); packet[PKT_LENGTH_L] = DXL_LOBYTE(packet_length_out); packet[PKT_LENGTH_H] = DXL_HIBYTE(packet_length_out); } void dxl_remove_stuffing(unsigned char * packet) { int i = 0, index = 0; int packet_length_in = DXL_MAKEWORD(packet[PKT_LENGTH_L], packet[PKT_LENGTH_H]); int packet_length_out = packet_length_in; unsigned char temp[MAXNUM_TXPACKET] = {0}; index = PKT_INSTRUCTION; for( i = 0; i < packet_length_in - 2; i++) // except CRC { if(packet[i+PKT_INSTRUCTION] == 0xFD && packet[i+PKT_INSTRUCTION+1] == 0xFD && packet[i+PKT_INSTRUCTION-1] == 0xFF && packet[i+PKT_INSTRUCTION-2] == 0xFF) { // FF FF FD FD packet_length_out--; i++; } packet[index++] = packet[i+PKT_INSTRUCTION]; } packet[index++] = packet[PKT_INSTRUCTION+packet_length_in-2]; packet[index++] = packet[PKT_INSTRUCTION+packet_length_in-1]; packet[PKT_LENGTH_L] = DXL_LOBYTE(packet_length_out); packet[PKT_LENGTH_H] = DXL_HIBYTE(packet_length_out); } void dxlProInterrupt(byte data){ if(gbDXLWritePointerEx > 255){//prevent buffer overflow, gbpDXLDataBuffer size is 256 bytes clearBuffer256Ex(); } gbpDXLDataBufferEx[gbDXLWritePointerEx++] = (uint8)USART1->regs->DR; //[ROBOTIS]Support to Dynamixel SDK. } void clearBuffer256Ex(void){ gbDXLReadPointerEx = gbDXLWritePointerEx = 0; } byte checkNewArriveEx(void){ if(gbDXLReadPointerEx != gbDXLWritePointerEx) return 1; else return 0; } void TxByteToDXLEx(byte bTxData){ //USART_SendData(USART1,bTxData); //while( USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET ); USART1->regs->DR = (bTxData & (u16)0x01FF); while( (USART1->regs->SR & ((u16)0x0040)) == RESET ); } byte RxByteFromDXLEx(void){ if(gbDXLWritePointerEx > 255){ // prevent exceptions clearBuffer256Ex(); return 0; } return gbpDXLDataBufferEx[gbDXLReadPointerEx++]; } /** * @brief communicate with dynamixel bus on CM-9XX series. After transmitting packets to the bus, also it receives status feedback packets. * @param bID dynamixel ID * @param bInst Instruction number, you can find it from dynamixel.h * @param wTxParaLen length of packet * */ byte txrx_PacketEx(byte bID, byte bInst, word wTxParaLen){ #define TRY_NUM 2//;;2 word wTxLen, bRxLenEx, bTryCount; gbBusUsedEx = 1; for(bTryCount = 0; bTryCount < 1; bTryCount++) { gbDXLReadPointerEx = gbDXLWritePointerEx; //BufferClear050728 /************************************** Transfer packet ***************************************************/ wTxLen = tx_PacketEx(bID, bInst, wTxParaLen); if(bInst == INST_PING_EX) { if(bID == BROADCAST_ID) { gbRxLengthEx = bRxLenEx = 255; } else { gbRxLengthEx = bRxLenEx = 14;//6; } } else if(bInst == INST_READ_EX) { /*txpacket[PKT_PARAMETER+2] = (unsigned char)DXL_LOBYTE(length); txpacket[PKT_PARAMETER+3] = (unsigned char)DXL_HIBYTE(length);*/ gbRxLengthEx = bRxLenEx = 11+DXL_MAKEWORD(gbpParameterEx[2], gbpParameterEx[3]);//6+gbpParameterEx[1]; } else if( bID == BROADCAST_ID ) { gbRxLengthEx = bRxLenEx = 0; break; } else { gbRxLengthEx = bRxLenEx = 11;//6; } if(bRxLenEx)//(gbpValidServo[bID] > 0x81 || bInst != INST_WRITE)) //ValidServo = 0x80|RETURN_LEVEL { /************************************** Receive packet ***************************************************/ gbRxLengthEx = rx_PacketEx(bRxLenEx); //TxDStringC("gbRxLengthEx = ");TxD_Dec_U8C(gbRxLengthEx);TxDStringC("\r\n"); //TxDStringC("bRxLenEx = ");TxD_Dec_U8C(bRxLenEx);TxDStringC("\r\n"); // if(gbRxLength != bRxLenEx) //&& bRxLenEx != 255) before Ver 1.11e if((gbRxLengthEx != bRxLenEx) && (bRxLenEx != 255)) // after Ver 1.11f { unsigned long ulCounter; word wTimeoutCount; ulCounter = 0; wTimeoutCount = 0; //TxDByteC('0');//TxDStringC("\r\n TEST POINT 0");//TxDString("\r\n Err ID:0x"); while(ulCounter++ < RX_TIMEOUT_COUNT2) { if(gbDXLReadPointerEx != gbDXLWritePointerEx) { gbDXLReadPointerEx= gbDXLWritePointerEx; //BufferClear ulCounter = 0; if(wTimeoutCount++ > 100 ) { //uDelay(0);// porting ydh added break; //porting ydh 100->245 //;;;;;; min max ╡┌╣┘▓± found at Ver 1.11e } nDelay(NANO_TIME_DELAY);// porting ydh added 20120210. } //uDelay(0);// porting ydh added nDelay(NANO_TIME_DELAY);// porting ydh added } //TxDByteC('1');//TxDStringC("\r\n TEST POINT 1");//TxDString("\r\n Err ID:0x"); gbDXLReadPointerEx = gbDXLWritePointerEx; //BufferClear } else { //TxDByteC('6');//TxDStringC("\r\n TEST POINT 6");//TxDString("\r\n Err ID:0x"); break; } } } //TxDByteC('2');//TxDStringC("\r\n TEST POINT 2");//TxDString("\r\n Err ID:0x"); gbBusUsedEx = 0; if((gbRxLengthEx != bRxLenEx) && (gbpTxBufferEx[4] != BROADCAST_ID)) { //TxDByteC('3');// //TxDStringC("\r\n TEST POINT 3");//TxDString("\r\n Err ID:0x"); //#ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 //TxDString("\r\n Err ID:0x"); //TxDHex8(bID); //TxDStringC("\r\n ->[DXL]Err: "); //PrintBufferEx(gbpTxBufferEx,wTxLen); //TxDStringC("\r\n <-[DXL]Err: "); //PrintBufferEx(gbpRxBufferEx,gbRxLengthEx); //#endif return 0; } //TxDString("\r\n TEST POINT 4");//TxDString("\r\n Err ID:0x"); #ifdef CM9_DEBUG /*TxDStringC("\r\n ->[TX Buffer]: "); PrintBufferEx(gbpTxBufferEx,wTxLen); TxDStringC("\r\n <-[RX Buffer]: "); PrintBufferEx(gbpRxBufferEx,gbRxLengthEx);*/ #endif //gbLengthForPacketMaking =0; return 1; } //░╣╝÷┐í ╕┬░╘ ╣▐┤┬ └╠└» : ┼δ╜┼┐í╖»░í │¬┐└╕Θ Length░í ╞▓╕▒ ░í┤╔╝║└╠ ╣½├┤ │⌠▒Γ ╢º╣« byte rx_PacketEx(word wRxLength){ unsigned long ulCounter, ulTimeLimit; byte bCount, bLength; word wCheckSum; byte bTimeout; bTimeout = 0; if(wRxLength == 255) ulTimeLimit = RX_TIMEOUT_COUNT1; else ulTimeLimit = RX_TIMEOUT_COUNT2; for(bCount = 0; bCount < wRxLength; bCount++) { ulCounter = 0; while(gbDXLReadPointerEx == gbDXLWritePointerEx) { nDelay(NANO_TIME_DELAY); // porting ydh if(ulCounter++ > ulTimeLimit) { bTimeout = 1; break; } uDelay(0); //porting ydh added } if(bTimeout) break; gbpRxBufferEx[bCount] = gbpDXLDataBufferEx[gbDXLReadPointerEx++]; //TxDStringC("gbpRxBufferEx = ");TxDHex8C(gbpRxBufferEx[bCount]);TxDStringC("\r\n"); if(gbDXLReadPointerEx > 255){ clearBuffer256Ex(); //TxDStringC("gbDXLReadPointerEx overflow!!\r\n"); // break; } } bLength = bCount; // data length read from usart buffer //TxDStringC("read from bLength = ");TxDHex8C(bLength);TxDStringC("\r\n"); wCheckSum = 0; //TxDStringC("gbpRxBufferEx[9] = ");TxDHex8C(gbpRxBufferEx[9]);TxDStringC("\r\n"); if( gbpTxBufferEx[PKT_ID] != BROADCAST_ID ) { if(bTimeout && wRxLength != 255) { #ifdef CM9_DEBUG TxDStringC("Rx Timeout"); #endif clearBuffer256Ex(); return 0; } if(bLength > 3) //checking available length. { if(gbpRxBufferEx[0] != 0xff || gbpRxBufferEx[1] != 0xff || gbpRxBufferEx[2] != 0xfd) { #ifdef CM9_DEBUG TxDStringC("Wrong Header");//[Wrong Header] #endif clearBuffer256Ex(); return 0; } if(gbpRxBufferEx[PKT_ID] != gbpTxBufferEx[PKT_ID] ) { #ifdef CM9_DEBUG TxDStringC("[Error:TxID != RxID]"); #endif clearBuffer256Ex(); return 0; } if(gbpRxBufferEx[5] != bLength-7) { #ifdef CM9_DEBUG TxDStringC("RxLength Error"); #endif clearBuffer256Ex(); return 0; } wCheckSum = DXL_MAKEWORD(gbpRxBufferEx[wRxLength-2], gbpRxBufferEx[wRxLength-1]); if(update_crc(0, gbpRxBufferEx, wRxLength-2) == wCheckSum){ // -2 : except CRC16 return bLength; } else{ #ifdef CM9_DEBUG TxDStringC("CRC-16 Error\r\n"); #endif return 0; } } } return bLength; } byte tx_PacketEx(byte bID, byte bInstruction, word wParameterLength){ word wCount, wCheckSum, wPacketLength; gbpTxBufferEx[0] = 0xff; gbpTxBufferEx[1] = 0xff; gbpTxBufferEx[2] = 0xfd; gbpTxBufferEx[3] = 0x00; gbpTxBufferEx[4] = bID; /*if(bInstruction == INST_SYNC_WRITE_EX){ gbpTxBufferEx[5] = DXL_LOBYTE(wParameterLength+7);// packet length = total parameter length(ID + data) + 7( start_addr + data_length + length + instruction ) gbpTxBufferEx[6] = DXL_HIBYTE(wParameterLength+7); }else*/ { gbpTxBufferEx[5] = DXL_LOBYTE(wParameterLength+3);// packet length = total parameter length(address + data) + 3( length + instruction ) gbpTxBufferEx[6] = DXL_HIBYTE(wParameterLength+3); } gbpTxBufferEx[7] = bInstruction; //TxDStringC("wParameterLength = ");TxDHex8C(wParameterLength);TxDStringC("\r\n"); //TxDStringC("--------------\r\n"); for(wCount = 0; wCount < wParameterLength; wCount++) { gbpTxBufferEx[wCount+8] = gbpParameterEx[wCount]; //push address and data to packet //TxDStringC("gbpParameterEx = ");TxDHex8C(gbpParameterEx[wCount]);TxDStringC("\r\n"); } // Character stuffing // dxl_add_stuffing(gbpTxBufferEx); // Packet Header wCheckSum = 0; //wPacketLength = wParameterLength+8;// total packet length including packet header length wPacketLength = DXL_MAKEWORD(gbpTxBufferEx[5], gbpTxBufferEx[6])+5; //add packet header and ID length // TxDStringC("wPacketLength = ");TxDHex8C(wPacketLength);TxDStringC("\r\n"); // Check MAX packet length if(wPacketLength > (MAXNUM_TXPACKET)){ return 0; } // Add CRC16 wCheckSum = update_crc(0, gbpTxBufferEx, wPacketLength); // -2 : except CRC16 gbpTxBufferEx[wPacketLength] = DXL_LOBYTE(wCheckSum); // last - 1 gbpTxBufferEx[wPacketLength+1] = DXL_HIBYTE(wCheckSum); // last - 0 wPacketLength += 2; //add crc length DXL_TXD; // this define is declared in dxl_constants.h for(wCount = 0; wCount < wPacketLength; wCount++) { TxByteToDXLEx(gbpTxBufferEx[wCount]); } DXL_RXD;// this define is declared in dxl_constants.h return(wPacketLength); }
722,285
./robotis_cm9_series/cm-9_ide/processing-head/libraries/RC100/utility/rc100_core.c
// Zigbee SDK platform independent source #include "rc100_core.h" //#include "rc100_hal.h" #include "usart.h" #include "gpio.h" unsigned char gbRcvPacket[6]; unsigned char gbRcvPacketNum; unsigned short gwRcvData; unsigned char gbRcvFlag; void TxDByteUart2(byte bTxdData) { /*USART_SendData(USART1,bTxdData); while( USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET ); */ USART2->regs->DR = (bTxdData & (u16)0x01FF); while( (USART2->regs->SR & ((u16)0x0040)) == RESET ); } byte RxDByteUart2(void) { byte bTemp; bTemp = gbpPacketDataBuffer[gbPacketReadPointer++]; gbPacketReadPointer = gbPacketReadPointer & 0x1F; //added 2012-11-23 return bTemp; } int rc100_hal_tx( unsigned char *pPacket, int numPacket ) { // Transmiting date // *pPacket: data array pointer // numPacket: number of data array // Return: number of data transmitted. -1 is error. unsigned char i; for(i=0 ; i<numPacket; i++ ) TxDByteUart2(pPacket[i]); return numPacket; } byte CheckNewArrive(void) { if(gbPacketReadPointer != gbPacketWritePointer) return 1; else return 0; } int rc100_hal_rx( unsigned char *pPacket, int numPacket ) { // Recieving date // *pPacket: data array pointer // numPacket: number of data array // Return: number of data recieved. -1 is error. unsigned char i; for( i=0 ; i<numPacket ; i++ ) { if (CheckNewArrive()) pPacket[i] = RxDByteUart2(); else return i; } return numPacket; } void rc100Interrupt(byte data){ gbpPacketDataBuffer[gbPacketWritePointer++] = (uint8)USART2->regs->DR; gbPacketWritePointer = gbPacketWritePointer & 0x1F; } int rc100Initialize(uint32 baudrate ) { /* * Opening device * baudrate: Real baudrate (ex> 115200, 57600, 38400...) * Return: 0(Failed), 1(Succeed) * * */ gpio_set_mode(GPIOA, 2, GPIO_AF_OUTPUT_PP); gpio_set_mode(GPIOA, 3, GPIO_INPUT_FLOATING); usart_init(USART2); //TxDStringC("USART clock = ");TxDHex32C(STM32_PCLK2);TxDStringC("\r\n"); usart_set_baud_rate(USART2, STM32_PCLK1, baudrate); usart_attach_interrupt(USART2,rc100Interrupt); usart_enable(USART2); gbRcvFlag = 0; gwRcvData = 0; gbRcvPacketNum = 0; /*Clear rx tx uart2 buffer */ gbPacketWritePointer =0; gbPacketReadPointer=0; return 1; } void rc100Terminate(void) { // Closing device usart_detach_interrupt(USART2); usart_disable(USART2); } int rc100TxData(int data) { unsigned char SndPacket[6]; unsigned short word = (unsigned short)data; unsigned char lowbyte = (unsigned char)(word & 0xff); unsigned char highbyte = (unsigned char)((word >> 8) & 0xff); SndPacket[0] = 0xff; SndPacket[1] = 0x55; SndPacket[2] = lowbyte; SndPacket[3] = ~lowbyte; SndPacket[4] = highbyte; SndPacket[5] = ~highbyte; if( rc100_hal_tx( SndPacket, 6 ) != 6 ) return 0; return 1; } /* extern volatile byte gbPacketWritePointer; // PC, Wireless extern volatile byte gbPacketReadPointer ; */ int rc100RxCheck(void) { int RcvNum; unsigned char checksum; int i, j; if(gbRcvFlag == 1) return 1; // Fill packet buffer if(gbRcvPacketNum < 6) { RcvNum = rc100_hal_rx( &gbRcvPacket[gbRcvPacketNum], (6 - gbRcvPacketNum) ); if( RcvNum != -1 ) gbRcvPacketNum += RcvNum; } // Find header if(gbRcvPacketNum >= 2) { for( i=0; i<gbRcvPacketNum; i++ ) { if(gbRcvPacket[i] == 0xff) { if(i <= (gbRcvPacketNum - 2)) { if(gbRcvPacket[i+1] == 0x55) break; } } } if(i > 0) { if(i == gbRcvPacketNum) { // Can not find header if(gbRcvPacket[i - 1] == 0xff) i--; } // Remove data before header for( j=i; j<gbRcvPacketNum; j++) { gbRcvPacket[j - i] = gbRcvPacket[j]; } gbRcvPacketNum -= i; } } // Verify packet if(gbRcvPacketNum == 6) { if(gbRcvPacket[0] == 0xff && gbRcvPacket[1] == 0x55) { checksum = ~gbRcvPacket[3]; if(gbRcvPacket[2] == checksum) { checksum = ~gbRcvPacket[5]; if(gbRcvPacket[4] == checksum) { gwRcvData = (unsigned short)((gbRcvPacket[4] << 8) & 0xff00); gwRcvData += gbRcvPacket[2]; gbRcvFlag = 1; } } } gbRcvPacket[0] = 0x00; gbRcvPacketNum = 0; } return gbRcvFlag; } int rc100RxData(void) { gbRcvFlag = 0; return (int)gwRcvData; }
722,286
./robotis_cm9_series/cm-9_ide/processing-head/libraries/EEPROM/utility/eeprom_core.c
/* Includes ------------------------------------------------------------------*/ #include "eeprom_core.h" u8 gbUsePage; long glWritePtr; u16 EEPROM_Read( u16 wVirtualAddrss ) { long lSrcPtr,lBasePtr; long lTempVirtualAddrss; if( gbUsePage == PAGE0 ) lBasePtr = PAGE0_BASE_ADDRESS+4; else lBasePtr = PAGE1_BASE_ADDRESS+4; lSrcPtr = glWritePtr; while(1) { if( lBasePtr > lSrcPtr ) return 0xFFFF; lTempVirtualAddrss = *((u16 * ) lSrcPtr); if( wVirtualAddrss == lTempVirtualAddrss ) return (*((u16 * ) (lSrcPtr+2))); lSrcPtr-=4; } } void EEPROM_Write( u16 wVirtualAddrss , u16 wData ) { u16 wTag0,wTag1; wTag0 = *(u16 *)(PAGE0_BASE_ADDRESS); wTag1 = *(u16 *)(PAGE1_BASE_ADDRESS); // eeprom ┐╡┐¬└╠ ░í╡µ ├í┤┬┴÷ ░╦╗τ╟╪╝¡, ░í╡µ├í┤┘╕Θ, eeprom page╕ª ║»╚»╟╪┴╪┤┘. if( (gbUsePage == PAGE0) && ( glWritePtr > (PAGE0_BASE_ADDRESS + FLASH_PAGE_SIZE - 4) ) ) { FLASH_ProgramHalfWord( PAGE0_BASE_ADDRESS, STATUS_EEPROM_FULL ); gbUsePage = PAGE1; if( wTag1 == STATUS_EEPROM_USE ) EEPROM_ERASE(PAGE1); FLASH_ProgramHalfWord( PAGE1_BASE_ADDRESS, STATUS_EEPROM_USE ); EEPROM_COPY_PAGE(PAGE1,PAGE0); // copy from 0 to 1. EEPROM_ERASE(PAGE0); EEPROM_WRITE_PONTER_SETUP(gbUsePage); } else if( (gbUsePage == PAGE1) && ( glWritePtr > (PAGE1_BASE_ADDRESS + FLASH_PAGE_SIZE - 4) ) ) { FLASH_ProgramHalfWord( PAGE1_BASE_ADDRESS, STATUS_EEPROM_FULL ); gbUsePage = PAGE0; if( wTag0 == STATUS_EEPROM_USE ) EEPROM_ERASE(PAGE0); FLASH_ProgramHalfWord( PAGE0_BASE_ADDRESS, STATUS_EEPROM_USE ); EEPROM_COPY_PAGE(PAGE0,PAGE1); // copy from 1 to 0. EEPROM_ERASE(PAGE1); EEPROM_WRITE_PONTER_SETUP(gbUsePage); } // TxDLong16(glWritePtr); TxDString(" x "); TxDLong16(wVirtualAddrss); TxDString("\r\n"); FLASH_ProgramHalfWord( glWritePtr, wVirtualAddrss ); FLASH_ProgramHalfWord( glWritePtr+2, wData ); glWritePtr +=4; } void EEPROM_INIT(void) { u16 wTag0,wTag1; wTag0 = *(u16 *)(PAGE0_BASE_ADDRESS); wTag1 = *(u16 *)(PAGE1_BASE_ADDRESS); FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR | FLASH_FLAG_OPTERR); // FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | // FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); while(1) { if( wTag0 == STATUS_EEPROM_EMPTY ) { if( wTag1 == STATUS_EEPROM_EMPTY ) { FLASH_ProgramHalfWord( PAGE0_BASE_ADDRESS, STATUS_EEPROM_USE ); gbUsePage = PAGE0; } else if( wTag1 == STATUS_EEPROM_USE ) { gbUsePage = PAGE1; } else if( wTag1 == STATUS_EEPROM_FULL ) { gbUsePage = PAGE1; //Erase_EEPROM(PAGE0); FLASH_ProgramHalfWord( PAGE0_BASE_ADDRESS, STATUS_EEPROM_USE ); EEPROM_COPY_PAGE(PAGE0,PAGE1); // copy from 1 to 0. EEPROM_ERASE(PAGE1); } } else if( wTag0 == STATUS_EEPROM_USE ) { if( wTag1 == STATUS_EEPROM_EMPTY ) { gbUsePage = PAGE0; } else if( wTag1 == STATUS_EEPROM_USE ) { // impossible. //while(1); // print error code. } else if( wTag1 == STATUS_EEPROM_FULL ) { //copy ╡╟┤° ╡╡┴▀, ╜╟╞╨╟╤ ░µ┐∞ └╠╣╟╖╬, page 0╕ª ╗Φ┴ª╟╧░φ, ┤┘╜├ ─½╟╟╟╤┤┘. gbUsePage = PAGE1; EEPROM_ERASE(PAGE0); FLASH_ProgramHalfWord( PAGE0_BASE_ADDRESS, STATUS_EEPROM_USE ); EEPROM_COPY_PAGE(PAGE0,PAGE1); // copy from 1 to 0. EEPROM_ERASE(PAGE1); } } else if( wTag0 == STATUS_EEPROM_FULL ) { if( wTag1 == STATUS_EEPROM_EMPTY ) { gbUsePage = PAGE1; //Erase_EEPROM(1); FLASH_ProgramHalfWord( PAGE1_BASE_ADDRESS, STATUS_EEPROM_USE ); EEPROM_COPY_PAGE(PAGE1,PAGE0); // copy from 0 to 1. EEPROM_ERASE(PAGE0); } else if( wTag1 == STATUS_EEPROM_USE ) { gbUsePage = PAGE1; EEPROM_ERASE(PAGE1); FLASH_ProgramHalfWord( PAGE1_BASE_ADDRESS, STATUS_EEPROM_USE ); EEPROM_COPY_PAGE(PAGE1,PAGE0); // copy from 0 to 1. EEPROM_ERASE(PAGE0); } else if( wTag1 == STATUS_EEPROM_FULL ) { // impossible. //while(1); // print error code. } } EEPROM_WRITE_PONTER_SETUP(gbUsePage); if( glWritePtr == PAGE0_BASE_ADDRESS + FLASH_PAGE_SIZE - 4) FLASH_ProgramHalfWord( PAGE0_BASE_ADDRESS, STATUS_EEPROM_FULL ); else if( glWritePtr == PAGE1_BASE_ADDRESS + FLASH_PAGE_SIZE - 4) FLASH_ProgramHalfWord( PAGE1_BASE_ADDRESS, STATUS_EEPROM_FULL ); else break; } } void EEPROM_WRITE_PONTER_SETUP(u8 Page) { long lTempPointer, lBaseAddress; u16 wTempData; if( Page == PAGE0 ) lBaseAddress = PAGE0_BASE_ADDRESS; else if( Page == PAGE1 ) lBaseAddress = PAGE1_BASE_ADDRESS; lTempPointer = lBaseAddress + FLASH_PAGE_SIZE - 4; while(1) { wTempData = *((u16 * ) lTempPointer); if( wTempData != 0xFFFF ) { glWritePtr = lTempPointer+4; return ; } lTempPointer -=4; if( lTempPointer == lBaseAddress ) { glWritePtr = lBaseAddress + 4; return ; } } } void EEPROM_COPY_PAGE(u8 DestPage, u8 SrcPage) { long lVirtualAddress = MAX_VIRTUAL_ADDRESS; long lTempVirtualAddrss; long lSrcPtr, lDestPtr,lBasePtr; if( SrcPage == PAGE0 ) { lBasePtr = PAGE0_BASE_ADDRESS+4; lDestPtr = PAGE1_BASE_ADDRESS+4; } else { lBasePtr = PAGE1_BASE_ADDRESS+4; lDestPtr = PAGE0_BASE_ADDRESS+4; } while(1) { if( lVirtualAddress < 0 ) break; lSrcPtr = glWritePtr; while(1) { if( lBasePtr > lSrcPtr ) { FLASH_ProgramWord ( lDestPtr + (lVirtualAddress*4) , (lVirtualAddress | 0xFFFF0000) ); break; } lTempVirtualAddrss = *((u16 * ) lSrcPtr); if( lVirtualAddress == lTempVirtualAddrss ) { FLASH_ProgramWord ( lDestPtr + (lVirtualAddress*4) , *((long * ) lSrcPtr) ); break; } lSrcPtr-=4; } lVirtualAddress--; } } void EEPROM_ERASE(u8 Page) { FLASH_ClearFlag(/*FLASH_FLAG_BSY | FLASH_FLAG_EOP |*/ FLASH_FLAG_PGERR /*| FLASH_FLAG_WRPRTERR | FLASH_FLAG_OPTERR*/); // jason added 20130424 FLASH_Status status = FLASH_COMPLETE; if(Page == PAGE0) status = FLASH_ErasePage(PAGE0_BASE_ADDRESS); //FLASH_EraseSector(GetSector(PAGE0_BASE_ADDRESS), VoltageRange_3); else status = FLASH_ErasePage(PAGE1_BASE_ADDRESS); //FLASH_EraseSector(GetSector(PAGE1_BASE_ADDRESS), VoltageRange_3); if(status != FLASH_COMPLETE){ return; //TxDString("erase fail!!\r\n"); } } /* Private typedef -------------- /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
722,287
./robotis_cm9_series/cm-9_ide/processing-head/libraries/BKP/utility/bkp_core.c
/****************************************************************************** * The MIT License * * Copyright (c) 2010 LeafLabs, LLC. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /* * @file bkp.h * @brief Backup register support. * @change [ROBOTIS] 2013-06-12 changed filename to bkp_core.c * */ #include "bkp_core.h" //[ROBOTIS] changed to bkp_core.h #include "pwr.h" #include "rcc.h" #include "bitband.h" #include "util.h" static inline __io uint32* data_register(uint8 reg); bkp_dev bkp = { .regs = BKP_BASE, }; /** Backup device. */ const bkp_dev *BKP = &bkp; /** * @brief Initialize backup interface. * * Enables the power and backup interface clocks, and resets the * backup device. */ void bkp_init(void) { /* Don't call pwr_init(), or you'll reset the device. We just * need the clock. */ rcc_clk_enable(RCC_PWR); rcc_clk_enable(RCC_BKP); rcc_reset_dev(RCC_BKP); } /** * Enable write access to the backup registers. Backup interface must * be initialized for subsequent register writes to work. * @see bkp_init() */ void bkp_enable_writes(void) { *bb_perip(&PWR_BASE->CR, PWR_CR_DBP) = 1; } /** * Disable write access to the backup registers. */ void bkp_disable_writes(void) { *bb_perip(&PWR_BASE->CR, PWR_CR_DBP) = 0; } /** * Read a value from given backup data register. * @param reg Data register to read, from 1 to BKP_NR_DATA_REGS (10 on * medium-density devices, 42 on high-density devices). */ uint16 bkp_read(uint8 reg) { __io uint32* dr = data_register(reg); if (!dr) { ASSERT(0); /* nonexistent register */ return 0; } return (uint16)*dr; } /** * @brief Write a value to given data register. * * Write access to backup registers must be enabled. * * @param reg Data register to write, from 1 to BKP_NR_DATA_REGS (10 * on medium-density devices, 42 on high-density devices). * @param val Value to write into the register. * @see bkp_enable_writes() */ void bkp_write(uint8 reg, uint16 val) { __io uint32* dr = data_register(reg); if (!dr) { ASSERT(0); /* nonexistent register */ return; } *dr = (uint32)val; } /* * Data register memory layout is not contiguous. It's split up from * 1--NR_LOW_DRS, beginning at BKP_BASE->DR1, through to * (NR_LOW_DRS+1)--BKP_NR_DATA_REGS, beginning at BKP_BASE->DR11. */ #define NR_LOW_DRS 10 static inline __io uint32* data_register(uint8 reg) { if (reg < 1 || reg > BKP_NR_DATA_REGS) { return 0; } #if BKP_NR_DATA_REGS == NR_LOW_DRS return (uint32*)BKP_BASE + reg; #else if (reg <= NR_LOW_DRS) { return (uint32*)BKP_BASE + reg; } else { return (uint32*)&(BKP_BASE->DR11) + (reg - NR_LOW_DRS - 1); } #endif }
722,288
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/queue.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. FreeRTOS supports many tools and architectures. V7.0.0 is sponsored by: Atollic AB - Atollic provides professional embedded systems development tools for C/C++ development, code analysis and test automation. See http://www.atollic.com *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ #include <stdlib.h> #include <string.h> /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE #include "FreeRTOS.h" #include "task.h" #include "croutine.h" #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*----------------------------------------------------------- * PUBLIC LIST API documented in list.h *----------------------------------------------------------*/ /* Constants used with the cRxLock and cTxLock structure members. */ #define queueUNLOCKED ( ( signed portBASE_TYPE ) -1 ) #define queueLOCKED_UNMODIFIED ( ( signed portBASE_TYPE ) 0 ) #define queueERRONEOUS_UNBLOCK ( -1 ) /* For internal use only. */ #define queueSEND_TO_BACK ( 0 ) #define queueSEND_TO_FRONT ( 1 ) /* Effectively make a union out of the xQUEUE structure. */ #define pxMutexHolder pcTail #define uxQueueType pcHead #define uxRecursiveCallCount pcReadFrom #define queueQUEUE_IS_MUTEX NULL /* Semaphores do not actually store or copy data, so have an items size of zero. */ #define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( 0 ) #define queueDONT_BLOCK ( ( portTickType ) 0 ) #define queueMUTEX_GIVE_BLOCK_TIME ( ( portTickType ) 0 ) /* * Definition of the queue used by the scheduler. * Items are queued by copy, not reference. */ typedef struct QueueDefinition { signed char *pcHead; /*< Points to the beginning of the queue storage area. */ signed char *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ signed char *pcWriteTo; /*< Points to the free next place in the storage area. */ signed char *pcReadFrom; /*< Points to the last place that a queued item was read from. */ xList xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ xList xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ volatile unsigned portBASE_TYPE uxMessagesWaiting;/*< The number of items currently in the queue. */ unsigned portBASE_TYPE uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ unsigned portBASE_TYPE uxItemSize; /*< The size of each items that the queue will hold. */ signed portBASE_TYPE xRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ signed portBASE_TYPE xTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ } xQUEUE; /*-----------------------------------------------------------*/ /* * Inside this file xQueueHandle is a pointer to a xQUEUE structure. * To keep the definition private the API header file defines it as a * pointer to void. */ typedef xQUEUE * xQueueHandle; /* * Prototypes for public functions are included here so we don't have to * include the API header file (as it defines xQueueHandle differently). These * functions are documented in the API header file. */ xQueueHandle xQueueCreate( unsigned portBASE_TYPE uxQueueLength, unsigned portBASE_TYPE uxItemSize ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueGenericSend( xQueueHandle xQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ) PRIVILEGED_FUNCTION; unsigned portBASE_TYPE uxQueueMessagesWaiting( const xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; void vQueueDelete( xQueueHandle xQueue ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueGenericSendFromISR( xQueueHandle pxQueue, const void * const pvItemToQueue, signed portBASE_TYPE *pxHigherPriorityTaskWoken, portBASE_TYPE xCopyPosition ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueGenericReceive( xQueueHandle pxQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueReceiveFromISR( xQueueHandle pxQueue, void * const pvBuffer, signed portBASE_TYPE *pxTaskWoken ) PRIVILEGED_FUNCTION; xQueueHandle xQueueCreateMutex( void ) PRIVILEGED_FUNCTION; xQueueHandle xQueueCreateCountingSemaphore( unsigned portBASE_TYPE uxCountValue, unsigned portBASE_TYPE uxInitialCount ) PRIVILEGED_FUNCTION; portBASE_TYPE xQueueTakeMutexRecursive( xQueueHandle xMutex, portTickType xBlockTime ) PRIVILEGED_FUNCTION; portBASE_TYPE xQueueGiveMutexRecursive( xQueueHandle xMutex ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueAltGenericSend( xQueueHandle pxQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueAltGenericReceive( xQueueHandle pxQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueIsQueueEmptyFromISR( const xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueIsQueueFullFromISR( const xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; unsigned portBASE_TYPE uxQueueMessagesWaitingFromISR( const xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; void vQueueWaitForMessageRestricted( xQueueHandle pxQueue, portTickType xTicksToWait ) PRIVILEGED_FUNCTION; /* * Co-routine queue functions differ from task queue functions. Co-routines are * an optional component. */ #if configUSE_CO_ROUTINES == 1 signed portBASE_TYPE xQueueCRSendFromISR( xQueueHandle pxQueue, const void *pvItemToQueue, signed portBASE_TYPE xCoRoutinePreviouslyWoken ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueCRReceiveFromISR( xQueueHandle pxQueue, void *pvBuffer, signed portBASE_TYPE *pxTaskWoken ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueCRSend( xQueueHandle pxQueue, const void *pvItemToQueue, portTickType xTicksToWait ) PRIVILEGED_FUNCTION; signed portBASE_TYPE xQueueCRReceive( xQueueHandle pxQueue, void *pvBuffer, portTickType xTicksToWait ) PRIVILEGED_FUNCTION; #endif /* * The queue registry is just a means for kernel aware debuggers to locate * queue structures. It has no other purpose so is an optional component. */ #if configQUEUE_REGISTRY_SIZE > 0 /* The type stored within the queue registry array. This allows a name to be assigned to each queue making kernel aware debugging a little more user friendly. */ typedef struct QUEUE_REGISTRY_ITEM { signed char *pcQueueName; xQueueHandle xHandle; } xQueueRegistryItem; /* The queue registry is simply an array of xQueueRegistryItem structures. The pcQueueName member of a structure being NULL is indicative of the array position being vacant. */ xQueueRegistryItem xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; /* Removes a queue from the registry by simply setting the pcQueueName member to NULL. */ static void vQueueUnregisterQueue( xQueueHandle xQueue ) PRIVILEGED_FUNCTION; void vQueueAddToRegistry( xQueueHandle xQueue, signed char *pcQueueName ) PRIVILEGED_FUNCTION; #endif /* * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not * prevent an ISR from adding or removing items to the queue, but does prevent * an ISR from removing tasks from the queue event lists. If an ISR finds a * queue is locked it will instead increment the appropriate queue lock count * to indicate that a task may require unblocking. When the queue in unlocked * these lock counts are inspected, and the appropriate action taken. */ static void prvUnlockQueue( xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; /* * Uses a critical section to determine if there is any data in a queue. * * @return pdTRUE if the queue contains no items, otherwise pdFALSE. */ static signed portBASE_TYPE prvIsQueueEmpty( const xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; /* * Uses a critical section to determine if there is any space in a queue. * * @return pdTRUE if there is no space, otherwise pdFALSE; */ static signed portBASE_TYPE prvIsQueueFull( const xQueueHandle pxQueue ) PRIVILEGED_FUNCTION; /* * Copies an item into the queue, either at the front of the queue or the * back of the queue. */ static void prvCopyDataToQueue( xQUEUE *pxQueue, const void *pvItemToQueue, portBASE_TYPE xPosition ) PRIVILEGED_FUNCTION; /* * Copies an item out of a queue. */ static void prvCopyDataFromQueue( xQUEUE * const pxQueue, const void *pvBuffer ) PRIVILEGED_FUNCTION; /*-----------------------------------------------------------*/ /* * Macro to mark a queue as locked. Locking a queue prevents an ISR from * accessing the queue event lists. */ #define prvLockQueue( pxQueue ) \ taskENTER_CRITICAL(); \ { \ if( ( pxQueue )->xRxLock == queueUNLOCKED ) \ { \ ( pxQueue )->xRxLock = queueLOCKED_UNMODIFIED; \ } \ if( ( pxQueue )->xTxLock == queueUNLOCKED ) \ { \ ( pxQueue )->xTxLock = queueLOCKED_UNMODIFIED; \ } \ } \ taskEXIT_CRITICAL() /*-----------------------------------------------------------*/ /*----------------------------------------------------------- * PUBLIC QUEUE MANAGEMENT API documented in queue.h *----------------------------------------------------------*/ xQueueHandle xQueueCreate( unsigned portBASE_TYPE uxQueueLength, unsigned portBASE_TYPE uxItemSize ) { xQUEUE *pxNewQueue; size_t xQueueSizeInBytes; xQueueHandle xReturn = NULL; /* Allocate the new queue structure. */ if( uxQueueLength > ( unsigned portBASE_TYPE ) 0 ) { pxNewQueue = ( xQUEUE * ) pvPortMalloc( sizeof( xQUEUE ) ); if( pxNewQueue != NULL ) { /* Create the list of pointers to queue items. The queue is one byte longer than asked for to make wrap checking easier/faster. */ xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ) + ( size_t ) 1; pxNewQueue->pcHead = ( signed char * ) pvPortMalloc( xQueueSizeInBytes ); if( pxNewQueue->pcHead != NULL ) { /* Initialise the queue members as described above where the queue type is defined. */ pxNewQueue->pcTail = pxNewQueue->pcHead + ( uxQueueLength * uxItemSize ); pxNewQueue->uxMessagesWaiting = ( unsigned portBASE_TYPE ) 0U; pxNewQueue->pcWriteTo = pxNewQueue->pcHead; pxNewQueue->pcReadFrom = pxNewQueue->pcHead + ( ( uxQueueLength - ( unsigned portBASE_TYPE ) 1U ) * uxItemSize ); pxNewQueue->uxLength = uxQueueLength; pxNewQueue->uxItemSize = uxItemSize; pxNewQueue->xRxLock = queueUNLOCKED; pxNewQueue->xTxLock = queueUNLOCKED; /* Likewise ensure the event queues start with the correct state. */ vListInitialise( &( pxNewQueue->xTasksWaitingToSend ) ); vListInitialise( &( pxNewQueue->xTasksWaitingToReceive ) ); traceQUEUE_CREATE( pxNewQueue ); xReturn = pxNewQueue; } else { traceQUEUE_CREATE_FAILED(); vPortFree( pxNewQueue ); } } } configASSERT( xReturn ); return xReturn; } /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) xQueueHandle xQueueCreateMutex( void ) { xQUEUE *pxNewQueue; /* Allocate the new queue structure. */ pxNewQueue = ( xQUEUE * ) pvPortMalloc( sizeof( xQUEUE ) ); if( pxNewQueue != NULL ) { /* Information required for priority inheritance. */ pxNewQueue->pxMutexHolder = NULL; pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; /* Queues used as a mutex no data is actually copied into or out of the queue. */ pxNewQueue->pcWriteTo = NULL; pxNewQueue->pcReadFrom = NULL; /* Each mutex has a length of 1 (like a binary semaphore) and an item size of 0 as nothing is actually copied into or out of the mutex. */ pxNewQueue->uxMessagesWaiting = ( unsigned portBASE_TYPE ) 0U; pxNewQueue->uxLength = ( unsigned portBASE_TYPE ) 1U; pxNewQueue->uxItemSize = ( unsigned portBASE_TYPE ) 0U; pxNewQueue->xRxLock = queueUNLOCKED; pxNewQueue->xTxLock = queueUNLOCKED; /* Ensure the event queues start with the correct state. */ vListInitialise( &( pxNewQueue->xTasksWaitingToSend ) ); vListInitialise( &( pxNewQueue->xTasksWaitingToReceive ) ); /* Start with the semaphore in the expected state. */ xQueueGenericSend( pxNewQueue, NULL, ( portTickType ) 0U, queueSEND_TO_BACK ); traceCREATE_MUTEX( pxNewQueue ); } else { traceCREATE_MUTEX_FAILED(); } configASSERT( pxNewQueue ); return pxNewQueue; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if configUSE_RECURSIVE_MUTEXES == 1 portBASE_TYPE xQueueGiveMutexRecursive( xQueueHandle pxMutex ) { portBASE_TYPE xReturn; configASSERT( pxMutex ); /* If this is the task that holds the mutex then pxMutexHolder will not change outside of this task. If this task does not hold the mutex then pxMutexHolder can never coincidentally equal the tasks handle, and as this is the only condition we are interested in it does not matter if pxMutexHolder is accessed simultaneously by another task. Therefore no mutual exclusion is required to test the pxMutexHolder variable. */ if( pxMutex->pxMutexHolder == xTaskGetCurrentTaskHandle() ) { traceGIVE_MUTEX_RECURSIVE( pxMutex ); /* uxRecursiveCallCount cannot be zero if pxMutexHolder is equal to the task handle, therefore no underflow check is required. Also, uxRecursiveCallCount is only modified by the mutex holder, and as there can only be one, no mutual exclusion is required to modify the uxRecursiveCallCount member. */ ( pxMutex->uxRecursiveCallCount )--; /* Have we unwound the call count? */ if( pxMutex->uxRecursiveCallCount == 0 ) { /* Return the mutex. This will automatically unblock any other task that might be waiting to access the mutex. */ xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); } xReturn = pdPASS; } else { /* We cannot give the mutex because we are not the holder. */ xReturn = pdFAIL; traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); } return xReturn; } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if configUSE_RECURSIVE_MUTEXES == 1 portBASE_TYPE xQueueTakeMutexRecursive( xQueueHandle pxMutex, portTickType xBlockTime ) { portBASE_TYPE xReturn; configASSERT( pxMutex ); /* Comments regarding mutual exclusion as per those within xQueueGiveMutexRecursive(). */ traceTAKE_MUTEX_RECURSIVE( pxMutex ); if( pxMutex->pxMutexHolder == xTaskGetCurrentTaskHandle() ) { ( pxMutex->uxRecursiveCallCount )++; xReturn = pdPASS; } else { xReturn = xQueueGenericReceive( pxMutex, NULL, xBlockTime, pdFALSE ); /* pdPASS will only be returned if we successfully obtained the mutex, we may have blocked to reach here. */ if( xReturn == pdPASS ) { ( pxMutex->uxRecursiveCallCount )++; } else { traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); } } return xReturn; } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if configUSE_COUNTING_SEMAPHORES == 1 xQueueHandle xQueueCreateCountingSemaphore( unsigned portBASE_TYPE uxCountValue, unsigned portBASE_TYPE uxInitialCount ) { xQueueHandle pxHandle; pxHandle = xQueueCreate( ( unsigned portBASE_TYPE ) uxCountValue, queueSEMAPHORE_QUEUE_ITEM_LENGTH ); if( pxHandle != NULL ) { pxHandle->uxMessagesWaiting = uxInitialCount; traceCREATE_COUNTING_SEMAPHORE(); } else { traceCREATE_COUNTING_SEMAPHORE_FAILED(); } configASSERT( pxHandle ); return pxHandle; } #endif /* configUSE_COUNTING_SEMAPHORES */ /*-----------------------------------------------------------*/ signed portBASE_TYPE xQueueGenericSend( xQueueHandle pxQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ) { signed portBASE_TYPE xEntryTimeSet = pdFALSE; xTimeOutType xTimeOut; configASSERT( pxQueue ); configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) ); /* This function relaxes the coding standard somewhat to allow return statements within the function itself. This is done in the interest of execution time efficiency. */ for( ;; ) { taskENTER_CRITICAL(); { /* Is there room on the queue now? To be running we must be the highest priority task wanting to access the queue. */ if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { traceQUEUE_SEND( pxQueue ); prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); /* If there was a task waiting for data to arrive on the queue then unblock it now. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE ) { /* The unblocked task has a priority higher than our own so yield immediately. Yes it is ok to do this from within the critical section - the kernel takes care of that. */ portYIELD_WITHIN_API(); } } taskEXIT_CRITICAL(); /* Return to the original privilege level before exiting the function. */ return pdPASS; } else { if( xTicksToWait == ( portTickType ) 0 ) { /* The queue was full and no block time is specified (or the block time has expired) so leave now. */ taskEXIT_CRITICAL(); /* Return to the original privilege level before exiting the function. */ traceQUEUE_SEND_FAILED( pxQueue ); return errQUEUE_FULL; } else if( xEntryTimeSet == pdFALSE ) { /* The queue was full and a block time was specified so configure the timeout structure. */ vTaskSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } } } taskEXIT_CRITICAL(); /* Interrupts and other tasks can send to and receive from the queue now the critical section has been exited. */ vTaskSuspendAll(); prvLockQueue( pxQueue ); /* Update the timeout state to see if it has expired yet. */ if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) { if( prvIsQueueFull( pxQueue ) ) { traceBLOCKING_ON_QUEUE_SEND( pxQueue ); vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); /* Unlocking the queue means queue events can effect the event list. It is possible that interrupts occurring now remove this task from the event list again - but as the scheduler is suspended the task will go onto the pending ready last instead of the actual ready list. */ prvUnlockQueue( pxQueue ); /* Resuming the scheduler will move tasks from the pending ready list into the ready list - so it is feasible that this task is already in a ready list before it yields - in which case the yield will not cause a context switch unless there is also a higher priority task in the pending ready list. */ if( !xTaskResumeAll() ) { portYIELD_WITHIN_API(); } } else { /* Try again. */ prvUnlockQueue( pxQueue ); ( void ) xTaskResumeAll(); } } else { /* The timeout has expired. */ prvUnlockQueue( pxQueue ); ( void ) xTaskResumeAll(); /* Return to the original privilege level before exiting the function. */ traceQUEUE_SEND_FAILED( pxQueue ); return errQUEUE_FULL; } } } /*-----------------------------------------------------------*/ #if configUSE_ALTERNATIVE_API == 1 signed portBASE_TYPE xQueueAltGenericSend( xQueueHandle pxQueue, const void * const pvItemToQueue, portTickType xTicksToWait, portBASE_TYPE xCopyPosition ) { signed portBASE_TYPE xEntryTimeSet = pdFALSE; xTimeOutType xTimeOut; configASSERT( pxQueue ); configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) ); for( ;; ) { taskENTER_CRITICAL(); { /* Is there room on the queue now? To be running we must be the highest priority task wanting to access the queue. */ if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { traceQUEUE_SEND( pxQueue ); prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); /* If there was a task waiting for data to arrive on the queue then unblock it now. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE ) { /* The unblocked task has a priority higher than our own so yield immediately. */ portYIELD_WITHIN_API(); } } taskEXIT_CRITICAL(); return pdPASS; } else { if( xTicksToWait == ( portTickType ) 0 ) { taskEXIT_CRITICAL(); return errQUEUE_FULL; } else if( xEntryTimeSet == pdFALSE ) { vTaskSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } } } taskEXIT_CRITICAL(); taskENTER_CRITICAL(); { if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) { if( prvIsQueueFull( pxQueue ) ) { traceBLOCKING_ON_QUEUE_SEND( pxQueue ); vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); portYIELD_WITHIN_API(); } } else { taskEXIT_CRITICAL(); traceQUEUE_SEND_FAILED( pxQueue ); return errQUEUE_FULL; } } taskEXIT_CRITICAL(); } } #endif /* configUSE_ALTERNATIVE_API */ /*-----------------------------------------------------------*/ #if configUSE_ALTERNATIVE_API == 1 signed portBASE_TYPE xQueueAltGenericReceive( xQueueHandle pxQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking ) { signed portBASE_TYPE xEntryTimeSet = pdFALSE; xTimeOutType xTimeOut; signed char *pcOriginalReadPosition; configASSERT( pxQueue ); configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) ); for( ;; ) { taskENTER_CRITICAL(); { if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ) { /* Remember our read position in case we are just peeking. */ pcOriginalReadPosition = pxQueue->pcReadFrom; prvCopyDataFromQueue( pxQueue, pvBuffer ); if( xJustPeeking == pdFALSE ) { traceQUEUE_RECEIVE( pxQueue ); /* We are actually removing data. */ --( pxQueue->uxMessagesWaiting ); #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { /* Record the information required to implement priority inheritance should it become necessary. */ pxQueue->pxMutexHolder = xTaskGetCurrentTaskHandle(); } } #endif if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE ) { portYIELD_WITHIN_API(); } } } else { traceQUEUE_PEEK( pxQueue ); /* We are not removing the data, so reset our read pointer. */ pxQueue->pcReadFrom = pcOriginalReadPosition; /* The data is being left in the queue, so see if there are any other tasks waiting for the data. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { /* Tasks that are removed from the event list will get added to the pending ready list as the scheduler is still suspended. */ if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority than this task. */ portYIELD_WITHIN_API(); } } } taskEXIT_CRITICAL(); return pdPASS; } else { if( xTicksToWait == ( portTickType ) 0 ) { taskEXIT_CRITICAL(); traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } else if( xEntryTimeSet == pdFALSE ) { vTaskSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } } } taskEXIT_CRITICAL(); taskENTER_CRITICAL(); { if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) { if( prvIsQueueEmpty( pxQueue ) ) { traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { portENTER_CRITICAL(); vTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder ); portEXIT_CRITICAL(); } } #endif vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); portYIELD_WITHIN_API(); } } else { taskEXIT_CRITICAL(); traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } } taskEXIT_CRITICAL(); } } #endif /* configUSE_ALTERNATIVE_API */ /*-----------------------------------------------------------*/ signed portBASE_TYPE xQueueGenericSendFromISR( xQueueHandle pxQueue, const void * const pvItemToQueue, signed portBASE_TYPE *pxHigherPriorityTaskWoken, portBASE_TYPE xCopyPosition ) { signed portBASE_TYPE xReturn; unsigned portBASE_TYPE uxSavedInterruptStatus; configASSERT( pxQueue ); configASSERT( pxHigherPriorityTaskWoken ); configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) ); /* Similar to xQueueGenericSend, except we don't block if there is no room in the queue. Also we don't directly wake a task that was blocked on a queue read, instead we return a flag to say whether a context switch is required or not (i.e. has a task with a higher priority than us been woken by this post). */ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { traceQUEUE_SEND_FROM_ISR( pxQueue ); prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); /* If the queue is locked we do not alter the event list. This will be done when the queue is unlocked later. */ if( pxQueue->xTxLock == queueUNLOCKED ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ *pxHigherPriorityTaskWoken = pdTRUE; } } } else { /* Increment the lock count so the task that unlocks the queue knows that data was posted while it was locked. */ ++( pxQueue->xTxLock ); } xReturn = pdPASS; } else { traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); xReturn = errQUEUE_FULL; } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ signed portBASE_TYPE xQueueGenericReceive( xQueueHandle pxQueue, void * const pvBuffer, portTickType xTicksToWait, portBASE_TYPE xJustPeeking ) { signed portBASE_TYPE xEntryTimeSet = pdFALSE; xTimeOutType xTimeOut; signed char *pcOriginalReadPosition; configASSERT( pxQueue ); configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) ); /* This function relaxes the coding standard somewhat to allow return statements within the function itself. This is done in the interest of execution time efficiency. */ for( ;; ) { taskENTER_CRITICAL(); { /* Is there data in the queue now? To be running we must be the highest priority task wanting to access the queue. */ if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ) { /* Remember our read position in case we are just peeking. */ pcOriginalReadPosition = pxQueue->pcReadFrom; prvCopyDataFromQueue( pxQueue, pvBuffer ); if( xJustPeeking == pdFALSE ) { traceQUEUE_RECEIVE( pxQueue ); /* We are actually removing data. */ --( pxQueue->uxMessagesWaiting ); #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { /* Record the information required to implement priority inheritance should it become necessary. */ pxQueue->pxMutexHolder = xTaskGetCurrentTaskHandle(); } } #endif if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE ) { portYIELD_WITHIN_API(); } } } else { traceQUEUE_PEEK( pxQueue ); /* We are not removing the data, so reset our read pointer. */ pxQueue->pcReadFrom = pcOriginalReadPosition; /* The data is being left in the queue, so see if there are any other tasks waiting for the data. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { /* Tasks that are removed from the event list will get added to the pending ready list as the scheduler is still suspended. */ if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority than this task. */ portYIELD_WITHIN_API(); } } } taskEXIT_CRITICAL(); return pdPASS; } else { if( xTicksToWait == ( portTickType ) 0 ) { /* The queue was empty and no block time is specified (or the block time has expired) so leave now. */ taskEXIT_CRITICAL(); traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } else if( xEntryTimeSet == pdFALSE ) { /* The queue was empty and a block time was specified so configure the timeout structure. */ vTaskSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } } } taskEXIT_CRITICAL(); /* Interrupts and other tasks can send to and receive from the queue now the critical section has been exited. */ vTaskSuspendAll(); prvLockQueue( pxQueue ); /* Update the timeout state to see if it has expired yet. */ if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) { if( prvIsQueueEmpty( pxQueue ) ) { traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { portENTER_CRITICAL(); { vTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder ); } portEXIT_CRITICAL(); } } #endif vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); prvUnlockQueue( pxQueue ); if( !xTaskResumeAll() ) { portYIELD_WITHIN_API(); } } else { /* Try again. */ prvUnlockQueue( pxQueue ); ( void ) xTaskResumeAll(); } } else { prvUnlockQueue( pxQueue ); ( void ) xTaskResumeAll(); traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } } } /*-----------------------------------------------------------*/ signed portBASE_TYPE xQueueReceiveFromISR( xQueueHandle pxQueue, void * const pvBuffer, signed portBASE_TYPE *pxTaskWoken ) { signed portBASE_TYPE xReturn; unsigned portBASE_TYPE uxSavedInterruptStatus; configASSERT( pxQueue ); configASSERT( pxTaskWoken ); configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( unsigned portBASE_TYPE ) 0U ) ) ); uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { /* We cannot block from an ISR, so check there is data available. */ if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ) { traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); prvCopyDataFromQueue( pxQueue, pvBuffer ); --( pxQueue->uxMessagesWaiting ); /* If the queue is locked we will not modify the event list. Instead we update the lock count so the task that unlocks the queue will know that an ISR has removed data while the queue was locked. */ if( pxQueue->xRxLock == queueUNLOCKED ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { /* The task waiting has a higher priority than us so force a context switch. */ *pxTaskWoken = pdTRUE; } } } else { /* Increment the lock count so the task that unlocks the queue knows that data was removed while it was locked. */ ++( pxQueue->xRxLock ); } xReturn = pdPASS; } else { xReturn = pdFAIL; traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ unsigned portBASE_TYPE uxQueueMessagesWaiting( const xQueueHandle pxQueue ) { unsigned portBASE_TYPE uxReturn; configASSERT( pxQueue ); taskENTER_CRITICAL(); uxReturn = pxQueue->uxMessagesWaiting; taskEXIT_CRITICAL(); return uxReturn; } /*-----------------------------------------------------------*/ unsigned portBASE_TYPE uxQueueMessagesWaitingFromISR( const xQueueHandle pxQueue ) { unsigned portBASE_TYPE uxReturn; configASSERT( pxQueue ); uxReturn = pxQueue->uxMessagesWaiting; return uxReturn; } /*-----------------------------------------------------------*/ void vQueueDelete( xQueueHandle pxQueue ) { configASSERT( pxQueue ); traceQUEUE_DELETE( pxQueue ); vQueueUnregisterQueue( pxQueue ); vPortFree( pxQueue->pcHead ); vPortFree( pxQueue ); } /*-----------------------------------------------------------*/ static void prvCopyDataToQueue( xQUEUE *pxQueue, const void *pvItemToQueue, portBASE_TYPE xPosition ) { if( pxQueue->uxItemSize == ( unsigned portBASE_TYPE ) 0 ) { #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { /* The mutex is no longer being held. */ vTaskPriorityDisinherit( ( void * ) pxQueue->pxMutexHolder ); pxQueue->pxMutexHolder = NULL; } } #endif } else if( xPosition == queueSEND_TO_BACK ) { memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( unsigned ) pxQueue->uxItemSize ); pxQueue->pcWriteTo += pxQueue->uxItemSize; if( pxQueue->pcWriteTo >= pxQueue->pcTail ) { pxQueue->pcWriteTo = pxQueue->pcHead; } } else { memcpy( ( void * ) pxQueue->pcReadFrom, pvItemToQueue, ( unsigned ) pxQueue->uxItemSize ); pxQueue->pcReadFrom -= pxQueue->uxItemSize; if( pxQueue->pcReadFrom < pxQueue->pcHead ) { pxQueue->pcReadFrom = ( pxQueue->pcTail - pxQueue->uxItemSize ); } } ++( pxQueue->uxMessagesWaiting ); } /*-----------------------------------------------------------*/ static void prvCopyDataFromQueue( xQUEUE * const pxQueue, const void *pvBuffer ) { if( pxQueue->uxQueueType != queueQUEUE_IS_MUTEX ) { pxQueue->pcReadFrom += pxQueue->uxItemSize; if( pxQueue->pcReadFrom >= pxQueue->pcTail ) { pxQueue->pcReadFrom = pxQueue->pcHead; } memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); } } /*-----------------------------------------------------------*/ static void prvUnlockQueue( xQueueHandle pxQueue ) { /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ /* The lock counts contains the number of extra data items placed or removed from the queue while the queue was locked. When a queue is locked items can be added or removed, but the event lists cannot be updated. */ taskENTER_CRITICAL(); { /* See if data was added to the queue while it was locked. */ while( pxQueue->xTxLock > queueLOCKED_UNMODIFIED ) { /* Data was posted while the queue was locked. Are any tasks blocked waiting for data to become available? */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { /* Tasks that are removed from the event list will get added to the pending ready list as the scheduler is still suspended. */ if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ vTaskMissedYield(); } --( pxQueue->xTxLock ); } else { break; } } pxQueue->xTxLock = queueUNLOCKED; } taskEXIT_CRITICAL(); /* Do the same for the Rx lock. */ taskENTER_CRITICAL(); { while( pxQueue->xRxLock > queueLOCKED_UNMODIFIED ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { vTaskMissedYield(); } --( pxQueue->xRxLock ); } else { break; } } pxQueue->xRxLock = queueUNLOCKED; } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ static signed portBASE_TYPE prvIsQueueEmpty( const xQueueHandle pxQueue ) { signed portBASE_TYPE xReturn; taskENTER_CRITICAL(); xReturn = ( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0 ); taskEXIT_CRITICAL(); return xReturn; } /*-----------------------------------------------------------*/ signed portBASE_TYPE xQueueIsQueueEmptyFromISR( const xQueueHandle pxQueue ) { signed portBASE_TYPE xReturn; configASSERT( pxQueue ); xReturn = ( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0 ); return xReturn; } /*-----------------------------------------------------------*/ static signed portBASE_TYPE prvIsQueueFull( const xQueueHandle pxQueue ) { signed portBASE_TYPE xReturn; taskENTER_CRITICAL(); xReturn = ( pxQueue->uxMessagesWaiting == pxQueue->uxLength ); taskEXIT_CRITICAL(); return xReturn; } /*-----------------------------------------------------------*/ signed portBASE_TYPE xQueueIsQueueFullFromISR( const xQueueHandle pxQueue ) { signed portBASE_TYPE xReturn; configASSERT( pxQueue ); xReturn = ( pxQueue->uxMessagesWaiting == pxQueue->uxLength ); return xReturn; } /*-----------------------------------------------------------*/ #if configUSE_CO_ROUTINES == 1 signed portBASE_TYPE xQueueCRSend( xQueueHandle pxQueue, const void *pvItemToQueue, portTickType xTicksToWait ) { signed portBASE_TYPE xReturn; /* If the queue is already full we may have to block. A critical section is required to prevent an interrupt removing something from the queue between the check to see if the queue is full and blocking on the queue. */ portDISABLE_INTERRUPTS(); { if( prvIsQueueFull( pxQueue ) ) { /* The queue is full - do we want to block or just leave without posting? */ if( xTicksToWait > ( portTickType ) 0 ) { /* As this is called from a coroutine we cannot block directly, but return indicating that we need to block. */ vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); portENABLE_INTERRUPTS(); return errQUEUE_BLOCKED; } else { portENABLE_INTERRUPTS(); return errQUEUE_FULL; } } } portENABLE_INTERRUPTS(); portNOP(); portDISABLE_INTERRUPTS(); { if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { /* There is room in the queue, copy the data into the queue. */ prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); xReturn = pdPASS; /* Were any co-routines waiting for data to become available? */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { /* In this instance the co-routine could be placed directly into the ready list as we are within a critical section. Instead the same pending ready list mechanism is used as if the event were caused from within an interrupt. */ if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The co-routine waiting has a higher priority so record that a yield might be appropriate. */ xReturn = errQUEUE_YIELD; } } } else { xReturn = errQUEUE_FULL; } } portENABLE_INTERRUPTS(); return xReturn; } #endif /*-----------------------------------------------------------*/ #if configUSE_CO_ROUTINES == 1 signed portBASE_TYPE xQueueCRReceive( xQueueHandle pxQueue, void *pvBuffer, portTickType xTicksToWait ) { signed portBASE_TYPE xReturn; /* If the queue is already empty we may have to block. A critical section is required to prevent an interrupt adding something to the queue between the check to see if the queue is empty and blocking on the queue. */ portDISABLE_INTERRUPTS(); { if( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0 ) { /* There are no messages in the queue, do we want to block or just leave with nothing? */ if( xTicksToWait > ( portTickType ) 0 ) { /* As this is a co-routine we cannot block directly, but return indicating that we need to block. */ vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); portENABLE_INTERRUPTS(); return errQUEUE_BLOCKED; } else { portENABLE_INTERRUPTS(); return errQUEUE_FULL; } } } portENABLE_INTERRUPTS(); portNOP(); portDISABLE_INTERRUPTS(); { if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ) { /* Data is available from the queue. */ pxQueue->pcReadFrom += pxQueue->uxItemSize; if( pxQueue->pcReadFrom >= pxQueue->pcTail ) { pxQueue->pcReadFrom = pxQueue->pcHead; } --( pxQueue->uxMessagesWaiting ); memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); xReturn = pdPASS; /* Were any co-routines waiting for space to become available? */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { /* In this instance the co-routine could be placed directly into the ready list as we are within a critical section. Instead the same pending ready list mechanism is used as if the event were caused from within an interrupt. */ if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { xReturn = errQUEUE_YIELD; } } } else { xReturn = pdFAIL; } } portENABLE_INTERRUPTS(); return xReturn; } #endif /*-----------------------------------------------------------*/ #if configUSE_CO_ROUTINES == 1 signed portBASE_TYPE xQueueCRSendFromISR( xQueueHandle pxQueue, const void *pvItemToQueue, signed portBASE_TYPE xCoRoutinePreviouslyWoken ) { /* Cannot block within an ISR so if there is no space on the queue then exit without doing anything. */ if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); /* We only want to wake one co-routine per ISR, so check that a co-routine has not already been woken. */ if( !xCoRoutinePreviouslyWoken ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { return pdTRUE; } } } } return xCoRoutinePreviouslyWoken; } #endif /*-----------------------------------------------------------*/ #if configUSE_CO_ROUTINES == 1 signed portBASE_TYPE xQueueCRReceiveFromISR( xQueueHandle pxQueue, void *pvBuffer, signed portBASE_TYPE *pxCoRoutineWoken ) { signed portBASE_TYPE xReturn; /* We cannot block from an ISR, so check there is data available. If not then just leave without doing anything. */ if( pxQueue->uxMessagesWaiting > ( unsigned portBASE_TYPE ) 0 ) { /* Copy the data from the queue. */ pxQueue->pcReadFrom += pxQueue->uxItemSize; if( pxQueue->pcReadFrom >= pxQueue->pcTail ) { pxQueue->pcReadFrom = pxQueue->pcHead; } --( pxQueue->uxMessagesWaiting ); memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); if( !( *pxCoRoutineWoken ) ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { *pxCoRoutineWoken = pdTRUE; } } } xReturn = pdPASS; } else { xReturn = pdFAIL; } return xReturn; } #endif /*-----------------------------------------------------------*/ #if configQUEUE_REGISTRY_SIZE > 0 void vQueueAddToRegistry( xQueueHandle xQueue, signed char *pcQueueName ) { unsigned portBASE_TYPE ux; /* See if there is an empty space in the registry. A NULL name denotes a free slot. */ for( ux = ( unsigned portBASE_TYPE ) 0U; ux < configQUEUE_REGISTRY_SIZE; ux++ ) { if( xQueueRegistry[ ux ].pcQueueName == NULL ) { /* Store the information on this queue. */ xQueueRegistry[ ux ].pcQueueName = pcQueueName; xQueueRegistry[ ux ].xHandle = xQueue; break; } } } #endif /*-----------------------------------------------------------*/ #if configQUEUE_REGISTRY_SIZE > 0 static void vQueueUnregisterQueue( xQueueHandle xQueue ) { unsigned portBASE_TYPE ux; /* See if the handle of the queue being unregistered in actually in the registry. */ for( ux = ( unsigned portBASE_TYPE ) 0U; ux < configQUEUE_REGISTRY_SIZE; ux++ ) { if( xQueueRegistry[ ux ].xHandle == xQueue ) { /* Set the name to NULL to show that this slot if free again. */ xQueueRegistry[ ux ].pcQueueName = NULL; break; } } } #endif /*-----------------------------------------------------------*/ #if configUSE_TIMERS == 1 void vQueueWaitForMessageRestricted( xQueueHandle pxQueue, portTickType xTicksToWait ) { /* This function should not be called by application code hence the 'Restricted' in its name. It is not part of the public API. It is designed for use by kernel code, and has special calling requirements. It can result in vListInsert() being called on a list that can only possibly ever have one item in it, so the list will be fast, but even so it should be called with the scheduler locked and not from a critical section. */ /* Only do anything if there are no messages in the queue. This function will not actually cause the task to block, just place it on a blocked list. It will not block until the scheduler is unlocked - at which time a yield will be performed. If an item is added to the queue while the queue is locked, and the calling task blocks on the queue, then the calling task will be immediately unblocked when the queue is unlocked. */ prvLockQueue( pxQueue ); if( pxQueue->uxMessagesWaiting == ( unsigned portBASE_TYPE ) 0U ) { /* There is nothing in the queue, block for the specified period. */ vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); } prvUnlockQueue( pxQueue ); } #endif
722,289
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/list.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. FreeRTOS supports many tools and architectures. V7.0.0 is sponsored by: Atollic AB - Atollic provides professional embedded systems development tools for C/C++ development, code analysis and test automation. See http://www.atollic.com *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ #include <stdlib.h> #include "FreeRTOS.h" #include "list.h" /*----------------------------------------------------------- * PUBLIC LIST API documented in list.h *----------------------------------------------------------*/ void vListInitialise( xList *pxList ) { /* The list structure contains a list item which is used to mark the end of the list. To initialise the list the list end is inserted as the only list entry. */ pxList->pxIndex = ( xListItem * ) &( pxList->xListEnd ); /* The list end value is the highest possible value in the list to ensure it remains at the end of the list. */ pxList->xListEnd.xItemValue = portMAX_DELAY; /* The list end next and previous pointers point to itself so we know when the list is empty. */ pxList->xListEnd.pxNext = ( xListItem * ) &( pxList->xListEnd ); pxList->xListEnd.pxPrevious = ( xListItem * ) &( pxList->xListEnd ); pxList->uxNumberOfItems = ( unsigned portBASE_TYPE ) 0U; } /*-----------------------------------------------------------*/ void vListInitialiseItem( xListItem *pxItem ) { /* Make sure the list item is not recorded as being on a list. */ pxItem->pvContainer = NULL; } /*-----------------------------------------------------------*/ void vListInsertEnd( xList *pxList, xListItem *pxNewListItem ) { volatile xListItem * pxIndex; /* Insert a new list item into pxList, but rather than sort the list, makes the new list item the last item to be removed by a call to pvListGetOwnerOfNextEntry. This means it has to be the item pointed to by the pxIndex member. */ pxIndex = pxList->pxIndex; pxNewListItem->pxNext = pxIndex->pxNext; pxNewListItem->pxPrevious = pxList->pxIndex; pxIndex->pxNext->pxPrevious = ( volatile xListItem * ) pxNewListItem; pxIndex->pxNext = ( volatile xListItem * ) pxNewListItem; pxList->pxIndex = ( volatile xListItem * ) pxNewListItem; /* Remember which list the item is in. */ pxNewListItem->pvContainer = ( void * ) pxList; ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ void vListInsert( xList *pxList, xListItem *pxNewListItem ) { volatile xListItem *pxIterator; portTickType xValueOfInsertion; /* Insert the new list item into the list, sorted in ulListItem order. */ xValueOfInsertion = pxNewListItem->xItemValue; /* If the list already contains a list item with the same item value then the new list item should be placed after it. This ensures that TCB's which are stored in ready lists (all of which have the same ulListItem value) get an equal share of the CPU. However, if the xItemValue is the same as the back marker the iteration loop below will not end. This means we need to guard against this by checking the value first and modifying the algorithm slightly if necessary. */ if( xValueOfInsertion == portMAX_DELAY ) { pxIterator = pxList->xListEnd.pxPrevious; } else { /* *** NOTE *********************************************************** If you find your application is crashing here then likely causes are: 1) Stack overflow - see http://www.freertos.org/Stacks-and-stack-overflow-checking.html 2) Incorrect interrupt priority assignment, especially on Cortex-M3 parts where numerically high priority values denote low actual interrupt priories, which can seem counter intuitive. See configMAX_SYSCALL_INTERRUPT_PRIORITY on http://www.freertos.org/a00110.html 3) Calling an API function from within a critical section or when the scheduler is suspended. 4) Using a queue or semaphore before it has been initialised or before the scheduler has been started (are interrupts firing before vTaskStartScheduler() has been called?). See http://www.freertos.org/FAQHelp.html for more tips. **********************************************************************/ for( pxIterator = ( xListItem * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) { /* There is nothing to do here, we are just iterating to the wanted insertion position. */ } } pxNewListItem->pxNext = pxIterator->pxNext; pxNewListItem->pxNext->pxPrevious = ( volatile xListItem * ) pxNewListItem; pxNewListItem->pxPrevious = pxIterator; pxIterator->pxNext = ( volatile xListItem * ) pxNewListItem; /* Remember which list the item is in. This allows fast removal of the item later. */ pxNewListItem->pvContainer = ( void * ) pxList; ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ void vListRemove( xListItem *pxItemToRemove ) { xList * pxList; pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; /* The list item knows which list it is in. Obtain the list from the list item. */ pxList = ( xList * ) pxItemToRemove->pvContainer; /* Make sure the index is left pointing to a valid item. */ if( pxList->pxIndex == pxItemToRemove ) { pxList->pxIndex = pxItemToRemove->pxPrevious; } pxItemToRemove->pvContainer = NULL; ( pxList->uxNumberOfItems )--; } /*-----------------------------------------------------------*/
722,290
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/tasks.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. FreeRTOS supports many tools and architectures. V7.0.0 is sponsored by: Atollic AB - Atollic provides professional embedded systems development tools for C/C++ development, code analysis and test automation. See http://www.atollic.com *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE #include "FreeRTOS.h" #include "task.h" #include "timers.h" #include "StackMacros.h" #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /* * Macro to define the amount of stack available to the idle task. */ #define tskIDLE_STACK_SIZE configMINIMAL_STACK_SIZE /* * Task control block. A task control block (TCB) is allocated to each task, * and stores the context of the task. */ typedef struct tskTaskControlBlock { volatile portSTACK_TYPE *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE STRUCT. */ #if ( portUSING_MPU_WRAPPERS == 1 ) xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE STRUCT. */ #endif xListItem xGenericListItem; /*< List item used to place the TCB in ready and blocked queues. */ xListItem xEventListItem; /*< List item used to place the TCB in event lists. */ unsigned portBASE_TYPE uxPriority; /*< The priority of the task where 0 is the lowest priority. */ portSTACK_TYPE *pxStack; /*< Points to the start of the stack. */ signed char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ #if ( portSTACK_GROWTH > 0 ) portSTACK_TYPE *pxEndOfStack; /*< Used for stack overflow checking on architectures where the stack grows up from low memory. */ #endif #if ( portCRITICAL_NESTING_IN_TCB == 1 ) unsigned portBASE_TYPE uxCriticalNesting; #endif #if ( configUSE_TRACE_FACILITY == 1 ) unsigned portBASE_TYPE uxTCBNumber; /*< This is used for tracing the scheduler and making debugging easier only. */ #endif #if ( configUSE_MUTEXES == 1 ) unsigned portBASE_TYPE uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ #endif #if ( configUSE_APPLICATION_TASK_TAG == 1 ) pdTASK_HOOK_CODE pxTaskTag; #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) unsigned long ulRunTimeCounter; /*< Used for calculating how much CPU time each task is utilising. */ #endif } tskTCB; /* * Some kernel aware debuggers require data to be viewed to be global, rather * than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER #define static #endif /*lint -e956 */ PRIVILEGED_DATA tskTCB * volatile pxCurrentTCB = NULL; /* Lists for ready and blocked tasks. --------------------*/ PRIVILEGED_DATA static xList pxReadyTasksLists[ configMAX_PRIORITIES ]; /*< Prioritised ready tasks. */ PRIVILEGED_DATA static xList xDelayedTaskList1; /*< Delayed tasks. */ PRIVILEGED_DATA static xList xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ PRIVILEGED_DATA static xList * volatile pxDelayedTaskList ; /*< Points to the delayed task list currently being used. */ PRIVILEGED_DATA static xList * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ PRIVILEGED_DATA static xList xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready queue when the scheduler is resumed. */ #if ( INCLUDE_vTaskDelete == 1 ) PRIVILEGED_DATA static volatile xList xTasksWaitingTermination; /*< Tasks that have been deleted - but the their memory not yet freed. */ PRIVILEGED_DATA static volatile unsigned portBASE_TYPE uxTasksDeleted = ( unsigned portBASE_TYPE ) 0; #endif #if ( INCLUDE_vTaskSuspend == 1 ) PRIVILEGED_DATA static xList xSuspendedTaskList; /*< Tasks that are currently suspended. */ #endif /* File private variables. --------------------------------*/ PRIVILEGED_DATA static volatile unsigned portBASE_TYPE uxCurrentNumberOfTasks = ( unsigned portBASE_TYPE ) 0; PRIVILEGED_DATA static volatile portTickType xTickCount = ( portTickType ) 0; PRIVILEGED_DATA static unsigned portBASE_TYPE uxTopUsedPriority = tskIDLE_PRIORITY; PRIVILEGED_DATA static volatile unsigned portBASE_TYPE uxTopReadyPriority = tskIDLE_PRIORITY; PRIVILEGED_DATA static volatile signed portBASE_TYPE xSchedulerRunning = pdFALSE; PRIVILEGED_DATA static volatile unsigned portBASE_TYPE uxSchedulerSuspended = ( unsigned portBASE_TYPE ) pdFALSE; PRIVILEGED_DATA static volatile unsigned portBASE_TYPE uxMissedTicks = ( unsigned portBASE_TYPE ) 0; PRIVILEGED_DATA static volatile portBASE_TYPE xMissedYield = ( portBASE_TYPE ) pdFALSE; PRIVILEGED_DATA static volatile portBASE_TYPE xNumOfOverflows = ( portBASE_TYPE ) 0; PRIVILEGED_DATA static unsigned portBASE_TYPE uxTaskNumber = ( unsigned portBASE_TYPE ) 0; PRIVILEGED_DATA static portTickType xNextTaskUnblockTime = ( portTickType ) portMAX_DELAY; #if ( configGENERATE_RUN_TIME_STATS == 1 ) PRIVILEGED_DATA static char pcStatsString[ 50 ] ; PRIVILEGED_DATA static unsigned long ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ static void prvGenerateRunTimeStatsForTasksInList( const signed char *pcWriteBuffer, xList *pxList, unsigned long ulTotalRunTime ) PRIVILEGED_FUNCTION; #endif /* Debugging and trace facilities private variables and macros. ------------*/ /* * The value used to fill the stack of a task when the task is created. This * is used purely for checking the high water mark for tasks. */ #define tskSTACK_FILL_BYTE ( 0xa5U ) /* * Macros used by vListTask to indicate which state a task is in. */ #define tskBLOCKED_CHAR ( ( signed char ) 'B' ) #define tskREADY_CHAR ( ( signed char ) 'R' ) #define tskDELETED_CHAR ( ( signed char ) 'D' ) #define tskSUSPENDED_CHAR ( ( signed char ) 'S' ) /* * Macros and private variables used by the trace facility. */ #if ( configUSE_TRACE_FACILITY == 1 ) #define tskSIZE_OF_EACH_TRACE_LINE ( ( unsigned long ) ( sizeof( unsigned long ) + sizeof( unsigned long ) ) ) PRIVILEGED_DATA static volatile signed char * volatile pcTraceBuffer; PRIVILEGED_DATA static signed char *pcTraceBufferStart; PRIVILEGED_DATA static signed char *pcTraceBufferEnd; PRIVILEGED_DATA static signed portBASE_TYPE xTracing = pdFALSE; static unsigned portBASE_TYPE uxPreviousTask = 255U; PRIVILEGED_DATA static char pcStatusString[ 50 ]; #endif /*-----------------------------------------------------------*/ /* * Macro that writes a trace of scheduler activity to a buffer. This trace * shows which task is running when and is very useful as a debugging tool. * As this macro is called each context switch it is a good idea to undefine * it if not using the facility. */ #if ( configUSE_TRACE_FACILITY == 1 ) #define vWriteTraceToBuffer() \ { \ if( xTracing ) \ { \ if( uxPreviousTask != pxCurrentTCB->uxTCBNumber ) \ { \ if( ( pcTraceBuffer + tskSIZE_OF_EACH_TRACE_LINE ) < pcTraceBufferEnd ) \ { \ uxPreviousTask = pxCurrentTCB->uxTCBNumber; \ *( unsigned long * ) pcTraceBuffer = ( unsigned long ) xTickCount; \ pcTraceBuffer += sizeof( unsigned long ); \ *( unsigned long * ) pcTraceBuffer = ( unsigned long ) uxPreviousTask; \ pcTraceBuffer += sizeof( unsigned long ); \ } \ else \ { \ xTracing = pdFALSE; \ } \ } \ } \ } #else #define vWriteTraceToBuffer() #endif /*-----------------------------------------------------------*/ /* * Place the task represented by pxTCB into the appropriate ready queue for * the task. It is inserted at the end of the list. One quirk of this is * that if the task being inserted is at the same priority as the currently * executing task, then it will only be rescheduled after the currently * executing task has been rescheduled. */ #define prvAddTaskToReadyQueue( pxTCB ) \ if( ( pxTCB )->uxPriority > uxTopReadyPriority ) \ { \ uxTopReadyPriority = ( pxTCB )->uxPriority; \ } \ vListInsertEnd( ( xList * ) &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xGenericListItem ) ) /*-----------------------------------------------------------*/ /* * Macro that looks at the list of tasks that are currently delayed to see if * any require waking. * * Tasks are stored in the queue in the order of their wake time - meaning * once one tasks has been found whose timer has not expired we need not look * any further down the list. */ #define prvCheckDelayedTasks() \ { \ portTickType xItemValue; \ \ /* Is the tick count greater than or equal to the wake time of the first \ task referenced from the delayed tasks list? */ \ if( xTickCount >= xNextTaskUnblockTime ) \ { \ for( ;; ) \ { \ if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) \ { \ /* The delayed list is empty. Set xNextTaskUnblockTime to the \ maximum possible value so it is extremely unlikely that the \ if( xTickCount >= xNextTaskUnblockTime ) test will pass next \ time through. */ \ xNextTaskUnblockTime = portMAX_DELAY; \ break; \ } \ else \ { \ /* The delayed list is not empty, get the value of the item at \ the head of the delayed list. This is the time at which the \ task at the head of the delayed list should be removed from \ the Blocked state. */ \ pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); \ xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xGenericListItem ) ); \ \ if( xTickCount < xItemValue ) \ { \ /* It is not time to unblock this item yet, but the item \ value is the time at which the task at the head of the \ blocked list should be removed from the Blocked state - \ so record the item value in xNextTaskUnblockTime. */ \ xNextTaskUnblockTime = xItemValue; \ break; \ } \ \ /* It is time to remove the item from the Blocked state. */ \ vListRemove( &( pxTCB->xGenericListItem ) ); \ \ /* Is the task waiting on an event also? */ \ if( pxTCB->xEventListItem.pvContainer ) \ { \ vListRemove( &( pxTCB->xEventListItem ) ); \ } \ prvAddTaskToReadyQueue( pxTCB ); \ } \ } \ } \ } /*-----------------------------------------------------------*/ /* * Several functions take an xTaskHandle parameter that can optionally be NULL, * where NULL is used to indicate that the handle of the currently executing * task should be used in place of the parameter. This macro simply checks to * see if the parameter is NULL and returns a pointer to the appropriate TCB. */ #define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? ( tskTCB * ) pxCurrentTCB : ( tskTCB * ) ( pxHandle ) ) /* Callback function prototypes. --------------------------*/ extern void vApplicationStackOverflowHook( xTaskHandle *pxTask, signed char *pcTaskName ); extern void vApplicationTickHook( void ); /* File private functions. --------------------------------*/ /* * Utility to ready a TCB for a given task. Mainly just copies the parameters * into the TCB structure. */ static void prvInitialiseTCBVariables( tskTCB *pxTCB, const signed char * const pcName, unsigned portBASE_TYPE uxPriority, const xMemoryRegion * const xRegions, unsigned short usStackDepth ) PRIVILEGED_FUNCTION; /* * Utility to ready all the lists used by the scheduler. This is called * automatically upon the creation of the first task. */ static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; /* * The idle task, which as all tasks is implemented as a never ending loop. * The idle task is automatically created and added to the ready lists upon * creation of the first user task. * * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific * language extensions. The equivalent prototype for this function is: * * void prvIdleTask( void *pvParameters ); * */ static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ); /* * Utility to free all memory allocated by the scheduler to hold a TCB, * including the stack pointed to by the TCB. * * This does not free memory allocated by the task itself (i.e. memory * allocated by calls to pvPortMalloc from within the tasks application code). */ #if ( ( INCLUDE_vTaskDelete == 1 ) || ( INCLUDE_vTaskCleanUpResources == 1 ) ) static void prvDeleteTCB( tskTCB *pxTCB ) PRIVILEGED_FUNCTION; #endif /* * Used only by the idle task. This checks to see if anything has been placed * in the list of tasks waiting to be deleted. If so the task is cleaned up * and its TCB deleted. */ static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; /* * The currently executing task is entering the Blocked state. Add the task to * either the current or the overflow delayed task list. */ static void prvAddCurrentTaskToDelayedList( portTickType xTimeToWake ) PRIVILEGED_FUNCTION; /* * Allocates memory from the heap for a TCB and associated stack. Checks the * allocation was successful. */ static tskTCB *prvAllocateTCBAndStack( unsigned short usStackDepth, portSTACK_TYPE *puxStackBuffer ) PRIVILEGED_FUNCTION; /* * Called from vTaskList. vListTasks details all the tasks currently under * control of the scheduler. The tasks may be in one of a number of lists. * prvListTaskWithinSingleList accepts a list and details the tasks from * within just that list. * * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM * NORMAL APPLICATION CODE. */ #if ( configUSE_TRACE_FACILITY == 1 ) static void prvListTaskWithinSingleList( const signed char *pcWriteBuffer, xList *pxList, signed char cStatus ) PRIVILEGED_FUNCTION; #endif /* * When a task is created, the stack of the task is filled with a known value. * This function determines the 'high water mark' of the task stack by * determining how much of the stack remains at the original preset value. */ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) static unsigned short usTaskCheckFreeStackSpace( const unsigned char * pucStackByte ) PRIVILEGED_FUNCTION; #endif /*lint +e956 */ /*----------------------------------------------------------- * TASK CREATION API documented in task.h *----------------------------------------------------------*/ signed portBASE_TYPE xTaskGenericCreate( pdTASK_CODE pxTaskCode, const signed char * const pcName, unsigned short usStackDepth, void *pvParameters, unsigned portBASE_TYPE uxPriority, xTaskHandle *pxCreatedTask, portSTACK_TYPE *puxStackBuffer, const xMemoryRegion * const xRegions ) { signed portBASE_TYPE xReturn; tskTCB * pxNewTCB; configASSERT( pxTaskCode ); configASSERT( ( uxPriority < configMAX_PRIORITIES ) ); /* Allocate the memory required by the TCB and stack for the new task, checking that the allocation was successful. */ pxNewTCB = prvAllocateTCBAndStack( usStackDepth, puxStackBuffer ); if( pxNewTCB != NULL ) { portSTACK_TYPE *pxTopOfStack; #if( portUSING_MPU_WRAPPERS == 1 ) /* Should the task be created in privileged mode? */ portBASE_TYPE xRunPrivileged; if( ( uxPriority & portPRIVILEGE_BIT ) != 0x00 ) { xRunPrivileged = pdTRUE; } else { xRunPrivileged = pdFALSE; } uxPriority &= ~portPRIVILEGE_BIT; #endif /* portUSING_MPU_WRAPPERS == 1 */ /* Calculate the top of stack address. This depends on whether the stack grows from high memory to low (as per the 80x86) or visa versa. portSTACK_GROWTH is used to make the result positive or negative as required by the port. */ #if( portSTACK_GROWTH < 0 ) { pxTopOfStack = pxNewTCB->pxStack + ( usStackDepth - ( unsigned short ) 1 ); pxTopOfStack = ( portSTACK_TYPE * ) ( ( ( unsigned long ) pxTopOfStack ) & ( ( unsigned long ) ~portBYTE_ALIGNMENT_MASK ) ); /* Check the alignment of the calculated top of stack is correct. */ configASSERT( ( ( ( unsigned long ) pxTopOfStack & ( unsigned long ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); } #else { pxTopOfStack = pxNewTCB->pxStack; /* Check the alignment of the stack buffer is correct. */ configASSERT( ( ( ( unsigned long ) pxNewTCB->pxStack & ( unsigned long ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); /* If we want to use stack checking on architectures that use a positive stack growth direction then we also need to store the other extreme of the stack space. */ pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( usStackDepth - 1 ); } #endif /* Setup the newly allocated TCB with the initial state of the task. */ prvInitialiseTCBVariables( pxNewTCB, pcName, uxPriority, xRegions, usStackDepth ); /* Initialize the TCB stack to look as if the task was already running, but had been interrupted by the scheduler. The return address is set to the start of the task function. Once the stack has been initialised the top of stack variable is updated. */ #if( portUSING_MPU_WRAPPERS == 1 ) { pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); } #else { pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); } #endif /* Check the alignment of the initialised stack. */ configASSERT( ( ( ( unsigned long ) pxNewTCB->pxTopOfStack & ( unsigned long ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); if( ( void * ) pxCreatedTask != NULL ) { /* Pass the TCB out - in an anonymous way. The calling function/ task can use this as a handle to delete the task later if required.*/ *pxCreatedTask = ( xTaskHandle ) pxNewTCB; } /* We are going to manipulate the task queues to add this task to a ready list, so must make sure no interrupts occur. */ taskENTER_CRITICAL(); { uxCurrentNumberOfTasks++; if( pxCurrentTCB == NULL ) { /* There are no other tasks, or all the other tasks are in the suspended state - make this the current task. */ pxCurrentTCB = pxNewTCB; if( uxCurrentNumberOfTasks == ( unsigned portBASE_TYPE ) 1 ) { /* This is the first task to be created so do the preliminary initialisation required. We will not recover if this call fails, but we will report the failure. */ prvInitialiseTaskLists(); } } else { /* If the scheduler is not already running, make this task the current task if it is the highest priority task to be created so far. */ if( xSchedulerRunning == pdFALSE ) { if( pxCurrentTCB->uxPriority <= uxPriority ) { pxCurrentTCB = pxNewTCB; } } } /* Remember the top priority to make context switching faster. Use the priority in pxNewTCB as this has been capped to a valid value. */ if( pxNewTCB->uxPriority > uxTopUsedPriority ) { uxTopUsedPriority = pxNewTCB->uxPriority; } #if ( configUSE_TRACE_FACILITY == 1 ) { /* Add a counter into the TCB for tracing only. */ pxNewTCB->uxTCBNumber = uxTaskNumber; } #endif uxTaskNumber++; prvAddTaskToReadyQueue( pxNewTCB ); xReturn = pdPASS; traceTASK_CREATE( pxNewTCB ); } taskEXIT_CRITICAL(); } else { xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; traceTASK_CREATE_FAILED(); } if( xReturn == pdPASS ) { if( xSchedulerRunning != pdFALSE ) { /* If the created task is of a higher priority than the current task then it should run now. */ if( pxCurrentTCB->uxPriority < uxPriority ) { portYIELD_WITHIN_API(); } } } return xReturn; } /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) void vTaskDelete( xTaskHandle pxTaskToDelete ) { tskTCB *pxTCB; taskENTER_CRITICAL(); { /* Ensure a yield is performed if the current task is being deleted. */ if( pxTaskToDelete == pxCurrentTCB ) { pxTaskToDelete = NULL; } /* If null is passed in here then we are deleting ourselves. */ pxTCB = prvGetTCBFromHandle( pxTaskToDelete ); /* Remove task from the ready list and place in the termination list. This will stop the task from be scheduled. The idle task will check the termination list and free up any memory allocated by the scheduler for the TCB and stack. */ vListRemove( &( pxTCB->xGenericListItem ) ); /* Is the task waiting on an event also? */ if( pxTCB->xEventListItem.pvContainer ) { vListRemove( &( pxTCB->xEventListItem ) ); } vListInsertEnd( ( xList * ) &xTasksWaitingTermination, &( pxTCB->xGenericListItem ) ); /* Increment the ucTasksDeleted variable so the idle task knows there is a task that has been deleted and that it should therefore check the xTasksWaitingTermination list. */ ++uxTasksDeleted; /* Increment the uxTaskNumberVariable also so kernel aware debuggers can detect that the task lists need re-generating. */ uxTaskNumber++; traceTASK_DELETE( pxTCB ); } taskEXIT_CRITICAL(); /* Force a reschedule if we have just deleted the current task. */ if( xSchedulerRunning != pdFALSE ) { if( ( void * ) pxTaskToDelete == NULL ) { portYIELD_WITHIN_API(); } } } #endif /*----------------------------------------------------------- * TASK CONTROL API documented in task.h *----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelayUntil == 1 ) void vTaskDelayUntil( portTickType * const pxPreviousWakeTime, portTickType xTimeIncrement ) { portTickType xTimeToWake; portBASE_TYPE xAlreadyYielded, xShouldDelay = pdFALSE; configASSERT( pxPreviousWakeTime ); configASSERT( ( xTimeIncrement > 0 ) ); vTaskSuspendAll(); { /* Generate the tick time at which the task wants to wake. */ xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; if( xTickCount < *pxPreviousWakeTime ) { /* The tick count has overflowed since this function was lasted called. In this case the only time we should ever actually delay is if the wake time has also overflowed, and the wake time is greater than the tick time. When this is the case it is as if neither time had overflowed. */ if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xTickCount ) ) { xShouldDelay = pdTRUE; } } else { /* The tick time has not overflowed. In this case we will delay if either the wake time has overflowed, and/or the tick time is less than the wake time. */ if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xTickCount ) ) { xShouldDelay = pdTRUE; } } /* Update the wake time ready for the next call. */ *pxPreviousWakeTime = xTimeToWake; if( xShouldDelay != pdFALSE ) { traceTASK_DELAY_UNTIL(); /* We must remove ourselves from the ready list before adding ourselves to the blocked list as the same list item is used for both lists. */ vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); prvAddCurrentTaskToDelayedList( xTimeToWake ); } } xAlreadyYielded = xTaskResumeAll(); /* Force a reschedule if xTaskResumeAll has not already done so, we may have put ourselves to sleep. */ if( !xAlreadyYielded ) { portYIELD_WITHIN_API(); } } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelay == 1 ) void vTaskDelay( portTickType xTicksToDelay ) { portTickType xTimeToWake; signed portBASE_TYPE xAlreadyYielded = pdFALSE; /* A delay time of zero just forces a reschedule. */ if( xTicksToDelay > ( portTickType ) 0 ) { vTaskSuspendAll(); { traceTASK_DELAY(); /* A task that is removed from the event list while the scheduler is suspended will not get placed in the ready list or removed from the blocked list until the scheduler is resumed. This task cannot be in an event list as it is the currently executing task. */ /* Calculate the time to wake - this may overflow but this is not a problem. */ xTimeToWake = xTickCount + xTicksToDelay; /* We must remove ourselves from the ready list before adding ourselves to the blocked list as the same list item is used for both lists. */ vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); prvAddCurrentTaskToDelayedList( xTimeToWake ); } xAlreadyYielded = xTaskResumeAll(); } /* Force a reschedule if xTaskResumeAll has not already done so, we may have put ourselves to sleep. */ if( !xAlreadyYielded ) { portYIELD_WITHIN_API(); } } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) unsigned portBASE_TYPE uxTaskPriorityGet( xTaskHandle pxTask ) { tskTCB *pxTCB; unsigned portBASE_TYPE uxReturn; taskENTER_CRITICAL(); { /* If null is passed in here then we are changing the priority of the calling function. */ pxTCB = prvGetTCBFromHandle( pxTask ); uxReturn = pxTCB->uxPriority; } taskEXIT_CRITICAL(); return uxReturn; } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskPrioritySet == 1 ) void vTaskPrioritySet( xTaskHandle pxTask, unsigned portBASE_TYPE uxNewPriority ) { tskTCB *pxTCB; unsigned portBASE_TYPE uxCurrentPriority; portBASE_TYPE xYieldRequired = pdFALSE; configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); /* Ensure the new priority is valid. */ if( uxNewPriority >= configMAX_PRIORITIES ) { uxNewPriority = configMAX_PRIORITIES - ( unsigned portBASE_TYPE ) 1U; } taskENTER_CRITICAL(); { if( pxTask == pxCurrentTCB ) { pxTask = NULL; } /* If null is passed in here then we are changing the priority of the calling function. */ pxTCB = prvGetTCBFromHandle( pxTask ); traceTASK_PRIORITY_SET( pxTask, uxNewPriority ); #if ( configUSE_MUTEXES == 1 ) { uxCurrentPriority = pxTCB->uxBasePriority; } #else { uxCurrentPriority = pxTCB->uxPriority; } #endif if( uxCurrentPriority != uxNewPriority ) { /* The priority change may have readied a task of higher priority than the calling task. */ if( uxNewPriority > uxCurrentPriority ) { if( pxTask != NULL ) { /* The priority of another task is being raised. If we were raising the priority of the currently running task there would be no need to switch as it must have already been the highest priority task. */ xYieldRequired = pdTRUE; } } else if( pxTask == NULL ) { /* Setting our own priority down means there may now be another task of higher priority that is ready to execute. */ xYieldRequired = pdTRUE; } #if ( configUSE_MUTEXES == 1 ) { /* Only change the priority being used if the task is not currently using an inherited priority. */ if( pxTCB->uxBasePriority == pxTCB->uxPriority ) { pxTCB->uxPriority = uxNewPriority; } /* The base priority gets set whatever. */ pxTCB->uxBasePriority = uxNewPriority; } #else { pxTCB->uxPriority = uxNewPriority; } #endif listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( configMAX_PRIORITIES - ( portTickType ) uxNewPriority ) ); /* If the task is in the blocked or suspended list we need do nothing more than change it's priority variable. However, if the task is in a ready list it needs to be removed and placed in the queue appropriate to its new priority. */ if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxCurrentPriority ] ), &( pxTCB->xGenericListItem ) ) ) { /* The task is currently in its ready list - remove before adding it to it's new ready list. As we are in a critical section we can do this even if the scheduler is suspended. */ vListRemove( &( pxTCB->xGenericListItem ) ); prvAddTaskToReadyQueue( pxTCB ); } if( xYieldRequired == pdTRUE ) { portYIELD_WITHIN_API(); } } } taskEXIT_CRITICAL(); } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) void vTaskSuspend( xTaskHandle pxTaskToSuspend ) { tskTCB *pxTCB; taskENTER_CRITICAL(); { /* Ensure a yield is performed if the current task is being suspended. */ if( pxTaskToSuspend == pxCurrentTCB ) { pxTaskToSuspend = NULL; } /* If null is passed in here then we are suspending ourselves. */ pxTCB = prvGetTCBFromHandle( pxTaskToSuspend ); traceTASK_SUSPEND( pxTCB ); /* Remove task from the ready/delayed list and place in the suspended list. */ vListRemove( &( pxTCB->xGenericListItem ) ); /* Is the task waiting on an event also? */ if( pxTCB->xEventListItem.pvContainer ) { vListRemove( &( pxTCB->xEventListItem ) ); } vListInsertEnd( ( xList * ) &xSuspendedTaskList, &( pxTCB->xGenericListItem ) ); } taskEXIT_CRITICAL(); if( ( void * ) pxTaskToSuspend == NULL ) { if( xSchedulerRunning != pdFALSE ) { /* We have just suspended the current task. */ portYIELD_WITHIN_API(); } else { /* The scheduler is not running, but the task that was pointed to by pxCurrentTCB has just been suspended and pxCurrentTCB must be adjusted to point to a different task. */ if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) { /* No other tasks are ready, so set pxCurrentTCB back to NULL so when the next task is created pxCurrentTCB will be set to point to it no matter what its relative priority is. */ pxCurrentTCB = NULL; } else { vTaskSwitchContext(); } } } } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) signed portBASE_TYPE xTaskIsTaskSuspended( xTaskHandle xTask ) { portBASE_TYPE xReturn = pdFALSE; const tskTCB * const pxTCB = ( tskTCB * ) xTask; /* It does not make sense to check if the calling task is suspended. */ configASSERT( xTask ); /* Is the task we are attempting to resume actually in the suspended list? */ if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xGenericListItem ) ) != pdFALSE ) { /* Has the task already been resumed from within an ISR? */ if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) != pdTRUE ) { /* Is it in the suspended list because it is in the Suspended state? It is possible to be in the suspended list because it is blocked on a task with no timeout specified. */ if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) == pdTRUE ) { xReturn = pdTRUE; } } } return xReturn; } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) void vTaskResume( xTaskHandle pxTaskToResume ) { tskTCB *pxTCB; /* It does not make sense to resume the calling task. */ configASSERT( pxTaskToResume ); /* Remove the task from whichever list it is currently in, and place it in the ready list. */ pxTCB = ( tskTCB * ) pxTaskToResume; /* The parameter cannot be NULL as it is impossible to resume the currently executing task. */ if( ( pxTCB != NULL ) && ( pxTCB != pxCurrentTCB ) ) { taskENTER_CRITICAL(); { if( xTaskIsTaskSuspended( pxTCB ) == pdTRUE ) { traceTASK_RESUME( pxTCB ); /* As we are in a critical section we can access the ready lists even if the scheduler is suspended. */ vListRemove( &( pxTCB->xGenericListItem ) ); prvAddTaskToReadyQueue( pxTCB ); /* We may have just resumed a higher priority task. */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { /* This yield may not cause the task just resumed to run, but will leave the lists in the correct state for the next yield. */ portYIELD_WITHIN_API(); } } } taskEXIT_CRITICAL(); } } #endif /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) portBASE_TYPE xTaskResumeFromISR( xTaskHandle pxTaskToResume ) { portBASE_TYPE xYieldRequired = pdFALSE; tskTCB *pxTCB; configASSERT( pxTaskToResume ); pxTCB = ( tskTCB * ) pxTaskToResume; if( xTaskIsTaskSuspended( pxTCB ) == pdTRUE ) { traceTASK_RESUME_FROM_ISR( pxTCB ); if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE ) { xYieldRequired = ( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ); vListRemove( &( pxTCB->xGenericListItem ) ); prvAddTaskToReadyQueue( pxTCB ); } else { /* We cannot access the delayed or ready lists, so will hold this task pending until the scheduler is resumed, at which point a yield will be performed if necessary. */ vListInsertEnd( ( xList * ) &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); } } return xYieldRequired; } #endif /*----------------------------------------------------------- * PUBLIC SCHEDULER CONTROL documented in task.h *----------------------------------------------------------*/ void vTaskStartScheduler( void ) { portBASE_TYPE xReturn; /* Add the idle task at the lowest priority. */ xReturn = xTaskCreate( prvIdleTask, ( signed char * ) "IDLE", tskIDLE_STACK_SIZE, ( void * ) NULL, ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), ( xTaskHandle * ) NULL ); #if ( configUSE_TIMERS == 1 ) { if( xReturn == pdPASS ) { xReturn = xTimerCreateTimerTask(); } } #endif if( xReturn == pdPASS ) { /* Interrupts are turned off here, to ensure a tick does not occur before or during the call to xPortStartScheduler(). The stacks of the created tasks contain a status word with interrupts switched on so interrupts will automatically get re-enabled when the first task starts to run. STEPPING THROUGH HERE USING A DEBUGGER CAN CAUSE BIG PROBLEMS IF THE DEBUGGER ALLOWS INTERRUPTS TO BE PROCESSED. */ portDISABLE_INTERRUPTS(); xSchedulerRunning = pdTRUE; xTickCount = ( portTickType ) 0; /* If configGENERATE_RUN_TIME_STATS is defined then the following macro must be defined to configure the timer/counter used to generate the run time counter time base. */ portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); /* Setting up the timer tick is hardware specific and thus in the portable interface. */ if( xPortStartScheduler() ) { /* Should not reach here as if the scheduler is running the function will not return. */ } else { /* Should only reach here if a task calls xTaskEndScheduler(). */ } } /* This line will only be reached if the kernel could not be started. */ configASSERT( xReturn ); } /*-----------------------------------------------------------*/ void vTaskEndScheduler( void ) { /* Stop the scheduler interrupts and call the portable scheduler end routine so the original ISRs can be restored if necessary. The port layer must ensure interrupts enable bit is left in the correct state. */ portDISABLE_INTERRUPTS(); xSchedulerRunning = pdFALSE; vPortEndScheduler(); } /*----------------------------------------------------------*/ void vTaskSuspendAll( void ) { /* A critical section is not required as the variable is of type portBASE_TYPE. */ ++uxSchedulerSuspended; } /*----------------------------------------------------------*/ signed portBASE_TYPE xTaskResumeAll( void ) { register tskTCB *pxTCB; signed portBASE_TYPE xAlreadyYielded = pdFALSE; /* If uxSchedulerSuspended is zero then this function does not match a previous call to vTaskSuspendAll(). */ configASSERT( uxSchedulerSuspended ); /* It is possible that an ISR caused a task to be removed from an event list while the scheduler was suspended. If this was the case then the removed task will have been added to the xPendingReadyList. Once the scheduler has been resumed it is safe to move all the pending ready tasks from this list into their appropriate ready list. */ taskENTER_CRITICAL(); { --uxSchedulerSuspended; if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE ) { if( uxCurrentNumberOfTasks > ( unsigned portBASE_TYPE ) 0 ) { portBASE_TYPE xYieldRequired = pdFALSE; /* Move any readied tasks from the pending list into the appropriate ready list. */ while( listLIST_IS_EMPTY( ( xList * ) &xPendingReadyList ) == pdFALSE ) { pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( ( ( xList * ) &xPendingReadyList ) ); vListRemove( &( pxTCB->xEventListItem ) ); vListRemove( &( pxTCB->xGenericListItem ) ); prvAddTaskToReadyQueue( pxTCB ); /* If we have moved a task that has a priority higher than the current task then we should yield. */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { xYieldRequired = pdTRUE; } } /* If any ticks occurred while the scheduler was suspended then they should be processed now. This ensures the tick count does not slip, and that any delayed tasks are resumed at the correct time. */ if( uxMissedTicks > ( unsigned portBASE_TYPE ) 0 ) { while( uxMissedTicks > ( unsigned portBASE_TYPE ) 0 ) { vTaskIncrementTick(); --uxMissedTicks; } /* As we have processed some ticks it is appropriate to yield to ensure the highest priority task that is ready to run is the task actually running. */ #if configUSE_PREEMPTION == 1 { xYieldRequired = pdTRUE; } #endif } if( ( xYieldRequired == pdTRUE ) || ( xMissedYield == pdTRUE ) ) { xAlreadyYielded = pdTRUE; xMissedYield = pdFALSE; portYIELD_WITHIN_API(); } } } } taskEXIT_CRITICAL(); return xAlreadyYielded; } /*----------------------------------------------------------- * PUBLIC TASK UTILITIES documented in task.h *----------------------------------------------------------*/ portTickType xTaskGetTickCount( void ) { portTickType xTicks; /* Critical section required if running on a 16 bit processor. */ taskENTER_CRITICAL(); { xTicks = xTickCount; } taskEXIT_CRITICAL(); return xTicks; } /*-----------------------------------------------------------*/ portTickType xTaskGetTickCountFromISR( void ) { portTickType xReturn; unsigned portBASE_TYPE uxSavedInterruptStatus; uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); xReturn = xTickCount; portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ unsigned portBASE_TYPE uxTaskGetNumberOfTasks( void ) { /* A critical section is not required because the variables are of type portBASE_TYPE. */ return uxCurrentNumberOfTasks; } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) void vTaskList( signed char *pcWriteBuffer ) { unsigned portBASE_TYPE uxQueue; /* This is a VERY costly function that should be used for debug only. It leaves interrupts disabled for a LONG time. */ vTaskSuspendAll(); { /* Run through all the lists that could potentially contain a TCB and report the task name, state and stack high water mark. */ *pcWriteBuffer = ( signed char ) 0x00; strcat( ( char * ) pcWriteBuffer, ( const char * ) "\r\n" ); uxQueue = uxTopUsedPriority + ( unsigned portBASE_TYPE ) 1U; do { uxQueue--; if( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxQueue ] ) ) == pdFALSE ) { prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) &( pxReadyTasksLists[ uxQueue ] ), tskREADY_CHAR ); } }while( uxQueue > ( unsigned short ) tskIDLE_PRIORITY ); if( listLIST_IS_EMPTY( pxDelayedTaskList ) == pdFALSE ) { prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) pxDelayedTaskList, tskBLOCKED_CHAR ); } if( listLIST_IS_EMPTY( pxOverflowDelayedTaskList ) == pdFALSE ) { prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) pxOverflowDelayedTaskList, tskBLOCKED_CHAR ); } #if( INCLUDE_vTaskDelete == 1 ) { if( listLIST_IS_EMPTY( &xTasksWaitingTermination ) == pdFALSE ) { prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) &xTasksWaitingTermination, tskDELETED_CHAR ); } } #endif #if ( INCLUDE_vTaskSuspend == 1 ) { if( listLIST_IS_EMPTY( &xSuspendedTaskList ) == pdFALSE ) { prvListTaskWithinSingleList( pcWriteBuffer, ( xList * ) &xSuspendedTaskList, tskSUSPENDED_CHAR ); } } #endif } xTaskResumeAll(); } #endif /*----------------------------------------------------------*/ #if ( configGENERATE_RUN_TIME_STATS == 1 ) void vTaskGetRunTimeStats( signed char *pcWriteBuffer ) { unsigned portBASE_TYPE uxQueue; unsigned long ulTotalRunTime; /* This is a VERY costly function that should be used for debug only. It leaves interrupts disabled for a LONG time. */ vTaskSuspendAll(); { #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); #else ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); #endif /* Divide ulTotalRunTime by 100 to make the percentage caluclations simpler in the prvGenerateRunTimeStatsForTasksInList() function. */ ulTotalRunTime /= 100UL; /* Run through all the lists that could potentially contain a TCB, generating a table of run timer percentages in the provided buffer. */ *pcWriteBuffer = ( signed char ) 0x00; strcat( ( char * ) pcWriteBuffer, ( const char * ) "\r\n" ); uxQueue = uxTopUsedPriority + ( unsigned portBASE_TYPE ) 1U; do { uxQueue--; if( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxQueue ] ) ) == pdFALSE ) { prvGenerateRunTimeStatsForTasksInList( pcWriteBuffer, ( xList * ) &( pxReadyTasksLists[ uxQueue ] ), ulTotalRunTime ); } }while( uxQueue > ( unsigned short ) tskIDLE_PRIORITY ); if( listLIST_IS_EMPTY( pxDelayedTaskList ) == pdFALSE ) { prvGenerateRunTimeStatsForTasksInList( pcWriteBuffer, ( xList * ) pxDelayedTaskList, ulTotalRunTime ); } if( listLIST_IS_EMPTY( pxOverflowDelayedTaskList ) == pdFALSE ) { prvGenerateRunTimeStatsForTasksInList( pcWriteBuffer, ( xList * ) pxOverflowDelayedTaskList, ulTotalRunTime ); } #if ( INCLUDE_vTaskDelete == 1 ) { if( listLIST_IS_EMPTY( &xTasksWaitingTermination ) == pdFALSE ) { prvGenerateRunTimeStatsForTasksInList( pcWriteBuffer, ( xList * ) &xTasksWaitingTermination, ulTotalRunTime ); } } #endif #if ( INCLUDE_vTaskSuspend == 1 ) { if( listLIST_IS_EMPTY( &xSuspendedTaskList ) == pdFALSE ) { prvGenerateRunTimeStatsForTasksInList( pcWriteBuffer, ( xList * ) &xSuspendedTaskList, ulTotalRunTime ); } } #endif } xTaskResumeAll(); } #endif /*----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) void vTaskStartTrace( signed char * pcBuffer, unsigned long ulBufferSize ) { configASSERT( pcBuffer ); configASSERT( ulBufferSize ); taskENTER_CRITICAL(); { pcTraceBuffer = ( signed char * )pcBuffer; pcTraceBufferStart = pcBuffer; pcTraceBufferEnd = pcBuffer + ( ulBufferSize - tskSIZE_OF_EACH_TRACE_LINE ); xTracing = pdTRUE; } taskEXIT_CRITICAL(); } #endif /*----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) unsigned long ulTaskEndTrace( void ) { unsigned long ulBufferLength; taskENTER_CRITICAL(); xTracing = pdFALSE; taskEXIT_CRITICAL(); ulBufferLength = ( unsigned long ) ( pcTraceBuffer - pcTraceBufferStart ); return ulBufferLength; } #endif /*----------------------------------------------------------- * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES * documented in task.h *----------------------------------------------------------*/ void vTaskIncrementTick( void ) { tskTCB * pxTCB; /* Called by the portable layer each time a tick interrupt occurs. Increments the tick then checks to see if the new tick value will cause any tasks to be unblocked. */ if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE ) { ++xTickCount; if( xTickCount == ( portTickType ) 0 ) { xList *pxTemp; /* Tick count has overflowed so we need to swap the delay lists. If there are any items in pxDelayedTaskList here then there is an error! */ configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); pxTemp = pxDelayedTaskList; pxDelayedTaskList = pxOverflowDelayedTaskList; pxOverflowDelayedTaskList = pxTemp; xNumOfOverflows++; if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) { /* The new current delayed list is empty. Set xNextTaskUnblockTime to the maximum possible value so it is extremely unlikely that the if( xTickCount >= xNextTaskUnblockTime ) test will pass until there is an item in the delayed list. */ xNextTaskUnblockTime = portMAX_DELAY; } else { /* The new current delayed list is not empty, get the value of the item at the head of the delayed list. This is the time at which the task at the head of the delayed list should be removed from the Blocked state. */ pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( pxTCB->xGenericListItem ) ); } } /* See if this tick has made a timeout expire. */ prvCheckDelayedTasks(); } else { ++uxMissedTicks; /* The tick hook gets called at regular intervals, even if the scheduler is locked. */ #if ( configUSE_TICK_HOOK == 1 ) { vApplicationTickHook(); } #endif } #if ( configUSE_TICK_HOOK == 1 ) { /* Guard against the tick hook being called when the missed tick count is being unwound (when the scheduler is being unlocked. */ if( uxMissedTicks == ( unsigned portBASE_TYPE ) 0U ) { vApplicationTickHook(); } } #endif traceTASK_INCREMENT_TICK( xTickCount ); } /*-----------------------------------------------------------*/ #if ( ( INCLUDE_vTaskCleanUpResources == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) void vTaskCleanUpResources( void ) { unsigned short usQueue; volatile tskTCB *pxTCB; usQueue = ( unsigned short ) uxTopUsedPriority + ( unsigned short ) 1; /* Remove any TCB's from the ready queues. */ do { usQueue--; while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ usQueue ] ) ) == pdFALSE ) { listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &( pxReadyTasksLists[ usQueue ] ) ); vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) ); prvDeleteTCB( ( tskTCB * ) pxTCB ); } }while( usQueue > ( unsigned short ) tskIDLE_PRIORITY ); /* Remove any TCB's from the delayed queue. */ while( listLIST_IS_EMPTY( &xDelayedTaskList1 ) == pdFALSE ) { listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &xDelayedTaskList1 ); vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) ); prvDeleteTCB( ( tskTCB * ) pxTCB ); } /* Remove any TCB's from the overflow delayed queue. */ while( listLIST_IS_EMPTY( &xDelayedTaskList2 ) == pdFALSE ) { listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &xDelayedTaskList2 ); vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) ); prvDeleteTCB( ( tskTCB * ) pxTCB ); } while( listLIST_IS_EMPTY( &xSuspendedTaskList ) == pdFALSE ) { listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &xSuspendedTaskList ); vListRemove( ( xListItem * ) &( pxTCB->xGenericListItem ) ); prvDeleteTCB( ( tskTCB * ) pxTCB ); } } #endif /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) void vTaskSetApplicationTaskTag( xTaskHandle xTask, pdTASK_HOOK_CODE pxHookFunction ) { tskTCB *xTCB; /* If xTask is NULL then we are setting our own task hook. */ if( xTask == NULL ) { xTCB = ( tskTCB * ) pxCurrentTCB; } else { xTCB = ( tskTCB * ) xTask; } /* Save the hook function in the TCB. A critical section is required as the value can be accessed from an interrupt. */ taskENTER_CRITICAL(); xTCB->pxTaskTag = pxHookFunction; taskEXIT_CRITICAL(); } #endif /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) pdTASK_HOOK_CODE xTaskGetApplicationTaskTag( xTaskHandle xTask ) { tskTCB *xTCB; pdTASK_HOOK_CODE xReturn; /* If xTask is NULL then we are setting our own task hook. */ if( xTask == NULL ) { xTCB = ( tskTCB * ) pxCurrentTCB; } else { xTCB = ( tskTCB * ) xTask; } /* Save the hook function in the TCB. A critical section is required as the value can be accessed from an interrupt. */ taskENTER_CRITICAL(); xReturn = xTCB->pxTaskTag; taskEXIT_CRITICAL(); return xReturn; } #endif /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) portBASE_TYPE xTaskCallApplicationTaskHook( xTaskHandle xTask, void *pvParameter ) { tskTCB *xTCB; portBASE_TYPE xReturn; /* If xTask is NULL then we are calling our own task hook. */ if( xTask == NULL ) { xTCB = ( tskTCB * ) pxCurrentTCB; } else { xTCB = ( tskTCB * ) xTask; } if( xTCB->pxTaskTag != NULL ) { xReturn = xTCB->pxTaskTag( pvParameter ); } else { xReturn = pdFAIL; } return xReturn; } #endif /*-----------------------------------------------------------*/ void vTaskSwitchContext( void ) { if( uxSchedulerSuspended != ( unsigned portBASE_TYPE ) pdFALSE ) { /* The scheduler is currently suspended - do not allow a context switch. */ xMissedYield = pdTRUE; } else { traceTASK_SWITCHED_OUT(); #if ( configGENERATE_RUN_TIME_STATS == 1 ) { unsigned long ulTempCounter; #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE portALT_GET_RUN_TIME_COUNTER_VALUE( ulTempCounter ); #else ulTempCounter = portGET_RUN_TIME_COUNTER_VALUE(); #endif /* Add the amount of time the task has been running to the accumulated time so far. The time the task started running was stored in ulTaskSwitchedInTime. Note that there is no overflow protection here so count values are only valid until the timer overflows. Generally this will be about 1 hour assuming a 1uS timer increment. */ pxCurrentTCB->ulRunTimeCounter += ( ulTempCounter - ulTaskSwitchedInTime ); ulTaskSwitchedInTime = ulTempCounter; } #endif taskFIRST_CHECK_FOR_STACK_OVERFLOW(); taskSECOND_CHECK_FOR_STACK_OVERFLOW(); /* Find the highest priority queue that contains ready tasks. */ while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopReadyPriority ] ) ) ) { configASSERT( uxTopReadyPriority ); --uxTopReadyPriority; } /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the tasks of the same priority get an equal share of the processor time. */ listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopReadyPriority ] ) ); traceTASK_SWITCHED_IN(); vWriteTraceToBuffer(); } } /*-----------------------------------------------------------*/ void vTaskPlaceOnEventList( const xList * const pxEventList, portTickType xTicksToWait ) { portTickType xTimeToWake; configASSERT( pxEventList ); /* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED OR THE SCHEDULER SUSPENDED. */ /* Place the event list item of the TCB in the appropriate event list. This is placed in the list in priority order so the highest priority task is the first to be woken by the event. */ vListInsert( ( xList * ) pxEventList, ( xListItem * ) &( pxCurrentTCB->xEventListItem ) ); /* We must remove ourselves from the ready list before adding ourselves to the blocked list as the same list item is used for both lists. We have exclusive access to the ready lists as the scheduler is locked. */ vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); #if ( INCLUDE_vTaskSuspend == 1 ) { if( xTicksToWait == portMAX_DELAY ) { /* Add ourselves to the suspended task list instead of a delayed task list to ensure we are not woken by a timing event. We will block indefinitely. */ vListInsertEnd( ( xList * ) &xSuspendedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); } else { /* Calculate the time at which the task should be woken if the event does not occur. This may overflow but this doesn't matter. */ xTimeToWake = xTickCount + xTicksToWait; prvAddCurrentTaskToDelayedList( xTimeToWake ); } } #else { /* Calculate the time at which the task should be woken if the event does not occur. This may overflow but this doesn't matter. */ xTimeToWake = xTickCount + xTicksToWait; prvAddCurrentTaskToDelayedList( xTimeToWake ); } #endif } /*-----------------------------------------------------------*/ #if configUSE_TIMERS == 1 void vTaskPlaceOnEventListRestricted( const xList * const pxEventList, portTickType xTicksToWait ) { portTickType xTimeToWake; configASSERT( pxEventList ); /* This function should not be called by application code hence the 'Restricted' in its name. It is not part of the public API. It is designed for use by kernel code, and has special calling requirements - it should be called from a critical section. */ /* Place the event list item of the TCB in the appropriate event list. In this case it is assume that this is the only task that is going to be waiting on this event list, so the faster vListInsertEnd() function can be used in place of vListInsert. */ vListInsertEnd( ( xList * ) pxEventList, ( xListItem * ) &( pxCurrentTCB->xEventListItem ) ); /* We must remove this task from the ready list before adding it to the blocked list as the same list item is used for both lists. This function is called form a critical section. */ vListRemove( ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); /* Calculate the time at which the task should be woken if the event does not occur. This may overflow but this doesn't matter. */ xTimeToWake = xTickCount + xTicksToWait; prvAddCurrentTaskToDelayedList( xTimeToWake ); } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ signed portBASE_TYPE xTaskRemoveFromEventList( const xList * const pxEventList ) { tskTCB *pxUnblockedTCB; portBASE_TYPE xReturn; /* THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED OR THE SCHEDULER SUSPENDED. It can also be called from within an ISR. */ /* The event list is sorted in priority order, so we can remove the first in the list, remove the TCB from the delayed list, and add it to the ready list. If an event is for a queue that is locked then this function will never get called - the lock count on the queue will get modified instead. This means we can always expect exclusive access to the event list here. This function assumes that a check has already been made to ensure that pxEventList is not empty. */ pxUnblockedTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); configASSERT( pxUnblockedTCB ); vListRemove( &( pxUnblockedTCB->xEventListItem ) ); if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE ) { vListRemove( &( pxUnblockedTCB->xGenericListItem ) ); prvAddTaskToReadyQueue( pxUnblockedTCB ); } else { /* We cannot access the delayed or ready lists, so will hold this task pending until the scheduler is resumed. */ vListInsertEnd( ( xList * ) &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); } if( pxUnblockedTCB->uxPriority >= pxCurrentTCB->uxPriority ) { /* Return true if the task removed from the event list has a higher priority than the calling task. This allows the calling task to know if it should force a context switch now. */ xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } /*-----------------------------------------------------------*/ void vTaskSetTimeOutState( xTimeOutType * const pxTimeOut ) { configASSERT( pxTimeOut ); pxTimeOut->xOverflowCount = xNumOfOverflows; pxTimeOut->xTimeOnEntering = xTickCount; } /*-----------------------------------------------------------*/ portBASE_TYPE xTaskCheckForTimeOut( xTimeOutType * const pxTimeOut, portTickType * const pxTicksToWait ) { portBASE_TYPE xReturn; configASSERT( pxTimeOut ); configASSERT( pxTicksToWait ); taskENTER_CRITICAL(); { #if ( INCLUDE_vTaskSuspend == 1 ) /* If INCLUDE_vTaskSuspend is set to 1 and the block time specified is the maximum block time then the task should block indefinitely, and therefore never time out. */ if( *pxTicksToWait == portMAX_DELAY ) { xReturn = pdFALSE; } else /* We are not blocking indefinitely, perform the checks below. */ #endif if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( ( portTickType ) xTickCount >= ( portTickType ) pxTimeOut->xTimeOnEntering ) ) { /* The tick count is greater than the time at which vTaskSetTimeout() was called, but has also overflowed since vTaskSetTimeOut() was called. It must have wrapped all the way around and gone past us again. This passed since vTaskSetTimeout() was called. */ xReturn = pdTRUE; } else if( ( ( portTickType ) ( ( portTickType ) xTickCount - ( portTickType ) pxTimeOut->xTimeOnEntering ) ) < ( portTickType ) *pxTicksToWait ) { /* Not a genuine timeout. Adjust parameters for time remaining. */ *pxTicksToWait -= ( ( portTickType ) xTickCount - ( portTickType ) pxTimeOut->xTimeOnEntering ); vTaskSetTimeOutState( pxTimeOut ); xReturn = pdFALSE; } else { xReturn = pdTRUE; } } taskEXIT_CRITICAL(); return xReturn; } /*-----------------------------------------------------------*/ void vTaskMissedYield( void ) { xMissedYield = pdTRUE; } /* * ----------------------------------------------------------- * The Idle task. * ---------------------------------------------------------- * * The portTASK_FUNCTION() macro is used to allow port/compiler specific * language extensions. The equivalent prototype for this function is: * * void prvIdleTask( void *pvParameters ); * */ static portTASK_FUNCTION( prvIdleTask, pvParameters ) { /* Stop warnings. */ ( void ) pvParameters; for( ;; ) { /* See if any tasks have been deleted. */ prvCheckTasksWaitingTermination(); #if ( configUSE_PREEMPTION == 0 ) { /* If we are not using preemption we keep forcing a task switch to see if any other task has become available. If we are using preemption we don't need to do this as any task becoming available will automatically get the processor anyway. */ taskYIELD(); } #endif #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) { /* When using preemption tasks of equal priority will be timesliced. If a task that is sharing the idle priority is ready to run then the idle task should yield before the end of the timeslice. A critical region is not required here as we are just reading from the list, and an occasional incorrect value will not matter. If the ready list at the idle priority contains more than one task then a task other than the idle task is ready to execute. */ if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( unsigned portBASE_TYPE ) 1 ) { taskYIELD(); } } #endif #if ( configUSE_IDLE_HOOK == 1 ) { extern void vApplicationIdleHook( void ); /* Call the user defined function from within the idle task. This allows the application designer to add background functionality without the overhead of a separate task. NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. */ vApplicationIdleHook(); } #endif } } /*lint !e715 pvParameters is not accessed but all task functions require the same prototype. */ /*----------------------------------------------------------- * File private functions documented at the top of the file. *----------------------------------------------------------*/ static void prvInitialiseTCBVariables( tskTCB *pxTCB, const signed char * const pcName, unsigned portBASE_TYPE uxPriority, const xMemoryRegion * const xRegions, unsigned short usStackDepth ) { /* Store the function name in the TCB. */ #if configMAX_TASK_NAME_LEN > 1 { /* Don't bring strncpy into the build unnecessarily. */ strncpy( ( char * ) pxTCB->pcTaskName, ( const char * ) pcName, ( unsigned short ) configMAX_TASK_NAME_LEN ); } #endif pxTCB->pcTaskName[ ( unsigned short ) configMAX_TASK_NAME_LEN - ( unsigned short ) 1 ] = ( signed char ) '\0'; /* This is used as an array index so must ensure it's not too large. First remove the privilege bit if one is present. */ if( uxPriority >= configMAX_PRIORITIES ) { uxPriority = configMAX_PRIORITIES - ( unsigned portBASE_TYPE ) 1U; } pxTCB->uxPriority = uxPriority; #if ( configUSE_MUTEXES == 1 ) { pxTCB->uxBasePriority = uxPriority; } #endif vListInitialiseItem( &( pxTCB->xGenericListItem ) ); vListInitialiseItem( &( pxTCB->xEventListItem ) ); /* Set the pxTCB as a link back from the xListItem. This is so we can get back to the containing TCB from a generic item in a list. */ listSET_LIST_ITEM_OWNER( &( pxTCB->xGenericListItem ), pxTCB ); /* Event lists are always in priority order. */ listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) uxPriority ); listSET_LIST_ITEM_OWNER( &( pxTCB->xEventListItem ), pxTCB ); #if ( portCRITICAL_NESTING_IN_TCB == 1 ) { pxTCB->uxCriticalNesting = ( unsigned portBASE_TYPE ) 0; } #endif #if ( configUSE_APPLICATION_TASK_TAG == 1 ) { pxTCB->pxTaskTag = NULL; } #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) { pxTCB->ulRunTimeCounter = 0UL; } #endif #if ( portUSING_MPU_WRAPPERS == 1 ) { vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, pxTCB->pxStack, usStackDepth ); } #else { ( void ) xRegions; ( void ) usStackDepth; } #endif } /*-----------------------------------------------------------*/ #if ( portUSING_MPU_WRAPPERS == 1 ) void vTaskAllocateMPURegions( xTaskHandle xTaskToModify, const xMemoryRegion * const xRegions ) { tskTCB *pxTCB; if( xTaskToModify == pxCurrentTCB ) { xTaskToModify = NULL; } /* If null is passed in here then we are deleting ourselves. */ pxTCB = prvGetTCBFromHandle( xTaskToModify ); vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); } /*-----------------------------------------------------------*/ #endif static void prvInitialiseTaskLists( void ) { unsigned portBASE_TYPE uxPriority; for( uxPriority = ( unsigned portBASE_TYPE ) 0U; uxPriority < configMAX_PRIORITIES; uxPriority++ ) { vListInitialise( ( xList * ) &( pxReadyTasksLists[ uxPriority ] ) ); } vListInitialise( ( xList * ) &xDelayedTaskList1 ); vListInitialise( ( xList * ) &xDelayedTaskList2 ); vListInitialise( ( xList * ) &xPendingReadyList ); #if ( INCLUDE_vTaskDelete == 1 ) { vListInitialise( ( xList * ) &xTasksWaitingTermination ); } #endif #if ( INCLUDE_vTaskSuspend == 1 ) { vListInitialise( ( xList * ) &xSuspendedTaskList ); } #endif /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList using list2. */ pxDelayedTaskList = &xDelayedTaskList1; pxOverflowDelayedTaskList = &xDelayedTaskList2; } /*-----------------------------------------------------------*/ static void prvCheckTasksWaitingTermination( void ) { #if ( INCLUDE_vTaskDelete == 1 ) { portBASE_TYPE xListIsEmpty; /* ucTasksDeleted is used to prevent vTaskSuspendAll() being called too often in the idle task. */ if( uxTasksDeleted > ( unsigned portBASE_TYPE ) 0 ) { vTaskSuspendAll(); xListIsEmpty = listLIST_IS_EMPTY( &xTasksWaitingTermination ); xTaskResumeAll(); if( xListIsEmpty == pdFALSE ) { tskTCB *pxTCB; taskENTER_CRITICAL(); { pxTCB = ( tskTCB * ) listGET_OWNER_OF_HEAD_ENTRY( ( ( xList * ) &xTasksWaitingTermination ) ); vListRemove( &( pxTCB->xGenericListItem ) ); --uxCurrentNumberOfTasks; --uxTasksDeleted; } taskEXIT_CRITICAL(); prvDeleteTCB( pxTCB ); } } } #endif } /*-----------------------------------------------------------*/ static void prvAddCurrentTaskToDelayedList( portTickType xTimeToWake ) { /* The list item will be inserted in wake time order. */ listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xGenericListItem ), xTimeToWake ); if( xTimeToWake < xTickCount ) { /* Wake time has overflowed. Place this item in the overflow list. */ vListInsert( ( xList * ) pxOverflowDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); } else { /* The wake time has not overflowed, so we can use the current block list. */ vListInsert( ( xList * ) pxDelayedTaskList, ( xListItem * ) &( pxCurrentTCB->xGenericListItem ) ); /* If the task entering the blocked state was placed at the head of the list of blocked tasks then xNextTaskUnblockTime needs to be updated too. */ if( xTimeToWake < xNextTaskUnblockTime ) { xNextTaskUnblockTime = xTimeToWake; } } } /*-----------------------------------------------------------*/ static tskTCB *prvAllocateTCBAndStack( unsigned short usStackDepth, portSTACK_TYPE *puxStackBuffer ) { tskTCB *pxNewTCB; /* Allocate space for the TCB. Where the memory comes from depends on the implementation of the port malloc function. */ pxNewTCB = ( tskTCB * ) pvPortMalloc( sizeof( tskTCB ) ); if( pxNewTCB != NULL ) { /* Allocate space for the stack used by the task being created. The base of the stack memory stored in the TCB so the task can be deleted later if required. */ pxNewTCB->pxStack = ( portSTACK_TYPE * ) pvPortMallocAligned( ( ( ( size_t )usStackDepth ) * sizeof( portSTACK_TYPE ) ), puxStackBuffer ); if( pxNewTCB->pxStack == NULL ) { /* Could not allocate the stack. Delete the allocated TCB. */ vPortFree( pxNewTCB ); pxNewTCB = NULL; } else { /* Just to help debugging. */ memset( pxNewTCB->pxStack, tskSTACK_FILL_BYTE, usStackDepth * sizeof( portSTACK_TYPE ) ); } } return pxNewTCB; } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) static void prvListTaskWithinSingleList( const signed char *pcWriteBuffer, xList *pxList, signed char cStatus ) { volatile tskTCB *pxNextTCB, *pxFirstTCB; unsigned short usStackRemaining; /* Write the details of all the TCB's in pxList into the buffer. */ listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); do { listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); #if ( portSTACK_GROWTH > 0 ) { usStackRemaining = usTaskCheckFreeStackSpace( ( unsigned char * ) pxNextTCB->pxEndOfStack ); } #else { usStackRemaining = usTaskCheckFreeStackSpace( ( unsigned char * ) pxNextTCB->pxStack ); } #endif sprintf( pcStatusString, ( char * ) "%s\t\t%c\t%u\t%u\t%u\r\n", pxNextTCB->pcTaskName, cStatus, ( unsigned int ) pxNextTCB->uxPriority, usStackRemaining, ( unsigned int ) pxNextTCB->uxTCBNumber ); strcat( ( char * ) pcWriteBuffer, ( char * ) pcStatusString ); } while( pxNextTCB != pxFirstTCB ); } #endif /*-----------------------------------------------------------*/ #if ( configGENERATE_RUN_TIME_STATS == 1 ) static void prvGenerateRunTimeStatsForTasksInList( const signed char *pcWriteBuffer, xList *pxList, unsigned long ulTotalRunTime ) { volatile tskTCB *pxNextTCB, *pxFirstTCB; unsigned long ulStatsAsPercentage; /* Write the run time stats of all the TCB's in pxList into the buffer. */ listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); do { /* Get next TCB in from the list. */ listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /* Divide by zero check. */ if( ulTotalRunTime > 0UL ) { /* Has the task run at all? */ if( pxNextTCB->ulRunTimeCounter == 0 ) { /* The task has used no CPU time at all. */ sprintf( pcStatsString, ( char * ) "%s\t\t0\t\t0%%\r\n", pxNextTCB->pcTaskName ); } else { /* What percentage of the total run time has the task used? This will always be rounded down to the nearest integer. ulTotalRunTime has already been divided by 100. */ ulStatsAsPercentage = pxNextTCB->ulRunTimeCounter / ulTotalRunTime; if( ulStatsAsPercentage > 0UL ) { #ifdef portLU_PRINTF_SPECIFIER_REQUIRED { sprintf( pcStatsString, ( char * ) "%s\t\t%lu\t\t%lu%%\r\n", pxNextTCB->pcTaskName, pxNextTCB->ulRunTimeCounter, ulStatsAsPercentage ); } #else { /* sizeof( int ) == sizeof( long ) so a smaller printf() library can be used. */ sprintf( pcStatsString, ( char * ) "%s\t\t%u\t\t%u%%\r\n", pxNextTCB->pcTaskName, ( unsigned int ) pxNextTCB->ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); } #endif } else { /* If the percentage is zero here then the task has consumed less than 1% of the total run time. */ #ifdef portLU_PRINTF_SPECIFIER_REQUIRED { sprintf( pcStatsString, ( char * ) "%s\t\t%lu\t\t<1%%\r\n", pxNextTCB->pcTaskName, pxNextTCB->ulRunTimeCounter ); } #else { /* sizeof( int ) == sizeof( long ) so a smaller printf() library can be used. */ sprintf( pcStatsString, ( char * ) "%s\t\t%u\t\t<1%%\r\n", pxNextTCB->pcTaskName, ( unsigned int ) pxNextTCB->ulRunTimeCounter ); } #endif } } strcat( ( char * ) pcWriteBuffer, ( char * ) pcStatsString ); } } while( pxNextTCB != pxFirstTCB ); } #endif /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) static unsigned short usTaskCheckFreeStackSpace( const unsigned char * pucStackByte ) { register unsigned short usCount = 0; while( *pucStackByte == tskSTACK_FILL_BYTE ) { pucStackByte -= portSTACK_GROWTH; usCount++; } usCount /= sizeof( portSTACK_TYPE ); return usCount; } #endif /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) unsigned portBASE_TYPE uxTaskGetStackHighWaterMark( xTaskHandle xTask ) { tskTCB *pxTCB; unsigned char *pcEndOfStack; unsigned portBASE_TYPE uxReturn; pxTCB = prvGetTCBFromHandle( xTask ); #if portSTACK_GROWTH < 0 { pcEndOfStack = ( unsigned char * ) pxTCB->pxStack; } #else { pcEndOfStack = ( unsigned char * ) pxTCB->pxEndOfStack; } #endif uxReturn = ( unsigned portBASE_TYPE ) usTaskCheckFreeStackSpace( pcEndOfStack ); return uxReturn; } #endif /*-----------------------------------------------------------*/ #if ( ( INCLUDE_vTaskDelete == 1 ) || ( INCLUDE_vTaskCleanUpResources == 1 ) ) static void prvDeleteTCB( tskTCB *pxTCB ) { /* Free up the memory allocated by the scheduler for the task. It is up to the task to free any memory allocated at the application level. */ vPortFreeAligned( pxTCB->pxStack ); vPortFree( pxTCB ); } #endif /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) xTaskHandle xTaskGetCurrentTaskHandle( void ) { xTaskHandle xReturn; /* A critical section is not required as this is not called from an interrupt and the current TCB will always be the same for any individual execution thread. */ xReturn = pxCurrentTCB; return xReturn; } #endif /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) portBASE_TYPE xTaskGetSchedulerState( void ) { portBASE_TYPE xReturn; if( xSchedulerRunning == pdFALSE ) { xReturn = taskSCHEDULER_NOT_STARTED; } else { if( uxSchedulerSuspended == ( unsigned portBASE_TYPE ) pdFALSE ) { xReturn = taskSCHEDULER_RUNNING; } else { xReturn = taskSCHEDULER_SUSPENDED; } } return xReturn; } #endif /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) void vTaskPriorityInherit( xTaskHandle * const pxMutexHolder ) { tskTCB * const pxTCB = ( tskTCB * ) pxMutexHolder; configASSERT( pxMutexHolder ); if( pxTCB->uxPriority < pxCurrentTCB->uxPriority ) { /* Adjust the mutex holder state to account for its new priority. */ listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) pxCurrentTCB->uxPriority ); /* If the task being modified is in the ready state it will need to be moved in to a new list. */ if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxTCB->uxPriority ] ), &( pxTCB->xGenericListItem ) ) ) { vListRemove( &( pxTCB->xGenericListItem ) ); /* Inherit the priority before being moved into the new list. */ pxTCB->uxPriority = pxCurrentTCB->uxPriority; prvAddTaskToReadyQueue( pxTCB ); } else { /* Just inherit the priority. */ pxTCB->uxPriority = pxCurrentTCB->uxPriority; } } } #endif /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) void vTaskPriorityDisinherit( xTaskHandle * const pxMutexHolder ) { tskTCB * const pxTCB = ( tskTCB * ) pxMutexHolder; if( pxMutexHolder != NULL ) { if( pxTCB->uxPriority != pxTCB->uxBasePriority ) { /* We must be the running task to be able to give the mutex back. Remove ourselves from the ready list we currently appear in. */ vListRemove( &( pxTCB->xGenericListItem ) ); /* Disinherit the priority before adding ourselves into the new ready list. */ pxTCB->uxPriority = pxTCB->uxBasePriority; listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) pxTCB->uxPriority ); prvAddTaskToReadyQueue( pxTCB ); } } } #endif /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) void vTaskEnterCritical( void ) { portDISABLE_INTERRUPTS(); if( xSchedulerRunning != pdFALSE ) { ( pxCurrentTCB->uxCriticalNesting )++; } } #endif /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) void vTaskExitCritical( void ) { if( xSchedulerRunning != pdFALSE ) { if( pxCurrentTCB->uxCriticalNesting > 0 ) { ( pxCurrentTCB->uxCriticalNesting )--; if( pxCurrentTCB->uxCriticalNesting == 0 ) { portENABLE_INTERRUPTS(); } } } } #endif /*-----------------------------------------------------------*/
722,291
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/croutine.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. FreeRTOS supports many tools and architectures. V7.0.0 is sponsored by: Atollic AB - Atollic provides professional embedded systems development tools for C/C++ development, code analysis and test automation. See http://www.atollic.com *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ #include "FreeRTOS.h" #include "task.h" #include "croutine.h" /* * Some kernel aware debuggers require data to be viewed to be global, rather * than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER #define static #endif /* Lists for ready and blocked co-routines. --------------------*/ static xList pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ static xList xDelayedCoRoutineList1; /*< Delayed co-routines. */ static xList xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ static xList * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */ static xList * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ static xList xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ /* Other file private variables. --------------------------------*/ corCRCB * pxCurrentCoRoutine = NULL; static unsigned portBASE_TYPE uxTopCoRoutineReadyPriority = 0; static portTickType xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; /* The initial state of the co-routine when it is created. */ #define corINITIAL_STATE ( 0 ) /* * Place the co-routine represented by pxCRCB into the appropriate ready queue * for the priority. It is inserted at the end of the list. * * This macro accesses the co-routine ready lists and therefore must not be * used from within an ISR. */ #define prvAddCoRoutineToReadyQueue( pxCRCB ) \ { \ if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ { \ uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ } \ vListInsertEnd( ( xList * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ } /* * Utility to ready all the lists used by the scheduler. This is called * automatically upon the creation of the first co-routine. */ static void prvInitialiseCoRoutineLists( void ); /* * Co-routines that are readied by an interrupt cannot be placed directly into * the ready lists (there is no mutual exclusion). Instead they are placed in * in the pending ready list in order that they can later be moved to the ready * list by the co-routine scheduler. */ static void prvCheckPendingReadyList( void ); /* * Macro that looks at the list of co-routines that are currently delayed to * see if any require waking. * * Co-routines are stored in the queue in the order of their wake time - * meaning once one co-routine has been found whose timer has not expired * we need not look any further down the list. */ static void prvCheckDelayedList( void ); /*-----------------------------------------------------------*/ signed portBASE_TYPE xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, unsigned portBASE_TYPE uxPriority, unsigned portBASE_TYPE uxIndex ) { signed portBASE_TYPE xReturn; corCRCB *pxCoRoutine; /* Allocate the memory that will store the co-routine control block. */ pxCoRoutine = ( corCRCB * ) pvPortMalloc( sizeof( corCRCB ) ); if( pxCoRoutine ) { /* If pxCurrentCoRoutine is NULL then this is the first co-routine to be created and the co-routine data structures need initialising. */ if( pxCurrentCoRoutine == NULL ) { pxCurrentCoRoutine = pxCoRoutine; prvInitialiseCoRoutineLists(); } /* Check the priority is within limits. */ if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) { uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; } /* Fill out the co-routine control block from the function parameters. */ pxCoRoutine->uxState = corINITIAL_STATE; pxCoRoutine->uxPriority = uxPriority; pxCoRoutine->uxIndex = uxIndex; pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; /* Initialise all the other co-routine control block parameters. */ vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); /* Set the co-routine control block as a link back from the xListItem. This is so we can get back to the containing CRCB from a generic item in a list. */ listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); /* Event lists are always in priority order. */ listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), configMAX_PRIORITIES - ( portTickType ) uxPriority ); /* Now the co-routine has been initialised it can be added to the ready list at the correct priority. */ prvAddCoRoutineToReadyQueue( pxCoRoutine ); xReturn = pdPASS; } else { xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; } return xReturn; } /*-----------------------------------------------------------*/ void vCoRoutineAddToDelayedList( portTickType xTicksToDelay, xList *pxEventList ) { portTickType xTimeToWake; /* Calculate the time to wake - this may overflow but this is not a problem. */ xTimeToWake = xCoRoutineTickCount + xTicksToDelay; /* We must remove ourselves from the ready list before adding ourselves to the blocked list as the same list item is used for both lists. */ vListRemove( ( xListItem * ) &( pxCurrentCoRoutine->xGenericListItem ) ); /* The list item will be inserted in wake time order. */ listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); if( xTimeToWake < xCoRoutineTickCount ) { /* Wake time has overflowed. Place this item in the overflow list. */ vListInsert( ( xList * ) pxOverflowDelayedCoRoutineList, ( xListItem * ) &( pxCurrentCoRoutine->xGenericListItem ) ); } else { /* The wake time has not overflowed, so we can use the current block list. */ vListInsert( ( xList * ) pxDelayedCoRoutineList, ( xListItem * ) &( pxCurrentCoRoutine->xGenericListItem ) ); } if( pxEventList ) { /* Also add the co-routine to an event list. If this is done then the function must be called with interrupts disabled. */ vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); } } /*-----------------------------------------------------------*/ static void prvCheckPendingReadyList( void ) { /* Are there any co-routines waiting to get moved to the ready list? These are co-routines that have been readied by an ISR. The ISR cannot access the ready lists itself. */ while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) { corCRCB *pxUnblockedCRCB; /* The pending ready list can be accessed by an ISR. */ portDISABLE_INTERRUPTS(); { pxUnblockedCRCB = ( corCRCB * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) ); vListRemove( &( pxUnblockedCRCB->xEventListItem ) ); } portENABLE_INTERRUPTS(); vListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); } } /*-----------------------------------------------------------*/ static void prvCheckDelayedList( void ) { corCRCB *pxCRCB; xPassedTicks = xTaskGetTickCount() - xLastTickCount; while( xPassedTicks ) { xCoRoutineTickCount++; xPassedTicks--; /* If the tick count has overflowed we need to swap the ready lists. */ if( xCoRoutineTickCount == 0 ) { xList * pxTemp; /* Tick count has overflowed so we need to swap the delay lists. If there are any items in pxDelayedCoRoutineList here then there is an error! */ pxTemp = pxDelayedCoRoutineList; pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; pxOverflowDelayedCoRoutineList = pxTemp; } /* See if this tick has made a timeout expire. */ while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) { pxCRCB = ( corCRCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) { /* Timeout not yet expired. */ break; } portDISABLE_INTERRUPTS(); { /* The event could have occurred just before this critical section. If this is the case then the generic list item will have been moved to the pending ready list and the following line is still valid. Also the pvContainer parameter will have been set to NULL so the following lines are also valid. */ vListRemove( &( pxCRCB->xGenericListItem ) ); /* Is the co-routine waiting on an event also? */ if( pxCRCB->xEventListItem.pvContainer ) { vListRemove( &( pxCRCB->xEventListItem ) ); } } portENABLE_INTERRUPTS(); prvAddCoRoutineToReadyQueue( pxCRCB ); } } xLastTickCount = xCoRoutineTickCount; } /*-----------------------------------------------------------*/ void vCoRoutineSchedule( void ) { /* See if any co-routines readied by events need moving to the ready lists. */ prvCheckPendingReadyList(); /* See if any delayed co-routines have timed out. */ prvCheckDelayedList(); /* Find the highest priority queue that contains ready co-routines. */ while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) { if( uxTopCoRoutineReadyPriority == 0 ) { /* No more co-routines to check. */ return; } --uxTopCoRoutineReadyPriority; } /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines of the same priority get an equal share of the processor time. */ listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); /* Call the co-routine. */ ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); return; } /*-----------------------------------------------------------*/ static void prvInitialiseCoRoutineLists( void ) { unsigned portBASE_TYPE uxPriority; for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) { vListInitialise( ( xList * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); } vListInitialise( ( xList * ) &xDelayedCoRoutineList1 ); vListInitialise( ( xList * ) &xDelayedCoRoutineList2 ); vListInitialise( ( xList * ) &xPendingReadyCoRoutineList ); /* Start with pxDelayedCoRoutineList using list1 and the pxOverflowDelayedCoRoutineList using list2. */ pxDelayedCoRoutineList = &xDelayedCoRoutineList1; pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; } /*-----------------------------------------------------------*/ signed portBASE_TYPE xCoRoutineRemoveFromEventList( const xList *pxEventList ) { corCRCB *pxUnblockedCRCB; signed portBASE_TYPE xReturn; /* This function is called from within an interrupt. It can only access event lists and the pending ready list. This function assumes that a check has already been made to ensure pxEventList is not empty. */ pxUnblockedCRCB = ( corCRCB * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); vListRemove( &( pxUnblockedCRCB->xEventListItem ) ); vListInsertEnd( ( xList * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; }
722,292
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/port.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ /*----------------------------------------------------------- * Implementation of functions defined in portable.h for the ARM CM3 port. *----------------------------------------------------------*/ /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY is defined. The value should also ensure backward compatibility. FreeRTOS.org versions prior to V4.4.0 did not include this definition. */ #ifndef configKERNEL_INTERRUPT_PRIORITY #define configKERNEL_INTERRUPT_PRIORITY 255 #endif /* Constants required to manipulate the NVIC. */ #define portNVIC_SYSTICK_CTRL ( ( volatile unsigned long *) 0xe000e010 ) #define portNVIC_SYSTICK_LOAD ( ( volatile unsigned long *) 0xe000e014 ) #define portNVIC_INT_CTRL ( ( volatile unsigned long *) 0xe000ed04 ) #define portNVIC_SYSPRI2 ( ( volatile unsigned long *) 0xe000ed20 ) #define portNVIC_SYSTICK_CLK 0x00000004 #define portNVIC_SYSTICK_INT 0x00000002 #define portNVIC_SYSTICK_ENABLE 0x00000001 #define portNVIC_PENDSVSET 0x10000000 #define portNVIC_PENDSV_PRI ( ( ( unsigned long ) configKERNEL_INTERRUPT_PRIORITY ) << 16 ) #define portNVIC_SYSTICK_PRI ( ( ( unsigned long ) configKERNEL_INTERRUPT_PRIORITY ) << 24 ) /* Constants required to set up the initial stack. */ #define portINITIAL_XPSR ( 0x01000000 ) /* The priority used by the kernel is assigned to a variable to make access from inline assembler easier. */ const unsigned long ulKernelPriority = configKERNEL_INTERRUPT_PRIORITY; /* Each task maintains its own interrupt status in the critical nesting variable. */ static unsigned portBASE_TYPE uxCriticalNesting = 0xaaaaaaaa; /* * Setup the timer to generate the tick interrupts. */ static void prvSetupTimerInterrupt( void ); /* * Exception handlers. */ void xPortPendSVHandler( void ) __attribute__ (( naked )); void xPortSysTickHandler( void ); void vPortSVCHandler( void ) __attribute__ (( naked )); /* * Start first task is a separate function so it can be tested in isolation. */ void vPortStartFirstTask( void ) __attribute__ (( naked )); /*-----------------------------------------------------------*/ /* * See header file for description. */ portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters ) { /* Simulate the stack frame as it would be created by a context switch interrupt. */ pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */ *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ pxTopOfStack--; *pxTopOfStack = ( portSTACK_TYPE ) pxCode; /* PC */ pxTopOfStack--; *pxTopOfStack = 0; /* LR */ pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ *pxTopOfStack = ( portSTACK_TYPE ) pvParameters; /* R0 */ pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */ return pxTopOfStack; } /*-----------------------------------------------------------*/ // !!! Maple // void vPortSVCHandler( void ) void __exc_svc( void ) // !!! Maple { __asm volatile ( " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */ " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */ " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ " ldmia r0!, {r4-r11} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */ " msr psp, r0 \n" /* Restore the task stack pointer. */ " mov r0, #0 \n" " msr basepri, r0 \n" " orr r14, #0xd \n" " bx r14 \n" " \n" " .align 2 \n" "pxCurrentTCBConst2: .word pxCurrentTCB \n" ); } /*-----------------------------------------------------------*/ void vPortStartFirstTask( void ) { __asm volatile( " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */ " ldr r0, [r0] \n" " ldr r0, [r0] \n" " msr msp, r0 \n" /* Set the msp back to the start of the stack. */ " cpsie i \n" /* Globally enable interrupts. */ " svc 0 \n" /* System call to start first task. */ " nop \n" ); } /*-----------------------------------------------------------*/ /* * See header file for description. */ portBASE_TYPE xPortStartScheduler( void ) { /* Make PendSV, CallSV and SysTick the same priroity as the kernel. */ *(portNVIC_SYSPRI2) |= portNVIC_PENDSV_PRI; *(portNVIC_SYSPRI2) |= portNVIC_SYSTICK_PRI; // !!! Maple systick_attach_callback(&xPortSysTickHandler); // /* Start the timer that generates the tick ISR. Interrupts are disabled // here already. */ // prvSetupTimerInterrupt(); // !!! Maple /* Initialise the critical nesting count ready for the first task. */ uxCriticalNesting = 0; /* Start the first task. */ vPortStartFirstTask(); /* Should not get here! */ return 0; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { /* It is unlikely that the CM3 port will require this function as there is nothing to return to. */ } /*-----------------------------------------------------------*/ void vPortYieldFromISR( void ) { /* Set a PendSV to request a context switch. */ *(portNVIC_INT_CTRL) = portNVIC_PENDSVSET; } /*-----------------------------------------------------------*/ void vPortEnterCritical( void ) { portDISABLE_INTERRUPTS(); uxCriticalNesting++; } /*-----------------------------------------------------------*/ void vPortExitCritical( void ) { uxCriticalNesting--; if( uxCriticalNesting == 0 ) { portENABLE_INTERRUPTS(); } } /*-----------------------------------------------------------*/ // !!! Maple // void xPortPendSVHandler( void ) void __exc_pendsv( void ) // !!! Maple { /* This is a naked function. */ __asm volatile ( " mrs r0, psp \n" " \n" " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */ " ldr r2, [r3] \n" " \n" " stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */ " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */ " \n" " stmdb sp!, {r3, r14} \n" " mov r0, %0 \n" " msr basepri, r0 \n" " bl vTaskSwitchContext \n" " mov r0, #0 \n" " msr basepri, r0 \n" " ldmia sp!, {r3, r14} \n" " \n" /* Restore the context, including the critical nesting count. */ " ldr r1, [r3] \n" " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ " ldmia r0!, {r4-r11} \n" /* Pop the registers. */ " msr psp, r0 \n" " bx r14 \n" " \n" " .align 2 \n" "pxCurrentTCBConst: .word pxCurrentTCB \n" ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY) ); } /*-----------------------------------------------------------*/ void xPortSysTickHandler( void ) { unsigned long ulDummy; /* If using preemption, also force a context switch. */ #if configUSE_PREEMPTION == 1 *(portNVIC_INT_CTRL) = portNVIC_PENDSVSET; #endif ulDummy = portSET_INTERRUPT_MASK_FROM_ISR(); { vTaskIncrementTick(); } portCLEAR_INTERRUPT_MASK_FROM_ISR( ulDummy ); } /*-----------------------------------------------------------*/ /* * Setup the systick timer to generate the tick interrupts at the required * frequency. */ void prvSetupTimerInterrupt( void ) { /* Configure SysTick to interrupt at the requested rate. */ *(portNVIC_SYSTICK_LOAD) = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; *(portNVIC_SYSTICK_CTRL) = portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE; } /*-----------------------------------------------------------*/
722,293
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/timers.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. FreeRTOS supports many tools and architectures. V7.0.0 is sponsored by: Atollic AB - Atollic provides professional embedded systems development tools for C/C++ development, code analysis and test automation. See http://www.atollic.com *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /* This entire source file will be skipped if the application is not configured to include software timer functionality. This #if is closed at the very bottom of this file. If you want to include software timer functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ #if ( configUSE_TIMERS == 1 ) /* Misc definitions. */ #define tmrNO_DELAY ( portTickType ) 0U /* The definition of the timers themselves. */ typedef struct tmrTimerControl { const signed char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ xListItem xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ portTickType xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ unsigned portBASE_TYPE uxAutoReload; /*<< Set to pdTRUE if the timer should be automatically restarted once expired. Set to pdFALSE if the timer is, in effect, a one shot timer. */ void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ tmrTIMER_CALLBACK pxCallbackFunction; /*<< The function that will be called when the timer expires. */ } xTIMER; /* The definition of messages that can be sent and received on the timer queue. */ typedef struct tmrTimerQueueMessage { portBASE_TYPE xMessageID; /*<< The command being sent to the timer service task. */ portTickType xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ xTIMER * pxTimer; /*<< The timer to which the command will be applied. */ } xTIMER_MESSAGE; /* The list in which active timers are stored. Timers are referenced in expire time order, with the nearest expiry time at the front of the list. Only the timer service task is allowed to access xActiveTimerList. */ PRIVILEGED_DATA static xList xActiveTimerList1; PRIVILEGED_DATA static xList xActiveTimerList2; PRIVILEGED_DATA static xList *pxCurrentTimerList; PRIVILEGED_DATA static xList *pxOverflowTimerList; /* A queue that is used to send commands to the timer service task. */ PRIVILEGED_DATA static xQueueHandle xTimerQueue = NULL; /*-----------------------------------------------------------*/ /* * Initialise the infrastructure used by the timer service task if it has not * been initialised already. */ static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION; /* * The timer service task (daemon). Timer functionality is controlled by this * task. Other tasks communicate with the timer service task using the * xTimerQueue queue. */ static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION; /* * Called by the timer service task to interpret and process a command it * received on the timer queue. */ static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION; /* * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, * depending on if the expire time causes a timer counter overflow. */ static portBASE_TYPE prvInsertTimerInActiveList( xTIMER *pxTimer, portTickType xNextExpiryTime, portTickType xTimeNow, portTickType xCommandTime ) PRIVILEGED_FUNCTION; /* * An active timer has reached its expire time. Reload the timer if it is an * auto reload timer, then call its callback. */ static void prvProcessExpiredTimer( portTickType xNextExpireTime, portTickType xTimeNow ) PRIVILEGED_FUNCTION; /* * The tick count has overflowed. Switch the timer lists after ensuring the * current timer list does not still reference some timers. */ static void prvSwitchTimerLists( portTickType xLastTime ) PRIVILEGED_FUNCTION; /* * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE * if a tick count overflow occurred since prvSampleTimeNow() was last called. */ static portTickType prvSampleTimeNow( portBASE_TYPE *pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION; /* * If the timer list contains any active timers then return the expire time of * the timer that will expire first and set *pxListWasEmpty to false. If the * timer list does not contain any timers then return 0 and set *pxListWasEmpty * to pdTRUE. */ static portTickType prvGetNextExpireTime( portBASE_TYPE *pxListWasEmpty ) PRIVILEGED_FUNCTION; /* * If a timer has expired, process it. Otherwise, block the timer service task * until either a timer does expire or a command is received. */ static void prvProcessTimerOrBlockTask( portTickType xNextExpireTime, portBASE_TYPE xListWasEmpty ) PRIVILEGED_FUNCTION; /*-----------------------------------------------------------*/ portBASE_TYPE xTimerCreateTimerTask( void ) { portBASE_TYPE xReturn = pdFAIL; /* This function is called when the scheduler is started if configUSE_TIMERS is set to 1. Check that the infrastructure used by the timer service task has been created/initialised. If timers have already been created then the initialisation will already have been performed. */ prvCheckForValidListAndQueue(); if( xTimerQueue != NULL ) { xReturn = xTaskCreate( prvTimerTask, ( const signed char * ) "Tmr Svc", ( unsigned short ) configTIMER_TASK_STACK_DEPTH, NULL, ( unsigned portBASE_TYPE ) configTIMER_TASK_PRIORITY, NULL); } configASSERT( xReturn ); return xReturn; } /*-----------------------------------------------------------*/ xTimerHandle xTimerCreate( const signed char *pcTimerName, portTickType xTimerPeriodInTicks, unsigned portBASE_TYPE uxAutoReload, void *pvTimerID, tmrTIMER_CALLBACK pxCallbackFunction ) { xTIMER *pxNewTimer; /* Allocate the timer structure. */ if( xTimerPeriodInTicks == ( portTickType ) 0U ) { pxNewTimer = NULL; configASSERT( ( xTimerPeriodInTicks > 0 ) ); } else { pxNewTimer = ( xTIMER * ) pvPortMalloc( sizeof( xTIMER ) ); if( pxNewTimer != NULL ) { /* Ensure the infrastructure used by the timer service task has been created/initialised. */ prvCheckForValidListAndQueue(); /* Initialise the timer structure members using the function parameters. */ pxNewTimer->pcTimerName = pcTimerName; pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; pxNewTimer->uxAutoReload = uxAutoReload; pxNewTimer->pvTimerID = pvTimerID; pxNewTimer->pxCallbackFunction = pxCallbackFunction; vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); traceTIMER_CREATE( pxNewTimer ); } else { traceTIMER_CREATE_FAILED(); } } return ( xTimerHandle ) pxNewTimer; } /*-----------------------------------------------------------*/ portBASE_TYPE xTimerGenericCommand( xTimerHandle xTimer, portBASE_TYPE xCommandID, portTickType xOptionalValue, portBASE_TYPE *pxHigherPriorityTaskWoken, portTickType xBlockTime ) { portBASE_TYPE xReturn = pdFAIL; xTIMER_MESSAGE xMessage; /* Send a message to the timer service task to perform a particular action on a particular timer definition. */ if( xTimerQueue != NULL ) { /* Send a command to the timer service task to start the xTimer timer. */ xMessage.xMessageID = xCommandID; xMessage.xMessageValue = xOptionalValue; xMessage.pxTimer = ( xTIMER * ) xTimer; if( pxHigherPriorityTaskWoken == NULL ) { if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) { xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xBlockTime ); } else { xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); } } else { xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); } traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); } return xReturn; } /*-----------------------------------------------------------*/ static void prvProcessExpiredTimer( portTickType xNextExpireTime, portTickType xTimeNow ) { xTIMER *pxTimer; portBASE_TYPE xResult; /* Remove the timer from the list of active timers. A check has already been performed to ensure the list is not empty. */ pxTimer = ( xTIMER * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); vListRemove( &( pxTimer->xTimerListItem ) ); traceTIMER_EXPIRED( pxTimer ); /* If the timer is an auto reload timer then calculate the next expiry time and re-insert the timer in the list of active timers. */ if( pxTimer->uxAutoReload == ( unsigned portBASE_TYPE ) pdTRUE ) { /* This is the only time a timer is inserted into a list using a time relative to anything other than the current time. It will therefore be inserted into the correct list relative to the time this task thinks it is now, even if a command to switch lists due to a tick count overflow is already waiting in the timer queue. */ if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) == pdTRUE ) { /* The timer expired before it was added to the active timer list. Reload it now. */ xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START, xNextExpireTime, NULL, tmrNO_DELAY ); configASSERT( xResult ); ( void ) xResult; } } /* Call the timer callback. */ pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer ); } /*-----------------------------------------------------------*/ static void prvTimerTask( void *pvParameters ) { portTickType xNextExpireTime; portBASE_TYPE xListWasEmpty; /* Just to avoid compiler warnings. */ ( void ) pvParameters; for( ;; ) { /* Query the timers list to see if it contains any timers, and if so, obtain the time at which the next timer will expire. */ xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); /* If a timer has expired, process it. Otherwise, block this task until either a timer does expire, or a command is received. */ prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); /* Empty the command queue. */ prvProcessReceivedCommands(); } } /*-----------------------------------------------------------*/ static void prvProcessTimerOrBlockTask( portTickType xNextExpireTime, portBASE_TYPE xListWasEmpty ) { portTickType xTimeNow; portBASE_TYPE xTimerListsWereSwitched; vTaskSuspendAll(); { /* Obtain the time now to make an assessment as to whether the timer has expired or not. If obtaining the time causes the lists to switch then don't process this timer as any timers that remained in the list when the lists were switched will have been processed within the prvSampelTimeNow() function. */ xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); if( xTimerListsWereSwitched == pdFALSE ) { /* The tick count has not overflowed, has the timer expired? */ if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) { xTaskResumeAll(); prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); } else { /* The tick count has not overflowed, and the next expire time has not been reached yet. This task should therefore block to wait for the next expire time or a command to be received - whichever comes first. The following line cannot be reached unless xNextExpireTime > xTimeNow, except in the case when the current timer list is empty. */ vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ) ); if( xTaskResumeAll() == pdFALSE ) { /* Yield to wait for either a command to arrive, or the block time to expire. If a command arrived between the critical section being exited and this yield then the yield will not cause the task to block. */ portYIELD_WITHIN_API(); } } } else { xTaskResumeAll(); } } } /*-----------------------------------------------------------*/ static portTickType prvGetNextExpireTime( portBASE_TYPE *pxListWasEmpty ) { portTickType xNextExpireTime; /* Timers are listed in expiry time order, with the head of the list referencing the task that will expire first. Obtain the time at which the timer with the nearest expiry time will expire. If there are no active timers then just set the next expire time to 0. That will cause this task to unblock when the tick count overflows, at which point the timer lists will be switched and the next expiry time can be re-assessed. */ *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); if( *pxListWasEmpty == pdFALSE ) { xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); } else { /* Ensure the task unblocks when the tick count rolls over. */ xNextExpireTime = ( portTickType ) 0U; } return xNextExpireTime; } /*-----------------------------------------------------------*/ static portTickType prvSampleTimeNow( portBASE_TYPE *pxTimerListsWereSwitched ) { portTickType xTimeNow; static portTickType xLastTime = ( portTickType ) 0U; xTimeNow = xTaskGetTickCount(); if( xTimeNow < xLastTime ) { prvSwitchTimerLists( xLastTime ); *pxTimerListsWereSwitched = pdTRUE; } else { *pxTimerListsWereSwitched = pdFALSE; } xLastTime = xTimeNow; return xTimeNow; } /*-----------------------------------------------------------*/ static portBASE_TYPE prvInsertTimerInActiveList( xTIMER *pxTimer, portTickType xNextExpiryTime, portTickType xTimeNow, portTickType xCommandTime ) { portBASE_TYPE xProcessTimerNow = pdFALSE; listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); if( xNextExpiryTime <= xTimeNow ) { /* Has the expiry time elapsed between the command to start/reset a timer was issued, and the time the command was processed? */ if( ( ( portTickType ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) { /* The time between a command being issued and the command being processed actually exceeds the timers period. */ xProcessTimerNow = pdTRUE; } else { vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); } } else { if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) { /* If, since the command was issued, the tick count has overflowed but the expiry time has not, then the timer must have already passed its expiry time and should be processed immediately. */ xProcessTimerNow = pdTRUE; } else { vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); } } return xProcessTimerNow; } /*-----------------------------------------------------------*/ static void prvProcessReceivedCommands( void ) { xTIMER_MESSAGE xMessage; xTIMER *pxTimer; portBASE_TYPE xTimerListsWereSwitched, xResult; portTickType xTimeNow; /* In this case the xTimerListsWereSwitched parameter is not used, but it must be present in the function call. */ xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) { pxTimer = xMessage.pxTimer; /* Is the timer already in a list of active timers? When the command is trmCOMMAND_PROCESS_TIMER_OVERFLOW, the timer will be NULL as the command is to the task rather than to an individual timer. */ if( pxTimer != NULL ) { if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) { /* The timer is in a list, remove it. */ vListRemove( &( pxTimer->xTimerListItem ) ); } } traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.xMessageValue ); switch( xMessage.xMessageID ) { case tmrCOMMAND_START : /* Start or restart a timer. */ if( prvInsertTimerInActiveList( pxTimer, xMessage.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.xMessageValue ) == pdTRUE ) { /* The timer expired before it was added to the active timer list. Process it now. */ pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer ); if( pxTimer->uxAutoReload == ( unsigned portBASE_TYPE ) pdTRUE ) { xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START, xMessage.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); configASSERT( xResult ); ( void ) xResult; } } break; case tmrCOMMAND_STOP : /* The timer has already been removed from the active list. There is nothing to do here. */ break; case tmrCOMMAND_CHANGE_PERIOD : pxTimer->xTimerPeriodInTicks = xMessage.xMessageValue; configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); break; case tmrCOMMAND_DELETE : /* The timer has already been removed from the active list, just free up the memory. */ vPortFree( pxTimer ); break; default : /* Don't expect to get here. */ break; } } } /*-----------------------------------------------------------*/ static void prvSwitchTimerLists( portTickType xLastTime ) { portTickType xNextExpireTime, xReloadTime; xList *pxTemp; xTIMER *pxTimer; portBASE_TYPE xResult; /* Remove compiler warnings if configASSERT() is not defined. */ ( void ) xLastTime; /* The tick count has overflowed. The timer lists must be switched. If there are any timers still referenced from the current timer list then they must have expired and should be processed before the lists are switched. */ while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) { xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); /* Remove the timer from the list. */ pxTimer = ( xTIMER * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); vListRemove( &( pxTimer->xTimerListItem ) ); /* Execute its callback, then send a command to restart the timer if it is an auto-reload timer. It cannot be restarted here as the lists have not yet been switched. */ pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer ); if( pxTimer->uxAutoReload == ( unsigned portBASE_TYPE ) pdTRUE ) { /* Calculate the reload value, and if the reload value results in the timer going into the same timer list then it has already expired and the timer should be re-inserted into the current list so it is processed again within this loop. Otherwise a command should be sent to restart the timer to ensure it is only inserted into a list after the lists have been swapped. */ xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); if( xReloadTime > xNextExpireTime ) { listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); } else { xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START, xNextExpireTime, NULL, tmrNO_DELAY ); configASSERT( xResult ); ( void ) xResult; } } } pxTemp = pxCurrentTimerList; pxCurrentTimerList = pxOverflowTimerList; pxOverflowTimerList = pxTemp; } /*-----------------------------------------------------------*/ static void prvCheckForValidListAndQueue( void ) { /* Check that the list from which active timers are referenced, and the queue used to communicate with the timer service, have been initialised. */ taskENTER_CRITICAL(); { if( xTimerQueue == NULL ) { vListInitialise( &xActiveTimerList1 ); vListInitialise( &xActiveTimerList2 ); pxCurrentTimerList = &xActiveTimerList1; pxOverflowTimerList = &xActiveTimerList2; xTimerQueue = xQueueCreate( ( unsigned portBASE_TYPE ) configTIMER_QUEUE_LENGTH, sizeof( xTIMER_MESSAGE ) ); } } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ portBASE_TYPE xTimerIsTimerActive( xTimerHandle xTimer ) { portBASE_TYPE xTimerIsInActiveList; xTIMER *pxTimer = ( xTIMER * ) xTimer; /* Is the timer in the list of active timers? */ taskENTER_CRITICAL(); { /* Checking to see if it is in the NULL list in effect checks to see if it is referenced from either the current or the overflow timer lists in one go, but the logic has to be reversed, hence the '!'. */ xTimerIsInActiveList = !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) ); } taskEXIT_CRITICAL(); return xTimerIsInActiveList; } /*-----------------------------------------------------------*/ void *pvTimerGetTimerID( xTimerHandle xTimer ) { xTIMER *pxTimer = ( xTIMER * ) xTimer; return pxTimer->pvTimerID; } /*-----------------------------------------------------------*/ /* This entire source file will be skipped if the application is not configured to include software timer functionality. If you want to include software timer functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ #endif /* configUSE_TIMERS == 1 */
722,294
./robotis_cm9_series/cm-9_ide/processing-head/libraries/FreeRTOS/utility/heap_2.c
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ /* * A sample implementation of pvPortMalloc() and vPortFree() that permits * allocated blocks to be freed, but does not combine adjacent free blocks * into a single larger block. * * See heap_1.c and heap_3.c for alternative implementations, and the memory * management pages of http://www.FreeRTOS.org for more information. */ #include <stdlib.h> /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE #include "FreeRTOS.h" #include "task.h" #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /* Allocate the memory for the heap. The struct is used to force byte alignment without using any non-portable code. */ static union xRTOS_HEAP { #if portBYTE_ALIGNMENT == 8 volatile portDOUBLE dDummy; #else volatile unsigned long ulDummy; #endif unsigned char ucHeap[ configTOTAL_HEAP_SIZE ]; } xHeap; /* Define the linked list structure. This is used to link free blocks in order of their size. */ typedef struct A_BLOCK_LINK { struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ size_t xBlockSize; /*<< The size of the free block. */ } xBlockLink; static const unsigned short heapSTRUCT_SIZE = ( sizeof( xBlockLink ) + portBYTE_ALIGNMENT - ( sizeof( xBlockLink ) % portBYTE_ALIGNMENT ) ); #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) /* Create a couple of list links to mark the start and end of the list. */ static xBlockLink xStart, xEnd; /* Keeps track of the number of free bytes remaining, but says nothing about fragmentation. */ static size_t xFreeBytesRemaining = configTOTAL_HEAP_SIZE; /* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */ /* * Insert a block into the list of free blocks - which is ordered by size of * the block. Small blocks at the start of the list and large blocks at the end * of the list. */ #define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ { \ xBlockLink *pxIterator; \ size_t xBlockSize; \ \ xBlockSize = pxBlockToInsert->xBlockSize; \ \ /* Iterate through the list until a block is found that has a larger size */ \ /* than the block we are inserting. */ \ for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ { \ /* There is nothing to do here - just iterate to the correct position. */ \ } \ \ /* Update the list to include the block being inserted in the correct */ \ /* position. */ \ pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ pxIterator->pxNextFreeBlock = pxBlockToInsert; \ } /*-----------------------------------------------------------*/ #define prvHeapInit() \ { \ xBlockLink *pxFirstFreeBlock; \ \ /* xStart is used to hold a pointer to the first item in the list of free */ \ /* blocks. The void cast is used to prevent compiler warnings. */ \ xStart.pxNextFreeBlock = ( void * ) xHeap.ucHeap; \ xStart.xBlockSize = ( size_t ) 0; \ \ /* xEnd is used to mark the end of the list of free blocks. */ \ xEnd.xBlockSize = configTOTAL_HEAP_SIZE; \ xEnd.pxNextFreeBlock = NULL; \ \ /* To start with there is a single free block that is sized to take up the \ entire heap space. */ \ pxFirstFreeBlock = ( void * ) xHeap.ucHeap; \ pxFirstFreeBlock->xBlockSize = configTOTAL_HEAP_SIZE; \ pxFirstFreeBlock->pxNextFreeBlock = &xEnd; \ } /*-----------------------------------------------------------*/ void *pvPortMalloc( size_t xWantedSize ) { xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink; static portBASE_TYPE xHeapHasBeenInitialised = pdFALSE; void *pvReturn = NULL; vTaskSuspendAll(); { /* If this is the first call to malloc then the heap will require initialisation to setup the list of free blocks. */ if( xHeapHasBeenInitialised == pdFALSE ) { prvHeapInit(); xHeapHasBeenInitialised = pdTRUE; } /* The wanted size is increased so it can contain a xBlockLink structure in addition to the requested amount of bytes. */ if( xWantedSize > 0 ) { xWantedSize += heapSTRUCT_SIZE; /* Ensure that blocks are always aligned to the required number of bytes. */ if( xWantedSize & portBYTE_ALIGNMENT_MASK ) { /* Byte alignment required. */ xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); } } if( ( xWantedSize > 0 ) && ( xWantedSize < configTOTAL_HEAP_SIZE ) ) { /* Blocks are stored in byte order - traverse the list from the start (smallest) block until one of adequate size is found. */ pxPreviousBlock = &xStart; pxBlock = xStart.pxNextFreeBlock; while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock ) ) { pxPreviousBlock = pxBlock; pxBlock = pxBlock->pxNextFreeBlock; } /* If we found the end marker then a block of adequate size was not found. */ if( pxBlock != &xEnd ) { /* Return the memory space - jumping over the xBlockLink structure at its start. */ pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); /* This block is being returned for use so must be taken our of the list of free blocks. */ pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; /* If the block is larger than required it can be split into two. */ if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) { /* This block is to be split into two. Create a new block following the number of bytes requested. The void cast is used to prevent byte alignment warnings from the compiler. */ pxNewBlockLink = ( void * ) ( ( ( unsigned char * ) pxBlock ) + xWantedSize ); /* Calculate the sizes of two blocks split from the single block. */ pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; pxBlock->xBlockSize = xWantedSize; /* Insert the new block into the list of free blocks. */ prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); } xFreeBytesRemaining -= pxBlock->xBlockSize; } } } xTaskResumeAll(); #if( configUSE_MALLOC_FAILED_HOOK == 1 ) { if( pvReturn == NULL ) { extern void vApplicationMallocFailedHook( void ); vApplicationMallocFailedHook(); } } #endif return pvReturn; } /*-----------------------------------------------------------*/ void vPortFree( void *pv ) { unsigned char *puc = ( unsigned char * ) pv; xBlockLink *pxLink; if( pv ) { /* The memory being freed will have an xBlockLink structure immediately before it. */ puc -= heapSTRUCT_SIZE; /* This casting is to keep the compiler from issuing warnings. */ pxLink = ( void * ) puc; vTaskSuspendAll(); { /* Add this block to the list of free blocks. */ prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) ); xFreeBytesRemaining += pxLink->xBlockSize; } xTaskResumeAll(); } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { /* This just exists to keep the linker quiet. */ }
722,295
./robotis_cm9_series/cm-9_ide/processing-head/hardware/robotis/cores/robotis/spi.c
/****************************************************************************** * The MIT License * * Copyright (c) 2010 Perry Hung. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file spi.c * @author Marti Bolivar <mbolivar@leaflabs.com> * @brief Serial Peripheral Interface (SPI) support. * Currently, there is no Integrated Interchip Sound (I2S) support. */ #include "spi.h" #include "bitband.h" static void spi_reconfigure(spi_dev *dev, uint32 cr1_config); /* * SPI devices */ static spi_dev spi1 = { .regs = SPI1_BASE, .clk_id = RCC_SPI1, .irq_num = NVIC_SPI1, }; /** SPI device 1 */ spi_dev *SPI1 = &spi1; static spi_dev spi2 = { .regs = SPI2_BASE, .clk_id = RCC_SPI2, .irq_num = NVIC_SPI2, }; /** SPI device 2 */ spi_dev *SPI2 = &spi2; #ifdef STM32_HIGH_DENSITY static spi_dev spi3 = { .regs = SPI3_BASE, .clk_id = RCC_SPI3, .irq_num = NVIC_SPI3, }; /** SPI device 3 */ spi_dev *SPI3 = &spi3; #endif /* * SPI convenience routines */ /** * @brief Initialize and reset a SPI device. * @param dev Device to initialize and reset. */ void spi_init(spi_dev *dev) { rcc_clk_enable(dev->clk_id); rcc_reset_dev(dev->clk_id); } /** * @brief Configure GPIO bit modes for use as a SPI port's pins. * @param as_master If true, configure bits for use as a bus master. * Otherwise, configure bits for use as slave. * @param nss_dev NSS pin's GPIO device * @param comm_dev SCK, MISO, MOSI pins' GPIO device * @param nss_bit NSS pin's GPIO bit on nss_dev * @param sck_bit SCK pin's GPIO bit on comm_dev * @param miso_bit MISO pin's GPIO bit on comm_dev * @param mosi_bit MOSI pin's GPIO bit on comm_dev */ void spi_gpio_cfg(uint8 as_master, gpio_dev *nss_dev, uint8 nss_bit, gpio_dev *comm_dev, uint8 sck_bit, uint8 miso_bit, uint8 mosi_bit) { if (as_master) { gpio_set_mode(nss_dev, nss_bit, GPIO_AF_OUTPUT_PP); gpio_set_mode(comm_dev, sck_bit, GPIO_AF_OUTPUT_PP); gpio_set_mode(comm_dev, miso_bit, GPIO_INPUT_FLOATING); gpio_set_mode(comm_dev, mosi_bit, GPIO_AF_OUTPUT_PP); } else { gpio_set_mode(nss_dev, nss_bit, GPIO_INPUT_FLOATING); gpio_set_mode(comm_dev, sck_bit, GPIO_INPUT_FLOATING); gpio_set_mode(comm_dev, miso_bit, GPIO_AF_OUTPUT_PP); gpio_set_mode(comm_dev, mosi_bit, GPIO_INPUT_FLOATING); } } /** * @brief Configure and enable a SPI device as bus master. * * The device's peripheral will be disabled before being reconfigured. * * @param dev Device to configure as bus master * @param baud Bus baud rate * @param mode SPI mode * @param flags Logical OR of spi_cfg_flag values. * @see spi_cfg_flag */ void spi_master_enable(spi_dev *dev, spi_baud_rate baud, spi_mode mode, uint32 flags) { spi_reconfigure(dev, baud | flags | SPI_CR1_MSTR | mode); } /** * @brief Configure and enable a SPI device as a bus slave. * * The device's peripheral will be disabled before being reconfigured. * * @param dev Device to configure as a bus slave * @param mode SPI mode * @param flags Logical OR of spi_cfg_flag values. * @see spi_cfg_flag */ void spi_slave_enable(spi_dev *dev, spi_mode mode, uint32 flags) { spi_reconfigure(dev, flags | mode); } /** * @brief Nonblocking SPI transmit. * @param dev SPI port to use for transmission * @param buf Buffer to transmit. The sizeof buf's elements are * inferred from dev's data frame format (i.e., are * correctly treated as 8-bit or 16-bit quantities). * @param len Maximum number of elements to transmit. * @return Number of elements transmitted. */ uint32 spi_tx(spi_dev *dev, const void *buf, uint32 len) { uint32 txed = 0; uint8 byte_frame = spi_dff(dev) == SPI_DFF_8_BIT; while (spi_is_tx_empty(dev) && (txed < len)) { if (byte_frame) { dev->regs->DR = ((const uint8*)buf)[txed++]; } else { dev->regs->DR = ((const uint16*)buf)[txed++]; } } return txed; } /** * @brief Call a function on each SPI port * @param fn Function to call. */ void spi_foreach(void (*fn)(spi_dev*)) { fn(SPI1); fn(SPI2); #ifdef STM32_HIGH_DENSITY fn(SPI3); #endif } /** * @brief Enable a SPI peripheral * @param dev Device to enable */ void spi_peripheral_enable(spi_dev *dev) { bb_peri_set_bit(&dev->regs->CR1, SPI_CR1_SPE_BIT, 1); } /** * @brief Disable a SPI peripheral * @param dev Device to disable */ void spi_peripheral_disable(spi_dev *dev) { bb_peri_set_bit(&dev->regs->CR1, SPI_CR1_SPE_BIT, 0); } /** * @brief Enable DMA requests whenever the transmit buffer is empty * @param dev SPI device on which to enable TX DMA requests */ void spi_tx_dma_enable(spi_dev *dev) { bb_peri_set_bit(&dev->regs->CR2, SPI_CR2_TXDMAEN_BIT, 1); } /** * @brief Disable DMA requests whenever the transmit buffer is empty * @param dev SPI device on which to disable TX DMA requests */ void spi_tx_dma_disable(spi_dev *dev) { bb_peri_set_bit(&dev->regs->CR2, SPI_CR2_TXDMAEN_BIT, 0); } /** * @brief Enable DMA requests whenever the receive buffer is empty * @param dev SPI device on which to enable RX DMA requests */ void spi_rx_dma_enable(spi_dev *dev) { bb_peri_set_bit(&dev->regs->CR2, SPI_CR2_RXDMAEN_BIT, 1); } /** * @brief Disable DMA requests whenever the receive buffer is empty * @param dev SPI device on which to disable RX DMA requests */ void spi_rx_dma_disable(spi_dev *dev) { bb_peri_set_bit(&dev->regs->CR2, SPI_CR2_RXDMAEN_BIT, 0); } /* * SPI auxiliary routines */ static void spi_reconfigure(spi_dev *dev, uint32 cr1_config) { spi_irq_disable(dev, SPI_INTERRUPTS_ALL); spi_peripheral_disable(dev); dev->regs->CR1 = cr1_config; spi_peripheral_enable(dev); } /* * IRQ handlers (TODO) */
722,296
./robotis_cm9_series/cm-9_ide/processing-head/hardware/robotis/cores/robotis/gpio.c
/****************************************************************************** * The MIT License * * Copyright (c) 2010 Perry Hung. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @brief GPIO initialization routine */ #include "gpio.h" #include "rcc.h" /* * GPIO devices */ gpio_dev gpioa = { .regs = GPIOA_BASE, .clk_id = RCC_GPIOA, .exti_port = AFIO_EXTI_PA, }; /** GPIO port A device. */ gpio_dev* const GPIOA = &gpioa; gpio_dev gpiob = { .regs = GPIOB_BASE, .clk_id = RCC_GPIOB, .exti_port = AFIO_EXTI_PB, }; /** GPIO port B device. */ gpio_dev* const GPIOB = &gpiob; gpio_dev gpioc = { .regs = GPIOC_BASE, .clk_id = RCC_GPIOC, .exti_port = AFIO_EXTI_PC, }; /** GPIO port C device. */ gpio_dev* const GPIOC = &gpioc; gpio_dev gpiod = { .regs = GPIOD_BASE, .clk_id = RCC_GPIOD, .exti_port = AFIO_EXTI_PD, }; /** GPIO port D device. */ gpio_dev* const GPIOD = &gpiod; #ifdef STM32_HIGH_DENSITY gpio_dev gpioe = { .regs = GPIOE_BASE, .clk_id = RCC_GPIOE, .exti_port = AFIO_EXTI_PE, }; /** GPIO port E device. */ gpio_dev* const GPIOE = &gpioe; gpio_dev gpiof = { .regs = GPIOF_BASE, .clk_id = RCC_GPIOF, .exti_port = AFIO_EXTI_PF, }; /** GPIO port F device. */ gpio_dev* const GPIOF = &gpiof; gpio_dev gpiog = { .regs = GPIOG_BASE, .clk_id = RCC_GPIOG, .exti_port = AFIO_EXTI_PG, }; /** GPIO port G device. */ gpio_dev* const GPIOG = &gpiog; #endif /* * GPIO convenience routines */ /** * Initialize a GPIO device. * * Enables the clock for and resets the given device. * * @param dev GPIO device to initialize. */ void gpio_init(gpio_dev *dev) { rcc_clk_enable(dev->clk_id); rcc_reset_dev(dev->clk_id); } /** * Initialize and reset all available GPIO devices. */ void gpio_init_all(void) { gpio_init(GPIOA); gpio_init(GPIOB); gpio_init(GPIOC); gpio_init(GPIOD); #ifdef STM32_HIGH_DENSITY gpio_init(GPIOE); gpio_init(GPIOF); gpio_init(GPIOG); #endif } /** * Set the mode of a GPIO pin. * * @param dev GPIO device. * @param pin Pin on the device whose mode to set, 0--15. * @param mode General purpose or alternate function mode to set the pin to. * @see gpio_pin_mode */ void gpio_set_mode(gpio_dev *dev, uint8 pin, gpio_pin_mode mode) { gpio_reg_map *regs = dev->regs; __io uint32 *cr = &regs->CRL + (pin >> 3); uint32 shift = (pin & 0x7) * 4; uint32 tmp = *cr; tmp &= ~(0xF << shift); tmp |= (mode == GPIO_INPUT_PU ? GPIO_INPUT_PD : mode) << shift; *cr = tmp; if (mode == GPIO_INPUT_PD) { regs->ODR &= ~BIT(pin); } else if (mode == GPIO_INPUT_PU) { regs->ODR |= BIT(pin); } } /* * AFIO */ /** * @brief Initialize the AFIO clock, and reset the AFIO registers. */ void afio_init(void) { rcc_clk_enable(RCC_AFIO); rcc_reset_dev(RCC_AFIO); } #define AFIO_EXTI_SEL_MASK 0xF /** * @brief Select a source input for an external interrupt. * * @param exti External interrupt. * @param gpio_port Port which contains pin to use as source input. * @see afio_exti_num * @see afio_exti_port */ void afio_exti_select(afio_exti_num exti, afio_exti_port gpio_port) { __io uint32 *exti_cr = &AFIO_BASE->EXTICR1 + exti / 4; uint32 shift = 4 * (exti % 4); uint32 cr = *exti_cr; cr &= ~(AFIO_EXTI_SEL_MASK << shift); cr |= gpio_port << shift; *exti_cr = cr; } /** * @brief Perform an alternate function remap. * @param remapping Remapping to perform. */ void afio_remap(afio_remap_peripheral remapping) { if (remapping & AFIO_REMAP_USE_MAPR2) { remapping &= ~AFIO_REMAP_USE_MAPR2; AFIO_BASE->MAPR2 |= remapping; } else { AFIO_BASE->MAPR |= remapping; } }
722,297
./robotis_cm9_series/cm-9_ide/processing-head/hardware/robotis/cores/robotis/flash.c
/****************************************************************************** * The MIT License * * Copyright (c) 2010 Perry Hung. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file flash.c * @brief Flash management functions */ //#include "libpandora.h" #include "flash.h" #include "bitband.h" #include "util.h" /* Delay definition */ #define EraseTimeout ((uint32)0x000B0000) #define ProgramTimeout ((uint32)0x00002000) /** * @brief Turn on the hardware prefetcher. */ void flash_enable_prefetch(void) { *bb_perip(&FLASH_BASE->ACR, FLASH_ACR_PRFTBE_BIT) = 1; } /** * @brief Set flash wait states * * See ST PM0042, section 3.1 for restrictions on the acceptable value * of wait_states for a given SYSCLK configuration. * * @param wait_states number of wait states (one of * FLASH_WAIT_STATE_0, FLASH_WAIT_STATE_1, * FLASH_WAIT_STATE_2). */ void flash_set_latency(uint32 wait_states) { uint32 val = FLASH_BASE->ACR; val &= ~FLASH_ACR_LATENCY; val |= wait_states; FLASH_BASE->ACR = val; } /** * @brief Clears the FLASH's pending flags. * @note This function can be used for all STM32F10x devices. * - For STM32F10X_XL devices, this function clears Bank1 or Bank2Æs pending flags * - For other devices, it clears Bank1Æs pending flags. * @param FLASH_FLAG: specifies the FLASH flags to clear. * This parameter can be any combination of the following values: * @arg FLASH_FLAG_PGERR: FLASH Program error flag * @arg FLASH_FLAG_WRPRTERR: FLASH Write protected error flag * @arg FLASH_FLAG_EOP: FLASH End of Operation flag * @retval None */ void FLASH_ClearFlag(uint32 FLASH_FLAG) { /* Check the parameters */ ASSERT(IS_FLASH_CLEAR_FLAG(FLASH_FLAG)) ; /* Clear the flags */ FLASH_BASE->SR = FLASH_FLAG; } /** * @brief Unlocks the FLASH Program Erase Controller. * @note This function can be used for all STM32F10x devices. * - For STM32F10X_XL devices this function unlocks Bank1 and Bank2. * - For all other devices it unlocks Bank1 and it is equivalent * to FLASH_UnlockBank1 function.. * @param None * @retval None */ void FLASH_Unlock(void) { /* Authorize the FPEC of Bank1 Access */ FLASH_BASE->KEYR = FLASH_KEY1; FLASH_BASE->KEYR = FLASH_KEY2; #ifdef STM32F10X_XL /* Authorize the FPEC of Bank2 Access */ FLASH_BASE->KEYR2 = FLASH_KEY1; FLASH_BASE->KEYR2 = FLASH_KEY2; #endif /* STM32F10X_XL */ } /** * @brief Unlocks the FLASH Bank1 Program Erase Controller. * @note This function can be used for all STM32F10x devices. * - For STM32F10X_XL devices this function unlocks Bank1. * - For all other devices it unlocks Bank1 and it is * equivalent to FLASH_Unlock function. * @param None * @retval None */ void FLASH_UnlockBank1(void) { /* Authorize the FPEC of Bank1 Access */ FLASH_BASE->KEYR = FLASH_KEY1; FLASH_BASE->KEYR = FLASH_KEY2; } /** * @brief Locks the FLASH Program Erase Controller. * @note This function can be used for all STM32F10x devices. * - For STM32F10X_XL devices this function Locks Bank1 and Bank2. * - For all other devices it Locks Bank1 and it is equivalent * to FLASH_LockBank1 function. * @param None * @retval None */ void FLASH_Lock(void) { /* Set the Lock Bit to lock the FPEC and the CR of Bank1 */ FLASH_BASE->CR |= FLASH_CR_LOCK; #ifdef STM32F10X_XL /* Set the Lock Bit to lock the FPEC and the CR of Bank2 */ FLASH_BASE->CR2 |= FLASH_CR_LOCK; #endif /* STM32F10X_XL */ } /** * @brief Locks the FLASH Bank1 Program Erase Controller. * @note this function can be used for all STM32F10x devices. * - For STM32F10X_XL devices this function Locks Bank1. * - For all other devices it Locks Bank1 and it is equivalent * to FLASH_Lock function. * @param None * @retval None */ void FLASH_LockBank1(void) { /* Set the Lock Bit to lock the FPEC and the CR of Bank1 */ FLASH_BASE->CR |= FLASH_CR_LOCK;//CR_LOCK_Set; } /** * @brief Returns the FLASH Bank1 Status. * @note This function can be used for all STM32F10x devices, it is equivalent * to FLASH_GetStatus function. * @param None * @retval FLASH Status: The returned value can be: FLASH_BUSY, FLASH_ERROR_PG, * FLASH_ERROR_WRP or FLASH_COMPLETE */ FLASH_Status FLASH_GetBank1Status(void) { FLASH_Status flashstatus = FLASH_COMPLETE; if((FLASH_BASE->SR & FLASH_FLAG_BANK1_BSY) == FLASH_FLAG_BSY) { flashstatus = FLASH_BUSY; } else { if((FLASH_BASE->SR & FLASH_FLAG_BANK1_PGERR) != 0) { flashstatus = FLASH_ERROR_PG; } else { if((FLASH_BASE->SR & FLASH_FLAG_BANK1_WRPRTERR) != 0 ) { flashstatus = FLASH_ERROR_WRP; } else { flashstatus = FLASH_COMPLETE; } } } /* Return the Flash Status */ return flashstatus; } /** * @brief Waits for a Flash operation to complete or a TIMEOUT to occur. * @note This function can be used for all STM32F10x devices, * it is equivalent to FLASH_WaitForLastBank1Operation. * - For STM32F10X_XL devices this function waits for a Bank1 Flash operation * to complete or a TIMEOUT to occur. * - For all other devices it waits for a Flash operation to complete * or a TIMEOUT to occur. * @param Timeout: FLASH programming Timeout * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_WaitForLastOperation(uint32 Timeout) { FLASH_Status status = FLASH_COMPLETE; /* Check for the Flash Status */ status = FLASH_GetBank1Status(); /* Wait for a Flash operation to complete or a TIMEOUT to occur */ while((status == FLASH_BUSY) && (Timeout != 0x00)) { status = FLASH_GetBank1Status(); Timeout--; } if(Timeout == 0x00 ) { status = FLASH_TIMEOUT; } /* Return the operation status */ return status; } /** * @brief Programs a half word at a specified Option Byte Data address. * @note This function can be used for all STM32F10x devices. * @param Address: specifies the address to be programmed. * This parameter can be 0x1FFFF804 or 0x1FFFF806. * @param Data: specifies the data to be programmed. * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_ProgramOptionByteData(uint32 Address, uint8 Data) { FLASH_Status status = FLASH_COMPLETE; /* Check the parameters */ ASSERT(IS_OB_DATA_ADDRESS(Address)); status = FLASH_WaitForLastOperation(ProgramTimeout); if(status == FLASH_COMPLETE) { /* Authorize the small information block programming */ FLASH_BASE->OPTKEYR = FLASH_KEY1; FLASH_BASE->OPTKEYR = FLASH_KEY2; /* Enables the Option Bytes Programming operation */ FLASH_BASE->CR |= FLASH_CR_OPTPG;//CR_OPTPG_Set; *(__io uint16*)Address = Data; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); if(status != FLASH_TIMEOUT) { /* if the program operation is completed, disable the OPTPG Bit */ FLASH_BASE->CR &= CR_OPTPG_Reset; } } /* Return the Option Byte Data Program Status */ return status; } /** * @brief Programs a half word at a specified address. * @note This function can be used for all STM32F10x devices. * @param Address: specifies the address to be programmed. * @param Data: specifies the data to be programmed. * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_ProgramHalfWord(uint32 Address, uint16 Data) { FLASH_Status status = FLASH_COMPLETE; /* Check the parameters */ ASSERT(IS_FLASH_ADDRESS(Address)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); if(status == FLASH_COMPLETE) { /* if the previous operation is completed, proceed to program the new data */ FLASH_BASE->CR |= FLASH_CR_PG;//CR_PG_Set; *(__io uint16*)Address = Data; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); /* Disable the PG Bit */ FLASH_BASE->CR &= CR_PG_Reset; } /* Return the Program Status */ return status; } /** * @brief Programs a word at a specified address. * @note This function can be used for all STM32F10x devices. * @param Address: specifies the address to be programmed. * @param Data: specifies the data to be programmed. * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_ProgramWord(uint32 Address, uint32 Data) { FLASH_Status status = FLASH_COMPLETE; __io uint32 tmp = 0; /* Check the parameters */ ASSERT(IS_FLASH_ADDRESS(Address)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); if(status == FLASH_COMPLETE) { /* if the previous operation is completed, proceed to program the new first half word */ FLASH_BASE->CR |= FLASH_CR_PG;//CR_PG_Set; *(__io uint16*)Address = (uint16)Data; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); if(status == FLASH_COMPLETE) { /* if the previous operation is completed, proceed to program the new second half word */ tmp = Address + 2; *(__io uint16*) tmp = Data >> 16; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); /* Disable the PG Bit */ FLASH_BASE->CR &= CR_PG_Reset; } else { /* Disable the PG Bit */ FLASH_BASE->CR &= CR_PG_Reset; } } /* Return the Program Status */ return status; } /** * @brief Erases a specified FLASH page. * @note This function can be used for all STM32F10x devices. * @param Page_Address: The page address to be erased. * @retval FLASH Status: The returned value can be: FLASH_BUSY, FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_ErasePage(uint32 Page_Address) { FLASH_Status status = FLASH_COMPLETE; /* Check the parameters */ ASSERT(IS_FLASH_ADDRESS(Page_Address)); /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(EraseTimeout); if(status == FLASH_COMPLETE) { /* if the previous operation is completed, proceed to erase the page */ FLASH_BASE->CR|= FLASH_CR_PER;//CR_PER_Set; FLASH_BASE->AR = Page_Address; FLASH_BASE->CR|= FLASH_CR_STRT;//CR_STRT_Set; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(EraseTimeout); /* Disable the PER Bit */ FLASH_BASE->CR &= CR_PER_Reset; } /* Return the Erase Status */ return status; } /** * @brief Erases all FLASH pages. * @note This function can be used for all STM32F10x devices. * @param None * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_EraseAllPages(void) { FLASH_Status status = FLASH_COMPLETE; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(EraseTimeout); if(status == FLASH_COMPLETE) { /* if the previous operation is completed, proceed to erase all pages */ FLASH_BASE->CR |= FLASH_CR_MER;//CR_MER_Set; FLASH_BASE->CR |= FLASH_CR_STRT;//CR_STRT_Set; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(EraseTimeout); /* Disable the MER Bit */ FLASH_BASE->CR &= CR_MER_Reset; } /* Return the Erase Status */ return status; }
722,298
./robotis_cm9_series/cm-9_ide/processing-head/hardware/robotis/cores/robotis/dxl.c
/* * dxl.c * * Created on: 2013. 4. 18. * Author: in2storm */ #include "dxl.h" #ifdef CM9_DEBUG extern void TxDByteC(uint8 buf); extern void TxDStringC(char *str); extern void TxDHex8C(u16 bSentData); extern void TxDHex16C(u16 wSentData); extern void TxDHex32C(u32 lSentData); void PrintBuffer(byte *bpPrintBuffer, byte bLength) { byte bCount; if(bLength == 0) { if(gbpTxBuffer[2] == BROADCAST_ID) { TxDStringC("\r\n No Data[at Broadcast ID 0xFE]"); } else { TxDStringC("\r\n No Data(Check ID, Operating Mode, Baud rate)");//TxDString("\r\n No Data(Check ID, Operating Mode, Baud rate)"); } } for(bCount = 0; bCount < bLength; bCount++) { TxDHex8C(bpPrintBuffer[bCount]); TxDByteC(' '); } TxDStringC(" LEN:");//("(LEN:") TxDHex8C(bLength); TxDStringC("\r\n"); } #endif uint32 Dummy(uint32 tmp){ return tmp; } void uDelay(uint32 uTime) { uint32 cnt, max; static uint32 tmp = 0; for( max=0; max < uTime; max++) { for( cnt=0; cnt < 10 ; cnt++ ) { tmp +=Dummy(cnt); } } //tmpdly = tmp; } void nDelay(uint32 nTime) { //100ns uint32 cnt, max; cnt=0; static uint32 tmp = 0; for( max=0; max < nTime; max++) { //for( cnt=0; cnt < 10 ; cnt++ ) //{ tmp +=Dummy(cnt); //} } //tmpdly = tmp; } void clearBuffer256(void){ gbDXLReadPointer = gbDXLWritePointer = 0; } byte checkNewArrive(void){ if(gbDXLReadPointer != gbDXLWritePointer) return 1; else return 0; } void TxByteToDXL(byte bTxData){ //USART_SendData(USART1,bTxData); //while( USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET ); USART1->regs->DR = (bTxData & (u16)0x01FF); while( (USART1->regs->SR & ((u16)0x0040)) == RESET ); } byte RxByteFromDXL(void){ return gbpDXLDataBuffer[gbDXLReadPointer++]; } /** * @brief communicate with dynamixel bus on CM-9XX series. After transmitting packets to the bus, also it receives status feedback packets. * @param bID dynamixel ID * @param bInst Instruction number, you can find it from dynamixel.h * @param bTxParaLen length of packet * */ byte txrx_Packet(byte bID, byte bInst, byte bTxParaLen){ #define TRY_NUM 2//;;2 byte bTxLen, bRxLenEx, bTryCount; gbBusUsed = 1; for(bTryCount = 0; bTryCount < TRY_NUM; bTryCount++) { gbDXLReadPointer = gbDXLWritePointer; //BufferClear050728 bTxLen = tx_Packet(bID, bInst, bTxParaLen); if(bInst == INST_PING) { if(bID == BROADCAST_ID) { gbRxLength = bRxLenEx = 255; } else { gbRxLength = bRxLenEx = 6; } } else if(bInst == INST_READ) { gbRxLength = bRxLenEx = 6+gbpParameter[1]; } else if( bID == BROADCAST_ID ) { gbRxLength = bRxLenEx = 0; break; } else { gbRxLength = bRxLenEx = 6; } if(bRxLenEx)//(gbpValidServo[bID] > 0x81 || bInst != INST_WRITE)) //ValidServo = 0x80|RETURN_LEVEL { gbRxLength = rx_Packet(bRxLenEx); //TxDStringC("gbRxLength = ");TxD_Dec_U8C(gbRxLength);TxDStringC("\r\n"); //TxDStringC("bRxLenEx = ");TxD_Dec_U8C(bRxLenEx);TxDStringC("\r\n"); // if(gbRxLength != bRxLenEx) //&& bRxLenEx != 255) before Ver 1.11e if((gbRxLength != bRxLenEx) && (bRxLenEx != 255)) // after Ver 1.11f { unsigned long ulCounter; word wTimeoutCount; ulCounter = 0; wTimeoutCount = 0; //TxDByteC('0');//TxDStringC("\r\n TEST POINT 0");//TxDString("\r\n Err ID:0x"); while(ulCounter++ < RX_TIMEOUT_COUNT2) { if(gbDXLReadPointer != gbDXLWritePointer) { gbDXLReadPointer = gbDXLWritePointer; //BufferClear ulCounter = 0; if(wTimeoutCount++ > 100 ) { //uDelay(0);// porting ydh added break; //porting ydh 100->245 //;;;;;; min max ╡┌╣┘▓± found at Ver 1.11e } nDelay(NANO_TIME_DELAY);// porting ydh added 20120210. } //uDelay(0);// porting ydh added nDelay(NANO_TIME_DELAY);// porting ydh added } //TxDByteC('1');//TxDStringC("\r\n TEST POINT 1");//TxDString("\r\n Err ID:0x"); gbDXLReadPointer = gbDXLWritePointer; //BufferClear } else { //TxDByteC('6');//TxDStringC("\r\n TEST POINT 6");//TxDString("\r\n Err ID:0x"); break; } } } //TxDByteC('2');//TxDStringC("\r\n TEST POINT 2");//TxDString("\r\n Err ID:0x"); gbBusUsed = 0; if((gbRxLength != bRxLenEx) && (gbpTxBuffer[2] != BROADCAST_ID)) { //TxDByteC('3');//TxDStringC("\r\n TEST POINT 3");//TxDString("\r\n Err ID:0x"); #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 //TxDString("\r\n Err ID:0x"); //TxDHex8(bID); //TxDString("\r\n ->[DXL]Err: "); PrintBuffer(gbpTxBuffer,bTxLen); //TxDString("\r\n <-[DXL]Err: "); PrintBuffer(gbpRxBuffer,gbRxLength); #endif #ifdef PRINT_OUT_TRACE_ERROR_PRINT_TO_USART2 //TxDString("\r\n {[ERROR:");TxD16Hex(0x8100);TxDByte(':');TxD16Hex(bID);TxDByte(':');TxD8Hex(bInst);TxDByte(']');TxDByte('}'); //TxDByte(bID);TxDByte(' '); //TxDByte(bInst);TxDByte(' '); //TxDByte(gbpParameter[0]);TxDByte(' '); //TxDByte(gbpParameter[1]);TxDByte(' '); #endif return 0; } //TxDString("\r\n TEST POINT 4");//TxDString("\r\n Err ID:0x"); #ifdef PRINT_OUT_PACKET_TO_USART2 TxDStringC("\r\n ->[TX Buffer]: "); PrintBuffer(gbpTxBuffer,bTxLen); TxDStringC("\r\n <-[RX Buffer]: "); PrintBuffer(gbpRxBuffer,gbRxLength); #endif //gbLengthForPacketMaking =0; return 1; } //░╣╝÷┐í ╕┬░╘ ╣▐┤┬ └╠└» : ┼δ╜┼┐í╖»░í │¬┐└╕Θ Length░í ╞▓╕▒ ░í┤╔╝║└╠ ╣½├┤ │⌠▒Γ ╢º╣« byte rx_Packet(byte bRxLength){ unsigned long ulCounter, ulTimeLimit; byte bCount, bLength, bChecksum; byte bTimeout; bTimeout = 0; if(bRxLength == 255) ulTimeLimit = RX_TIMEOUT_COUNT1; else ulTimeLimit = RX_TIMEOUT_COUNT2; for(bCount = 0; bCount < bRxLength; bCount++) { ulCounter = 0; while(gbDXLReadPointer == gbDXLWritePointer) { nDelay(NANO_TIME_DELAY); // porting ydh if(ulCounter++ > ulTimeLimit) { bTimeout = 1; break; } uDelay(0); //porting ydh added } if(bTimeout) break; gbpRxBuffer[bCount] = gbpDXLDataBuffer[gbDXLReadPointer++]; //TxDStringC("gbpRxBuffer = ");TxDHex8C(gbpRxBuffer[bCount]);TxDStringC("\r\n"); } bLength = bCount; bChecksum = 0; if( gbpTxBuffer[2] != BROADCAST_ID ) { if(bTimeout && bRxLength != 255) { #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 TxDString("Rx Timeout"); TxDByte(bLength); #endif clearBuffer256(); //return 0; } if(bLength > 3) //checking available length. { if(gbpRxBuffer[0] != 0xff || gbpRxBuffer[1] != 0xff ) { #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 TxDStringC("Wrong Header");//[Wrong Header] #endif clearBuffer256(); return 0; } if(gbpRxBuffer[2] != gbpTxBuffer[2] ) { #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 TxDStringC("[Error:TxID != RxID]"); #endif clearBuffer256(); return 0; } if(gbpRxBuffer[3] != bLength-4) { #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 TxDStringC("RxLength Error"); #endif clearBuffer256(); return 0; } for(bCount = 2; bCount < bLength; bCount++) bChecksum += gbpRxBuffer[bCount]; if(bChecksum != 0xff) { #ifdef PRINT_OUT_COMMUNICATION_ERROR_TO_USART2 TxDStringC("[RxChksum Error]"); #endif clearBuffer256(); return 0; } } } return bLength; } byte tx_Packet(byte bID, byte bInstruction, byte bParameterLength){ byte bCount,bCheckSum,bPacketLength; gbpTxBuffer[0] = 0xff; gbpTxBuffer[1] = 0xff; gbpTxBuffer[2] = bID; gbpTxBuffer[3] = bParameterLength+2; //Length(Paramter,Instruction,Checksum) gbpTxBuffer[4] = bInstruction; for(bCount = 0; bCount < bParameterLength; bCount++) { gbpTxBuffer[bCount+5] = gbpParameter[bCount]; } bCheckSum = 0; bPacketLength = bParameterLength+4+2; for(bCount = 2; bCount < bPacketLength-1; bCount++) //except 0xff,checksum { bCheckSum += gbpTxBuffer[bCount]; } gbpTxBuffer[bCount] = ~bCheckSum; //Writing Checksum with Bit Inversion DXL_TXD; // this define is declared in dxl.h for(bCount = 0; bCount < bPacketLength; bCount++) { TxByteToDXL(gbpTxBuffer[bCount]); } DXL_RXD;// this define is declared in dxl.h return(bPacketLength); }
722,299
./robotis_cm9_series/cm-9_ide/processing-head/hardware/robotis/cores/robotis/nvic.c
/****************************************************************************** * The MIT License * * Copyright (c) 2010 Perry Hung. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @brief Nested interrupt controller routines */ #include "nvic.h" #include "scb.h" #include "stm32.h" /** * @brief Set interrupt priority for an interrupt line * * Note: The STM32 only implements 4 bits of priority, ignoring the * lower 4 bits. This means there are only 16 levels of priority. * Bits[3:0] read as zero and ignore writes. * * @param irqn device to set * @param priority Priority to set, 0 being highest priority and 15 * being lowest. */ void nvic_irq_set_priority(nvic_irq_num irqn, uint8 priority) { if (irqn < 0) { /* This interrupt is in the system handler block */ SCB_BASE->SHP[((uint32)irqn & 0xF) - 4] = (priority & 0xF) << 4; } else { NVIC_BASE->IP[irqn] = (priority & 0xF) << 4; } } /** * @brief Initialize the NVIC * @param vector_table_address Vector table base address. * @param offset Offset from vector_table_address. Some restrictions * apply to the use of nonzero offsets; see ST RM0008 * and the ARM Cortex M3 Technical Reference Manual. */ void nvic_init(uint32 vector_table_address, uint32 offset) { uint32 i; nvic_set_vector_table(vector_table_address, offset); /* * Lower priority level for all peripheral interrupts to lowest * possible. */ for (i = 0; i < STM32_NR_INTERRUPTS; i++) { nvic_irq_set_priority((nvic_irq_num)i, 0xF); } /* Lower systick interrupt priority to lowest level */ nvic_irq_set_priority(NVIC_SYSTICK, 0xF); } /** * Reset the vector table address. */ void nvic_set_vector_table(uint32 addr, uint32 offset) { SCB_BASE->VTOR = addr | (offset & 0x1FFFFF80); }
722,300
./robotis_cm9_series/cm-9_ide/processing-head/hardware/robotis/cores/robotis/rcc.c
/****************************************************************************** * The MIT License * * Copyright (c) 2010 Perry Hung. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @brief Implements pretty much only the basic clock setup on the * stm32, clock enable/disable and peripheral reset commands. */ #include "rcc.h" #include "util.h" #include "flash.h" #include "bitband.h" #define APB1 RCC_APB1 #define APB2 RCC_APB2 #define AHB RCC_AHB struct rcc_dev_info { const rcc_clk_domain clk_domain; const uint8 line_num; }; /* Device descriptor table, maps rcc_clk_id onto bus and enable/reset * register bit numbers. */ static const struct rcc_dev_info rcc_dev_table[] = { [RCC_GPIOA] = { .clk_domain = APB2, .line_num = 2 }, [RCC_GPIOB] = { .clk_domain = APB2, .line_num = 3 }, [RCC_GPIOC] = { .clk_domain = APB2, .line_num = 4 }, [RCC_GPIOD] = { .clk_domain = APB2, .line_num = 5 }, [RCC_AFIO] = { .clk_domain = APB2, .line_num = 0 }, [RCC_ADC1] = { .clk_domain = APB2, .line_num = 9 }, [RCC_ADC2] = { .clk_domain = APB2, .line_num = 10 }, [RCC_ADC3] = { .clk_domain = APB2, .line_num = 15 }, [RCC_USART1] = { .clk_domain = APB2, .line_num = 14 }, [RCC_USART2] = { .clk_domain = APB1, .line_num = 17 }, [RCC_USART3] = { .clk_domain = APB1, .line_num = 18 }, [RCC_TIMER1] = { .clk_domain = APB2, .line_num = 11 }, [RCC_TIMER2] = { .clk_domain = APB1, .line_num = 0 }, [RCC_TIMER3] = { .clk_domain = APB1, .line_num = 1 }, [RCC_TIMER4] = { .clk_domain = APB1, .line_num = 2 }, [RCC_SPI1] = { .clk_domain = APB2, .line_num = 12 }, [RCC_SPI2] = { .clk_domain = APB1, .line_num = 14 }, [RCC_DMA1] = { .clk_domain = AHB, .line_num = 0 }, [RCC_PWR] = { .clk_domain = APB1, .line_num = 28}, [RCC_BKP] = { .clk_domain = APB1, .line_num = 27}, [RCC_I2C1] = { .clk_domain = APB1, .line_num = 21 }, [RCC_I2C2] = { .clk_domain = APB1, .line_num = 22 }, [RCC_CRC] = { .clk_domain = AHB, .line_num = 6}, [RCC_FLITF] = { .clk_domain = AHB, .line_num = 4}, [RCC_SRAM] = { .clk_domain = AHB, .line_num = 2}, #if defined(STM32_HIGH_DENSITY) || defined(STM32_XL_DENSITY) [RCC_GPIOE] = { .clk_domain = APB2, .line_num = 6 }, [RCC_GPIOF] = { .clk_domain = APB2, .line_num = 7 }, [RCC_GPIOG] = { .clk_domain = APB2, .line_num = 8 }, [RCC_UART4] = { .clk_domain = APB1, .line_num = 19 }, [RCC_UART5] = { .clk_domain = APB1, .line_num = 20 }, [RCC_TIMER5] = { .clk_domain = APB1, .line_num = 3 }, [RCC_TIMER6] = { .clk_domain = APB1, .line_num = 4 }, [RCC_TIMER7] = { .clk_domain = APB1, .line_num = 5 }, [RCC_TIMER8] = { .clk_domain = APB2, .line_num = 13 }, [RCC_FSMC] = { .clk_domain = AHB, .line_num = 8 }, [RCC_DAC] = { .clk_domain = APB1, .line_num = 29 }, [RCC_DMA2] = { .clk_domain = AHB, .line_num = 1 }, [RCC_SDIO] = { .clk_domain = AHB, .line_num = 10 }, [RCC_SPI3] = { .clk_domain = APB1, .line_num = 15 }, #endif #ifdef STM32_XL_DENSITY [RCC_TIMER9] = { .clk_domain = APB2, .line_num = 19 }, [RCC_TIMER10] = { .clk_domain = APB2, .line_num = 20 }, [RCC_TIMER11] = { .clk_domain = APB2, .line_num = 21 }, [RCC_TIMER12] = { .clk_domain = APB1, .line_num = 6 }, [RCC_TIMER13] = { .clk_domain = APB1, .line_num = 7 }, [RCC_TIMER14] = { .clk_domain = APB1, .line_num = 8 }, #endif }; /** * @brief Initialize the clock control system. Initializes the system * clock source to use the PLL driven by an external oscillator * @param sysclk_src system clock source, must be PLL * @param pll_src pll clock source, must be HSE * @param pll_mul pll multiplier */ void rcc_clk_init(rcc_sysclk_src sysclk_src, rcc_pllsrc pll_src, rcc_pll_multiplier pll_mul) { uint32 cfgr = 0; uint32 cr; /* Assume that we're going to clock the chip off the PLL, fed by * the HSE */ ASSERT(sysclk_src == RCC_CLKSRC_PLL && pll_src == RCC_PLLSRC_HSE); RCC_BASE->CFGR = pll_src | pll_mul; /* Turn on the HSE */ cr = RCC_BASE->CR; cr |= RCC_CR_HSEON; RCC_BASE->CR = cr; while (!(RCC_BASE->CR & RCC_CR_HSERDY)) ; /* Now the PLL */ cr |= RCC_CR_PLLON; RCC_BASE->CR = cr; while (!(RCC_BASE->CR & RCC_CR_PLLRDY)) ; /* Finally, let's switch over to the PLL */ cfgr &= ~RCC_CFGR_SW; cfgr |= RCC_CFGR_SW_PLL; RCC_BASE->CFGR = cfgr; while ((RCC_BASE->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL) ; } /** * @brief Turn on the clock line on a peripheral * @param id Clock ID of the peripheral to turn on. */ void rcc_clk_enable(rcc_clk_id id) { static const __io uint32* enable_regs[] = { [APB1] = &RCC_BASE->APB1ENR, [APB2] = &RCC_BASE->APB2ENR, [AHB] = &RCC_BASE->AHBENR, }; rcc_clk_domain clk_domain = rcc_dev_clk(id); __io uint32* enr = (__io uint32*)enable_regs[clk_domain]; uint8 lnum = rcc_dev_table[id].line_num; bb_peri_set_bit(enr, lnum, 1); } /** * @brief Reset a peripheral. * @param id Clock ID of the peripheral to reset. */ void rcc_reset_dev(rcc_clk_id id) { static const __io uint32* reset_regs[] = { [APB1] = &RCC_BASE->APB1RSTR, [APB2] = &RCC_BASE->APB2RSTR, }; rcc_clk_domain clk_domain = rcc_dev_clk(id); __io void* addr = (__io void*)reset_regs[clk_domain]; uint8 lnum = rcc_dev_table[id].line_num; bb_peri_set_bit(addr, lnum, 1); bb_peri_set_bit(addr, lnum, 0); } /** * @brief Get a peripheral's clock domain * @param id Clock ID of the peripheral whose clock domain to return * @return Clock source for the given clock ID */ rcc_clk_domain rcc_dev_clk(rcc_clk_id id) { return rcc_dev_table[id].clk_domain; } /** * @brief Set the divider on a peripheral prescaler * @param prescaler prescaler to set * @param divider prescaler divider */ void rcc_set_prescaler(rcc_prescaler prescaler, uint32 divider) { static const uint32 masks[] = { [RCC_PRESCALER_AHB] = RCC_CFGR_HPRE, [RCC_PRESCALER_APB1] = RCC_CFGR_PPRE1, [RCC_PRESCALER_APB2] = RCC_CFGR_PPRE2, [RCC_PRESCALER_USB] = RCC_CFGR_USBPRE, [RCC_PRESCALER_ADC] = RCC_CFGR_ADCPRE, }; uint32 cfgr = RCC_BASE->CFGR; cfgr &= ~masks[prescaler]; cfgr |= divider; RCC_BASE->CFGR = cfgr; }