Debian Codegraph @

channels/chan_unistim.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * UNISTIM channel driver for asterisk
5 *
6 * Copyright (C) 2005 - 2007, Cedric Hans
7 *
8 * Cedric Hans <[email protected]>
9 *
10 * Asterisk 1.4 patch by Peter Be
11 *
12 * See http://www.asterisk.org for more information about
13 * the Asterisk project. Please do not directly contact
14 * any of the maintainers of this project for assistance;
15 * the project provides a web site, mailing lists and IRC
16 * channels for your use.
17 *
18 * This program is free software, distributed under the terms of
19 * the GNU General Public License Version 2. See the LICENSE file
20 * at the top of the source tree.
21 */
22
23 /*!
24 * \file
25 *
26 * \brief chan_unistim channel driver for Asterisk
27 * \author Cedric Hans <[email protected]>
28 *
29 * Unistim (Unified Networks IP Stimulus) channel driver
30 * for Nortel i2002, i2004 and i2050
31 *
32 * \ingroup channel_drivers
33 */
34
35 /*** MODULEINFO
36 <support_level>extended</support_level>
37 ***/
38
39 #include "asterisk.h"
40
41 #include <sys/stat.h>
42 #include <signal.h>
43
44 #if defined(__CYGWIN__) || defined(__NetBSD__)
45 /*
46 * cygwin headers are partly inconsistent. struct iovec is defined in sys/uio.h
47 * which is not included by default by sys/socket.h - in_pktinfo is defined in
48 * w32api/ws2tcpip.h but this probably has compatibility problems with sys/socket.h
49 * So for the time being we simply disable HAVE_PKTINFO when building under cygwin.
50 * This should be done in some common header, but for now this is the only file
51 * using iovec and in_pktinfo so it suffices to apply the fix here.
52 */
53 #ifdef HAVE_PKTINFO
54 #undef HAVE_PKTINFO
55 #endif
56 #endif /* __CYGWIN__ || __NetBSD__ */
57
58 #include "asterisk/paths.h" /* ast_config_AST_LOG_DIR used in (too ?) many places */
59 #include "asterisk/network.h"
60 #include "asterisk/channel.h"
61 #include "asterisk/config.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/rtp_engine.h"
65 #include "asterisk/unaligned.h"
66 #include "asterisk/netsock2.h"
67 #include "asterisk/acl.h"
68 #include "asterisk/callerid.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/app.h"
71 #include "asterisk/mwi.h"
72 #include "asterisk/musiconhold.h"
73 #include "asterisk/causes.h"
74 #include "asterisk/indications.h"
75 #include "asterisk/pickup.h"
76 #include "asterisk/astobj2.h"
77 #include "asterisk/astdb.h"
78 #include "asterisk/features_config.h"
79 #include "asterisk/bridge.h"
80 #include "asterisk/stasis_channels.h"
81 #include "asterisk/format_cache.h"
82
83 #define DEFAULTCONTEXT "default"
84 #define DEFAULTCALLERID "Unknown"
85 #define DEFAULTCALLERNAME " "
86 #define DEFAULTHEIGHT 3
87 #define USTM_LOG_DIR "unistimHistory"
88 #define USTM_LANG_DIR "unistimLang"
89
90 /*! Size of the transmit buffer */
91 #define MAX_BUF_SIZE 64
92 /*! Number of slots for the transmit queue */
93 #define MAX_BUF_NUMBER 150
94 /*! Number of digits displayed on screen */
95 #define MAX_SCREEN_NUMBER 15
96 /*! Length of month label size */
97 #define MONTH_LABEL_SIZE 3
98 /*! Try x times before removing the phone */
99 #define NB_MAX_RETRANSMIT 8
100 /*! Nb of milliseconds waited when no events are scheduled */
101 #define IDLE_WAIT 1000
102 /*! Wait x milliseconds before resending a packet */
103 #define RETRANSMIT_TIMER 2000
104 /*! How often the mailbox is checked for new messages */
105 #define TIMER_MWI 5000
106 /*! Timeout value for entered number being dialed */
107 #define DEFAULT_INTERDIGIT_TIMER 4000
108
109 /*! Not used */
110 #define DEFAULT_CODEC 0x00
111 #define SIZE_PAGE 4096
112 #define DEVICE_NAME_LEN 16
113 #define AST_CONFIG_MAX_PATH 255
114 #define MAX_ENTRY_LOG 30
115
116 #define SUB_REAL 0
117 #define SUB_RING 1
118 #define SUB_THREEWAY 2
119
120 struct ast_format_cap *global_cap;
121
122 enum autoprovision {
123 AUTOPROVISIONING_NO = 0,
124 AUTOPROVISIONING_YES,
125 AUTOPROVISIONING_TN
126 };
127
128 enum autoprov_extn {
129 /*! Do not create an extension into the default dialplan */
130 EXTENSION_NONE = 0,
131 /*! Prompt user for an extension number and register it */
132 EXTENSION_ASK,
133 /*! Register an extension with the line=> value */
134 EXTENSION_LINE,
135 /*! Used with AUTOPROVISIONING_TN */
136 EXTENSION_TN
137 };
138 #define OUTPUT_HANDSET 0xC0
139 #define OUTPUT_HEADPHONE 0xC1
140 #define OUTPUT_SPEAKER 0xC2
141
142 #define VOLUME_LOW 0x01
143 #define VOLUME_LOW_SPEAKER 0x03
144 #define VOLUME_NORMAL 0x02
145 #define VOLUME_INSANELY_LOUD 0x07
146
147 #define MUTE_OFF 0x00
148 #define MUTE_ON 0xFF
149 #define MUTE_ON_DISCRET 0xCE
150
151 #define LED_BAR_OFF 0x00 /* bar off */
152 #define LED_BAR_ON 0x01 /* bar on */
153 #define LED_BAR_P2 0x02 /* bar 1s on/1s */
154 #define LED_BAR_P3 0x03 /* bar 2.5s on/0.5s off */
155 #define LED_BAR_P4 0x04 /* bar 0.6s on/0.3s off */
156 #define LED_BAR_P5 0x05 /* bar 0.5s on/0.5s off */
157 #define LED_BAR_P6 0x06 /* bar 2s on/0.5s off */
158 #define LED_BAR_P7 0x07 /* bar off */
159 #define LED_SPEAKER_OFF 0x08
160 #define LED_SPEAKER_ON 0x09
161 #define LED_HEADPHONE_OFF 0x010
162 #define LED_HEADPHONE_ON 0x011
163 #define LED_MUTE_OFF 0x018
164 #define LED_MUTE_ON 0x019
165 #define LED_MUTE_BLINK 0x1A
166
167 #define SIZE_HEADER 6
168 #define SIZE_MAC_ADDR 17
169 #define TEXT_LENGTH_MAX 24
170 #define TEXT_LINE0 0x00
171 #define TEXT_LINE1 0x20
172 #define TEXT_LINE2 0x40
173 #define TEXT_NORMAL 0x05
174 #define TEXT_INVERSE 0x25
175 #define STATUS_LENGTH_MAX 28
176
177 #define FAV_ICON_NONE 0x00
178 #define FAV_ICON_ONHOOK_BLACK 0x20
179 #define FAV_ICON_ONHOOK_WHITE 0x21
180 #define FAV_ICON_SPEAKER_ONHOOK_BLACK 0x22
181 #define FAV_ICON_SPEAKER_ONHOOK_WHITE 0x23
182 #define FAV_ICON_OFFHOOK_BLACK 0x24
183 #define FAV_ICON_OFFHOOK_WHITE 0x25
184 #define FAV_ICON_ONHOLD_BLACK 0x26
185 #define FAV_ICON_ONHOLD_WHITE 0x27
186 #define FAV_ICON_SPEAKER_OFFHOOK_BLACK 0x28
187 #define FAV_ICON_SPEAKER_OFFHOOK_WHITE 0x29
188 #define FAV_ICON_PHONE_BLACK 0x2A
189 #define FAV_ICON_PHONE_WHITE 0x2B
190 #define FAV_ICON_SPEAKER_ONHOLD_BLACK 0x2C
191 #define FAV_ICON_SPEAKER_ONHOLD_WHITE 0x2D
192 #define FAV_ICON_HEADPHONES 0x2E
193 #define FAV_ICON_HEADPHONES_ONHOLD 0x2F
194 #define FAV_ICON_HOME 0x30
195 #define FAV_ICON_CITY 0x31
196 #define FAV_ICON_SHARP 0x32
197 #define FAV_ICON_PAGER 0x33
198 #define FAV_ICON_CALL_CENTER 0x34
199 #define FAV_ICON_FAX 0x35
200 #define FAV_ICON_MAILBOX 0x36
201 #define FAV_ICON_REFLECT 0x37
202 #define FAV_ICON_COMPUTER 0x38
203 #define FAV_ICON_FORWARD 0x39
204 #define FAV_ICON_LOCKED 0x3A
205 #define FAV_ICON_TRASH 0x3B
206 #define FAV_ICON_INBOX 0x3C
207 #define FAV_ICON_OUTBOX 0x3D
208 #define FAV_ICON_MEETING 0x3E
209 #define FAV_ICON_BOX 0x3F
210
211 #define FAV_BLINK_FAST 0x20
212 #define FAV_BLINK_SLOW 0x40
213
214 #define FAV_MAX_LENGTH 0x0A
215
216 #define FAVNUM 6
217 #define EXPNUM 24
218 #define FAV_LINE_ICON FAV_ICON_ONHOOK_BLACK
219
220 static void dummy(char *unused, ...)
221 {
222 return;
223 }
224
225 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
226 * \note Values shown here match the defaults shown in unistim.conf.sample */
227 static struct ast_jb_conf default_jbconf =
228 {
229 .flags = 0,
230 .max_size = 200,
231 .resync_threshold = 1000,
232 .impl = "fixed",
233 .target_extra = 40,
234 };
235 static struct ast_jb_conf global_jbconf;
236
237
238 /* #define DUMP_PACKET 1 */
239 /* #define DEBUG_TIMER ast_verbose */
240
241 #define DEBUG_TIMER dummy
242 /*! Enable verbose output. can also be set with the CLI */
243 static int unistimdebug = 0;
244 static int unistim_port;
245 static enum autoprovision autoprovisioning = AUTOPROVISIONING_NO;
246 static int unistim_keepalive;
247 static int unistimsock = -1;
248
249 static struct {
250 unsigned int tos;
251 unsigned int tos_audio;
252 unsigned int cos;
253 unsigned int cos_audio;
254 } qos = { 0, 0, 0, 0 };
255
256 static struct io_context *io;
257 static struct ast_sched_context *sched;
258 static struct sockaddr_in public_ip = { 0, };
259 static unsigned char *buff; /*! Receive buffer address */
260 static int unistim_reloading = 0;
261 AST_MUTEX_DEFINE_STATIC(unistim_reload_lock);
262
263 /*! This is the thread for the monitor which checks for input on the channels
264 * which are not currently in use. */
265 static pthread_t monitor_thread = AST_PTHREADT_NULL;
266
267 /*! Protect the monitoring thread, so only one process can kill or start it, and not
268 * when it's doing something critical. */
269 AST_MUTEX_DEFINE_STATIC(monlock);
270 /*! Protect the session list */
271 AST_MUTEX_DEFINE_STATIC(sessionlock);
272 /*! Protect the device list */
273 AST_MUTEX_DEFINE_STATIC(devicelock);
274
275 enum phone_state {
276 STATE_INIT,
277 STATE_AUTHDENY,
278 STATE_MAINPAGE,
279 STATE_EXTENSION,
280 STATE_DIALPAGE,
281 STATE_RINGING,
282 STATE_CALL,
283 STATE_SELECTOPTION,
284 STATE_SELECTCODEC,
285 STATE_SELECTLANGUAGE,
286 STATE_CLEANING,
287 STATE_HISTORY
288 };
289
290 enum handset_state {
291 STATE_ONHOOK,
292 STATE_OFFHOOK,
293 };
294
295 enum phone_key {
296 KEY_0 = 0x40,
297 KEY_1 = 0x41,
298 KEY_2 = 0x42,
299 KEY_3 = 0x43,
300 KEY_4 = 0x44,
301 KEY_5 = 0x45,
302 KEY_6 = 0x46,
303 KEY_7 = 0x47,
304 KEY_8 = 0x48,
305 KEY_9 = 0x49,
306 KEY_STAR = 0x4a,
307 KEY_SHARP = 0x4b,
308 KEY_UP = 0x4c,
309 KEY_DOWN = 0x4d,
310 KEY_RIGHT = 0x4e,
311 KEY_LEFT = 0x4f,
312 KEY_QUIT = 0x50,
313 KEY_COPY = 0x51,
314 KEY_FUNC1 = 0x54,
315 KEY_FUNC2 = 0x55,
316 KEY_FUNC3 = 0x56,
317 KEY_FUNC4 = 0x57,
318 KEY_ONHOLD = 0x5b,
319 KEY_HANGUP = 0x5c,
320 KEY_MUTE = 0x5d,
321 KEY_HEADPHN = 0x5e,
322 KEY_LOUDSPK = 0x5f,
323 KEY_FAV0 = 0x60,
324 KEY_FAV1 = 0x61,
325 KEY_FAV2 = 0x62,
326 KEY_FAV3 = 0x63,
327 KEY_FAV4 = 0x64,
328 KEY_FAV5 = 0x65,
329 KEY_COMPUTR = 0x7b,
330 KEY_CONF = 0x7c,
331 KEY_SNDHIST = 0x7d,
332 KEY_RCVHIST = 0x7e,
333 KEY_INDEX = 0x7f
334 };
335
336 enum charset {
337 LANG_DEFAULT,
338 ISO_8859_1,
339 ISO_8859_2,
340 ISO_8859_4,
341 ISO_8859_5,
342 ISO_2022_JP,
343 };
344
345 static const int dtmf_row[] = { 697, 770, 852, 941 };
346 static const float dtmf_col[] = { 1209, 1336, 1477, 1633 };
347
348 struct wsabuf {
349 u_long len;
350 unsigned char *buf;
351 };
352
353 struct unistim_subchannel {
354 ast_mutex_t lock;
355 unsigned int subtype; /*! SUB_REAL, SUB_RING or SUB_THREEWAY */
356 struct ast_channel *owner; /*! Asterisk channel used by the subchannel */
357 struct unistim_line *parent; /*! Unistim line */
358 struct ast_rtp_instance *rtp; /*! RTP handle */
359 int softkey; /*! Softkey assigned */
360 pthread_t ss_thread; /*! unistim_ss thread handle */
361 int alreadygone;
362 int holding; /*! this subchannel holds someone */
363 signed char ringvolume;
364 signed char ringstyle;
365 int moh; /*!< Music on hold in progress */
366 AST_LIST_ENTRY(unistim_subchannel) list;
367 };
368
369 /*!
370 * \todo Convert to stringfields
371 */
372 struct unistim_line {
373 ast_mutex_t lock;
374 char name[80]; /*! Like 200 */
375 char fullname[101]; /*! Like USTM/200\@black */
376 char exten[AST_MAX_EXTENSION]; /*! Extension where to start */
377 char cid_num[AST_MAX_EXTENSION]; /*! CallerID Number */
378 char mailbox[AST_MAX_EXTENSION]; /*! Mailbox for MWI */
379 char musicclass[MAX_MUSICCLASS]; /*! MusicOnHold class */
380 ast_group_t callgroup; /*! Call group */
381 ast_group_t pickupgroup; /*! Pickup group */
382 char accountcode[AST_MAX_ACCOUNT_CODE]; /*! Account code (for billing) */
383 int amaflags; /*! AMA flags (for billing) */
384 struct ast_format_cap *cap; /*! Codec supported */
385 char parkinglot[AST_MAX_CONTEXT]; /*! Parkinglot */
386 struct unistim_line *next;
387 struct unistim_device *parent;
388 AST_LIST_ENTRY(unistim_line) list;
389 };
390
391 /*!
392 * \brief A device containing one or more lines
393 */
394 static struct unistim_device {
395 ast_mutex_t lock;
396 int receiver_state; /*!< state of the receiver (see ReceiverState) */
397 int size_phone_number; /*!< size of the phone number */
398 char context[AST_MAX_EXTENSION]; /*!< Context to start in */
399 char phone_number[AST_MAX_EXTENSION]; /*!< the phone number entered by the user */
400 char redial_number[AST_MAX_EXTENSION]; /*!< the last phone number entered by the user */
401 char id[18]; /*!< mac address of the current phone in ascii */
402 char name[DEVICE_NAME_LEN]; /*!< name of the device */
403 int hasexp; /*!< if device have expansion connected */
404 char expsoftkeylabel[EXPNUM][11]; /*!< soft key label */
405 char softkeylabel[FAVNUM][11]; /*!< soft key label */
406 char softkeynumber[FAVNUM][AST_MAX_EXTENSION]; /*!< number dialed when the soft key is pressed */
407 char softkeyicon[FAVNUM]; /*!< icon number */
408 char softkeydevice[FAVNUM][16]; /*!< name of the device monitored */
409 struct unistim_subchannel *ssub[FAVNUM];
410 struct unistim_line *sline[FAVNUM];
411 struct unistim_device *sp[FAVNUM]; /*!< pointer to the device monitored by this soft key */
412 char language[MAX_LANGUAGE]; /*!< Language for asterisk sounds */
413 int height; /*!< The number of lines the phone can display */
414 char maintext0[25]; /*!< when the phone is idle, display this string on line 0 */
415 char maintext1[25]; /*!< when the phone is idle, display this string on line 1 */
416 char maintext2[25]; /*!< when the phone is idle, display this string on line 2 */
417 char titledefault[13]; /*!< title (text before date/time) */
418 char datetimeformat; /*!< format used for displaying time/date */
419 signed char contrast; /*!< contrast */
420 char country[3]; /*!< country used for dial tone frequency */
421 struct ast_tone_zone *tz; /*!< Tone zone for res_indications (ring, busy, congestion) */
422 signed char ringvolume; /*!< Ring volume */
423 signed char ringstyle; /*!< Ring melody */
424 signed char cwvolume; /*!< Ring volume on call waiting */
425 signed char cwstyle; /*!< Ring melody on call waiting */
426 int interdigit_timer; /*!< Interdigit timer for dialing number by timeout */
427 int dtmfduration; /*!< DTMF playback duration */
428 time_t nextdial; /*!< Timer used for dial by timeout */
429 int rtp_port; /*!< RTP port used by the phone */
430 int rtp_method; /*!< Select the unistim data used to establish a RTP session */
431 int status_method; /*!< Select the unistim packet used for sending status text */
432 char codec_number; /*!< The current codec used to make calls */
433 int missed_call; /*!< Number of call unanswered */
434 int callhistory; /*!< Allowed to record call history */
435 int sharp_dial; /*!< Execute Dial on '#' or not */
436 char lst_cid[TEXT_LENGTH_MAX]; /*!< Last callerID received */
437 char lst_cnm[TEXT_LENGTH_MAX]; /*!< Last callername received */
438 char call_forward[AST_MAX_EXTENSION]; /*!< Forward number */
439 int output; /*!< Handset, headphone or speaker */
440 int previous_output; /*!< Previous output */
441 int volume; /*!< Default volume */
442 int selected; /*!< softkey selected */
443 int microphone; /*!< Microphone mode (audio tx) */
444 int lastmsgssent; /*! Used by MWI */
445 time_t nextmsgcheck; /*! Used by MWI */
446 int nat; /*!< Used by the obscure ast_rtp_setnat */
447 enum autoprov_extn extension; /*!< See ifdef EXTENSION for valid values */
448 char extension_number[11]; /*!< Extension number entered by the user */
449 signed char to_delete; /*!< Used in reload */
450 struct ast_silence_generator *silence_generator;
451 AST_LIST_HEAD(,unistim_subchannel) subs; /*!< pointer to our current connection, channel... */
452 AST_LIST_HEAD(,unistim_line) lines;
453 struct ast_ha *ha;
454 struct unistimsession *session;
455 struct unistim_device *next;
456 } *devices = NULL;
457
458 #define MAX_PHONE_NUMBER_LENGTH (AST_MAX_EXTENSION - 1)
459
460 static struct unistimsession {
461 ast_mutex_t lock;
462 struct sockaddr_in sin; /*!< IP address of the phone */
463 struct sockaddr_in sout; /*!< IP address of server */
464 int timeout; /*!< time-out in ticks : resend packet if no ack was received before the timeout occurred */
465 unsigned short seq_phone; /*!< sequence number for the next packet (when we receive a request) */
466 unsigned short seq_server; /*!< sequence number for the next packet (when we send a request) */
467 unsigned short last_seq_ack; /*!< sequence number of the last ACK received */
468 unsigned long tick_next_ping; /*!< time for the next ping */
469 int last_buf_available; /*!< number of a free slot */
470 int nb_retransmit; /*!< number of retransmission */
471 int state; /*!< state of the phone (see phone_state) */
472 int size_buff_entry; /*!< size of the buffer used to enter data */
473 char buff_entry[16]; /*!< Buffer for temporary data */
474 char macaddr[18]; /*!< mac address of the phone (not always available) */
475 char firmware[8]; /*!< firmware of the phone (not always available) */
476 struct wsabuf wsabufsend[MAX_BUF_NUMBER]; /*!< Size of each paquet stored in the buffer array & pointer to this buffer */
477 unsigned char buf[MAX_BUF_NUMBER][MAX_BUF_SIZE]; /*!< Buffer array used to keep the latest non-acked paquets */
478 struct unistim_device *device;
479 struct unistimsession *next;
480 } *sessions = NULL;
481
482 /*! Store on screen phone menu item (label and handler function) */
483 struct unistim_menu_item {
484 char *label;
485 int state;
486 void (*handle_option)(struct unistimsession *);
487 };
488
489 /*! Language item for currently existed translations */
490 struct unistim_languages {
491 char *label;
492 char *lang_short;
493 int encoding;
494 struct ao2_container *trans;
495 };
496
497 /*!
498 * \page Unistim datagram formats
499 *
500 * Format of datagrams :
501 * bytes 0 & 1 : ffff for discovery packet, 0000 for everything else
502 * byte 2 : sequence number (high part)
503 * byte 3 : sequence number (low part)
504 * byte 4 : 2 = ask question or send info, 1 = answer or ACK, 0 = retransmit request
505 * byte 5 : direction, 1 = server to phone, 2 = phone to server arguments
506 */
507
508 static const unsigned char packet_rcv_discovery[] =
509 { 0xff, 0xff, 0xff, 0xff, 0x02, 0x02, 0xff, 0xff, 0xff, 0xff, 0x9e, 0x03, 0x08 };
510 static const unsigned char packet_send_discovery_ack[] =
511 { 0x00, 0x00, /*Initial Seq (2 bytes) */ 0x00, 0x00, 0x00, 0x01 };
512
513 static const unsigned char packet_recv_firm_version[] =
514 { 0x00, 0x00, 0x00, 0x13, 0x9a, 0x0a, 0x02 };
515 static const unsigned char packet_recv_it_type[] =
516 { 0x00, 0x00, 0x00, 0x13, 0x9a, 0x04, 0x03 };
517 static const unsigned char packet_recv_pressed_key[] =
518 { 0x00, 0x00, 0x00, 0x13, 0x99, 0x04, 0x00 };
519 static const unsigned char packet_recv_pick_up[] =
520 { 0x00, 0x00, 0x00, 0x13, 0x99, 0x03, 0x04 };
521 static const unsigned char packet_recv_hangup[] =
522 { 0x00, 0x00, 0x00, 0x13, 0x99, 0x03, 0x03 };
523 static const unsigned char packet_recv_r2[] = { 0x00, 0x00, 0x00, 0x13, 0x96, 0x03, 0x03 };
524
525 /*! Expansion module (i2004 KEM) */
526 static const unsigned char packet_recv_expansion_pressed_key[] =
527 { 0x00, 0x00, 0x00, 0x13, 0x89, 0x04, 0x59 };
528 static const unsigned char packet_send_expansion_next[] = { 0x09, 0x03, 0x17 };
529 static const unsigned char packet_send_expansion_icon[] = { 0x09, 0x06, 0x59, 0x05, /*pos */ 0x47, /*icon */ 0x20 }; /* display an icon in front of the text zone */
530 static const unsigned char packet_send_expansion_text[] = { 0x09, 0x0f, 0x57, 0x19, /*pos */ 0x47, /*text */ 0x20,
531 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 /*end_text */ };
532
533
534 /*! TransportAdapter */
535 static const unsigned char packet_recv_resume_connection_with_server[] =
536 { 0xff, 0xff, 0xff, 0xff, 0x9e, 0x03, 0x08 };
537 static const unsigned char packet_recv_mac_addr[] =
538 { 0xff, 0xff, 0xff, 0xff, 0x9a, 0x0d, 0x07 /*MacAddr */ };
539
540 static const unsigned char packet_send_date_time3[] =
541 { 0x11, 0x09, 0x02, 0x02, /*Month */ 0x05, /*Day */ 0x06, /*Hour */ 0x07,
542 /*Minutes */ 0x08, 0x32
543 };
544 static const unsigned char packet_send_date_time[] =
545 { 0x11, 0x09, 0x02, 0x0a, /*Month */ 0x05, /*Day */ 0x06, /*Hour */ 0x07, /*Minutes */
546 0x08, 0x32, 0x17, 0x04, 0x24, 0x07, 0x19,
547 0x04, 0x07, 0x00, 0x19, 0x05, 0x09, 0x3e, 0x0f, 0x16, 0x05, 0x00, 0x80, 0x00, 0x1e,
548 0x05, 0x12, 0x00, 0x78
549 };
550
551 static const unsigned char packet_send_no_ring[] =
552 { 0x16, 0x04, 0x1a, 0x00, 0x16, 0x04, 0x11, 0x00 };
553 static const unsigned char packet_send_s4[] =
554 { 0x16, 0x04, 0x1a, 0x00, 0x16, 0x04, 0x11, 0x00, 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff,
555 0x16, 0x05, 0x1c, 0x00, 0x00, 0x17, 0x05,
556 0x0b, 0x00, 0x00, 0x19, 0x04, 0x00, 0x00, 0x19, 0x04, 0x00, 0x08, 0x19, 0x04, 0x00,
557 0x10, 0x19, 0x04, 0x00, 0x18, 0x16, 0x05,
558 0x31, 0x00, 0x00, 0x16, 0x05, 0x04, 0x00, 0x00
559 };
560 static const unsigned char packet_send_call[] =
561 { 0x16, 0x04, 0x1a, 0x00, 0x16, 0x04, 0x11, 0x00, 0x16, 0x06, 0x32, 0xdf,
562 0x00, 0xff, 0x16, 0x05, 0x1c, 0x00, 0x00, 0x16, 0x0a, 0x38, 0x00, 0x12, 0xca, 0x03,
563 0xc0, 0xc3, 0xc5, 0x16, 0x16, 0x30, 0x00,
564 0x00, /*codec */ 0x12, 0x12, /* frames per packet */ 0x01, 0x5c, 0x00, /*port RTP */
565 0x0f, 0xa0, /* port RTCP */ 0x9c, 0x41,
566 /*port RTP */ 0x0f, 0xa0, /* port RTCP */ 0x9c, 0x41, /* IP Address */ 0x0a, 0x01,
567 0x16, 0x66
568 };
569 static const unsigned char packet_send_stream_based_tone_off[] =
570 { 0x16, 0x05, 0x1c, 0x00, 0x00 };
571
572 static const unsigned char packet_send_mute[] = { 0x16, 0x05, 0x04, 0x00, 0x00 };
573 #ifdef NOT_USED
574 static const unsigned char packet_send_CloseAudioStreamRX[] = { 0x16, 0x05, 0x31, 0x00, 0xff };
575 static const unsigned char packet_send_CloseAudioStreamTX[] = { 0x16, 0x05, 0x31, 0xff, 0x00 };
576 #endif
577 static const unsigned char packet_send_stream_based_tone_on[] =
578 { 0x16, 0x06, 0x1b, 0x00, 0x00, 0x05 };
579 static const unsigned char packet_send_stream_based_tone_single_freq[] =
580 { 0x16, 0x06, 0x1d, 0x00, 0x01, 0xb8 };
581 static const unsigned char packet_send_stream_based_tone_dual_freq[] =
582 { 0x16, 0x08, 0x1d, 0x00, 0x01, 0xb8, 0x01, 0x5e };
583 static const unsigned char packet_send_select_output[] =
584 { 0x16, 0x06, 0x32, 0xc0, 0x01, 0x00 };
585
586 static const unsigned char packet_send_ring[] =
587 { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x16, 0x05, 0x1c, 0x00, 0x00, 0x16,
588 0x04, 0x1a, 0x01, 0x16, 0x05, 0x12, 0x13 /* Ring type 10 to 17 */ , 0x18, 0x16, 0x04, 0x18, /* volume 00, 10, 20... */
589 0x20, 0x16, 0x04, 0x10, 0x00
590 };
591 //static const unsigned char packet_send_end_call[] =
592 // { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x16, 0x05, 0x31, 0x00, 0x00, /* Headset LED off */ 0x19, 0x04, 0x00,
593 //0x10, /* Mute LED off */ 0x19, 0x04, 0x00, 0x18,/* Stream unmute */ 0x16, 0x05, 0x04, 0x00, 0x00, /* Query RTCP */ 0x16, 0x04, 0x37, 0x10 };
594 static const unsigned char packet_send_end_call[] =
595 { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x16, 0x05, 0x31, 0x00, 0x00, /* Query RTCP */ 0x16, 0x04, 0x37, 0x10 };
596 static const unsigned char packet_send_s9[] =
597 { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x19, 0x04, 0x00, 0x10, 0x16, 0x05, 0x1c, 0x00,
598 0x00 };
599 static const unsigned char packet_send_rtp_packet_size[] =
600 { 0x16, 0x08, 0x38, 0x00, 0x00, 0xe0, 0x00, 0xa0 };
601 static const unsigned char packet_send_jitter_buffer_conf[] =
602 { 0x16, 0x0e, 0x3a, 0x00, /* jitter */ 0x02, /* high water mark */ 0x04, 0x00, 0x00,
603 /* early packet resync 2 bytes */ 0x3e, 0x80,
604 0x00, 0x00, /* late packet resync 2 bytes */ 0x3e, 0x80
605 };
606
607 /* Duration in ms div 2 (0x20 = 64ms, 0x08 = 16ms)
608 static unsigned char packet_send_StreamBasedToneCad[] =
609 { 0x16, 0x0a, 0x1e, 0x00, duration on 0x0a, duration off 0x0d, duration on 0x0a, duration off 0x0d, duration on 0x0a, duration off 0x2b }; */
610 static const unsigned char packet_send_open_audio_stream_rx[] =
611 { 0x16, 0x1a, 0x30, 0x00, 0xff, /* Codec */ 0x00, 0x00, 0x01, 0x00, 0xb8, 0xb8, 0x0e,
612 0x0e, 0x01, /* Port */ 0x14, 0x50, 0x00,
613 0x00, /* Port */ 0x14, 0x50, 0x00, 0x00, /* Dest IP */ 0x0a, 0x93, 0x69, 0x05
614 };
615 static const unsigned char packet_send_open_audio_stream_tx[] =
616 { 0x16, 0x1a, 0x30, 0xff, 0x00, 0x00, /* Codec */ 0x00, 0x01, 0x00, 0xb8, 0xb8, 0x0e,
617 0x0e, 0x01, /* Local port */ 0x14, 0x50,
618 0x00, 0x00, /* Rmt Port */ 0x14, 0x50, 0x00, 0x00, /* Dest IP */ 0x0a, 0x93, 0x69, 0x05
619 };
620
621 static const unsigned char packet_send_open_audio_stream_rx3[] =
622 { 0x16, 0x1a, 0x30, 0x00, 0xff, /* Codec */ 0x00, 0x00, 0x02, 0x01, 0xb8, 0xb8, 0x06,
623 0x06, 0x81, /* RTP Port */ 0x14, 0x50,
624 /* RTCP Port */ 0x14,
625 0x51, /* RTP Port */ 0x14, 0x50, /* RTCP Port */ 0x00, 0x00, /* Dest IP */ 0x0a, 0x93,
626 0x69, 0x05
627 };
628 static const unsigned char packet_send_open_audio_stream_tx3[] =
629 { 0x16, 0x1a, 0x30, 0xff, 0x00, 0x00, /* Codec */ 0x00, 0x02, 0x01, 0xb8, 0xb8, 0x06,
630 0x06, 0x81, /* RTP Local port */ 0x14, 0x50,
631 /* RTCP Port */ 0x00, 0x00, /* RTP Rmt Port */ 0x14, 0x50, /* RTCP Port */ 0x00, 0x00,
632 /* Dest IP */ 0x0a, 0x93, 0x69, 0x05
633 };
634
635 static const unsigned char packet_send_arrow[] = { 0x17, 0x04, 0x04, 0x00 };
636 static const unsigned char packet_send_blink_cursor[] = { 0x17, 0x04, 0x10, 0x86 };
637 static const unsigned char packet_send_date_time2[] = { 0x17, 0x04, 0x17, 0x3d, 0x11, 0x09, 0x02, 0x0a, /*Month */ 0x05, /*Day */
638 0x06, /*Hour */ 0x07, /*Minutes */ 0x08, 0x32
639 };
640 static const unsigned char packet_send_Contrast[] =
641 { 0x17, 0x04, 0x24, /*Contrast */ 0x08 };
642 static const unsigned char packet_send_start_timer[] =
643 { 0x17, 0x05, 0x0b, /*Timer option*/0x05, /* Timer ID */0x00, 0x17, 0x08, 0x16,
644 /* Text */ 'T', 'i', 'm', 'e', 'r' };
645 static const unsigned char packet_send_stop_timer[] = { 0x17, 0x05, 0x0b, 0x02, 0x00 };
646 static const unsigned char packet_send_icon[] = { 0x17, 0x05, 0x14, /*pos */ 0x00, /*icon */ 0x25 }; /* display an icon in front of the text zone */
647 static const unsigned char packet_send_S7[] = { 0x17, 0x06, 0x0f, 0x30, 0x07, 0x07 };
648 static const unsigned char packet_send_set_pos_cursor[] =
649 { 0x17, 0x06, 0x10, 0x81, 0x04, /*pos */ 0x20 };
650
651 static unsigned char monthlabels[] =
652 { 'J', 'a', 'n', 'F', 'e', 'b', 'M', 'a', 'r', 'A', 'p', 'r', 'M', 'a', 'y', 'J', 'u', 'n',
653 'J', 'u', 'l', 'A', 'u', 'g', 'S', 'e', 'p', 'O', 'c', 't', 'N', 'o', 'v', 'D', 'e', 'c' };
654 static unsigned char packet_send_monthlabels_download[] =
655 { 0x17, 0x0a, 0x15, /* Month (3 char) */ '-', '-', '-', '-', '-', '-', 0x20 };
656 static const unsigned char packet_send_favorite[] =
657 { 0x17, 0x0f, 0x19, 0x10, /*pos */ 0x01, /*name */ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
658 0x20, 0x20, 0x20, 0x20, /*end_name */ 0x19,
659 0x05, 0x0f, /*pos */ 0x01, /*icone */ 0x00
660 };
661 static const unsigned char packet_send_title[] =
662 { 0x17, 0x10, 0x19, 0x02, /*text */ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
663 0x20, 0x20, 0x20, 0x20 /*end_text */ };
664 static const unsigned char packet_send_text[] =
665 { 0x17, 0x1e, 0x1b, 0x04, /*pos */ 0x00, /*inverse */ 0x25, /*text */ 0x20, 0x20,
666 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
667 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
668 /*end_text */ 0x17, 0x04, 0x10, 0x87
669 };
670 static const unsigned char packet_send_status[] =
671 { 0x17, 0x20, 0x19, 0x08, /*text */ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
672 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
673 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 /*end_text */
674 };
675 static const unsigned char packet_send_status2[] =
676 { 0x17, 0x0b, 0x19, /* pos [08|28|48|68] */ 0x00, /* text */ 0x20, 0x20, 0x20, 0x20,
677 0x20, 0x20, 0x20 /* end_text */ };
678
679 /* Multiple character set support */
680 /* ISO-8859-1 - Western European) */
681 static const unsigned char packet_send_charset_iso_8859_1[] =
682 { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x41, 0x1b, 0x00 };
683 /* ISO-8859-2 - Central European) */
684 static const unsigned char packet_send_charset_iso_8859_2[] =
685 { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x42, 0x1b, 0x00 };
686 /* ISO-8859-4 - Baltic) */
687 static const unsigned char packet_send_charset_iso_8859_4[] =
688 { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x44, 0x1b, 0x00 };
689 /* ISO 8859-5 - cyrillic */
690 static const unsigned char packet_send_charset_iso_8859_5[] =
691 { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x4c, 0x1b, 0x00 };
692 /* Japanese (ISO-2022-JP ?) */
693 static const unsigned char packet_send_charset_iso_2022_jp[] =
694 { 0x17, 0x08, 0x21, 0x1b, 0x29, 0x49, 0x1b, 0x7e };
695
696 static const unsigned char packet_send_led_update[] = { 0x19, 0x04, 0x00, 0x00 };
697
698 static const unsigned char packet_send_query_basic_manager_04[] = { 0x1a, 0x04, 0x01, 0x04 };
699 static const unsigned char packet_send_query_mac_address[] = { 0x1a, 0x04, 0x01, 0x08 };
700 static const unsigned char packet_send_query_basic_manager_10[] = { 0x1a, 0x04, 0x01, 0x10 };
701 static const unsigned char packet_send_S1[] = { 0x1a, 0x07, 0x07, 0x00, 0x00, 0x00, 0x13 };
702
703 static unsigned char packet_send_ping[] =
704 { 0x1e, 0x05, 0x12, 0x00, /*Watchdog timer */ 0x78 };
705
706 #define BUFFSEND unsigned char buffsend[64] = { 0x00, 0x00, 0xaa, 0xbb, 0x02, 0x01 }
707
708 static const char tdesc[] = "UNISTIM Channel Driver";
709 static const char channel_type[] = "USTM";
710
711 /*! Protos */
712 static struct ast_channel *unistim_new(struct unistim_subchannel *sub, int state, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor);
713 static int load_module(void);
714 static int reload(void);
715 static int unload_module(void);
716 static int reload_config(void);
717 static void unistim_set_owner(struct unistim_subchannel *sub, struct ast_channel *chan);
718 static void show_main_page(struct unistimsession *pte);
719 static struct ast_channel *unistim_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor,
720 const char *dest, int *cause);
721 static int unistim_call(struct ast_channel *ast, const char *dest, int timeout);
722 static int unistim_hangup(struct ast_channel *ast);
723 static int unistim_answer(struct ast_channel *ast);
724 static struct ast_frame *unistim_read(struct ast_channel *ast);
725 static int unistim_write(struct ast_channel *ast, struct ast_frame *frame);
726 static int unistim_indicate(struct ast_channel *ast, int ind, const void *data,
727 size_t datalen);
728 static int unistim_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
729 static int unistim_senddigit_begin(struct ast_channel *ast, char digit);
730 static int unistim_senddigit_end(struct ast_channel *ast, char digit,
731 unsigned int duration);
732 static int unistim_sendtext(struct ast_channel *ast, const char *text);
733
734 static int write_entry_history(struct unistimsession *pte, FILE * f, char c,
735 char *line1);
736 static void change_callerid(struct unistimsession *pte, int type, char *callerid);
737
738 static struct ast_channel_tech unistim_tech = {
739 .type = channel_type,
740 .description = tdesc,
741 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
742 .requester = unistim_request,
743 .call = unistim_call,
744 .hangup = unistim_hangup,
745 .answer = unistim_answer,
746 .read = unistim_read,
747 .write = unistim_write,
748 .indicate = unistim_indicate,
749 .fixup = unistim_fixup,
750 .send_digit_begin = unistim_senddigit_begin,
751 .send_digit_end = unistim_senddigit_end,
752 .send_text = unistim_sendtext,
753 };
754
755 static void send_start_rtp(struct unistim_subchannel *);
756
757 static void send_callerid_screen(struct unistimsession *, struct unistim_subchannel *);
758 static void key_favorite(struct unistimsession *, char);
759
760 static void handle_select_codec(struct unistimsession *);
761 static void handle_select_language(struct unistimsession *);
762 static int find_language(const char*);
763
764 static int unistim_free_sub(struct unistim_subchannel *);
765
766 static struct unistim_menu_item options_menu[] =
767 {
768 {"Change codec", STATE_SELECTCODEC, handle_select_codec},
769 {"Language", STATE_SELECTLANGUAGE, handle_select_language},
770 {NULL, 0, NULL}
771 };
772
773 static struct unistim_languages options_languages[] =
774 {
775 {"English", "en", ISO_8859_1, NULL},
776 {"French", "fr", ISO_8859_1, NULL},
777 {"Russian", "ru", ISO_8859_5, NULL},
778 {NULL, NULL, 0, NULL}
779 };
780
781 static char ustm_strcopy[1024];
782
783 struct ustm_lang_entry {
784 const char *str_orig;
785 const char *str_trans;
786 };
787
788 static int lang_hash_fn(const void *obj, const int flags)
789 {
790 const struct ustm_lang_entry *entry = obj;
791 return ast_str_hash(entry->str_orig);
792 }
793
794 static int lang_cmp_fn(void *obj, void *arg, int flags)
795 {
796 struct ustm_lang_entry *entry1 = obj;
797 struct ustm_lang_entry *entry2 = arg;
798
799 return (!strcmp(entry1->str_orig, entry2->str_orig)) ? (CMP_MATCH | CMP_STOP) : 0;
800 }
801
802 static const char *ustmtext(const char *str, struct unistimsession *pte)
803 {
804 struct ustm_lang_entry *lang_entry;
805 struct ustm_lang_entry le_search;
806 struct unistim_languages *lang = NULL;
807 int size;
808
809 if (pte->device) {
810 lang = &options_languages[find_language(pte->device->language)];
811 }
812 if (!lang) {
813 return str;
814 }
815 /* Check if specified language exists */
816 if (!lang->trans) {
817 char tmp[1024], *p, *p_orig = NULL, *p_trans = NULL;
818 FILE *f;
819
820 lang->trans = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 8,
821 lang_hash_fn, NULL, lang_cmp_fn);
822 if (!lang->trans) {
823 ast_log(LOG_ERROR, "Unable to allocate container for translation!\n");
824 return str;
825 }
826 snprintf(tmp, sizeof(tmp), "%s/%s/%s.po", ast_config_AST_VAR_DIR,
827 USTM_LANG_DIR, lang->lang_short);
828 f = fopen(tmp, "r");
829 if (!f) {
830 ast_log(LOG_WARNING, "There is no translation file for '%s'\n", lang->lang_short);
831 return str;
832 }
833 while (fgets(tmp, sizeof(tmp), f)) {
834 if (!(p = strchr(tmp, '\n'))) {
835 ast_log(LOG_ERROR, "Too long line found in language file - truncated!\n");
836 continue;
837 }
838 *p = '\0';
839 if (!(p = strchr(tmp, '"'))) {
840 continue;
841 }
842 if (tmp == strstr(tmp, "msgid")) {
843 p_orig = ast_strdup(p + 1);
844 p = strchr(p_orig, '"');
845 } else if (tmp == strstr(tmp, "msgstr")) {
846 p_trans = ast_strdup(p + 1);
847 p = strchr(p_trans, '"');
848 } else {
849 continue;
850 }
851 *p = '\0';
852 if (!p_trans || !p_orig) {
853 continue;
854 }
855 if (ast_strlen_zero(p_trans)) {
856 ast_free(p_trans);
857 ast_free(p_orig);
858 p_trans = NULL;
859 p_orig = NULL;
860 continue;
861 }
862 if (!(lang_entry = ao2_alloc(sizeof(*lang_entry), NULL))) {
863 fclose(f);
864 return str;
865 }
866
867 lang_entry->str_trans = p_trans;
868 lang_entry->str_orig = p_orig;
869 ao2_link(lang->trans, lang_entry);
870 p_trans = NULL;
871 p_orig = NULL;
872 }
873
874 fclose(f);
875 }
876
877 le_search.str_orig = str;
878 if ((lang_entry = ao2_find(lang->trans, &le_search, OBJ_POINTER))) {
879 size = strlen(lang_entry->str_trans)+1;
880 if (size > 1024) {
881 size = 1024;
882 }
883 memcpy(ustm_strcopy, lang_entry->str_trans, size);
884 ao2_ref(lang_entry, -1);
885 return ustm_strcopy;
886 }
887
888 return str;
889 }
890
891 static void display_last_error(const char *sz_msg)
892 {
893 /* Display the error message */
894 ast_log(LOG_WARNING, "%s : (%d) %s\n", sz_msg, errno, strerror(errno));
895 }
896
897 static unsigned int get_tick_count(void)
898 {
899 struct timeval now = ast_tvnow();
900
901 return (now.tv_sec * 1000) + (now.tv_usec / 1000);
902 }
903
904 /* Send data to a phone without retransmit nor buffering */
905 static void send_raw_client(int size, const unsigned char *data, struct sockaddr_in *addr_to,
906 const struct sockaddr_in *addr_ourip)
907 {
908 #ifdef HAVE_PKTINFO
909 struct iovec msg_iov;
910 struct msghdr msg;
911 char buffer[CMSG_SPACE(sizeof(struct in_pktinfo))];
912 struct cmsghdr *ip_msg = (struct cmsghdr *) buffer;
913 struct in_pktinfo *pki = (struct in_pktinfo *) CMSG_DATA(ip_msg);
914
915 /* cast this to a non-const pointer, since the sendmsg() API
916 * does not provide read-only and write-only flavors of the
917 * structures used for its arguments, but in this case we know
918 * the data will not be modified
919 */
920 msg_iov.iov_base = (char *) data;
921 msg_iov.iov_len = size;
922
923 msg.msg_name = addr_to; /* optional address */
924 msg.msg_namelen = sizeof(struct sockaddr_in); /* size of address */
925 msg.msg_iov = &msg_iov; /* scatter/gather array */
926 msg.msg_iovlen = 1; /* # elements in msg_iov */
927 msg.msg_control = ip_msg; /* ancillary data */
928 msg.msg_controllen = sizeof(buffer); /* ancillary data buffer len */
929 msg.msg_flags = 0; /* flags on received message */
930
931 ip_msg->cmsg_len = CMSG_LEN(sizeof(*pki));
932 ip_msg->cmsg_level = IPPROTO_IP;
933 ip_msg->cmsg_type = IP_PKTINFO;
934 pki->ipi_ifindex = 0; /* Interface index, 0 = use interface specified in routing table */
935 pki->ipi_spec_dst.s_addr = addr_ourip->sin_addr.s_addr; /* Local address */
936 /* pki->ipi_addr = ; Header Destination address - ignored by kernel */
937
938 #ifdef DUMP_PACKET
939 if (unistimdebug) {
940 int tmp;
941 ast_verb(0, "\n**> From %s sending %d bytes to %s ***\n",
942 ast_inet_ntoa(addr_ourip->sin_addr), (int) size,
943 ast_inet_ntoa(addr_to->sin_addr));
944 for (tmp = 0; tmp < size; tmp++)
945 ast_verb(0, "%02hhx ", data[tmp]);
946 ast_verb(0, "\n******************************************\n");
947
948 }
949 #endif
950
951 if (sendmsg(unistimsock, &msg, 0) == -1) {
952 display_last_error("Error sending data");
953 }
954 #else
955 if (sendto(unistimsock, data, size, 0, (struct sockaddr *) addr_to, sizeof(*addr_to))
956 == -1)
957 display_last_error("Error sending data");
958 #endif
959 }
960
961 static void send_client(int size, const unsigned char *data, struct unistimsession *pte)
962 {
963 unsigned int tick;
964 int buf_pos;
965 unsigned short seq = ntohs(++pte->seq_server);
966
967 ast_mutex_lock(&pte->lock);
968 buf_pos = pte->last_buf_available;
969
970 if (buf_pos >= MAX_BUF_NUMBER) {
971 ast_log(LOG_WARNING, "Error : send queue overflow\n");
972 ast_mutex_unlock(&pte->lock);
973 return;
974 }
975 memcpy((void *)data + sizeof(unsigned short), (void *)&seq, sizeof(unsigned short));
976 pte->wsabufsend[buf_pos].len = size;
977 memcpy(pte->wsabufsend[buf_pos].buf, data, size);
978
979 tick = get_tick_count();
980 pte->timeout = tick + RETRANSMIT_TIMER;
981
982 /*#ifdef DUMP_PACKET */
983 if (unistimdebug) {
984 ast_verb(0, "Sending data with seq #0x%04x Using slot #%d :\n", (unsigned)pte->seq_server, buf_pos);
985 }
986 /*#endif */
987 send_raw_client(pte->wsabufsend[buf_pos].len, pte->wsabufsend[buf_pos].buf, &(pte->sin),
988 &(pte->sout));
989 pte->last_buf_available++;
990 ast_mutex_unlock(&pte->lock);
991 }
992
993 static void send_ping(struct unistimsession *pte)
994 {
995 BUFFSEND;
996 if (unistimdebug) {
997 ast_verb(0, "Sending ping\n");
998 }
999 pte->tick_next_ping = get_tick_count() + unistim_keepalive;
1000 memcpy(buffsend + SIZE_HEADER, packet_send_ping, sizeof(packet_send_ping));
1001 send_client(SIZE_HEADER + sizeof(packet_send_ping), buffsend, pte);
1002 }
1003
1004 static int get_to_address(int fd, struct sockaddr_in *toAddr)
1005 {
1006 #ifdef HAVE_PKTINFO
1007 int err;
1008 char cmbuf[0x100];
1009 struct cmsghdr *cmsg;
1010 struct sockaddr_in peeraddr;
1011 struct in_addr addr;
1012 struct msghdr mh = {
1013 .msg_name = &peeraddr,
1014 .msg_namelen = sizeof(peeraddr),
1015 .msg_control = cmbuf,
1016 .msg_controllen = sizeof(cmbuf),
1017 };
1018 memset(&addr, 0, sizeof(addr));
1019 /* Get info about the incoming packet */
1020 err = recvmsg(fd, &mh, MSG_PEEK);
1021 if (err == -1) {
1022 ast_log(LOG_WARNING, "recvmsg returned an error: %s\n", strerror(errno));
1023 return err;
1024 }
1025 for(cmsg = CMSG_FIRSTHDR(&mh);
1026 cmsg != NULL;
1027 cmsg = CMSG_NXTHDR(&mh, cmsg))
1028 {
1029 if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) {
1030 struct in_pktinfo *pkt = (struct in_pktinfo*)CMSG_DATA(cmsg);
1031 addr = pkt->ipi_addr;
1032 if (unistimdebug) {
1033 ast_verb(0, "message received on address %s\n", ast_inet_ntoa(addr));
1034 }
1035 }
1036 }
1037 memcpy(&toAddr->sin_addr, &addr, sizeof(struct in_addr));
1038 return err;
1039 #else
1040 memcpy(toAddr, &public_ip, sizeof(*toAddr));
1041 return 0;
1042 #endif
1043 }
1044
1045
1046 /* Allocate memory & initialize structures for a new phone */
1047 /* addr_from : ip address of the phone */
1048 static struct unistimsession *create_client(const struct sockaddr_in *addr_from)
1049 {
1050 int tmp;
1051 struct unistimsession *s;
1052
1053 if (!(s = ast_calloc(1, sizeof(*s))))
1054 return NULL;
1055
1056 memcpy(&s->sin, addr_from, sizeof(struct sockaddr_in));
1057 if (get_to_address(unistimsock, &s->sout) < 0) {
1058 ast_free(s);
1059 return NULL;
1060 }
1061 s->sout.sin_family = AF_INET;
1062 if (unistimdebug) {
1063 ast_verb(0, "Creating a new entry for the phone from %s received via server ip %s\n",
1064 ast_inet_ntoa(addr_from->sin_addr), ast_inet_ntoa(s->sout.sin_addr));
1065 }
1066 ast_mutex_init(&s->lock);
1067 ast_mutex_lock(&sessionlock);
1068 s->next = sessions;
1069 sessions = s;
1070
1071 s->timeout = get_tick_count() + RETRANSMIT_TIMER;
1072 s->state = STATE_INIT;
1073 s->tick_next_ping = get_tick_count() + unistim_keepalive;
1074 /* Initialize struct wsabuf */
1075 for (tmp = 0; tmp < MAX_BUF_NUMBER; tmp++) {
1076 s->wsabufsend[tmp].buf = s->buf[tmp];
1077 }
1078 ast_mutex_unlock(&sessionlock);
1079 return s;
1080 }
1081
1082 static void send_end_call(struct unistimsession *pte)
1083 {
1084 BUFFSEND;
1085 if (unistimdebug) {
1086 ast_verb(0, "Sending end call\n");
1087 }
1088 memcpy(buffsend + SIZE_HEADER, packet_send_end_call, sizeof(packet_send_end_call));
1089 send_client(SIZE_HEADER + sizeof(packet_send_end_call), buffsend, pte);
1090 }
1091
1092 static void set_ping_timer(struct unistimsession *pte)
1093 {
1094 unsigned int tick = 0; /* XXX what is this for, anyways */
1095
1096 pte->timeout = pte->tick_next_ping;
1097 DEBUG_TIMER("tick = %u next ping at %u tick\n", tick, pte->timeout);
1098 return;
1099 }
1100
1101 /* Checking if our send queue is empty,
1102 * if true, setting up a timer for keepalive */
1103 static void check_send_queue(struct unistimsession *pte)
1104 {
1105 /* Check if our send queue contained only one element */
1106 if (pte->last_buf_available == 1) {
1107 if (unistimdebug) {
1108 ast_verb(0, "Our single packet was ACKed.\n");
1109 }
1110 pte->last_buf_available--;
1111 set_ping_timer(pte);
1112 return;
1113 }
1114 /* Check if this ACK catch up our latest packet */
1115 else if (pte->last_seq_ack + 1 == pte->seq_server + 1) {
1116 if (unistimdebug) {
1117 ast_verb(0, "Our send queue is completely ACKed.\n");
1118 }
1119 pte->last_buf_available = 0; /* Purge the send queue */
1120 set_ping_timer(pte);
1121 return;
1122 }
1123 if (unistimdebug) {
1124 ast_verb(0, "We still have packets in our send queue\n");
1125 }
1126 return;
1127 }
1128
1129 static void send_start_timer(struct unistimsession *pte)
1130 {
1131 BUFFSEND;
1132 if (unistimdebug) {
1133 ast_verb(0, "Sending start timer\n");
1134 }
1135 memcpy(buffsend + SIZE_HEADER, packet_send_start_timer, sizeof(packet_send_start_timer));
1136 send_client(SIZE_HEADER + sizeof(packet_send_start_timer), buffsend, pte);
1137 }
1138
1139 static void send_stop_timer(struct unistimsession *pte)
1140 {
1141 BUFFSEND;
1142 if (unistimdebug) {
1143 ast_verb(0, "Sending stop timer\n");
1144 }
1145 memcpy(buffsend + SIZE_HEADER, packet_send_stop_timer, sizeof(packet_send_stop_timer));
1146 send_client(SIZE_HEADER + sizeof(packet_send_stop_timer), buffsend, pte);
1147 }
1148
1149 static void send_icon(unsigned char pos, unsigned char status, struct unistimsession *pte)
1150 {
1151 BUFFSEND;
1152 if (unistimdebug) {
1153 ast_verb(0, "Sending icon pos %d with status 0x%02hhx\n", pos, status);
1154 }
1155 memcpy(buffsend + SIZE_HEADER, packet_send_icon, sizeof(packet_send_icon));
1156 buffsend[9] = pos;
1157 buffsend[10] = status;
1158 send_client(SIZE_HEADER + sizeof(packet_send_icon), buffsend, pte);
1159 }
1160
1161 static void send_expansion_next(struct unistimsession *pte)
1162 {
1163 BUFFSEND;
1164 memcpy(buffsend + SIZE_HEADER, packet_send_expansion_next, sizeof(packet_send_expansion_next));
1165 send_client(SIZE_HEADER + sizeof(packet_send_expansion_next), buffsend, pte);
1166 }
1167
1168
1169 static void send_expansion_icon(unsigned char pos, unsigned char status, struct unistimsession *pte)
1170 {
1171 BUFFSEND;
1172 if (unistimdebug) {
1173 ast_verb(0, "Sending expansion icon pos %d with status 0x%02hhx\n", pos, status);
1174 }
1175 memcpy(buffsend + SIZE_HEADER, packet_send_expansion_icon, sizeof(packet_send_expansion_icon));
1176 buffsend[10] = pos;
1177 buffsend[11] = status;
1178 send_client(SIZE_HEADER + sizeof(packet_send_expansion_icon), buffsend, pte);
1179 }
1180
1181 /* inverse : TEXT_INVERSE : yes, TEXT_NORMAL : no */
1182 static void send_expansion_text(unsigned char pos, struct unistimsession *pte, const char *text)
1183 {
1184 int i;
1185 BUFFSEND;
1186 if (!text) {
1187 ast_log(LOG_ERROR, "[expansion] Asked to display NULL text (pos %d)\n", pos);
1188 return;
1189 }
1190 if (unistimdebug) {
1191 ast_verb(0, "[expansion] Sending text at pos %d\n", pos);
1192 }
1193 memcpy(buffsend + SIZE_HEADER, packet_send_expansion_text, sizeof(packet_send_expansion_text));
1194 buffsend[10] = pos;
1195 i = strlen(text);
1196 if (i > TEXT_LENGTH_MAX) {
1197 i = TEXT_LENGTH_MAX;
1198 }
1199 memcpy(buffsend + 11, text, i);
1200 send_client(SIZE_HEADER + sizeof(packet_send_expansion_text), buffsend, pte);
1201 }
1202
1203 static void send_tone(struct unistimsession *pte, uint16_t tone1, uint16_t tone2)
1204 {
1205 BUFFSEND;
1206 if (!tone1) {
1207 if (unistimdebug) {
1208 ast_verb(0, "Sending Stream Based Tone Off\n");
1209 }
1210 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_off,
1211 sizeof(packet_send_stream_based_tone_off));
1212 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_off), buffsend, pte);
1213 return;
1214 }
1215 /* Since most of the world use a continuous tone, it's useless
1216 if (unistimdebug)
1217 ast_verb(0, "Sending Stream Based Tone Cadence Download\n");
1218 memcpy (buffsend + SIZE_HEADER, packet_send_StreamBasedToneCad, sizeof (packet_send_StreamBasedToneCad));
1219 send_client (SIZE_HEADER + sizeof (packet_send_StreamBasedToneCad), buffsend, pte); */
1220 if (unistimdebug) {
1221 ast_verb(0, "Sending Stream Based Tone Frequency Component List Download %d %d\n", tone1, tone2);
1222 }
1223 tone1 *= 8;
1224 if (!tone2) {
1225 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_single_freq,
1226 sizeof(packet_send_stream_based_tone_single_freq));
1227 put_unaligned_uint16(&buffsend[10], htons(tone1));
1228 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_single_freq), buffsend,
1229 pte);
1230 } else {
1231 tone2 *= 8;
1232 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_dual_freq,
1233 sizeof(packet_send_stream_based_tone_dual_freq));
1234 put_unaligned_uint16(&buffsend[10], htons(tone1));
1235 put_unaligned_uint16(&buffsend[12], htons(tone2));
1236 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_dual_freq), buffsend,
1237 pte);
1238 }
1239
1240 if (unistimdebug) {
1241 ast_verb(0, "Sending Stream Based Tone On\n");
1242 }
1243 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_on,
1244 sizeof(packet_send_stream_based_tone_on));
1245 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_on), buffsend, pte);
1246 }
1247
1248 /* Positions for favorites
1249 |--------------------|
1250 | 5 2 | <-- not on screen in i2002
1251 | 4 1 |
1252 | 3 0 |
1253
1254
1255 KEM Positions
1256
1257 |--------------------|
1258 | 12 24 |
1259 | 11 23 |
1260 | 10 22 |
1261 | 9 21 |
1262 | 8 20 |
1263 | 7 19 |
1264 | 6 18 |
1265 | 5 17 |
1266 | 4 16 |
1267 | 3 15 |
1268 | 2 14 |
1269 | 1 13 |
1270
1271 */
1272
1273 /* status (icons) : 00 = nothing, 2x/3x = see parser.h, 4x/5x = blink fast, 6x/7x = blink slow */
1274 static void
1275 send_favorite(unsigned char pos, unsigned char status, struct unistimsession *pte,
1276 const char *text)
1277 {
1278 BUFFSEND;
1279 int i;
1280
1281 if (unistimdebug) {
1282 ast_verb(0, "Sending favorite pos %d with status 0x%02hhx\n", pos, status);
1283 }
1284 memcpy(buffsend + SIZE_HEADER, packet_send_favorite, sizeof(packet_send_favorite));
1285 buffsend[10] = pos;
1286 buffsend[24] = pos;
1287 buffsend[25] = status;
1288 i = strlen(ustmtext(text, pte));
1289 if (i > FAV_MAX_LENGTH) {
1290 i = FAV_MAX_LENGTH;
1291 }
1292 memcpy(buffsend + FAV_MAX_LENGTH + 1, ustmtext(text, pte), i);
1293 send_client(SIZE_HEADER + sizeof(packet_send_favorite), buffsend, pte);
1294 }
1295
1296 static void send_favorite_short(unsigned char pos, unsigned char status, struct unistimsession *pte) {
1297 send_favorite(pos, status, pte, pte->device->softkeylabel[pos]);
1298 return;
1299 }
1300
1301 static void send_favorite_selected(unsigned char status, struct unistimsession *pte) {
1302 if (pte->device->selected != -1) {
1303 send_favorite(pte->device->selected, status, pte, pte->device->softkeylabel[pte->device->selected]);
1304 }
1305 return;
1306 }
1307
1308 static void send_expansion_short(unsigned char pos, unsigned char status, struct unistimsession *pte) {
1309 send_expansion_icon(pos, status, pte);
1310 send_expansion_text(pos, pte, ustmtext(pte->device->expsoftkeylabel[pos], pte));
1311 send_expansion_next(pte);
1312 return;
1313 }
1314
1315 static int soft_key_visible(struct unistim_device* d, unsigned char num)
1316 {
1317 if(d->height == 1 && num % 3 == 2) {
1318 return 0;
1319 }
1320 return 1;
1321 }
1322
1323 static void refresh_all_favorite(struct unistimsession *pte)
1324 {
1325 unsigned char i = 0;
1326 char data[256];
1327 struct unistim_line *line;
1328 line = AST_LIST_FIRST(&pte->device->lines);
1329
1330 if (unistimdebug) {
1331 ast_verb(0, "Refreshing all favorite\n");
1332 }
1333 for (i = 0; i < FAVNUM; i++) {
1334 unsigned char status = pte->device->softkeyicon[i];
1335
1336 if (!soft_key_visible(pte->device, i)) {
1337 continue;
1338 }
1339 if (!strcasecmp(pte->device->softkeylabel[i], "DND") && line) {
1340 if (!ast_db_get("DND", line->name, data, sizeof(data))) {
1341 status = FAV_ICON_SPEAKER_ONHOOK_WHITE;
1342 }
1343 }
1344
1345 send_favorite_short(i, status, pte);
1346 }
1347 if (pte->device->hasexp) {
1348 for (i = 0; i < EXPNUM; i++) {
1349 send_expansion_short(i, FAV_ICON_NONE, pte);
1350 }
1351 }
1352 }
1353
1354 static int is_key_favorite(struct unistim_device *d, int fav)
1355 {
1356 if ((fav < 0) || (fav >= FAVNUM)) {
1357 return 0;
1358 }
1359 if (d->sline[fav]) {
1360 return 0;
1361 }
1362 if (d->softkeynumber[fav][0] == '\0') {
1363 return 0;
1364 }
1365 return 1;
1366 }
1367
1368 static int is_key_line(struct unistim_device *d, int fav)
1369 {
1370 if ((fav < 0) || (fav >= FAVNUM)) {
1371 return 0;
1372 }
1373 if (!d->sline[fav]) {
1374 return 0;
1375 }
1376 if (is_key_favorite(d, fav)) {
1377 return 0;
1378 }
1379 return 1;
1380 }
1381
1382 static int get_active_softkey(struct unistimsession *pte)
1383 {
1384 return pte->device->selected;
1385 }
1386
1387 static int get_avail_softkey(struct unistimsession *pte, const char* name)
1388 {
1389 int i;
1390
1391 if (!is_key_line(pte->device, pte->device->selected)) {
1392 pte->device->selected = -1;
1393 }
1394 for (i = 0; i < FAVNUM; i++) {
1395 if (pte->device->selected != -1 && pte->device->selected != i) {
1396 continue;
1397 }
1398 if (!soft_key_visible(pte->device, i)) {
1399 continue;
1400 }
1401 if (pte->device->ssub[i]) {
1402 continue;
1403 }
1404 if (is_key_line(pte->device, i)) {
1405 if (name && strcmp(name, pte->device->sline[i]->name)) {
1406 continue;
1407 }
1408 if (unistimdebug) {
1409 ast_verb(0, "Found softkey %d for device %s\n", i, name);
1410 }
1411 return i;
1412 }
1413 }
1414 return -1;
1415 }
1416
1417
1418 /* Change the status for this phone (pte) and update for each phones where pte is bookmarked
1419 * use FAV_ICON_*_BLACK constant in status parameters */
1420 static void change_favorite_icon(struct unistimsession *pte, unsigned char status)
1421 {
1422 struct unistim_device *d = devices;
1423 int i;
1424 /* Update the current phone line softkey icon */
1425 if (pte->state != STATE_CLEANING) {
1426 int softkeylinepos = get_active_softkey(pte);
1427 if (softkeylinepos != -1) {
1428 send_favorite_short(softkeylinepos, status, pte);
1429 }
1430 }
1431 /* Notify other phones if we're in their bookmark */
1432 while (d) {
1433 for (i = 0; i < FAVNUM; i++) {
1434 if (d->sp[i] == pte->device) { /* It's us ? */
1435 if (d->softkeyicon[i] != status) { /* Avoid resending the same icon */
1436 d->softkeyicon[i] = status;
1437 if (d->session) {
1438 send_favorite(i, status + 1, d->session, d->softkeylabel[i]);
1439 }
1440 }
1441 }
1442 }
1443 d = d->next;
1444 }
1445 }
1446
1447 static int register_extension(const struct unistimsession *pte)
1448 {
1449 struct unistim_line *line;
1450 line = AST_LIST_FIRST(&pte->device->lines);
1451 if (unistimdebug) {
1452 ast_verb(0, "Trying to register extension '%s' into context '%s' to %s\n",
1453 pte->device->extension_number, pte->device->context,
1454 line->fullname);
1455 }
1456 return ast_add_extension(pte->device->context, 0,
1457 pte->device->extension_number, 1, NULL, NULL, "Dial",
1458 line->fullname, 0, "Unistim");
1459 }
1460
1461 static int unregister_extension(const struct unistimsession *pte)
1462 {
1463 if (unistimdebug) {
1464 ast_verb(0, "Trying to unregister extension '%s' context '%s'\n",
1465 pte->device->extension_number, pte->device->context);
1466 }
1467 return ast_context_remove_extension(pte->device->context,
1468 pte->device->extension_number, 1, "Unistim");
1469 }
1470
1471 /* Free memory allocated for a phone */
1472 static void close_client(struct unistimsession *s)
1473 {
1474 struct unistim_subchannel *sub = NULL;
1475 struct unistimsession *cur, *prev = NULL;
1476 ast_mutex_lock(&sessionlock);
1477 cur = sessions;
1478 /* Looking for the session in the linked chain */
1479 while (cur) {
1480 if (cur == s) {
1481 break;
1482 }
1483 prev = cur;
1484 cur = cur->next;
1485 }
1486 if (cur) { /* Session found ? */
1487 if (cur->device) { /* This session was registered ? */
1488 s->state = STATE_CLEANING;
1489 if (unistimdebug) {
1490 ast_verb(0, "close_client session %p device %p\n", s, s->device);
1491 }
1492 change_favorite_icon(s, FAV_ICON_NONE);
1493 ast_mutex_lock(&s->device->lock);
1494 AST_LIST_LOCK(&s->device->subs);
1495 AST_LIST_TRAVERSE_SAFE_BEGIN(&s->device->subs, sub, list) {
1496 if (!sub) {
1497 continue;
1498 }
1499 if (sub->owner) { /* Call in progress ? */
1500 if (unistimdebug) {
1501 ast_verb(0, "Aborting call\n");
1502 }
1503 ast_queue_hangup_with_cause(sub->owner, AST_CAUSE_NETWORK_OUT_OF_ORDER);
1504 } else {
1505 if (unistimdebug) {
1506 ast_debug(1, "Released sub %u of channel %s@%s\n", sub->subtype, sub->parent->name, s->device->name);
1507 }
1508 AST_LIST_REMOVE_CURRENT(list);
1509 unistim_free_sub(sub);
1510 }
1511 }
1512 AST_LIST_TRAVERSE_SAFE_END;
1513 AST_LIST_UNLOCK(&s->device->subs);
1514
1515 if (!ast_strlen_zero(s->device->extension_number)) {
1516 unregister_extension(s);
1517 }
1518 cur->device->session = NULL;
1519 ast_mutex_unlock(&s->device->lock);
1520 } else {
1521 if (unistimdebug) {
1522 ast_verb(0, "Freeing an unregistered client\n");
1523 }
1524 }
1525 if (prev) {
1526 prev->next = cur->next;
1527 } else {
1528 sessions = cur->next;
1529 }
1530 ast_mutex_destroy(&s->lock);
1531 ast_free(s);
1532 } else {
1533 ast_log(LOG_WARNING, "Trying to delete non-existent session %p?\n", s);
1534 }
1535 ast_mutex_unlock(&sessionlock);
1536 return;
1537 }
1538
1539 /* Return 1 if the session chained link was modified */
1540 static int send_retransmit(struct unistimsession *pte)
1541 {
1542 int i;
1543
1544 ast_mutex_lock(&pte->lock);
1545 if (++pte->nb_retransmit >= NB_MAX_RETRANSMIT) {
1546 if (unistimdebug) {
1547 ast_verb(0, "Too many retransmit - freeing client\n");
1548 }
1549 ast_mutex_unlock(&pte->lock);
1550 close_client(pte);
1551 return 1;
1552 }
1553 pte->timeout = get_tick_count() + RETRANSMIT_TIMER;
1554
1555 for (i = pte->last_buf_available - (pte->seq_server - pte->last_seq_ack);
1556 i < pte->last_buf_available; i++) {
1557 if (i < 0) {
1558 ast_log(LOG_WARNING,
1559 "Asked to retransmit an ACKed slot ! last_buf_available=%d, seq_server = #0x%04x last_seq_ack = #0x%04x\n",
1560 pte->last_buf_available, (unsigned)pte->seq_server, (unsigned)pte->last_seq_ack);
1561 continue;
1562 }
1563
1564 if (unistimdebug) {
1565 unsigned short *sbuf = (unsigned short *) pte->wsabufsend[i].buf;
1566 unsigned short seq;
1567
1568 seq = ntohs(sbuf[1]);
1569 ast_verb(0, "Retransmit slot #%d (seq=#0x%04x), last ack was #0x%04x\n", i,
1570 (unsigned)seq, (unsigned)pte->last_seq_ack);
1571 }
1572 send_raw_client(pte->wsabufsend[i].len, pte->wsabufsend[i].buf, &pte->sin,
1573 &pte->sout);
1574 }
1575 ast_mutex_unlock(&pte->lock);
1576 return 0;
1577 }
1578
1579 /* inverse : TEXT_INVERSE : yes, TEXT_NORMAL : no */
1580 static void send_text(unsigned char pos, unsigned char inverse, struct unistimsession *pte,
1581 const char *text)
1582 {
1583 int i;
1584 BUFFSEND;
1585 if (!text) {
1586 ast_log(LOG_ERROR, "Asked to display NULL text (pos %d, inverse flag %d)\n", pos, inverse);
1587 return;
1588 }
1589 if (pte->device && pte->device->height == 1 && pos != TEXT_LINE0) {
1590 return;
1591 }
1592 if (unistimdebug) {
1593 ast_verb(0, "Sending text at pos %d, inverse flag %d\n", pos, inverse);
1594 }
1595 memcpy(buffsend + SIZE_HEADER, packet_send_text, sizeof(packet_send_text));
1596 buffsend[10] = pos;
1597 buffsend[11] = inverse;
1598 i = strlen(text);
1599 if (i > TEXT_LENGTH_MAX) {
1600 i = TEXT_LENGTH_MAX;
1601 }
1602 memcpy(buffsend + 12, text, i);
1603 send_client(SIZE_HEADER + sizeof(packet_send_text), buffsend, pte);
1604 }
1605
1606 static void send_text_status(struct unistimsession *pte, const char *text)
1607 {
1608 BUFFSEND;
1609 int i;
1610 if (unistimdebug) {
1611 ast_verb(0, "Sending status text\n");
1612 }
1613 if (pte->device) {
1614 if (pte->device->status_method == 1) { /* For new firmware and i2050 soft phone */
1615 int n = strlen(text);
1616 /* Must send individual button separately */
1617 int j;
1618 for (i = 0, j = 0; i < 4; i++, j += 7) {
1619 int pos = 0x08 + (i * 0x20);
1620 memcpy(buffsend + SIZE_HEADER, packet_send_status2,
1621 sizeof(packet_send_status2));
1622
1623 buffsend[9] = pos;
1624 memcpy(buffsend + 10, (j < n) ? (text + j) : " ", 7);
1625 send_client(SIZE_HEADER + sizeof(packet_send_status2), buffsend, pte);
1626 }
1627 return;
1628 }
1629 }
1630
1631 memcpy(buffsend + SIZE_HEADER, packet_send_status, sizeof(packet_send_status));
1632 i = strlen(text);
1633 if (i > STATUS_LENGTH_MAX) {
1634 i = STATUS_LENGTH_MAX;
1635 }
1636 memcpy(buffsend + 10, text, i);
1637 send_client(SIZE_HEADER + sizeof(packet_send_status), buffsend, pte);
1638
1639 }
1640
1641 static void send_led_update(struct unistimsession *pte, unsigned char led)
1642 {
1643 BUFFSEND;
1644 if (unistimdebug) {
1645 ast_verb(0, "Sending led_update (%x)\n", (unsigned)led);
1646 }
1647 memcpy(buffsend + SIZE_HEADER, packet_send_led_update, sizeof(packet_send_led_update));
1648 buffsend[9] = led;
1649 send_client(SIZE_HEADER + sizeof(packet_send_led_update), buffsend, pte);
1650 }
1651
1652 static void send_mute(struct unistimsession *pte, unsigned char mute)
1653 {
1654 /*
1655 0x00 = unmute TX, 0x01 = mute TX
1656 0x20 = unmute RX, 0x21 = mute RX
1657 */
1658 BUFFSEND;
1659 if (unistimdebug) {
1660 ast_verb(0, "Sending mute packet (%x)\n", (unsigned)mute);
1661 }
1662 memcpy(buffsend + SIZE_HEADER, packet_send_mute, sizeof(packet_send_mute));
1663 buffsend[9] = mute;
1664 send_client(SIZE_HEADER + sizeof(packet_send_mute), buffsend, pte);
1665 }
1666
1667
1668 /* output = OUTPUT_HANDSET, OUTPUT_HEADPHONE or OUTPUT_SPEAKER
1669 * volume = VOLUME_LOW, VOLUME_NORMAL, VOLUME_INSANELY_LOUD
1670 * mute = MUTE_OFF, MUTE_ON */
1671 static void
1672 send_select_output(struct unistimsession *pte, unsigned char output, unsigned char volume,
1673 unsigned char mute)
1674 {
1675 BUFFSEND;
1676 int mute_icon = -1;
1677 if (unistimdebug) {
1678 ast_verb(0, "Sending select output packet output=%x volume=%x mute=%x\n",
1679 (unsigned)output, (unsigned)volume, (unsigned)mute);
1680 }
1681 memcpy(buffsend + SIZE_HEADER, packet_send_select_output,
1682 sizeof(packet_send_select_output));
1683 buffsend[9] = output;
1684 if (output == OUTPUT_SPEAKER && volume == VOLUME_LOW) {
1685 volume = VOLUME_LOW_SPEAKER;
1686 }
1687 buffsend[10] = volume;
1688 if (mute == MUTE_ON_DISCRET) {
1689 buffsend[11] = MUTE_ON;
1690 } else {
1691 buffsend[11] = mute;
1692 }
1693 send_client(SIZE_HEADER + sizeof(packet_send_select_output), buffsend, pte);
1694 if (output == OUTPUT_HANDSET) {
1695 mute_icon = (mute == MUTE_ON) ? FAV_ICON_ONHOLD_BLACK : FAV_ICON_OFFHOOK_BLACK;
1696 send_led_update(pte, LED_SPEAKER_OFF);
1697 send_led_update(pte, LED_HEADPHONE_OFF);
1698 } else if (output == OUTPUT_HEADPHONE) {
1699 mute_icon = (mute == MUTE_ON)? FAV_ICON_HEADPHONES_ONHOLD : FAV_ICON_HEADPHONES;
1700 send_led_update(pte, LED_SPEAKER_OFF);
1701 send_led_update(pte, LED_HEADPHONE_ON);
1702 } else if (output == OUTPUT_SPEAKER) {
1703 send_led_update(pte, LED_SPEAKER_ON);
1704 send_led_update(pte, LED_HEADPHONE_OFF);
1705 if (pte->device->receiver_state == STATE_OFFHOOK) {
1706 mute_icon = (mute == MUTE_ON)? FAV_ICON_SPEAKER_ONHOLD_BLACK : FAV_ICON_SPEAKER_ONHOOK_BLACK;
1707 } else {
1708 mute_icon = (mute == MUTE_ON)? FAV_ICON_SPEAKER_ONHOLD_BLACK : FAV_ICON_SPEAKER_OFFHOOK_BLACK;
1709 }
1710 } else {
1711 ast_log(LOG_WARNING, "Invalid output (%d)\n", output);
1712 }
1713 if (mute_icon != -1) {
1714 change_favorite_icon(pte, mute_icon);
1715 }
1716 if (output != pte->device->output) {
1717 pte->device->previous_output = pte->device->output;
1718 }
1719 pte->device->output = output;
1720 }
1721 static void send_ring(struct unistimsession *pte, signed char volume, signed char style)
1722 {
1723 BUFFSEND;
1724 if (unistimdebug) {
1725 ast_verb(0, "Sending ring packet\n");
1726 }
1727 memcpy(buffsend + SIZE_HEADER, packet_send_ring, sizeof(packet_send_ring));
1728 buffsend[24] = style + 0x10;
1729 buffsend[29] = volume * 0x10;
1730 send_client(SIZE_HEADER + sizeof(packet_send_ring), buffsend, pte);
1731 }
1732
1733 static void send_no_ring(struct unistimsession *pte)
1734 {
1735 BUFFSEND;
1736 if (unistimdebug) {
1737 ast_verb(0, "Sending no ring packet\n");
1738 }
1739 memcpy(buffsend + SIZE_HEADER, packet_send_no_ring, sizeof(packet_send_no_ring));
1740 send_client(SIZE_HEADER + sizeof(packet_send_no_ring), buffsend, pte);
1741 }
1742
1743 static void send_texttitle(struct unistimsession *pte, const char *text)
1744 {
1745 BUFFSEND;
1746 int i;
1747 if (unistimdebug) {
1748 ast_verb(0, "Sending title text\n");
1749 }
1750 memcpy(buffsend + SIZE_HEADER, packet_send_title, sizeof(packet_send_title));
1751 i = strlen(text);
1752 if (i > 12) {
1753 i = 12;
1754 }
1755 memcpy(buffsend + 10, text, i);
1756 send_client(SIZE_HEADER + sizeof(packet_send_title), buffsend, pte);
1757 }
1758
1759 static void send_idle_clock(struct unistimsession *pte)
1760 {
1761 send_text(TEXT_LINE0, TEXT_NORMAL, pte, "");
1762 }
1763
1764 static void send_month_labels(struct unistimsession *pte, int month)
1765 {
1766 BUFFSEND;
1767 char month_name[MONTH_LABEL_SIZE + 1];
1768 int i = 0;
1769 if (unistimdebug) {
1770 ast_verb(0, "Sending Month Labels\n");
1771 }
1772 month_name[MONTH_LABEL_SIZE] = '\0';
1773 memcpy(buffsend + SIZE_HEADER, packet_send_monthlabels_download, sizeof(packet_send_monthlabels_download));
1774 while (i < 2) {
1775 memcpy(month_name, &monthlabels[month * MONTH_LABEL_SIZE], MONTH_LABEL_SIZE);
1776 memcpy(buffsend + SIZE_HEADER + 3 + i*MONTH_LABEL_SIZE, ustmtext(month_name, pte), MONTH_LABEL_SIZE);
1777 ast_log(LOG_WARNING,"%s\n", month_name);
1778 ast_log(LOG_WARNING,"%s\n", ustmtext(month_name, pte));
1779 month = (month + 1)%12;
1780 i++;
1781 }
1782 send_client(SIZE_HEADER + sizeof(packet_send_monthlabels_download), buffsend, pte);
1783 }
1784
1785
1786 static void send_date_time(struct unistimsession *pte)
1787 {
1788 BUFFSEND;
1789 struct timeval now = ast_tvnow();
1790 struct ast_tm atm = { 0, };
1791
1792 if (unistimdebug) {
1793 ast_verb(0, "Sending Time & Date\n");
1794 }
1795 memcpy(buffsend + SIZE_HEADER, packet_send_date_time, sizeof(packet_send_date_time));
1796 ast_localtime(&now, &atm, NULL);
1797 buffsend[10] = (unsigned char) atm.tm_mon + 1;
1798 buffsend[11] = (unsigned char) atm.tm_mday;
1799 buffsend[12] = (unsigned char) atm.tm_hour;
1800 buffsend[13] = (unsigned char) atm.tm_min;
1801 send_client(SIZE_HEADER + sizeof(packet_send_date_time), buffsend, pte);
1802 send_month_labels(pte, atm.tm_mon);
1803 }
1804
1805 static void send_date_time2(struct unistimsession *pte)
1806 {
1807 BUFFSEND;
1808 struct timeval now = ast_tvnow();
1809 struct ast_tm atm = { 0, };
1810
1811 if (unistimdebug) {
1812 ast_verb(0, "Sending Time & Date #2\n");
1813 }
1814 memcpy(buffsend + SIZE_HEADER, packet_send_date_time2, sizeof(packet_send_date_time2));
1815 ast_localtime(&now, &atm, NULL);
1816 if (pte->device) {
1817 buffsend[9] = pte->device->datetimeformat;
1818 } else {
1819 buffsend[9] = 61;
1820 }
1821 buffsend[14] = (unsigned char) atm.tm_mon + 1;
1822 buffsend[15] = (unsigned char) atm.tm_mday;
1823 buffsend[16] = (unsigned char) atm.tm_hour;
1824 buffsend[17] = (unsigned char) atm.tm_min;
1825 send_client(SIZE_HEADER + sizeof(packet_send_date_time2), buffsend, pte);
1826 }
1827
1828 static void send_date_time3(struct unistimsession *pte)
1829 {
1830 BUFFSEND;
1831 struct timeval now = ast_tvnow();
1832 struct ast_tm atm = { 0, };
1833
1834 if (unistimdebug) {
1835 ast_verb(0, "Sending Time & Date #3\n");
1836 }
1837 memcpy(buffsend + SIZE_HEADER, packet_send_date_time3, sizeof(packet_send_date_time3));
1838 ast_localtime(&now, &atm, NULL);
1839 buffsend[10] = (unsigned char) atm.tm_mon + 1;
1840 buffsend[11] = (unsigned char) atm.tm_mday;
1841 buffsend[12] = (unsigned char) atm.tm_hour;
1842 buffsend[13] = (unsigned char) atm.tm_min;
1843 send_client(SIZE_HEADER + sizeof(packet_send_date_time3), buffsend, pte);
1844 }
1845
1846 static void send_blink_cursor(struct unistimsession *pte)
1847 {
1848 BUFFSEND;
1849 if (unistimdebug) {
1850 ast_verb(0, "Sending set blink\n");
1851 }
1852 memcpy(buffsend + SIZE_HEADER, packet_send_blink_cursor, sizeof(packet_send_blink_cursor));
1853 send_client(SIZE_HEADER + sizeof(packet_send_blink_cursor), buffsend, pte);
1854 return;
1855 }
1856
1857 /* pos : 0xab (a=0/2/4 = line ; b = row) */
1858 static void send_cursor_pos(struct unistimsession *pte, unsigned char pos)
1859 {
1860 BUFFSEND;
1861 if (unistimdebug) {
1862 ast_verb(0, "Sending set cursor position\n");
1863 }
1864 memcpy(buffsend + SIZE_HEADER, packet_send_set_pos_cursor,
1865 sizeof(packet_send_set_pos_cursor));
1866 buffsend[11] = pos;
1867 send_client(SIZE_HEADER + sizeof(packet_send_set_pos_cursor), buffsend, pte);
1868 return;
1869 }
1870
1871 static void send_charset_update(struct unistimsession *pte, int charset)
1872 {
1873 const unsigned char* packet_send_charset;
1874 int packet_size;
1875 BUFFSEND;
1876 if (unistimdebug) {
1877 ast_verb(0, "Sending set default charset\n");
1878 }
1879 if (charset == LANG_DEFAULT) {
1880 charset = options_languages[find_language(pte->device->language)].encoding;
1881 }
1882 switch (charset) {
1883 case ISO_8859_2:
1884 packet_send_charset = packet_send_charset_iso_8859_2;
1885 packet_size = sizeof(packet_send_charset_iso_8859_2);
1886 break;
1887 case ISO_8859_4:
1888 packet_send_charset = packet_send_charset_iso_8859_4;
1889 packet_size = sizeof(packet_send_charset_iso_8859_4);
1890 break;
1891 case ISO_8859_5:
1892 packet_send_charset = packet_send_charset_iso_8859_5;
1893 packet_size = sizeof(packet_send_charset_iso_8859_5);
1894 break;
1895 case ISO_2022_JP:
1896 packet_send_charset = packet_send_charset_iso_2022_jp;
1897 packet_size = sizeof(packet_send_charset_iso_2022_jp);
1898 break;
1899 case ISO_8859_1:
1900 default:
1901 packet_send_charset = packet_send_charset_iso_8859_1;
1902 packet_size = sizeof(packet_send_charset_iso_8859_1);
1903 }
1904 memcpy(buffsend + SIZE_HEADER, packet_send_charset, packet_size);
1905 send_client(SIZE_HEADER + packet_size, buffsend, pte);
1906 return;
1907 }
1908
1909 static void rcv_resume_connection_with_server(struct unistimsession *pte)
1910 {
1911 BUFFSEND;
1912 if (unistimdebug) {
1913 ast_verb(0, "ResumeConnectionWithServer received\n");
1914 ast_verb(0, "Sending packet_send_query_mac_address\n");
1915 }
1916 memcpy(buffsend + SIZE_HEADER, packet_send_query_mac_address,
1917 sizeof(packet_send_query_mac_address));
1918 send_client(SIZE_HEADER + sizeof(packet_send_query_mac_address), buffsend, pte);
1919 return;
1920 }
1921
1922 static int unistim_register(struct unistimsession *s)
1923 {
1924 struct unistim_device *d;
1925
1926 ast_mutex_lock(&devicelock);
1927 d = devices;
1928 while (d) {
1929 if (!strcasecmp(s->macaddr, d->id)) {
1930 /* XXX Deal with IP authentication */
1931 s->device = d;
1932 d->session = s;
1933 d->codec_number = DEFAULT_CODEC;
1934 d->missed_call = 0;
1935 d->receiver_state = STATE_ONHOOK;
1936 break;
1937 }
1938 d = d->next;
1939 }
1940 ast_mutex_unlock(&devicelock);
1941
1942 if (!d) {
1943 return 0;
1944 }
1945
1946 return 1;
1947 }
1948
1949 static void unistim_line_copy(struct unistim_line *dst, struct unistim_line *src)
1950 {
1951 struct ast_format_cap *tmp = src->cap;
1952 memcpy(dst, src, sizeof(*dst)); /* this over writes the cap ptr, so we have to reset it */
1953 src->cap = tmp;
1954 ast_format_cap_append_from_cap(src->cap, dst->cap, AST_MEDIA_TYPE_UNKNOWN);
1955 }
1956
1957 static struct unistim_line *unistim_line_destroy(struct unistim_line *l)
1958 {
1959 if (!l) {
1960 return NULL;
1961 }
1962 ao2_ref(l->cap, -1);
1963 ast_free(l);
1964 return NULL;
1965 }
1966
1967 static struct unistim_line *unistim_line_alloc(void)
1968 {
1969 struct unistim_line *l;
1970 if (!(l = ast_calloc(1, sizeof(*l)))) {
1971 return NULL;
1972 }
1973
1974 if (!(l->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1975 ast_free(l);
1976 return NULL;
1977 }
1978 return l;
1979 }
1980
1981 static int unistim_free_sub(struct unistim_subchannel *sub) {
1982 if (unistimdebug) {
1983 ast_debug(1, "Released sub %u of channel %s@%s\n", sub->subtype, sub->parent->name, sub->parent->parent->name);
1984 }
1985 ast_mutex_destroy(&sub->lock);
1986 ast_free(sub);
1987 return 0;
1988 }
1989
1990 static struct unistim_subchannel *unistim_alloc_sub(struct unistim_device *d, int x)
1991 {
1992 struct unistim_subchannel *sub;
1993 if (!(sub = ast_calloc(1, sizeof(*sub)))) {
1994 return NULL;
1995 }
1996
1997 if (unistimdebug) {
1998 ast_verb(3, "Allocating UNISTIM subchannel #%d on %s ptr=%p\n", x, d->name, sub);
1999 }
2000 sub->ss_thread = AST_PTHREADT_NULL;
2001 sub->subtype = x;
2002 AST_LIST_LOCK(&d->subs);
2003 AST_LIST_INSERT_TAIL(&d->subs, sub, list);
2004 AST_LIST_UNLOCK(&d->subs);
2005 ast_mutex_init(&sub->lock);
2006 return sub;
2007 }
2008
2009 static int unistim_unalloc_sub(struct unistim_device *d, struct unistim_subchannel *sub)
2010 {
2011 struct unistim_subchannel *s;
2012
2013 AST_LIST_LOCK(&d->subs);
2014 AST_LIST_TRAVERSE_SAFE_BEGIN(&d->subs, s, list) {
2015 if (!s) {
2016 continue;
2017 }
2018 if (s != sub) {
2019 continue;
2020 }
2021 AST_LIST_REMOVE_CURRENT(list);
2022 unistim_free_sub(sub);
2023 }
2024 AST_LIST_TRAVERSE_SAFE_END;
2025 AST_LIST_UNLOCK(&d->subs);
2026 return 0;
2027 }
2028
2029 static const char *subtype_tostr(const int type)
2030 {
2031 switch (type) {
2032 case SUB_REAL:
2033 return "REAL";
2034 case SUB_RING:
2035 return "RINGING";
2036 case SUB_THREEWAY:
2037 return "THREEWAY";
2038 }
2039 return "UNKNOWN";
2040 }
2041
2042 static const char *ptestate_tostr(const int type)
2043 {
2044 switch (type) {
2045 case STATE_INIT:
2046 return "INIT";
2047 case STATE_AUTHDENY:
2048 return "AUTHDENY";
2049 case STATE_MAINPAGE:
2050 return "MAINPAGE";
2051 case STATE_EXTENSION:
2052 return "EXTENSION";
2053 case STATE_DIALPAGE:
2054 return "DIALPAGE";
2055 case STATE_RINGING:
2056 return "RINGING";
2057 case STATE_CALL:
2058 return "CALL";
2059 case STATE_SELECTOPTION:
2060 return "SELECTOPTION";
2061 case STATE_SELECTCODEC:
2062 return "SELECTCODEC";
2063 case STATE_SELECTLANGUAGE:
2064 return "SELECTLANGUAGE";
2065 case STATE_CLEANING:
2066 return "CLEARING";
2067 case STATE_HISTORY:
2068 return "HISTORY";
2069 }
2070 return "UNKNOWN";
2071 }
2072
2073 static void rcv_mac_addr(struct unistimsession *pte, const unsigned char *buf)
2074 {
2075 BUFFSEND;
2076 int tmp, i = 0;
2077 char addrmac[19];
2078 int res = 0;
2079 for (tmp = 15; tmp < 15 + SIZE_HEADER; tmp++) {
2080 sprintf(&addrmac[i], "%02hhx", buf[tmp]);
2081 i += 2;
2082 }
2083 if (unistimdebug) {
2084 ast_verb(0, "MAC Address received: %s\n", addrmac);
2085 }
2086 strcpy(pte->macaddr, addrmac);
2087 res = unistim_register(pte);
2088 if (!res) {
2089 switch (autoprovisioning) {
2090 case AUTOPROVISIONING_NO:
2091 ast_log(LOG_WARNING, "No entry found for this phone : %s\n", addrmac);
2092 pte->state = STATE_AUTHDENY;
2093 break;
2094 case AUTOPROVISIONING_YES:
2095 {
2096 struct unistim_device *d = NULL, *newd = NULL;
2097 struct unistim_line *newl = NULL, *l = NULL;
2098 if (unistimdebug) {
2099 ast_verb(0, "New phone, autoprovisioning on\n");
2100 }
2101 /* First : locate the [template] section */
2102 ast_mutex_lock(&devicelock);
2103 d = devices;
2104 while (d) {
2105 if (strcasecmp(d->name, "template")) {
2106 d = d->next;
2107 continue;
2108 }
2109 /* Found, cloning this entry */
2110 if (!(newd = ast_malloc(sizeof(*newd)))) {
2111 ast_mutex_unlock(&devicelock);
2112 return;
2113 }
2114 memcpy(newd, d, sizeof(*newd));
2115 ast_mutex_init(&newd->lock);
2116 newd->lines.first = NULL;
2117 newd->lines.last = NULL;
2118 AST_LIST_LOCK(&d->lines);
2119 AST_LIST_TRAVERSE(&d->lines, l, list) {
2120 if (!(newl = unistim_line_alloc())) {
2121 break;
2122 }
2123 unistim_line_copy(l, newl);
2124 newl->parent = newd;
2125 ast_copy_string(newl->name, l->name, sizeof(newl->name));
2126 snprintf(newl->fullname, sizeof(newl->fullname), "USTM/%s@%s",
2127 newl->name, newd->name);
2128 snprintf(l->name, sizeof(l->name), "%d", atoi(l->name) + 1);
2129
2130 AST_LIST_LOCK(&newd->lines);
2131 AST_LIST_INSERT_TAIL(&newd->lines, newl, list);
2132 AST_LIST_UNLOCK(&newd->lines);
2133 }
2134 AST_LIST_UNLOCK(&d->lines);
2135 if (!newl) {
2136 ast_free(newd);
2137 ast_mutex_unlock(&devicelock);
2138 }
2139
2140 /* Ok, now updating some fields */
2141 ast_copy_string(newd->id, addrmac, sizeof(newd->id));
2142 ast_copy_string(newd->name, addrmac, sizeof(newd->name));
2143 if (newd->extension == EXTENSION_NONE) {
2144 newd->extension = EXTENSION_ASK;
2145 }
2146
2147 newd->receiver_state = STATE_ONHOOK;
2148 newd->session = pte;
2149 newd->language[0] = '\0';
2150 newd->to_delete = -1;
2151 newd->next = NULL;
2152 pte->device = newd;
2153
2154 /* Go to the end of the linked chain */
2155 while (d->next) {
2156 d = d->next;
2157 }
2158 d->next = newd;
2159 d = newd;
2160 break;
2161 }
2162 ast_mutex_unlock(&devicelock);
2163 if (!d) {
2164 ast_log(LOG_WARNING, "No entry [template] found in unistim.conf\n");
2165 pte->state = STATE_AUTHDENY;
2166 }
2167 }
2168 break;
2169 case AUTOPROVISIONING_TN:
2170 pte->state = STATE_AUTHDENY;
2171 break;
2172 default:
2173 ast_log(LOG_WARNING, "Internal error : unknown autoprovisioning value = %u\n",
2174 autoprovisioning);
2175 }
2176 }
2177 if (pte->state != STATE_AUTHDENY) {
2178 struct unistim_line *line;
2179 struct unistim_subchannel *sub;
2180
2181 ast_verb(3, "Device '%s' successfully registered\n", pte->device->name);
2182
2183 AST_LIST_LOCK(&pte->device->subs);
2184 AST_LIST_TRAVERSE_SAFE_BEGIN(&pte->device->subs, sub, list) {
2185 if (sub) {
2186 ast_log(LOG_ERROR, "Subchannel lost sice reboot. Hanged channel may appear!\n");
2187 AST_LIST_REMOVE_CURRENT(list);
2188 ast_free(sub);
2189 }
2190 }
2191 AST_LIST_TRAVERSE_SAFE_END;
2192 AST_LIST_UNLOCK(&pte->device->subs);
2193
2194 switch (pte->device->extension) {
2195 case EXTENSION_NONE:
2196 pte->state = STATE_MAINPAGE;
2197 break;
2198 case EXTENSION_ASK:
2199 /* Checking if we already have an extension number */
2200 if (ast_strlen_zero(pte->device->extension_number)) {
2201 pte->state = STATE_EXTENSION;
2202 } else {
2203 /* Yes, because of a phone reboot. We don't ask again for the TN */
2204 if (register_extension(pte)) {
2205 pte->state = STATE_EXTENSION;
2206 } else {
2207 pte->state = STATE_MAINPAGE;
2208 }
2209 }
2210 break;
2211 case EXTENSION_LINE:
2212 line = AST_LIST_FIRST(&pte->device->lines);
2213 ast_copy_string(pte->device->extension_number, line->name,
2214 sizeof(pte->device->extension_number));
2215 if (register_extension(pte)) {
2216 pte->state = STATE_EXTENSION;
2217 } else {
2218 pte->state = STATE_MAINPAGE;
2219 }
2220 break;
2221 case EXTENSION_TN:
2222 /* If we are here, it's because of a phone reboot */
2223 pte->state = STATE_MAINPAGE;
2224 break;
2225 default:
2226 ast_log(LOG_WARNING, "Internal error, extension value unknown : %u\n",
2227 pte->device->extension);
2228 pte->state = STATE_AUTHDENY;
2229 break;
2230 }
2231 }
2232 if (pte->state == STATE_EXTENSION) {
2233 if (pte->device->extension != EXTENSION_TN) {
2234 pte->device->extension = EXTENSION_ASK;
2235 }
2236 pte->device->extension_number[0] = '\0';
2237 }
2238 if (unistimdebug) {
2239 ast_verb(0, "\nSending S1\n");
2240 }
2241 memcpy(buffsend + SIZE_HEADER, packet_send_S1, sizeof(packet_send_S1));
2242 send_client(SIZE_HEADER + sizeof(packet_send_S1), buffsend, pte);
2243
2244 if (unistimdebug) {
2245 ast_verb(0, "Sending query_basic_manager_04\n");
2246 }
2247 memcpy(buffsend + SIZE_HEADER, packet_send_query_basic_manager_04,
2248 sizeof(packet_send_query_basic_manager_04));
2249 send_client(SIZE_HEADER + sizeof(packet_send_query_basic_manager_04), buffsend, pte);
2250
2251 if (unistimdebug) {
2252 ast_verb(0, "Sending query_basic_manager_10\n");
2253 }
2254 memcpy(buffsend + SIZE_HEADER, packet_send_query_basic_manager_10,
2255 sizeof(packet_send_query_basic_manager_10));
2256 send_client(SIZE_HEADER + sizeof(packet_send_query_basic_manager_10), buffsend, pte);
2257
2258 send_date_time(pte);
2259 return;
2260 }
2261
2262 static int write_entry_history(struct unistimsession *pte, FILE * f, char c, char *line1)
2263 {
2264 if (fwrite(&c, 1, 1, f) != 1) {
2265 display_last_error("Unable to write history log header.");
2266 return -1;
2267 }
2268 if (fwrite(line1, TEXT_LENGTH_MAX, 1, f) != 1) {
2269 display_last_error("Unable to write history entry - date.");
2270 return -1;
2271 }
2272 if (fwrite(pte->device->lst_cid, TEXT_LENGTH_MAX, 1, f) != 1) {
2273 display_last_error("Unable to write history entry - callerid.");
2274 return -1;
2275 }
2276 if (fwrite(pte->device->lst_cnm, TEXT_LENGTH_MAX, 1, f) != 1) {
2277 display_last_error("Unable to write history entry - callername.");
2278 return -1;
2279 }
2280 return 0;
2281 }
2282
2283 static int write_history(struct unistimsession *pte, char way, char ismissed)
2284 {
2285 char tmp[AST_CONFIG_MAX_PATH], tmp2[AST_CONFIG_MAX_PATH];
2286 char line1[TEXT_LENGTH_MAX + 1];
2287 char count = 0, *histbuf;
2288 int size;
2289 FILE *f, *f2;
2290 struct timeval now = ast_tvnow();
2291 struct ast_tm atm = { 0, };
2292
2293 if (!pte->device) {
2294 return -1;
2295 }
2296 if (!pte->device->callhistory) {
2297 return 0;
2298 }
2299 if (strchr(pte->device->name, '/') || (pte->device->name[0] == '.')) {
2300 ast_log(LOG_WARNING, "Account code '%s' insecure for writing file\n",
2301 pte->device->name);
2302 return -1;
2303 }
2304
2305 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, USTM_LOG_DIR);
2306 if (ast_mkdir(tmp, 0770)) {
2307 ast_log(LOG_WARNING, "Unable to create directory for history\n");
2308 return -1;
2309 }
2310
2311 ast_localtime(&now, &atm, NULL);
2312 if (ismissed) {
2313 if (way == 'i') {
2314 ast_copy_string(tmp2, ustmtext("Miss", pte), sizeof(tmp2));
2315 } else {
2316 ast_copy_string(tmp2, ustmtext("Fail", pte), sizeof(tmp2));
2317 }
2318 } else {
2319 ast_copy_string(tmp2, ustmtext("Answ", pte), sizeof(tmp2));
2320 }
2321 snprintf(line1, sizeof(line1), "%04d/%02d/%02d %02d:%02d:%02d %s",
2322 atm.tm_year + 1900, atm.tm_mon + 1, atm.tm_mday, atm.tm_hour,
2323 atm.tm_min, atm.tm_sec, tmp2);
2324
2325 snprintf(tmp, sizeof(tmp), "%s/%s/%s-%c.csv", ast_config_AST_LOG_DIR,
2326 USTM_LOG_DIR, pte->device->name, way);
2327 if ((f = fopen(tmp, "r"))) {
2328 struct stat bufstat;
2329
2330 if (stat(tmp, &bufstat)) {
2331 display_last_error("Unable to stat history log.");
2332 fclose(f);
2333 return -1;
2334 }
2335 size = 1 + (MAX_ENTRY_LOG * TEXT_LENGTH_MAX * 3);
2336 if (bufstat.st_size != size) {
2337 ast_log(LOG_WARNING,
2338 "History file %s has an incorrect size (%d instead of %d). It will be replaced by a new one.",
2339 tmp, (int) bufstat.st_size, size);
2340 fclose(f);
2341 f = NULL;
2342 count = 1;
2343 }
2344 }
2345
2346 /* If we can't open the log file, we create a brand new one */
2347 if (!f) {
2348 char c = 1;
2349 int i;
2350
2351 if ((errno != ENOENT) && (count == 0)) {
2352 display_last_error("Unable to open history log.");
2353 return -1;
2354 }
2355 f = fopen(tmp, "w");
2356 if (!f) {
2357 display_last_error("Unable to create history log.");
2358 return -1;
2359 }
2360 if (write_entry_history(pte, f, c, line1)) {
2361 fclose(f);
2362 return -1;
2363 }
2364 memset(line1, ' ', TEXT_LENGTH_MAX);
2365 for (i = 3; i < MAX_ENTRY_LOG * 3; i++) {
2366 if (fwrite(line1, TEXT_LENGTH_MAX, 1, f) != 1) {
2367 display_last_error("Unable to write history entry - stuffing.");
2368 fclose(f);
2369 return -1;
2370 }
2371 }
2372 if (fclose(f)) {
2373 display_last_error("Unable to close history - creation.");
2374 }
2375 return 0;
2376 }
2377 /* We can open the log file, we create a temporary one, we add our entry and copy the rest */
2378 if (fread(&count, 1, 1, f) != 1) {
2379 display_last_error("Unable to read history header.");
2380 fclose(f);
2381 return -1;
2382 }
2383 if (count > MAX_ENTRY_LOG) {
2384 ast_log(LOG_WARNING, "Invalid count in history header of %s (%d max %d)\n", tmp,
2385 count, MAX_ENTRY_LOG);
2386 fclose(f);
2387 return -1;
2388 }
2389 snprintf(tmp2, sizeof(tmp2), "%s/%s/%s-%c.csv.tmp", ast_config_AST_LOG_DIR,
2390 USTM_LOG_DIR, pte->device->name, way);
2391 if (!(f2 = fopen(tmp2, "w"))) {
2392 display_last_error("Unable to create temporary history log.");
2393 fclose(f);
2394 return -1;
2395 }
2396
2397 if (++count > MAX_ENTRY_LOG) {
2398 count = MAX_ENTRY_LOG;
2399 }
2400 if (write_entry_history(pte, f2, count, line1)) {
2401 fclose(f);
2402 fclose(f2);
2403 return -1;
2404 }
2405 size = (MAX_ENTRY_LOG - 1) * TEXT_LENGTH_MAX * 3;
2406 if (!(histbuf = ast_malloc(size))) {
2407 fclose(f);
2408 fclose(f2);
2409 return -1;
2410 }
2411
2412 if (fread(histbuf, size, 1, f) != 1) {
2413 ast_free(histbuf);
2414 fclose(f);
2415 fclose(f2);
2416 display_last_error("Unable to read previous history entries.");
2417 return -1;
2418 }
2419 if (fwrite(histbuf, size, 1, f2) != 1) {
2420 ast_free(histbuf);
2421 fclose(f);
2422 fclose(f2);
2423 display_last_error("Unable to write previous history entries.");
2424 return -1;
2425 }
2426 ast_free(histbuf);
2427 if (fclose(f)) {
2428 display_last_error("Unable to close history log.");
2429 }
2430 if (fclose(f2)) {
2431 display_last_error("Unable to close temporary history log.");
2432 }
2433 if (unlink(tmp)) {
2434 display_last_error("Unable to remove old history log.");
2435 }
2436 if (rename(tmp2, tmp)) {
2437 display_last_error("Unable to rename new history log.");
2438 }
2439 return 0;
2440 }
2441
2442 static int attempt_transfer(struct unistim_subchannel *p1, struct unistim_subchannel *p2)
2443 {
2444 RAII_VAR(struct ast_channel *, chana, NULL, ast_channel_unref);
2445 RAII_VAR(struct ast_channel *, chanb, NULL, ast_channel_unref);
2446
2447 if (!p1->owner || !p2->owner) {
2448 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
2449 return -1;
2450 }
2451 chana = ast_channel_ref(p1->owner);
2452 chanb = ast_channel_ref(p2->owner);
2453
2454 switch (ast_bridge_transfer_attended(chana, chanb)) {
2455 case AST_BRIDGE_TRANSFER_INVALID:
2456 ast_log(LOG_WARNING, "Transfer failed. Invalid bridge setup\n");
2457 break;
2458 case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
2459 ast_log(LOG_WARNING, "Transfer not permitted\n");
2460 break;
2461 case AST_BRIDGE_TRANSFER_FAIL:
2462 ast_log(LOG_WARNING, "Transfer encountered internal error\n");
2463 break;
2464 case AST_BRIDGE_TRANSFER_SUCCESS:
2465 return 0;
2466 }
2467
2468 /* Control only reaches this point if transfer has failed */
2469 ast_softhangup_nolock(chana, AST_SOFTHANGUP_DEV);
2470 ast_softhangup_nolock(chanb, AST_SOFTHANGUP_DEV);
2471 return -1;
2472 }
2473
2474 void change_callerid(struct unistimsession *pte, int type, char *callerid)
2475 {
2476 char *data;
2477 int size;
2478
2479 if (type) {
2480 data = pte->device->lst_cnm;
2481 } else {
2482 data = pte->device->lst_cid;
2483 }
2484
2485 /* This is very nearly strncpy(), except that the remaining buffer
2486 * is padded with ' ', instead of '\0' */
2487 memset(data, ' ', TEXT_LENGTH_MAX);
2488 size = strlen(callerid);
2489 if (size > TEXT_LENGTH_MAX) {
2490 size = TEXT_LENGTH_MAX;
2491 }
2492 memcpy(data, callerid, size);
2493 }
2494
2495 static struct unistim_subchannel* get_sub(struct unistim_device *device, int type)
2496 {
2497 struct unistim_subchannel *sub = NULL;
2498
2499 AST_LIST_LOCK(&device->subs);
2500 AST_LIST_TRAVERSE(&device->subs, sub, list) {
2501 if (!sub) {
2502 continue;
2503 }
2504 if (sub->subtype == type) {
2505 break;
2506 }
2507 }
2508 AST_LIST_UNLOCK(&device->subs);
2509
2510 return sub;
2511 }
2512
2513 static struct unistim_subchannel* get_sub_holding(struct unistim_device *device, int type, int holding)
2514 {
2515 struct unistim_subchannel *sub = NULL;
2516
2517 AST_LIST_LOCK(&device->subs);
2518 AST_LIST_TRAVERSE(&device->subs, sub, list) {
2519 if (!sub) {
2520 continue;
2521 }
2522 if (sub->subtype == type && sub->holding == holding) {
2523 break;
2524 }
2525 }
2526 AST_LIST_UNLOCK(&device->subs);
2527
2528 return sub;
2529 }
2530
2531 static void sub_start_silence(struct unistimsession *pte, struct unistim_subchannel *sub)
2532 {
2533 /* Silence our channel */
2534 if (!pte->device->silence_generator) {
2535 pte->device->silence_generator =
2536 ast_channel_start_silence_generator(sub->owner);
2537 if (pte->device->silence_generator == NULL) {
2538 ast_log(LOG_WARNING, "Unable to start a silence generator.\n");
2539 } else if (unistimdebug) {
2540 ast_verb(0, "Starting silence generator\n");
2541 }
2542 }
2543
2544 }
2545
2546 static void sub_stop_silence(struct unistimsession *pte, struct unistim_subchannel *sub)
2547 {
2548 /* Stop the silence generator */
2549 if (pte->device->silence_generator) {
2550 if (unistimdebug) {
2551 ast_verb(0, "Stopping silence generator\n");
2552 }
2553 if (sub->owner) {
2554 ast_channel_stop_silence_generator(sub->owner, pte->device->silence_generator);
2555 } else {
2556 ast_log(LOG_WARNING, "Trying to stop silence generator on a null channel!\n");
2557 }
2558 pte->device->silence_generator = NULL;
2559 }
2560 }
2561
2562 static void sub_hold(struct unistimsession *pte, struct unistim_subchannel *sub)
2563 {
2564 if (!sub) {
2565 return;
2566 }
2567 sub->moh = 1;
2568 sub->holding = 1;
2569 send_favorite_short(sub->softkey, FAV_ICON_ONHOLD_BLACK + FAV_BLINK_SLOW, pte);
2570 send_select_output(pte, pte->device->output, pte->device->volume, MUTE_ON);
2571 send_stop_timer(pte);
2572 if (sub->owner) {
2573 ast_queue_hold(sub->owner, NULL);
2574 }
2575 return;
2576 }
2577
2578 static void sub_unhold(struct unistimsession *pte, struct unistim_subchannel *sub)
2579 {
2580 struct unistim_subchannel *sub_real;
2581
2582 sub_real = get_sub(pte->device, SUB_REAL);
2583 if (sub_real) {
2584 sub_hold(pte, sub_real);
2585 }
2586
2587 sub->moh = 0;
2588 sub->holding = 0;
2589 send_favorite_short(sub->softkey, FAV_ICON_OFFHOOK_BLACK, pte);
2590 send_select_output(pte, pte->device->output, pte->device->volume, MUTE_OFF);
2591 send_start_timer(pte);
2592 if (sub->owner) {
2593 ast_queue_unhold(sub->owner);
2594 if (sub->rtp) {
2595 send_start_rtp(sub);
2596 }
2597 }
2598 return;
2599 }
2600
2601 static void close_call(struct unistimsession *pte)
2602 {
2603 struct unistim_subchannel *sub, *sub_transf;
2604
2605 sub = get_sub(pte->device, SUB_REAL);
2606 sub_transf = get_sub(pte->device, SUB_THREEWAY);
2607 send_stop_timer(pte);
2608 if (!sub) {
2609 ast_log(LOG_WARNING, "Close call without sub\n");
2610 return;
2611 }
2612 send_favorite_short(sub->softkey, FAV_LINE_ICON, pte);
2613 if (sub->owner) {
2614 sub->alreadygone = 1;
2615 if (sub_transf) {
2616 sub_transf->alreadygone = 1;
2617 if (attempt_transfer(sub, sub_transf) < 0) {
2618 ast_verb(0, "attempt_transfer failed.\n");
2619 }
2620 } else {
2621 ast_queue_hangup(sub->owner);
2622 }
2623 } else {
2624 if (sub_transf) {
2625 if (sub_transf->owner) {
2626 ast_queue_hangup_with_cause(sub_transf->owner, AST_CAUSE_NORMAL_CLEARING);
2627 } else {
2628 ast_log(LOG_WARNING, "threeway sub without owner\n");
2629 }
2630 } else {
2631 ast_verb(0, "USTM(%s@%s-%d) channel already destroyed\n", sub->parent->name,
2632 pte->device->name, sub->softkey);
2633 }
2634 }
2635 change_callerid(pte, 0, pte->device->redial_number);
2636 change_callerid(pte, 1, "");
2637 write_history(pte, 'o', pte->device->missed_call);
2638 pte->device->missed_call = 0;
2639 show_main_page(pte);
2640 return;
2641 }
2642
2643 static void ignore_call(struct unistimsession *pte)
2644 {
2645 send_no_ring(pte);
2646 return;
2647 }
2648
2649 static void discard_call(struct unistimsession *pte)
2650 {
2651 struct unistim_subchannel* sub;
2652 sub = get_sub(pte->device, SUB_RING);
2653 if (!sub) {
2654 return;
2655 }
2656
2657 ast_queue_hangup_with_cause(sub->owner, AST_CAUSE_NORMAL_CLEARING);
2658 return;
2659 }
2660
2661 static void *unistim_ss(void *data)
2662 {
2663 struct ast_channel *chan = data;
2664 struct unistim_subchannel *sub = ast_channel_tech_pvt(chan);
2665 struct unistim_line *l = sub->parent;
2666 struct unistimsession *s = l->parent->session;
2667 int res;
2668
2669 if (!s) {
2670 return NULL;
2671 }
2672 ast_verb(3, "Starting switch on '%s@%s-%d' to %s\n", l->name, l->parent->name, sub->softkey, s->device->phone_number);
2673 ast_channel_lock(chan);
2674 ast_channel_exten_set(chan, s->device->phone_number);
2675 ast_setstate(chan, AST_STATE_RING);
2676 ast_channel_unlock(chan);
2677 ast_copy_string(s->device->redial_number, s->device->phone_number,
2678 sizeof(s->device->redial_number));
2679 res = ast_pbx_run(chan);
2680 if (res) {
2681 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2682 send_tone(s, 1000, 0);
2683 }
2684 return NULL;
2685 }
2686
2687 static int find_rtp_port(struct unistim_subchannel *s)
2688 {
2689 struct unistim_subchannel *sub = NULL;
2690 int rtp_start = s->parent->parent->rtp_port;
2691 struct ast_sockaddr us_tmp;
2692 struct sockaddr_in us = { 0, };
2693
2694 AST_LIST_LOCK(&s->parent->parent->subs);
2695 AST_LIST_TRAVERSE(&s->parent->parent->subs, sub, list) {
2696 if (!sub) {
2697 continue;
2698 }
2699 if (sub->rtp) {
2700 ast_rtp_instance_get_remote_address(sub->rtp, &us_tmp);
2701 ast_sockaddr_to_sin(&us_tmp, &us);
2702 if (htons(us.sin_port)) {
2703 rtp_start = htons(us.sin_port) + 1;
2704 break;
2705 }
2706 }
2707 }
2708 AST_LIST_UNLOCK(&s->parent->parent->subs);
2709 return rtp_start;
2710 }
2711
2712 static void send_start_rtp(struct unistim_subchannel *sub)
2713 {
2714 BUFFSEND;
2715
2716 int codec;
2717 struct sockaddr_in public = { 0, };
2718 struct sockaddr_in us = { 0, };
2719 struct sockaddr_in sin = { 0, };
2720 struct ast_sockaddr us_tmp;
2721 struct ast_sockaddr sin_tmp;
2722 struct unistimsession *pte;
2723
2724 ast_rtp_instance_get_local_address(sub->rtp, &us_tmp);
2725 ast_sockaddr_to_sin(&us_tmp, &us);
2726 ast_rtp_instance_get_remote_address(sub->rtp, &sin_tmp);
2727 ast_sockaddr_to_sin(&sin_tmp, &sin);
2728
2729 /* Setting up RTP of the phone */
2730 if (public_ip.sin_family == 0) { /* NAT IP override ? */
2731 memcpy(&public, &us, sizeof(public)); /* No defined, using IP from recvmsg */
2732 } else {
2733 memcpy(&public, &public_ip, sizeof(public)); /* override */
2734 }
2735 if (unistimdebug) {
2736 ast_verb(0, "RTP started : Our IP/port is : %s:%hd with codec %s\n",
2737 ast_inet_ntoa(us.sin_addr),
2738 htons(us.sin_port), ast_format_get_name(ast_channel_readformat(sub->owner)));
2739 ast_verb(0, "Starting phone RTP stack. Our public IP is %s\n",
2740 ast_inet_ntoa(public.sin_addr));
2741 }
2742
2743 pte = sub->parent->parent->session;
2744 codec = ast_rtp_codecs_payload_code_tx(ast_rtp_instance_get_codecs(sub->rtp),
2745 1, ast_channel_readformat(sub->owner), 0);
2746 if ((ast_format_cmp(ast_channel_readformat(sub->owner), ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) ||
2747 (ast_format_cmp(ast_channel_readformat(sub->owner), ast_format_alaw) == AST_FORMAT_CMP_EQUAL)) {
2748 if (unistimdebug) {
2749 ast_verb(0, "Sending packet_send_rtp_packet_size for codec %d\n", codec);
2750 }
2751 memcpy(buffsend + SIZE_HEADER, packet_send_rtp_packet_size,
2752 sizeof(packet_send_rtp_packet_size));
2753 buffsend[10] = (int) codec & 0xffffffffLL;
2754 send_client(SIZE_HEADER + sizeof(packet_send_rtp_packet_size), buffsend, pte);
2755 }
2756 if (unistimdebug) {
2757 ast_verb(0, "Sending Jitter Buffer Parameters Configuration\n");
2758 }
2759 memcpy(buffsend + SIZE_HEADER, packet_send_jitter_buffer_conf,
2760 sizeof(packet_send_jitter_buffer_conf));
2761 send_client(SIZE_HEADER + sizeof(packet_send_jitter_buffer_conf), buffsend, pte);
2762 if (pte->device->rtp_method != 0) {
2763 uint16_t rtcpsin_port = ntohs(us.sin_port) + 1; /* RTCP port is RTP + 1 */
2764
2765 if (unistimdebug) {
2766 ast_verb(0, "Sending OpenAudioStreamTX using method #%d\n", pte->device->rtp_method);
2767 }
2768 if (pte->device->rtp_method == 3) {
2769 memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_tx3,
2770 sizeof(packet_send_open_audio_stream_tx3));
2771 } else {
2772 memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_tx,
2773 sizeof(packet_send_open_audio_stream_tx));
2774 }
2775 if (pte->device->rtp_method != 2) {
2776 memcpy(buffsend + 28, &public.sin_addr, sizeof(public.sin_addr));
2777 put_unaligned_uint16(&buffsend[20], sin.sin_port);
2778 put_unaligned_uint16(&buffsend[22], htons(rtcpsin_port));
2779 put_unaligned_uint16(&buffsend[24], us.sin_port);
2780 put_unaligned_uint16(&buffsend[26], htons(rtcpsin_port));
2781 } else {
2782 memcpy(buffsend + 23, &public.sin_addr, sizeof(public.sin_addr));
2783 put_unaligned_uint16(&buffsend[15], sin.sin_port);
2784 put_unaligned_uint16(&buffsend[19], us.sin_port);
2785 }
2786 buffsend[11] = codec; /* rx */
2787 buffsend[12] = codec; /* tx */
2788 send_client(SIZE_HEADER + sizeof(packet_send_open_audio_stream_tx), buffsend, pte);
2789
2790 if (unistimdebug) {
2791 ast_verb(0, "Sending OpenAudioStreamRX\n");
2792 }
2793 if (pte->device->rtp_method == 3) {
2794 memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_rx3,
2795 sizeof(packet_send_open_audio_stream_rx3));
2796 } else {
2797 memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_rx,
2798 sizeof(packet_send_open_audio_stream_rx));
2799 }
2800 if (pte->device->rtp_method != 2) {
2801 memcpy(buffsend + 28, &public.sin_addr, sizeof(public.sin_addr));
2802 put_unaligned_uint16(&buffsend[20], sin.sin_port);
2803 put_unaligned_uint16(&buffsend[22], htons(rtcpsin_port));
2804 put_unaligned_uint16(&buffsend[24], us.sin_port);
2805 put_unaligned_uint16(&buffsend[26], htons(rtcpsin_port));
2806 } else {
2807 memcpy(buffsend + 23, &public.sin_addr, sizeof(public.sin_addr));
2808 put_unaligned_uint16(&buffsend[15], sin.sin_port);
2809 put_unaligned_uint16(&buffsend[19], us.sin_port);
2810 }
2811 buffsend[11] = codec; /* rx */
2812 buffsend[12] = codec; /* tx */
2813 send_client(SIZE_HEADER + sizeof(packet_send_open_audio_stream_rx), buffsend, pte);
2814 } else {
2815 uint16_t rtcpsin_port = htons(us.sin_port) + 1; /* RTCP port is RTP + 1 */
2816
2817 if (unistimdebug) {
2818 ast_verb(0, "Sending packet_send_call default method\n");
2819 }
2820
2821 memcpy(buffsend + SIZE_HEADER, packet_send_call, sizeof(packet_send_call));
2822 memcpy(buffsend + 53, &public.sin_addr, sizeof(public.sin_addr));
2823 /* Destination port when sending RTP */
2824 put_unaligned_uint16(&buffsend[49], us.sin_port);
2825 /* Destination port when sending RTCP */
2826 put_unaligned_uint16(&buffsend[51], htons(rtcpsin_port));
2827 /* Codec */
2828 buffsend[40] = codec;
2829 buffsend[41] = codec;
2830 if (ast_format_cmp(ast_channel_readformat(sub->owner), ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
2831 buffsend[42] = 1; /* 1 = 20ms (160 bytes), 2 = 40ms (320 bytes) */
2832 } else if (ast_format_cmp(ast_channel_readformat(sub->owner), ast_format_alaw) == AST_FORMAT_CMP_EQUAL) {
2833 buffsend[42] = 1; /* 1 = 20ms (160 bytes), 2 = 40ms (320 bytes) */
2834 } else if (ast_format_cmp(ast_channel_readformat(sub->owner), ast_format_g723) == AST_FORMAT_CMP_EQUAL) {
2835 buffsend[42] = 2; /* 1 = 30ms (24 bytes), 2 = 60 ms (48 bytes) */
2836 } else if (ast_format_cmp(ast_channel_readformat(sub->owner), ast_format_g729) == AST_FORMAT_CMP_EQUAL) {
2837 buffsend[42] = 2; /* 1 = 10ms (10 bytes), 2 = 20ms (20 bytes) */
2838 } else {
2839 ast_log(LOG_WARNING, "Unsupported codec %s!\n",
2840 ast_format_get_name(ast_channel_readformat(sub->owner)));
2841 }
2842 /* Source port for transmit RTP and Destination port for receiving RTP */
2843 put_unaligned_uint16(&buffsend[45], sin.sin_port);
2844 put_unaligned_uint16(&buffsend[47], htons(rtcpsin_port));
2845 send_client(SIZE_HEADER + sizeof(packet_send_call), buffsend, pte);
2846 }
2847 }
2848
2849 static void start_rtp(struct unistim_subchannel *sub)
2850 {
2851 struct sockaddr_in sin = { 0, };
2852 struct sockaddr_in sout = { 0, };
2853 struct ast_sockaddr sin_tmp;
2854 struct ast_sockaddr sout_tmp;
2855
2856 /* Sanity checks */
2857 if (!sub) {
2858 ast_log(LOG_WARNING, "start_rtp with a null subchannel !\n");
2859 return;
2860 }
2861 if (!sub->parent) {
2862 ast_log(LOG_WARNING, "start_rtp with a null line!\n");
2863 return;
2864 }
2865 if (!sub->parent->parent) {
2866 ast_log(LOG_WARNING, "start_rtp with a null device!\n");
2867 return;
2868 }
2869 if (!sub->parent->parent->session) {
2870 ast_log(LOG_WARNING, "start_rtp with a null session!\n");
2871 return;
2872 }
2873 if (!sub->owner) {
2874 ast_log(LOG_WARNING, "start_rtp with a null asterisk channel!\n");
2875 return;
2876 }
2877 sout = sub->parent->parent->session->sout;
2878 ast_mutex_lock(&sub->lock);
2879 /* Allocate the RTP */
2880 if (unistimdebug) {
2881 ast_verb(0, "Starting RTP. Bind on %s\n", ast_inet_ntoa(sout.sin_addr));
2882 }
2883 ast_sockaddr_from_sin(&sout_tmp, &sout);
2884 sub->rtp = ast_rtp_instance_new("asterisk", sched, &sout_tmp, NULL);
2885 if (!sub->rtp) {
2886 ast_log(LOG_WARNING, "Unable to create RTP session: %s binaddr=%s\n",
2887 strerror(errno), ast_inet_ntoa(sout.sin_addr));
2888 ast_mutex_unlock(&sub->lock);
2889 return;
2890 }
2891 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_RTCP, 1);
2892 ast_rtp_instance_set_channel_id(sub->rtp, ast_channel_uniqueid(sub->owner));
2893 ast_channel_internal_fd_set(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
2894 ast_channel_internal_fd_set(sub->owner, 1, ast_rtp_instance_fd(sub->rtp, 1));
2895 ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "UNISTIM RTP");
2896 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, sub->parent->parent->nat);
2897
2898 /* Create the RTP connection */
2899 sin.sin_family = AF_INET;
2900 /* Setting up RTP for our side */
2901 memcpy(&sin.sin_addr, &sub->parent->parent->session->sin.sin_addr,
2902 sizeof(sin.sin_addr));
2903
2904 sin.sin_port = htons(find_rtp_port(sub));
2905 ast_sockaddr_from_sin(&sin_tmp, &sin);
2906 ast_rtp_instance_set_remote_address(sub->rtp, &sin_tmp);
2907 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(sub->owner), ast_channel_readformat(sub->owner)) == AST_FORMAT_CMP_NOT_EQUAL) {
2908 struct ast_format *tmpfmt;
2909 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
2910
2911 tmpfmt = ast_format_cap_get_format(ast_channel_nativeformats(sub->owner), 0);
2912 ast_log(LOG_WARNING,
2913 "Our read/writeformat has been changed to something incompatible: %s, using %s best codec from %s\n",
2914 ast_format_get_name(ast_channel_readformat(sub->owner)),
2915 ast_format_get_name(tmpfmt),
2916 ast_format_cap_get_names(ast_channel_nativeformats(sub->owner), &cap_buf));
2917
2918 ast_channel_set_readformat(sub->owner, tmpfmt);
2919 ast_channel_set_writeformat(sub->owner, tmpfmt);
2920 ao2_ref(tmpfmt, -1);
2921 }
2922 send_start_rtp(sub);
2923 ast_mutex_unlock(&sub->lock);
2924 }
2925
2926 static void send_dial_tone(struct unistimsession *pte)
2927 {
2928 struct ast_tone_zone_sound *ts = NULL;
2929 struct ast_tone_zone_part tone_data;
2930 char *s = NULL;
2931 char *ind;
2932
2933 if ((ts = ast_get_indication_tone(pte->device->tz, "dial"))) {
2934 ind = ast_strdupa(ts->data);
2935 s = strsep(&ind, ",");
2936 ast_tone_zone_part_parse(s, &tone_data);
2937 send_tone(pte, tone_data.freq1, tone_data.freq2);
2938 if (unistimdebug) {
2939 ast_verb(0, "Country code found (%s), freq1=%u freq2=%u\n",
2940 pte->device->tz->country, tone_data.freq1, tone_data.freq2);
2941 }
2942 ts = ast_tone_zone_sound_unref(ts);
2943 }
2944 }
2945
2946 static void show_phone_number(struct unistimsession *pte)
2947 {
2948 char tmp[TEXT_LENGTH_MAX + 1];
2949 const char *tmp_number = ustmtext("Number:", pte);
2950 int line, tmp_copy, offset = 0, i;
2951
2952 pte->device->phone_number[pte->device->size_phone_number] = '\0';
2953 if (pte->device->size_phone_number > MAX_SCREEN_NUMBER) {
2954 offset = pte->device->size_phone_number - MAX_SCREEN_NUMBER - 1;
2955 if (offset > strlen(tmp_number)) {
2956 offset = strlen(tmp_number);
2957 }
2958 tmp_copy = strlen(tmp_number) - offset + 1;
2959 if (tmp_copy > sizeof(tmp)) {
2960 tmp_copy = sizeof(tmp);
2961 }
2962 memcpy(tmp, tmp_number + offset, tmp_copy);
2963 } else {
2964 ast_copy_string(tmp, tmp_number, sizeof(tmp));
2965 }
2966
2967 offset = (pte->device->size_phone_number >= TEXT_LENGTH_MAX) ? (pte->device->size_phone_number - TEXT_LENGTH_MAX +1) : 0;
2968 if (pte->device->size_phone_number) {
2969 memcpy(tmp + strlen(tmp), pte->device->phone_number + offset, pte->device->size_phone_number - offset + 1);
2970 }
2971 offset = strlen(tmp);
2972
2973 for (i = strlen(tmp); i < TEXT_LENGTH_MAX; i++) {
2974 tmp[i] = '.';
2975 }
2976 tmp[i] = '\0';
2977
2978 line = (pte->device->height == 1) ? TEXT_LINE0 : TEXT_LINE2;
2979 send_text(line, TEXT_NORMAL, pte, tmp);
2980 send_blink_cursor(pte);
2981 send_cursor_pos(pte, (unsigned char) (line + offset));
2982 send_led_update(pte, LED_BAR_OFF);
2983 }
2984
2985 static void handle_dial_page(struct unistimsession *pte)
2986 {
2987 pte->state = STATE_DIALPAGE;
2988 if (pte->device->call_forward[0] == -1) {
2989 send_text(TEXT_LINE0, TEXT_NORMAL, pte, "");
2990 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("Enter forward", pte));
2991 send_text_status(pte, ustmtext("Fwd Cancel BackSp Erase", pte));
2992 if (pte->device->call_forward[1] != 0) {
2993 ast_copy_string(pte->device->phone_number, pte->device->call_forward + 1,
2994 sizeof(pte->device->phone_number));
2995 show_phone_number(pte);
2996 send_led_update(pte, LED_BAR_OFF);
2997 return;
2998 }
2999 } else {
3000 if ((pte->device->output == OUTPUT_HANDSET) &&
3001 (pte->device->receiver_state == STATE_ONHOOK)) {
3002 send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
3003 } else {
3004 send_select_output(pte, pte->device->output, pte->device->volume, MUTE_OFF);
3005 }
3006 send_dial_tone(pte);
3007
3008 if (pte->device->height > 1) {
3009 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Enter the number to dial", pte));
3010 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("and press Call", pte));
3011 }
3012 if (ast_strlen_zero(pte->device->redial_number)) {
3013 send_text_status(pte, ustmtext("Call BackSp Erase", pte));
3014 } else {
3015 send_text_status(pte, ustmtext("Call Redial BackSp Erase", pte));
3016 }
3017 }
3018
3019 pte->device->size_phone_number = 0;
3020 pte->device->phone_number[0] = 0;
3021 show_phone_number(pte);
3022 change_favorite_icon(pte, FAV_ICON_PHONE_BLACK);
3023 send_icon(TEXT_LINE0, FAV_ICON_NONE, pte);
3024 pte->device->missed_call = 0;
3025 send_led_update(pte, LED_BAR_OFF);
3026 pte->device->lastmsgssent = -1;
3027 return;
3028 }
3029
3030 static void swap_subs(struct unistim_subchannel *a, struct unistim_subchannel *b)
3031 {
3032 struct ast_rtp_instance *rtp;
3033 int fds;
3034
3035 if (unistimdebug) {
3036 ast_verb(0, "Swapping %p and %p\n", a, b);
3037 }
3038 if ((!a->owner) || (!b->owner)) {
3039 ast_log(LOG_WARNING,
3040 "Attempted to swap subchannels with a null owner : sub #%p=%p sub #%p=%p\n",
3041 a, a->owner, b, b->owner);
3042 return;
3043 }
3044 rtp = a->rtp;
3045 a->rtp = b->rtp;
3046 b->rtp = rtp;
3047
3048 fds = ast_channel_fd(a->owner, 0);
3049 ast_channel_internal_fd_set(a->owner, 0, ast_channel_fd(b->owner, 0));
3050 ast_channel_internal_fd_set(b->owner, 0, fds);
3051
3052 fds = ast_channel_fd(a->owner, 1);
3053 ast_channel_internal_fd_set(a->owner, 1, ast_channel_fd(b->owner, 1));
3054 ast_channel_internal_fd_set(b->owner, 1, fds);
3055 }
3056
3057 /* Step 1 : Music On Hold for peer, Dialing screen for us */
3058 static void transfer_call_step1(struct unistimsession *pte)
3059 {
3060 struct unistim_subchannel *sub /*, *sub_trans */;
3061 struct unistim_device *d = pte->device;
3062
3063 sub = get_sub(d, SUB_REAL);
3064 /* sub_trans = get_sub(d, SUB_THREEWAY); */
3065
3066 if (!sub || !sub->owner) {
3067 ast_log(LOG_WARNING, "Unable to find subchannel for music on hold\n");
3068 return;
3069 }
3070 /* Start music on hold if appropriate */
3071 if (sub->moh) {
3072 ast_log(LOG_WARNING, "Transfer with peer already listening music on hold\n");
3073 } else {
3074 ast_queue_hold(sub->owner, sub->parent->musicclass);
3075 sub->moh = 1;
3076 sub->subtype = SUB_THREEWAY;
3077 }
3078 sub_start_silence(pte, sub);
3079 handle_dial_page(pte);
3080 }
3081
3082 static void transfer_cancel_step2(struct unistimsession *pte)
3083 {
3084 struct unistim_subchannel *sub, *sub_trans;
3085 struct unistim_device *d = pte->device;
3086
3087 sub = get_sub(d, SUB_REAL);
3088 sub_trans = get_sub(d, SUB_THREEWAY);
3089
3090 if (!sub || !sub->owner) {
3091 ast_log(LOG_WARNING, "Unable to find subchannel for music on hold\n");
3092 return;
3093 }
3094 if (sub_trans) {
3095 if (unistimdebug) {
3096 ast_verb(0, "Transfer canceled, hangup our threeway channel\n");
3097 }
3098 if (sub->owner) {
3099 swap_subs(sub, sub_trans);
3100 ast_queue_unhold(sub_trans->owner);
3101 sub_trans->moh = 0;
3102 sub_trans->subtype = SUB_REAL;
3103 sub->subtype = SUB_THREEWAY;
3104 ast_queue_hangup_with_cause(sub->owner, AST_CAUSE_NORMAL_CLEARING);
3105 } else {
3106 ast_log(LOG_WARNING, "Canceling a threeway channel without owner\n");
3107 }
3108 return;
3109 }
3110 }
3111
3112 /* From phone to PBX */
3113 static void handle_call_outgoing(struct unistimsession *s)
3114 {
3115 struct ast_channel *c;
3116 struct unistim_subchannel *sub;
3117 int softkey;
3118
3119 s->state = STATE_CALL;
3120
3121 sub = get_sub(s->device, SUB_THREEWAY);
3122 if (sub) {
3123 /* If sub for threway call created than we use transfer behavior */
3124 struct unistim_subchannel *sub_trans = NULL;
3125 struct unistim_device *d = s->device;
3126
3127 sub_trans = get_sub(d, SUB_REAL);
3128 if (sub_trans) {
3129 ast_log(LOG_WARNING, "Can't transfer while active subchannel exists!\n");
3130 return;
3131 }
3132 if (!sub->owner) {
3133 ast_log(LOG_WARNING, "Unable to find subchannel with music on hold\n");
3134 return;
3135 }
3136
3137 sub_trans = unistim_alloc_sub(d, SUB_REAL);
3138 if (!sub_trans) {
3139 ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
3140 return;
3141 }
3142 sub_trans->parent = sub->parent;
3143 sub_stop_silence(s, sub);
3144 send_tone(s, 0, 0);
3145 /* Make new channel */
3146 c = unistim_new(sub_trans, AST_STATE_DOWN, NULL, NULL);
3147 if (!c) {
3148 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %p\n", sub->parent);
3149 return;
3150 }
3151 /* Swap things around between the three-way and real call */
3152 swap_subs(sub, sub_trans);
3153 send_select_output(s, s->device->output, s->device->volume, MUTE_OFF);
3154 if (s->device->height == 1) {
3155 send_text(TEXT_LINE0, TEXT_NORMAL, s, s->device->phone_number);
3156 } else {
3157 send_text(TEXT_LINE0, TEXT_NORMAL, s, ustmtext("Calling (pre-transfer)", s));
3158 send_text(TEXT_LINE1, TEXT_NORMAL, s, s->device->phone_number);
3159 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("Dialing...", s));
3160 }
3161 send_text_status(s, ustmtext("TransfrCancel", s));
3162
3163 if (ast_pthread_create(&sub->ss_thread, NULL, unistim_ss, c)) {
3164 ast_log(LOG_WARNING, "Unable to start simple switch on channel %p\n", c);
3165 sub->ss_thread = AST_PTHREADT_NULL;
3166 ast_hangup(c);
3167 return;
3168 }
3169 if (unistimdebug) {
3170 ast_verb(0, "Started three way call on channel %p (%s) subchan %u\n",
3171 sub_trans->owner, ast_channel_name(sub_trans->owner), sub_trans->subtype);
3172 }
3173 return;
3174 }
3175
3176 softkey = get_avail_softkey(s, NULL);
3177 if (softkey == -1) {
3178 ast_log(LOG_WARNING, "Have no avail softkey for calling\n");
3179 return;
3180 }
3181 sub = get_sub(s->device, SUB_REAL);
3182 if (sub) { /* have already call assigned */
3183 sub_hold(s, sub); /* Need to put on hold */
3184 }
3185 if (!(sub = unistim_alloc_sub(s->device, SUB_REAL))) {
3186 ast_log(LOG_WARNING, "Unable to allocate subchannel!\n");
3187 return;
3188 }
3189 sub->parent = s->device->sline[softkey];
3190 s->device->ssub[softkey] = sub;
3191 sub->softkey = softkey;
3192
3193 if (unistimdebug) {
3194 ast_verb(0, "Using softkey %d, line %p\n", sub->softkey, sub->parent);
3195 }
3196 send_favorite_short(sub->softkey, FAV_ICON_OFFHOOK_BLACK, s);
3197 s->device->selected = -1;
3198 if (!sub->owner) { /* A call is already in progress ? */
3199 RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, NULL, ao2_cleanup);
3200 const char *pickupexten;
3201
3202 c = unistim_new(sub, AST_STATE_DOWN, NULL, NULL); /* No, starting a new one */
3203 if (!sub->rtp) { /* Need to start RTP before calling ast_pbx_run */
3204 start_rtp(sub);
3205 }
3206 if (c) {
3207 ast_channel_lock(c);
3208 pickup_cfg = ast_get_chan_features_pickup_config(c);
3209 if (!pickup_cfg) {
3210 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
3211 pickupexten = "";
3212 } else {
3213 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
3214 }
3215 ast_channel_unlock(c);
3216 }
3217 if (c && !strcmp(s->device->phone_number, pickupexten)) {
3218 if (unistimdebug) {
3219 ast_verb(0, "Try to pickup in unistim_new\n");
3220 }
3221 send_text(TEXT_LINE0, TEXT_NORMAL, s, "");
3222 send_text_status(s, ustmtext(" Transf Hangup", s));
3223 send_start_timer(s);
3224 if (ast_pickup_call(c)) {
3225 ast_log(LOG_NOTICE, "Nothing to pick up\n");
3226 ast_channel_hangupcause_set(c, AST_CAUSE_CALL_REJECTED);
3227 } else {
3228 ast_channel_hangupcause_set(c, AST_CAUSE_NORMAL_CLEARING);
3229 }
3230 ast_hangup(c);
3231 c = NULL;
3232 } else if (c) {
3233 send_select_output(s, s->device->output, s->device->volume, MUTE_OFF);
3234 send_tone(s, 0, 0); /* Dialing empty number should also stop dial tone */
3235 if (s->device->height == 1) {
3236 if (strlen(s->device->phone_number) > 0) {
3237 send_text(TEXT_LINE0, TEXT_NORMAL, s, s->device->phone_number);
3238 } else {
3239 send_text(TEXT_LINE0, TEXT_NORMAL, s, ustmtext("Calling...", s));
3240 }
3241 } else {
3242 send_text(TEXT_LINE0, TEXT_NORMAL, s, ustmtext("Calling :", s));
3243 send_text(TEXT_LINE1, TEXT_NORMAL, s, s->device->phone_number);
3244 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("Dialing...", s));
3245 }
3246 send_text_status(s, ustmtext(" Hangup", s));
3247
3248 /* start switch */
3249 if (ast_pthread_create(&sub->ss_thread, NULL, unistim_ss, c)) {
3250 ast_log(LOG_WARNING, "Unable to create switch thread\n");
3251 sub->ss_thread = AST_PTHREADT_NULL;
3252 ast_queue_hangup_with_cause(c, AST_CAUSE_SWITCH_CONGESTION);
3253 }
3254 } else
3255 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n",
3256 sub->parent->name, s->device->name);
3257 } else {
3258 ast_debug(1, "Current sub [%s] already has owner\n", ast_channel_name(sub->owner));
3259 }
3260 return;
3261 }
3262
3263 /* From PBX to phone */
3264 static void handle_call_incoming(struct unistimsession *s)
3265 {
3266 struct unistim_subchannel *sub = NULL;
3267 int i;
3268
3269 s->state = STATE_CALL;
3270 s->device->missed_call = 0;
3271 send_no_ring(s);
3272 sub = get_sub(s->device, SUB_RING); /* Put other SUB_REAL call on hold */
3273 if (!sub) {
3274 ast_log(LOG_WARNING, "No ringing lines on: %s\n", s->device->name);
3275 return;
3276 }
3277 /* Change icons for all ringing keys */
3278 for (i = 0; i < FAVNUM; i++) {
3279 if (!s->device->ssub[i]) { /* No sub assigned - skip */
3280 continue;
3281 }
3282 if (s->device->ssub[i]->subtype == SUB_REAL) {
3283 sub_hold(s, s->device->ssub[i]);
3284 }
3285 if (s->device->ssub[i] != sub) {
3286 continue;
3287 }
3288 if (sub->softkey == i) { /* If softkey assigned at this moment - do not erase */
3289 continue;
3290 }
3291 if (sub->softkey < 0) { /* If softkey not defined - first one used */
3292 sub->softkey = i;
3293 continue;
3294 }
3295 send_favorite_short(i, FAV_LINE_ICON, s);
3296 s->device->ssub[i] = NULL;
3297 }
3298 if (sub->softkey < 0) {
3299 ast_log(LOG_WARNING, "Can not assign softkey for incoming call on: %s\n", s->device->name);
3300 return;
3301 }
3302 send_favorite_short(sub->softkey, FAV_ICON_OFFHOOK_BLACK, s);
3303 sub->parent = s->device->sline[sub->softkey];
3304 sub->subtype = SUB_REAL;
3305 if (unistimdebug) {
3306 ast_verb(0, "Handle Call Incoming for %s@%s\n", sub->parent->name,
3307 s->device->name);
3308 }
3309 start_rtp(sub);
3310 if (!sub->rtp) {
3311 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
3312 return;
3313 }
3314 if (sub->owner) {
3315 ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
3316 }
3317 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("is on-line", s));
3318 send_text_status(s, ustmtext(" Transf Hangup", s));
3319 send_start_timer(s);
3320
3321 if ((s->device->output == OUTPUT_HANDSET) &&
3322 (s->device->receiver_state == STATE_ONHOOK)) {
3323 send_select_output(s, OUTPUT_SPEAKER, s->device->volume, MUTE_OFF);
3324 } else {
3325 send_select_output(s, s->device->output, s->device->volume, MUTE_OFF);
3326 }
3327 write_history(s, 'i', 0);
3328 return;
3329 }
3330
3331 static int send_dtmf_tone(struct unistimsession *pte, char digit)
3332 {
3333 int row, col;
3334
3335 if (unistimdebug) {
3336 ast_verb(0, "Phone Play Digit %c\n", digit);
3337 }
3338 if (pte->device->dtmfduration > 0) {
3339 row = (digit - '1') % 3;
3340 col = (digit - '1' - row) / 3;
3341 if (digit >= '1' && digit <='9') {
3342 send_tone(pte, dtmf_row[row], dtmf_col[col]);
3343 } else if (digit >= 'A' && digit <= 'D') {
3344 send_tone(pte, dtmf_row[digit-'A'], dtmf_col[3]);
3345 } else if (digit == '*') {
3346 send_tone(pte, dtmf_row[3], dtmf_col[0]);
3347 } else if (digit == '0') {
3348 send_tone(pte, dtmf_row[3], dtmf_col[1]);
3349 } else if (digit == '#') {
3350 send_tone(pte, dtmf_row[3], dtmf_col[2]);
3351 } else {
3352 send_tone(pte, 500, 2000);
3353 }
3354 }
3355 return 0;
3356 }
3357
3358 static int unistim_do_senddigit(struct unistimsession *pte, char digit)
3359 {
3360 struct ast_frame f = { .frametype = AST_FRAME_DTMF, .subclass.integer = digit, .src = "unistim" };
3361 struct unistim_subchannel *sub;
3362
3363 sub = get_sub(pte->device, SUB_REAL);
3364 if (!sub || !sub->owner || sub->alreadygone) {
3365 ast_log(LOG_WARNING, "Unable to find subchannel in dtmf senddigit\n");
3366 return -1;
3367 }
3368
3369 /* Send DTMF indication _before_ playing sounds */
3370 ast_queue_frame(sub->owner, &f);
3371 if (pte->device->dtmfduration > 0) {
3372 if (unistimdebug) {
3373 ast_verb(0, "Send Digit %c (%i ms)\n", digit, pte->device->dtmfduration);
3374 }
3375 send_dtmf_tone(pte, digit);
3376 usleep(pte->device->dtmfduration * 1000); /* XXX Less than perfect, blocking an important thread is not a good idea */
3377 send_tone(pte, 0, 0);
3378 }
3379 return 0;
3380 }
3381
3382 static void handle_key_fav(struct unistimsession *pte, char keycode)
3383 {
3384 int keynum = keycode - KEY_FAV0;
3385 struct unistim_subchannel *sub, *sub_key = NULL;
3386 sub = get_sub_holding(pte->device, SUB_REAL, 0);
3387
3388 /* Make an action on selected favorite key */
3389 if (!pte->device->ssub[keynum]) { /* Key have no assigned call */
3390 sub = get_sub_holding(pte->device, SUB_REAL, 0);
3391 send_favorite_selected(FAV_LINE_ICON, pte);
3392 if (is_key_line(pte->device, keynum)) {
3393 if (unistimdebug) {
3394 ast_verb(0, "Handle line w/o sub - dialpage\n");
3395 }
3396 pte->device->selected = keynum;
3397 sub_hold(pte, sub); /* Put active call on hold */
3398 send_stop_timer(pte);
3399 handle_dial_page(pte);
3400 } else if (is_key_favorite(pte->device, keynum)) {
3401 /* Put active call on hold in handle_call_outgoing function, after preparation and
3402 checking if lines available for calling */
3403 if (unistimdebug) {
3404 ast_verb(0, "Handle favorite w/o sub - dialing\n");
3405 }
3406 if ((pte->device->output == OUTPUT_HANDSET) &&
3407 (pte->device->receiver_state == STATE_ONHOOK)) {
3408 send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
3409 } else {
3410 send_select_output(pte, pte->device->output, pte->device->volume, MUTE_OFF);
3411 }
3412 key_favorite(pte, keycode);
3413 }
3414 } else {
3415 sub_key = pte->device->ssub[keynum];
3416 /* Favicon have assigned sub, activate it and put current on hold */
3417 if (sub_key->subtype == SUB_REAL && !sub_key->holding) {
3418 sub_hold(pte, sub_key);
3419 show_main_page(pte);
3420 } else if (sub_key->subtype == SUB_REAL && sub_key->holding) {
3421 /* We are going to unhold line (we should put active line on hold, of any) */
3422 if (pte->state == STATE_DIALPAGE){
3423 send_tone(pte, 0, 0);
3424 }
3425 sub_hold(pte, sub);
3426 send_callerid_screen(pte, sub_key);
3427 sub_unhold(pte, sub_key);
3428 pte->state = STATE_CALL;
3429 } else if (sub_key->subtype == SUB_RING) {
3430 sub_hold(pte, sub);
3431 sub_key->softkey = keynum;
3432 handle_call_incoming(pte);
3433 }
3434 }
3435 }
3436
3437 static void key_call(struct unistimsession *pte, char keycode)
3438 {
3439 struct unistim_subchannel *sub = get_sub(pte->device, SUB_REAL);
3440 struct unistim_subchannel *sub_3way = get_sub(pte->device, SUB_THREEWAY);
3441
3442 if (!sub) {
3443 return;
3444 }
3445 if ((keycode >= KEY_0) && (keycode <= KEY_SHARP)) {
3446 if (keycode == KEY_SHARP) {
3447 keycode = '#';
3448 } else if (keycode == KEY_STAR) {
3449 keycode = '*';
3450 } else {
3451 keycode -= 0x10;
3452 }
3453 unistim_do_senddigit(pte, keycode);
3454 return;
3455 }
3456 switch (keycode) {
3457 case KEY_FUNC1:
3458 if (sub->owner && ast_channel_state(sub->owner) == AST_STATE_UP) {
3459 if (sub_3way) {
3460 close_call(pte);
3461 }
3462 }
3463 break;
3464 case KEY_FUNC2:
3465 if (sub_3way) {
3466 transfer_cancel_step2(pte);
3467 } else if (ast_channel_state(sub->owner) == AST_STATE_UP) {
3468 transfer_call_step1(pte);
3469 }
3470 break;
3471 case KEY_HANGUP:
3472 case KEY_FUNC4:
3473 if (!sub_3way) {
3474 close_call(pte);
3475 }
3476 break;
3477 case KEY_FAV0:
3478 case KEY_FAV1:
3479 case KEY_FAV2:
3480 case KEY_FAV3:
3481 case KEY_FAV4:
3482 case KEY_FAV5:
3483 handle_key_fav(pte, keycode);
3484 break;
3485 case KEY_HEADPHN:
3486 if (pte->device->output == OUTPUT_HEADPHONE) {
3487 send_select_output(pte, OUTPUT_HANDSET, pte->device->volume, MUTE_OFF);
3488 } else {
3489 send_select_output(pte, OUTPUT_HEADPHONE, pte->device->volume, MUTE_OFF);
3490 }
3491 break;
3492 case KEY_LOUDSPK:
3493 if (pte->device->output != OUTPUT_SPEAKER)
3494 send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
3495 else
3496 send_select_output(pte, pte->device->previous_output, pte->device->volume,
3497 MUTE_OFF);
3498 break;
3499 case KEY_ONHOLD:
3500 if (!sub) {
3501 if(pte->device->ssub[pte->device->selected]) {
3502 sub = pte->device->ssub[pte->device->selected];
3503 } else {
3504 break;
3505 }
3506 }
3507 if (sub->holding) {
3508 sub_unhold(pte, sub);
3509 } else {
3510 sub_hold(pte, sub);
3511 }
3512 break;
3513 }
3514 return;
3515 }
3516
3517 static void key_ringing(struct unistimsession *pte, char keycode)
3518 {
3519 switch (keycode) {
3520 case KEY_FAV0:
3521 case KEY_FAV1:
3522 case KEY_FAV2:
3523 case KEY_FAV3:
3524 case KEY_FAV4:
3525 case KEY_FAV5:
3526 handle_key_fav(pte, keycode);
3527 break;
3528 case KEY_FUNC3:
3529 ignore_call(pte);
3530 break;
3531 case KEY_HANGUP:
3532 case KEY_FUNC4:
3533 discard_call(pte);
3534 break;
3535 case KEY_LOUDSPK:
3536 pte->device->output = OUTPUT_SPEAKER;
3537 handle_call_incoming(pte);
3538 break;
3539 case KEY_HEADPHN:
3540 pte->device->output = OUTPUT_HEADPHONE;
3541 handle_call_incoming(pte);
3542 break;
3543 case KEY_FUNC1:
3544 handle_call_incoming(pte);
3545 break;
3546 }
3547 return;
3548 }
3549
3550 static void key_favorite(struct unistimsession *pte, char keycode)
3551 {
3552 int fav = keycode - KEY_FAV0;
3553 if (!is_key_favorite(pte->device, fav)) {
3554 ast_log(LOG_WARNING, "It's not a favorite key\n");
3555 return;
3556 }
3557 ast_copy_string(pte->device->phone_number, pte->device->softkeynumber[fav],
3558 sizeof(pte->device->phone_number));
3559 handle_call_outgoing(pte);
3560 return;
3561 }
3562
3563 static void key_dial_page(struct unistimsession *pte, char keycode)
3564 {
3565 struct unistim_subchannel *sub = get_sub(pte->device, SUB_THREEWAY);
3566
3567 pte->device->nextdial = 0;
3568 if (keycode == KEY_FUNC3) {
3569 if (pte->device->size_phone_number <= 1) {
3570 keycode = KEY_FUNC4;
3571 } else {
3572 pte->device->size_phone_number -= 2;
3573 keycode = pte->device->phone_number[pte->device->size_phone_number] + 0x10;
3574 }
3575 }
3576 if (keycode == KEY_SHARP && pte->device->sharp_dial == 1) {
3577 keycode = KEY_FUNC1;
3578 }
3579 if ((keycode >= KEY_0) && (keycode <= KEY_SHARP)) {
3580 int i = pte->device->size_phone_number;
3581
3582 /*
3583 * If the phone_number buffer is already full, bail now to prevent an overrun.
3584 */
3585 if (pte->device->size_phone_number >= MAX_PHONE_NUMBER_LENGTH) {
3586 return;
3587 }
3588 if (pte->device->size_phone_number == 0) {
3589 send_tone(pte, 0, 0);
3590 }
3591 if (keycode == KEY_SHARP) {
3592 keycode = '#';
3593 } else if (keycode == KEY_STAR) {
3594 keycode = '*';
3595 } else {
3596 keycode -= 0x10;
3597 }
3598 pte->device->phone_number[i] = keycode;
3599 pte->device->size_phone_number++;
3600 pte->device->phone_number[i + 1] = 0;
3601 show_phone_number(pte);
3602
3603 if (ast_exists_extension(NULL, pte->device->context, pte->device->phone_number, 1, NULL) &&
3604 !ast_matchmore_extension(NULL, pte->device->context, pte->device->phone_number, 1, NULL)) {
3605 keycode = KEY_FUNC1;
3606 } else {
3607 if (pte->device->interdigit_timer) {
3608 pte->device->nextdial = get_tick_count() + pte->device->interdigit_timer;
3609 }
3610 }
3611 }
3612 if (keycode == KEY_FUNC4) {
3613 pte->device->size_phone_number = 0;
3614 show_phone_number(pte);
3615 return;
3616 }
3617
3618 if (pte->device->call_forward[0] == -1) {
3619 if (keycode == KEY_FUNC1) {
3620 ast_copy_string(pte->device->call_forward, pte->device->phone_number,
3621 sizeof(pte->device->call_forward));
3622 show_main_page(pte);
3623 } else if ((keycode == KEY_FUNC2) || (keycode == KEY_HANGUP)) {
3624 pte->device->call_forward[0] = '\0';
3625 send_led_update(pte, LED_SPEAKER_OFF);
3626 send_led_update(pte, LED_HEADPHONE_OFF);
3627 show_main_page(pte);
3628 }
3629 return;
3630 }
3631 switch (keycode) {
3632 case KEY_FUNC2:
3633 if (ast_strlen_zero(pte->device->redial_number)) {
3634 break;
3635 }
3636 ast_copy_string(pte->device->phone_number, pte->device->redial_number,
3637 sizeof(pte->device->phone_number));
3638 case KEY_FUNC1:
3639 handle_call_outgoing(pte);
3640 break;
3641 case KEY_HANGUP:
3642 if (sub && sub->owner) {
3643 sub_stop_silence(pte, sub);
3644 send_tone(pte, 0, 0);
3645 ast_queue_unhold(sub->owner);
3646 sub->moh = 0;
3647 sub->subtype = SUB_REAL;
3648 pte->state = STATE_CALL;
3649
3650 send_text_status(pte, ustmtext(" Transf Hangup", pte));
3651 send_callerid_screen(pte, sub);
3652 } else {
3653 send_led_update(pte, LED_SPEAKER_OFF);
3654 send_led_update(pte, LED_HEADPHONE_OFF);
3655 show_main_page(pte);
3656 }
3657 break;
3658 case KEY_FAV0:
3659 case KEY_FAV1:
3660 case KEY_FAV2:
3661 case KEY_FAV3:
3662 case KEY_FAV4:
3663 case KEY_FAV5:
3664 send_favorite_selected(FAV_LINE_ICON, pte);
3665 pte->device->selected = -1;
3666 handle_key_fav(pte, keycode);
3667 break;
3668 case KEY_LOUDSPK:
3669 if (pte->device->output == OUTPUT_SPEAKER) {
3670 if (pte->device->receiver_state == STATE_OFFHOOK) {
3671 send_select_output(pte, pte->device->previous_output, pte->device->volume,
3672 MUTE_OFF);
3673 } else {
3674 show_main_page(pte);
3675 }
3676 } else {
3677 send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
3678 }
3679 break;
3680 case KEY_HEADPHN:
3681 if (pte->device->output == OUTPUT_HEADPHONE) {
3682 if (pte->device->receiver_state == STATE_OFFHOOK) {
3683 send_select_output(pte, OUTPUT_HANDSET, pte->device->volume, MUTE_OFF);
3684 } else {
3685 show_main_page(pte);
3686 }
3687 } else {
3688 send_select_output(pte, OUTPUT_HEADPHONE, pte->device->volume, MUTE_OFF);
3689 }
3690 break;
3691 }
3692 return;
3693 }
3694
3695 static void handle_select_option(struct unistimsession *pte)
3696 {
3697 char tmp[128];
3698
3699 if (pte->state != STATE_SELECTOPTION) {
3700 pte->state = STATE_SELECTOPTION;
3701 pte->size_buff_entry = 1;
3702 pte->buff_entry[0] = 0; /* Position in menu */
3703 }
3704 snprintf(tmp, sizeof(tmp), "%d. %s", pte->buff_entry[0] + 1, ustmtext(options_menu[(int)pte->buff_entry[0]].label, pte));
3705 send_text(TEXT_LINE0, TEXT_NORMAL, pte, tmp);
3706 send_text_status(pte, ustmtext("Select Cancel", pte));
3707 return;
3708 }
3709
3710 static void key_select_option(struct unistimsession *pte, char keycode)
3711 {
3712 switch (keycode) {
3713 case KEY_DOWN:
3714 pte->buff_entry[0]++;
3715 if (options_menu[(int)pte->buff_entry[0]].label == NULL) {
3716 pte->buff_entry[0]--;
3717 }
3718 break;
3719 case KEY_UP:
3720 if (pte->buff_entry[0] > 0) {
3721 pte->buff_entry[0]--;
3722 }
3723 break;
3724 case KEY_FUNC1:
3725 options_menu[(int)pte->buff_entry[0]].handle_option(pte);
3726 return;
3727 case KEY_HANGUP:
3728 case KEY_FUNC4:
3729 show_main_page(pte);
3730 return;
3731 }
3732
3733 handle_select_option(pte);
3734 return;
3735 }
3736
3737 #define SELECTCODEC_START_ENTRY_POS 15
3738 #define SELECTCODEC_MAX_LENGTH 2
3739 #define SELECTCODEC_MSG "Codec number : .."
3740 static void handle_select_codec(struct unistimsession *pte)
3741 {
3742 char buf[30], buf2[6];
3743
3744 pte->state = STATE_SELECTCODEC;
3745 ast_copy_string(buf, ustmtext("Using codec", pte), sizeof(buf));
3746 snprintf(buf2, sizeof(buf2), " %d", pte->device->codec_number);
3747 strcat(buf, buf2);
3748 strcat(buf, " (G711u=0,");
3749
3750 send_text(TEXT_LINE0, TEXT_NORMAL, pte, buf);
3751 send_text(TEXT_LINE1, TEXT_NORMAL, pte, "G723=4,G711a=8,G729A=18)");
3752 send_text(TEXT_LINE2, TEXT_INVERSE, pte, SELECTCODEC_MSG);
3753 send_blink_cursor(pte);
3754 send_cursor_pos(pte, TEXT_LINE2 + SELECTCODEC_START_ENTRY_POS);
3755 pte->size_buff_entry = 0;
3756 send_text_status(pte, ustmtext("Select BackSp Erase Cancel", pte));
3757 return;
3758 }
3759
3760 static void key_select_codec(struct unistimsession *pte, char keycode)
3761 {
3762 if (keycode == KEY_FUNC2) {
3763 if (pte->size_buff_entry <= 1) {
3764 keycode = KEY_FUNC3;
3765 } else {
3766 pte->size_buff_entry -= 2;
3767 keycode = pte->buff_entry[pte->size_buff_entry] + 0x10;
3768 }
3769 }
3770 if ((keycode >= KEY_0) && (keycode <= KEY_9)) {
3771 char tmpbuf[] = SELECTCODEC_MSG;
3772 int i = 0;
3773
3774 if (pte->size_buff_entry >= SELECTCODEC_MAX_LENGTH) {
3775 return;
3776 }
3777 while (i < pte->size_buff_entry) {
3778 tmpbuf[i + SELECTCODEC_START_ENTRY_POS] = pte->buff_entry[i];
3779 i++;
3780 }
3781 tmpbuf[i + SELECTCODEC_START_ENTRY_POS] = keycode - 0x10;
3782 pte->buff_entry[i] = keycode - 0x10;
3783 pte->size_buff_entry++;
3784 send_text(TEXT_LINE2, TEXT_INVERSE, pte, tmpbuf);
3785 send_blink_cursor(pte);
3786 send_cursor_pos(pte,
3787 (unsigned char) (TEXT_LINE2 + SELECTCODEC_START_ENTRY_POS + 1 + i));
3788 return;
3789 }
3790
3791 switch (keycode) {
3792 case KEY_FUNC1:
3793 if (pte->size_buff_entry == 1) {
3794 pte->device->codec_number = pte->buff_entry[0] - 48;
3795 } else if (pte->size_buff_entry == 2) {
3796 pte->device->codec_number =
3797 ((pte->buff_entry[0] - 48) * 10) + (pte->buff_entry[1] - 48);
3798 }
3799 show_main_page(pte);
3800 break;
3801 case KEY_FUNC3:
3802 pte->size_buff_entry = 0;
3803 send_text(TEXT_LINE2, TEXT_INVERSE, pte, SELECTCODEC_MSG);
3804 send_blink_cursor(pte);
3805 send_cursor_pos(pte, TEXT_LINE2 + SELECTCODEC_START_ENTRY_POS);
3806 break;
3807 case KEY_HANGUP:
3808 case KEY_FUNC4:
3809 show_main_page(pte);
3810 break;
3811 }
3812 return;
3813 }
3814
3815 static int find_language(const char* lang)
3816 {
3817 int i = 0;
3818 while (options_languages[i].lang_short != NULL) {
3819 if(!strcmp(options_languages[i].lang_short, lang)) {
3820 return i;
3821 }
3822 i++;
3823 }
3824 return 0;
3825 }
3826
3827 static void handle_select_language(struct unistimsession *pte)
3828 {
3829 char tmp_language[40];
3830 struct unistim_languages lang;
3831
3832 if (pte->state != STATE_SELECTLANGUAGE) {
3833 pte->state = STATE_SELECTLANGUAGE;
3834 pte->size_buff_entry = 1;
3835 pte->buff_entry[0] = find_language(pte->device->language);
3836 }
3837 lang = options_languages[(int)pte->buff_entry[0]];
3838 ast_copy_string(tmp_language, pte->device->language, sizeof(tmp_language));
3839 ast_copy_string(pte->device->language, lang.lang_short, sizeof(pte->device->language));
3840 send_charset_update(pte, lang.encoding);
3841 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext(lang.label, pte));
3842
3843 ast_copy_string(pte->device->language, tmp_language, sizeof(pte->device->language));
3844 lang = options_languages[find_language(pte->device->language)];
3845 send_charset_update(pte, lang.encoding);
3846 send_text_status(pte, ustmtext("Select Cancel", pte));
3847 return;
3848 }
3849
3850 static void key_select_language(struct unistimsession *pte, char keycode)
3851 {
3852 switch (keycode) {
3853 case KEY_DOWN:
3854 pte->buff_entry[0]++;
3855 if (options_languages[(int)pte->buff_entry[0]].label == NULL) {
3856 pte->buff_entry[0]--;
3857 }
3858 break;
3859 case KEY_UP:
3860 if (pte->buff_entry[0] > 0) {
3861 pte->buff_entry[0]--;
3862 }
3863 break;
3864 case KEY_FUNC1:
3865 ast_copy_string(pte->device->language, options_languages[(int)pte->buff_entry[0]].lang_short, sizeof(pte->device->language));
3866 send_charset_update(pte, options_languages[(int)pte->buff_entry[0]].encoding);
3867 refresh_all_favorite(pte);
3868 show_main_page(pte);
3869 return;
3870 case KEY_HANGUP:
3871 case KEY_FUNC4:
3872 handle_select_option(pte);
3873 return;
3874 }
3875
3876 handle_select_language(pte);
3877 return;
3878 }
3879
3880
3881 #define SELECTEXTENSION_START_ENTRY_POS 0
3882 #define SELECTEXTENSION_MAX_LENGTH 10
3883 #define SELECTEXTENSION_MSG ".........."
3884 static void show_extension_page(struct unistimsession *pte)
3885 {
3886 pte->state = STATE_EXTENSION;
3887
3888 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Please enter a Terminal", pte));
3889 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("Number (TN) :", pte));
3890 send_text(TEXT_LINE2, TEXT_NORMAL, pte, SELECTEXTENSION_MSG);
3891 send_blink_cursor(pte);
3892 send_cursor_pos(pte, TEXT_LINE2 + SELECTEXTENSION_START_ENTRY_POS);
3893 send_text_status(pte, ustmtext("Enter BackSpcErase", pte));
3894 pte->size_buff_entry = 0;
3895 return;
3896 }
3897
3898 static void key_select_extension(struct unistimsession *pte, char keycode)
3899 {
3900 if (keycode == KEY_FUNC2) {
3901 if (pte->size_buff_entry <= 1) {
3902 keycode = KEY_FUNC3;
3903 } else {
3904 pte->size_buff_entry -= 2;
3905 keycode = pte->buff_entry[pte->size_buff_entry] + 0x10;
3906 }
3907 }
3908 if ((keycode >= KEY_0) && (keycode <= KEY_9)) {
3909 char tmpbuf[] = SELECTEXTENSION_MSG;
3910 int i = 0;
3911
3912 if (pte->size_buff_entry >= SELECTEXTENSION_MAX_LENGTH) {
3913 return;
3914 }
3915 while (i < pte->size_buff_entry) {
3916 tmpbuf[i + SELECTEXTENSION_START_ENTRY_POS] = pte->buff_entry[i];
3917 i++;
3918 }
3919 tmpbuf[i + SELECTEXTENSION_START_ENTRY_POS] = keycode - 0x10;
3920 pte->buff_entry[i] = keycode - 0x10;
3921 pte->size_buff_entry++;
3922 send_text(TEXT_LINE2, TEXT_NORMAL, pte, tmpbuf);
3923 send_blink_cursor(pte);
3924 send_cursor_pos(pte, (unsigned char) (TEXT_LINE2 + SELECTEXTENSION_START_ENTRY_POS + 1 + i));
3925 return;
3926 }
3927
3928 switch (keycode) {
3929 case KEY_FUNC1:
3930 if (pte->size_buff_entry < 1) {
3931 return;
3932 }
3933 if (autoprovisioning == AUTOPROVISIONING_TN) {
3934 struct unistim_device *d;
3935
3936 /* First step : looking for this TN in our device list */
3937 ast_mutex_lock(&devicelock);
3938 d = devices;
3939 pte->buff_entry[pte->size_buff_entry] = '\0';
3940 while (d) {
3941 if (d->id[0] == 'T') { /* It's a TN device ? */
3942 /* It's the TN we're looking for ? */
3943 if (!strcmp((d->id) + 1, pte->buff_entry)) {
3944 pte->device = d;
3945 d->session = pte;
3946 d->codec_number = DEFAULT_CODEC;
3947 d->missed_call = 0;
3948 d->receiver_state = STATE_ONHOOK;
3949 strcpy(d->id, pte->macaddr);
3950 pte->device->extension_number[0] = 'T';
3951 pte->device->extension = EXTENSION_TN;
3952 ast_copy_string((pte->device->extension_number) + 1,
3953 pte->buff_entry, pte->size_buff_entry + 1);
3954 ast_mutex_unlock(&devicelock);
3955 show_main_page(pte);
3956 refresh_all_favorite(pte);
3957 return;
3958 }
3959 }
3960 d = d->next;
3961 }
3962 ast_mutex_unlock(&devicelock);
3963 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Invalid Terminal Number.", pte));
3964 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("Please try again :", pte));
3965 send_cursor_pos(pte, (unsigned char) (TEXT_LINE2 + SELECTEXTENSION_START_ENTRY_POS +
3966 pte->size_buff_entry));
3967 send_blink_cursor(pte);
3968 } else {
3969 ast_copy_string(pte->device->extension_number, pte->buff_entry,
3970 pte->size_buff_entry + 1);
3971 if (register_extension(pte)) {
3972 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Invalid extension.", pte));
3973 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("Please try again :", pte));
3974 send_cursor_pos(pte, (unsigned char) (TEXT_LINE2 +
3975 SELECTEXTENSION_START_ENTRY_POS +
3976 pte->size_buff_entry));
3977 send_blink_cursor(pte);
3978 } else
3979 show_main_page(pte);
3980 }
3981 break;
3982 case KEY_FUNC3:
3983 pte->size_buff_entry = 0;
3984 send_text(TEXT_LINE2, TEXT_NORMAL, pte, SELECTEXTENSION_MSG);
3985 send_blink_cursor(pte);
3986 send_cursor_pos(pte, TEXT_LINE2 + SELECTEXTENSION_START_ENTRY_POS);
3987 break;
3988 }
3989 return;
3990 }
3991
3992 static void show_entry_history(struct unistimsession *pte, FILE ** f)
3993 {
3994 char line[TEXT_LENGTH_MAX + 1], status[STATUS_LENGTH_MAX + 1], func1[10], func2[10],
3995 func3[10];
3996
3997 /* Display date/time and call status */
3998 if (fread(line, TEXT_LENGTH_MAX, 1, *f) != 1) {
3999 display_last_error("Can't read history date entry");
4000 fclose(*f);
4001 return;
4002 }
4003 line[sizeof(line) - 1] = '\0';
4004 if (pte->device->height == 1) {
4005 if (pte->buff_entry[3] == 1) {
4006 send_text(TEXT_LINE0, TEXT_NORMAL, pte, line);
4007 }
4008 } else {
4009 send_text(TEXT_LINE0, TEXT_NORMAL, pte, line);
4010 }
4011 /* Display number */
4012 if (fread(line, TEXT_LENGTH_MAX, 1, *f) != 1) {
4013 display_last_error("Can't read callerid entry");
4014 fclose(*f);
4015 return;
4016 }
4017 line[sizeof(line) - 1] = '\0';
4018 ast_copy_string(pte->device->lst_cid, line, sizeof(pte->device->lst_cid));
4019 ast_trim_blanks(pte->device->lst_cid);
4020 if (pte->device->height == 1) {
4021 if (pte->buff_entry[3] == 2) {
4022 send_text(TEXT_LINE0, TEXT_NORMAL, pte, line);
4023 }
4024 } else {
4025 send_text(TEXT_LINE1, TEXT_NORMAL, pte, line);
4026 }
4027 /* Display name */
4028 if (fread(line, TEXT_LENGTH_MAX, 1, *f) != 1) {
4029 display_last_error("Can't read callername entry");
4030 fclose(*f);
4031 return;
4032 }
4033 line[sizeof(line) - 1] = '\0';
4034 if (pte->device->height == 1) {
4035 if (pte->buff_entry[3] == 3) {
4036 send_text(TEXT_LINE0, TEXT_NORMAL, pte, line);
4037 }
4038 } else {
4039 send_text(TEXT_LINE2, TEXT_NORMAL, pte, line);
4040 }
4041 fclose(*f);
4042
4043 snprintf(line, sizeof(line), "%s %03d/%03d", ustmtext("Call", pte), pte->buff_entry[2],
4044 pte->buff_entry[1]);
4045 send_texttitle(pte, line);
4046
4047 if (pte->buff_entry[2] == 1) {
4048 ast_copy_string(func1, " ", sizeof(func1));
4049 } else {
4050 ast_copy_string(func1, ustmtext("Prev ", pte), sizeof(func1));
4051 }
4052 if (pte->buff_entry[2] >= pte->buff_entry[1]) {
4053 ast_copy_string(func2, " ", sizeof(func2));
4054 } else {
4055 ast_copy_string(func2, ustmtext("Next ", pte), sizeof(func2));
4056 }
4057 if (strlen(pte->device->lst_cid)) {
4058 ast_copy_string(func3, ustmtext("Redial ", pte), sizeof(func3));
4059 } else {
4060 ast_copy_string(func3, " ", sizeof(func3));
4061 }
4062 snprintf(status, sizeof(status), "%s%s%s%s", func1, func2, func3, ustmtext("Cancel", pte));
4063 send_text_status(pte, status);
4064 }
4065
4066 static char open_history(struct unistimsession *pte, char way, FILE ** f)
4067 {
4068 char tmp[AST_CONFIG_MAX_PATH];
4069 char count;
4070
4071 snprintf(tmp, sizeof(tmp), "%s/%s/%s-%c.csv", ast_config_AST_LOG_DIR,
4072 USTM_LOG_DIR, pte->device->name, way);
4073 *f = fopen(tmp, "r");
4074 if (!*f) {
4075 display_last_error("Unable to open history file");
4076 return 0;
4077 }
4078 if (fread(&count, 1, 1, *f) != 1) {
4079 display_last_error("Unable to read history header - display.");
4080 fclose(*f);
4081 *f = NULL;
4082 return 0;
4083 }
4084 if (count > MAX_ENTRY_LOG) {
4085 ast_log(LOG_WARNING, "Invalid count in history header of %s (%d max %d)\n", tmp,
4086 count, MAX_ENTRY_LOG);
4087 fclose(*f);
4088 *f = NULL;
4089 return 0;
4090 }
4091 return count;
4092 }
4093
4094 static void show_history(struct unistimsession *pte, char way)
4095 {
4096 FILE *f;
4097 char count;
4098
4099 if (!pte->device) {
4100 return;
4101 }
4102 if (!pte->device->callhistory) {
4103 return;
4104 }
4105 count = open_history(pte, way, &f);
4106 if (!count) {
4107 return;
4108 }
4109 pte->buff_entry[0] = way;
4110 pte->buff_entry[1] = count;
4111 pte->buff_entry[2] = 1;
4112 pte->buff_entry[3] = 1;
4113 show_entry_history(pte, &f);
4114 pte->state = STATE_HISTORY;
4115 }
4116
4117 static void show_main_page(struct unistimsession *pte)
4118 {
4119 char tmpbuf[TEXT_LENGTH_MAX + 1];
4120 const char *text;
4121
4122 if ((pte->device->extension == EXTENSION_ASK) &&
4123 (ast_strlen_zero(pte->device->extension_number))) {
4124 show_extension_page(pte);
4125 return;
4126 }
4127
4128 pte->state = STATE_MAINPAGE;
4129 send_led_update(pte, LED_BAR_OFF);
4130 pte->device->lastmsgssent = -1;
4131
4132 send_tone(pte, 0, 0);
4133 send_stop_timer(pte); /* case of holding call */
4134 send_select_output(pte, pte->device->output, pte->device->volume, MUTE_ON_DISCRET);
4135 send_led_update(pte, LED_SPEAKER_OFF);
4136 send_led_update(pte, LED_HEADPHONE_OFF);
4137
4138 if (!ast_strlen_zero(pte->device->call_forward)) {
4139 if (pte->device->height == 1) {
4140 char tmp_field[100];
4141 snprintf(tmp_field, sizeof(tmp_field), "%s %s", ustmtext("Fwd to:", pte), pte->device->call_forward);
4142 send_text(TEXT_LINE0, TEXT_NORMAL, pte, tmp_field);
4143 } else {
4144 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Call forwarded to :", pte));
4145 send_text(TEXT_LINE1, TEXT_NORMAL, pte, pte->device->call_forward);
4146 }
4147 send_icon(TEXT_LINE0, FAV_ICON_REFLECT + FAV_BLINK_SLOW, pte);
4148 if (ast_strlen_zero(pte->device->redial_number)) {
4149 send_text_status(pte, ustmtext("Dial NoFwd ", pte));
4150 } else {
4151 send_text_status(pte, ustmtext("Dial Redial NoFwd ", pte));
4152 }
4153 } else {
4154 if ((pte->device->extension == EXTENSION_ASK) || (pte->device->extension == EXTENSION_TN)) {
4155 if (ast_strlen_zero(pte->device->redial_number)) {
4156 send_text_status(pte, ustmtext("Dial Fwd Unregis", pte));
4157 } else {
4158 send_text_status(pte, ustmtext("Dial Redial Fwd Unregis", pte));
4159 }
4160 } else {
4161 if (ast_strlen_zero(pte->device->redial_number)) {
4162 send_text_status(pte, ustmtext("Dial Fwd Pickup", pte));
4163 } else {
4164 send_text_status(pte, ustmtext("Dial Redial Fwd Pickup", pte));
4165 }
4166 }
4167 send_text(TEXT_LINE1, TEXT_NORMAL, pte, pte->device->maintext1);
4168 if (pte->device->missed_call == 0) {
4169 send_date_time2(pte);
4170 send_idle_clock(pte);
4171 if (strlen(pte->device->maintext0)) {
4172 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext(pte->device->maintext0, pte));
4173 }
4174 } else {
4175 if (pte->device->missed_call == 1) {
4176 text = ustmtext("unanswered call", pte);
4177 } else {
4178 text = ustmtext("unanswered calls", pte);
4179 }
4180 snprintf(tmpbuf, sizeof(tmpbuf), "%d %s", pte->device->missed_call, text);
4181 send_text(TEXT_LINE0, TEXT_NORMAL, pte, tmpbuf);
4182 send_icon(TEXT_LINE0, FAV_ICON_CALL_CENTER + FAV_BLINK_SLOW, pte);
4183 }
4184 }
4185 if (pte->device->height > 1) {
4186 if (ast_strlen_zero(pte->device->maintext2)) {
4187 strcpy(tmpbuf, "IP : ");
4188 strcat(tmpbuf, ast_inet_ntoa(pte->sin.sin_addr));
4189 send_text(TEXT_LINE2, TEXT_NORMAL, pte, tmpbuf);
4190 } else {
4191 send_text(TEXT_LINE2, TEXT_NORMAL, pte, ustmtext(pte->device->maintext2, pte));
4192 }
4193 }
4194
4195 send_texttitle(pte, ustmtext(pte->device->titledefault, pte));
4196 change_favorite_icon(pte, FAV_LINE_ICON);
4197 }
4198
4199 static void key_main_page(struct unistimsession *pte, char keycode)
4200 {
4201 if (pte->device->missed_call) {
4202 send_icon(TEXT_LINE0, FAV_ICON_NONE, pte);
4203 pte->device->missed_call = 0;
4204 }
4205 if ((keycode >= KEY_0) && (keycode <= KEY_SHARP)) {
4206 handle_dial_page(pte);
4207 key_dial_page(pte, keycode);
4208 return;
4209 }
4210 switch (keycode) {
4211 case KEY_FUNC1:
4212 pte->device->selected = get_avail_softkey(pte, NULL);
4213 handle_dial_page(pte);
4214 break;
4215 case KEY_FUNC2:
4216 if (ast_strlen_zero(pte->device->redial_number)) {
4217 break;
4218 }
4219 if ((pte->device->output == OUTPUT_HANDSET) &&
4220 (pte->device->receiver_state == STATE_ONHOOK)) {
4221 send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
4222 } else {
4223 send_select_output(pte, pte->device->output, pte->device->volume, MUTE_OFF);
4224 }
4225 ast_copy_string(pte->device->phone_number, pte->device->redial_number,
4226 sizeof(pte->device->phone_number));
4227 handle_call_outgoing(pte);
4228 break;
4229 case KEY_FUNC3:
4230 if (!ast_strlen_zero(pte->device->call_forward)) {
4231 /* Cancel call forwarding */
4232 memmove(pte->device->call_forward + 1, pte->device->call_forward,
4233 sizeof(pte->device->call_forward) - 1);
4234 pte->device->call_forward[0] = '\0';
4235 send_icon(TEXT_LINE0, FAV_ICON_NONE, pte);
4236 pte->device->output = OUTPUT_HANDSET; /* Seems to be reset somewhere */
4237 show_main_page(pte);
4238 break;
4239 }
4240 pte->device->call_forward[0] = -1;
4241 handle_dial_page(pte);
4242 break;
4243 case KEY_FUNC4:
4244 if (pte->device->extension == EXTENSION_ASK) {
4245 unregister_extension(pte);
4246 pte->device->extension_number[0] = '\0';
4247 show_extension_page(pte);
4248 } else if (pte->device->extension == EXTENSION_TN) {
4249 ast_mutex_lock(&devicelock);
4250 strcpy(pte->device->id, pte->device->extension_number);
4251 pte->buff_entry[0] = '\0';
4252 pte->size_buff_entry = 0;
4253 pte->device->session = NULL;
4254 pte->device = NULL;
4255 ast_mutex_unlock(&devicelock);
4256 show_extension_page(pte);
4257 } else { /* Pickup function */
4258 /* XXX Is there a way to get a specific channel here? */
4259 RAII_VAR(struct ast_features_pickup_config *, pickup_cfg,
4260 ast_get_chan_features_pickup_config(NULL), ao2_cleanup);
4261
4262 if (!pickup_cfg) {
4263 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
4264 break;
4265 }
4266
4267 pte->device->selected = -1;
4268 ast_copy_string(pte->device->phone_number, pickup_cfg->pickupexten,
4269 sizeof(pte->device->phone_number));
4270 handle_call_outgoing(pte);
4271 }
4272 break;
4273 case KEY_FAV0:
4274 case KEY_FAV1:
4275 case KEY_FAV2:
4276 case KEY_FAV3:
4277 case KEY_FAV4:
4278 case KEY_FAV5:
4279 handle_key_fav(pte, keycode);
4280 break;
4281 case KEY_CONF:
4282 handle_select_option(pte);
4283 break;
4284 case KEY_LOUDSPK:
4285 send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
4286 handle_dial_page(pte);
4287 break;
4288 case KEY_HEADPHN:
4289 send_select_output(pte, OUTPUT_HEADPHONE, pte->device->volume, MUTE_OFF);
4290 handle_dial_page(pte);
4291 break;
4292 case KEY_SNDHIST:
4293 show_history(pte, 'o');
4294 break;
4295 case KEY_RCVHIST:
4296 show_history(pte, 'i');
4297 break;
4298 }
4299 return;
4300 }
4301
4302 static void key_history(struct unistimsession *pte, char keycode)
4303 {
4304 FILE *f;
4305 char count;
4306 long offset;
4307 int flag = 0;
4308
4309 switch (keycode) {
4310 case KEY_LEFT:
4311 if (pte->device->height == 1) {
4312 if (pte->buff_entry[3] <= 1) {
4313 return;
4314 }
4315 pte->buff_entry[3]--;
4316 flag = 1;
4317 break;
4318 }
4319 case KEY_UP:
4320 case KEY_FUNC1:
4321 if (pte->buff_entry[2] <= 1) {
4322 return;
4323 }
4324 pte->buff_entry[2]--;
4325 flag = 1;
4326 break;
4327 case KEY_RIGHT:
4328 if (pte->device->height == 1) {
4329 if (pte->buff_entry[3] == 3) {
4330 return;
4331 }
4332 pte->buff_entry[3]++;
4333 flag = 1;
4334 break;
4335 }
4336 case KEY_DOWN:
4337 case KEY_FUNC2:
4338 if (pte->buff_entry[2] >= pte->buff_entry[1]) {
4339 return;
4340 }
4341 pte->buff_entry[2]++;
4342 flag = 1;
4343 break;
4344 case KEY_FUNC3:
4345 if (ast_strlen_zero(pte->device->lst_cid)) {
4346 break;
4347 }
4348 ast_copy_string(pte->device->redial_number, pte->device->lst_cid,
4349 sizeof(pte->device->redial_number));
4350 key_main_page(pte, KEY_FUNC2);
4351 break;
4352 case KEY_FUNC4:
4353 case KEY_HANGUP:
4354 show_main_page(pte);
4355 break;
4356 case KEY_SNDHIST:
4357 if (pte->buff_entry[0] == 'i') {
4358 show_history(pte, 'o');
4359 } else {
4360 show_main_page(pte);
4361 }
4362 break;
4363 case KEY_RCVHIST:
4364 if (pte->buff_entry[0] == 'i') {
4365 show_main_page(pte);
4366 } else {
4367 show_history(pte, 'i');
4368 }
4369 break;
4370 }
4371
4372 if (flag) {
4373 count = open_history(pte, pte->buff_entry[0], &f);
4374 if (!count) {
4375 return;
4376 }
4377 offset = ((pte->buff_entry[2] - 1) * TEXT_LENGTH_MAX * 3);
4378 if (fseek(f, offset, SEEK_CUR)) {
4379 display_last_error("Unable to seek history entry.");
4380 fclose(f);
4381 return;
4382 }
4383 show_entry_history(pte, &f);
4384 }
4385
4386 return;
4387 }
4388
4389 static void init_phone_step2(struct unistimsession *pte)
4390 {
4391 BUFFSEND;
4392 if (unistimdebug) {
4393 ast_verb(0, "Sending S4\n");
4394 }
4395 memcpy(buffsend + SIZE_HEADER, packet_send_s4, sizeof(packet_send_s4));
4396 send_client(SIZE_HEADER + sizeof(packet_send_s4), buffsend, pte);
4397 send_date_time2(pte);
4398 send_date_time3(pte);
4399 if (unistimdebug) {
4400 ast_verb(0, "Sending S7\n");
4401 }
4402 memcpy(buffsend + SIZE_HEADER, packet_send_S7, sizeof(packet_send_S7));
4403 send_client(SIZE_HEADER + sizeof(packet_send_S7), buffsend, pte);
4404 if (unistimdebug) {
4405 ast_verb(0, "Sending Contrast\n");
4406 }
4407 memcpy(buffsend + SIZE_HEADER, packet_send_Contrast, sizeof(packet_send_Contrast));
4408 if (pte->device != NULL) {
4409 buffsend[9] = pte->device->contrast;
4410 }
4411 send_client(SIZE_HEADER + sizeof(packet_send_Contrast), buffsend, pte);
4412
4413 if (unistimdebug) {
4414 ast_verb(0, "Sending S9\n");
4415 }
4416 memcpy(buffsend + SIZE_HEADER, packet_send_s9, sizeof(packet_send_s9));
4417 send_client(SIZE_HEADER + sizeof(packet_send_s9), buffsend, pte);
4418 send_no_ring(pte);
4419
4420 if (unistimdebug) {
4421 ast_verb(0, "Sending S7\n");
4422 }
4423 memcpy(buffsend + SIZE_HEADER, packet_send_S7, sizeof(packet_send_S7));
4424 send_client(SIZE_HEADER + sizeof(packet_send_S7), buffsend, pte);
4425 send_led_update(pte, LED_BAR_OFF);
4426 send_ping(pte);
4427 if (unistimdebug) {
4428 ast_verb(0, "Sending init language\n");
4429 }
4430 if (pte->device) {
4431 send_charset_update(pte, options_languages[find_language(pte->device->language)].encoding);
4432 }
4433 if (pte->state < STATE_MAINPAGE) {
4434 if (autoprovisioning == AUTOPROVISIONING_TN) {
4435 show_extension_page(pte);
4436 return;
4437 } else {
4438 int i;
4439 char tmp[30];
4440
4441 for (i = 1; i < FAVNUM; i++) {
4442 send_favorite(i, 0, pte, "");
4443 }
4444 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Phone is not registered", pte));
4445 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("in unistim.conf", pte));
4446 strcpy(tmp, "MAC = ");
4447 strcat(tmp, pte->macaddr);
4448 send_text(TEXT_LINE2, TEXT_NORMAL, pte, tmp);
4449 send_text_status(pte, "");
4450 send_texttitle(pte, ustmtext("UNISTIM for*", pte));
4451 return;
4452 }
4453 }
4454 show_main_page(pte);
4455 refresh_all_favorite(pte);
4456 if (unistimdebug) {
4457 ast_verb(0, "Sending arrow\n");
4458 }
4459 memcpy(buffsend + SIZE_HEADER, packet_send_arrow, sizeof(packet_send_arrow));
4460 send_client(SIZE_HEADER + sizeof(packet_send_arrow), buffsend, pte);
4461 return;
4462 }
4463
4464 /* Toggles the state of microphone muting */
4465 static void microphone_mute_toggle(struct unistimsession *pte)
4466 {
4467 if (pte->device->microphone == MUTE_OFF) {
4468 pte->device->microphone = MUTE_ON;
4469 send_led_update(pte, LED_MUTE_ON);
4470 } else if (pte->device->microphone == MUTE_ON) {
4471 pte->device->microphone = MUTE_OFF;
4472 send_led_update(pte, LED_MUTE_OFF);
4473 }
4474 send_mute(pte, (pte->device->microphone & 0x01));
4475 }
4476
4477 static void process_request(int size, unsigned char *buf, struct unistimsession *pte)
4478 {
4479 char tmpbuf[255];
4480 if (memcmp
4481 (buf + SIZE_HEADER, packet_recv_resume_connection_with_server,
4482 sizeof(packet_recv_resume_connection_with_server)) == 0) {
4483 rcv_resume_connection_with_server(pte);
4484 return;
4485 }
4486 if (memcmp(buf + SIZE_HEADER, packet_recv_firm_version, sizeof(packet_recv_firm_version)) == 0) {
4487 buf[size] = 0;
4488 if (unistimdebug) {
4489 ast_verb(0, "Got the firmware version : '%s'\n", buf + 13);
4490 }
4491 ast_copy_string(pte->firmware, (char *) (buf + 13), sizeof(pte->firmware));
4492 init_phone_step2(pte);
4493 return;
4494 }
4495 if (memcmp(buf + SIZE_HEADER, packet_recv_it_type, sizeof(packet_recv_it_type)) == 0) {
4496 char type = buf[13];
4497 if (unistimdebug) {
4498 ast_verb(0, "Got the equipment type: '%d'\n", type);
4499 }
4500 switch (type) {
4501 case 0x03: /* i2002 */
4502 if (pte->device) {
4503 pte->device->height = 1;
4504 }
4505 break;
4506 }
4507 return;
4508 }
4509 if (memcmp(buf + SIZE_HEADER, packet_recv_mac_addr, sizeof(packet_recv_mac_addr)) == 0) {
4510 rcv_mac_addr(pte, buf);
4511 return;
4512 }
4513 if (memcmp(buf + SIZE_HEADER, packet_recv_r2, sizeof(packet_recv_r2)) == 0) {
4514 if (unistimdebug) {
4515 ast_verb(0, "R2 received\n");
4516 }
4517 return;
4518 }
4519
4520 if (pte->state < STATE_MAINPAGE) {
4521 if (unistimdebug) {
4522 ast_verb(0, "Request not authorized in this state\n");
4523 }
4524 return;
4525 }
4526 if (!memcmp(buf + SIZE_HEADER, packet_recv_expansion_pressed_key, sizeof(packet_recv_expansion_pressed_key))) {
4527 char keycode = buf[13];
4528
4529 if (unistimdebug) {
4530 ast_verb(0, "Expansion key pressed: keycode = 0x%02hhx - current state: %s\n", (unsigned char)keycode,
4531 ptestate_tostr(pte->state));
4532 }
4533 }
4534 if (!memcmp(buf + SIZE_HEADER, packet_recv_pressed_key, sizeof(packet_recv_pressed_key))) {
4535 char keycode = buf[13];
4536
4537 if (unistimdebug) {
4538 ast_verb(0, "Key pressed: keycode = 0x%02hhx - current state: %s\n", (unsigned char)keycode,
4539 ptestate_tostr(pte->state));
4540 }
4541 if (keycode == KEY_MUTE) {
4542 microphone_mute_toggle(pte);
4543 }
4544 switch (pte->state) {
4545 case STATE_INIT:
4546 if (unistimdebug) {
4547 ast_verb(0, "No keys allowed in the init state\n");
4548 }
4549 break;
4550 case STATE_AUTHDENY:
4551 if (unistimdebug) {
4552 ast_verb(0, "No keys allowed in authdeny state\n");
4553 }
4554 break;
4555 case STATE_MAINPAGE:
4556 key_main_page(pte, keycode);
4557 break;
4558 case STATE_DIALPAGE:
4559 key_dial_page(pte, keycode);
4560 break;
4561 case STATE_RINGING:
4562 key_ringing(pte, keycode);
4563 break;
4564 case STATE_CALL:
4565 key_call(pte, keycode);
4566 break;
4567 case STATE_EXTENSION:
4568 key_select_extension(pte, keycode);
4569 break;
4570 case STATE_SELECTOPTION:
4571 key_select_option(pte, keycode);
4572 break;
4573 case STATE_SELECTCODEC:
4574 key_select_codec(pte, keycode);
4575 break;
4576 case STATE_SELECTLANGUAGE:
4577 key_select_language(pte, keycode);
4578 break;
4579 case STATE_HISTORY:
4580 key_history(pte, keycode);
4581 break;
4582 default:
4583 ast_log(LOG_WARNING, "Key : Unknown state\n");
4584 }
4585 return;
4586 }
4587 if (memcmp(buf + SIZE_HEADER, packet_recv_pick_up, sizeof(packet_recv_pick_up)) == 0) {
4588 if (unistimdebug) {
4589 ast_verb(0, "Handset off hook, current state: %s\n", ptestate_tostr(pte->state));
4590 }
4591 if (!pte->device) { /* We are not yet registered (asking for a TN in AUTOPROVISIONING_TN) */
4592 return;
4593 }
4594 pte->device->receiver_state = STATE_OFFHOOK;
4595 if (pte->device->output == OUTPUT_HEADPHONE) {
4596 send_select_output(pte, OUTPUT_HEADPHONE, pte->device->volume, MUTE_OFF);
4597 } else {
4598 send_select_output(pte, OUTPUT_HANDSET, pte->device->volume, MUTE_OFF);
4599 }
4600 if (pte->state == STATE_RINGING) {
4601 handle_call_incoming(pte);
4602 } else if ((pte->state == STATE_DIALPAGE) || (pte->state == STATE_CALL)) {
4603 send_select_output(pte, OUTPUT_HANDSET, pte->device->volume, MUTE_OFF);
4604 } else if (pte->state == STATE_EXTENSION) { /* We must have a TN before calling */
4605 return;
4606 } else {
4607 pte->device->selected = get_avail_softkey(pte, NULL);
4608 send_select_output(pte, OUTPUT_HANDSET, pte->device->volume, MUTE_OFF);
4609 handle_dial_page(pte);
4610 }
4611 return;
4612 }
4613 if (memcmp(buf + SIZE_HEADER, packet_recv_hangup, sizeof(packet_recv_hangup)) == 0) {
4614 if (unistimdebug) {
4615 ast_verb(0, "Handset on hook, current state: %s\n", ptestate_tostr(pte->state));
4616 }
4617 if (!pte->device) {
4618 return;
4619 }
4620 pte->device->receiver_state = STATE_ONHOOK;
4621 if (pte->state == STATE_CALL) {
4622 if (pte->device->output != OUTPUT_SPEAKER) {
4623 close_call(pte);
4624 }
4625 } else if (pte->state == STATE_EXTENSION) {
4626 return;
4627 } else {
4628 pte->device->nextdial = 0;
4629 show_main_page(pte);
4630 }
4631 return;
4632 }
4633 strcpy(tmpbuf, ast_inet_ntoa(pte->sin.sin_addr));
4634 strcat(tmpbuf, " Unknown request packet\n");
4635 if (unistimdebug) {
4636 ast_debug(1, "%s", tmpbuf);
4637 }
4638 return;
4639 }
4640
4641 static void parsing(int size, unsigned char *buf, struct unistimsession *pte,
4642 struct sockaddr_in *addr_from)
4643 {
4644 unsigned short *sbuf = (unsigned short *) buf;
4645 unsigned short seq;
4646 char tmpbuf[255];
4647
4648 strcpy(tmpbuf, ast_inet_ntoa(addr_from->sin_addr));
4649
4650 if (size < 10) {
4651 if (size == 0) {
4652 ast_log(LOG_WARNING, "%s Read error\n", tmpbuf);
4653 } else {
4654 ast_log(LOG_NOTICE, "%s Packet too short - ignoring\n", tmpbuf);
4655 }
4656 return;
4657 }
4658 if (sbuf[0] == 0xffff) { /* Starting with 0xffff ? *//* Yes, discovery packet ? */
4659 if (size != sizeof(packet_rcv_discovery)) {
4660 ast_log(LOG_NOTICE, "%s Invalid size of a discovery packet\n", tmpbuf);
4661 } else {
4662 if (memcmp(buf, packet_rcv_discovery, sizeof(packet_rcv_discovery)) == 0) {
4663 if (unistimdebug) {
4664 ast_verb(0, "Discovery packet received - Sending Discovery ACK\n");
4665 }
4666 if (pte) { /* A session was already active for this IP ? */
4667 if (pte->state == STATE_INIT) { /* Yes, but it's a dupe */
4668 if (unistimdebug) {
4669 ast_verb(1, "Duplicated Discovery packet\n");
4670 }
4671 send_raw_client(sizeof(packet_send_discovery_ack),
4672 packet_send_discovery_ack, addr_from, &pte->sout);
4673 pte->seq_phone = (short) 0x0000; /* reset sequence number */
4674 } else { /* No, probably a reboot, phone side */
4675 close_client(pte); /* Cleanup the previous session */
4676 if (create_client(addr_from)) {
4677 send_raw_client(sizeof(packet_send_discovery_ack),
4678 packet_send_discovery_ack, addr_from, &pte->sout);
4679 }
4680 }
4681 } else {
4682 /* Creating new entry in our phone list */
4683 if ((pte = create_client(addr_from))) {
4684 send_raw_client(sizeof(packet_send_discovery_ack),
4685 packet_send_discovery_ack, addr_from, &pte->sout);
4686 }
4687 }
4688 return;
4689 }
4690 ast_log(LOG_NOTICE, "%s Invalid discovery packet\n", tmpbuf);
4691 }
4692 return;
4693 }
4694 if (!pte) {
4695 if (unistimdebug) {
4696 ast_verb(0, "%s Not a discovery packet from an unknown source : ignoring\n", tmpbuf);
4697 }
4698 return;
4699 }
4700
4701 if (sbuf[0] != 0) { /* Starting with something else than 0x0000 ? */
4702 ast_log(LOG_NOTICE, "Unknown packet received - ignoring\n");
4703 return;
4704 }
4705 if (buf[5] != 2) {
4706 ast_log(LOG_NOTICE, "%s Wrong direction : got 0x%02hhx expected 0x02\n", tmpbuf, buf[5]);
4707 return;
4708 }
4709 seq = ntohs(sbuf[1]);
4710 if (buf[4] == 1) {
4711 ast_mutex_lock(&pte->lock);
4712 if (unistimdebug) {
4713 ast_verb(0, "ACK received for packet #0x%04x\n", (unsigned)seq);
4714 }
4715 pte->nb_retransmit = 0;
4716
4717 if ((pte->last_seq_ack) + 1 == seq) {
4718 pte->last_seq_ack++;
4719 check_send_queue(pte);
4720 ast_mutex_unlock(&pte->lock);
4721 return;
4722 }
4723 if (pte->last_seq_ack > seq) {
4724 if (pte->last_seq_ack == 0xffff) {
4725 ast_verb(0, "ACK at 0xffff, restarting counter.\n");
4726 pte->last_seq_ack = 0;
4727 } else {
4728 ast_log(LOG_NOTICE,
4729 "%s Warning : ACK received for an already ACKed packet : #0x%04x we are at #0x%04x\n",
4730 tmpbuf, (unsigned)seq, (unsigned)pte->last_seq_ack);
4731 }
4732 ast_mutex_unlock(&pte->lock);
4733 return;
4734 }
4735 if (pte->seq_server < seq) {
4736 ast_log(LOG_NOTICE,
4737 "%s Error : ACK received for a non-existent packet : #0x%04x\n",
4738 tmpbuf, (unsigned)pte->seq_server);
4739 ast_mutex_unlock(&pte->lock);
4740 return;
4741 }
4742 if (unistimdebug) {
4743 ast_verb(0, "%s ACK gap : Received ACK #0x%04x, previous was #0x%04x\n",
4744 tmpbuf, (unsigned)seq, (unsigned)pte->last_seq_ack);
4745 }
4746 pte->last_seq_ack = seq;
4747 check_send_queue(pte);
4748 ast_mutex_unlock(&pte->lock);
4749 return;
4750 }
4751 if (buf[4] == 2) {
4752 if (unistimdebug) {
4753 ast_verb(0, "Request received\n");
4754 }
4755 if (pte->seq_phone == seq) {
4756 /* Send ACK */
4757 buf[4] = 1;
4758 buf[5] = 1;
4759 send_raw_client(SIZE_HEADER, buf, addr_from, &pte->sout);
4760 pte->seq_phone++;
4761
4762 process_request(size, buf, pte);
4763 return;
4764 }
4765 if (pte->seq_phone > seq) {
4766 ast_log(LOG_NOTICE,
4767 "%s Warning : received a retransmitted packet : #0x%04x (we are at #0x%04x)\n",
4768 tmpbuf, (unsigned)seq, (unsigned)pte->seq_phone);
4769 /* BUG ? pte->device->seq_phone = seq; */
4770 /* Send ACK */
4771 buf[4] = 1;
4772 buf[5] = 1;
4773 send_raw_client(SIZE_HEADER, buf, addr_from, &pte->sout);
4774 return;
4775 }
4776 ast_log(LOG_NOTICE,
4777 "%s Warning : we lost a packet : received #0x%04x (we are at #0x%04x)\n",
4778 tmpbuf, (unsigned)seq, (unsigned)pte->seq_phone);
4779 return;
4780 }
4781 if (buf[4] == 0) {
4782 ast_log(LOG_NOTICE, "%s Retransmit request for packet #0x%04x\n", tmpbuf, (unsigned)seq);
4783 if (pte->last_seq_ack > seq) {
4784 ast_log(LOG_NOTICE,
4785 "%s Error : received a request for an already ACKed packet : #0x%04x\n",
4786 tmpbuf, (unsigned)pte->last_seq_ack);
4787 return;
4788 }
4789 if (pte->seq_server < seq) {
4790 ast_log(LOG_NOTICE,
4791 "%s Error : received a request for a non-existent packet : #0x%04x\n",
4792 tmpbuf, (unsigned)pte->seq_server);
4793 return;
4794 }
4795 send_retransmit(pte);
4796 return;
4797 }
4798 ast_log(LOG_NOTICE, "%s Unknown request : got 0x%02hhx expected 0x00,0x01 or 0x02\n", tmpbuf, buf[4]);
4799 return;
4800 }
4801
4802 static struct unistimsession *channel_to_session(struct ast_channel *ast)
4803 {
4804 struct unistim_subchannel *sub;
4805 if (!ast) {
4806 ast_log(LOG_WARNING, "Unistim callback function called with a null channel\n");
4807 return NULL;
4808 }
4809 if (!ast_channel_tech_pvt(ast)) {
4810 ast_log(LOG_WARNING, "Unistim callback function called without a tech_pvt\n");
4811 return NULL;
4812 }
4813 sub = ast_channel_tech_pvt(ast);
4814
4815 if (!sub->parent) {
4816 ast_log(LOG_WARNING, "Unistim callback function called without a line\n");
4817 return NULL;
4818 }
4819 if (!sub->parent->parent) {
4820 ast_log(LOG_WARNING, "Unistim callback function called without a device\n");
4821 return NULL;
4822 }
4823 ast_mutex_lock(&sub->parent->parent->lock);
4824 if (!sub->parent->parent->session) {
4825 ast_log(LOG_WARNING, "Unistim callback function called without a session\n");
4826 ast_mutex_unlock(&sub->parent->parent->lock);
4827 return NULL;
4828 }
4829 ast_mutex_unlock(&sub->parent->parent->lock);
4830 return sub->parent->parent->session;
4831 }
4832
4833 static void send_callerid_screen(struct unistimsession *pte, struct unistim_subchannel *sub)
4834 {
4835 char *cidname_str;
4836 char *cidnum_str;
4837
4838 if (!sub) {
4839 return;
4840 }
4841 if (sub->owner) {
4842 if (ast_channel_connected(sub->owner)->id.number.valid && ast_channel_connected(sub->owner)->id.number.str) {
4843 cidnum_str = ast_channel_connected(sub->owner)->id.number.str;
4844 } else {
4845 cidnum_str = DEFAULTCALLERID;
4846 }
4847 change_callerid(pte, 0, cidnum_str);
4848 if (strlen(cidnum_str) == 0) {
4849 cidnum_str = DEFAULTCALLERID;
4850 }
4851
4852 if (ast_channel_connected(sub->owner)->id.name.valid && ast_channel_connected(sub->owner)->id.name.str) {
4853 cidname_str = ast_channel_connected(sub->owner)->id.name.str;
4854 } else {
4855 cidname_str = DEFAULTCALLERNAME;
4856 }
4857 change_callerid(pte, 1, cidname_str);
4858 if (strlen(cidname_str) == 0) {
4859 cidname_str = DEFAULTCALLERNAME;
4860 }
4861
4862 if (pte->device->height == 1) {
4863 char tmpstr[256];
4864 snprintf(tmpstr, sizeof(tmpstr), "%s %s", cidnum_str, ustmtext(cidname_str, pte));
4865 send_text(TEXT_LINE0, TEXT_NORMAL, pte, tmpstr);
4866 } else {
4867 send_text(TEXT_LINE0, TEXT_NORMAL, pte, cidname_str);
4868 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext(cidnum_str, pte));
4869 }
4870 }
4871 }
4872
4873 /*--- unistim_call: Initiate UNISTIM call from PBX ---*/
4874 /* used from the dial() application */
4875 static int unistim_call(struct ast_channel *ast, const char *dest, int timeout)
4876 {
4877 int res = 0, i;
4878 struct unistim_subchannel *sub, *sub_real;
4879 struct unistimsession *session;
4880 signed char ringstyle, ringvolume;
4881
4882 session = channel_to_session(ast);
4883 if (!session) {
4884 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
4885 return -1;
4886 }
4887 sub = ast_channel_tech_pvt(ast);
4888 sub_real = get_sub(session->device, SUB_REAL);
4889 if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
4890 ast_log(LOG_WARNING, "unistim_call called on %s, neither down nor reserved\n",
4891 ast_channel_name(ast));
4892 return -1;
4893 }
4894
4895 if (unistimdebug) {
4896 ast_verb(3, "unistim_call(%s)\n", ast_channel_name(ast));
4897 }
4898 session->state = STATE_RINGING;
4899 send_callerid_screen(session, sub);
4900 if (ast_strlen_zero(ast_channel_call_forward(ast))) { /* Send ring only if no call forward, otherwise short ring will appear */
4901 send_text(TEXT_LINE2, TEXT_NORMAL, session, ustmtext("is calling you.", session));
4902 send_text_status(session, ustmtext("Accept Ignore Hangup", session));
4903
4904 if (sub_real) {
4905 ringstyle = session->device->cwstyle;
4906 ringvolume = session->device->cwvolume;
4907 } else {
4908 ringstyle = (sub->ringstyle == -1) ? session->device->ringstyle : sub->ringstyle;
4909 ringvolume = (sub->ringvolume == -1) ? session->device->ringvolume : sub->ringvolume;
4910 }
4911 send_ring(session, ringvolume, ringstyle);
4912 change_favorite_icon(session, FAV_ICON_SPEAKER_ONHOOK_BLACK + FAV_BLINK_FAST);
4913 /* Send call identification to all */
4914 for (i = 0; i < FAVNUM; i++) {
4915 if (!soft_key_visible(session->device, i)) {
4916 continue;
4917 }
4918 if (session->device->ssub[i]) {
4919 continue;
4920 }
4921 if (is_key_line(session->device, i) && !strcmp(sub->parent->name, session->device->sline[i]->name)) {
4922 if (unistimdebug) {
4923 ast_verb(0, "Found softkey %d for line %s\n", i, sub->parent->name);
4924 }
4925 send_favorite_short(i, FAV_ICON_SPEAKER_ONHOOK_BLACK + FAV_BLINK_FAST, session);
4926 session->device->ssub[i] = sub;
4927 }
4928 }
4929 }
4930 ast_setstate(ast, AST_STATE_RINGING);
4931 ast_queue_control(ast, AST_CONTROL_RINGING);
4932 return res;
4933 }
4934
4935 static int unistim_hangup_clean(struct ast_channel *ast, struct unistim_subchannel *sub) {
4936 ast_mutex_lock(&sub->lock);
4937 ast_channel_tech_pvt_set(ast, NULL);
4938 unistim_set_owner(sub, NULL);
4939 sub->alreadygone = 0;
4940 if (sub->rtp) {
4941 if (unistimdebug) {
4942 ast_verb(0, "Destroying RTP session\n");
4943 }
4944 ast_rtp_instance_stop(sub->rtp);
4945 ast_rtp_instance_destroy(sub->rtp);
4946 sub->rtp = NULL;
4947 }
4948 ast_mutex_unlock(&sub->lock);
4949 return 0;
4950 }
4951
4952 /*--- unistim_hangup: Hangup UNISTIM call */
4953 static int unistim_hangup(struct ast_channel *ast)
4954 {
4955 struct unistim_subchannel *sub = NULL, *sub_real = NULL, *sub_trans = NULL;
4956 struct unistim_line *l;
4957 struct unistim_device *d;
4958 struct unistimsession *s;
4959 int i,end_call = 1;
4960
4961 s = channel_to_session(ast);
4962 sub = ast_channel_tech_pvt(ast);
4963 l = sub->parent;
4964 d = l->parent;
4965 if (!s) {
4966 ast_debug(1, "Asked to hangup channel not connected\n");
4967 unistim_hangup_clean(ast, sub);
4968 return 0;
4969 }
4970 if (unistimdebug) {
4971 ast_verb(0, "unistim_hangup(%s) on %s@%s (STATE_%s)\n", ast_channel_name(ast), l->name, l->parent->name, ptestate_tostr(s->state));
4972 }
4973 sub_trans = get_sub(d, SUB_THREEWAY);
4974 sub_real = get_sub(d, SUB_REAL);
4975 if (sub_trans && (sub_trans->owner) && (sub->subtype == SUB_REAL)) { /* 3rd party busy or congested and transfer_cancel_step2 does not called */
4976 if (unistimdebug) {
4977 ast_verb(0, "Threeway call disconnected, switching to real call\n");
4978 }
4979 ast_queue_unhold(sub_trans->owner);
4980 sub_trans->moh = 0;
4981 sub_trans->subtype = SUB_REAL;
4982 swap_subs(sub_trans, sub);
4983 send_text_status(s, ustmtext(" Transf Hangup", s));
4984 send_callerid_screen(s, sub_trans);
4985 unistim_hangup_clean(ast, sub);
4986 unistim_unalloc_sub(d, sub);
4987 return 0;
4988 }
4989 if (sub_real && (sub_real->owner) && (sub->subtype == SUB_THREEWAY) && (s->state == STATE_CALL)) { /* 3way call cancelled by softkey pressed */
4990 if (unistimdebug) {
4991 ast_verb(0, "Real call disconnected, stay in call\n");
4992 }
4993 send_text_status(s, ustmtext(" Transf Hangup", s));
4994 send_callerid_screen(s, sub_real);
4995 unistim_hangup_clean(ast, sub);
4996 unistim_unalloc_sub(d, sub);
4997 return 0;
4998 }
4999 if (sub->subtype == SUB_REAL) {
5000 sub_stop_silence(s, sub);
5001 } else if (sub->subtype == SUB_RING) {
5002 send_no_ring(s);
5003 for (i = 0; i < FAVNUM; i++) {
5004 if (!soft_key_visible(s->device, i)) {
5005 continue;
5006 }
5007 if (d->ssub[i] != sub) {
5008 if (d->ssub[i] != NULL) { /* Found other subchannel active other than hangup'ed one */
5009 end_call = 0;
5010 }
5011 continue;
5012 }
5013 if (is_key_line(d, i) && !strcmp(l->name, d->sline[i]->name)) {
5014 send_favorite_short(i, FAV_LINE_ICON, s);
5015 d->ssub[i] = NULL;
5016 continue;
5017 }
5018 }
5019 }
5020 if (end_call) {
5021 send_end_call(s); /* Send end call packet only if ending active call, in other way sound should be loosed */
5022 }
5023 sub->moh = 0;
5024 if (sub->softkey >= 0) {
5025 send_favorite_short(sub->softkey, FAV_LINE_ICON, s);
5026 }
5027 /* Delete assign sub to softkey */
5028 for (i = 0; i < FAVNUM; i++) {
5029 if (d->ssub[i] == sub) {
5030 d->ssub[i] = NULL;
5031 break;
5032 }
5033 }
5034 /*refresh_all_favorite(s); */ /* TODO: Update favicons in case of DND keys */
5035 if (s->state == STATE_RINGING && sub->subtype == SUB_RING) {
5036 send_no_ring(s);
5037 if (ast_channel_hangupcause(ast) != AST_CAUSE_ANSWERED_ELSEWHERE) {
5038 d->missed_call++;
5039 write_history(s, 'i', 1);
5040 }
5041 if (!sub_real) {
5042 show_main_page(s);
5043 } else { /* hangup on a ringing line: reset status to reflect that we're still on an active call */
5044 s->state = STATE_CALL;
5045 send_callerid_screen(s, sub_real);
5046 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("is on-line", s));
5047 send_text_status(s, ustmtext(" Transf Hangup", s));
5048 send_favorite_short(sub->softkey, FAV_ICON_OFFHOOK_BLACK, s);
5049
5050 }
5051 }
5052 if (s->state == STATE_CALL && sub->subtype == SUB_REAL) {
5053 close_call(s);
5054 }
5055 sub->softkey = -1;
5056 unistim_hangup_clean(ast, sub);
5057 unistim_unalloc_sub(d, sub);
5058 return 0;
5059 }
5060
5061 /*--- unistim_answer: Answer UNISTIM call */
5062 static int unistim_answer(struct ast_channel *ast)
5063 {
5064 int res = 0;
5065 struct unistim_subchannel *sub;
5066 struct unistim_line *l;
5067 struct unistim_device *d;
5068 struct unistimsession *s;
5069
5070 s = channel_to_session(ast);
5071 if (!s) {
5072 ast_log(LOG_WARNING, "unistim_answer on a disconnected device ?\n");
5073 return -1;
5074 }
5075 sub = ast_channel_tech_pvt(ast);
5076 l = sub->parent;
5077 d = l->parent;
5078
5079 if (unistimdebug) {
5080 ast_verb(0, "unistim_answer(%s) on %s@%s-%d\n", ast_channel_name(ast), l->name,
5081 l->parent->name, sub->softkey);
5082 }
5083 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("is now on-line", s));
5084 if (get_sub(d, SUB_THREEWAY)) {
5085 send_text_status(s, ustmtext("Transf Cancel", s));
5086 } else {
5087 send_text_status(s, ustmtext(" Transf Hangup", s));
5088 }
5089 send_start_timer(s);
5090 if (ast_channel_state(ast) != AST_STATE_UP)
5091 ast_setstate(ast, AST_STATE_UP);
5092 return res;
5093 }
5094
5095 /*--- unistimsock_read: Read data from UNISTIM socket ---*/
5096 /* Successful messages is connected to UNISTIM call and forwarded to parsing() */
5097 static int unistimsock_read(int *id, int fd, short events, void *ignore)
5098 {
5099 struct sockaddr_in addr_from = { 0, };
5100 struct unistimsession *cur = NULL;
5101 int found = 0;
5102 int dw_num_bytes_rcvd;
5103 unsigned int size_addr_from;
5104 #ifdef DUMP_PACKET
5105 int dw_num_bytes_rcvdd;
5106 #endif
5107
5108 size_addr_from = sizeof(addr_from);
5109 dw_num_bytes_rcvd =
5110 recvfrom(unistimsock, buff, SIZE_PAGE, 0, (struct sockaddr *) &addr_from,
5111 &size_addr_from);
5112 if (dw_num_bytes_rcvd == -1) {
5113 if (errno == EAGAIN) {
5114 ast_log(LOG_NOTICE, "UNISTIM: Received packet with bad UDP checksum\n");
5115 } else if (errno != ECONNREFUSED) {
5116 ast_log(LOG_WARNING, "Recv error %d (%s)\n", errno, strerror(errno));
5117 }
5118 return 1;
5119 }
5120
5121 /* Looking in the phone list if we already have a registration for him */
5122 ast_mutex_lock(&sessionlock);
5123 cur = sessions;
5124 while (cur) {
5125 if (cur->sin.sin_addr.s_addr == addr_from.sin_addr.s_addr) {
5126 found = 1;
5127 break;
5128 }
5129 cur = cur->next;
5130 }
5131 ast_mutex_unlock(&sessionlock);
5132
5133 #ifdef DUMP_PACKET
5134 if (unistimdebug)
5135 ast_verb(0, "\n*** Dump %d bytes from %s - phone_table[%d] ***\n",
5136 dw_num_bytes_rcvd, ast_inet_ntoa(addr_from.sin_addr), tmp);
5137 for (dw_num_bytes_rcvdd = 0; dw_num_bytes_rcvdd < dw_num_bytes_rcvd;
5138 dw_num_bytes_rcvdd++)
5139 ast_verb(0, "%02hhx ", buff[dw_num_bytes_rcvdd]);
5140 ast_verb(0, "\n******************************************\n");
5141 #endif
5142
5143 if (!found) {
5144 if (unistimdebug) {
5145 ast_verb(0, "Received a packet from an unknown source\n");
5146 }
5147 parsing(dw_num_bytes_rcvd, buff, NULL, (struct sockaddr_in *) &addr_from);
5148
5149 } else {
5150 parsing(dw_num_bytes_rcvd, buff, cur, (struct sockaddr_in *) &addr_from);
5151 }
5152 return 1;
5153 }
5154
5155 static struct ast_frame *unistim_rtp_read(const struct ast_channel *ast,
5156 const struct unistim_subchannel *sub)
5157 {
5158 /* Retrieve audio/etc from channel. Assumes sub->lock is already held. */
5159 struct ast_frame *f;
5160
5161 if (!ast) {
5162 ast_log(LOG_WARNING, "Channel NULL while reading\n");
5163 return &ast_null_frame;
5164 }
5165
5166 if (!sub->rtp) {
5167 ast_log(LOG_WARNING, "RTP handle NULL while reading on subchannel %u\n",
5168 sub->subtype);
5169 return &ast_null_frame;
5170 }
5171
5172 switch (ast_channel_fdno(ast)) {
5173 case 0:
5174 f = ast_rtp_instance_read(sub->rtp, 0); /* RTP Audio */
5175 break;
5176 case 1:
5177 f = ast_rtp_instance_read(sub->rtp, 1); /* RTCP Control Channel */
5178 break;
5179 default:
5180 f = &ast_null_frame;
5181 }
5182
5183 if (sub->owner) {
5184 /* We already hold the channel lock */
5185 if (f->frametype == AST_FRAME_VOICE) {
5186 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(sub->owner), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
5187 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5188 struct ast_format_cap *caps;
5189
5190 ast_debug(1,
5191 "Oooh, format changed from %s to %s\n",
5192 ast_format_cap_get_names(ast_channel_nativeformats(sub->owner), &cap_buf),
5193 ast_format_get_name(f->subclass.format));
5194
5195 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
5196 if (caps) {
5197 ast_format_cap_append(caps, f->subclass.format, 0);
5198 ast_channel_nativeformats_set(sub->owner, caps);
5199 ao2_ref(caps, -1);
5200 }
5201 ast_set_read_format(sub->owner, ast_channel_readformat(sub->owner));
5202 ast_set_write_format(sub->owner, ast_channel_writeformat(sub->owner));
5203 }
5204 }
5205 }
5206
5207 return f;
5208 }
5209
5210 static struct ast_frame *unistim_read(struct ast_channel *ast)
5211 {
5212 struct ast_frame *fr;
5213 struct unistim_subchannel *sub = ast_channel_tech_pvt(ast);
5214
5215 ast_mutex_lock(&sub->lock);
5216 fr = unistim_rtp_read(ast, sub);
5217 ast_mutex_unlock(&sub->lock);
5218
5219 return fr;
5220 }
5221
5222 static int unistim_write(struct ast_channel *ast, struct ast_frame *frame)
5223 {
5224 struct unistim_subchannel *sub = ast_channel_tech_pvt(ast);
5225 int res = 0;
5226
5227 if (frame->frametype != AST_FRAME_VOICE) {
5228 if (frame->frametype == AST_FRAME_IMAGE) {
5229 return 0;
5230 } else {
5231 ast_log(LOG_WARNING, "Can't send %u type frames with unistim_write\n",
5232 frame->frametype);
5233 return 0;
5234 }
5235 } else {
5236 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
5237 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5238
5239 ast_log(LOG_WARNING,
5240 "Asked to transmit frame type %s, while native formats is %s (read/write = (%s/%s)\n",
5241 ast_format_get_name(frame->subclass.format),
5242 ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
5243 ast_format_get_name(ast_channel_readformat(ast)),
5244 ast_format_get_name(ast_channel_writeformat(ast)));
5245 return -1;
5246 }
5247 }
5248
5249 if (sub) {
5250 ast_mutex_lock(&sub->lock);
5251 if (sub->rtp) {
5252 res = ast_rtp_instance_write(sub->rtp, frame);
5253 }
5254 ast_mutex_unlock(&sub->lock);
5255 }
5256
5257 return res;
5258 }
5259
5260 static int unistim_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
5261 {
5262 struct unistim_subchannel *p = ast_channel_tech_pvt(newchan);
5263 struct unistim_line *l = p->parent;
5264
5265 ast_mutex_lock(&p->lock);
5266
5267 ast_debug(1, "New owner for channel USTM/%s@%s-%u is %s\n", l->name,
5268 l->parent->name, p->subtype, ast_channel_name(newchan));
5269
5270 if (p->owner != oldchan) {
5271 ast_log(LOG_WARNING, "old channel wasn't %s (%p) but was %s (%p)\n",
5272 ast_channel_name(oldchan), oldchan, ast_channel_name(p->owner), p->owner);
5273 ast_mutex_unlock(&p->lock);
5274 return -1;
5275 }
5276
5277 unistim_set_owner(p, newchan);
5278
5279 ast_mutex_unlock(&p->lock);
5280
5281 return 0;
5282
5283 }
5284
5285 static char *control2str(int ind)
5286 {
5287 switch (ind) {
5288 case AST_CONTROL_HANGUP:
5289 return "Other end has hungup";
5290 case AST_CONTROL_RING:
5291 return "Local ring";
5292 case AST_CONTROL_RINGING:
5293 return "Remote end is ringing";
5294 case AST_CONTROL_ANSWER:
5295 return "Remote end has answered";
5296 case AST_CONTROL_BUSY:
5297 return "Remote end is busy";
5298 case AST_CONTROL_TAKEOFFHOOK:
5299 return "Make it go off hook";
5300 case AST_CONTROL_OFFHOOK:
5301 return "Line is off hook";
5302 case AST_CONTROL_CONGESTION:
5303 return "Congestion (circuits busy)";
5304 case AST_CONTROL_FLASH:
5305 return "Flash hook";
5306 case AST_CONTROL_WINK:
5307 return "Wink";
5308 case AST_CONTROL_OPTION:
5309 return "Set a low-level option";
5310 case AST_CONTROL_RADIO_KEY:
5311 return "Key Radio";
5312 case AST_CONTROL_RADIO_UNKEY:
5313 return "Un-Key Radio";
5314 case AST_CONTROL_CONNECTED_LINE:
5315 return "Remote end changed";
5316 case AST_CONTROL_SRCCHANGE:
5317 return "RTP source updated";
5318 case AST_CONTROL_SRCUPDATE:
5319 return "Source of media changed";
5320 case -1:
5321 return "Stop tone";
5322 }
5323 return "UNKNOWN";
5324 }
5325
5326 static void in_band_indication(struct ast_channel *ast, const struct ast_tone_zone *tz,
5327 const char *indication)
5328 {
5329 struct ast_tone_zone_sound *ts = NULL;
5330
5331 if ((ts = ast_get_indication_tone(tz, indication))) {
5332 ast_playtones_start(ast, 0, ts->data, 1);
5333 ts = ast_tone_zone_sound_unref(ts);
5334 } else {
5335 ast_log(LOG_WARNING, "Unable to get indication tone for %s\n", indication);
5336 }
5337 }
5338
5339 static int unistim_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
5340 {
5341 struct unistim_subchannel *sub;
5342 struct unistim_line *l;
5343 struct unistimsession *s;
5344
5345 if (unistimdebug) {
5346 ast_verb(3, "Asked to indicate '%s' (%d) condition on channel %s\n",
5347 control2str(ind), ind, ast_channel_name(ast));
5348 }
5349
5350 s = channel_to_session(ast);
5351 if (!s) {
5352 return -1;
5353 }
5354 sub = ast_channel_tech_pvt(ast);
5355 l = sub->parent;
5356
5357 switch (ind) {
5358 case AST_CONTROL_RINGING:
5359 if (ast_channel_state(ast) != AST_STATE_UP) {
5360 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("Ringing...", s));
5361 in_band_indication(ast, l->parent->tz, "ring");
5362 s->device->missed_call = -1;
5363 break;
5364 }
5365 return -1;
5366 case AST_CONTROL_BUSY:
5367 if (ast_channel_state(ast) != AST_STATE_UP) {
5368 sub->alreadygone = 1;
5369 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("Busy", s));
5370 in_band_indication(ast, l->parent->tz, "busy");
5371 s->device->missed_call = -1;
5372 break;
5373 }
5374 return -1;
5375 case AST_CONTROL_INCOMPLETE:
5376 /* Overlapped dialing is not currently supported for UNIStim. Treat an indication
5377 * of incomplete as congestion
5378 */
5379 case AST_CONTROL_CONGESTION:
5380 if (ast_channel_state(ast) != AST_STATE_UP) {
5381 sub->alreadygone = 1;
5382 send_text(TEXT_LINE2, TEXT_NORMAL, s, ustmtext("Congestion", s));
5383 in_band_indication(ast, l->parent->tz, "congestion");
5384 s->device->missed_call = -1;
5385 break;
5386 }
5387 return -1;
5388 case AST_CONTROL_HOLD:
5389 ast_moh_start(ast, data, NULL);
5390 break;
5391 case AST_CONTROL_UNHOLD:
5392 ast_moh_stop(ast);
5393 break;
5394 case AST_CONTROL_PROGRESS:
5395 case AST_CONTROL_SRCUPDATE:
5396 case AST_CONTROL_PROCEEDING:
5397 case AST_CONTROL_UPDATE_RTP_PEER:
5398 break;
5399 case -1:
5400 ast_playtones_stop(ast);
5401 s->device->missed_call = 0;
5402 break;
5403 case AST_CONTROL_CONNECTED_LINE:
5404 ast_log(LOG_NOTICE, "Connected party is now %s <%s>\n",
5405 S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, ""),
5406 S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, ""));
5407 if (sub->subtype == SUB_REAL) {
5408 send_callerid_screen(s, sub);
5409 }
5410 break;
5411 case AST_CONTROL_SRCCHANGE:
5412 if (sub->rtp) {
5413 ast_rtp_instance_change_source(sub->rtp);
5414 }
5415 break;
5416 default:
5417 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
5418 /* fallthrough */
5419 case AST_CONTROL_PVT_CAUSE_CODE:
5420 case AST_CONTROL_MASQUERADE_NOTIFY:
5421 return -1;
5422 }
5423
5424 return 0;
5425 }
5426
5427 static struct unistim_subchannel *find_subchannel_by_name(const char *dest)
5428 {
5429 struct unistim_line *l;
5430 struct unistim_device *d;
5431 struct unistim_subchannel *sub = NULL;
5432 char line[256];
5433 char *at;
5434 char *device;
5435
5436 ast_copy_string(line, dest, sizeof(line));
5437 at = strchr(line, '@');
5438 if (!at) {
5439 ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
5440 return NULL;
5441 }
5442 *at = '\0';
5443 at++;
5444 device = at;
5445 ast_mutex_lock(&devicelock);
5446 d = devices;
5447 at = strchr(device, '/'); /* Extra options ? */
5448 if (at) {
5449 *at = '\0';
5450 }
5451 while (d) {
5452 if (!strcasecmp(d->name, device)) {
5453 if (unistimdebug) {
5454 ast_verb(0, "Found device: %s\n", d->name);
5455 }
5456 /* Found the device */
5457 AST_LIST_LOCK(&d->lines);
5458 AST_LIST_TRAVERSE(&d->lines, l, list) {
5459 /* Search for the right line */
5460 if (!strcasecmp(l->name, line)) {
5461 if (unistimdebug) {
5462 ast_verb(0, "Found line: %s\n", l->name);
5463 }
5464 sub = get_sub(d, SUB_REAL);
5465 if (!sub) {
5466 sub = unistim_alloc_sub(d, SUB_REAL);
5467 }
5468 if (sub->owner) {
5469 /* Allocate additional channel if asterisk channel already here */
5470 sub = unistim_alloc_sub(d, SUB_REAL);
5471 sub->holding = 1;
5472 }
5473 sub->ringvolume = -1;
5474 sub->ringstyle = -1;
5475 if (at) { /* Other options ? */
5476 at++; /* Skip slash */
5477 if (*at == 'r') { /* distinctive ring */
5478 at++;
5479 if ((*at < '0') || (*at > '7')) { /* ring style */
5480 ast_log(LOG_WARNING, "Invalid ring selection (%s)", at);
5481 } else {
5482 signed char ring_volume = -1;
5483 signed char ring_style = *at - '0';
5484 at++;
5485 if ((*at >= '0') && (*at <= '3')) { /* ring volume */
5486 ring_volume = *at - '0';
5487 }
5488 if (unistimdebug) {
5489 ast_verb(0, "Distinctive ring: style #%d volume %d\n",
5490 ring_style, ring_volume);
5491 }
5492 sub->ringvolume = ring_volume;
5493 sub->ringstyle = ring_style;
5494 }
5495 }
5496 }
5497 sub->parent = l;
5498 break;
5499 }
5500 }
5501 AST_LIST_UNLOCK(&d->lines);
5502 if (sub) {
5503 ast_mutex_unlock(&devicelock);
5504 return sub;
5505 }
5506 }
5507 d = d->next;
5508 }
5509 /* Device not found */
5510 ast_mutex_unlock(&devicelock);
5511
5512 return NULL;
5513 }
5514
5515 static int unistim_senddigit_begin(struct ast_channel *ast, char digit)
5516 {
5517 struct unistimsession *pte = channel_to_session(ast);
5518
5519 if (!pte) {
5520 return -1;
5521 }
5522 return send_dtmf_tone(pte, digit);
5523 }
5524
5525 static int unistim_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
5526 {
5527 struct unistimsession *pte = channel_to_session(ast);
5528
5529 if (!pte) {
5530 return -1;
5531 }
5532
5533 if (unistimdebug) {
5534 ast_verb(0, "Send Digit off %c (duration %d)\n", digit, duration);
5535 }
5536 send_tone(pte, 0, 0);
5537 return 0;
5538 }
5539
5540 /*--- unistim_sendtext: Display a text on the phone screen ---*/
5541 /* Called from PBX core text message functions */
5542 static int unistim_sendtext(struct ast_channel *ast, const char *text)
5543 {
5544 struct unistimsession *pte = channel_to_session(ast);
5545 int size;
5546 char tmp[TEXT_LENGTH_MAX + 1];
5547
5548 if (unistimdebug) {
5549 ast_verb(0, "unistim_sendtext called\n");
5550 }
5551 if (!text) {
5552 ast_log(LOG_WARNING, "unistim_sendtext called with a null text\n");
5553 return -1;
5554 }
5555
5556 if (!pte) {
5557 return -1;
5558 }
5559
5560 size = strlen(text);
5561 if (text[0] == '@') {
5562 int pos = 0, i = 1, tok = 0, sz = 0;
5563 char label[11];
5564 char number[16];
5565 char icon = '\0';
5566 char cur = '\0';
5567
5568 memset(label, 0, 11);
5569 memset(number, 0, 16);
5570 while (text[i]) {
5571 cur = text[i++];
5572 switch (tok) {
5573 case 0:
5574 if ((cur < '0') && (cur > '5')) {
5575 ast_log(LOG_WARNING,
5576 "sendtext failed : position must be a number between 0 and 5\n");
5577 return 1;
5578 }
5579 pos = cur - '0';
5580 tok = 1;
5581 continue;
5582 case 1:
5583 if (cur != '@') {
5584 ast_log(LOG_WARNING, "sendtext failed : invalid position\n");
5585 return 1;
5586 }
5587 tok = 2;
5588 continue;
5589 case 2:
5590 if ((cur < '3') && (cur > '6')) {
5591 ast_log(LOG_WARNING,
5592 "sendtext failed : icon must be a number between 32 and 63 (first digit invalid)\n");
5593 return 1;
5594 }
5595 icon = (cur - '0') * 10;
5596 tok = 3;
5597 continue;
5598 case 3:
5599 if ((cur < '0') && (cur > '9')) {
5600 ast_log(LOG_WARNING,
5601 "sendtext failed : icon must be a number between 32 and 63 (second digit invalid)\n");
5602 return 1;
5603 }
5604 icon += (cur - '0');
5605 tok = 4;
5606 continue;
5607 case 4:
5608 if (cur != '@') {
5609 ast_log(LOG_WARNING,
5610 "sendtext failed : icon must be a number between 32 and 63 (too many digits)\n");
5611 return 1;
5612 }
5613 tok = 5;
5614 continue;
5615 case 5:
5616 if (cur == '@') {
5617 tok = 6;
5618 sz = 0;
5619 continue;
5620 }
5621 if (sz > 10) {
5622 continue;
5623 }
5624 label[sz] = cur;
5625 sz++;
5626 continue;
5627 case 6:
5628 if (sz > 15) {
5629 ast_log(LOG_WARNING,
5630 "sendtext failed : extension too long = %d (15 car max)\n",
5631 sz);
5632 return 1;
5633 }
5634 number[sz] = cur;
5635 sz++;
5636 continue;
5637 }
5638 }
5639 if (tok != 6) {
5640 ast_log(LOG_WARNING, "sendtext failed : incomplet command\n");
5641 return 1;
5642 }
5643 if (!pte->device) {
5644 ast_log(LOG_WARNING, "sendtext failed : no device ?\n");
5645 return 1;
5646 }
5647 strcpy(pte->device->softkeylabel[pos], label);
5648 strcpy(pte->device->softkeynumber[pos], number);
5649 pte->device->softkeyicon[pos] = icon;
5650 send_favorite(pos, icon, pte, label);
5651 return 0;
5652 }
5653
5654 if (size <= TEXT_LENGTH_MAX * 2) {
5655 if (pte->device->height == 1) {
5656 send_text(TEXT_LINE0, TEXT_NORMAL, pte, text);
5657 } else {
5658 send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Message :", pte));
5659 send_text(TEXT_LINE1, TEXT_NORMAL, pte, text);
5660 }
5661 if (size <= TEXT_LENGTH_MAX) {
5662 send_text(TEXT_LINE2, TEXT_NORMAL, pte, "");
5663 return 0;
5664 }
5665 memcpy(tmp, text + TEXT_LENGTH_MAX, TEXT_LENGTH_MAX);
5666 tmp[sizeof(tmp) - 1] = '\0';
5667 send_text(TEXT_LINE2, TEXT_NORMAL, pte, tmp);
5668 return 0;
5669 }
5670 send_text(TEXT_LINE0, TEXT_NORMAL, pte, text);
5671 memcpy(tmp, text + TEXT_LENGTH_MAX, TEXT_LENGTH_MAX);
5672 tmp[sizeof(tmp) - 1] = '\0';
5673 send_text(TEXT_LINE1, TEXT_NORMAL, pte, tmp);
5674 memcpy(tmp, text + TEXT_LENGTH_MAX * 2, TEXT_LENGTH_MAX);
5675 tmp[sizeof(tmp) - 1] = '\0';
5676 send_text(TEXT_LINE2, TEXT_NORMAL, pte, tmp);
5677 return 0;
5678 }
5679
5680 /*--- unistim_send_mwi_to_peer: Send message waiting indication ---*/
5681 static int unistim_send_mwi_to_peer(struct unistim_line *peer, unsigned int tick)
5682 {
5683 int new;
5684 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
5685
5686 msg = stasis_cache_get(ast_mwi_state_cache(), ast_mwi_state_type(), peer->mailbox);
5687 if (msg) {
5688 struct ast_mwi_state *mwi_state = stasis_message_data(msg);
5689 new = mwi_state->new_msgs;
5690 } else { /* Fall back on checking the mailbox directly */
5691 new = ast_app_has_voicemail(peer->mailbox, NULL);
5692 }
5693 ast_debug(3, "MWI Status for mailbox %s is %d, lastmsgsent:%d\n",
5694 peer->mailbox, new, peer->parent->lastmsgssent);
5695 peer->parent->nextmsgcheck = tick + TIMER_MWI;
5696
5697 /* Return now if it's the same thing we told them last time */
5698 if ((peer->parent->session->state != STATE_MAINPAGE) || (new == peer->parent->lastmsgssent)) {
5699 return 0;
5700 }
5701
5702 peer->parent->lastmsgssent = new;
5703 send_led_update(peer->parent->session, (new > 0)?LED_BAR_ON:LED_BAR_OFF);
5704
5705 return 0;
5706 }
5707
5708 /*--- unistim_new: Initiate a call in the UNISTIM channel */
5709 /* called from unistim_request (calls from the pbx ) */
5710 static struct ast_channel *unistim_new(struct unistim_subchannel *sub, int state, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
5711 {
5712 struct ast_format_cap *caps;
5713 struct ast_channel *tmp;
5714 struct unistim_line *l;
5715 struct ast_format *tmpfmt;
5716
5717 if (!sub) {
5718 ast_log(LOG_WARNING, "subchannel null in unistim_new\n");
5719 return NULL;
5720 }
5721 if (!sub->parent) {
5722 ast_log(LOG_WARNING, "no line for subchannel %p\n", sub);
5723 return NULL;
5724 }
5725
5726 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
5727 if (!caps) {
5728 return NULL;
5729 }
5730
5731 l = sub->parent;
5732 tmp = ast_channel_alloc(1, state, l->cid_num, NULL, l->accountcode, l->exten,
5733 l->parent->context, assignedids, requestor, l->amaflags, "USTM/%s@%s-%p", l->name, l->parent->name, sub);
5734 if (unistimdebug) {
5735 ast_verb(0, "unistim_new sub=%u (%p) chan=%p line=%s\n", sub->subtype, sub, tmp, l->name);
5736 }
5737 if (!tmp) {
5738 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
5739 ao2_ref(caps, -1);
5740 return NULL;
5741 }
5742
5743 ast_channel_stage_snapshot(tmp);
5744
5745 if (ast_format_cap_count(l->cap)) {
5746 ast_format_cap_append_from_cap(caps, l->cap, AST_MEDIA_TYPE_UNKNOWN);
5747 } else {
5748 ast_format_cap_append_from_cap(caps, global_cap, AST_MEDIA_TYPE_UNKNOWN);
5749 }
5750 ast_channel_nativeformats_set(tmp, caps);
5751 ao2_ref(caps, -1);
5752
5753 tmpfmt = ast_format_cap_get_format(ast_channel_nativeformats(tmp), 0);
5754
5755 if (unistimdebug) {
5756 struct ast_str *native_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5757 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5758 struct ast_str *global_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5759
5760 ast_verb(0, "Best codec = %s from nativeformats %s (line cap=%s global=%s)\n",
5761 ast_format_get_name(tmpfmt),
5762 ast_format_cap_get_names(ast_channel_nativeformats(tmp), &native_buf),
5763 ast_format_cap_get_names(l->cap, &cap_buf),
5764 ast_format_cap_get_names(global_cap, &global_buf));
5765 }
5766 if ((sub->rtp) && (sub->subtype == 0)) {
5767 if (unistimdebug) {
5768 ast_verb(0, "New unistim channel with a previous rtp handle ?\n");
5769 }
5770 ast_channel_internal_fd_set(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
5771 ast_channel_internal_fd_set(tmp, 1, ast_rtp_instance_fd(sub->rtp, 1));
5772 }
5773 if (sub->rtp) {
5774 ast_jb_configure(tmp, &global_jbconf);
5775 }
5776 /* tmp->type = type; */
5777 ast_setstate(tmp, state);
5778 if (state == AST_STATE_RING) {
5779 ast_channel_rings_set(tmp, 1);
5780 }
5781 ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
5782
5783 ast_channel_set_writeformat(tmp, tmpfmt);
5784 ast_channel_set_rawwriteformat(tmp, tmpfmt);
5785 ast_channel_set_readformat(tmp, tmpfmt);
5786 ast_channel_set_rawreadformat(tmp, tmpfmt);
5787 ao2_ref(tmpfmt, -1);
5788
5789 ast_channel_tech_pvt_set(tmp, sub);
5790 ast_channel_tech_set(tmp, &unistim_tech);
5791
5792 if (!ast_strlen_zero(l->parent->language)) {
5793 ast_channel_language_set(tmp, l->parent->language);
5794 }
5795 unistim_set_owner(sub, tmp);
5796 ast_update_use_count();
5797 ast_channel_callgroup_set(tmp, l->callgroup);
5798 ast_channel_pickupgroup_set(tmp, l->pickupgroup);
5799 ast_channel_call_forward_set(tmp, l->parent->call_forward);
5800 if (!ast_strlen_zero(l->cid_num)) {
5801 char *name, *loc, *instr;
5802 instr = ast_strdup(l->cid_num);
5803 if (instr) {
5804 ast_callerid_parse(instr, &name, &loc);
5805 ast_channel_caller(tmp)->id.number.valid = 1;
5806 ast_free(ast_channel_caller(tmp)->id.number.str);
5807 ast_channel_caller(tmp)->id.number.str = ast_strdup(loc);
5808 ast_channel_caller(tmp)->id.name.valid = 1;
5809 ast_free(ast_channel_caller(tmp)->id.name.str);
5810 ast_channel_caller(tmp)->id.name.str = ast_strdup(name);
5811 ast_free(instr);
5812 }
5813 }
5814 ast_channel_priority_set(tmp, 1);
5815
5816 ast_channel_stage_snapshot_done(tmp);
5817 ast_channel_unlock(tmp);
5818
5819 if (state != AST_STATE_DOWN) {
5820 if (unistimdebug) {
5821 ast_verb(0, "Starting pbx in unistim_new\n");
5822 }
5823 if (ast_pbx_start(tmp)) {
5824 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
5825 ast_hangup(tmp);
5826 tmp = NULL;
5827 }
5828 }
5829
5830 return tmp;
5831 }
5832
5833 static void unistim_set_owner(struct unistim_subchannel *sub, struct ast_channel *chan)
5834 {
5835 sub->owner = chan;
5836 if (sub->rtp) {
5837 ast_rtp_instance_set_channel_id(sub->rtp, sub->owner ? ast_channel_uniqueid(sub->owner) : "");
5838 }
5839 }
5840
5841 static void *do_monitor(void *data)
5842 {
5843 struct unistimsession *cur = NULL;
5844 unsigned int dw_timeout = 0;
5845 unsigned int tick;
5846 int res;
5847 int reloading;
5848
5849 /* Add an I/O event to our UDP socket */
5850 if (unistimsock > -1) {
5851 ast_io_add(io, unistimsock, unistimsock_read, AST_IO_IN, NULL);
5852 }
5853 /* This thread monitors our UDP socket and timers */
5854 for (;;) {
5855 /* This loop is executed at least every IDLE_WAITus (1s) or every time a packet is received */
5856 /* Looking for the smallest time-out value */
5857 tick = get_tick_count();
5858 dw_timeout = UINT_MAX;
5859 ast_mutex_lock(&sessionlock);
5860 cur = sessions;
5861 DEBUG_TIMER("checking timeout for session %p with tick = %u\n", cur, tick);
5862 while (cur) {
5863 DEBUG_TIMER("checking timeout for session %p timeout = %u\n", cur,
5864 cur->timeout);
5865 /* Check if we have miss something */
5866 if (cur->timeout <= tick) {
5867 DEBUG_TIMER("Event for session %p\n", cur);
5868 /* If the queue is empty, send a ping */
5869 if (cur->last_buf_available == 0) {
5870 send_ping(cur);
5871 } else {
5872 if (send_retransmit(cur)) {
5873 DEBUG_TIMER("The chained link was modified, restarting...\n");
5874 cur = sessions;
5875 dw_timeout = UINT_MAX;
5876 continue;
5877 }
5878 }
5879 }
5880 if (dw_timeout > cur->timeout - tick) {
5881 dw_timeout = cur->timeout - tick;
5882 }
5883 /* Checking if the phone is logged on for a new MWI */
5884 if (cur->device) {
5885 struct unistim_line *l;
5886 AST_LIST_LOCK(&cur->device->lines);
5887 AST_LIST_TRAVERSE(&cur->device->lines, l, list) {
5888 if ((!ast_strlen_zero(l->mailbox)) && (tick >= l->parent->nextmsgcheck)) {
5889 DEBUG_TIMER("Checking mailbox for MWI\n");
5890 unistim_send_mwi_to_peer(l, tick);
5891 break;
5892 }
5893 }
5894 AST_LIST_UNLOCK(&cur->device->lines);
5895 if (cur->device->nextdial && tick >= cur->device->nextdial) {
5896 handle_call_outgoing(cur);
5897 cur->device->nextdial = 0;
5898 }
5899 }
5900 cur = cur->next;
5901 }
5902 ast_mutex_unlock(&sessionlock);
5903 DEBUG_TIMER("Waiting for %dus\n", dw_timeout);
5904 res = dw_timeout;
5905 /* We should not wait more than IDLE_WAIT */
5906 if ((res < 0) || (res > IDLE_WAIT)) {
5907 res = IDLE_WAIT;
5908 }
5909 /* Wait for UDP messages for a maximum of res us */
5910 res = ast_io_wait(io, res); /* This function will call unistimsock_read if a packet is received */
5911 /* Check for a reload request */
5912 ast_mutex_lock(&unistim_reload_lock);
5913 reloading = unistim_reloading;
5914 unistim_reloading = 0;
5915 ast_mutex_unlock(&unistim_reload_lock);
5916 if (reloading) {
5917 ast_verb(1, "Reloading unistim.conf...\n");
5918 reload_config();
5919 }
5920 pthread_testcancel();
5921 }
5922 /* Never reached */
5923 return NULL;
5924 }
5925
5926 /*--- restart_monitor: Start the channel monitor thread ---*/
5927 static int restart_monitor(void)
5928 {
5929 pthread_attr_t attr;
5930 /* If we're supposed to be stopped -- stay stopped */
5931 if (monitor_thread == AST_PTHREADT_STOP) {
5932 return 0;
5933 }
5934 if (ast_mutex_lock(&monlock)) {
5935 ast_log(LOG_WARNING, "Unable to lock monitor\n");
5936 return -1;
5937 }
5938 if (monitor_thread == pthread_self()) {
5939 ast_mutex_unlock(&monlock);
5940 ast_log(LOG_WARNING, "Cannot kill myself\n");
5941 return -1;
5942 }
5943 if (monitor_thread != AST_PTHREADT_NULL) {
5944 /* Wake up the thread */
5945 pthread_kill(monitor_thread, SIGURG);
5946 } else {
5947 pthread_attr_init(&attr);
5948 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
5949 /* Start a new monitor */
5950 if (ast_pthread_create(&monitor_thread, &attr, do_monitor, NULL) < 0) {
5951 ast_mutex_unlock(&monlock);
5952 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
5953 return -1;
5954 }
5955 }
5956 ast_mutex_unlock(&monlock);
5957 return 0;
5958 }
5959
5960 /*--- unistim_request: PBX interface function ---*/
5961 /* UNISTIM calls initiated by the PBX arrive here */
5962 static struct ast_channel *unistim_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest,
5963 int *cause)
5964 {
5965 struct unistim_subchannel *sub, *sub_ring, *sub_trans;
5966 struct unistim_device *d;
5967 struct ast_channel *tmpc = NULL;
5968 char tmp[256];
5969
5970 if (!(ast_format_cap_iscompatible(cap, global_cap))) {
5971 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5972 struct ast_str *global_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5973 ast_log(LOG_NOTICE,
5974 "Asked to get a channel of unsupported format %s while capability is %s\n",
5975 ast_format_cap_get_names(cap, &cap_buf),
5976 ast_format_cap_get_names(global_cap, &global_buf));
5977 return NULL;
5978 }
5979
5980 ast_copy_string(tmp, dest, sizeof(tmp));
5981 if (ast_strlen_zero(tmp)) {
5982 ast_log(LOG_NOTICE, "Unistim channels require a device\n");
5983 return NULL;
5984 }
5985 sub = find_subchannel_by_name(tmp);
5986 if (!sub) {
5987 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
5988 *cause = AST_CAUSE_CONGESTION;
5989 return NULL;
5990 }
5991 d = sub->parent->parent;
5992 sub_ring = get_sub(d, SUB_RING);
5993 sub_trans = get_sub(d, SUB_THREEWAY);
5994 /* Another request already in progress */
5995 if (!d->session) {
5996 unistim_unalloc_sub(d, sub);
5997 *cause = AST_CAUSE_CONGESTION;
5998 return NULL;
5999 }
6000 if (sub_ring || sub_trans) {
6001 if (unistimdebug) {
6002 ast_verb(0, "Can't create channel, request already in progress: Busy!\n");
6003 }
6004 unistim_unalloc_sub(d, sub);
6005 *cause = AST_CAUSE_BUSY;
6006 return NULL;
6007 }
6008 if (d->session->state == STATE_DIALPAGE) {
6009 if (unistimdebug) {
6010 ast_verb(0, "Can't create channel, user on dialpage: Busy!\n");
6011 }
6012 unistim_unalloc_sub(d, sub);
6013 *cause = AST_CAUSE_BUSY;
6014 return NULL;
6015 }
6016
6017 if (get_avail_softkey(d->session, sub->parent->name) == -1) {
6018 if (unistimdebug) {
6019 ast_verb(0, "Can't create channel for line %s, all lines busy\n", sub->parent->name);
6020 }
6021 unistim_unalloc_sub(d, sub);
6022 *cause = AST_CAUSE_BUSY;
6023 return NULL;
6024 }
6025 sub->subtype = SUB_RING;
6026 sub->softkey = -1;
6027
6028 ast_format_cap_append_from_cap(sub->parent->cap, cap, AST_MEDIA_TYPE_UNKNOWN);
6029 tmpc = unistim_new(sub, AST_STATE_DOWN, assignedids, requestor);
6030 if (!tmpc) {
6031 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
6032 }
6033 if (unistimdebug) {
6034 ast_verb(0, "unistim_request owner = %p\n", sub->owner);
6035 }
6036 restart_monitor();
6037 /* and finish */
6038 return tmpc;
6039 }
6040
6041 static char *unistim_show_info(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6042 {
6043 struct unistim_device *device = devices;
6044 struct unistim_line *line;
6045 struct unistim_subchannel *sub;
6046 struct unistimsession *s;
6047 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
6048
6049 switch (cmd) {
6050 case CLI_INIT:
6051 e->command = "unistim show info";
6052 e->usage =
6053 "Usage: unistim show info\n"
6054 " Dump internal structures.\n\n"
6055 " device\n"
6056 " ->line\n"
6057 " -->sub\n"
6058 " ==>key\n";
6059 return NULL;
6060
6061 case CLI_GENERATE:
6062 return NULL; /* no completion */
6063 }
6064
6065 if (a->argc != e->args) {
6066 return CLI_SHOWUSAGE;
6067 }
6068 ast_cli(a->fd, "Dumping internal structures:\n");
6069 ast_mutex_lock(&devicelock);
6070 while (device) {
6071 int i;
6072
6073 ast_cli(a->fd, "\nname=%s id=%s ha=%p sess=%p device=%p selected=%d height=%d\n",
6074 device->name, device->id, device->ha, device->session,
6075 device, device->selected, device->height);
6076 AST_LIST_LOCK(&device->lines);
6077 AST_LIST_TRAVERSE(&device->lines,line,list) {
6078 ast_cli(a->fd,
6079 "->name=%s fullname=%s exten=%s callid=%s cap=%s line=%p\n",
6080 line->name, line->fullname, line->exten, line->cid_num,
6081 ast_format_cap_get_names(line->cap, &cap_buf), line);
6082 }
6083 AST_LIST_UNLOCK(&device->lines);
6084
6085 AST_LIST_LOCK(&device->subs);
6086 AST_LIST_TRAVERSE(&device->subs, sub, list) {
6087 if (!sub) {
6088 continue;
6089 }
6090 ast_cli(a->fd,
6091 "-->subtype=%s chan=%p rtp=%p line=%p alreadygone=%d softkey=%d\n",
6092 subtype_tostr(sub->subtype), sub->owner, sub->rtp, sub->parent,
6093 sub->alreadygone, sub->softkey);
6094 }
6095 AST_LIST_UNLOCK(&device->subs);
6096
6097 for (i = 0; i < FAVNUM; i++) {
6098 if (!soft_key_visible(device, i)) {
6099 continue;
6100 }
6101 ast_cli(a->fd, "==> %d. dev=%s icon=%#-4x label=%-10s number=%-5s sub=%p line=%p\n",
6102 i, device->softkeydevice[i], (unsigned)device->softkeyicon[i], device->softkeylabel[i], device->softkeynumber[i],
6103 device->ssub[i], device->sline[i]);
6104 }
6105 device = device->next;
6106 }
6107 ast_mutex_unlock(&devicelock);
6108 ast_cli(a->fd, "\nSessions:\n");
6109 ast_mutex_lock(&sessionlock);
6110 s = sessions;
6111 while (s) {
6112 ast_cli(a->fd,
6113 "sin=%s timeout=%d state=%s macaddr=%s device=%p session=%p\n",
6114 ast_inet_ntoa(s->sin.sin_addr), s->timeout, ptestate_tostr(s->state), s->macaddr,
6115 s->device, s);
6116 s = s->next;
6117 }
6118 ast_mutex_unlock(&sessionlock);
6119
6120 return CLI_SUCCESS;
6121 }
6122
6123 static char *unistim_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6124 {
6125 struct unistim_device *device = devices;
6126
6127 switch (cmd) {
6128 case CLI_INIT:
6129 e->command = "unistim show devices";
6130 e->usage =
6131 "Usage: unistim show devices\n"
6132 " Lists all known Unistim devices.\n";
6133 return NULL;
6134 case CLI_GENERATE:
6135 return NULL; /* no completion */
6136 }
6137
6138 if (a->argc != e->args)
6139 return CLI_SHOWUSAGE;
6140
6141 ast_cli(a->fd, "%-20.20s %-20.20s %-15.15s %-15.15s %s\n", "Name/username", "MAC", "Host", "Firmware", "Status");
6142 ast_mutex_lock(&devicelock);
6143 while (device) {
6144 ast_cli(a->fd, "%-20.20s %-20.20s %-15.15s %-15.15s %s\n",
6145 device->name, device->id,
6146 (!device->session) ? "(Unspecified)" : ast_inet_ntoa(device->session->sin.sin_addr),
6147 (!device->session) ? "(Unspecified)" : device->session->firmware,
6148 (!device->session) ? "UNKNOWN" : "OK");
6149 device = device->next;
6150 }
6151 ast_mutex_unlock(&devicelock);
6152
6153 return CLI_SUCCESS;
6154 }
6155
6156 static char *unistim_sp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6157 {
6158 BUFFSEND;
6159 struct unistim_subchannel *sub;
6160 int i, j = 0, len;
6161 unsigned char c, cc;
6162 char tmp[256];
6163
6164 switch (cmd) {
6165 case CLI_INIT:
6166 e->command = "unistim send packet";
6167 e->usage =
6168 "Usage: unistim send packet USTM/line@name hexa\n"
6169 " unistim send packet USTM/1000@hans 19040004\n";
6170 return NULL;
6171
6172 case CLI_GENERATE:
6173 return NULL; /* no completion */
6174 }
6175
6176 if (a->argc < 5) {
6177 return CLI_SHOWUSAGE;
6178 }
6179 if (strlen(a->argv[3]) < 9) {
6180 return CLI_SHOWUSAGE;
6181 }
6182 len = strlen(a->argv[4]);
6183 if (len % 2) {
6184 return CLI_SHOWUSAGE;
6185 }
6186 ast_copy_string(tmp, a->argv[3] + 5, sizeof(tmp));
6187 sub = find_subchannel_by_name(tmp);
6188 if (!sub) {
6189 ast_cli(a->fd, "Can't find '%s'\n", tmp);
6190 return CLI_SUCCESS;
6191 }
6192 if (!sub->parent->parent->session) {
6193 ast_cli(a->fd, "'%s' is not connected\n", tmp);
6194 return CLI_SUCCESS;
6195 }
6196 ast_cli(a->fd, "Sending '%s' to %s (%p)\n", a->argv[4], tmp, sub->parent->parent->session);
6197 for (i = 0; i < len; i++) {
6198 c = a->argv[4][i];
6199 if (c >= 'a') {
6200 c -= 'a' - 10;
6201 } else {
6202 c -= '0';
6203 }
6204 i++;
6205 cc = a->argv[4][i];
6206 if (cc >= 'a') {
6207 cc -= 'a' - 10;
6208 } else {
6209 cc -= '0';
6210 }
6211 tmp[j++] = (c << 4) | cc;
6212 }
6213 memcpy(buffsend + SIZE_HEADER, tmp, j);
6214 send_client(SIZE_HEADER + j, buffsend, sub->parent->parent->session);
6215 return CLI_SUCCESS;
6216 }
6217
6218 static char *unistim_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6219 {
6220 switch (cmd) {
6221 case CLI_INIT:
6222 e->command = "unistim set debug {on|off}";
6223 e->usage =
6224 "Usage: unistim set debug\n"
6225 " Display debug messages.\n";
6226 return NULL;
6227
6228 case CLI_GENERATE:
6229 return NULL; /* no completion */
6230 }
6231
6232 if (a->argc != e->args) {
6233 return CLI_SHOWUSAGE;
6234 }
6235 if (!strcasecmp(a->argv[3], "on")) {
6236 unistimdebug = 1;
6237 ast_cli(a->fd, "UNISTIM Debugging Enabled\n");
6238 } else if (!strcasecmp(a->argv[3], "off")) {
6239 unistimdebug = 0;
6240 ast_cli(a->fd, "UNISTIM Debugging Disabled\n");
6241 } else {
6242 return CLI_SHOWUSAGE;
6243 }
6244 return CLI_SUCCESS;
6245 }
6246
6247 /*! \brief --- unistim_reload: Force reload of module from cli ---
6248 * Runs in the asterisk main thread, so don't do anything useful
6249 * but setting a flag and waiting for do_monitor to do the job
6250 * in our thread */
6251 static char *unistim_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6252 {
6253 switch (cmd) {
6254 case CLI_INIT:
6255 e->command = "unistim reload";
6256 e->usage =
6257 "Usage: unistim reload\n"
6258 " Reloads UNISTIM configuration from unistim.conf\n";
6259 return NULL;
6260
6261 case CLI_GENERATE:
6262 return NULL; /* no completion */
6263 }
6264
6265 if (e && a && a->argc != e->args) {
6266 return CLI_SHOWUSAGE;
6267 }
6268 reload();
6269
6270 return CLI_SUCCESS;
6271 }
6272
6273 static struct ast_cli_entry unistim_cli[] = {
6274 AST_CLI_DEFINE(unistim_reload, "Reload UNISTIM configuration"),
6275 AST_CLI_DEFINE(unistim_show_info, "Show UNISTIM info"),
6276 AST_CLI_DEFINE(unistim_show_devices, "Show UNISTIM devices"),
6277 AST_CLI_DEFINE(unistim_sp, "Send packet (for reverse engineering)"),
6278 AST_CLI_DEFINE(unistim_do_debug, "Toggle UNITSTIM debugging"),
6279 };
6280
6281 static void unquote(char *out, const char *src, int maxlen)
6282 {
6283 int len = strlen(src);
6284 if (!len) {
6285 return;
6286 }
6287 if ((len > 1) && src[0] == '\"') {
6288 /* This is a quoted string */
6289 src++;
6290 /* Don't take more than what's there */
6291 len--;
6292 if (maxlen > len - 1) {
6293 maxlen = len - 1;
6294 }
6295 memcpy(out, src, maxlen);
6296 ((char *) out)[maxlen] = '\0';
6297 } else {
6298 memcpy(out, src, maxlen);
6299 }
6300 return;
6301 }
6302
6303 static int parse_bookmark(const char *text, struct unistim_device *d)
6304 {
6305 char line[256];
6306 char *at;
6307 char *number;
6308 char *icon;
6309 int p;
6310 int len = strlen(text);
6311
6312 ast_copy_string(line, text, sizeof(line));
6313 /* Position specified ? */
6314 if ((len > 2) && (line[1] == '@')) {
6315 p = line[0];
6316 if ((p >= '0') && (p <= '5')) {
6317 p -= '0';
6318 } else {
6319 ast_log(LOG_WARNING,
6320 "Invalid position for bookmark : must be between 0 and 5\n");
6321 return 0;
6322 }
6323 if (d->softkeyicon[p] != 0) {
6324 ast_log(LOG_WARNING, "Invalid position %d for bookmark : already used:\n", p);
6325 return 0;
6326 }
6327 memmove(line, line + 2, sizeof(line) - 2);
6328 } else {
6329 /* No position specified, looking for a free slot */
6330 for (p = 0; p < FAVNUM; p++) {
6331 if (!d->softkeyicon[p]) {
6332 break;
6333 }
6334 }
6335 if (p == FAVNUM) {
6336 ast_log(LOG_WARNING, "No more free bookmark position\n");
6337 return 0;
6338 }
6339 }
6340 at = strchr(line, '@');
6341 if (!at) {
6342 ast_log(LOG_NOTICE, "Bookmark entry '%s' has no @ (at) sign!\n", text);
6343 return 0;
6344 }
6345 *at = '\0';
6346 at++;
6347 number = at;
6348 at = strchr(at, '@');
6349 if (ast_strlen_zero(number)) {
6350 ast_log(LOG_NOTICE, "Bookmark entry '%s' has no number\n", text);
6351 return 0;
6352 }
6353 if (ast_strlen_zero(line)) {
6354 ast_log(LOG_NOTICE, "Bookmark entry '%s' has no description\n", text);
6355 return 0;
6356 }
6357
6358 at = strchr(number, '@');
6359 if (!at) {
6360 d->softkeyicon[p] = FAV_ICON_SHARP; /* default icon */
6361 } else {
6362 *at = '\0';
6363 at++;
6364 icon = at;
6365 if (ast_strlen_zero(icon)) {
6366 ast_log(LOG_NOTICE, "Bookmark entry '%s' has no icon value\n", text);
6367 return 0;
6368 }
6369 if (strncmp(icon, "USTM/", 5)) {
6370 d->softkeyicon[p] = atoi(icon);
6371 } else {
6372 d->softkeyicon[p] = 1;
6373 ast_copy_string(d->softkeydevice[p], icon + 5, sizeof(d->softkeydevice[p]));
6374 }
6375 }
6376 ast_copy_string(d->softkeylabel[p], line, sizeof(d->softkeylabel[p]));
6377 ast_copy_string(d->softkeynumber[p], number, sizeof(d->softkeynumber[p]));
6378 if (unistimdebug) {
6379 ast_verb(0, "New bookmark at pos %d label='%s' number='%s' icon=%#x\n",
6380 p, d->softkeylabel[p], d->softkeynumber[p], (unsigned)d->softkeyicon[p]);
6381 }
6382 return 1;
6383 }
6384
6385 /* Looking for dynamic icons entries in bookmarks */
6386 static void finish_bookmark(void)
6387 {
6388 struct unistim_device *d = devices;
6389 int i;
6390 ast_mutex_lock(&devicelock);
6391 while (d) {
6392 for (i = 0; i < 6; i++) {
6393 if (d->softkeyicon[i] == 1) { /* Something for us */
6394 struct unistim_device *d2 = devices;
6395 while (d2) {
6396 if (!strcmp(d->softkeydevice[i], d2->name)) {
6397 d->sp[i] = d2;
6398 d->softkeyicon[i] = 0;
6399 break;
6400 }
6401 d2 = d2->next;
6402 }
6403 if (d->sp[i] == NULL) {
6404 ast_log(LOG_NOTICE, "Bookmark entry with device %s not found\n",
6405 d->softkeydevice[i]);
6406 }
6407 }
6408 }
6409 d = d->next;
6410 }
6411 ast_mutex_unlock(&devicelock);
6412 }
6413
6414 static struct unistim_line *find_line_by_number(struct unistim_device *d, const char *val) {
6415 struct unistim_line *l, *ret = NULL;
6416
6417 AST_LIST_LOCK(&d->lines);
6418 AST_LIST_TRAVERSE(&d->lines, l, list) {
6419 if (!strcmp(l->name, val)) {
6420 ret = l;
6421 break;
6422 }
6423 }
6424 AST_LIST_UNLOCK(&d->lines);
6425 return ret;
6426 }
6427
6428 static void delete_device(struct unistim_device *d)
6429 {
6430 struct unistim_line *l;
6431 struct unistim_subchannel *sub;
6432 struct unistimsession *s;
6433
6434 if (unistimdebug) {
6435 ast_verb(0, "Removing device '%s'\n", d->name);
6436 }
6437 AST_LIST_LOCK(&d->subs);
6438 AST_LIST_TRAVERSE_SAFE_BEGIN(&d->subs, sub, list){
6439 if (sub->subtype == SUB_REAL) {
6440 if (sub->owner) {
6441 ast_log(LOG_WARNING,
6442 "Device '%s' was not deleted : a call is in progress. Try again later.\n",
6443 d->name);
6444 AST_LIST_UNLOCK(&d->subs);
6445 return;
6446 }
6447 }
6448 if (sub->subtype == SUB_THREEWAY) {
6449 ast_log(LOG_WARNING,
6450 "Device '%s' with threeway call subchannels allocated, aborting.\n",
6451 d->name);
6452 AST_LIST_UNLOCK(&d->subs);
6453 return;
6454 }
6455 AST_LIST_REMOVE_CURRENT(list);
6456 ast_mutex_destroy(&sub->lock);
6457 ast_free(sub);
6458 }
6459 AST_LIST_TRAVERSE_SAFE_END
6460 AST_LIST_UNLOCK(&d->subs);
6461
6462
6463 AST_LIST_LOCK(&d->lines);
6464 AST_LIST_TRAVERSE_SAFE_BEGIN(&d->lines, l, list){
6465 AST_LIST_REMOVE_CURRENT(list);
6466 ast_mutex_destroy(&l->lock);
6467 unistim_line_destroy(l);
6468 }
6469 AST_LIST_TRAVERSE_SAFE_END
6470 AST_LIST_UNLOCK(&d->lines);
6471
6472 if (d->session) {
6473 if (sessions == d->session) {
6474 sessions = d->session->next;
6475 } else {
6476 s = sessions;
6477 while (s) {
6478 if (s->next == d->session) {
6479 s->next = d->session->next;
6480 break;
6481 }
6482 s = s->next;
6483 }
6484 }
6485 ast_mutex_destroy(&d->session->lock);
6486 ast_free(d->session);
6487 }
6488 if (devices == d) {
6489 devices = d->next;
6490 } else {
6491 struct unistim_device *d2 = devices;
6492 while (d2) {
6493 if (d2->next == d) {
6494 d2->next = d->next;
6495 break;
6496 }
6497 d2 = d2->next;
6498 }
6499 }
6500 if (d->tz) {
6501 d->tz = ast_tone_zone_unref(d->tz);
6502 }
6503 ast_mutex_destroy(&d->lock);
6504 ast_free(d);
6505 }
6506
6507 static struct unistim_device *build_device(const char *cat, const struct ast_variable *v)
6508 {
6509 struct unistim_device *d;
6510 struct unistim_line *l = NULL, *lt = NULL;
6511 int create = 1;
6512 int nbsoftkey, dateformat, timeformat, callhistory, sharpdial, linecnt;
6513 char linelabel[AST_MAX_EXTENSION];
6514 signed char ringvolume, ringstyle, cwvolume, cwstyle;
6515
6516 /* First, we need to know if we already have this name in our list */
6517 /* Get a lock for the device chained list */
6518 ast_mutex_lock(&devicelock);
6519 d = devices;
6520 while (d) {
6521 if (!strcmp(d->name, cat)) {
6522 /* Yep, we already have this one */
6523 if (unistimsock < 0) {
6524 /* It's a dupe */
6525 ast_log(LOG_WARNING, "Duplicate entry found (%s), ignoring.\n", cat);
6526 ast_mutex_unlock(&devicelock);
6527 return NULL;
6528 }
6529 /* we're reloading right now */
6530 create = 0;
6531 break;
6532 }
6533 d = d->next;
6534 }
6535 ast_mutex_unlock(&devicelock);
6536 if (!(lt = ast_calloc(1, sizeof(*lt)))) {
6537 return NULL;
6538 }
6539 if (create) {
6540 if (!(d = ast_calloc(1, sizeof(*d)))) {
6541 return NULL;
6542 }
6543 ast_mutex_init(&d->lock);
6544 ast_copy_string(d->name, cat, sizeof(d->name));
6545
6546 ast_copy_string(d->context, DEFAULTCONTEXT, sizeof(d->context));
6547 d->contrast = -1;
6548 d->output = OUTPUT_HANDSET;
6549 d->previous_output = OUTPUT_HANDSET;
6550 d->volume = VOLUME_LOW;
6551 d->microphone = MUTE_OFF;
6552 d->height = DEFAULTHEIGHT;
6553 d->selected = -1;
6554 d->interdigit_timer = DEFAULT_INTERDIGIT_TIMER;
6555 } else {
6556 /* Delete existing line information */
6557 AST_LIST_LOCK(&d->lines);
6558 AST_LIST_TRAVERSE_SAFE_BEGIN(&d->lines, l, list){
6559 AST_LIST_REMOVE_CURRENT(list);
6560 unistim_line_destroy(l);
6561 }
6562 AST_LIST_TRAVERSE_SAFE_END
6563 AST_LIST_UNLOCK(&d->lines);
6564
6565 /* reset bookmarks */
6566 memset(d->softkeylabel, 0, sizeof(d->softkeylabel));
6567 memset(d->softkeynumber, 0, sizeof(d->softkeynumber));
6568 memset(d->softkeyicon, 0, sizeof(d->softkeyicon));
6569 memset(d->softkeydevice, 0, sizeof(d->softkeydevice));
6570 memset(d->ssub, 0, sizeof(d->ssub));
6571 memset(d->sline, 0, sizeof(d->sline));
6572 memset(d->sp, 0, sizeof(d->sp));
6573 }
6574 linelabel[0] = '\0';
6575 dateformat = 1;
6576 timeformat = 1;
6577 ringvolume = 2;
6578 cwvolume = 1;
6579 callhistory = 1;
6580 sharpdial = 0;
6581 ringstyle = 3;
6582 cwstyle = 2;
6583 nbsoftkey = 0;
6584 linecnt = 0;
6585 d->dtmfduration = 0;
6586 while (v) {
6587 if (!strcasecmp(v->name, "rtp_port")) {
6588 d->rtp_port = atoi(v->value);
6589 } else if (!strcasecmp(v->name, "rtp_method")) {
6590 d->rtp_method = atoi(v->value);
6591 } else if (!strcasecmp(v->name, "status_method")) {
6592 d->status_method = atoi(v->value);
6593 } else if (!strcasecmp(v->name, "device")) {
6594 ast_copy_string(d->id, v->value, sizeof(d->id));
6595 } else if (!strcasecmp(v->name, "tn")) {
6596 ast_copy_string(d->extension_number, v->value, sizeof(d->extension_number));
6597 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
6598 int acl_error = 0;
6599 d->ha = ast_append_ha(v->name, v->value, d->ha, &acl_error);
6600 if (acl_error) {
6601 ast_log(LOG_ERROR, "Invalid ACL '%s' specified for device '%s' on line %d. Deleting device\n",
6602 v->value, cat, v->lineno);
6603 delete_device(d);
6604 return NULL;
6605 }
6606 } else if (!strcasecmp(v->name, "context")) {
6607 ast_copy_string(d->context, v->value, sizeof(d->context));
6608 } else if (!strcasecmp(v->name, "maintext0")) {
6609 unquote(d->maintext0, v->value, sizeof(d->maintext0) - 1);
6610 } else if (!strcasecmp(v->name, "maintext1")) {
6611 unquote(d->maintext1, v->value, sizeof(d->maintext1) - 1);
6612 } else if (!strcasecmp(v->name, "maintext2")) {
6613 unquote(d->maintext2, v->value, sizeof(d->maintext2) - 1);
6614 } else if (!strcasecmp(v->name, "titledefault")) {
6615 unquote(d->titledefault, v->value, sizeof(d->titledefault) - 1);
6616 } else if (!strcasecmp(v->name, "dateformat")) {
6617 dateformat = atoi(v->value);
6618 } else if (!strcasecmp(v->name, "timeformat")) {
6619 timeformat = atoi(v->value);
6620 } else if (!strcasecmp(v->name, "contrast")) {
6621 d->contrast = atoi(v->value);
6622 if ((d->contrast < 0) || (d->contrast > 15)) {
6623 ast_log(LOG_WARNING, "contrast must be between 0 and 15\n");
6624 d->contrast = 8;
6625 }
6626 } else if (!strcasecmp(v->name, "nat")) {
6627 d->nat = ast_true(v->value);
6628 } else if (!strcasecmp(v->name, "hasexp")) {
6629 d->hasexp = ast_true(v->value);
6630 } else if (!strcasecmp(v->name, "ringvolume")) {
6631 ringvolume = atoi(v->value);
6632 } else if (!strcasecmp(v->name, "ringstyle")) {
6633 ringstyle = atoi(v->value);
6634 } else if (!strcasecmp(v->name, "cwvolume")) {
6635 cwvolume = atoi(v->value);
6636 } else if (!strcasecmp(v->name, "cwstyle")) {
6637 cwstyle = atoi(v->value);
6638 } else if (!strcasecmp(v->name, "callhistory")) {
6639 callhistory = atoi(v->value);
6640 } else if (!strcasecmp(v->name, "sharpdial")) {
6641 sharpdial = ast_true(v->value) ? 1 : 0;
6642 } else if (!strcasecmp(v->name, "interdigit_timer")) {
6643 d->interdigit_timer = atoi(v->value);
6644 } else if (!strcasecmp(v->name, "dtmf_duration")) {
6645 d->dtmfduration = atoi(v->value);
6646 if (d->dtmfduration > 150) {
6647 d->dtmfduration = 150;
6648 }
6649 } else if (!strcasecmp(v->name, "callerid")) {
6650 if (!strcasecmp(v->value, "asreceived")) {
6651 lt->cid_num[0] = '\0';
6652 } else {
6653 ast_copy_string(lt->cid_num, v->value, sizeof(lt->cid_num));
6654 }
6655 } else if (!strcasecmp(v->name, "language")) {
6656 ast_copy_string(d->language, v->value, sizeof(d->language));
6657 } else if (!strcasecmp(v->name, "country")) {
6658 ast_copy_string(d->country, v->value, sizeof(d->country));
6659 } else if (!strcasecmp(v->name, "accountcode")) {
6660 ast_copy_string(lt->accountcode, v->value, sizeof(lt->accountcode));
6661 } else if (!strcasecmp(v->name, "amaflags")) {
6662 int y;
6663 y = ast_channel_string2amaflag(v->value);
6664 if (y < 0) {
6665 ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value,
6666 v->lineno);
6667 } else {
6668 lt->amaflags = y;
6669 }
6670 } else if (!strcasecmp(v->name, "musiconhold")) {
6671 ast_copy_string(lt->musicclass, v->value, sizeof(lt->musicclass));
6672 } else if (!strcasecmp(v->name, "callgroup")) {
6673 lt->callgroup = ast_get_group(v->value);
6674 } else if (!strcasecmp(v->name, "pickupgroup")) {
6675 lt->pickupgroup = ast_get_group(v->value);
6676 } else if (!strcasecmp(v->name, "mailbox")) {
6677 ast_copy_string(lt->mailbox, v->value, sizeof(lt->mailbox));
6678 } else if (!strcasecmp(v->name, "parkinglot")) {
6679 ast_copy_string(lt->parkinglot, v->value, sizeof(lt->parkinglot));
6680 } else if (!strcasecmp(v->name, "linelabel")) {
6681 unquote(linelabel, v->value, sizeof(linelabel) - 1);
6682 } else if (!strcasecmp(v->name, "extension")) {
6683 if (!strcasecmp(v->value, "none")) {
6684 d->extension = EXTENSION_NONE;
6685 } else if (!strcasecmp(v->value, "ask")) {
6686 d->extension = EXTENSION_ASK;
6687 } else if (!strcasecmp(v->value, "line")) {
6688 d->extension = EXTENSION_LINE;
6689 } else {
6690 ast_log(LOG_WARNING, "Unknown extension option.\n");
6691 }
6692 } else if (!strcasecmp(v->name, "bookmark")) {
6693 if (nbsoftkey > 5) {
6694 ast_log(LOG_WARNING,
6695 "More than 6 softkeys defined. Ignoring new entries.\n");
6696 } else {
6697 if (parse_bookmark(v->value, d)) {
6698 nbsoftkey++;
6699 }
6700 }
6701 } else if (!strcasecmp(v->name, "line")) {
6702 int len = strlen(linelabel);
6703 int create_line = 0;
6704
6705 l = find_line_by_number(d, v->value);
6706 if (!l) { /* If line still not exists */
6707 if (!(l = unistim_line_alloc())) {
6708 ast_free(d);
6709 ast_free(lt);
6710 return NULL;
6711 }
6712 lt->cap = l->cap;
6713 memcpy(l, lt, sizeof(*l));
6714 ast_mutex_init(&l->lock);
6715 create_line = 1;
6716 }
6717 d->to_delete = 0;
6718
6719 /* Set softkey info for new line*/
6720 d->sline[nbsoftkey] = l;
6721 d->softkeyicon[nbsoftkey] = FAV_LINE_ICON;
6722 if (!len) { /* label is undefined ? */
6723 ast_copy_string(d->softkeylabel[nbsoftkey], v->value, sizeof(d->softkeylabel[nbsoftkey]));
6724 } else {
6725 int softkeylinepos = 0;
6726 if ((len > 2) && (linelabel[1] == '@')) {
6727 softkeylinepos = linelabel[0];
6728 if ((softkeylinepos >= '0') && (softkeylinepos <= '5')) {
6729 softkeylinepos -= '0';
6730 d->softkeyicon[nbsoftkey] = FAV_ICON_NONE;
6731 } else {
6732 ast_log(LOG_WARNING,
6733 "Invalid position for linelabel : must be between 0 and 5\n");
6734 }
6735 ast_copy_string(d->softkeylabel[softkeylinepos], linelabel + 2,
6736 sizeof(d->softkeylabel[softkeylinepos]));
6737 d->softkeyicon[softkeylinepos] = FAV_LINE_ICON;
6738 } else {
6739 ast_copy_string(d->softkeylabel[nbsoftkey], linelabel,
6740 sizeof(d->softkeylabel[nbsoftkey]));
6741 }
6742 }
6743 nbsoftkey++;
6744
6745 if (create_line) {
6746 ast_copy_string(l->name, v->value, sizeof(l->name));
6747 snprintf(l->fullname, sizeof(l->fullname), "USTM/%s@%s", l->name, d->name);
6748 if (!ast_strlen_zero(l->mailbox)) {
6749 if (unistimdebug) {
6750 ast_verb(3, "Setting mailbox '%s' on %s@%s\n", l->mailbox, d->name, l->name);
6751 }
6752 }
6753 ast_format_cap_append_from_cap(l->cap, global_cap, AST_MEDIA_TYPE_UNKNOWN);
6754 l->parent = d;
6755 linecnt++;
6756 AST_LIST_LOCK(&d->lines);
6757 AST_LIST_INSERT_TAIL(&d->lines, l, list);
6758 AST_LIST_UNLOCK(&d->lines);
6759 }
6760 } else if (!strcasecmp(v->name, "height")) {
6761 /* Allow the user to lower the expected display lines on the phone
6762 * For example the Nortel i2001 and i2002 only have one ! */
6763 d->height = atoi(v->value);
6764 } else
6765 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name,
6766 v->lineno);
6767 v = v->next;
6768 }
6769 ast_free(lt);
6770 if (linecnt == 0) {
6771 ast_log(LOG_ERROR, "An Unistim device must have at least one line!\n");
6772 ast_free(d);
6773 return NULL;
6774 }
6775 d->ringvolume = ringvolume;
6776 d->ringstyle = ringstyle;
6777 d->cwvolume = cwvolume;
6778 d->cwstyle = cwstyle;
6779 d->callhistory = callhistory;
6780 d->sharp_dial = sharpdial;
6781 d->tz = ast_get_indication_zone(d->country);
6782 if ((d->tz == NULL) && !ast_strlen_zero(d->country)) {
6783 ast_log(LOG_WARNING, "Country '%s' was not found in indications.conf\n",
6784 d->country);
6785 }
6786 d->datetimeformat = 48 + (dateformat * 4);
6787 d->datetimeformat += timeformat;
6788 if ((autoprovisioning == AUTOPROVISIONING_TN) &&
6789 (!ast_strlen_zero(d->extension_number))) {
6790 d->extension = EXTENSION_TN;
6791 if (!ast_strlen_zero(d->id)) {
6792 ast_log(LOG_WARNING,
6793 "tn= and device= can't be used together. Ignoring device= entry\n");
6794 }
6795 d->id[0] = 'T'; /* magic : this is a tn entry */
6796 ast_copy_string((d->id) + 1, d->extension_number, sizeof(d->id) - 1);
6797 d->extension_number[0] = '\0';
6798 } else if (ast_strlen_zero(d->id)) {
6799 if (strcmp(d->name, "template")) {
6800 ast_log(LOG_ERROR, "You must specify the mac address with device=\n");
6801 if (d->tz) {
6802 d->tz = ast_tone_zone_unref(d->tz);
6803 }
6804 ast_free(d);
6805 return NULL;
6806 } else {
6807 strcpy(d->id, "000000000000");
6808 }
6809 }
6810 if (!d->rtp_port) {
6811 d->rtp_port = 10000;
6812 }
6813 if (d->contrast == -1) {
6814 d->contrast = 8;
6815 }
6816 if (ast_strlen_zero(d->maintext1)) {
6817 strcpy(d->maintext1, d->name);
6818 }
6819 if (ast_strlen_zero(d->titledefault)) {
6820 struct ast_tm tm = { 0, };
6821 struct timeval cur_time = ast_tvnow();
6822
6823 if ((ast_localtime(&cur_time, &tm, 0)) == 0 || ast_strlen_zero(tm.tm_zone)) {
6824 ast_log(LOG_WARNING, "Error in ast_localtime()\n");
6825 ast_copy_string(d->titledefault, "UNISTIM for*", 12);
6826 } else {
6827 if (strlen(tm.tm_zone) < 4) {
6828 strcpy(d->titledefault, "TimeZone ");
6829 strcat(d->titledefault, tm.tm_zone);
6830 } else if (strlen(tm.tm_zone) < 9) {
6831 strcpy(d->titledefault, "TZ ");
6832 strcat(d->titledefault, tm.tm_zone);
6833 } else {
6834 ast_copy_string(d->titledefault, tm.tm_zone, 12);
6835 }
6836 }
6837 }
6838 /* Update the chained link if it's a new device */
6839 if (create) {
6840 ast_mutex_lock(&devicelock);
6841 d->next = devices;
6842 devices = d;
6843 ast_mutex_unlock(&devicelock);
6844 ast_verb(3, "Added device '%s'\n", d->name);
6845 } else {
6846 ast_verb(3, "Device '%s' reloaded\n", d->name);
6847 }
6848 return d;
6849 }
6850
6851 /*--- reload_config: Re-read unistim.conf config file ---*/
6852 static int reload_config(void)
6853 {
6854 struct ast_config *cfg;
6855 struct ast_variable *v;
6856 struct sockaddr_in bindaddr = { 0, };
6857 char *config = "unistim.conf";
6858 char *cat;
6859 struct unistim_device *d;
6860 const int reuseFlag = 1;
6861 struct unistimsession *s;
6862 struct ast_flags config_flags = { 0, };
6863
6864 cfg = ast_config_load(config, config_flags);
6865 /* We *must* have a config file otherwise stop immediately */
6866 if (!cfg) {
6867 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
6868 return -1;
6869 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
6870 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config);
6871 return -1;
6872 }
6873
6874 /* Copy the default jb config over global_jbconf */
6875 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
6876
6877 unistim_keepalive = 120;
6878 unistim_port = 0;
6879 v = ast_variable_browse(cfg, "general");
6880 while (v) {
6881 /* handle jb conf */
6882 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
6883 continue;
6884 }
6885 if (!strcasecmp(v->name, "keepalive")) {
6886 unistim_keepalive = atoi(v->value);
6887 } else if (!strcasecmp(v->name, "port")) {
6888 unistim_port = atoi(v->value);
6889 } else if (!strcasecmp(v->name, "tos")) {
6890 if (ast_str2tos(v->value, &qos.tos)) {
6891 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
6892 }
6893 } else if (!strcasecmp(v->name, "tos_audio")) {
6894 if (ast_str2tos(v->value, &qos.tos_audio)) {
6895 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
6896 }
6897 } else if (!strcasecmp(v->name, "cos")) {
6898 if (ast_str2cos(v->value, &qos.cos)) {
6899 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
6900 }
6901 } else if (!strcasecmp(v->name, "cos_audio")) {
6902 if (ast_str2cos(v->value, &qos.cos_audio)) {
6903 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
6904 }
6905 } else if (!strcasecmp(v->name, "debug")) {
6906 if (!strcasecmp(v->value, "no")) {
6907 unistimdebug = 0;
6908 } else if (!strcasecmp(v->value, "yes")) {
6909 unistimdebug = 1;
6910 }
6911 } else if (!strcasecmp(v->name, "autoprovisioning")) {
6912 if (!strcasecmp(v->value, "no")) {
6913 autoprovisioning = AUTOPROVISIONING_NO;
6914 } else if (!strcasecmp(v->value, "yes")) {
6915 autoprovisioning = AUTOPROVISIONING_YES;
6916 } else if (!strcasecmp(v->value, "tn")) {
6917 autoprovisioning = AUTOPROVISIONING_TN;
6918 } else {
6919 ast_log(LOG_WARNING, "Unknown autoprovisioning option.\n");
6920 }
6921 } else if (!strcasecmp(v->name, "public_ip")) {
6922 if (!ast_strlen_zero(v->value)) {
6923 struct ast_sockaddr addr = { {0,} };
6924 if (ast_sockaddr_resolve_first_af(&addr, v->value, PARSE_PORT_FORBID, AF_INET)) {
6925 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
6926 } else {
6927 ast_sockaddr_to_sin(&addr, &public_ip);
6928 }
6929 }
6930 }
6931 v = v->next;
6932 }
6933 if ((unistim_keepalive < 10) ||
6934 (unistim_keepalive >
6935 255 - (((NB_MAX_RETRANSMIT + 1) * RETRANSMIT_TIMER) / 1000))) {
6936 ast_log(LOG_ERROR, "keepalive is invalid in %s\n", config);
6937 ast_config_destroy(cfg);
6938 return -1;
6939 }
6940 packet_send_ping[4] =
6941 unistim_keepalive + (((NB_MAX_RETRANSMIT + 1) * RETRANSMIT_TIMER) / 1000);
6942 if ((unistim_port < 1) || (unistim_port > 65535)) {
6943 ast_log(LOG_ERROR, "port is not set or invalid in %s\n", config);
6944 ast_config_destroy(cfg);
6945 return -1;
6946 }
6947 unistim_keepalive *= 1000;
6948
6949 ast_mutex_lock(&devicelock);
6950 d = devices;
6951 while (d) {
6952 if (d->to_delete >= 0) {
6953 d->to_delete = 1;
6954 }
6955 d = d->next;
6956 }
6957 ast_mutex_unlock(&devicelock);
6958 /* load the device sections */
6959 cat = ast_category_browse(cfg, NULL);
6960 while (cat) {
6961 if (strcasecmp(cat, "general")) {
6962 d = build_device(cat, ast_variable_browse(cfg, cat));
6963 }
6964 cat = ast_category_browse(cfg, cat);
6965 }
6966 ast_mutex_lock(&devicelock);
6967 d = devices;
6968 while (d) {
6969 if (d->to_delete) {
6970 delete_device(d);
6971 d = devices;
6972 continue;
6973 }
6974 d = d->next;
6975 }
6976 finish_bookmark();
6977 ast_mutex_unlock(&devicelock);
6978 ast_config_destroy(cfg);
6979 ast_mutex_lock(&sessionlock);
6980 s = sessions;
6981 while (s) {
6982 if (s->device) {
6983 refresh_all_favorite(s);
6984 if (ast_strlen_zero(s->device->language)) {
6985 struct unistim_languages lang;
6986 lang = options_languages[find_language(s->device->language)];
6987 send_charset_update(s, lang.encoding);
6988 }
6989 }
6990 s = s->next;
6991 }
6992 ast_mutex_unlock(&sessionlock);
6993 /* We don't recreate a socket when reloading (locks would be necessary). */
6994 if (unistimsock > -1) {
6995 return 0;
6996 }
6997 bindaddr.sin_addr.s_addr = INADDR_ANY;
6998 bindaddr.sin_port = htons(unistim_port);
6999 bindaddr.sin_family = AF_INET;
7000 unistimsock = socket(AF_INET, SOCK_DGRAM, 0);
7001 if (unistimsock < 0) {
7002 ast_log(LOG_WARNING, "Unable to create UNISTIM socket: %s\n", strerror(errno));
7003 return -1;
7004 }
7005 #ifdef HAVE_PKTINFO
7006 {
7007 const int pktinfoFlag = 1;
7008 setsockopt(unistimsock, IPPROTO_IP, IP_PKTINFO, &pktinfoFlag,
7009 sizeof(pktinfoFlag));
7010 }
7011 #else
7012 if (public_ip.sin_family == 0) {
7013 ast_log(LOG_WARNING,
7014 "Your OS does not support IP_PKTINFO, you must set public_ip.\n");
7015 unistimsock = -1;
7016 return -1;
7017 }
7018 #endif
7019 setsockopt(unistimsock, SOL_SOCKET, SO_REUSEADDR, (const char *) &reuseFlag,
7020 sizeof(reuseFlag));
7021 if (bind(unistimsock, (struct sockaddr *) &bindaddr, sizeof(bindaddr)) < 0) {
7022 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
7023 ast_inet_ntoa(bindaddr.sin_addr), htons(bindaddr.sin_port),
7024 strerror(errno));
7025 close(unistimsock);
7026 unistimsock = -1;
7027 } else {
7028 ast_verb(2, "UNISTIM Listening on %s:%d\n", ast_inet_ntoa(bindaddr.sin_addr), htons(bindaddr.sin_port));
7029 ast_set_qos(unistimsock, qos.tos, qos.cos, "UNISTIM");
7030 }
7031 return 0;
7032 }
7033
7034 static enum ast_rtp_glue_result unistim_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
7035 {
7036 struct unistim_subchannel *sub = ast_channel_tech_pvt(chan);
7037
7038 if (!sub) {
7039 return AST_RTP_GLUE_RESULT_FORBID;
7040 }
7041 if (!sub->rtp) {
7042 return AST_RTP_GLUE_RESULT_FORBID;
7043 }
7044
7045 ao2_ref(sub->rtp, +1);
7046 *instance = sub->rtp;
7047
7048 return AST_RTP_GLUE_RESULT_LOCAL;
7049 }
7050
7051 static int unistim_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, const struct ast_format_cap *codecs, int nat_active)
7052 {
7053 struct unistim_subchannel *sub = ast_channel_tech_pvt(chan);
7054 struct sockaddr_in them = { 0, };
7055 struct sockaddr_in us = { 0, };
7056
7057 if (!rtp) {
7058 return 0;
7059 }
7060
7061 sub = (struct unistim_subchannel *) ast_channel_tech_pvt(chan);
7062 if (!sub) {
7063 ast_log(LOG_ERROR, "No Private Structure, this is bad\n");
7064 return -1;
7065 }
7066 {
7067 struct ast_sockaddr tmp;
7068 ast_rtp_instance_get_remote_address(rtp, &tmp);
7069 ast_sockaddr_to_sin(&tmp, &them);
7070 ast_rtp_instance_get_local_address(rtp, &tmp);
7071 ast_sockaddr_to_sin(&tmp, &us);
7072 }
7073
7074 /* TODO: Set rtp on phone in case of direct rtp (not implemented) */
7075
7076 return 0;
7077 }
7078
7079 static struct ast_rtp_glue unistim_rtp_glue = {
7080 .type = channel_type,
7081 .get_rtp_info = unistim_get_rtp_peer,
7082 .update_peer = unistim_set_rtp_peer,
7083 };
7084
7085 /*--- load_module: PBX load module - initialization ---*/
7086 int load_module(void)
7087 {
7088 int res;
7089
7090 if (!(global_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
7091 goto buff_failed;
7092 }
7093 if (!(unistim_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
7094 goto buff_failed;
7095 }
7096
7097 ast_format_cap_append(global_cap, ast_format_ulaw, 0);
7098 ast_format_cap_append(global_cap, ast_format_alaw, 0);
7099 ast_format_cap_append_from_cap(unistim_tech.capabilities, global_cap, AST_MEDIA_TYPE_AUDIO);
7100
7101 if (!(buff = ast_malloc(SIZE_PAGE))) {
7102 goto buff_failed;
7103 }
7104
7105 io = io_context_create();
7106 if (!io) {
7107 ast_log(LOG_ERROR, "Failed to allocate IO context\n");
7108 goto io_failed;
7109 }
7110
7111 sched = ast_sched_context_create();
7112 if (!sched) {
7113 ast_log(LOG_ERROR, "Failed to allocate scheduler context\n");
7114 goto sched_failed;
7115 }
7116
7117 res = reload_config();
7118 if (res) {
7119 ao2_ref(unistim_tech.capabilities, -1);
7120 ao2_ref(global_cap, -1);
7121 ast_sched_context_destroy(sched);
7122 io_context_destroy(io);
7123 return AST_MODULE_LOAD_DECLINE;
7124 }
7125 /* Make sure we can register our unistim channel type */
7126 if (ast_channel_register(&unistim_tech)) {
7127 ast_log(LOG_ERROR, "Unable to register channel type '%s'\n", channel_type);
7128 goto chanreg_failed;
7129 }
7130
7131 ast_rtp_glue_register(&unistim_rtp_glue);
7132
7133 ast_cli_register_multiple(unistim_cli, ARRAY_LEN(unistim_cli));
7134
7135 restart_monitor();
7136
7137 return AST_MODULE_LOAD_SUCCESS;
7138
7139 chanreg_failed:
7140 /*! XXX \todo Leaking anything allocated by reload_config() ... */
7141 ast_sched_context_destroy(sched);
7142 sched = NULL;
7143 sched_failed:
7144 io_context_destroy(io);
7145 io = NULL;
7146 io_failed:
7147 ast_free(buff);
7148 buff = NULL;
7149 buff_failed:
7150 ao2_cleanup(global_cap);
7151 global_cap = NULL;
7152 ao2_cleanup(unistim_tech.capabilities);
7153 unistim_tech.capabilities = NULL;
7154 return AST_MODULE_LOAD_DECLINE;
7155 }
7156
7157 static int unload_module(void)
7158 {
7159 /* First, take us out of the channel loop */
7160 if (sched) {
7161 ast_sched_context_destroy(sched);
7162 }
7163
7164 ast_cli_unregister_multiple(unistim_cli, ARRAY_LEN(unistim_cli));
7165
7166 ast_channel_unregister(&unistim_tech);
7167 ao2_cleanup(unistim_tech.capabilities);
7168 ast_rtp_glue_unregister(&unistim_rtp_glue);
7169
7170 ast_mutex_lock(&monlock);
7171 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
7172 pthread_cancel(monitor_thread);
7173 pthread_kill(monitor_thread, SIGURG);
7174 pthread_join(monitor_thread, NULL);
7175 }
7176 monitor_thread = AST_PTHREADT_STOP;
7177 ast_mutex_unlock(&monlock);
7178
7179 if (buff) {
7180 ast_free(buff);
7181 }
7182 if (unistimsock > -1) {
7183 close(unistimsock);
7184 }
7185 ao2_ref(global_cap, -1);
7186
7187 return 0;
7188 }
7189
7190 /*! reload: Part of Asterisk module interface ---*/
7191 int reload(void)
7192 {
7193 if (unistimdebug) {
7194 ast_verb(0, "reload unistim\n");
7195 }
7196 ast_mutex_lock(&unistim_reload_lock);
7197 if (!unistim_reloading) {
7198 unistim_reloading = 1;
7199 }
7200 ast_mutex_unlock(&unistim_reload_lock);
7201
7202 restart_monitor();
7203
7204 return 0;
7205 }
7206
7207 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "UNISTIM Protocol (USTM)",
7208 .support_level = AST_MODULE_SUPPORT_EXTENDED,
7209 .load = load_module,
7210 .unload = unload_module,
7211 .reload = reload,
7212 );