1 /*
2  * libpri: An implementation of Primary Rate ISDN
3  *
4  * Written by Mark Spencer <markster@digium.com>
5  *
6  * Copyright (C) 2001-2005, Digium, Inc.
7  * All Rights Reserved.
8  */
9 
10 /*
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2 as published by the
19  * Free Software Foundation. See the LICENSE file included with
20  * this program for more details.
21  *
22  * In addition, when this program is distributed with Asterisk in
23  * any form that would qualify as a 'combined work' or as a
24  * 'derivative work' (but not mere aggregation), you can redistribute
25  * and/or modify the combination under the terms of the license
26  * provided with that copy of Asterisk, instead of the license
27  * terms granted here.
28  */
29 
30 #include "compat.h"
31 #include "libpri.h"
32 #include "pri_internal.h"
33 #include "pri_facility.h"
34 
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <time.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <stdio.h>
41 #include <limits.h>
42 
43 enum mandatory_ie_status {
44 	MAND_STATUS_OK,
45 	MAND_STATUS_CONTENT_ERROR,
46 	MAND_STATUS_MISSING,
47 };
48 
49 #define MAX_MAND_IES 10
50 
51 struct msgtype {
52 	int msgnum;
53 	char *name;
54 	int mandies[MAX_MAND_IES];
55 };
56 
57 static struct msgtype msgs[] = {
58 	/* Call establishment messages */
59 	{ Q931_ALERTING, "ALERTING", { Q931_CHANNEL_IDENT } },
60 	{ Q931_CALL_PROCEEDING, "CALL PROCEEDING", { Q931_CHANNEL_IDENT } },
61 	{ Q931_CONNECT, "CONNECT", { Q931_CHANNEL_IDENT } },
62 	{ Q931_CONNECT_ACKNOWLEDGE, "CONNECT ACKNOWLEDGE" },
63 	/*
64 	 * Very early in libpri SVN history (SVN -r154) a change was explicitly
65 	 * made to not care about a missing Progress Indicator ie.  There is no
66 	 * explanation in the commit message why this was done even though
67 	 * Q.931 and ECMA-143 clearly show that the ie is mandatory for a
68 	 * PROGRESS message.
69 	 *
70 	 * Hazzarding a guess, I think it was because of the
71 	 * ALERTING_NO_PROGRESS support for Mitel switches.  (SVN -r44)
72 	 */
73 #ifdef ALERTING_NO_PROGRESS
74 	{ Q931_PROGRESS, "PROGRESS" },
75 #else
76 	{ Q931_PROGRESS, "PROGRESS", { Q931_PROGRESS_INDICATOR } },
77 #endif
78 	{ Q931_SETUP, "SETUP", { Q931_BEARER_CAPABILITY, Q931_CHANNEL_IDENT } },
79 	{ Q931_SETUP_ACKNOWLEDGE, "SETUP ACKNOWLEDGE", { Q931_CHANNEL_IDENT } },
80 
81 	/* Call disestablishment messages */
82 	{ Q931_DISCONNECT, "DISCONNECT", { Q931_CAUSE } },
83 	{ Q931_RELEASE, "RELEASE" },
84 	{ Q931_RELEASE_COMPLETE, "RELEASE COMPLETE" },
85 	{ Q931_RESTART, "RESTART", { Q931_RESTART_INDICATOR } },
86 	{ Q931_RESTART_ACKNOWLEDGE, "RESTART ACKNOWLEDGE", { Q931_RESTART_INDICATOR } },
87 
88 	/* Miscellaneous */
89 	{ Q931_STATUS, "STATUS", { Q931_CAUSE, Q931_IE_CALL_STATE } },
90 	{ Q931_STATUS_ENQUIRY, "STATUS ENQUIRY" },
91 	{ Q931_USER_INFORMATION, "USER_INFORMATION" },
92 	{ Q931_SEGMENT, "SEGMENT" },
93 	{ Q931_CONGESTION_CONTROL, "CONGESTION CONTROL" },
94 	{ Q931_INFORMATION, "INFORMATION" },
95 	{ Q931_FACILITY, "FACILITY" },
96 	{ Q931_REGISTER, "REGISTER" },
97 	{ Q931_NOTIFY, "NOTIFY", { Q931_IE_NOTIFY_IND } },
98 
99 	/* Call Management */
100 	{ Q931_HOLD, "HOLD" },
101 	{ Q931_HOLD_ACKNOWLEDGE, "HOLD ACKNOWLEDGE" },
102 	{ Q931_HOLD_REJECT, "HOLD REJECT", { Q931_CAUSE } },
103 	{ Q931_RETRIEVE, "RETRIEVE" },
104 	{ Q931_RETRIEVE_ACKNOWLEDGE, "RETRIEVE ACKNOWLEDGE" },
105 	{ Q931_RETRIEVE_REJECT, "RETRIEVE REJECT", { Q931_CAUSE } },
106 	{ Q931_RESUME, "RESUME" },
107 	{ Q931_RESUME_ACKNOWLEDGE, "RESUME ACKNOWLEDGE", { Q931_CHANNEL_IDENT } },
108 	{ Q931_RESUME_REJECT, "RESUME REJECT", { Q931_CAUSE } },
109 	{ Q931_SUSPEND, "SUSPEND" },
110 	{ Q931_SUSPEND_ACKNOWLEDGE, "SUSPEND ACKNOWLEDGE" },
111 	{ Q931_SUSPEND_REJECT, "SUSPEND REJECT" },
112 
113 	{ Q931_ANY_MESSAGE, "ANY MESSAGE" },
114 };
115 
116 static int post_handle_q931_message(struct pri *ctrl, struct q931_mh *mh, struct q931_call *c, enum mandatory_ie_status mand_status);
117 static void nt_ptmp_handle_q931_message(struct pri *ctrl, struct q931_mh *mh, struct q931_call *c, int *allow_event, int *allow_posthandle);
118 
119 struct msgtype att_maintenance_msgs[] = {
120 	{ ATT_SERVICE, "SERVICE", { Q931_CHANNEL_IDENT } },
121 	{ ATT_SERVICE_ACKNOWLEDGE, "SERVICE ACKNOWLEDGE", { Q931_CHANNEL_IDENT } },
122 };
123 
124 struct msgtype national_maintenance_msgs[] = {
125 	{ NATIONAL_SERVICE, "SERVICE", { Q931_CHANNEL_IDENT } },
126 	{ NATIONAL_SERVICE_ACKNOWLEDGE, "SERVICE ACKNOWLEDGE", { Q931_CHANNEL_IDENT } },
127 };
128 static int post_handle_maintenance_message(struct pri *ctrl, int protodisc, struct q931_mh *mh, struct q931_call *c);
129 
130 static struct msgtype causes[] = {
131 	{ PRI_CAUSE_UNALLOCATED, "Unallocated (unassigned) number" },
132 	{ PRI_CAUSE_NO_ROUTE_TRANSIT_NET, "No route to specified transmit network" },
133 	{ PRI_CAUSE_NO_ROUTE_DESTINATION, "No route to destination" },
134 	{ PRI_CAUSE_CHANNEL_UNACCEPTABLE, "Channel unacceptable" },
135 	{ PRI_CAUSE_CALL_AWARDED_DELIVERED, "Call awarded and being delivered in an established channel" },
136 	{ PRI_CAUSE_NORMAL_CLEARING, "Normal Clearing" },
137 	{ PRI_CAUSE_USER_BUSY, "User busy" },
138 	{ PRI_CAUSE_NO_USER_RESPONSE, "No user responding" },
139 	{ PRI_CAUSE_NO_ANSWER, "User alerting, no answer" },
140 	{ PRI_CAUSE_CALL_REJECTED, "Call Rejected" },
141 	{ PRI_CAUSE_NUMBER_CHANGED, "Number changed" },
142 	{ PRI_CAUSE_NONSELECTED_USER_CLEARING, "Non-selected user clearing" },
143 	{ PRI_CAUSE_DESTINATION_OUT_OF_ORDER, "Destination out of order" },
144 	{ PRI_CAUSE_INVALID_NUMBER_FORMAT, "Invalid number format" },
145 	{ PRI_CAUSE_FACILITY_REJECTED, "Facility rejected" },
146 	{ PRI_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "Response to STATus ENQuiry" },
147 	{ PRI_CAUSE_NORMAL_UNSPECIFIED, "Normal, unspecified" },
148 	{ PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION, "Circuit/channel congestion" },
149 	{ PRI_CAUSE_NETWORK_OUT_OF_ORDER, "Network out of order" },
150 	{ PRI_CAUSE_NORMAL_TEMPORARY_FAILURE, "Temporary failure" },
151 	{ PRI_CAUSE_SWITCH_CONGESTION, "Switching equipment congestion" },
152 	{ PRI_CAUSE_ACCESS_INFO_DISCARDED, "Access information discarded" },
153 	{ PRI_CAUSE_REQUESTED_CHAN_UNAVAIL, "Requested channel not available" },
154 	{ PRI_CAUSE_PRE_EMPTED, "Pre-empted" },
155 	{ PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED, "Resource unavailable, unspecified" },
156 	{ PRI_CAUSE_FACILITY_NOT_SUBSCRIBED, "Facility not subscribed" },
157 	{ PRI_CAUSE_OUTGOING_CALL_BARRED, "Outgoing call barred" },
158 	{ PRI_CAUSE_INCOMING_CALL_BARRED, "Incoming call barred" },
159 	{ PRI_CAUSE_BEARERCAPABILITY_NOTAUTH, "Bearer capability not authorized" },
160 	{ PRI_CAUSE_BEARERCAPABILITY_NOTAVAIL, "Bearer capability not available" },
161 	{ PRI_CAUSE_SERVICEOROPTION_NOTAVAIL, "Service or option not available, unspecified" },
162 	{ PRI_CAUSE_BEARERCAPABILITY_NOTIMPL, "Bearer capability not implemented" },
163 	{ PRI_CAUSE_CHAN_NOT_IMPLEMENTED, "Channel not implemented" },
164 	{ PRI_CAUSE_FACILITY_NOT_IMPLEMENTED, "Facility not implemented" },
165 	{ PRI_CAUSE_INVALID_CALL_REFERENCE, "Invalid call reference value" },
166 	{ PRI_CAUSE_IDENTIFIED_CHANNEL_NOTEXIST, "Identified channel does not exist" },
167 	{ PRI_CAUSE_INCOMPATIBLE_DESTINATION, "Incompatible destination" },
168 	{ PRI_CAUSE_INVALID_MSG_UNSPECIFIED, "Invalid message unspecified" },
169 	{ PRI_CAUSE_MANDATORY_IE_MISSING, "Mandatory information element is missing" },
170 	{ PRI_CAUSE_MESSAGE_TYPE_NONEXIST, "Message type nonexist." },
171 	{ PRI_CAUSE_WRONG_MESSAGE, "Wrong message" },
172 	{ PRI_CAUSE_IE_NONEXIST, "Info. element nonexist or not implemented" },
173 	{ PRI_CAUSE_INVALID_IE_CONTENTS, "Invalid information element contents" },
174 	{ PRI_CAUSE_WRONG_CALL_STATE, "Message not compatible with call state" },
175 	{ PRI_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "Recover on timer expiry" },
176 	{ PRI_CAUSE_MANDATORY_IE_LENGTH_ERROR, "Mandatory IE length error" },
177 	{ PRI_CAUSE_PROTOCOL_ERROR, "Protocol error, unspecified" },
178 	{ PRI_CAUSE_INTERWORKING, "Interworking, unspecified" },
179 };
180 
181 static struct msgtype facilities[] = {
182        { PRI_NSF_SID_PREFERRED, "CPN (SID) preferred" },
183        { PRI_NSF_ANI_PREFERRED, "BN (ANI) preferred" },
184        { PRI_NSF_SID_ONLY, "CPN (SID) only" },
185        { PRI_NSF_ANI_ONLY, "BN (ANI) only" },
186        { PRI_NSF_CALL_ASSOC_TSC, "Call Associated TSC" },
187        { PRI_NSF_NOTIF_CATSC_CLEARING, "Notification of CATSC Clearing or Resource Unavailable" },
188        { PRI_NSF_OPERATOR, "Operator" },
189        { PRI_NSF_PCCO, "Pre-subscribed Common Carrier Operator (PCCO)" },
190        { PRI_NSF_SDN, "SDN (including GSDN)" },
191        { PRI_NSF_TOLL_FREE_MEGACOM, "Toll Free MEGACOM" },
192        { PRI_NSF_MEGACOM, "MEGACOM" },
193        { PRI_NSF_ACCUNET, "ACCUNET Switched Digital Service" },
194        { PRI_NSF_LONG_DISTANCE_SERVICE, "Long Distance Service" },
195        { PRI_NSF_INTERNATIONAL_TOLL_FREE, "International Toll Free Service" },
196        { PRI_NSF_ATT_MULTIQUEST, "AT&T MultiQuest" },
197        { PRI_NSF_CALL_REDIRECTION_SERVICE, "Call Redirection Service" }
198 };
199 
200 #define FLAG_WHOLE_INTERFACE	0x01
201 #define FLAG_PREFERRED			0x02
202 #define FLAG_EXCLUSIVE			0x04
203 
204 #define RESET_INDICATOR_CHANNEL	0
205 #define RESET_INDICATOR_DS1		6
206 #define RESET_INDICATOR_PRI		7
207 
208 #define TRANS_MODE_64_CIRCUIT	0x10
209 #define TRANS_MODE_2x64_CIRCUIT	0x11
210 #define TRANS_MODE_384_CIRCUIT	0x13
211 #define TRANS_MODE_1536_CIRCUIT	0x15
212 #define TRANS_MODE_1920_CIRCUIT	0x17
213 #define TRANS_MODE_MULTIRATE	0x18
214 #define TRANS_MODE_PACKET		0x40
215 
216 #define RATE_ADAPT_56K			0x0f
217 
218 #define LAYER_2_LAPB			0x46
219 
220 #define LAYER_3_X25				0x66
221 
222 /* The 4ESS uses a different audio field */
223 #define PRI_TRANS_CAP_AUDIO_4ESS	0x08
224 
225 /* Don't forget to update PRI_PROG_xxx at libpri.h */
226 #define Q931_PROG_CALL_NOT_E2E_ISDN						0x01
227 #define Q931_PROG_CALLED_NOT_ISDN						0x02
228 #define Q931_PROG_CALLER_NOT_ISDN						0x03
229 #define Q931_PROG_CALLER_RETURNED_TO_ISDN					0x04
230 #define Q931_PROG_INBAND_AVAILABLE						0x08
231 #define Q931_PROG_DELAY_AT_INTERF						0x0a
232 #define Q931_PROG_INTERWORKING_WITH_PUBLIC				0x10
233 #define Q931_PROG_INTERWORKING_NO_RELEASE				0x11
234 #define Q931_PROG_INTERWORKING_NO_RELEASE_PRE_ANSWER	0x12
235 #define Q931_PROG_INTERWORKING_NO_RELEASE_POST_ANSWER	0x13
236 
237 #define CODE_CCITT					0x0
238 #define CODE_INTERNATIONAL 			0x1
239 #define CODE_NATIONAL 				0x2
240 #define CODE_NETWORK_SPECIFIC		0x3
241 
242 #define LOC_USER					0x0
243 #define LOC_PRIV_NET_LOCAL_USER		0x1
244 #define LOC_PUB_NET_LOCAL_USER		0x2
245 #define LOC_TRANSIT_NET				0x3
246 #define LOC_PUB_NET_REMOTE_USER		0x4
247 #define LOC_PRIV_NET_REMOTE_USER	0x5
248 #define LOC_INTERNATIONAL_NETWORK	0x7
249 #define LOC_NETWORK_BEYOND_INTERWORKING	0xa
250 
251 static char *ie2str(int ie);
252 
253 
254 #define FUNC_DUMP(name) void (name)(int full_ie, struct pri *pri, q931_ie *ie, int len, char prefix)
255 #define FUNC_RECV(name) int (name)(int full_ie, struct pri *pri, q931_call *call, int msgtype, q931_ie *ie, int len)
256 #define FUNC_SEND(name) int (name)(int full_ie, struct pri *pri, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
257 
258 #if 1
259 /* Update call state with transition trace. */
260 #define UPDATE_OURCALLSTATE(ctrl, call, newstate) \
261 	do { \
262 		if (((ctrl)->debug & PRI_DEBUG_Q931_STATE) && (call)->ourcallstate != (newstate)) { \
263 			pri_message((ctrl), \
264 				DBGHEAD "%s %d enters state %d (%s).  Hold state: %s\n", \
265 				DBGINFO, ((call) == (call)->master_call) ? "Call" : "Subcall", \
266 				(call)->cr, (newstate), q931_call_state_str(newstate), \
267 				q931_hold_state_str((call)->master_call->hold_state)); \
268 		} \
269 		(call)->ourcallstate = (newstate); \
270 	} while (0)
271 #else
272 /* Update call state with no trace. */
273 #define UPDATE_OURCALLSTATE(ctrl, call, newstate) (call)->ourcallstate = (newstate)
274 #endif
275 
276 #if 1
277 /* Update hold state with transition trace. */
278 #define UPDATE_HOLD_STATE(ctrl, master_call, newstate) \
279 	do { \
280 		if (((ctrl)->debug & PRI_DEBUG_Q931_STATE) \
281 			&& (master_call)->hold_state != (newstate)) { \
282 			pri_message((ctrl), \
283 				DBGHEAD "Call %d in state %d (%s) enters Hold state: %s\n", \
284 				DBGINFO, (master_call)->cr, (master_call)->ourcallstate, \
285 				q931_call_state_str((master_call)->ourcallstate), \
286 				q931_hold_state_str(newstate)); \
287 		} \
288 		(master_call)->hold_state = (newstate); \
289 	} while (0)
290 #else
291 /* Update hold state with no trace. */
292 #define UPDATE_HOLD_STATE(ctrl, master_call, newstate) (master_call)->hold_state = (newstate)
293 #endif
294 
295 struct ie {
296 	/* Maximal count of same IEs at the message (0 - any, 1..n - limited) */
297 	int max_count;
298 	/* IE code */
299 	int ie;
300 	/* IE friendly name */
301 	char *name;
302 	/* Dump an IE for debugging (preceed all lines by prefix) */
303 	FUNC_DUMP(*dump);
304 	/* Handle IE  returns 0 on success, -1 on failure */
305 	FUNC_RECV(*receive);
306 	/* Add IE to a message, return the # of bytes added or -1 on failure */
307 	FUNC_SEND(*transmit);
308 };
309 
310 /*!
311  * \internal
312  * \brief Encode the channel id information to pass to upper level.
313  *
314  * \param call Q.931 call leg
315  *
316  * \return Encoded channel value.
317  */
q931_encode_channel(const q931_call * call)318 static int q931_encode_channel(const q931_call *call)
319 {
320 	int held_call;
321 	int channelno;
322 	int ds1no;
323 
324 	switch (call->master_call->hold_state) {
325 	case Q931_HOLD_STATE_CALL_HELD:
326 	case Q931_HOLD_STATE_RETRIEVE_REQ:
327 	case Q931_HOLD_STATE_RETRIEVE_IND:
328 		held_call = 1 << 18;
329 		break;
330 	default:
331 		held_call = 0;
332 		break;
333 	}
334 	if (held_call || call->cis_call) {
335 		/* So a -1 does not wipe out the held_call or cis_call flags. */
336 		channelno = call->channelno & 0xFF;
337 		ds1no = call->ds1no & 0xFF;
338 	} else {
339 		channelno = call->channelno;
340 		ds1no = call->ds1no;
341 	}
342 	return channelno | (ds1no << 8) | (call->ds1explicit << 16) | (call->cis_call << 17)
343 		| held_call;
344 }
345 
346 /*!
347  * \brief Check if the given call ptr is valid.
348  *
349  * \param ctrl D channel controller.
350  * \param call Q.931 call leg.
351  *
352  * \retval TRUE if call ptr is valid.
353  * \retval FALSE if call ptr is invalid.
354  */
q931_is_call_valid(struct pri * ctrl,struct q931_call * call)355 int q931_is_call_valid(struct pri *ctrl, struct q931_call *call)
356 {
357 	struct q931_call *cur;
358 	struct q921_link *link;
359 	int idx;
360 
361 	if (!call) {
362 		return 0;
363 	}
364 
365 	if (!ctrl) {
366 		/* Must use suspect ctrl from call ptr. */
367 		if (!call->pri) {
368 			/* Definitely a bad call pointer. */
369 			return 0;
370 		}
371 		ctrl = call->pri;
372 	}
373 
374 	/* Check real call records. */
375 	for (cur = *ctrl->callpool; cur; cur = cur->next) {
376 		if (call == cur) {
377 			/* Found it. */
378 			return 1;
379 		}
380 		if (cur->outboundbroadcast) {
381 			/* Check subcalls for call ptr. */
382 			for (idx = 0; idx < ARRAY_LEN(cur->subcalls); ++idx) {
383 				if (call == cur->subcalls[idx]) {
384 					/* Found it. */
385 					return 1;
386 				}
387 			}
388 		}
389 	}
390 
391 	/* Check dummy call records. */
392 	for (link = &ctrl->link; link; link = link->next) {
393 		if (link->dummy_call == call) {
394 			/* Found it. */
395 			return 1;
396 		}
397 	}
398 
399 	/* Well it looks like this is a stale call ptr. */
400 	return 0;
401 }
402 
403 /*!
404  * \brief Check if the given call ptr is valid and gripe if not.
405  *
406  * \param ctrl D channel controller.
407  * \param call Q.931 call leg.
408  * \param func_name Calling function name for debug tracing. (__PRETTY_FUNCTION__)
409  * \param func_line Calling function line number for debug tracing. (__LINE__)
410  *
411  * \retval TRUE if call ptr is valid.
412  * \retval FALSE if call ptr is invalid.
413  */
q931_is_call_valid_gripe(struct pri * ctrl,struct q931_call * call,const char * func_name,unsigned long func_line)414 int q931_is_call_valid_gripe(struct pri *ctrl, struct q931_call *call, const char *func_name, unsigned long func_line)
415 {
416 	int res;
417 
418 	if (!call) {
419 		/* Let's not gripe about this invalid call pointer. */
420 		return 0;
421 	}
422 	res = q931_is_call_valid(ctrl, call);
423 	if (!res) {
424 		pri_message(ctrl, "!! %s() line:%lu Called with invalid call ptr (%p)\n",
425 			func_name, func_line, call);
426 	}
427 	return res;
428 }
429 
430 /*!
431  * \brief Initialize the given struct q931_party_name
432  *
433  * \param name Structure to initialize
434  *
435  * \return Nothing
436  */
q931_party_name_init(struct q931_party_name * name)437 void q931_party_name_init(struct q931_party_name *name)
438 {
439 	name->valid = 0;
440 	name->presentation = PRI_PRES_UNAVAILABLE;
441 	name->char_set = PRI_CHAR_SET_ISO8859_1;
442 	name->str[0] = '\0';
443 }
444 
445 /*!
446  * \brief Initialize the given struct q931_party_number
447  *
448  * \param number Structure to initialize
449  *
450  * \return Nothing
451  */
q931_party_number_init(struct q931_party_number * number)452 void q931_party_number_init(struct q931_party_number *number)
453 {
454 	number->valid = 0;
455 	number->presentation = PRES_NUMBER_NOT_AVAILABLE;
456 	number->plan = (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
457 	number->str[0] = '\0';
458 }
459 
460 /*!
461  * \brief Initialize the given struct q931_party_subaddress
462  *
463  * \param subaddress Structure to initialize
464  *
465  * \return Nothing
466  */
q931_party_subaddress_init(struct q931_party_subaddress * subaddress)467 void q931_party_subaddress_init(struct q931_party_subaddress *subaddress)
468 {
469 	subaddress->valid = 0;
470 	subaddress->type = 0;
471 	subaddress->odd_even_indicator = 0;
472 	subaddress->length = 0;
473 	subaddress->data[0] = '\0';
474 }
475 
476 /*!
477  * \brief Initialize the given struct q931_party_address
478  *
479  * \param address Structure to initialize
480  *
481  * \return Nothing
482  */
q931_party_address_init(struct q931_party_address * address)483 void q931_party_address_init(struct q931_party_address *address)
484 {
485 	q931_party_number_init(&address->number);
486 	q931_party_subaddress_init(&address->subaddress);
487 }
488 
489 /*!
490  * \brief Initialize the given struct q931_party_id
491  *
492  * \param id Structure to initialize
493  *
494  * \return Nothing
495  */
q931_party_id_init(struct q931_party_id * id)496 void q931_party_id_init(struct q931_party_id *id)
497 {
498 	q931_party_name_init(&id->name);
499 	q931_party_number_init(&id->number);
500 	q931_party_subaddress_init(&id->subaddress);
501 }
502 
503 /*!
504  * \brief Initialize the given struct q931_party_redirecting
505  *
506  * \param redirecting Structure to initialize
507  *
508  * \return Nothing
509  */
q931_party_redirecting_init(struct q931_party_redirecting * redirecting)510 void q931_party_redirecting_init(struct q931_party_redirecting *redirecting)
511 {
512 	q931_party_id_init(&redirecting->from);
513 	q931_party_id_init(&redirecting->to);
514 	q931_party_id_init(&redirecting->orig_called);
515 	redirecting->state = Q931_REDIRECTING_STATE_IDLE;
516 	redirecting->count = 0;
517 	redirecting->orig_reason = PRI_REDIR_UNKNOWN;
518 	redirecting->reason = PRI_REDIR_UNKNOWN;
519 }
520 
521 /*!
522  * \brief Compare the left and right party name.
523  *
524  * \param left Left parameter party name.
525  * \param right Right parameter party name.
526  *
527  * \retval < 0 when left < right.
528  * \retval == 0 when left == right.
529  * \retval > 0 when left > right.
530  */
q931_party_name_cmp(const struct q931_party_name * left,const struct q931_party_name * right)531 int q931_party_name_cmp(const struct q931_party_name *left, const struct q931_party_name *right)
532 {
533 	int cmp;
534 
535 	if (!left->valid) {
536 		if (!right->valid) {
537 			return 0;
538 		}
539 		return -1;
540 	} else if (!right->valid) {
541 		return 1;
542 	}
543 	cmp = left->char_set - right->char_set;
544 	if (cmp) {
545 		return cmp;
546 	}
547 	cmp = strcmp(left->str, right->str);
548 	if (cmp) {
549 		return cmp;
550 	}
551 	cmp = left->presentation - right->presentation;
552 	return cmp;
553 }
554 
555 /*!
556  * \brief Compare the left and right party number.
557  *
558  * \param left Left parameter party number.
559  * \param right Right parameter party number.
560  *
561  * \retval < 0 when left < right.
562  * \retval == 0 when left == right.
563  * \retval > 0 when left > right.
564  */
q931_party_number_cmp(const struct q931_party_number * left,const struct q931_party_number * right)565 int q931_party_number_cmp(const struct q931_party_number *left, const struct q931_party_number *right)
566 {
567 	int cmp;
568 
569 	if (!left->valid) {
570 		if (!right->valid) {
571 			return 0;
572 		}
573 		return -1;
574 	} else if (!right->valid) {
575 		return 1;
576 	}
577 	cmp = left->plan - right->plan;
578 	if (cmp) {
579 		return cmp;
580 	}
581 	cmp = strcmp(left->str, right->str);
582 	if (cmp) {
583 		return cmp;
584 	}
585 	cmp = left->presentation - right->presentation;
586 	return cmp;
587 }
588 
589 /*!
590  * \brief Compare the left and right party subaddress.
591  *
592  * \param left Left parameter party subaddress.
593  * \param right Right parameter party subaddress.
594  *
595  * \retval < 0 when left < right.
596  * \retval == 0 when left == right.
597  * \retval > 0 when left > right.
598  */
q931_party_subaddress_cmp(const struct q931_party_subaddress * left,const struct q931_party_subaddress * right)599 int q931_party_subaddress_cmp(const struct q931_party_subaddress *left, const struct q931_party_subaddress *right)
600 {
601 	int cmp;
602 
603 	if (!left->valid) {
604 		if (!right->valid) {
605 			return 0;
606 		}
607 		return -1;
608 	} else if (!right->valid) {
609 		return 1;
610 	}
611 	cmp = left->type - right->type;
612 	if (cmp) {
613 		return cmp;
614 	}
615 	cmp = memcmp(left->data, right->data,
616 		(left->length < right->length) ? left->length : right->length);
617 	if (cmp) {
618 		return cmp;
619 	}
620 	cmp = left->length - right->length;
621 	if (cmp) {
622 		return cmp;
623 	}
624 	cmp = left->odd_even_indicator - right->odd_even_indicator;
625 	return cmp;
626 }
627 
628 /*!
629  * \brief Compare the left and right party address.
630  *
631  * \param left Left parameter party address.
632  * \param right Right parameter party address.
633  *
634  * \retval < 0 when left < right.
635  * \retval == 0 when left == right.
636  * \retval > 0 when left > right.
637  */
q931_party_address_cmp(const struct q931_party_address * left,const struct q931_party_address * right)638 int q931_party_address_cmp(const struct q931_party_address *left, const struct q931_party_address *right)
639 {
640 	int cmp;
641 
642 	cmp = q931_party_number_cmp(&left->number, &right->number);
643 	if (cmp) {
644 		return cmp;
645 	}
646 	cmp = q931_party_subaddress_cmp(&left->subaddress, &right->subaddress);
647 	return cmp;
648 }
649 
650 /*!
651  * \brief Compare the left and right party id.
652  *
653  * \param left Left parameter party id.
654  * \param right Right parameter party id.
655  *
656  * \retval < 0 when left < right.
657  * \retval == 0 when left == right.
658  * \retval > 0 when left > right.
659  */
q931_party_id_cmp(const struct q931_party_id * left,const struct q931_party_id * right)660 int q931_party_id_cmp(const struct q931_party_id *left, const struct q931_party_id *right)
661 {
662 	int cmp;
663 
664 	cmp = q931_party_number_cmp(&left->number, &right->number);
665 	if (cmp) {
666 		return cmp;
667 	}
668 	cmp = q931_party_subaddress_cmp(&left->subaddress, &right->subaddress);
669 	if (cmp) {
670 		return cmp;
671 	}
672 	cmp = q931_party_name_cmp(&left->name, &right->name);
673 	return cmp;
674 }
675 
676 /*!
677  * \brief Compare the left and right party id addresses.
678  *
679  * \param left Left parameter party id.
680  * \param right Right parameter party id.
681  *
682  * \retval < 0 when left < right.
683  * \retval == 0 when left == right.
684  * \retval > 0 when left > right.
685  */
q931_party_id_cmp_address(const struct q931_party_id * left,const struct q931_party_id * right)686 int q931_party_id_cmp_address(const struct q931_party_id *left, const struct q931_party_id *right)
687 {
688 	int cmp;
689 
690 	cmp = q931_party_number_cmp(&left->number, &right->number);
691 	if (cmp) {
692 		return cmp;
693 	}
694 	cmp = q931_party_subaddress_cmp(&left->subaddress, &right->subaddress);
695 	return cmp;
696 }
697 
698 /*!
699  * \brief Compare the party id to the party address.
700  *
701  * \param id Party id.
702  * \param address Party address.
703  *
704  * \retval < 0 when id < address.
705  * \retval == 0 when id == address.
706  * \retval > 0 when id > address.
707  */
q931_cmp_party_id_to_address(const struct q931_party_id * id,const struct q931_party_address * address)708 int q931_cmp_party_id_to_address(const struct q931_party_id *id, const struct q931_party_address *address)
709 {
710 	int cmp;
711 
712 	cmp = q931_party_number_cmp(&id->number, &address->number);
713 	if (cmp) {
714 		return cmp;
715 	}
716 	cmp = q931_party_subaddress_cmp(&id->subaddress, &address->subaddress);
717 	return cmp;
718 }
719 
720 /*!
721  * \brief Copy a party id into a party address.
722  *
723  * \param address Party address.
724  * \param id Party id.
725  *
726  * \return Nothing
727  */
q931_party_id_copy_to_address(struct q931_party_address * address,const struct q931_party_id * id)728 void q931_party_id_copy_to_address(struct q931_party_address *address, const struct q931_party_id *id)
729 {
730 	address->number = id->number;
731 	address->subaddress = id->subaddress;
732 }
733 
734 /*!
735  * \brief Copy the Q.931 party name to the PRI party name structure.
736  *
737  * \param pri_name PRI party name structure
738  * \param q931_name Q.931 party name structure
739  *
740  * \return Nothing
741  */
q931_party_name_copy_to_pri(struct pri_party_name * pri_name,const struct q931_party_name * q931_name)742 void q931_party_name_copy_to_pri(struct pri_party_name *pri_name, const struct q931_party_name *q931_name)
743 {
744 	if (q931_name->valid) {
745 		pri_name->valid = 1;
746 		pri_name->presentation = q931_name->presentation;
747 		pri_name->char_set = q931_name->char_set;
748 		libpri_copy_string(pri_name->str, q931_name->str, sizeof(pri_name->str));
749 	} else {
750 		pri_name->valid = 0;
751 		pri_name->presentation = PRI_PRES_UNAVAILABLE;
752 		pri_name->char_set = PRI_CHAR_SET_ISO8859_1;
753 		pri_name->str[0] = '\0';
754 	}
755 }
756 
757 /*!
758  * \brief Copy the Q.931 party number to the PRI party number structure.
759  *
760  * \param pri_number PRI party number structure
761  * \param q931_number Q.931 party number structure
762  *
763  * \return Nothing
764  */
q931_party_number_copy_to_pri(struct pri_party_number * pri_number,const struct q931_party_number * q931_number)765 void q931_party_number_copy_to_pri(struct pri_party_number *pri_number, const struct q931_party_number *q931_number)
766 {
767 	if (q931_number->valid) {
768 		pri_number->valid = 1;
769 		pri_number->presentation = q931_number->presentation;
770 		pri_number->plan = q931_number->plan;
771 		libpri_copy_string(pri_number->str, q931_number->str, sizeof(pri_number->str));
772 	} else {
773 		pri_number->valid = 0;
774 		pri_number->presentation = PRES_NUMBER_NOT_AVAILABLE;
775 		pri_number->plan = (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
776 		pri_number->str[0] = '\0';
777 	}
778 }
779 
780 /*!
781  * \brief Copy the Q.931 party subaddress to the PRI party subaddress structure.
782  *
783  * \param pri_subaddress PRI party subaddress structure
784  * \param q931_subaddress Q.931 party subaddress structure
785  *
786  * \return Nothing
787  */
q931_party_subaddress_copy_to_pri(struct pri_party_subaddress * pri_subaddress,const struct q931_party_subaddress * q931_subaddress)788 void q931_party_subaddress_copy_to_pri(struct pri_party_subaddress *pri_subaddress, const struct q931_party_subaddress *q931_subaddress)
789 {
790 	int length;
791 
792 	if (!q931_subaddress->valid) {
793 		pri_subaddress->valid = 0;
794 		pri_subaddress->type = 0;
795 		pri_subaddress->odd_even_indicator = 0;
796 		pri_subaddress->length = 0;
797 		pri_subaddress->data[0] = '\0';
798 		return;
799 	}
800 
801 	pri_subaddress->valid = 1;
802 	pri_subaddress->type = q931_subaddress->type;
803 	pri_subaddress->odd_even_indicator = q931_subaddress->odd_even_indicator;
804 
805 	/*
806 	 * The size of pri_subaddress->data[] is not the same as the size of
807 	 * q931_subaddress->data[].
808 	 */
809 	length = q931_subaddress->length;
810 	pri_subaddress->length = length;
811 	memcpy(pri_subaddress->data, q931_subaddress->data, length);
812 	pri_subaddress->data[length] = '\0';
813 }
814 
815 /*!
816  * \brief Copy the Q.931 party address to the PRI party address structure.
817  *
818  * \param pri_address PRI party address structure
819  * \param q931_address Q.931 party address structure
820  *
821  * \return Nothing
822  */
q931_party_address_copy_to_pri(struct pri_party_address * pri_address,const struct q931_party_address * q931_address)823 void q931_party_address_copy_to_pri(struct pri_party_address *pri_address, const struct q931_party_address *q931_address)
824 {
825 	q931_party_number_copy_to_pri(&pri_address->number, &q931_address->number);
826 	q931_party_subaddress_copy_to_pri(&pri_address->subaddress, &q931_address->subaddress);
827 }
828 
829 /*!
830  * \brief Copy the Q.931 party id to the PRI party id structure.
831  *
832  * \param pri_id PRI party id structure
833  * \param q931_id Q.931 party id structure
834  *
835  * \return Nothing
836  */
q931_party_id_copy_to_pri(struct pri_party_id * pri_id,const struct q931_party_id * q931_id)837 void q931_party_id_copy_to_pri(struct pri_party_id *pri_id, const struct q931_party_id *q931_id)
838 {
839 	q931_party_name_copy_to_pri(&pri_id->name, &q931_id->name);
840 	q931_party_number_copy_to_pri(&pri_id->number, &q931_id->number);
841 	q931_party_subaddress_copy_to_pri(&pri_id->subaddress, &q931_id->subaddress);
842 }
843 
844 /*!
845  * \brief Copy the Q.931 redirecting data to the PRI redirecting structure.
846  *
847  * \param pri_redirecting PRI redirecting structure
848  * \param q931_redirecting Q.931 redirecting structure
849  *
850  * \return Nothing
851  */
q931_party_redirecting_copy_to_pri(struct pri_party_redirecting * pri_redirecting,const struct q931_party_redirecting * q931_redirecting)852 void q931_party_redirecting_copy_to_pri(struct pri_party_redirecting *pri_redirecting, const struct q931_party_redirecting *q931_redirecting)
853 {
854 	q931_party_id_copy_to_pri(&pri_redirecting->from, &q931_redirecting->from);
855 	q931_party_id_copy_to_pri(&pri_redirecting->to, &q931_redirecting->to);
856 	q931_party_id_copy_to_pri(&pri_redirecting->orig_called,
857 		&q931_redirecting->orig_called);
858 	pri_redirecting->count = q931_redirecting->count;
859 	pri_redirecting->orig_reason = q931_redirecting->orig_reason;
860 	pri_redirecting->reason = q931_redirecting->reason;
861 }
862 
863 /*!
864  * \brief Fixup some values in the q931_party_id that may be objectionable by switches.
865  *
866  * \param ctrl D channel controller.
867  * \param id Party ID to tweak.
868  *
869  * \return Nothing
870  */
q931_party_id_fixup(const struct pri * ctrl,struct q931_party_id * id)871 void q931_party_id_fixup(const struct pri *ctrl, struct q931_party_id *id)
872 {
873 	switch (ctrl->switchtype) {
874 	case PRI_SWITCH_DMS100:
875 	case PRI_SWITCH_ATT4ESS:
876 		/* Doesn't like certain presentation types */
877 		if (id->number.valid
878 			&& (id->number.presentation & PRI_PRES_RESTRICTION) == PRI_PRES_ALLOWED) {
879 			/* i.e., If presentation is allowed it must be a network number */
880 			id->number.presentation = PRES_ALLOWED_NETWORK_NUMBER;
881 		}
882 		break;
883 	default:
884 		break;
885 	}
886 }
887 
888 /*!
889  * \brief Determine the overall presentation value for the given party.
890  *
891  * \param id Party to determine the overall presentation value.
892  *
893  * \return Overall presentation value for the given party.
894  */
q931_party_id_presentation(const struct q931_party_id * id)895 int q931_party_id_presentation(const struct q931_party_id *id)
896 {
897 	int number_priority;
898 	int number_value;
899 	int number_screening;
900 	int name_priority;
901 	int name_value;
902 
903 	/* Determine name presentation priority. */
904 	if (!id->name.valid) {
905 		name_value = PRI_PRES_UNAVAILABLE;
906 		name_priority = 3;
907 	} else {
908 		name_value = id->name.presentation & PRI_PRES_RESTRICTION;
909 		switch (name_value) {
910 		case PRI_PRES_RESTRICTED:
911 			name_priority = 0;
912 			break;
913 		case PRI_PRES_ALLOWED:
914 			name_priority = 1;
915 			break;
916 		case PRI_PRES_UNAVAILABLE:
917 			name_priority = 2;
918 			break;
919 		default:
920 			name_value = PRI_PRES_UNAVAILABLE;
921 			name_priority = 3;
922 			break;
923 		}
924 	}
925 
926 	/* Determine number presentation priority. */
927 	if (!id->number.valid) {
928 		number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
929 		number_value = PRI_PRES_UNAVAILABLE;
930 		number_priority = 3;
931 	} else {
932 		number_screening = id->number.presentation & PRI_PRES_NUMBER_TYPE;
933 		number_value = id->number.presentation & PRI_PRES_RESTRICTION;
934 		switch (number_value) {
935 		case PRI_PRES_RESTRICTED:
936 			number_priority = 0;
937 			break;
938 		case PRI_PRES_ALLOWED:
939 			number_priority = 1;
940 			break;
941 		case PRI_PRES_UNAVAILABLE:
942 			number_priority = 2;
943 			break;
944 		default:
945 			number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
946 			number_value = PRI_PRES_UNAVAILABLE;
947 			number_priority = 3;
948 			break;
949 		}
950 	}
951 
952 	/* Select the wining presentation value. */
953 	if (name_priority < number_priority) {
954 		number_value = name_value;
955 	}
956 	if (number_value == PRI_PRES_UNAVAILABLE) {
957 		return PRES_NUMBER_NOT_AVAILABLE;
958 	}
959 
960 	return number_value | number_screening;
961 }
962 
963 /*!
964  * \internal
965  * \brief Get binary buffer contents into the destination buffer.
966  *
967  * \param dst Destination buffer.
968  * \param dst_size Destination buffer sizeof()
969  * \param src Source buffer.
970  * \param src_len Source buffer length to copy.
971  *
972  * \note The destination buffer is nul terminated just in case
973  * the contents are used as a string anyway.
974  *
975  * \retval 0 on success.
976  * \retval -1 on error.  The copy did not happen.
977  */
q931_memget(unsigned char * dst,size_t dst_size,const unsigned char * src,int src_len)978 static int q931_memget(unsigned char *dst, size_t dst_size, const unsigned char *src, int src_len)
979 {
980 	if (src_len < 0 || src_len > dst_size - 1) {
981 		dst[0] = 0;
982 		return -1;
983 	}
984 	memcpy(dst, src, src_len);
985 	dst[src_len] = 0;
986 	return 0;
987 }
988 
989 /*!
990  * \internal
991  * \brief Get source buffer contents into the destination buffer for a string.
992  *
993  * \param dst Destination buffer.
994  * \param dst_size Destination buffer sizeof()
995  * \param src Source buffer.
996  * \param src_len Source buffer length to copy.
997  *
998  * \note The destination buffer is nul terminated.
999  * \note Nul bytes from the source buffer are not copied.
1000  *
1001  * \retval 0 on success.
1002  * \retval -1 if nul bytes were found in the source data.
1003  */
q931_strget(unsigned char * dst,size_t dst_size,const unsigned char * src,int src_len)1004 static int q931_strget(unsigned char *dst, size_t dst_size, const unsigned char *src, int src_len)
1005 {
1006 	int saw_nul;
1007 
1008 	if (src_len < 1) {
1009 		dst[0] = '\0';
1010 		return 0;
1011 	}
1012 
1013 	saw_nul = 0;
1014 	--dst_size;
1015 	while (dst_size && src_len) {
1016 		if (*src) {
1017 			*dst++ = *src;
1018 			--dst_size;
1019 		} else {
1020 			/* Skip nul bytes in the source buffer. */
1021 			saw_nul = -1;
1022 		}
1023 		++src;
1024 		--src_len;
1025 	}
1026 	*dst = '\0';
1027 
1028 	return saw_nul;
1029 }
1030 
1031 
1032 /*!
1033  * \internal
1034  * \brief Get source buffer contents into the destination buffer for a string.
1035  *
1036  * \param ctrl D channel controller.
1037  * \param ie_name IE name to report nul bytes found in.
1038  * \param dst Destination buffer.
1039  * \param dst_size Destination buffer sizeof()
1040  * \param src Source buffer.
1041  * \param src_len Source buffer length to copy.
1042  *
1043  * \note The destination buffer is nul terminated.
1044  * \note Nul bytes from the source buffer are not copied.
1045  *
1046  * \retval 0 on success.
1047  * \retval -1 if nul bytes were found in the source data.
1048  */
q931_strget_gripe(struct pri * ctrl,const char * ie_name,unsigned char * dst,size_t dst_size,const unsigned char * src,int src_len)1049 static int q931_strget_gripe(struct pri *ctrl, const char *ie_name, unsigned char *dst, size_t dst_size, const unsigned char *src, int src_len)
1050 {
1051 	int saw_nul;
1052 
1053 /* To quietly remove nul octets just comment out the following line. */
1054 #define UNCONDITIONALLY_REPORT_REMOVED_NUL_OCTETS	1
1055 
1056 	saw_nul = q931_strget(dst, dst_size, src, src_len);
1057 	if (saw_nul
1058 #if !defined(UNCONDITIONALLY_REPORT_REMOVED_NUL_OCTETS)
1059 		&& (ctrl->debug & PRI_DEBUG_Q931_STATE)
1060 #endif
1061 		) {
1062 		pri_message(ctrl, "!! Removed nul octets from IE '%s' and returning '%s'.\n",
1063 			ie_name, dst);
1064 	}
1065 
1066 	return saw_nul;
1067 }
1068 
1069 /*!
1070  * \internal
1071  * \brief Clear the display text.
1072  *
1073  * \param call Q.931 call to clear display text.
1074  *
1075  * \return Nothing
1076  */
q931_display_clear(struct q931_call * call)1077 static void q931_display_clear(struct q931_call *call)
1078 {
1079 	call->display.text = NULL;
1080 }
1081 
1082 /*!
1083  * \internal
1084  * \brief Set the display text for the party name.
1085  *
1086  * \param call Q.931 call to set display text to the party name.
1087  *
1088  * \return Nothing
1089  */
q931_display_name_send(struct q931_call * call,const struct q931_party_name * name)1090 static void q931_display_name_send(struct q931_call *call, const struct q931_party_name *name)
1091 {
1092 	if (name->valid) {
1093 		switch (name->presentation & PRI_PRES_RESTRICTION) {
1094 		case PRI_PRES_ALLOWED:
1095 			call->display.text = (unsigned char *) name->str;
1096 			call->display.full_ie = 0;
1097 			call->display.length = strlen(name->str);
1098 			call->display.char_set = name->char_set;
1099 			break;
1100 		default:
1101 			call->display.text = NULL;
1102 			break;
1103 		}
1104 	} else {
1105 		call->display.text = NULL;
1106 	}
1107 }
1108 
1109 /*!
1110  * \brief Get the display text into the party name.
1111  *
1112  * \param call Q.931 call to get the display text into the party name.
1113  * \param name Party name to fill if there is display text.
1114  *
1115  * \note
1116  * The party name is not touched if there is no display text.
1117  *
1118  * \note
1119  * The display text is consumed.
1120  *
1121  * \return TRUE if party name filled.
1122  */
q931_display_name_get(struct q931_call * call,struct q931_party_name * name)1123 int q931_display_name_get(struct q931_call *call, struct q931_party_name *name)
1124 {
1125 	if (!call->display.text) {
1126 		return 0;
1127 	}
1128 
1129 	name->valid = 1;
1130 	name->char_set = call->display.char_set;
1131 	q931_strget_gripe(call->pri, ie2str(call->display.full_ie),
1132 		(unsigned char *) name->str, sizeof(name->str), call->display.text,
1133 		call->display.length);
1134 	if (name->str[0]) {
1135 		name->presentation = PRI_PRES_ALLOWED;
1136 	} else {
1137 		name->presentation = PRI_PRES_RESTRICTED;
1138 	}
1139 
1140 	/* Mark the display text as consumed. */
1141 	call->display.text = NULL;
1142 
1143 	return 1;
1144 }
1145 
1146 /*!
1147  * \internal
1148  * \brief Fill a subcmd with any display text.
1149  *
1150  * \param ctrl D channel controller.
1151  * \param call Q.931 call leg.
1152  *
1153  * \note
1154  * The display text is consumed.
1155  *
1156  * \return Nothing
1157  */
q931_display_subcmd(struct pri * ctrl,struct q931_call * call)1158 static void q931_display_subcmd(struct pri *ctrl, struct q931_call *call)
1159 {
1160 	struct pri_subcommand *subcmd;
1161 
1162 	if (call->display.text && call->display.length
1163 		&& (ctrl->display_flags.receive & PRI_DISPLAY_OPTION_TEXT)) {
1164 		subcmd = q931_alloc_subcommand(ctrl);
1165 		if (subcmd) {
1166 			/* Setup display text subcommand */
1167 			subcmd->cmd = PRI_SUBCMD_DISPLAY_TEXT;
1168 			subcmd->u.display.char_set = call->display.char_set;
1169 			q931_strget_gripe(ctrl, ie2str(call->display.full_ie),
1170 				(unsigned char *) subcmd->u.display.text, sizeof(subcmd->u.display.text),
1171 				call->display.text, call->display.length);
1172 			subcmd->u.display.length = strlen(subcmd->u.display.text);
1173 		}
1174 	}
1175 
1176 	/* Mark the display text as consumed. */
1177 	call->display.text = NULL;
1178 }
1179 
1180 /*!
1181  * \brief Find the winning subcall if it exists or current call if not outboundbroadcast.
1182  *
1183  * \param call Starting Q.931 call record of search.
1184  *
1185  * \retval winning-call or given call if not outboundbroadcast.
1186  * \retval NULL if no winning call yet.
1187  */
q931_find_winning_call(struct q931_call * call)1188 struct q931_call *q931_find_winning_call(struct q931_call *call)
1189 {
1190 	struct q931_call *master;
1191 
1192 	master = call->master_call;
1193 	if (master->outboundbroadcast) {
1194 		/* We have potential subcalls.  Now get the winning call if declared yet. */
1195 		if (master->pri_winner < 0) {
1196 			/* Winner not declared yet.*/
1197 			call = NULL;
1198 		} else {
1199 			call = master->subcalls[master->pri_winner];
1200 		}
1201 	}
1202 	return call;
1203 }
1204 
1205 /*!
1206  * \internal
1207  * \brief Append the given ie contents to the save ie location.
1208  *
1209  * \param save_ie Saved ie contents to append new ie.
1210  * \param ie Contents to append.
1211  *
1212  * \return Nothing
1213  */
q931_append_ie_contents(struct q931_saved_ie_contents * save_ie,struct q931_ie * ie)1214 static void q931_append_ie_contents(struct q931_saved_ie_contents *save_ie, struct q931_ie *ie)
1215 {
1216 	int size;
1217 
1218 	size = ie->len + 2;
1219 	if (size < sizeof(save_ie->data) - save_ie->length) {
1220 		/* Contents will fit so append it. */
1221 		memcpy(&save_ie->data[save_ie->length], ie, size);
1222 		save_ie->length += size;
1223 	}
1224 }
1225 
q931_clr_subcommands(struct pri * ctrl)1226 static void q931_clr_subcommands(struct pri *ctrl)
1227 {
1228 	ctrl->subcmds.counter_subcmd = 0;
1229 }
1230 
q931_alloc_subcommand(struct pri * ctrl)1231 struct pri_subcommand *q931_alloc_subcommand(struct pri *ctrl)
1232 {
1233 	if (ctrl->subcmds.counter_subcmd < PRI_MAX_SUBCOMMANDS) {
1234 		return &ctrl->subcmds.subcmd[ctrl->subcmds.counter_subcmd++];
1235 	}
1236 
1237 	pri_error(ctrl, "ERROR: Too many facility subcommands\n");
1238 	return NULL;
1239 }
1240 
code2str(int code,struct msgtype * codes,int max)1241 static char *code2str(int code, struct msgtype *codes, int max)
1242 {
1243 	int x;
1244 	for (x=0;x<max; x++)
1245 		if (codes[x].msgnum == code)
1246 			return codes[x].name;
1247 	return "Unknown";
1248 }
1249 
pritype(int type)1250 static char *pritype(int type)
1251 {
1252 	switch (type) {
1253 	case PRI_CPE:
1254 		return "CPE";
1255 		break;
1256 	case PRI_NETWORK:
1257 		return "NET";
1258 		break;
1259 	default:
1260 		return "UNKNOWN";
1261 	}
1262 }
1263 
binary(int b,int len)1264 static char *binary(int b, int len) {
1265 	static char res[33];
1266 	int x;
1267 	memset(res, 0, sizeof(res));
1268 	if (len > 32)
1269 		len = 32;
1270 	for (x=1;x<=len;x++)
1271 		res[x-1] = b & (1 << (len - x)) ? '1' : '0';
1272 	return res;
1273 }
1274 
receive_channel_id(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)1275 static int receive_channel_id(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
1276 {
1277 	int x;
1278 	int pos = 0;
1279 	int need_extended_channel_octets;/*!< TRUE if octets 3.2 and 3.3 need to be present. */
1280 
1281 	call->channel_id_ie_mandatory = 0;
1282 
1283 	if (ie->len < 1) {
1284 		/* Must have at least one payload octet. */
1285 		pri_error(ctrl, "!! Channel Identification ie too short\n");
1286 		return -1;
1287 	}
1288 
1289 	call->restart.count = 0;
1290 
1291 	if (ie->data[0] & 0x08) {
1292 		call->chanflags = FLAG_EXCLUSIVE;
1293 	} else {
1294 		call->chanflags = FLAG_PREFERRED;
1295 	}
1296 
1297 	need_extended_channel_octets = 0;
1298 	if (ie->data[0] & 0x20) {
1299 		/* PRI encoded interface type */
1300 		switch (ie->data[0] & 0x03) {
1301 		case 0x00:
1302 			/* No channel */
1303 			call->channelno = 0;
1304 			call->chanflags = FLAG_PREFERRED;
1305 			break;
1306 		case 0x01:
1307 			/* As indicated in following octets */
1308 			need_extended_channel_octets = 1;
1309 			break;
1310 		case 0x03:
1311 			/* Any channel */
1312 			call->chanflags = FLAG_PREFERRED;
1313 			break;
1314 		default:
1315 			pri_error(ctrl, "!! Unexpected Channel selection %d\n", ie->data[0] & 0x03);
1316 			return -1;
1317 		}
1318 	} else {
1319 		/* BRI encoded interface type */
1320 		switch (ie->data[0] & 0x03) {
1321 		case 0x00:
1322 			/* No channel */
1323 			call->channelno = 0;
1324 			call->chanflags = FLAG_PREFERRED;
1325 			break;
1326 		case 0x03:
1327 			/* Any channel */
1328 			call->chanflags = FLAG_PREFERRED;
1329 			break;
1330 		default:
1331 			/* Specified B channel (B1 or B2) */
1332 			call->channelno = ie->data[0] & 0x03;
1333 			break;
1334 		}
1335 	}
1336 
1337 	pos++;
1338 	if (ie->data[0] & 0x40) {
1339 		/* Explicitly defined DS1 (One or more 3.1 octets expected) */
1340 		if (ctrl->switchtype == PRI_SWITCH_QSIG) {
1341 			pri_error(ctrl, "!! Q.SIG does not support Channel Identification octet 3.1\n");
1342 			return -1;
1343 		}
1344 		if (ie->len <= pos) {
1345 			pri_error(ctrl, "!! Missing expected Channel Identification octet 3.1\n");
1346 			return -1;
1347 		}
1348 
1349 		/* Extract explicit DS1 reference. */
1350 		call->ds1no = ie->data[pos] & 0x7f;
1351 		call->ds1explicit = 1;
1352 
1353 		/* Advance to 3.2 octet if present. */
1354 		do {
1355 			++pos;
1356 		} while (pos < ie->len && !(ie->data[pos - 1] & 0x80));
1357 	} else {
1358 		call->ds1explicit = 0;
1359 	}
1360 
1361 	if (ie->data[0] & 0x04) {
1362 		/* D channel call.  Signaling only. */
1363 		call->cis_call = 1;
1364 		call->chanflags = FLAG_EXCLUSIVE;/* For safety mark this channel as exclusive. */
1365 		call->channelno = 0;
1366 		return 0;
1367 	}
1368 
1369 	if (need_extended_channel_octets && pos + 2 <= ie->len) {
1370 		/*
1371 		 * Octet 3.2 and at least one octet 3.3 are present.
1372 		 *
1373 		 * Process octet 3.2
1374 		 */
1375 		if ((ie->data[pos] & 0x0f) != 3) {
1376 			/* Channel type/mapping is not for B channel units. */
1377 			pri_error(ctrl, "!! Unexpected Channel Type %d\n", ie->data[pos] & 0x0f);
1378 			return -1;
1379 		}
1380 		if ((ie->data[pos] & 0x60) != 0) {
1381 			pri_error(ctrl, "!! Invalid CCITT coding %d\n", (ie->data[pos] & 0x60) >> 5);
1382 			return -1;
1383 		}
1384 		if (ie->data[pos++] & 0x10) {
1385 			/* Process 3.3 octets as a Slot Map */
1386 			call->slotmap = 0;
1387 			call->slotmap_size = (ie->len - pos > 3) ? 1 : 0;
1388 
1389 			/*
1390 			 * We will be tolerant of partial slot maps that do not
1391 			 * specify the upper channels.  We will assume they
1392 			 * are not requested.
1393 			 *
1394 			 * We will only read up to 24 or 32 bit channel maps.
1395 			 */
1396 			for (x = call->slotmap_size ? 4 : 3; x--;) {
1397 				call->slotmap <<= 8;
1398 				call->slotmap |= ie->data[pos++];
1399 				if (ie->len <= pos) {
1400 					/* No more ie contents. */
1401 					break;
1402 				}
1403 			}
1404 
1405 			if (msgtype == Q931_RESTART) {
1406 				int bit;
1407 
1408 				/* Convert the slotmap to a channel list for RESTART support. */
1409 				for (bit = 0; bit < ARRAY_LEN(call->restart.chan_no); ++bit) {
1410 					if (call->slotmap & (1UL << bit)) {
1411 						call->restart.chan_no[call->restart.count++] = bit
1412 							+ (call->slotmap_size ? 0 : 1);
1413 					}
1414 				}
1415 			}
1416 		} else {
1417 			/*
1418 			 * Process 3.3 octets as either a single channel or a channel list
1419 			 *
1420 			 * Get single channel
1421 			 */
1422 			call->channelno = ie->data[pos] & 0x7f;
1423 			if (ctrl->chan_mapping_logical && call->channelno > 15) {
1424 				call->channelno++;
1425 			}
1426 
1427 			if (msgtype == Q931_RESTART) {
1428 				/* Read in channel list for RESTART support. */
1429 				while (call->restart.count < ARRAY_LEN(call->restart.chan_no)) {
1430 					int chan_no;
1431 
1432 					chan_no = ie->data[pos] & 0x7f;
1433 					if (ctrl->chan_mapping_logical && chan_no > 15) {
1434 						++chan_no;
1435 					}
1436 					call->restart.chan_no[call->restart.count++] = chan_no;
1437 					if (ie->data[pos++] & 0x80) {
1438 						/* Channel list finished. */
1439 						break;
1440 					}
1441 					if (ie->len <= pos) {
1442 						/* No more ie contents. */
1443 						break;
1444 					}
1445 				}
1446 			}
1447 		}
1448 	} else if (need_extended_channel_octets) {
1449 		pri_error(ctrl, "!! Missing expected Channel Identification octets 3.2 or 3.3\n");
1450 		return -1;
1451 	}
1452 	return 0;
1453 }
1454 
transmit_channel_id(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)1455 static int transmit_channel_id(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
1456 {
1457 	int pos = 0;
1458 
1459 	/* We are ready to transmit single IE only */
1460 	if (order > 1)
1461 		return 0;
1462 
1463 	if (call->cis_call) {
1464 		/*
1465 		 * Read the standards docs to figure this out.
1466 		 * Q.SIG ECMA-165 section 7.3
1467 		 * ITU Q.931 section 4.5.13
1468 		 */
1469 		ie->data[pos++] = ctrl->bri ? 0x8c : 0xac;
1470 		return pos + 2;
1471 	}
1472 
1473 	/* Start with standard stuff */
1474 	if (ctrl->switchtype == PRI_SWITCH_GR303_TMC)
1475 		ie->data[pos] = 0x69;
1476 	else if (ctrl->bri) {
1477 		ie->data[pos] = 0x80;
1478 		ie->data[pos] |= (call->channelno & 0x3);
1479 	} else {
1480 		/* PRI */
1481 		if (call->slotmap != -1 || (call->chanflags & FLAG_WHOLE_INTERFACE)) {
1482 			/* Specified channel */
1483 			ie->data[pos] = 0xa1;
1484 		} else if (call->channelno < 0 || call->channelno == 0xff) {
1485 			/* Any channel */
1486 			ie->data[pos] = 0xa3;
1487 		} else if (!call->channelno) {
1488 			/* No channel */
1489 			ie->data[pos] = 0xa0;
1490 		} else {
1491 			/* Specified channel */
1492 			ie->data[pos] = 0xa1;
1493 		}
1494 	}
1495 	if (call->chanflags & FLAG_EXCLUSIVE) {
1496 		/* Channel is exclusive */
1497 		if (!(ie->data[pos] & 0x03)) {
1498 			/* An exclusive no channel id ie is to be discarded. */
1499 			return 0;
1500 		}
1501 		ie->data[pos] |= 0x08;
1502 	} else if (!call->chanflags) {
1503 		/* Don't need this IE */
1504 		return 0;
1505 	}
1506 
1507 	if (!ctrl->bri && (((ctrl->switchtype != PRI_SWITCH_QSIG) && (call->ds1no > 0)) || call->ds1explicit)) {
1508 		/* We are specifying the interface.  Octet 3.1 */
1509 		ie->data[pos++] |= 0x40;
1510 		ie->data[pos++] = 0x80 | call->ds1no;
1511 	} else {
1512 		++pos;
1513 	}
1514 
1515 	if (!ctrl->bri && (ie->data[0] & 0x03) == 0x01 /* Specified channel */
1516 		&& !(call->chanflags & FLAG_WHOLE_INTERFACE)) {
1517 		/* The 3.2 and 3.3 octets need to be present */
1518 		ie->data[pos] = 0x83;
1519 		if (0 < call->channelno && call->channelno != 0xff) {
1520 			/* Channel number specified and preferred over slot map if we have one. */
1521 			++pos;
1522 			if (msgtype == Q931_RESTART_ACKNOWLEDGE && call->restart.count) {
1523 				int chan_no;
1524 				int idx;
1525 
1526 				/* Build RESTART_ACKNOWLEDGE channel list */
1527 				for (idx = 0; idx < call->restart.count; ++idx) {
1528 					chan_no = call->restart.chan_no[idx];
1529 					if (ctrl->chan_mapping_logical && chan_no > 16) {
1530 						--chan_no;
1531 					}
1532 					if (call->restart.count <= idx + 1) {
1533 						/* Last channel list channel. */
1534 						chan_no |= 0x80;
1535 					}
1536 					ie->data[pos++] = chan_no;
1537 				}
1538 			} else {
1539 				if (ctrl->chan_mapping_logical && call->channelno > 16) {
1540 					ie->data[pos++] = 0x80 | (call->channelno - 1);
1541 				} else {
1542 					ie->data[pos++] = 0x80 | call->channelno;
1543 				}
1544 			}
1545 		} else if (call->slotmap != -1) {
1546 			int octet;
1547 
1548 			/* We have to send a slot map */
1549 			ie->data[pos++] |= 0x10;
1550 			for (octet = call->slotmap_size ? 4 : 3; octet--;) {
1551 				ie->data[pos++] = (call->slotmap >> (8 * octet)) & 0xff;
1552 			}
1553 		} else {
1554 			pri_error(ctrl, "XXX We need either a channelno or slotmap but have neither!\n");
1555 			/* Discard this malformed ie. */
1556 			return 0;
1557 		}
1558 	}
1559 
1560 	return pos + 2;
1561 }
1562 
dump_channel_id(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)1563 static void dump_channel_id(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
1564 {
1565 	int pos;
1566 	int x;
1567 	int res;
1568 
1569 	static const char *msg_chan_sel[] = {
1570 		"No channel selected", "B1 channel", "B2 channel", "Any channel selected",
1571 		"No channel selected", "As indicated in following octets", "Reserved", "Any channel selected"
1572 	};
1573 
1574 	pri_message(ctrl,
1575 		"%c %s (len=%2d) [ Ext: %d  IntID: %s  %s  Spare: %d  %s  Dchan: %d\n",
1576 		prefix, ie2str(full_ie), len,
1577 		(ie->data[0] & 0x80) ? 1 : 0,
1578 		(ie->data[0] & 0x40) ? "Explicit" : "Implicit",
1579 		(ie->data[0] & 0x20) ? "Other(PRI)" : "BRI",
1580 		(ie->data[0] & 0x10) ? 1 : 0,
1581 		(ie->data[0] & 0x08) ? "Exclusive" : "Preferred",
1582 		(ie->data[0] & 0x04) ? 1 : 0);
1583 	pri_message(ctrl, "%c                       ChanSel: %s\n",
1584 		prefix, msg_chan_sel[(ie->data[0] & 0x03) | ((ie->data[0] & 0x20) >> 3)]);
1585 	pos = 1;
1586 	len -= 2;
1587 	if (ie->data[0] & 0x40) {
1588 		/* Explicitly defined DS1 (One or more 3.1 octets expected) */
1589 		if (ctrl->switchtype == PRI_SWITCH_QSIG) {
1590 			pri_message(ctrl, "%c                       Octet 3.1 specified when Q.SIG!\n",
1591 				prefix);
1592 		}
1593 		if (pos < len) {
1594 			do {
1595 				pri_message(ctrl, "%c                       Ext: %d  DS1 Identifier: %d\n",
1596 					prefix, (ie->data[pos] & 0x80) >> 7, ie->data[pos] & 0x7f);
1597 				++pos;
1598 			} while (!(ie->data[pos - 1] & 0x80) && pos < len);
1599 		} else {
1600 			pri_message(ctrl, "%c                       Octet 3.1 is missing!\n", prefix);
1601 		}
1602 	} else {
1603 		/* Implicitly defined DS1 */
1604 	}
1605 	if (pos < len) {
1606 		/* Octet 3.2 present */
1607 		pri_message(ctrl,
1608 			"%c                       Ext: %d  Coding: %d  %s Specified  Channel Type: %d\n",
1609 			prefix, (ie->data[pos] & 0x80) >> 7, (ie->data[pos] & 60) >> 5,
1610 			(ie->data[pos] & 0x10) ? "Slot Map" : "Number", ie->data[pos] & 0x0f);
1611 		++pos;
1612 	}
1613 	if (pos < len) {
1614 		/* One or more 3.3 octets present */
1615 		if (!(ie->data[pos - 1] & 0x10)) {
1616 			/* Number specified */
1617 			do {
1618 				pri_message(ctrl,
1619 					"%c                       Ext: %d  Channel: %d Type: %s%c\n",
1620 					prefix, (ie->data[pos] & 0x80) >> 7,
1621 					(ie->data[pos]) & 0x7f, pritype(ctrl->localtype),
1622 					(pos + 1 < len) ? ' ' : ']');
1623 				++pos;
1624 			} while (pos < len);
1625 		} else {
1626 			/* Map specified */
1627 			res = 0;
1628 			x = 0;
1629 			do {
1630 				res <<= 8;
1631 				res |= ie->data[pos++];
1632 				++x;
1633 			} while (pos < len);
1634 			pri_message(ctrl, "%c                       Map len: %d  Map: %s ]\n", prefix,
1635 				x, binary(res, x << 3));
1636 		}
1637 	} else {
1638 		pri_message(ctrl, "%c                     ]\n", prefix);
1639 	}
1640 }
1641 
ri2str(int ri)1642 static char *ri2str(int ri)
1643 {
1644 	static struct msgtype ris[] = {
1645 		{ 0, "Indicated Channel" },
1646 		{ 6, "Single DS1 Facility" },
1647 		{ 7, "All DS1 Facilities" },
1648 	};
1649 	return code2str(ri, ris, sizeof(ris) / sizeof(ris[0]));
1650 }
1651 
dump_restart_indicator(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)1652 static void dump_restart_indicator(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
1653 {
1654 	pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  Spare: %d  Resetting %s (%d) ]\n",
1655 		prefix, ie2str(full_ie), len, (ie->data[0] & 0x80) >> 7,
1656 		(ie->data[0] & 0x78) >> 3, ri2str(ie->data[0] & 0x7), ie->data[0] & 0x7);
1657 }
1658 
receive_restart_indicator(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)1659 static int receive_restart_indicator(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
1660 {
1661 	/* Pretty simple */
1662 	call->ri = ie->data[0] & 0x7;
1663 	return 0;
1664 }
1665 
transmit_restart_indicator(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)1666 static int transmit_restart_indicator(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
1667 {
1668 	/* Pretty simple */
1669 	switch(call->ri) {
1670 	case 0:
1671 	case 6:
1672 	case 7:
1673 		ie->data[0] = 0x80 | (call->ri & 0x7);
1674 		break;
1675 	case 5:
1676 		/* Switch compatibility */
1677 		ie->data[0] = 0xA0 | (call->ri & 0x7);
1678 		break;
1679 	default:
1680 		pri_error(ctrl, "!! Invalid restart indicator value %d\n", call->ri);
1681 		return-1;
1682 	}
1683 	return 3;
1684 }
1685 
redirection_reason2str(int mode)1686 static char *redirection_reason2str(int mode)
1687 {
1688 	static struct msgtype modes[] = {
1689 		{ PRI_REDIR_UNKNOWN, "Unknown" },
1690 		{ PRI_REDIR_FORWARD_ON_BUSY, "Forwarded on busy" },
1691 		{ PRI_REDIR_FORWARD_ON_NO_REPLY, "Forwarded on no reply" },
1692 		{ PRI_REDIR_DEFLECTION, "Call deflected" },
1693 		{ PRI_REDIR_DTE_OUT_OF_ORDER, "Called DTE out of order" },
1694 		{ PRI_REDIR_FORWARDED_BY_DTE, "Forwarded by called DTE" },
1695 		{ PRI_REDIR_UNCONDITIONAL, "Forwarded unconditionally" },
1696 	};
1697 	return code2str(mode, modes, sizeof(modes) / sizeof(modes[0]));
1698 }
1699 
cap2str(int mode)1700 static char *cap2str(int mode)
1701 {
1702 	static struct msgtype modes[] = {
1703 		{ PRI_TRANS_CAP_SPEECH, "Speech" },
1704 		{ PRI_TRANS_CAP_DIGITAL, "Unrestricted digital information" },
1705 		{ PRI_TRANS_CAP_RESTRICTED_DIGITAL, "Restricted digital information" },
1706 		{ PRI_TRANS_CAP_3_1K_AUDIO, "3.1kHz audio" },
1707 		{ PRI_TRANS_CAP_DIGITAL_W_TONES, "Unrestricted digital information with tones/announcements" },
1708 		{ PRI_TRANS_CAP_VIDEO, "Video" },
1709 		{ PRI_TRANS_CAP_AUDIO_4ESS, "3.1khz audio (4ESS)" },
1710 	};
1711 	return code2str(mode, modes, sizeof(modes) / sizeof(modes[0]));
1712 }
1713 
mode2str(int mode)1714 static char *mode2str(int mode)
1715 {
1716 	static struct msgtype modes[] = {
1717 		{ TRANS_MODE_64_CIRCUIT, "64kbps, circuit-mode" },
1718 		{ TRANS_MODE_2x64_CIRCUIT, "2x64kbps, circuit-mode" },
1719 		{ TRANS_MODE_384_CIRCUIT, "384kbps, circuit-mode" },
1720 		{ TRANS_MODE_1536_CIRCUIT, "1536kbps, circuit-mode" },
1721 		{ TRANS_MODE_1920_CIRCUIT, "1920kbps, circuit-mode" },
1722 		{ TRANS_MODE_MULTIRATE, "Multirate (Nx64kbps)" },
1723 		{ TRANS_MODE_PACKET, "Packet Mode" },
1724 	};
1725 	return code2str(mode, modes, sizeof(modes) / sizeof(modes[0]));
1726 }
1727 
l12str(int proto)1728 static char *l12str(int proto)
1729 {
1730 	static struct msgtype protos[] = {
1731  		{ PRI_LAYER_1_ITU_RATE_ADAPT, "V.110 Rate Adaption" },
1732 		{ PRI_LAYER_1_ULAW, "u-Law" },
1733 		{ PRI_LAYER_1_ALAW, "A-Law" },
1734 		{ PRI_LAYER_1_G721, "G.721 ADPCM" },
1735 		{ PRI_LAYER_1_G722_G725, "G.722/G.725 7kHz Audio" },
1736  		{ PRI_LAYER_1_H223_H245, "H.223/H.245 Multimedia" },
1737 		{ PRI_LAYER_1_NON_ITU_ADAPT, "Non-ITU Rate Adaption" },
1738 		{ PRI_LAYER_1_V120_RATE_ADAPT, "V.120 Rate Adaption" },
1739 		{ PRI_LAYER_1_X31_RATE_ADAPT, "X.31 Rate Adaption" },
1740 	};
1741 	return code2str(proto, protos, sizeof(protos) / sizeof(protos[0]));
1742 }
1743 
ra2str(int proto)1744 static char *ra2str(int proto)
1745 {
1746 	static struct msgtype protos[] = {
1747 		{ PRI_RATE_ADAPT_9K6, "9.6 kbit/s" },
1748 	};
1749 	return code2str(proto, protos, sizeof(protos) / sizeof(protos[0]));
1750 }
1751 
l22str(int proto)1752 static char *l22str(int proto)
1753 {
1754 	static struct msgtype protos[] = {
1755 		{ LAYER_2_LAPB, "LAPB" },
1756 	};
1757 	return code2str(proto, protos, sizeof(protos) / sizeof(protos[0]));
1758 }
1759 
l32str(int proto)1760 static char *l32str(int proto)
1761 {
1762 	static struct msgtype protos[] = {
1763 		{ LAYER_3_X25, "X.25" },
1764 	};
1765 	return code2str(proto, protos, sizeof(protos) / sizeof(protos[0]));
1766 }
1767 
int_rate2str(int proto)1768 static char *int_rate2str(int proto)
1769 {
1770     static struct msgtype protos[] = {
1771 		{ PRI_INT_RATE_8K, "8 kbit/s" },
1772 		{ PRI_INT_RATE_16K, "16 kbit/s" },
1773 		{ PRI_INT_RATE_32K, "32 kbit/s" },
1774     };
1775     return code2str(proto, protos, sizeof(protos) / sizeof(protos[0]));
1776 }
1777 
dump_bearer_capability(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)1778 static void dump_bearer_capability(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
1779 {
1780 	int pos=2;
1781 	pri_message(ctrl,
1782 		"%c %s (len=%2d) [ Ext: %d  Coding-Std: %d  Info transfer capability: %s (%d)\n",
1783 		prefix, ie2str(full_ie), len, (ie->data[0] & 0x80 ) >> 7,
1784 		(ie->data[0] & 0x60) >> 5, cap2str(ie->data[0] & 0x1f),
1785 		(ie->data[0] & 0x1f));
1786 	pri_message(ctrl, "%c                              Ext: %d  Trans mode/rate: %s (%d)\n", prefix, (ie->data[1] & 0x80) >> 7, mode2str(ie->data[1] & 0x7f), ie->data[1] & 0x7f);
1787 
1788 	/* octet 4.1 exists if mode/rate is multirate */
1789 	if ((ie->data[1] & 0x7f) == 0x18) {
1790 		pri_message(ctrl, "%c                              Ext: %d  Transfer rate multiplier: %d x 64\n", prefix, (ie->data[2] & 0x80) >> 7, ie->data[2] & 0x7f);
1791 		pos++;
1792 	}
1793 
1794 	/* don't count the IE num and length as part of the data */
1795 	len -= 2;
1796 
1797 	/* Look for octet 5; this is identified by bits 5,6 == 01 */
1798      	if (pos < len &&
1799 		(ie->data[pos] & 0x60) == 0x20) {
1800 
1801 		/* although the layer1 is only the bottom 5 bits of the byte,
1802 		   previous versions of this library passed bits 5&6 through
1803 		   too, so we have to do the same for binary compatability */
1804 		u_int8_t layer1 = ie->data[pos] & 0x7f;
1805 
1806 		pri_message(ctrl, "%c                                User information layer 1: %s (%d)\n",
1807 		            prefix, l12str(layer1), layer1);
1808 		pos++;
1809 
1810 		/* octet 5a? */
1811 		if (pos < len && !(ie->data[pos-1] & 0x80)) {
1812 			int ra = ie->data[pos] & 0x7f;
1813 
1814 			pri_message(ctrl, "%c                                Async: %d, Negotiation: %d, "
1815 				"User rate: %s (%#x)\n",
1816 				prefix,
1817 				ra & PRI_RATE_ADAPT_ASYNC ? 1 : 0,
1818 				ra & PRI_RATE_ADAPT_NEGOTIATION_POSS ? 1 : 0,
1819 				ra2str(ra & PRI_RATE_USER_RATE_MASK),
1820 				ra & PRI_RATE_USER_RATE_MASK);
1821 			pos++;
1822 		}
1823 
1824 		/* octet 5b? */
1825 		if (pos < len && !(ie->data[pos-1] & 0x80)) {
1826 			u_int8_t data = ie->data[pos];
1827 			if (layer1 == PRI_LAYER_1_ITU_RATE_ADAPT) {
1828 				pri_message(ctrl, "%c                                Intermediate rate: %s (%d), "
1829 					"NIC on Tx: %d, NIC on Rx: %d, "
1830 					"Flow control on Tx: %d, "
1831 					"Flow control on Rx: %d\n",
1832 					prefix, int_rate2str((data & 0x60)>>5),
1833 					(data & 0x60)>>5,
1834 					(data & 0x10)?1:0,
1835 					(data & 0x08)?1:0,
1836 					(data & 0x04)?1:0,
1837 					(data & 0x02)?1:0);
1838 			} else if (layer1 == PRI_LAYER_1_V120_RATE_ADAPT) {
1839 				pri_message(ctrl, "%c                                Hdr: %d, Multiframe: %d, Mode: %d, "
1840 					"LLI negot: %d, Assignor: %d, "
1841 					"In-band neg: %d\n", prefix,
1842 					(data & 0x40)?1:0,
1843 					(data & 0x20)?1:0,
1844 					(data & 0x10)?1:0,
1845 					(data & 0x08)?1:0,
1846 					(data & 0x04)?1:0,
1847 					(data & 0x02)?1:0);
1848 			} else {
1849 				pri_message(ctrl, "%c                                Unknown octet 5b: 0x%x\n",
1850 					prefix, data);
1851 			}
1852 			pos++;
1853 		}
1854 
1855 		/* octet 5c? */
1856 		if (pos < len && !(ie->data[pos-1] & 0x80)) {
1857 			u_int8_t data = ie->data[pos];
1858 			const char *stop_bits[] = {"?","1","1.5","2"};
1859 			const char *data_bits[] = {"?","5","7","8"};
1860 			const char *parity[] = {"Odd","?","Even","None",
1861 				       "zero","one","?","?"};
1862 
1863 			pri_message(ctrl, "%c                                Stop bits: %s, data bits: %s, "
1864 			    "parity: %s\n", prefix,
1865 			    stop_bits[(data & 0x60) >> 5],
1866 			    data_bits[(data & 0x18) >> 3],
1867 			    parity[(data & 0x7)]);
1868 
1869 			pos++;
1870 		}
1871 
1872 			/* octet 5d? */
1873 		if (pos < len && !(ie->data[pos-1] & 0x80)) {
1874 			u_int8_t data = ie->data[pos];
1875 			pri_message(ctrl, "%c                                Duplex mode: %d, modem type: %d\n",
1876 				prefix, (data & 0x40) ? 1 : 0,data & 0x3F);
1877  			pos++;
1878 		}
1879  	}
1880 
1881 
1882 	/* Look for octet 6; this is identified by bits 5,6 == 10 */
1883 	if (pos < len &&
1884 		(ie->data[pos] & 0x60) == 0x40) {
1885 		pri_message(ctrl, "%c                                User information layer 2: %s (%d)\n",
1886 			prefix, l22str(ie->data[pos] & 0x1f),
1887 			ie->data[pos] & 0x1f);
1888 		pos++;
1889 	}
1890 
1891 	/* Look for octet 7; this is identified by bits 5,6 == 11 */
1892 	if (pos < len && (ie->data[pos] & 0x60) == 0x60) {
1893 		pri_message(ctrl, "%c                                User information layer 3: %s (%d)\n",
1894 			prefix, l32str(ie->data[pos] & 0x1f),
1895 			ie->data[pos] & 0x1f);
1896 		pos++;
1897 
1898 		/* octets 7a and 7b? */
1899 		if (pos + 1 < len && !(ie->data[pos-1] & 0x80) &&
1900 			!(ie->data[pos] & 0x80)) {
1901 			unsigned int proto;
1902 			proto = ((ie->data[pos] & 0xF) << 4 ) |
1903 			         (ie->data[pos+1] & 0xF);
1904 
1905 			pri_message(ctrl, "%c                                Network layer: 0x%x\n", prefix,
1906 			            proto );
1907 			pos += 2;
1908 		}
1909 	}
1910 }
1911 
receive_bearer_capability(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)1912 static int receive_bearer_capability(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
1913 {
1914 	int pos = 2;
1915 
1916 	switch (ie->data[0] & 0x60) {
1917 	case 0x00:/* ITU-T standardized coding */
1918 		call->bc.transcapability = ie->data[0] & 0x1f;
1919 		call->bc.transmoderate = ie->data[1] & 0x7f;
1920 
1921 		/* octet 4.1 exists if mode/rate is multirate */
1922 		if (call->bc.transmoderate == TRANS_MODE_MULTIRATE) {
1923 			call->bc.transmultiple = ie->data[pos++] & 0x7f;
1924 		}
1925 
1926 		/* Look for octet 5; this is identified by bits 5,6 == 01 */
1927 		if (pos < len && (ie->data[pos] & 0x60) == 0x20) {
1928 			/* although the layer1 is only the bottom 5 bits of the byte,
1929 			   previous versions of this library passed bits 5&6 through
1930 			   too, so we have to do the same for binary compatability */
1931 			call->bc.userl1 = ie->data[pos] & 0x7f;
1932 			pos++;
1933 
1934 			/* octet 5a? */
1935 			if (pos < len && !(ie->data[pos-1] & 0x80)) {
1936 				call->bc.rateadaption = ie->data[pos] & 0x7f;
1937 				pos++;
1938 			}
1939 
1940 			/* octets 5b through 5d? */
1941 			while (pos < len && !(ie->data[pos-1] & 0x80)) {
1942 				pos++;
1943 			}
1944 
1945 		}
1946 
1947 		/* Look for octet 6; this is identified by bits 5,6 == 10 */
1948 		if (pos < len && (ie->data[pos] & 0x60) == 0x40) {
1949 			call->bc.userl2 = ie->data[pos++] & 0x1f;
1950 		}
1951 
1952 		/* Look for octet 7; this is identified by bits 5,6 == 11 */
1953 		if (pos < len && (ie->data[pos] & 0x60) == 0x60) {
1954 			call->bc.userl3 = ie->data[pos++] & 0x1f;
1955 		}
1956 		break;
1957 	case 0x20:/* ISO/IEC standard */
1958 		if (ie->data[0] == 0xa8 && ie->data[1] == 0x80) {
1959 			/*
1960 			 * Q.SIG uses for CIS calls. ECMA-165 Section 11.3.1
1961 			 * This mandatory ie is more or less a place holder in this case.
1962 			 */
1963 			call->bc.transcapability = PRI_TRANS_CAP_DIGITAL;
1964 			call->bc.transmoderate = TRANS_MODE_64_CIRCUIT;
1965 			break;
1966 		}
1967 		/* Fall through */
1968 	default:
1969 		pri_error(ctrl, "!! Coding-standard field is not Q.931.\n");
1970 		return -1;
1971 	}
1972 	return 0;
1973 }
1974 
transmit_bearer_capability(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)1975 static int transmit_bearer_capability(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
1976 {
1977 	int tc;
1978 	int pos;
1979 
1980 	/* We are ready to transmit single IE only */
1981 	if(order > 1)
1982 		return 0;
1983 
1984 	if (ctrl->link.next && !ctrl->bri) {
1985 		/* Bearer capability is *hard coded* in GR-303 */
1986 		ie->data[0] = 0x88;
1987 		ie->data[1] = 0x90;
1988 		return 4;
1989 	}
1990 
1991 	if (call->cis_call) {
1992 		ie->data[0] = 0xa8;
1993 		ie->data[1] = 0x80;
1994 		return 4;
1995 	}
1996 
1997 	tc = call->bc.transcapability;
1998 	ie->data[0] = 0x80 | tc;
1999 	ie->data[1] = call->bc.transmoderate | 0x80;
2000 
2001 	pos = 2;
2002 	/* octet 4.1 exists if mode/rate is multirate */
2003 	if (call->bc.transmoderate == TRANS_MODE_MULTIRATE) {
2004 		ie->data[pos++] = call->bc.transmultiple | 0x80;
2005 	}
2006 
2007 	if ((tc & PRI_TRANS_CAP_DIGITAL) && (ctrl->switchtype == PRI_SWITCH_EUROISDN_E1) &&
2008 		(call->bc.transmoderate == TRANS_MODE_PACKET)) {
2009 		/* Apparently EuroISDN switches don't seem to like user layer 2/3 */
2010 		return 4;
2011 	}
2012 
2013 	if ((tc & PRI_TRANS_CAP_DIGITAL) && (call->bc.transmoderate == TRANS_MODE_64_CIRCUIT)) {
2014 		/* Unrestricted digital 64k data calls don't use user layer 2/3 */
2015 		return 4;
2016 	}
2017 
2018 	if (call->bc.transmoderate != TRANS_MODE_PACKET) {
2019 		/* If you have an AT&T 4ESS, you don't send any more info */
2020 		if ((ctrl->switchtype != PRI_SWITCH_ATT4ESS) && (call->bc.userl1 > -1)) {
2021 			ie->data[pos++] = call->bc.userl1 | 0x80; /* XXX Ext bit? XXX */
2022 			if (call->bc.userl1 == PRI_LAYER_1_ITU_RATE_ADAPT) {
2023 				ie->data[pos++] = call->bc.rateadaption | 0x80;
2024 			}
2025 			return pos + 2;
2026  		}
2027 
2028  		ie->data[pos++] = 0xa0 | (call->bc.userl1 & 0x1f);
2029 
2030  		if (call->bc.userl1 == PRI_LAYER_1_ITU_RATE_ADAPT) {
2031  		    ie->data[pos-1] &= ~0x80; /* clear EXT bit in octet 5 */
2032  		    ie->data[pos++] = call->bc.rateadaption | 0x80;
2033  		}
2034  	}
2035 
2036 
2037  	if (call->bc.userl2 != -1)
2038  		ie->data[pos++] = 0xc0 | (call->bc.userl2 & 0x1f);
2039 
2040  	if (call->bc.userl3 != -1)
2041  		ie->data[pos++] = 0xe0 | (call->bc.userl3 & 0x1f);
2042 
2043  	return pos + 2;
2044 }
2045 
pri_plan2str(int plan)2046 char *pri_plan2str(int plan)
2047 {
2048 	static struct msgtype plans[] = {
2049 		{ PRI_INTERNATIONAL_ISDN, "International number in ISDN" },
2050 		{ PRI_NATIONAL_ISDN, "National number in ISDN" },
2051 		{ PRI_LOCAL_ISDN, "Local number in ISDN" },
2052 		{ PRI_PRIVATE, "Private numbering plan" },
2053 		{ PRI_UNKNOWN, "Unknown numbering plan" },
2054 	};
2055 	return code2str(plan, plans, sizeof(plans) / sizeof(plans[0]));
2056 }
2057 
npi2str(int plan)2058 static char *npi2str(int plan)
2059 {
2060 	static struct msgtype plans[] = {
2061 		{ PRI_NPI_UNKNOWN, "Unknown Number Plan" },
2062 		{ PRI_NPI_E163_E164, "ISDN/Telephony Numbering Plan (E.164/E.163)" },
2063 		{ PRI_NPI_X121, "Data Numbering Plan (X.121)" },
2064 		{ PRI_NPI_F69, "Telex Numbering Plan (F.69)" },
2065 		{ PRI_NPI_NATIONAL, "National Standard Numbering Plan" },
2066 		{ PRI_NPI_PRIVATE, "Private Numbering Plan" },
2067 		{ PRI_NPI_RESERVED, "Reserved Number Plan" },
2068 	};
2069 	return code2str(plan, plans, sizeof(plans) / sizeof(plans[0]));
2070 }
2071 
ton2str(int plan)2072 static char *ton2str(int plan)
2073 {
2074 	static struct msgtype plans[] = {
2075 		{ PRI_TON_UNKNOWN, "Unknown Number Type" },
2076 		{ PRI_TON_INTERNATIONAL, "International Number" },
2077 		{ PRI_TON_NATIONAL, "National Number" },
2078 		{ PRI_TON_NET_SPECIFIC, "Network Specific Number" },
2079 		{ PRI_TON_SUBSCRIBER, "Subscriber Number" },
2080 		{ PRI_TON_ABBREVIATED, "Abbreviated number" },
2081 		{ PRI_TON_RESERVED, "Reserved Number" },
2082 	};
2083 	return code2str(plan, plans, sizeof(plans) / sizeof(plans[0]));
2084 }
2085 
subaddrtype2str(int plan)2086 static char *subaddrtype2str(int plan)
2087 {
2088 	static struct msgtype plans[] = {
2089 		{ 0, "NSAP (X.213/ISO 8348 AD2)" },
2090 		{ 2, "User Specified" },
2091 	};
2092 	return code2str(plan, plans, sizeof(plans) / sizeof(plans[0]));
2093 }
2094 
2095 /* Calling Party Category (Definitions from Q.763) */
cpc2str(int plan)2096 static char *cpc2str(int plan)
2097 {
2098 	static struct msgtype plans[] = {
2099 		{ 0, "Unknown Source" },
2100 		{ 1, "Operator French" },
2101 		{ 2, "Operator English" },
2102 		{ 3, "Operator German" },
2103 		{ 4, "Operator Russian" },
2104 		{ 5, "Operator Spanish" },
2105 		{ 6, "Mut Agree Chinese" },
2106 		{ 7, "Mut Agreement" },
2107 		{ 8, "Mut Agree Japanese" },
2108 		{ 9, "National Operator" },
2109 		{ 10, "Ordinary Toll Caller" },
2110 		{ 11, "Priority Toll Caller" },
2111 		{ 12, "Data Call" },
2112 		{ 13, "Test Call" },
2113 		{ 14, "Spare" },
2114 		{ 15, "Pay Phone" },
2115 	};
2116 	return code2str(plan, plans, ARRAY_LEN(plans));
2117 }
2118 
pri_pres2str(int pres)2119 char *pri_pres2str(int pres)
2120 {
2121 	static struct msgtype press[] = {
2122 		{ PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED,        "Presentation allowed, User-provided, not screened" },
2123 		{ PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN,     "Presentation allowed, User-provided, verified and passed" },
2124 		{ PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN,     "Presentation allowed, User-provided, verified and failed" },
2125 		{ PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER,                "Presentation allowed, Network provided" },
2126 
2127 		{ PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED,     "Presentation restricted, User-provided, not screened" },
2128 		{ PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN,  "Presentation restricted, User-provided, verified and passed" },
2129 		{ PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN,  "Presentation restricted, User-provided, verified and failed" },
2130 		{ PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER,             "Presentation restricted, Network provided" },
2131 
2132 		{ PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_UNSCREENED,    "Number not available, User-provided, not screened" },
2133 		{ PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_PASSED_SCREEN, "Number not available, User-provided, verified and passed" },
2134 		{ PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_FAILED_SCREEN, "Number not available, User-provided, verified and failed" },
2135 		{ PRI_PRES_UNAVAILABLE | PRI_PRES_NETWORK_NUMBER,            "Number not available, Network provided" },
2136 
2137 		{ PRI_PRES_RESERVED | PRI_PRES_USER_NUMBER_UNSCREENED,       "Reserved, User-provided, not screened" },
2138 		{ PRI_PRES_RESERVED | PRI_PRES_USER_NUMBER_PASSED_SCREEN,    "Reserved, User-provided, verified and passed" },
2139 		{ PRI_PRES_RESERVED | PRI_PRES_USER_NUMBER_FAILED_SCREEN,    "Reserved, User-provided, verified and failed" },
2140 		{ PRI_PRES_RESERVED | PRI_PRES_NETWORK_NUMBER,               "Reserved, Network provided" },
2141 	};
2142 
2143 	pres &= (PRI_PRES_RESTRICTION | PRI_PRES_NUMBER_TYPE);
2144 	return code2str(pres, press, sizeof(press) / sizeof(press[0]));
2145 }
2146 
q931_get_subaddr_specific(unsigned char * num,int maxlen,unsigned char * src,int len,char oddflag)2147 static void q931_get_subaddr_specific(unsigned char *num, int maxlen, unsigned char *src, int len, char oddflag)
2148 {
2149 	/* User Specified */
2150 	int x;
2151 	char *ptr = (char *) num;
2152 
2153 	if (len <= 0) {
2154 		num[0] = '\0';
2155 		return;
2156 	}
2157 
2158 	if (((len * 2) + 1) > maxlen) {
2159 		len = (maxlen / 2) - 1;
2160 	}
2161 
2162 	for (x = 0; x < (len - 1); ++x) {
2163 		ptr += sprintf(ptr, "%02x", src[x]);
2164 	}
2165 
2166 	if (oddflag) {
2167 		/* ODD */
2168 		sprintf(ptr, "%01x", (src[len - 1]) >> 4);
2169 	} else {
2170 		/* EVEN */
2171 		sprintf(ptr, "%02x", src[len - 1]);
2172 	}
2173 }
2174 
transmit_subaddr_helper(int full_ie,struct pri * ctrl,struct q931_party_subaddress * q931_subaddress,int msgtype,q931_ie * ie,int offset,int len,int order)2175 static int transmit_subaddr_helper(int full_ie, struct pri *ctrl, struct q931_party_subaddress *q931_subaddress, int msgtype, q931_ie *ie, int offset, int len, int order)
2176 {
2177 	size_t datalen;
2178 
2179 	if (!q931_subaddress->valid) {
2180 		return 0;
2181 	}
2182 
2183 	datalen = q931_subaddress->length;
2184 	if (!q931_subaddress->type) {
2185 		/* 0 = NSAP */
2186 		/* 0 = Odd/Even indicator */
2187 		ie->data[0] = 0x80;
2188 	} else {
2189 		/* 2 = User Specified */
2190 		ie->data[0] = q931_subaddress->odd_even_indicator ? 0xA8 : 0xA0;
2191 	}
2192 	memcpy(ie->data + offset, q931_subaddress->data, datalen);
2193 
2194 	return datalen + (offset + 2);
2195 }
2196 
receive_subaddr_helper(int full_ie,struct pri * ctrl,struct q931_party_subaddress * q931_subaddress,int msgtype,q931_ie * ie,int offset,int len)2197 static int receive_subaddr_helper(int full_ie, struct pri *ctrl, struct q931_party_subaddress *q931_subaddress, int msgtype, q931_ie *ie, int offset, int len)
2198 {
2199 	if (len <= 0) {
2200 		return -1;
2201 	}
2202 
2203 	q931_subaddress->valid = 1;
2204 	q931_subaddress->length = len;
2205 	/* type: 0 = NSAP, 2 = User Specified */
2206 	q931_subaddress->type = ((ie->data[0] & 0x70) >> 4);
2207 	q931_subaddress->odd_even_indicator = (ie->data[0] & 0x08) ? 1 : 0;
2208 	q931_memget(q931_subaddress->data, sizeof(q931_subaddress->data),
2209 		ie->data + offset, len);
2210 
2211 	return 0;
2212 }
2213 
dump_subaddr_helper(int full_ie,struct pri * ctrl,q931_ie * ie,int offset,int len,int datalen,char prefix)2214 static void dump_subaddr_helper(int full_ie, struct pri *ctrl, q931_ie *ie, int offset, int len, int datalen, char prefix)
2215 {
2216 	unsigned char cnum[256];
2217 
2218 	if (!(ie->data[0] & 0x70)) {
2219 		/* NSAP  Get it as a string for dump display purposes only. */
2220 		q931_strget(cnum, sizeof(cnum), ie->data + offset, datalen);
2221 	} else {
2222 		/* User Specified */
2223 		q931_get_subaddr_specific(cnum, sizeof(cnum), ie->data + offset, datalen,
2224 			ie->data[0] & 0x08);
2225 	}
2226 
2227 	pri_message(ctrl,
2228 		"%c %s (len=%2d) [ Ext: %d  Type: %s (%d)  O: %d  '%s' ]\n",
2229 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2230 		subaddrtype2str((ie->data[0] & 0x70) >> 4), (ie->data[0] & 0x70) >> 4,
2231 		(ie->data[0] & 0x08) >> 3, cnum);
2232 }
2233 
dump_called_party_number(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2234 static void dump_called_party_number(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2235 {
2236 	unsigned char cnum[256];
2237 
2238 	q931_strget(cnum, sizeof(cnum), ie->data + 1, len - 3);
2239 	pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  TON: %s (%d)  NPI: %s (%d)  '%s' ]\n",
2240 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2241 		ton2str((ie->data[0] >> 4) & 0x07), (ie->data[0] >> 4) & 0x07,
2242 		npi2str(ie->data[0] & 0x0f), ie->data[0] & 0x0f, cnum);
2243 }
2244 
dump_called_party_subaddr(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2245 static void dump_called_party_subaddr(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2246 {
2247 	dump_subaddr_helper(full_ie, ctrl, ie, 1, len, len - 3, prefix);
2248 }
2249 
dump_calling_party_number(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2250 static void dump_calling_party_number(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2251 {
2252 	unsigned char cnum[256];
2253 
2254 	if (ie->data[0] & 0x80) {
2255 		q931_strget(cnum, sizeof(cnum), ie->data + 1, len - 3);
2256 	} else {
2257 		q931_strget(cnum, sizeof(cnum), ie->data + 2, len - 4);
2258 	}
2259 	pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  TON: %s (%d)  NPI: %s (%d)\n",
2260 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2261 		ton2str((ie->data[0] >> 4) & 0x07), (ie->data[0] >> 4) & 0x07,
2262 		npi2str(ie->data[0] & 0x0f), ie->data[0] & 0x0f);
2263 	if (ie->data[0] & 0x80) {
2264 		pri_message(ctrl, "%c                                 Presentation: %s (%d)  '%s' ]\n",
2265 			prefix, pri_pres2str(0), 0, cnum);
2266 	} else {
2267 		pri_message(ctrl, "%c                                 Presentation: %s (%d)  '%s' ]\n",
2268 			prefix, pri_pres2str(ie->data[1] & 0x7f), ie->data[1] & 0x7f, cnum);
2269 	}
2270 }
2271 
dump_calling_party_subaddr(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2272 static void dump_calling_party_subaddr(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2273 {
2274 	dump_subaddr_helper(full_ie, ctrl, ie, 1, len, len - 3, prefix);
2275 }
2276 
dump_calling_party_category(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2277 static void dump_calling_party_category(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2278 {
2279 	pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  Cat: %s (%d) ]\n",
2280 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2281 		cpc2str(ie->data[0] & 0x0F), ie->data[0] & 0x0F);
2282 }
2283 
dump_redirecting_number(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2284 static void dump_redirecting_number(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2285 {
2286 	unsigned char cnum[256];
2287 	int i = 0;
2288 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2289 	   walking through all bytes until one with ext bit (8) set to 1 */
2290 	do {
2291 		switch(i) {
2292 		case 0:	/* Octet 3 */
2293 			pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  TON: %s (%d)  NPI: %s (%d)",
2294 				prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2295 				ton2str((ie->data[0] >> 4) & 0x07), (ie->data[0] >> 4) & 0x07,
2296 				npi2str(ie->data[0] & 0x0f), ie->data[0] & 0x0f);
2297 			break;
2298 		case 1: /* Octet 3a */
2299 			pri_message(ctrl, "\n");
2300 			pri_message(ctrl, "%c                               Ext: %d  Presentation: %s (%d)",
2301 				prefix, ie->data[1] >> 7, pri_pres2str(ie->data[1] & 0x7f), ie->data[1] & 0x7f);
2302 			break;
2303 		case 2: /* Octet 3b */
2304 			pri_message(ctrl, "\n");
2305 			pri_message(ctrl, "%c                               Ext: %d  Reason: %s (%d)",
2306 				prefix, ie->data[2] >> 7, redirection_reason2str(ie->data[2] & 0x7f), ie->data[2] & 0x7f);
2307 			break;
2308 		}
2309 	} while (!(ie->data[i++] & 0x80));
2310 	q931_strget(cnum, sizeof(cnum), ie->data + i, ie->len - i);
2311 	pri_message(ctrl, "  '%s' ]\n", cnum);
2312 }
2313 
dump_redirection_number(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2314 static void dump_redirection_number(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2315 {
2316 	unsigned char cnum[256];
2317 	int i = 0;
2318 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2319 	   walking through all bytes until one with ext bit (8) set to 1 */
2320 	do {
2321 		switch (i) {
2322 		case 0:	/* Octet 3 */
2323 			pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  TON: %s (%d)  NPI: %s (%d)",
2324 				prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2325 				ton2str((ie->data[0] >> 4) & 0x07), (ie->data[0] >> 4) & 0x07,
2326 				npi2str(ie->data[0] & 0x0f), ie->data[0] & 0x0f);
2327 			break;
2328 		case 1: /* Octet 3a */
2329 			pri_message(ctrl, "\n");
2330 			pri_message(ctrl, "%c                               Ext: %d  Presentation: %s (%d)",
2331 				prefix, ie->data[1] >> 7, pri_pres2str(ie->data[1] & 0x7f), ie->data[1] & 0x7f);
2332 			break;
2333 		}
2334 	} while (!(ie->data[i++] & 0x80));
2335 	q931_strget(cnum, sizeof(cnum), ie->data + i, ie->len - i);
2336 	pri_message(ctrl, "  '%s' ]\n", cnum);
2337 }
2338 
receive_connected_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2339 static int receive_connected_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2340 {
2341 	int i = 0;
2342 
2343 	/* Reference Q.951 Section 5.4.1 for ie */
2344 	call->connected_number_in_message = 1;
2345 	call->remote_id.number.valid = 1;
2346 	call->remote_id.number.presentation =
2347 		PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
2348 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2349 	   walking through all bytes until one with ext bit (8) set to 1 */
2350 	do {
2351 		switch (i) {
2352 		case 0:
2353 			call->remote_id.number.plan = ie->data[i] & 0x7f;
2354 
2355 			/*
2356 			 * Work around a bug in a Lucent switch implementation that
2357 			 * sets the extension bit in octet 3 even though octet 3a
2358 			 * is present.
2359 			 *
2360 			 * The same issue was seen in a NI2 switch implementation.
2361 			 * It was probably a Lucent switch configured for NI2
2362 			 * operation.  To avoid further surprises, I'm going to
2363 			 * enable the work around for all North American switch
2364 			 * types.
2365 			 */
2366 			if (ie->data[i] & 0x80) {
2367 				/* Octet 3 extension bit is set */
2368 				if (ctrl->switchtype != PRI_SWITCH_LUCENT5E
2369 					&& ctrl->switchtype != PRI_SWITCH_ATT4ESS
2370 					&& ctrl->switchtype != PRI_SWITCH_NI1
2371 					&& ctrl->switchtype != PRI_SWITCH_NI2
2372 					&& ctrl->switchtype != PRI_SWITCH_DMS100) {
2373 					/* Not a potentially buggy switch type. */
2374 					break;
2375 				}
2376 				if (!(ie->data[i + 1] & 0x80)) {
2377 					/*
2378 					 * The possible octet 3a doesn't have the extension
2379 					 * bit set.  It is likely not the erroneous octet 3a.
2380 					 */
2381 					break;
2382 				}
2383 			}
2384 			/* Octet 3a is present */
2385 			++i;
2386 			/* Fall through */
2387 		case 1:
2388 			/* Keep only the presentation and screening fields */
2389 			call->remote_id.number.presentation =
2390 				ie->data[i] & (PRI_PRES_RESTRICTION | PRI_PRES_NUMBER_TYPE);
2391 			break;
2392 		}
2393 	} while (!(ie->data[i++] & 0x80));
2394 	q931_strget_gripe(ctrl, ie2str(full_ie), (unsigned char *) call->remote_id.number.str,
2395 		sizeof(call->remote_id.number.str), ie->data + i, ie->len - i);
2396 
2397 	return 0;
2398 }
2399 
transmit_connected_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2400 static int transmit_connected_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2401 {
2402 	size_t datalen;
2403 
2404 	if (!call->local_id.number.valid) {
2405 		return 0;
2406 	}
2407 
2408 	datalen = strlen(call->local_id.number.str);
2409 	ie->data[0] = call->local_id.number.plan;
2410 	ie->data[1] = 0x80 | call->local_id.number.presentation;
2411 	memcpy(ie->data + 2, call->local_id.number.str, datalen);
2412 	return datalen + (2 + 2);
2413 }
2414 
dump_connected_number(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2415 static void dump_connected_number(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2416 {
2417 	unsigned char cnum[256];
2418 	int i = 0;
2419 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2420 	   walking through all bytes until one with ext bit (8) set to 1 */
2421 	do {
2422 		switch(i) {
2423 		case 0:	/* Octet 3 */
2424 			pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  TON: %s (%d)  NPI: %s (%d)",
2425 				prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2426 				ton2str((ie->data[0] >> 4) & 0x07), (ie->data[0] >> 4) & 0x07,
2427 				npi2str(ie->data[0] & 0x0f), ie->data[0] & 0x0f);
2428 
2429 			/*
2430 			 * Work around a bug in a Lucent switch implementation that
2431 			 * sets the extension bit in octet 3 even though octet 3a
2432 			 * is present.
2433 			 *
2434 			 * The same issue was seen in a NI2 switch implementation.
2435 			 * It was probably a Lucent switch configured for NI2
2436 			 * operation.  To avoid further surprises, I'm going to
2437 			 * enable the work around for all North American switch
2438 			 * types.
2439 			 */
2440 			if (ie->data[i] & 0x80) {
2441 				/* Octet 3 extension bit is set */
2442 				if (ctrl->switchtype != PRI_SWITCH_LUCENT5E
2443 					&& ctrl->switchtype != PRI_SWITCH_ATT4ESS
2444 					&& ctrl->switchtype != PRI_SWITCH_NI1
2445 					&& ctrl->switchtype != PRI_SWITCH_NI2
2446 					&& ctrl->switchtype != PRI_SWITCH_DMS100) {
2447 					/* Not a potentially buggy switch type. */
2448 					break;
2449 				}
2450 				if (!(ie->data[i + 1] & 0x80)) {
2451 					/*
2452 					 * The possible octet 3a doesn't have the extension
2453 					 * bit set.  It is likely not the erroneous octet 3a.
2454 					 */
2455 					break;
2456 				}
2457 				pri_message(ctrl, "\n");
2458 				pri_message(ctrl, "%c                             Switch bug workaround.\n",
2459 					prefix);
2460 				pri_message(ctrl, "%c                             Assuming octet 3a is present.",
2461 					prefix);
2462 			}
2463 			/* Octet 3a is present */
2464 			++i;
2465 			/* Fall through */
2466 		case 1: /* Octet 3a */
2467 			pri_message(ctrl, "\n");
2468 			pri_message(ctrl, "%c                             Ext: %d  Presentation: %s (%d)",
2469 				prefix, ie->data[1] >> 7, pri_pres2str(ie->data[1] & 0x7f), ie->data[1] & 0x7f);
2470 			break;
2471 		}
2472 	} while(!(ie->data[i++]& 0x80));
2473 	q931_strget(cnum, sizeof(cnum), ie->data + i, ie->len - i);
2474 	pri_message(ctrl, "  '%s' ]\n", cnum);
2475 }
2476 
receive_connected_subaddr(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2477 static int receive_connected_subaddr(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2478 {
2479 	if (len < 3) {
2480 		return -1;
2481 	}
2482 
2483 	return receive_subaddr_helper(full_ie, ctrl, &call->remote_id.subaddress, msgtype, ie,
2484 		1, len - 3);
2485 }
2486 
transmit_connected_subaddr(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2487 static int transmit_connected_subaddr(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2488 {
2489 	return transmit_subaddr_helper(full_ie, ctrl, &call->local_id.subaddress, msgtype, ie,
2490 		1, len, order);
2491 }
2492 
dump_connected_subaddr(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2493 static void dump_connected_subaddr(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2494 {
2495 	dump_subaddr_helper(full_ie, ctrl, ie, 1, len, len - 3, prefix);
2496 }
2497 
receive_redirecting_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2498 static int receive_redirecting_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2499 {
2500 	int i = 0;
2501 
2502 	/* Reference Q.952 Section 4.1.2 for ie */
2503 	call->redirecting_number_in_message = 1;
2504 	call->redirecting.from.number.valid = 1;
2505 	call->redirecting.from.number.presentation =
2506 		PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
2507 	call->redirecting.reason = PRI_REDIR_UNKNOWN;
2508 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2509 	   walking through all bytes until one with ext bit (8) set to 1 */
2510 	do {
2511 		switch (i) {
2512 		case 0:
2513 			call->redirecting.from.number.plan = ie->data[i] & 0x7f;
2514 			break;
2515 		case 1:
2516 			/* Keep only the presentation and screening fields */
2517 			call->redirecting.from.number.presentation =
2518 				ie->data[i] & (PRI_PRES_RESTRICTION | PRI_PRES_NUMBER_TYPE);
2519 			break;
2520 		case 2:
2521 			call->redirecting.reason = ie->data[i] & 0x0f;
2522 			break;
2523 		}
2524 	} while (!(ie->data[i++] & 0x80));
2525 	q931_strget_gripe(ctrl, ie2str(full_ie),
2526 		(unsigned char *) call->redirecting.from.number.str,
2527 		sizeof(call->redirecting.from.number.str), ie->data + i, ie->len - i);
2528 	return 0;
2529 }
2530 
transmit_redirecting_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2531 static int transmit_redirecting_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2532 {
2533 	size_t datalen;
2534 
2535 	if (order > 1)
2536 		return 0;
2537 	if (!call->redirecting.from.number.valid) {
2538 		return 0;
2539 	}
2540 	if (BRI_TE_PTMP(ctrl)) {
2541 		/*
2542 		 * We should not send this ie to the network if we are the TE
2543 		 * PTMP side since phones do not redirect calls within
2544 		 * themselves.  Well... If you consider someone else dialing the
2545 		 * handset a redirection then how is the network to know?
2546 		 */
2547 		return 0;
2548 	}
2549 	if (call->redirecting.state != Q931_REDIRECTING_STATE_IDLE) {
2550 		/*
2551 		 * There was a DivertingLegInformation2 in the message so the
2552 		 * Q931_REDIRECTING_NUMBER ie is redundant.  Some networks
2553 		 * (Deutsche Telekom) complain about it.
2554 		 */
2555 		return 0;
2556 	}
2557 
2558 	datalen = strlen(call->redirecting.from.number.str);
2559 	ie->data[0] = call->redirecting.from.number.plan;
2560 #if 1
2561 	/* ETSI and Q.952 do not define the screening field */
2562 	ie->data[1] = call->redirecting.from.number.presentation & PRI_PRES_RESTRICTION;
2563 #else
2564 	/* Q.931 defines the screening field */
2565 	ie->data[1] = call->redirecting.from.number.presentation;
2566 #endif
2567 	ie->data[2] = (call->redirecting.reason & 0x0f) | 0x80;
2568 	memcpy(ie->data + 3, call->redirecting.from.number.str, datalen);
2569 	return datalen + (3 + 2);
2570 }
2571 
dump_redirecting_subaddr(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2572 static void dump_redirecting_subaddr(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2573 {
2574 	dump_subaddr_helper(full_ie, ctrl, ie, 2, len, len - 4, prefix);
2575 }
2576 
receive_redirection_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2577 static int receive_redirection_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2578 {
2579 	int i = 0;
2580 
2581 	/* Reference Q.952 Section 4.1.3 for ie */
2582 	call->redirection_number.valid = 1;
2583 	call->redirection_number.presentation =
2584 		PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
2585 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2586 	   walking through all bytes until one with ext bit (8) set to 1 */
2587 	do {
2588 		switch (i) {
2589 		case 0:
2590 			call->redirection_number.plan = ie->data[i] & 0x7f;
2591 			break;
2592 		case 1:
2593 			/* Keep only the presentation and screening fields */
2594 			call->redirection_number.presentation =
2595 				ie->data[i] & (PRI_PRES_RESTRICTION | PRI_PRES_NUMBER_TYPE);
2596 			break;
2597 		}
2598 	} while (!(ie->data[i++] & 0x80));
2599 	q931_strget_gripe(ctrl, ie2str(full_ie),
2600 		(unsigned char *) call->redirection_number.str,
2601 		sizeof(call->redirection_number.str), ie->data + i, ie->len - i);
2602 	return 0;
2603 }
2604 
transmit_redirection_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2605 static int transmit_redirection_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2606 {
2607 	size_t datalen;
2608 
2609 	if (order > 1) {
2610 		return 0;
2611 	}
2612 	if (!call->redirection_number.valid) {
2613 		return 0;
2614 	}
2615 
2616 	datalen = strlen(call->redirection_number.str);
2617 	ie->data[0] = call->redirection_number.plan;
2618 	ie->data[1] = (call->redirection_number.presentation & PRI_PRES_RESTRICTION) | 0x80;
2619 	memcpy(ie->data + 2, call->redirection_number.str, datalen);
2620 	return datalen + (2 + 2);
2621 }
2622 
receive_calling_party_subaddr(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2623 static int receive_calling_party_subaddr(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2624 {
2625 	if (len < 3) {
2626 		return -1;
2627 	}
2628 
2629 	return receive_subaddr_helper(full_ie, ctrl, &call->remote_id.subaddress, msgtype, ie,
2630 		1, len - 3);
2631 }
2632 
transmit_calling_party_subaddr(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2633 static int transmit_calling_party_subaddr(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2634 {
2635 	return transmit_subaddr_helper(full_ie, ctrl, &call->local_id.subaddress, msgtype, ie,
2636 		1, len, order);
2637 }
2638 
receive_called_party_subaddr(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2639 static int receive_called_party_subaddr(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2640 {
2641 	if (len < 3) {
2642 		return -1;
2643 	}
2644 	return receive_subaddr_helper(full_ie, ctrl, &call->called.subaddress, msgtype, ie, 1,
2645 		len - 3);
2646 }
2647 
transmit_called_party_subaddr(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2648 static int transmit_called_party_subaddr(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2649 {
2650 	return transmit_subaddr_helper(full_ie, ctrl, &call->called.subaddress, msgtype, ie,
2651 		1, len, order);
2652 }
2653 
receive_called_party_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2654 static int receive_called_party_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2655 {
2656 	size_t called_len;
2657 	size_t max_len;
2658 	char *called_end;
2659 
2660 	if (len < 3) {
2661 		return -1;
2662 	}
2663 
2664 	switch (msgtype) {
2665 	case Q931_FACILITY:
2666 		if (!q931_is_dummy_call(call)) {
2667 			/* Discard the number. */
2668 			return 0;
2669 		}
2670 		/* Fall through */
2671 	case Q931_REGISTER:
2672 		/* Accept the number for REGISTER only because it is so similar to SETUP. */
2673 	case Q931_SETUP:
2674 		q931_strget((unsigned char *) call->called.number.str,
2675 			sizeof(call->called.number.str), ie->data + 1, len - 3);
2676 		break;
2677 	case Q931_INFORMATION:
2678 		if (call->ourcallstate == Q931_CALL_STATE_OVERLAP_RECEIVING) {
2679 			/*
2680 			 * Since we are receiving overlap digits now, we need to append
2681 			 * them to any previously received digits in call->called.number.str.
2682 			 */
2683 			called_len = strlen(call->called.number.str);
2684 			called_end = call->called.number.str + called_len;
2685 			max_len = (sizeof(call->called.number.str) - 1) - called_len;
2686 			if (max_len < len - 3) {
2687 				called_len = max_len;
2688 			} else {
2689 				called_len = len - 3;
2690 			}
2691 			strncat(called_end, (char *) ie->data + 1, called_len);
2692 		}
2693 		break;
2694 	default:
2695 		/* Discard the number. */
2696 		return 0;
2697 	}
2698 	call->called.number.valid = 1;
2699 	call->called.number.plan = ie->data[0] & 0x7f;
2700 
2701 	q931_strget_gripe(ctrl, ie2str(full_ie), (unsigned char *) call->overlap_digits,
2702 		sizeof(call->overlap_digits), ie->data + 1, len - 3);
2703 	return 0;
2704 }
2705 
transmit_called_party_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2706 static int transmit_called_party_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2707 {
2708 	size_t datalen;
2709 
2710 	if (!call->called.number.valid) {
2711 		return 0;
2712 	}
2713 
2714 	datalen = strlen(call->overlap_digits);
2715 	ie->data[0] = 0x80 | call->called.number.plan;
2716 	memcpy(ie->data + 1, call->overlap_digits, datalen);
2717 	return datalen + (1 + 2);
2718 }
2719 
receive_calling_party_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2720 static int receive_calling_party_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2721 {
2722 	int i = 0;
2723 	struct q931_party_number number;
2724 
2725 	/* Reference Q.931 Section 4.5.10 for ie */
2726 	q931_party_number_init(&number);
2727 	number.valid = 1;
2728 	number.presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
2729 
2730 	/* To follow Q.931 (4.5.1), we must search for start of octet 4 by
2731 	   walking through all bytes until one with ext bit (8) set to 1 */
2732 	do {
2733 		switch (i) {
2734 		case 0:
2735 			number.plan = ie->data[i] & 0x7f;
2736 			break;
2737 		case 1:
2738 			/* Keep only the presentation and screening fields */
2739 			number.presentation =
2740 				ie->data[i] & (PRI_PRES_RESTRICTION | PRI_PRES_NUMBER_TYPE);
2741 			break;
2742 		}
2743 	} while (!(ie->data[i++] & 0x80));
2744 	q931_strget_gripe(ctrl, ie2str(full_ie), (unsigned char *) number.str,
2745 		sizeof(number.str), ie->data + i, ie->len - i);
2746 
2747 	/* There can be more than one calling party number ie in the SETUP message. */
2748 	if (number.presentation == (PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER)
2749 		|| number.presentation == (PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER)) {
2750 		/* The number is network provided so it is an ANI number. */
2751 		call->ani = number;
2752 		if (!call->remote_id.number.valid) {
2753 			/* Copy ANI to CallerID if CallerID is not already set. */
2754 			call->remote_id.number = number;
2755 		}
2756 	} else {
2757 		call->remote_id.number = number;
2758 	}
2759 
2760 	return 0;
2761 }
2762 
transmit_calling_party_number(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2763 static int transmit_calling_party_number(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2764 {
2765 	size_t datalen;
2766 
2767 	if (!call->local_id.number.valid) {
2768 		return 0;
2769 	}
2770 
2771 	datalen = strlen(call->local_id.number.str);
2772 	ie->data[0] = call->local_id.number.plan;
2773 	ie->data[1] = 0x80 | call->local_id.number.presentation;
2774 	memcpy(ie->data + 2, call->local_id.number.str, datalen);
2775 	return datalen + (2 + 2);
2776 }
2777 
dump_user_user(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2778 static void dump_user_user(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2779 {
2780 	int x;
2781 
2782 	pri_message(ctrl, "%c %s (len=%2d) [", prefix, ie2str(full_ie), len);
2783 	for (x = 0; x < ie->len; ++x) {
2784 		pri_message(ctrl, " %02x", ie->data[x] & 0x7f);
2785 	}
2786 	pri_message(ctrl, " ]\n");
2787 }
2788 
2789 
receive_user_user(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2790 static int receive_user_user(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2791 {
2792 	call->useruserprotocoldisc = ie->data[0] & 0xff;
2793 	if (call->useruserprotocoldisc == 4) { /* IA5 */
2794 		q931_memget((unsigned char *) call->useruserinfo, sizeof(call->useruserinfo), ie->data + 1, len - 3);
2795 	}
2796 	return 0;
2797 }
2798 
transmit_user_user(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2799 static int transmit_user_user(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2800 {
2801 	int datalen = strlen(call->useruserinfo);
2802 	if (datalen > 0) {
2803 		/* Restricted to 35 characters */
2804 		if (msgtype == Q931_USER_INFORMATION) {
2805 			if (datalen > 260)
2806 				datalen = 260;
2807 		} else {
2808 			if (datalen > 35)
2809 				datalen = 35;
2810 		}
2811 		ie->data[0] = 4; /* IA5 characters */
2812 		memcpy(&ie->data[1], call->useruserinfo, datalen);
2813 		call->useruserinfo[0] = '\0';
2814 		return datalen + 3;
2815 	}
2816 
2817 	return 0;
2818 }
2819 
dump_change_status(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2820 static void dump_change_status(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2821 {
2822 	int x;
2823 
2824 	pri_message(ctrl, "%c %s (len=%2d) [", prefix, ie2str(full_ie), len);
2825 	for (x = 0; x < ie->len; ++x) {
2826 		pri_message(ctrl, " %02x", ie->data[x] & 0x7f);
2827 	}
2828 	pri_message(ctrl, " ]\n");
2829 
2830 	switch (ctrl->switchtype) {
2831 	case PRI_SWITCH_NI2:
2832 	case PRI_SWITCH_DMS100:
2833 	case PRI_SWITCH_LUCENT5E:
2834 	case PRI_SWITCH_ATT4ESS:
2835 		break;
2836 	default:
2837 		/* ie not supported by this switch type */
2838 		pri_message(ctrl, "%c   %s is treated as unknown by current switch type.\n",
2839 			prefix, ie2str(full_ie));
2840 		break;
2841 	}
2842 }
2843 
receive_change_status(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2844 static int receive_change_status(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2845 {
2846 	switch (ctrl->switchtype) {
2847 	case PRI_SWITCH_NI2:
2848 	case PRI_SWITCH_DMS100:
2849 	case PRI_SWITCH_LUCENT5E:
2850 	case PRI_SWITCH_ATT4ESS:
2851 		break;
2852 	default:
2853 		/* ie not supported by this switch type */
2854 		return -1;
2855 	}
2856 	call->changestatus = ie->data[0] & 0x0f;
2857 	return 0;
2858 }
2859 
transmit_change_status(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2860 static int transmit_change_status(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2861 {
2862 	ie->data[0] = 0xc0 | call->changestatus;
2863 	return 3;
2864 }
2865 
prog2str(int prog)2866 static char *prog2str(int prog)
2867 {
2868 	static struct msgtype progs[] = {
2869 		{ Q931_PROG_CALL_NOT_E2E_ISDN, "Call is not end-to-end ISDN; further call progress information may be available inband." },
2870 		{ Q931_PROG_CALLED_NOT_ISDN, "Called equipment is non-ISDN." },
2871 		{ Q931_PROG_CALLER_NOT_ISDN, "Calling equipment is non-ISDN." },
2872 		{ Q931_PROG_INBAND_AVAILABLE, "Inband information or appropriate pattern now available." },
2873 		{ Q931_PROG_DELAY_AT_INTERF, "Delay in response at called Interface." },
2874 		{ Q931_PROG_INTERWORKING_WITH_PUBLIC, "Interworking with a public network." },
2875 		{ Q931_PROG_INTERWORKING_NO_RELEASE, "Interworking with a network unable to supply a release signal." },
2876 		{ Q931_PROG_INTERWORKING_NO_RELEASE_PRE_ANSWER, "Interworking with a network unable to supply a release signal before answer." },
2877 		{ Q931_PROG_INTERWORKING_NO_RELEASE_POST_ANSWER, "Interworking with a network unable to supply a release signal after answer." },
2878 	};
2879 	return code2str(prog, progs, sizeof(progs) / sizeof(progs[0]));
2880 }
2881 
coding2str(int cod)2882 static char *coding2str(int cod)
2883 {
2884 	static struct msgtype cods[] = {
2885 		{ CODE_CCITT, "CCITT (ITU) standard" },
2886 		{ CODE_INTERNATIONAL, "Non-ITU international standard" },
2887 		{ CODE_NATIONAL, "National standard" },
2888 		{ CODE_NETWORK_SPECIFIC, "Network specific standard" },
2889 	};
2890 	return code2str(cod, cods, sizeof(cods) / sizeof(cods[0]));
2891 }
2892 
loc2str(int loc)2893 static char *loc2str(int loc)
2894 {
2895 	static struct msgtype locs[] = {
2896 		{ LOC_USER, "User" },
2897 		{ LOC_PRIV_NET_LOCAL_USER, "Private network serving the local user" },
2898 		{ LOC_PUB_NET_LOCAL_USER, "Public network serving the local user" },
2899 		{ LOC_TRANSIT_NET, "Transit network" },
2900 		{ LOC_PUB_NET_REMOTE_USER, "Public network serving the remote user" },
2901 		{ LOC_PRIV_NET_REMOTE_USER, "Private network serving the remote user" },
2902 		{ LOC_INTERNATIONAL_NETWORK, "International network" },
2903 		{ LOC_NETWORK_BEYOND_INTERWORKING, "Network beyond the interworking point" },
2904 	};
2905 	return code2str(loc, locs, sizeof(locs) / sizeof(locs[0]));
2906 }
2907 
dump_progress_indicator(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)2908 static void dump_progress_indicator(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
2909 {
2910 	pri_message(ctrl,
2911 		"%c %s (len=%2d) [ Ext: %d  Coding: %s (%d)  0: %d  Location: %s (%d)\n",
2912 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
2913 		coding2str((ie->data[0] & 0x60) >> 5), (ie->data[0] & 0x60) >> 5,
2914 		(ie->data[0] & 0x10) >> 4, loc2str(ie->data[0] & 0xf), ie->data[0] & 0xf);
2915 	pri_message(ctrl, "%c                               Ext: %d  Progress Description: %s (%d) ]\n",
2916 		prefix, ie->data[1] >> 7, prog2str(ie->data[1] & 0x7f), ie->data[1] & 0x7f);
2917 }
2918 
receive_display(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2919 static int receive_display(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2920 {
2921 	u_int8_t *data;
2922 
2923 	if (ctrl->display_flags.receive & PRI_DISPLAY_OPTION_BLOCK) {
2924 		return 0;
2925 	}
2926 
2927 	data = ie->data;
2928 	if (data[0] & 0x80) {
2929 		/* Skip over character set */
2930 		data++;
2931 		len--;
2932 	}
2933 
2934 	call->display.text = data;
2935 	call->display.full_ie = full_ie;
2936 	call->display.length = len - 2;
2937 	call->display.char_set = PRI_CHAR_SET_ISO8859_1;
2938 	return 0;
2939 }
2940 
transmit_display(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)2941 static int transmit_display(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
2942 {
2943 	size_t datalen;
2944 	int i;
2945 
2946 	if (!call->display.text || !call->display.length) {
2947 		return 0;
2948 	}
2949 	if (ctrl->display_flags.send & PRI_DISPLAY_OPTION_BLOCK) {
2950 		return 0;
2951 	}
2952 
2953 	i = 0;
2954 	switch (ctrl->switchtype) {
2955 	case PRI_SWITCH_QSIG:
2956 	case PRI_SWITCH_EUROISDN_E1:
2957 	case PRI_SWITCH_EUROISDN_T1:
2958 		break;
2959 	default:
2960 		/* Prefix text with character set indicator. */
2961 		ie->data[0] = 0xb1;
2962 		++i;
2963 		break;
2964 	}
2965 
2966 	datalen = call->display.length;
2967 	if (MAX_DISPLAY_TEXT < datalen + i) {
2968 		datalen = MAX_DISPLAY_TEXT - i;
2969 	}
2970 	memcpy(ie->data + i, call->display.text, datalen);
2971 	return 2 + i + datalen;
2972 }
2973 
receive_progress_indicator(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)2974 static int receive_progress_indicator(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
2975 {
2976 	call->progloc = ie->data[0] & 0xf;
2977 	call->progcode = (ie->data[0] & 0x60) >> 5;
2978 	call->progress = (ie->data[1] & 0x7f);
2979 	switch (call->progress) {
2980 	case Q931_PROG_CALL_NOT_E2E_ISDN:
2981 		call->progressmask |= PRI_PROG_CALL_NOT_E2E_ISDN;
2982 		break;
2983 	case Q931_PROG_CALLED_NOT_ISDN:
2984 		call->progressmask |= PRI_PROG_CALLED_NOT_ISDN;
2985 		break;
2986 	case Q931_PROG_CALLER_NOT_ISDN:
2987 		call->progressmask |= PRI_PROG_CALLER_NOT_ISDN;
2988 		break;
2989 	case Q931_PROG_CALLER_RETURNED_TO_ISDN:
2990 		call->progressmask |= PRI_PROG_CALLER_RETURNED_TO_ISDN;
2991 		break;
2992 	case Q931_PROG_INBAND_AVAILABLE:
2993 		call->progressmask |= PRI_PROG_INBAND_AVAILABLE;
2994 		break;
2995 	case Q931_PROG_DELAY_AT_INTERF:
2996 		call->progressmask |= PRI_PROG_DELAY_AT_INTERF;
2997 		break;
2998 	case Q931_PROG_INTERWORKING_WITH_PUBLIC:
2999 		call->progressmask |= PRI_PROG_INTERWORKING_WITH_PUBLIC;
3000 		break;
3001 	case Q931_PROG_INTERWORKING_NO_RELEASE:
3002 		call->progressmask |= PRI_PROG_INTERWORKING_NO_RELEASE;
3003 		break;
3004 	case Q931_PROG_INTERWORKING_NO_RELEASE_PRE_ANSWER:
3005 		call->progressmask |= PRI_PROG_INTERWORKING_NO_RELEASE_PRE_ANSWER;
3006 		break;
3007 	case Q931_PROG_INTERWORKING_NO_RELEASE_POST_ANSWER:
3008 		call->progressmask |= PRI_PROG_INTERWORKING_NO_RELEASE_POST_ANSWER;
3009 		break;
3010 	default:
3011 		pri_error(ctrl, "XXX Invalid Progress indicator value received: %02x\n",(ie->data[1] & 0x7f));
3012 		return -1;
3013 	}
3014 	return 0;
3015 }
3016 
3017 static void q931_apdu_timeout(void *data);
3018 
transmit_facility(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3019 static int transmit_facility(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3020 {
3021 	struct apdu_event **prev;
3022 	struct apdu_event *cur;
3023 	int apdu_len;
3024 
3025 	for (prev = &call->apdus, cur = call->apdus;
3026 		cur;
3027 		prev = &cur->next, cur = cur->next) {
3028 		if (!cur->sent && (cur->message == msgtype || cur->message == Q931_ANY_MESSAGE)) {
3029 			break;
3030 		}
3031 	}
3032 	if (!cur) {
3033 		/* No APDU found */
3034 		return 0;
3035 	}
3036 
3037 	if (ctrl->debug & PRI_DEBUG_APDU) {
3038 		pri_message(ctrl, "Adding facility ie contents to send in %s message:\n",
3039 			msg2str(msgtype));
3040 		facility_decode_dump(ctrl, cur->apdu, cur->apdu_len);
3041 	}
3042 
3043 	if (len < cur->apdu_len) {
3044 		pri_error(ctrl,
3045 			"Could not fit facility ie in message.  Size needed:%d  Available space:%d\n",
3046 			cur->apdu_len + 2, len);
3047 
3048 		/* Remove APDU from list. */
3049 		*prev = cur->next;
3050 
3051 		if (cur->response.callback) {
3052 			/* Indicate to callback that the APDU had a problem getting sent. */
3053 			cur->response.callback(APDU_CALLBACK_REASON_ERROR, ctrl, call, cur, NULL);
3054 		}
3055 
3056 		free(cur);
3057 		return 0;
3058 	}
3059 
3060 	memcpy(ie->data, cur->apdu, cur->apdu_len);
3061 	apdu_len = cur->apdu_len;
3062 	cur->sent = 1;
3063 
3064 	if (cur->response.callback && cur->response.timeout_time) {
3065 		int failed;
3066 
3067 		if (0 < cur->response.timeout_time) {
3068 			/* Sender specified a timeout duration. */
3069 			cur->timer = pri_schedule_event(ctrl, cur->response.timeout_time,
3070 				q931_apdu_timeout, cur);
3071 			failed = !cur->timer;
3072 		} else {
3073 			/* Sender wants to "timeout" only when specified messages are received. */
3074 			failed = !cur->response.num_messages;
3075 		}
3076 		if (failed) {
3077 			/* Remove APDU from list. */
3078 			*prev = cur->next;
3079 
3080 			/* Indicate to callback that the APDU had a problem getting sent. */
3081 			cur->response.callback(APDU_CALLBACK_REASON_ERROR, ctrl, call, cur, NULL);
3082 
3083 			free(cur);
3084 		}
3085 	} else {
3086 		/* Remove APDU from list. */
3087 		*prev = cur->next;
3088 		free(cur);
3089 	}
3090 
3091 	return apdu_len + 2;
3092 }
3093 
receive_facility(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3094 static int receive_facility(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3095 {
3096 	/* Delay processing facility ie's till after all other ie's are processed. */
3097 	if (MAX_FACILITY_IES <= ctrl->facility.count) {
3098 		pri_message(ctrl, "!! Too many facility ie's to delay.\n");
3099 		return -1;
3100 	}
3101 	/* Make sure we have enough room for the protocol profile ie octet(s) */
3102 	if (ie->data + ie->len < ie->data + 2) {
3103 		return -1;
3104 	}
3105 
3106 	/* Save the facility ie location for delayed decode. */
3107 	ctrl->facility.ie[ctrl->facility.count] = ie;
3108 	ctrl->facility.codeset[ctrl->facility.count] = Q931_IE_CODESET((unsigned) full_ie);
3109 	++ctrl->facility.count;
3110 	return 0;
3111 }
3112 
process_facility(struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie)3113 static int process_facility(struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie)
3114 {
3115 	struct fac_extension_header header;
3116 	struct rose_message rose;
3117 	const unsigned char *pos;
3118 	const unsigned char *end;
3119 
3120 	pos = ie->data;
3121 	end = ie->data + ie->len;
3122 
3123 	/* Make sure we have enough room for the protocol profile ie octet(s) */
3124 	if (end < pos + 2) {
3125 		return -1;
3126 	}
3127 	switch (*pos & Q932_PROTOCOL_MASK) {
3128 	case Q932_PROTOCOL_ROSE:
3129 	case Q932_PROTOCOL_EXTENSIONS:
3130 		break;
3131 	default:
3132 	case Q932_PROTOCOL_CMIP:
3133 	case Q932_PROTOCOL_ACSE:
3134 		if (ctrl->debug & PRI_DEBUG_APDU) {
3135 			pri_message(ctrl,
3136 				"!! Don't know how to handle Q.932 Protocol Profile type 0x%X\n",
3137 				*pos & Q932_PROTOCOL_MASK);
3138 		}
3139 		return -1;
3140 	}
3141 	if (!(*pos & 0x80)) {
3142 		/* DMS-100 Service indicator octet - Just ignore for now */
3143 		++pos;
3144 	}
3145 	++pos;
3146 
3147 	if (ctrl->debug & PRI_DEBUG_APDU) {
3148 		asn1_dump(ctrl, pos, end);
3149 	}
3150 
3151 	pos = fac_dec_extension_header(ctrl, pos, end, &header);
3152 	if (!pos) {
3153 		return -1;
3154 	}
3155 	if (header.npp_present) {
3156 		if (ctrl->debug & PRI_DEBUG_APDU) {
3157 			pri_message(ctrl,
3158 				"!! Don't know how to handle Network Protocol Profile type 0x%X\n",
3159 				header.npp);
3160 		}
3161 		return -1;
3162 	}
3163 
3164 	/* Process all components in the facility. */
3165 	while (pos < end) {
3166 		pos = rose_decode(ctrl, pos, end, &rose);
3167 		if (!pos) {
3168 			return -1;
3169 		}
3170 		switch (rose.type) {
3171 		case ROSE_COMP_TYPE_INVOKE:
3172 			rose_handle_invoke(ctrl, call, msgtype, ie, &header, &rose.component.invoke);
3173 			break;
3174 		case ROSE_COMP_TYPE_RESULT:
3175 			rose_handle_result(ctrl, call, msgtype, ie, &header, &rose.component.result);
3176 			break;
3177 		case ROSE_COMP_TYPE_ERROR:
3178 			rose_handle_error(ctrl, call, msgtype, ie, &header, &rose.component.error);
3179 			break;
3180 		case ROSE_COMP_TYPE_REJECT:
3181 			rose_handle_reject(ctrl, call, msgtype, ie, &header, &rose.component.reject);
3182 			break;
3183 		default:
3184 			return -1;
3185 		}
3186 	}
3187 	return 0;
3188 }
3189 
q931_handle_facilities(struct pri * ctrl,q931_call * call,int msgtype)3190 static void q931_handle_facilities(struct pri *ctrl, q931_call *call, int msgtype)
3191 {
3192 	unsigned idx;
3193 	unsigned codeset;
3194 	unsigned full_ie;
3195 	q931_ie *ie;
3196 
3197 	for (idx = 0; idx < ctrl->facility.count; ++idx) {
3198 		ie = ctrl->facility.ie[idx];
3199 		if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
3200 			codeset = ctrl->facility.codeset[idx];
3201 			full_ie = Q931_FULL_IE(codeset, ie->ie);
3202 			pri_message(ctrl, "-- Delayed processing IE %d (cs%d, %s)\n", ie->ie, codeset, ie2str(full_ie));
3203 		}
3204 		process_facility(ctrl, call, msgtype, ie);
3205 	}
3206 }
3207 
3208 /*!
3209  * \internal
3210  * \brief Check if any APDU responses "timeout" with the current Q.931 message.
3211  *
3212  * \param ctrl D channel controller.
3213  * \param call Q.931 call leg.
3214  * \param msgtype Q.931 message type received.
3215  *
3216  * \return Nothing
3217  */
q931_apdu_msg_expire(struct pri * ctrl,struct q931_call * call,int msgtype)3218 static void q931_apdu_msg_expire(struct pri *ctrl, struct q931_call *call, int msgtype)
3219 {
3220 	struct apdu_event **prev;
3221 	struct apdu_event **prev_next;
3222 	struct apdu_event *cur;
3223 	unsigned idx;
3224 
3225 	for (prev = &call->apdus; *prev; prev = prev_next) {
3226 		cur = *prev;
3227 		prev_next = &cur->next;
3228 		if (cur->sent) {
3229 			for (idx = 0; idx < cur->response.num_messages; ++idx) {
3230 				if (cur->response.message_type[idx] == msgtype) {
3231 					/*
3232 					 * APDU response message "timeout".
3233 					 *
3234 					 * Extract the APDU from the list so it cannot be
3235 					 * deleted from under us by the callback.
3236 					 */
3237 					prev_next = prev;
3238 					*prev = cur->next;
3239 
3240 					/* Stop any response timeout. */
3241 					pri_schedule_del(ctrl, cur->timer);
3242 					cur->timer = 0;
3243 
3244 					cur->response.callback(APDU_CALLBACK_REASON_TIMEOUT, ctrl, call, cur, NULL);
3245 
3246 					free(cur);
3247 					break;
3248 				}
3249 			}
3250 		}
3251 	}
3252 }
3253 
transmit_progress_indicator(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3254 static int transmit_progress_indicator(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3255 {
3256 	int code;
3257 	int mask;
3258 
3259 	/* Can't send progress indicator on GR-303 -- EVER! */
3260 	if (ctrl->link.next && !ctrl->bri)
3261 		return 0;
3262 	if (call->progressmask > 0) {
3263 		if (call->progressmask & (mask = PRI_PROG_CALL_NOT_E2E_ISDN))
3264 			code = Q931_PROG_CALL_NOT_E2E_ISDN;
3265 		else if (call->progressmask & (mask = PRI_PROG_CALLED_NOT_ISDN))
3266 			code = Q931_PROG_CALLED_NOT_ISDN;
3267 		else if (call->progressmask & (mask = PRI_PROG_CALLER_NOT_ISDN))
3268 			code = Q931_PROG_CALLER_NOT_ISDN;
3269 		else if (call->progressmask & (mask = PRI_PROG_INBAND_AVAILABLE))
3270 			code = Q931_PROG_INBAND_AVAILABLE;
3271 		else if (call->progressmask & (mask = PRI_PROG_DELAY_AT_INTERF))
3272 			code = Q931_PROG_DELAY_AT_INTERF;
3273 		else if (call->progressmask & (mask = PRI_PROG_INTERWORKING_WITH_PUBLIC))
3274 			code = Q931_PROG_INTERWORKING_WITH_PUBLIC;
3275 		else if (call->progressmask & (mask = PRI_PROG_INTERWORKING_NO_RELEASE))
3276 			code = Q931_PROG_INTERWORKING_NO_RELEASE;
3277 		else if (call->progressmask & (mask = PRI_PROG_INTERWORKING_NO_RELEASE_PRE_ANSWER))
3278 			code = Q931_PROG_INTERWORKING_NO_RELEASE_PRE_ANSWER;
3279 		else if (call->progressmask & (mask = PRI_PROG_INTERWORKING_NO_RELEASE_POST_ANSWER))
3280 			code = Q931_PROG_INTERWORKING_NO_RELEASE_POST_ANSWER;
3281 		else {
3282 			code = 0;
3283 			pri_error(ctrl, "XXX Undefined progress bit: %x\n", call->progressmask);
3284 		}
3285 		if (code) {
3286 			ie->data[0] = 0x80 | (call->progcode << 5)  | (call->progloc);
3287 			ie->data[1] = 0x80 | code;
3288 			call->progressmask &= ~mask;
3289 			return 4;
3290 		}
3291 	}
3292 	/* Leave off */
3293 	return 0;
3294 }
transmit_call_state(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3295 static int transmit_call_state(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3296 {
3297 	ie->data[0] = Q931_CALL_STATE_NULL;
3298 	switch (call->ourcallstate) {
3299 	case Q931_CALL_STATE_NULL:
3300 	case Q931_CALL_STATE_CALL_INITIATED:
3301 	case Q931_CALL_STATE_OVERLAP_SENDING:
3302 	case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
3303 	case Q931_CALL_STATE_CALL_DELIVERED:
3304 	case Q931_CALL_STATE_CALL_PRESENT:
3305 	case Q931_CALL_STATE_CALL_RECEIVED:
3306 	case Q931_CALL_STATE_CONNECT_REQUEST:
3307 	case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
3308 	case Q931_CALL_STATE_ACTIVE:
3309 	case Q931_CALL_STATE_DISCONNECT_REQUEST:
3310 	case Q931_CALL_STATE_DISCONNECT_INDICATION:
3311 	case Q931_CALL_STATE_SUSPEND_REQUEST:
3312 	case Q931_CALL_STATE_RESUME_REQUEST:
3313 	case Q931_CALL_STATE_RELEASE_REQUEST:
3314 	case Q931_CALL_STATE_CALL_ABORT:
3315 	case Q931_CALL_STATE_OVERLAP_RECEIVING:
3316 	case Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE:
3317 	case Q931_CALL_STATE_RESTART_REQUEST:
3318 	case Q931_CALL_STATE_RESTART:
3319 		ie->data[0] = call->ourcallstate;
3320 		break;
3321 	case Q931_CALL_STATE_NOT_SET:
3322 		break;
3323 	}
3324 	return 3;
3325 }
3326 
receive_call_state(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3327 static int receive_call_state(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3328 {
3329 	call->sugcallstate = ie->data[0] & 0x3f;
3330 	return 0;
3331 }
3332 
3333 /*!
3334  * \brief Convert the internal Q.931 call state to a string.
3335  *
3336  * \param callstate Internal Q.931 call state.
3337  *
3338  * \return String equivalent of the given Q.931 call state.
3339  */
q931_call_state_str(enum Q931_CALL_STATE callstate)3340 const char *q931_call_state_str(enum Q931_CALL_STATE callstate)
3341 {
3342 	static struct msgtype callstates[] = {
3343 /* *INDENT-OFF* */
3344 		{ Q931_CALL_STATE_NULL,                     "Null" },
3345 		{ Q931_CALL_STATE_CALL_INITIATED,           "Call Initiated" },
3346 		{ Q931_CALL_STATE_OVERLAP_SENDING,          "Overlap Sending" },
3347 		{ Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING, "Outgoing Call Proceeding" },
3348 		{ Q931_CALL_STATE_CALL_DELIVERED,           "Call Delivered" },
3349 		{ Q931_CALL_STATE_CALL_PRESENT,             "Call Present" },
3350 		{ Q931_CALL_STATE_CALL_RECEIVED,            "Call Received" },
3351 		{ Q931_CALL_STATE_CONNECT_REQUEST,          "Connect Request" },
3352 		{ Q931_CALL_STATE_INCOMING_CALL_PROCEEDING, "Incoming Call Proceeding" },
3353 		{ Q931_CALL_STATE_ACTIVE,                   "Active" },
3354 		{ Q931_CALL_STATE_DISCONNECT_REQUEST,       "Disconnect Request" },
3355 		{ Q931_CALL_STATE_DISCONNECT_INDICATION,    "Disconnect Indication" },
3356 		{ Q931_CALL_STATE_SUSPEND_REQUEST,          "Suspend Request" },
3357 		{ Q931_CALL_STATE_RESUME_REQUEST,           "Resume Request" },
3358 		{ Q931_CALL_STATE_RELEASE_REQUEST,          "Release Request" },
3359 		{ Q931_CALL_STATE_CALL_ABORT,               "Call Abort" },
3360 		{ Q931_CALL_STATE_OVERLAP_RECEIVING,        "Overlap Receiving" },
3361 		{ Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE, "Call Independent Service" },
3362 		{ Q931_CALL_STATE_RESTART_REQUEST,          "Restart Request" },
3363 		{ Q931_CALL_STATE_RESTART,                  "Restart" },
3364 		{ Q931_CALL_STATE_NOT_SET,                  "Not set. Internal use only." },
3365 /* *INDENT-ON* */
3366 	};
3367 	return code2str(callstate, callstates, ARRAY_LEN(callstates));
3368 }
3369 
3370 /*!
3371  * \internal
3372  * \brief Convert the Q.932 supplementary hold state to a string.
3373  *
3374  * \param state Q.932 supplementary hold state.
3375  *
3376  * \return String equivalent of the given hold state.
3377  */
q931_hold_state_str(enum Q931_HOLD_STATE state)3378 static const char *q931_hold_state_str(enum Q931_HOLD_STATE state)
3379 {
3380 	static struct msgtype hold_states[] = {
3381 /* *INDENT-OFF* */
3382 		{ Q931_HOLD_STATE_IDLE,         "Idle" },
3383 		{ Q931_HOLD_STATE_HOLD_REQ,     "Hold Request" },
3384 		{ Q931_HOLD_STATE_HOLD_IND,     "Hold Indication" },
3385 		{ Q931_HOLD_STATE_CALL_HELD,    "Call Held" },
3386 		{ Q931_HOLD_STATE_RETRIEVE_REQ, "Retrieve Request" },
3387 		{ Q931_HOLD_STATE_RETRIEVE_IND, "Retrieve Indication" },
3388 /* *INDENT-ON* */
3389 	};
3390 	return code2str(state, hold_states, ARRAY_LEN(hold_states));
3391 }
3392 
dump_call_state(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3393 static void dump_call_state(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3394 {
3395 	pri_message(ctrl, "%c %s (len=%2d) [ Ext: %d  Coding: %s (%d)  Call state: %s (%d)\n",
3396 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
3397 		coding2str((ie->data[0] & 0xC0) >> 6), (ie->data[0] & 0xC0) >> 6,
3398 		q931_call_state_str(ie->data[0] & 0x3f), ie->data[0] & 0x3f);
3399 }
3400 
dump_call_identity(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3401 static void dump_call_identity(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3402 {
3403 	int x;
3404 
3405 	pri_message(ctrl, "%c %s (len=%2d) [ ", prefix, ie2str(full_ie), len);
3406 	for (x = 0; x < ie->len; ++x) {
3407 		pri_message(ctrl, "0x%02X ", ie->data[x]);
3408 	}
3409 	pri_message(ctrl, " ]\n");
3410 }
3411 
dump_time_date(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3412 static void dump_time_date(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3413 {
3414 	pri_message(ctrl, "%c %s (len=%2d) [ ", prefix, ie2str(full_ie), len);
3415 	if (ie->len > 0)
3416 		pri_message(ctrl, "%02d", ie->data[0]);
3417 	if (ie->len > 1)
3418 		pri_message(ctrl, "-%02d", ie->data[1]);
3419 	if (ie->len > 2)
3420 		pri_message(ctrl, "-%02d", ie->data[2]);
3421 	if (ie->len > 3)
3422 		pri_message(ctrl, " %02d", ie->data[3]);
3423 	if (ie->len > 4)
3424 		pri_message(ctrl, ":%02d", ie->data[4]);
3425 	if (ie->len > 5)
3426 		pri_message(ctrl, ":%02d", ie->data[5]);
3427 	pri_message(ctrl, " ]\n");
3428 }
3429 
receive_time_date(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3430 static int receive_time_date(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3431 {
3432 	/* Ignore incoming Date/Time since we have no use for it at this time. */
3433 	return 0;
3434 }
3435 
transmit_time_date(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3436 static int transmit_time_date(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3437 {
3438 	time_t now;
3439 	struct tm timedate;
3440 	int ie_len;
3441 
3442 	do {
3443 		if (ctrl->date_time_send < PRI_DATE_TIME_SEND_DATE) {
3444 			ie_len = 0;
3445 			break;
3446 		}
3447 
3448 		/* Send the current date/time. */
3449 		time(&now);
3450 		localtime_r(&now, &timedate);
3451 		ie->data[0] = timedate.tm_year - 100; /* 1900+ */
3452 		ie->data[1] = timedate.tm_mon + 1;
3453 		ie->data[2] = timedate.tm_mday;
3454 		ie_len = 2 + 3;
3455 		if (ctrl->date_time_send < PRI_DATE_TIME_SEND_DATE_HH) {
3456 			break;
3457 		}
3458 
3459 		/* Add optional hour. */
3460 		ie->data[3] = timedate.tm_hour;
3461 		++ie_len;
3462 		if (ctrl->date_time_send < PRI_DATE_TIME_SEND_DATE_HHMM) {
3463 			break;
3464 		}
3465 
3466 		/* Add optional minutes. */
3467 		ie->data[4] = timedate.tm_min;
3468 		++ie_len;
3469 		if (ctrl->date_time_send < PRI_DATE_TIME_SEND_DATE_HHMMSS) {
3470 			break;
3471 		}
3472 
3473 		/* Add optional seconds. */
3474 		ie->data[5] = timedate.tm_sec;
3475 		++ie_len;
3476 	} while (0);
3477 	return ie_len;
3478 }
3479 
dump_keypad_facility(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3480 static void dump_keypad_facility(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3481 {
3482 	unsigned char tmp[64];
3483 
3484 	q931_strget(tmp, sizeof(tmp), ie->data, ie->len);
3485 	pri_message(ctrl, "%c %s (len=%2d) [ %s ]\n", prefix, ie2str(full_ie), ie->len, tmp);
3486 }
3487 
receive_keypad_facility(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3488 static int receive_keypad_facility(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3489 {
3490 	if (ie->len == 0)
3491 		return -1;
3492 
3493 	q931_strget_gripe(ctrl, ie2str(full_ie), (unsigned char *) call->keypad_digits,
3494 		sizeof(call->keypad_digits), ie->data, ie->len);
3495 
3496 	return 0;
3497 }
3498 
transmit_keypad_facility(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3499 static int transmit_keypad_facility(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3500 {
3501 	int sublen;
3502 
3503 	sublen = strlen(call->keypad_digits);
3504 	if (sublen) {
3505 		libpri_copy_string((char *) ie->data, call->keypad_digits, sizeof(call->keypad_digits));
3506 		return sublen + 2;
3507 	} else
3508 		return 0;
3509 }
3510 
dump_display(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3511 static void dump_display(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3512 {
3513 	int x;
3514 	unsigned char buf[2*80 + 1];
3515 	char tmp[20 + 1];
3516 
3517 	x = 0;
3518 	if (ie->len && (ie->data[x] & 0x80)) {
3519 		snprintf(tmp, sizeof(tmp), "Charset: %02x ", ie->data[x] & 0x7f);
3520 		++x;
3521 	} else {
3522 		tmp[0] = '\0';
3523 	}
3524 	q931_strget(buf, sizeof(buf), &ie->data[x], ie->len - x);
3525 	pri_message(ctrl, "%c %s (len=%2d) %s[ %s ]\n",
3526 		prefix, ie2str(full_ie), ie->len, tmp, buf);
3527 }
3528 
3529 #define CHECK_OVERFLOW(limit) \
3530 	if (tmpptr - tmp + limit >= sizeof(tmp)) { \
3531 		*tmpptr = '\0'; \
3532 		pri_message(ctrl, "%s", tmpptr = tmp); \
3533 	}
3534 
dump_ie_data(struct pri * ctrl,unsigned char * c,int len)3535 static void dump_ie_data(struct pri *ctrl, unsigned char *c, int len)
3536 {
3537 	static char hexs[16] = "0123456789ABCDEF";
3538 	char tmp[1024], *tmpptr;
3539 	int lastascii = 0;
3540 	tmpptr = tmp;
3541 	for (; len; --len, ++c) {
3542 		CHECK_OVERFLOW(7);
3543 		if (isprint(*c)) {
3544 			if (!lastascii) {
3545 				if (tmpptr != tmp) {
3546 					*tmpptr++ = ',';
3547 					*tmpptr++ = ' ';
3548 				}
3549 				*tmpptr++ = '\'';
3550 				lastascii = 1;
3551 			}
3552 			*tmpptr++ = *c;
3553 		} else {
3554 			if (lastascii) {
3555 				*tmpptr++ = '\'';
3556 				lastascii = 0;
3557 			}
3558 			if (tmpptr != tmp) {
3559 				*tmpptr++ = ',';
3560 				*tmpptr++ = ' ';
3561 			}
3562 			*tmpptr++ = '0';
3563 			*tmpptr++ = 'x';
3564 			*tmpptr++ = hexs[(*c >> 4) & 0x0f];
3565 			*tmpptr++ = hexs[(*c) & 0x0f];
3566 		}
3567 	}
3568 	if (lastascii)
3569 		*tmpptr++ = '\'';
3570 	*tmpptr = '\0';
3571 	pri_message(ctrl, "%s", tmp);
3572 }
3573 
dump_facility(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3574 static void dump_facility(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3575 {
3576 	pri_message(ctrl, "%c %s (len=%2d, codeset=%d) [ ",
3577 		prefix, ie2str(full_ie), len, Q931_IE_CODESET(full_ie));
3578 	dump_ie_data(ctrl, ie->data, ie->len);
3579 	pri_message(ctrl, " ]\n");
3580 #if 0	/* Lets not dump parse of facility contents here anymore. */
3581 	/*
3582 	 * The ASN.1 decode dump has already been done when the facility ie was added to the outgoing
3583 	 * message or the ASN.1 decode dump will be done when the facility ie is processed on incoming
3584 	 * messages.  This dump is redundant and very noisy.
3585 	 */
3586 	if (ie->len > 1) {
3587 		int dataat = (ie->data[0] & 0x80) ? 1 : 2;
3588 
3589 		pri_message(ctrl, "PROTOCOL %02X\n", ie->data[0] & Q932_PROTOCOL_MASK);
3590 		asn1_dump(ctrl, ie->data + dataat, ie->data + ie->len);
3591 	}
3592 #endif	/* Lets not dump parse of facility contents here anymore. */
3593 }
3594 
dump_network_spec_fac(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3595 static void dump_network_spec_fac(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3596 {
3597 	pri_message(ctrl, "%c %s (len=%2d) [ ", prefix, ie2str(full_ie), ie->len);
3598 	if (ie->data[0] == 0x00) {
3599 		pri_message(ctrl, "%s", code2str(ie->data[1], facilities, ARRAY_LEN(facilities)));
3600 	} else {
3601 		dump_ie_data(ctrl, ie->data, ie->len);
3602 	}
3603 	pri_message(ctrl, " ]\n");
3604 }
3605 
receive_network_spec_fac(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3606 static int receive_network_spec_fac(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3607 {
3608 	return 0;
3609 }
3610 
transmit_network_spec_fac(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3611 static int transmit_network_spec_fac(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3612 {
3613 	/* We are ready to transmit single IE only */
3614 	if (order > 1)
3615 		return 0;
3616 
3617 	if (ctrl->nsf != PRI_NSF_NONE) {
3618 		ie->data[0] = 0x00;
3619 		ie->data[1] = ctrl->nsf;
3620 		return 4;
3621 	}
3622 	/* Leave off */
3623 	return 0;
3624 }
3625 
pri_cause2str(int cause)3626 char *pri_cause2str(int cause)
3627 {
3628 	return code2str(cause, causes, sizeof(causes) / sizeof(causes[0]));
3629 }
3630 
pri_causeclass2str(int cause)3631 static char *pri_causeclass2str(int cause)
3632 {
3633 	static struct msgtype causeclasses[] = {
3634 		{ 0, "Normal Event" },
3635 		{ 1, "Normal Event" },
3636 		{ 2, "Network Congestion (resource unavailable)" },
3637 		{ 3, "Service or Option not Available" },
3638 		{ 4, "Service or Option not Implemented" },
3639 		{ 5, "Invalid message (e.g. parameter out of range)" },
3640 		{ 6, "Protocol Error (e.g. unknown message)" },
3641 		{ 7, "Interworking" },
3642 	};
3643 	return code2str(cause, causeclasses, sizeof(causeclasses) / sizeof(causeclasses[0]));
3644 }
3645 
dump_cause(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3646 static void dump_cause(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3647 {
3648 	int x;
3649 	int cause_ind = 1;
3650 	int data_ind = 2;
3651 
3652 	pri_message(ctrl,
3653 		"%c %s (len=%2d) [ Ext: %d  Coding: %s (%d)  Spare: %d  Location: %s (%d)\n",
3654 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
3655 		coding2str((ie->data[0] & 0x60) >> 5), (ie->data[0] & 0x60) >> 5,
3656 		(ie->data[0] & 0x10) >> 4, loc2str(ie->data[0] & 0xf), ie->data[0] & 0xf);
3657 	if ((ie->data[0] & 0x80) == 0) {
3658 		const char *recommendation;
3659 
3660 		switch (ie->data[1] & 0x7f) {
3661 		case 0x00:
3662 			recommendation = "Q.931";
3663 			break;
3664 		case 0x03:
3665 			recommendation = "X.21";
3666 			break;
3667 		case 0x04:
3668 			recommendation = "X.25";
3669 			break;
3670 		case 0x05:
3671 			recommendation = "Q.1031/Q.1051";
3672 			break;
3673 		default:
3674 			recommendation = "Reserved";
3675 			break;
3676 		}
3677 		pri_message(ctrl, "%c                  Ext: %d  Recommendation: %s (%d)\n",
3678 			prefix, (ie->data[1] >> 7), recommendation, ie->data[1] & 0x7f);
3679 
3680 		cause_ind = 2;
3681 		data_ind = 3;
3682 	}
3683 	pri_message(ctrl, "%c                  Ext: %d  Cause: %s (%d), class = %s (%d) ]\n",
3684 		prefix, (ie->data[cause_ind] >> 7), pri_cause2str(ie->data[cause_ind] & 0x7f), ie->data[cause_ind] & 0x7f,
3685 		pri_causeclass2str((ie->data[cause_ind] & 0x7f) >> 4), (ie->data[cause_ind] & 0x7f) >> 4);
3686 	if (ie->len <= data_ind) {
3687 		return;
3688 	}
3689 	/* Dump cause data in readable form */
3690 	switch(ie->data[cause_ind] & 0x7f) {
3691 	case PRI_CAUSE_IE_NONEXIST:
3692 		for (x = data_ind; x < ie->len; x++) {
3693 			pri_message(ctrl, "%c              Cause data %d: %02x (%d, %s IE)\n", prefix, x-1, ie->data[x], ie->data[x], ie2str(ie->data[x]));
3694 		}
3695 		break;
3696 	case PRI_CAUSE_WRONG_CALL_STATE:
3697 		for (x = data_ind; x < ie->len; x++) {
3698 			pri_message(ctrl, "%c              Cause data %d: %02x (%d, %s message)\n", prefix, x-1, ie->data[x], ie->data[x], msg2str(ie->data[x]));
3699 		}
3700 		break;
3701 	case PRI_CAUSE_RECOVERY_ON_TIMER_EXPIRE:
3702 		pri_message(ctrl, "%c              Cause data:", prefix);
3703 		for (x = data_ind; x < ie->len; x++) {
3704 			pri_message(ctrl, " %02x", ie->data[x]);
3705 		}
3706 		pri_message(ctrl, " (Timer T");
3707 		for (x = data_ind; x < ie->len; x++) {
3708 			pri_message(ctrl, "%c", ((ie->data[x] >= ' ') && (ie->data[x] < 0x7f)) ? ie->data[x] : '.');
3709 		}
3710 		pri_message(ctrl, ")\n");
3711 		break;
3712 	default:
3713 		for (x = data_ind; x < ie->len; x++) {
3714 			pri_message(ctrl, "%c              Cause data %d: %02x (%d)\n", prefix, x-1, ie->data[x], ie->data[x]);
3715 		}
3716 		break;
3717 	}
3718 }
3719 
receive_cause(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3720 static int receive_cause(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3721 {
3722 	call->causeloc = ie->data[0] & 0xf;
3723 	call->causecode = (ie->data[0] & 0x60) >> 5;
3724 	if (ie->data[0] & 0x80) {
3725 		call->cause = (ie->data[1] & 0x7f);
3726 	} else {
3727 		call->cause = (ie->data[2] & 0x7f);
3728 	}
3729 	return 0;
3730 }
3731 
transmit_cause(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3732 static int transmit_cause(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3733 {
3734 	/* We are ready to transmit single IE only */
3735 	if (order > 1)
3736 		return 0;
3737 
3738 	if (call->cause > 0) {
3739 		ie->data[0] = 0x80 | (call->causecode << 5)  | (call->causeloc);
3740 		ie->data[1] = 0x80 | (call->cause);
3741 		return 4;
3742 	} else {
3743 		/* Leave off */
3744 		return 0;
3745 	}
3746 }
3747 
dump_sending_complete(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3748 static void dump_sending_complete(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3749 {
3750 	pri_message(ctrl, "%c %s (len=%2d)\n", prefix, ie2str(full_ie), len);
3751 }
3752 
receive_sending_complete(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3753 static int receive_sending_complete(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3754 {
3755 	/* We've got a "Complete" message: Exect no further digits. */
3756 	call->complete = 1;
3757 	return 0;
3758 }
3759 
transmit_sending_complete(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3760 static int transmit_sending_complete(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3761 {
3762 	if ((ctrl->overlapdial && call->complete) || /* Explicit */
3763 		(!ctrl->overlapdial && ((ctrl->switchtype == PRI_SWITCH_EUROISDN_E1) ||
3764 		/* Implicit */   	   (ctrl->switchtype == PRI_SWITCH_EUROISDN_T1)))) {
3765 		/* Include this single-byte IE */
3766 		return 1;
3767 	}
3768 	return 0;
3769 }
3770 
notify2str(int info)3771 static char *notify2str(int info)
3772 {
3773 	/* ITU-T Q.763 */
3774 	static struct msgtype notifies[] = {
3775 		{ PRI_NOTIFY_USER_SUSPENDED, "User suspended" },
3776 		{ PRI_NOTIFY_USER_RESUMED, "User resumed" },
3777 		{ PRI_NOTIFY_BEARER_CHANGE, "Bearer service change (DSS1)" },
3778 		{ PRI_NOTIFY_ASN1_COMPONENT, "ASN.1 encoded component (DSS1)" },
3779 		{ PRI_NOTIFY_COMPLETION_DELAY, "Call completion delay" },
3780 		{ PRI_NOTIFY_CONF_ESTABLISHED, "Conference established" },
3781 		{ PRI_NOTIFY_CONF_DISCONNECTED, "Conference disconnected" },
3782 		{ PRI_NOTIFY_CONF_PARTY_ADDED, "Other party added" },
3783 		{ PRI_NOTIFY_CONF_ISOLATED, "Isolated" },
3784 		{ PRI_NOTIFY_CONF_REATTACHED, "Reattached" },
3785 		{ PRI_NOTIFY_CONF_OTHER_ISOLATED, "Other party isolated" },
3786 		{ PRI_NOTIFY_CONF_OTHER_REATTACHED, "Other party reattached" },
3787 		{ PRI_NOTIFY_CONF_OTHER_SPLIT, "Other party split" },
3788 		{ PRI_NOTIFY_CONF_OTHER_DISCONNECTED, "Other party disconnected" },
3789 		{ PRI_NOTIFY_CONF_FLOATING, "Conference floating" },
3790 		{ PRI_NOTIFY_WAITING_CALL, "Call is waiting call" },
3791 		{ PRI_NOTIFY_DIVERSION_ACTIVATED, "Diversion activated (DSS1)" },
3792 		{ PRI_NOTIFY_TRANSFER_ALERTING, "Call transfer, alerting" },
3793 		{ PRI_NOTIFY_TRANSFER_ACTIVE, "Call transfer, active" },
3794 		{ PRI_NOTIFY_REMOTE_HOLD, "Remote hold" },
3795 		{ PRI_NOTIFY_REMOTE_RETRIEVAL, "Remote retrieval" },
3796 		{ PRI_NOTIFY_CALL_DIVERTING, "Call is diverting" },
3797 	};
3798 	return code2str(info, notifies, sizeof(notifies) / sizeof(notifies[0]));
3799 }
3800 
dump_notify(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3801 static void dump_notify(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3802 {
3803 	pri_message(ctrl, "%c %s (len=%2d): Ext: %d  %s (%d)\n",
3804 		prefix, ie2str(full_ie), len, ie->data[0] >> 7,
3805 		notify2str(ie->data[0] & 0x7f), ie->data[0] & 0x7f);
3806 }
3807 
receive_notify(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3808 static int receive_notify(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3809 {
3810 	call->notify = ie->data[0] & 0x7F;
3811 	return 0;
3812 }
3813 
transmit_notify(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3814 static int transmit_notify(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3815 {
3816 	if (call->notify >= 0) {
3817 		ie->data[0] = 0x80 | call->notify;
3818 		return 3;
3819 	}
3820 	return 0;
3821 }
3822 
dump_shift(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3823 static void dump_shift(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3824 {
3825 	pri_message(ctrl, "%c %sLocking Shift (len=%02d): Requested codeset %d\n",
3826 		prefix, (full_ie & 8) ? "Non-" : "", len, full_ie & 7);
3827 }
3828 
lineinfo2str(int info)3829 static char *lineinfo2str(int info)
3830 {
3831 	/* NAPNA ANI II digits */
3832 	static struct msgtype lineinfo[] = {
3833 		{  0, "Plain Old Telephone Service (POTS)" },
3834 		{  1, "Multiparty line (more than 2)" },
3835 		{  2, "ANI failure" },
3836 		{  6, "Station Level Rating" },
3837 		{  7, "Special Operator Handling Required" },
3838 		{ 20, "Automatic Identified Outward Dialing (AIOD)" },
3839 		{ 23, "Coing or Non-Coin" },
3840 		{ 24, "Toll free translated to POTS originated for non-pay station" },
3841 		{ 25, "Toll free translated to POTS originated from pay station" },
3842 		{ 27, "Pay station with coin control signalling" },
3843 		{ 29, "Prison/Inmate Service" },
3844 		{ 30, "Intercept (blank)" },
3845 		{ 31, "Intercept (trouble)" },
3846 		{ 32, "Intercept (regular)" },
3847 		{ 34, "Telco Operator Handled Call" },
3848 		{ 52, "Outward Wide Area Telecommunications Service (OUTWATS)" },
3849 		{ 60, "TRS call from unrestricted line" },
3850 		{ 61, "Cellular/Wireless PCS (Type 1)" },
3851 		{ 62, "Cellular/Wireless PCS (Type 2)" },
3852 		{ 63, "Cellular/Wireless PCS (Roaming)" },
3853 		{ 66, "TRS call from hotel/motel" },
3854 		{ 67, "TRS call from restricted line" },
3855 		{ 70, "Line connected to pay station" },
3856 		{ 93, "Private virtual network call" },
3857 	};
3858 	return code2str(info, lineinfo, sizeof(lineinfo) / sizeof(lineinfo[0]));
3859 }
3860 
dump_line_information(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3861 static void dump_line_information(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3862 {
3863 	pri_message(ctrl, "%c %s (len=%02d): %s (%d)\n",
3864 		prefix, ie2str(full_ie), len, lineinfo2str(ie->data[0]), ie->data[0]);
3865 }
3866 
receive_line_information(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3867 static int receive_line_information(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3868 {
3869 	call->ani2 = ie->data[0];
3870 	return 0;
3871 }
3872 
transmit_line_information(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)3873 static int transmit_line_information(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
3874 {
3875 #if 0	/* XXX Is this IE possible for 4ESS only? XXX */
3876 	if(ctrl->switchtype == PRI_SWITCH_ATT4ESS) {
3877 		ie->data[0] = 0;
3878 		return 3;
3879 	}
3880 #endif
3881 	return 0;
3882 }
3883 
3884 
gdencoding2str(int encoding)3885 static char *gdencoding2str(int encoding)
3886 {
3887 	static struct msgtype gdencoding[] = {
3888 		{ 0, "BCD even" },
3889 		{ 1, "BCD odd" },
3890 		{ 2, "IA5" },
3891 		{ 3, "Binary" },
3892 	};
3893 	return code2str(encoding, gdencoding, sizeof(gdencoding) / sizeof(gdencoding[0]));
3894 }
3895 
gdtype2str(int type)3896 static char *gdtype2str(int type)
3897 {
3898 	static struct msgtype gdtype[] = {
3899 		{  0, "Account Code" },
3900 		{  1, "Auth Code" },
3901 		{  2, "Customer ID" },
3902 		{  3, "Universal Access" },
3903 		{  4, "Info Digits" },
3904 		{  5, "Callid" },
3905 		{  6, "Opart" },
3906 		{  7, "TCN" },
3907 		{  9, "Adin" },
3908 	};
3909 	return code2str(type, gdtype, sizeof(gdtype) / sizeof(gdtype[0]));
3910 }
3911 
dump_generic_digits(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)3912 static void dump_generic_digits(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
3913 {
3914 	int encoding;
3915 	int type;
3916 	int idx;
3917 	int value;
3918 	if (len < 3) {
3919 		pri_message(ctrl, "%c %s (len=%02d): Invalid length\n",
3920 			prefix, ie2str(full_ie), len);
3921 		return;
3922 	}
3923 	encoding = (ie->data[0] >> 5) & 7;
3924 	type = ie->data[0] & 0x1F;
3925 	pri_message(ctrl, "%c %s (len=%02d): Encoding %s  Type %s\n",
3926 		prefix, ie2str(full_ie), len, gdencoding2str(encoding), gdtype2str(type));
3927 	if (encoding == 3) {	/* Binary */
3928 		pri_message(ctrl, "%c                            Don't know how to handle binary encoding\n",
3929 			prefix);
3930 		return;
3931 	}
3932 	if (len == 3)	/* No number information */
3933 		return;
3934 	pri_message(ctrl, "%c                            Digits: ", prefix);
3935 	value = 0;
3936 	for(idx = 3; idx < len; ++idx) {
3937 		switch(encoding) {
3938 		case 0:		/* BCD even */
3939 		case 1:		/* BCD odd */
3940 			pri_message(ctrl, "%d", ie->data[idx-2] & 0x0f);
3941 			value = value * 10 + (ie->data[idx-2] & 0x0f);
3942 			if(!encoding || (idx+1 < len)) {	/* Special handling for BCD odd */
3943 				pri_message(ctrl, "%d", (ie->data[idx-2] >> 4) & 0x0f);
3944 				value = value * 10 + ((ie->data[idx-2] >> 4) & 0x0f);
3945 			}
3946 			break;
3947 		case 2:		/* IA5 */
3948 			pri_message(ctrl, "%c", ie->data[idx-2]);
3949 			value = value * 10 + ie->data[idx-2] - '0';
3950 			break;
3951 		}
3952 	}
3953 	switch(type) {
3954 		case 4:		/* Info Digits */
3955 			pri_message(ctrl, " - %s", lineinfo2str(value));
3956 			break;
3957 	}
3958 	pri_message(ctrl, "\n");
3959 }
3960 
receive_generic_digits(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)3961 static int receive_generic_digits(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
3962 {
3963 	int encoding;
3964 	int type;
3965 	int idx;
3966 	int value;
3967 	int num_idx;
3968 	char number[260];
3969 
3970 	if (len < 3) {
3971 		pri_error(ctrl, "Invalid length of Generic Digits IE\n");
3972 		return -1;
3973 	}
3974 	encoding = (ie->data[0] >> 5) & 7;
3975 	type = ie->data[0] & 0x1F;
3976 	if (encoding == 3) {	/* Binary */
3977 		pri_message(ctrl, "!! Unable to handle binary encoded Generic Digits IE\n");
3978 		return 0;
3979 	}
3980 	if (len == 3)	/* No number information */
3981 		return 0;
3982 	value = 0;
3983 	switch(type) {
3984 	/* Integer value handling */
3985 	case 4:		/* Info Digits */
3986 		for(idx = 3; idx < len; ++idx) {
3987 			switch(encoding) {
3988 			case 0:		/* BCD even */
3989 			case 1:		/* BCD odd */
3990 				value = value * 10 + (ie->data[idx-2] & 0x0f);
3991 				if(!encoding || (idx+1 < len))	/* Special handling for BCD odd */
3992 					value = value * 10 + ((ie->data[idx-2] >> 4) & 0x0f);
3993 				break;
3994 			case 2:		/* IA5 */
3995 				value = value * 10 + (ie->data[idx-2] - '0');
3996 				break;
3997 			}
3998 		}
3999 		break;
4000 	/* String value handling */
4001 	case 5:		/* Callid */
4002 		num_idx = 0;
4003 		for(idx = 3; (idx < len) && (num_idx < sizeof(number) - 4); ++idx) {
4004 			switch(encoding) {
4005 			case 0:		/* BCD even */
4006 			case 1:		/* BCD odd */
4007 				number[num_idx++] = '0' + (ie->data[idx-2] & 0x0f);
4008 				if(!encoding || (idx+1 < len))	/* Special handling for BCD odd */
4009 					number[num_idx++] = '0' + ((ie->data[idx-2] >> 4) & 0x0f);
4010 				break;
4011 			case 2:
4012 				number[num_idx++] = ie->data[idx-2];
4013 				break;
4014 			}
4015 		}
4016 		number[num_idx] = '\0';
4017 		break;
4018 	}
4019 	switch(type) {
4020 	case 4:		/* Info Digits */
4021 		call->ani2 = value;
4022 		break;
4023 #if 0
4024 	case 5:		/* Callid */
4025 		if (!call->remote_id.number.valid) {
4026 			call->remote_id.number.valid = 1;
4027 			call->remote_id.number.presentation =
4028 				PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
4029 			call->remote_id.number.plan = PRI_UNKNOWN;
4030 			libpri_copy_string(call->remote_id.number.str, number,
4031 				sizeof(call->remote_id.number.str));
4032 		}
4033 		break;
4034 #endif
4035 	}
4036 	return 0;
4037 }
4038 
transmit_generic_digits(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)4039 static int transmit_generic_digits(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
4040 {
4041 #if 0	/* XXX Is this IE possible for other switches? XXX */
4042 	if (order > 1)
4043 		return 0;
4044 
4045 	if(ctrl->switchtype == PRI_SWITCH_NI1) {
4046 		ie->data[0] = 0x04;	/* BCD even, Info Digits */
4047 		ie->data[1] = 0x00;	/* POTS */
4048 		return 4;
4049 	}
4050 #endif
4051 	return 0;
4052 }
4053 
4054 
signal2str(int signal)4055 static char *signal2str(int signal)
4056 {
4057 	/* From Q.931 4.5.8 Table 4-24 */
4058 	static struct msgtype mtsignal[] = {
4059 		{  0, "Dial tone" },
4060 		{  1, "Ring back tone" },
4061 		{  2, "Intercept tone" },
4062 		{  3, "Network congestion tone" },
4063 		{  4, "Busy tone" },
4064 		{  5, "Confirm tone" },
4065 		{  6, "Answer tone" },
4066 		{  7, "Call waiting tone" },
4067 		{  8, "Off-hook warning tone" },
4068 		{  9, "Pre-emption tone" },
4069 		{ 63, "Tones off" },
4070 		{ 64, "Alerting on - pattern 0" },
4071 		{ 65, "Alerting on - pattern 1" },
4072 		{ 66, "Alerting on - pattern 2" },
4073 		{ 67, "Alerting on - pattern 3" },
4074 		{ 68, "Alerting on - pattern 4" },
4075 		{ 69, "Alerting on - pattern 5" },
4076 		{ 70, "Alerting on - pattern 6" },
4077 		{ 71, "Alerting on - pattern 7" },
4078 		{ 79, "Alerting off" },
4079 	};
4080 	return code2str(signal, mtsignal, sizeof(mtsignal) / sizeof(mtsignal[0]));
4081 }
4082 
4083 
dump_signal(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)4084 static void dump_signal(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
4085 {
4086 	pri_message(ctrl, "%c %s (len=%02d): ", prefix, ie2str(full_ie), len);
4087 	if (len < 3) {
4088 		pri_message(ctrl, "Invalid length\n");
4089 		return;
4090 	}
4091 	pri_message(ctrl, "Signal %s (%d)\n", signal2str(ie->data[0]), ie->data[0]);
4092 }
4093 
dump_transit_count(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)4094 static void dump_transit_count(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
4095 {
4096 	/* Defined in ECMA-225 */
4097 	pri_message(ctrl, "%c %s (len=%02d): ", prefix, ie2str(full_ie), len);
4098 	if (len < 3) {
4099 		pri_message(ctrl, "Invalid length\n");
4100 		return;
4101 	}
4102 	pri_message(ctrl, "Count=%d (0x%02x)\n", ie->data[0] & 0x1f, ie->data[0] & 0x1f);
4103 }
4104 
dump_reverse_charging_indication(int full_ie,struct pri * ctrl,q931_ie * ie,int len,char prefix)4105 static void dump_reverse_charging_indication(int full_ie, struct pri *ctrl, q931_ie *ie, int len, char prefix)
4106 {
4107 	pri_message(ctrl, "%c %s (len=%02d): %d\n", prefix, ie2str(full_ie), len, ie->data[0] & 0x7);
4108 }
4109 
receive_reverse_charging_indication(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len)4110 static int receive_reverse_charging_indication(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len)
4111 {
4112 	call->reversecharge = ie->data[0] & 0x7;
4113 	return 0;
4114 }
4115 
transmit_reverse_charging_indication(int full_ie,struct pri * ctrl,q931_call * call,int msgtype,q931_ie * ie,int len,int order)4116 static int transmit_reverse_charging_indication(int full_ie, struct pri *ctrl, q931_call *call, int msgtype, q931_ie *ie, int len, int order)
4117 {
4118 	if (call->reversecharge != PRI_REVERSECHARGE_NONE) {
4119 		ie->data[0] = 0x80 | (call->reversecharge & 0x7);
4120 		return 3;
4121 	}
4122 	return 0;
4123 }
4124 
4125 static struct ie ies[] = {
4126 	/* Codeset 0 - Comprehension required ie's with varying support. */
4127 	{ 1, Q931_IE_SEGMENTED_MSG, "Segmented Message" }, /* Not supported.  Just ie name is available for message decode. */
4128 	{ 1, Q931_IE_CHANGE_STATUS, "Change Status Information", dump_change_status, receive_change_status, transmit_change_status },
4129 
4130 	/* Codeset 0 - Common */
4131 	{ 0, Q931_LOCKING_SHIFT, "Locking Shift", dump_shift },
4132 	{ 0, Q931_BEARER_CAPABILITY, "Bearer Capability", dump_bearer_capability, receive_bearer_capability, transmit_bearer_capability },
4133 	{ 0, Q931_CAUSE, "Cause", dump_cause, receive_cause, transmit_cause },
4134 	{ 1, Q931_IE_CALL_STATE, "Call State", dump_call_state, receive_call_state, transmit_call_state },
4135 	{ 0, Q931_CHANNEL_IDENT, "Channel ID", dump_channel_id, receive_channel_id, transmit_channel_id },
4136 	{ 0, Q931_PROGRESS_INDICATOR, "Progress Indicator", dump_progress_indicator, receive_progress_indicator, transmit_progress_indicator },
4137 	{ 0, Q931_NETWORK_SPEC_FAC, "Network-Specific Facilities", dump_network_spec_fac, receive_network_spec_fac, transmit_network_spec_fac },
4138 	{ 1, Q931_INFORMATION_RATE, "Information Rate" },
4139 	{ 1, Q931_TRANSIT_DELAY, "End-to-End Transit Delay" },
4140 	{ 1, Q931_TRANS_DELAY_SELECT, "Transmit Delay Selection and Indication" },
4141 	{ 1, Q931_BINARY_PARAMETERS, "Packet-layer Binary Parameters" },
4142 	{ 1, Q931_WINDOW_SIZE, "Packet-layer Window Size" },
4143 	{ 1, Q931_CLOSED_USER_GROUP, "Closed User Group" },
4144 	{ 1, Q931_REVERSE_CHARGE_INDIC, "Reverse Charging Indication", dump_reverse_charging_indication, receive_reverse_charging_indication, transmit_reverse_charging_indication },
4145 	{ 1, Q931_CALLING_PARTY_NUMBER, "Calling Party Number", dump_calling_party_number, receive_calling_party_number, transmit_calling_party_number },
4146 	{ 1, Q931_CALLING_PARTY_SUBADDR, "Calling Party Subaddress", dump_calling_party_subaddr, receive_calling_party_subaddr, transmit_calling_party_subaddr },
4147 	{ 1, Q931_CALLED_PARTY_NUMBER, "Called Party Number", dump_called_party_number, receive_called_party_number, transmit_called_party_number },
4148 	{ 1, Q931_CALLED_PARTY_SUBADDR, "Called Party Subaddress", dump_called_party_subaddr, receive_called_party_subaddr, transmit_called_party_subaddr },
4149 	{ 0, Q931_REDIRECTING_NUMBER, "Redirecting Number", dump_redirecting_number, receive_redirecting_number, transmit_redirecting_number },
4150 	{ 1, Q931_REDIRECTING_SUBADDR, "Redirecting Subaddress", dump_redirecting_subaddr },
4151 	{ 0, Q931_TRANSIT_NET_SELECT, "Transit Network Selection" },
4152 	{ 1, Q931_RESTART_INDICATOR, "Restart Indicator", dump_restart_indicator, receive_restart_indicator, transmit_restart_indicator },
4153 	{ 0, Q931_LOW_LAYER_COMPAT, "Low-layer Compatibility" },
4154 	{ 0, Q931_HIGH_LAYER_COMPAT, "High-layer Compatibility" },
4155 	{ 1, Q931_PACKET_SIZE, "Packet Size" },
4156 	{ 0, Q931_IE_FACILITY, "Facility" , dump_facility, receive_facility, transmit_facility },
4157 	{ 1, Q931_IE_REDIRECTION_NUMBER, "Redirection Number", dump_redirection_number, receive_redirection_number, transmit_redirection_number },
4158 	{ 1, Q931_IE_REDIRECTION_SUBADDR, "Redirection Subaddress" },
4159 	{ 1, Q931_IE_FEATURE_ACTIVATE, "Feature Activation" },
4160 	{ 1, Q931_IE_INFO_REQUEST, "Feature Request" },
4161 	{ 1, Q931_IE_FEATURE_IND, "Feature Indication" },
4162 	{ 1, Q931_IE_CALL_IDENTITY, "Call Identity", dump_call_identity },
4163 	{ 1, Q931_IE_ENDPOINT_ID, "Endpoint Identification" },
4164 	{ 1, Q931_IE_NOTIFY_IND, "Notification Indicator", dump_notify, receive_notify, transmit_notify },
4165 	{ 1, Q931_DISPLAY, "Display", dump_display, receive_display, transmit_display },
4166 	{ 1, Q931_IE_TIME_DATE, "Date/Time", dump_time_date, receive_time_date, transmit_time_date },
4167 	{ 1, Q931_IE_KEYPAD_FACILITY, "Keypad Facility", dump_keypad_facility, receive_keypad_facility, transmit_keypad_facility },
4168 	{ 0, Q931_IE_SIGNAL, "Signal", dump_signal },
4169 	{ 1, Q931_IE_SWITCHHOOK, "Switch-hook" },
4170 	{ 1, Q931_IE_USER_USER, "User-User Information", dump_user_user, receive_user_user, transmit_user_user },
4171 	{ 1, Q931_IE_ESCAPE_FOR_EXT, "Escape for Extension" },
4172 	{ 1, Q931_IE_CALL_STATUS, "Call Status" },
4173 	{ 1, Q931_IE_CONNECTED_ADDR, "Connected Address", dump_connected_number, receive_connected_number, transmit_connected_number },
4174 	{ 1, Q931_IE_CONNECTED_NUM, "Connected Number", dump_connected_number, receive_connected_number, transmit_connected_number },
4175 	{ 1, Q931_IE_CONNECTED_SUBADDR, "Connected Subaddress", dump_connected_subaddr, receive_connected_subaddr, transmit_connected_subaddr },
4176 	{ 1, Q931_IE_ORIGINAL_CALLED_NUMBER, "Original Called Number", dump_redirecting_number, receive_redirecting_number, transmit_redirecting_number },
4177 	{ 1, Q931_IE_USER_USER_FACILITY, "User-User Facility" },
4178 	{ 1, Q931_IE_UPDATE, "Update" },
4179 	{ 1, Q931_SENDING_COMPLETE, "Sending Complete", dump_sending_complete, receive_sending_complete, transmit_sending_complete },
4180 	/* Codeset 4 - Q.SIG specific */
4181 	{ 1, QSIG_IE_TRANSIT_COUNT | Q931_CODESET(4), "Transit Count", dump_transit_count },
4182 	/* Codeset 5 - National specific (ETSI PISN specific) */
4183 	{ 1, Q931_CALLING_PARTY_CATEGORY, "Calling Party Category", dump_calling_party_category },
4184 	/* Codeset 6 - Network specific */
4185 	{ 1, Q931_IE_ORIGINATING_LINE_INFO, "Originating Line Information", dump_line_information, receive_line_information, transmit_line_information },
4186 	{ 1, Q931_IE_FACILITY | Q931_CODESET(6), "Facility", dump_facility, receive_facility, transmit_facility },
4187 	{ 1, Q931_DISPLAY | Q931_CODESET(6), "Display (CS6)", dump_display, receive_display, transmit_display },
4188 	{ 0, Q931_IE_GENERIC_DIGITS, "Generic Digits", dump_generic_digits, receive_generic_digits, transmit_generic_digits },
4189 	/* Codeset 7 */
4190 };
4191 
ie2str(int ie)4192 static char *ie2str(int ie)
4193 {
4194 	unsigned int x;
4195 
4196 	/* Special handling for Locking/Non-Locking Shifts */
4197 	switch (ie & 0xf8) {
4198 	case Q931_LOCKING_SHIFT:
4199 		switch (ie & 7) {
4200 		case 0:
4201 			return "!! INVALID Locking Shift To Codeset 0";
4202 		case 1:
4203 			return "Locking Shift To Codeset 1";
4204 		case 2:
4205 			return "Locking Shift To Codeset 2";
4206 		case 3:
4207 			return "Locking Shift To Codeset 3";
4208 		case 4:
4209 			return "Locking Shift To Codeset 4";
4210 		case 5:
4211 			return "Locking Shift To Codeset 5";
4212 		case 6:
4213 			return "Locking Shift To Codeset 6";
4214 		case 7:
4215 			return "Locking Shift To Codeset 7";
4216 		default:
4217 			break;
4218 		}
4219 		break;
4220 	case Q931_NON_LOCKING_SHIFT:
4221 		switch (ie & 7) {
4222 		case 0:
4223 			return "Non-Locking Shift To Codeset 0";
4224 		case 1:
4225 			return "Non-Locking Shift To Codeset 1";
4226 		case 2:
4227 			return "Non-Locking Shift To Codeset 2";
4228 		case 3:
4229 			return "Non-Locking Shift To Codeset 3";
4230 		case 4:
4231 			return "Non-Locking Shift To Codeset 4";
4232 		case 5:
4233 			return "Non-Locking Shift To Codeset 5";
4234 		case 6:
4235 			return "Non-Locking Shift To Codeset 6";
4236 		case 7:
4237 			return "Non-Locking Shift To Codeset 7";
4238 		default:
4239 			break;
4240 		}
4241 		break;
4242 	default:
4243 		break;
4244 	}
4245 	for (x = 0; x < ARRAY_LEN(ies); ++x) {
4246 		if (ie == ies[x].ie) {
4247 			return ies[x].name;
4248 		}
4249 	}
4250 	return "Unknown Information Element";
4251 }
4252 
ielen(q931_ie * ie)4253 static inline unsigned int ielen(q931_ie *ie)
4254 {
4255 	if ((ie->ie & 0x80) != 0)
4256 		return 1;
4257 	else
4258 		return 2 + ie->len;
4259 }
4260 
ielen_checked(q931_ie * ie,int len_remaining)4261 static inline int ielen_checked(q931_ie *ie, int len_remaining)
4262 {
4263 	int len;
4264 
4265 	if (ie->ie & 0x80) {
4266 		len = 1;
4267 	} else if (len_remaining < 2) {
4268 		/* There is no length octet when there should be. */
4269 		len = -1;
4270 	} else {
4271 		len = 2 + ie->len;
4272 		if (len_remaining < len) {
4273 			/* There is not enough room left in the packet for this ie. */
4274 			len = -1;
4275 		}
4276 	}
4277 	return len;
4278 }
4279 
msg2str(int msg)4280 const char *msg2str(int msg)
4281 {
4282 	unsigned int x;
4283 	for (x=0;x<sizeof(msgs) / sizeof(msgs[0]); x++)
4284 		if (msgs[x].msgnum == msg)
4285 			return msgs[x].name;
4286 	return "Unknown Message Type";
4287 }
4288 
maintenance_msg2str(int msg,int pd)4289 static char *maintenance_msg2str(int msg, int pd)
4290 {
4291 	unsigned int x, max;
4292 	struct msgtype *m = NULL;
4293 
4294 	if (pd == MAINTENANCE_PROTOCOL_DISCRIMINATOR_1) {
4295 		m = att_maintenance_msgs;
4296 		max = ARRAY_LEN(att_maintenance_msgs);
4297 	} else {
4298 		m = national_maintenance_msgs;
4299 		max = ARRAY_LEN(national_maintenance_msgs);
4300 	}
4301 
4302 	for (x = 0; x < max; x++) {
4303 		if (m[x].msgnum == msg) {
4304 			return m[x].name;
4305 		}
4306 	}
4307 	return "Unknown Message Type";
4308 }
4309 
4310 /* Decode the call reference */
q931_cr(q931_h * h)4311 static inline int q931_cr(q931_h *h)
4312 {
4313 	int cr;
4314 	int x;
4315 
4316 	if (h->crlen > 3) {
4317 		pri_error(NULL, "Call Reference Length Too long: %d\n", h->crlen);
4318 		return Q931_DUMMY_CALL_REFERENCE;
4319 	}
4320 	switch (h->crlen) {
4321 	case 2:
4322 		cr = 0;
4323 		for (x = 0; x < h->crlen; ++x) {
4324 			cr <<= 8;
4325 			cr |= h->crv[x];
4326 		}
4327 		break;
4328 	case 1:
4329 		cr = h->crv[0];
4330 		if (cr & 0x80) {
4331 			cr &= ~0x80;
4332 			cr |= Q931_CALL_REFERENCE_FLAG;
4333 		}
4334 		break;
4335 	case 0:
4336 		cr = Q931_DUMMY_CALL_REFERENCE;
4337 		break;
4338 	default:
4339 		pri_error(NULL, "Call Reference Length not supported: %d\n", h->crlen);
4340 		cr = Q931_DUMMY_CALL_REFERENCE;
4341 		break;
4342 	}
4343 	return cr;
4344 }
4345 
q931_dumpie(struct pri * ctrl,int codeset,q931_ie * ie,char prefix)4346 static inline void q931_dumpie(struct pri *ctrl, int codeset, q931_ie *ie, char prefix)
4347 {
4348 	unsigned int x;
4349 	int full_ie = Q931_FULL_IE(codeset, ie->ie);
4350 	int base_ie;
4351 	char *buf = malloc(ielen(ie) * 3 + 1);
4352 	int buflen = 0;
4353 
4354 	buf[0] = '\0';
4355 	if (!(ie->ie & 0x80)) {
4356 		buflen += sprintf(buf, " %02x", ielen(ie)-2);
4357 		for (x = 0; x + 2 < ielen(ie); ++x)
4358 			buflen += sprintf(buf + buflen, " %02x", ie->data[x]);
4359 	}
4360 	pri_message(ctrl, "%c [%02x%s]\n", prefix, ie->ie, buf);
4361 	free(buf);
4362 
4363 	/* Special treatment for shifts */
4364 	if((full_ie & 0xf0) == Q931_LOCKING_SHIFT)
4365 		full_ie &= 0xff;
4366 
4367 	base_ie = (((full_ie & ~0x7f) == Q931_FULL_IE(0, 0x80)) && ((full_ie & 0x70) != 0x20)) ? full_ie & ~0x0f : full_ie;
4368 
4369 	for (x = 0; x < ARRAY_LEN(ies); ++x)
4370 		if (ies[x].ie == base_ie) {
4371 			if (ies[x].dump)
4372 				ies[x].dump(full_ie, ctrl, ie, ielen(ie), prefix);
4373 			else
4374 				pri_message(ctrl, "%c IE: %s (len = %d)\n", prefix, ies[x].name, ielen(ie));
4375 			return;
4376 		}
4377 
4378 	pri_error(ctrl, "!! %c Unknown IE %d (cs%d, len = %d)\n", prefix, Q931_IE_IE(base_ie), Q931_IE_CODESET(base_ie), ielen(ie));
4379 }
4380 
4381 /*!
4382  * \brief Initialize the call record.
4383  *
4384  * \param link Q.921 link associated with the call.
4385  * \param call Q.931 call leg.
4386  * \param cr Call Reference identifier.
4387  *
4388  * \note The call record is assumed to already be memset() to zero.
4389  *
4390  * \return Nothing
4391  */
q931_init_call_record(struct q921_link * link,struct q931_call * call,int cr)4392 void q931_init_call_record(struct q921_link *link, struct q931_call *call, int cr)
4393 {
4394 	struct pri *ctrl;
4395 
4396 	call->cr = cr;
4397 	call->slotmap = -1;
4398 	call->channelno = -1;
4399 	if (cr != Q931_DUMMY_CALL_REFERENCE) {
4400 		call->newcall = 1;
4401 	}
4402 	call->ourcallstate = Q931_CALL_STATE_NULL;
4403 	call->peercallstate = Q931_CALL_STATE_NULL;
4404 	call->sugcallstate = Q931_CALL_STATE_NOT_SET;
4405 	call->ri = -1;
4406 	call->bc.transcapability = -1;
4407 	call->bc.transmoderate = -1;
4408 	call->bc.transmultiple = -1;
4409 	call->bc.userl1 = -1;
4410 	call->bc.userl2 = -1;
4411 	call->bc.userl3 = -1;
4412 	call->bc.rateadaption = -1;
4413 	call->progress = -1;
4414 	call->causecode = -1;
4415 	call->causeloc = -1;
4416 	call->cause = -1;
4417 	call->useruserprotocoldisc = -1;
4418 	call->aoc_units = -1;
4419 	call->changestatus = -1;
4420 	call->reversecharge = -1;
4421 	call->pri_winner = -1;
4422 	call->master_call = call;
4423 	q931_party_number_init(&call->redirection_number);
4424 	q931_party_address_init(&call->called);
4425 	q931_party_id_init(&call->local_id);
4426 	q931_party_id_init(&call->remote_id);
4427 	q931_party_number_init(&call->ani);
4428 	q931_party_redirecting_init(&call->redirecting);
4429 
4430 	/* The call is now attached to whoever called us */
4431 	ctrl = link->ctrl;
4432 	call->pri = ctrl;
4433 	if (cr == Q931_DUMMY_CALL_REFERENCE) {
4434 		/* Dummy calls are always for the given link. */
4435 		call->link = link;
4436 	} else if (BRI_TE_PTMP(ctrl)) {
4437 		/* Always uses the specific TEI link. */
4438 		call->link = ctrl->link.next;
4439 	} else {
4440 		call->link = link;
4441 	}
4442 }
4443 
4444 /*!
4445  * \internal
4446  * \brief Create a new call record.
4447  *
4448  * \param link Q.921 link associated with the call.
4449  * \param cr Call Reference identifier.
4450  *
4451  * \retval record on success.
4452  * \retval NULL on error.
4453  */
q931_create_call_record(struct q921_link * link,int cr)4454 static struct q931_call *q931_create_call_record(struct q921_link *link, int cr)
4455 {
4456 	struct q931_call *call;
4457 	struct q931_call *prev;
4458 	struct pri *ctrl;
4459 
4460 	ctrl = link->ctrl;
4461 
4462 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
4463 		pri_message(ctrl, "-- Making new call for cref %d\n", cr);
4464 	}
4465 
4466 	call = calloc(1, sizeof(*call));
4467 	if (!call) {
4468 		return NULL;
4469 	}
4470 
4471 	/* Initialize call structure. */
4472 	q931_init_call_record(link, call, cr);
4473 
4474 	/* Append to the list end */
4475 	if (*ctrl->callpool) {
4476 		/* Find the list end. */
4477 		for (prev = *ctrl->callpool; prev->next; prev = prev->next) {
4478 		}
4479 		prev->next = call;
4480 	} else {
4481 		/* List was empty. */
4482 		*ctrl->callpool = call;
4483 	}
4484 
4485 	return call;
4486 }
4487 
4488 /*!
4489  * \internal
4490  * \brief Find a call in the active call pool.
4491  *
4492  * \param link Q.921 link associated with the call.
4493  * \param cr Call Reference identifier.
4494  *
4495  * \retval call if found.
4496  * \retval NULL if not found.
4497  */
q931_find_call(struct q921_link * link,int cr)4498 static struct q931_call *q931_find_call(struct q921_link *link, int cr)
4499 {
4500 	struct q931_call *cur;
4501 	struct pri *ctrl;
4502 
4503 	if (cr == Q931_DUMMY_CALL_REFERENCE) {
4504 		return link->dummy_call;
4505 	}
4506 
4507 	ctrl = link->ctrl;
4508 
4509 	if (BRI_NT_PTMP(ctrl) && !(cr & Q931_CALL_REFERENCE_FLAG)) {
4510 		if (link->tei == Q921_TEI_GROUP) {
4511 			/* Broadcast TEI.  This is bad.  We are using the wrong link structure. */
4512 			pri_error(ctrl, "Looking for cref %d when using broadcast TEI.\n", cr);
4513 			return NULL;
4514 		}
4515 
4516 		/* We are looking for a call reference value that the other side allocated. */
4517 		for (cur = *ctrl->callpool; cur; cur = cur->next) {
4518 			if (cur->cr == cr && cur->link == link) {
4519 				/* Found existing call.  The call reference and link matched. */
4520 				break;
4521 			}
4522 		}
4523 	} else {
4524 		for (cur = *ctrl->callpool; cur; cur = cur->next) {
4525 			if (cur->cr == cr) {
4526 				/* Found existing call. */
4527 				switch (ctrl->switchtype) {
4528 				case PRI_SWITCH_GR303_EOC:
4529 				case PRI_SWITCH_GR303_TMC:
4530 					break;
4531 				default:
4532 					if (!ctrl->bri) {
4533 						/* The call is now attached to whoever called us */
4534 						cur->pri = ctrl;
4535 						cur->link = link;
4536 					}
4537 					break;
4538 				}
4539 				break;
4540 			}
4541 		}
4542 	}
4543 	return cur;
4544 }
4545 
q931_getcall(struct q921_link * link,int cr)4546 static struct q931_call *q931_getcall(struct q921_link *link, int cr)
4547 {
4548 	struct q931_call *cur;
4549 	struct pri *ctrl;
4550 
4551 	cur = q931_find_call(link, cr);
4552 	if (cur) {
4553 		return cur;
4554 	}
4555 	if (cr == Q931_DUMMY_CALL_REFERENCE) {
4556 		/* Do not create new dummy call records. */
4557 		return NULL;
4558 	}
4559 	ctrl = link->ctrl;
4560 	if (link->tei == Q921_TEI_GROUP
4561 		&& BRI_NT_PTMP(ctrl)) {
4562 		/* Do not create NT PTMP broadcast call records here. */
4563 		pri_error(ctrl,
4564 			"NT PTMP cannot create call record for cref %d on the broadcast TEI.\n", cr);
4565 		return NULL;
4566 	}
4567 
4568 	/* No call record exists, make a new one */
4569 	return q931_create_call_record(link, cr);
4570 }
4571 
4572 /*!
4573  * \brief Create a new call record for an outgoing call.
4574  *
4575  * \param ctrl D channel controller.
4576  *
4577  * \retval call on success.
4578  * \retval NULL on error.
4579  */
q931_new_call(struct pri * ctrl)4580 struct q931_call *q931_new_call(struct pri *ctrl)
4581 {
4582 	struct q931_call *cur;
4583 	struct q921_link *link;
4584 	int first_cref;
4585 	int cref;
4586 
4587 	/* Find a new call reference value. */
4588 	first_cref = ctrl->cref;
4589 	do {
4590 		cref = Q931_CALL_REFERENCE_FLAG | ctrl->cref;
4591 
4592 		/* Next call reference. */
4593 		++ctrl->cref;
4594 		if (!ctrl->bri) {
4595 			if (ctrl->cref > 32767) {
4596 				ctrl->cref = 1;
4597 			}
4598 		} else {
4599 			if (ctrl->cref > 127) {
4600 				ctrl->cref = 1;
4601 			}
4602 		}
4603 
4604 		/* Is the call reference value in use? */
4605 		for (cur = *ctrl->callpool; cur; cur = cur->next) {
4606 			if (cur->cr == cref) {
4607 				/* Yes it is in use. */
4608 				if (first_cref == ctrl->cref) {
4609 					/* All call reference values are in use! */
4610 					return NULL;
4611 				}
4612 				break;
4613 			}
4614 		}
4615 	} while (cur);
4616 
4617 	link = &ctrl->link;
4618 	return q931_create_call_record(link, cref);
4619 }
4620 
4621 static void stop_t303(struct q931_call *call);
4622 
stop_t312(struct q931_call * call)4623 static void stop_t312(struct q931_call *call)
4624 {
4625 	/* T312 should only be running on the master call */
4626 	pri_schedule_del(call->pri, call->t312_timer);
4627 	call->t312_timer = 0;
4628 }
4629 
cleanup_and_free_call(struct q931_call * cur)4630 static void cleanup_and_free_call(struct q931_call *cur)
4631 {
4632 	struct pri *ctrl;
4633 
4634 	ctrl = cur->pri;
4635 	pri_schedule_del(ctrl, cur->restart.timer);
4636 	pri_schedule_del(ctrl, cur->restart_tx.t316_timer);
4637 	pri_schedule_del(ctrl, cur->retranstimer);
4638 	pri_schedule_del(ctrl, cur->hold_timer);
4639 	pri_schedule_del(ctrl, cur->fake_clearing_timer);
4640 	stop_t303(cur);
4641 	stop_t312(cur);
4642 	pri_call_apdu_queue_cleanup(cur);
4643 	if (cur->cc.record) {
4644 		/* Unlink CC associations. */
4645 		if (cur->cc.record->original_call == cur) {
4646 			cur->cc.record->original_call = NULL;
4647 		}
4648 		if (cur->cc.record->signaling == cur) {
4649 			cur->cc.record->signaling = NULL;
4650 		}
4651 	}
4652 	free(cur);
4653 }
4654 
q931_get_subcall_count(struct q931_call * master)4655 int q931_get_subcall_count(struct q931_call *master)
4656 {
4657 	int count = 0;
4658 	int idx;
4659 
4660 	for (idx = 0; idx < ARRAY_LEN(master->subcalls); ++idx) {
4661 		if (master->subcalls[idx]) {
4662 			++count;
4663 		}
4664 	}
4665 
4666 	return count;
4667 }
4668 
4669 static int pri_internal_clear(struct q931_call *call);
4670 
4671 /*!
4672  * \brief Fake RELEASE for NT-PTMP initiated SETUPs w/o response
4673  *
4674  * \param param call Call is not a subcall call record.
4675  */
pri_fake_clearing(struct q931_call * call)4676 static void pri_fake_clearing(struct q931_call *call)
4677 {
4678 	struct pri *ctrl;
4679 
4680 	ctrl = call->pri;
4681 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
4682 		pri_message(ctrl, "Fake clearing.  cref:%d\n", call->cr);
4683 	}
4684 
4685 	/*
4686 	 * This does not need to be running since this is what we are
4687 	 * doing right now anyway.
4688 	 */
4689 	pri_schedule_del(ctrl, call->fake_clearing_timer);
4690 	call->fake_clearing_timer = 0;
4691 
4692 	if (call->cause == -1) {
4693 		/* Ensure that there is a resonable cause code. */
4694 		call->cause = PRI_CAUSE_NO_USER_RESPONSE;
4695 	}
4696 	if (pri_internal_clear(call) == Q931_RES_HAVEEVENT) {
4697 		ctrl->schedev = 1;
4698 	}
4699 }
4700 
pri_fake_clearing_expiry(void * data)4701 static void pri_fake_clearing_expiry(void *data)
4702 {
4703 	struct q931_call *master = data;
4704 
4705 	master->fake_clearing_timer = 0;
4706 	pri_fake_clearing(master);
4707 }
4708 
pri_create_fake_clearing(struct pri * ctrl,struct q931_call * master)4709 static void pri_create_fake_clearing(struct pri *ctrl, struct q931_call *master)
4710 {
4711 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
4712 		pri_message(ctrl, "Fake clearing requested.  cref:%d\n", master->cr);
4713 	}
4714 	pri_schedule_del(ctrl, master->fake_clearing_timer);
4715 	master->fake_clearing_timer = pri_schedule_event(ctrl, 0, pri_fake_clearing_expiry,
4716 		master);
4717 }
4718 
t312_expiry(void * data)4719 static void t312_expiry(void *data)
4720 {
4721 	struct q931_call *master = data;
4722 	struct pri *ctrl;
4723 
4724 	ctrl = master->pri;
4725 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
4726 		pri_message(ctrl, "T312 timed out.  cref:%d\n", master->cr);
4727 	}
4728 
4729 	master->t312_timer = 0;
4730 	if (!q931_get_subcall_count(master)) {
4731 		/* No subcalls remain. */
4732 		switch (master->ourcallstate) {
4733 		case Q931_CALL_STATE_CALL_ABORT:
4734 			/* We can destroy the master. */
4735 			q931_destroycall(ctrl, master);
4736 			break;
4737 		default:
4738 			/* Let the upper layer know about the lack of call prospects. */
4739 			UPDATE_OURCALLSTATE(ctrl, master, Q931_CALL_STATE_CALL_ABORT);
4740 			pri_fake_clearing(master);
4741 			break;
4742 		}
4743 	}
4744 }
4745 
4746 /*! \param master Master call record for PTMP NT call. */
start_t312(struct q931_call * master)4747 static void start_t312(struct q931_call *master)
4748 {
4749 	struct pri *ctrl;
4750 
4751 	ctrl = master->pri;
4752 	pri_schedule_del(ctrl, master->t312_timer);
4753 	master->t312_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T312],
4754 		t312_expiry, master);
4755 }
4756 
4757 /*!
4758  * \internal
4759  * \brief Helper function to destroy a subcall.
4760  *
4761  * \param master Q.931 master call of subcall to destroy.
4762  * \param idx Master subcall index to destroy.
4763  *
4764  * \return Nothing
4765  */
q931_destroy_subcall(struct q931_call * master,int idx)4766 static void q931_destroy_subcall(struct q931_call *master, int idx)
4767 {
4768 	struct pri *ctrl = master->pri;
4769 
4770 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
4771 		pri_message(ctrl, "Destroying subcall %p of call %p at %d\n",
4772 			master->subcalls[idx], master, idx);
4773 	}
4774 	cleanup_and_free_call(master->subcalls[idx]);
4775 	if (master->pri_winner == idx) {
4776 		/* This was the winning subcall. */
4777 		master->pri_winner = -1;
4778 	}
4779 	master->subcalls[idx] = NULL;
4780 }
4781 
q931_destroycall(struct pri * ctrl,q931_call * c)4782 void q931_destroycall(struct pri *ctrl, q931_call *c)
4783 {
4784 	struct q931_call *cur;
4785 	struct q931_call *prev;
4786 	struct q931_call *slave;
4787 	int i;
4788 	int slavesleft;
4789 
4790 	if (q931_is_dummy_call(c)) {
4791 		/* Cannot destroy the dummy call. */
4792 		return;
4793 	}
4794 	if (c->master_call != c) {
4795 		slave = c;
4796 		c = slave->master_call;
4797 	} else {
4798 		slave = NULL;
4799 	}
4800 
4801 	prev = NULL;
4802 	cur = *ctrl->callpool;
4803 	while (cur) {
4804 		if (cur == c) {
4805 			if (slave) {
4806 				/* Destroying a slave. */
4807 				for (i = 0; i < ARRAY_LEN(cur->subcalls); ++i) {
4808 					if (cur->subcalls[i] == slave) {
4809 						q931_destroy_subcall(cur, i);
4810 						break;
4811 					}
4812 				}
4813 
4814 				/* How many slaves are left? */
4815 				slavesleft = 0;
4816 				for (i = 0; i < ARRAY_LEN(cur->subcalls); ++i) {
4817 					if (cur->subcalls[i]) {
4818 						if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
4819 							pri_message(ctrl, "Subcall still present at %d\n", i);
4820 						}
4821 						++slavesleft;
4822 					}
4823 				}
4824 
4825 				if (slavesleft || cur->t312_timer || cur->master_hanging_up) {
4826 					return;
4827 				}
4828 
4829 				/* No slaves left. */
4830 				switch (cur->ourcallstate) {
4831 				case Q931_CALL_STATE_CALL_ABORT:
4832 					break;
4833 				default:
4834 					/* Let the upper layer know about the call clearing. */
4835 					UPDATE_OURCALLSTATE(ctrl, cur, Q931_CALL_STATE_CALL_ABORT);
4836 					pri_create_fake_clearing(ctrl, cur);
4837 					return;
4838 				}
4839 
4840 				/* We can try to destroy the master now. */
4841 			} else {
4842 				/* Destroy any slaves that may be present as well. */
4843 				slavesleft = 0;
4844 				for (i = 0; i < ARRAY_LEN(cur->subcalls); ++i) {
4845 					if (cur->subcalls[i]) {
4846 						++slavesleft;
4847 						q931_destroy_subcall(cur, i);
4848 					}
4849 				}
4850 			}
4851 
4852 			if (cur->fake_clearing_timer) {
4853 				/*
4854 				 * Must wait for the fake clearing to complete before destroying
4855 				 * the master call record.
4856 				 */
4857 				return;
4858 			}
4859 			if (slavesleft) {
4860 				/* This is likely not good. */
4861 				pri_error(ctrl,
4862 					"Destroyed %d subcalls unconditionally with the master.  cref:%d\n",
4863 					slavesleft, cur->cr);
4864 			}
4865 
4866 			/* Master call or normal call destruction. */
4867 			if (prev)
4868 				prev->next = cur->next;
4869 			else
4870 				*ctrl->callpool = cur->next;
4871 			if (ctrl->debug & PRI_DEBUG_Q931_STATE)
4872 				pri_message(ctrl,
4873 					"Destroying call %p, ourstate %s, peerstate %s, hold-state %s\n",
4874 					cur,
4875 					q931_call_state_str(cur->ourcallstate),
4876 					q931_call_state_str(cur->peercallstate),
4877 					q931_hold_state_str(cur->hold_state));
4878 			cleanup_and_free_call(cur);
4879 			return;
4880 		}
4881 		prev = cur;
4882 		cur = cur->next;
4883 	}
4884 	pri_error(ctrl, "Can't destroy call %p cref:%d!\n", c, c->cr);
4885 }
4886 
add_ie(struct pri * ctrl,q931_call * call,int msgtype,int ie,q931_ie * iet,int maxlen,int * codeset)4887 static int add_ie(struct pri *ctrl, q931_call *call, int msgtype, int ie, q931_ie *iet, int maxlen, int *codeset)
4888 {
4889 	unsigned int x;
4890 	int res, total_res;
4891 	int have_shift;
4892 	int ies_count, order;
4893 
4894 	for (x = 0; x < ARRAY_LEN(ies); ++x) {
4895 		if (ies[x].ie == ie) {
4896 			/* This is our baby */
4897 			if (ies[x].transmit) {
4898 				/* Prepend with CODE SHIFT IE if required */
4899 				if (*codeset != Q931_IE_CODESET(ies[x].ie)) {
4900 					/* Locking shift to codeset 0 isn't possible */
4901 					iet->ie = Q931_IE_CODESET(ies[x].ie) | (Q931_IE_CODESET(ies[x].ie) ? Q931_LOCKING_SHIFT : Q931_NON_LOCKING_SHIFT);
4902 					have_shift = 1;
4903 					iet = (q931_ie *)((char *)iet + 1);
4904 					maxlen--;
4905 				}
4906 				else
4907 					have_shift = 0;
4908 				ies_count = ies[x].max_count;
4909 				if (ies_count == 0)
4910 					ies_count = INT_MAX;
4911 				order = 0;
4912 				total_res = 0;
4913 				do {
4914 					iet->ie = ie;
4915 					res = ies[x].transmit(ie, ctrl, call, msgtype, iet, maxlen, ++order);
4916 					/* Error if res < 0 or ignored if res == 0 */
4917 					if (res < 0)
4918 						return res;
4919 					if (res > 0) {
4920 						if ((iet->ie & 0x80) == 0) /* Multibyte IE */
4921 							iet->len = res - 2;
4922 						if (msgtype == Q931_SETUP && *codeset == 0) {
4923 							switch (iet->ie) {
4924 							case Q931_BEARER_CAPABILITY:
4925 								if (!(call->cc.saved_ie_flags & CC_SAVED_IE_BC)) {
4926 									/* Save first BC ie contents for possible CC. */
4927 									call->cc.saved_ie_flags |= CC_SAVED_IE_BC;
4928 									q931_append_ie_contents(&call->cc.saved_ie_contents,
4929 										iet);
4930 								}
4931 								break;
4932 							case Q931_LOW_LAYER_COMPAT:
4933 								if (!(call->cc.saved_ie_flags & CC_SAVED_IE_LLC)) {
4934 									/* Save first LLC ie contents for possible CC. */
4935 									call->cc.saved_ie_flags |= CC_SAVED_IE_LLC;
4936 									q931_append_ie_contents(&call->cc.saved_ie_contents,
4937 										iet);
4938 								}
4939 								break;
4940 							case Q931_HIGH_LAYER_COMPAT:
4941 								if (!(call->cc.saved_ie_flags & CC_SAVED_IE_HLC)) {
4942 									/* Save first HLC ie contents for possible CC. */
4943 									call->cc.saved_ie_flags |= CC_SAVED_IE_HLC;
4944 									q931_append_ie_contents(&call->cc.saved_ie_contents,
4945 										iet);
4946 								}
4947 								break;
4948 							default:
4949 								break;
4950 							}
4951 						}
4952 						total_res += res;
4953 						maxlen -= res;
4954 						iet = (q931_ie *)((char *)iet + res);
4955 					}
4956 				} while (res > 0 && order < ies_count);
4957 				if (have_shift && total_res) {
4958 					if (Q931_IE_CODESET(ies[x].ie))
4959 						*codeset = Q931_IE_CODESET(ies[x].ie);
4960 					return total_res + 1; /* Shift is single-byte IE */
4961 				}
4962 				return total_res;
4963 			} else {
4964 				pri_error(ctrl, "!! Don't know how to add IE %d (%s)\n", ie, ie2str(ie));
4965 				return -1;
4966 			}
4967 		}
4968 	}
4969 	pri_error(ctrl, "!! Unknown IE %d (%s)\n", ie, ie2str(ie));
4970 	return -1;
4971 }
4972 
disc2str(int disc)4973 static char *disc2str(int disc)
4974 {
4975 	static struct msgtype discs[] = {
4976 		{ Q931_PROTOCOL_DISCRIMINATOR, "Q.931" },
4977 		{ GR303_PROTOCOL_DISCRIMINATOR, "GR-303" },
4978 		{ MAINTENANCE_PROTOCOL_DISCRIMINATOR_1, "AT&T Maintenance" },
4979 		{ MAINTENANCE_PROTOCOL_DISCRIMINATOR_2, "New AT&T Maintenance" },
4980 	};
4981 	return code2str(disc, discs, sizeof(discs) / sizeof(discs[0]));
4982 }
4983 
4984 /*!
4985  * \internal
4986  * \brief Dump the Q.931 message header.
4987  *
4988  * \param ctrl D channel controller.
4989  * \param tei TEI the packet is associated with.
4990  * \param h Q.931 packet contents/header.
4991  * \param len Received length of the Q.931 packet.
4992  * \param c Message direction prefix character.
4993  *
4994  * \retval 0 on success.
4995  * \retval -1 on error.
4996  */
q931_dump_header(struct pri * ctrl,int tei,q931_h * h,int len,char c)4997 static int q931_dump_header(struct pri *ctrl, int tei, q931_h *h, int len, char c)
4998 {
4999 	q931_mh *mh;
5000 	int cref;
5001 
5002 	pri_message(ctrl, "%c Protocol Discriminator: %s (%d)  len=%d\n", c, disc2str(h->pd), h->pd, len);
5003 
5004 	if (len < 2 || len < 2 + h->crlen) {
5005 		pri_message(ctrl, "%c Message too short for call reference. len=%d\n",
5006 			c, len);
5007 		return -1;
5008 	}
5009 	cref = q931_cr(h);
5010 	pri_message(ctrl, "%c TEI=%d Call Ref: len=%2d (reference %d/0x%X) (%s)\n",
5011 		c, tei, h->crlen, cref & ~Q931_CALL_REFERENCE_FLAG,
5012 		cref & ~Q931_CALL_REFERENCE_FLAG, (cref == Q931_DUMMY_CALL_REFERENCE)
5013 			? "Dummy"
5014 			: (cref & Q931_CALL_REFERENCE_FLAG)
5015 				? "Sent to originator" : "Sent from originator");
5016 
5017 	if (len < 3 + h->crlen) {
5018 		pri_message(ctrl, "%c Message too short for supported protocols. len=%d\n",
5019 			c, len);
5020 		return -1;
5021 	}
5022 
5023 	/* Message header begins at the end of the call reference number */
5024 	mh = (q931_mh *)(h->contents + h->crlen);
5025 	switch (h->pd) {
5026 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_1:
5027 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_2:
5028 		pri_message(ctrl, "%c Message Type: %s (%d)\n", c, maintenance_msg2str(mh->msg, h->pd), mh->msg);
5029 		break;
5030 	default:
5031 		/* Unknown protocol discriminator but we will treat it as Q.931 anyway. */
5032 	case GR303_PROTOCOL_DISCRIMINATOR:
5033 	case Q931_PROTOCOL_DISCRIMINATOR:
5034 		pri_message(ctrl, "%c Message Type: %s (%d)\n", c, msg2str(mh->msg), mh->msg);
5035 		break;
5036 	}
5037 
5038 	return 0;
5039 }
5040 
5041 /*!
5042  * \internal
5043  * \brief Q.931 is passing this message to Q.921 debug indication.
5044  *
5045  * \param ctrl D channel controller.
5046  * \param tei TEI the packet is associated with.
5047  * \param h Q.931 packet contents/header.
5048  * \param len Received length of the Q.931 packet
5049  *
5050  * \return Nothing
5051  */
q931_to_q921_passing_dump(struct pri * ctrl,int tei,q931_h * h,int len)5052 static void q931_to_q921_passing_dump(struct pri *ctrl, int tei, q931_h *h, int len)
5053 {
5054 	char c;
5055 
5056 	c = '>';
5057 
5058 	pri_message(ctrl, "\n");
5059 	pri_message(ctrl, "%c DL-DATA request\n", c);
5060 	q931_dump_header(ctrl, tei, h, len, c);
5061 }
5062 
5063 /*!
5064  * \brief Debug dump the given Q.931 packet.
5065  *
5066  * \param ctrl D channel controller.
5067  * \param tei TEI the packet is associated with.
5068  * \param h Q.931 packet contents/header.
5069  * \param len Received length of the Q.931 packet
5070  * \param txrx TRUE if packet is transmitted/outgoing
5071  *
5072  * \return Nothing
5073  */
q931_dump(struct pri * ctrl,int tei,q931_h * h,int len,int txrx)5074 void q931_dump(struct pri *ctrl, int tei, q931_h *h, int len, int txrx)
5075 {
5076 	q931_mh *mh;
5077 	char c;
5078 	int x;
5079 	int r;
5080 	int cur_codeset;
5081 	int codeset;
5082 
5083 	c = txrx ? '>' : '<';
5084 
5085 	if (!(ctrl->debug & (PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW))) {
5086 		/* Put out a blank line if Q.921 is not dumping. */
5087 		pri_message(ctrl, "\n");
5088 	}
5089 	if (q931_dump_header(ctrl, tei, h, len, c)) {
5090 		return;
5091 	}
5092 
5093 	/* Drop length of header, including call reference */
5094 	mh = (q931_mh *)(h->contents + h->crlen);
5095 	len -= (h->crlen + 3);
5096 	codeset = cur_codeset = 0;
5097 	for (x = 0; x < len; x += r) {
5098 		r = ielen_checked((q931_ie *) (mh->data + x), len - x);
5099 		if (r < 0) {
5100 			/* We have garbage on the end of the packet. */
5101 			pri_message(ctrl, "Not enough room for codeset:%d ie:%d(%02x)\n", cur_codeset,
5102 				mh->data[x], mh->data[x]);
5103 			break;
5104 		}
5105 		q931_dumpie(ctrl, cur_codeset, (q931_ie *)(mh->data + x), c);
5106 		switch (mh->data[x] & 0xf8) {
5107 		case Q931_LOCKING_SHIFT:
5108 			if ((mh->data[x] & 7) > 0)
5109 				codeset = cur_codeset = mh->data[x] & 7;
5110 			break;
5111 		case Q931_NON_LOCKING_SHIFT:
5112 			cur_codeset = mh->data[x] & 7;
5113 			break;
5114 		default:
5115 			/* Reset temporary codeset change */
5116 			cur_codeset = codeset;
5117 			break;
5118 		}
5119 	}
5120 }
5121 
q931_handle_ie(int codeset,struct pri * ctrl,q931_call * c,int msg,q931_ie * ie)5122 static int q931_handle_ie(int codeset, struct pri *ctrl, q931_call *c, int msg, q931_ie *ie)
5123 {
5124 	unsigned int x;
5125 	int full_ie = Q931_FULL_IE(codeset, ie->ie);
5126 
5127 	if (ctrl->debug & PRI_DEBUG_Q931_STATE)
5128 		pri_message(ctrl, "-- Processing IE %d (cs%d, %s)\n", ie->ie, codeset, ie2str(full_ie));
5129 	if (msg == Q931_SETUP && codeset == 0) {
5130 		switch (ie->ie) {
5131 		case Q931_BEARER_CAPABILITY:
5132 			if (!(c->cc.saved_ie_flags & CC_SAVED_IE_BC)) {
5133 				/* Save first BC ie contents for possible CC. */
5134 				c->cc.saved_ie_flags |= CC_SAVED_IE_BC;
5135 				q931_append_ie_contents(&c->cc.saved_ie_contents, ie);
5136 			}
5137 			break;
5138 		case Q931_LOW_LAYER_COMPAT:
5139 			if (!(c->cc.saved_ie_flags & CC_SAVED_IE_LLC)) {
5140 				/* Save first LLC ie contents for possible CC. */
5141 				c->cc.saved_ie_flags |= CC_SAVED_IE_LLC;
5142 				q931_append_ie_contents(&c->cc.saved_ie_contents, ie);
5143 			}
5144 			break;
5145 		case Q931_HIGH_LAYER_COMPAT:
5146 			if (!(c->cc.saved_ie_flags & CC_SAVED_IE_HLC)) {
5147 				/* Save first HLC ie contents for possible CC. */
5148 				c->cc.saved_ie_flags |= CC_SAVED_IE_HLC;
5149 				q931_append_ie_contents(&c->cc.saved_ie_contents, ie);
5150 			}
5151 			break;
5152 		default:
5153 			break;
5154 		}
5155 	}
5156 	for (x = 0; x < ARRAY_LEN(ies); ++x) {
5157 		if (full_ie == ies[x].ie) {
5158 			if (ies[x].receive)
5159 				return ies[x].receive(full_ie, ctrl, c, msg, ie, ielen(ie));
5160 			else {
5161 				if (ctrl->debug & PRI_DEBUG_Q931_ANOMALY)
5162 					pri_message(ctrl, "!! No handler for IE %d (cs%d, %s)\n", ie->ie, codeset, ie2str(full_ie));
5163 				return -1;
5164 			}
5165 		}
5166 	}
5167 	pri_message(ctrl, "!! Unknown IE %d (cs%d)\n", ie->ie, codeset);
5168 	return -1;
5169 }
5170 
5171 /* Returns header and message header and modifies length in place */
init_header(struct pri * ctrl,q931_call * call,unsigned char * buf,q931_h ** hb,q931_mh ** mhb,int * len,int protodisc)5172 static void init_header(struct pri *ctrl, q931_call *call, unsigned char *buf, q931_h **hb, q931_mh **mhb, int *len, int protodisc)
5173 {
5174 	q931_h *h = (q931_h *) buf;
5175 	q931_mh *mh;
5176 	unsigned crv;
5177 
5178 	if (protodisc) {
5179 		h->pd = protodisc;
5180 	} else {
5181 		h->pd = ctrl->protodisc;
5182 	}
5183 	h->x0 = 0;		/* Reserved 0 */
5184 	if (q931_is_dummy_call(call)) {
5185 		h->crlen = 0;
5186 	} else if (!ctrl->bri) {
5187 		/* Two bytes of Call Reference. */
5188 		h->crlen = 2;
5189 		if (ctrl->link.next) {
5190 			/* On GR-303, Q931_CALL_REFERENCE_FLAG is always 0 */
5191 			crv = ((unsigned) call->cr) & ~Q931_CALL_REFERENCE_FLAG;
5192 		} else {
5193 			/* Invert the Q931_CALL_REFERENCE_FLAG to make it from our sense */
5194 			crv = ((unsigned) call->cr) ^ Q931_CALL_REFERENCE_FLAG;
5195 		}
5196 		h->crv[0] = (crv >> 8) & 0xff;
5197 		h->crv[1] = crv & 0xff;
5198 	} else {
5199 		h->crlen = 1;
5200 		/* Invert the Q931_CALL_REFERENCE_FLAG to make it from our sense */
5201 		crv = ((unsigned) call->cr) ^ Q931_CALL_REFERENCE_FLAG;
5202 		h->crv[0] = ((crv >> 8) & 0x80) | (crv & 0x7f);
5203 	}
5204 	*hb = h;
5205 
5206 	*len -= 3;/* Protocol discriminator, call reference length, message type id */
5207 	*len -= h->crlen;
5208 
5209 	mh = (q931_mh *) (h->contents + h->crlen);
5210 	mh->f = 0;
5211 	*mhb = mh;
5212 }
5213 
q931_xmit(struct q921_link * link,q931_h * h,int len,int cr,int uiframe)5214 static void q931_xmit(struct q921_link *link, q931_h *h, int len, int cr, int uiframe)
5215 {
5216 	struct pri *ctrl;
5217 
5218 	ctrl = link->ctrl;
5219 	ctrl->q931_txcount++;
5220 	if (uiframe) {
5221 		if (link->tei != Q921_TEI_GROUP) {
5222 			pri_error(ctrl, "Huh?! Attempting to send UI-frame on TEI %d\n", link->tei);
5223 			return;
5224 		}
5225 		q921_transmit_uiframe(link, h, len);
5226 		if (ctrl->debug & PRI_DEBUG_Q931_DUMP) {
5227 			/*
5228 			 * The transmit operation might dump the Q.921 header, so logging
5229 			 * the Q.931 message body after the transmit puts the sections of
5230 			 * the message in the right order in the log,
5231 			 */
5232 			q931_dump(ctrl, link->tei, h, len, 1);
5233 		}
5234 	} else {
5235 		/*
5236 		 * Indicate passing the Q.931 message to Q.921 first.  Q.921 may
5237 		 * have to request a TEI or bring the connection up before it can
5238 		 * actually send the message.  Therefore, the Q.931 message may
5239 		 * actually get sent a few seconds later.  Q.921 will dump the
5240 		 * Q.931 message as appropriate at that time.
5241 		 */
5242 		if (ctrl->debug & PRI_DEBUG_Q931_DUMP) {
5243 			q931_to_q921_passing_dump(ctrl, link->tei, h, len);
5244 		}
5245 		q921_transmit_iframe(link, h, len, cr);
5246 	}
5247 }
5248 
5249 /*!
5250  * \internal
5251  * \brief Build and send the requested message.
5252  *
5253  * \param ctrl D channel controller.
5254  * \param call Q.931 call leg
5255  * \param msgtype Q.931 message type to build.
5256  * \param ies List of ie's to put in the message.
5257  *
5258  * \note The ie's in the ie list must be in numerical order.
5259  * See Q.931 section 4.5.1 coding rules.
5260  *
5261  * \retval 0 on success.
5262  * \retval -1 on error.
5263  */
send_message(struct pri * ctrl,q931_call * call,int msgtype,int ies[])5264 static int send_message(struct pri *ctrl, q931_call *call, int msgtype, int ies[])
5265 {
5266 	unsigned char buf[1024];
5267 	q931_h *h;
5268 	q931_mh *mh;
5269 	int len;
5270 	int res;
5271 	int offset=0;
5272 	int x;
5273 	int codeset;
5274 	int uiframe;
5275 
5276 	if (call->outboundbroadcast && call->master_call == call && msgtype != Q931_SETUP) {
5277 		pri_error(ctrl,
5278 			"Attempting to use master call record to send %s on BRI PTMP NT %p\n",
5279 			msg2str(msgtype), ctrl);
5280 		return -1;
5281 	}
5282 
5283 	if (!call->link) {
5284 		pri_error(ctrl,
5285 			"Call w/ cref:%d is not associated with a link.  TEI removed due to error conditions?\n",
5286 			call->cr);
5287 		return -1;
5288 	}
5289 
5290 	memset(buf, 0, sizeof(buf));
5291 	len = sizeof(buf);
5292 	init_header(ctrl, call, buf, &h, &mh, &len, (msgtype >> 8));
5293 	mh->msg = msgtype & 0x00ff;
5294 	x=0;
5295 	codeset = 0;
5296 	while(ies[x] > -1) {
5297 		res = add_ie(ctrl, call, mh->msg, ies[x], (q931_ie *)(mh->data + offset), len, &codeset);
5298 		if (res < 0) {
5299 			pri_error(ctrl, "!! Unable to add IE '%s'\n", ie2str(ies[x]));
5300 			return -1;
5301 		}
5302 
5303 		offset += res;
5304 		len -= res;
5305 		x++;
5306 	}
5307 	/* Invert the logic */
5308 	len = sizeof(buf) - len;
5309 
5310 	uiframe = 0;
5311 	if (BRI_NT_PTMP(ctrl)) {
5312 		/* NT PTMP is the only mode that can broadcast Q.931 messages. */
5313 		switch (msgtype) {
5314 		case Q931_SETUP:
5315 			/*
5316 			 * For NT-PTMP mode, we need to check the following:
5317 			 * MODE = NT-PTMP
5318 			 * MESSAGE = SETUP
5319 			 *
5320 			 * If those are true, we need to send the SETUP in a UI frame
5321 			 * instead of an I-frame.
5322 			 */
5323 			uiframe = 1;
5324 			break;
5325 		case Q931_FACILITY:
5326 			if (call->link->tei == Q921_TEI_GROUP) {
5327 				/* Broadcast TEI. */
5328 				if (q931_is_dummy_call(call)) {
5329 					/*
5330 					 * This is a FACILITY message on the dummy call reference
5331 					 * for the broadcast TEI.
5332 					 */
5333 					uiframe = 1;
5334 				} else {
5335 					pri_error(ctrl,
5336 						"Attempting to broadcast %s on cref %d\n",
5337 						msg2str(msgtype), call->cr);
5338 					return -1;
5339 				}
5340 			}
5341 			break;
5342 		default:
5343 			break;
5344 		}
5345 		if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
5346 			/* This message is only interesting for NT PTMP mode. */
5347 			pri_message(ctrl,
5348 				"Sending message for call %p on call->link: %p with TEI/SAPI %d/%d\n",
5349 				call, call->link, call->link->tei, call->link->sapi);
5350 		}
5351 	}
5352 	q931_xmit(call->link, h, len, 1, uiframe);
5353 	call->acked = 1;
5354 	return 0;
5355 }
5356 
5357 static int maintenance_service_ies[] = { Q931_IE_CHANGE_STATUS, Q931_CHANNEL_IDENT, -1 };
5358 
maintenance_service_ack(struct pri * ctrl,q931_call * c)5359 static int maintenance_service_ack(struct pri *ctrl, q931_call *c)
5360 {
5361 	int pd = MAINTENANCE_PROTOCOL_DISCRIMINATOR_1;
5362 	int mt = ATT_SERVICE_ACKNOWLEDGE;
5363 
5364 	if (ctrl->switchtype == PRI_SWITCH_NI2) {
5365 		pd = MAINTENANCE_PROTOCOL_DISCRIMINATOR_2;
5366 		mt = NATIONAL_SERVICE_ACKNOWLEDGE;
5367 	}
5368 	return send_message(ctrl, c, (pd << 8) | mt, maintenance_service_ies);
5369 }
5370 
5371 /*!
5372  * \note Maintenance service messages only supported in PRI mode.
5373  */
maintenance_service(struct pri * ctrl,int span,int channel,int changestatus)5374 int maintenance_service(struct pri *ctrl, int span, int channel, int changestatus)
5375 {
5376 	struct q931_call *c;
5377 	int pd = MAINTENANCE_PROTOCOL_DISCRIMINATOR_1;
5378 	int mt = ATT_SERVICE;
5379 
5380 	c = q931_getcall(&ctrl->link, 0 | Q931_CALL_REFERENCE_FLAG);
5381 	if (!c) {
5382 		return -1;
5383 	}
5384 	if (channel > -1) {
5385 		c->channelno = channel & 0xff;
5386 		c->chanflags = FLAG_EXCLUSIVE;
5387 	} else {
5388 		c->channelno = channel;
5389 		c->chanflags = FLAG_EXCLUSIVE | FLAG_WHOLE_INTERFACE;
5390 	}
5391 	c->ds1no = span;
5392 	c->ds1explicit = 0;
5393 	c->changestatus = changestatus;
5394 
5395 	if (ctrl->switchtype == PRI_SWITCH_NI2) {
5396 		pd = MAINTENANCE_PROTOCOL_DISCRIMINATOR_2;
5397 		mt = NATIONAL_SERVICE;
5398 	}
5399 	return send_message(ctrl, c, (pd << 8) | mt, maintenance_service_ies);
5400 }
5401 
q931_status(struct pri * ctrl,q931_call * call,int cause)5402 static int q931_status(struct pri *ctrl, q931_call *call, int cause)
5403 {
5404 	static int status_ies[] = {
5405 		Q931_CAUSE,
5406 		Q931_IE_CALL_STATE,
5407 		-1
5408 	};
5409 
5410 	call->cause = cause;
5411 	call->causecode = CODE_CCITT;
5412 	call->causeloc = LOC_USER;
5413 	return send_message(ctrl, call, Q931_STATUS, status_ies);
5414 }
5415 
q931_information(struct pri * ctrl,q931_call * c,char digit)5416 int q931_information(struct pri *ctrl, q931_call *c, char digit)
5417 {
5418 	static int information_ies[] = {
5419 		Q931_CALLED_PARTY_NUMBER,
5420 		-1
5421 	};
5422 
5423 	c->overlap_digits[0] = digit;
5424 	c->overlap_digits[1] = '\0';
5425 
5426 	/*
5427 	 * Since we are doing overlap dialing now, we need to accumulate
5428 	 * the digits into call->called.number.str.
5429 	 */
5430 	c->called.number.valid = 1;
5431 	if (strlen(c->called.number.str) < sizeof(c->called.number.str) - 1) {
5432 		/* There is enough room for the new digit. */
5433 		strcat(c->called.number.str, c->overlap_digits);
5434 	}
5435 
5436 	return send_message(ctrl, c, Q931_INFORMATION, information_ies);
5437 }
5438 
5439 /*!
5440  * \internal
5441  * \brief Actually send display text if in the right call state.
5442  *
5443  * \param ctrl D channel controller.
5444  * \param call Q.931 call leg
5445  * \param display Display text to send.
5446  *
5447  * \retval 0 on success.
5448  * \retval -1 on error.
5449  */
q931_display_text_helper(struct pri * ctrl,struct q931_call * call,const struct pri_subcmd_display_txt * display)5450 static int q931_display_text_helper(struct pri *ctrl, struct q931_call *call, const struct pri_subcmd_display_txt *display)
5451 {
5452 	int status;
5453 	static int information_display_ies[] = {
5454 		Q931_DISPLAY,
5455 		-1
5456 	};
5457 
5458 	switch (call->ourcallstate) {
5459 	case Q931_CALL_STATE_OVERLAP_SENDING:
5460 	case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
5461 	case Q931_CALL_STATE_CALL_DELIVERED:
5462 	case Q931_CALL_STATE_CALL_RECEIVED:
5463 	case Q931_CALL_STATE_CONNECT_REQUEST:
5464 	case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
5465 	case Q931_CALL_STATE_ACTIVE:
5466 	case Q931_CALL_STATE_OVERLAP_RECEIVING:
5467 		call->display.text = (unsigned char *) display->text;
5468 		call->display.full_ie = 0;
5469 		call->display.length = display->length;
5470 		call->display.char_set = display->char_set;
5471 		status = send_message(ctrl, call, Q931_INFORMATION, information_display_ies);
5472 		q931_display_clear(call);
5473 		break;
5474 	default:
5475 		status = 0;
5476 		break;
5477 	}
5478 
5479 	return status;
5480 }
5481 
5482 /*!
5483  * \brief Send display text during a call.
5484  *
5485  * \param ctrl D channel controller.
5486  * \param call Q.931 call leg
5487  * \param display Display text to send.
5488  *
5489  * \retval 0 on success.
5490  * \retval -1 on error.
5491  */
q931_display_text(struct pri * ctrl,struct q931_call * call,const struct pri_subcmd_display_txt * display)5492 int q931_display_text(struct pri *ctrl, struct q931_call *call, const struct pri_subcmd_display_txt *display)
5493 {
5494 	int status;
5495 	unsigned idx;
5496 	struct q931_call *subcall;
5497 
5498 	if ((ctrl->display_flags.send & (PRI_DISPLAY_OPTION_BLOCK | PRI_DISPLAY_OPTION_TEXT))
5499 		!= PRI_DISPLAY_OPTION_TEXT) {
5500 		/* Not enabled */
5501 		return 0;
5502 	}
5503 	if (call->outboundbroadcast && call->master_call == call) {
5504 		status = 0;
5505 		for (idx = 0; idx < ARRAY_LEN(call->subcalls); ++idx) {
5506 			subcall = call->subcalls[idx];
5507 			if (subcall && q931_display_text_helper(ctrl, subcall, display)) {
5508 				status = -1;
5509 			}
5510 		}
5511 	} else {
5512 		status = q931_display_text_helper(ctrl, call, display);
5513 	}
5514 	return status;
5515 }
5516 
5517 
5518 static int keypad_facility_ies[] = { Q931_IE_KEYPAD_FACILITY, -1 };
5519 
q931_keypad_facility(struct pri * ctrl,q931_call * call,const char * digits)5520 int q931_keypad_facility(struct pri *ctrl, q931_call *call, const char *digits)
5521 {
5522 	libpri_copy_string(call->keypad_digits, digits, sizeof(call->keypad_digits));
5523 	return send_message(ctrl, call, Q931_INFORMATION, keypad_facility_ies);
5524 }
5525 
5526 static int restart_ack_ies[] = { Q931_CHANNEL_IDENT, Q931_RESTART_INDICATOR, -1 };
5527 
restart_ack(struct pri * ctrl,q931_call * c)5528 static int restart_ack(struct pri *ctrl, q931_call *c)
5529 {
5530 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
5531 	c->peercallstate = Q931_CALL_STATE_NULL;
5532 	return send_message(ctrl, c, Q931_RESTART_ACKNOWLEDGE, restart_ack_ies);
5533 }
5534 
q931_facility(struct pri * ctrl,struct q931_call * call)5535 int q931_facility(struct pri *ctrl, struct q931_call *call)
5536 {
5537 	static int facility_ies[] = {
5538 		Q931_IE_FACILITY,
5539 		-1
5540 	};
5541 
5542 	return send_message(ctrl, call, Q931_FACILITY, facility_ies);
5543 }
5544 
5545 /*!
5546  * \brief Send a FACILITY message with the called party number and subaddress ies.
5547  *
5548  * \param ctrl D channel controller.
5549  * \param call Call leg to send message over.
5550  * \param called Called party information to send.
5551  *
5552  * \note
5553  * This function can only be used by the dummy call because the call's called
5554  * structure is used by normal calls to contain persistent information.
5555  *
5556  * \retval 0 on success.
5557  * \retval -1 on error.
5558  */
q931_facility_called(struct pri * ctrl,struct q931_call * call,const struct q931_party_id * called)5559 int q931_facility_called(struct pri *ctrl, struct q931_call *call, const struct q931_party_id *called)
5560 {
5561 	static int facility_called_ies[] = {
5562 		Q931_IE_FACILITY,
5563 		Q931_CALLED_PARTY_NUMBER,
5564 		Q931_CALLED_PARTY_SUBADDR,
5565 		-1
5566 	};
5567 
5568 	q931_party_id_copy_to_address(&call->called, called);
5569 	libpri_copy_string(call->overlap_digits, call->called.number.str,
5570 		sizeof(call->overlap_digits));
5571 	return send_message(ctrl, call, Q931_FACILITY, facility_called_ies);
5572 }
5573 
q931_facility_display_name(struct pri * ctrl,struct q931_call * call,const struct q931_party_name * name)5574 int q931_facility_display_name(struct pri *ctrl, struct q931_call *call, const struct q931_party_name *name)
5575 {
5576 	int status;
5577 	static int facility_display_ies[] = {
5578 		Q931_IE_FACILITY,
5579 		Q931_DISPLAY,
5580 		-1
5581 	};
5582 
5583 	q931_display_name_send(call, name);
5584 	status = send_message(ctrl, call, Q931_FACILITY, facility_display_ies);
5585 	q931_display_clear(call);
5586 	return status;
5587 }
5588 
5589 /*!
5590  * \brief Send a FACILITY RequestSubaddress with optional redirection name and number.
5591  *
5592  * \param ctrl D channel controller.
5593  * \param call Q.931 call leg
5594  * \param notify Notification indicator
5595  * \param name Redirection name to send if not NULL.
5596  * \param number Redirection number to send if not NULL.
5597  *
5598  * \retval 0 on success.
5599  * \retval -1 on error.
5600  */
q931_request_subaddress(struct pri * ctrl,struct q931_call * call,int notify,const struct q931_party_name * name,const struct q931_party_number * number)5601 int q931_request_subaddress(struct pri *ctrl, struct q931_call *call, int notify, const struct q931_party_name *name, const struct q931_party_number *number)
5602 {
5603 	int status;
5604 	struct q931_call *winner;
5605 	static int facility_notify_ies[] = {
5606 		Q931_IE_FACILITY,
5607 		Q931_IE_NOTIFY_IND,
5608 		Q931_DISPLAY,
5609 		Q931_IE_REDIRECTION_NUMBER,
5610 		-1
5611 	};
5612 
5613 	winner = q931_find_winning_call(call);
5614 	if (!winner) {
5615 		return -1;
5616 	}
5617 	q931_display_clear(winner);
5618 	if (number) {
5619 		winner->redirection_number = *number;
5620 		if (number->valid && name
5621 			&& (ctrl->display_flags.send & PRI_DISPLAY_OPTION_NAME_UPDATE)) {
5622 			q931_display_name_send(winner, name);
5623 		}
5624 	} else {
5625 		q931_party_number_init(&winner->redirection_number);
5626 	}
5627 	winner->notify = notify;
5628 	if (rose_request_subaddress_encode(ctrl, winner)
5629 		|| send_message(ctrl, winner, Q931_FACILITY, facility_notify_ies)) {
5630 		pri_message(ctrl,
5631 			"Could not schedule facility message for request subaddress.\n");
5632 		status = -1;
5633 	} else {
5634 		status = 0;
5635 	}
5636 	q931_display_clear(winner);
5637 
5638 	return status;
5639 }
5640 
5641 /*!
5642  * \brief Send a FACILITY SubaddressTransfer to all parties.
5643  *
5644  * \param ctrl D channel controller.
5645  * \param call Q.931 call leg
5646  *
5647  * \retval 0 on success.
5648  * \retval -1 on error.
5649  */
q931_subaddress_transfer(struct pri * ctrl,struct q931_call * call)5650 int q931_subaddress_transfer(struct pri *ctrl, struct q931_call *call)
5651 {
5652 	int status;
5653 	unsigned idx;
5654 	struct q931_call *subcall;
5655 
5656 	if (call->outboundbroadcast && call->master_call == call) {
5657 		status = 0;
5658 		for (idx = 0; idx < ARRAY_LEN(call->subcalls); ++idx) {
5659 			subcall = call->subcalls[idx];
5660 			if (subcall) {
5661 				/* Send to all subcalls that have given a positive response. */
5662 				switch (subcall->ourcallstate) {
5663 				case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
5664 				case Q931_CALL_STATE_CALL_DELIVERED:
5665 				case Q931_CALL_STATE_ACTIVE:
5666 					if (send_subaddress_transfer(ctrl, subcall)) {
5667 						status = -1;
5668 					}
5669 					break;
5670 				default:
5671 					break;
5672 				}
5673 			}
5674 		}
5675 	} else {
5676 		status = send_subaddress_transfer(ctrl, call);
5677 	}
5678 	return status;
5679 }
5680 
5681 /*!
5682  * \internal
5683  * \brief Actually send a NOTIFY message with optional redirection name and number.
5684  *
5685  * \param ctrl D channel controller.
5686  * \param call Q.931 call leg
5687  * \param notify Notification indicator
5688  * \param name Redirection display name to send if not NULL.
5689  * \param number Redirection number to send if not NULL.
5690  *
5691  * \retval 0 on success.
5692  * \retval -1 on error.
5693  */
q931_notify_redirection_helper(struct pri * ctrl,struct q931_call * call,int notify,const struct q931_party_name * name,const struct q931_party_number * number)5694 static int q931_notify_redirection_helper(struct pri *ctrl, struct q931_call *call, int notify, const struct q931_party_name *name, const struct q931_party_number *number)
5695 {
5696 	int status;
5697 	static int notify_ies[] = {
5698 		Q931_IE_NOTIFY_IND,
5699 		Q931_DISPLAY,
5700 		Q931_IE_REDIRECTION_NUMBER,
5701 		-1
5702 	};
5703 
5704 	q931_display_clear(call);
5705 	if (number) {
5706 		call->redirection_number = *number;
5707 		if (number->valid && name
5708 			&& (ctrl->display_flags.send & PRI_DISPLAY_OPTION_NAME_UPDATE)) {
5709 			q931_display_name_send(call, name);
5710 		}
5711 	} else {
5712 		q931_party_number_init(&call->redirection_number);
5713 	}
5714 	call->notify = notify;
5715 	status = send_message(ctrl, call, Q931_NOTIFY, notify_ies);
5716 	q931_display_clear(call);
5717 	return status;
5718 }
5719 
5720 /*!
5721  * \brief Send a NOTIFY message with optional redirection name and number.
5722  *
5723  * \param ctrl D channel controller.
5724  * \param call Q.931 call leg
5725  * \param notify Notification indicator
5726  * \param name Redirection display name to send if not NULL.
5727  * \param number Redirection number to send if not NULL.
5728  *
5729  * \retval 0 on success.
5730  * \retval -1 on error.
5731  */
q931_notify_redirection(struct pri * ctrl,struct q931_call * call,int notify,const struct q931_party_name * name,const struct q931_party_number * number)5732 int q931_notify_redirection(struct pri *ctrl, struct q931_call *call, int notify, const struct q931_party_name *name, const struct q931_party_number *number)
5733 {
5734 	int status;
5735 	unsigned idx;
5736 	struct q931_call *subcall;
5737 
5738 	if (call->outboundbroadcast && call->master_call == call) {
5739 		status = 0;
5740 		for (idx = 0; idx < ARRAY_LEN(call->subcalls); ++idx) {
5741 			subcall = call->subcalls[idx];
5742 			if (subcall) {
5743 				/* Send to all subcalls that have given a positive response. */
5744 				switch (subcall->ourcallstate) {
5745 				case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
5746 				case Q931_CALL_STATE_CALL_DELIVERED:
5747 				case Q931_CALL_STATE_ACTIVE:
5748 					if (q931_notify_redirection_helper(ctrl, subcall, notify, name, number)) {
5749 						status = -1;
5750 					}
5751 					break;
5752 				default:
5753 					break;
5754 				}
5755 			}
5756 		}
5757 	} else {
5758 		status = q931_notify_redirection_helper(ctrl, call, notify, name, number);
5759 	}
5760 	return status;
5761 }
5762 
q931_notify(struct pri * ctrl,q931_call * c,int channel,int info)5763 int q931_notify(struct pri *ctrl, q931_call *c, int channel, int info)
5764 {
5765 	switch (ctrl->switchtype) {
5766 	case PRI_SWITCH_EUROISDN_T1:
5767 	case PRI_SWITCH_EUROISDN_E1:
5768 		break;
5769 	default:
5770 		if ((info > 0x2) || (info < 0x00)) {
5771 			return -1;
5772 		}
5773 		break;
5774 	}
5775 
5776 	if (info >= 0) {
5777 		info &= 0x7F;
5778 	} else {
5779 		/* Cannot send NOTIFY message if the mandatory ie is not going to be present. */
5780 		return -1;
5781 	}
5782 	return q931_notify_redirection(ctrl, c, info, NULL, NULL);
5783 }
5784 
5785 static int call_progress_ies[] = {
5786 #ifndef ALERTING_NO_PROGRESS
5787 	Q931_PROGRESS_INDICATOR,
5788 #endif
5789 	-1
5790 };
5791 
q931_call_progress(struct pri * ctrl,q931_call * c,int channel,int info)5792 int q931_call_progress(struct pri *ctrl, q931_call *c, int channel, int info)
5793 {
5794 	if (c->ourcallstate == Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE) {
5795 		/* Cannot send this message when in this state */
5796 		return 0;
5797 	}
5798 	if (channel) {
5799 		c->ds1no = (channel & 0xff00) >> 8;
5800 		c->ds1explicit = (channel & 0x10000) >> 16;
5801 		c->channelno = channel & 0xff;
5802 	}
5803 
5804 	if (info) {
5805 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
5806 		c->progcode = CODE_CCITT;
5807 		c->progressmask = PRI_PROG_INBAND_AVAILABLE;
5808 	} else {
5809 		/* PI is mandatory IE for PROGRESS message - Q.931 3.1.8 */
5810 		pri_error(ctrl, "XXX Progress message requested but no information is provided\n");
5811 		c->progressmask = 0;
5812 	}
5813 
5814 	c->alive = 1;
5815 	return send_message(ctrl, c, Q931_PROGRESS, call_progress_ies);
5816 }
5817 
5818 static int call_progress_with_cause_ies[] = {
5819 	Q931_CAUSE,
5820 #ifndef ALERTING_NO_PROGRESS
5821 	Q931_PROGRESS_INDICATOR,
5822 #endif
5823 	-1
5824 };
5825 
q931_call_progress_with_cause(struct pri * ctrl,q931_call * c,int channel,int info,int cause)5826 int q931_call_progress_with_cause(struct pri *ctrl, q931_call *c, int channel, int info, int cause)
5827 {
5828 	if (c->ourcallstate == Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE) {
5829 		/* Cannot send this message when in this state */
5830 		return 0;
5831 	}
5832 	if (channel) {
5833 		c->ds1no = (channel & 0xff00) >> 8;
5834 		c->ds1explicit = (channel & 0x10000) >> 16;
5835 		c->channelno = channel & 0xff;
5836 	}
5837 
5838 	if (info) {
5839 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
5840 		c->progcode = CODE_CCITT;
5841 		c->progressmask = PRI_PROG_INBAND_AVAILABLE;
5842 	} else {
5843 		/* PI is mandatory IE for PROGRESS message - Q.931 3.1.8 */
5844 		pri_error(ctrl, "XXX Progress message requested but no information is provided\n");
5845 		c->progressmask = 0;
5846 	}
5847 
5848 	c->cause = cause;
5849 	c->causecode = CODE_CCITT;
5850 	c->causeloc = LOC_PRIV_NET_LOCAL_USER;
5851 
5852 	c->alive = 1;
5853 	return send_message(ctrl, c, Q931_PROGRESS, call_progress_with_cause_ies);
5854 }
5855 
5856 static int call_proceeding_ies[] = {
5857 	Q931_CHANNEL_IDENT,
5858 #ifndef ALERTING_NO_PROGRESS
5859 	Q931_PROGRESS_INDICATOR,
5860 #endif
5861 	-1
5862 };
5863 
q931_call_proceeding(struct pri * ctrl,q931_call * c,int channel,int info)5864 int q931_call_proceeding(struct pri *ctrl, q931_call *c, int channel, int info)
5865 {
5866 	if (c->proc) {
5867 		/* We have already sent a PROCEEDING message.  Don't send another one. */
5868 		return 0;
5869 	}
5870 	if (c->ourcallstate == Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE) {
5871 		/* Cannot send this message when in this state */
5872 		return 0;
5873 	}
5874 	if (channel) {
5875 		c->ds1no = (channel & 0xff00) >> 8;
5876 		c->ds1explicit = (channel & 0x10000) >> 16;
5877 		c->channelno = channel & 0xff;
5878 	}
5879 	c->chanflags &= ~FLAG_PREFERRED;
5880 	c->chanflags |= FLAG_EXCLUSIVE;
5881 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_INCOMING_CALL_PROCEEDING);
5882 	c->peercallstate = Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING;
5883 	if (info) {
5884 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
5885 		c->progcode = CODE_CCITT;
5886 		c->progressmask = PRI_PROG_INBAND_AVAILABLE;
5887 	} else
5888 		c->progressmask = 0;
5889 	c->proc = 1;
5890 	c->alive = 1;
5891 	return send_message(ctrl, c, Q931_CALL_PROCEEDING, call_proceeding_ies);
5892 }
5893 
5894 static int alerting_ies[] = {
5895 	Q931_IE_FACILITY,
5896 #ifndef ALERTING_NO_PROGRESS
5897 	Q931_PROGRESS_INDICATOR,
5898 #endif
5899 	Q931_IE_USER_USER,
5900 	-1
5901 };
5902 
q931_alerting(struct pri * ctrl,q931_call * c,int channel,int info)5903 int q931_alerting(struct pri *ctrl, q931_call *c, int channel, int info)
5904 {
5905 	if (c->ourcallstate == Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE) {
5906 		/* Cannot send this message when in this state */
5907 		return 0;
5908 	}
5909 	if (!c->proc)
5910 		q931_call_proceeding(ctrl, c, channel, 0);
5911 	if (info) {
5912 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
5913 		c->progcode = CODE_CCITT;
5914 		c->progressmask = PRI_PROG_INBAND_AVAILABLE;
5915 	} else
5916 		c->progressmask = 0;
5917 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_RECEIVED);
5918 	c->peercallstate = Q931_CALL_STATE_CALL_DELIVERED;
5919 	c->alive = 1;
5920 
5921 	switch (ctrl->switchtype) {
5922 	case PRI_SWITCH_QSIG:
5923 		if (c->local_id.name.valid) {
5924 			/* Send calledName with ALERTING */
5925 			rose_called_name_encode(ctrl, c, Q931_ALERTING);
5926 		}
5927 		break;
5928 	default:
5929 		break;
5930 	}
5931 
5932 	if (c->cc.record) {
5933 		pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_MSG_ALERTING);
5934 	}
5935 
5936 	return send_message(ctrl, c, Q931_ALERTING, alerting_ies);
5937 }
5938 
5939 static int setup_ack_ies[] = {
5940 	Q931_CHANNEL_IDENT,
5941 	Q931_IE_FACILITY,
5942 	Q931_PROGRESS_INDICATOR,
5943 	-1
5944 };
5945 
q931_setup_ack(struct pri * ctrl,q931_call * c,int channel,int nonisdn,int inband)5946 int q931_setup_ack(struct pri *ctrl, q931_call *c, int channel, int nonisdn, int inband)
5947 {
5948 	if (c->ourcallstate == Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE) {
5949 		/* Cannot send this message when in this state */
5950 		return 0;
5951 	}
5952 	if (channel) {
5953 		c->ds1no = (channel & 0xff00) >> 8;
5954 		c->ds1explicit = (channel & 0x10000) >> 16;
5955 		c->channelno = channel & 0xff;
5956 	}
5957 	c->chanflags &= ~FLAG_PREFERRED;
5958 	c->chanflags |= FLAG_EXCLUSIVE;
5959 
5960 	c->progressmask = 0;
5961 	if (nonisdn && (ctrl->switchtype != PRI_SWITCH_DMS100)) {
5962 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
5963 		c->progcode = CODE_CCITT;
5964 		c->progressmask |= PRI_PROG_CALLED_NOT_ISDN;
5965 	}
5966 	if (inband) {
5967 		/* Inband audio is present (i.e. dialtone) */
5968 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
5969 		c->progcode = CODE_CCITT;
5970 		c->progressmask |= PRI_PROG_INBAND_AVAILABLE;
5971 	}
5972 
5973 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_OVERLAP_RECEIVING);
5974 	c->peercallstate = Q931_CALL_STATE_OVERLAP_SENDING;
5975 	c->alive = 1;
5976 	return send_message(ctrl, c, Q931_SETUP_ACKNOWLEDGE, setup_ack_ies);
5977 }
5978 
5979 /* T313 expiry, first time */
pri_connect_timeout(void * data)5980 static void pri_connect_timeout(void *data)
5981 {
5982 	struct q931_call *c = data;
5983 	struct pri *ctrl = c->pri;
5984 
5985 	if (ctrl->debug & PRI_DEBUG_Q931_STATE)
5986 		pri_message(ctrl, "Timed out looking for connect acknowledge\n");
5987 	c->retranstimer = 0;
5988 	q931_disconnect(ctrl, c, PRI_CAUSE_NORMAL_CLEARING);
5989 }
5990 
5991 /* T308 expiry, first time */
pri_release_timeout(void * data)5992 static void pri_release_timeout(void *data)
5993 {
5994 	struct q931_call *c = data;
5995 	struct pri *ctrl = c->pri;
5996 
5997 	if (ctrl->debug & PRI_DEBUG_Q931_STATE)
5998 		pri_message(ctrl, "Timed out looking for release complete\n");
5999 	c->t308_timedout++;
6000 	c->retranstimer = 0;
6001 	c->alive = 1;
6002 
6003 	/* The call to q931_release will re-schedule T308 */
6004 	q931_release(ctrl, c, c->cause);
6005 }
6006 
6007 /* T308 expiry, second time */
pri_release_finaltimeout(void * data)6008 static void pri_release_finaltimeout(void *data)
6009 {
6010 	struct q931_call *c = data;
6011 	struct pri *ctrl = c->pri;
6012 
6013 	c->retranstimer = 0;
6014 	c->alive = 1;
6015 	if (ctrl->debug & PRI_DEBUG_Q931_STATE)
6016 		pri_message(ctrl, "Final time-out looking for release complete\n");
6017 	c->t308_timedout++;
6018 	c->ourcallstate = Q931_CALL_STATE_NULL;
6019 	c->peercallstate = Q931_CALL_STATE_NULL;
6020 	q931_clr_subcommands(ctrl);
6021 	ctrl->schedev = 1;
6022 	ctrl->ev.e = PRI_EVENT_HANGUP_ACK;
6023 	ctrl->ev.hangup.subcmds = &ctrl->subcmds;
6024 	ctrl->ev.hangup.channel = q931_encode_channel(c);
6025 	ctrl->ev.hangup.cause = c->cause;
6026 	ctrl->ev.hangup.cref = c->cr;
6027 	ctrl->ev.hangup.call = c->master_call;
6028 	ctrl->ev.hangup.aoc_units = c->aoc_units;
6029 	ctrl->ev.hangup.call_held = NULL;
6030 	ctrl->ev.hangup.call_active = NULL;
6031 	libpri_copy_string(ctrl->ev.hangup.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.hangup.useruserinfo));
6032 	pri_hangup(ctrl, c, c->cause);
6033 }
6034 
6035 /* T305 expiry, first time */
pri_disconnect_timeout(void * data)6036 static void pri_disconnect_timeout(void *data)
6037 {
6038 	struct q931_call *c = data;
6039 	struct pri *ctrl = c->pri;
6040 
6041 	if (ctrl->debug & PRI_DEBUG_Q931_STATE)
6042 		pri_message(ctrl, "Timed out looking for release\n");
6043 	c->retranstimer = 0;
6044 	c->alive = 1;
6045 	q931_release(ctrl, c, PRI_CAUSE_NORMAL_CLEARING);
6046 }
6047 
6048 static int connect_ies[] = {
6049 	Q931_CHANNEL_IDENT,
6050 	Q931_IE_FACILITY,
6051 	Q931_PROGRESS_INDICATOR,
6052 	Q931_DISPLAY,
6053 	Q931_IE_TIME_DATE,
6054 	Q931_IE_CONNECTED_NUM,
6055 	Q931_IE_CONNECTED_SUBADDR,
6056 	-1
6057 };
6058 
q931_connect(struct pri * ctrl,q931_call * c,int channel,int nonisdn)6059 int q931_connect(struct pri *ctrl, q931_call *c, int channel, int nonisdn)
6060 {
6061 	if (c->ourcallstate == Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE) {
6062 		/* Cannot send this message when in this state */
6063 		return 0;
6064 	}
6065 	if (channel) {
6066 		c->ds1no = (channel & 0xff00) >> 8;
6067 		c->ds1explicit = (channel & 0x10000) >> 16;
6068 		c->channelno = channel & 0xff;
6069 	}
6070 	c->chanflags &= ~FLAG_PREFERRED;
6071 	c->chanflags |= FLAG_EXCLUSIVE;
6072 	if (nonisdn && (ctrl->switchtype != PRI_SWITCH_DMS100)) {
6073 		c->progloc = LOC_PRIV_NET_LOCAL_USER;
6074 		c->progcode = CODE_CCITT;
6075 		c->progressmask = PRI_PROG_CALLED_NOT_ISDN;
6076 	} else
6077 		c->progressmask = 0;
6078 	if(ctrl->localtype == PRI_NETWORK || ctrl->switchtype == PRI_SWITCH_QSIG)
6079 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_ACTIVE);
6080 	else
6081 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CONNECT_REQUEST);
6082 	c->peercallstate = Q931_CALL_STATE_ACTIVE;
6083 	c->alive = 1;
6084 	/* Connect request timer */
6085 	pri_schedule_del(ctrl, c->retranstimer);
6086 	c->retranstimer = 0;
6087 	if ((c->ourcallstate == Q931_CALL_STATE_CONNECT_REQUEST) && (ctrl->bri || (!ctrl->link.next)))
6088 		c->retranstimer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T313], pri_connect_timeout, c);
6089 
6090 	if (c->redirecting.state == Q931_REDIRECTING_STATE_PENDING_TX_DIV_LEG_3) {
6091 		c->redirecting.state = Q931_REDIRECTING_STATE_IDLE;
6092 		/* Send DivertingLegInformation3 with CONNECT. */
6093 		c->redirecting.to = c->local_id;
6094 		if (!c->redirecting.to.number.valid) {
6095 			q931_party_number_init(&c->redirecting.to.number);
6096 			c->redirecting.to.number.valid = 1;
6097 			c->redirecting.to.number.presentation =
6098 				PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
6099 		}
6100 		rose_diverting_leg_information3_encode(ctrl, c, Q931_CONNECT);
6101 	}
6102 	switch (ctrl->switchtype) {
6103 	case PRI_SWITCH_QSIG:
6104 		if (c->local_id.name.valid) {
6105 			/* Send connectedName with CONNECT */
6106 			rose_connected_name_encode(ctrl, c, Q931_CONNECT);
6107 		}
6108 		break;
6109 	default:
6110 		break;
6111 	}
6112 	if (ctrl->display_flags.send & PRI_DISPLAY_OPTION_NAME_INITIAL) {
6113 		q931_display_name_send(c, &c->local_id.name);
6114 	} else {
6115 		q931_display_clear(c);
6116 	}
6117 	return send_message(ctrl, c, Q931_CONNECT, connect_ies);
6118 }
6119 
6120 static int release_ies[] = { Q931_CAUSE, Q931_IE_FACILITY, Q931_IE_USER_USER, -1 };
6121 
q931_release(struct pri * ctrl,q931_call * c,int cause)6122 int q931_release(struct pri *ctrl, q931_call *c, int cause)
6123 {
6124 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_RELEASE_REQUEST);
6125 	/* c->peercallstate stays the same */
6126 	if (c->alive) {
6127 		c->alive = 0;
6128 		c->cause = cause;
6129 		c->causecode = CODE_CCITT;
6130 		c->causeloc = LOC_PRIV_NET_LOCAL_USER;
6131 		if (c->acked) {
6132 			pri_schedule_del(ctrl, c->retranstimer);
6133 			if (!c->t308_timedout) {
6134 				c->retranstimer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T308], pri_release_timeout, c);
6135 			} else {
6136 				c->retranstimer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T308], pri_release_finaltimeout, c);
6137 			}
6138 			if (c->cc.record) {
6139 				pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_MSG_RELEASE);
6140 			}
6141 			return send_message(ctrl, c, Q931_RELEASE, release_ies);
6142 		} else {
6143 			if (c->cc.record) {
6144 				pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_MSG_RELEASE_COMPLETE);
6145 			}
6146 			return send_message(ctrl, c, Q931_RELEASE_COMPLETE, release_ies); /* Yes, release_ies, not release_complete_ies */
6147 		}
6148 	} else
6149 		return 0;
6150 }
6151 
6152 static int restart_ies[] = { Q931_CHANNEL_IDENT, Q931_RESTART_INDICATOR, -1 };
6153 
6154 static void t316_expire(void *vcall);
6155 
6156 /*!
6157  * \internal
6158  * \brief Send the RESTART message to the peer.
6159  *
6160  * \param call Q.931 call leg
6161  * \param channel Encoded channel id to use.
6162  *
6163  * \retval 0 on success.
6164  * \retval -1 on error.
6165  */
q931_send_restart(struct q931_call * call)6166 static int q931_send_restart(struct q931_call *call)
6167 {
6168 	struct pri *ctrl = call->pri;
6169 	int channel = call->restart_tx.channel;
6170 
6171 	/* Start timer T316 if enabled. */
6172 	if (0 < ctrl->timers[PRI_TIMER_T316]) {
6173 		call->restart_tx.t316_timer =
6174 			pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T316], t316_expire, call);
6175 		--call->restart_tx.remain;
6176 	}
6177 
6178 	call->ri = 0;
6179 	call->ds1no = (channel >> 8) & 0xFF;
6180 	call->ds1explicit = (channel >> 16) & 0x1;
6181 	call->channelno = channel & 0xFF;
6182 	call->chanflags &= ~FLAG_PREFERRED;
6183 	call->chanflags |= FLAG_EXCLUSIVE;
6184 	UPDATE_OURCALLSTATE(ctrl, call, Q931_CALL_STATE_RESTART);
6185 	call->peercallstate = Q931_CALL_STATE_RESTART_REQUEST;
6186 	return send_message(ctrl, call, Q931_RESTART, restart_ies);
6187 }
6188 
6189 /*!
6190  * \internal
6191  * \brief T316 expired.
6192  *
6193  * \param vcall Q.931 call leg
6194  *
6195  * \return Nothing
6196  */
t316_expire(void * vcall)6197 static void t316_expire(void *vcall)
6198 {
6199 	struct q931_call *call = vcall;
6200 
6201 	call->restart_tx.t316_timer = 0;
6202 
6203 	if (call->restart_tx.remain) {
6204 		/* Retransmit the RESTART */
6205 		q931_send_restart(call);
6206 	} else {
6207 		int channel = call->restart_tx.channel;
6208 
6209 		pri_message(call->pri,
6210 			"!! Peer failed to ack our RESTART request for ds1/channel:%d/%d.\n",
6211 			(channel >> 8) & 0xFF, channel & 0xFF);
6212 	}
6213 }
6214 
6215 /*!
6216  * \internal
6217  * \brief Stop timer T316.
6218  *
6219  * \param call Q.931 call leg
6220  *
6221  * \return Nothing
6222  */
stop_t316(struct q931_call * call)6223 static void stop_t316(struct q931_call *call)
6224 {
6225 	pri_schedule_del(call->pri, call->restart_tx.t316_timer);
6226 	call->restart_tx.t316_timer = 0;
6227 }
6228 
6229 /*!
6230  * \brief Send the RESTART message to the peer.
6231  *
6232  * \param ctrl D channel controller.
6233  * \param channel Encoded channel id to use.
6234  *
6235  * \note
6236  * Sending RESTART in NT PTMP mode is not supported at the
6237  * present time.
6238  *
6239  * \note
6240  * NT PTMP should broadcast the RESTART if there is a TEI
6241  * allocated.  Otherwise it should immediately ACK the RESTART
6242  * itself to avoid the T316 timeout delay (2 minutes) since
6243  * there might not be anything connected.  The broadcast could
6244  * be handled in a similar manner to the broadcast SETUP.
6245  *
6246  * \todo NT PTMP mode should implement some protection from
6247  * receiving a RESTART on channels in use by another TEI.
6248  *
6249  * \retval 0 on success.
6250  * \retval -1 on error.
6251  */
q931_restart(struct pri * ctrl,int channel)6252 int q931_restart(struct pri *ctrl, int channel)
6253 {
6254 	struct q931_call *call;
6255 
6256 	if (!channel) {
6257 		return -1;
6258 	}
6259 	call = q931_getcall(&ctrl->link, 0 | Q931_CALL_REFERENCE_FLAG);
6260 	if (!call) {
6261 		return -1;
6262 	}
6263 
6264 	stop_t316(call);
6265 	call->restart_tx.remain = (0 < ctrl->timers[PRI_TIMER_N316])
6266 		? ctrl->timers[PRI_TIMER_N316] : 1;
6267 	call->restart_tx.channel = channel;
6268 	return q931_send_restart(call);
6269 }
6270 
6271 static int disconnect_ies[] = { Q931_CAUSE, Q931_IE_FACILITY, Q931_IE_USER_USER, -1 };
6272 
q931_disconnect(struct pri * ctrl,q931_call * c,int cause)6273 int q931_disconnect(struct pri *ctrl, q931_call *c, int cause)
6274 {
6275 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_DISCONNECT_REQUEST);
6276 	c->peercallstate = Q931_CALL_STATE_DISCONNECT_INDICATION;
6277 	if (c->alive) {
6278 		c->alive = 0;
6279 		c->cause = cause;
6280 		c->causecode = CODE_CCITT;
6281 		c->causeloc = LOC_PRIV_NET_LOCAL_USER;
6282 		c->sendhangupack = 1;
6283 
6284 		if (c->cc.record) {
6285 			pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_MSG_DISCONNECT);
6286 		}
6287 
6288 		pri_schedule_del(ctrl, c->retranstimer);
6289 		c->retranstimer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T305], pri_disconnect_timeout, c);
6290 		return send_message(ctrl, c, Q931_DISCONNECT, disconnect_ies);
6291 	} else
6292 		return 0;
6293 }
6294 
6295 static int setup_ies[] = {
6296 	Q931_BEARER_CAPABILITY,
6297 	Q931_CHANNEL_IDENT,
6298 	Q931_IE_FACILITY,
6299 	Q931_PROGRESS_INDICATOR,
6300 	Q931_NETWORK_SPEC_FAC,
6301 	Q931_DISPLAY,
6302 	Q931_IE_KEYPAD_FACILITY,
6303 	Q931_REVERSE_CHARGE_INDIC,
6304 	Q931_CALLING_PARTY_NUMBER,
6305 	Q931_CALLING_PARTY_SUBADDR,
6306 	Q931_CALLED_PARTY_NUMBER,
6307 	Q931_CALLED_PARTY_SUBADDR,
6308 	Q931_REDIRECTING_NUMBER,
6309 	Q931_IE_USER_USER,
6310 	Q931_SENDING_COMPLETE,
6311 	Q931_IE_ORIGINATING_LINE_INFO,
6312 	Q931_IE_GENERIC_DIGITS,
6313 	-1
6314 };
6315 
6316 static int gr303_setup_ies[] = {
6317 	Q931_BEARER_CAPABILITY,
6318 	Q931_CHANNEL_IDENT,
6319 	-1
6320 };
6321 
6322 /*! Call Independent Signalling SETUP ie's */
6323 static int cis_setup_ies[] = {
6324 	Q931_BEARER_CAPABILITY,
6325 	Q931_CHANNEL_IDENT,
6326 	Q931_IE_FACILITY,
6327 	Q931_IE_KEYPAD_FACILITY,
6328 	Q931_CALLING_PARTY_NUMBER,
6329 	Q931_CALLING_PARTY_SUBADDR,
6330 	Q931_CALLED_PARTY_NUMBER,
6331 	Q931_CALLED_PARTY_SUBADDR,
6332 	Q931_SENDING_COMPLETE,
6333 	-1
6334 };
6335 
stop_t303(struct q931_call * call)6336 static void stop_t303(struct q931_call *call)
6337 {
6338 	/* T303 should only be running on the master call */
6339 	pri_schedule_del(call->pri, call->t303_timer);
6340 	call->t303_timer = 0;
6341 }
6342 
6343 static void t303_expiry(void *data);
6344 
6345 /*! \param call Call is not a subcall call record. */
start_t303(struct q931_call * call)6346 static void start_t303(struct q931_call *call)
6347 {
6348 	struct pri *ctrl;
6349 
6350 	ctrl = call->pri;
6351 	pri_schedule_del(ctrl, call->t303_timer);
6352 	call->t303_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T303], t303_expiry,
6353 		call);
6354 }
6355 
t303_expiry(void * data)6356 static void t303_expiry(void *data)
6357 {
6358 	struct q931_call *c = data;/* Call is not a subcall call record. */
6359 	struct pri *ctrl = c->pri;
6360 	int res;
6361 
6362 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
6363 		pri_message(ctrl, "T303 timed out.  cref:%d\n", c->cr);
6364 	}
6365 
6366 	c->t303_expirycnt++;
6367 	c->t303_timer = 0;
6368 
6369 	if (c->cause != -1) {
6370 		/* We got a DISCONNECT, RELEASE, or RELEASE_COMPLETE and no other responses. */
6371 		if (c->outboundbroadcast) {
6372 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_ABORT);
6373 		} else {
6374 			/* This should never happen.  T303 should not be running in this case. */
6375 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
6376 			c->peercallstate = Q931_CALL_STATE_NULL;
6377 		}
6378 		pri_fake_clearing(c);
6379 	} else if (c->t303_expirycnt < 2) {
6380 		/*!
6381 		 * \todo XXX Resending the SETUP message loses any facility ies
6382 		 * that the original may have had that were not added by
6383 		 * pri_call_add_standard_apdus().  Actually any message Q.931
6384 		 * retransmits will lose the facility ies.
6385 		 */
6386 		pri_call_add_standard_apdus(ctrl, c);
6387 		if (ctrl->display_flags.send & PRI_DISPLAY_OPTION_NAME_INITIAL) {
6388 			q931_display_name_send(c, &c->local_id.name);
6389 		} else {
6390 			q931_display_clear(c);
6391 		}
6392 		c->cc.saved_ie_contents.length = 0;
6393 		c->cc.saved_ie_flags = 0;
6394 		if (ctrl->link.next && !ctrl->bri)
6395 			res = send_message(ctrl, c, Q931_SETUP, gr303_setup_ies);
6396 		else if (c->cis_call)
6397 			res = send_message(ctrl, c, Q931_SETUP, cis_setup_ies);
6398 		else
6399 			res = send_message(ctrl, c, Q931_SETUP, setup_ies);
6400 		if (res) {
6401 			pri_error(ctrl, "Error resending setup message!\n");
6402 		}
6403 		start_t303(c);
6404 		if (c->outboundbroadcast) {
6405 			start_t312(c);
6406 		}
6407 	} else {
6408 		/*
6409 		 * We never got any response for a normal call or an
6410 		 * establishment response from any TEI for a master/subcall
6411 		 * call.
6412 		 */
6413 		c->cause = PRI_CAUSE_NO_USER_RESPONSE;
6414 		if (c->outboundbroadcast) {
6415 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_ABORT);
6416 		} else {
6417 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
6418 			c->peercallstate = Q931_CALL_STATE_NULL;
6419 		}
6420 		pri_fake_clearing(c);
6421 	}
6422 }
6423 
q931_setup(struct pri * ctrl,q931_call * c,struct pri_sr * req)6424 int q931_setup(struct pri *ctrl, q931_call *c, struct pri_sr *req)
6425 {
6426 	int res;
6427 
6428 	if (!req->called.number.valid && (!req->keypad_digits || !req->keypad_digits[0])) {
6429 		/* No called number or keypad digits to send. */
6430 		return -1;
6431 	}
6432 
6433 	c->called = req->called;
6434 	libpri_copy_string(c->overlap_digits, req->called.number.str, sizeof(c->overlap_digits));
6435 
6436 	if (req->keypad_digits) {
6437 		libpri_copy_string(c->keypad_digits, req->keypad_digits,
6438 			sizeof(c->keypad_digits));
6439 	} else {
6440 		c->keypad_digits[0] = '\0';
6441 	}
6442 
6443 	c->bc.transcapability = req->transmode;
6444 	c->bc.transmoderate = TRANS_MODE_64_CIRCUIT;
6445 	if (!req->userl1)
6446 		req->userl1 = PRI_LAYER_1_ULAW;
6447 	c->bc.userl1 = req->userl1;
6448 	c->bc.userl2 = -1;
6449 	c->bc.userl3 = -1;
6450 
6451 	c->ds1no = (req->channel & 0xff00) >> 8;
6452 	c->ds1explicit = (req->channel & 0x10000) >> 16;
6453 	if ((ctrl->localtype == PRI_CPE) && ctrl->link.next && !ctrl->bri) {
6454 		c->channelno = 0;
6455 		c->chanflags = 0;
6456 	} else {
6457 		c->channelno = req->channel & 0xff;
6458 		if (req->exclusive) {
6459 			c->chanflags = FLAG_EXCLUSIVE;
6460 		} else {
6461 			c->chanflags = FLAG_PREFERRED;
6462 		}
6463 	}
6464 	if (ctrl->localtype == PRI_CPE) {
6465 		c->channel_id_ie_mandatory = 1;
6466 	}
6467 
6468 	c->slotmap = -1;
6469 	c->nonisdn = req->nonisdn;
6470 	c->newcall = 0;
6471 	c->cis_call = req->cis_call;
6472 	c->cis_recognized = req->cis_call;
6473 	c->cis_auto_disconnect = req->cis_auto_disconnect;
6474 	c->complete = req->numcomplete;
6475 
6476 	if (req->caller.number.valid) {
6477 		c->local_id = req->caller;
6478 		q931_party_id_fixup(ctrl, &c->local_id);
6479 	}
6480 
6481 	if (req->redirecting.from.number.valid) {
6482 		c->redirecting = req->redirecting;
6483 		q931_party_id_fixup(ctrl, &c->redirecting.from);
6484 		q931_party_id_fixup(ctrl, &c->redirecting.to);
6485 		q931_party_id_fixup(ctrl, &c->redirecting.orig_called);
6486 	}
6487 
6488 	if (req->useruserinfo)
6489 		libpri_copy_string(c->useruserinfo, req->useruserinfo, sizeof(c->useruserinfo));
6490 	else
6491 		c->useruserinfo[0] = '\0';
6492 
6493 	if (req->nonisdn && (ctrl->switchtype == PRI_SWITCH_NI2))
6494 		c->progressmask = PRI_PROG_CALLER_NOT_ISDN;
6495 	else
6496 		c->progressmask = 0;
6497 
6498 	c->reversecharge = req->reversecharge;
6499 
6500 	c->aoc_charging_request = req->aoc_charging_request;
6501 
6502 	pri_call_add_standard_apdus(ctrl, c);
6503 	if (ctrl->display_flags.send & PRI_DISPLAY_OPTION_NAME_INITIAL) {
6504 		q931_display_name_send(c, &c->local_id.name);
6505 	} else {
6506 		q931_display_clear(c);
6507 	}
6508 
6509 	/* Save the initial cc-parties. */
6510 	c->cc.party_a = c->local_id;
6511 	c->cc.originated = 1;
6512 	if (c->redirecting.from.number.valid) {
6513 		c->cc.initially_redirected = 1;
6514 	}
6515 
6516 	c->cc.saved_ie_contents.length = 0;
6517 	c->cc.saved_ie_flags = 0;
6518 	if (BRI_NT_PTMP(ctrl)) {
6519 		c->outboundbroadcast = 1;
6520 	}
6521 	if (ctrl->link.next && !ctrl->bri)
6522 		res = send_message(ctrl, c, Q931_SETUP, gr303_setup_ies);
6523 	else if (c->cis_call)
6524 		res = send_message(ctrl, c, Q931_SETUP, cis_setup_ies);
6525 	else
6526 		res = send_message(ctrl, c, Q931_SETUP, setup_ies);
6527 	if (!res) {
6528 		c->alive = 1;
6529 		/* make sure we call PRI_EVENT_HANGUP_ACK once we send/receive RELEASE_COMPLETE */
6530 		c->sendhangupack = 1;
6531 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_INITIATED);
6532 		c->peercallstate = Q931_CALL_STATE_CALL_PRESENT;
6533 		c->t303_expirycnt = 0;
6534 		start_t303(c);
6535 		if (c->outboundbroadcast) {
6536 			start_t312(c);
6537 		}
6538 	}
6539 	return res;
6540 }
6541 
6542 static int register_ies[] = { Q931_IE_FACILITY, -1 };
6543 
6544 /*!
6545  * \brief Build and send the REGISTER message.
6546  *
6547  * \param ctrl D channel controller.
6548  * \param call Q.931 call leg
6549  *
6550  * \retval 0 on success.
6551  * \retval -1 on error.
6552  */
q931_register(struct pri * ctrl,q931_call * call)6553 int q931_register(struct pri *ctrl, q931_call *call)
6554 {
6555 	int res;
6556 
6557 	call->newcall = 0;
6558 
6559 	call->cis_call = 1;
6560 	call->cis_recognized = 1;
6561 	call->cis_auto_disconnect = 0;
6562 	call->chanflags = FLAG_EXCLUSIVE;/* For safety mark this channel as exclusive. */
6563 	call->channelno = 0;
6564 
6565 	res = send_message(ctrl, call, Q931_REGISTER, register_ies);
6566 	if (!res) {
6567 		call->alive = 1;
6568 
6569 		UPDATE_OURCALLSTATE(ctrl, call, Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE);
6570 		call->peercallstate = Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE;
6571 	}
6572 	return res;
6573 }
6574 
6575 static int release_complete_ies[] = { Q931_IE_FACILITY, Q931_IE_USER_USER, -1 };
6576 
q931_release_complete(struct pri * ctrl,q931_call * c,int cause)6577 static int q931_release_complete(struct pri *ctrl, q931_call *c, int cause)
6578 {
6579 	int res = 0;
6580 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
6581 	c->peercallstate = Q931_CALL_STATE_NULL;
6582 	if (c->cc.record) {
6583 		pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_MSG_RELEASE_COMPLETE);
6584 	}
6585 	if (cause > -1) {
6586 		c->cause = cause;
6587 		c->causecode = CODE_CCITT;
6588 		c->causeloc = LOC_PRIV_NET_LOCAL_USER;
6589 		/* release_ies has CAUSE in it */
6590 		res = send_message(ctrl, c, Q931_RELEASE_COMPLETE, release_ies);
6591 	} else
6592 		res = send_message(ctrl, c, Q931_RELEASE_COMPLETE, release_complete_ies);
6593 	c->alive = 0;
6594 	/* release the structure */
6595 	res += pri_hangup(ctrl, c, cause);
6596 	return res;
6597 }
6598 
6599 static int connect_ack_ies[] = { -1 };
6600 static int connect_ack_w_chan_id_ies[] = { Q931_CHANNEL_IDENT, -1 };
6601 static int gr303_connect_ack_ies[] = { Q931_CHANNEL_IDENT, -1 };
6602 
q931_connect_acknowledge(struct pri * ctrl,q931_call * call,int channel)6603 int q931_connect_acknowledge(struct pri *ctrl, q931_call *call, int channel)
6604 {
6605 	int *use_ies;
6606 	struct q931_call *winner;
6607 
6608 	winner = q931_find_winning_call(call);
6609 	if (!winner) {
6610 		return -1;
6611 	}
6612 
6613 	if (winner != call) {
6614 		UPDATE_OURCALLSTATE(ctrl, call, Q931_CALL_STATE_ACTIVE);
6615 		call->peercallstate = Q931_CALL_STATE_ACTIVE;
6616 	}
6617 	UPDATE_OURCALLSTATE(ctrl, winner, Q931_CALL_STATE_ACTIVE);
6618 	winner->peercallstate = Q931_CALL_STATE_ACTIVE;
6619 	if (channel) {
6620 		winner->ds1no = (channel & 0xff00) >> 8;
6621 		winner->ds1explicit = (channel & 0x10000) >> 16;
6622 		winner->channelno = channel & 0xff;
6623 		winner->chanflags &= ~FLAG_PREFERRED;
6624 		winner->chanflags |= FLAG_EXCLUSIVE;
6625 	}
6626 	use_ies = NULL;
6627 	if (ctrl->link.next && !ctrl->bri) {
6628 		if (ctrl->localtype == PRI_CPE) {
6629 			use_ies = gr303_connect_ack_ies;
6630 		}
6631 	} else if (channel) {
6632 		use_ies = connect_ack_w_chan_id_ies;
6633 	} else {
6634 		use_ies = connect_ack_ies;
6635 	}
6636 	if (use_ies) {
6637 		return send_message(ctrl, winner, Q931_CONNECT_ACKNOWLEDGE, use_ies);
6638 	}
6639 	return 0;
6640 }
6641 
6642 /*!
6643  * \internal
6644  * \brief Send HOLD message response wait timeout.
6645  *
6646  * \param data Q.931 call leg. (Master Q.931 subcall structure)
6647  *
6648  * \return Nothing
6649  */
q931_hold_timeout(void * data)6650 static void q931_hold_timeout(void *data)
6651 {
6652 	struct q931_call *call = data;
6653 	struct q931_call *master = call->master_call;
6654 	struct pri *ctrl = call->pri;
6655 
6656 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
6657 		pri_message(ctrl, "Time-out waiting for HOLD response\n");
6658 	}
6659 
6660 	/* Ensure that the timer is deleted. */
6661 	pri_schedule_del(ctrl, master->hold_timer);
6662 	master->hold_timer = 0;
6663 
6664 	/* Don't change the hold state if there was HOLD a collision. */
6665 	switch (master->hold_state) {
6666 	case Q931_HOLD_STATE_HOLD_REQ:
6667 		UPDATE_HOLD_STATE(ctrl, master, Q931_HOLD_STATE_IDLE);
6668 		break;
6669 	default:
6670 		break;
6671 	}
6672 
6673 	q931_clr_subcommands(ctrl);
6674 	ctrl->schedev = 1;
6675 	ctrl->ev.e = PRI_EVENT_HOLD_REJ;
6676 	ctrl->ev.hold_rej.channel = q931_encode_channel(call);
6677 	ctrl->ev.hold_rej.call = master;
6678 	ctrl->ev.hold_rej.cause = PRI_CAUSE_MESSAGE_TYPE_NONEXIST;
6679 	ctrl->ev.hold_rej.subcmds = &ctrl->subcmds;
6680 }
6681 
6682 /*!
6683  * \internal
6684  * \brief Determine if a hold request is allowed now.
6685  *
6686  * \param ctrl D channel controller.
6687  * \param call Q.931 call leg. (Master Q.931 subcall structure)
6688  *
6689  * \retval TRUE if we can send a HOLD request.
6690  * \retval FALSE if not allowed.
6691  */
q931_is_hold_allowed(const struct pri * ctrl,const struct q931_call * call)6692 static int q931_is_hold_allowed(const struct pri *ctrl, const struct q931_call *call)
6693 {
6694 	int allowed;
6695 
6696 	allowed = 0;
6697 	switch (call->ourcallstate) {
6698 	case Q931_CALL_STATE_CALL_RECEIVED:
6699 	case Q931_CALL_STATE_CONNECT_REQUEST:
6700 	case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
6701 		if (PTMP_MODE(ctrl)) {
6702 			/* HOLD request only allowed in these states if point-to-point mode. */
6703 			break;
6704 		}
6705 		/* Fall through */
6706 	case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
6707 	case Q931_CALL_STATE_CALL_DELIVERED:
6708 	case Q931_CALL_STATE_ACTIVE:
6709 		switch (call->hold_state) {
6710 		case Q931_HOLD_STATE_IDLE:
6711 			allowed = 1;
6712 			break;
6713 		default:
6714 			break;
6715 		}
6716 		break;
6717 	case Q931_CALL_STATE_DISCONNECT_INDICATION:
6718 	case Q931_CALL_STATE_RELEASE_REQUEST:
6719 		/* Ignore HOLD request in these states. */
6720 		break;
6721 	default:
6722 		break;
6723 	}
6724 
6725 	return allowed;
6726 }
6727 
6728 static int hold_ies[] = {
6729 	-1
6730 };
6731 
6732 /*!
6733  * \brief Send the HOLD message.
6734  *
6735  * \param ctrl D channel controller.
6736  * \param call Q.931 call leg. (Master Q.931 subcall structure)
6737  *
6738  * \retval 0 on success.
6739  * \retval -1 on error.
6740  */
q931_send_hold(struct pri * ctrl,struct q931_call * call)6741 int q931_send_hold(struct pri *ctrl, struct q931_call *call)
6742 {
6743 	struct q931_call *winner;
6744 
6745 	winner = q931_find_winning_call(call);
6746 	if (!winner || !q931_is_hold_allowed(ctrl, call)) {
6747 		return -1;
6748 	}
6749 	pri_schedule_del(ctrl, call->hold_timer);
6750 	call->hold_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T_HOLD],
6751 		q931_hold_timeout, winner);
6752 	if (!call->hold_timer || send_message(ctrl, winner, Q931_HOLD, hold_ies)) {
6753 		pri_schedule_del(ctrl, call->hold_timer);
6754 		call->hold_timer = 0;
6755 		return -1;
6756 	}
6757 	UPDATE_HOLD_STATE(ctrl, call, Q931_HOLD_STATE_HOLD_REQ);
6758 	return 0;
6759 }
6760 
6761 static int hold_ack_ies[] = {
6762 	-1
6763 };
6764 
6765 /*!
6766  * \brief Send the HOLD ACKNOWLEDGE message.
6767  *
6768  * \param ctrl D channel controller.
6769  * \param call Q.931 call leg. (Master Q.931 subcall structure)
6770  *
6771  * \retval 0 on success.
6772  * \retval -1 on error.
6773  */
q931_send_hold_ack(struct pri * ctrl,struct q931_call * call)6774 int q931_send_hold_ack(struct pri *ctrl, struct q931_call *call)
6775 {
6776 	struct q931_call *winner;
6777 
6778 	UPDATE_HOLD_STATE(ctrl, call, Q931_HOLD_STATE_CALL_HELD);
6779 
6780 	winner = q931_find_winning_call(call);
6781 	if (!winner) {
6782 		return -1;
6783 	}
6784 
6785 	/* Call is now on hold so forget the channel. */
6786 	winner->channelno = 0;/* No channel */
6787 	winner->ds1no = 0;
6788 	winner->ds1explicit = 0;
6789 	winner->chanflags = 0;
6790 
6791 	return send_message(ctrl, winner, Q931_HOLD_ACKNOWLEDGE, hold_ack_ies);
6792 }
6793 
6794 static int hold_reject_ies[] = {
6795 	Q931_CAUSE,
6796 	-1
6797 };
6798 
6799 /*!
6800  * \internal
6801  * \brief Send the HOLD REJECT message only.
6802  *
6803  * \param ctrl D channel controller.
6804  * \param call Q.931 call leg. (subcall)
6805  * \param cause Q.931 cause code for rejecting the hold request.
6806  *
6807  * \retval 0 on success.
6808  * \retval -1 on error.
6809  */
q931_send_hold_rej_msg(struct pri * ctrl,struct q931_call * call,int cause)6810 static int q931_send_hold_rej_msg(struct pri *ctrl, struct q931_call *call, int cause)
6811 {
6812 	call->cause = cause;
6813 	call->causecode = CODE_CCITT;
6814 	call->causeloc = LOC_PRIV_NET_LOCAL_USER;
6815 	return send_message(ctrl, call, Q931_HOLD_REJECT, hold_reject_ies);
6816 }
6817 
6818 /*!
6819  * \brief Send the HOLD REJECT message.
6820  *
6821  * \param ctrl D channel controller.
6822  * \param call Q.931 call leg. (Master Q.931 subcall structure)
6823  * \param cause Q.931 cause code for rejecting the hold request.
6824  *
6825  * \retval 0 on success.
6826  * \retval -1 on error.
6827  */
q931_send_hold_rej(struct pri * ctrl,struct q931_call * call,int cause)6828 int q931_send_hold_rej(struct pri *ctrl, struct q931_call *call, int cause)
6829 {
6830 	struct q931_call *winner;
6831 
6832 	UPDATE_HOLD_STATE(ctrl, call, Q931_HOLD_STATE_IDLE);
6833 
6834 	winner = q931_find_winning_call(call);
6835 	if (!winner) {
6836 		return -1;
6837 	}
6838 
6839 	return q931_send_hold_rej_msg(ctrl, winner, cause);
6840 }
6841 
6842 /*!
6843  * \internal
6844  * \brief Send RETRIEVE message response wait timeout.
6845  *
6846  * \param data Q.931 call leg. (Master Q.931 subcall structure)
6847  *
6848  * \return Nothing
6849  */
q931_retrieve_timeout(void * data)6850 static void q931_retrieve_timeout(void *data)
6851 {
6852 	struct q931_call *call = data;
6853 	struct q931_call *master = call->master_call;
6854 	struct pri *ctrl = call->pri;
6855 
6856 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
6857 		pri_message(ctrl, "Time-out waiting for RETRIEVE response\n");
6858 	}
6859 
6860 	/* Ensure that the timer is deleted. */
6861 	pri_schedule_del(ctrl, master->hold_timer);
6862 	master->hold_timer = 0;
6863 
6864 	/* Don't change the hold state if there was RETRIEVE a collision. */
6865 	switch (master->hold_state) {
6866 	case Q931_HOLD_STATE_CALL_HELD:
6867 	case Q931_HOLD_STATE_RETRIEVE_REQ:
6868 		UPDATE_HOLD_STATE(ctrl, master, Q931_HOLD_STATE_CALL_HELD);
6869 
6870 		/* Call is still on hold so forget the channel. */
6871 		call->channelno = 0;/* No channel */
6872 		call->ds1no = 0;
6873 		call->ds1explicit = 0;
6874 		call->chanflags = 0;
6875 		break;
6876 	default:
6877 		break;
6878 	}
6879 
6880 	q931_clr_subcommands(ctrl);
6881 	ctrl->schedev = 1;
6882 	ctrl->ev.e = PRI_EVENT_RETRIEVE_REJ;
6883 	ctrl->ev.retrieve_rej.channel = q931_encode_channel(call);
6884 	ctrl->ev.retrieve_rej.call = master;
6885 	ctrl->ev.retrieve_rej.cause = PRI_CAUSE_MESSAGE_TYPE_NONEXIST;
6886 	ctrl->ev.retrieve_rej.subcmds = &ctrl->subcmds;
6887 }
6888 
6889 /*!
6890  * \internal
6891  * \brief Determine if a retrieve request is allowed now.
6892  *
6893  * \param ctrl D channel controller.
6894  * \param call Q.931 call leg. (Master Q.931 subcall structure)
6895  *
6896  * \retval TRUE if we can send a RETRIEVE request.
6897  * \retval FALSE if not allowed.
6898  */
q931_is_retrieve_allowed(const struct pri * ctrl,const struct q931_call * call)6899 static int q931_is_retrieve_allowed(const struct pri *ctrl, const struct q931_call *call)
6900 {
6901 	int allowed;
6902 
6903 	allowed = 0;
6904 	switch (call->ourcallstate) {
6905 	case Q931_CALL_STATE_CALL_RECEIVED:
6906 	case Q931_CALL_STATE_CONNECT_REQUEST:
6907 	case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
6908 		if (PTMP_MODE(ctrl)) {
6909 			/* RETRIEVE request only allowed in these states if point-to-point mode. */
6910 			break;
6911 		}
6912 		/* Fall through */
6913 	case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
6914 	case Q931_CALL_STATE_CALL_DELIVERED:
6915 	case Q931_CALL_STATE_ACTIVE:
6916 		switch (call->hold_state) {
6917 		case Q931_HOLD_STATE_CALL_HELD:
6918 			allowed = 1;
6919 			break;
6920 		default:
6921 			break;
6922 		}
6923 		break;
6924 	case Q931_CALL_STATE_DISCONNECT_INDICATION:
6925 	case Q931_CALL_STATE_RELEASE_REQUEST:
6926 		/* Ignore RETRIEVE request in these states. */
6927 		break;
6928 	default:
6929 		break;
6930 	}
6931 
6932 	return allowed;
6933 }
6934 
6935 static int retrieve_ies[] = {
6936 	Q931_CHANNEL_IDENT,
6937 	-1
6938 };
6939 
6940 /*!
6941  * \brief Send the RETRIEVE message.
6942  *
6943  * \param ctrl D channel controller.
6944  * \param call Q.931 call leg. (Master Q.931 subcall structure)
6945  * \param channel Encoded channel id to use.  If zero do not send channel id.
6946  *
6947  * \retval 0 on success.
6948  * \retval -1 on error.
6949  */
q931_send_retrieve(struct pri * ctrl,struct q931_call * call,int channel)6950 int q931_send_retrieve(struct pri *ctrl, struct q931_call *call, int channel)
6951 {
6952 	struct q931_call *winner;
6953 
6954 	winner = q931_find_winning_call(call);
6955 	if (!winner || !q931_is_retrieve_allowed(ctrl, call)) {
6956 		return -1;
6957 	}
6958 
6959 	if (channel) {
6960 		winner->ds1no = (channel & 0xff00) >> 8;
6961 		winner->ds1explicit = (channel & 0x10000) >> 16;
6962 		winner->channelno = channel & 0xff;
6963 		if (ctrl->localtype == PRI_NETWORK && winner->channelno != 0xFF) {
6964 			winner->chanflags = FLAG_EXCLUSIVE;
6965 		} else {
6966 			winner->chanflags = FLAG_PREFERRED;
6967 		}
6968 	} else {
6969 		/* Do not send Q931_CHANNEL_IDENT */
6970 		winner->chanflags = 0;
6971 	}
6972 
6973 	pri_schedule_del(ctrl, call->hold_timer);
6974 	call->hold_timer = pri_schedule_event(ctrl, ctrl->timers[PRI_TIMER_T_RETRIEVE],
6975 		q931_retrieve_timeout, winner);
6976 	if (!call->hold_timer || send_message(ctrl, winner, Q931_RETRIEVE, retrieve_ies)) {
6977 		pri_schedule_del(ctrl, call->hold_timer);
6978 		call->hold_timer = 0;
6979 
6980 		/* Call is still on hold so forget the channel. */
6981 		winner->channelno = 0;/* No channel */
6982 		winner->ds1no = 0;
6983 		winner->ds1explicit = 0;
6984 		winner->chanflags = 0;
6985 		return -1;
6986 	}
6987 	UPDATE_HOLD_STATE(ctrl, call, Q931_HOLD_STATE_RETRIEVE_REQ);
6988 	return 0;
6989 }
6990 
6991 static int retrieve_ack_ies[] = {
6992 	Q931_CHANNEL_IDENT,
6993 	-1
6994 };
6995 
6996 /*!
6997  * \brief Send the RETRIEVE ACKNOWLEDGE message.
6998  *
6999  * \param ctrl D channel controller.
7000  * \param call Q.931 call leg. (Master Q.931 subcall structure)
7001  * \param channel Encoded channel id to use.
7002  *
7003  * \retval 0 on success.
7004  * \retval -1 on error.
7005  */
q931_send_retrieve_ack(struct pri * ctrl,struct q931_call * call,int channel)7006 int q931_send_retrieve_ack(struct pri *ctrl, struct q931_call *call, int channel)
7007 {
7008 	struct q931_call *winner;
7009 
7010 	winner = q931_find_winning_call(call);
7011 	if (!winner) {
7012 		return -1;
7013 	}
7014 
7015 	winner->ds1no = (channel & 0xff00) >> 8;
7016 	winner->ds1explicit = (channel & 0x10000) >> 16;
7017 	winner->channelno = channel & 0xff;
7018 	winner->chanflags = FLAG_EXCLUSIVE;
7019 
7020 	UPDATE_HOLD_STATE(ctrl, call, Q931_HOLD_STATE_IDLE);
7021 
7022 	return send_message(ctrl, winner, Q931_RETRIEVE_ACKNOWLEDGE, retrieve_ack_ies);
7023 }
7024 
7025 static int retrieve_reject_ies[] = {
7026 	Q931_CAUSE,
7027 	-1
7028 };
7029 
7030 /*!
7031  * \internal
7032  * \brief Send the RETRIEVE REJECT message only.
7033  *
7034  * \param ctrl D channel controller.
7035  * \param call Q.931 call leg. (subcall)
7036  * \param cause Q.931 cause code for rejecting the retrieve request.
7037  *
7038  * \retval 0 on success.
7039  * \retval -1 on error.
7040  */
q931_send_retrieve_rej_msg(struct pri * ctrl,struct q931_call * call,int cause)7041 static int q931_send_retrieve_rej_msg(struct pri *ctrl, struct q931_call *call, int cause)
7042 {
7043 	call->cause = cause;
7044 	call->causecode = CODE_CCITT;
7045 	call->causeloc = LOC_PRIV_NET_LOCAL_USER;
7046 	return send_message(ctrl, call, Q931_RETRIEVE_REJECT, retrieve_reject_ies);
7047 }
7048 
7049 /*!
7050  * \brief Send the RETRIEVE REJECT message.
7051  *
7052  * \param ctrl D channel controller.
7053  * \param call Q.931 call leg. (Master Q.931 subcall structure)
7054  * \param cause Q.931 cause code for rejecting the retrieve request.
7055  *
7056  * \retval 0 on success.
7057  * \retval -1 on error.
7058  */
q931_send_retrieve_rej(struct pri * ctrl,struct q931_call * call,int cause)7059 int q931_send_retrieve_rej(struct pri *ctrl, struct q931_call *call, int cause)
7060 {
7061 	struct q931_call *winner;
7062 
7063 	UPDATE_HOLD_STATE(ctrl, call, Q931_HOLD_STATE_CALL_HELD);
7064 
7065 	winner = q931_find_winning_call(call);
7066 	if (!winner) {
7067 		return -1;
7068 	}
7069 
7070 	/* Call is still on hold so forget the channel. */
7071 	winner->channelno = 0;/* No channel */
7072 	winner->ds1no = 0;
7073 	winner->ds1explicit = 0;
7074 	winner->chanflags = 0;
7075 
7076 	return q931_send_retrieve_rej_msg(ctrl, winner, cause);
7077 }
7078 
__q931_hangup(struct pri * ctrl,q931_call * c,int cause)7079 static int __q931_hangup(struct pri *ctrl, q931_call *c, int cause)
7080 {
7081 	int disconnect = 1;
7082 	int release_compl = 0;
7083 
7084 	if (!ctrl || !c) {
7085 		return -1;
7086 	}
7087 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7088 		pri_message(ctrl,
7089 			DBGHEAD "ourstate %s, peerstate %s, hold-state %s\n", DBGINFO,
7090 			q931_call_state_str(c->ourcallstate),
7091 			q931_call_state_str(c->peercallstate),
7092 			q931_hold_state_str(c->master_call->hold_state));
7093 	}
7094 
7095 	/* If mandatory IE was missing, insist upon that cause code */
7096 	if (c->cause == PRI_CAUSE_MANDATORY_IE_MISSING)
7097 		cause = c->cause;
7098 	switch (cause) {
7099 	case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
7100 	case PRI_CAUSE_REQUESTED_CHAN_UNAVAIL:
7101 	case PRI_CAUSE_IDENTIFIED_CHANNEL_NOTEXIST:
7102 	case PRI_CAUSE_UNALLOCATED:
7103 		if (!ctrl->hangup_fix_enabled) {
7104 			/* Legacy: We'll send RELEASE_COMPLETE with these causes */
7105 			disconnect = 0;
7106 			release_compl = 1;
7107 			break;
7108 		}
7109 		/* Fall through */
7110 	case PRI_CAUSE_INCOMPATIBLE_DESTINATION:
7111 		/* See Q.931 Section 5.3.2 a) */
7112 		switch (c->ourcallstate) {
7113 		case Q931_CALL_STATE_NULL:
7114 		case Q931_CALL_STATE_CALL_INITIATED:
7115 		case Q931_CALL_STATE_CALL_PRESENT:
7116 			/*
7117 			 * Send RELEASE_COMPLETE because some other message
7118 			 * has not been sent previously.
7119 			 */
7120 			disconnect = 0;
7121 			release_compl = 1;
7122 			break;
7123 		case Q931_CALL_STATE_CONNECT_REQUEST:
7124 			/*
7125 			 * Send RELEASE because the B channel negotiation failed
7126 			 * for call waiting.
7127 			 */
7128 			disconnect = 0;
7129 			break;
7130 		default:
7131 			/*
7132 			 * Send DISCONNECT because some other message
7133 			 * has been sent previously.
7134 			 */
7135 			break;
7136 		}
7137 		break;
7138 	case PRI_CAUSE_INVALID_CALL_REFERENCE:
7139 		/* We'll send RELEASE_COMPLETE with these causes */
7140 		disconnect = 0;
7141 		release_compl = 1;
7142 		break;
7143 	case PRI_CAUSE_CHANNEL_UNACCEPTABLE:
7144 	case PRI_CAUSE_CALL_AWARDED_DELIVERED:
7145 	case PRI_CAUSE_NONSELECTED_USER_CLEARING:
7146 		/* We'll send RELEASE with these causes */
7147 		disconnect = 0;
7148 		break;
7149 	default:
7150 		break;
7151 	}
7152 	if (c->cis_call) {
7153 		disconnect = 0;
7154 	}
7155 
7156 	c->hangupinitiated = 1;
7157 	stop_t303(c);
7158 
7159 	/* All other causes we send with DISCONNECT */
7160 	switch(c->ourcallstate) {
7161 	case Q931_CALL_STATE_NULL:
7162 		if (c->peercallstate == Q931_CALL_STATE_NULL)
7163 			/* free the resources if we receive or send REL_COMPL */
7164 			pri_destroycall(ctrl, c);
7165 		else if (c->peercallstate == Q931_CALL_STATE_RELEASE_REQUEST)
7166 			q931_release_complete(ctrl,c,cause);
7167 		break;
7168 	case Q931_CALL_STATE_CALL_INITIATED:
7169 		/* we sent SETUP */
7170 	case Q931_CALL_STATE_OVERLAP_SENDING:
7171 		/* received SETUP_ACKNOWLEDGE */
7172 	case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
7173 		/* received CALL_PROCEEDING */
7174 	case Q931_CALL_STATE_CALL_DELIVERED:
7175 		/* received ALERTING */
7176 	case Q931_CALL_STATE_CALL_PRESENT:
7177 		/* received SETUP */
7178 	case Q931_CALL_STATE_CALL_RECEIVED:
7179 		/* sent ALERTING */
7180 	case Q931_CALL_STATE_CONNECT_REQUEST:
7181 		/* sent CONNECT */
7182 	case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
7183 		/* we sent CALL_PROCEEDING */
7184 	case Q931_CALL_STATE_OVERLAP_RECEIVING:
7185 		/* received SETUP_ACKNOWLEDGE */
7186 		/* send DISCONNECT in general */
7187 		switch (c->peercallstate) {
7188 		default:
7189 			if (disconnect)
7190 				q931_disconnect(ctrl,c,cause);
7191 			else if (release_compl)
7192 				q931_release_complete(ctrl,c,cause);
7193 			else
7194 				q931_release(ctrl,c,cause);
7195 			break;
7196 		case Q931_CALL_STATE_NULL:
7197 		case Q931_CALL_STATE_DISCONNECT_REQUEST:
7198 		case Q931_CALL_STATE_DISCONNECT_INDICATION:
7199 		case Q931_CALL_STATE_RELEASE_REQUEST:
7200 		case Q931_CALL_STATE_RESTART_REQUEST:
7201 		case Q931_CALL_STATE_RESTART:
7202 			pri_error(ctrl,
7203 				"Weird, doing nothing but this shouldn't happen, ourstate %s, peerstate %s\n",
7204 				q931_call_state_str(c->ourcallstate),
7205 				q931_call_state_str(c->peercallstate));
7206 			break;
7207 		}
7208 		break;
7209 	case Q931_CALL_STATE_ACTIVE:
7210 		/* received CONNECT */
7211 		if (c->cis_call) {
7212 			q931_release(ctrl, c, cause);
7213 			break;
7214 		}
7215 		q931_disconnect(ctrl,c,cause);
7216 		break;
7217 	case Q931_CALL_STATE_DISCONNECT_REQUEST:
7218 		/* sent DISCONNECT */
7219 		q931_release(ctrl,c,cause);
7220 		break;
7221 	case Q931_CALL_STATE_CALL_ABORT:
7222 		/* Don't do anything, waiting for T312 to expire. */
7223 		break;
7224 	case Q931_CALL_STATE_DISCONNECT_INDICATION:
7225 		/* received DISCONNECT */
7226 		if (c->peercallstate == Q931_CALL_STATE_DISCONNECT_REQUEST) {
7227 			c->alive = 1;
7228 			q931_release(ctrl,c,cause);
7229 		}
7230 		break;
7231 	case Q931_CALL_STATE_RELEASE_REQUEST:
7232 		/* sent RELEASE */
7233 		/* don't do anything, waiting for RELEASE_COMPLETE */
7234 		break;
7235 	case Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE:
7236 		/* we sent or received REGISTER */
7237 		q931_release_complete(ctrl, c, cause);
7238 		break;
7239 	case Q931_CALL_STATE_RESTART:
7240 	case Q931_CALL_STATE_RESTART_REQUEST:
7241 		/* sent RESTART */
7242 		pri_error(ctrl,
7243 			"q931_hangup shouldn't be called in this state, ourstate %s, peerstate %s\n",
7244 			q931_call_state_str(c->ourcallstate),
7245 			q931_call_state_str(c->peercallstate));
7246 		break;
7247 	default:
7248 		pri_error(ctrl,
7249 			"We're not yet handling hanging up when our state is %d, contact support@digium.com, ourstate %s, peerstate %s\n",
7250 			c->ourcallstate,
7251 			q931_call_state_str(c->ourcallstate),
7252 			q931_call_state_str(c->peercallstate));
7253 		return -1;
7254 	}
7255 	/* we did handle hangup properly at this point */
7256 	return 0;
7257 }
7258 
7259 static void initiate_hangup_if_needed(struct q931_call *master, int idx, int cause);
7260 
q931_hangup(struct pri * ctrl,q931_call * call,int cause)7261 int q931_hangup(struct pri *ctrl, q931_call *call, int cause)
7262 {
7263 	int i;
7264 
7265 	if (call->master_call->outboundbroadcast) {
7266 		if (call->master_call == call) {
7267 			int slaves;
7268 
7269 			if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7270 				pri_message(ctrl, DBGHEAD "Hangup master cref:%d\n", DBGINFO, call->cr);
7271 			}
7272 
7273 			UPDATE_OURCALLSTATE(ctrl, call, Q931_CALL_STATE_CALL_ABORT);
7274 			if (call->pri_winner < 0 && call->alive) {
7275 				/*
7276 				 * Fake clearing if we have no winner to get rid of the upper
7277 				 * layer.
7278 				 */
7279 				pri_create_fake_clearing(ctrl, call);
7280 			} else if (call->fake_clearing_timer) {
7281 				/*
7282 				 * No need for fake clearing to be running anymore.
7283 				 * Will this actually happen?
7284 				 */
7285 				if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7286 					pri_message(ctrl, "Fake clearing request cancelled.  cref:%d\n",
7287 						call->cr);
7288 				}
7289 				pri_schedule_del(ctrl, call->fake_clearing_timer);
7290 				call->fake_clearing_timer = 0;
7291 			}
7292 
7293 			/* Initiate hangup of slaves */
7294 			call->master_hanging_up = 1;
7295 			for (i = 0; i < ARRAY_LEN(call->subcalls); ++i) {
7296 				if (call->subcalls[i]) {
7297 					if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7298 						pri_message(ctrl, DBGHEAD "Hanging up %d, winner:%d subcall:%p\n",
7299 							DBGINFO, i, call->pri_winner, call->subcalls[i]);
7300 					}
7301 					if (i == call->pri_winner) {
7302 						q931_hangup(ctrl, call->subcalls[i], cause);
7303 					} else {
7304 						initiate_hangup_if_needed(call, i, cause);
7305 					}
7306 				}
7307 			}
7308 			call->master_hanging_up = 0;
7309 
7310 			slaves = q931_get_subcall_count(call);
7311 			if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7312 				pri_message(ctrl, DBGHEAD "Remaining slaves %d\n", DBGINFO, slaves);
7313 			}
7314 
7315 			stop_t303(call);
7316 			if (!call->t312_timer && !slaves) {
7317 				/*
7318 				 * T312 has expired and no slaves are left so we can safely
7319 				 * destroy the master.
7320 				 */
7321 				q931_destroycall(ctrl, call);
7322 			}
7323 			return 0;
7324 		} else {
7325 			if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7326 				pri_message(ctrl, DBGHEAD "Hangup slave cref:%d\n", DBGINFO, call->cr);
7327 			}
7328 			return __q931_hangup(ctrl, call, cause);
7329 		}
7330 	} else {
7331 		if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7332 			pri_message(ctrl, DBGHEAD "Hangup other cref:%d\n", DBGINFO, call->cr);
7333 		}
7334 		return __q931_hangup(ctrl, call, cause);
7335 	}
7336 	return 0;
7337 }
7338 
prepare_to_handle_maintenance_message(struct pri * ctrl,q931_mh * mh,q931_call * c)7339 static int prepare_to_handle_maintenance_message(struct pri *ctrl, q931_mh *mh, q931_call *c)
7340 {
7341 	if ((!ctrl) || (!mh) || (!c)) {
7342 		return -1;
7343 	}
7344 	/* SERVICE messages are a superset of messages that can take b-channels
7345 	 * or entire d-channels in and out of service */
7346 	switch(mh->msg) {
7347 		/* the ATT_SERVICE/ATT_SERVICE_ACKNOWLEDGE and NATIONAL_SERVICE/NATIONAL_SERVICE_ACKNOWLEDGE
7348 		 * are mirrors of each other.  We only have to check for one type because they are pre-handled
7349 		 * the same way as each other */
7350 		case ATT_SERVICE:
7351 		case ATT_SERVICE_ACKNOWLEDGE:
7352 			c->channelno = -1;
7353 			c->slotmap = -1;
7354 			c->chanflags = 0;
7355 			c->ds1explicit = 0;
7356 			c->ds1no = 0;
7357 			c->cis_call = 0;
7358 			c->ri = -1;
7359 			c->changestatus = -1;
7360 			break;
7361 		default:
7362 			pri_error(ctrl,
7363 				"!! Don't know how to pre-handle maintenance message type '0x%X'\n",
7364 				mh->msg);
7365 			return -1;
7366 	}
7367 	return 0;
7368 }
7369 
prepare_to_handle_q931_message(struct pri * ctrl,q931_mh * mh,q931_call * c)7370 static int prepare_to_handle_q931_message(struct pri *ctrl, q931_mh *mh, q931_call *c)
7371 {
7372 	if ((!ctrl) || (!mh) || (!c)) {
7373 		return -1;
7374 	}
7375 
7376 	switch(mh->msg) {
7377 	case Q931_RESTART:
7378 		if (ctrl->debug & PRI_DEBUG_Q931_STATE)
7379 			pri_message(ctrl, "-- Processing Q.931 Restart\n");
7380 		/* Reset information */
7381 		c->channelno = -1;
7382 		c->slotmap = -1;
7383 		c->chanflags = 0;
7384 		c->ds1no = 0;
7385 		c->ds1explicit = 0;
7386 		c->cis_call = 0;
7387 		c->ri = -1;
7388 		break;
7389 	case Q931_FACILITY:
7390 		c->notify = -1;
7391 		q931_party_number_init(&c->redirection_number);
7392 		if (q931_is_dummy_call(c)) {
7393 			q931_party_address_init(&c->called);
7394 		}
7395 		break;
7396 	case Q931_SETUP:
7397 		if (ctrl->debug & PRI_DEBUG_Q931_STATE)
7398 			pri_message(ctrl, "-- Processing Q.931 Call Setup\n");
7399 		c->cc.saved_ie_contents.length = 0;
7400 		c->cc.saved_ie_flags = 0;
7401 		/* Fall through */
7402 	case Q931_REGISTER:
7403 		c->channelno = -1;
7404 		c->slotmap = -1;
7405 		c->chanflags = 0;
7406 		c->ds1no = 0;
7407 		c->ri = -1;
7408 
7409 		c->bc.transcapability = -1;
7410 		c->bc.transmoderate = -1;
7411 		c->bc.transmultiple = -1;
7412 		c->bc.userl1 = -1;
7413 		c->bc.userl2 = -1;
7414 		c->bc.userl3 = -1;
7415 		c->bc.rateadaption = -1;
7416 
7417 		q931_party_address_init(&c->called);
7418 		q931_party_id_init(&c->local_id);
7419 		q931_party_id_init(&c->remote_id);
7420 		q931_party_number_init(&c->ani);
7421 		q931_party_redirecting_init(&c->redirecting);
7422 
7423 		/*
7424 		 * Make sure that keypad and overlap digit buffers are empty in
7425 		 * case they are not in the message.
7426 		 */
7427 		c->keypad_digits[0] = '\0';
7428 		c->overlap_digits[0] = '\0';
7429 
7430 		c->useruserprotocoldisc = -1;
7431 		c->useruserinfo[0] = '\0';
7432 		c->complete = 0;
7433 		c->nonisdn = 0;
7434 		c->aoc_units = -1;
7435 		c->reversecharge = -1;
7436 		/* Fall through */
7437 	case Q931_CONNECT:
7438 	case Q931_ALERTING:
7439 	case Q931_PROGRESS:
7440 		c->useruserinfo[0] = '\0';
7441 		c->cause = -1;
7442 		/* Fall through */
7443 	case Q931_SETUP_ACKNOWLEDGE:
7444 	case Q931_CALL_PROCEEDING:
7445 		c->progress = -1;
7446 		c->progressmask = 0;
7447 		break;
7448 	case Q931_CONNECT_ACKNOWLEDGE:
7449 		pri_schedule_del(ctrl, c->retranstimer);
7450 		c->retranstimer = 0;
7451 		break;
7452 	case Q931_RELEASE:
7453 	case Q931_DISCONNECT:
7454 		c->cause = -1;
7455 		c->causecode = -1;
7456 		c->causeloc = -1;
7457 		c->progress = -1;
7458 		c->progressmask = 0;
7459 		c->aoc_units = -1;
7460 		pri_schedule_del(ctrl, c->retranstimer);
7461 		c->retranstimer = 0;
7462 		c->useruserinfo[0] = '\0';
7463 		break;
7464 	case Q931_RELEASE_COMPLETE:
7465 		pri_schedule_del(ctrl, c->retranstimer);
7466 		c->retranstimer = 0;
7467 		c->useruserinfo[0] = '\0';
7468 		/* Fall through */
7469 	case Q931_STATUS:
7470 		c->cause = -1;
7471 		c->causecode = -1;
7472 		c->causeloc = -1;
7473 		c->sugcallstate = Q931_CALL_STATE_NOT_SET;
7474 		c->aoc_units = -1;
7475 		break;
7476 	case Q931_RESTART_ACKNOWLEDGE:
7477 		c->channelno = -1;
7478 		c->ds1no = 0;
7479 		c->ds1explicit = 0;
7480 		c->cis_call = 0;
7481 		break;
7482 	case Q931_INFORMATION:
7483 		/*
7484 		 * Make sure that keypad and overlap digit buffers are empty in
7485 		 * case they are not in the message.
7486 		 */
7487 		c->keypad_digits[0] = '\0';
7488 		c->overlap_digits[0] = '\0';
7489 		break;
7490 	case Q931_STATUS_ENQUIRY:
7491 		break;
7492 	case Q931_NOTIFY:
7493 		c->notify = -1;
7494 		q931_party_number_init(&c->redirection_number);
7495 		break;
7496 	case Q931_HOLD:
7497 		break;
7498 	case Q931_HOLD_ACKNOWLEDGE:
7499 		break;
7500 	case Q931_HOLD_REJECT:
7501 		c->cause = -1;
7502 		break;
7503 	case Q931_RETRIEVE:
7504 		c->channelno = 0xFF;
7505 		c->ds1no = 0;
7506 		c->ds1explicit = 0;
7507 		break;
7508 	case Q931_RETRIEVE_ACKNOWLEDGE:
7509 		break;
7510 	case Q931_RETRIEVE_REJECT:
7511 		c->cause = -1;
7512 		break;
7513 	case Q931_USER_INFORMATION:
7514 	case Q931_SEGMENT:
7515 	case Q931_CONGESTION_CONTROL:
7516 	case Q931_RESUME:
7517 	case Q931_RESUME_ACKNOWLEDGE:
7518 	case Q931_RESUME_REJECT:
7519 	case Q931_SUSPEND:
7520 	case Q931_SUSPEND_ACKNOWLEDGE:
7521 	case Q931_SUSPEND_REJECT:
7522 		pri_error(ctrl, "!! Not yet handling pre-handle message type %s (0x%X)\n",
7523 			msg2str(mh->msg), mh->msg);
7524 		/* Fall through */
7525 	default:
7526 		pri_error(ctrl, "!! Don't know how to pre-handle message type %s (0x%X)\n",
7527 			msg2str(mh->msg), mh->msg);
7528 		q931_status(ctrl,c, PRI_CAUSE_MESSAGE_TYPE_NONEXIST);
7529 		return -1;
7530 	}
7531 	return 0;
7532 }
7533 
q931_get_subcall_winner(struct q931_call * master)7534 static struct q931_call *q931_get_subcall_winner(struct q931_call *master)
7535 {
7536 	if (master->pri_winner < 0) {
7537 		return NULL;
7538 	} else {
7539 		return master->subcalls[master->pri_winner];
7540 	}
7541 }
7542 
initiate_hangup_if_needed(struct q931_call * master,int idx,int cause)7543 static void initiate_hangup_if_needed(struct q931_call *master, int idx, int cause)
7544 {
7545 	struct pri *ctrl;
7546 	struct q931_call *subcall;
7547 
7548 	ctrl = master->pri;
7549 	subcall = master->subcalls[idx];
7550 
7551 	if (!subcall->hangupinitiated) {
7552 		q931_hangup(ctrl, subcall, cause);
7553 		if (master->subcalls[idx] == subcall) {
7554 			/* The subcall was not destroyed. */
7555 			subcall->alive = 0;
7556 		}
7557 	}
7558 }
7559 
q931_set_subcall_winner(struct q931_call * subcall)7560 static void q931_set_subcall_winner(struct q931_call *subcall)
7561 {
7562 	struct q931_call *master = subcall->master_call;
7563 	int i;
7564 
7565 	/* Set the winner first */
7566 	for (i = 0; ; ++i) {
7567 		if (ARRAY_LEN(master->subcalls) <= i) {
7568 			pri_error(subcall->pri, "We should always find the winner in the list!\n");
7569 			return;
7570 		}
7571 		if (master->subcalls[i] == subcall) {
7572 			master->pri_winner = i;
7573 			break;
7574 		}
7575 	}
7576 
7577 	/* Start tear down of calls that were not chosen */
7578 	for (i = 0; i < ARRAY_LEN(master->subcalls); ++i) {
7579 		if (master->subcalls[i] && master->subcalls[i] != subcall) {
7580 			initiate_hangup_if_needed(master, i, PRI_CAUSE_NONSELECTED_USER_CLEARING);
7581 		}
7582 	}
7583 }
7584 
q931_get_subcall(struct q921_link * link,struct q931_call * master_call)7585 static struct q931_call *q931_get_subcall(struct q921_link *link, struct q931_call *master_call)
7586 {
7587 	int i;
7588 	struct q931_call *cur;
7589 	struct pri *ctrl;
7590 	int firstfree = -1;
7591 
7592 	ctrl = link->ctrl;
7593 
7594 	/* First try to locate our subcall */
7595 	for (i = 0; i < ARRAY_LEN(master_call->subcalls); ++i) {
7596 		if (master_call->subcalls[i]) {
7597 			if (master_call->subcalls[i]->link == link) {
7598 				return master_call->subcalls[i];
7599 			}
7600 		} else if (firstfree == -1) {
7601 			firstfree = i;
7602 		}
7603 	}
7604 	if (firstfree < 0) {
7605 		pri_error(ctrl, "Tried to add more than %d TEIs to call and failed\n",
7606 			(int) ARRAY_LEN(master_call->subcalls));
7607 		return NULL;
7608 	}
7609 
7610 	/* Create new subcall. */
7611 	cur = malloc(sizeof(*cur));
7612 	if (!cur) {
7613 		pri_error(ctrl, "Unable to allocate call\n");
7614 		return NULL;
7615 	}
7616 	*cur = *master_call;
7617 	//cur->pri = ctrl;/* We get this assignment for free. */
7618 	cur->link = link;
7619 	cur->next = NULL;
7620 	cur->apdus = NULL;
7621 	cur->bridged_call = NULL;
7622 	//cur->master_call = master_call; /* We get this assignment for free. */
7623 	for (i = 0; i < ARRAY_LEN(cur->subcalls); ++i) {
7624 		cur->subcalls[i] = NULL;
7625 	}
7626 	cur->t303_timer = 0;/* T303 should only be on on the master call */
7627 	cur->t312_timer = 0;/* T312 should only be on on the master call */
7628 	cur->fake_clearing_timer = 0;/* Fake clearing should only be on on the master call */
7629 	cur->hold_timer = 0;
7630 	cur->retranstimer = 0;
7631 
7632 	/*
7633 	 * Mark this subcall as a newcall until it is determined if the
7634 	 * subcall can compete for the call.
7635 	 */
7636 	cur->newcall = 1;
7637 
7638 	/* Assume we sent a SETUP and this is the first response to it from this peer. */
7639 	cur->ourcallstate = Q931_CALL_STATE_CALL_INITIATED;
7640 	cur->peercallstate = Q931_CALL_STATE_CALL_PRESENT;
7641 
7642 	master_call->subcalls[firstfree] = cur;
7643 
7644 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7645 		pri_message(ctrl, "Adding subcall %p for TEI %d to call %p at position %d\n",
7646 			cur, link->tei, master_call, firstfree);
7647 	}
7648 	/* Should only get here if the TEI is not found */
7649 	return cur;
7650 }
7651 
q931_receive(struct q921_link * link,q931_h * h,int len)7652 int q931_receive(struct q921_link *link, q931_h *h, int len)
7653 {
7654 	q931_mh *mh;
7655 	struct q931_call *c;
7656 	struct pri *ctrl;
7657 	q931_ie *ie;
7658 	unsigned int x;
7659 	int y;
7660 	int res;
7661 	int r;
7662 	int mandies[MAX_MAND_IES];
7663 	int is_mandatory;
7664 	int codeset, cur_codeset;
7665 	int last_ie[8];
7666 	int cref;
7667 	int allow_event;
7668 	int allow_posthandle;
7669 	enum mandatory_ie_status mand_status;
7670 
7671 	ctrl = link->ctrl;
7672 	memset(last_ie, 0, sizeof(last_ie));
7673 	ctrl->q931_rxcount++;
7674 	if (len < 3 || len < 3 + h->crlen) {
7675 		/* Message too short for supported protocols. */
7676 		return -1;
7677 	}
7678 	switch (h->pd) {
7679 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_1:
7680 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_2:
7681 		if (!ctrl->service_message_support) {
7682 			/* Real service message support has not been enabled (and is OFF in libpri by default),
7683 			 * so we have to revert to the 'traditional' KLUDGE of changing byte 4 from a 0xf (SERVICE)
7684 			 * to a 0x7 (SERVICE ACKNOWLEDGE) */
7685 			/* This is the weird maintenance stuff.  We majorly
7686 			   KLUDGE this by changing byte 4 from a 0xf (SERVICE)
7687 			   to a 0x7 (SERVICE ACKNOWLEDGE) */
7688 			h->raw[h->crlen + 2] -= 0x8;
7689 			q931_xmit(link, h, len, 1, 0);
7690 			return 0;
7691 		}
7692 		break;
7693 	default:
7694 		if (h->pd != ctrl->protodisc) {
7695 			pri_error(ctrl,
7696 				"Warning: unknown/inappropriate protocol discriminator received (%02x/%d)\n",
7697 				h->pd, h->pd);
7698 			return 0;
7699 		}
7700 		break;
7701 	}
7702 
7703 	cref = q931_cr(h);
7704 	c = q931_getcall(link, cref);
7705 	if (!c) {
7706 		pri_error(ctrl, "Unable to locate call %d\n", cref);
7707 		return -1;
7708 	}
7709 	if (c->master_call->outboundbroadcast && link != &ctrl->link) {
7710 		c = q931_get_subcall(link, c->master_call);
7711 		if (!c) {
7712 			pri_error(ctrl, "Unable to locate subcall for %d\n", cref);
7713 			return -1;
7714 		}
7715 	}
7716 
7717 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
7718 		pri_message(ctrl,
7719 			"Received message for call %p on link %p TEI/SAPI %d/%d\n",
7720 			c, link, link->tei, link->sapi);
7721 	}
7722 
7723 	/* Preliminary handling */
7724 	ctrl->facility.count = 0;
7725 	c->connected_number_in_message = 0;
7726 	c->redirecting_number_in_message = 0;
7727 	mh = (q931_mh *)(h->contents + h->crlen);
7728 	switch (h->pd) {
7729 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_1:
7730 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_2:
7731 		prepare_to_handle_maintenance_message(ctrl, mh, c);
7732 		break;
7733 	default:
7734 		/* Unknown protocol discriminator but we will treat it as Q.931 anyway. */
7735 	case GR303_PROTOCOL_DISCRIMINATOR:
7736 	case Q931_PROTOCOL_DISCRIMINATOR:
7737 		if (prepare_to_handle_q931_message(ctrl, mh, c)) {
7738 			/* Discard message.  We don't know how to handle it. */
7739 			if (c->newcall) {
7740 				pri_destroycall(ctrl, c);
7741 			}
7742 			return 0;
7743 		}
7744 		break;
7745 	}
7746 	q931_clr_subcommands(ctrl);
7747 	q931_display_clear(c);
7748 
7749 	/* Determine which ies are mandatory for this message. */
7750 	memset(mandies, 0, sizeof(mandies));
7751 	for (x = 0; x < ARRAY_LEN(msgs); ++x)  {
7752 		if (msgs[x].msgnum == mh->msg) {
7753 			memcpy(mandies, msgs[x].mandies, sizeof(mandies));
7754 			break;
7755 		}
7756 	}
7757 	for (x = 0; x < ARRAY_LEN(mandies); ++x) {
7758 		if (mandies[x]) {
7759 			/* Check mandatory channel identification ie exceptions */
7760 			if (mandies[x] != Q931_CHANNEL_IDENT
7761 				/* Always mandatory for RESUME_ACKNOWLEDGE */
7762 				|| mh->msg == Q931_RESUME_ACKNOWLEDGE
7763 				/* Mandatory in Net -> CPE direction for SETUP */
7764 				|| (mh->msg == Q931_SETUP && ctrl->localtype == PRI_CPE)
7765 				/* Mandatory for first SETUP response message in Net -> CPE direction. */
7766 				|| c->channel_id_ie_mandatory) {
7767 				/* ie is mandatory for this message */
7768 				continue;
7769 			}
7770 			/* ie is not mandatory for this message */
7771 			mandies[x] = 0;
7772 		}
7773 	}
7774 	mand_status = MAND_STATUS_OK;
7775 
7776 	/* Do real IE processing */
7777 	len -= (h->crlen + 3);
7778 	codeset = cur_codeset = 0;
7779 	for (x = 0; x < len; x += r) {
7780 		ie = (q931_ie *)(mh->data + x);
7781 		r = ielen_checked(ie, len - x);
7782 		if (r < 0) {
7783 			/* We have garbage on the end of the packet. */
7784 			pri_error(ctrl, "XXX Message longer than it should be?? XXX\n");
7785 			if (x) {
7786 				/* Allow the message anyway.  We have already processed an ie. */
7787 				break;
7788 			}
7789 			q931_display_clear(c);
7790 			return -1;
7791 		}
7792 
7793 		/* Check if processing a mandatory ie. */
7794 		is_mandatory = 0;
7795 		for (y = 0; y < ARRAY_LEN(mandies); ++y) {
7796 			if (mandies[y] == Q931_FULL_IE(cur_codeset, ie->ie)) {
7797 				mandies[y] = 0;
7798 				is_mandatory = 1;
7799 			}
7800 		}
7801 
7802 		/* Special processing for codeset shifts */
7803 		switch (ie->ie & 0xf8) {
7804 		case Q931_LOCKING_SHIFT:
7805 			y = ie->ie & 7;	/* Requested codeset */
7806 			/* Locking shifts couldn't go to lower codeset, and couldn't follows non-locking shifts - verify this */
7807 			if ((cur_codeset != codeset) && (ctrl->debug & PRI_DEBUG_Q931_ANOMALY))
7808 				pri_message(ctrl, "XXX Locking shift immediately follows non-locking shift (from %d through %d to %d) XXX\n", codeset, cur_codeset, y);
7809 			if (y > 0) {
7810 				if ((y < codeset) && (ctrl->debug & PRI_DEBUG_Q931_ANOMALY))
7811 					pri_error(ctrl, "!! Trying to locked downshift codeset from %d to %d !!\n", codeset, y);
7812 				codeset = cur_codeset = y;
7813 			}
7814 			else {
7815 				/* Locking shift to codeset 0 is forbidden by all specifications */
7816 				pri_error(ctrl, "!! Invalid locking shift to codeset 0 !!\n");
7817 			}
7818 			break;
7819 		case Q931_NON_LOCKING_SHIFT:
7820 			cur_codeset = ie->ie & 7;
7821 			break;
7822 		default:
7823 			/* Sanity check for IE code order */
7824 			if (!(ie->ie & 0x80)) {
7825 				if (last_ie[cur_codeset] > ie->ie) {
7826 					if ((ctrl->debug & PRI_DEBUG_Q931_ANOMALY))
7827 						pri_message(ctrl, "XXX Out-of-order IE %d at codeset %d (last was %d)\n", ie->ie, cur_codeset, last_ie[cur_codeset]);
7828 				}
7829 				else
7830 					last_ie[cur_codeset] = ie->ie;
7831 			}
7832 			/* Ignore non-locking shifts for TR41459-based signalling */
7833 			switch (ctrl->switchtype) {
7834 			case PRI_SWITCH_LUCENT5E:
7835 			case PRI_SWITCH_ATT4ESS:
7836 				if (cur_codeset != codeset) {
7837 					if ((ctrl->debug & PRI_DEBUG_Q931_DUMP))
7838 						pri_message(ctrl, "XXX Ignoring IE %d for temporary codeset %d XXX\n", ie->ie, cur_codeset);
7839 					break;
7840 				}
7841 				/* Fall through */
7842 			default:
7843 				y = q931_handle_ie(cur_codeset, ctrl, c, mh->msg, ie);
7844 				if (y < 0 && is_mandatory) {
7845 					/* Error processing mandatory ie. */
7846 					mand_status = MAND_STATUS_CONTENT_ERROR;
7847 					pri_error(ctrl, "%s: Error in mandatory IE %d (cs%d, %s)\n",
7848 						msg2str(mh->msg),
7849 						ie->ie,
7850 						cur_codeset,
7851 						ie2str(Q931_FULL_IE(codeset, ie->ie)));
7852 				}
7853 				/* XXX Applicable to codeset 0 only? XXX */
7854 				if (!cur_codeset && !(ie->ie & 0xf0) && (y < 0)) {
7855 					/*
7856 					 * Q.931 Section 5.8.7.1
7857 					 * Unhandled ies in codeset 0 with the
7858 					 * upper nybble zero are mandatory.
7859 					 */
7860 					mandies[MAX_MAND_IES - 1] = Q931_FULL_IE(cur_codeset, ie->ie);
7861 				}
7862 				break;
7863 			}
7864 			/* Reset current codeset */
7865 			cur_codeset = codeset;
7866 			break;
7867 		}
7868 	}
7869 
7870 	/* Check for missing mandatory ies. */
7871 	for (x = 0; x < ARRAY_LEN(mandies); ++x) {
7872 		if (mandies[x]) {
7873 			/* This mandatory ie was not processed. */
7874 			mand_status = MAND_STATUS_MISSING;
7875 			pri_error(ctrl, "%s: Missing mandatory IE %d (cs%d, %s)\n",
7876 				msg2str(mh->msg),
7877 				Q931_IE_IE(mandies[x]),
7878 				Q931_IE_CODESET(mandies[x]),
7879 				ie2str(mandies[x]));
7880 		}
7881 	}
7882 
7883 	if (mand_status == MAND_STATUS_OK) {
7884 		switch (mh->msg) {
7885 		case Q931_SETUP:
7886 		case Q931_CONNECT:
7887 			if (ctrl->display_flags.receive & PRI_DISPLAY_OPTION_NAME_INITIAL) {
7888 				q931_display_name_get(c, &c->remote_id.name);
7889 			}
7890 			break;
7891 		default:
7892 			break;
7893 		}
7894 
7895 		/* Now handle the facility ie's after all the other ie's were processed. */
7896 		q931_handle_facilities(ctrl, c, mh->msg);
7897 	}
7898 	q931_apdu_msg_expire(ctrl, c, mh->msg);
7899 
7900 	/* Post handling */
7901 	switch (h->pd) {
7902 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_1:
7903 	case MAINTENANCE_PROTOCOL_DISCRIMINATOR_2:
7904 		res = post_handle_maintenance_message(ctrl, h->pd, mh, c);
7905 		q931_display_clear(c);
7906 		break;
7907 	default:
7908 		allow_event = 1;
7909 		allow_posthandle = 1;
7910 
7911 		if (c->master_call->outboundbroadcast) {
7912 			nt_ptmp_handle_q931_message(ctrl, mh, c, &allow_event, &allow_posthandle);
7913 			if (allow_event) {
7914 				q931_apdu_msg_expire(ctrl, c->master_call, mh->msg);
7915 			}
7916 		}
7917 
7918 		if (allow_posthandle) {
7919 			res = post_handle_q931_message(ctrl, mh, c, mand_status);
7920 			if (res == Q931_RES_HAVEEVENT && !allow_event) {
7921 				res = 0;
7922 			}
7923 		} else {
7924 			q931_display_clear(c);
7925 			res = 0;
7926 		}
7927 		break;
7928 	}
7929 	return res;
7930 }
7931 
post_handle_maintenance_message(struct pri * ctrl,int protodisc,struct q931_mh * mh,struct q931_call * c)7932 static int post_handle_maintenance_message(struct pri *ctrl, int protodisc, struct q931_mh *mh, struct q931_call *c)
7933 {
7934 	/* Do some maintenance stuff */
7935 	if (((protodisc == MAINTENANCE_PROTOCOL_DISCRIMINATOR_1) && (mh->msg == ATT_SERVICE))
7936 		|| ((protodisc == MAINTENANCE_PROTOCOL_DISCRIMINATOR_2) && (mh->msg == NATIONAL_SERVICE))) {
7937 		if (c->channelno > 0) {
7938 			ctrl->ev.e = PRI_EVENT_SERVICE;
7939 			ctrl->ev.service.channel = q931_encode_channel(c);
7940 			ctrl->ev.service.changestatus = 0x0f & c->changestatus;
7941 		} else {
7942 			switch (0x0f & c->changestatus) {
7943 			case SERVICE_CHANGE_STATUS_INSERVICE:
7944 				ctrl->ev.e = PRI_EVENT_DCHAN_UP;
7945 				//q921_dchannel_up(ctrl);
7946 				break;
7947 			case SERVICE_CHANGE_STATUS_OUTOFSERVICE:
7948 				ctrl->ev.e = PRI_EVENT_DCHAN_DOWN;
7949 				//q921_dchannel_down(ctrl);
7950 				break;
7951 			default:
7952 				pri_error(ctrl, "!! Don't know how to handle span service change status '%d'\n", (0x0f & c->changestatus));
7953 				return -1;
7954 			}
7955 		}
7956 		maintenance_service_ack(ctrl, c);
7957 		return Q931_RES_HAVEEVENT;
7958 	}
7959 	if (((protodisc == MAINTENANCE_PROTOCOL_DISCRIMINATOR_1) && (mh->msg == ATT_SERVICE_ACKNOWLEDGE))
7960 		|| ((protodisc == MAINTENANCE_PROTOCOL_DISCRIMINATOR_2) && (mh->msg == NATIONAL_SERVICE_ACKNOWLEDGE))) {
7961 		if (c->channelno > 0) {
7962 			ctrl->ev.e = PRI_EVENT_SERVICE_ACK;
7963 			ctrl->ev.service_ack.channel = q931_encode_channel(c);
7964 			ctrl->ev.service_ack.changestatus = 0x0f & c->changestatus;
7965 		} else {
7966 			switch (0x0f & c->changestatus) {
7967 			case SERVICE_CHANGE_STATUS_INSERVICE:
7968 				ctrl->ev.e = PRI_EVENT_DCHAN_UP;
7969 				//q921_dchannel_up(ctrl);
7970 				break;
7971 			case SERVICE_CHANGE_STATUS_OUTOFSERVICE:
7972 				ctrl->ev.e = PRI_EVENT_DCHAN_DOWN;
7973 				//q921_dchannel_down(ctrl);
7974 				break;
7975 			default:
7976 				pri_error(ctrl, "!! Don't know how to handle span service change status '%d'\n", (0x0f & c->changestatus));
7977 				return -1;
7978 			}
7979 		}
7980 		return Q931_RES_HAVEEVENT;
7981 	}
7982 
7983 	pri_error(ctrl, "!! Don't know how to post-handle maintenance message type 0x%X\n",
7984 		mh->msg);
7985 	return -1;
7986 }
7987 
7988 /*!
7989  * \internal
7990  * \brief Rank the given Q.931 call state for call etablishment.
7991  *
7992  * \param state Q.931 call state to rank for competing PTMP NT calls.
7993  *
7994  * \return Call establishment state ranking.
7995  */
q931_rank_state(enum Q931_CALL_STATE state)7996 static enum Q931_RANKED_CALL_STATE q931_rank_state(enum Q931_CALL_STATE state)
7997 {
7998 	enum Q931_RANKED_CALL_STATE rank;
7999 
8000 	switch (state) {
8001 	case Q931_CALL_STATE_CALL_INITIATED:
8002 	case Q931_CALL_STATE_CALL_PRESENT:
8003 		rank = Q931_RANKED_CALL_STATE_PRESENT;
8004 		break;
8005 	case Q931_CALL_STATE_OVERLAP_SENDING:
8006 	case Q931_CALL_STATE_OVERLAP_RECEIVING:
8007 		rank = Q931_RANKED_CALL_STATE_OVERLAP;
8008 		break;
8009 	case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
8010 	case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
8011 		rank = Q931_RANKED_CALL_STATE_PROCEEDING;
8012 		break;
8013 	case Q931_CALL_STATE_CALL_DELIVERED:
8014 	case Q931_CALL_STATE_CALL_RECEIVED:
8015 	case Q931_CALL_STATE_CONNECT_REQUEST:
8016 		rank = Q931_RANKED_CALL_STATE_ALERTING;
8017 		break;
8018 	case Q931_CALL_STATE_ACTIVE:
8019 	case Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE:
8020 		rank = Q931_RANKED_CALL_STATE_CONNECT;
8021 		break;
8022 	case Q931_CALL_STATE_CALL_ABORT:
8023 		rank = Q931_RANKED_CALL_STATE_ABORT;
8024 		break;
8025 	default:
8026 		rank = Q931_RANKED_CALL_STATE_OTHER;
8027 		break;
8028 	}
8029 
8030 	return rank;
8031 }
8032 
8033 /*!
8034  * \brief Determine if the master will pass an event to the upper layer.
8035  *
8036  * \param ctrl D channel controller.
8037  * \param subcall Q.931 call leg.
8038  * \param msg_type Current message type being processed.
8039  *
8040  * \note This function must parallel nt_ptmp_handle_q931_message().
8041  *
8042  * \retval TRUE if the master will pass an event to the upper layer.
8043  * \retval FALSE if the event will be blocked.
8044  */
q931_master_pass_event(struct pri * ctrl,struct q931_call * subcall,int msg_type)8045 int q931_master_pass_event(struct pri *ctrl, struct q931_call *subcall, int msg_type)
8046 {
8047 	struct q931_call *winner;
8048 	struct q931_call *master;
8049 	enum Q931_RANKED_CALL_STATE master_rank;
8050 	enum Q931_RANKED_CALL_STATE subcall_rank;
8051 	int will_pass;	/*!< TRUE if the master will pass an event to the upper layer. */
8052 
8053 	master = subcall->master_call;
8054 	if (subcall == master) {
8055 		/* We are the master call so of course the master will pass an event. */
8056 		return 1;
8057 	}
8058 
8059 	winner = q931_get_subcall_winner(master);
8060 	if (winner && subcall == winner) {
8061 		/* We are the winner so of course the master will pass an event. */
8062 		return 1;
8063 	}
8064 
8065 	master_rank = q931_rank_state(master->ourcallstate);
8066 	will_pass = 0;
8067 	switch (msg_type) {
8068 	case Q931_SETUP_ACKNOWLEDGE:
8069 #if 0	/* Overlap dialing in PTMP NT mode not supported at the present time. */
8070 		if (master_rank < Q931_RANKED_CALL_STATE_OVERLAP) {
8071 			will_pass = 1;
8072 		}
8073 #endif	/* Overlap dialing in PTMP NT mode not supported at the present time. */
8074 		break;
8075 	case Q931_CALL_PROCEEDING:
8076 		if (master_rank < Q931_RANKED_CALL_STATE_PROCEEDING) {
8077 			will_pass = 1;
8078 		}
8079 		break;
8080 	case Q931_PROGRESS:
8081 		/*
8082 		 * We will just ignore this message since there could be multiple devices
8083 		 * competing for this call.  Who has access to the B channel at this time
8084 		 * to give in-band signals anyway?
8085 		 */
8086 		break;
8087 	case Q931_ALERTING:
8088 		if (master_rank < Q931_RANKED_CALL_STATE_ALERTING) {
8089 			will_pass = 1;
8090 		}
8091 		break;
8092 	case Q931_CONNECT:
8093 		if (master_rank < Q931_RANKED_CALL_STATE_CONNECT) {
8094 			/* We are expected to be the winner for the next message. */
8095 			will_pass = 1;
8096 		}
8097 		break;
8098 	case Q931_DISCONNECT:
8099 	case Q931_RELEASE:
8100 	case Q931_RELEASE_COMPLETE:
8101 		/* Only deal with the winner. */
8102 		break;
8103 	case Q931_FACILITY:
8104 	case Q931_NOTIFY:
8105 		if (!winner) {
8106 			/* The overlap rank does not count here. */
8107 			if (master_rank == Q931_RANKED_CALL_STATE_OVERLAP) {
8108 				master_rank = Q931_RANKED_CALL_STATE_PRESENT;
8109 			}
8110 			subcall_rank = q931_rank_state(subcall->ourcallstate);
8111 			if (subcall_rank == Q931_RANKED_CALL_STATE_OVERLAP) {
8112 				subcall_rank = Q931_RANKED_CALL_STATE_PRESENT;
8113 			}
8114 			if (master_rank == subcall_rank) {
8115 				/*
8116 				 * No winner yet but the subcall is as advanced as the master.
8117 				 * Allow the supplementary service event to pass.
8118 				 */
8119 				will_pass = 1;
8120 			}
8121 		}
8122 		break;
8123 	default:
8124 		/* Only deal with the winner. */
8125 		break;
8126 	}
8127 
8128 	return will_pass;
8129 }
8130 
8131 /*!
8132  * \internal
8133  * \brief Handle outboundbroadcast incoming messages for the master_call's state.
8134  *
8135  * \param ctrl D channel controller.
8136  * \param mh Q.931 message type header.
8137  * \param subcall Q.931 call leg.
8138  * \param allow_event Where to set the allow event to upper layer flag.
8139  * \param allow_posthandle Where to set the allow post handle event flag.
8140  *
8141  * \details
8142  * This is where we interact the subcalls state with the master_call's state.
8143  *
8144  * \note This function must parallel q931_master_pass_event().
8145  *
8146  * \return Nothing
8147  */
nt_ptmp_handle_q931_message(struct pri * ctrl,struct q931_mh * mh,struct q931_call * subcall,int * allow_event,int * allow_posthandle)8148 static void nt_ptmp_handle_q931_message(struct pri *ctrl, struct q931_mh *mh, struct q931_call *subcall, int *allow_event, int *allow_posthandle)
8149 {
8150 	struct q931_call *master = subcall->master_call;
8151 	struct q931_call *winner = q931_get_subcall_winner(master);
8152 	enum Q931_RANKED_CALL_STATE master_rank;
8153 	enum Q931_RANKED_CALL_STATE subcall_rank;
8154 
8155 	/* For broadcast calls, we default to not allowing events to keep events received to a minimum
8156 	 * and to allow post processing, since that is where hangup and subcall state handling and other processing is done */
8157 	*allow_event = 0;
8158 	*allow_posthandle = 1;
8159 
8160 	master_rank = q931_rank_state(master->ourcallstate);
8161 	if (master_rank < Q931_RANKED_CALL_STATE_CONNECT) {
8162 		/* This subcall can compete for the call. */
8163 		subcall->newcall = 0;
8164 	}
8165 
8166 	switch (mh->msg) {
8167 	case Q931_SETUP_ACKNOWLEDGE:
8168 #if 0	/* Overlap dialing in PTMP NT mode not supported at the present time. */
8169 		if (master_rank < Q931_RANKED_CALL_STATE_OVERLAP) {
8170 			*allow_event = 1;
8171 			UPDATE_OURCALLSTATE(ctrl, master, Q931_CALL_STATE_OVERLAP_SENDING);
8172 		}
8173 #endif	/* Overlap dialing in PTMP NT mode not supported at the present time. */
8174 		break;
8175 	case Q931_CALL_PROCEEDING:
8176 		if (master_rank < Q931_RANKED_CALL_STATE_PROCEEDING) {
8177 			*allow_event = 1;
8178 			UPDATE_OURCALLSTATE(ctrl, master, Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING);
8179 		}
8180 		break;
8181 	case Q931_PROGRESS:
8182 		/*
8183 		 * We will just ignore this message since there could be multiple devices
8184 		 * competing for this call.  Who has access to the B channel at this time
8185 		 * to give in-band signals anyway?
8186 		 */
8187 		break;
8188 	case Q931_ALERTING:
8189 		if (master_rank < Q931_RANKED_CALL_STATE_ALERTING) {
8190 			*allow_event = 1;
8191 			UPDATE_OURCALLSTATE(ctrl, master, Q931_CALL_STATE_CALL_DELIVERED);
8192 		}
8193 		break;
8194 	case Q931_CONNECT:
8195 		if (master_rank < Q931_RANKED_CALL_STATE_CONNECT) {
8196 			UPDATE_OURCALLSTATE(ctrl, master, Q931_CALL_STATE_ACTIVE);
8197 			q931_set_subcall_winner(subcall);
8198 			*allow_event = 1;
8199 		} else {
8200 			/* Call clearing of non selected calls occurs in
8201 			 * q931_set_subcall_winner() - All we need to do is make sure
8202 			 * that this connect is not acknowledged */
8203 			*allow_posthandle = 0;
8204 		}
8205 		break;
8206 	case Q931_DISCONNECT:
8207 	case Q931_RELEASE:
8208 	case Q931_RELEASE_COMPLETE:
8209 		if (!winner) {
8210 			int master_priority;
8211 			int slave_priority;
8212 
8213 			/* Pass up the cause on a priority basis. */
8214 			switch (master->cause) {
8215 			case PRI_CAUSE_USER_BUSY:
8216 				master_priority = 2;
8217 				break;
8218 			case PRI_CAUSE_CALL_REJECTED:
8219 				master_priority = 1;
8220 				break;
8221 			default:
8222 				master_priority = 0;
8223 				break;
8224 			case -1:
8225 				/* First time priority. */
8226 				master_priority = -2;
8227 				break;
8228 			}
8229 			switch (subcall->cause) {
8230 			case PRI_CAUSE_USER_BUSY:
8231 				slave_priority = 2;
8232 				break;
8233 			case PRI_CAUSE_CALL_REJECTED:
8234 				slave_priority = 1;
8235 				break;
8236 			default:
8237 				slave_priority = 0;
8238 				break;
8239 			case PRI_CAUSE_INCOMPATIBLE_DESTINATION:
8240 				/* Cause explicitly ignored */
8241 				slave_priority = -1;
8242 				break;
8243 			}
8244 			if (master_priority < slave_priority) {
8245 				/* Pass up the cause to the master. */
8246 				master->cause = subcall->cause;
8247 			}
8248 		} else {
8249 			/* There *is* a winner */
8250 			if (subcall == winner) {
8251 				/* .. and we're it: */
8252 				*allow_event = 1;
8253 				UPDATE_OURCALLSTATE(ctrl, master, Q931_CALL_STATE_CALL_ABORT);
8254 			}
8255 		}
8256 		break;
8257 	case Q931_FACILITY:
8258 	case Q931_NOTIFY:
8259 		if (winner) {
8260 			if (subcall == winner) {
8261 				/* Only deal with the winner. */
8262 				*allow_event = 1;
8263 			}
8264 		} else {
8265 			/* The overlap rank does not count here. */
8266 			if (master_rank == Q931_RANKED_CALL_STATE_OVERLAP) {
8267 				master_rank = Q931_RANKED_CALL_STATE_PRESENT;
8268 			}
8269 			subcall_rank = q931_rank_state(subcall->ourcallstate);
8270 			if (subcall_rank == Q931_RANKED_CALL_STATE_OVERLAP) {
8271 				subcall_rank = Q931_RANKED_CALL_STATE_PRESENT;
8272 			}
8273 			if (master_rank == subcall_rank) {
8274 				/*
8275 				 * No winner yet but the subcall is as advanced as the master.
8276 				 * Allow the supplementary service event to pass.
8277 				 */
8278 				*allow_event = 1;
8279 			}
8280 		}
8281 		break;
8282 	default:
8283 		if (winner && subcall == winner) {
8284 			/* Only deal with the winner. */
8285 			*allow_event = 1;
8286 		}
8287 		break;
8288 	}
8289 }
8290 
8291 /*!
8292  * \internal
8293  * \brief Fill in the RING event fields.
8294  *
8295  * \param ctrl D channel controller.
8296  * \param call Q.931 call leg
8297  *
8298  * \return Nothing
8299  */
q931_fill_ring_event(struct pri * ctrl,struct q931_call * call)8300 static void q931_fill_ring_event(struct pri *ctrl, struct q931_call *call)
8301 {
8302 	struct pri_subcommand *subcmd;
8303 
8304 	if (call->redirecting.from.number.valid && !call->redirecting.count) {
8305 		/*
8306 		 * This is most likely because the redirecting number came in
8307 		 * with the redirecting ie only and not a DivertingLegInformation2.
8308 		 */
8309 		call->redirecting.count = 1;
8310 	}
8311 	if (call->redirecting.state == Q931_REDIRECTING_STATE_PENDING_TX_DIV_LEG_3) {
8312 		/*
8313 		 * Valid for Q.SIG and ETSI PRI/BRI-PTP modes:
8314 		 * Setup the redirecting.to informtion so we can identify
8315 		 * if the user wants to manually supply the COLR for this
8316 		 * redirected to number if further redirects could happen.
8317 		 *
8318 		 * All the user needs to do is set the REDIRECTING(to-pres)
8319 		 * to the COLR and REDIRECTING(to-num) = complete-dialed-number
8320 		 * (i.e. CALLERID(dnid)) to be safe after determining that the
8321 		 * incoming call was redirected by checking if the
8322 		 * REDIRECTING(count) is nonzero.
8323 		 */
8324 		call->redirecting.to.number = call->called.number;
8325 		call->redirecting.to.number.presentation =
8326 			PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
8327 	}
8328 
8329 	ctrl->ev.e = PRI_EVENT_RING;
8330 	ctrl->ev.ring.subcmds = &ctrl->subcmds;
8331 	ctrl->ev.ring.channel = q931_encode_channel(call);
8332 
8333 	/* Calling party information */
8334 	ctrl->ev.ring.callingpres = q931_party_id_presentation(&call->remote_id);
8335 	ctrl->ev.ring.callingplan = call->remote_id.number.plan;
8336 	if (call->ani.valid) {
8337 		ctrl->ev.ring.callingplanani = call->ani.plan;
8338 		libpri_copy_string(ctrl->ev.ring.callingani, call->ani.str,
8339 			sizeof(ctrl->ev.ring.callingani));
8340 	} else {
8341 		ctrl->ev.ring.callingplanani = -1;
8342 		ctrl->ev.ring.callingani[0] = '\0';
8343 	}
8344 	libpri_copy_string(ctrl->ev.ring.callingnum, call->remote_id.number.str,
8345 		sizeof(ctrl->ev.ring.callingnum));
8346 	libpri_copy_string(ctrl->ev.ring.callingname, call->remote_id.name.str,
8347 		sizeof(ctrl->ev.ring.callingname));
8348 	q931_party_id_copy_to_pri(&ctrl->ev.ring.calling, &call->remote_id);
8349 	/* for backwards compatibility, still need ctrl->ev.ring.callingsubaddr */
8350 	if (!call->remote_id.subaddress.type) {
8351 		/* NSAP: Type = 0 */
8352 		libpri_copy_string(ctrl->ev.ring.callingsubaddr,
8353 			(char *) call->remote_id.subaddress.data,
8354 			sizeof(ctrl->ev.ring.callingsubaddr));
8355 	} else {
8356 		ctrl->ev.ring.callingsubaddr[0] = '\0';
8357 	}
8358 
8359 	ctrl->ev.ring.ani2 = call->ani2;
8360 
8361 	/* Called party information */
8362 	ctrl->ev.ring.calledplan = call->called.number.plan;
8363 	libpri_copy_string(ctrl->ev.ring.callednum, call->called.number.str,
8364 		sizeof(ctrl->ev.ring.callednum));
8365 	q931_party_subaddress_copy_to_pri(&ctrl->ev.ring.called_subaddress,
8366 		&call->called.subaddress);
8367 
8368 	/* Original called party information (For backward compatibility) */
8369 	libpri_copy_string(ctrl->ev.ring.origcalledname,
8370 		call->redirecting.orig_called.name.str, sizeof(ctrl->ev.ring.origcalledname));
8371 	libpri_copy_string(ctrl->ev.ring.origcallednum,
8372 		call->redirecting.orig_called.number.str, sizeof(ctrl->ev.ring.origcallednum));
8373 	ctrl->ev.ring.callingplanorigcalled = call->redirecting.orig_called.number.plan;
8374 	if (call->redirecting.orig_called.number.valid
8375 		|| call->redirecting.orig_called.name.valid) {
8376 		ctrl->ev.ring.origredirectingreason = call->redirecting.orig_reason;
8377 	} else {
8378 		ctrl->ev.ring.origredirectingreason = -1;
8379 	}
8380 
8381 	/* Redirecting from party information (For backward compatibility) */
8382 	ctrl->ev.ring.callingplanrdnis = call->redirecting.from.number.plan;
8383 	libpri_copy_string(ctrl->ev.ring.redirectingnum, call->redirecting.from.number.str,
8384 		sizeof(ctrl->ev.ring.redirectingnum));
8385 	libpri_copy_string(ctrl->ev.ring.redirectingname, call->redirecting.from.name.str,
8386 		sizeof(ctrl->ev.ring.redirectingname));
8387 
8388 	ctrl->ev.ring.redirectingreason = call->redirecting.reason;
8389 
8390 	libpri_copy_string(ctrl->ev.ring.useruserinfo, call->useruserinfo,
8391 		sizeof(ctrl->ev.ring.useruserinfo));
8392 	call->useruserinfo[0] = '\0';
8393 
8394 	libpri_copy_string(ctrl->ev.ring.keypad_digits, call->keypad_digits,
8395 		sizeof(ctrl->ev.ring.keypad_digits));
8396 
8397 	ctrl->ev.ring.flexible = !(call->chanflags & FLAG_EXCLUSIVE);
8398 	ctrl->ev.ring.cref = call->cr;
8399 	ctrl->ev.ring.call = call->master_call;
8400 	ctrl->ev.ring.layer1 = call->bc.userl1;
8401 	ctrl->ev.ring.complete = call->complete;
8402 	ctrl->ev.ring.ctype = call->bc.transcapability;
8403 	ctrl->ev.ring.progress = call->progress;
8404 	ctrl->ev.ring.progressmask = call->progressmask;
8405 	ctrl->ev.ring.reversecharge = call->reversecharge;
8406 
8407 	if (call->redirecting.count) {
8408 		subcmd = q931_alloc_subcommand(ctrl);
8409 		if (subcmd) {
8410 			/* Setup redirecting subcommand */
8411 			subcmd->cmd = PRI_SUBCMD_REDIRECTING;
8412 			q931_party_redirecting_copy_to_pri(&subcmd->u.redirecting,
8413 				&call->redirecting);
8414 		}
8415 	}
8416 }
8417 
8418 /*!
8419  * \internal
8420  * \brief Fill in the FACILITY event fields.
8421  *
8422  * \param ctrl D channel controller.
8423  * \param call Q.931 call leg.
8424  *
8425  * \return Nothing
8426  */
q931_fill_facility_event(struct pri * ctrl,struct q931_call * call)8427 static void q931_fill_facility_event(struct pri *ctrl, struct q931_call *call)
8428 {
8429 	ctrl->ev.e = PRI_EVENT_FACILITY;
8430 	ctrl->ev.facility.subcmds = &ctrl->subcmds;
8431 	ctrl->ev.facility.channel = q931_encode_channel(call);
8432 	ctrl->ev.facility.cref = call->cr;
8433 	if (q931_is_dummy_call(call)) {
8434 		ctrl->ev.facility.call = NULL;
8435 	} else {
8436 		ctrl->ev.facility.call = call->master_call;
8437 	}
8438 	ctrl->ev.facility.subcall = call;
8439 
8440 	/* Need to do this for backward compatibility with struct pri_event_facname */
8441 	libpri_copy_string(ctrl->ev.facility.callingname, call->remote_id.name.str,
8442 		sizeof(ctrl->ev.facility.callingname));
8443 	libpri_copy_string(ctrl->ev.facility.callingnum, call->remote_id.number.str,
8444 		sizeof(ctrl->ev.facility.callingnum));
8445 	ctrl->ev.facility.callingpres = q931_party_id_presentation(&call->remote_id);
8446 	ctrl->ev.facility.callingplan = call->remote_id.number.plan;
8447 }
8448 
8449 /*!
8450  * \internal
8451  * \brief APDU wait for response message timeout.
8452  *
8453  * \param data Callback data pointer.
8454  *
8455  * \return Nothing
8456  */
q931_apdu_timeout(void * data)8457 static void q931_apdu_timeout(void *data)
8458 {
8459 	struct apdu_event *apdu;
8460 	struct pri *ctrl;
8461 	struct q931_call *call;
8462 	int free_it;
8463 
8464 	apdu = data;
8465 	call = apdu->call;
8466 	ctrl = call->pri;
8467 
8468 	/*
8469 	 * Extract the APDU from the list so it cannot be
8470 	 * deleted from under us by the callback.
8471 	 */
8472 	free_it = pri_call_apdu_extract(call, apdu);
8473 
8474 	q931_clr_subcommands(ctrl);
8475 	apdu->response.callback(APDU_CALLBACK_REASON_TIMEOUT, ctrl, call, apdu, NULL);
8476 	if (ctrl->subcmds.counter_subcmd) {
8477 		q931_fill_facility_event(ctrl, call);
8478 		ctrl->schedev = 1;
8479 	}
8480 
8481 	if (free_it) {
8482 		free(apdu);
8483 	}
8484 }
8485 
8486 /*!
8487  * \brief Generic call-completion timeout event handler.
8488  *
8489  * \param ctrl D channel controller.
8490  * \param cc_record Call completion record to process event.
8491  * \param event Event to process.
8492  *
8493  * \retval nonzero if cc record destroyed because FSM completed.
8494  */
q931_cc_timeout(struct pri * ctrl,struct pri_cc_record * cc_record,enum CC_EVENTS event)8495 int q931_cc_timeout(struct pri *ctrl, struct pri_cc_record *cc_record, enum CC_EVENTS event)
8496 {
8497 	q931_call *call;
8498 	q931_call *dummy;
8499 	int fsm_complete;
8500 
8501 	q931_clr_subcommands(ctrl);
8502 	dummy = ctrl->link.dummy_call;
8503 	call = cc_record->signaling;
8504 	if (!call) {
8505 		/* Substitute the broadcast dummy call reference call. */
8506 		call = dummy;
8507 	}
8508 	fsm_complete = pri_cc_event(ctrl, call, cc_record, event);
8509 	if (ctrl->subcmds.counter_subcmd) {
8510 		q931_fill_facility_event(ctrl, dummy);
8511 		ctrl->schedev = 1;
8512 	}
8513 	return fsm_complete;
8514 }
8515 
8516 /*!
8517  * \brief Generic call-completion indirect event creation.
8518  *
8519  * \param ctrl D channel controller.
8520  * \param cc_record Call completion record to process event.
8521  * \param func Function to call that will generate a libpri event.
8522  *
8523  * \return Nothing
8524  */
q931_cc_indirect(struct pri * ctrl,struct pri_cc_record * cc_record,void (* func)(struct pri * ctrl,q931_call * call,struct pri_cc_record * cc_record))8525 void q931_cc_indirect(struct pri *ctrl, struct pri_cc_record *cc_record, void (*func)(struct pri *ctrl, q931_call *call, struct pri_cc_record *cc_record))
8526 {
8527 	q931_call *call;
8528 	q931_call *dummy;
8529 
8530 	q931_clr_subcommands(ctrl);
8531 	dummy = ctrl->link.dummy_call;
8532 	call = cc_record->signaling;
8533 	if (!call) {
8534 		/* Substitute the broadcast dummy call reference call. */
8535 		call = dummy;
8536 	}
8537 	func(ctrl, call, cc_record);
8538 	if (ctrl->subcmds.counter_subcmd) {
8539 		q931_fill_facility_event(ctrl, dummy);
8540 		ctrl->schedev = 1;
8541 	}
8542 }
8543 
8544 /*!
8545  * \brief Find the transfer call indicated by the given link_id.
8546  *
8547  * \param ctrl D channel controller.
8548  * \param link_id Link id of the other call involved in the transfer.
8549  *
8550  * \retval found-master-call on success.
8551  * \retval NULL on error.
8552  */
q931_find_link_id_call(struct pri * ctrl,int link_id)8553 struct q931_call *q931_find_link_id_call(struct pri *ctrl, int link_id)
8554 {
8555 	struct q931_call *cur;
8556 	struct q931_call *winner;
8557 	struct q931_call *match;
8558 
8559 	match = NULL;
8560 	for (cur = *ctrl->callpool; cur; cur = cur->next) {
8561 		if (cur->is_link_id_valid && cur->link_id == link_id) {
8562 			/* Found the link_id call. */
8563 			winner = q931_find_winning_call(cur);
8564 			if (!winner) {
8565 				/* There is no winner. */
8566 				break;
8567 			}
8568 			switch (winner->ourcallstate) {
8569 			case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
8570 			case Q931_CALL_STATE_CALL_DELIVERED:
8571 			case Q931_CALL_STATE_CALL_RECEIVED:
8572 			case Q931_CALL_STATE_CONNECT_REQUEST:
8573 			case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
8574 			case Q931_CALL_STATE_ACTIVE:
8575 				/* The link_id call is in a state suitable for transfer. */
8576 				match = cur;
8577 				break;
8578 			default:
8579 				/* The link_id call is not in a good state to transfer. */
8580 				break;
8581 			}
8582 			break;
8583 		}
8584 	}
8585 
8586 	return match;
8587 }
8588 
8589 /*!
8590  * \brief Find the active call given the held call.
8591  *
8592  * \param ctrl D channel controller.
8593  * \param held_call Held call to help locate a compatible active call.
8594  *
8595  * \retval master-active-call on success.
8596  * \retval NULL on error.
8597  */
q931_find_held_active_call(struct pri * ctrl,struct q931_call * held_call)8598 struct q931_call *q931_find_held_active_call(struct pri *ctrl, struct q931_call *held_call)
8599 {
8600 	struct q931_call *cur;
8601 	struct q931_call *winner;
8602 	struct q931_call *match;
8603 
8604 	if (!held_call->link) {
8605 		/* Held call does not have an active link. */
8606 		return NULL;
8607 	}
8608 	match = NULL;
8609 	for (cur = *ctrl->callpool; cur; cur = cur->next) {
8610 		if (cur->hold_state == Q931_HOLD_STATE_IDLE) {
8611 			/* Found an active call. */
8612 			winner = q931_find_winning_call(cur);
8613 			if (!winner || (BRI_NT_PTMP(ctrl) && winner->link != held_call->link)) {
8614 				/* There is no winner or the active call does not go to the same TEI. */
8615 				continue;
8616 			}
8617 			switch (winner->ourcallstate) {
8618 			case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
8619 			case Q931_CALL_STATE_CALL_DELIVERED:
8620 			case Q931_CALL_STATE_CALL_RECEIVED:
8621 			case Q931_CALL_STATE_CONNECT_REQUEST:
8622 			case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
8623 			case Q931_CALL_STATE_ACTIVE:
8624 				break;
8625 			default:
8626 				/* Active call not in a good state to transfer. */
8627 				continue;
8628 			}
8629 			if (q931_party_number_cmp(&winner->remote_id.number,
8630 				&held_call->remote_id.number)) {
8631 				/* The remote party number does not match.  This is a weak match. */
8632 				match = cur;
8633 				continue;
8634 			}
8635 			/* Found an exact match. */
8636 			match = cur;
8637 			break;
8638 		}
8639 	}
8640 
8641 	return match;
8642 }
8643 
8644 /*!
8645  * \internal
8646  * \brief Find the held call given the active call.
8647  *
8648  * \param ctrl D channel controller.
8649  * \param active_call Active call to help locate a compatible held call.
8650  *
8651  * \retval master-held-call on success.
8652  * \retval NULL on error.
8653  */
q931_find_held_call(struct pri * ctrl,struct q931_call * active_call)8654 static struct q931_call *q931_find_held_call(struct pri *ctrl, struct q931_call *active_call)
8655 {
8656 	struct q931_call *cur;
8657 	struct q931_call *winner;
8658 	struct q931_call *match;
8659 
8660 	if (!active_call->link) {
8661 		/* Active call does not have an active link. */
8662 		return NULL;
8663 	}
8664 	match = NULL;
8665 	for (cur = *ctrl->callpool; cur; cur = cur->next) {
8666 		if (cur->hold_state == Q931_HOLD_STATE_CALL_HELD) {
8667 			/* Found a held call. */
8668 			winner = q931_find_winning_call(cur);
8669 			if (!winner || (BRI_NT_PTMP(ctrl) && winner->link != active_call->link)) {
8670 				/* There is no winner or the held call does not go to the same TEI. */
8671 				continue;
8672 			}
8673 			switch (winner->ourcallstate) {
8674 			case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
8675 			case Q931_CALL_STATE_CALL_DELIVERED:
8676 			case Q931_CALL_STATE_CALL_RECEIVED:
8677 			case Q931_CALL_STATE_CONNECT_REQUEST:
8678 			case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
8679 			case Q931_CALL_STATE_ACTIVE:
8680 				break;
8681 			default:
8682 				/* Held call not in a good state to transfer. */
8683 				continue;
8684 			}
8685 			if (q931_party_number_cmp(&winner->remote_id.number,
8686 				&active_call->remote_id.number)) {
8687 				/* The remote party number does not match.  This is a weak match. */
8688 				match = cur;
8689 				continue;
8690 			}
8691 			/* Found an exact match. */
8692 			match = cur;
8693 			break;
8694 		}
8695 	}
8696 
8697 	return match;
8698 }
8699 
8700 /*!
8701  * \internal
8702  * \brief Determine RELEASE_COMPLETE cause code for newcall rejection.
8703  *
8704  * \param call Q.931 call leg.
8705  *
8706  * \return Cause code for RELEASE_COMPLETE.
8707  */
newcall_rel_comp_cause(struct q931_call * call)8708 static int newcall_rel_comp_cause(struct q931_call *call)
8709 {
8710 	struct q931_call *master;
8711 	int cause;
8712 
8713 	cause = PRI_CAUSE_INVALID_CALL_REFERENCE;
8714 	master = call->master_call;
8715 	if (master != call && master->t312_timer) {
8716 		switch (master->ourcallstate) {
8717 		case Q931_CALL_STATE_CALL_ABORT:
8718 			cause = PRI_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
8719 			break;
8720 		default:
8721 			break;
8722 		}
8723 	}
8724 
8725 	return cause;
8726 }
8727 
8728 /*!
8729  * \internal
8730  * \brief Restart channel notify event for upper layer notify chain timeout.
8731  *
8732  * \param data Callback data pointer.
8733  *
8734  * \return Nothing
8735  */
q931_restart_notify_timeout(void * data)8736 static void q931_restart_notify_timeout(void *data)
8737 {
8738 	struct q931_call *call = data;
8739 	struct pri *ctrl = call->pri;
8740 
8741 	/* Create channel restart event to upper layer. */
8742 	call->channelno = call->restart.chan_no[call->restart.idx++];
8743 	ctrl->ev.e = PRI_EVENT_RESTART;
8744 	ctrl->ev.restart.channel = q931_encode_channel(call);
8745 	ctrl->schedev = 1;
8746 
8747 	/* Reschedule for next channel restart event needed. */
8748 	if (call->restart.idx < call->restart.count) {
8749 		call->restart.timer = pri_schedule_event(ctrl, 0, q931_restart_notify_timeout,
8750 			call);
8751 	} else {
8752 		/* No more restart events needed. */
8753 		call->restart.timer = 0;
8754 
8755 		/* Send back the Restart Acknowledge.  All channels are now restarted. */
8756 		if (call->slotmap != -1) {
8757 			/* Send slotmap format. */
8758 			call->channelno = -1;
8759 		}
8760 		restart_ack(ctrl, call);
8761 	}
8762 }
8763 
8764 /*!
8765  * \internal
8766  * \brief Setup restart channel notify events for upper layer.
8767  *
8768  * \param call Q.931 call leg.
8769  *
8770  * \return Nothing
8771  */
q931_restart_notify(struct q931_call * call)8772 static void q931_restart_notify(struct q931_call *call)
8773 {
8774 	struct pri *ctrl = call->pri;
8775 
8776 	/* Start notify chain. */
8777 	pri_schedule_del(ctrl, call->restart.timer);
8778 	call->restart.idx = 0;
8779 	q931_restart_notify_timeout(call);
8780 }
8781 
8782 /*!
8783  * \internal
8784  * \brief Process the decoded information in the Q.931 message.
8785  *
8786  * \param ctrl D channel controller.
8787  * \param mh Q.931 message header.
8788  * \param c Q.931 call leg.
8789  * \param mand_status Mandatory ie status
8790  *
8791  * \note
8792  * When this function returns c may be destroyed so you can no
8793  * longer dereference it.
8794  *
8795  * \retval 0 if no error or event.
8796  * \retval Q931_RES_HAVEEVENT if have an event.
8797  * \retval -1 on error.
8798  */
post_handle_q931_message(struct pri * ctrl,struct q931_mh * mh,struct q931_call * c,enum mandatory_ie_status mand_status)8799 static int post_handle_q931_message(struct pri *ctrl, struct q931_mh *mh, struct q931_call *c, enum mandatory_ie_status mand_status)
8800 {
8801 	int res;
8802 	int changed;
8803 	int mand_cause;
8804 	enum Q931_CALL_STATE ourcallstate_orig;
8805 	struct apdu_event *cur = NULL;
8806 	struct pri_subcommand *subcmd;
8807 	struct q931_call *master_call;
8808 
8809 	mand_cause = 0;
8810 	switch (mand_status) {
8811 	case MAND_STATUS_OK:
8812 		break;
8813 	case MAND_STATUS_CONTENT_ERROR:
8814 		mand_cause = PRI_CAUSE_INVALID_IE_CONTENTS;
8815 		break;
8816 	case MAND_STATUS_MISSING:
8817 		mand_cause = PRI_CAUSE_MANDATORY_IE_MISSING;
8818 		break;
8819 	}
8820 
8821 	switch(mh->msg) {
8822 	case Q931_RESTART:
8823 		q931_display_subcmd(ctrl, c);
8824 		if (mand_status != MAND_STATUS_OK) {
8825 			q931_status(ctrl, c, mand_cause);
8826 			pri_destroycall(ctrl, c);
8827 			break;
8828 		}
8829 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_RESTART);
8830 		c->peercallstate = Q931_CALL_STATE_RESTART_REQUEST;
8831 
8832 		/* Notify upper layer of restart event */
8833 		if ((c->channelno == -1 && c->slotmap == -1) || !c->restart.count) {
8834 			/*
8835 			 * Whole link restart or channel not identified by Channel ID ie
8836 			 * 3.3 octets.
8837 			 *
8838 			 * Send back the Restart Acknowledge
8839 			 */
8840 			restart_ack(ctrl, c);
8841 
8842 			/* Create channel restart event to upper layer. */
8843 			ctrl->ev.e = PRI_EVENT_RESTART;
8844 			ctrl->ev.restart.channel = q931_encode_channel(c);
8845 		} else {
8846 			/* Start notify chain. */
8847 			q931_restart_notify(c);
8848 		}
8849 		return Q931_RES_HAVEEVENT;
8850 	case Q931_REGISTER:
8851 		q931_display_subcmd(ctrl, c);
8852 
8853 		/* Must be new call */
8854 		if (!c->newcall) {
8855 			q931_status(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
8856 			break;
8857 		}
8858 		c->newcall = 0;
8859 		c->alive = 1;
8860 
8861 		c->cis_call = 1;
8862 		c->chanflags = FLAG_EXCLUSIVE;/* For safety mark this channel as exclusive. */
8863 		c->channelno = 0;
8864 
8865 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE);
8866 		c->peercallstate = Q931_CALL_STATE_CALL_INDEPENDENT_SERVICE;
8867 
8868 		if (c->cc.hangup_call) {
8869 			q931_release_complete(ctrl, c, PRI_CAUSE_NORMAL_CLEARING);
8870 			break;
8871 		}
8872 		if (/* c->cis_call && */ !c->cis_recognized) {
8873 			pri_message(ctrl,
8874 				"-- CIS connection not marked as handled.  Disconnecting it.\n");
8875 			q931_release_complete(ctrl, c, PRI_CAUSE_FACILITY_NOT_IMPLEMENTED);
8876 			break;
8877 		}
8878 
8879 		q931_fill_ring_event(ctrl, c);
8880 		return Q931_RES_HAVEEVENT;
8881 	case Q931_SETUP:
8882 		q931_display_subcmd(ctrl, c);
8883 		if (mand_status != MAND_STATUS_OK) {
8884 			q931_release_complete(ctrl, c, mand_cause);
8885 			break;
8886 		}
8887 		/* Must be new call */
8888 		if (!c->newcall) {
8889 			break;
8890 		}
8891 		if (c->progressmask & PRI_PROG_CALLER_NOT_ISDN)
8892 			c->nonisdn = 1;
8893 		c->newcall = 0;
8894 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_PRESENT);
8895 		c->peercallstate = Q931_CALL_STATE_CALL_INITIATED;
8896 		if (c->cis_call) {
8897 			/*
8898 			 * Make call alive so any message events clearing this
8899 			 * signaling call can pass up any subcmds.
8900 			 */
8901 			c->alive = 1;
8902 		} else {
8903 			/* it's not yet a call since higher level can respond with RELEASE or RELEASE_COMPLETE */
8904 			c->alive = 0;
8905 		}
8906 		if (c->bc.transmoderate != TRANS_MODE_64_CIRCUIT) {
8907 			q931_release_complete(ctrl, c, PRI_CAUSE_BEARERCAPABILITY_NOTIMPL);
8908 			break;
8909 		}
8910 		if (c->cc.hangup_call) {
8911 			q931_release_complete(ctrl, c, PRI_CAUSE_NORMAL_CLEARING);
8912 			break;
8913 		}
8914 		if (c->cis_call && !c->cis_recognized) {
8915 			pri_message(ctrl, "-- CIS call not marked as handled.  Disconnecting it.\n");
8916 			q931_release_complete(ctrl, c, PRI_CAUSE_FACILITY_NOT_IMPLEMENTED);
8917 			break;
8918 		}
8919 
8920 		/* Save the initial cc-parties. (Incoming SETUP can only be a master call.) */
8921 		c->cc.party_a = c->remote_id;
8922 
8923 		q931_fill_ring_event(ctrl, c);
8924 		return Q931_RES_HAVEEVENT;
8925 	case Q931_ALERTING:
8926 		q931_display_subcmd(ctrl, c);
8927 		if (mand_status != MAND_STATUS_OK) {
8928 			q931_status(ctrl, c, mand_cause);
8929 			break;
8930 		}
8931 		stop_t303(c->master_call);
8932 		if (c->newcall) {
8933 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
8934 			break;
8935 		}
8936 		switch (c->ourcallstate) {
8937 		default:
8938 			q931_status(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
8939 			return 0;
8940 		case Q931_CALL_STATE_CALL_INITIATED:
8941 		case Q931_CALL_STATE_OVERLAP_SENDING:
8942 		case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
8943 			break;
8944 		}
8945 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CALL_DELIVERED);
8946 		c->peercallstate = Q931_CALL_STATE_CALL_RECEIVED;
8947 		ctrl->ev.e = PRI_EVENT_RINGING;
8948 		ctrl->ev.ringing.subcmds = &ctrl->subcmds;
8949 		ctrl->ev.ringing.channel = q931_encode_channel(c);
8950 		ctrl->ev.ringing.cref = c->cr;
8951 		ctrl->ev.ringing.call = c->master_call;
8952 		ctrl->ev.ringing.progress = c->progress;
8953 		ctrl->ev.ringing.progressmask = c->progressmask;
8954 
8955 		libpri_copy_string(ctrl->ev.ringing.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.ringing.useruserinfo));
8956 		c->useruserinfo[0] = '\0';
8957 
8958 		switch (ctrl->switchtype) {
8959 		case PRI_SWITCH_QSIG:
8960 			pri_cc_qsig_determine_available(ctrl, c);
8961 			break;
8962 		default:
8963 			break;
8964 		}
8965 
8966 		for (cur = c->apdus; cur; cur = cur->next) {
8967 			if (!cur->sent && cur->message == Q931_FACILITY) {
8968 				q931_facility(ctrl, c);
8969 				break;
8970 			}
8971 		}
8972 
8973 		return Q931_RES_HAVEEVENT;
8974 	case Q931_CONNECT:
8975 		q931_display_subcmd(ctrl, c);
8976 		if (mand_status != MAND_STATUS_OK) {
8977 			q931_status(ctrl, c, mand_cause);
8978 			break;
8979 		}
8980 		stop_t303(c->master_call);
8981 		if (c->newcall) {
8982 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
8983 			break;
8984 		}
8985 		switch (c->ourcallstate) {
8986 		case Q931_CALL_STATE_CALL_INITIATED:
8987 		case Q931_CALL_STATE_OVERLAP_SENDING:
8988 		case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
8989 		case Q931_CALL_STATE_CALL_DELIVERED:
8990 		case Q931_CALL_STATE_CALL_PRESENT:
8991 		case Q931_CALL_STATE_CALL_RECEIVED:
8992 		case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
8993 		case Q931_CALL_STATE_OVERLAP_RECEIVING:
8994 			/* Accept CONNECT in these states. */
8995 			break;
8996 		default:
8997 			q931_status(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
8998 			return 0;
8999 		}
9000 
9001 		ctrl->ev.e = PRI_EVENT_ANSWER;
9002 		ctrl->ev.answer.subcmds = &ctrl->subcmds;
9003 		ctrl->ev.answer.channel = q931_encode_channel(c);
9004 		ctrl->ev.answer.cref = c->cr;
9005 		ctrl->ev.answer.call = c->master_call;
9006 		ctrl->ev.answer.progress = c->progress;
9007 		ctrl->ev.answer.progressmask = c->progressmask;
9008 		libpri_copy_string(ctrl->ev.answer.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.answer.useruserinfo));
9009 		c->useruserinfo[0] = '\0';
9010 
9011 		if (!ctrl->manual_connect_ack) {
9012 			q931_connect_acknowledge(ctrl, c, 0);
9013 		} else {
9014 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_CONNECT_REQUEST);
9015 			c->peercallstate = Q931_CALL_STATE_CONNECT_REQUEST;
9016 		}
9017 
9018 		if (c->cis_auto_disconnect && c->cis_call) {
9019 			/* Make sure WE release when we initiate a signalling only connection */
9020 			q931_hangup(ctrl, c, PRI_CAUSE_NORMAL_CLEARING);
9021 		} else {
9022 			c->incoming_ct_state = INCOMING_CT_STATE_IDLE;
9023 
9024 			/* Setup connected line subcommand */
9025 			subcmd = q931_alloc_subcommand(ctrl);
9026 			if (subcmd) {
9027 				subcmd->cmd = PRI_SUBCMD_CONNECTED_LINE;
9028 				q931_party_id_copy_to_pri(&subcmd->u.connected_line.id, &c->remote_id);
9029 			}
9030 
9031 			return Q931_RES_HAVEEVENT;
9032 		}
9033 		break;
9034 	case Q931_FACILITY:
9035 		q931_display_subcmd(ctrl, c);
9036 		if (c->newcall) {
9037 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9038 			break;
9039 		}
9040 		switch (c->incoming_ct_state) {
9041 		case INCOMING_CT_STATE_POST_CONNECTED_LINE:
9042 			c->incoming_ct_state = INCOMING_CT_STATE_IDLE;
9043 			subcmd = q931_alloc_subcommand(ctrl);
9044 			if (subcmd) {
9045 				subcmd->cmd = PRI_SUBCMD_CONNECTED_LINE;
9046 				q931_party_id_copy_to_pri(&subcmd->u.connected_line.id, &c->remote_id);
9047 			}
9048 			break;
9049 		default:
9050 			break;
9051 		}
9052 		if (ctrl->subcmds.counter_subcmd) {
9053 			q931_fill_facility_event(ctrl, c);
9054 			return Q931_RES_HAVEEVENT;
9055 		}
9056 		break;
9057 	case Q931_PROGRESS:
9058 		ctrl->ev.e = PRI_EVENT_PROGRESS;
9059 		ctrl->ev.proceeding.cause = c->cause;
9060 		/* Fall through */
9061 	case Q931_CALL_PROCEEDING:
9062 		q931_display_subcmd(ctrl, c);
9063 		if (mand_status != MAND_STATUS_OK) {
9064 			q931_status(ctrl, c, mand_cause);
9065 			break;
9066 		}
9067 		stop_t303(c->master_call);
9068 		ctrl->ev.proceeding.subcmds = &ctrl->subcmds;
9069 		if (c->newcall) {
9070 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9071 			break;
9072 		}
9073 		if ((c->ourcallstate != Q931_CALL_STATE_CALL_INITIATED) &&
9074 		    (c->ourcallstate != Q931_CALL_STATE_OVERLAP_SENDING) &&
9075 		    (c->ourcallstate != Q931_CALL_STATE_CALL_DELIVERED) &&
9076 		    (c->ourcallstate != Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING)) {
9077 			if (mh->msg == Q931_PROGRESS
9078 				&& c->ourcallstate == Q931_CALL_STATE_ACTIVE
9079 				&& ctrl->switchtype == PRI_SWITCH_QSIG) {
9080 				/*
9081 				 * Q.SIG is odd to allow PROGRESS when in the Active state since
9082 				 * the media path is already open.  Ignore it since it doesn't
9083 				 * convey anything very useful.  Maybe they will stop doing it.
9084 				 *
9085 				 * See ECMA-143 Section 10.1.7.2.
9086 				 */
9087 				break;
9088 			}
9089 			q931_status(ctrl,c,PRI_CAUSE_WRONG_MESSAGE);
9090 			break;
9091 		}
9092 		ctrl->ev.proceeding.channel = q931_encode_channel(c);
9093 		if (mh->msg == Q931_CALL_PROCEEDING) {
9094 			ctrl->ev.e = PRI_EVENT_PROCEEDING;
9095 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING);
9096 			c->peercallstate = Q931_CALL_STATE_INCOMING_CALL_PROCEEDING;
9097 		}
9098 		ctrl->ev.proceeding.progress = c->progress;
9099 		ctrl->ev.proceeding.progressmask = c->progressmask;
9100 		ctrl->ev.proceeding.cref = c->cr;
9101 		ctrl->ev.proceeding.call = c->master_call;
9102 
9103 		for (cur = c->apdus; cur; cur = cur->next) {
9104 			if (!cur->sent && cur->message == Q931_FACILITY) {
9105 				q931_facility(ctrl, c);
9106 				break;
9107 			}
9108 		}
9109 		return Q931_RES_HAVEEVENT;
9110 	case Q931_CONNECT_ACKNOWLEDGE:
9111 		q931_display_subcmd(ctrl, c);
9112 		if (c->newcall) {
9113 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9114 			break;
9115 		}
9116 		switch (c->ourcallstate) {
9117 		default:
9118 			q931_status(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9119 			return 0;
9120 		case Q931_CALL_STATE_CONNECT_REQUEST:
9121 		case Q931_CALL_STATE_ACTIVE:
9122 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_ACTIVE);
9123 			c->peercallstate = Q931_CALL_STATE_ACTIVE;
9124 			if (ctrl->manual_connect_ack) {
9125 				ctrl->ev.e = PRI_EVENT_CONNECT_ACK;
9126 				ctrl->ev.connect_ack.subcmds = &ctrl->subcmds;
9127 				ctrl->ev.connect_ack.channel = q931_encode_channel(c);
9128 				ctrl->ev.connect_ack.call = c->master_call;
9129 				return Q931_RES_HAVEEVENT;
9130 			}
9131 			break;
9132 		}
9133 		break;
9134 	case Q931_STATUS:
9135 		q931_display_subcmd(ctrl, c);
9136 		if (mand_status != MAND_STATUS_OK) {
9137 			q931_status(ctrl, c, mand_cause);
9138 			break;
9139 		}
9140 		if (c->newcall) {
9141 			if (c->cr & 0x7fff)
9142 				q931_release_complete(ctrl,c,PRI_CAUSE_WRONG_CALL_STATE);
9143 			break;
9144 		}
9145 		/* Do nothing */
9146 		/* Also when the STATUS asks for the call of an unexisting reference send RELEASE_COMPLETE */
9147 		if ((ctrl->debug & PRI_DEBUG_Q931_ANOMALY) &&
9148 		    (c->cause != PRI_CAUSE_INTERWORKING))
9149 			pri_error(ctrl, "Received unsolicited status: %s\n", pri_cause2str(c->cause));
9150 		if (
9151 #if 0
9152 			/*
9153 			 * Workaround for S-12 ver 7.3 - it responds to
9154 			 * invalid/non-implemented IEs in SETUP with NULL call state.
9155 			 */
9156 			!c->sugcallstate && (c->ourcallstate != Q931_CALL_STATE_CALL_INITIATED)
9157 #else
9158 			/*
9159 			 * Remove "workaround" since it breaks certification testing. If
9160 			 * we receive a STATUS message of call state NULL and we are not
9161 			 * in the call state NULL we must clear resources and return to
9162 			 * the call state to pass testing.  See section 5.8.11 of Q.931.
9163 			 */
9164 
9165 			!c->sugcallstate
9166 #endif
9167 			) {
9168 			ctrl->ev.hangup.subcmds = &ctrl->subcmds;
9169 			ctrl->ev.hangup.channel = q931_encode_channel(c);
9170 			ctrl->ev.hangup.cause = c->cause;
9171 			ctrl->ev.hangup.cref = c->cr;
9172 			ctrl->ev.hangup.call = c->master_call;
9173 			ctrl->ev.hangup.aoc_units = c->aoc_units;
9174 			ctrl->ev.hangup.call_held = NULL;
9175 			ctrl->ev.hangup.call_active = NULL;
9176 			libpri_copy_string(ctrl->ev.hangup.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.hangup.useruserinfo));
9177 			/* Free resources */
9178 			UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
9179 			c->peercallstate = Q931_CALL_STATE_NULL;
9180 
9181 			if (c->outboundbroadcast && (c != q931_get_subcall_winner(c->master_call))) {
9182 				/* Complete clearing the disconnecting non-winning subcall. */
9183 				pri_hangup(ctrl, c, -1);
9184 				return 0;
9185 			}
9186 
9187 			/* Free resources */
9188 			if (c->alive) {
9189 				ctrl->ev.e = PRI_EVENT_HANGUP;
9190 				c->alive = 0;
9191 			} else if (c->sendhangupack) {
9192 				ctrl->ev.e = PRI_EVENT_HANGUP_ACK;
9193 				pri_hangup(ctrl, c, c->cause);
9194 			} else {
9195 				pri_hangup(ctrl, c, c->cause);
9196 				return 0;
9197 			}
9198 			return Q931_RES_HAVEEVENT;
9199 		}
9200 		break;
9201 	case Q931_RELEASE_COMPLETE:
9202 		q931_display_subcmd(ctrl, c);
9203 		c->hangupinitiated = 1;
9204 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
9205 		c->peercallstate = Q931_CALL_STATE_NULL;
9206 
9207 		ctrl->ev.hangup.subcmds = &ctrl->subcmds;
9208 		ctrl->ev.hangup.channel = q931_encode_channel(c);
9209 		ctrl->ev.hangup.cause = c->cause;
9210 		ctrl->ev.hangup.cref = c->cr;
9211 		ctrl->ev.hangup.call = c->master_call;
9212 		ctrl->ev.hangup.aoc_units = c->aoc_units;
9213 		ctrl->ev.hangup.call_held = NULL;
9214 		ctrl->ev.hangup.call_active = NULL;
9215 		libpri_copy_string(ctrl->ev.hangup.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.hangup.useruserinfo));
9216 		c->useruserinfo[0] = '\0';
9217 
9218 		if (c->cc.record && c->cc.record->signaling == c) {
9219 			pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_SIGNALING_GONE);
9220 		}
9221 
9222 		if (c->outboundbroadcast && (c != q931_get_subcall_winner(c->master_call))) {
9223 			/* Complete clearing the disconnecting non-winning subcall. */
9224 			pri_hangup(ctrl, c, -1);
9225 			return 0;
9226 		}
9227 
9228 		/* Free resources */
9229 		if (c->alive) {
9230 			ctrl->ev.e = PRI_EVENT_HANGUP;
9231 			c->alive = 0;
9232 		} else if (c->sendhangupack) {
9233 			ctrl->ev.e = PRI_EVENT_HANGUP_ACK;
9234 			pri_hangup(ctrl, c, c->cause);
9235 		} else {
9236 			pri_hangup(ctrl, c, c->cause);
9237 			return 0;
9238 		}
9239 		return Q931_RES_HAVEEVENT;
9240 	case Q931_RELEASE:
9241 		q931_display_subcmd(ctrl, c);
9242 		c->hangupinitiated = 1;
9243 		if (mand_status != MAND_STATUS_OK) {
9244 			/* Force mandatory ie cause */
9245 			c->cause = mand_cause;
9246 		}
9247 
9248 		/*
9249 		 * Don't send RELEASE_COMPLETE if they sent us RELEASE while we
9250 		 * were waiting for RELEASE_COMPLETE from them, assume a NULL state.
9251 		 */
9252 		if (c->ourcallstate == Q931_CALL_STATE_RELEASE_REQUEST)
9253 			c->peercallstate = Q931_CALL_STATE_NULL;
9254 		else {
9255 			c->peercallstate = Q931_CALL_STATE_RELEASE_REQUEST;
9256 		}
9257 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
9258 
9259 		if (c->newcall) {
9260 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9261 			break;
9262 		}
9263 
9264 		ctrl->ev.e = PRI_EVENT_HANGUP;
9265 		ctrl->ev.hangup.subcmds = &ctrl->subcmds;
9266 		ctrl->ev.hangup.channel = q931_encode_channel(c);
9267 		ctrl->ev.hangup.cause = c->cause;
9268 		ctrl->ev.hangup.cref = c->cr;
9269 		ctrl->ev.hangup.call = c->master_call;
9270 		ctrl->ev.hangup.aoc_units = c->aoc_units;
9271 		ctrl->ev.hangup.call_held = NULL;
9272 		ctrl->ev.hangup.call_active = NULL;
9273 		libpri_copy_string(ctrl->ev.hangup.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.hangup.useruserinfo));
9274 		c->useruserinfo[0] = '\0';
9275 
9276 		if (c->cc.record && c->cc.record->signaling == c) {
9277 			pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_SIGNALING_GONE);
9278 		}
9279 
9280 		if (c->outboundbroadcast && (c != q931_get_subcall_winner(c->master_call))) {
9281 			/* Complete clearing the disconnecting non-winning subcall. */
9282 			pri_hangup(ctrl, c, -1);
9283 			return 0;
9284 		}
9285 		return Q931_RES_HAVEEVENT;
9286 	case Q931_DISCONNECT:
9287 		q931_display_subcmd(ctrl, c);
9288 		c->hangupinitiated = 1;
9289 		if (mand_status != MAND_STATUS_OK) {
9290 			/* Still let user call release */
9291 			c->cause = mand_cause;
9292 		}
9293 		if (c->newcall) {
9294 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9295 			break;
9296 		}
9297 
9298 		/*
9299 		 * Determine if there are any calls that can be proposed for
9300 		 * a transfer of held call on disconnect.
9301 		 */
9302 		ctrl->ev.hangup.call_held = NULL;
9303 		ctrl->ev.hangup.call_active = NULL;
9304 		switch (c->ourcallstate) {
9305 		case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
9306 		case Q931_CALL_STATE_CALL_DELIVERED:
9307 		case Q931_CALL_STATE_CALL_RECEIVED:
9308 		case Q931_CALL_STATE_CONNECT_REQUEST:
9309 		case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
9310 		case Q931_CALL_STATE_ACTIVE:
9311 			if (c->master_call->hold_state == Q931_HOLD_STATE_CALL_HELD) {
9312 				/* Held call is being disconnected first. */
9313 				ctrl->ev.hangup.call_held = c->master_call;
9314 				ctrl->ev.hangup.call_active = q931_find_held_active_call(ctrl, c);
9315 			} else {
9316 				/* Active call is being disconnected first. */
9317 				if (q931_find_winning_call(c) == c) {
9318 					/*
9319 					 * Only a normal call or the winning call of a broadcast SETUP
9320 					 * can participate in a transfer of held call on disconnet.
9321 					 */
9322 					ctrl->ev.hangup.call_active = c->master_call;
9323 					ctrl->ev.hangup.call_held = q931_find_held_call(ctrl, c);
9324 				}
9325 			}
9326 			break;
9327 		default:
9328 			break;
9329 		}
9330 		if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9331 			if (ctrl->ev.hangup.call_held) {
9332 				pri_message(ctrl, "-- Found held call: %p cref:%d\n",
9333 					ctrl->ev.hangup.call_held, ctrl->ev.hangup.call_held->cr);
9334 			}
9335 			if (ctrl->ev.hangup.call_active) {
9336 				pri_message(ctrl, "-- Found active call: %p cref:%d\n",
9337 					ctrl->ev.hangup.call_active, ctrl->ev.hangup.call_active->cr);
9338 			}
9339 			if (ctrl->ev.hangup.call_held && ctrl->ev.hangup.call_active) {
9340 				pri_message(ctrl, "-- Transfer held call on disconnect possible.\n");
9341 			}
9342 		}
9343 
9344 		ourcallstate_orig = c->ourcallstate;
9345 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_DISCONNECT_INDICATION);
9346 		c->peercallstate = Q931_CALL_STATE_DISCONNECT_REQUEST;
9347 		c->sendhangupack = 1;
9348 
9349 		/* wait for a RELEASE so that sufficient time has passed
9350 		   for the inband audio to be heard */
9351 		if (ctrl->acceptinbanddisconnect
9352 			&& (c->progressmask & PRI_PROG_INBAND_AVAILABLE)) {
9353 			switch (ourcallstate_orig) {
9354 			case Q931_CALL_STATE_CALL_INITIATED:
9355 			case Q931_CALL_STATE_OVERLAP_SENDING:
9356 			case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
9357 			case Q931_CALL_STATE_CALL_DELIVERED:
9358 				/*
9359 				 * Open the media path if it isn't already open so
9360 				 * the user can hear the inband audio.
9361 				 */
9362 				if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9363 					pri_message(ctrl, "Report the DISCONNECT as a PROGRESS instead.\n");
9364 				}
9365 				ctrl->ev.e = PRI_EVENT_PROGRESS;
9366 				ctrl->ev.proceeding.cause = c->cause;
9367 				ctrl->ev.proceeding.subcmds = &ctrl->subcmds;
9368 				ctrl->ev.proceeding.channel = q931_encode_channel(c);
9369 				ctrl->ev.proceeding.progress = c->progress;
9370 				ctrl->ev.proceeding.progressmask = c->progressmask;
9371 				ctrl->ev.proceeding.cref = c->cr;
9372 				ctrl->ev.proceeding.call = c->master_call;
9373 				return Q931_RES_HAVEEVENT;
9374 			default:
9375 				break;
9376 			}
9377 			/*
9378 			 * Suppress reporting DISCONNECT to the upper layer.  The
9379 			 * media path should already be open and we cannot report
9380 			 * a PROGRESS at this time anyway.
9381 			 */
9382 			break;
9383 		}
9384 
9385 		/* Return such an event */
9386 		ctrl->ev.e = PRI_EVENT_HANGUP_REQ;
9387 		ctrl->ev.hangup.subcmds = &ctrl->subcmds;
9388 		ctrl->ev.hangup.channel = q931_encode_channel(c);
9389 		ctrl->ev.hangup.cause = c->cause;
9390 		ctrl->ev.hangup.cref = c->cr;
9391 		ctrl->ev.hangup.call = c->master_call;
9392 		ctrl->ev.hangup.aoc_units = c->aoc_units;
9393 		libpri_copy_string(ctrl->ev.hangup.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.hangup.useruserinfo));
9394 		c->useruserinfo[0] = '\0';
9395 
9396 		if (c->outboundbroadcast && (c != q931_get_subcall_winner(c->master_call))) {
9397 			/* Complete clearing the disconnecting non-winning subcall. */
9398 			pri_hangup(ctrl, c, -1);
9399 			return 0;
9400 		}
9401 
9402 		if (c->alive) {
9403 			switch (c->cause) {
9404 			case PRI_CAUSE_USER_BUSY:
9405 			case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
9406 				switch (ctrl->switchtype) {
9407 				case PRI_SWITCH_QSIG:
9408 					pri_cc_qsig_determine_available(ctrl, c);
9409 					break;
9410 				default:
9411 					break;
9412 				}
9413 				break;
9414 			default:
9415 				break;
9416 			}
9417 
9418 			return Q931_RES_HAVEEVENT;
9419 		} else {
9420 			pri_hangup(ctrl,c,c->cause);
9421 		}
9422 		break;
9423 	case Q931_RESTART_ACKNOWLEDGE:
9424 		q931_display_subcmd(ctrl, c);
9425 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
9426 		c->peercallstate = Q931_CALL_STATE_NULL;
9427 		ctrl->ev.e = PRI_EVENT_RESTART_ACK;
9428 		ctrl->ev.restartack.channel = q931_encode_channel(c);
9429 		if (c->restart_tx.t316_timer
9430 			/*
9431 			 * Since the DS1 value can vary, only check the channel number.
9432 			 * We're only supposed to have one RESTART request outstanding
9433 			 * at a time anyway.
9434 			 */
9435 			&& (c->restart_tx.channel & 0xFF) == (ctrl->ev.restartack.channel & 0xFF)) {
9436 			/* This is the RESTART ACKNOWLEDGE we are expecting. */
9437 			stop_t316(c);
9438 		}
9439 		return Q931_RES_HAVEEVENT;
9440 	case Q931_INFORMATION:
9441 		/* XXX We're handling only INFORMATION messages that contain
9442 		       overlap dialing received digit
9443 		       +  the "Complete" msg which is basically an EOF on further digits
9444 		   XXX */
9445 		q931_display_subcmd(ctrl, c);
9446 		if (c->newcall) {
9447 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9448 			break;
9449 		}
9450 		if (strlen(c->keypad_digits)) {
9451 			ctrl->ev.e = PRI_EVENT_KEYPAD_DIGIT;
9452 			ctrl->ev.digit.subcmds = &ctrl->subcmds;
9453 			ctrl->ev.digit.call = c->master_call;
9454 			ctrl->ev.digit.channel = q931_encode_channel(c);
9455 			libpri_copy_string(ctrl->ev.digit.digits, c->keypad_digits, sizeof(ctrl->ev.digit.digits));
9456 			return Q931_RES_HAVEEVENT;
9457 		}
9458 		ctrl->ev.e = PRI_EVENT_INFO_RECEIVED;
9459 		ctrl->ev.ring.subcmds = &ctrl->subcmds;
9460 		ctrl->ev.ring.call = c->master_call;
9461 		ctrl->ev.ring.channel = q931_encode_channel(c);
9462 		libpri_copy_string(ctrl->ev.ring.callednum, c->overlap_digits, sizeof(ctrl->ev.ring.callednum));
9463 
9464 		q931_party_id_copy_to_pri(&ctrl->ev.ring.calling, &c->remote_id);
9465 		/* for backwards compatibility, still need ctrl->ev.ring.callingsubaddr */
9466 		if (!c->remote_id.subaddress.type) {	/* NSAP: Type = 0 */
9467 			libpri_copy_string(ctrl->ev.ring.callingsubaddr, (char *) c->remote_id.subaddress.data, sizeof(ctrl->ev.ring.callingsubaddr));
9468 		} else {
9469 			ctrl->ev.ring.callingsubaddr[0] = '\0';
9470 		}
9471 
9472 		ctrl->ev.ring.complete = c->complete;	/* this covers IE 33 (Sending Complete) */
9473 		return Q931_RES_HAVEEVENT;
9474 	case Q931_STATUS_ENQUIRY:
9475 		q931_display_clear(c);
9476 		if (c->newcall) {
9477 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9478 		} else
9479 			q931_status(ctrl,c, PRI_CAUSE_RESPONSE_TO_STATUS_ENQUIRY);
9480 		break;
9481 	case Q931_SETUP_ACKNOWLEDGE:
9482 		q931_display_subcmd(ctrl, c);
9483 		if (mand_status != MAND_STATUS_OK) {
9484 			q931_status(ctrl, c, mand_cause);
9485 			break;
9486 		}
9487 		stop_t303(c->master_call);
9488 		if (c->newcall) {
9489 			q931_release_complete(ctrl, c, newcall_rel_comp_cause(c));
9490 			break;
9491 		}
9492 		switch (c->ourcallstate) {
9493 		default:
9494 			q931_status(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9495 			return 0;
9496 		case Q931_CALL_STATE_CALL_INITIATED:
9497 			break;
9498 		}
9499 		UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_OVERLAP_SENDING);
9500 		c->peercallstate = Q931_CALL_STATE_OVERLAP_RECEIVING;
9501 		ctrl->ev.e = PRI_EVENT_SETUP_ACK;
9502 		ctrl->ev.setup_ack.subcmds = &ctrl->subcmds;
9503 		ctrl->ev.setup_ack.channel = q931_encode_channel(c);
9504 		ctrl->ev.setup_ack.call = c->master_call;
9505 		ctrl->ev.setup_ack.progressmask = c->progressmask;
9506 
9507 		for (cur = c->apdus; cur; cur = cur->next) {
9508 			if (!cur->sent && cur->message == Q931_FACILITY) {
9509 				q931_facility(ctrl, c);
9510 				break;
9511 			}
9512 		}
9513 
9514 		return Q931_RES_HAVEEVENT;
9515 	case Q931_NOTIFY:
9516 		res = 0;
9517 		changed = 0;
9518 		switch (c->notify) {
9519 		case PRI_NOTIFY_CALL_DIVERTING:
9520 			if (c->redirection_number.valid) {
9521 				c->redirecting.to.number = c->redirection_number;
9522 				if (c->redirecting.count < PRI_MAX_REDIRECTS) {
9523 					++c->redirecting.count;
9524 				}
9525 				switch (c->ourcallstate) {
9526 				case Q931_CALL_STATE_CALL_DELIVERED:
9527 					/* Call is deflecting after we have seen an ALERTING message */
9528 					c->redirecting.reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
9529 					break;
9530 				default:
9531 					/* Call is deflecting for call forwarding unconditional or busy reason. */
9532 					c->redirecting.reason = PRI_REDIR_UNKNOWN;
9533 					break;
9534 				}
9535 
9536 				/* Setup redirecting subcommand */
9537 				subcmd = q931_alloc_subcommand(ctrl);
9538 				if (subcmd) {
9539 					subcmd->cmd = PRI_SUBCMD_REDIRECTING;
9540 					q931_party_redirecting_copy_to_pri(&subcmd->u.redirecting,
9541 						&c->redirecting);
9542 				}
9543 			}
9544 
9545 			q931_display_subcmd(ctrl, c);
9546 			if (ctrl->subcmds.counter_subcmd) {
9547 				q931_fill_facility_event(ctrl, c);
9548 				res = Q931_RES_HAVEEVENT;
9549 			}
9550 			break;
9551 		case PRI_NOTIFY_TRANSFER_ACTIVE:
9552 			if (q931_party_number_cmp(&c->remote_id.number, &c->redirection_number)) {
9553 				/* The remote party number information changed. */
9554 				c->remote_id.number = c->redirection_number;
9555 				changed = 1;
9556 			}
9557 			/* Fall through */
9558 		case PRI_NOTIFY_TRANSFER_ALERTING:
9559 			if (ctrl->display_flags.receive & PRI_DISPLAY_OPTION_NAME_UPDATE) {
9560 				struct q931_party_name name;
9561 
9562 				if (q931_display_name_get(c, &name)) {
9563 					if (q931_party_name_cmp(&c->remote_id.name, &name)) {
9564 						/* The remote party name information changed. */
9565 						c->remote_id.name = name;
9566 						changed = 1;
9567 					}
9568 				}
9569 			}
9570 			if (c->redirection_number.valid
9571 				&& q931_party_number_cmp(&c->remote_id.number, &c->redirection_number)) {
9572 				/* The remote party number information changed. */
9573 				c->remote_id.number = c->redirection_number;
9574 				changed = 1;
9575 			}
9576 			if (c->remote_id.subaddress.valid) {
9577 				/*
9578 				 * Clear the subaddress as the remote party has been changed.
9579 				 * Any new subaddress will arrive later.
9580 				 */
9581 				q931_party_subaddress_init(&c->remote_id.subaddress);
9582 				changed = 1;
9583 			}
9584 			if (changed) {
9585 				/* Setup connected line subcommand */
9586 				subcmd = q931_alloc_subcommand(ctrl);
9587 				if (subcmd) {
9588 					subcmd->cmd = PRI_SUBCMD_CONNECTED_LINE;
9589 					q931_party_id_copy_to_pri(&subcmd->u.connected_line.id,
9590 						&c->remote_id);
9591 				}
9592 			}
9593 
9594 			q931_display_subcmd(ctrl, c);
9595 			if (ctrl->subcmds.counter_subcmd) {
9596 				q931_fill_facility_event(ctrl, c);
9597 				res = Q931_RES_HAVEEVENT;
9598 			}
9599 			break;
9600 		default:
9601 			ctrl->ev.e = PRI_EVENT_NOTIFY;
9602 			ctrl->ev.notify.subcmds = &ctrl->subcmds;
9603 			ctrl->ev.notify.channel = q931_encode_channel(c);
9604 			ctrl->ev.notify.info = c->notify;
9605 			ctrl->ev.notify.call = c->master_call;
9606 			res = Q931_RES_HAVEEVENT;
9607 			break;
9608 		}
9609 		q931_display_subcmd(ctrl, c);
9610 		return res;
9611 	case Q931_HOLD:
9612 		q931_display_subcmd(ctrl, c);
9613 		res = 0;
9614 		if (!ctrl->hold_support) {
9615 			/*
9616 			 * Blocking any calls from getting on HOLD effectively
9617 			 * disables HOLD/RETRIEVE.
9618 			 */
9619 			q931_send_hold_rej_msg(ctrl, c, PRI_CAUSE_FACILITY_NOT_IMPLEMENTED);
9620 			break;
9621 		}
9622 		switch (c->ourcallstate) {
9623 		case Q931_CALL_STATE_CALL_RECEIVED:
9624 		case Q931_CALL_STATE_CONNECT_REQUEST:
9625 		case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
9626 			if (PTMP_MODE(ctrl)) {
9627 				/* HOLD request only allowed in these states if point-to-point mode. */
9628 				q931_send_hold_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9629 				break;
9630 			}
9631 			/* Fall through */
9632 		case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
9633 		case Q931_CALL_STATE_CALL_DELIVERED:
9634 		case Q931_CALL_STATE_ACTIVE:
9635 			if (!q931_find_winning_call(c)) {
9636 				/*
9637 				 * Only the winning call of a broadcast SETUP can do hold since the
9638 				 * call must be answered first.
9639 				 */
9640 				q931_send_hold_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9641 				break;
9642 			}
9643 			master_call = c->master_call;
9644 			switch (master_call->hold_state) {
9645 			case Q931_HOLD_STATE_HOLD_REQ:
9646 				if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9647 					pri_message(ctrl, "HOLD collision\n");
9648 				}
9649 				if (ctrl->localtype == PRI_NETWORK) {
9650 					/* The network ignores HOLD request on a hold collision. */
9651 					break;
9652 				}
9653 				/* Fall through */
9654 			case Q931_HOLD_STATE_IDLE:
9655 				ctrl->ev.e = PRI_EVENT_HOLD;
9656 				ctrl->ev.hold.channel = q931_encode_channel(c);
9657 				ctrl->ev.hold.call = master_call;
9658 				ctrl->ev.hold.subcmds = &ctrl->subcmds;
9659 				res = Q931_RES_HAVEEVENT;
9660 
9661 				UPDATE_HOLD_STATE(ctrl, master_call, Q931_HOLD_STATE_HOLD_IND);
9662 				break;
9663 			default:
9664 				q931_send_hold_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9665 				break;
9666 			}
9667 			break;
9668 		case Q931_CALL_STATE_DISCONNECT_INDICATION:
9669 		case Q931_CALL_STATE_RELEASE_REQUEST:
9670 			/* Ignore HOLD request in these states. */
9671 			break;
9672 		default:
9673 			q931_send_hold_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9674 			break;
9675 		}
9676 		return res;
9677 	case Q931_HOLD_ACKNOWLEDGE:
9678 		q931_display_subcmd(ctrl, c);
9679 		res = 0;
9680 		master_call = c->master_call;
9681 		switch (master_call->hold_state) {
9682 		case Q931_HOLD_STATE_HOLD_REQ:
9683 			ctrl->ev.e = PRI_EVENT_HOLD_ACK;
9684 			ctrl->ev.hold_ack.channel = q931_encode_channel(c);
9685 			ctrl->ev.hold_ack.call = master_call;
9686 			ctrl->ev.hold_ack.subcmds = &ctrl->subcmds;
9687 			res = Q931_RES_HAVEEVENT;
9688 
9689 			UPDATE_HOLD_STATE(ctrl, master_call, Q931_HOLD_STATE_CALL_HELD);
9690 
9691 			/* Call is now on hold so forget the channel. */
9692 			c->channelno = 0;/* No channel */
9693 			c->ds1no = 0;
9694 			c->ds1explicit = 0;
9695 			c->chanflags = 0;
9696 
9697 			/* Stop T-HOLD timer */
9698 			pri_schedule_del(ctrl, master_call->hold_timer);
9699 			master_call->hold_timer = 0;
9700 			break;
9701 		default:
9702 			/* Ignore response.  Response is late or spurrious. */
9703 			break;
9704 		}
9705 		return res;
9706 	case Q931_HOLD_REJECT:
9707 		q931_display_subcmd(ctrl, c);
9708 		res = 0;
9709 		master_call = c->master_call;
9710 		switch (master_call->hold_state) {
9711 		case Q931_HOLD_STATE_HOLD_REQ:
9712 			if (mand_status != MAND_STATUS_OK) {
9713 				/* Still, let hold rejection continue. */
9714 				c->cause = mand_cause;
9715 			}
9716 			ctrl->ev.e = PRI_EVENT_HOLD_REJ;
9717 			ctrl->ev.hold_rej.channel = q931_encode_channel(c);
9718 			ctrl->ev.hold_rej.call = master_call;
9719 			ctrl->ev.hold_rej.cause = c->cause;
9720 			ctrl->ev.hold_rej.subcmds = &ctrl->subcmds;
9721 			res = Q931_RES_HAVEEVENT;
9722 
9723 			UPDATE_HOLD_STATE(ctrl, master_call, Q931_HOLD_STATE_IDLE);
9724 
9725 			/* Stop T-HOLD timer */
9726 			pri_schedule_del(ctrl, master_call->hold_timer);
9727 			master_call->hold_timer = 0;
9728 			break;
9729 		default:
9730 			/* Ignore response.  Response is late or spurrious. */
9731 			break;
9732 		}
9733 		return res;
9734 	case Q931_RETRIEVE:
9735 		q931_display_subcmd(ctrl, c);
9736 		res = 0;
9737 		switch (c->ourcallstate) {
9738 		case Q931_CALL_STATE_CALL_RECEIVED:
9739 		case Q931_CALL_STATE_CONNECT_REQUEST:
9740 		case Q931_CALL_STATE_INCOMING_CALL_PROCEEDING:
9741 			if (PTMP_MODE(ctrl)) {
9742 				/* RETRIEVE request only allowed in these states if point-to-point mode. */
9743 				q931_send_retrieve_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9744 				break;
9745 			}
9746 			/* Fall through */
9747 		case Q931_CALL_STATE_OUTGOING_CALL_PROCEEDING:
9748 		case Q931_CALL_STATE_CALL_DELIVERED:
9749 		case Q931_CALL_STATE_ACTIVE:
9750 			if (!q931_find_winning_call(c)) {
9751 				/*
9752 				 * Only the winning call of a broadcast SETUP can do hold since the
9753 				 * call must be answered first.
9754 				 */
9755 				q931_send_retrieve_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9756 				break;
9757 			}
9758 			master_call = c->master_call;
9759 			switch (master_call->hold_state) {
9760 			case Q931_HOLD_STATE_RETRIEVE_REQ:
9761 				if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9762 					pri_message(ctrl, "RETRIEVE collision\n");
9763 				}
9764 				if (ctrl->localtype == PRI_NETWORK) {
9765 					/* The network ignores RETRIEVE request on a retrieve collision. */
9766 					break;
9767 				}
9768 				/* Fall through */
9769 			case Q931_HOLD_STATE_CALL_HELD:
9770 				ctrl->ev.e = PRI_EVENT_RETRIEVE;
9771 				ctrl->ev.retrieve.channel = q931_encode_channel(c);
9772 				ctrl->ev.retrieve.call = master_call;
9773 				ctrl->ev.retrieve.flexible = !(c->chanflags & FLAG_EXCLUSIVE);
9774 				ctrl->ev.retrieve.subcmds = &ctrl->subcmds;
9775 				res = Q931_RES_HAVEEVENT;
9776 
9777 				UPDATE_HOLD_STATE(ctrl, master_call, Q931_HOLD_STATE_RETRIEVE_IND);
9778 				break;
9779 			default:
9780 				q931_send_retrieve_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9781 				break;
9782 			}
9783 			break;
9784 		case Q931_CALL_STATE_DISCONNECT_INDICATION:
9785 		case Q931_CALL_STATE_RELEASE_REQUEST:
9786 			/* Ignore RETRIEVE request in these states. */
9787 			break;
9788 		default:
9789 			q931_send_retrieve_rej_msg(ctrl, c, PRI_CAUSE_WRONG_CALL_STATE);
9790 			break;
9791 		}
9792 		return res;
9793 	case Q931_RETRIEVE_ACKNOWLEDGE:
9794 		q931_display_subcmd(ctrl, c);
9795 		res = 0;
9796 		master_call = c->master_call;
9797 		switch (master_call->hold_state) {
9798 		case Q931_HOLD_STATE_RETRIEVE_REQ:
9799 			UPDATE_HOLD_STATE(ctrl, master_call, Q931_HOLD_STATE_IDLE);
9800 
9801 			/* Stop T-RETRIEVE timer */
9802 			pri_schedule_del(ctrl, master_call->hold_timer);
9803 			master_call->hold_timer = 0;
9804 
9805 			ctrl->ev.e = PRI_EVENT_RETRIEVE_ACK;
9806 			ctrl->ev.retrieve_ack.channel = q931_encode_channel(c);
9807 			ctrl->ev.retrieve_ack.call = master_call;
9808 			ctrl->ev.retrieve_ack.subcmds = &ctrl->subcmds;
9809 			res = Q931_RES_HAVEEVENT;
9810 			break;
9811 		default:
9812 			/* Ignore response.  Response is late or spurrious. */
9813 			break;
9814 		}
9815 		return res;
9816 	case Q931_RETRIEVE_REJECT:
9817 		q931_display_subcmd(ctrl, c);
9818 		res = 0;
9819 		master_call = c->master_call;
9820 		switch (master_call->hold_state) {
9821 		case Q931_HOLD_STATE_CALL_HELD:
9822 			/* In this state likely because of a RETRIEVE collision. */
9823 		case Q931_HOLD_STATE_RETRIEVE_REQ:
9824 			UPDATE_HOLD_STATE(ctrl, master_call, Q931_HOLD_STATE_CALL_HELD);
9825 
9826 			/* Call is still on hold so forget the channel. */
9827 			c->channelno = 0;/* No channel */
9828 			c->ds1no = 0;
9829 			c->ds1explicit = 0;
9830 			c->chanflags = 0;
9831 
9832 			/* Stop T-RETRIEVE timer */
9833 			pri_schedule_del(ctrl, master_call->hold_timer);
9834 			master_call->hold_timer = 0;
9835 
9836 			if (mand_status != MAND_STATUS_OK) {
9837 				/* Still, let retrive rejection continue. */
9838 				c->cause = mand_cause;
9839 			}
9840 			ctrl->ev.e = PRI_EVENT_RETRIEVE_REJ;
9841 			ctrl->ev.retrieve_rej.channel = q931_encode_channel(c);
9842 			ctrl->ev.retrieve_rej.call = master_call;
9843 			ctrl->ev.retrieve_rej.cause = c->cause;
9844 			ctrl->ev.retrieve_rej.subcmds = &ctrl->subcmds;
9845 			res = Q931_RES_HAVEEVENT;
9846 			break;
9847 		default:
9848 			/* Ignore response.  Response is late or spurrious. */
9849 			break;
9850 		}
9851 		return res;
9852 	case Q931_USER_INFORMATION:
9853 	case Q931_SEGMENT:
9854 	case Q931_CONGESTION_CONTROL:
9855 	case Q931_RESUME:
9856 	case Q931_RESUME_ACKNOWLEDGE:
9857 	case Q931_RESUME_REJECT:
9858 	case Q931_SUSPEND:
9859 	case Q931_SUSPEND_ACKNOWLEDGE:
9860 	case Q931_SUSPEND_REJECT:
9861 		pri_error(ctrl, "!! Not yet handling post-handle message type %s (0x%X)\n",
9862 			msg2str(mh->msg), mh->msg);
9863 		/* Fall through */
9864 	default:
9865 		pri_error(ctrl, "!! Don't know how to post-handle message type %s (0x%X)\n",
9866 			msg2str(mh->msg), mh->msg);
9867 		q931_display_clear(c);
9868 		q931_status(ctrl,c, PRI_CAUSE_MESSAGE_TYPE_NONEXIST);
9869 		if (c->newcall) {
9870 			pri_destroycall(ctrl, c);
9871 		}
9872 		return -1;
9873 	}
9874 	return 0;
9875 }
9876 
9877 /* Clear a call, although we did not receive any hangup notification. */
pri_internal_clear(struct q931_call * c)9878 static int pri_internal_clear(struct q931_call *c)
9879 {
9880 	struct pri *ctrl = c->pri;
9881 	int res;
9882 
9883 	pri_schedule_del(ctrl, c->retranstimer);
9884 	c->retranstimer = 0;
9885 	c->useruserinfo[0] = '\0';
9886 	//c->cause = -1;
9887 	c->causecode = -1;
9888 	c->causeloc = -1;
9889 	c->sugcallstate = Q931_CALL_STATE_NOT_SET;
9890 	c->aoc_units = -1;
9891 
9892 	if (c->master_call->outboundbroadcast
9893 		&& c == q931_find_winning_call(c)) {
9894 		/* Pass the hangup cause to the master_call. */
9895 		c->master_call->cause = c->cause;
9896 	}
9897 
9898 	q931_clr_subcommands(ctrl);
9899 	ctrl->ev.hangup.subcmds = &ctrl->subcmds;
9900 	ctrl->ev.hangup.channel = q931_encode_channel(c);
9901 	ctrl->ev.hangup.cause = c->cause;
9902 	ctrl->ev.hangup.cref = c->cr;
9903 	ctrl->ev.hangup.call = c->master_call;
9904 	ctrl->ev.hangup.aoc_units = c->aoc_units;
9905 	ctrl->ev.hangup.call_held = NULL;
9906 	ctrl->ev.hangup.call_active = NULL;
9907 	libpri_copy_string(ctrl->ev.hangup.useruserinfo, c->useruserinfo, sizeof(ctrl->ev.hangup.useruserinfo));
9908 
9909 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9910 		pri_message(ctrl, DBGHEAD "alive %d, hangupack %d\n", DBGINFO, c->alive,
9911 			c->sendhangupack);
9912 	}
9913 
9914 	if (c->cc.record) {
9915 		if (c->cc.record->signaling == c) {
9916 			pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_SIGNALING_GONE);
9917 		} else if (c->cc.record->original_call == c) {
9918 			pri_cc_event(ctrl, c, c->cc.record, CC_EVENT_INTERNAL_CLEARING);
9919 		}
9920 	}
9921 
9922 	/* Free resources */
9923 	if (c->alive) {
9924 		c->alive = 0;
9925 		ctrl->ev.e = PRI_EVENT_HANGUP;
9926 		res = Q931_RES_HAVEEVENT;
9927 	} else if (c->sendhangupack) {
9928 		pri_hangup(ctrl, c, c->cause);
9929 		ctrl->ev.e = PRI_EVENT_HANGUP_ACK;
9930 		res = Q931_RES_HAVEEVENT;
9931 	} else {
9932 		pri_hangup(ctrl, c, c->cause);
9933 		if (ctrl->subcmds.counter_subcmd) {
9934 			q931_fill_facility_event(ctrl, ctrl->link.dummy_call);
9935 			res = Q931_RES_HAVEEVENT;
9936 		} else {
9937 			res = 0;
9938 		}
9939 	}
9940 
9941 	return res;
9942 }
9943 
9944 /* Handle T309 timeout for an active call. */
pri_dl_down_timeout(void * data)9945 static void pri_dl_down_timeout(void *data)
9946 {
9947 	struct q931_call *c = data;
9948 	struct pri *ctrl = c->pri;
9949 
9950 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9951 		pri_message(ctrl, "T309 timed out waiting for data link re-establishment\n");
9952 	}
9953 
9954 	c->retranstimer = 0;
9955 	c->cause = PRI_CAUSE_DESTINATION_OUT_OF_ORDER;
9956 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
9957 	c->peercallstate = Q931_CALL_STATE_NULL;
9958 	if (pri_internal_clear(c) == Q931_RES_HAVEEVENT) {
9959 		ctrl->schedev = 1;
9960 	}
9961 }
9962 
9963 /* Handle Layer 2 down event for a non active call. */
pri_dl_down_cancelcall(void * data)9964 static void pri_dl_down_cancelcall(void *data)
9965 {
9966 	struct q931_call *c = data;
9967 	struct pri *ctrl = c->pri;
9968 
9969 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
9970 		pri_message(ctrl, "Cancel call after data link failure\n");
9971 	}
9972 
9973 	c->retranstimer = 0;
9974 	c->cause = PRI_CAUSE_DESTINATION_OUT_OF_ORDER;
9975 	UPDATE_OURCALLSTATE(ctrl, c, Q931_CALL_STATE_NULL);
9976 	c->peercallstate = Q931_CALL_STATE_NULL;
9977 	if (pri_internal_clear(c) == Q931_RES_HAVEEVENT) {
9978 		ctrl->schedev = 1;
9979 	}
9980 }
9981 
9982 /*!
9983  * \internal
9984  * \brief Convert the DL event to a string.
9985  *
9986  * \param event Data-link event to convert to a string.
9987  *
9988  * \return DL event string
9989  */
q931_dl_event2str(enum Q931_DL_EVENT event)9990 static const char *q931_dl_event2str(enum Q931_DL_EVENT event)
9991 {
9992 	const char *str;
9993 
9994 	str = "Unknown";
9995 	switch (event) {
9996 	case Q931_DL_EVENT_NONE:
9997 		str = "Q931_DL_EVENT_NONE";
9998 		break;
9999 	case Q931_DL_EVENT_DL_ESTABLISH_IND:
10000 		str = "Q931_DL_EVENT_DL_ESTABLISH_IND";
10001 		break;
10002 	case Q931_DL_EVENT_DL_ESTABLISH_CONFIRM:
10003 		str = "Q931_DL_EVENT_DL_ESTABLISH_CONFIRM";
10004 		break;
10005 	case Q931_DL_EVENT_DL_RELEASE_IND:
10006 		str = "Q931_DL_EVENT_DL_RELEASE_IND";
10007 		break;
10008 	case Q931_DL_EVENT_DL_RELEASE_CONFIRM:
10009 		str = "Q931_DL_EVENT_DL_RELEASE_CONFIRM";
10010 		break;
10011 	case Q931_DL_EVENT_TEI_REMOVAL:
10012 		str = "Q931_DL_EVENT_TEI_REMOVAL";
10013 		break;
10014 	}
10015 	return str;
10016 }
10017 
10018 /*!
10019  * \brief Receive a DL event from layer 2.
10020  *
10021  * \param link Q.921 link event occurred on.
10022  * \param event Data-link event reporting.
10023  *
10024  * \return Nothing
10025  */
q931_dl_event(struct q921_link * link,enum Q931_DL_EVENT event)10026 void q931_dl_event(struct q921_link *link, enum Q931_DL_EVENT event)
10027 {
10028 	struct q931_call *cur;
10029 	struct q931_call *cur_next;
10030 	struct q931_call *call;
10031 	struct pri *ctrl;
10032 	int idx;
10033 
10034 	if (!link) {
10035 		return;
10036 	}
10037 
10038 	ctrl = link->ctrl;
10039 
10040 	if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
10041 		pri_message(ctrl, "TEI=%d DL event: %s(%d)\n", link->tei,
10042 			q931_dl_event2str(event), event);
10043 	}
10044 
10045 	switch (event) {
10046 	case Q931_DL_EVENT_TEI_REMOVAL:
10047 		if (!BRI_NT_PTMP(ctrl)) {
10048 			/* Only NT PTMP has anything to worry about when the TEI is removed. */
10049 			break;
10050 		}
10051 
10052 		/*
10053 		 * For NT PTMP, this deviation from the specifications is needed
10054 		 * because we have no way to re-associate any T309 calls on the
10055 		 * removed TEI.
10056 		 */
10057 		for (cur = *ctrl->callpool; cur; cur = cur->next) {
10058 			if (cur->outboundbroadcast) {
10059 				/* Does this master call have a subcall on the link that went down? */
10060 				call = NULL;
10061 				for (idx = 0; idx < ARRAY_LEN(cur->subcalls); ++idx) {
10062 					if (cur->subcalls[idx] && cur->subcalls[idx]->link == link) {
10063 						/* This subcall is on the link that went down. */
10064 						call = cur->subcalls[idx];
10065 						break;
10066 					}
10067 				}
10068 				if (!call) {
10069 					/* No subcall is on the link that went down. */
10070 					continue;
10071 				}
10072 			} else if (cur->link != link) {
10073 				/* This call is not on the link that went down. */
10074 				continue;
10075 			} else {
10076 				call = cur;
10077 			}
10078 
10079 			if (!(cur->cr & ~Q931_CALL_REFERENCE_FLAG)) {
10080 				/* Simply destroy the global call reference call record. */
10081 				if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
10082 					pri_message(ctrl, "TEI=%d Destroying global call record\n",
10083 						link->tei);
10084 				}
10085 				q931_destroycall(ctrl, call);
10086 				continue;
10087 			}
10088 
10089 			/*
10090 			 * NOTE:  We are gambling that no T309 timer's have had a chance
10091 			 * to expire.  They should not expire since we are either called
10092 			 * immediately after the Q931_DL_EVENT_DL_RELEASE_xxx or after a
10093 			 * timeout of 0.
10094 			 */
10095 			if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
10096 				pri_message(ctrl, "Cancel call cref=%d on channel %d in state %d (%s)\n",
10097 					call->cr, call->channelno, call->ourcallstate,
10098 					q931_call_state_str(call->ourcallstate));
10099 			}
10100 			call->link = NULL;
10101 			pri_schedule_del(ctrl, call->retranstimer);
10102 			call->retranstimer = pri_schedule_event(ctrl, 0, pri_dl_down_cancelcall,
10103 				call);
10104 		}
10105 		break;
10106 	case Q931_DL_EVENT_DL_RELEASE_IND:
10107 	case Q931_DL_EVENT_DL_RELEASE_CONFIRM:
10108 		for (cur = *ctrl->callpool; cur; cur = cur_next) {
10109 			/* The master call could get destroyed if the last subcall dies. */
10110 			cur_next = cur->next;
10111 
10112 			if (!(cur->cr & ~Q931_CALL_REFERENCE_FLAG)) {
10113 				/* Don't do anything on the global call reference call record. */
10114 				continue;
10115 			}
10116 			if (cur->outboundbroadcast) {
10117 				/* Does this master call have a subcall on the link that went down? */
10118 				call = NULL;
10119 				for (idx = 0; idx < ARRAY_LEN(cur->subcalls); ++idx) {
10120 					if (cur->subcalls[idx] && cur->subcalls[idx]->link == link) {
10121 						/* This subcall is on the link that went down. */
10122 						call = cur->subcalls[idx];
10123 						break;
10124 					}
10125 				}
10126 				if (!call) {
10127 					/* No subcall is on the link that went down. */
10128 					continue;
10129 				}
10130 			} else if (cur->link != link) {
10131 				/* This call is not on the link that went down. */
10132 				continue;
10133 			} else {
10134 				call = cur;
10135 			}
10136 			switch (call->ourcallstate) {
10137 			case Q931_CALL_STATE_ACTIVE:
10138 				/* NOTE: Only a winning subcall can get to the active state. */
10139 				if (ctrl->nfas) {
10140 					/*
10141 					 * The upper layer should handle T309 for NFAS since the calls
10142 					 * could be maintained by a backup D channel if the B channel
10143 					 * for the call did not go into alarm.
10144 					 */
10145 					break;
10146 				}
10147 				/*
10148 				 * For a call in Active state, activate T309 only if there is
10149 				 * no timer already running.
10150 				 *
10151 				 * NOTE: cur != call when we have a winning subcall.
10152 				 */
10153 				if (!cur->retranstimer || !call->retranstimer) {
10154 					if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
10155 						pri_message(ctrl, "Start T309 for call cref=%d on channel %d\n",
10156 							call->cr, call->channelno);
10157 					}
10158 					call->retranstimer = pri_schedule_event(ctrl,
10159 						ctrl->timers[PRI_TIMER_T309], pri_dl_down_timeout, call);
10160 				}
10161 				break;
10162 			case Q931_CALL_STATE_NULL:
10163 				break;
10164 			default:
10165 				/*
10166 				 * For a call that is not in Active state, schedule internal
10167 				 * clearing of the call 'ASAP' (delay 0).
10168 				 *
10169 				 * NOTE: We are killing NFAS calls that are not connected yet
10170 				 * because there are likely messages in flight when this link
10171 				 * went down that could leave the call in an unknown/stuck state.
10172 				 */
10173 				if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
10174 					pri_message(ctrl,
10175 						"Cancel call cref=%d on channel %d in state %d (%s)\n",
10176 						call->cr, call->channelno, call->ourcallstate,
10177 						q931_call_state_str(call->ourcallstate));
10178 				}
10179 				if (cur->outboundbroadcast) {
10180 					/* Simply destroy non-winning subcalls. */
10181 					q931_destroycall(ctrl, call);
10182 					continue;
10183 				}
10184 				pri_schedule_del(ctrl, call->retranstimer);
10185 				call->retranstimer = pri_schedule_event(ctrl, 0, pri_dl_down_cancelcall,
10186 					call);
10187 				break;
10188 			}
10189 		}
10190 		break;
10191 	case Q931_DL_EVENT_DL_ESTABLISH_IND:
10192 	case Q931_DL_EVENT_DL_ESTABLISH_CONFIRM:
10193 		for (cur = *ctrl->callpool; cur; cur = cur->next) {
10194 			if (!(cur->cr & ~Q931_CALL_REFERENCE_FLAG)) {
10195 				/* Don't do anything on the global call reference call record. */
10196 				continue;
10197 			}
10198 			if (cur->outboundbroadcast) {
10199 				/* Does this master call have a subcall on the link that came up? */
10200 				call = NULL;
10201 				for (idx = 0; idx < ARRAY_LEN(cur->subcalls); ++idx) {
10202 					if (cur->subcalls[idx] && cur->subcalls[idx]->link == link) {
10203 						/* This subcall is on the link that came up. */
10204 						call = cur->subcalls[idx];
10205 						break;
10206 					}
10207 				}
10208 				if (!call) {
10209 					/* No subcall is on the link that came up. */
10210 					continue;
10211 				}
10212 			} else if (cur->link != link) {
10213 				/* This call is not on the link that came up. */
10214 				continue;
10215 			} else {
10216 				call = cur;
10217 			}
10218 			switch (call->ourcallstate) {
10219 			case Q931_CALL_STATE_ACTIVE:
10220 				/* NOTE: Only a winning subcall can get to the active state. */
10221 				if (pri_schedule_check(ctrl, call->retranstimer, pri_dl_down_timeout, call)) {
10222 					if (ctrl->debug & PRI_DEBUG_Q931_STATE) {
10223 						pri_message(ctrl, "Stop T309 for call cref=%d on channel %d\n",
10224 							call->cr, call->channelno);
10225 					}
10226 					pri_schedule_del(ctrl, call->retranstimer);
10227 					call->retranstimer = 0;
10228 				}
10229 				q931_status(ctrl, call, PRI_CAUSE_NORMAL_UNSPECIFIED);
10230 				break;
10231 			case Q931_CALL_STATE_NULL:
10232 			case Q931_CALL_STATE_DISCONNECT_REQUEST:
10233 			case Q931_CALL_STATE_DISCONNECT_INDICATION:
10234 			case Q931_CALL_STATE_RELEASE_REQUEST:
10235 				break;
10236 			default:
10237 				if (event == Q931_DL_EVENT_DL_ESTABLISH_CONFIRM) {
10238 					/*
10239 					 * Lets not send a STATUS message for this call as we
10240 					 * requested the link to be established as a likely
10241 					 * result of this call.
10242 					 */
10243 					break;
10244 				}
10245 				/*
10246 				 * The STATUS message sent here is not required by Q.931,
10247 				 * but it may help anyway.
10248 				 * This looks like a new call started while the link was down.
10249 				 */
10250 				q931_status(ctrl, call, PRI_CAUSE_NORMAL_UNSPECIFIED);
10251 				break;
10252 			}
10253 		}
10254 		break;
10255 	default:
10256 		pri_message(ctrl, DBGHEAD "unexpected event %d.\n", DBGINFO, event);
10257 		break;
10258 	}
10259 }
10260 
q931_call_getcrv(struct pri * ctrl,q931_call * call,int * callmode)10261 int q931_call_getcrv(struct pri *ctrl, q931_call *call, int *callmode)
10262 {
10263 	if (callmode)
10264 		*callmode = call->cr & 0x7;
10265 	return ((call->cr & 0x7fff) >> 3);
10266 }
10267 
q931_call_setcrv(struct pri * ctrl,q931_call * call,int crv,int callmode)10268 int q931_call_setcrv(struct pri *ctrl, q931_call *call, int crv, int callmode)
10269 {
10270 	/* Do not allow changing the dummy call reference */
10271 	if (!q931_is_dummy_call(call)) {
10272 		call->cr = (crv << 3) & 0x7fff;
10273 		call->cr |= (callmode & 0x7);
10274 	}
10275 	return 0;
10276 }
10277