1 /**
2 * q931.cpp
3 * This file is part of the YATE Project http://YATE.null.ro
4 *
5 * Yet Another Signalling Stack - implements the support for SS7, ISDN and PSTN
6 *
7 * Yet Another Telephony Engine - a fully featured software PBX and IVR
8 * Copyright (C) 2004-2014 Null Team
9 *
10 * This software is distributed under multiple licenses;
11 * see the COPYING file in the main directory for licensing
12 * information for this specific distribution.
13 *
14 * This use of this software may be subject to additional restrictions.
15 * See the LEGAL file in the main directory for details.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 */
21
22 #include "yatesig.h"
23
24 #include <string.h>
25
26
27 using namespace TelEngine;
28
29 /**
30 * DEFINEs controlling Q.931 implementation
31 * Q931_ACCEPT_RESTART
32 * Controls acceptance of RESTART and RESTART ACK messages even if they don't have the global call reference
33 * Yes: Accept anyway
34 * No: Don't accept these messages if they don't have the global call reference
35 */
36 #ifndef Q931_ACCEPT_RESTART
37 // #define Q931_ACCEPT_RESTART
38 #endif
39
40 #define Q931_MSG_PROTOQ931 0x08 // Q.931 protocol discriminator in the message header
41
42 // Clear the bit 7 for each byte in a buffer
clearBit7(const void * buffer,u_int32_t len)43 static inline void clearBit7(const void* buffer, u_int32_t len)
44 {
45 u_int8_t* data = (u_int8_t*)buffer;
46 for (u_int32_t i = 0; i < len; i++)
47 data[i] &= 0x7f;
48 }
49
50 // Dump data to a given parameter of a named list. Clear bit 7 if requested
dumpDataBit7(NamedList * dest,const void * data,u_int32_t len,bool keepBit7=true,const char * name="unparsed-data")51 static inline void dumpDataBit7(NamedList* dest, const void* data, u_int32_t len,
52 bool keepBit7 = true, const char* name = "unparsed-data")
53 {
54 String tmp((const char*)data,len);
55 if (!keepBit7)
56 clearBit7(tmp.c_str(),tmp.length());
57 dest->addParam(name,tmp);
58 }
59
60 // Fill a message header. header parameter must be large enough to store message header
61 // Return header length
fillHeader(u_int8_t * header,ISDNQ931Message * msg,DebugEnabler * dbg)62 static inline u_int8_t fillHeader(u_int8_t* header, ISDNQ931Message* msg,
63 DebugEnabler* dbg)
64 {
65 header[0] = Q931_MSG_PROTOQ931;
66 // Dummy call reference ?
67 if (msg->dummyCallRef()) {
68 header[1] = 0;
69 header[2] = msg->type() & 0x7f; // Message type. Bit 7 must be 0
70 return 3;
71 }
72 // Check message's call reference length
73 if (!msg->callRefLen() || msg->callRefLen() > 4) {
74 Debug(dbg,DebugNote,
75 "Can't encode message (%p) with call reference length %u",
76 msg,msg->callRefLen());
77 return 0;
78 }
79 // Call reference length
80 header[1] = 0x0f & msg->callRefLen();
81 // Set call reference field
82 // For the initiator, bit 7 of the first byte of call reference must be 0
83 header[2] = msg->initiator() ? 0 : 0x80;
84 u_int8_t len = 2;
85 u_int8_t shift = msg->callRefLen() * 8;
86 do {
87 shift -= 8;
88 header[len++] |= (u_int8_t)(msg->callRef() >> shift);
89 }
90 while (shift);
91 // Set message type. Bit 7 must be 0
92 header[len++] = msg->type() & 0x7f;
93 return len;
94 }
95
96 /**
97 * IEParam
98 * Q.931 message IE parameter description
99 */
100 struct IEParam
101 {
102 public:
addParamIEParam103 inline const char* addParam(NamedList* dest, u_int8_t data,
104 const char* defVal = 0) const {
105 const char* tmp = lookup(data & mask,values,defVal);
106 if (tmp)
107 dest->addParam(name,tmp);
108 return tmp;
109 }
addBoolParamIEParam110 inline bool addBoolParam(NamedList* dest, u_int8_t data, bool toggle) const {
111 bool result = toggle ^ ((data & mask) != 0);
112 dest->addParam(name,String::boolText(result));
113 return result;
114 }
addIntParamIEParam115 inline void addIntParam(NamedList* dest, u_int8_t data) const {
116 if (!addParam(dest,data))
117 dest->addParam(name,String((unsigned int)(data & mask)));
118 }
119
dumpDataIEParam120 inline void dumpData(NamedList* dest, const u_int8_t* data, u_int32_t len) const
121 { SignallingUtils::dumpData(0,*dest,name,data,len); }
122
dumpDataBit7IEParam123 inline void dumpDataBit7(NamedList* dest, const u_int8_t* data, u_int32_t len,
124 bool keepBit7) const
125 { ::dumpDataBit7(dest,(const void*)data,len,keepBit7,name); }
126
getValueIEParam127 inline int getValue(NamedList* ns, bool applyMask = true, int defVal = 0) const {
128 int tmp = lookup(ns->getValue(name),values,defVal);
129 if (applyMask)
130 tmp &= mask;
131 return tmp;
132 }
133
134 const char* name;
135 u_int8_t mask;
136 const TokenDict* values;
137 };
138
139 /**
140 * Q931Parser
141 * Q.931 message encoder/decoder
142 */
143 class Q931Parser
144 {
145 public:
Q931Parser(ISDNQ931ParserData & data)146 inline Q931Parser(ISDNQ931ParserData& data)
147 : m_settings(&data), m_msg(0), m_codeset(0), m_activeCodeset(0), m_skip(false)
148 {}
149
150 // Decode received data.
151 // If the message is a SEGMENT decode only the header and the first IE.
152 // If valid, fill the buffer with the rest of the message. If segData is 0, drop the message.
153 // @param segData Segment message data
154 // @return Valid ISDNQ931Message pointer on success or 0.
155 ISDNQ931Message* decode(const DataBlock& buffer, DataBlock* segData);
156
157 // Encode a message.
158 // If the message is longer then max allowed and segmentation is allowed, split it into SEGMENT messages
159 // Failure reasons:
160 // Message too long and segmentation not allowed
161 // Message too long, segmentation allowed, but too many segments
162 // @param msg The message to encode.
163 // @param dest List of DataBlock with the message segments.
164 // @return The number of segments on success or 0 on failure.
165 u_int8_t encode(ISDNQ931Message* msg, ObjList& dest);
166
167 // Field names
168 static const TokenDict s_dict_congestion[];
169 static const TokenDict s_dict_bearerTransCap[];
170 static const TokenDict s_dict_bearerTransMode[];
171 static const TokenDict s_dict_bearerTransRate[];
172 static const TokenDict s_dict_bearerProto1[];
173 static const TokenDict s_dict_bearerProto2[];
174 static const TokenDict s_dict_bearerProto3[];
175 static const TokenDict s_dict_typeOfNumber[];
176 static const TokenDict s_dict_numPlan[];
177 static const TokenDict s_dict_presentation[];
178 static const TokenDict s_dict_screening[];
179 static const TokenDict s_dict_subaddrType[];
180 static const TokenDict s_dict_channelIDSelect_BRI[];
181 static const TokenDict s_dict_channelIDSelect_PRI[];
182 static const TokenDict s_dict_channelIDUnits[];
183 static const TokenDict s_dict_loLayerProto2[];
184 static const TokenDict s_dict_loLayerProto3[];
185 static const TokenDict s_dict_networkIdType[];
186 static const TokenDict s_dict_networkIdPlan[];
187 static const TokenDict s_dict_notification[];
188 static const TokenDict s_dict_progressDescr[];
189 static const TokenDict s_dict_restartClass[];
190 static const TokenDict s_dict_signalValue[];
191
192 private:
193 // Encode a full message. Parameter ieEncoded is true if the IEs buffers are already filled
194 // Check if the message fits the maximum length
195 // Return 1 on success and 0 on failure
196 u_int8_t encodeMessage(ObjList& dest, bool ieEncoded,
197 u_int8_t* header, u_int8_t headerLen);
198 // Encode each IE into it's buffer
199 // Check if the largest buffer fits the maximum message length
200 bool encodeIEList(bool& segmented, u_int8_t headerLen);
201 // Append a segment buffer to a list. Increase the segment counter
202 // Check if the counter is valid (don't exceed the maximum segments count)
203 bool appendSegment(ObjList& dest, DataBlock* segment, u_int8_t& count);
204 // Reset data. Returns the message
reset()205 inline ISDNQ931Message* reset() {
206 ISDNQ931Message* msg = m_msg;
207 m_msg = 0;
208 m_activeCodeset = m_codeset = 0;
209 return msg;
210 }
211 // Reset data. Returns the value
reset(u_int8_t val)212 inline u_int8_t reset(u_int8_t val) {
213 m_msg = 0;
214 m_activeCodeset = m_codeset = 0;
215 return val;
216 }
217 // Encode an IE to a buffer
218 // Return false on failure
219 bool encodeIE(ISDNQ931IE* ie, DataBlock& buffer);
220 // Add an error parameter to a given IE
221 ISDNQ931IE* errorParseIE(ISDNQ931IE* ie, const char* reason,
222 const u_int8_t* data, u_int32_t len);
223 // Check the encoding a given IE. Before checking apply a 0x60 mask
224 // Add a parameter if the check fails
225 bool checkCoding(u_int8_t value, u_int8_t expected, ISDNQ931IE* ie);
226 // Skip data until an element with bit 7 (0/1 ext) set is found. Skip this one too
227 // Parameter 'crt' is modified in the process. On exit points to the element which won't be skipped
228 // Return the number of element to skip
229 u_int8_t skipExt(const u_int8_t* data, u_int8_t len, u_int8_t& crt);
230 // Parse the received data to get the message header. Create message on success
231 // @return False to stop the parser
232 bool createMessage(u_int8_t* data, u_int32_t len);
233 // Process received Segment message
234 ISDNQ931Message* processSegment(const u_int8_t* data, u_int32_t len,
235 DataBlock* segData);
236 // Parse the received data to get an IE
237 // @param data The data to parse
238 // @param len Data length
239 // @param consumed The number of bytes consumed by the IE
240 // @return Pointer to a valid IE or 0 to stop the parser
241 ISDNQ931IE* getIE(const u_int8_t* data, u_int32_t len, u_int32_t& consumed);
242 // Constructs a fixed (1 byte) length IE
243 // @param data The data
244 // @return Valid ISDNQ931IE pointer
245 ISDNQ931IE* getFixedIE(u_int8_t data);
246 // Shift the codeset while parsing
247 // @param ie Pointer to a valid ISDNQ931IE of type Shift
248 void shiftCodeset(const ISDNQ931IE* ie);
249 // Common methods for decoding Bearer capabilities and Low layer compatibility
250 void decodeLayer1(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len,
251 u_int8_t& crt, const IEParam* ieParam, u_int8_t ieParamIdx);
252 void decodeLayer2(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len,
253 u_int8_t& crt, const IEParam* ieParam, u_int8_t ieParamIdx);
254 void decodeLayer3(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len,
255 u_int8_t& crt, const IEParam* ieParam, u_int8_t ieParamIdx);
256 // Decode the corresponding variable IE
257 ISDNQ931IE* decodeBearerCaps(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
258 ISDNQ931IE* decodeCallIdentity(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
259 ISDNQ931IE* decodeCallState(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
260 ISDNQ931IE* decodeChannelID(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
261 ISDNQ931IE* decodeProgress(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
262 ISDNQ931IE* decodeNetFacility(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
263 ISDNQ931IE* decodeNotification(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
264 ISDNQ931IE* decodeDisplay(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
265 ISDNQ931IE* decodeDateTime(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
266 ISDNQ931IE* decodeKeypad(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
267 ISDNQ931IE* decodeSignal(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
268 ISDNQ931IE* decodeCallingNo(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
269 ISDNQ931IE* decodeCallingSubAddr(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
270 ISDNQ931IE* decodeCalledNo(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
271 ISDNQ931IE* decodeCalledSubAddr(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
272 ISDNQ931IE* decodeRestart(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
273 ISDNQ931IE* decodeSegmented(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
274 ISDNQ931IE* decodeNetTransit(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
275 ISDNQ931IE* decodeLoLayerCompat(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
276 ISDNQ931IE* decodeHiLayerCompat(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
277 ISDNQ931IE* decodeUserUser(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len);
278 // It seems that the Connected number has the same layout as the Calling number IE
decodeConnectedNo(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)279 inline ISDNQ931IE* decodeConnectedNo(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len)
280 { return decodeCallingNo(ie,data,len); }
281 // Encode the corresponding variable IE
282 bool encodeBearerCaps(ISDNQ931IE* ie, DataBlock& buffer);
283 bool encodeCallState(ISDNQ931IE* ie, DataBlock& buffer);
284 bool encodeChannelID(ISDNQ931IE* ie, DataBlock& buffer);
285 bool encodeDisplay(ISDNQ931IE* ie, DataBlock& buffer);
286 bool encodeCallingNo(ISDNQ931IE* ie, DataBlock& buffer);
287 bool encodeCalledNo(ISDNQ931IE* ie, DataBlock& buffer);
288 bool encodeProgress(ISDNQ931IE* ie, DataBlock& buffer);
289 bool encodeNotification(ISDNQ931IE* ie, DataBlock& buffer);
290 bool encodeKeypad(ISDNQ931IE* ie, DataBlock& buffer);
291 bool encodeSignal(ISDNQ931IE* ie, DataBlock& buffer);
292 bool encodeRestart(ISDNQ931IE* ie, DataBlock& buffer);
293 bool encodeSendComplete(ISDNQ931IE* ie, DataBlock& buffer);
294 bool encodeHighLayerCap(ISDNQ931IE* ie, DataBlock& buffer);
295 bool encodeUserUser(ISDNQ931IE* ie, DataBlock& buffer);
296
297 ISDNQ931ParserData* m_settings; // Settings
298 ISDNQ931Message* m_msg; // Current encoded/decoded message
299 u_int8_t m_codeset; // Current codeset
300 u_int8_t m_activeCodeset; // Active codeset
301 bool m_skip; // Skip current IE
302 };
303
304
305 /**
306 * ISDNQ931IEData
307 */
ISDNQ931IEData(bool bri)308 ISDNQ931IEData::ISDNQ931IEData(bool bri)
309 : m_bri(bri),
310 m_channelMandatory(true),
311 m_channelByNumber(true)
312 {
313 }
314
processBearerCaps(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)315 bool ISDNQ931IEData::processBearerCaps(ISDNQ931Message* msg, bool add,
316 ISDNQ931ParserData* data)
317 {
318 if (!msg)
319 return false;
320 if (add) {
321 ISDNQ931IE* ie = new ISDNQ931IE(ISDNQ931IE::BearerCaps);
322 ie->addParam("transfer-cap",m_transferCapability);
323 ie->addParam("transfer-mode",m_transferMode);
324 ie->addParam("transfer-rate",m_transferRate);
325 ie->addParam("layer1-protocol",m_format);
326 // Q.931 Table 4.6: Send Layer 2/3 only in 'packet switching' (0x40) mode
327 if (m_transferMode == lookup(0x40,Q931Parser::s_dict_bearerTransMode)) {
328 ie->addParam("layer2-protocol","q921");
329 ie->addParam("layer3-protocol","q931");
330 }
331 msg->appendSafe(ie);
332 return true;
333 }
334 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::BearerCaps);
335 if (!ie) {
336 m_transferCapability = "";
337 m_transferMode = "";
338 m_transferRate = "";
339 return false;
340 }
341 m_transferCapability = ie->getValue(YSTRING("transfer-cap"));
342 m_transferMode = ie->getValue(YSTRING("transfer-mode"));
343 m_transferRate = ie->getValue(YSTRING("transfer-rate"));
344 m_format = ie->getValue(YSTRING("layer1-protocol"));
345 return true;
346 }
347
processChannelID(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)348 bool ISDNQ931IEData::processChannelID(ISDNQ931Message* msg, bool add,
349 ISDNQ931ParserData* data)
350 {
351 if (!msg)
352 return false;
353 if (add) {
354 ISDNQ931IE* ie = new ISDNQ931IE(ISDNQ931IE::ChannelID);
355 ie->addParam("interface-bri",String::boolText(m_bri));
356 ie->addParam("channel-exclusive",String::boolText(m_channelMandatory));
357 ie->addParam("channel-select",m_channelSelect);
358 ie->addParam("type",m_channelType);
359 ie->addParam("channel-by-number",String::boolText(true));
360 ie->addParam("channels",m_channels);
361 msg->appendSafe(ie);
362 return true;
363 }
364 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::ChannelID);
365 m_channels = "";
366 if (!ie) {
367 m_channelMandatory = m_channelByNumber = false;
368 return false;
369 }
370 m_bri = ie->getBoolValue(YSTRING("interface-bri"),m_bri);
371 m_channelMandatory = ie->getBoolValue(YSTRING("channel-exclusive"));
372 m_channelByNumber = ie->getBoolValue(YSTRING("channel-by-number"));
373 m_channelType = ie->getValue(YSTRING("type"));
374 m_channelSelect = ie->getValue(YSTRING("channel-select"));
375 if (m_bri && m_channelSelect) {
376 m_channelByNumber = true;
377 if (m_channelSelect == "b1")
378 m_channels = "1";
379 else if (m_channelSelect == "b2")
380 m_channels = "2";
381 else
382 return false;
383 }
384 // ChannelID IE may repeat if channel is given by number
385 if (m_channelByNumber) {
386 unsigned int n = ie->length();
387 for (unsigned int i = 0; i < n; i++) {
388 NamedString* ns = ie->getParam(i);
389 if (ns && (ns->name() == YSTRING("channels")))
390 m_channels.append(*ns,",");
391 }
392 }
393 else
394 m_channels = ie->getValue(YSTRING("slot-map"));
395 return true;
396 }
397
processProgress(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)398 bool ISDNQ931IEData::processProgress(ISDNQ931Message* msg, bool add,
399 ISDNQ931ParserData* data)
400 {
401 if (!msg)
402 return false;
403 if (add) {
404 // Remove non-isdn-source/non-isdn-destination
405 if (data) {
406 if (!data->flag(ISDNQ931::SendNonIsdnSource))
407 SignallingUtils::removeFlag(m_progress,"non-isdn-source");
408 if (data->flag(ISDNQ931::IgnoreNonIsdnDest))
409 SignallingUtils::removeFlag(m_progress,"non-isdn-destination");
410 }
411 if (!m_progress.null())
412 msg->appendIEValue(ISDNQ931IE::Progress,"description",m_progress);
413 }
414 else {
415 // Progress may repeat
416 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::Progress);
417 for (; ie; ie = msg->getIE(ISDNQ931IE::Progress,ie))
418 m_progress.append(ie->getValue(YSTRING("description")),",");
419 }
420 return !m_progress.null();
421 }
422
processRestart(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)423 bool ISDNQ931IEData::processRestart(ISDNQ931Message* msg, bool add,
424 ISDNQ931ParserData* data)
425 {
426 if (!msg)
427 return false;
428 if (add) {
429 msg->appendIEValue(ISDNQ931IE::Restart,"class",m_restart);
430 return true;
431 }
432 m_restart = msg->getIEValue(ISDNQ931IE::Restart,"class");
433 return !m_restart.null();
434 }
435
processNotification(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)436 bool ISDNQ931IEData::processNotification(ISDNQ931Message* msg, bool add,
437 ISDNQ931ParserData* data)
438 {
439 if (!msg)
440 return false;
441 if (add) {
442 if (data && data->flag(ISDNQ931::CheckNotifyInd)) {
443 int val = lookup(m_notification,Q931Parser::s_dict_notification,-1);
444 if (val < 0 && val > 2)
445 return false;
446 }
447 msg->appendIEValue(ISDNQ931IE::Notification,"notification",m_notification);
448 return true;
449 }
450 m_notification = msg->getIEValue(ISDNQ931IE::Notification,"notification");
451 return !m_notification.null();
452 }
453
processCalledNo(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)454 bool ISDNQ931IEData::processCalledNo(ISDNQ931Message* msg, bool add,
455 ISDNQ931ParserData* data)
456 {
457 if (!msg)
458 return false;
459 if (add) {
460 ISDNQ931IE* ie = new ISDNQ931IE(ISDNQ931IE::CalledNo);
461 ie->addParam("number",m_calledNo);
462 if (!m_callerType.null())
463 ie->addParam("type",m_calledType);
464 if (!m_callerPlan.null())
465 ie->addParam("plan",m_calledPlan);
466 msg->appendSafe(ie);
467 return true;
468 }
469 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::CalledNo);
470 if (!ie) {
471 m_calledNo = "";
472 return false;
473 }
474 m_calledNo = ie->getValue(YSTRING("number"));
475 m_calledType = ie->getValue(YSTRING("type"));
476 m_calledPlan = ie->getValue(YSTRING("plan"));
477 return true;
478 }
479
processCallingNo(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)480 bool ISDNQ931IEData::processCallingNo(ISDNQ931Message* msg, bool add,
481 ISDNQ931ParserData* data)
482 {
483 if (!msg)
484 return false;
485 if (add) {
486 if (!m_callerNo)
487 return false;
488 ISDNQ931IE* ie = new ISDNQ931IE(ISDNQ931IE::CallingNo);
489 ie->addParam("number",m_callerNo);
490 if (!m_callerType.null())
491 ie->addParam("type",m_callerType);
492 if (!m_callerPlan.null())
493 ie->addParam("plan",m_callerPlan);
494 if (data && data->flag(ISDNQ931::ForcePresNetProv)) {
495 ie->addParam("presentation",lookup(0x00,Q931Parser::s_dict_presentation));
496 ie->addParam("screening",lookup(0x03,Q931Parser::s_dict_screening));
497 }
498 else {
499 ie->addParam("presentation",m_callerPres);
500 ie->addParam("screening",m_callerScreening);
501 }
502 msg->appendSafe(ie);
503 return true;
504 }
505 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::CallingNo);
506 if (!ie) {
507 m_callerNo = "";
508 return false;
509 }
510 m_callerNo = ie->getValue(YSTRING("number"));
511 m_callerType = ie->getValue(YSTRING("type"));
512 m_callerPlan = ie->getValue(YSTRING("plan"));
513 m_callerPres = ie->getValue(YSTRING("presentation"));
514 m_callerScreening = ie->getValue(YSTRING("screening"));
515 return true;
516 }
517
processCause(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)518 bool ISDNQ931IEData::processCause(ISDNQ931Message* msg, bool add,
519 ISDNQ931ParserData* data)
520 {
521 if (!msg)
522 return false;
523 if (add) {
524 msg->appendIEValue(ISDNQ931IE::Cause,0,m_reason?m_reason:"normal-clearing");
525 return true;
526 }
527 m_reason = msg->getIEValue(ISDNQ931IE::Cause,0);
528 return !m_reason.null();
529 }
530
processDisplay(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)531 bool ISDNQ931IEData::processDisplay(ISDNQ931Message* msg, bool add,
532 ISDNQ931ParserData* data)
533 {
534 if (!msg)
535 return false;
536 if (add) {
537 if (m_display.null() || !data || data->flag(ISDNQ931::NoDisplayIE))
538 return false;
539 msg->appendIEValue(ISDNQ931IE::Display,"display",m_display);
540 return true;
541 }
542 m_display = msg->getIEValue(ISDNQ931IE::Display,"display");
543 return !m_display.null();
544 }
545
processKeypad(ISDNQ931Message * msg,bool add,ISDNQ931ParserData * data)546 bool ISDNQ931IEData::processKeypad(ISDNQ931Message* msg, bool add,
547 ISDNQ931ParserData* data)
548 {
549 if (!msg)
550 return false;
551 if (add) {
552 msg->appendIEValue(ISDNQ931IE::Keypad,"keypad",m_keypad);
553 return true;
554 }
555 m_keypad = msg->getIEValue(ISDNQ931IE::Keypad,"keypad");
556 return !m_keypad.null();
557 }
558
559 /**
560 * ISDNQ931State
561 */
562 const TokenDict ISDNQ931State::s_states[] = {
563 {"Null", Null},
564 {"CallInitiated", CallInitiated},
565 {"OverlapSend", OverlapSend},
566 {"OutgoingProceeding", OutgoingProceeding},
567 {"CallDelivered", CallDelivered},
568 {"CallPresent", CallPresent},
569 {"CallReceived", CallReceived},
570 {"ConnectReq", ConnectReq},
571 {"IncomingProceeding", IncomingProceeding},
572 {"Active", Active},
573 {"DisconnectReq", DisconnectReq},
574 {"DisconnectIndication", DisconnectIndication},
575 {"SuspendReq", SuspendReq},
576 {"ResumeReq", ResumeReq},
577 {"ReleaseReq", ReleaseReq},
578 {"CallAbort", CallAbort},
579 {"OverlapRecv", OverlapRecv},
580 {"RestartReq", RestartReq},
581 {"Restart", Restart},
582 {0,0}
583 };
584
checkStateRecv(int type,bool * retrans)585 bool ISDNQ931State::checkStateRecv(int type, bool* retrans)
586 {
587 #define STATE_CHECK_RETRANS(st) \
588 if (state() == st) { \
589 if (retrans) \
590 *retrans = true; \
591 return false; \
592 }
593 switch (type) {
594 case ISDNQ931Message::Setup:
595 STATE_CHECK_RETRANS(CallPresent)
596 if (state() != Null)
597 break;
598 return true;
599 case ISDNQ931Message::SetupAck:
600 STATE_CHECK_RETRANS(OverlapSend)
601 if (state() != CallInitiated)
602 break;
603 return true;
604 case ISDNQ931Message::Proceeding:
605 STATE_CHECK_RETRANS(OutgoingProceeding)
606 if (state() != CallInitiated && state() != OverlapSend)
607 break;
608 return true;
609 case ISDNQ931Message::Alerting:
610 STATE_CHECK_RETRANS(CallDelivered)
611 if (state() != CallInitiated && state() != OutgoingProceeding)
612 break;
613 return true;
614 case ISDNQ931Message::Connect:
615 STATE_CHECK_RETRANS(Active)
616 if (state() != CallInitiated && state() != OutgoingProceeding &&
617 state() != CallDelivered)
618 break;
619 return true;
620 case ISDNQ931Message::ConnectAck:
621 STATE_CHECK_RETRANS(Active)
622 if (state() != ConnectReq && state() != Active)
623 break;
624 return true;
625 case ISDNQ931Message::Disconnect:
626 STATE_CHECK_RETRANS(DisconnectIndication)
627 switch (state()) {
628 case CallInitiated:
629 case OutgoingProceeding:
630 case CallDelivered:
631 case CallPresent:
632 case CallReceived:
633 case ConnectReq:
634 case IncomingProceeding:
635 case Active:
636 case OverlapSend:
637 return true;
638 default: ;
639 }
640 break;
641 default:
642 if (state() == Null)
643 break;
644 return true;
645 }
646 return false;
647 #undef STATE_CHECK_RETRANS
648 }
649
checkStateSend(int type)650 bool ISDNQ931State::checkStateSend(int type)
651 {
652 switch (type) {
653 case ISDNQ931Message::Setup:
654 if (state() != Null)
655 break;
656 return true;
657 case ISDNQ931Message::SetupAck:
658 if (state() != CallPresent)
659 break;
660 return true;
661 case ISDNQ931Message::Proceeding:
662 if (state() != CallPresent && state() != OverlapRecv)
663 break;
664 return true;
665 case ISDNQ931Message::Alerting:
666 if (state() != CallPresent && state() != IncomingProceeding)
667 break;
668 return true;
669 case ISDNQ931Message::Connect:
670 if (state() != CallPresent && state() != IncomingProceeding &&
671 state() != CallReceived)
672 break;
673 return true;
674 case ISDNQ931Message::Disconnect:
675 switch (state()) {
676 case OutgoingProceeding:
677 case CallDelivered:
678 case CallPresent:
679 case CallReceived:
680 case ConnectReq:
681 case IncomingProceeding:
682 case Active:
683 case OverlapSend:
684 return true;
685 default: ;
686 }
687 break;
688 case ISDNQ931Message::Progress:
689 if (state() != CallPresent && state() != CallReceived &&
690 state() != IncomingProceeding)
691 break;
692 return true;
693 default:
694 if (state() == Null)
695 break;
696 return true;
697 }
698 return false;
699 }
700
701 /**
702 * ISDNQ931Call
703 */
704 #define Q931_CALL_ID this->outgoing(),this->callRef()
705
ISDNQ931Call(ISDNQ931 * controller,bool outgoing,u_int32_t callRef,u_int8_t callRefLen,u_int8_t tei)706 ISDNQ931Call::ISDNQ931Call(ISDNQ931* controller, bool outgoing,
707 u_int32_t callRef, u_int8_t callRefLen, u_int8_t tei)
708 : SignallingCall(controller,outgoing),
709 m_callRef(callRef),
710 m_callRefLen(callRefLen),
711 m_tei(tei),
712 m_circuit(0),
713 m_circuitChange(false),
714 m_channelIDSent(false),
715 m_rspBearerCaps(false),
716 m_inbandAvailable(false),
717 m_net(false),
718 m_data(controller && !controller->primaryRate()),
719 m_discTimer(0),
720 m_relTimer(0),
721 m_conTimer(0),
722 m_overlapSendTimer(0),
723 m_overlapRecvTimer(0),
724 m_retransSetupTimer(0),
725 m_terminate(false),
726 m_destroy(false),
727 m_destroyed(false)
728 {
729 Debug(q931(),DebugAll,"Call(%u,%u) direction=%s TEI=%u [%p]",
730 Q931_CALL_ID,(outgoing ? "outgoing" : "incoming"),tei,this);
731 for (u_int8_t i = 0; i < 127; i++)
732 m_broadcast[i] = false;
733 if (!controller) {
734 Debug(DebugWarn,"ISDNQ931Call(%u,%u). No call controller. Terminate [%p]",
735 Q931_CALL_ID,this);
736 m_terminate = m_destroy = true;
737 m_data.m_reason = "temporary-failure";
738 return;
739 }
740 m_net = q931() && q931()->network();
741 // Init timers
742 q931()->setInterval(m_discTimer,305);
743 q931()->setInterval(m_relTimer,308);
744 q931()->setInterval(m_conTimer,313);
745 m_overlapSendTimer.interval(10000);
746 m_overlapRecvTimer.interval(20000);
747 m_retransSetupTimer.interval(1000);
748 if (outgoing)
749 reserveCircuit();
750 }
751
~ISDNQ931Call()752 ISDNQ931Call::~ISDNQ931Call()
753 {
754 q931()->releaseCircuit(m_circuit);
755 if (state() != Null)
756 sendReleaseComplete("temporary-failure");
757 Debug(q931(),DebugAll,"Call(%u,%u) destroyed with reason '%s' [%p]",
758 Q931_CALL_ID,m_data.m_reason.c_str(),this);
759 }
760
761 // Set terminate flags and reason
setTerminate(bool destroy,const char * reason)762 void ISDNQ931Call::setTerminate(bool destroy, const char* reason)
763 {
764 Lock mylock(this);
765 if (m_destroyed)
766 return;
767 if (state() == CallAbort)
768 changeState(Null);
769 // Check terminate & destroy flags
770 if (m_terminate && destroy == m_destroy)
771 return;
772 m_terminate = true;
773 m_destroy = destroy;
774 if (m_data.m_reason.null())
775 m_data.m_reason = reason;
776 DDebug(q931(),DebugInfo,"Call(%u,%u). Set terminate. Destroy: %s [%p]",
777 Q931_CALL_ID,String::boolText(m_destroy),this);
778 }
779
780 // Send an event
sendEvent(SignallingEvent * event)781 bool ISDNQ931Call::sendEvent(SignallingEvent* event)
782 {
783 if (!event)
784 return false;
785 Lock mylock(this);
786 DDebug(q931(),DebugAll,"Call(%u,%u). sendEvent(%s) state=%s [%p]",
787 Q931_CALL_ID,event->name(),stateName(state()),this);
788 if (m_terminate || state() == CallAbort) {
789 mylock.drop();
790 delete event;
791 return false;
792 }
793 bool retVal = false;
794 switch (event->type()) {
795 case SignallingEvent::Progress:
796 retVal = sendProgress(event->message());
797 break;
798 case SignallingEvent::Ringing:
799 retVal = sendAlerting(event->message());
800 break;
801 case SignallingEvent::Accept:
802 if (m_overlap) {
803 sendSetupAck();
804 m_overlap = false;
805 break;
806 }
807 changeState(CallPresent);
808 retVal = sendCallProceeding(event->message());
809 break;
810 case SignallingEvent::Answer:
811 changeState(CallPresent);
812 retVal = sendConnect(event->message());
813 break;
814 case SignallingEvent::Release:
815 switch (state()) {
816 case DisconnectIndication:
817 retVal = sendRelease(0,event->message());
818 break;
819 case OutgoingProceeding:
820 case CallDelivered:
821 case CallPresent:
822 case CallReceived:
823 case ConnectReq:
824 case IncomingProceeding:
825 case Active:
826 retVal = sendDisconnect(event->message());
827 break;
828 case Null:
829 case ReleaseReq:
830 case CallAbort:
831 // Schedule destroy
832 m_terminate = m_destroy = true;
833 mylock.drop();
834 delete event;
835 return false;
836 default:
837 m_terminate = m_destroy = true;
838 retVal = sendReleaseComplete(event->message() ?
839 event->message()->params().getValue(YSTRING("reason")) : 0);
840 break;
841 }
842 break;
843 case SignallingEvent::Info:
844 retVal = sendInfo(event->message());
845 break;
846 case SignallingEvent::NewCall:
847 retVal = sendSetup(event->message());
848 break;
849 default:
850 Debug(q931(),DebugStub,
851 "Call(%u,%u). sendEvent not implemented for event '%s' [%p]",
852 Q931_CALL_ID,event->name(),this);
853 }
854 mylock.drop();
855 delete event;
856 return retVal;
857 }
858
859 // Process received messages. Generate events from them
860 // Get events from reserved circuit when no call event
getEvent(const Time & when)861 SignallingEvent* ISDNQ931Call::getEvent(const Time& when)
862 {
863 Lock mylock(this);
864 // Check for last event or destroyed/aborting
865 if (m_lastEvent || m_destroyed || state() == CallAbort)
866 return 0;
867 while (true) {
868 // Check for incoming messages
869 ISDNQ931Message* msg = static_cast<ISDNQ931Message*>(dequeue());
870 // No message: check terminate and timeouts. Try to get a circuit event
871 if (!msg) {
872 if (m_terminate)
873 m_lastEvent = processTerminate();
874 if (!m_lastEvent)
875 m_lastEvent = checkTimeout(when.msec());
876 if (!m_lastEvent)
877 m_lastEvent = getCircuitEvent(when);
878 break;
879 }
880 XDebug(q931(),DebugAll,
881 "Call(%u,%u). Dequeued message (%p): '%s' in state '%s' [%p]",
882 Q931_CALL_ID,msg,msg->name(),stateName(state()),this);
883 // Check for unknown madatory IE. See Q.931 7.8.7.1
884 if (msg->unknownMandatory()) {
885 Debug(q931(),DebugWarn,
886 "Call(%u,%u). Received message (%p): '%s' with unknown mandatory IE [%p]",
887 Q931_CALL_ID,msg,msg->name(),this);
888 TelEngine::destruct(msg);
889 m_lastEvent = releaseComplete("missing-mandatory-ie");
890 break;
891 }
892 switch (msg->type()) {
893 #define Q931_CALL_PROCESS_MSG(type,method) \
894 case type: \
895 m_lastEvent = !m_terminate ? method(msg) : processTerminate(msg); \
896 break;
897 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Alerting,processMsgAlerting)
898 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Proceeding,processMsgCallProceeding)
899 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Connect,processMsgConnect)
900 Q931_CALL_PROCESS_MSG(ISDNQ931Message::ConnectAck,processMsgConnectAck)
901 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Disconnect,processMsgDisconnect)
902 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Info,processMsgInfo)
903 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Notify,processMsgNotify)
904 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Progress,processMsgProgress)
905 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Release,processMsgRelease)
906 Q931_CALL_PROCESS_MSG(ISDNQ931Message::ReleaseComplete,processMsgRelease)
907 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Setup,processMsgSetup)
908 Q931_CALL_PROCESS_MSG(ISDNQ931Message::SetupAck,processMsgSetupAck)
909 Q931_CALL_PROCESS_MSG(ISDNQ931Message::Status,processMsgStatus)
910 Q931_CALL_PROCESS_MSG(ISDNQ931Message::StatusEnquiry,processMsgStatusEnquiry)
911 #undef Q931_CALL_PROCESS_MSG
912 case ISDNQ931Message::Suspend:
913 sendSuspendRej("service-not-implemented",0);
914 break;
915 case ISDNQ931Message::Resume:
916 q931()->sendStatus(this,"no-call-suspended",callTei());
917 break;
918 case ISDNQ931Message::SuspendAck:
919 case ISDNQ931Message::SuspendRej:
920 case ISDNQ931Message::ResumeAck:
921 case ISDNQ931Message::ResumeRej:
922 q931()->sendStatus(this,"wrong-state-message",callTei());
923 break;
924 default:
925 DDebug(q931(),DebugNote,
926 "Call(%u,%u). Received unknown/not implemented message '%s'. Sending status [%p]",
927 Q931_CALL_ID,msg->name(),this);
928 q931()->sendStatus(this,"unknown-message",callTei());
929 // Fall through to destruct the message and check timeouts
930 }
931 TelEngine::destruct(msg);
932 if (!m_lastEvent)
933 m_lastEvent = checkTimeout(when.msec());
934 if (!m_lastEvent)
935 m_lastEvent = getCircuitEvent(when);
936 break;
937 }
938 if (!m_lastEvent)
939 return 0;
940 XDebug(q931(),DebugInfo,"Call(%u,%u). Raising event '%s' state=%s [%p]",
941 Q931_CALL_ID,m_lastEvent->name(),stateName(state()),this);
942 return m_lastEvent;
943 }
944
945 // Get reserved circuit or this object
getObject(const String & name) const946 void* ISDNQ931Call::getObject(const String& name) const
947 {
948 if (name == YSTRING("SignallingCircuit"))
949 return m_circuit;
950 if (name == YSTRING("ISDNQ931Call"))
951 return (void*)this;
952 return SignallingCall::getObject(name);
953 }
954
955 // Data link change state notification from call controller
956 // Set termination flag. Send status if link is up
dataLinkState(bool up)957 void ISDNQ931Call::dataLinkState(bool up)
958 {
959 Lock mylock(this);
960 // Q.931 5.8.9. Terminate if not up and not in the active state
961 if (!up) {
962 if (state() != ISDNQ931Call::Active)
963 setTerminate(true,"net-out-of-order");
964 return;
965 }
966 // Q.931 5.8.8 Terminate in state OverlapSend and OverlapRecv
967 if (state() == ISDNQ931Call::OverlapSend ||
968 state() == ISDNQ931Call::OverlapRecv) {
969 setTerminate(true,"temporary-failure");
970 }
971 q931()->sendStatus(this,"normal",callTei());
972 }
973
974 // Process termination flags or requests (messages)
processTerminate(ISDNQ931Message * msg)975 SignallingEvent* ISDNQ931Call::processTerminate(ISDNQ931Message* msg)
976 {
977 XDebug(q931(),DebugAll,"Call(%u,%u). processTerminate(%s) state=%s [%p]",
978 Q931_CALL_ID,msg?msg->name():"",stateName(state()),this);
979 bool complete = m_destroy;
980 // We don't have to destroy and not send/received Release: Send Release
981 if (!m_destroy && state() != ReleaseReq && state() != DisconnectReq)
982 complete = false;
983 // Message is Release/ReleaseComplete: terminate
984 if (msg) {
985 if (msg->type() == ISDNQ931Message::Release ||
986 msg->type() == ISDNQ931Message::ReleaseComplete) {
987 changeState(Null);
988 m_data.processCause(msg,false);
989 complete = true;
990 }
991 else
992 DDebug(q931(),DebugNote,
993 "Call(%u,%u). Dropping received message '%s' while terminating [%p]",
994 Q931_CALL_ID,msg->name(),this);
995 }
996 if (complete)
997 return releaseComplete();
998 sendRelease("normal-clearing");
999 return 0;
1000 }
1001
1002 // Check message timeout for Connect, Disconnect, Release, Setup
checkTimeout(u_int64_t time)1003 SignallingEvent* ISDNQ931Call::checkTimeout(u_int64_t time)
1004 {
1005 #define CALL_TIMEOUT_DEBUG(info) \
1006 DDebug(q931(),DebugNote, \
1007 "Call(%u,%u). %s request timed out in state '%s' [%p]", \
1008 Q931_CALL_ID,info,stateName(state()),this);
1009 static const char* reason = "timeout";
1010 switch (state()) {
1011 case DisconnectReq:
1012 if (!m_discTimer.timeout(time))
1013 break;
1014 CALL_TIMEOUT_DEBUG("Disconnect")
1015 m_discTimer.stop();
1016 sendRelease(reason);
1017 break;
1018 case ReleaseReq:
1019 if (!m_relTimer.timeout(time))
1020 break;
1021 CALL_TIMEOUT_DEBUG("Release")
1022 m_relTimer.stop();
1023 changeState(Null);
1024 return releaseComplete(reason);
1025 case ConnectReq:
1026 if (!m_conTimer.timeout(time))
1027 break;
1028 CALL_TIMEOUT_DEBUG("Connect")
1029 m_conTimer.stop();
1030 m_data.m_reason = reason;
1031 sendDisconnect(0);
1032 break;
1033 case CallInitiated:
1034 if (!m_retransSetupTimer.timeout(time))
1035 break;
1036 CALL_TIMEOUT_DEBUG("Setup")
1037 m_retransSetupTimer.stop();
1038 m_data.m_reason = reason;
1039 return releaseComplete(reason);
1040 case OverlapSend:
1041 if (!m_overlapSendTimer.timeout(time)) {
1042 m_overlapSendTimer.stop();
1043 m_overlapSendTimer.start();
1044 }
1045 break;
1046 default: ;
1047 }
1048 return 0;
1049 #undef CALL_TIMEOUT_DEBUG
1050 }
1051
1052 // Check received messages for appropriate state or retransmission
1053 // Send status if not accepted and requested by the caller
checkMsgRecv(ISDNQ931Message * msg,bool status)1054 bool ISDNQ931Call::checkMsgRecv(ISDNQ931Message* msg, bool status)
1055 {
1056 bool retrans = false;
1057 if (checkStateRecv(msg->type(),&retrans))
1058 return true;
1059 if (retrans)
1060 XDebug(q931(),DebugAll,
1061 "Call(%u,%u). Dropping '%s' retransmission in state '%s' [%p]",
1062 Q931_CALL_ID,msg->name(),stateName(state()),this);
1063 else {
1064 Debug(q931(),DebugNote,
1065 "Call(%u,%u). Received '%s'. Invalid in state '%s'. Drop [%p]",
1066 Q931_CALL_ID,msg->name(),stateName(state()),this);
1067 if (status && state() != Null)
1068 q931()->sendStatus(this,"wrong-state-message",callTei());
1069 }
1070 return false;
1071 }
1072
1073 // Process ALERTING. See Q.931 3.1.1
1074 // IE: BearerCaps, ChannelID, Progress, Display, Signal, HiLayerCompat
processMsgAlerting(ISDNQ931Message * msg)1075 SignallingEvent* ISDNQ931Call::processMsgAlerting(ISDNQ931Message* msg)
1076 {
1077 if (!checkMsgRecv(msg,true))
1078 return 0;
1079 if (m_data.processChannelID(msg,false) && !reserveCircuit())
1080 return releaseComplete();
1081 // Notify format and circuit change
1082 if (m_circuitChange) {
1083 m_circuitChange = false;
1084 msg->params().setParam("circuit-change",String::boolText(true));
1085 }
1086 if (m_data.processBearerCaps(msg,false) && !m_data.m_format.null())
1087 msg->params().setParam("format",m_data.m_format);
1088 // Check if inband ringback is available
1089 if (m_data.processProgress(msg,false))
1090 m_inbandAvailable = m_inbandAvailable ||
1091 SignallingUtils::hasFlag(m_data.m_progress,"in-band-info");
1092 msg->params().addParam("earlymedia",String::boolText(m_inbandAvailable));
1093 changeState(CallDelivered);
1094 return new SignallingEvent(SignallingEvent::Ringing,msg,this);
1095 }
1096
1097 // Process CALL PROCEEDING. See Q.931 3.1.2
1098 // IE: BearerCaps, ChannelID, Progress, Display, HiLayerCompat
processMsgCallProceeding(ISDNQ931Message * msg)1099 SignallingEvent* ISDNQ931Call::processMsgCallProceeding(ISDNQ931Message* msg)
1100 {
1101 if (!checkMsgRecv(msg,true))
1102 return 0;
1103 if (m_data.processChannelID(msg,false) && !reserveCircuit())
1104 return releaseComplete();
1105 // Notify format and circuit change
1106 if (m_circuitChange) {
1107 m_circuitChange = false;
1108 msg->params().setParam("circuit-change",String::boolText(true));
1109 }
1110 if (m_data.processBearerCaps(msg,false) && !m_data.m_format.null())
1111 msg->params().setParam("format",m_data.m_format);
1112 changeState(OutgoingProceeding);
1113 return new SignallingEvent(SignallingEvent::Accept,msg,this);
1114 }
1115
1116 // Process CONNECT. See Q.931 3.1.3
1117 // IE: BearerCaps, ChannelID, Progress, Display, DateTime, Signal, LoLayerCompat, HiLayerCompat
processMsgConnect(ISDNQ931Message * msg)1118 SignallingEvent* ISDNQ931Call::processMsgConnect(ISDNQ931Message* msg)
1119 {
1120 m_retransSetupTimer.stop();
1121 if (!checkMsgRecv(msg,true))
1122 return 0;
1123 if (m_data.processChannelID(msg,false) && !reserveCircuit())
1124 return releaseComplete();
1125 // This is the last time we can receive a circuit. Check if we reserved one
1126 if (!m_circuit)
1127 return releaseComplete("invalid-message");
1128 // Notify format and circuit change
1129 if (m_circuitChange) {
1130 m_circuitChange = false;
1131 msg->params().setParam("circuit-change",String::boolText(true));
1132 }
1133 if (m_data.processBearerCaps(msg,false) && !m_data.m_format.null())
1134 msg->params().setParam("format",m_data.m_format);
1135 changeState(ConnectReq);
1136 SignallingEvent* event = new SignallingEvent(SignallingEvent::Answer,msg,this);
1137 sendConnectAck(0);
1138 return event;
1139 }
1140
1141 // Process CONNECT ACK. See Q.931 3.1.4
1142 // IE: Display, Signal
processMsgConnectAck(ISDNQ931Message * msg)1143 SignallingEvent* ISDNQ931Call::processMsgConnectAck(ISDNQ931Message* msg)
1144 {
1145 m_conTimer.stop();
1146 // Check if we've changed state to Active when sent Connect
1147 bool yes = q931() && !q931()->parserData().flag(ISDNQ931::NoActiveOnConnect);
1148 if (yes && state() == Active)
1149 return 0;
1150 if (!checkMsgRecv(msg,false))
1151 return 0;
1152 changeState(Active);
1153 return 0;
1154 }
1155
1156 // Process DISCONNECT. See Q.931 3.1.5
1157 // IE: Cause, Progress, Display, Signal
processMsgDisconnect(ISDNQ931Message * msg)1158 SignallingEvent* ISDNQ931Call::processMsgDisconnect(ISDNQ931Message* msg)
1159 {
1160 if (state() == DisconnectReq) {
1161 // Disconnect requested concurrently from both sides
1162 sendRelease();
1163 return 0;
1164 }
1165 if (!checkMsgRecv(msg,false))
1166 return 0;
1167 m_discTimer.stop();
1168 changeState(DisconnectIndication);
1169 if (m_data.processCause(msg,false))
1170 msg->params().setParam("reason",m_data.m_reason);
1171 return new SignallingEvent(SignallingEvent::Release,msg,this);
1172 }
1173
1174 // Process INFORMATION. See Q.931 3.1.6
1175 // IE: SendComplete, Display, Keypad, Signal, CalledNo
processMsgInfo(ISDNQ931Message * msg)1176 SignallingEvent* ISDNQ931Call::processMsgInfo(ISDNQ931Message* msg)
1177 {
1178 m_lastEvent = checkTimeout(10000);
1179 // Check complete
1180 bool complete = (0 != msg->getIE(ISDNQ931IE::SendComplete));
1181 msg->params().addParam("complete",String::boolText(complete));
1182 // Display
1183 m_data.processDisplay(msg,false);
1184 // Check tones
1185 const char* tone = msg->getIEValue(ISDNQ931IE::CalledNo,"number");
1186 if (!tone)
1187 tone = msg->getIEValue(ISDNQ931IE::Keypad,"keypad");
1188 if (tone)
1189 msg->params().addParam("tone",tone);
1190 return new SignallingEvent(SignallingEvent::Info,msg,this);
1191 }
1192
1193 // Process NOTIFY. See Q.931 3.1.7
1194 // IE: BearerCaps, Notification, Display
processMsgNotify(ISDNQ931Message * msg)1195 SignallingEvent* ISDNQ931Call::processMsgNotify(ISDNQ931Message* msg)
1196 {
1197 m_data.processNotification(msg,false);
1198 DDebug(q931(),DebugNote,
1199 "Call(%u,%u). Received '%s' with '%s'='%s' [%p]",
1200 Q931_CALL_ID,msg->name(),ISDNQ931IE::typeName(ISDNQ931IE::Notification),
1201 m_data.m_notification.c_str(),this);
1202 return 0;
1203 }
1204
1205 // Process PROGRESS. See Q.931 3.1.8
1206 // IE: BearerCaps, Cause, Progress (mandatory), Display, HiLayerCompat
processMsgProgress(ISDNQ931Message * msg)1207 SignallingEvent* ISDNQ931Call::processMsgProgress(ISDNQ931Message* msg)
1208 {
1209 // Q.931 says that we should ignore the message. We don't
1210 if (m_data.processProgress(msg,false))
1211 m_inbandAvailable = m_inbandAvailable ||
1212 SignallingUtils::hasFlag(m_data.m_progress,"in-band-info");
1213 msg->params().addParam("earlymedia",String::boolText(m_inbandAvailable));
1214 if (m_data.processCause(msg,false))
1215 msg->params().setParam("reason",m_data.m_reason);
1216 if (m_data.processDisplay(msg,false))
1217 msg->params().setParam("callername",m_data.m_display);
1218 return new SignallingEvent(SignallingEvent::Progress,msg,this);
1219 }
1220
1221 // Process RELEASE and RELEASE COMPLETE. See Q.931 3.1.9/3.1.10
1222 // IE: Cause, Display, Signal
processMsgRelease(ISDNQ931Message * msg)1223 SignallingEvent* ISDNQ931Call::processMsgRelease(ISDNQ931Message* msg)
1224 {
1225 if (!msg)
1226 return 0;
1227 m_discTimer.stop();
1228 m_relTimer.stop();
1229 m_conTimer.stop();
1230 if (!checkMsgRecv(msg,false))
1231 return 0;
1232 m_data.processCause(msg,false);
1233 if (m_data.m_reason.null())
1234 m_data.m_reason = "normal-clearing";
1235 msg->params().setParam("reason",m_data.m_reason);
1236 if (state() != ReleaseReq && msg->type() == ISDNQ931Message::Release)
1237 changeState(ReleaseReq);
1238 else
1239 changeState(Null);
1240 return releaseComplete();
1241 }
1242
1243 // Process SETUP. See Q.931 3.1.14
1244 // IE: Repeat, BearerCaps, ChannelID, Progress, NetFacility, Display,
1245 // Keypad, Signal, CallingNo, CallingSubAddr, CalledNo, CalledSubAddr,
1246 // NetTransit, Repeat, LoLayerCompat, HiLayerCompat
processMsgSetup(ISDNQ931Message * msg)1247 SignallingEvent* ISDNQ931Call::processMsgSetup(ISDNQ931Message* msg)
1248 {
1249 if (!checkMsgRecv(msg,true))
1250 return 0;
1251 changeState(CallPresent);
1252 // *** BearerCaps. Mandatory
1253 if (!m_data.processBearerCaps(msg,false))
1254 return errorNoIE(msg,ISDNQ931IE::BearerCaps,true);
1255 // Check for multiple BearerCaps
1256 ISDNQ931IE* bc = msg->getIE(ISDNQ931IE::BearerCaps);
1257 if (bc && msg->getIE(ISDNQ931IE::BearerCaps,bc))
1258 m_rspBearerCaps = true;
1259 // Check if transfer mode is 'circuit'
1260 if (m_data.m_transferMode != "circuit") {
1261 Debug(q931(),DebugWarn,
1262 "Call(%u,%u). Invalid or missing transfer mode '%s'. Releasing call [%p]",
1263 Q931_CALL_ID,m_data.m_transferMode.c_str(),this);
1264 return errorWrongIE(msg,ISDNQ931IE::BearerCaps,true);
1265 }
1266 // *** ChannelID. Mandatory on PRI
1267 if (msg->getIE(ISDNQ931IE::ChannelID))
1268 m_data.processChannelID(msg,false);
1269 else if (q931() && q931()->primaryRate())
1270 return errorNoIE(msg,ISDNQ931IE::ChannelID,true);
1271 // Check if channel contains valid PRI/BRI flag
1272 if (q931() && (m_data.m_bri == q931()->primaryRate())) {
1273 Debug(q931(),DebugWarn,
1274 "Call(%u,%u). Invalid interface type. Releasing call [%p]",
1275 Q931_CALL_ID,this);
1276 return errorWrongIE(msg,ISDNQ931IE::ChannelID,true);
1277 }
1278 // Get a circuit from controller
1279 if (reserveCircuit())
1280 m_circuit->updateFormat(m_data.m_format,0);
1281 else if (q931() && q931()->primaryRate())
1282 return releaseComplete("congestion");
1283 // *** CalledNo /CallingNo
1284 m_overlap = !m_data.processCalledNo(msg,false);
1285 m_data.processCallingNo(msg,false);
1286 // *** Display
1287 m_data.processDisplay(msg,false);
1288 // Set message parameters
1289 msg->params().setParam("caller",m_data.m_callerNo);
1290 msg->params().setParam("called",m_data.m_calledNo);
1291 msg->params().setParam("format",m_data.m_format);
1292 msg->params().setParam("callername",m_data.m_display);
1293 msg->params().setParam("callernumtype",m_data.m_callerType);
1294 msg->params().setParam("callernumplan",m_data.m_callerPlan);
1295 msg->params().setParam("callerpres",m_data.m_callerPres);
1296 msg->params().setParam("callerscreening",m_data.m_callerScreening);
1297 msg->params().setParam("callednumtype",m_data.m_calledType);
1298 msg->params().setParam("callednumplan",m_data.m_calledPlan);
1299 msg->params().setParam("overlapped",String::boolText(m_overlap));
1300 return new SignallingEvent(SignallingEvent::NewCall,msg,this);
1301 }
1302
1303 // Process SETUP ACKNOLEDGE. See Q.931 3.1.14
1304 // IE: ChannelID, Progress, Display, Signal
processMsgSetupAck(ISDNQ931Message * msg)1305 SignallingEvent* ISDNQ931Call::processMsgSetupAck(ISDNQ931Message* msg)
1306 {
1307 if (!checkMsgRecv(msg,true))
1308 return 0;
1309 if (!m_data.processChannelID(msg,false))
1310 return errorWrongIE(msg,ISDNQ931IE::ChannelID,true);
1311 // We don't implement overlap sending. So, just complete the number sending
1312 SignallingMessage* m = new SignallingMessage;
1313 m->params().addParam("complete",String::boolText(true));
1314 sendInfo(m);
1315 return 0;
1316 }
1317
1318 // Process STATUS. See Q.931 3.1.15, 5.8.11
1319 // Try to recover (retransmit) messages based on received status
1320 // IE: Cause, CallState, Display
processMsgStatus(ISDNQ931Message * msg)1321 SignallingEvent* ISDNQ931Call::processMsgStatus(ISDNQ931Message* msg)
1322 {
1323 const char* s = msg->getIEValue(ISDNQ931IE::CallState,"state");
1324 if (!m_data.processCause(msg,false))
1325 m_data.m_reason = "unknown";
1326 DDebug(q931(),DebugInfo,
1327 "Call(%u,%u). Received '%s' state=%s peer-state=%s cause='%s' [%p]",
1328 Q931_CALL_ID,msg->name(),
1329 stateName(state()),s,m_data.m_reason.c_str(),this);
1330 u_int8_t peerState = (u_int8_t)lookup(s,s_states,255);
1331 // Check for valid state
1332 if (peerState == 255)
1333 return 0;
1334 // Check for Null states (our's and peer's Null state)
1335 if (state() == Null) {
1336 if (peerState != Null) {
1337 // Change state to allow sending RELEASE COMPLETE
1338 changeState(CallAbort);
1339 sendReleaseComplete("wrong-state-message");
1340 }
1341 return 0;
1342 }
1343 if (peerState == Null)
1344 return releaseComplete();
1345 // Check peer wrong states (these are states associated with dummy call reference)
1346 if (peerState == Restart || peerState == RestartReq)
1347 return releaseComplete("wrong-state-message");
1348 // Check if we are releasing the call
1349 // Release the call, even if peer's state is a compatible one
1350 switch (state()) {
1351 case DisconnectReq:
1352 case DisconnectIndication:
1353 case SuspendReq:
1354 case ResumeReq:
1355 case ReleaseReq:
1356 case CallAbort:
1357 return releaseComplete("wrong-state-message");
1358 default: ;
1359 }
1360 // Try to recover
1361 // This can be done only if we assume that the peer didn't saw our last message
1362 SignallingMessage* sigMsg = new SignallingMessage;
1363 bool recover = false;
1364 switch (state()) {
1365 case CallReceived:
1366 // Sent Alerting
1367 // Can recover if peer's state is OutgoingProceeding
1368 if (peerState == OutgoingProceeding) {
1369 changeState(IncomingProceeding);
1370 sendAlerting(sigMsg);
1371 recover = true;
1372 }
1373 break;
1374 case ConnectReq:
1375 // Sent Connect
1376 // Can recover if peer's state is OutgoingProceeding or CallDelivered
1377 // (saw our Alerting or Proceeding)
1378 if (peerState == OutgoingProceeding || peerState == CallDelivered) {
1379 changeState(CallReceived);
1380 sendConnect(sigMsg);
1381 recover = true;
1382 }
1383 break;
1384 case IncomingProceeding:
1385 // Sent Proceeding
1386 // Can recover if peer's state is CallInitiated
1387 // TODO: if overlap implemented: check if we received a Setup with full called number
1388 if (peerState == CallInitiated) {
1389 changeState(CallPresent);
1390 sendCallProceeding(sigMsg);
1391 recover = true;
1392 }
1393 break;
1394 case Active:
1395 // Incoming: received ConnectAck. Nothing to be done
1396 // Outgoing: Sent ConnectAck. Recover only if peer's state is ConnectReq
1397 if (outgoing() && peerState == ConnectReq) {
1398 changeState(ConnectReq);
1399 sendConnectAck(sigMsg);
1400 recover = true;
1401 }
1402 else if (peerState == Active) {
1403 Debug(q931(),DebugNote,"Call(%u,%u). Recovering from STATUS, cause='%s' [%p]",
1404 Q931_CALL_ID,m_data.m_reason.c_str(),this);
1405 recover = true;
1406 }
1407 case CallInitiated: // We've sent Setup. Can't recover: something went wrong
1408 case OverlapSend:
1409 case OverlapRecv: // TODO: implement if overlap send/recv is implemented
1410 case CallDelivered: // Received Alerting. Sent nothing. Can't recover
1411 case CallPresent: // Received Setup. Sent nothing. Can't recover
1412 case OutgoingProceeding: // Received Proceeding. Sent nothing. Can't recover
1413 break;
1414 default: ;
1415 }
1416 TelEngine::destruct(sigMsg);
1417 if (!recover)
1418 return releaseComplete("wrong-state-message");
1419 return 0;
1420 }
1421
1422 // Process STATUS ENQUIRY. See Q.931 3.1.16, 5.8.10
1423 // IE: Display
processMsgStatusEnquiry(ISDNQ931Message * msg)1424 SignallingEvent* ISDNQ931Call::processMsgStatusEnquiry(ISDNQ931Message* msg)
1425 {
1426 q931()->sendStatus(this,"status-enquiry-rsp",callTei());
1427 return 0;
1428 }
1429
1430 // Check if the state allows to send a message
1431 #define MSG_CHECK_SEND(type) \
1432 if (!(q931() && checkStateSend(type))) { \
1433 DDebug(q931(),DebugNote, \
1434 "Call(%u,%u). Can't send msg='%s' in state=%s. %s [%p]", \
1435 Q931_CALL_ID,ISDNQ931Message::typeName(type), \
1436 stateName(state()),(q931()?"Invalid state":"No call controller"),\
1437 this); \
1438 return false; \
1439 }
1440
1441 // Send ALERTING. See Q.931 3.1.1
1442 // IE: BearerCaps, ChannelID, Progress, Display, Signal, HiLayerCompat
sendAlerting(SignallingMessage * sigMsg)1443 bool ISDNQ931Call::sendAlerting(SignallingMessage* sigMsg)
1444 {
1445 MSG_CHECK_SEND(ISDNQ931Message::Alerting)
1446 const char* format = 0;
1447 if (sigMsg) {
1448 format = sigMsg->params().getValue(YSTRING("format"));
1449 m_inbandAvailable = m_inbandAvailable ||
1450 sigMsg->params().getBoolValue(YSTRING("earlymedia"),false);
1451 if (m_inbandAvailable)
1452 SignallingUtils::appendFlag(m_data.m_progress,"in-band-info");
1453 }
1454 if (format)
1455 m_data.m_format = format;
1456 // Change state, send message
1457 changeState(CallReceived);
1458 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Alerting,this);
1459 if (m_rspBearerCaps) {
1460 m_data.processBearerCaps(msg,true);
1461 m_rspBearerCaps = false;
1462 }
1463 if (!m_channelIDSent) {
1464 if (!q931()->primaryRate()) {
1465 m_data.m_channelType = "B";
1466 if (m_circuit)
1467 m_data.m_channelSelect = lookup(m_circuit->code(),Q931Parser::s_dict_channelIDSelect_BRI);
1468 if (!m_data.m_channelSelect) {
1469 TelEngine::destruct(msg);
1470 return sendReleaseComplete("congestion");
1471 }
1472 }
1473 m_data.processChannelID(msg,true,&q931()->parserData());
1474 m_channelIDSent = true;
1475 }
1476 m_data.processProgress(msg,true);
1477 return q931()->sendMessage(msg,callTei());
1478 }
1479
1480 // Send CALL PROCEEDING. See Q.931 3.1.2
1481 // IE: BearerCaps, ChannelID, Progress, Display, HiLayerCompat
sendCallProceeding(SignallingMessage * sigMsg)1482 bool ISDNQ931Call::sendCallProceeding(SignallingMessage* sigMsg)
1483 {
1484 MSG_CHECK_SEND(ISDNQ931Message::Proceeding)
1485 // Change state, send message
1486 changeState(IncomingProceeding);
1487 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Proceeding,this);
1488 if (m_rspBearerCaps) {
1489 m_data.processBearerCaps(msg,true);
1490 m_rspBearerCaps = false;
1491 }
1492 if (!m_channelIDSent) {
1493 m_data.processChannelID(msg,true);
1494 m_channelIDSent = true;
1495 }
1496 return q931()->sendMessage(msg,callTei());
1497 }
1498
1499 // Send CONNECT. See Q.931 3.1.3
1500 // IE: BearerCaps, ChannelID, Progress, Display, DateTime, Signal,
1501 // LoLayerCompat, HiLayerCompat
sendConnect(SignallingMessage * sigMsg)1502 bool ISDNQ931Call::sendConnect(SignallingMessage* sigMsg)
1503 {
1504 MSG_CHECK_SEND(ISDNQ931Message::Connect)
1505 // Change state, start timer, send message
1506 if (q931()->parserData().flag(ISDNQ931::NoActiveOnConnect))
1507 changeState(ConnectReq);
1508 else
1509 changeState(Active);
1510 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Connect,this);
1511 if (m_rspBearerCaps) {
1512 m_data.processBearerCaps(msg,true,&q931()->parserData());
1513 m_rspBearerCaps = false;
1514 }
1515 if (!m_channelIDSent) {
1516 if (!q931()->primaryRate()) {
1517 m_data.m_channelType = "B";
1518 m_data.m_channelByNumber = true;
1519 m_data.m_channelSelect = lookup(m_circuit->code(),Q931Parser::s_dict_channelIDSelect_BRI);
1520 }
1521 m_data.processChannelID(msg,true,&q931()->parserData());
1522 m_channelIDSent = true;
1523 }
1524 // Progress indicator
1525 if (sigMsg) {
1526 m_data.m_progress = sigMsg->params().getValue(YSTRING("call-progress"));
1527 m_data.processProgress(msg,true,&q931()->parserData());
1528 }
1529 m_conTimer.start();
1530 return q931()->sendMessage(msg,callTei());
1531 }
1532
1533 // Send CONNECT ACK. See Q.931 3.1.4
1534 // IE: Display, Signal
sendConnectAck(SignallingMessage * sigMsg)1535 bool ISDNQ931Call::sendConnectAck(SignallingMessage* sigMsg)
1536 {
1537 MSG_CHECK_SEND(ISDNQ931Message::ConnectAck)
1538 // Change state, send message
1539 changeState(Active);
1540 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::ConnectAck,this);
1541 // Progress indicator
1542 if (sigMsg) {
1543 m_data.m_progress = sigMsg->params().getValue(YSTRING("call-progress"));
1544 m_data.processProgress(msg,true,&q931()->parserData());
1545 }
1546 else
1547 m_data.m_progress = "";
1548 return q931()->sendMessage(msg,callTei());
1549 }
1550
1551 // Send DISCONNECT. See Q.931 3.1.5
1552 // IE: Cause, Progress, Display, Signal
sendDisconnect(SignallingMessage * sigMsg)1553 bool ISDNQ931Call::sendDisconnect(SignallingMessage* sigMsg)
1554 {
1555 MSG_CHECK_SEND(ISDNQ931Message::Disconnect)
1556 m_data.m_reason = "";
1557 if (sigMsg)
1558 m_data.m_reason = sigMsg->params().getValue(YSTRING("reason"));
1559 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Disconnect,this);
1560 m_data.processCause(msg,true);
1561 changeState(DisconnectReq);
1562 m_discTimer.start();
1563 return q931()->sendMessage(msg,callTei());
1564 }
1565
1566 // Send INFORMATION. See Q.931 3.1.6
1567 // IE: SendComplete, Display, Keypad, Signal, CalledNo
sendInfo(SignallingMessage * sigMsg)1568 bool ISDNQ931Call::sendInfo(SignallingMessage* sigMsg)
1569 {
1570 if (!sigMsg)
1571 return false;
1572 MSG_CHECK_SEND(ISDNQ931Message::Info)
1573 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Info,this);
1574 // Check send complete complete
1575 if (sigMsg->params().getBoolValue(YSTRING("complete")))
1576 msg->appendSafe(new ISDNQ931IE(ISDNQ931IE::SendComplete));
1577 m_data.m_display = sigMsg->params().getValue(YSTRING("display"));
1578 m_data.processDisplay(msg,true,&q931()->parserData());
1579 // Check tones or ringing
1580 const char* tone = sigMsg->params().getValue(YSTRING("tone"));
1581 if (tone)
1582 msg->appendIEValue(ISDNQ931IE::Keypad,"keypad",tone);
1583 return q931()->sendMessage(msg,callTei());
1584 }
1585
1586 // Send PROGRESS. See Q.931 3.1.8
1587 // IE: BearerCaps, Cause, Progress (mandatory), Display, HiLayerCompat
sendProgress(SignallingMessage * sigMsg)1588 bool ISDNQ931Call::sendProgress(SignallingMessage* sigMsg)
1589 {
1590 MSG_CHECK_SEND(ISDNQ931Message::Progress)
1591 if (sigMsg) {
1592 m_data.m_progress = sigMsg->params().getValue(YSTRING("progress"));
1593 m_inbandAvailable = m_inbandAvailable ||
1594 sigMsg->params().getBoolValue(YSTRING("earlymedia"),false);
1595 if (m_inbandAvailable)
1596 SignallingUtils::appendFlag(m_data.m_progress,"in-band-info");
1597 }
1598 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Progress,this);
1599 m_data.processProgress(msg,true);
1600 return q931()->sendMessage(msg,callTei());
1601 }
1602
1603 // Send RELEASE. See Q.931 3.1.9
1604 // IE: Cause, Display, Signal
sendRelease(const char * reason,SignallingMessage * sigMsg)1605 bool ISDNQ931Call::sendRelease(const char* reason, SignallingMessage* sigMsg)
1606 {
1607 if (state() == ReleaseReq || state() == Null)
1608 return false;
1609 // Get reason
1610 if (!reason && sigMsg)
1611 reason = sigMsg->params().getValue(YSTRING("reason"),0);
1612 if (reason)
1613 m_data.m_reason = reason;
1614 m_terminate = true;
1615 changeState(ReleaseReq);
1616 m_relTimer.start();
1617 return q931()->sendRelease(this,true,m_data.m_reason,callTei());
1618 }
1619
1620 // Send RELEASE COMPLETE. See Q.931 3.1.10
1621 // IE: Cause, Display, Signal
sendReleaseComplete(const char * reason,const char * diag,u_int8_t tei)1622 bool ISDNQ931Call::sendReleaseComplete(const char* reason, const char* diag, u_int8_t tei)
1623 {
1624 m_relTimer.stop();
1625 if ((state() == Null) && (0 == tei))
1626 return false;
1627 if (reason)
1628 m_data.m_reason = reason;
1629 m_terminate = m_destroy = true;
1630 changeState(Null);
1631 q931()->releaseCircuit(m_circuit);
1632 if (callTei() >= 127) {
1633 for (u_int8_t i = 0; i < 127; i++)
1634 if (m_broadcast[i])
1635 return q931()->sendRelease(this,false,m_data.m_reason,i,diag);
1636 return true;
1637 }
1638 if (0 == tei)
1639 tei = callTei();
1640 return q931()->sendRelease(this,false,m_data.m_reason,tei,diag);
1641 }
1642
1643 // Send SETUP. See Q.931 3.1.14
1644 // IE: Repeat, BearerCaps, ChannelID, Progress, NetFacility, Display,
1645 // Keypad, Signal, CallingNo, CallingSubAddr, CalledNo, CalledSubAddr,
1646 // NetTransit, Repeat, LoLayerCompat, HiLayerCompat
sendSetup(SignallingMessage * sigMsg)1647 bool ISDNQ931Call::sendSetup(SignallingMessage* sigMsg)
1648 {
1649 if (!sigMsg)
1650 return false;
1651 MSG_CHECK_SEND(ISDNQ931Message::Setup)
1652 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Setup,this);
1653 while (true) {
1654 // TODO: fix it (don't send?) if overlapp dialing is used
1655 if (q931()->parserData().flag(ISDNQ931::ForceSendComplete))
1656 msg->appendSafe(new ISDNQ931IE(ISDNQ931IE::SendComplete));
1657 // BearerCaps
1658 m_data.m_transferCapability = "speech";
1659 m_data.m_transferMode = "circuit";
1660 m_data.m_transferRate = "64kbit";
1661 m_data.m_format = sigMsg->params().getValue(YSTRING("format"),q931()->format());
1662 if (0xffff == lookup(m_data.m_format,Q931Parser::s_dict_bearerProto1,0xffff))
1663 m_data.m_format = "alaw";
1664 m_data.processBearerCaps(msg,true);
1665 // ChannelID
1666 if (!m_circuit)
1667 break;
1668 if (m_net || q931()->primaryRate()) {
1669 // Reserving a circuit attempted only on PRI or if we are NET
1670 if (!reserveCircuit()) {
1671 m_data.m_reason = "network-busy";
1672 break;
1673 }
1674 m_circuit->updateFormat(m_data.m_format,0);
1675 m_data.m_channelMandatory = sigMsg->params().getBoolValue(YSTRING("channel-exclusive"),
1676 q931()->parserData().flag(ISDNQ931::ChannelExclusive));
1677 m_data.m_channelByNumber = true;
1678 m_data.m_channelType = "B";
1679 if (m_data.m_bri) {
1680 if (m_circuit->code() > 0 && m_circuit->code() < 3)
1681 m_data.m_channelSelect = lookup(m_circuit->code(),Q931Parser::s_dict_channelIDSelect_BRI);
1682 if (!m_data.m_channelSelect) {
1683 m_data.m_reason = "network-busy";
1684 break;
1685 }
1686 }
1687 else {
1688 m_data.m_channelSelect = "present";
1689 m_data.m_channels = m_circuit->code();
1690 }
1691 m_data.processChannelID(msg,true);
1692 }
1693 // Progress indicator
1694 m_data.m_progress = sigMsg->params().getValue(YSTRING("call-progress"));
1695 m_data.processProgress(msg,true,&q931()->parserData());
1696 // Display
1697 m_data.m_display = sigMsg->params().getValue(YSTRING("callername"));
1698 m_data.processDisplay(msg,true,&q931()->parserData());
1699 // CallingNo
1700 m_data.m_callerType = sigMsg->params().getValue(YSTRING("callernumtype"),q931()->numType());
1701 m_data.m_callerPlan = sigMsg->params().getValue(YSTRING("callernumplan"),q931()->numPlan());
1702 m_data.m_callerPres = sigMsg->params().getValue(YSTRING("callerpres"),q931()->numPresentation());
1703 m_data.m_callerScreening = sigMsg->params().getValue(YSTRING("callerscreening"),q931()->numScreening());
1704 m_data.m_callerNo = sigMsg->params().getValue(YSTRING("caller"));
1705 m_data.processCallingNo(msg,true);
1706 // CalledNo
1707 m_data.m_calledType = sigMsg->params().getValue(YSTRING("callednumtype"));
1708 m_data.m_calledPlan = sigMsg->params().getValue(YSTRING("callednumplan"));
1709 m_data.m_calledNo = sigMsg->params().getValue(YSTRING("called"));
1710 m_data.processCalledNo(msg,true);
1711 // Send
1712 changeState(CallInitiated);
1713 if (m_net && !q931()->primaryRate()) {
1714 m_tei = 127;
1715 m_retransSetupTimer.start();
1716 }
1717 if (q931()->sendMessage(msg,callTei(),&m_data.m_reason))
1718 return true;
1719 msg = 0;
1720 break;
1721 }
1722 TelEngine::destruct(msg);
1723 setTerminate(true,0);
1724 return false;
1725 }
1726
1727 // Send SUSPEND REJECT. See Q.931 3.1.20
1728 // IE: Cause, Display
sendSuspendRej(const char * reason,SignallingMessage * sigMsg)1729 bool ISDNQ931Call::sendSuspendRej(const char* reason, SignallingMessage* sigMsg)
1730 {
1731 if (!reason && sigMsg)
1732 reason = sigMsg->params().getValue(YSTRING("reason"));
1733 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::SuspendRej,this);
1734 msg->appendIEValue(ISDNQ931IE::Cause,0,reason);
1735 return q931()->sendMessage(msg,callTei());
1736 }
1737
sendSetupAck()1738 bool ISDNQ931Call::sendSetupAck()
1739 {
1740 MSG_CHECK_SEND(ISDNQ931Message::SetupAck)
1741 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::SetupAck,this);
1742 if (!m_channelIDSent) {
1743 m_data.m_channelType = "B";
1744 if (m_circuit)
1745 m_data.m_channelSelect = lookup(m_circuit->code(),Q931Parser::s_dict_channelIDSelect_BRI);
1746 if (!m_data.m_channelSelect) {
1747 Debug(q931(),DebugNote,"Call(%u,%u). No voice channel available [%p]",
1748 Q931_CALL_ID,this);
1749 return sendReleaseComplete("congestion");
1750 }
1751 m_data.processChannelID(msg,true,&q931()->parserData());
1752 m_channelIDSent = true;
1753 }
1754 return q931()->sendMessage(msg,callTei());
1755 }
1756
releaseComplete(const char * reason,const char * diag)1757 SignallingEvent* ISDNQ931Call::releaseComplete(const char* reason, const char* diag)
1758 {
1759 Lock mylock(this);
1760 if (m_destroyed)
1761 return 0;
1762 if (reason)
1763 m_data.m_reason = reason;
1764 DDebug(q931(),DebugInfo,
1765 "Call(%u,%u). Call release in state '%s'. Reason: '%s' [%p]",
1766 Q931_CALL_ID,stateName(state()),m_data.m_reason.c_str(),this);
1767 sendReleaseComplete(reason,diag);
1768 // Cleanup
1769 q931()->releaseCircuit(m_circuit);
1770 changeState(Null);
1771 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::ReleaseComplete,this);
1772 msg->params().addParam("reason",m_data.m_reason);
1773 SignallingEvent* event = new SignallingEvent(SignallingEvent::Release,msg,this);
1774 TelEngine::destruct(msg);
1775 deref();
1776 m_destroyed = m_terminate = m_destroy = true;
1777 return event;
1778 }
1779
1780 // Get an event from the reserved circuit
getCircuitEvent(const Time & when)1781 SignallingEvent* ISDNQ931Call::getCircuitEvent(const Time& when)
1782 {
1783 if (!m_circuit)
1784 return 0;
1785 SignallingCircuitEvent* ev = m_circuit->getEvent(when);
1786 if (!ev)
1787 return 0;
1788 SignallingEvent* event = 0;
1789 switch (ev->type()) {
1790 case SignallingCircuitEvent::Dtmf: {
1791 const char* tone = ev->getValue(YSTRING("tone"));
1792 if (!(tone && *tone))
1793 break;
1794 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Info,this);
1795 msg->params().addParam("tone",tone);
1796 msg->params().addParam("inband",String::boolText(true));
1797 event = new SignallingEvent(SignallingEvent::Info,msg,this);
1798 TelEngine::destruct(msg);
1799 }
1800 break;
1801 default: ;
1802 }
1803 delete ev;
1804 return event;
1805 }
1806
1807 // Reserve and connect a circuit. Change the reserved one if it must to
reserveCircuit()1808 bool ISDNQ931Call::reserveCircuit()
1809 {
1810 m_circuitChange = false;
1811 bool anyCircuit = false;
1812 while (true) {
1813 // For incoming BRI calls we reserve the circuit only one time (at SETUP)
1814 if (!(outgoing() || q931()->primaryRate())) {
1815 // Check if we are a BRI NET and we should assign any channel
1816 int briChan = lookup(m_data.m_channelSelect,Q931Parser::s_dict_channelIDSelect_BRI,3);
1817 if (m_net && (briChan == 3))
1818 anyCircuit = true;
1819 else
1820 m_data.m_channels = briChan;
1821 break;
1822 }
1823 // Outgoing calls
1824 if (!m_data.m_channelByNumber) {
1825 m_data.m_reason = "service-not-implemented";
1826 return false;
1827 }
1828 int reqCircuit = m_data.m_channels.toInteger(-1);
1829 // Check if we don't have a circuit reserved
1830 if (!m_circuit) {
1831 anyCircuit = (outgoing() || (reqCircuit < 0 && !m_data.m_channelMandatory)) &&
1832 (m_net || q931()->primaryRate());
1833 break;
1834 }
1835 // Check the received circuit if any
1836 if ((int)m_circuit->code() == reqCircuit)
1837 return true;
1838 // We already have a circuit and received a different one: force mandatory
1839 m_data.m_channelMandatory = true;
1840 break;
1841 }
1842 // Reserve the circuit
1843 m_circuitChange = true;
1844 if (anyCircuit)
1845 q931()->reserveCircuit(m_circuit);
1846 else
1847 q931()->reserveCircuit(m_circuit,0,-1,&m_data.m_channels,m_data.m_channelMandatory,true);
1848 if (m_circuit) {
1849 m_data.m_channels = m_circuit->code();
1850 u_int64_t t = Time::msecNow();
1851 if (!m_circuit->connect(m_data.m_format) && !m_net && (state() != ISDNQ931State::CallPresent)) {
1852 Debug(q931(),DebugNote,
1853 "Call(%u,%u). Failed to connect circuit [%p]",Q931_CALL_ID,this);
1854 return false;
1855 }
1856 t = Time::msecNow() - t;
1857 if (t > 100) {
1858 int level = DebugInfo;
1859 if (t > 300)
1860 level = DebugMild;
1861 else if (t > 200)
1862 level = DebugNote;
1863 Debug(q931(),level,"Call(%u,%u). Connected to circuit %u in %u ms [%p]",
1864 Q931_CALL_ID,m_circuit->code(),(unsigned int)t,this);
1865 }
1866 #ifdef DEBUG
1867 else
1868 Debug(q931(),DebugAll,"Call(%u,%u). Connected to circuit %u in %u ms [%p]",
1869 Q931_CALL_ID,m_circuit->code(),(unsigned int)t,this);
1870 #endif
1871 return true;
1872 }
1873 DDebug(q931(),DebugNote,
1874 "Call(%u,%u). Can't reserve%s circuit [%p]",
1875 Q931_CALL_ID,(anyCircuit ? " any" : ""),this);
1876 m_data.m_reason = anyCircuit ? "congestion" : "channel-unacceptable";
1877 return false;
1878 }
1879
1880 // Print debug message on missing IE
1881 // Generate a Release event if requested by caller
errorNoIE(ISDNQ931Message * msg,ISDNQ931IE::Type type,bool release)1882 SignallingEvent* ISDNQ931Call::errorNoIE(ISDNQ931Message* msg,
1883 ISDNQ931IE::Type type, bool release)
1884 {
1885 Debug(q931(),DebugNote,
1886 "Call(%u,%u). Received '%s' without mandatory IE '%s' [%p]",
1887 Q931_CALL_ID,msg->name(),ISDNQ931IE::typeName(type),this);
1888 if (release) {
1889 unsigned char c = (unsigned char)type;
1890 String tmp;
1891 tmp.hexify(&c,1);
1892 return releaseComplete("missing-mandatory-ie",tmp);
1893 }
1894 return 0;
1895 }
1896
1897 // Print debug message on wrong IE
1898 // Generate a Release event if requested by caller
errorWrongIE(ISDNQ931Message * msg,ISDNQ931IE::Type type,bool release)1899 SignallingEvent* ISDNQ931Call::errorWrongIE(ISDNQ931Message* msg,
1900 ISDNQ931IE::Type type, bool release)
1901 {
1902 Debug(q931(),DebugNote,
1903 "Call(%u,%u). Received '%s' containing IE '%s' with wrong data [%p]",
1904 Q931_CALL_ID,msg->name(),ISDNQ931IE::typeName(type),this);
1905 if (release) {
1906 unsigned char c = (unsigned char)type;
1907 String tmp;
1908 tmp.hexify(&c,1);
1909 return releaseComplete("invalid-ie",tmp);
1910 }
1911 return 0;
1912 }
1913
1914 // Change call state
changeState(State newState)1915 void ISDNQ931Call::changeState(State newState)
1916 {
1917 if (state() == newState)
1918 return;
1919 Debug(q931(),DebugAll,"Call(%u,%u). State '%s' --> '%s' [%p]",
1920 Q931_CALL_ID,stateName(state()),stateName(newState),this);
1921 m_state = newState;
1922 }
1923
q931()1924 ISDNQ931* ISDNQ931Call::q931()
1925 {
1926 return static_cast<ISDNQ931*>(SignallingCall::controller());
1927 }
1928
1929 #undef Q931_CALL_ID
1930 #undef MSG_CHECK_SEND
1931
1932 /**
1933 * ISDNQ931CallMonitor
1934 */
ISDNQ931CallMonitor(ISDNQ931Monitor * controller,u_int32_t callRef,bool netInit)1935 ISDNQ931CallMonitor::ISDNQ931CallMonitor(ISDNQ931Monitor* controller, u_int32_t callRef,
1936 bool netInit)
1937 : SignallingCall(controller,true),
1938 m_callRef(callRef),
1939 m_callerCircuit(0),
1940 m_calledCircuit(0),
1941 m_eventCircuit(0),
1942 m_netInit(netInit),
1943 m_circuitChange(false),
1944 m_terminate(false),
1945 m_terminator("engine")
1946 {
1947 Debug(q931(),DebugAll,"Monitor(%u) netInit=%s [%p]",
1948 m_callRef,String::boolText(netInit),this);
1949 if (!controller) {
1950 Debug(DebugWarn,"Monitor(%u). No monitor controller. Terminate [%p]",
1951 m_callRef,this);
1952 m_terminate = true;
1953 m_data.m_reason = "temporary-failure";
1954 return;
1955 }
1956 }
1957
~ISDNQ931CallMonitor()1958 ISDNQ931CallMonitor::~ISDNQ931CallMonitor()
1959 {
1960 releaseCircuit();
1961 DDebug(q931(),DebugAll,"Monitor(%u). Destroyed with reason '%s' [%p]",
1962 m_callRef,m_data.m_reason.c_str(),this);
1963 }
1964
1965 // Get an event from this monitor
getEvent(const Time & when)1966 SignallingEvent* ISDNQ931CallMonitor::getEvent(const Time& when)
1967 {
1968 Lock mylock(this);
1969 // Check for last event or aborting
1970 if (m_lastEvent || state() == CallAbort)
1971 return 0;
1972 if (m_terminate)
1973 return (m_lastEvent = releaseComplete());
1974 // Check for incoming messages
1975 ISDNQ931Message* msg = static_cast<ISDNQ931Message*>(dequeue());
1976 // No message: check terminate
1977 if (!msg)
1978 return (m_lastEvent = getCircuitEvent(when));
1979 XDebug(q931(),DebugAll,
1980 "Monitor(%u). Dequeued message (%p): '%s' in state '%s' [%p]",
1981 m_callRef,msg,msg->name(),stateName(state()),this);
1982 switch (msg->type()) {
1983 case ISDNQ931Message::Setup: m_lastEvent = processMsgSetup(msg); break;
1984 case ISDNQ931Message::Proceeding:
1985 case ISDNQ931Message::Alerting:
1986 case ISDNQ931Message::Connect: m_lastEvent = processMsgResponse(msg); break;
1987 case ISDNQ931Message::Disconnect:
1988 case ISDNQ931Message::Release:
1989 case ISDNQ931Message::ReleaseComplete: m_lastEvent = processMsgTerminate(msg); break;
1990 case ISDNQ931Message::Info: m_lastEvent = processMsgInfo(msg); break;
1991 case ISDNQ931Message::Notify:
1992 case ISDNQ931Message::Progress:
1993 case ISDNQ931Message::SetupAck:
1994 case ISDNQ931Message::ConnectAck:
1995 case ISDNQ931Message::Status:
1996 case ISDNQ931Message::StatusEnquiry:
1997 case ISDNQ931Message::Suspend:
1998 case ISDNQ931Message::Resume:
1999 case ISDNQ931Message::SuspendAck:
2000 case ISDNQ931Message::SuspendRej:
2001 case ISDNQ931Message::ResumeAck:
2002 case ISDNQ931Message::ResumeRej:
2003 XDebug(q931(),DebugAll,"Monitor(%u). Ignoring '%s' message [%p]",
2004 m_callRef,msg->name(),this);
2005 break;
2006 default:
2007 DDebug(q931(),DebugNote,"Monitor(%u). Unknown message '%s' [%p]",
2008 m_callRef,msg->name(),this);
2009 // Fall through to destruct the message and check timeouts
2010 }
2011 TelEngine::destruct(msg);
2012 if (!m_lastEvent)
2013 m_lastEvent = getCircuitEvent(when);
2014 return m_lastEvent;
2015 }
2016
2017 // Set termination flag
setTerminate(const char * reason)2018 void ISDNQ931CallMonitor::setTerminate(const char* reason)
2019 {
2020 Lock mylock(this);
2021 if (state() == CallAbort)
2022 changeState(Null);
2023 // Check terminate & destroy flags
2024 if (m_terminate)
2025 return;
2026 m_terminate = true;
2027 if (reason)
2028 m_data.m_reason = reason;
2029 DDebug(q931(),DebugInfo,
2030 "Monitor(%u). Set terminate [%p]",m_callRef,this);
2031 }
2032
2033 // Get caller's and called's circuit or this object
getObject(const String & name) const2034 void* ISDNQ931CallMonitor::getObject(const String& name) const
2035 {
2036 if (name == YSTRING("SignallingCircuitCaller"))
2037 return m_callerCircuit;
2038 if (name == YSTRING("SignallingCircuitCalled"))
2039 return m_calledCircuit;
2040 if (name == YSTRING("ISDNQ931CallMonitor"))
2041 return (void*)this;
2042 return SignallingCall::getObject(name);
2043 }
2044
2045 // Process SETUP. See Q.931 3.1.14
2046 // IE: Repeat, BearerCaps, ChannelID, Progress, NetFacility, Display,
2047 // Keypad, Signal, CallingNo, CallingSubAddr, CalledNo, CalledSubAddr,
2048 // NetTransit, Repeat, LoLayerCompat, HiLayerCompat
processMsgSetup(ISDNQ931Message * msg)2049 SignallingEvent* ISDNQ931CallMonitor::processMsgSetup(ISDNQ931Message* msg)
2050 {
2051 // These message should come from the call initiator
2052 if (!msg->initiator())
2053 return 0;
2054 changeState(CallPresent);
2055 // Process IEs
2056 m_data.processBearerCaps(msg,false);
2057 m_circuitChange = false;
2058 if (m_data.processChannelID(msg,false) && reserveCircuit() && m_circuitChange) {
2059 m_circuitChange = false;
2060 msg->params().setParam("circuit-change",String::boolText(true));
2061 }
2062 m_data.processCalledNo(msg,false);
2063 m_data.processCallingNo(msg,false);
2064 m_data.processDisplay(msg,false);
2065 // Get circuits from controller. Connect the caller's circuit
2066 if (reserveCircuit())
2067 connectCircuit(true);
2068 // Set message parameters
2069 msg->params().setParam("caller",m_data.m_callerNo);
2070 msg->params().setParam("called",m_data.m_calledNo);
2071 msg->params().setParam("format",m_data.m_format);
2072 msg->params().setParam("callername",m_data.m_display);
2073 msg->params().setParam("callernumtype",m_data.m_callerType);
2074 msg->params().setParam("callernumplan",m_data.m_callerPlan);
2075 msg->params().setParam("callerpres",m_data.m_callerPres);
2076 msg->params().setParam("callerscreening",m_data.m_callerScreening);
2077 msg->params().setParam("callednumtype",m_data.m_calledType);
2078 msg->params().setParam("callednumplan",m_data.m_calledPlan);
2079 return new SignallingEvent(SignallingEvent::NewCall,msg,this);
2080 }
2081
2082 // Process CALL PROCEEDING. See Q.931 3.1.2
2083 // IE: BearerCaps, ChannelID, Progress, Display, HiLayerCompat
2084 // Process ALERTING. See Q.931 3.1.1
2085 // IE: BearerCaps, ChannelID, Progress, Display, Signal, HiLayerCompat
2086 // Process CONNECT. See Q.931 3.1.3
2087 // IE: BearerCaps, ChannelID, Progress, Display, DateTime, Signal, LoLayerCompat, HiLayerCompat
2088 // All we need is BearerCaps (for data format) and ChannelID (for channel change)
processMsgResponse(ISDNQ931Message * msg)2089 SignallingEvent* ISDNQ931CallMonitor::processMsgResponse(ISDNQ931Message* msg)
2090 {
2091 SignallingEvent::Type type;
2092 // These responses should never come from the call initiator
2093 if (msg->initiator())
2094 return 0;
2095 switch (msg->type()) {
2096 case ISDNQ931Message::Proceeding:
2097 if (state() == OutgoingProceeding)
2098 return 0;
2099 changeState(OutgoingProceeding);
2100 type = SignallingEvent::Accept;
2101 break;
2102 case ISDNQ931Message::Alerting:
2103 if (state() == CallDelivered)
2104 return 0;
2105 changeState(CallDelivered);
2106 type = SignallingEvent::Ringing;
2107 break;
2108 case ISDNQ931Message::Connect:
2109 if (state() == Active)
2110 return 0;
2111 changeState(Active);
2112 type = SignallingEvent::Answer;
2113 break;
2114 default:
2115 return 0;
2116 }
2117 m_circuitChange = false;
2118 if (m_data.processChannelID(msg,false) && reserveCircuit() && m_circuitChange) {
2119 m_circuitChange = false;
2120 msg->params().setParam("circuit-change",String::boolText(true));
2121 }
2122 if (m_data.processBearerCaps(msg,false) && !m_data.m_format.null())
2123 msg->params().setParam("format",m_data.m_format);
2124 connectCircuit(true);
2125 connectCircuit(false);
2126 return new SignallingEvent(type,msg,this);
2127 }
2128
2129 // Process termination messages Disconnect, Release, ReleaseComplete
processMsgTerminate(ISDNQ931Message * msg)2130 SignallingEvent* ISDNQ931CallMonitor::processMsgTerminate(ISDNQ931Message* msg)
2131 {
2132 if (!msg)
2133 return 0;
2134 // Set terminator
2135 // Usually Disconnect and ReleaseComplete come from the termination initiator
2136 switch (msg->type()) {
2137 case ISDNQ931Message::Disconnect:
2138 case ISDNQ931Message::ReleaseComplete:
2139 m_terminator = msg->initiator() ? m_data.m_callerNo : m_data.m_calledNo;
2140 break;
2141 case ISDNQ931Message::Release:
2142 m_terminator = msg->initiator() ? m_data.m_calledNo : m_data.m_callerNo;
2143 break;
2144 default:
2145 return 0;
2146 }
2147 m_data.processCause(msg,false);
2148 return releaseComplete();
2149 }
2150
2151 // Process INFORMATION. See Q.931 3.1.6
2152 // IE: SendComplete, Display, Keypad, Signal, CalledNo
processMsgInfo(ISDNQ931Message * msg)2153 SignallingEvent* ISDNQ931CallMonitor::processMsgInfo(ISDNQ931Message* msg)
2154 {
2155 // Check complete
2156 bool complete = (0 != msg->getIE(ISDNQ931IE::SendComplete));
2157 if (complete)
2158 msg->params().addParam("complete",String::boolText(true));
2159 // Display
2160 m_data.processDisplay(msg,false);
2161 // Try to get digits
2162 const char* tone = msg->getIEValue(ISDNQ931IE::CalledNo,"number");
2163 if (!tone)
2164 tone = msg->getIEValue(ISDNQ931IE::Keypad,"keypad");
2165 if (tone)
2166 msg->params().addParam("tone",tone);
2167 msg->params().setParam("fromcaller",String::boolText(msg->initiator()));
2168 return new SignallingEvent(SignallingEvent::Info,msg,this);
2169 }
2170
2171 // Release monitor
releaseComplete(const char * reason)2172 SignallingEvent* ISDNQ931CallMonitor::releaseComplete(const char* reason)
2173 {
2174 Lock mylock(this);
2175 if (state() == Null)
2176 return 0;
2177 if (reason)
2178 m_data.m_reason = reason;
2179 DDebug(q931(),DebugInfo,
2180 "Monitor(%u). Monitor release in state '%s'. Reason: '%s' [%p]",
2181 m_callRef,stateName(state()),m_data.m_reason.c_str(),this);
2182 // Cleanup
2183 releaseCircuit();
2184 changeState(Null);
2185 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::ReleaseComplete,
2186 true,m_callRef,2);
2187 msg->params().addParam("reason",m_data.m_reason);
2188 msg->params().addParam("terminator",m_terminator);
2189 SignallingEvent* event = new SignallingEvent(SignallingEvent::Release,msg,this);
2190 TelEngine::destruct(msg);
2191 deref();
2192 return event;
2193 }
2194
2195 // Get an event from the reserved circuit
getCircuitEvent(const Time & when)2196 SignallingEvent* ISDNQ931CallMonitor::getCircuitEvent(const Time& when)
2197 {
2198 bool fromCaller = true;
2199 // Select circuit to get event from
2200 if (m_eventCircuit)
2201 if (m_eventCircuit == m_callerCircuit) {
2202 m_eventCircuit = m_calledCircuit;
2203 fromCaller = false;
2204 }
2205 else
2206 m_eventCircuit = m_callerCircuit;
2207 else
2208 m_eventCircuit = m_callerCircuit;
2209 SignallingCircuitEvent* ev = m_eventCircuit ? m_eventCircuit->getEvent(when) : 0;
2210 if (!ev)
2211 return 0;
2212 SignallingEvent* event = 0;
2213 switch (ev->type()) {
2214 case SignallingCircuitEvent::Dtmf: {
2215 const char* tone = ev->getValue(YSTRING("tone"));
2216 if (!(tone && *tone))
2217 break;
2218 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Info,
2219 !fromCaller,m_callRef,2);
2220 msg->params().addParam("tone",tone);
2221 msg->params().addParam("inband",String::boolText(true));
2222 msg->params().addParam("fromcaller",String::boolText(fromCaller));
2223 event = new SignallingEvent(SignallingEvent::Info,msg,this);
2224 TelEngine::destruct(msg);
2225 }
2226 break;
2227 default: ;
2228 }
2229 delete ev;
2230 return event;
2231 }
2232
2233 // Reserve circuit for caller and called
2234 // Reserve both circuits or none
reserveCircuit()2235 bool ISDNQ931CallMonitor::reserveCircuit()
2236 {
2237 m_circuitChange = false;
2238 if (!m_data.m_channelByNumber)
2239 return false;
2240 // Check the received circuit if any
2241 unsigned int code = (unsigned int)m_data.m_channels.toInteger(-1);
2242 if (m_data.m_channels.null())
2243 return 0 != m_callerCircuit;
2244 else if (m_callerCircuit && (code == m_callerCircuit->code()))
2245 return true;
2246 // Reserve the circuit
2247 m_circuitChange = true;
2248 releaseCircuit();
2249 if (q931()->reserveCircuit(code,m_netInit,&m_callerCircuit,&m_calledCircuit))
2250 return true;
2251 DDebug(q931(),DebugNote,
2252 "Monitor(%u). Can't reserve circuit [%p]",m_callRef,this);
2253 return false;
2254 }
2255
2256 // Release both reserved circuits
releaseCircuit()2257 void ISDNQ931CallMonitor::releaseCircuit()
2258 {
2259 if (m_callerCircuit) {
2260 q931()->releaseCircuit(m_callerCircuit);
2261 TelEngine::destruct(m_callerCircuit);
2262 }
2263 if (m_calledCircuit) {
2264 q931()->releaseCircuit(m_calledCircuit);
2265 TelEngine::destruct(m_calledCircuit);
2266 }
2267 }
2268
2269 // Connect a reserved circuit
connectCircuit(bool caller)2270 bool ISDNQ931CallMonitor::connectCircuit(bool caller)
2271 {
2272 if (caller) {
2273 if (m_callerCircuit && m_callerCircuit->connect(m_data.m_format))
2274 return true;
2275 }
2276 else
2277 if (m_calledCircuit && m_calledCircuit->connect(m_data.m_format))
2278 return true;
2279 DDebug(q931(),DebugNote,
2280 "Monitor(%u). Can't connect circuit for calle%s [%p]",
2281 m_callRef,caller?"r":"d",this);
2282 return false;
2283 }
2284
2285 // Change monitor state
changeState(State newState)2286 void ISDNQ931CallMonitor::changeState(State newState)
2287 {
2288 if (state() == newState)
2289 return;
2290 DDebug(q931(),DebugInfo,
2291 "Monitor(%u). Changing state from '%s' to '%s' [%p]",
2292 m_callRef,stateName(state()),stateName(newState),this);
2293 m_state = newState;
2294 }
2295
q931()2296 ISDNQ931Monitor* ISDNQ931CallMonitor::q931()
2297 {
2298 return static_cast<ISDNQ931Monitor*>(SignallingCall::controller());
2299 }
2300
2301 /**
2302 * ISDNQ931ParserData
2303 */
ISDNQ931ParserData(const NamedList & params,DebugEnabler * dbg)2304 ISDNQ931ParserData::ISDNQ931ParserData(const NamedList& params, DebugEnabler* dbg)
2305 : m_dbg(dbg),
2306 m_maxMsgLen(0),
2307 m_flags(0),
2308 m_flagsOrig(0)
2309 {
2310 m_allowSegment = params.getBoolValue(YSTRING("allowsegmentation"),false);
2311 m_maxSegments = params.getIntValue(YSTRING("maxsegments"),8);
2312 m_maxDisplay = params.getIntValue(YSTRING("max-display"),34);
2313 if (m_maxDisplay != 34 && m_maxDisplay != 82)
2314 m_maxDisplay = 34;
2315 m_extendedDebug = params.getBoolValue(YSTRING("extended-debug"),false);
2316 // Set flags
2317 String flags = params.getValue(YSTRING("switchtype"));
2318 SignallingUtils::encodeFlags(0,m_flagsOrig,flags,ISDNQ931::s_swType);
2319 SignallingUtils::encodeFlags(0,m_flagsOrig,flags,ISDNQ931::s_flags);
2320 m_flags = m_flagsOrig;
2321 }
2322
2323 /**
2324 * ISDNQ931
2325 */
2326 const TokenDict ISDNQ931::s_flags[] = {
2327 {"sendnonisdnsource", SendNonIsdnSource},
2328 {"ignorenonisdndest", IgnoreNonIsdnDest},
2329 {"forcepresnetprov", ForcePresNetProv},
2330 {"translate31kaudio", Translate31kAudio},
2331 {"urditransfercapsonly", URDITransferCapsOnly},
2332 {"nolayer1caps", NoLayer1Caps},
2333 {"ignorenonlockedie", IgnoreNonLockedIE},
2334 {"nodisplay", NoDisplayIE},
2335 {"nodisplaycharset", NoDisplayCharset},
2336 {"forcesendcomplete", ForceSendComplete},
2337 {"noactiveonconnect", NoActiveOnConnect},
2338 {"checknotifyind", CheckNotifyInd},
2339 {"channelexclusive", ChannelExclusive},
2340 {0,0},
2341 };
2342
2343 const TokenDict ISDNQ931::s_swType[] = {
2344 {"euro-isdn-e1", EuroIsdnE1},
2345 {"euro-isdn-t1", EuroIsdnT1},
2346 {"national-isdn", NationalIsdn},
2347 {"dms100", Dms100},
2348 {"lucent5e", Lucent5e},
2349 {"att4ess", Att4ess},
2350 {"qsig", QSIG},
2351 {"unknown", Unknown},
2352 {0,0}
2353 };
2354
ISDNQ931(const NamedList & params,const char * name)2355 ISDNQ931::ISDNQ931(const NamedList& params, const char* name)
2356 : SignallingComponent(name,¶ms,"isdn-q931"),
2357 SignallingCallControl(params,"isdn."),
2358 SignallingDumpable(SignallingDumper::Q931),
2359 ISDNLayer3(name),
2360 m_q921(0),
2361 m_q921Up(false),
2362 m_networkHint(true),
2363 m_primaryRate(true),
2364 m_transferModeCircuit(true),
2365 m_callRef(1),
2366 m_callRefLen(2),
2367 m_callRefMask(0),
2368 m_parserData(params),
2369 m_l2DownTimer(0),
2370 m_recvSgmTimer(0),
2371 m_syncCicTimer(0),
2372 m_syncCicCounter(2),
2373 m_callDiscTimer(0),
2374 m_callRelTimer(0),
2375 m_callConTimer(0),
2376 m_restartCic(0),
2377 m_lastRestart(0),
2378 m_syncGroupTimer(0),
2379 m_segmented(0),
2380 m_remaining(0),
2381 m_printMsg(true),
2382 m_extendedDebug(false),
2383 m_flagQ921Down(false),
2384 m_flagQ921Invalid(false)
2385 {
2386 #ifdef DEBUG
2387 if (debugAt(DebugAll)) {
2388 String tmp;
2389 params.dump(tmp,"\r\n ",'\'',true);
2390 Debug(this,DebugAll,"ISDNQ931::ISDNQ931(%p,'%s') [%p]%s",
2391 ¶ms,name,this,tmp.c_str());
2392 }
2393 #endif
2394 m_parserData.m_dbg = this;
2395 m_networkHint = params.getBoolValue(YSTRING("network"),m_networkHint);
2396 m_data.m_bri = !(m_primaryRate = params.getBoolValue(YSTRING("primary"),m_primaryRate));
2397 m_callRefLen = params.getIntValue(YSTRING("callreflen"),m_primaryRate ? 2 : 1);
2398 if (m_callRefLen < 1 || m_callRefLen > 4)
2399 m_callRefLen = 2;
2400 // Set mask. Bit 7 of the first byte of the message header it's used for initiator flag
2401 m_callRefMask = 0x7fffffff >> (8 * (4 - m_callRefLen));
2402 // Timers
2403 m_l2DownTimer.interval(params,"t309",60000,90000,false);
2404 m_recvSgmTimer.interval(params,"t314",3000,4000,false);
2405 m_syncCicTimer.interval(params,"t316",4000,5000,false);
2406 m_syncGroupTimer.interval(params,"channelsync",60,300,true,true);
2407 m_callDiscTimer.interval(params,"t305",0,5000,false);
2408 m_callRelTimer.interval(params,"t308",0,5000,false);
2409 m_callConTimer.interval(params,"t313",0,5000,false);
2410 m_cpeNumber = params.getValue(YSTRING("number"));
2411 m_numPlan = params.getValue(YSTRING("numplan"));
2412 if (0xffff == lookup(m_numPlan,Q931Parser::s_dict_numPlan,0xffff))
2413 m_numPlan = "unknown";
2414 m_numType = params.getValue(YSTRING("numtype"));
2415 if (0xffff == lookup(m_numType,Q931Parser::s_dict_typeOfNumber,0xffff))
2416 m_numType = "unknown";
2417 m_numPresentation = params.getValue(YSTRING("presentation"));
2418 if (0xffff == lookup(m_numPresentation,Q931Parser::s_dict_presentation,0xffff))
2419 m_numPresentation = "allowed";
2420 m_numScreening = params.getValue(YSTRING("screening"));
2421 if (0xffff == lookup(m_numScreening,Q931Parser::s_dict_screening,0xffff))
2422 m_numScreening = "user-provided";
2423 m_format = params.getValue(YSTRING("format"));
2424 if (0xffff == lookup(m_format,Q931Parser::s_dict_bearerProto1,0xffff))
2425 m_format = "alaw";
2426 // Debug
2427 setDebug(params.getBoolValue(YSTRING("print-messages"),false),
2428 params.getBoolValue(YSTRING("extended-debug"),false));
2429 if (debugAt(DebugInfo)) {
2430 String s(network() ? "NET" : "CPE");
2431 #ifdef DEBUG
2432 s << " type=" << lookup(m_parserData.m_flags,s_swType,"Custom");
2433 String t;
2434 for (const TokenDict* p = s_flags; p->token; p++)
2435 if (m_parserData.flag(p->value))
2436 t.append(p->token,",");
2437 if (!t.null())
2438 s << " (" << t << ")";
2439 s << " pri=" << String::boolText(m_primaryRate);
2440 s << " format=" << m_format;
2441 s << " callref-len=" << (unsigned int)m_callRefLen;
2442 s << " plan/type/pres/screen=" << m_numPlan << "/" <<
2443 m_numType << "/" << m_numPresentation << "/" << m_numScreening;
2444 s << " strategy=" << lookup(strategy(),SignallingCircuitGroup::s_strategy);
2445 s << " channelsync/l2Down/recvSgm/syncCic=" <<
2446 (unsigned int)m_syncGroupTimer.interval() << "/" <<
2447 (unsigned int)m_l2DownTimer.interval() << "/" <<
2448 (unsigned int)m_recvSgmTimer.interval() << "/" <<
2449 (unsigned int)m_syncCicTimer.interval();
2450 s << " segmentation=" << String::boolText(m_parserData.m_allowSegment);
2451 s << " max-segments=" << (unsigned int)m_parserData.m_maxSegments;
2452 #else
2453 s << " type=" << params.getValue(YSTRING("switchtype"));
2454 s << " pri=" << String::boolText(m_primaryRate);
2455 s << " format=" << m_format;
2456 s << " channelsync=" << String::boolText(0 != m_syncGroupTimer.interval());
2457 #endif
2458 Debug(this,DebugInfo,"ISDN Call Controller %s [%p]",s.c_str(),this);
2459 }
2460 setDumper(params.getValue(YSTRING("layer3dump")));
2461 m_syncGroupTimer.start();
2462 }
2463
~ISDNQ931()2464 ISDNQ931::~ISDNQ931()
2465 {
2466 if (m_calls.count()) {
2467 cleanup();
2468 m_calls.clear();
2469 }
2470 TelEngine::destruct(attach((ISDNLayer2*)0));
2471 TelEngine::destruct(SignallingCallControl::attach(0));
2472 DDebug(this,DebugAll,"ISDN Call Controller destroyed [%p]",this);
2473 }
2474
2475 // Initialize Q.931 and attach a layer 2
initialize(const NamedList * config)2476 bool ISDNQ931::initialize(const NamedList* config)
2477 {
2478 #ifdef DEBUG
2479 String tmp;
2480 if (config && debugAt(DebugAll))
2481 config->dump(tmp,"\r\n ",'\'',true);
2482 Debug(this,DebugInfo,"ISDNQ931::initialize(%p) [%p]%s",config,this,tmp.c_str());
2483 #endif
2484 if (config) {
2485 debugLevel(config->getIntValue(YSTRING("debuglevel_q931"),
2486 config->getIntValue(YSTRING("debuglevel"),-1)));
2487 setDebug(config->getBoolValue(YSTRING("print-messages"),false),
2488 config->getBoolValue(YSTRING("extended-debug"),false));
2489 }
2490 if (config && !layer2()) {
2491 const String* name = config->getParam(YSTRING("sig"));
2492 if (!name)
2493 name = config;
2494 if (!TelEngine::null(name)) {
2495 NamedPointer* ptr = YOBJECT(NamedPointer,name);
2496 NamedList* linkConfig = ptr ? YOBJECT(NamedList,ptr->userData()) : 0;
2497 NamedList params(*name + "/Q921");
2498 params.addParam("basename",*name);
2499 params.addParam("primary",String::boolText(primaryRate()));
2500 params.addParam("network",String::boolText(network()));
2501 if (linkConfig)
2502 params.copyParams(*linkConfig);
2503 else {
2504 if (config->hasSubParams(*name + "."))
2505 params.copySubParams(*config,*name + ".");
2506 else {
2507 params.addParam("local-config","true");
2508 params.copyParams(*config);
2509 }
2510 linkConfig = ¶ms;
2511 }
2512 params.clearParam(YSTRING("debugname"));
2513 ISDNLayer2* l2 = YSIGCREATE(ISDNLayer2,¶ms);
2514 if (!l2) {
2515 Debug(this,DebugWarn,"Could not create ISDN Layer 2 '%s' [%p]",name->c_str(),this);
2516 return false;
2517 }
2518 attach(l2);
2519 if (!l2->initialize(linkConfig))
2520 TelEngine::destruct(attach((ISDNLayer2*)0));
2521 }
2522 }
2523 return 0 != layer2();
2524 }
2525
statusName() const2526 const char* ISDNQ931::statusName() const
2527 {
2528 if (exiting())
2529 return "Exiting";
2530 if (!m_q921)
2531 return "Layer 2 missing";
2532 if (!m_q921Up)
2533 return "Layer 2 down";
2534 return "Operational";
2535 }
2536
2537 // Check if layer 2 may be up
q921Up() const2538 bool ISDNQ931::q921Up() const
2539 {
2540 if (!m_q921)
2541 return false;
2542 if (m_q921Up)
2543 return true;
2544 // Assume BRI NET is always up
2545 return !primaryRate() && network();
2546 }
2547
2548 // Send a message to layer 2
sendMessage(ISDNQ931Message * msg,u_int8_t tei,String * reason)2549 bool ISDNQ931::sendMessage(ISDNQ931Message* msg, u_int8_t tei, String* reason)
2550 {
2551 if (!msg) {
2552 if (reason)
2553 *reason = "wrong-message";
2554 return false;
2555 }
2556 Lock lock(l3Mutex());
2557 if (!q921Up()) {
2558 if (!m_flagQ921Invalid)
2559 Debug(this,DebugNote,
2560 "Refusing to send message. Layer 2 is missing or down");
2561 m_flagQ921Invalid = true;
2562 TelEngine::destruct(msg);
2563 if (reason)
2564 *reason = "net-out-of-order";
2565 return false;
2566 }
2567 m_flagQ921Invalid = false;
2568 // Print message after running encoder to view dumped data
2569 ObjList segments;
2570 u_int8_t count = msg->encode(m_parserData,segments);
2571 if (debugAt(DebugInfo) && m_printMsg) {
2572 String tmp;
2573 msg->toString(tmp,m_extendedDebug);
2574 Debug(this,DebugInfo,"Sending message (%p)%s",msg,tmp.c_str());
2575 }
2576 TelEngine::destruct(msg);
2577 ObjList* obj = segments.skipNull();
2578 if (!(count && obj)) {
2579 Debug(this,DebugNote,"Failed to send message (%p). Parser failure",msg);
2580 if (reason)
2581 *reason = "wrong-message";
2582 return false;
2583 }
2584 if (count != 1)
2585 DDebug(this,DebugNote,"Message (%p) was segmented in %u parts",msg,count);
2586 for (; obj; obj = obj->skipNext()) {
2587 DataBlock* buffer = static_cast<DataBlock*>(obj->get());
2588 dump(*buffer,true);
2589 if (!m_q921->sendData(*buffer,tei,true)) {
2590 if (reason)
2591 *reason = "net-out-of-order";
2592 return false;
2593 }
2594 }
2595 return true;
2596 }
2597
2598 // Data link up notification from layer 2
2599 // Notify calls
multipleFrameEstablished(u_int8_t tei,bool confirmation,bool timeout,ISDNLayer2 * layer2)2600 void ISDNQ931::multipleFrameEstablished(u_int8_t tei, bool confirmation, bool timeout, ISDNLayer2* layer2)
2601 {
2602 l3Mutex().lock();
2603 bool q921Tmp = m_q921Up;
2604 m_q921Up = true;
2605 if (m_q921Up != q921Tmp) {
2606 NamedList p("");
2607 p.addParam("type","isdn-q921");
2608 p.addParam("operational",String::boolText(m_q921Up));
2609 p.addParam("from",m_q921->toString());
2610 engine()->notify(this,p);
2611 }
2612 DDebug(this,DebugNote,"'Established' %s TEI %u",
2613 confirmation ? "confirmation" :"indication",tei);
2614 endReceiveSegment("Data link is up");
2615 m_l2DownTimer.stop();
2616 m_flagQ921Down = false;
2617 l3Mutex().unlock();
2618 if (confirmation)
2619 return;
2620 // Notify calls
2621 Lock lock(this);
2622 for (ObjList* obj = m_calls.skipNull(); obj; obj = obj->skipNext())
2623 (static_cast<ISDNQ931Call*>(obj->get()))->dataLinkState(true);
2624 }
2625
2626 // Data link down notification from layer 2
2627 // Notify calls
multipleFrameReleased(u_int8_t tei,bool confirmation,bool timeout,ISDNLayer2 * layer2)2628 void ISDNQ931::multipleFrameReleased(u_int8_t tei, bool confirmation, bool timeout, ISDNLayer2* layer2)
2629 {
2630 Lock lockLayer(l3Mutex());
2631 bool q921Tmp = m_q921Up;
2632 m_q921Up = false;
2633 if (m_q921Up != q921Tmp) {
2634 NamedList p("");
2635 p.addParam("type","isdn-q921");
2636 p.addParam("operational",String::boolText(m_q921Up));
2637 p.addParam("from",m_q921->toString());
2638 engine()->notify(this,p);
2639 }
2640 DDebug(this,DebugNote,"'Released' %s TEI %u. Timeout: %s",
2641 confirmation ? "confirmation" :"indication",tei,String::boolText(timeout));
2642 endReceiveSegment("Data link is down");
2643 // Re-establish if layer 2 doesn't have an automatically re-establish procedure
2644 if (m_q921 && !m_q921->autoRestart()) {
2645 DDebug(this,DebugNote,"Re-establish layer 2.");
2646 m_q921->multipleFrame(tei,true,false);
2647 }
2648 if (confirmation)
2649 return;
2650 if (primaryRate() && !m_l2DownTimer.started()) {
2651 XDebug(this,DebugAll,"Starting T309 (layer 2 down)");
2652 m_l2DownTimer.start();
2653 }
2654 lockLayer.drop();
2655 // Notify calls
2656 Lock lockCalls(this);
2657 for (ObjList* obj = m_calls.skipNull(); obj; obj = obj->skipNext())
2658 (static_cast<ISDNQ931Call*>(obj->get()))->dataLinkState(false);
2659 }
2660
2661 // Receive and parse data from layer 2
2662 // Process the message
receiveData(const DataBlock & data,u_int8_t tei,ISDNLayer2 * layer2)2663 void ISDNQ931::receiveData(const DataBlock& data, u_int8_t tei, ISDNLayer2* layer2)
2664 {
2665 XDebug(this,DebugAll,"Received data. Length: %u, TEI: %u",data.length(),tei);
2666 Lock lock(l3Mutex());
2667 ISDNQ931Message* msg = getMsg(data);
2668 if (!msg)
2669 return;
2670 // Dummy call reference
2671 if (msg->dummyCallRef()) {
2672 sendStatus("service-not-implemented",0,tei);
2673 TelEngine::destruct(msg);
2674 return;
2675 }
2676 // Global call reference or a message that should have a dummy call reference
2677 if (!msg->callRef() || msg->type() == ISDNQ931Message::Restart ||
2678 msg->type() == ISDNQ931Message::RestartAck) {
2679 processGlobalMsg(msg,tei);
2680 TelEngine::destruct(msg);
2681 return;
2682 }
2683 bool doMore = true;
2684 // This is an incoming message:
2685 // if initiator is true, the message is for an incoming call
2686 ISDNQ931Call* call = findCall(msg->callRef(),!msg->initiator(),tei);
2687 if (call && (call->callTei() == 127) && (call->callRef() == msg->callRef())) {
2688 // Call was or still is Point-to-Multipoint
2689 int i;
2690 switch (msg->type()) {
2691 case ISDNQ931Message::Disconnect:
2692 case ISDNQ931Message::ReleaseComplete:
2693 if ((tei < 127) && call->m_broadcast[tei])
2694 call->m_broadcast[tei] = false;
2695 else
2696 doMore = false;
2697 if (call->m_retransSetupTimer.timeout()) {
2698 call->m_retransSetupTimer.stop();
2699 for (i = 0; i < 127; i++) {
2700 if (call->m_broadcast[i]) {
2701 doMore = false;
2702 break;
2703 }
2704 }
2705 }
2706 if ((msg->type() != ISDNQ931Message::ReleaseComplete) && !doMore)
2707 sendRelease(false,msg->callRefLen(),msg->callRef(),
2708 tei,!msg->initiator());
2709 break;
2710 case ISDNQ931Message::Connect:
2711 if (tei >= 127)
2712 break;
2713 call->m_tei = tei;
2714 call->m_broadcast[tei] = false;
2715 // All other pending calls are to be aborted
2716 for (i = 0; i < 127; i++) {
2717 if (call->m_broadcast[i]) {
2718 sendRelease(true,msg->callRefLen(),msg->callRef(),
2719 i,!msg->initiator(),"answered");
2720 call->m_broadcast[i] = false;
2721 break;
2722 }
2723 }
2724 break;
2725 default:
2726 if (tei < 127)
2727 call->m_broadcast[tei] = true;
2728 }
2729 }
2730 while (doMore) {
2731 if (call) {
2732 if (msg->type() != ISDNQ931Message::Setup &&
2733 (call->callTei() == 127 || call->callTei() == tei)) {
2734 call->enqueue(msg);
2735 msg = 0;
2736 }
2737 else if (msg->type() != ISDNQ931Message::ReleaseComplete) {
2738 sendRelease((msg->type() != ISDNQ931Message::Release),
2739 msg->callRefLen(),msg->callRef(),tei,
2740 !msg->initiator(),"invalid-callref");
2741 }
2742 break;
2743 }
2744 // Check if it is a new incoming call
2745 if (msg->initiator() && msg->type() == ISDNQ931Message::Setup) {
2746 if (!primaryRate() && m_cpeNumber && !network()) {
2747 // We are a BRI CPE with a number - check the called party field
2748 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::CalledNo);
2749 if (ie) {
2750 const String* number = ie->getParam(YSTRING("number"));
2751 if (number && !number->startsWith(m_cpeNumber)) {
2752 DDebug(this,DebugInfo,"Setup was for '%s', not us.",number->c_str());
2753 break;
2754 }
2755 }
2756 }
2757 // Accept new calls only if no channel is restarting and not exiting
2758 String reason;
2759 if (acceptNewCall(false,reason)) {
2760 call = new ISDNQ931Call(this,false,msg->callRef(),msg->callRefLen(),tei);
2761 m_calls.append(call);
2762 call->enqueue(msg);
2763 msg = 0;
2764 call = 0;
2765 }
2766 else
2767 sendRelease(false,msg->callRefLen(),msg->callRef(),tei,
2768 !msg->initiator(),reason);
2769 break;
2770 }
2771 processInvalidMsg(msg,tei);
2772 break;
2773 }
2774 TelEngine::destruct(call);
2775 TelEngine::destruct(msg);
2776 }
2777
2778 // Attach layer 2
2779 // Update some data from the attached object
attach(ISDNLayer2 * q921)2780 ISDNLayer2* ISDNQ931::attach(ISDNLayer2* q921)
2781 {
2782 Lock lock(l3Mutex());
2783 if (m_q921 == q921)
2784 return 0;
2785 cleanup(q921 ? "layer 2 attach" : "layer 2 detach");
2786 ISDNLayer2* tmp = m_q921;
2787 m_q921 = q921;
2788 if (m_q921) {
2789 ISDNQ921* q = YOBJECT(ISDNQ921,m_q921);
2790 // Adjust timers from the new lower layer
2791 // Add 1000 ms to minimum value to allow the lower layer to re-establish
2792 // the data link before we make a retransmission
2793 if (q) {
2794 m_primaryRate = true;
2795 m_data.m_bri = false;
2796 u_int64_t min = q->dataTimeout();
2797 if (m_callDiscTimer.interval() <= min)
2798 m_callDiscTimer.interval(min + 1000);
2799 if (m_callRelTimer.interval() <= min)
2800 m_callRelTimer.interval(min + 1000);
2801 if (m_callConTimer.interval() <= min)
2802 m_callConTimer.interval(min + 1000);
2803 if (m_l2DownTimer.interval() <= min)
2804 m_l2DownTimer.interval(min + 1000);
2805 if (m_syncCicTimer.interval() <= min)
2806 m_syncCicTimer.interval(min + 1000);
2807 // Adjust some parser flags
2808 if (m_parserData.m_flagsOrig == EuroIsdnE1 && !q->network())
2809 m_parserData.m_flags |= NoDisplayIE;
2810 if (m_parserData.m_flagsOrig != QSIG && !q->network())
2811 m_parserData.m_flags |= NoActiveOnConnect;
2812 }
2813 else if (YOBJECT(ISDNQ921Management,m_q921)) {
2814 m_primaryRate = false;
2815 m_data.m_bri = true;
2816 m_callRefLen = 1;
2817 m_callRefMask = 0x7f;
2818 m_callRef &= m_callRefMask;
2819 }
2820 // Adjust parser data message length limit
2821 m_parserData.m_maxMsgLen = m_q921->maxUserData();
2822 }
2823 else {
2824 // Reset parser data if no layer 2
2825 m_parserData.m_maxMsgLen = 0;
2826 m_parserData.m_flags = m_parserData.m_flagsOrig;
2827 }
2828 lock.drop();
2829 if (tmp) {
2830 if (tmp->layer3() == this) {
2831 Debug(this,DebugAll,"Detaching L2 (%p,'%s') [%p]",
2832 tmp,tmp->toString().safe(),this);
2833 tmp->attach(0);
2834 }
2835 else {
2836 Debug(this,DebugNote,"Layer 2 (%p,'%s') was not attached to us [%p]",
2837 tmp,tmp->toString().safe(),this);
2838 tmp = 0;
2839 }
2840 }
2841 if (!q921)
2842 return tmp;
2843 Debug(this,DebugAll,"Attached L2 '%s' (%p,'%s') [%p]",
2844 (q921->network() ? "NET" : "CPE"),
2845 q921,q921->toString().safe(),this);
2846 insert(q921);
2847 q921->attach(this);
2848 return tmp;
2849 }
2850
2851 // Make an outgoing call from a given message
call(SignallingMessage * msg,String & reason)2852 SignallingCall* ISDNQ931::call(SignallingMessage* msg, String& reason)
2853 {
2854 if (!msg) {
2855 reason = "invalid-parameter";
2856 return 0;
2857 }
2858 Lock lock(l3Mutex());
2859 if (!acceptNewCall(true,reason)) {
2860 TelEngine::destruct(msg);
2861 return 0;
2862 }
2863 ISDNQ931Call* call = new ISDNQ931Call(this,true,m_callRef,m_callRefLen);
2864 if (!call->circuit()) {
2865 reason = "congestion";
2866 TelEngine::destruct(call);
2867 return 0;
2868 }
2869 call->ref();
2870 // Adjust m_callRef. Avoid to use 0
2871 m_callRef = (m_callRef + 1) & m_callRefMask;
2872 if (!m_callRef)
2873 m_callRef = 1;
2874 m_calls.append(call);
2875 SignallingEvent* event = new SignallingEvent(SignallingEvent::NewCall,msg,call);
2876 TelEngine::destruct(msg);
2877 call->sendEvent(event);
2878 return call;
2879 }
2880
2881 // Reset data. Terminate calls and pending operations
cleanup(const char * reason)2882 void ISDNQ931::cleanup(const char* reason)
2883 {
2884 DDebug(this,DebugAll,"Cleanup. Reason: '%s'",reason);
2885 terminateCalls(0,reason);
2886 endReceiveSegment(reason);
2887 endRestart(false,0);
2888 }
2889
2890 // Set the interval for a given timer
setInterval(SignallingTimer & timer,int id)2891 void ISDNQ931::setInterval(SignallingTimer& timer, int id)
2892 {
2893 switch (id) {
2894 case 305:
2895 timer.interval(m_callDiscTimer.interval());
2896 break;
2897 case 308:
2898 timer.interval(m_callRelTimer.interval());
2899 break;
2900 case 313:
2901 timer.interval(m_callConTimer.interval());
2902 break;
2903 default:
2904 Debug(this,DebugWarn,"Unknown interval %d",id);
2905 }
2906 }
2907
2908 // Check timeouts for segmented messages, layer 2 down state, restart circuits
timerTick(const Time & when)2909 void ISDNQ931::timerTick(const Time& when)
2910 {
2911 Lock mylock(l3Mutex(),SignallingEngine::maxLockWait());
2912 if (!mylock.locked())
2913 return;
2914 // Check segmented message
2915 if (m_recvSgmTimer.timeout(when.msec()))
2916 endReceiveSegment("timeout");
2917 // Terminate all calls if T309 (layer 2 down) timed out
2918 if (m_l2DownTimer.timeout(when.msec())) {
2919 m_l2DownTimer.stop();
2920 if (!m_flagQ921Down)
2921 Debug(this,DebugWarn,"Layer 2 was down for " FMT64 " ms",m_l2DownTimer.interval());
2922 m_flagQ921Down = true;
2923 cleanup("dest-out-of-order");
2924 }
2925 // Restart circuits
2926 if (!m_syncGroupTimer.interval())
2927 return;
2928 if (m_syncGroupTimer.started()) {
2929 if (m_syncGroupTimer.timeout(when.msec())) {
2930 m_syncGroupTimer.stop();
2931 sendRestart(when.msec(),false);
2932 }
2933 return;
2934 }
2935 if (!m_syncCicTimer.started()) {
2936 m_lastRestart = 0;
2937 m_syncGroupTimer.start(when.msec());
2938 return;
2939 }
2940 // Terminate restart procedure if timeout
2941 if (m_syncCicTimer.timeout(when.msec())) {
2942 m_syncCicTimer.stop();
2943 m_syncCicCounter.inc();
2944 if (m_syncCicCounter.full())
2945 endRestart(true,when.msec(),true);
2946 else
2947 sendRestart(when.msec(),true);
2948 }
2949 }
2950
2951 // Find a call by call reference and direction
findCall(u_int32_t callRef,bool outgoing,u_int8_t tei)2952 ISDNQ931Call* ISDNQ931::findCall(u_int32_t callRef, bool outgoing, u_int8_t tei)
2953 {
2954 Lock lock(this);
2955 ObjList* obj = m_calls.skipNull();
2956 for (; obj; obj = obj->skipNext()) {
2957 ISDNQ931Call* call = static_cast<ISDNQ931Call*>(obj->get());
2958 if (callRef == call->callRef() && outgoing == call->outgoing()) {
2959 if (!primaryRate() && (call->callTei() != tei) && (call->callTei() != 127))
2960 return 0;
2961 return (call->ref() ? call : 0);
2962 }
2963 }
2964 return 0;
2965 }
2966
2967 // Find a call by reserved circuit
findCall(unsigned int circuit)2968 ISDNQ931Call* ISDNQ931::findCall(unsigned int circuit)
2969 {
2970 Lock lock(this);
2971 ObjList* obj = m_calls.skipNull();
2972 for (; obj; obj = obj->skipNext()) {
2973 ISDNQ931Call* call = static_cast<ISDNQ931Call*>(obj->get());
2974 if (!call->circuit() || call->circuit()->code() != circuit)
2975 continue;
2976 return (call->ref() ? call : 0);
2977 }
2978 return 0;
2979 }
2980
2981 // Terminate a call or all of them
terminateCalls(ObjList * list,const char * reason)2982 void ISDNQ931::terminateCalls(ObjList* list, const char* reason)
2983 {
2984 Lock lock(this);
2985 // Terminate all calls if no list
2986 if (!list) {
2987 ObjList* obj = m_calls.skipNull();
2988 for (; obj; obj = obj->skipNext()) {
2989 ISDNQ931Call* call = static_cast<ISDNQ931Call*>(obj->get());
2990 call->setTerminate(true,reason);
2991 }
2992 return;
2993 }
2994 // Terminate calls from list
2995 for (ObjList* obj = list->skipNull(); obj; obj = obj->skipNext()) {
2996 int circuit = (static_cast<String*>(obj->get()))->toInteger(-1);
2997 if (circuit == -1)
2998 continue;
2999 ISDNQ931Call* call = findCall(circuit);
3000 if (call) {
3001 call->setTerminate(true,reason);
3002 TelEngine::destruct(call);
3003 continue;
3004 }
3005 // No call for this circuit. Release the circuit
3006 releaseCircuit(circuit);
3007 }
3008 }
3009
3010 // Check if new calls are acceptable
acceptNewCall(bool outgoing,String & reason)3011 bool ISDNQ931::acceptNewCall(bool outgoing, String& reason)
3012 {
3013 if (exiting() || !q921Up()) {
3014 Debug(this,DebugInfo,"Denying %s call request, reason: %s.",
3015 outgoing ? "outgoing" : "incoming",
3016 exiting() ? "exiting" : "link down");
3017 reason = "net-out-of-order";
3018 return false;
3019 }
3020 return true;
3021 }
3022
3023 // Helper function called in ISDNQ931::receive()
dropSegMsg(ISDNQ931 * q931,ISDNQ931Message * msg,const char * reason)3024 static inline ISDNQ931Message* dropSegMsg(ISDNQ931* q931, ISDNQ931Message* msg,
3025 const char* reason)
3026 {
3027 if (reason)
3028 Debug(q931,DebugNote,"Dropping message segment (%p): '%s'. %s",
3029 msg,msg->name(),reason);
3030 TelEngine::destruct(msg);
3031 return 0;
3032 }
3033
3034 // Parse received data
3035 // Create a message from it. Validate it. Process segmented messages
getMsg(const DataBlock & data)3036 ISDNQ931Message* ISDNQ931::getMsg(const DataBlock& data)
3037 {
3038 Lock lock(l3Mutex());
3039 DataBlock segData;
3040 ISDNQ931Message* msg = ISDNQ931Message::parse(m_parserData,data,&segData);
3041 if (!msg)
3042 return 0;
3043 // Print received message
3044 if (debugAt(DebugInfo) && m_printMsg) {
3045 String tmp;
3046 msg->toString(tmp,m_extendedDebug);
3047 Debug(this,DebugInfo,"Received message (%p)%s",msg,tmp.c_str());
3048 }
3049 dump(data,false);
3050 // Not a segment
3051 if (msg->type() != ISDNQ931Message::Segment) {
3052 // We was waiting for a segment: Drop waiting
3053 if (m_segmented)
3054 endReceiveSegment("Received non-segmented message");
3055 return msg;
3056 }
3057 // This is a message segment. Start timer. Get it's parameters
3058 m_recvSgmTimer.start();
3059 bool first;
3060 u_int8_t remaining = 0xff, type = 0xff;
3061 // Get parameters
3062 bool valid = false;
3063 while (true) {
3064 ISDNQ931IE* ie = msg->getIE(ISDNQ931IE::Segmented);
3065 if (!ie)
3066 break;
3067 NamedString* ns = ie->getParam(YSTRING("first"));
3068 if (!ns)
3069 break;
3070 first = ns->toBoolean();
3071 remaining = (u_int8_t)ie->getIntValue(YSTRING("remaining"),0xff);
3072 type = (u_int8_t)ie->getIntValue(YSTRING("message"),0xff);
3073 valid = true;
3074 break;
3075 }
3076 if (!valid || type == 0xff || remaining == 0xff)
3077 return dropSegMsg(this,msg,"Invalid or missing segmented IE");
3078 // Check segmented message type
3079 if (!ISDNQ931Message::typeName(type))
3080 return dropSegMsg(this,msg,"Unknown segmented message type");
3081 // SEGMENT message can't be segmented
3082 if (type == ISDNQ931Message::Segment)
3083 return dropSegMsg(this,msg,"Segmented message can't be a segment");
3084 // Check if this is a new one
3085 if (!m_segmented) {
3086 // Should be the first segment with a valid call reference
3087 if (!first || !msg->callRef())
3088 return dropSegMsg(this,msg,"Invalid message segment");
3089 // Create message
3090 XDebug(this,DebugAll,"Start receiving message segments");
3091 m_segmented = new ISDNQ931Message((ISDNQ931Message::Type)type,
3092 msg->initiator(),msg->callRef(),msg->callRefLen());
3093 TelEngine::destruct(msg);
3094 // Put the message header in the buffer
3095 u_int8_t header[7];
3096 m_segmentData.assign(header,fillHeader(header,m_segmented,this));
3097 m_remaining = remaining;
3098 m_segmentData += segData;
3099 // Strange case: Segmented message in 1 segment
3100 if (!remaining)
3101 return endReceiveSegment();
3102 return 0;
3103 }
3104 // Sould be a segment for the message we already have
3105 // Check call identification
3106 if (m_segmented->initiator() != msg->initiator() ||
3107 m_segmented->callRef() != msg->callRef()) {
3108 dropSegMsg(this,msg,"Invalid call identification");
3109 return endReceiveSegment("Segment with invalid call identification");
3110 }
3111 // Check segment parameters
3112 if (first || m_remaining <= remaining || m_remaining - remaining != 1) {
3113 dropSegMsg(this,msg,"Invalid Segmented IE parameters");
3114 return endReceiveSegment("Segment with invalid parameters");
3115 }
3116 TelEngine::destruct(msg);
3117 // Update data
3118 m_remaining--;
3119 m_segmentData += segData;
3120 // End receiving ?
3121 if (!m_remaining)
3122 return endReceiveSegment();
3123 return 0;
3124 }
3125
3126 // Terminate receiving segmented message
endReceiveSegment(const char * reason)3127 ISDNQ931Message* ISDNQ931::endReceiveSegment(const char* reason)
3128 {
3129 Lock lock(l3Mutex());
3130 m_recvSgmTimer.stop();
3131 if (!m_segmented)
3132 return 0;
3133 // Clear some data
3134 TelEngine::destruct(m_segmented);
3135 m_remaining = 0;
3136 // Drop ?
3137 if (reason) {
3138 Debug(this,DebugNote,"Drop receiving message segment. %s",reason);
3139 m_segmentData.clear();
3140 return 0;
3141 }
3142 // Received all message: reassembly
3143 XDebug(this,DebugNote,"Reassambly message segment(s)");
3144 ISDNQ931Message* msg = ISDNQ931Message::parse(m_parserData,m_segmentData,0);
3145 m_segmentData.clear();
3146 if (msg && debugAt(DebugInfo) && m_printMsg) {
3147 String tmp;
3148 msg->toString(tmp,m_extendedDebug);
3149 Debug(this,DebugInfo,"Completed segmented message. (%p)%s",msg,tmp.c_str());
3150 }
3151 return msg;
3152 }
3153
3154 // Process messages with global call reference and messages that should have it
processGlobalMsg(ISDNQ931Message * msg,u_int8_t tei)3155 void ISDNQ931::processGlobalMsg(ISDNQ931Message* msg, u_int8_t tei)
3156 {
3157 if (!msg)
3158 return;
3159 switch (msg->type()) {
3160 case ISDNQ931Message::Restart:
3161 case ISDNQ931Message::RestartAck:
3162 // These messages must have a global call reference
3163 if (msg->callRef()) {
3164 #ifndef Q931_ACCEPT_RESTART
3165 Debug(this,DebugNote,
3166 "Dropping (%p): '%s' without global call reference",
3167 msg,msg->name());
3168 sendStatus("invalid-message",m_callRefLen,tei);
3169 return;
3170 #else
3171 DDebug(this,DebugNote,"(%p): '%s' without global call reference",
3172 msg,msg->name());
3173 #endif
3174 }
3175 if (msg->type() == ISDNQ931Message::Restart) {
3176 processMsgRestart(msg,tei);
3177 return;
3178 }
3179 if (m_restartCic) {
3180 String tmp = msg->getIEValue(ISDNQ931IE::ChannelID,"channels");
3181 if (m_restartCic->code() == (unsigned int)tmp.toInteger(-1))
3182 endRestart(true,0);
3183 else
3184 Debug(this,DebugWarn,
3185 "'%s' with invalid circuit(s) '%s'. We've requested '%u'",
3186 msg->name(),tmp.c_str(),m_restartCic->code());
3187 }
3188 else
3189 sendStatus("wrong-state-message",m_callRefLen,tei);
3190 return;
3191 case ISDNQ931Message::Status:
3192 break;
3193 default:
3194 Debug(this,DebugNote,"Dropping (%p): '%s' with global call reference",
3195 msg,msg->name());
3196 sendStatus("invalid-callref",m_callRefLen,tei);
3197 return;
3198 }
3199 // Message is a STATUS one
3200 DDebug(this,m_restartCic ? DebugWarn : DebugInfo,
3201 "'%s' with global call reference. State: '%s'. Cause: '%s'",
3202 msg->name(),
3203 msg->getIEValue(ISDNQ931IE::CallState,"state","Unknown/missing"),
3204 msg->getIEValue(ISDNQ931IE::Cause,0,"Unknown/missing"));
3205 }
3206
3207 // Process restart requests
3208 // See Q.931 5.5
processMsgRestart(ISDNQ931Message * msg,u_int8_t tei)3209 void ISDNQ931::processMsgRestart(ISDNQ931Message* msg, u_int8_t tei)
3210 {
3211 m_data.processRestart(msg,false);
3212 m_data.processChannelID(msg,false);
3213 m_data.m_reason = "";
3214 ObjList* list = m_data.m_channels.split(',',false);
3215 unsigned char buf = 0;
3216 DDebug(this,DebugInfo,"Received '%s' class=%s circuits=%s",
3217 msg->name(),m_data.m_restart.c_str(),m_data.m_channels.c_str());
3218
3219 while (true) {
3220 if (m_data.m_restart == YSTRING("channels")) {
3221 if (list->count() > 0)
3222 terminateCalls(list,"resource-unavailable");
3223 else {
3224 m_data.m_reason = "invalid-ie";
3225 buf = ISDNQ931IE::ChannelID;
3226 }
3227 break;
3228 }
3229
3230 bool single = (m_data.m_restart == YSTRING("interface"));
3231 bool all = !single && (m_data.m_restart == YSTRING("all-interfaces"));
3232 // If all interfaces is specified, ChannelID must not be present
3233 // If ChannelID is present and allowed, it must contain a single channel code
3234 if (!(single || all) || (all && list->count() > 0) ||
3235 (single && list->count() > 1)) {
3236 m_data.m_reason = "invalid-ie";
3237 buf = ISDNQ931IE::Restart;
3238 break;
3239 }
3240
3241 // Terminate all calls if class is 'all-interfaces'
3242 if (all) {
3243 terminateCalls(0,"resource-unavailable");
3244 break;
3245 }
3246
3247 // Done if no circuits
3248 if (!circuits())
3249 break;
3250
3251 // Identify the span containing the D-channel
3252 SignallingCircuitSpan* span = 0;
3253 if (list->count()) {
3254 unsigned int code = static_cast<String*>(list->get())->toInteger(0);
3255 SignallingCircuit* cic = circuits()->find(code);
3256 if (cic)
3257 span = cic->span();
3258 }
3259 else {
3260 // FIXME: Make a proper implementation: identify the span containing the active D-channel
3261 // Use the first span
3262 ObjList* o = circuits()->m_spans.skipNull();
3263 if (o)
3264 span = static_cast<SignallingCircuitSpan*>(o->get());
3265 }
3266 if (span) {
3267 // Fill a list with all circuit codes used to reset and terminate calls
3268 ObjList m_terminate;
3269 for (ObjList* o = circuits()->circuits().skipNull(); o; o = o->skipNext()) {
3270 SignallingCircuit* cic = static_cast<SignallingCircuit*>(o->get());
3271 if (span == cic->span())
3272 m_terminate.append(new String(cic->code()));
3273 }
3274 terminateCalls(&m_terminate,"resource-unavailable");
3275 }
3276 else
3277 Debug(this,DebugNote,
3278 "Unable to identify span containing D-channel for '%s' request class=%s circuit=%s",
3279 msg->name(),m_data.m_restart.c_str(),m_data.m_channels.c_str());
3280 break;
3281 }
3282 TelEngine::destruct(list);
3283
3284 // ACK if no error
3285 if (m_data.m_reason.null()) {
3286 ISDNQ931Message* m = new ISDNQ931Message(ISDNQ931Message::RestartAck,
3287 false,0,m_callRefLen);
3288 m->append(msg->removeIE(ISDNQ931IE::ChannelID));
3289 m->append(msg->removeIE(ISDNQ931IE::Restart));
3290 sendMessage(m,tei);
3291 return;
3292 }
3293
3294 String diagnostic;
3295 if (buf)
3296 diagnostic.hexify(&buf,1);
3297 Debug(this,DebugNote,
3298 "Invalid '%s' request class=%s circuits=%s reason='%s' diagnostic=%s",
3299 msg->name(),m_data.m_restart.c_str(),m_data.m_channels.c_str(),
3300 m_data.m_reason.c_str(),diagnostic.c_str());
3301 sendStatus(m_data.m_reason,m_callRefLen,tei,0,false,ISDNQ931Call::Null,0,diagnostic);
3302 }
3303
3304 // Process messages with invalid call reference. See Q.931 5.8
processInvalidMsg(ISDNQ931Message * msg,u_int8_t tei)3305 void ISDNQ931::processInvalidMsg(ISDNQ931Message* msg, u_int8_t tei)
3306 {
3307 if (!msg)
3308 return;
3309 DDebug(this,DebugNote,"Received (%p): '%s' with invalid call reference %u [%p]",
3310 msg,msg->name(),msg->callRef(),this);
3311 switch (msg->type()) {
3312 case ISDNQ931Message::Resume:
3313 case ISDNQ931Message::Setup:
3314 case ISDNQ931Message::ReleaseComplete:
3315 break;
3316 case ISDNQ931Message::Release:
3317 sendRelease(false,msg->callRefLen(),msg->callRef(),
3318 tei,!msg->initiator(),"invalid-callref");
3319 break;
3320 case ISDNQ931Message::Status:
3321 // Assume our call state to be Null. See Q.931 5.8.11
3322 // Ignore the message if the reported state is Null
3323 {
3324 String s = msg->getIEValue(ISDNQ931IE::CallState,"state");
3325 if (s != ISDNQ931Call::stateName(ISDNQ931Call::Null))
3326 sendRelease(false,msg->callRefLen(),msg->callRef(),
3327 tei,!msg->initiator(),"wrong-state-message");
3328 }
3329 break;
3330 case ISDNQ931Message::StatusEnquiry:
3331 sendStatus("status-enquiry-rsp",msg->callRefLen(),msg->callRef(),
3332 tei,!msg->initiator(),ISDNQ931Call::Null);
3333 break;
3334 default:
3335 sendRelease(true,msg->callRefLen(),msg->callRef(),
3336 tei,!msg->initiator(),"invalid-callref");
3337 return;
3338 }
3339 }
3340
3341 // Try to reserve a circuit if none. Send a restart request on it's behalf
3342 // Start counting the restart interval if no circuit reserved
sendRestart(u_int64_t time,bool retrans)3343 void ISDNQ931::sendRestart(u_int64_t time, bool retrans)
3344 {
3345 Lock lock(l3Mutex());
3346 m_syncCicTimer.stop();
3347 if (!primaryRate())
3348 return;
3349 if (m_restartCic) {
3350 if (!retrans)
3351 return;
3352 }
3353 else {
3354 unsigned int count = circuits() ? circuits()->count() : 0;
3355 for (m_lastRestart++; m_lastRestart <= count; m_lastRestart++) {
3356 String tmp(m_lastRestart);
3357 if (reserveCircuit(m_restartCic,0,-1,&tmp,true))
3358 break;
3359 }
3360 if (!m_restartCic) {
3361 m_lastRestart = 0;
3362 m_syncGroupTimer.start(time ? time : Time::msecNow());
3363 return;
3364 }
3365 }
3366 String s(m_restartCic->code());
3367 DDebug(this,DebugNote,"%s restart for circuit(s) '%s'",
3368 !retrans ? "Sending" : "Retransmitting",s.c_str());
3369 // Create the message
3370 ISDNQ931Message* msg = new ISDNQ931Message(ISDNQ931Message::Restart,true,
3371 0,m_callRefLen);
3372 // Don't add 'interface' parameter. We always send the channels, not the interface
3373 ISDNQ931IE* ie = new ISDNQ931IE(ISDNQ931IE::ChannelID);
3374 ie->addParam("interface-bri",String::boolText(!primaryRate()));
3375 ie->addParam("channel-exclusive",String::boolText(true));
3376 ie->addParam("channel-select","present");
3377 ie->addParam("type","B");
3378 ie->addParam("channel-by-number",String::boolText(true));
3379 ie->addParam("channels",s);
3380 msg->appendSafe(ie);
3381 msg->appendIEValue(ISDNQ931IE::Restart,"class","channels");
3382 m_syncCicTimer.start(time ? time : Time::msecNow());
3383 sendMessage(msg,0);
3384 }
3385
3386 // End our restart requests
3387 // Release reserved circuit. Continue restarting circuits if requested
endRestart(bool restart,u_int64_t time,bool timeout)3388 void ISDNQ931::endRestart(bool restart, u_int64_t time, bool timeout)
3389 {
3390 Lock lock(l3Mutex());
3391 m_syncCicTimer.stop();
3392 m_syncCicCounter.reset();
3393 if (m_restartCic) {
3394 if (!timeout)
3395 XDebug(this,DebugInfo,"Ending restart for circuit(s) '%u'",m_restartCic->code());
3396 else
3397 Debug(this,DebugInfo,"Restart timed out for circuit(s) '%u'",
3398 m_restartCic->code());
3399 releaseCircuit(m_restartCic);
3400 m_restartCic = 0;
3401 }
3402 if (restart)
3403 sendRestart(time,false);
3404 else {
3405 m_lastRestart = 0;
3406 m_syncGroupTimer.start(time ? time : Time::msecNow());
3407 }
3408 }
3409
3410 // Send STATUS. See Q.931 3.1.16
3411 // IE: Cause, CallState, Display
sendStatus(const char * cause,u_int8_t callRefLen,u_int32_t callRef,u_int8_t tei,bool initiator,ISDNQ931Call::State state,const char * display,const char * diagnostic)3412 bool ISDNQ931::sendStatus(const char* cause, u_int8_t callRefLen, u_int32_t callRef,
3413 u_int8_t tei, bool initiator, ISDNQ931Call::State state, const char* display,
3414 const char* diagnostic)
3415 {
3416 if (!primaryRate())
3417 return false;
3418 // Create message
3419 ISDNQ931Message* msg = 0;
3420 if (callRefLen)
3421 msg = new ISDNQ931Message(ISDNQ931Message::Status,initiator,callRef,callRefLen);
3422 else
3423 msg = new ISDNQ931Message(ISDNQ931Message::Status);
3424 // Set our state for dummy or global call references
3425 if (!(callRef && callRefLen))
3426 state = m_restartCic ? ISDNQ931Call::RestartReq : ISDNQ931Call::Null;
3427 // Add IEs
3428 ISDNQ931IE* ie = msg->appendIEValue(ISDNQ931IE::Cause,0,cause);
3429 // We always send status about the local network
3430 ie->addParamPrefix("location","LN");
3431 if (diagnostic && ie)
3432 ie->addParamPrefix("diagnostic",diagnostic);
3433 msg->appendIEValue(ISDNQ931IE::CallState,"state",ISDNQ931Call::stateName(state));
3434 if (display)
3435 msg->appendIEValue(ISDNQ931IE::Display,"display",display);
3436 return sendMessage(msg,tei);
3437 }
3438
3439 // Send RELEASE (See Q.931 3.1.9) or RELEASE COMPLETE (See Q.931 3.1.10)
3440 // IE: Cause, Display, Signal
sendRelease(bool release,u_int8_t callRefLen,u_int32_t callRef,u_int8_t tei,bool initiator,const char * cause,const char * diag,const char * display,const char * signal)3441 bool ISDNQ931::sendRelease(bool release, u_int8_t callRefLen, u_int32_t callRef,
3442 u_int8_t tei, bool initiator, const char* cause, const char* diag,
3443 const char* display, const char* signal)
3444 {
3445 // Create message
3446 ISDNQ931Message::Type t = release ? ISDNQ931Message::Release : ISDNQ931Message::ReleaseComplete;
3447 ISDNQ931Message* msg = new ISDNQ931Message(t,initiator,callRef,callRefLen);
3448 // Add IEs
3449 if (cause) {
3450 ISDNQ931IE* ie = msg->appendIEValue(ISDNQ931IE::Cause,0,cause);
3451 if (diag)
3452 ie->addParamPrefix("diagnostic",diag);
3453 }
3454 if (display)
3455 msg->appendIEValue(ISDNQ931IE::Display,"display",display);
3456 if (signal)
3457 msg->appendIEValue(ISDNQ931IE::Signal,"signal",signal);
3458 return sendMessage(msg,tei);
3459 }
3460
3461 /**
3462 * ISDNQ931Monitor
3463 */
ISDNQ931Monitor(const NamedList & params,const char * name)3464 ISDNQ931Monitor::ISDNQ931Monitor(const NamedList& params, const char* name)
3465 : SignallingComponent(name,¶ms,"isdn-q931-mon"),
3466 SignallingCallControl(params,"isdn."),
3467 ISDNLayer3(name),
3468 m_q921Net(0), m_q921Cpe(0), m_cicNet(0), m_cicCpe(0),
3469 m_parserData(params),
3470 m_printMsg(true), m_extendedDebug(false)
3471 {
3472 #ifdef DEBUG
3473 if (debugAt(DebugAll)) {
3474 String tmp;
3475 params.dump(tmp,"\r\n ",'\'',true);
3476 Debug(this,DebugAll,"ISDNQ931Monitor::ISDNQ931Monitor(%p,'%s') [%p]%s",
3477 ¶ms,name,this,tmp.c_str());
3478 }
3479 #endif
3480 // Set parser data. Accept maximum data length
3481 m_parserData.m_maxMsgLen = 0xffffffff;
3482 m_parserData.m_dbg = this;
3483 // Debug
3484 setDebug(params.getBoolValue(YSTRING("print-messages"),true),
3485 params.getBoolValue(YSTRING("extended-debug"),false));
3486 }
3487
~ISDNQ931Monitor()3488 ISDNQ931Monitor::~ISDNQ931Monitor()
3489 {
3490 terminateMonitor(0,0);
3491 TelEngine::destruct(attach((ISDNQ921Passive*)0,true));
3492 TelEngine::destruct(attach((ISDNQ921Passive*)0,false));
3493 TelEngine::destruct(attach((SignallingCircuitGroup*)0,true));
3494 TelEngine::destruct(attach((SignallingCircuitGroup*)0,false));
3495 m_calls.clear();
3496 DDebug(this,DebugAll,"ISDN Monitor destroyed [%p]",this);
3497 }
3498
3499 // Initialize the monitor and attach both passive layer 2
initialize(const NamedList * config)3500 bool ISDNQ931Monitor::initialize(const NamedList* config)
3501 {
3502 #ifdef DEBUG
3503 String tmp;
3504 if (config && debugAt(DebugAll))
3505 config->dump(tmp,"\r\n ",'\'',true);
3506 Debug(this,DebugInfo,"ISDNQ931Monitor::initialize(%p) [%p]%s",config,this,tmp.c_str());
3507 #endif
3508 if (config) {
3509 debugLevel(config->getIntValue(YSTRING("debuglevel_q931"),
3510 config->getIntValue(YSTRING("debuglevel"),-1)));
3511 setDebug(config->getBoolValue(YSTRING("print-messages"),false),
3512 config->getBoolValue(YSTRING("extended-debug"),false));
3513 for (int i = 0; i <= 1; i++) {
3514 bool net = (0 == i);
3515 if (net && m_q921Net)
3516 continue;
3517 if (!net && m_q921Cpe)
3518 continue;
3519 NamedString* name = config->getParam(net ? "sig-net" : "sig-cpe");
3520 if (name) {
3521 NamedPointer* ptr = YOBJECT(NamedPointer,name);
3522 NamedList* linkConfig = ptr ? YOBJECT(NamedList,ptr->userData()) : 0;
3523 NamedList params(name->c_str());
3524 params.addParam("basename",*name);
3525 if (linkConfig)
3526 params.copyParams(*linkConfig);
3527 else {
3528 params.copySubParams(*config,*name + ".");
3529 linkConfig = ¶ms;
3530 }
3531 ISDNQ921Passive* l2 = YSIGCREATE(ISDNQ921Passive,¶ms);
3532 if (!l2)
3533 return false;
3534 attach(l2,net);
3535 if (!l2->initialize(linkConfig))
3536 TelEngine::destruct(attach((ISDNQ921Passive*)0,net));
3537 }
3538 }
3539 }
3540 return m_q921Net && m_q921Cpe;
3541 }
3542
statusName() const3543 const char* ISDNQ931Monitor::statusName() const
3544 {
3545 if (exiting())
3546 return "Exiting";
3547 if (!(m_q921Net && m_q921Cpe))
3548 return "Layer 2 missing";
3549 return "Operational";
3550 }
3551
3552 // Notification from layer 2 of data link set/release command or response
dataLinkState(u_int8_t tei,bool cmd,bool value,ISDNLayer2 * layer2)3553 void ISDNQ931Monitor::dataLinkState(u_int8_t tei, bool cmd, bool value, ISDNLayer2* layer2)
3554 {
3555 #ifdef DEBUG
3556 if (debugAt(DebugInfo)) {
3557 String tmp;
3558 if (cmd)
3559 tmp << "'" << (value ? "Establish" : "Release") << "' request";
3560 else
3561 tmp << "'" << (value ? "YES" : "NO") << "' response";
3562 DDebug(this,DebugInfo,"Captured %s from '%s'. Clearing monitors",
3563 tmp.c_str(),layer2->debugName());
3564 }
3565 #endif
3566 terminateMonitor(0,"net-out-of-order");
3567 }
3568
3569 // Notification from layer 2 of data link idle timeout
idleTimeout(ISDNLayer2 * layer2)3570 void ISDNQ931Monitor::idleTimeout(ISDNLayer2* layer2)
3571 {
3572 DDebug(this,DebugInfo,"Idle timeout from '%s'. Clearing monitors",
3573 layer2->debugName());
3574 terminateMonitor(0,"net-out-of-order");
3575 }
3576
3577 // Receive data
receiveData(const DataBlock & data,u_int8_t tei,ISDNLayer2 * layer2)3578 void ISDNQ931Monitor::receiveData(const DataBlock& data, u_int8_t tei, ISDNLayer2* layer2)
3579 {
3580 XDebug(this,DebugAll,"Received data. Length: %u, TEI: %u",data.length(),tei);
3581 //TODO: Implement segmentation
3582 ISDNQ931Message* msg = ISDNQ931Message::parse(m_parserData,data,0);
3583 if (!msg)
3584 return;
3585 msg->params().setParam("monitor-sender",layer2->debugName());
3586 // Print received message
3587 if (debugAt(DebugInfo) && m_printMsg) {
3588 String tmp;
3589 msg->toString(tmp,m_extendedDebug);
3590 Debug(this,DebugInfo,"Captured message from '%s' (%p)%s",
3591 layer2->debugName(),msg,tmp.c_str());
3592 }
3593 else
3594 DDebug(this,DebugInfo,"Captured '%s' (call ref: %u) from '%s'",
3595 msg->name(),msg->callRef(),layer2->debugName());
3596 // Drop some messages
3597 if (dropMessage(msg)) {
3598 if (msg->type() == ISDNQ931Message::Restart ||
3599 msg->type() == ISDNQ931Message::RestartAck)
3600 processMsgRestart(msg);
3601 else
3602 DDebug(this,DebugInfo,"Dropping message message (%p): '%s' from '%s'",
3603 msg,msg->name(),layer2->debugName());
3604 TelEngine::destruct(msg);
3605 return;
3606 }
3607 // Find a monitor for this message or create a new one
3608 ISDNQ931CallMonitor* mon = findMonitor(msg->callRef(),true);
3609 while (true) {
3610 if (mon) {
3611 mon->enqueue(msg);
3612 msg = 0;
3613 break;
3614 }
3615 // Check if it is a new incoming call
3616 if (msg->initiator() && msg->type() == ISDNQ931Message::Setup) {
3617 lock();
3618 ISDNQ931CallMonitor* newMon = new ISDNQ931CallMonitor(this,msg->callRef(),m_q921Net == layer2);
3619 m_calls.append(newMon);
3620 unlock();
3621 newMon->enqueue(msg);
3622 msg = 0;
3623 break;
3624 }
3625 DDebug(this,DebugInfo,
3626 "Dropping message message (%p): '%s' from '%s'. Missing monitor for call %u",
3627 msg,msg->name(),layer2->debugName(),msg->callRef());
3628 break;
3629 }
3630 TelEngine::destruct(mon);
3631 TelEngine::destruct(msg);
3632 }
3633
3634 // Attach ISDN Q.921 pasive transport that monitors one side of the link
attach(ISDNQ921Passive * q921,bool net)3635 ISDNQ921Passive* ISDNQ931Monitor::attach(ISDNQ921Passive* q921, bool net)
3636 {
3637 Lock lock(l3Mutex());
3638 // Yes, this is a reference to a pointer
3639 ISDNQ921Passive*& which = net ? m_q921Net : m_q921Cpe;
3640 // Make no change if same transport
3641 if (which == q921)
3642 return 0;
3643 terminateMonitor(0,q921 ? "layer 2 attach" : "layer 2 detach");
3644 ISDNQ921Passive* tmp = which;
3645 which = q921;
3646 lock.drop();
3647 const char* type = net ? "NET" : "CPE";
3648 if (tmp) {
3649 if (tmp->layer3() == this) {
3650 Debug(this,DebugAll,"Detaching L2 %s (%p,'%s') [%p]",
3651 type,tmp,tmp->toString().safe(),this);
3652 static_cast<ISDNLayer2*>(tmp)->attach(0);
3653 }
3654 else {
3655 Debug(this,DebugNote,"Layer 2 %s (%p,'%s') was not attached to us [%p]",
3656 type,tmp,tmp->toString().safe(),this);
3657 tmp = 0;
3658 }
3659 }
3660 if (!q921)
3661 return tmp;
3662 Debug(this,DebugAll,"Attached L2 %s (%p,'%s') [%p]",
3663 type,q921,q921->toString().safe(),this);
3664 insert(q921);
3665 q921->ISDNLayer2::attach(this);
3666 return tmp;
3667 }
3668
3669 // Attach a circuit group to this call controller
attach(SignallingCircuitGroup * circuits,bool net)3670 SignallingCircuitGroup* ISDNQ931Monitor::attach(SignallingCircuitGroup* circuits, bool net)
3671 {
3672 Lock lock(l3Mutex());
3673 // Yes, this is a reference to a pointer
3674 SignallingCircuitGroup*& which = net ? m_cicNet : m_cicCpe;
3675 SignallingCircuitGroup* tmp = which;
3676 // Don't attach if it's the same object
3677 if (tmp == circuits)
3678 return 0;
3679 terminateMonitor(0,circuits ? "circuit group attach" : "circuit group detach");
3680 if (tmp && circuits) {
3681 Debug(this,DebugNote,
3682 "Attached circuit group (%p) '%s' while we already have one (%p) '%s'",
3683 circuits,circuits->debugName(),tmp,tmp->debugName());
3684 }
3685 #ifdef DEBUG
3686 else if (circuits)
3687 Debug(this,DebugAll,"Circuit group (%p) '%s' attached",circuits,circuits->debugName());
3688 else
3689 Debug(this,DebugAll,"Circuit group (%p) '%s' detached",tmp,tmp->debugName());
3690 #endif
3691 which = circuits;
3692 return tmp;
3693 }
3694
3695 // Method called periodically to check timeouts
timerTick(const Time & when)3696 void ISDNQ931Monitor::timerTick(const Time& when)
3697 {
3698 }
3699
3700 // Reserve the same circuit code from both circuit groups
3701 // This is an atomic operation: if one circuit fails to be reserved, both of them will fail
reserveCircuit(unsigned int code,bool netInit,SignallingCircuit ** caller,SignallingCircuit ** called)3702 bool ISDNQ931Monitor::reserveCircuit(unsigned int code, bool netInit,
3703 SignallingCircuit** caller, SignallingCircuit** called)
3704 {
3705 Lock lock(l3Mutex());
3706 if (!(m_cicNet && m_cicCpe))
3707 return false;
3708 String cic(code);
3709 if (netInit) {
3710 *caller = m_cicNet->reserve(cic,true);
3711 *called = m_cicCpe->reserve(cic,true);
3712 }
3713 else {
3714 *caller = m_cicCpe->reserve(cic,true);
3715 *called = m_cicNet->reserve(cic,true);
3716 }
3717 if (*caller && *called)
3718 return true;
3719 releaseCircuit(*caller);
3720 releaseCircuit(*called);
3721 return false;
3722 }
3723
3724 // Release a circuit from both groups
releaseCircuit(SignallingCircuit * circuit)3725 bool ISDNQ931Monitor::releaseCircuit(SignallingCircuit* circuit)
3726 {
3727 Lock lock(l3Mutex());
3728 if (!circuit)
3729 return false;
3730 if (m_cicNet == circuit->group())
3731 return m_cicNet->release(circuit,true);
3732 if (m_cicCpe == circuit->group())
3733 return m_cicCpe->release(circuit,true);
3734 return false;
3735 }
3736
3737 // Process a restart or restart acknoledge message
3738 // Terminate the monitor having the circuit given in restart message
processMsgRestart(ISDNQ931Message * msg)3739 void ISDNQ931Monitor::processMsgRestart(ISDNQ931Message* msg)
3740 {
3741 if (msg->type() == ISDNQ931Message::Restart) {
3742 m_data.processRestart(msg,false);
3743 if (m_data.m_restart != "channels") {
3744 DDebug(this,DebugNote,"Unsupported '%s' request (class: '%s')",
3745 msg->name(),m_data.m_restart.c_str());
3746 return;
3747 }
3748 }
3749 m_data.processChannelID(msg,false);
3750 ObjList* list = m_data.m_channels.split(',',false);
3751 if (!list) {
3752 DDebug(this,DebugNote,"Incorrect '%s' message (circuit(s): '%s')",
3753 msg->name(),m_data.m_channels.c_str());
3754 return;
3755 }
3756 if (!m_printMsg)
3757 DDebug(this,DebugInfo,"Received '%s' message for circuit(s) '%s'",
3758 msg->name(),m_data.m_channels.c_str());
3759 // Terminate monitor(s)
3760 for (ObjList* o = list->skipNull(); o; o = o->skipNext()) {
3761 String* s = static_cast<String*>(o->get());
3762 ISDNQ931CallMonitor* mon = findMonitor(s->toInteger(-1),false);
3763 if (mon) {
3764 terminateMonitor(mon,"resource-unavailable");
3765 TelEngine::destruct(mon);
3766 }
3767 }
3768 delete list;
3769 }
3770
3771 // Find a call monitor by call reference or reserved circuit
findMonitor(unsigned int value,bool byCallRef)3772 ISDNQ931CallMonitor* ISDNQ931Monitor::findMonitor(unsigned int value, bool byCallRef)
3773 {
3774 Lock lock(this);
3775 ObjList* obj = m_calls.skipNull();
3776 if (byCallRef) {
3777 for (; obj; obj = obj->skipNext()) {
3778 ISDNQ931CallMonitor* mon = static_cast<ISDNQ931CallMonitor*>(obj->get());
3779 if (value == mon->m_callRef)
3780 return (mon->ref() ? mon : 0);
3781 }
3782 return 0;
3783 }
3784 // Find by reserved circuit
3785 for (; obj; obj = obj->skipNext()) {
3786 ISDNQ931CallMonitor* mon = static_cast<ISDNQ931CallMonitor*>(obj->get());
3787 if (mon->m_callerCircuit && value == mon->m_callerCircuit->code())
3788 return (mon->ref() ? mon : 0);
3789 }
3790 return 0;
3791 }
3792
3793 // Drop some messages
dropMessage(const ISDNQ931Message * msg)3794 bool ISDNQ931Monitor::dropMessage(const ISDNQ931Message* msg)
3795 {
3796 if (msg->dummyCallRef())
3797 return true;
3798 // Global call reference or a message that should have a dummy call reference
3799 if (!msg->callRef() || msg->type() == ISDNQ931Message::Restart ||
3800 msg->type() == ISDNQ931Message::RestartAck)
3801 return true;
3802 return false;
3803 }
3804
3805 // Terminate all monitors or only one
terminateMonitor(ISDNQ931CallMonitor * mon,const char * reason)3806 void ISDNQ931Monitor::terminateMonitor(ISDNQ931CallMonitor* mon, const char* reason)
3807 {
3808 Lock lock(this);
3809 if (mon) {
3810 mon->setTerminate(reason);
3811 return;
3812 }
3813 // Terminate all monitors
3814 ObjList* obj = m_calls.skipNull();
3815 for (; obj; obj = obj->skipNext()) {
3816 mon = static_cast<ISDNQ931CallMonitor*>(obj->get());
3817 mon->setTerminate(reason);
3818 }
3819 }
3820
3821 /**
3822 * ISDNQ931IE
3823 */
3824 const TokenDict ISDNQ931IE::s_type[] = {
3825 {"Shift", Shift},
3826 {"More data", MoreData},
3827 {"Sending complete", SendComplete},
3828 {"Congestion level", Congestion},
3829 {"Repeat indicator", Repeat},
3830 {"Segmented", Segmented},
3831 {"Bearer capability", BearerCaps},
3832 {"Cause", Cause},
3833 {"Call identity", CallIdentity},
3834 {"Call state", CallState},
3835 {"Channel identification", ChannelID},
3836 {"Progress indicator", Progress},
3837 {"Network-specific facilities", NetFacility},
3838 {"Notification indicator", Notification},
3839 {"Display", Display},
3840 {"Date/time", DateTime},
3841 {"Keypad facility", Keypad},
3842 {"Signal", Signal},
3843 {"Connected number", ConnectedNo},
3844 {"Calling number", CallingNo},
3845 {"Calling party subaddress", CallingSubAddr},
3846 {"Called number", CalledNo},
3847 {"Called party subaddress", CalledSubAddr},
3848 {"Transit network selection", NetTransit},
3849 {"Restart indicator", Restart},
3850 {"Low layer compatibility", LoLayerCompat},
3851 {"High layer compatibility", HiLayerCompat},
3852 // Not used
3853 {"User-user", UserUser},
3854 {"Escape", Escape},
3855 {0,0}
3856 };
3857
3858
ISDNQ931IE(u_int16_t type)3859 ISDNQ931IE::ISDNQ931IE(u_int16_t type)
3860 : NamedList(""), m_type(type)
3861 {
3862 *(String*)this = typeName(m_type,"Unknown");
3863 }
3864
~ISDNQ931IE()3865 ISDNQ931IE::~ISDNQ931IE()
3866 {
3867 }
3868
toString(String & dest,bool extendedDebug,const char * before)3869 void ISDNQ931IE::toString(String& dest, bool extendedDebug, const char* before)
3870 {
3871 dest << before;
3872 dest << *((NamedList*)this);
3873 // Append content ?
3874 if (extendedDebug) {
3875 // Add condeset and value
3876 dest << " (codeset=" << (m_type >> 8) << " type=" << (u_int8_t)m_type << ')';
3877 String tmp;
3878 // Dump data
3879 if (m_buffer.length()) {
3880 tmp.hexify(m_buffer.data(),m_buffer.length(),' ');
3881 dest << " " << tmp;
3882 }
3883 // Show fields
3884 tmp = before;
3885 tmp << " ";
3886 for (unsigned int i = 0; ; i++) {
3887 NamedString* param = getParam(i);
3888 if (!param)
3889 break;
3890 dest << tmp << param->name() << '=' << *param;
3891 }
3892 }
3893 }
3894
3895 /**
3896 * ISDNQ931Message
3897 */
3898 const TokenDict ISDNQ931Message::s_type[] = {
3899 {"ALERTING", Alerting},
3900 {"CALL PROCEEDING", Proceeding},
3901 {"CONNECT", Connect},
3902 {"CONNECT ACK", ConnectAck},
3903 {"PROGRESS", Progress},
3904 {"SETUP", Setup},
3905 {"SETUP ACK", SetupAck},
3906 {"RESUME", Resume},
3907 {"RESUME ACK", ResumeAck},
3908 {"RESUME REJECT", ResumeRej},
3909 {"SUSPEND", Suspend},
3910 {"SUSPEND ACK", SuspendAck},
3911 {"SUSPEND REJECT", SuspendRej},
3912 {"USER INFO", UserInfo},
3913 {"DISCONNECT", Disconnect},
3914 {"RELEASE", Release},
3915 {"RELEASE COMPLETE", ReleaseComplete},
3916 {"RESTART", Restart},
3917 {"RESTART ACK", RestartAck},
3918 {"SEGMENT", Segment},
3919 {"CONGESTION CONTROL", CongestionCtrl},
3920 {"INFORMATION", Info},
3921 {"NOTIFY", Notify},
3922 {"STATUS", Status},
3923 {"STATUS ENQUIRY", StatusEnquiry},
3924 {0,0}
3925 };
3926
ISDNQ931Message(Type type,bool initiator,u_int32_t callRef,u_int8_t callRefLen)3927 ISDNQ931Message::ISDNQ931Message(Type type, bool initiator,
3928 u_int32_t callRef, u_int8_t callRefLen)
3929 : SignallingMessage(typeName(type)),
3930 m_type(type),
3931 m_initiator(initiator),
3932 m_callRef(callRef),
3933 m_callRefLen(callRefLen),
3934 m_unkMandatory(false),
3935 m_dummy(false)
3936 {
3937 }
3938
ISDNQ931Message(Type type)3939 ISDNQ931Message::ISDNQ931Message(Type type)
3940 : SignallingMessage(typeName(type)),
3941 m_type(type),
3942 m_initiator(false),
3943 m_callRef(0),
3944 m_callRefLen(0),
3945 m_unkMandatory(false),
3946 m_dummy(true)
3947 {
3948 }
3949
ISDNQ931Message(Type type,ISDNQ931Call * call)3950 ISDNQ931Message::ISDNQ931Message(Type type, ISDNQ931Call* call)
3951 : SignallingMessage(typeName(type)),
3952 m_type(type),
3953 m_initiator(false),
3954 m_callRef(0),
3955 m_callRefLen(0),
3956 m_unkMandatory(false),
3957 m_dummy(false)
3958 {
3959 if (!call)
3960 return;
3961 m_initiator = call->outgoing();
3962 m_callRef = call->callRef();
3963 m_callRefLen = call->callRefLen();
3964 }
3965
~ISDNQ931Message()3966 ISDNQ931Message::~ISDNQ931Message()
3967 {
3968 }
3969
3970 // Get an IE from list starting from the begining or from a given point
getIE(ISDNQ931IE::Type type,ISDNQ931IE * base)3971 ISDNQ931IE* ISDNQ931Message::getIE(ISDNQ931IE::Type type, ISDNQ931IE* base)
3972 {
3973 ObjList* obj = m_ie.skipNull();
3974 // Set start point after base if non 0
3975 if (base) {
3976 for (; obj; obj = obj->skipNext())
3977 if (base == obj->get()) {
3978 obj = obj->skipNext();
3979 break;
3980 }
3981 }
3982 for (; obj; obj = obj->skipNext()) {
3983 ISDNQ931IE* ie = static_cast<ISDNQ931IE*>(obj->get());
3984 if (ie->type() == type)
3985 return ie;
3986 }
3987 return 0;
3988 }
3989
3990 // Remove an IE from list and returns it
removeIE(ISDNQ931IE::Type type,ISDNQ931IE * base)3991 ISDNQ931IE* ISDNQ931Message::removeIE(ISDNQ931IE::Type type, ISDNQ931IE* base)
3992 {
3993 ObjList* obj = m_ie.skipNull();
3994 // Set start point after base if non 0
3995 if (base) {
3996 for (; obj; obj = obj->skipNext())
3997 if (base == obj->get()) {
3998 obj = obj->skipNext();
3999 break;
4000 }
4001 }
4002 ISDNQ931IE* ie = 0;
4003 for (; obj; obj = obj->skipNext()) {
4004 ie = static_cast<ISDNQ931IE*>(obj->get());
4005 if (ie->type() == type)
4006 break;
4007 ie = 0;
4008 }
4009 if (ie)
4010 m_ie.remove(ie,false);
4011 return ie;
4012 }
4013
4014 // Safely appends an IE to the list
appendSafe(ISDNQ931IE * ie)4015 bool ISDNQ931Message::appendSafe(ISDNQ931IE* ie)
4016 {
4017 if (!ie)
4018 return false;
4019 // Special care for some IEs:
4020 // Don't append Shift or Segment. Don't accept Repeat for now
4021 switch (ie->type()) {
4022 case ISDNQ931IE::Shift:
4023 case ISDNQ931IE::Segmented:
4024 case ISDNQ931IE::Repeat:
4025 delete ie;
4026 return false;
4027 }
4028 // This is not a safe way, but is good for now
4029 // TODO: Insert the IE in the proper order. Insert Shift if nedded. Special care for Repeat IE
4030 append(ie);
4031 return true;
4032 }
4033
toString(String & dest,bool extendedDebug,const char * indent) const4034 void ISDNQ931Message::toString(String& dest, bool extendedDebug, const char* indent) const
4035 {
4036 #define STARTLINE(indent) "\r\n" << indent
4037 const char* enclose = "-----";
4038 String ind = indent;
4039 ind << " ";
4040 dest << STARTLINE(indent) << enclose;
4041 dest << STARTLINE(indent) << name() << STARTLINE(ind);
4042 if (!m_dummy) {
4043 dest << "[From initiator=" << String::boolText(m_initiator);
4044 dest << " CallRef=" << (unsigned int)m_callRef << ']';
4045 }
4046 else
4047 dest << "[Dummy call reference]";
4048 // Dump message header
4049 if (extendedDebug && m_buffer.length()) {
4050 String s;
4051 s.hexify(m_buffer.data(),m_buffer.length(),' ');
4052 dest << " " << s;
4053 }
4054 // Add IEs
4055 String ieBefore;
4056 ieBefore << STARTLINE(ind);
4057 ObjList* obj = m_ie.skipNull();
4058 for (; obj; obj = obj->skipNext()) {
4059 ISDNQ931IE* ie = static_cast<ISDNQ931IE*>(obj->get());
4060 ie->toString(dest,extendedDebug,ieBefore);
4061 }
4062 dest << STARTLINE(indent) << enclose;
4063 #undef STARTLINE
4064 }
4065
getObject(const String & name) const4066 void* ISDNQ931Message::getObject(const String& name) const
4067 {
4068 if (name == YSTRING("ISDNQ931Message"))
4069 return (void*)this;
4070 return SignallingMessage::getObject(name);
4071 }
4072
encode(ISDNQ931ParserData & parserData,ObjList & dest)4073 u_int8_t ISDNQ931Message::encode(ISDNQ931ParserData& parserData, ObjList& dest)
4074 {
4075 Q931Parser parser(parserData);
4076 return parser.encode(this,dest);
4077 }
4078
parse(ISDNQ931ParserData & parserData,const DataBlock & buffer,DataBlock * segData)4079 ISDNQ931Message* ISDNQ931Message::parse(ISDNQ931ParserData& parserData,
4080 const DataBlock& buffer, DataBlock* segData)
4081 {
4082 Q931Parser parser(parserData);
4083 return parser.decode(buffer,segData);
4084 }
4085
4086 /**
4087 * Q931Parser
4088 */
4089 #define Q931_MSG_PROTOQ931 0x08 // Q.931 protocol discriminator
4090 // Get bit 7 to check if the current byte is extended to the next one
4091 // Used to parse message IE
4092 #define Q931_EXT_FINAL(val) ((val & 0x80) != 0)
4093
4094 // Max values for some IEs
4095 #define Q931_MAX_BEARERCAPS_LEN 12
4096 #define Q931_MAX_SEGMENTED_LEN 4
4097 //#define Q931_MAX_CAUSE_LEN 32
4098 #define Q931_MAX_CHANNELID_LEN 255
4099 #define Q931_MAX_CALLINGNO_LEN 255
4100 #define Q931_MAX_CALLEDNO_LEN 255
4101 #define Q931_MAX_KEYPAD_LEN 34
4102
4103 // Parse errors
4104 static const char* s_errorNoData = "no data";
4105 static const char* s_errorWrongData = "inconsistent data";
4106 static const char* s_errorUnsuppCoding = "unsupported coding standard";
4107
4108 //
4109 // IE descriptions
4110 //
4111
4112 // *** Fixed (1 byte length) IEs
4113
4114 // 4.5.14
4115 const TokenDict Q931Parser::s_dict_congestion[] = {
4116 {"recv-ready", 0x00}, // Receiver ready
4117 {"recv-not-ready", 0x0f}, // Receiver not ready
4118 // aliases for level=...
4119 {"yes", 0x00},
4120 {"true", 0x00},
4121 {"no", 0x0f},
4122 {"false", 0x0f},
4123 {0,0}
4124 };
4125
4126 static const IEParam s_ie_ieFixed[] = {
4127 {"lock", 0x08, 0}, // Shift
4128 {"codeset", 0x07, 0}, // Shift
4129 {"level", 0x0f, Q931Parser::s_dict_congestion}, // Congestion
4130 {"indication", 0x0f, 0}, // Repeat
4131 {0,0,0}
4132 };
4133
4134 // *** Q.931 4.5.5: Bearer capability
4135
4136 // Q.931 4.5.5. Information transfer capability: Bits 0-4
4137 const TokenDict Q931Parser::s_dict_bearerTransCap[] = {
4138 {"speech", 0x00}, // Speech
4139 {"udi", 0x08}, // Unrestricted digital information
4140 {"rdi", 0x09}, // Restricted digital information
4141 {"3.1khz-audio", 0x10}, // 3.1 khz audio
4142 {"udi-ta", 0x11}, // Unrestricted digital information with tone/announcements
4143 {"video", 0x18}, // Video
4144 {0,0}
4145 };
4146
4147 // Q.931 4.5.5. Transfer mode: Bits 5,6
4148 const TokenDict Q931Parser::s_dict_bearerTransMode[] = {
4149 {"circuit", 0x00}, // Circuit switch mode
4150 {"packet", 0x40}, // Packet mode
4151 {0,0}
4152 };
4153
4154 // Q.931 4.5.5. Transfer rate: Bits 0-4
4155 const TokenDict Q931Parser::s_dict_bearerTransRate[] = {
4156 {"packet", 0x00}, // Packet mode use
4157 {"64kbit", 0x10}, // 64 kbit/s
4158 {"2x64kbit", 0x11}, // 2x64 kbit/s
4159 {"384kbit", 0x13}, // 384 kbit/s
4160 {"1536kbit", 0x15}, // 1536 kbit/s
4161 {"1920kbit", 0x17}, // 1920 kbit/s
4162 {"multirate", 0x18}, // Multirate (64 kbit/s base rate)
4163 {0,0}
4164 };
4165
4166 // Q.931 4.5.5. User information Layer 1 protocol: Bits 0-4
4167 const TokenDict Q931Parser::s_dict_bearerProto1[] = {
4168 {"v110", 0x01}, // Recomendation V.110 and X.30
4169 {"mulaw", 0x02}, // Recomendation G.711 mu-law
4170 {"alaw", 0x03}, // Recomendation G.711 A-law
4171 {"g721", 0x04}, // Recomendation G.721 32kbit/s ADPCM and I.460
4172 {"h221", 0x05}, // Recomendation H.221 and H.242
4173 {"non-CCITT", 0x07}, // Non CCITT standardized rate adaption
4174 {"v120", 0x08}, // Recomendation V.120
4175 {"x31", 0x09}, // Recomendation X.31 HDLC flag stuffing
4176 {0,0}
4177 };
4178
4179 // Q.931 4.5.5. User information Layer 2 protocol: Bits 0-4
4180 const TokenDict Q931Parser::s_dict_bearerProto2[] = {
4181 {"q921", 0x02}, // Recommendation Q.921 or I441
4182 {"x25", 0x06}, // Recommendation X.25 link layer
4183 {0,0}
4184 };
4185
4186 // Q.931 4.5.5. User information Layer 3 protocol: Bits 0-4
4187 const TokenDict Q931Parser::s_dict_bearerProto3[] = {
4188 {"q931", 0x02}, // Recommendation Q.931 or I451
4189 {"x25", 0x06}, // Recommendation X.25 packet layer
4190 {0,0}
4191 };
4192
4193 // IE description
4194 static const IEParam s_ie_ieBearerCaps[] = {
4195 {"transfer-cap", 0x1f, Q931Parser::s_dict_bearerTransCap}, // Tranfer capability
4196 {"transfer-mode", 0x60, Q931Parser::s_dict_bearerTransMode}, // Transfer mode
4197 {"transfer-rate", 0x1f, Q931Parser::s_dict_bearerTransRate}, // Transfer rate
4198 {"rate-multiplier", 0x7f, 0}, // Rate multiplier
4199 {"layer1-protocol", 0x1f, Q931Parser::s_dict_bearerProto1}, // Layer 1 protocol
4200 {"layer1-data", 0xff, 0}, // Unparsed layer 1 data (for modems)
4201 {"layer2-protocol", 0x1f, Q931Parser::s_dict_bearerProto2}, // Layer 2 protocol
4202 {"layer3-protocol", 0x1f, Q931Parser::s_dict_bearerProto3}, // Layer 3 protocol
4203 {0,0,0}
4204 };
4205
4206 // *** Q.931 4.5.6: Call identity
4207
4208 // IE description
4209 static const IEParam s_ie_ieCallIdentity[] = {
4210 {"identity", 0, 0}, // Call identity data
4211 {0,0,0}
4212 };
4213
4214 // *** Q.931 4.5.7: Call state
4215
4216 // Call state values: bit 0-5
4217
4218 // IE description
4219 static const IEParam s_ie_ieCallState[] = {
4220 {"state", 0x3f, ISDNQ931Call::s_states},
4221 {0,0,0}
4222 };
4223
4224 // *** Q.931 4.5.8: Called party number
4225 // Q.931 4.5.10: Calling party number
4226
4227 // Q.931 4.5.10 Type of number: Bits 4-6
4228 const TokenDict Q931Parser::s_dict_typeOfNumber[] = {
4229 {"unknown", 0x00}, // Unknown
4230 {"international", 0x10}, // International number
4231 {"national", 0x20}, // National number
4232 {"net-specific", 0x30}, // Network specific number
4233 {"subscriber", 0x40}, // Subscriber number
4234 {"abbreviated", 0x60}, // Abbreviated number
4235 {"reserved", 0x70}, // Reserved for extension
4236 {0,0}
4237 };
4238
4239 // Q.931 4.5.10 Numbering plan: Bits 0-3. Apply only for type 0,1,2,4
4240 const TokenDict Q931Parser::s_dict_numPlan[] = {
4241 {"unknown", 0x00}, // Unknown
4242 {"isdn", 0x01}, // ISDN/telephoby numbering plan
4243 {"data", 0x03}, // Data numbering plan
4244 {"telex", 0x04}, // Telex numbering plan
4245 {"national", 0x08}, // National numbering plan
4246 {"private", 0x09}, // Private numbering plan
4247 {"reserved", 0x0f}, // Reserved for extension
4248 {0,0}
4249 };
4250
4251 // Q.931 4.5.10 Presentation indicator: Bits 5,6
4252 const TokenDict Q931Parser::s_dict_presentation[] = {
4253 {"allowed", 0x00}, // Presentation allowed
4254 {"restricted", 0x20}, // Presentation restricted
4255 {"unavailable", 0x40}, // Number not available due to interworking
4256 {"reserved", 0x50}, // Reserved
4257 // Aliases for presentation=...
4258 {"yes", 0x00},
4259 {"true", 0x00},
4260 {"no", 0x20},
4261 {"false", 0x20},
4262 {0,0}
4263 };
4264
4265 // Q.931 4.5.10 Presentation indicator: Bits 0,1
4266 const TokenDict Q931Parser::s_dict_screening[] = {
4267 {"user-provided", 0x00}, // User-provided, not screened
4268 {"user-provided-passed", 0x01}, // User-provided, verified and passed
4269 {"user-provided-failed", 0x02}, // User-provided, verified and failed
4270 {"network-provided", 0x03}, // Network provided
4271 // Aliases for screening=...
4272 {"yes", 0x01}, // User-provided, verified and passed
4273 {"true", 0x01},
4274 {"no", 0x00}, // User-provided, not screened
4275 {"false", 0x00},
4276 {0,0}
4277 };
4278
4279 // IE description
4280 static const IEParam s_ie_ieNumber[] = {
4281 {"type", 0x70, Q931Parser::s_dict_typeOfNumber}, // Type of number
4282 {"plan", 0x0f, Q931Parser::s_dict_numPlan}, // Numbering plan
4283 {"presentation", 0x60, Q931Parser::s_dict_presentation}, // Presentation
4284 {"screening", 0x03, Q931Parser::s_dict_screening}, // Screening
4285 {"number", 0x7f, 0}, // The number
4286 {0,0,0}
4287 };
4288
4289 // *** Q.931 4.5.9: Called party subaddress
4290 // Q.931 4.5.11: Calling party subaddress
4291
4292 // Q.931 4.5.9 Type of subaddress: Bits 5-6
4293 const TokenDict Q931Parser::s_dict_subaddrType[] = {
4294 {"nsap", 0x00}, // NSAP (CCITT Rec. X.213/ISO 8348 AD2)
4295 {"user", 0x20}, // User-specified
4296 {0,0}
4297 };
4298
4299 // IE description
4300 static const IEParam s_ie_ieSubAddress[] = {
4301 {"type", 0x60, Q931Parser::s_dict_subaddrType}, // Type of subaddress
4302 {"odd", 0x10, 0}, // Odd/even indicator of number of address signals
4303 {"subaddress", 0xff, 0}, // Subaddress information
4304 {0,0,0}
4305 };
4306
4307 // *** Q.931 4.5.13: Channel identification
4308
4309 // Q.931 4.5.13. Channel id selection for BRI interface: Bits 0,1
4310 const TokenDict Q931Parser::s_dict_channelIDSelect_BRI[] = {
4311 {"none", 0x00}, // No channel
4312 {"b1", 0x01}, // B1 channel
4313 {"b2", 0x02}, // B2 channel
4314 {"any", 0x03}, // Any channel
4315 {0,0}
4316 };
4317
4318 // Q.931 4.5.13. Channel id selection for PRI interface: Bits 0,1
4319 const TokenDict Q931Parser::s_dict_channelIDSelect_PRI[] = {
4320 {"none", 0x00}, // No channel
4321 {"present", 0x01}, // Defined by the following bytes
4322 {"reserved", 0x02}, // Reserved value
4323 {"any", 0x03}, // Any channel
4324 {0,0}
4325 };
4326
4327 // Q.931 4.5.13. Channel type: Bits 0-3
4328 const TokenDict Q931Parser::s_dict_channelIDUnits[] = {
4329 {"B", 0x03}, // B-channel
4330 {"H0", 0x06}, // H0-channel
4331 {"H11", 0x08}, // H11-channel
4332 {"H12", 0x09}, // H12-channel
4333 {0,0}
4334 };
4335
4336 // IE description
4337 static const IEParam s_ie_ieChannelID[] = {
4338 {"interface-bri", 0x20, 0}, // Interface it's a basic rate one
4339 {"channel-exclusive", 0x08, 0}, // The indicated B channel is exclusive/preferred
4340 {"d-channel", 0x04, 0}, // The channel identified is the D-channel
4341 {"channel-select", 0x03, Q931Parser::s_dict_channelIDSelect_BRI}, // Channel select for BRI interface
4342 {"channel-select", 0x03, Q931Parser::s_dict_channelIDSelect_PRI}, // Channel select for PRI interface
4343 {"interface", 0x7f, 0}, // Interface identifier
4344 {"channel-by-number", 0x10, 0}, // Channel is given by number or slot map
4345 {"type", 0x0f, Q931Parser::s_dict_channelIDUnits}, // Channel type
4346 {"channels", 0x7f, 0}, // Channel number(s)
4347 {"slot-map", 0xff, 0}, // Slot-map
4348 {0,0,0}
4349 };
4350
4351 // *** Q.931 4.5.15: Date/time
4352
4353 // IE description
4354 static const IEParam s_ie_ieDateTime[] = {
4355 {"year", 0xff, 0}, // Integer value
4356 {"month", 0xff, 0},
4357 {"day", 0xff, 0},
4358 {"hour", 0xff, 0},
4359 {"minute", 0xff, 0},
4360 {"second", 0xff, 0},
4361 {0,0,0}
4362 };
4363
4364 // *** Q.931 4.5.16: Display
4365
4366 // IE description
4367 static const IEParam s_ie_ieDisplay[] = {
4368 {"charset", 0x7f, 0}, // Charset, if any
4369 {"display", 0x7f, 0}, // IA5 characters
4370 {0,0,0}
4371 };
4372
4373 // *** Q.931 4.5.17: High layer compatibility
4374
4375 // IE description
4376 static const IEParam s_ie_ieHiLayerCompat[] = {
4377 {"interpretation", 0x1c, 0}, // Interpretation
4378 {"presentation", 0x03, 0}, // Presentation method or protocol profile
4379 {"layer", 0x7f, 0}, // High layer characteristics identification if presentation is 0x01
4380 {"layer", 0x7f, 0}, // High layer characteristics identification for other values of interpretation
4381 {"layer-ext", 0x7f, 0}, // Extended high layer characteristics identification if presentation is 0x01
4382 {"layer-ext", 0x7f, 0}, // Extended high layer characteristics identification for other values of interpretation
4383 {0,0,0}
4384 };
4385
4386 // *** Q.931 4.5.18: Keypad facility
4387
4388 // IE description
4389 static const IEParam s_ie_ieKeypad[] = {
4390 {"keypad", 0, 0}, // IA5 characters
4391 {0,0,0}
4392 };
4393
4394 // *** Q.931 4.5.19: Low layer compatibility
4395
4396 // Q.931 4.5.19. User information Layer 2 protocol: Bits 0-4
4397 const TokenDict Q931Parser::s_dict_loLayerProto2[] = {
4398 {"iso1745", 0x01}, // Basic mode ISO 1745
4399 {"q921", 0x02}, // Recommendation Q.921 or I441
4400 {"x25", 0x06}, // Recommendation X.25 link layer
4401 {"x25-multilink", 0x0f}, // Recommendation X.25 multilink
4402 {"lapb", 0x08}, // Extended LAPB; for half duplex operation
4403 {"hdlc-arm", 0x09}, // HDLC ARM (ISO 4335)
4404 {"hdlc-nrm", 0x0a}, // HDLC NRM (ISO 4335)
4405 {"hdlc-abm", 0x0b}, // HDLC ABM (ISO 4335)
4406 {"lan", 0x0c}, // LAN logical link control
4407 {"x75", 0x0d}, // Recommendation X.75. Single Link Procedure (SLP)
4408 {"q922", 0x0e}, // Recommendation Q.922
4409 {"q922-core", 0x0f}, // Core aspects of Recommendation Q.922
4410 {"user", 0x10}, // User specified
4411 {"iso7776", 0x11}, // ISO 7776 DTE-DTE operation
4412 {0,0}
4413 };
4414
4415 // Q.931 4.5.19. User information Layer 3 protocol: Bits 0-4
4416 const TokenDict Q931Parser::s_dict_loLayerProto3[] = {
4417 {"q931", 0x02}, // Recommendation Q.931 or I451
4418 {"x25", 0x06}, // Recommendation X.25 packet layer
4419 {"iso8208", 0x07}, // ISO/IEC 8208 (X.25 packet level protocol for data terminal equipment)
4420 {"x223", 0x08}, // CCITT Rec. X.223|ISO 8878
4421 {"iso8473", 0x09}, // ISO/IEC 8473 (OSI connectionless mode protocol)
4422 {"t70", 0x0a}, // Recommendation T.70 minimum network layer
4423 {"iso-tr-9577", 0x0b}, // ISO/IEC TR 9577 (Protocol identification in the network layer)
4424 {"user", 0x10}, // User specified
4425 {0,0}
4426 };
4427
4428 // IE description
4429 static const IEParam s_ie_ieLoLayerCompat[] = {
4430 {"transfer-cap", 0x1f, Q931Parser::s_dict_bearerTransCap}, // Tranfer capability
4431 {"out-band", 0x40, 0}, // Outband negotiation possible or not
4432 {"transfer-mode", 0x60, Q931Parser::s_dict_bearerTransMode}, // Transfer mode
4433 {"transfer-rate", 0x1f, Q931Parser::s_dict_bearerTransRate}, // Transfer rate
4434 {"rate-multiplier", 0x7f, 0}, // Rate multiplier
4435 {"layer1-protocol", 0x1f, Q931Parser::s_dict_bearerProto1}, // Layer 1 protocol
4436 {"layer1-data", 0xff, 0}, // Unparsed layer 1 data
4437 {"layer2-protocol", 0x1f, Q931Parser::s_dict_loLayerProto2}, // Layer 2 protocol
4438 {"layer2-data", 0xff, 0}, // Unparsed layer 2 data
4439 {"layer2-window-size",0x1f, 0}, // Window size (k)
4440 {"layer3-protocol", 0x1f, Q931Parser::s_dict_loLayerProto3}, // Layer 3 protocol
4441 {"layer3-mode", 0x60, 0}, // Mode for CCITT 'layer3-protocol' values
4442 {"layer3-user-data", 0x7f, 0}, // Optional Layer 3 user data
4443 {"layer3-7a", 0x7f, 0}, // Unparsed octet 7a
4444 {"layer3-def-size", 0x1f, 0}, // Default packet size
4445 {"layer3-packet-size",0x7f, 0}, // Packet window size
4446 {0,0,0}
4447 };
4448
4449 // *** Q.931 4.5.21: Network-specific facilities
4450 // Q.931 4.5.29: Transit network selection
4451
4452 // Q.931 4.5.21. Type of network identification: Bits 4-6
4453 const TokenDict Q931Parser::s_dict_networkIdType[] = {
4454 {"user", 0x00}, // User specified
4455 {"national", 0x20}, // National network identification
4456 {"international", 0x30}, // International network identification
4457 {0,0}
4458 };
4459
4460 // Q.931 4.5.21. Network identification plan: Bits 0-3
4461 const TokenDict Q931Parser::s_dict_networkIdPlan[] = {
4462 {"unknown", 0x00}, // Unknown
4463 {"carrier", 0x01}, // Carrier identification code
4464 {"data", 0x03}, // Data network identification code (Recommendation X.121)
4465 {0,0}
4466 };
4467
4468 // Q.931 4.5.21: Network-specific facilities
4469 static const IEParam s_ie_ieNetFacility[] = {
4470 {"type", 0x70, Q931Parser::s_dict_networkIdType}, // Type of network identification
4471 {"plan", 0x0f, Q931Parser::s_dict_networkIdPlan}, // Network identification plan
4472 {"id", 0xff, 0}, // Network identification
4473 {"facility", 0xff, 0}, // Network-specific facility
4474 {0,0,0}
4475 };
4476
4477 // Q.931 4.5.29: Transit network selection
4478 static const IEParam s_ie_ieNetTransit[] = {
4479 {"type", 0x70, Q931Parser::s_dict_networkIdType}, // Type of network identification
4480 {"plan", 0x0f, Q931Parser::s_dict_networkIdPlan}, // Network identification plan
4481 {"id", 0xff, 0}, // Network identification
4482 {0,0,0}
4483 };
4484
4485 // *** Q.931 4.5.22: Notification
4486
4487 const TokenDict Q931Parser::s_dict_notification[] = {
4488 {"suspended", 0x00},
4489 {"resumed", 0x01},
4490 {"bearer-service-change", 0x02},
4491 {0,0}
4492 };
4493
4494 // IE description
4495 static const IEParam s_ie_ieNotification[] = {
4496 {"notification", 0x7f, Q931Parser::s_dict_notification},
4497 {0,0,0}
4498 };
4499
4500 // *** Q.931 4.5.23: Progress indication
4501
4502 // Progress description: Bits 0-6
4503 const TokenDict Q931Parser::s_dict_progressDescr[] = {
4504 {"non-isdn", 0x01}, // Call is not end-to-end ISDN, further call progress info may be present in-band
4505 {"non-isdn-destination", 0x02}, // Destination address is non ISDN
4506 {"non-isdn-source", 0x03}, // Source address is non ISDN
4507 {"return-to-isdn", 0x04}, // Call has returned to the ISDN
4508 {"interworking", 0x05}, // Interworking has occurred and has resulted in a telecommunication change
4509 {"in-band-info", 0x08}, // In-band info or an appropriate pattern is now available
4510 {0,0}
4511 };
4512
4513 // IE description
4514 static const IEParam s_ie_ieProgress[] = {
4515 {"location", 0x0f, SignallingUtils::locations()},
4516 {"description", 0x7f, Q931Parser::s_dict_progressDescr},
4517 {0,0,0}
4518 };
4519
4520 // *** Q.931 4.5.25: Restart indicator
4521
4522 // Class: Bits 0-2
4523 const TokenDict Q931Parser::s_dict_restartClass[] = {
4524 {"channels", 0x00}, // Indicated channels
4525 {"interface", 0x06}, // Single interface
4526 {"all-interfaces", 0x07}, // All interfaces
4527 {0,0}
4528 };
4529
4530 // IE description
4531 static const IEParam s_ie_ieRestart[] = {
4532 {"class", 0x07, Q931Parser::s_dict_restartClass},
4533 {0,0,0}
4534 };
4535
4536 // *** Q.931 4.5.26: Segmented message
4537
4538 // IE description
4539 static const IEParam s_ie_ieSegmented[] = {
4540 {"first", 0x80, 0}, // First/subsequent segment
4541 {"remaining", 0x7f, 0}, // Number of segments remaining
4542 {"message", 0x7f, 0}, // Segmented message type
4543 {0,0,0}
4544 };
4545
4546 // *** Q.931 4.5.28: Signal
4547
4548 // Q.931 4.5.28 Signal values: first byte
4549 const TokenDict Q931Parser::s_dict_signalValue[] = {
4550 {"dial", 0x00}, // Dial tone on
4551 {"ring", 0x01}, // Ring back tone on
4552 {"intercept", 0x02}, // Intercept tone on
4553 {"congestion", 0x03}, // Network congestion tone on
4554 {"busy", 0x04}, // Busy tone on
4555 {"confirm", 0x05}, // Confirm tone on
4556 {"answer", 0x06}, // Answer tone on
4557 {"call-waiting", 0x07}, // Call waiting tone on
4558 {"off-hook", 0x08}, // Off-hook tone on
4559 {"preemption", 0x09}, // Preemption tone on
4560 {"tones-off", 0x3f}, // Tones off
4561 {"patern0", 0x40}, // Alering on - patern 0
4562 {"patern1", 0x41}, // Alering on - patern 1
4563 {"patern2", 0x42}, // Alering on - patern 2
4564 {"patern3", 0x43}, // Alering on - patern 3
4565 {"patern4", 0x44}, // Alering on - patern 4
4566 {"patern5", 0x45}, // Alering on - patern 5
4567 {"patern6", 0x46}, // Alering on - patern 6
4568 {"patern7", 0x47}, // Alering on - patern 7
4569 {"alerting-off", 0x4f}, // Alerting off
4570 {0,0}
4571 };
4572
4573 // IE description
4574 static const IEParam s_ie_ieSignal[] = {
4575 {"signal", 0xff, Q931Parser::s_dict_signalValue}, // Signal value
4576 {0,0,0}
4577 };
4578
4579 // *** Q.931 4.5.30: User-user
4580
4581 // IE description
4582 static const IEParam s_ie_ieUserUser[] = {
4583 {"protocol", 0xff, 0}, // Protocol discriminator
4584 {"information", 0xff, 0}, // User information
4585 {0,0,0}
4586 };
4587
4588 // Decode received buffer
decode(const DataBlock & buffer,DataBlock * segData)4589 ISDNQ931Message* Q931Parser::decode(const DataBlock& buffer, DataBlock* segData)
4590 {
4591 XDebug(m_settings->m_dbg,DebugAll,"Start parse %u bytes",buffer.length());
4592 // Set data
4593 u_int8_t* data = (u_int8_t*)buffer.data();
4594 u_int32_t len = buffer.length();
4595 // Parse header. Create message
4596 if (!createMessage(data,len))
4597 return reset();
4598 // Skip header bytes:
4599 // 3: protocol discriminator, call reference length, message type
4600 // n: call reference
4601 u_int32_t consumed = 3 + m_msg->callRefLen();
4602 ISDNQ931IE* ie = 0;
4603 // Parse SEGMENT
4604 if (m_msg->type() == ISDNQ931Message::Segment) {
4605 len -= consumed;
4606 data += consumed;
4607 return processSegment(data,len,segData);
4608 }
4609 // Parse IEs
4610 m_activeCodeset = m_codeset = 0;
4611 for (;;) {
4612 // Append IE if any
4613 if (ie) {
4614 // Skip non-locked IEs if told to do so
4615 if (m_settings->flag(ISDNQ931::IgnoreNonLockedIE)) {
4616 bool ignore = false;
4617 if (ie->type() == ISDNQ931IE::Shift)
4618 ignore = m_skip = !ie->getBoolValue(YSTRING("lock"),false);
4619 else if (m_skip) {
4620 ignore = true;
4621 m_skip = false;
4622 }
4623 if (ignore) {
4624 String* s = static_cast<String*>(ie);
4625 *s = String("ignored-") + *s;
4626 }
4627 }
4628 XDebug(m_settings->m_dbg,DebugAll,"Adding IE '%s'. %u bytes consumed [%p]",
4629 ie->c_str(),consumed,m_msg);
4630 if (m_settings->m_extendedDebug)
4631 ie->m_buffer.assign(data,consumed);
4632 m_msg->append(ie);
4633 }
4634 // Reset the active codeset
4635 m_activeCodeset = m_codeset;
4636 // End of data ?
4637 if (consumed >= len)
4638 break;
4639 len -= consumed;
4640 data += consumed;
4641 consumed = 0;
4642 ie = getIE(data,len,consumed);
4643 if (!ie)
4644 break;
4645 // Check shift
4646 if (ie->type() == ISDNQ931IE::Shift)
4647 shiftCodeset(ie);
4648 }
4649 return reset();
4650 }
4651
4652 // Encode a message to a buffer. If buffer is too long, split it into segments if allowed
encode(ISDNQ931Message * msg,ObjList & dest)4653 u_int8_t Q931Parser::encode(ISDNQ931Message* msg, ObjList& dest)
4654 {
4655 if (!msg)
4656 return 0;
4657 m_msg = msg;
4658 // Set message header buffer
4659 // Proto discriminator (1) + call reference length (1) + call reference (max 4) + type (1) + [Segmented IE]
4660 u_int8_t header[7 + Q931_MAX_SEGMENTED_LEN];
4661 ::memset(header,0,sizeof(header));
4662 u_int8_t headerLen = fillHeader(header,m_msg,m_settings->m_dbg);
4663 if (!headerLen) {
4664 reset();
4665 return 0;
4666 }
4667 if (m_settings->m_extendedDebug)
4668 msg->m_buffer.assign(header,headerLen);
4669 // We assume that at this point the IE list is ready to be encoded as it is
4670 // Check if segmentation is allowed
4671 if (!m_settings->m_allowSegment)
4672 return encodeMessage(dest,false,header,headerLen);
4673 // Segmentation is allowed
4674 bool segmented = false;
4675 // Encode each IE into it's buffer. Check if the largest IE will fit in a message
4676 if (!encodeIEList(segmented,headerLen))
4677 return reset(0);
4678 // Check if the message is segmented
4679 if (!segmented)
4680 return encodeMessage(dest,true,header,headerLen);
4681 // Message will be segmented. Change the header
4682 // Change the message type to Segment. Append Segmented IE
4683 u_int8_t msgType = header[headerLen - 1]; // Message type it's the last byte of the header
4684 header[headerLen - 1] = 0x7f & (u_int8_t)ISDNQ931Message::Segment;
4685 header[headerLen++] = 0x7f & (u_int8_t)ISDNQ931IE::Segmented;
4686 header[headerLen++] = 2; // IE information length after IE header
4687 u_int8_t remainingIdx = headerLen; // Remember the index to write the remaining segments count
4688 header[headerLen++] = 0; // Reserved space for remaining segments
4689 header[headerLen++] = msgType; // Message type
4690 // Create message segments
4691 ObjList* obj = m_msg->ieList()->skipNull();
4692 u_int8_t count = 0;
4693 DataBlock* segment = 0;
4694 while (true) {
4695 ISDNQ931IE* ie = static_cast<ISDNQ931IE*>(obj->get());
4696 DataBlock* data = &(ie->m_buffer);
4697 obj = obj->skipNext();
4698 // Force append when done with the list
4699 bool append = (bool)(!obj);
4700 if (!segment)
4701 segment = new DataBlock(header,headerLen);
4702 // Add data to buffer if we have enough place
4703 // Force append if new data excceeds the segment length
4704 if (segment->length() + data->length() <= m_settings->m_maxMsgLen) {
4705 *segment += *data;
4706 data = 0;
4707 }
4708 else
4709 append = true;
4710 // Append segment to list
4711 if (append) {
4712 if (!appendSegment(dest,segment,count)) {
4713 count = 0;
4714 break;
4715 }
4716 segment = 0;
4717 }
4718 // Append data to segment if not already added
4719 if (data) {
4720 if (!segment)
4721 segment = new DataBlock(header,headerLen);
4722 *segment += *data;
4723 }
4724 // Keep going if we have more IEs
4725 if (obj)
4726 continue;
4727 // No more IEs. Check if last one was added to segment
4728 if (segment && !appendSegment(dest,segment,count)) {
4729 count = 0;
4730 break;
4731 }
4732 break;
4733 }
4734 if (!count) {
4735 dest.clear();
4736 return reset(0);
4737 }
4738 u_int8_t remaining = count;
4739 bool first = true;
4740 obj = dest.skipNull();
4741 for (; obj; obj = obj->skipNext()) {
4742 segment = static_cast<DataBlock*>(obj->get());
4743 u_int8_t* data = (u_int8_t*)(segment->data());
4744 if (!first)
4745 data[remainingIdx] = --remaining;
4746 else {
4747 data[remainingIdx] = 0x80 | --remaining;
4748 first = false;
4749 }
4750 }
4751 return reset(count);
4752 }
4753
4754 // Create message segments if segmented
encodeMessage(ObjList & dest,bool ieEncoded,u_int8_t * header,u_int8_t headerLen)4755 u_int8_t Q931Parser::encodeMessage(ObjList& dest, bool ieEncoded,
4756 u_int8_t* header, u_int8_t headerLen)
4757 {
4758 DataBlock* buf = new DataBlock(header,headerLen);
4759 ObjList* obj = m_msg->ieList()->skipNull();
4760 for (; obj; obj = obj->skipNext()) {
4761 ISDNQ931IE* ie = static_cast<ISDNQ931IE*>(obj->get());
4762 // Encode current IE if not already encoded
4763 if (!ieEncoded && !encodeIE(ie,ie->m_buffer)) {
4764 delete buf;
4765 return reset(0);
4766 }
4767 // Check for valid data length
4768 if (buf->length() + ie->m_buffer.length() > m_settings->m_maxMsgLen) {
4769 Debug(m_settings->m_dbg,DebugWarn,
4770 "Can't encode message. Length %u exceeds limit %u [%p]",
4771 buf->length() + ie->m_buffer.length(),m_settings->m_maxMsgLen,m_msg);
4772 delete buf;
4773 return reset(0);
4774 }
4775 *buf += ie->m_buffer;
4776 }
4777 dest.append(buf);
4778 return reset(1);
4779 }
4780
4781 // Encode a list of IEs
encodeIEList(bool & segmented,u_int8_t headerLen)4782 bool Q931Parser::encodeIEList(bool& segmented, u_int8_t headerLen)
4783 {
4784 segmented = false;
4785 ObjList* obj = m_msg->ieList()->skipNull();
4786 // Empty message
4787 if (!obj)
4788 return true;
4789 // Encode each IE into it's buffer
4790 u_int32_t dataLen = headerLen;
4791 ISDNQ931IE* ieMax = 0;
4792 for (; obj; obj = obj->skipNext()) {
4793 // Encode current IE
4794 ISDNQ931IE* ie = static_cast<ISDNQ931IE*>(obj->get());
4795 if (!encodeIE(ie,ie->m_buffer))
4796 return false;
4797 // Check if the message will be segmented
4798 if (!segmented) {
4799 dataLen += ie->m_buffer.length();
4800 if (dataLen > m_settings->m_maxMsgLen)
4801 segmented = true;
4802 }
4803 // Keep the IE with the largest buffer
4804 if (!ieMax || ieMax->m_buffer.length() < ie->m_buffer.length())
4805 ieMax = ie;
4806 }
4807 // Check if the largest IE buffer fits a message
4808 if (ieMax && ieMax->m_buffer.length() > m_settings->m_maxMsgLen - headerLen) {
4809 Debug(m_settings->m_dbg,DebugWarn,
4810 "Can't encode message. IE '%s' with length %u won't fit limit %u [%p]",
4811 ieMax->c_str(),ieMax->m_buffer.length(),m_settings->m_maxMsgLen,m_msg);
4812 return false;
4813 }
4814 return true;
4815 }
4816
4817 // Append a segment to a given list
appendSegment(ObjList & dest,DataBlock * segment,u_int8_t & count)4818 bool Q931Parser::appendSegment(ObjList& dest, DataBlock* segment,
4819 u_int8_t& count)
4820 {
4821 count++;
4822 // We can't split a message in more then 128 segments (see Q.931 4.5.26)
4823 if (count <= m_settings->m_maxSegments) {
4824 dest.append(segment);
4825 return true;
4826 }
4827 delete segment;
4828 Debug(m_settings->m_dbg,DebugWarn,
4829 "Can't encode message. Too many segments [%p]",m_msg);
4830 return false;
4831 }
4832
4833 // Encode a single IE
encodeIE(ISDNQ931IE * ie,DataBlock & buffer)4834 bool Q931Parser::encodeIE(ISDNQ931IE* ie, DataBlock& buffer)
4835 {
4836 switch (ie->type()) {
4837 case ISDNQ931IE::BearerCaps: return encodeBearerCaps(ie,buffer);
4838 case ISDNQ931IE::Cause:
4839 {
4840 DataBlock tmp;
4841 if (SignallingUtils::encodeCause(
4842 static_cast<SignallingComponent*>(m_settings->m_dbg),
4843 tmp,*ie,ISDNQ931IE::typeName(ie->type()),false)) {
4844 unsigned char id = ISDNQ931IE::Cause;
4845 buffer.assign(&id,1);
4846 buffer += tmp;
4847 return true;
4848 }
4849 return false;
4850 }
4851 case ISDNQ931IE::Display: return encodeDisplay(ie,buffer);
4852 case ISDNQ931IE::CallingNo: return encodeCallingNo(ie,buffer);
4853 case ISDNQ931IE::CalledNo: return encodeCalledNo(ie,buffer);
4854 case ISDNQ931IE::CallState: return encodeCallState(ie,buffer);
4855 case ISDNQ931IE::ChannelID: return encodeChannelID(ie,buffer);
4856 case ISDNQ931IE::Progress: return encodeProgress(ie,buffer);
4857 case ISDNQ931IE::Notification: return encodeNotification(ie,buffer);
4858 case ISDNQ931IE::Keypad: return encodeKeypad(ie,buffer);
4859 case ISDNQ931IE::Signal: return encodeSignal(ie,buffer);
4860 case ISDNQ931IE::Restart: return encodeRestart(ie,buffer);
4861 case ISDNQ931IE::SendComplete: return encodeSendComplete(ie,buffer);
4862 case ISDNQ931IE::HiLayerCompat: return encodeHighLayerCap(ie,buffer);
4863 case ISDNQ931IE::UserUser: return encodeUserUser(ie,buffer);
4864 }
4865 Debug(m_settings->m_dbg,DebugMild,"Encoding not implemented for IE '%s' [%p]",
4866 ie->c_str(),m_msg);
4867 // Encode anyway. Only type with length=0
4868 u_int8_t header[2] = {(u_int8_t)ie->type(),0};
4869 buffer.assign(header,sizeof(header));
4870 return true;
4871 }
4872
errorParseIE(ISDNQ931IE * ie,const char * reason,const u_int8_t * data,u_int32_t len)4873 ISDNQ931IE* Q931Parser::errorParseIE(ISDNQ931IE* ie,
4874 const char* reason, const u_int8_t* data, u_int32_t len)
4875 {
4876 Debug(m_settings->m_dbg,DebugNote,"Error parse IE ('%s'): %s [%p]",
4877 ie->c_str(),reason,m_msg);
4878 ie->addParam("error",reason);
4879 if (len)
4880 SignallingUtils::dumpData(0,*ie,"error-data",data,len);
4881 return ie;
4882 }
4883
4884 // Check the coding standard of an IE
checkCoding(u_int8_t value,u_int8_t expected,ISDNQ931IE * ie)4885 bool Q931Parser::checkCoding(u_int8_t value, u_int8_t expected, ISDNQ931IE* ie)
4886 {
4887 value &= 0x60;
4888 if (value == expected)
4889 return true;
4890 String s = lookup(value,SignallingUtils::codings(),0);
4891 if (s.null())
4892 s = (unsigned int)value;
4893 ie->addParam("coding",s.c_str());
4894 return false;
4895 }
4896
4897 // Skip extended bytes until a byte with bit 0 is reached
skipExt(const u_int8_t * data,u_int8_t len,u_int8_t & crt)4898 u_int8_t Q931Parser::skipExt(const u_int8_t* data, u_int8_t len, u_int8_t& crt)
4899 {
4900 u_int8_t skip = 0;
4901 for (; crt < len && !Q931_EXT_FINAL(data[crt]); crt++, skip++) ;
4902 if (crt < len) {
4903 crt++;
4904 skip++;
4905 }
4906 return skip;
4907 }
4908
4909 // Create a message from received data (parse message header)
4910 // See Q.931 5.8.1, 5.8.2, 5.8.3.1 for protocol discriminator, message length
4911 // and call reference length errors
createMessage(u_int8_t * data,u_int32_t len)4912 bool Q931Parser::createMessage(u_int8_t* data, u_int32_t len)
4913 {
4914 bool initiator = false;
4915 u_int32_t callRef = 0;
4916 u_int8_t callRefLen = 0;
4917 // We should have at least 3 bytes:
4918 // 1 for protocol discriminator, 1 for call reference and 1 for message type
4919 if (!data || len < 3) {
4920 Debug(m_settings->m_dbg,DebugWarn,
4921 "Not enough data (%u) for message header",len);
4922 return false;
4923 }
4924 // Check protocol discriminator
4925 if (data[0] != Q931_MSG_PROTOQ931) {
4926 Debug(m_settings->m_dbg,DebugWarn,"Unknown protocol discriminator %u",data[0]);
4927 return false;
4928 }
4929 // Check for dummy call reference
4930 if (data[1]) {
4931 // Call id length: bits 4-7 of the 2nd byte should be 0
4932 if (data[1] & 0xf0) {
4933 Debug(m_settings->m_dbg,DebugWarn,
4934 "Call reference length %u is incorrect",data[1]);
4935 return false;
4936 }
4937 // Call id length: bits 0-3 of the 2nd byte
4938 callRefLen = data[1] & 0x0f;
4939 // Initiator flag: bit 7 of the 3rd byte - 0: From initiator. 1: To initiator
4940 initiator = (data[2] & 0x80) == 0;
4941 // We should have at least (callRefLen + 3) bytes:
4942 // 1 for protocol discriminator, 1 for call reference length,
4943 // 1 for message type and the call reference
4944 if ((unsigned int)(callRefLen + 3) > len) {
4945 Debug(m_settings->m_dbg,DebugWarn,
4946 "Call reference length %u greater then data length %u",
4947 callRefLen,len);
4948 return false;
4949 }
4950 // Call reference
4951 switch (callRefLen) {
4952 case 4:
4953 callRef = (data[2] & 0x7f) << 24 | data[3] << 16 | data[4] << 8 | data[5];
4954 break;
4955 case 3:
4956 callRef = (data[2] & 0x7f) << 16 | data[3] << 8 | data[4];
4957 break;
4958 case 2:
4959 callRef = (data[2] & 0x7f) << 8 | data[3];
4960 break;
4961 case 1:
4962 callRef = data[2] & 0x7f;
4963 break;
4964 default:
4965 Debug(m_settings->m_dbg,DebugWarn,
4966 "Unsupported call reference length %u",callRefLen);
4967 return false;
4968 }
4969 }
4970 // Message type: bits 0-6 of the 1st byte after the call reference
4971 u_int8_t t = data[callRefLen + 2] & 0x7f;
4972 if (!ISDNQ931Message::typeName(t)) {
4973 Debug(m_settings->m_dbg,DebugNote,"Unknown message type %u",t);
4974 return false;
4975 }
4976 if (callRefLen)
4977 m_msg = new ISDNQ931Message((ISDNQ931Message::Type)t,initiator,callRef,
4978 callRefLen);
4979 else
4980 m_msg = new ISDNQ931Message((ISDNQ931Message::Type)t);
4981 if (m_settings->m_extendedDebug)
4982 m_msg->m_buffer.assign(data,callRefLen + 3);
4983 XDebug(m_settings->m_dbg,DebugAll,"Created message (%p): '%s'",
4984 m_msg,m_msg->name());
4985 return true;
4986 }
4987
4988 // Process received Segment message
processSegment(const u_int8_t * data,u_int32_t len,DataBlock * segData)4989 ISDNQ931Message* Q931Parser::processSegment(const u_int8_t* data, u_int32_t len,
4990 DataBlock* segData)
4991 {
4992 if (!segData) {
4993 Debug(m_settings->m_dbg,DebugNote,
4994 "Dropping segment message. Not allowed [%p]",m_msg);
4995 TelEngine::destruct(m_msg);
4996 return reset();
4997 }
4998 u_int32_t consumed = 0;
4999 ISDNQ931IE* ie = getIE(data,len,consumed);
5000 if (!ie) {
5001 TelEngine::destruct(m_msg);
5002 return reset();
5003 }
5004 if (ie->type() != ISDNQ931IE::Segmented || consumed > len) {
5005 Debug(m_settings->m_dbg,DebugNote,
5006 "Dropping segment message with missing or invalid Segmented IE [%p]",
5007 m_msg);
5008 delete ie;
5009 TelEngine::destruct(m_msg);
5010 return reset();
5011 }
5012 m_msg->append(ie);
5013 segData->assign((void*)(data + consumed),len - consumed);
5014 return reset();
5015 }
5016
5017 // Get a single IE from a buffer
getIE(const u_int8_t * data,u_int32_t len,u_int32_t & consumed)5018 ISDNQ931IE* Q931Parser::getIE(const u_int8_t* data, u_int32_t len, u_int32_t& consumed)
5019 {
5020 consumed = 0;
5021 if (!(data && len))
5022 return 0;
5023 // Check if this is a fixed (1 byte length) or variable length IE
5024 // Fixed: Bit 7 is 1. See Q.931 4.5.1
5025 if ((data[0] >> 7)) {
5026 consumed = 1;
5027 return getFixedIE(data[0]);
5028 }
5029 // Get type
5030 u_int16_t type = ((u_int16_t)m_activeCodeset << 8) | data[0];
5031 // Variable length
5032 // Check/Get length. Byte 2 is the length of the rest of the IE
5033 u_int8_t ieLen = ((len == 1) ? 1 : data[1]);
5034 XDebug(m_settings->m_dbg,DebugAll,"Decoding IE %u=%s len=%u [%p]",
5035 type,ISDNQ931IE::typeName(type,"Unknown"),ieLen,m_msg);
5036 if (len == 1 || ieLen > len - 2) {
5037 Debug(m_settings->m_dbg,DebugNote,
5038 "Invalid variable IE length %u. Remaing data: %u [%p]",
5039 ieLen,len,m_msg);
5040 consumed = len;
5041 return 0;
5042 }
5043 consumed = 2 + ieLen;
5044 // Skip type and length
5045 u_int8_t* ieData = (u_int8_t*)data + 2;
5046 switch (type) {
5047 #define CASE_DECODE_IE(id,method) case id: return method(new ISDNQ931IE(id),ieData,ieLen);
5048 CASE_DECODE_IE(ISDNQ931IE::BearerCaps,decodeBearerCaps)
5049 CASE_DECODE_IE(ISDNQ931IE::Display,decodeDisplay)
5050 CASE_DECODE_IE(ISDNQ931IE::CallingNo,decodeCallingNo)
5051 CASE_DECODE_IE(ISDNQ931IE::CalledNo,decodeCalledNo)
5052 CASE_DECODE_IE(ISDNQ931IE::CallIdentity,decodeCallIdentity)
5053 CASE_DECODE_IE(ISDNQ931IE::CallState,decodeCallState)
5054 CASE_DECODE_IE(ISDNQ931IE::ChannelID,decodeChannelID)
5055 CASE_DECODE_IE(ISDNQ931IE::Progress,decodeProgress)
5056 CASE_DECODE_IE(ISDNQ931IE::NetFacility,decodeNetFacility)
5057 CASE_DECODE_IE(ISDNQ931IE::Notification,decodeNotification)
5058 CASE_DECODE_IE(ISDNQ931IE::DateTime,decodeDateTime)
5059 CASE_DECODE_IE(ISDNQ931IE::Keypad,decodeKeypad)
5060 CASE_DECODE_IE(ISDNQ931IE::Signal,decodeSignal)
5061 CASE_DECODE_IE(ISDNQ931IE::ConnectedNo,decodeConnectedNo)
5062 CASE_DECODE_IE(ISDNQ931IE::CallingSubAddr,decodeCallingSubAddr)
5063 CASE_DECODE_IE(ISDNQ931IE::CalledSubAddr,decodeCalledSubAddr)
5064 CASE_DECODE_IE(ISDNQ931IE::Restart,decodeRestart)
5065 CASE_DECODE_IE(ISDNQ931IE::Segmented,decodeSegmented)
5066 CASE_DECODE_IE(ISDNQ931IE::NetTransit,decodeNetTransit)
5067 CASE_DECODE_IE(ISDNQ931IE::LoLayerCompat,decodeLoLayerCompat)
5068 CASE_DECODE_IE(ISDNQ931IE::HiLayerCompat,decodeHiLayerCompat)
5069 CASE_DECODE_IE(ISDNQ931IE::UserUser,decodeUserUser)
5070 #undef CASE_DECODE_IE
5071 case ISDNQ931IE::Cause:
5072 {
5073 ISDNQ931IE* ie = new ISDNQ931IE(type);
5074 if (SignallingUtils::decodeCause(
5075 static_cast<SignallingComponent*>(m_settings->m_dbg),
5076 *ie,ieData,ieLen,ie->c_str(),false))
5077 return ie;
5078 TelEngine::destruct(ie);
5079 return 0;
5080 }
5081 default: ;
5082 }
5083 // Unknown or unhandled IE
5084 // Check bits 4-7: If 0: the value MUST be a known one (See Q.931, Table 4-3, Note 5)
5085 if ((data[0] >> 4) == 0) {
5086 Debug(m_settings->m_dbg,DebugMild,
5087 "Found unknown mandatory IE: %u [%p]",type,m_msg);
5088 m_msg->setUnknownMandatory();
5089 }
5090 ISDNQ931IE* ie = new ISDNQ931IE(type);
5091 SignallingUtils::dumpData(0,*ie,"dumped-data",ieData,ieLen);
5092 return ie;
5093 }
5094
5095 // Check Shift IE. Change current codeset
shiftCodeset(const ISDNQ931IE * ie)5096 void Q931Parser::shiftCodeset(const ISDNQ931IE* ie)
5097 {
5098 bool locking = ie->getBoolValue(YSTRING("lock"),false);
5099 int value = ie->getIntValue(YSTRING("codeset"),0);
5100 XDebug(m_settings->m_dbg,DebugAll,
5101 "Process %s shift with codeset %u [%p]",
5102 locking?"locking":"non locking",value,m_msg);
5103 // Values 1,2,3 are reserved
5104 if (value && value < 4) {
5105 Debug(m_settings->m_dbg,DebugNote,
5106 "Ignoring shift with reserved codeset [%p]",m_msg);
5107 return;
5108 }
5109 // Non locking shift
5110 if (!locking) {
5111 DDebug(m_settings->m_dbg,DebugNote,
5112 "Non locking shift. Set active codeset to %u [%p]",
5113 value,m_msg);
5114 m_activeCodeset = value;
5115 return;
5116 }
5117 // Locking shift. MUST not be lower then the current one
5118 if (value < m_codeset) {
5119 Debug(m_settings->m_dbg,DebugNote,
5120 "Ignoring locking shift with lower value %u then the current one %u [%p]",
5121 value,m_codeset,m_msg);
5122 return;
5123 }
5124 m_activeCodeset = m_codeset = value;
5125 DDebug(m_settings->m_dbg,DebugNote,
5126 "Locking shift. Codeset set to %u [%p]",m_codeset,m_msg);
5127 }
5128
5129 // Parse a single fixed length IE
getFixedIE(u_int8_t data)5130 ISDNQ931IE* Q931Parser::getFixedIE(u_int8_t data)
5131 {
5132 // Type1: bits 7-4 define the IE type. Bits 3-0 contain the value
5133 // Type2: bits 7-4 are 1010. The type is the whole byte
5134 u_int16_t type = data & 0xf0;
5135 if (type == 0xa0)
5136 type = data;
5137 type |= (u_int16_t)m_activeCodeset << 8;
5138 ISDNQ931IE* ie = new ISDNQ931IE(type);
5139 switch (type) {
5140 // Type 1
5141 case ISDNQ931IE::Shift:
5142 s_ie_ieFixed[0].addBoolParam(ie,data,true);
5143 s_ie_ieFixed[1].addIntParam(ie,data);
5144 break;
5145 case ISDNQ931IE::Congestion:
5146 s_ie_ieFixed[2].addIntParam(ie,data);
5147 break;
5148 case ISDNQ931IE::Repeat:
5149 s_ie_ieFixed[3].addIntParam(ie,data);
5150 break;
5151 // Type 2
5152 case ISDNQ931IE::MoreData:
5153 case ISDNQ931IE::SendComplete:
5154 break;
5155 default:
5156 SignallingUtils::dumpData(0,*ie,"Unknown fixed IE",&data,1);
5157 }
5158 return ie;
5159 }
5160
5161 // Q.931 4.5.5
decodeBearerCaps(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5162 ISDNQ931IE* Q931Parser::decodeBearerCaps(ISDNQ931IE* ie, const u_int8_t* data,
5163 u_int32_t len)
5164 {
5165 #define CHECK_INDEX(idx) {if (idx >= len) return errorParseIE(ie,len ? s_errorWrongData : s_errorNoData,0,0);}
5166 CHECK_INDEX(0)
5167 // Byte 0: Coding standard (bit 5,6), Information transfer capability (bit 0-4)
5168 // Translate transfer cap 0x08 to 0x10
5169 if (!checkCoding(data[0],0,ie)) // Check coding standard (CCITT: 0)
5170 return errorParseIE(ie,s_errorUnsuppCoding,data,len);
5171 s_ie_ieBearerCaps[0].addIntParam(ie,data[0]);
5172 if (m_settings->flag(ISDNQ931::Translate31kAudio)) {
5173 NamedString* ns = ie->getParam(s_ie_ieBearerCaps[0].name);
5174 if (ns && *ns == lookup(0x08,s_ie_ieBearerCaps[0].values))
5175 *ns = lookup(0x10,s_ie_ieBearerCaps[0].values);
5176 }
5177 // End of data ?
5178 CHECK_INDEX(1)
5179 // Byte 1: Transfer mode (bit 5,6), Transfer rate (bit 0-4)
5180 s_ie_ieBearerCaps[1].addIntParam(ie,data[1]); // Transfer mode
5181 s_ie_ieBearerCaps[2].addIntParam(ie,data[1]); // Transfer rate
5182 u_int8_t crt = 2;
5183 // Figure 4.11 Note 1: Next byte is the rate multiplier if the transfer rate is 'multirate' (0x18)
5184 if ((data[1] & 0x1f) == 0x18) {
5185 CHECK_INDEX(2)
5186 s_ie_ieBearerCaps[3].addIntParam(ie,data[2]);
5187 crt = 3;
5188 }
5189 // Get user information layer data
5190 u_int8_t crtLayer = 0;
5191 while (true) {
5192 // End of data ?
5193 if (crt >= len)
5194 return ie;
5195 // Get and check layer (must be greater than the current one)
5196 u_int8_t layer = (data[crt] & 0x60) >> 5;
5197 if (layer <= crtLayer || layer > 3)
5198 return errorParseIE(ie,s_errorWrongData,data + crt,len - crt);
5199 crtLayer = layer;
5200 // Process layer information
5201 switch (crtLayer) {
5202 case 1:
5203 decodeLayer1(ie,data,len,crt,s_ie_ieBearerCaps,4);
5204 continue;
5205 case 2:
5206 decodeLayer2(ie,data,len,crt,s_ie_ieBearerCaps,6);
5207 continue;
5208 case 3:
5209 decodeLayer3(ie,data,len,crt,s_ie_ieBearerCaps,7);
5210 }
5211 break;
5212 }
5213 // Dump any remaining data
5214 if (crt < len)
5215 SignallingUtils::dumpData(0,*ie,"garbage",data+crt,len-crt);
5216 return ie;
5217 #undef CHECK_INDEX
5218 }
5219
5220 // Q.931 4.5.6
decodeCallIdentity(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5221 ISDNQ931IE* Q931Parser::decodeCallIdentity(ISDNQ931IE* ie, const u_int8_t* data,
5222 u_int32_t len)
5223 {
5224 if (!len)
5225 return errorParseIE(ie,s_errorNoData,0,0);
5226 s_ie_ieCallIdentity[0].dumpData(ie,data,len);
5227 return ie;
5228 }
5229
5230 // Q.931 4.5.7
decodeCallState(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5231 ISDNQ931IE* Q931Parser::decodeCallState(ISDNQ931IE* ie, const u_int8_t* data,
5232 u_int32_t len)
5233 {
5234 if (!len)
5235 return errorParseIE(ie,s_errorNoData,0,0);
5236 if (!checkCoding(data[0],0,ie)) // Check coding standard (CCITT: 0)
5237 return errorParseIE(ie,s_errorUnsuppCoding,data,len);
5238 s_ie_ieCallState[0].addIntParam(ie,data[0]);
5239 if (len > 1)
5240 SignallingUtils::dumpData(0,*ie,"garbage",data + 1,len - 1);
5241 return ie;
5242 }
5243
5244 // Q.931 4.5.13
decodeChannelID(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5245 ISDNQ931IE* Q931Parser::decodeChannelID(ISDNQ931IE* ie, const u_int8_t* data,
5246 u_int32_t len)
5247 {
5248 #define DUMP_DATA_AND_EXIT {if (crt < len) SignallingUtils::dumpData(0,*ie,"garbage",data+crt,len-crt); return ie;}
5249 if (!len)
5250 return errorParseIE(ie,s_errorNoData,0,0);
5251 // Byte 0
5252 // Bit 6 - Interface identifier 0: implicit 1: identified by the next byte(s)
5253 // Bit 5 - Interface type 0: basic 1: other (e.g. primary rate)
5254 // Bit 3 - Preferred/exclusive channel 0: indicated channel is preferred 1: only indicated channel is acceptable
5255 // Bit 2 - Identified channel is a D-channel or not
5256 // Bit 0,1 - Channel selection
5257 bool briInterface = s_ie_ieChannelID[0].addBoolParam(ie,data[0],true); // Interface type
5258 s_ie_ieChannelID[1].addBoolParam(ie,data[0],false); // Preferred/Exclusive B channel
5259 s_ie_ieChannelID[2].addBoolParam(ie,data[0],false); // D-channel flag
5260 // Channel selection
5261 if (briInterface)
5262 s_ie_ieChannelID[3].addParam(ie,data[0]); // Channel select for BRI interface
5263 else
5264 s_ie_ieChannelID[4].addParam(ie,data[0]); // Channel select for PRI interface
5265 // Optional Byte 1: Interface identifier if present
5266 u_int8_t crt = 1;
5267 bool interfaceIDExplicit = (data[0] & 0x40) != 0;
5268 if (interfaceIDExplicit) {
5269 if (len == 1)
5270 return errorParseIE(ie,s_errorWrongData,0,0);
5271 // Calculate length of the interface ID
5272 for (; crt < len && !Q931_EXT_FINAL(data[crt]); crt++);
5273 s_ie_ieChannelID[5].dumpData(ie,data + 1,crt - 1);
5274 crt++;
5275 }
5276 // See Q.931 Figure 4.18, Note 2 and 5. Terminate if it's a BRI interface or the interface is explicitely given
5277 // If not a BRI interface or the interface is not explicit:
5278 // check channel selection. If 1: the channel is indicated by the following bytes = continue
5279 if (briInterface || interfaceIDExplicit || 1 != (data[0] & 0x03))
5280 DUMP_DATA_AND_EXIT
5281 // Optional Byte: Coding standard (bit 5,6), Channel indication (bit 4), Channel type (bit 0-3)
5282 // Check coding standard (CCITT: 0)
5283 if (crt >= len)
5284 return ie;
5285 if (!checkCoding(data[crt],0,ie))
5286 return errorParseIE(ie,s_errorUnsuppCoding,data + crt,len - crt);
5287 bool byNumber = s_ie_ieChannelID[6].addBoolParam(ie,data[crt],true); // Channel is indicated by number/slot-map
5288 s_ie_ieChannelID[7].addIntParam(ie,data[crt]); // Channel type
5289 crt++;
5290 // Optional Byte: Channel number or slot map
5291 // The rest of the data is a list of channels or the slot map
5292 if (crt >= len)
5293 return ie;
5294 u_int8_t idx = byNumber ? 8 : 9;
5295 String param;
5296 for (; crt < len; crt++) {
5297 String tmp((unsigned int)(data[crt] & s_ie_ieChannelID[idx].mask));
5298 param.append(tmp,",");
5299 // Bit 7 is used to end channel numbers. See Q.931 Figure 4.18 Note 3
5300 if (byNumber && Q931_EXT_FINAL(data[crt])) {
5301 crt++;
5302 break;
5303 }
5304 }
5305 ie->addParam(s_ie_ieChannelID[idx].name,param);
5306 DUMP_DATA_AND_EXIT
5307 #undef DUMP_DATA_AND_EXIT
5308 }
5309
5310 // Q.931 4.5.23
decodeProgress(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5311 ISDNQ931IE* Q931Parser::decodeProgress(ISDNQ931IE* ie, const u_int8_t* data,
5312 u_int32_t len)
5313 {
5314 if (!len)
5315 return errorParseIE(ie,s_errorNoData,0,0);
5316 // data[0]: Bits 5,6: coding standard
5317 // Bits 0-3: Location
5318 if (!checkCoding(data[0],0,ie)) // Check coding standard (CCITT: 0)
5319 return errorParseIE(ie,s_errorUnsuppCoding,data,len);
5320 s_ie_ieProgress[0].addIntParam(ie,data[0]);
5321 // data[1]: Progress indication
5322 if (len == 1)
5323 return errorParseIE(ie,s_errorWrongData,0,0);
5324 s_ie_ieProgress[1].addIntParam(ie,data[1]);
5325 // Dump any remaining data
5326 if (len > 2)
5327 SignallingUtils::dumpData(0,*ie,"garbage",data + 2,len - 2);
5328 return ie;
5329 }
5330
5331 // Q.931 4.5.21
decodeNetFacility(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5332 ISDNQ931IE* Q931Parser::decodeNetFacility(ISDNQ931IE* ie, const u_int8_t* data,
5333 u_int32_t len)
5334 {
5335 if (!len)
5336 return errorParseIE(ie,s_errorNoData,0,0);
5337 // data[0]: Length of network identification (0 bytes or at least 2 bytes)
5338 // If non 0: data[1]: Bits 4-6: Type of network identification. Bits 0-3: Network identification plan
5339 // data[2] --> data[crt-1]: Network identification
5340 // data[crt]: Network specific facilities
5341 // Start of 'Network specific facilities'
5342 u_int8_t crt = data[0] + 1;
5343 // Check if the indicated length is correct
5344 if (crt >= len)
5345 return errorParseIE(ie,s_errorWrongData,data,len);
5346 // Network identification exists
5347 if (crt > 1) {
5348 // Mandatory: data[1], data[2]
5349 if (crt < 3)
5350 return errorParseIE(ie,s_errorWrongData,data + 1,1);
5351 s_ie_ieNetFacility[0].addIntParam(ie,data[1]);
5352 s_ie_ieNetFacility[1].addIntParam(ie,data[1]);
5353 s_ie_ieNetFacility[2].dumpDataBit7(ie,data + 2,crt - 2,true);
5354 }
5355 // Network specific facilities
5356 s_ie_ieNetFacility[3].addIntParam(ie,data[crt]);
5357 // Dump any remaining data
5358 crt++;
5359 if (crt < len)
5360 SignallingUtils::dumpData(0,*ie,"garbage",data + crt,len - crt);
5361 return ie;
5362 }
5363
5364 // Q.931 4.5.22
decodeNotification(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5365 ISDNQ931IE* Q931Parser::decodeNotification(ISDNQ931IE* ie, const u_int8_t* data,
5366 u_int32_t len)
5367 {
5368 if (!len)
5369 return errorParseIE(ie,s_errorNoData,0,0);
5370 s_ie_ieNotification[0].addIntParam(ie,data[0]);
5371 // Dump any remaining data
5372 if (len > 1)
5373 SignallingUtils::dumpData(0,*ie,"garbage",data + 1,len - 1);
5374 return ie;
5375 }
5376
5377 // Q.931 4.5.15
decodeDateTime(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5378 ISDNQ931IE* Q931Parser::decodeDateTime(ISDNQ931IE* ie, const u_int8_t* data,
5379 u_int32_t len)
5380 {
5381 #define DATETIME_SET(crt) \
5382 if (crt >= len) return errorParseIE(ie,s_errorWrongData,0,0);\
5383 s_ie_ieDateTime[crt].addIntParam(ie,data[crt]);
5384 #define DATETIME_SET_OPT(crt) \
5385 if (crt >= len) return ie;\
5386 s_ie_ieDateTime[crt].addIntParam(ie,data[crt]); \
5387 crt++;
5388 if (!len)
5389 return errorParseIE(ie,s_errorNoData,0,0);
5390 DATETIME_SET(0)
5391 DATETIME_SET(1)
5392 DATETIME_SET(2)
5393 u_int8_t crt = 3;
5394 DATETIME_SET_OPT(crt)
5395 DATETIME_SET_OPT(crt)
5396 DATETIME_SET_OPT(crt)
5397 // Dump any remaining data
5398 if (crt < len)
5399 SignallingUtils::dumpData(0,*ie,"garbage",data + crt,len - crt);
5400 return ie;
5401 #undef DATETIME_SET
5402 #undef DATETIME_SET_OPT
5403 }
5404
5405 // Q.931 4.5.16
decodeDisplay(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5406 ISDNQ931IE* Q931Parser::decodeDisplay(ISDNQ931IE* ie, const u_int8_t* data,
5407 u_int32_t len)
5408 {
5409 if (!len)
5410 return errorParseIE(ie,s_errorNoData,0,0);
5411 // Check charset
5412 if (0 != (data[0] & 0x80)) {
5413 s_ie_ieDisplay[0].addIntParam(ie,data[0]);
5414 data++;
5415 len--;
5416 }
5417 s_ie_ieDisplay[1].dumpDataBit7(ie,data,len,false);
5418 return ie;
5419 }
5420
5421 // Q.931 4.5.18
decodeKeypad(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5422 ISDNQ931IE* Q931Parser::decodeKeypad(ISDNQ931IE* ie, const u_int8_t* data,
5423 u_int32_t len)
5424 {
5425 if (!len)
5426 return errorParseIE(ie,s_errorNoData,0,0);
5427 s_ie_ieKeypad[0].dumpDataBit7(ie,data,len,false);
5428 return ie;
5429 }
5430
5431 // Q.931 4.5.28
decodeSignal(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5432 ISDNQ931IE* Q931Parser::decodeSignal(ISDNQ931IE* ie, const u_int8_t* data,
5433 u_int32_t len)
5434 {
5435 if (!len)
5436 return errorParseIE(ie,s_errorNoData,0,0);
5437 s_ie_ieSignal[0].addIntParam(ie,data[0]);
5438 // Dump any remaining data
5439 if (len > 1)
5440 SignallingUtils::dumpData(0,*ie,"garbage",data + 1,len - 1);
5441 return ie;
5442 }
5443
5444 // Q.931 4.5.10
decodeCallingNo(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5445 ISDNQ931IE* Q931Parser::decodeCallingNo(ISDNQ931IE* ie, const u_int8_t* data,
5446 u_int32_t len)
5447 {
5448 if (!len)
5449 return errorParseIE(ie,s_errorNoData,0,0);
5450 // Byte 0: Type of number (bit 4-6), Numbering plan (bit 0-3)
5451 // Number type
5452 s_ie_ieNumber[0].addParam(ie,data[0]); // Type of number
5453 switch (data[0] & 0x70) { // Numbering plan (applicable only if type is 0,1,2,4)
5454 case 0x00: case 0x10: case 0x20: case 0x40:
5455 s_ie_ieNumber[1].addParam(ie,data[0]);
5456 }
5457 // End of data ?
5458 if (len == 1)
5459 return ie;
5460 // Optional Byte 1: Presentation indicator (bit 5,6), Screening (bit 0,1)
5461 // Presentation exists ?
5462 u_int8_t crt = Q931_EXT_FINAL(data[0]) ? 1 : 2;
5463 if (crt == 2) {
5464 s_ie_ieNumber[2].addParam(ie,data[1]);
5465 s_ie_ieNumber[3].addParam(ie,data[1]);
5466 }
5467 // Rest of data: The number
5468 if (crt < len)
5469 s_ie_ieNumber[4].dumpDataBit7(ie,data + crt,len - crt,false);
5470 return ie;
5471 }
5472
5473 // Q.931 4.5.11
decodeCallingSubAddr(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5474 ISDNQ931IE* Q931Parser::decodeCallingSubAddr(ISDNQ931IE* ie, const u_int8_t* data,
5475 u_int32_t len)
5476 {
5477 if (!len)
5478 return errorParseIE(ie,s_errorNoData,0,0);
5479 s_ie_ieSubAddress[0].addIntParam(ie,data[0]);
5480 s_ie_ieSubAddress[1].addBoolParam(ie,data[0],false);
5481 if (len == 1)
5482 return errorParseIE(ie,s_errorNoData,0,0);
5483 s_ie_ieSubAddress[2].dumpData(ie,data + 1,len - 1);
5484 return ie;
5485 }
5486
5487 // Q.931 4.5.8
decodeCalledNo(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5488 ISDNQ931IE* Q931Parser::decodeCalledNo(ISDNQ931IE* ie, const u_int8_t* data,
5489 u_int32_t len)
5490 {
5491 if (!len)
5492 return errorParseIE(ie,s_errorNoData,0,0);
5493 // Byte 0: Type of number (bit 4-6), Numbering plan (bit 0-3)
5494 s_ie_ieNumber[0].addParam(ie,data[0]); // Type of number
5495 switch (data[0] & 0x70) { // Numbering plan (applicable only if type is 0,1,2,4)
5496 case 0x00: case 0x10: case 0x20: case 0x40:
5497 s_ie_ieNumber[1].addParam(ie,data[0]);
5498 }
5499 // Rest of data: The number
5500 if (len > 1)
5501 s_ie_ieNumber[4].dumpDataBit7(ie,data + 1,len - 1,false);
5502 return ie;
5503 }
5504
5505 // Q.931 4.5.9
decodeCalledSubAddr(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5506 ISDNQ931IE* Q931Parser::decodeCalledSubAddr(ISDNQ931IE* ie, const u_int8_t* data,
5507 u_int32_t len)
5508 {
5509 if (!len)
5510 return errorParseIE(ie,s_errorNoData,0,0);
5511 s_ie_ieSubAddress[0].addIntParam(ie,data[0]);
5512 s_ie_ieSubAddress[1].addBoolParam(ie,data[0],false);
5513 if (len == 1)
5514 return errorParseIE(ie,s_errorNoData,0,0);
5515 s_ie_ieSubAddress[2].dumpData(ie,data + 1,len - 1);
5516 return ie;
5517 }
5518
5519 // Q.931 4.5.25
decodeRestart(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5520 ISDNQ931IE* Q931Parser::decodeRestart(ISDNQ931IE* ie, const u_int8_t* data,
5521 u_int32_t len)
5522 {
5523 if (!len)
5524 return errorParseIE(ie,s_errorNoData,0,0);
5525 // data[0]: Bits 0-2: Restart class
5526 s_ie_ieRestart[0].addIntParam(ie,data[0]);
5527 // Dump any remaining data
5528 if (len > 1)
5529 SignallingUtils::dumpData(0,*ie,"garbage",data + 1,len - 1);
5530 return ie;
5531 }
5532
5533 // Q.931 4.5.26
decodeSegmented(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5534 ISDNQ931IE* Q931Parser::decodeSegmented(ISDNQ931IE* ie, const u_int8_t* data,
5535 u_int32_t len)
5536 {
5537 if (!len)
5538 return errorParseIE(ie,s_errorNoData,0,0);
5539 // data[0]: bit 7: First/subsequent segment. bits 0-6: number of segments remaining
5540 s_ie_ieSegmented[0].addBoolParam(ie,data[0],false);
5541 s_ie_ieSegmented[1].addIntParam(ie,data[0]);
5542 // Segmented message type
5543 if (len == 1)
5544 return errorParseIE(ie,s_errorWrongData,0,0);
5545 s_ie_ieSegmented[2].addIntParam(ie,data[1]);
5546 // Dump any remaining data
5547 if (len > 2)
5548 SignallingUtils::dumpData(0,*ie,"garbage",data + 2,len - 2);
5549 return ie;
5550 }
5551
5552 // Q.931 4.5.29
decodeNetTransit(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5553 ISDNQ931IE* Q931Parser::decodeNetTransit(ISDNQ931IE* ie, const u_int8_t* data,
5554 u_int32_t len)
5555 {
5556 if (!len)
5557 return errorParseIE(ie,s_errorNoData,0,0);
5558 // data[0]: Bits 4-6: Type of network identification. Bits 0-3: Network identification plan
5559 s_ie_ieNetTransit[0].addIntParam(ie,data[0]);
5560 s_ie_ieNetTransit[1].addIntParam(ie,data[0]);
5561 // Network identification
5562 if (len == 1)
5563 return errorParseIE(ie,s_errorNoData,0,0);
5564 s_ie_ieNetTransit[2].dumpDataBit7(ie,data + 1,len - 1,false);
5565 return ie;
5566 }
5567
5568 // Q.931 4.5.19
decodeLoLayerCompat(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5569 ISDNQ931IE* Q931Parser::decodeLoLayerCompat(ISDNQ931IE* ie, const u_int8_t* data,
5570 u_int32_t len)
5571 {
5572 #define CHECK_INDEX(idx) {if (idx >= len) return errorParseIE(ie,len ? s_errorWrongData : s_errorNoData,0,0);}
5573 CHECK_INDEX(0)
5574 // data[0]: Bits 5,6: coding standard. Bits 0-4: transfer capability
5575 if (!checkCoding(data[0],0,ie)) // Check coding standard (CCITT: 0)
5576 return errorParseIE(ie,s_errorUnsuppCoding,data,len);
5577 s_ie_ieLoLayerCompat[0].addIntParam(ie,data[0]);
5578 u_int8_t crt = 1;
5579 // Out-band negotiation is present only if data[0] has bit 7 not set
5580 if (!Q931_EXT_FINAL(data[0])) {
5581 CHECK_INDEX(1)
5582 s_ie_ieLoLayerCompat[1].addBoolParam(ie,data[1],false);
5583 crt = 2;
5584 }
5585 CHECK_INDEX(crt)
5586 // Transfer mode and transfer rate
5587 s_ie_ieLoLayerCompat[2].addIntParam(ie,data[1]);
5588 s_ie_ieLoLayerCompat[3].addIntParam(ie,data[1]);
5589 crt++;
5590 // Rate multiplier. Only if transfer rate is 'multirate'
5591 if ((data[crt-1] & 0x1f) == 0x18) {
5592 CHECK_INDEX(crt)
5593 s_ie_ieLoLayerCompat[4].addIntParam(ie,data[1]);
5594 crt++;
5595 }
5596 // Get user information layer data
5597 u_int8_t crtLayer = 0;
5598 while (true) {
5599 // End of data ?
5600 if (crt >= len)
5601 return ie;
5602 // Get and check layer (must be greater than the current one)
5603 u_int8_t layer = (data[crt] & 0x60) >> 5;
5604 if (layer <= crtLayer || layer > 3)
5605 return errorParseIE(ie,s_errorWrongData,data + crt,len - crt);
5606 crtLayer = layer;
5607 // Process layer information
5608 switch (crtLayer) {
5609 case 1:
5610 decodeLayer1(ie,data,len,crt,s_ie_ieLoLayerCompat,5);
5611 continue;
5612 case 2:
5613 decodeLayer2(ie,data,len,crt,s_ie_ieLoLayerCompat,7);
5614 continue;
5615 case 3:
5616 decodeLayer3(ie,data,len,crt,s_ie_ieLoLayerCompat,10);
5617 }
5618 break;
5619 }
5620 // Dump any remaining data
5621 if (crt < len)
5622 SignallingUtils::dumpData(0,*ie,"garbage",data + crt,len - crt);
5623 return ie;
5624 #undef CHECK_INDEX
5625 }
5626
5627 // Q.931 4.5.17
decodeHiLayerCompat(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5628 ISDNQ931IE* Q931Parser::decodeHiLayerCompat(ISDNQ931IE* ie, const u_int8_t* data,
5629 u_int32_t len)
5630 {
5631 if (!len)
5632 return errorParseIE(ie,s_errorNoData,0,0);
5633 // data[0]: Bits 5,6: coding standard
5634 // Bits 2-4: interpretation
5635 // Bits 0,1: presenttion
5636 if (!checkCoding(data[0],0,ie)) // Check coding standard (CCITT: 0)
5637 return errorParseIE(ie,s_errorUnsuppCoding,data,len);
5638 s_ie_ieHiLayerCompat[0].addIntParam(ie,data[0]); // interpretation
5639 s_ie_ieHiLayerCompat[1].addIntParam(ie,data[0]); // presentation
5640 if (len == 1)
5641 return errorParseIE(ie,s_errorWrongData,0,0);
5642 u_int8_t crt = 2;
5643 u_int8_t presIndex = ((data[0] & 0x03) == 0x01) ? 2 : 4;
5644 // High layer characteristics identification
5645 s_ie_ieHiLayerCompat[presIndex].addIntParam(ie,data[1]);
5646 // Extended high layer characteristics identification
5647 if (!Q931_EXT_FINAL(data[1])) {
5648 if (len == 2)
5649 return errorParseIE(ie,s_errorWrongData,0,0);
5650 s_ie_ieHiLayerCompat[presIndex+1].addIntParam(ie,data[2]);
5651 crt = 3;
5652 }
5653 // Dump any remaining data
5654 if (crt < len)
5655 SignallingUtils::dumpData(0,*ie,"garbage",data + crt,len - crt);
5656 return ie;
5657 }
5658
5659 // Q.931 4.5.30
decodeUserUser(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len)5660 ISDNQ931IE* Q931Parser::decodeUserUser(ISDNQ931IE* ie, const u_int8_t* data,
5661 u_int32_t len)
5662 {
5663 if (!len)
5664 return errorParseIE(ie,s_errorNoData,0,0);
5665 // data[0]: Protocol discriminator
5666 s_ie_ieUserUser[0].addIntParam(ie,data[0]);
5667 if (len == 1)
5668 return errorParseIE(ie,s_errorWrongData,0,0);
5669 // Remaining data: user information
5670 s_ie_ieUserUser[1].dumpData(ie,data + 1,len - 1);
5671 return ie;
5672 }
5673
decodeLayer1(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len,u_int8_t & crt,const IEParam * ieParam,u_int8_t ieParamIdx)5674 void Q931Parser::decodeLayer1(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len,
5675 u_int8_t& crt, const IEParam* ieParam, u_int8_t ieParamIdx)
5676 {
5677 ieParam[ieParamIdx].addIntParam(ie,data[crt]);
5678 crt++;
5679 // Done with layer 1 data ?
5680 if (Q931_EXT_FINAL(data[crt-1]))
5681 return;
5682 // Skip data up to (and including) the first byte with bit 7 set
5683 u_int8_t skip = skipExt(data,len,crt);
5684 if (skip)
5685 ieParam[ieParamIdx+1].dumpData(ie,data + crt - skip,skip);
5686 }
5687
decodeLayer2(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len,u_int8_t & crt,const IEParam * ieParam,u_int8_t ieParamIdx)5688 void Q931Parser::decodeLayer2(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len,
5689 u_int8_t& crt, const IEParam* ieParam, u_int8_t ieParamIdx)
5690 {
5691 #define CHECK_INDEX \
5692 if (Q931_EXT_FINAL(data[crt-1])) \
5693 return; \
5694 if (crt >= len) { \
5695 errorParseIE(ie,s_errorWrongData,0,0); \
5696 return; \
5697 }
5698 ieParam[ieParamIdx].addIntParam(ie,data[crt]);
5699 crt++;
5700 // This is all for bearer capabilities
5701 if (ie->type() == ISDNQ931IE::BearerCaps)
5702 return;
5703 // IE is 'Low layer compatibility'
5704 // Skip data: see Q.931 Table 4-16 description for octet 6a
5705 CHECK_INDEX
5706 ieParam[ieParamIdx+1].addIntParam(ie,data[crt]);
5707 crt++;
5708 // This byte should be the window size
5709 CHECK_INDEX
5710 ieParam[ieParamIdx+2].addIntParam(ie,data[crt]);
5711 crt++;
5712 #undef CHECK_INDEX
5713 }
5714
decodeLayer3(ISDNQ931IE * ie,const u_int8_t * data,u_int32_t len,u_int8_t & crt,const IEParam * ieParam,u_int8_t ieParamIdx)5715 void Q931Parser::decodeLayer3(ISDNQ931IE* ie, const u_int8_t* data, u_int32_t len,
5716 u_int8_t& crt, const IEParam* ieParam, u_int8_t ieParamIdx)
5717 {
5718 #define CHECK_INDEX \
5719 if (Q931_EXT_FINAL(data[crt-1])) \
5720 return; \
5721 if (crt >= len) { \
5722 errorParseIE(ie,s_errorWrongData,0,0); \
5723 return; \
5724 }
5725 ieParam[ieParamIdx].addIntParam(ie,data[crt]);
5726 crt++;
5727 // This is all for bearer capabilities
5728 if (ie->type() == ISDNQ931IE::BearerCaps)
5729 return;
5730 // IE is 'Low layer compatibility'
5731 CHECK_INDEX
5732 // See Q.931 Figure 4-25 Notes 7,8
5733 bool advance = false;
5734 switch (data[crt-1] & 0x1f) {
5735 // x25, iso8208, x223
5736 case 0x06: case 0x07: case 0x08:
5737 ieParam[ieParamIdx+1].addIntParam(ie,data[crt]);
5738 advance = true;
5739 break;
5740 // User specified
5741 case 0x10:
5742 ieParam[ieParamIdx+2].addIntParam(ie,data[crt]);
5743 break;
5744 default:
5745 ieParam[ieParamIdx+3].addIntParam(ie,data[crt]);
5746 }
5747 crt++;
5748 if (!advance)
5749 return;
5750 // Default packet size
5751 CHECK_INDEX
5752 ieParam[ieParamIdx+4].addIntParam(ie,data[crt]);
5753 crt++;
5754 // Packet window size
5755 CHECK_INDEX
5756 ieParam[ieParamIdx+5].addIntParam(ie,data[crt]);
5757 crt++;
5758 #undef CHECK_INDEX
5759 }
5760
5761 #define CHECK_IE_LENGTH(len,maxlen) \
5762 if (len > maxlen) { \
5763 Debug(m_settings->m_dbg,DebugNote, \
5764 "Can't encode '%s' IE. Length %lu exceeds maximum allowed %u [%p]", \
5765 ie->c_str(),(long unsigned int)len,maxlen,m_msg); \
5766 return false; \
5767 }
5768
encodeBearerCaps(ISDNQ931IE * ie,DataBlock & buffer)5769 bool Q931Parser::encodeBearerCaps(ISDNQ931IE* ie, DataBlock& buffer)
5770 {
5771 u_int8_t data[8] = {(u_int8_t)ie->type(),2,0x80,0x80};
5772 // 2: Coding standard (bit 5,6) 0:CCITT, Transfer capability (bit 0-4)
5773 // Translate '3.1khz-audio' (0x10) to 0x08
5774 data[2] |= s_ie_ieBearerCaps[0].getValue(ie);
5775 u_int8_t transCap = data[2] & 0x1f;
5776 if (m_settings->flag(ISDNQ931::Translate31kAudio) && (0x10 == transCap)) {
5777 transCap = 0x08;
5778 data[2] = (data[2] & 0xd0) | 0x08;
5779 }
5780 // 3: Transfer mode (bit 5,6), Transfer rate (bit 0-4)
5781 data[3] |= s_ie_ieBearerCaps[1].getValue(ie);
5782 // Figure 4.11 Note 1: Next byte is the rate multiplier if the transfer
5783 // rate is 'multirate' (0x18)
5784 u_int8_t transRate = s_ie_ieBearerCaps[2].getValue(ie);
5785 data[3] |= transRate;
5786 if (transRate == 0x18) {
5787 data[1] = 3;
5788 data[4] = 0x80 | s_ie_ieBearerCaps[3].getValue(ie);
5789 }
5790 // Check if this all data we'll send with Bearer Capability
5791 unsigned int layer = 1;
5792 if (m_settings->flag(ISDNQ931::NoLayer1Caps) ||
5793 (m_settings->flag(ISDNQ931::URDITransferCapsOnly) &&
5794 (transCap == 0x08 || transCap == 0x09)))
5795 layer = 4;
5796 // User information layer data
5797 // Bit 7 = 1, Bits 5,6 = layer, Bits 0-4: the value
5798 // Layer 1 data is at index 4 in s_ie_ieBearerCaps
5799 // Layer 2 data is at index 6 in s_ie_ieBearerCaps
5800 // Layer 3 data is at index 7 in s_ie_ieBearerCaps
5801 for (unsigned int idx = 4; layer < 4; idx++) {
5802 int tmp = s_ie_ieBearerCaps[idx].getValue(ie,false,-1);
5803 if (tmp == -1) {
5804 DDebug(m_settings->m_dbg,DebugAll,
5805 "Stop encoding '%s' IE. No user information layer %d protocol [%p]",
5806 ie->c_str(),layer,m_msg);
5807 break;
5808 }
5809 data[1]++;
5810 data[data[1] + 1] = 0x80 | ((u_int8_t)layer << 5) |
5811 ((u_int8_t)tmp & s_ie_ieBearerCaps[idx].mask);
5812 if (layer == 1)
5813 layer += 2;
5814 else
5815 layer++;
5816 }
5817 CHECK_IE_LENGTH(data[1] + 2,Q931_MAX_BEARERCAPS_LEN)
5818 buffer.assign(data,data[1] + 2);
5819 return true;
5820 }
5821
encodeCallState(ISDNQ931IE * ie,DataBlock & buffer)5822 bool Q931Parser::encodeCallState(ISDNQ931IE* ie, DataBlock& buffer)
5823 {
5824 u_int8_t data[3] = {(u_int8_t)ie->type(),1,0};
5825 u_int8_t callstate = (u_int8_t)s_ie_ieCallState[0].getValue(ie,false,255);
5826 if (callstate == 255) {
5827 const char* name = s_ie_ieCallState[0].name;
5828 Debug(m_settings->m_dbg,DebugNote,
5829 "Can't encode '%s' IE with unknown or missing field %s=%s [%p]",
5830 ie->c_str(),name,ie->getValue(name),m_msg);
5831 return false;
5832 }
5833 data[2] |= callstate & s_ie_ieCallState[0].mask;
5834 buffer.assign(data,sizeof(data));
5835 return true;
5836 }
5837
encodeChannelID(ISDNQ931IE * ie,DataBlock & buffer)5838 bool Q931Parser::encodeChannelID(ISDNQ931IE* ie, DataBlock& buffer)
5839 {
5840 DataBlock dataBuffer;
5841 u_int8_t tmp;
5842 // *** Byte 0
5843 // Bit 6 - Interface identifier 0: implicit 1: identified by the next byte(s)
5844 // Bit 5 - Interface type 0: basic 1: other (e.g. primary rate)
5845 // Bit 3 - Preferred/exclusive channel 0: indicated channel is preferred 1: only indicated channel is acceptable
5846 // Bit 2 - Identified channel is a D-channel or not
5847 // Bit 0,1 - Channel selection
5848 tmp = 0x80;
5849 String interfaceID = ie->getValue(s_ie_ieChannelID[5].name);
5850 if (!interfaceID.null()) {
5851 Debug(m_settings->m_dbg,DebugWarn,
5852 "Can't encode '%s' IE. Interface identifier encoding not implemeted [%p]",
5853 ie->c_str(),m_msg);
5854 return false;
5855 //TODO: tmp |= 0x40;
5856 }
5857 // BRI flag is 0 is briInterface is true
5858 bool briInterface = ie->getBoolValue(s_ie_ieChannelID[0].name);
5859 if (!briInterface)
5860 tmp |= s_ie_ieChannelID[0].mask;
5861 if (ie->getBoolValue(s_ie_ieChannelID[1].name)) // Preferred/Exclusive B channel
5862 tmp |= s_ie_ieChannelID[1].mask;
5863 if (ie->getBoolValue(s_ie_ieChannelID[2].name)) // D-channel flag
5864 tmp |= s_ie_ieChannelID[2].mask;
5865 // Channel selection
5866 if (briInterface)
5867 tmp |= (u_int8_t)s_ie_ieChannelID[3].getValue(ie);
5868 else
5869 tmp |= (u_int8_t)s_ie_ieChannelID[4].getValue(ie);
5870 dataBuffer.assign(&tmp,1);
5871 // Optional Byte 1: Interface identifier if present
5872 if (!interfaceID.null()) {
5873 if (!interfaceID.length() || interfaceID.length() > 254) {
5874 Debug(m_settings->m_dbg,DebugNote,
5875 "Can't encode '%s' IE with incorrect interface identifier length %u [%p]",
5876 ie->c_str(),interfaceID.length(),m_msg);
5877 return false;
5878 }
5879 //TODO: Encode interface identifier. Add to dataBuffer
5880 }
5881 // See Q.931 Figure 4.18, Note 2 and 5. Terminate if it's a BRI interface or the interface is explicitely given
5882 // If not a BRI interface or the interface is not explicit:
5883 // check channel selection. If 1: the channel is indicated by the following bytes
5884 if (!(briInterface || !interfaceID.null() || 1 != (tmp & 0x03))) {
5885 tmp = 0x80; // Coding standard 0: CCITT
5886 // Channel is indicated by number/slot-map flag is 0 for number
5887 bool byNumber = ie->getBoolValue(s_ie_ieChannelID[6].name);
5888 if (!byNumber)
5889 tmp |= s_ie_ieChannelID[6].mask;
5890 tmp |= s_ie_ieChannelID[7].getValue(ie); // Channel type
5891 dataBuffer += DataBlock(&tmp,1);
5892 String s;
5893 if (byNumber)
5894 s = ie->getValue(s_ie_ieChannelID[8].name);
5895 else
5896 s = ie->getValue(s_ie_ieChannelID[9].name);
5897 ObjList* list = s.split(',',false);
5898 ObjList* obj = list->skipNull();
5899 unsigned int count = list->count();
5900 for (; obj; obj = obj->skipNext(), count--) {
5901 tmp = (static_cast<String*>(obj->get()))->toInteger(255);
5902 if (tmp == 255)
5903 continue;
5904 // Last octet must have bit 7 set to 1
5905 if (count == 1)
5906 tmp |= 0x80;
5907 else
5908 tmp &= 0x7f;
5909 dataBuffer += DataBlock(&tmp,1);
5910 }
5911 delete list;
5912 }
5913 // Create buffer
5914 u_int8_t header[2] = {(u_int8_t)ie->type(),(u_int8_t)dataBuffer.length()};
5915 CHECK_IE_LENGTH(dataBuffer.length() + sizeof(header),Q931_MAX_CHANNELID_LEN)
5916 buffer.assign(header,sizeof(header));
5917 buffer += dataBuffer;
5918 return true;
5919 }
5920
encodeDisplay(ISDNQ931IE * ie,DataBlock & buffer)5921 bool Q931Parser::encodeDisplay(ISDNQ931IE* ie, DataBlock& buffer)
5922 {
5923 u_int8_t header[3] = {(u_int8_t)ie->type(),0,0x80};
5924 u_int8_t headerLen = 2;
5925 // Check charset
5926 if (!m_settings->flag(ISDNQ931::NoDisplayCharset)) {
5927 headerLen++;
5928 header[1] = 1;
5929 header[2] |= 0x31;
5930 }
5931 // Process display
5932 String display = ie->getValue(s_ie_ieDisplay[1].name);
5933 // Check size (the charset will steel a char from display)
5934 unsigned int maxlen = m_settings->m_maxDisplay - headerLen;
5935 if (display.length() > maxlen) {
5936 Debug(m_settings->m_dbg,DebugMild,
5937 "Truncating '%s' IE. Size %u greater then %u [%p]",
5938 ie->c_str(),display.length(),maxlen,m_msg);
5939 display = display.substr(0,maxlen);
5940 }
5941 header[1] += display.length();
5942 clearBit7(display.c_str(),display.length());
5943 // Encode
5944 CHECK_IE_LENGTH(display.length() + headerLen,m_settings->m_maxDisplay)
5945 buffer.assign(header,headerLen);
5946 buffer.append(display);
5947 return true;
5948 }
5949
encodeCallingNo(ISDNQ931IE * ie,DataBlock & buffer)5950 bool Q931Parser::encodeCallingNo(ISDNQ931IE* ie, DataBlock& buffer)
5951 {
5952 u_int8_t data[4] = {(u_int8_t)ie->type(),1,0x80,0x80};
5953 // Byte 2: Type of number (bit 4-6), Numbering plan (bit 0-3)
5954 u_int8_t tmp = s_ie_ieNumber[0].getValue(ie); // Type of number
5955 data[2] |= tmp;
5956 switch (tmp) { // Numbering plan (applicable only if type is 0,1,2,4)
5957 case 0x00: case 0x10: case 0x20: case 0x40:
5958 data[2] |= s_ie_ieNumber[1].getValue(ie);
5959 }
5960 // Optional: Presentation indicator (bit 5,6), Screening (bit 0,1)
5961 String s = ie->getValue(s_ie_ieNumber[2].name);
5962 if (!s.null()) {
5963 data[1] = 2; // Set length
5964 data[2] &= 0x7f; // Clear bit 7 to signal the presence of the next octet
5965 data[3] |= s_ie_ieNumber[2].getValue(ie);
5966 data[3] |= s_ie_ieNumber[3].getValue(ie);
5967 }
5968 // Rest of data: The number
5969 String number = ie->getValue(s_ie_ieNumber[4].name);
5970 clearBit7(number.c_str(),number.length());
5971 u_int8_t dataLen = data[1] + 2;
5972 CHECK_IE_LENGTH(number.length() + dataLen,Q931_MAX_CALLINGNO_LEN)
5973 data[1] += number.length();
5974 buffer.assign(data,dataLen);
5975 buffer += number;
5976 return true;
5977 }
5978
encodeCalledNo(ISDNQ931IE * ie,DataBlock & buffer)5979 bool Q931Parser::encodeCalledNo(ISDNQ931IE* ie, DataBlock& buffer)
5980 {
5981 u_int8_t data[3] = {(u_int8_t)ie->type(),1,0x80};
5982 // Byte 2: Type of number (bit 4-6), Numbering plan (bit 0-3)
5983 u_int8_t tmp = s_ie_ieNumber[0].getValue(ie); // Type of number
5984 data[2] |= tmp;
5985 switch (tmp) { // Numbering plan (applicable only if type is 0,1,2,4)
5986 case 0x00: case 0x10: case 0x20: case 0x40:
5987 data[2] |= s_ie_ieNumber[1].getValue(ie);
5988 }
5989 // Rest of data: The number
5990 String number = ie->getValue(s_ie_ieNumber[4].name);
5991 clearBit7(number.c_str(),number.length());
5992 CHECK_IE_LENGTH(number.length() + sizeof(data),Q931_MAX_CALLEDNO_LEN)
5993 data[1] += number.length();
5994 buffer.assign(data,sizeof(data));
5995 buffer += number;
5996 return true;
5997 }
5998
encodeProgress(ISDNQ931IE * ie,DataBlock & buffer)5999 bool Q931Parser::encodeProgress(ISDNQ931IE* ie, DataBlock& buffer)
6000 {
6001 u_int8_t data[4] = {(u_int8_t)ie->type(),2,0x80,0x80};
6002 // data[2]: Bits 5,6: coding standard
6003 // Bits 0-3: Location
6004 // Coding standard (0: CCITT). If no location, set it to 0x01: "LPN"
6005 data[2] |= s_ie_ieProgress[0].getValue(ie,true,0x01);
6006 // data[3]: Progress indicatior
6007 data[3] |= s_ie_ieProgress[1].getValue(ie);
6008 buffer.assign(data,sizeof(data));
6009 return true;
6010 }
6011
encodeNotification(ISDNQ931IE * ie,DataBlock & buffer)6012 bool Q931Parser::encodeNotification(ISDNQ931IE* ie, DataBlock& buffer)
6013 {
6014 u_int8_t data[3] = {(u_int8_t)ie->type(),1,0x80};
6015 data[2] |= s_ie_ieNotification[0].getValue(ie,true,0xff);
6016 buffer.assign(data,sizeof(data));
6017 return true;
6018 }
6019
encodeKeypad(ISDNQ931IE * ie,DataBlock & buffer)6020 bool Q931Parser::encodeKeypad(ISDNQ931IE* ie, DataBlock& buffer)
6021 {
6022 u_int8_t data[2] = {(u_int8_t)ie->type(),0};
6023 // Process keypad
6024 String keypad = ie->getValue(s_ie_ieKeypad[0].name);
6025 CHECK_IE_LENGTH(keypad.length() + sizeof(data),Q931_MAX_KEYPAD_LEN)
6026 data[1] = keypad.length();
6027 clearBit7(keypad.c_str(),keypad.length());
6028 // Encode
6029 buffer.assign(data,sizeof(data));
6030 buffer.append(keypad);
6031 return true;
6032 }
6033
encodeSignal(ISDNQ931IE * ie,DataBlock & buffer)6034 bool Q931Parser::encodeSignal(ISDNQ931IE* ie, DataBlock& buffer)
6035 {
6036 u_int8_t data[3] = {(u_int8_t)ie->type(),1,0};
6037 data[2] = s_ie_ieSignal[0].getValue(ie,true,0xff);
6038 buffer.assign(data,sizeof(data));
6039 return true;
6040 }
6041
encodeRestart(ISDNQ931IE * ie,DataBlock & buffer)6042 bool Q931Parser::encodeRestart(ISDNQ931IE* ie, DataBlock& buffer)
6043 {
6044 u_int8_t data[3] = {(u_int8_t)ie->type(),1,0x80};
6045 data[2] |= s_ie_ieRestart[0].getValue(ie,true,0xff);
6046 buffer.assign(data,sizeof(data));
6047 return true;
6048 }
6049
encodeSendComplete(ISDNQ931IE * ie,DataBlock & buffer)6050 bool Q931Parser::encodeSendComplete(ISDNQ931IE* ie, DataBlock& buffer)
6051 {
6052 u_int8_t data[1] = {(u_int8_t)ie->type()};
6053 buffer.assign(data,sizeof(data));
6054 return true;
6055 }
6056
encodeHighLayerCap(ISDNQ931IE * ie,DataBlock & buffer)6057 bool Q931Parser::encodeHighLayerCap(ISDNQ931IE* ie, DataBlock& buffer)
6058 {
6059 // **coding standard **
6060 //octet 1:information element identifier 7d
6061 // 2:the length of contents
6062 // 3:bit -8 extension set to 1
6063 // -7-6 coding standad
6064 // -5-4-3 interpretation
6065 // -2-1 presentation method of protocol profile
6066 // 4:bit -8 extension set to 0
6067 // -7-1 high layer caracteristics identification
6068
6069 // TODO: implement it!
6070 u_int8_t tmp[4];
6071 tmp[0]=0x7d; tmp[1]=0x02; tmp[2]=0x91; tmp[3]=0x81;
6072 buffer.assign(tmp,sizeof(tmp));
6073 return true;
6074 }
6075
encodeUserUser(ISDNQ931IE * ie,DataBlock & buffer)6076 bool Q931Parser::encodeUserUser(ISDNQ931IE* ie, DataBlock& buffer)
6077 {
6078 // TODO: implement it!
6079 u_int8_t tmp[10];
6080 tmp[0]=0x7e;tmp[1]=0x08;tmp[2]=0x04;tmp[3]=0x30;tmp[4]=0x39;
6081 tmp[5]=0x32;tmp[6]=0x21;tmp[7]=0x30;tmp[8]=0x39;tmp[9]=0x32;
6082 buffer.assign(tmp,sizeof(tmp));
6083 return true;
6084 }
6085
6086 /* vi: set ts=8 sw=4 sts=4 noet: */
6087