Allow Asterisk to compile under GCC 4.10
[asterisk/asterisk.git] / channels / chan_unistim.c
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 <cedric.hans@mlkj.net>
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 <cedric.hans@mlkj.net>
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 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include <sys/stat.h>
44 #include <signal.h>
45
46 #if defined(__CYGWIN__)
47 /*
48  * cygwin headers are partly inconsistent. struct iovec is defined in sys/uio.h
49  * which is not included by default by sys/socket.h - in_pktinfo is defined in
50  * w32api/ws2tcpip.h but this probably has compatibility problems with sys/socket.h
51  * So for the time being we simply disable HAVE_PKTINFO when building under cygwin.
52  *    This should be done in some common header, but for now this is the only file
53  * using iovec and in_pktinfo so it suffices to apply the fix here.
54  */
55 #ifdef HAVE_PKTINFO
56 #undef HAVE_PKTINFO
57 #endif
58 #endif /* __CYGWIN__ */
59
60 #include "asterisk/paths.h"     /* ast_config_AST_LOG_DIR used in (too ?) many places */
61 #include "asterisk/network.h"
62 #include "asterisk/channel.h"
63 #include "asterisk/config.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/rtp_engine.h"
67 #include "asterisk/netsock2.h"
68 #include "asterisk/acl.h"
69 #include "asterisk/callerid.h"
70 #include "asterisk/cli.h"
71 #include "asterisk/app.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
82 #define DEFAULTCONTEXT    "default"
83 #define DEFAULTCALLERID  "Unknown"
84 #define DEFAULTCALLERNAME       " "
85 #define DEFAULTHEIGHT    3
86 #define USTM_LOG_DIR        "unistimHistory"
87 #define USTM_LANG_DIR       "unistimLang"
88
89 /*! Size of the transmit buffer */
90 #define MAX_BUF_SIZE        64
91 /*! Number of slots for the transmit queue */
92 #define MAX_BUF_NUMBER    150
93 /*! Number of digits displayed on screen */
94 #define MAX_SCREEN_NUMBER   15
95 /*! Length of month label size */
96 #define MONTH_LABEL_SIZE 3
97 /*! Try x times before removing the phone */
98 #define NB_MAX_RETRANSMIT       8
99 /*! Nb of milliseconds waited when no events are scheduled */
100 #define IDLE_WAIT              1000
101 /*! Wait x milliseconds before resending a packet */
102 #define RETRANSMIT_TIMER        2000
103 /*! How often the mailbox is checked for new messages */
104 #define TIMER_MWI              5000
105 /*! Timeout value for entered number being dialed */
106 #define DEFAULT_INTERDIGIT_TIMER        4000
107
108 /*! Not used */
109 #define DEFAULT_CODEC      0x00
110 #define SIZE_PAGE              4096
111 #define DEVICE_NAME_LEN  16
112 #define AST_CONFIG_MAX_PATH     255
113 #define MAX_ENTRY_LOG      30
114
115 #define SUB_REAL                0
116 #define SUB_RING                1
117 #define SUB_THREEWAY            2
118 #define SUB_ONHOLD              3
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
166 #define SIZE_HEADER          6
167 #define SIZE_MAC_ADDR      17
168 #define TEXT_LENGTH_MAX  24
169 #define TEXT_LINE0            0x00
170 #define TEXT_LINE1            0x20
171 #define TEXT_LINE2            0x40
172 #define TEXT_NORMAL          0x05
173 #define TEXT_INVERSE        0x25
174 #define STATUS_LENGTH_MAX       28
175
176 #define FAV_ICON_NONE              0x00
177 #define FAV_ICON_ONHOOK_BLACK      0x20
178 #define FAV_ICON_ONHOOK_WHITE      0x21
179 #define FAV_ICON_SPEAKER_ONHOOK_BLACK   0x22
180 #define FAV_ICON_SPEAKER_ONHOOK_WHITE   0x23
181 #define FAV_ICON_OFFHOOK_BLACK    0x24
182 #define FAV_ICON_OFFHOOK_WHITE    0x25
183 #define FAV_ICON_ONHOLD_BLACK      0x26
184 #define FAV_ICON_ONHOLD_WHITE      0x27
185 #define FAV_ICON_SPEAKER_OFFHOOK_BLACK  0x28
186 #define FAV_ICON_SPEAKER_OFFHOOK_WHITE  0x29
187 #define FAV_ICON_PHONE_BLACK        0x2A
188 #define FAV_ICON_PHONE_WHITE        0x2B
189 #define FAV_ICON_SPEAKER_ONHOLD_BLACK   0x2C
190 #define FAV_ICON_SPEAKER_ONHOLD_WHITE   0x2D
191 #define FAV_ICON_HEADPHONES          0x2E
192 #define FAV_ICON_HEADPHONES_ONHOLD      0x2F
193 #define FAV_ICON_HOME              0x30
194 #define FAV_ICON_CITY              0x31
195 #define FAV_ICON_SHARP            0x32
196 #define FAV_ICON_PAGER            0x33
197 #define FAV_ICON_CALL_CENTER        0x34
198 #define FAV_ICON_FAX                0x35
199 #define FAV_ICON_MAILBOX                0x36
200 #define FAV_ICON_REFLECT                0x37
201 #define FAV_ICON_COMPUTER              0x38
202 #define FAV_ICON_FORWARD                0x39
203 #define FAV_ICON_LOCKED          0x3A
204 #define FAV_ICON_TRASH            0x3B
205 #define FAV_ICON_INBOX            0x3C
206 #define FAV_ICON_OUTBOX          0x3D
207 #define FAV_ICON_MEETING                0x3E
208 #define FAV_ICON_BOX                0x3F
209
210 #define FAV_BLINK_FAST            0x20
211 #define FAV_BLINK_SLOW            0x40
212
213 #define FAV_MAX_LENGTH            0x0A
214
215 #define FAVNUM                    6
216 #define EXPNUM                    24
217 #define FAV_LINE_ICON         FAV_ICON_ONHOOK_BLACK
218
219 static void dummy(char *unused, ...)
220 {
221         return;
222 }
223
224 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
225  *  \note Values shown here match the defaults shown in unistim.conf.sample */
226 static struct ast_jb_conf default_jbconf =
227 {
228         .flags = 0,
229         .max_size = 200,
230         .resync_threshold = 1000,
231         .impl = "fixed",
232         .target_extra = 40,
233 };
234 static struct ast_jb_conf global_jbconf;
235
236
237 /* #define DUMP_PACKET 1 */
238 /* #define DEBUG_TIMER ast_verbose */
239
240 #define DEBUG_TIMER dummy
241 /*! Enable verbose output. can also be set with the CLI */
242 static int unistimdebug = 0;
243 static int unistim_port;
244 static enum autoprovision autoprovisioning = AUTOPROVISIONING_NO;
245 static int unistim_keepalive;
246 static int unistimsock = -1;
247
248 static struct {
249         unsigned int tos;
250         unsigned int tos_audio;
251         unsigned int cos;
252         unsigned int cos_audio;
253 } qos = { 0, 0, 0, 0 };
254
255 static struct io_context *io;
256 static struct ast_sched_context *sched;
257 static struct sockaddr_in public_ip = { 0, };
258 static unsigned char *buff; /*! Receive buffer address */
259 static int unistim_reloading = 0;
260 AST_MUTEX_DEFINE_STATIC(unistim_reload_lock);
261
262 /*! This is the thread for the monitor which checks for input on the channels
263  * which are not currently in use.  */
264 static pthread_t monitor_thread = AST_PTHREADT_NULL;
265
266 /*! Protect the monitoring thread, so only one process can kill or start it, and not
267  *    when it's doing something critical. */
268 AST_MUTEX_DEFINE_STATIC(monlock);
269 /*! Protect the session list */
270 AST_MUTEX_DEFINE_STATIC(sessionlock);
271 /*! Protect the device list */
272 AST_MUTEX_DEFINE_STATIC(devicelock);
273
274 enum phone_state {
275         STATE_INIT,
276         STATE_AUTHDENY,
277         STATE_MAINPAGE,
278         STATE_EXTENSION,
279         STATE_DIALPAGE,
280         STATE_RINGING,
281         STATE_CALL,
282         STATE_SELECTOPTION,
283         STATE_SELECTCODEC,
284         STATE_SELECTLANGUAGE,
285         STATE_CLEANING,
286         STATE_HISTORY
287 };
288
289 enum handset_state {
290         STATE_ONHOOK,
291         STATE_OFFHOOK,
292 };
293
294 enum phone_key {
295         KEY_0 = 0x40,
296         KEY_1 = 0x41,
297         KEY_2 = 0x42,
298         KEY_3 = 0x43,
299         KEY_4 = 0x44,
300         KEY_5 = 0x45,
301         KEY_6 = 0x46,
302         KEY_7 = 0x47,
303         KEY_8 = 0x48,
304         KEY_9 = 0x49,
305         KEY_STAR = 0x4a,
306         KEY_SHARP = 0x4b,
307         KEY_UP = 0x4c,
308         KEY_DOWN = 0x4d,
309         KEY_RIGHT = 0x4e,
310         KEY_LEFT = 0x4f,
311         KEY_QUIT = 0x50,
312         KEY_COPY = 0x51,
313         KEY_FUNC1 = 0x54,
314         KEY_FUNC2 = 0x55,
315         KEY_FUNC3 = 0x56,
316         KEY_FUNC4 = 0x57,
317         KEY_ONHOLD = 0x5b,
318         KEY_HANGUP = 0x5c,
319         KEY_MUTE = 0x5d,
320         KEY_HEADPHN = 0x5e,
321         KEY_LOUDSPK = 0x5f,
322         KEY_FAV0 = 0x60,
323         KEY_FAV1 = 0x61,
324         KEY_FAV2 = 0x62,
325         KEY_FAV3 = 0x63,
326         KEY_FAV4 = 0x64,
327         KEY_FAV5 = 0x65,
328         KEY_COMPUTR = 0x7b,
329         KEY_CONF = 0x7c,
330         KEY_SNDHIST = 0x7d,
331         KEY_RCVHIST = 0x7e,
332         KEY_INDEX = 0x7f
333 };
334
335 enum charset {
336         LANG_DEFAULT,
337         ISO_8859_1,
338         ISO_8859_2,
339         ISO_8859_4,
340         ISO_8859_5,
341         ISO_2022_JP,
342 };
343
344 static const int dtmf_row[] = { 697,  770,  852,  941 };
345 static const float dtmf_col[] = { 1209, 1336, 1477, 1633 };
346
347 struct wsabuf {
348         u_long len;
349         unsigned char *buf;
350 };
351
352 struct unistim_subchannel {
353         ast_mutex_t lock;
354         unsigned int subtype;           /*! SUB_REAL, SUB_RING, SUB_THREEWAY or SUB_ONHOLD */
355         struct ast_channel *owner;      /*! Asterisk channel used by the subchannel */
356         struct unistim_line *parent;    /*! Unistim line */
357         struct ast_rtp_instance *rtp;   /*! RTP handle */
358         int softkey;                    /*! Softkey assigned */
359         pthread_t ss_thread;            /*! unistim_ss thread handle */
360         int alreadygone;
361         char ringvolume;
362         char ringstyle;
363         int moh;                                        /*!< Music on hold in progress */
364         AST_LIST_ENTRY(unistim_subchannel) list;
365 };
366
367 /*!
368  * \todo Convert to stringfields
369  */
370 struct unistim_line {
371         ast_mutex_t lock;
372         char name[80]; /*! Like 200 */
373         char fullname[80]; /*! Like USTM/200\@black */
374         char exten[AST_MAX_EXTENSION]; /*! Extension where to start */
375         char cid_num[AST_MAX_EXTENSION]; /*! CallerID Number */
376         char mailbox[AST_MAX_EXTENSION]; /*! Mailbox for MWI */
377         char musicclass[MAX_MUSICCLASS]; /*! MusicOnHold class */
378         ast_group_t callgroup; /*! Call group */
379         ast_group_t pickupgroup; /*! Pickup group */
380         char accountcode[AST_MAX_ACCOUNT_CODE]; /*! Account code (for billing) */
381         int amaflags; /*! AMA flags (for billing) */
382         struct ast_format_cap *cap; /*! Codec supported */
383         char parkinglot[AST_MAX_CONTEXT]; /*! Parkinglot */
384         struct unistim_line *next;
385         struct unistim_device *parent;
386         AST_LIST_ENTRY(unistim_line) list;
387 };
388
389 /*!
390  * \brief A device containing one or more lines
391  */
392 static struct unistim_device {
393         ast_mutex_t lock;
394         int receiver_state;           /*!< state of the receiver (see ReceiverState) */
395         int size_phone_number;    /*!< size of the phone number */
396         char context[AST_MAX_EXTENSION]; /*!< Context to start in */
397         char phone_number[AST_MAX_EXTENSION];     /*!< the phone number entered by the user */
398         char redial_number[AST_MAX_EXTENSION];   /*!< the last phone number entered by the user */
399         char id[18];                        /*!< mac address of the current phone in ascii */
400         char name[DEVICE_NAME_LEN];     /*!< name of the device */
401         int hasexp;                          /*!< if device have expansion connected */
402         char expsoftkeylabel[EXPNUM][11];       /*!< soft key label */
403         char softkeylabel[FAVNUM][11];       /*!< soft key label */
404         char softkeynumber[FAVNUM][AST_MAX_EXTENSION];      /*!< number dialed when the soft key is pressed */
405         char softkeyicon[FAVNUM];           /*!< icon number */
406         char softkeydevice[FAVNUM][16];      /*!< name of the device monitored */
407         struct unistim_subchannel *ssub[FAVNUM];
408         struct unistim_line *sline[FAVNUM];
409         struct unistim_device *sp[FAVNUM];   /*!< pointer to the device monitored by this soft key */
410         char language[MAX_LANGUAGE];    /*!< Language for asterisk sounds */
411         int height;                                                     /*!< The number of lines the phone can display */
412         char maintext0[25];                  /*!< when the phone is idle, display this string on line 0 */
413         char maintext1[25];                  /*!< when the phone is idle, display this string on line 1 */
414         char maintext2[25];                  /*!< when the phone is idle, display this string on line 2 */
415         char titledefault[13];    /*!< title (text before date/time) */
416         char datetimeformat;        /*!< format used for displaying time/date */
417         char contrast;                    /*!< contrast */
418         char country[3];                        /*!< country used for dial tone frequency */
419         struct ast_tone_zone *tz;              /*!< Tone zone for res_indications (ring, busy, congestion) */
420         char ringvolume;                        /*!< Ring volume */
421         char ringstyle;                  /*!< Ring melody */
422         char cwvolume;                  /*!< Ring volume on call waiting */
423         char cwstyle;                    /*!< Ring melody on call waiting */
424         int interdigit_timer;           /*!< Interdigit timer for dialing number by timeout */
425         int dtmfduration;               /*!< DTMF playback duration */
426         time_t nextdial;                /*!< Timer used for dial by timeout */
427         int rtp_port;                      /*!< RTP port used by the phone */
428         int rtp_method;                  /*!< Select the unistim data used to establish a RTP session */
429         int status_method;                    /*!< Select the unistim packet used for sending status text */
430         char codec_number;                    /*!< The current codec used to make calls */
431         int missed_call;                        /*!< Number of call unanswered */
432         int callhistory;                        /*!< Allowed to record call history */
433         int sharp_dial;                         /*!< Execute Dial on '#' or not */
434         char lst_cid[TEXT_LENGTH_MAX];  /*!< Last callerID received */
435         char lst_cnm[TEXT_LENGTH_MAX];  /*!< Last callername recevied */
436         char call_forward[AST_MAX_EXTENSION];   /*!< Forward number */
437         int output;                                  /*!< Handset, headphone or speaker */
438         int previous_output;        /*!< Previous output */
439         int volume;                                  /*!< Default volume */
440         int selected;                           /*!< softkey selected */
441         int microphone;                         /*!< Microphone mode (audio tx) */
442         int lastmsgssent;                                                   /*! Used by MWI */
443         time_t nextmsgcheck;                                            /*! Used by MWI */
444         int nat;                                        /*!< Used by the obscure ast_rtp_setnat */
445         enum autoprov_extn extension;   /*!< See ifdef EXTENSION for valid values */
446         char extension_number[11];      /*!< Extension number entered by the user */
447         char to_delete;                  /*!< Used in reload */
448         struct ast_silence_generator *silence_generator;
449         AST_LIST_HEAD(,unistim_subchannel) subs; /*!< pointer to our current connection, channel... */
450         AST_LIST_HEAD(,unistim_line) lines;
451         struct ast_ha *ha;
452         struct unistimsession *session;
453         struct unistim_device *next;
454 } *devices = NULL;
455
456 static struct unistimsession {
457         ast_mutex_t lock;
458         struct sockaddr_in sin;  /*!< IP address of the phone */
459         struct sockaddr_in sout;        /*!< IP address of server */
460         int timeout;                        /*!< time-out in ticks : resend packet if no ack was received before the timeout occured */
461         unsigned short seq_phone;       /*!< sequence number for the next packet (when we receive a request) */
462         unsigned short seq_server;      /*!< sequence number for the next packet (when we send a request) */
463         unsigned short last_seq_ack;    /*!< sequence number of the last ACK received */
464         unsigned long tick_next_ping;   /*!< time for the next ping */
465         int last_buf_available;  /*!< number of a free slot */
466         int nb_retransmit;                    /*!< number of retransmition */
467         int state;                                    /*!< state of the phone (see phone_state) */
468         int size_buff_entry;        /*!< size of the buffer used to enter datas */
469         char buff_entry[16];        /*!< Buffer for temporary datas */
470         char macaddr[18];                      /*!< mac adress of the phone (not always available) */
471         char firmware[8];                      /*!< firmware of the phone (not always available) */
472         struct wsabuf wsabufsend[MAX_BUF_NUMBER];      /*!< Size of each paquet stored in the buffer array & pointer to this buffer */
473         unsigned char buf[MAX_BUF_NUMBER][MAX_BUF_SIZE];        /*!< Buffer array used to keep the lastest non-acked paquets */
474         struct unistim_device *device;
475         struct unistimsession *next;
476 } *sessions = NULL;
477
478 /*! Store on screen phone menu item (label and handler function) */
479 struct unistim_menu_item {
480         char *label;
481         int state;
482         void (*handle_option)(struct unistimsession *);
483 };
484
485 /*! Language item for currently existed translations */
486 struct unistim_languages {
487         char *label;
488         char *lang_short;
489         int encoding;
490         struct ao2_container *trans;
491 };
492
493 /*!
494  * \page Unistim datagram formats
495  *
496  * Format of datagrams :
497  * bytes 0 & 1 : ffff for discovery packet, 0000 for everything else
498  * byte 2 : sequence number (high part)
499  * byte 3 : sequence number (low part)
500  * byte 4 : 2 = ask question or send info, 1 = answer or ACK, 0 = retransmit request
501  * byte 5 : direction, 1 = server to phone, 2 = phone to server arguments
502  */
503
504 static const unsigned char packet_rcv_discovery[] =
505         { 0xff, 0xff, 0xff, 0xff, 0x02, 0x02, 0xff, 0xff, 0xff, 0xff, 0x9e, 0x03, 0x08 };
506 static const unsigned char packet_send_discovery_ack[] =
507         { 0x00, 0x00, /*Initial Seq (2 bytes) */ 0x00, 0x00, 0x00, 0x01 };
508
509 static const unsigned char packet_recv_firm_version[] =
510         { 0x00, 0x00, 0x00, 0x13, 0x9a, 0x0a, 0x02 };
511 static const unsigned char packet_recv_it_type[] =
512         { 0x00, 0x00, 0x00, 0x13, 0x9a, 0x04, 0x03 };
513 static const unsigned char packet_recv_pressed_key[] =
514         { 0x00, 0x00, 0x00, 0x13, 0x99, 0x04, 0x00 };
515 static const unsigned char packet_recv_pick_up[] =
516         { 0x00, 0x00, 0x00, 0x13, 0x99, 0x03, 0x04 };
517 static const unsigned char packet_recv_hangup[] =
518         { 0x00, 0x00, 0x00, 0x13, 0x99, 0x03, 0x03 };
519 static const unsigned char packet_recv_r2[] = { 0x00, 0x00, 0x00, 0x13, 0x96, 0x03, 0x03 };
520
521 /*! Expansion module (i2004 KEM) */
522 static const unsigned char packet_recv_expansion_pressed_key[] =
523         { 0x00, 0x00, 0x00, 0x13, 0x89, 0x04, 0x59 };
524 static const unsigned char packet_send_expansion_next[] = { 0x09, 0x03, 0x17 };
525 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 */
526 static const unsigned char packet_send_expansion_text[] = { 0x09, 0x0f, 0x57, 0x19, /*pos */ 0x47, /*text */ 0x20,
527         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 /*end_text */ };
528
529
530 /*! TransportAdapter */
531 static const unsigned char packet_recv_resume_connection_with_server[] =
532         { 0xff, 0xff, 0xff, 0xff, 0x9e, 0x03, 0x08 };
533 static const unsigned char packet_recv_mac_addr[] =
534         { 0xff, 0xff, 0xff, 0xff, 0x9a, 0x0d, 0x07 /*MacAddr */  };
535
536 static const unsigned char packet_send_date_time3[] =
537         { 0x11, 0x09, 0x02, 0x02, /*Month */ 0x05, /*Day */ 0x06, /*Hour */ 0x07,
538 /*Minutes */ 0x08, 0x32
539 };
540 static const unsigned char packet_send_date_time[] =
541         { 0x11, 0x09, 0x02, 0x0a, /*Month */ 0x05, /*Day */ 0x06, /*Hour */ 0x07, /*Minutes */
542 0x08, 0x32, 0x17, 0x04, 0x24, 0x07, 0x19,
543         0x04, 0x07, 0x00, 0x19, 0x05, 0x09, 0x3e, 0x0f, 0x16, 0x05, 0x00, 0x80, 0x00, 0x1e,
544                 0x05, 0x12, 0x00, 0x78
545 };
546
547 static const unsigned char packet_send_no_ring[] =
548         { 0x16, 0x04, 0x1a, 0x00, 0x16, 0x04, 0x11, 0x00 };
549 static const unsigned char packet_send_s4[] =
550         { 0x16, 0x04, 0x1a, 0x00, 0x16, 0x04, 0x11, 0x00, 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff,
551 0x16, 0x05, 0x1c, 0x00, 0x00, 0x17, 0x05,
552         0x0b, 0x00, 0x00, 0x19, 0x04, 0x00, 0x00, 0x19, 0x04, 0x00, 0x08, 0x19, 0x04, 0x00,
553                 0x10, 0x19, 0x04, 0x00, 0x18, 0x16, 0x05,
554         0x31, 0x00, 0x00, 0x16, 0x05, 0x04, 0x00, 0x00
555 };
556 static const unsigned char packet_send_call[] =
557         { 0x16, 0x04, 0x1a, 0x00, 0x16, 0x04, 0x11, 0x00, 0x16, 0x06, 0x32, 0xdf,
558         0x00, 0xff, 0x16, 0x05, 0x1c, 0x00, 0x00, 0x16, 0x0a, 0x38, 0x00, 0x12, 0xca, 0x03,
559                 0xc0, 0xc3, 0xc5, 0x16, 0x16, 0x30, 0x00,
560         0x00, /*codec */ 0x12, 0x12, /* frames per packet */ 0x01, 0x5c, 0x00, /*port RTP */
561                 0x0f, 0xa0, /* port RTCP */ 0x9c, 0x41,
562         /*port RTP */ 0x0f, 0xa0, /* port RTCP */ 0x9c, 0x41, /* IP Address */ 0x0a, 0x01,
563                 0x16, 0x66
564 };
565 static const unsigned char packet_send_stream_based_tone_off[] =
566         { 0x16, 0x05, 0x1c, 0x00, 0x00 };
567
568 static const unsigned char packet_send_mute[] = { 0x16, 0x05, 0x04, 0x00, 0x00 };
569 static const unsigned char packet_send_CloseAudioStreamRX[] = { 0x16, 0x05, 0x31, 0x00, 0xff };
570 static const unsigned char packet_send_CloseAudioStreamTX[] = { 0x16, 0x05, 0x31, 0xff, 0x00 };
571 static const unsigned char packet_send_stream_based_tone_on[] =
572         { 0x16, 0x06, 0x1b, 0x00, 0x00, 0x05 };
573 static const unsigned char packet_send_stream_based_tone_single_freq[] =
574         { 0x16, 0x06, 0x1d, 0x00, 0x01, 0xb8 };
575 static const unsigned char packet_send_stream_based_tone_dial_freq[] =
576         { 0x16, 0x08, 0x1d, 0x00, 0x01, 0xb8, 0x01, 0x5e };
577 static const unsigned char packet_send_select_output[] =
578         { 0x16, 0x06, 0x32, 0xc0, 0x01, 0x00 };
579
580 static const unsigned char packet_send_ring[] =
581         { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x16, 0x05, 0x1c, 0x00, 0x00, 0x16,
582         0x04, 0x1a, 0x01, 0x16, 0x05, 0x12, 0x13 /* Ring type 10 to 17 */ , 0x18, 0x16, 0x04, 0x18,     /* volume 00, 10, 20... */
583         0x20, 0x16, 0x04, 0x10, 0x00
584 };
585 //static const unsigned char packet_send_end_call[] =
586 //      { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x16, 0x05, 0x31, 0x00, 0x00, /* Headset LED off */ 0x19, 0x04, 0x00,
587 //0x10, /* Mute LED off */ 0x19, 0x04, 0x00, 0x18,/* Stream unmute */ 0x16, 0x05, 0x04, 0x00, 0x00, /* Query RTCP */ 0x16, 0x04, 0x37, 0x10 };
588 static const unsigned char packet_send_end_call[] =
589         { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x16, 0x05, 0x31, 0x00, 0x00, /* Query RTCP */ 0x16, 0x04, 0x37, 0x10 };
590 static const unsigned char packet_send_s9[] =
591         { 0x16, 0x06, 0x32, 0xdf, 0x00, 0xff, 0x19, 0x04, 0x00, 0x10, 0x16, 0x05, 0x1c, 0x00,
592 0x00 };
593 static const unsigned char packet_send_rtp_packet_size[] =
594         { 0x16, 0x08, 0x38, 0x00, 0x00, 0xe0, 0x00, 0xa0 };
595 static const unsigned char packet_send_jitter_buffer_conf[] =
596         { 0x16, 0x0e, 0x3a, 0x00, /* jitter */ 0x02, /* high water mark */ 0x04, 0x00, 0x00,
597 /* early packet resync 2 bytes */ 0x3e, 0x80,
598         0x00, 0x00, /* late packet resync 2 bytes */ 0x3e, 0x80
599 };
600
601 /* Duration in ms div 2 (0x20 = 64ms, 0x08 = 16ms)
602 static unsigned char packet_send_StreamBasedToneCad[] =
603   { 0x16, 0x0a, 0x1e, 0x00, duration on  0x0a, duration off  0x0d, duration on 0x0a, duration off 0x0d, duration on 0x0a, duration off 0x2b }; */
604 static const unsigned char packet_send_open_audio_stream_rx[] =
605         { 0x16, 0x1a, 0x30, 0x00, 0xff, /* Codec */ 0x00, 0x00, 0x01, 0x00, 0xb8, 0xb8, 0x0e,
606 0x0e, 0x01, /* Port */ 0x14, 0x50, 0x00,
607         0x00, /* Port */ 0x14, 0x50, 0x00, 0x00, /* Dest IP */ 0x0a, 0x93, 0x69, 0x05
608 };
609 static const unsigned char packet_send_open_audio_stream_tx[] =
610         { 0x16, 0x1a, 0x30, 0xff, 0x00, 0x00, /* Codec */ 0x00, 0x01, 0x00, 0xb8, 0xb8, 0x0e,
611 0x0e, 0x01, /* Local port */ 0x14, 0x50,
612         0x00, 0x00, /* Rmt Port */ 0x14, 0x50, 0x00, 0x00, /* Dest IP */ 0x0a, 0x93, 0x69, 0x05
613 };
614
615 static const unsigned char packet_send_open_audio_stream_rx3[] =
616         { 0x16, 0x1a, 0x30, 0x00, 0xff, /* Codec */ 0x00, 0x00, 0x02, 0x01, 0xb8, 0xb8, 0x06,
617 0x06, 0x81, /* RTP Port */ 0x14, 0x50,
618 /* RTCP Port */ 0x14,
619         0x51, /* RTP Port */ 0x14, 0x50, /* RTCP Port */ 0x00, 0x00, /* Dest IP */ 0x0a, 0x93,
620                 0x69, 0x05
621 };
622 static const unsigned char packet_send_open_audio_stream_tx3[] =
623         { 0x16, 0x1a, 0x30, 0xff, 0x00, 0x00, /* Codec */ 0x00, 0x02, 0x01, 0xb8, 0xb8, 0x06,
624 0x06, 0x81, /* RTP Local port */ 0x14, 0x50,
625         /* RTCP Port */ 0x00, 0x00, /* RTP Rmt Port */ 0x14, 0x50, /* RTCP Port */ 0x00, 0x00,
626                 /* Dest IP */ 0x0a, 0x93, 0x69, 0x05
627 };
628
629 static const unsigned char packet_send_arrow[] = { 0x17, 0x04, 0x04, 0x00 };
630 static const unsigned char packet_send_blink_cursor[] = { 0x17, 0x04, 0x10, 0x86 };
631 static const unsigned char packet_send_date_time2[] = { 0x17, 0x04, 0x17, 0x3d, 0x11, 0x09, 0x02, 0x0a, /*Month */ 0x05,   /*Day */
632         0x06, /*Hour */ 0x07, /*Minutes */ 0x08, 0x32
633 };
634 static const unsigned char packet_send_Contrast[] =
635         { 0x17, 0x04, 0x24, /*Contrast */ 0x08 };
636 static const unsigned char packet_send_start_timer[] =
637         { 0x17, 0x05, 0x0b, /*Timer option*/0x05, /* Timer ID */0x00, 0x17, 0x08, 0x16,
638         /* Text */ 'T', 'i', 'm', 'e', 'r' };
639 static const unsigned char packet_send_stop_timer[] = { 0x17, 0x05, 0x0b, 0x02, 0x00 };
640 static const unsigned char packet_send_icon[] = { 0x17, 0x05, 0x14, /*pos */ 0x00, /*icon */ 0x25 };      /* display an icon in front of the text zone */
641 static const unsigned char packet_send_S7[] = { 0x17, 0x06, 0x0f, 0x30, 0x07, 0x07 };
642 static const unsigned char packet_send_set_pos_cursor[] =
643         { 0x17, 0x06, 0x10, 0x81, 0x04, /*pos */ 0x20 };
644
645 static unsigned char monthlabels[] =
646         { 'J', 'a', 'n', 'F', 'e', 'b', 'M', 'a', 'r', 'A', 'p', 'r', 'M', 'a', 'y', 'J', 'u', 'n',
647                 'J', 'u', 'l', 'A', 'u', 'g', 'S', 'e', 'p', 'O', 'c', 't', 'N', 'o', 'v', 'D', 'e', 'c' };
648 static unsigned char packet_send_monthlabels_download[] =
649   { 0x17, 0x0a, 0x15, /* Month (3 char) */ '-', '-', '-', '-', '-', '-', 0x20 };
650 static const unsigned char packet_send_favorite[] =
651         { 0x17, 0x0f, 0x19, 0x10, /*pos */ 0x01, /*name */ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
652 0x20, 0x20, 0x20, 0x20, /*end_name */ 0x19,
653         0x05, 0x0f, /*pos */ 0x01, /*icone */ 0x00
654 };
655 static const unsigned char packet_send_title[] =
656         { 0x17, 0x10, 0x19, 0x02, /*text */ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
657 0x20, 0x20, 0x20, 0x20 /*end_text */  };
658 static const unsigned char packet_send_text[] =
659         { 0x17, 0x1e, 0x1b, 0x04, /*pos */ 0x00, /*inverse */ 0x25, /*text */ 0x20, 0x20,
660 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
661         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
662                 /*end_text */ 0x17, 0x04, 0x10, 0x87
663 };
664 static const unsigned char packet_send_status[] =
665         { 0x17, 0x20, 0x19, 0x08, /*text */ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
666 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
667         0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20    /*end_text */
668 };
669 static const unsigned char packet_send_status2[] =
670         { 0x17, 0x0b, 0x19, /* pos [08|28|48|68] */ 0x00, /* text */ 0x20, 0x20, 0x20, 0x20,
671 0x20, 0x20, 0x20 /* end_text */  };
672
673 /* Multiple character set support */
674 /* ISO-8859-1 - Western European) */
675 static const unsigned char packet_send_charset_iso_8859_1[] =
676         { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x41, 0x1b, 0x00 };
677 /* ISO-8859-2 - Central European) */
678 static const unsigned char packet_send_charset_iso_8859_2[] =
679         { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x42, 0x1b, 0x00 };
680 /* ISO-8859-4 - Baltic) */
681 static const unsigned char packet_send_charset_iso_8859_4[] =
682         { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x44, 0x1b, 0x00 };
683 /* ISO 8859-5 - cyrilic */
684 static const unsigned char packet_send_charset_iso_8859_5[] =
685         { 0x17, 0x08, 0x21, 0x1b, 0x2d, 0x4c, 0x1b, 0x00 };
686 /* Japaneese (ISO-2022-JP ?) */
687 static const unsigned char packet_send_charset_iso_2022_jp[] =
688         { 0x17, 0x08, 0x21, 0x1b, 0x29, 0x49, 0x1b, 0x7e };
689
690 static const unsigned char packet_send_led_update[] = { 0x19, 0x04, 0x00, 0x00 };
691
692 static const unsigned char packet_send_query_basic_manager_04[] = { 0x1a, 0x04, 0x01, 0x04 };
693 static const unsigned char packet_send_query_mac_address[] = { 0x1a, 0x04, 0x01, 0x08 };
694 static const unsigned char packet_send_query_basic_manager_10[] = { 0x1a, 0x04, 0x01, 0x10 };
695 static const unsigned char packet_send_S1[] = { 0x1a, 0x07, 0x07, 0x00, 0x00, 0x00, 0x13 };
696
697 static unsigned char packet_send_ping[] =
698         { 0x1e, 0x05, 0x12, 0x00, /*Watchdog timer */ 0x78 };
699
700 #define BUFFSEND unsigned char buffsend[64] = { 0x00, 0x00, 0xaa, 0xbb, 0x02, 0x01 }
701
702 static const char tdesc[] = "UNISTIM Channel Driver";
703 static const char channel_type[] = "USTM";
704
705 /*! Protos */
706 static struct ast_channel *unistim_new(struct unistim_subchannel *sub, int state, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor);
707 static int load_module(void);
708 static int reload(void);
709 static int unload_module(void);
710 static int reload_config(void);
711 static void unistim_set_owner(struct unistim_subchannel *sub, struct ast_channel *chan);
712 static void show_main_page(struct unistimsession *pte);
713 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,
714         const char *dest, int *cause);
715 static int unistim_call(struct ast_channel *ast, const char *dest, int timeout);
716 static int unistim_hangup(struct ast_channel *ast);
717 static int unistim_answer(struct ast_channel *ast);
718 static struct ast_frame *unistim_read(struct ast_channel *ast);
719 static int unistim_write(struct ast_channel *ast, struct ast_frame *frame);
720 static int unistim_indicate(struct ast_channel *ast, int ind, const void *data,
721         size_t datalen);
722 static int unistim_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
723 static int unistim_senddigit_begin(struct ast_channel *ast, char digit);
724 static int unistim_senddigit_end(struct ast_channel *ast, char digit,
725         unsigned int duration);
726 static int unistim_sendtext(struct ast_channel *ast, const char *text);
727
728 static int write_entry_history(struct unistimsession *pte, FILE * f, char c,
729         char *line1);
730 static void change_callerid(struct unistimsession *pte, int type, char *callerid);
731
732 static struct ast_channel_tech unistim_tech = {
733         .type = channel_type,
734         .description = tdesc,
735         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
736         .requester = unistim_request,
737         .call = unistim_call,
738         .hangup = unistim_hangup,
739         .answer = unistim_answer,
740         .read = unistim_read,
741         .write = unistim_write,
742         .indicate = unistim_indicate,
743         .fixup = unistim_fixup,
744         .send_digit_begin = unistim_senddigit_begin,
745         .send_digit_end = unistim_senddigit_end,
746         .send_text = unistim_sendtext,
747 };
748
749 static void send_start_rtp(struct unistim_subchannel *);
750
751 static void send_callerid_screen(struct unistimsession *, struct unistim_subchannel *);
752 static void key_favorite(struct unistimsession *, char);
753
754 static void handle_select_codec(struct unistimsession *);
755 static void handle_select_language(struct unistimsession *);
756 static int find_language(const char*);
757
758 static int unistim_free_sub(struct unistim_subchannel *);
759
760 static struct unistim_menu_item options_menu[] =
761 {
762         {"Change codec", STATE_SELECTCODEC, handle_select_codec},
763         {"Language", STATE_SELECTLANGUAGE, handle_select_language},
764         {NULL, 0, NULL}
765 };
766
767 static struct unistim_languages options_languages[] =
768 {
769         {"English", "en", ISO_8859_1, NULL},
770         {"French", "fr", ISO_8859_1, NULL},
771         {"Russian", "ru", ISO_8859_5, NULL},
772         {NULL, NULL, 0, NULL}
773 };
774
775 static char ustm_strcopy[1024];
776
777 struct ustm_lang_entry {
778         const char *str_orig;
779         const char *str_trans;
780 };
781
782 static int lang_hash_fn(const void *obj, const int flags)
783 {
784         const struct ustm_lang_entry *entry = obj;
785         return ast_str_hash(entry->str_orig);
786 }
787
788 static int lang_cmp_fn(void *obj, void *arg, int flags)
789 {
790         struct ustm_lang_entry *entry1 = obj;
791         struct ustm_lang_entry *entry2 = arg;
792
793         return (!strcmp(entry1->str_orig, entry2->str_orig)) ? (CMP_MATCH | CMP_STOP) : 0;
794 }
795
796 static const char *ustmtext(const char *str, struct unistimsession *pte)
797 {
798         struct ustm_lang_entry *lang_entry;
799         struct ustm_lang_entry le_search;
800         struct unistim_languages *lang = NULL;
801         int size;
802
803         if (pte->device) {
804                 lang = &options_languages[find_language(pte->device->language)];
805         }
806         if (!lang) {
807                 return str;
808         }
809         /* Check if specified language exists */
810         if (!lang->trans) {
811                 char tmp[1024], *p, *p_orig = NULL, *p_trans = NULL;
812                 FILE *f;
813
814                 if (!(lang->trans = ao2_container_alloc(8, lang_hash_fn, lang_cmp_fn))) {
815                         ast_log(LOG_ERROR, "Unable to allocate container for translation!\n");
816                         return str;
817                 }
818                 snprintf(tmp, sizeof(tmp), "%s/%s/%s.po", ast_config_AST_VAR_DIR,
819                          USTM_LANG_DIR, lang->lang_short);
820                 f = fopen(tmp, "r");
821                 if (!f) {
822                         ast_log(LOG_WARNING, "There is no translation file for '%s'\n", lang->lang_short);
823                         return str;
824                 }
825                 while (fgets(tmp, sizeof(tmp), f)) {
826                         if (!(p = strchr(tmp, '\n'))) {
827                                 ast_log(LOG_ERROR, "Too long line found in language file - truncated!\n");
828                                 continue;
829                         }
830                         *p = '\0';
831                         if (!(p = strchr(tmp, '"'))) {
832                                 continue;
833                         }
834                         if (tmp == strstr(tmp, "msgid")) {
835                                 p_orig = ast_strdup(p + 1);
836                                 p = strchr(p_orig, '"');
837                         } else if (tmp == strstr(tmp, "msgstr")) {
838                                 p_trans = ast_strdup(p + 1);
839                                 p = strchr(p_trans, '"');
840                         } else {
841                                 continue;
842                         }
843                         *p = '\0';
844                         if (!p_trans || !p_orig) {
845                                 continue;
846                         }
847                         if (ast_strlen_zero(p_trans)) {
848                                 ast_free(p_trans);
849                                 ast_free(p_orig);
850                                 p_trans = NULL;
851                                 p_orig = NULL;
852                                 continue;
853                         }
854                         if (!(lang_entry = ao2_alloc(sizeof(*lang_entry), NULL))) {
855                                 fclose(f);
856                                 return str;
857                         }
858
859                         lang_entry->str_trans = p_trans;
860                         lang_entry->str_orig = p_orig;
861                         ao2_link(lang->trans, lang_entry);
862                         p_trans = NULL;
863                         p_orig = NULL;
864                 }
865
866                 fclose(f);
867         }
868
869         le_search.str_orig = str;
870         if ((lang_entry = ao2_find(lang->trans, &le_search, OBJ_POINTER))) {
871                 size = strlen(lang_entry->str_trans)+1;
872                 if (size > 1024) {
873                         size = 1024;
874                 }
875                 memcpy(ustm_strcopy, lang_entry->str_trans, size);
876                 ao2_ref(lang_entry, -1);
877                 return ustm_strcopy;
878         }
879
880         return str;
881 }
882
883 static void display_last_error(const char *sz_msg)
884 {
885         /* Display the error message */
886         ast_log(LOG_WARNING, "%s : (%d) %s\n", sz_msg, errno, strerror(errno));
887 }
888
889 static unsigned int get_tick_count(void)
890 {
891         struct timeval now = ast_tvnow();
892
893         return (now.tv_sec * 1000) + (now.tv_usec / 1000);
894 }
895
896 /* Send data to a phone without retransmit nor buffering */
897 static void send_raw_client(int size, const unsigned char *data, struct sockaddr_in *addr_to,
898                             const struct sockaddr_in *addr_ourip)
899 {
900 #ifdef HAVE_PKTINFO
901         struct iovec msg_iov;
902         struct msghdr msg;
903         char buffer[CMSG_SPACE(sizeof(struct in_pktinfo))];
904         struct cmsghdr *ip_msg = (struct cmsghdr *) buffer;
905         struct in_pktinfo *pki = (struct in_pktinfo *) CMSG_DATA(ip_msg);
906
907         /* cast this to a non-const pointer, since the sendmsg() API
908          * does not provide read-only and write-only flavors of the
909          * structures used for its arguments, but in this case we know
910          * the data will not be modified
911          */
912         msg_iov.iov_base = (char *) data;
913         msg_iov.iov_len = size;
914
915         msg.msg_name = addr_to;  /* optional address */
916         msg.msg_namelen = sizeof(struct sockaddr_in);   /* size of address */
917         msg.msg_iov = &msg_iov;  /* scatter/gather array */
918         msg.msg_iovlen = 1;                  /* # elements in msg_iov */
919         msg.msg_control = ip_msg;       /* ancillary data */
920         msg.msg_controllen = sizeof(buffer);    /* ancillary data buffer len */
921         msg.msg_flags = 0;                    /* flags on received message */
922
923         ip_msg->cmsg_len = CMSG_LEN(sizeof(*pki));
924         ip_msg->cmsg_level = IPPROTO_IP;
925         ip_msg->cmsg_type = IP_PKTINFO;
926         pki->ipi_ifindex = 0;      /* Interface index, 0 = use interface specified in routing table */
927         pki->ipi_spec_dst.s_addr = addr_ourip->sin_addr.s_addr; /* Local address */
928         /* pki->ipi_addr = ;   Header Destination address - ignored by kernel */
929
930 #ifdef DUMP_PACKET
931         if (unistimdebug) {
932                 int tmp;
933                 ast_verb(0, "\n**> From %s sending %d bytes to %s ***\n",
934                                         ast_inet_ntoa(addr_ourip->sin_addr), (int) size,
935                                         ast_inet_ntoa(addr_to->sin_addr));
936                 for (tmp = 0; tmp < size; tmp++)
937                         ast_verb(0, "%.2x ", (unsigned char) data[tmp]);
938                 ast_verb(0, "\n******************************************\n");
939
940         }
941 #endif
942
943         if (sendmsg(unistimsock, &msg, 0) == -1) {
944                 display_last_error("Error sending datas");
945         }
946 #else
947         if (sendto(unistimsock, data, size, 0, (struct sockaddr *) addr_to, sizeof(*addr_to))
948                 == -1)
949                 display_last_error("Error sending datas");
950 #endif
951 }
952
953 static void send_client(int size, const unsigned char *data, struct unistimsession *pte)
954 {
955         unsigned int tick;
956         int buf_pos;
957         unsigned short seq = ntohs(++pte->seq_server);
958
959         ast_mutex_lock(&pte->lock);
960         buf_pos = pte->last_buf_available;
961
962         if (buf_pos >= MAX_BUF_NUMBER) {
963                 ast_log(LOG_WARNING, "Error : send queue overflow\n");
964                 ast_mutex_unlock(&pte->lock);
965                 return;
966         }
967         memcpy((void *)data + sizeof(unsigned short), (void *)&seq, sizeof(unsigned short));
968         pte->wsabufsend[buf_pos].len = size;
969         memcpy(pte->wsabufsend[buf_pos].buf, data, size);
970
971         tick = get_tick_count();
972         pte->timeout = tick + RETRANSMIT_TIMER;
973
974 /*#ifdef DUMP_PACKET */
975         if (unistimdebug) {
976                 ast_verb(6, "Sending datas with seq #0x%.4x Using slot #%d :\n", (unsigned)pte->seq_server, buf_pos);
977         }
978 /*#endif */
979         send_raw_client(pte->wsabufsend[buf_pos].len, pte->wsabufsend[buf_pos].buf, &(pte->sin),
980                                   &(pte->sout));
981         pte->last_buf_available++;
982         ast_mutex_unlock(&pte->lock);
983 }
984
985 static void send_ping(struct unistimsession *pte)
986 {
987         BUFFSEND;
988         if (unistimdebug) {
989                 ast_verb(6, "Sending ping\n");
990         }
991         pte->tick_next_ping = get_tick_count() + unistim_keepalive;
992         memcpy(buffsend + SIZE_HEADER, packet_send_ping, sizeof(packet_send_ping));
993         send_client(SIZE_HEADER + sizeof(packet_send_ping), buffsend, pte);
994 }
995
996 static int get_to_address(int fd, struct sockaddr_in *toAddr)
997 {
998 #ifdef HAVE_PKTINFO
999         int err;
1000         struct msghdr msg;
1001         struct {
1002                 struct cmsghdr cm;
1003                 int len;
1004                 struct in_addr address;
1005         } ip_msg;
1006
1007         /* Zero out the structures before we use them */
1008         /* This sets several key values to NULL */
1009         memset(&msg, 0, sizeof(msg));
1010         memset(&ip_msg, 0, sizeof(ip_msg));
1011
1012         /* Initialize the message structure */
1013         msg.msg_control = &ip_msg;
1014         msg.msg_controllen = sizeof(ip_msg);
1015         /* Get info about the incoming packet */
1016         err = recvmsg(fd, &msg, MSG_PEEK);
1017         if (err == -1) {
1018                 ast_log(LOG_WARNING, "recvmsg returned an error: %s\n", strerror(errno));
1019         }
1020         memcpy(&toAddr->sin_addr, &ip_msg.address, sizeof(struct in_addr));
1021         return err;
1022 #else
1023         memcpy(&toAddr, &public_ip, sizeof(&toAddr));
1024         return 0;
1025 #endif
1026 }
1027
1028 /* Allocate memory & initialize structures for a new phone */
1029 /* addr_from : ip address of the phone */
1030 static struct unistimsession *create_client(const struct sockaddr_in *addr_from)
1031 {
1032         int tmp;
1033         struct unistimsession *s;
1034
1035         if (!(s = ast_calloc(1, sizeof(*s))))
1036                 return NULL;
1037
1038         memcpy(&s->sin, addr_from, sizeof(struct sockaddr_in));
1039         get_to_address(unistimsock, &s->sout);
1040         s->sout.sin_family = AF_INET;
1041         if (unistimdebug) {
1042                 ast_verb(0, "Creating a new entry for the phone from %s received via server ip %s\n",
1043                          ast_inet_ntoa(addr_from->sin_addr), ast_inet_ntoa(s->sout.sin_addr));
1044         }
1045         ast_mutex_init(&s->lock);
1046         ast_mutex_lock(&sessionlock);
1047         s->next = sessions;
1048         sessions = s;
1049
1050         s->timeout = get_tick_count() + RETRANSMIT_TIMER;
1051         s->state = STATE_INIT;
1052         s->tick_next_ping = get_tick_count() + unistim_keepalive;
1053         /* Initialize struct wsabuf  */
1054         for (tmp = 0; tmp < MAX_BUF_NUMBER; tmp++) {
1055                 s->wsabufsend[tmp].buf = s->buf[tmp];
1056         }
1057         ast_mutex_unlock(&sessionlock);
1058         return s;
1059 }
1060
1061 static void send_end_call(struct unistimsession *pte)
1062 {
1063         BUFFSEND;
1064         if (unistimdebug) {
1065                 ast_verb(0, "Sending end call\n");
1066         }
1067         memcpy(buffsend + SIZE_HEADER, packet_send_end_call, sizeof(packet_send_end_call));
1068         send_client(SIZE_HEADER + sizeof(packet_send_end_call), buffsend, pte);
1069 }
1070
1071 static void set_ping_timer(struct unistimsession *pte)
1072 {
1073         unsigned int tick = 0;  /* XXX what is this for, anyways */
1074
1075         pte->timeout = pte->tick_next_ping;
1076         DEBUG_TIMER("tick = %u next ping at %u tick\n", tick, pte->timeout);
1077         return;
1078 }
1079
1080 /* Checking if our send queue is empty,
1081  * if true, setting up a timer for keepalive */
1082 static void check_send_queue(struct unistimsession *pte)
1083 {
1084         /* Check if our send queue contained only one element */
1085         if (pte->last_buf_available == 1) {
1086                 if (unistimdebug) {
1087                         ast_verb(6, "Our single packet was ACKed.\n");
1088                 }
1089                 pte->last_buf_available--;
1090                 set_ping_timer(pte);
1091                 return;
1092         }
1093         /* Check if this ACK catch up our latest packet */
1094         else if (pte->last_seq_ack + 1 == pte->seq_server + 1) {
1095                 if (unistimdebug) {
1096                         ast_verb(6, "Our send queue is completely ACKed.\n");
1097                 }
1098                 pte->last_buf_available = 0;    /* Purge the send queue */
1099                 set_ping_timer(pte);
1100                 return;
1101         }
1102         if (unistimdebug) {
1103                 ast_verb(6, "We still have packets in our send queue\n");
1104         }
1105         return;
1106 }
1107
1108 static void send_start_timer(struct unistimsession *pte)
1109 {
1110         BUFFSEND;
1111         if (unistimdebug) {
1112                 ast_verb(0, "Sending start timer\n");
1113         }
1114         memcpy(buffsend + SIZE_HEADER, packet_send_start_timer, sizeof(packet_send_start_timer));
1115         send_client(SIZE_HEADER + sizeof(packet_send_start_timer), buffsend, pte);
1116 }
1117
1118 static void send_stop_timer(struct unistimsession *pte)
1119 {
1120         BUFFSEND;
1121         if (unistimdebug) {
1122                 ast_verb(0, "Sending stop timer\n");
1123         }
1124         memcpy(buffsend + SIZE_HEADER, packet_send_stop_timer, sizeof(packet_send_stop_timer));
1125         send_client(SIZE_HEADER + sizeof(packet_send_stop_timer), buffsend, pte);
1126 }
1127
1128 static void send_icon(unsigned char pos, unsigned char status, struct unistimsession *pte)
1129 {
1130         BUFFSEND;
1131         if (unistimdebug) {
1132                 ast_verb(0, "Sending icon pos %d with status 0x%.2x\n", pos, (unsigned)status);
1133         }
1134         memcpy(buffsend + SIZE_HEADER, packet_send_icon, sizeof(packet_send_icon));
1135         buffsend[9] = pos;
1136         buffsend[10] = status;
1137         send_client(SIZE_HEADER + sizeof(packet_send_icon), buffsend, pte);
1138 }
1139
1140 static void send_expansion_next(struct unistimsession *pte)
1141 {
1142         BUFFSEND;
1143         memcpy(buffsend + SIZE_HEADER, packet_send_expansion_next, sizeof(packet_send_expansion_next));
1144         send_client(SIZE_HEADER + sizeof(packet_send_expansion_next), buffsend, pte);
1145 }
1146
1147
1148 static void send_expansion_icon(unsigned char pos, unsigned char status, struct unistimsession *pte)
1149 {
1150         BUFFSEND;
1151         if (unistimdebug) {
1152                 ast_verb(0, "Sending expansion icon pos %d with status 0x%.2x\n", pos, (unsigned)status);
1153         }
1154         memcpy(buffsend + SIZE_HEADER, packet_send_expansion_icon, sizeof(packet_send_expansion_icon));
1155         buffsend[10] = pos;
1156         buffsend[11] = status;
1157         send_client(SIZE_HEADER + sizeof(packet_send_expansion_icon), buffsend, pte);
1158 }
1159
1160 /* inverse : TEXT_INVERSE : yes, TEXT_NORMAL  : no */
1161 static void send_expansion_text(unsigned char pos, struct unistimsession *pte, const char *text)
1162 {
1163         int i;
1164         BUFFSEND;
1165         if (!text) {
1166                 ast_log(LOG_ERROR, "[expansion] Asked to display NULL text (pos %d)\n", pos);
1167                 return;
1168         }
1169         if (unistimdebug) {
1170                 ast_verb(0, "[expansion] Sending text at pos %d\n", pos);
1171         }
1172         memcpy(buffsend + SIZE_HEADER, packet_send_expansion_text, sizeof(packet_send_expansion_text));
1173         buffsend[10] = pos;
1174         i = strlen(text);
1175         if (i > TEXT_LENGTH_MAX) {
1176                 i = TEXT_LENGTH_MAX;
1177         }
1178         memcpy(buffsend + 11, text, i);
1179         send_client(SIZE_HEADER + sizeof(packet_send_expansion_text), buffsend, pte);
1180 }
1181
1182 static void send_tone(struct unistimsession *pte, uint16_t tone1, uint16_t tone2)
1183 {
1184         BUFFSEND;
1185         if (!tone1) {
1186                 if (unistimdebug) {
1187                         ast_verb(0, "Sending Stream Based Tone Off\n");
1188                 }
1189                 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_off,
1190                            sizeof(packet_send_stream_based_tone_off));
1191                 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_off), buffsend, pte);
1192                 return;
1193         }
1194         /* Since most of the world use a continuous tone, it's useless
1195            if (unistimdebug)
1196            ast_verb(0, "Sending Stream Based Tone Cadence Download\n");
1197            memcpy (buffsend + SIZE_HEADER, packet_send_StreamBasedToneCad, sizeof (packet_send_StreamBasedToneCad));
1198            send_client (SIZE_HEADER + sizeof (packet_send_StreamBasedToneCad), buffsend, pte); */
1199         if (unistimdebug) {
1200                 ast_verb(0, "Sending Stream Based Tone Frequency Component List Download %d %d\n", tone1, tone2);
1201         }
1202         tone1 *= 8;
1203         if (!tone2) {
1204                 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_single_freq,
1205                            sizeof(packet_send_stream_based_tone_single_freq));
1206                 buffsend[10] = (tone1 & 0xff00) >> 8;
1207                 buffsend[11] = (tone1 & 0x00ff);
1208                 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_single_freq), buffsend,
1209                                    pte);
1210         } else {
1211                 tone2 *= 8;
1212                 memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_dial_freq,
1213                            sizeof(packet_send_stream_based_tone_dial_freq));
1214                 buffsend[10] = (tone1 & 0xff00) >> 8;
1215                 buffsend[11] = (tone1 & 0x00ff);
1216                 buffsend[12] = (tone2 & 0xff00) >> 8;
1217                 buffsend[13] = (tone2 & 0x00ff);
1218                 send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_dial_freq), buffsend,
1219                                    pte);
1220         }
1221
1222         if (unistimdebug) {
1223                 ast_verb(0, "Sending Stream Based Tone On\n");
1224         }
1225         memcpy(buffsend + SIZE_HEADER, packet_send_stream_based_tone_on,
1226                    sizeof(packet_send_stream_based_tone_on));
1227         send_client(SIZE_HEADER + sizeof(packet_send_stream_based_tone_on), buffsend, pte);
1228 }
1229
1230 /* Positions for favorites
1231  |--------------------|
1232  |  5            2    | <-- not on screen in i2002
1233  |  4            1    |
1234  |  3            0    |
1235
1236
1237  KEM Positions
1238
1239  |--------------------|
1240  |  12           24   |
1241  |  11           23   |
1242  |  10           22   |
1243  |  9            21   |
1244  |  8            20   |
1245  |  7            19   |
1246  |  6            18   |
1247  |  5            17   |
1248  |  4            16   |
1249  |  3            15   |
1250  |  2            14   |
1251  |  1            13   |
1252
1253 */
1254
1255 /* status (icons) : 00 = nothing, 2x/3x = see parser.h, 4x/5x = blink fast, 6x/7x = blink slow */
1256 static void
1257 send_favorite(unsigned char pos, unsigned char status, struct unistimsession *pte,
1258                          const char *text)
1259 {
1260         BUFFSEND;
1261         int i;
1262
1263         if (unistimdebug) {
1264                 ast_verb(0, "Sending favorite pos %d with status 0x%.2x\n", pos, (unsigned)status);
1265         }
1266         memcpy(buffsend + SIZE_HEADER, packet_send_favorite, sizeof(packet_send_favorite));
1267         buffsend[10] = pos;
1268         buffsend[24] = pos;
1269         buffsend[25] = status;
1270         i = strlen(ustmtext(text, pte));
1271         if (i > FAV_MAX_LENGTH) {
1272                 i = FAV_MAX_LENGTH;
1273         }
1274         memcpy(buffsend + FAV_MAX_LENGTH + 1, ustmtext(text, pte), i);
1275         send_client(SIZE_HEADER + sizeof(packet_send_favorite), buffsend, pte);
1276 }
1277
1278 static void send_favorite_short(unsigned char pos, unsigned char status, struct unistimsession *pte) {
1279         send_favorite(pos, status, pte, pte->device->softkeylabel[pos]);
1280         return;
1281 }
1282
1283 static void send_favorite_selected(unsigned char status, struct unistimsession *pte) {
1284         if (pte->device->selected != -1) {
1285                 send_favorite(pte->device->selected, status, pte, pte->device->softkeylabel[pte->device->selected]);
1286         }
1287         return;
1288 }
1289
1290 static void send_expansion_short(unsigned char pos, unsigned char status, struct unistimsession *pte) {
1291         send_expansion_icon(pos, status, pte);
1292         send_expansion_text(pos, pte, ustmtext(pte->device->expsoftkeylabel[pos], pte));
1293         send_expansion_next(pte);
1294         return;
1295 }
1296
1297 static int soft_key_visible(struct unistim_device* d, unsigned char num)
1298 {
1299         if(d->height == 1 && num % 3 == 2) {
1300                 return 0;
1301         }
1302         return 1;
1303 }
1304
1305 static void refresh_all_favorite(struct unistimsession *pte)
1306 {
1307         unsigned char i = 0;
1308         char data[256];
1309         struct unistim_line *line;
1310         line = AST_LIST_FIRST(&pte->device->lines);
1311
1312         if (unistimdebug) {
1313                 ast_verb(0, "Refreshing all favorite\n");
1314         }
1315         for (i = 0; i < FAVNUM; i++) {
1316                 unsigned char status = pte->device->softkeyicon[i];
1317
1318                 if (!soft_key_visible(pte->device, i)) {
1319                         continue;
1320                 }
1321                 if (!strcasecmp(pte->device->softkeylabel[i], "DND") && line) {
1322                         if (!ast_db_get("DND", line->name, data, sizeof(data))) {
1323                                 status = FAV_ICON_SPEAKER_ONHOOK_WHITE;
1324                         }
1325                 }
1326
1327                 send_favorite_short(i, status, pte);
1328         }
1329         if (pte->device->hasexp) {
1330                 for (i = 0; i < EXPNUM; i++) {
1331                         send_expansion_short(i, FAV_ICON_NONE, pte);
1332                 }
1333         }
1334 }
1335
1336 static int is_key_favorite(struct unistim_device *d, int fav)
1337 {
1338         if ((fav < 0) && (fav > 5)) {
1339                 return 0;
1340         }
1341         if (d->sline[fav]) {
1342                 return 0;
1343         }
1344         if (d->softkeynumber[fav][0] == '\0') {
1345                 return 0;
1346         }
1347         return 1;
1348 }
1349
1350 static int is_key_line(struct unistim_device *d, int fav)
1351 {
1352         if ((fav < 0) && (fav > 5)) {
1353                 return 0;
1354         }
1355         if (!d->sline[fav]) {
1356                 return 0;
1357         }
1358         if (is_key_favorite(d, fav)) {
1359                 return 0;
1360         }
1361         return 1;
1362 }
1363
1364 static int get_active_softkey(struct unistimsession *pte)
1365 {
1366         return pte->device->selected;
1367 }
1368
1369 static int get_avail_softkey(struct unistimsession *pte, const char* name)
1370 {
1371         int i;
1372
1373         if (!is_key_line(pte->device, pte->device->selected)) {
1374                 pte->device->selected = -1;
1375         }
1376         for (i = 0; i < FAVNUM; i++) {
1377                 if (pte->device->selected != -1 && pte->device->selected != i) {
1378                         continue;
1379                 }
1380                 if (!soft_key_visible(pte->device, i)) {
1381                         continue;
1382                 }
1383                 if (pte->device->ssub[i]) {
1384                         continue;
1385                 }
1386                 if (is_key_line(pte->device, i)) {
1387                         if (name && strcmp(name, pte->device->sline[i]->name)) {
1388                                 continue;
1389                         }
1390                         if (unistimdebug) {
1391                                 ast_verb(0, "Found softkey %d for device %s\n", i, name);
1392                         }
1393                         return i;
1394                 }
1395         }
1396         return -1;
1397 }
1398
1399
1400 /* Change the status for this phone (pte) and update for each phones where pte is bookmarked
1401  * use FAV_ICON_*_BLACK constant in status parameters */
1402 static void change_favorite_icon(struct unistimsession *pte, unsigned char status)
1403 {
1404         struct unistim_device *d = devices;
1405         int i;
1406         /* Update the current phone line softkey icon */
1407         if (pte->state != STATE_CLEANING) {
1408                 int softkeylinepos = get_active_softkey(pte);
1409                 if (softkeylinepos != -1) {
1410                         send_favorite_short(softkeylinepos, status, pte);
1411                 }
1412         }
1413         /* Notify other phones if we're in their bookmark */
1414         while (d) {
1415                 for (i = 0; i < FAVNUM; i++) {
1416                         if (d->sp[i] == pte->device) {  /* It's us ? */
1417                                 if (d->softkeyicon[i] != status) {      /* Avoid resending the same icon */
1418                                         d->softkeyicon[i] = status;
1419                                         if (d->session) {
1420                                                 send_favorite(i, status + 1, d->session, d->softkeylabel[i]);
1421                                         }
1422                                 }
1423                         }
1424                 }
1425                 d = d->next;
1426         }
1427 }
1428
1429 static int register_extension(const struct unistimsession *pte)
1430 {
1431         struct unistim_line *line;
1432         line = AST_LIST_FIRST(&pte->device->lines);
1433         if (unistimdebug) {
1434                 ast_verb(0, "Trying to register extension '%s' into context '%s' to %s\n",
1435                                         pte->device->extension_number, pte->device->context,
1436                                         line->fullname);
1437         }
1438         return ast_add_extension(pte->device->context, 0,
1439                                                          pte->device->extension_number, 1, NULL, NULL, "Dial",
1440                                                          line->fullname, 0, "Unistim");
1441 }
1442
1443 static int unregister_extension(const struct unistimsession *pte)
1444 {
1445         if (unistimdebug) {
1446                 ast_verb(0, "Trying to unregister extension '%s' context '%s'\n",
1447                                         pte->device->extension_number, pte->device->context);
1448         }
1449         return ast_context_remove_extension(pte->device->context,
1450                                                                                 pte->device->extension_number, 1, "Unistim");
1451 }
1452
1453 /* Free memory allocated for a phone */
1454 static void close_client(struct unistimsession *s)
1455 {
1456         struct unistim_subchannel *sub = NULL;
1457         struct unistimsession *cur, *prev = NULL;
1458         ast_mutex_lock(&sessionlock);
1459         cur = sessions;
1460         /* Looking for the session in the linked chain */
1461         while (cur) {
1462                 if (cur == s) {
1463                         break;
1464                 }
1465                 prev = cur;
1466                 cur = cur->next;
1467         }
1468         if (cur) {                                    /* Session found ? */
1469                 if (cur->device) {            /* This session was registered ? */
1470                         s->state = STATE_CLEANING;
1471                         if (unistimdebug) {
1472                                 ast_verb(0, "close_client session %p device %p\n", s, s->device);
1473                         }
1474                         change_favorite_icon(s, FAV_ICON_NONE);
1475                         ast_mutex_lock(&s->device->lock);
1476                         AST_LIST_LOCK(&s->device->subs);
1477                         AST_LIST_TRAVERSE_SAFE_BEGIN(&s->device->subs, sub, list) {
1478                                 if (!sub) {
1479                                         continue;
1480                                 }
1481                                 if (sub->owner) {       /* Call in progress ? */
1482                                         if (unistimdebug) {
1483                                                 ast_verb(0, "Aborting call\n");
1484                                         }
1485                                         ast_queue_hangup_with_cause(sub->owner, AST_CAUSE_NETWORK_OUT_OF_ORDER);
1486                                 } else {
1487                                         if (unistimdebug) {
1488                                                 ast_debug(1, "Released sub %u of channel %s@%s\n", sub->subtype, sub->parent->name, s->device->name);
1489                                         }
1490                                         AST_LIST_REMOVE_CURRENT(list);
1491                                         unistim_free_sub(sub);
1492                                 }
1493                         }
1494                         AST_LIST_TRAVERSE_SAFE_END;
1495                         AST_LIST_UNLOCK(&s->device->subs);
1496
1497                         if (!ast_strlen_zero(s->device->extension_number)) {
1498                                 unregister_extension(s);
1499                         }
1500                         cur->device->session = NULL;
1501                         ast_mutex_unlock(&s->device->lock);
1502                 } else {
1503                         if (unistimdebug) {
1504                                 ast_verb(0, "Freeing an unregistered client\n");
1505                         }
1506                 }
1507                 if (prev) {
1508                         prev->next = cur->next;
1509                 } else {
1510                         sessions = cur->next;
1511                 }
1512                 ast_mutex_destroy(&s->lock);
1513                 ast_free(s);
1514         } else {
1515                 ast_log(LOG_WARNING, "Trying to delete non-existent session %p?\n", s);
1516         }
1517         ast_mutex_unlock(&sessionlock);
1518         return;
1519 }
1520
1521 /* Return 1 if the session chained link was modified */
1522 static int send_retransmit(struct unistimsession *pte)
1523 {
1524         int i;
1525
1526         ast_mutex_lock(&pte->lock);
1527         if (++pte->nb_retransmit >= NB_MAX_RETRANSMIT) {
1528                 if (unistimdebug) {
1529                         ast_verb(0, "Too many retransmit - freeing client\n");
1530                 }
1531                 ast_mutex_unlock(&pte->lock);
1532                 close_client(pte);
1533                 return 1;
1534         }
1535         pte->timeout = get_tick_count() + RETRANSMIT_TIMER;
1536
1537         for (i = pte->last_buf_available - (pte->seq_server - pte->last_seq_ack);
1538                  i < pte->last_buf_available; i++) {
1539                 if (i < 0) {
1540                         ast_log(LOG_WARNING,
1541                                         "Asked to retransmit an ACKed slot ! last_buf_available=%d, seq_server = #0x%.4x last_seq_ack = #0x%.4x\n",
1542                                         pte->last_buf_available, (unsigned)pte->seq_server, (unsigned)pte->last_seq_ack);
1543                         continue;
1544                 }
1545
1546                 if (unistimdebug) {
1547                         unsigned short *sbuf = (unsigned short *) pte->wsabufsend[i].buf;
1548                         unsigned short seq;
1549
1550                         seq = ntohs(sbuf[1]);
1551                         ast_verb(0, "Retransmit slot #%d (seq=#0x%.4x), last ack was #0x%.4x\n", i,
1552                                                 (unsigned)seq, (unsigned)pte->last_seq_ack);
1553                 }
1554                 send_raw_client(pte->wsabufsend[i].len, pte->wsabufsend[i].buf, &pte->sin,
1555                                           &pte->sout);
1556         }
1557         ast_mutex_unlock(&pte->lock);
1558         return 0;
1559 }
1560
1561 /* inverse : TEXT_INVERSE : yes, TEXT_NORMAL  : no */
1562 static void send_text(unsigned char pos, unsigned char inverse, struct unistimsession *pte,
1563                  const char *text)
1564 {
1565         int i;
1566         BUFFSEND;
1567         if (!text) {
1568                 ast_log(LOG_ERROR, "Asked to display NULL text (pos %d, inverse flag %d)\n", pos, inverse);
1569                 return;
1570         }
1571         if (pte->device && pte->device->height == 1 && pos != TEXT_LINE0) {
1572                 return;
1573         }
1574         if (unistimdebug) {
1575                 ast_verb(0, "Sending text at pos %d, inverse flag %d\n", pos, inverse);
1576         }
1577         memcpy(buffsend + SIZE_HEADER, packet_send_text, sizeof(packet_send_text));
1578         buffsend[10] = pos;
1579         buffsend[11] = inverse;
1580         i = strlen(text);
1581         if (i > TEXT_LENGTH_MAX) {
1582                 i = TEXT_LENGTH_MAX;
1583         }
1584         memcpy(buffsend + 12, text, i);
1585         send_client(SIZE_HEADER + sizeof(packet_send_text), buffsend, pte);
1586 }
1587
1588 static void send_text_status(struct unistimsession *pte, const char *text)
1589 {
1590         BUFFSEND;
1591         int i;
1592         if (unistimdebug) {
1593                 ast_verb(0, "Sending status text\n");
1594         }
1595         if (pte->device) {
1596                 if (pte->device->status_method == 1) {  /* For new firmware and i2050 soft phone */
1597                         int n = strlen(text);
1598                         /* Must send individual button separately */
1599                         int j;
1600                         for (i = 0, j = 0; i < 4; i++, j += 7) {
1601                                 int pos = 0x08 + (i * 0x20);
1602                                 memcpy(buffsend + SIZE_HEADER, packet_send_status2,
1603                                            sizeof(packet_send_status2));
1604
1605                                 buffsend[9] = pos;
1606                                 memcpy(buffsend + 10, (j < n) ? (text + j) : "       ", 7);
1607                                 send_client(SIZE_HEADER + sizeof(packet_send_status2), buffsend, pte);
1608                         }
1609                         return;
1610                 }
1611         }
1612
1613         memcpy(buffsend + SIZE_HEADER, packet_send_status, sizeof(packet_send_status));
1614         i = strlen(text);
1615         if (i > STATUS_LENGTH_MAX) {
1616                 i = STATUS_LENGTH_MAX;
1617         }
1618         memcpy(buffsend + 10, text, i);
1619         send_client(SIZE_HEADER + sizeof(packet_send_status), buffsend, pte);
1620
1621 }
1622
1623 static void send_led_update(struct unistimsession *pte, unsigned char led)
1624 {
1625         BUFFSEND;
1626         if (unistimdebug) {
1627                 ast_verb(0, "Sending led_update (%x)\n", (unsigned)led);
1628         }
1629         memcpy(buffsend + SIZE_HEADER, packet_send_led_update, sizeof(packet_send_led_update));
1630         buffsend[9] = led;
1631         send_client(SIZE_HEADER + sizeof(packet_send_led_update), buffsend, pte);
1632 }
1633
1634 static void send_mute(struct unistimsession *pte, unsigned char mute)
1635 {
1636 /*
1637         0x00 = unmute TX, 0x01 = mute TX
1638         0x20 = unmute RX, 0x21 = mute RX
1639 */
1640         BUFFSEND;
1641         if (unistimdebug) {
1642                 ast_verb(0, "Sending mute packet (%x)\n", (unsigned)mute);
1643         }
1644         memcpy(buffsend + SIZE_HEADER, packet_send_mute, sizeof(packet_send_mute));
1645         buffsend[9] = mute;
1646         send_client(SIZE_HEADER + sizeof(packet_send_mute), buffsend, pte);
1647 }
1648
1649
1650 /* output = OUTPUT_HANDSET, OUTPUT_HEADPHONE or OUTPUT_SPEAKER
1651  * volume = VOLUME_LOW, VOLUME_NORMAL, VOLUME_INSANELY_LOUD
1652  * mute = MUTE_OFF, MUTE_ON */
1653 static void
1654 send_select_output(struct unistimsession *pte, unsigned char output, unsigned char volume,
1655                                  unsigned char mute)
1656 {
1657         BUFFSEND;
1658         int mute_icon = -1;
1659         if (unistimdebug) {
1660                 ast_verb(0, "Sending select output packet output=%x volume=%x mute=%x\n",
1661                         (unsigned)output, (unsigned)volume, (unsigned)mute);
1662         }
1663         memcpy(buffsend + SIZE_HEADER, packet_send_select_output,
1664                    sizeof(packet_send_select_output));
1665         buffsend[9] = output;
1666         if (output == OUTPUT_SPEAKER && volume == VOLUME_LOW) {
1667                 volume = VOLUME_LOW_SPEAKER;
1668         }
1669         buffsend[10] = volume;
1670         if (mute == MUTE_ON_DISCRET) {
1671                 buffsend[11] = MUTE_ON;
1672         } else {
1673                 buffsend[11] = mute;
1674         }
1675         send_client(SIZE_HEADER + sizeof(packet_send_select_output), buffsend, pte);
1676         if (output == OUTPUT_HANDSET) {
1677                 mute_icon = (mute == MUTE_ON) ? FAV_ICON_ONHOLD_BLACK : FAV_ICON_OFFHOOK_BLACK;
1678                 send_led_update(pte, LED_SPEAKER_OFF);
1679                 send_led_update(pte, LED_HEADPHONE_OFF);
1680         } else if (output == OUTPUT_HEADPHONE) {
1681                 mute_icon = (mute == MUTE_ON)? FAV_ICON_HEADPHONES_ONHOLD : FAV_ICON_HEADPHONES;
1682                 send_led_update(pte, LED_SPEAKER_OFF);
1683                 send_led_update(pte, LED_HEADPHONE_ON);
1684         } else if (output == OUTPUT_SPEAKER) {
1685                 send_led_update(pte, LED_SPEAKER_ON);
1686                 send_led_update(pte, LED_HEADPHONE_OFF);
1687                 if (pte->device->receiver_state == STATE_OFFHOOK) {
1688                         mute_icon = (mute == MUTE_ON)? FAV_ICON_SPEAKER_ONHOLD_BLACK : FAV_ICON_SPEAKER_ONHOOK_BLACK;
1689                 } else {
1690                         mute_icon = (mute == MUTE_ON)? FAV_ICON_SPEAKER_ONHOLD_BLACK : FAV_ICON_SPEAKER_OFFHOOK_BLACK;
1691                 }
1692         } else {
1693                 ast_log(LOG_WARNING, "Invalid output (%d)\n", output);
1694         }
1695         if (mute_icon != -1) {
1696                 change_favorite_icon(pte, mute_icon);
1697         }
1698         if (output != pte->device->output) {
1699                 pte->device->previous_output = pte->device->output;
1700         }
1701         pte->device->output = output;
1702 }
1703 static void send_ring(struct unistimsession *pte, char volume, char style)
1704 {
1705         BUFFSEND;
1706         if (unistimdebug) {
1707                 ast_verb(0, "Sending ring packet\n");
1708         }
1709         memcpy(buffsend + SIZE_HEADER, packet_send_ring, sizeof(packet_send_ring));
1710         buffsend[24] = style + 0x10;
1711         buffsend[29] = volume * 0x10;
1712         send_client(SIZE_HEADER + sizeof(packet_send_ring), buffsend, pte);
1713 }
1714
1715 static void send_no_ring(struct unistimsession *pte)
1716 {
1717         BUFFSEND;
1718         if (unistimdebug) {
1719                 ast_verb(0, "Sending no ring packet\n");
1720         }
1721         memcpy(buffsend + SIZE_HEADER, packet_send_no_ring, sizeof(packet_send_no_ring));
1722         send_client(SIZE_HEADER + sizeof(packet_send_no_ring), buffsend, pte);
1723 }
1724
1725 static void send_texttitle(struct unistimsession *pte, const char *text)
1726 {
1727         BUFFSEND;
1728         int i;
1729         if (unistimdebug) {
1730                 ast_verb(0, "Sending title text\n");
1731         }
1732         memcpy(buffsend + SIZE_HEADER, packet_send_title, sizeof(packet_send_title));
1733         i = strlen(text);
1734         if (i > 12) {
1735                 i = 12;
1736         }
1737         memcpy(buffsend + 10, text, i);
1738         send_client(SIZE_HEADER + sizeof(packet_send_title), buffsend, pte);
1739 }
1740
1741 static void send_idle_clock(struct unistimsession *pte)
1742 {
1743         send_text(TEXT_LINE0, TEXT_NORMAL, pte, "");
1744 }
1745
1746 static void send_month_labels(struct unistimsession *pte, int month)
1747 {
1748         BUFFSEND;
1749         char month_name[MONTH_LABEL_SIZE + 1];
1750         int i = 0;
1751         if (unistimdebug) {
1752                 ast_verb(0, "Sending Month Labels\n");
1753         }
1754         month_name[MONTH_LABEL_SIZE] = '\0';
1755         memcpy(buffsend + SIZE_HEADER, packet_send_monthlabels_download, sizeof(packet_send_monthlabels_download));
1756         while (i < 2) {
1757                 memcpy(month_name, &monthlabels[month * MONTH_LABEL_SIZE], MONTH_LABEL_SIZE);
1758                 memcpy(buffsend + SIZE_HEADER + 3 + i*MONTH_LABEL_SIZE, ustmtext(month_name, pte), MONTH_LABEL_SIZE);
1759                 ast_log(LOG_WARNING,"%s\n", month_name);
1760                 ast_log(LOG_WARNING,"%s\n", ustmtext(month_name, pte));
1761                 month = (month + 1)%12;
1762                 i++;
1763         }
1764         send_client(SIZE_HEADER + sizeof(packet_send_monthlabels_download), buffsend, pte);
1765 }
1766
1767
1768 static void send_date_time(struct unistimsession *pte)
1769 {
1770         BUFFSEND;
1771         struct timeval now = ast_tvnow();
1772         struct ast_tm atm = { 0, };
1773
1774         if (unistimdebug) {
1775                 ast_verb(0, "Sending Time & Date\n");
1776         }
1777         memcpy(buffsend + SIZE_HEADER, packet_send_date_time, sizeof(packet_send_date_time));
1778         ast_localtime(&now, &atm, NULL);
1779         buffsend[10] = (unsigned char) atm.tm_mon + 1;
1780         buffsend[11] = (unsigned char) atm.tm_mday;
1781         buffsend[12] = (unsigned char) atm.tm_hour;
1782         buffsend[13] = (unsigned char) atm.tm_min;
1783         send_client(SIZE_HEADER + sizeof(packet_send_date_time), buffsend, pte);
1784         send_month_labels(pte, atm.tm_mon);
1785 }
1786
1787 static void send_date_time2(struct unistimsession *pte)
1788 {
1789         BUFFSEND;
1790         struct timeval now = ast_tvnow();
1791         struct ast_tm atm = { 0, };
1792
1793         if (unistimdebug) {
1794                 ast_verb(0, "Sending Time & Date #2\n");
1795         }
1796         memcpy(buffsend + SIZE_HEADER, packet_send_date_time2, sizeof(packet_send_date_time2));
1797         ast_localtime(&now, &atm, NULL);
1798         if (pte->device) {
1799                 buffsend[9] = pte->device->datetimeformat;
1800         } else {
1801                 buffsend[9] = 61;
1802         }
1803         buffsend[14] = (unsigned char) atm.tm_mon + 1;
1804         buffsend[15] = (unsigned char) atm.tm_mday;
1805         buffsend[16] = (unsigned char) atm.tm_hour;
1806         buffsend[17] = (unsigned char) atm.tm_min;
1807         send_client(SIZE_HEADER + sizeof(packet_send_date_time2), buffsend, pte);
1808 }
1809
1810 static void send_date_time3(struct unistimsession *pte)
1811 {
1812         BUFFSEND;
1813         struct timeval now = ast_tvnow();
1814         struct ast_tm atm = { 0, };
1815
1816         if (unistimdebug) {
1817                 ast_verb(0, "Sending Time & Date #3\n");
1818         }
1819         memcpy(buffsend + SIZE_HEADER, packet_send_date_time3, sizeof(packet_send_date_time3));
1820         ast_localtime(&now, &atm, NULL);
1821         buffsend[10] = (unsigned char) atm.tm_mon + 1;
1822         buffsend[11] = (unsigned char) atm.tm_mday;
1823         buffsend[12] = (unsigned char) atm.tm_hour;
1824         buffsend[13] = (unsigned char) atm.tm_min;
1825         send_client(SIZE_HEADER + sizeof(packet_send_date_time3), buffsend, pte);
1826 }
1827
1828 static void send_blink_cursor(struct unistimsession *pte)
1829 {
1830         BUFFSEND;
1831         if (unistimdebug) {
1832                 ast_verb(0, "Sending set blink\n");
1833         }
1834         memcpy(buffsend + SIZE_HEADER, packet_send_blink_cursor, sizeof(packet_send_blink_cursor));
1835         send_client(SIZE_HEADER + sizeof(packet_send_blink_cursor), buffsend, pte);
1836         return;
1837 }
1838
1839 /* pos : 0xab (a=0/2/4 = line ; b = row) */
1840 static void send_cursor_pos(struct unistimsession *pte, unsigned char pos)
1841 {
1842         BUFFSEND;
1843         if (unistimdebug) {
1844                 ast_verb(0, "Sending set cursor position\n");
1845         }
1846         memcpy(buffsend + SIZE_HEADER, packet_send_set_pos_cursor,
1847                    sizeof(packet_send_set_pos_cursor));
1848         buffsend[11] = pos;
1849         send_client(SIZE_HEADER + sizeof(packet_send_set_pos_cursor), buffsend, pte);
1850         return;
1851 }
1852
1853 static void send_charset_update(struct unistimsession *pte, int charset)
1854 {
1855         const unsigned char* packet_send_charset;
1856         int packet_size;
1857         BUFFSEND;
1858         if (unistimdebug) {
1859                 ast_verb(0, "Sending set default charset\n");
1860         }
1861         if (charset == LANG_DEFAULT) {
1862                 charset = options_languages[find_language(pte->device->language)].encoding;
1863         }
1864         switch (charset) {
1865         case ISO_8859_2:
1866                 packet_send_charset = packet_send_charset_iso_8859_2;
1867                 packet_size = sizeof(packet_send_charset_iso_8859_2);
1868                 break;
1869         case ISO_8859_4:
1870                 packet_send_charset = packet_send_charset_iso_8859_4;
1871                 packet_size = sizeof(packet_send_charset_iso_8859_4);
1872                 break;
1873         case ISO_8859_5:
1874                 packet_send_charset = packet_send_charset_iso_8859_5;
1875                 packet_size = sizeof(packet_send_charset_iso_8859_5);
1876                 break;
1877         case ISO_2022_JP:
1878                 packet_send_charset = packet_send_charset_iso_2022_jp;
1879                 packet_size = sizeof(packet_send_charset_iso_2022_jp);
1880                 break;
1881         case ISO_8859_1:
1882         default:
1883                 packet_send_charset = packet_send_charset_iso_8859_1;
1884                 packet_size = sizeof(packet_send_charset_iso_8859_1);
1885         }
1886         memcpy(buffsend + SIZE_HEADER, packet_send_charset, packet_size);
1887         send_client(SIZE_HEADER + packet_size, buffsend, pte);
1888         return;
1889 }
1890
1891 static void rcv_resume_connection_with_server(struct unistimsession *pte)
1892 {
1893         BUFFSEND;
1894         if (unistimdebug) {
1895                 ast_verb(0, "ResumeConnectionWithServer received\n");
1896                 ast_verb(0, "Sending packet_send_query_mac_address\n");
1897         }
1898         memcpy(buffsend + SIZE_HEADER, packet_send_query_mac_address,
1899                    sizeof(packet_send_query_mac_address));
1900         send_client(SIZE_HEADER + sizeof(packet_send_query_mac_address), buffsend, pte);
1901         return;
1902 }
1903
1904 static int unistim_register(struct unistimsession *s)
1905 {
1906         struct unistim_device *d;
1907
1908         ast_mutex_lock(&devicelock);
1909         d = devices;
1910         while (d) {
1911                 if (!strcasecmp(s->macaddr, d->id)) {
1912                         /* XXX Deal with IP authentication */
1913                         s->device = d;
1914                         d->session = s;
1915                         d->codec_number = DEFAULT_CODEC;
1916                         d->missed_call = 0;
1917                         d->receiver_state = STATE_ONHOOK;
1918                         break;
1919                 }
1920                 d = d->next;
1921         }
1922         ast_mutex_unlock(&devicelock);
1923
1924         if (!d) {
1925                 return 0;
1926         }
1927
1928         return 1;
1929 }
1930
1931 static void unistim_line_copy(struct unistim_line *dst, struct unistim_line *src)
1932 {
1933         struct ast_format_cap *tmp = src->cap;
1934         memcpy(dst, src, sizeof(*dst)); /* this over writes the cap ptr, so we have to reset it */
1935         src->cap = tmp;
1936         ast_format_cap_copy(src->cap, dst->cap);
1937 }
1938
1939 static struct unistim_line *unistim_line_destroy(struct unistim_line *l)
1940 {
1941         if (!l) {
1942                 return NULL;
1943         }
1944         l->cap = ast_format_cap_destroy(l->cap);
1945         ast_free(l);
1946         return NULL;
1947 }
1948
1949 static struct unistim_line *unistim_line_alloc(void)
1950 {
1951         struct unistim_line *l;
1952         if (!(l = ast_calloc(1, sizeof(*l)))) {
1953                 return NULL;
1954         }
1955
1956         if (!(l->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK))) {
1957                 ast_free(l);
1958                 return NULL;
1959         }
1960         return l;
1961 }
1962
1963 static int unistim_free_sub(struct unistim_subchannel *sub) {
1964         if (unistimdebug) {
1965                 ast_debug(1, "Released sub %u of channel %s@%s\n", sub->subtype, sub->parent->name, sub->parent->parent->name);
1966         }
1967         ast_mutex_destroy(&sub->lock);
1968         ast_free(sub);
1969         return 0;
1970 }
1971
1972 static struct unistim_subchannel *unistim_alloc_sub(struct unistim_device *d, int x)
1973 {
1974         struct unistim_subchannel *sub;
1975         if (!(sub = ast_calloc(1, sizeof(*sub)))) {
1976                 return NULL;
1977         }
1978
1979         if (unistimdebug) {
1980                 ast_verb(3, "Allocating UNISTIM subchannel #%d on %s ptr=%p\n", x, d->name, sub);
1981         }
1982         sub->ss_thread = AST_PTHREADT_NULL;
1983         sub->subtype = x;
1984         AST_LIST_LOCK(&d->subs);
1985         AST_LIST_INSERT_TAIL(&d->subs, sub, list);
1986         AST_LIST_UNLOCK(&d->subs);
1987         ast_mutex_init(&sub->lock);
1988         return sub;
1989 }
1990
1991 static int unistim_unalloc_sub(struct unistim_device *d, struct unistim_subchannel *sub)
1992 {
1993         struct unistim_subchannel *s;
1994
1995         AST_LIST_LOCK(&d->subs);
1996         AST_LIST_TRAVERSE_SAFE_BEGIN(&d->subs, s, list) {
1997                 if (!s) {
1998                         continue;
1999                 }
2000                 if (s != sub) {
2001                         continue;
2002                 }
2003                 AST_LIST_REMOVE_CURRENT(list);
2004                 unistim_free_sub(sub);
2005         }
2006         AST_LIST_TRAVERSE_SAFE_END;
2007         AST_LIST_UNLOCK(&d->subs);
2008         return 0;
2009 }
2010
2011 static const char *subtype_tostr(const int type)
2012 {
2013         switch (type) {
2014         case SUB_REAL:
2015                 return "REAL";
2016         case SUB_ONHOLD:
2017                 return "ONHOLD";
2018         case SUB_RING:
2019                 return "RINGING";
2020         case SUB_THREEWAY:
2021                 return "THREEWAY";
2022         }
2023         return "UNKNOWN";
2024 }
2025
2026 static const char *ptestate_tostr(const int type)
2027 {
2028         switch (type) {
2029         case STATE_INIT:
2030                 return "INIT";
2031         case STATE_AUTHDENY:
2032                 return "AUTHDENY";
2033         case STATE_MAINPAGE:
2034                 return "MAINPAGE";
2035         case STATE_EXTENSION:
2036                 return "EXTENSION";
2037         case STATE_DIALPAGE:
2038                 return "DIALPAGE";
2039         case STATE_RINGING:
2040                 return "RINGING";
2041         case STATE_CALL:
2042                 return "CALL";
2043         case STATE_SELECTOPTION:
2044                 return "SELECTOPTION";
2045         case STATE_SELECTCODEC:
2046                 return "SELECTCODEC";
2047         case STATE_SELECTLANGUAGE:
2048                 return "SELECTLANGUAGE";
2049         case STATE_CLEANING:
2050                 return "CLEARING";
2051         case STATE_HISTORY:
2052                 return "HISTORY";
2053         }
2054         return "UNKNOWN";
2055 }
2056
2057 static void rcv_mac_addr(struct unistimsession *pte, const unsigned char *buf)
2058 {
2059         BUFFSEND;
2060         int tmp, i = 0;
2061         char addrmac[19];
2062         int res = 0;
2063         for (tmp = 15; tmp < 15 + SIZE_HEADER; tmp++) {
2064                 sprintf(&addrmac[i], "%.2x", (unsigned) buf[tmp]);
2065                 i += 2;
2066         }
2067         if (unistimdebug) {
2068                 ast_verb(0, "MAC Address received: %s\n", addrmac);
2069         }
2070         strcpy(pte->macaddr, addrmac);
2071         res = unistim_register(pte);
2072         if (!res) {
2073                 switch (autoprovisioning) {
2074                 case AUTOPROVISIONING_NO:
2075                         ast_log(LOG_WARNING, "No entry found for this phone : %s\n", addrmac);
2076                         pte->state = STATE_AUTHDENY;
2077                         break;
2078                 case AUTOPROVISIONING_YES:
2079                         {
2080                                 struct unistim_device *d = NULL, *newd = NULL;
2081                                 struct unistim_line *newl = NULL, *l = NULL;
2082                                 if (unistimdebug) {
2083                                         ast_verb(0, "New phone, autoprovisioning on\n");
2084                                 }
2085                                 /* First : locate the [template] section */
2086                                 ast_mutex_lock(&devicelock);
2087                                 d = devices;
2088                                 while (d) {
2089                                         if (strcasecmp(d->name, "template")) {
2090                                                 d = d->next;
2091                                                 continue;
2092                                         }
2093                                         /* Found, cloning this entry */
2094                                         if (!(newd = ast_malloc(sizeof(*newd)))) {
2095                                                 ast_mutex_unlock(&devicelock);
2096                                                 return;
2097                                         }
2098                                         memcpy(newd, d, sizeof(*newd));
2099                                         ast_mutex_init(&newd->lock);
2100                                         newd->lines.first = NULL;
2101                                         newd->lines.last = NULL;
2102                                         AST_LIST_LOCK(&d->lines);
2103                                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2104                                                 if (!(newl = unistim_line_alloc())) {
2105                                                         break;
2106                                                 }
2107                                                 unistim_line_copy(l, newl);
2108                                                 newl->parent = newd;
2109                                                 ast_copy_string(newl->name, l->name, sizeof(newl->name));
2110                                                 snprintf(newl->fullname, sizeof(newl->fullname), "USTM/%s@%s",
2111                                                                  newl->name, newd->name);
2112                                                 snprintf(l->name, sizeof(l->name), "%d", atoi(l->name) + 1);
2113
2114                                                 AST_LIST_LOCK(&newd->lines);
2115                                                 AST_LIST_INSERT_TAIL(&newd->lines, newl, list);
2116                                                 AST_LIST_UNLOCK(&newd->lines);
2117                                         }
2118                                         AST_LIST_UNLOCK(&d->lines);
2119                                         if (!newl) {
2120                                                 ast_free(newd);
2121                                                 ast_mutex_unlock(&devicelock);
2122                                         }
2123
2124                                         /* Ok, now updating some fields */
2125                                         ast_copy_string(newd->id, addrmac, sizeof(newd->id));
2126                                         ast_copy_string(newd->name, addrmac, sizeof(newd->name));
2127                                         if (newd->extension == EXTENSION_NONE) {
2128                                                 newd->extension = EXTENSION_ASK;
2129                                         }
2130
2131                                         newd->receiver_state = STATE_ONHOOK;
2132                                         newd->session = pte;
2133                                         newd->language[0] = '\0';
2134                                         newd->to_delete = -1;
2135                                         newd->next = NULL;
2136                                         pte->device = newd;
2137
2138                                         /* Go to the end of the linked chain */
2139                                         while (d->next) {
2140                                                 d = d->next;
2141                                         }
2142                                         d->next = newd;
2143                                         d = newd;
2144                                         break;
2145                                 }
2146                                 ast_mutex_unlock(&devicelock);
2147                                 if (!d) {
2148                                         ast_log(LOG_WARNING, "No entry [template] found in unistim.conf\n");
2149                                         pte->state = STATE_AUTHDENY;
2150                                 }
2151                         }
2152                         break;
2153                 case AUTOPROVISIONING_TN:
2154                         pte->state = STATE_AUTHDENY;
2155                         break;
2156                 default:
2157                         ast_log(LOG_WARNING, "Internal error : unknown autoprovisioning value = %u\n",
2158                                         autoprovisioning);
2159                 }
2160         }
2161         if (pte->state != STATE_AUTHDENY) {
2162                 struct unistim_line *line;
2163                 struct unistim_subchannel *sub;
2164
2165                 ast_verb(3, "Device '%s' successfuly registered\n", pte->device->name);
2166
2167                 AST_LIST_LOCK(&pte->device->subs);
2168                 AST_LIST_TRAVERSE_SAFE_BEGIN(&pte->device->subs, sub, list) {
2169                         if (sub) {
2170                                 ast_log(LOG_ERROR, "Subchannel lost sice reboot. Hanged channel may apear!\n");
2171                                 AST_LIST_REMOVE_CURRENT(list);
2172                                 ast_free(sub);
2173                         }
2174                 }
2175                 AST_LIST_TRAVERSE_SAFE_END;
2176                 AST_LIST_UNLOCK(&pte->device->subs);
2177
2178                 switch (pte->device->extension) {
2179                 case EXTENSION_NONE:
2180                         pte->state = STATE_MAINPAGE;
2181                         break;
2182                 case EXTENSION_ASK:
2183                         /* Checking if we already have an extension number */
2184                         if (ast_strlen_zero(pte->device->extension_number)) {
2185                                 pte->state = STATE_EXTENSION;
2186                         } else {
2187                                 /* Yes, because of a phone reboot. We don't ask again for the TN */
2188                                 if (register_extension(pte)) {
2189                                         pte->state = STATE_EXTENSION;
2190                                 } else {
2191                                         pte->state = STATE_MAINPAGE;
2192                                 }
2193                         }
2194                         break;
2195                 case EXTENSION_LINE:
2196                         line = AST_LIST_FIRST(&pte->device->lines);
2197                         ast_copy_string(pte->device->extension_number, line->name,
2198                                                         sizeof(pte->device->extension_number));
2199                         if (register_extension(pte)) {
2200                                 pte->state = STATE_EXTENSION;
2201                         } else {
2202                                 pte->state = STATE_MAINPAGE;
2203                         }
2204                         break;
2205                 case EXTENSION_TN:
2206                         /* If we are here, it's because of a phone reboot */
2207                         pte->state = STATE_MAINPAGE;
2208                         break;
2209                 default:
2210                         ast_log(LOG_WARNING, "Internal error, extension value unknown : %u\n",
2211                                         pte->device->extension);
2212                         pte->state = STATE_AUTHDENY;
2213                         break;
2214                 }
2215         }
2216         if (pte->state == STATE_EXTENSION) {
2217                 if (pte->device->extension != EXTENSION_TN) {
2218                         pte->device->extension = EXTENSION_ASK;
2219                 }
2220                 pte->device->extension_number[0] = '\0';
2221         }
2222         if (unistimdebug) {
2223                 ast_verb(0, "\nSending S1\n");
2224         }
2225         memcpy(buffsend + SIZE_HEADER, packet_send_S1, sizeof(packet_send_S1));
2226         send_client(SIZE_HEADER + sizeof(packet_send_S1), buffsend, pte);
2227
2228         if (unistimdebug) {
2229                 ast_verb(0, "Sending query_basic_manager_04\n");
2230         }
2231         memcpy(buffsend + SIZE_HEADER, packet_send_query_basic_manager_04,
2232                    sizeof(packet_send_query_basic_manager_04));
2233         send_client(SIZE_HEADER + sizeof(packet_send_query_basic_manager_04), buffsend, pte);
2234
2235         if (unistimdebug) {
2236                 ast_verb(0, "Sending query_basic_manager_10\n");
2237         }
2238         memcpy(buffsend + SIZE_HEADER, packet_send_query_basic_manager_10,
2239                    sizeof(packet_send_query_basic_manager_10));
2240         send_client(SIZE_HEADER + sizeof(packet_send_query_basic_manager_10), buffsend, pte);
2241
2242         send_date_time(pte);
2243         return;
2244 }
2245
2246 static int write_entry_history(struct unistimsession *pte, FILE * f, char c, char *line1)
2247 {
2248         if (fwrite(&c, 1, 1, f) != 1) {
2249                 display_last_error("Unable to write history log header.");
2250                 return -1;
2251         }
2252         if (fwrite(line1, TEXT_LENGTH_MAX, 1, f) != 1) {
2253                 display_last_error("Unable to write history entry - date.");
2254                 return -1;
2255         }
2256         if (fwrite(pte->device->lst_cid, TEXT_LENGTH_MAX, 1, f) != 1) {
2257                 display_last_error("Unable to write history entry - callerid.");
2258                 return -1;
2259         }
2260         if (fwrite(pte->device->lst_cnm, TEXT_LENGTH_MAX, 1, f) != 1) {
2261                 display_last_error("Unable to write history entry - callername.");
2262                 return -1;
2263         }
2264         return 0;
2265 }
2266
2267 static int write_history(struct unistimsession *pte, char way, char ismissed)
2268 {
2269         char tmp[AST_CONFIG_MAX_PATH], tmp2[AST_CONFIG_MAX_PATH];
2270         char line1[TEXT_LENGTH_MAX + 1];
2271         char count = 0, *histbuf;
2272         int size;
2273         FILE *f, *f2;
2274         struct timeval now = ast_tvnow();
2275         struct ast_tm atm = { 0, };
2276
2277         if (!pte->device) {
2278                 return -1;
2279         }
2280         if (!pte->device->callhistory) {
2281                 return 0;
2282         }
2283         if (strchr(pte->device->name, '/') || (pte->device->name[0] == '.')) {
2284                 ast_log(LOG_WARNING, "Account code '%s' insecure for writing file\n",
2285                                 pte->device->name);
2286                 return -1;
2287         }
2288
2289         snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, USTM_LOG_DIR);
2290         if (ast_mkdir(tmp, 0770)) {
2291                 ast_log(LOG_WARNING, "Unable to create directory for history\n");
2292                 return -1;
2293         }
2294
2295         ast_localtime(&now, &atm, NULL);
2296         if (ismissed) {
2297                 if (way == 'i') {
2298                         ast_copy_string(tmp2, ustmtext("Miss", pte), sizeof(tmp2));
2299                 } else {
2300                         ast_copy_string(tmp2, ustmtext("Fail", pte), sizeof(tmp2));
2301                 }
2302         } else {
2303                 ast_copy_string(tmp2, ustmtext("Answ", pte), sizeof(tmp2));
2304         }
2305         snprintf(line1, sizeof(line1), "%04d/%02d/%02d %02d:%02d:%02d %s",
2306                          atm.tm_year + 1900, atm.tm_mon + 1, atm.tm_mday, atm.tm_hour,
2307                          atm.tm_min, atm.tm_sec, tmp2);
2308
2309         snprintf(tmp, sizeof(tmp), "%s/%s/%s-%c.csv", ast_config_AST_LOG_DIR,
2310                          USTM_LOG_DIR, pte->device->name, way);
2311         if ((f = fopen(tmp, "r"))) {
2312                 struct stat bufstat;
2313
2314                 if (stat(tmp, &bufstat)) {
2315                         display_last_error("Unable to stat history log.");
2316                         fclose(f);
2317                         return -1;
2318                 }
2319                 size = 1 + (MAX_ENTRY_LOG * TEXT_LENGTH_MAX * 3);
2320                 if (bufstat.st_size != size) {
2321                         ast_log(LOG_WARNING,
2322                                         "History file %s has an incorrect size (%d instead of %d). It will be replaced by a new one.",
2323                                         tmp, (int) bufstat.st_size, size);
2324                         fclose(f);
2325                         f = NULL;
2326                         count = 1;
2327                 }
2328         }
2329
2330         /* If we can't open the log file, we create a brand new one */
2331         if (!f) {
2332                 char c = 1;
2333                 int i;
2334
2335                 if ((errno != ENOENT) && (count == 0)) {
2336                         display_last_error("Unable to open history log.");
2337                         return -1;
2338                 }
2339                 f = fopen(tmp, "w");
2340                 if (!f) {
2341                         display_last_error("Unable to create history log.");
2342                         return -1;
2343                 }
2344                 if (write_entry_history(pte, f, c, line1)) {
2345                         fclose(f);
2346                         return -1;
2347                 }
2348                 memset(line1, ' ', TEXT_LENGTH_MAX);
2349                 for (i = 3; i < MAX_ENTRY_LOG * 3; i++) {
2350                         if (fwrite(line1, TEXT_LENGTH_MAX, 1, f) != 1) {
2351                                 display_last_error("Unable to write history entry - stuffing.");
2352                                 fclose(f);
2353                                 return -1;
2354                         }
2355                 }
2356                 if (fclose(f)) {
2357                         display_last_error("Unable to close history - creation.");
2358                 }
2359                 return 0;
2360         }
2361         /* We can open the log file, we create a temporary one, we add our entry and copy the rest */
2362         if (fread(&count, 1, 1, f) != 1) {
2363                 display_last_error("Unable to read history header.");
2364                 fclose(f);
2365                 return -1;
2366         }
2367         if (count > MAX_ENTRY_LOG) {
2368                 ast_log(LOG_WARNING, "Invalid count in history header of %s (%d max %d)\n", tmp,
2369                                 count, MAX_ENTRY_LOG);
2370                 fclose(f);
2371                 return -1;
2372         }
2373         snprintf(tmp2, sizeof(tmp2), "%s/%s/%s-%c.csv.tmp", ast_config_AST_LOG_DIR,
2374                          USTM_LOG_DIR, pte->device->name, way);
2375         if (!(f2 = fopen(tmp2, "w"))) {
2376                 display_last_error("Unable to create temporary history log.");
2377                 fclose(f);
2378                 return -1;
2379         }
2380
2381         if (++count > MAX_ENTRY_LOG) {
2382                 count = MAX_ENTRY_LOG;
2383         }
2384         if (write_entry_history(pte, f2, count, line1)) {
2385                 fclose(f);
2386                 fclose(f2);
2387                 return -1;
2388         }
2389         size = (MAX_ENTRY_LOG - 1) * TEXT_LENGTH_MAX * 3;
2390         if (!(histbuf = ast_malloc(size))) {
2391                 fclose(f);
2392                 fclose(f2);
2393                 return -1;
2394         }
2395
2396         if (fread(histbuf, size, 1, f) != 1) {
2397                 ast_free(histbuf);
2398                 fclose(f);
2399                 fclose(f2);
2400                 display_last_error("Unable to read previous history entries.");
2401                 return -1;
2402         }
2403         if (fwrite(histbuf, size, 1, f2) != 1) {
2404                 ast_free(histbuf);
2405                 fclose(f);
2406                 fclose(f2);
2407                 display_last_error("Unable to write previous history entries.");
2408                 return -1;
2409         }
2410         ast_free(histbuf);
2411         if (fclose(f)) {
2412                 display_last_error("Unable to close history log.");
2413         }
2414         if (fclose(f2)) {
2415                 display_last_error("Unable to close temporary history log.");
2416         }
2417         if (unlink(tmp)) {
2418                 display_last_error("Unable to remove old history log.");
2419         }
2420         if (rename(tmp2, tmp)) {
2421                 display_last_error("Unable to rename new history log.");
2422         }
2423         return 0;
2424 }
2425
2426 static int attempt_transfer(struct unistim_subchannel *p1, struct unistim_subchannel *p2)
2427 {
2428         RAII_VAR(struct ast_channel *, chana, NULL, ast_channel_unref);
2429         RAII_VAR(struct ast_channel *, chanb, NULL, ast_channel_unref);
2430
2431         if (!p1->owner || !p2->owner) {
2432                 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
2433                 return -1;
2434         }
2435         chana = ast_channel_ref(p1->owner);
2436         chanb = ast_channel_ref(p2->owner);
2437
2438         switch (ast_bridge_transfer_attended(chana, chanb)) {
2439         case AST_BRIDGE_TRANSFER_INVALID:
2440                 ast_log(LOG_WARNING, "Transfer failed. Invalid bridge setup\n");
2441                 break;
2442         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
2443                 ast_log(LOG_WARNING, "Transfer not permitted\n");
2444                 break;
2445         case AST_BRIDGE_TRANSFER_FAIL:
2446                 ast_log(LOG_WARNING, "Transfer encountered internal error\n");
2447                 break;
2448         case AST_BRIDGE_TRANSFER_SUCCESS:
2449                 return 0;
2450         }
2451
2452         /* Control only reaches this point if transfer has failed */
2453         ast_softhangup_nolock(chana, AST_SOFTHANGUP_DEV);
2454         ast_softhangup_nolock(chanb, AST_SOFTHANGUP_DEV);
2455         return -1;
2456 }
2457
2458 void change_callerid(struct unistimsession *pte, int type, char *callerid)
2459 {
2460         char *data;
2461         int size;
2462
2463         if (type) {
2464                 data = pte->device->lst_cnm;
2465         } else {
2466                 data = pte->device->lst_cid;
2467         }
2468
2469         /* This is very nearly strncpy(), except that the remaining buffer
2470          * is padded with ' ', instead of '\0' */
2471         memset(data, ' ', TEXT_LENGTH_MAX);
2472         size = strlen(callerid);
2473         if (size > TEXT_LENGTH_MAX) {
2474                 size = TEXT_LENGTH_MAX;
2475         }
2476         memcpy(data, callerid, size);
2477 }
2478
2479 static struct unistim_subchannel* get_sub(struct unistim_device *device, int type)
2480 {
2481         struct unistim_subchannel *sub = NULL;
2482
2483         AST_LIST_LOCK(&device->subs);
2484         AST_LIST_TRAVERSE(&device->subs, sub, list) {
2485                 if (!sub) {
2486                         continue;
2487                 }
2488                 if (sub->subtype == type) {
2489                         break;
2490                 }
2491         }
2492         AST_LIST_UNLOCK(&device->subs);
2493
2494         return sub;
2495 }
2496
2497 static void sub_start_silence(struct unistimsession *pte, struct unistim_subchannel *sub)
2498 {
2499         /* Silence our channel */
2500         if (!pte->device->silence_generator) {
2501                 pte->device->silence_generator =
2502                         ast_channel_start_silence_generator(sub->owner);
2503                 if (pte->device->silence_generator == NULL) {
2504                         ast_log(LOG_WARNING, "Unable to start a silence generator.\n");
2505                 } else if (unistimdebug) {
2506                         ast_verb(0, "Starting silence generator\n");
2507                 }
2508         }
2509
2510 }
2511
2512 static void sub_stop_silence(struct unistimsession *pte, struct unistim_subchannel *sub)
2513 {
2514         /* Stop the silence generator */
2515         if (pte->device->silence_generator) {
2516                 if (unistimdebug) {
2517                         ast_verb(0, "Stopping silence generator\n");
2518                 }
2519                 if (sub->owner) {
2520                         ast_channel_stop_silence_generator(sub->owner, pte->device->silence_generator);
2521                 } else {
2522                         ast_log(LOG_WARNING, "Trying to stop silence generator on a null channel!\n");
2523                 }
2524                 pte->device->silence_generator = NULL;
2525         }
2526 }
2527
2528 static void sub_hold(struct unistimsession *pte, struct unistim_subchannel *sub)
2529 {
2530         if (!sub) {
2531                 return;
2532         }
2533         sub->moh = 1;
2534         sub->subtype = SUB_ONHOLD;
2535         send_favorite_short(sub->softkey, FAV_ICON_ONHOLD_BLACK + FAV_BLINK_SLOW, pte);
2536         send_select_output(pte, pte->device->output, pte->device->volume, MUTE_ON);
2537         send_stop_timer(pte);
2538         if (sub->owner) {
2539                 ast_queue_hold(sub->owner, NULL);
2540                 send_end_call(pte);
2541         }
2542         return;
2543 }
2544
2545 static void sub_unhold(struct unistimsession *pte, struct unistim_subchannel *sub)
2546 {
2547         struct unistim_subchannel *sub_real;
2548
2549         sub_real = get_sub(pte->device, SUB_REAL);
2550         if (sub_real) {
2551             sub_hold(pte, sub_real);
2552         }
2553
2554         sub->moh = 0;
2555         sub->subtype = SUB_REAL;
2556         send_favorite_short(sub->softkey, FAV_ICON_OFFHOOK_BLACK, pte);
2557         send_select_output(pte, pte->device->output, pte->device->volume, MUTE_OFF);
2558         send_start_timer(pte);
2559         if (sub->owner) {
2560                 ast_queue_unhold(sub->owner);
2561                 if (sub->rtp) {
2562                         send_start_rtp(sub);
2563                 }
2564         }
2565         return;
2566 }
2567
2568 static void close_call(struct unistimsession *pte)
2569 {
2570         struct unistim_subchannel *sub, *sub_transf;
2571
2572         sub = get_sub(pte->device, SUB_REAL);
2573         sub_transf = get_sub(pte->device, SUB_THREEWAY);
2574         send_stop_timer(pte);
2575         if (!sub) {
2576                 ast_log(LOG_WARNING, "Close call without sub\n");
2577                 return;
2578         }
2579         send_favorite_short(sub->softkey, FAV_LINE_ICON, pte);
2580         if (sub->owner) {
2581                 sub->alreadygone = 1;
2582                 if (sub_transf) {
2583                         sub_transf->alreadygone = 1;
2584                         if (attempt_transfer(sub, sub_transf) < 0) {
2585                                 ast_verb(0, "attempt_transfer failed.\n");
2586                         }
2587                 } else {
2588                         ast_queue_hangup(sub->owner);
2589                 }
2590         } else {
2591                 if (sub_transf) {
2592                         if (sub_transf->owner) {
2593                                 ast_queue_hangup_with_cause(sub_transf->owner, AST_CAUSE_NORMAL_CLEARING);
2594                         } else {
2595                                 ast_log(LOG_WARNING, "threeway sub without owner\n");
2596                         }
2597                 } else {
2598                         ast_verb(0, "USTM(%s@%s-%d) channel already destroyed\n", sub->parent->name,
2599                                                 pte->device->name, sub->softkey);
2600                 }
2601         }
2602         change_callerid(pte, 0, pte->device->redial_number);
2603         change_callerid(pte, 1, "");
2604         write_history(pte, 'o', pte->device->missed_call);
2605         pte->device->missed_call = 0;
2606         show_main_page(pte);
2607         return;
2608 }
2609
2610 static void ignore_call(struct unistimsession *pte)
2611 {
2612         send_no_ring(pte);
2613         return;
2614 }
2615
2616 static void discard_call(struct unistimsession *pte)
2617 {
2618         struct unistim_subchannel* sub;
2619         sub = get_sub(pte->device, SUB_RING);
2620         if (!sub) {
2621             return;
2622         }
2623
2624         ast_queue_hangup_with_cause(sub->owner, AST_CAUSE_NORMAL_CLEARING);
2625         return;
2626 }
2627
2628 static void *unistim_ss(void *data)
2629 {
2630         struct ast_channel *chan = data;
2631         struct unistim_subchannel *sub = ast_channel_tech_pvt(chan);
2632         struct unistim_line *l = sub->parent;
2633         struct unistimsession *s = l->parent->session;
2634         int res;
2635
2636         ast_verb(3, "Starting switch on '%s@%s-%d' to %s\n", l->name, l->parent->name, sub->softkey, s->device->phone_number);
2637         ast_channel_lock(chan);
2638         ast_channel_exten_set(chan, s->device->phone_number);
2639         ast_setstate(chan, AST_STATE_RING);
2640         ast_channel_unlock(chan);
2641         ast_copy_string(s->device->redial_number, s->device->phone_number,
2642                                         sizeof(s->device->redial_number));
2643         res = ast_pbx_run(chan);
2644         if (res) {
2645                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2646                 send_tone(s, 1000, 0);
2647         }
2648         return NULL;
2649 }
2650
2651 static int find_rtp_port(struct unistim_subchannel *s)
2652 {
2653         struct unistim_subchannel *sub = NULL;
2654         int rtp_start = s->parent->parent->rtp_port;
2655         struct ast_sockaddr us_tmp;
2656         struct sockaddr_in us = { 0, };
2657
2658         AST_LIST_LOCK(&s->parent->parent->subs);
2659         AST_LIST_TRAVERSE(&s->parent->parent->subs, sub, list) {
2660                 if (!sub) {
2661                         continue;
2662                 }
2663                 if (sub->rtp) {
2664                         ast_rtp_instance_get_remote_address(sub->rtp, &us_tmp);
2665                         ast_sockaddr_to_sin(&us_tmp, &us);
2666                         if (htons(us.sin_port)) {
2667                                 rtp_start = htons(us.sin_port) + 1;
2668                                 break;
2669                         }
2670                 }
2671         }
2672         AST_LIST_UNLOCK(&s->parent->parent->subs);
2673         return rtp_start;
2674 }
2675
2676 static void send_start_rtp(struct unistim_subchannel *sub)
2677 {
2678         BUFFSEND;
2679
2680         int codec;
2681         struct sockaddr_in public = { 0, };
2682         struct sockaddr_in us = { 0, };
2683         struct sockaddr_in sin = { 0, };
2684         struct ast_sockaddr us_tmp;
2685         struct ast_sockaddr sin_tmp;
2686         struct unistimsession *pte;
2687
2688         ast_rtp_instance_get_local_address(sub->rtp, &us_tmp);
2689         ast_sockaddr_to_sin(&us_tmp, &us);
2690         ast_rtp_instance_get_remote_address(sub->rtp, &sin_tmp);
2691         ast_sockaddr_to_sin(&sin_tmp, &sin);
2692
2693         /* Setting up RTP of the phone */
2694         if (public_ip.sin_family == 0) {  /* NAT IP override ?   */
2695                 memcpy(&public, &us, sizeof(public));   /* No defined, using IP from recvmsg  */
2696         } else {
2697                 memcpy(&public, &public_ip, sizeof(public));    /* override  */
2698         }
2699         if (unistimdebug) {
2700                 ast_verb(0, "RTP started : Our IP/port is : %s:%hd with codec %s\n",
2701                          ast_inet_ntoa(us.sin_addr),
2702                          htons(us.sin_port), ast_getformatname(ast_channel_readformat(sub->owner)));
2703                 ast_verb(0, "Starting phone RTP stack. Our public IP is %s\n",
2704                                         ast_inet_ntoa(public.sin_addr));
2705         }
2706
2707         pte = sub->parent->parent->session;
2708         codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 1, ast_channel_readformat(sub->owner), 0);
2709         if ((ast_channel_readformat(sub->owner)->id == AST_FORMAT_ULAW) ||
2710                 (ast_channel_readformat(sub->owner)->id == AST_FORMAT_ALAW)) {
2711                 if (unistimdebug) {
2712                         ast_verb(0, "Sending packet_send_rtp_packet_size for codec %d\n", codec);
2713                 }
2714                 memcpy(buffsend + SIZE_HEADER, packet_send_rtp_packet_size,
2715                            sizeof(packet_send_rtp_packet_size));
2716                 buffsend[10] = (int) codec & 0xffffffffLL;
2717                 send_client(SIZE_HEADER + sizeof(packet_send_rtp_packet_size), buffsend, pte);
2718         }
2719         if (unistimdebug) {
2720                 ast_verb(0, "Sending Jitter Buffer Parameters Configuration\n");
2721         }
2722         memcpy(buffsend + SIZE_HEADER, packet_send_jitter_buffer_conf,
2723                    sizeof(packet_send_jitter_buffer_conf));
2724         send_client(SIZE_HEADER + sizeof(packet_send_jitter_buffer_conf), buffsend, pte);
2725         if (pte->device->rtp_method != 0) {
2726                 uint16_t rtcpsin_port = htons(us.sin_port) + 1; /* RTCP port is RTP + 1 */
2727
2728                 if (unistimdebug) {
2729                         ast_verb(0, "Sending OpenAudioStreamTX using method #%d\n", pte->device->rtp_method);
2730                 }
2731                 if (pte->device->rtp_method == 3) {
2732                         memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_tx3,
2733                                    sizeof(packet_send_open_audio_stream_tx3));
2734                 } else {
2735                         memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_tx,
2736                                    sizeof(packet_send_open_audio_stream_tx));
2737                 }
2738                 if (pte->device->rtp_method != 2) {
2739                         memcpy(buffsend + 28, &public.sin_addr, sizeof(public.sin_addr));
2740                         buffsend[20] = (htons(sin.sin_port) & 0xff00) >> 8;
2741                         buffsend[21] = (htons(sin.sin_port) & 0x00ff);
2742                         buffsend[23] = (rtcpsin_port & 0x00ff);
2743                         buffsend[22] = (rtcpsin_port & 0xff00) >> 8;
2744                         buffsend[25] = (us.sin_port & 0xff00) >> 8;
2745                         buffsend[24] = (us.sin_port & 0x00ff);
2746                         buffsend[27] = (rtcpsin_port & 0x00ff);
2747                         buffsend[26] = (rtcpsin_port & 0xff00) >> 8;
2748                 } else {
2749                         memcpy(buffsend + 23, &public.sin_addr, sizeof(public.sin_addr));
2750                         buffsend[15] = (htons(sin.sin_port) & 0xff00) >> 8;
2751                         buffsend[16] = (htons(sin.sin_port) & 0x00ff);
2752                         buffsend[20] = (us.sin_port & 0xff00) >> 8;
2753                         buffsend[19] = (us.sin_port & 0x00ff);
2754                 }
2755                 buffsend[11] = codec; /* rx */
2756                 buffsend[12] = codec; /* tx */
2757                 send_client(SIZE_HEADER + sizeof(packet_send_open_audio_stream_tx), buffsend, pte);
2758
2759                 if (unistimdebug) {
2760                         ast_verb(0, "Sending OpenAudioStreamRX\n");
2761                 }
2762                 if (pte->device->rtp_method == 3) {
2763                         memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_rx3,
2764                                    sizeof(packet_send_open_audio_stream_rx3));
2765                 } else {
2766                         memcpy(buffsend + SIZE_HEADER, packet_send_open_audio_stream_rx,
2767                                    sizeof(packet_send_open_audio_stream_rx));
2768                 }
2769                 if (pte->device->rtp_method != 2) {
2770                         memcpy(buffsend + 28, &public.sin_addr, sizeof(public.sin_addr));
2771                         buffsend[20] = (htons(sin.sin_port) & 0xff00) >> 8;
2772                         buffsend[21] = (htons(sin.sin_port) & 0x00ff);
2773                         buffsend[23] = (rtcpsin_port & 0x00ff);
2774                         buffsend[22] = (rtcpsin_port & 0xff00) >> 8;
2775                         buffsend[25] = (us.sin_port & 0xff00) >> 8;
2776                         buffsend[24] = (us.sin_port & 0x00ff);
2777                         buffsend[27] = (rtcpsin_port & 0x00ff);
2778                         buffsend[26] = (rtcpsin_port & 0xff00) >> 8;
2779                 } else {
2780                         memcpy(buffsend + 23, &public.sin_addr, sizeof(public.sin_addr));
2781                         buffsend[15] = (htons(sin.sin_port) & 0xff00) >> 8;
2782                         buffsend[16] = (htons(sin.sin_port) & 0x00ff);
2783                         buffsend[20] = (us.sin_port & 0xff00) >> 8;
2784                         buffsend[19] = (us.sin_port & 0x00ff);
2785                 }
2786                 buffsend[11] = codec; /* rx */
2787                 buffsend[12] = codec; /* tx */
2788                 send_client(SIZE_HEADER + sizeof(packet_send_open_audio_stream_rx), buffsend, pte);
2789         } else {
2790                 uint16_t rtcpsin_port = htons(us.sin_port) + 1; /* RTCP port is RTP + 1 */
2791
2792                 if (unistimdebug) {
2793                         ast_verb(0, "Sending packet_send_call default method\n");
2794                 }
2795
2796                 memcpy(buffsend + SIZE_HEADER, packet_send_call, sizeof(packet_send_call));
2797                 memcpy(buffsend + 53, &public.sin_addr, sizeof(public.sin_addr));
2798                 /* Destination port when sending RTP */
2799                 buffsend[49] = (us.sin_port & 0x00ff);
2800                 buffsend[50] = (us.sin_port & 0xff00) >> 8;
2801                 /* Destination port when sending RTCP */
2802                 buffsend[52] = (rtcpsin_port & 0x00ff);
2803                 buffsend[51] = (rtcpsin_port & 0xff00) >> 8;
2804                 /* Codec */
2805                 buffsend[40] = codec;
2806                 buffsend[41] = codec;
2807                 if (ast_channel_readformat(sub->owner)->id == AST_FORMAT_ULAW) {
2808                         buffsend[42] = 1;       /* 1 = 20ms (160 bytes), 2 = 40ms (320 bytes) */
2809                 } else if (ast_channel_readformat(sub->owner)->id == AST_FORMAT_ALAW) {
2810                         buffsend[42] = 1;       /* 1 = 20ms (160 bytes), 2 = 40ms (320 bytes) */
2811                 } else if (ast_channel_readformat(sub->owner)->id == AST_FORMAT_G723_1) {
2812                         buffsend[42] = 2;       /* 1 = 30ms (24 bytes), 2 = 60 ms (48 bytes) */
2813                 } else if (ast_channel_readformat(sub->owner)->id == AST_FORMAT_G729A) {
2814                         buffsend[42] = 2;       /* 1 = 10ms (10 bytes), 2 = 20ms (20 bytes) */
2815                 } else {
2816                         ast_log(LOG_WARNING, "Unsupported codec %s!\n",
2817                                         ast_getformatname(ast_channel_readformat(sub->owner)));
2818                 }
2819                 /* Source port for transmit RTP and Destination port for receiving RTP */
2820                 buffsend[45] = (htons(sin.sin_port) & 0xff00) >> 8;
2821                 buffsend[46] = (htons(sin.sin_port) & 0x00ff);
2822                 buffsend[47] = (rtcpsin_port & 0xff00) >> 8;
2823                 buffsend[48] = (rtcpsin_port & 0x00ff);
2824                 send_client(SIZE_HEADER + sizeof(packet_send_call), buffsend, pte);
2825         }
2826 }
2827
2828 static void start_rtp(struct unistim_subchannel *sub)
2829 {
2830         struct sockaddr_in sin = { 0, };
2831         struct sockaddr_in sout = { 0, };
2832         struct ast_sockaddr sin_tmp;
2833         struct ast_sockaddr sout_tmp;
2834
2835         /* Sanity checks */
2836         if (!sub) {
2837                 ast_log(LOG_WARNING, "start_rtp with a null subchannel !\n");
2838                 return;
2839         }
2840         if (!sub->parent) {
2841                 ast_log(LOG_WARNING, "start_rtp with a null line!\n");
2842                 return;
2843         }
2844         if (!sub->parent->parent) {
2845                 ast_log(LOG_WARNING, "start_rtp with a null device!\n");
2846                 return;
2847         }
2848         if (!sub->parent->parent->session) {
2849                 ast_log(LOG_WARNING, "start_rtp with a null session!\n");
2850                 return;
2851         }
2852         if (!sub->owner) {
2853                 ast_log(LOG_WARNING, "start_rtp with a null asterisk channel!\n");
2854                 return;
2855         }
2856         sout = sub->parent->parent->session->sout;
2857         ast_mutex_lock(&sub->lock);
2858         /* Allocate the RTP */
2859         if (unistimdebug) {
2860                 ast_verb(0, "Starting RTP. Bind on %s\n", ast_inet_ntoa(sout.sin_addr));
2861         }
2862         ast_sockaddr_from_sin(&sout_tmp, &sout);
2863         sub->rtp = ast_rtp_instance_new("asterisk", sched, &sout_tmp, NULL);
2864         if (!sub->rtp) {
2865                 ast_log(LOG_WARNING, "Unable to create RTP session: %s binaddr=%s\n",
2866                                 strerror(errno), ast_inet_ntoa(sout.sin_addr));
2867                 ast_mutex_unlock(&sub->lock);
2868                 return;
2869         }
2870         ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_RTCP, 1);
2871         ast_rtp_instance_set_channel_id(sub->rtp, ast_channel_uniqueid(sub->owner));
2872         ast_channel_internal_fd_set(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
2873         ast_channel_internal_fd_set(sub->owner, 1, ast_rtp_instance_fd(sub->rtp, 1));
2874         ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "UNISTIM RTP");
2875         ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, sub->parent->parent->nat);
2876
2877         /* Create the RTP connection */
2878         sin.sin_family = AF_INET;
2879         /* Setting up RTP for our side */
2880         memcpy(&sin.sin_addr, &sub->parent->parent->session->sin.sin_addr,
2881                    sizeof(sin.sin_addr));
2882
2883         sin.sin_port = htons(find_rtp_port(sub));
2884         ast_sockaddr_from_sin(&sin_tmp, &sin);
2885         ast_rtp_instance_set_remote_address(sub->rtp, &sin_tmp);
2886         if (!ast_format_cap_iscompatible(ast_channel_nativeformats(sub->owner), ast_channel_readformat(sub->owner))) {
2887                 struct ast_format tmpfmt;
2888                 char tmp[256];
2889                 ast_best_codec(ast_channel_nativeformats(sub->owner), &tmpfmt);
2890                 ast_log(LOG_WARNING,
2891                                 "Our read/writeformat has been changed to something incompatible: %s, using %s best codec from %s\n",
2892                                 ast_getformatname(ast_channel_readformat(sub->owner)),
2893                                 ast_getformatname(&tmpfmt),
2894                                 ast_getformatname_multiple(tmp, sizeof(tmp), ast_channel_nativeformats(sub->owner)));
2895
2896                 ast_format_copy(ast_channel_readformat(sub->owner), &tmpfmt);
2897                 ast_format_copy(ast_channel_writeformat(sub->owner), &tmpfmt);
2898         }
2899         send_start_rtp(sub);
2900         ast_mutex_unlock(&sub->lock);
2901 }
2902
2903 static void send_dial_tone(struct unistimsession *pte)
2904 {
2905         struct ast_tone_zone_sound *ts = NULL;
2906         struct ast_tone_zone_part tone_data;
2907         char *s = NULL;
2908         char *ind;
2909
2910         if ((ts = ast_get_indication_tone(pte->device->tz, "dial"))) {
2911                 ind = ast_strdupa(ts->data);
2912                 s = strsep(&ind, ",");
2913                 ast_tone_zone_part_parse(s, &tone_data);
2914                 send_tone(pte, tone_data.freq1, tone_data.freq2);
2915                 if (unistimdebug) {
2916                         ast_verb(0, "Country code found (%s), freq1=%u freq2=%u\n",
2917                                                         pte->device->tz->country, tone_data.freq1, tone_data.freq2);
2918                 }
2919                 ts = ast_tone_zone_sound_unref(ts);
2920         }
2921 }
2922
2923 static void show_phone_number(struct unistimsession *pte)
2924 {
2925         char tmp[TEXT_LENGTH_MAX + 1];
2926         const char *tmp_number = ustmtext("Number:", pte);
2927         int line, tmp_copy, offset = 0, i;
2928
2929         pte->device->phone_number[pte->device->size_phone_number] = '\0';
2930         if  (pte->device->size_phone_number > MAX_SCREEN_NUMBER) {
2931                 offset = pte->device->size_phone_number - MAX_SCREEN_NUMBER - 1;
2932                 if (offset > strlen(tmp_number)) {
2933                         offset = strlen(tmp_number);
2934                 }
2935                 tmp_copy = strlen(tmp_number) - offset + 1;
2936                 if (tmp_copy > sizeof(tmp)) {
2937                         tmp_copy = sizeof(tmp);
2938                 }
2939                 memcpy(tmp, tmp_number + offset, tmp_copy);
2940         } else {
2941                 ast_copy_string(tmp, tmp_number, sizeof(tmp));
2942         }
2943
2944         offset = (pte->device->size_phone_number >= TEXT_LENGTH_MAX) ? (pte->device->size_phone_number - TEXT_LENGTH_MAX +1) : 0;
2945         if (pte->device->size_phone_number) {
2946                 memcpy(tmp + strlen(tmp), pte->device->phone_number + offset, pte->device->size_phone_number - offset + 1);
2947         }
2948         offset = strlen(tmp);
2949
2950         for (i = strlen(tmp); i < TEXT_LENGTH_MAX; i++) {
2951                 tmp[i] = '.';
2952         }
2953         tmp[i] = '\0';
2954
2955         line = (pte->device->height == 1) ? TEXT_LINE0 : TEXT_LINE2;
2956         send_text(line, TEXT_NORMAL, pte, tmp);
2957         send_blink_cursor(pte);
2958         send_cursor_pos(pte, (unsigned char) (line + offset));
2959         send_led_update(pte, LED_BAR_OFF);
2960 }
2961
2962 static void handle_dial_page(struct unistimsession *pte)
2963 {
2964         pte->state = STATE_DIALPAGE;
2965         if (pte->device->call_forward[0] == -1) {
2966                 send_text(TEXT_LINE0, TEXT_NORMAL, pte, "");
2967                 send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("Enter forward", pte));
2968                 send_text_status(pte, ustmtext("Fwd    Cancel BackSp Erase", pte));
2969                 if (pte->device->call_forward[1] != 0) {
2970                         ast_copy_string(pte->device->phone_number, pte->device->call_forward + 1,
2971                                                         sizeof(pte->device->phone_number));
2972                         show_phone_number(pte);
2973                         send_led_update(pte, LED_BAR_OFF);
2974                         return;
2975                 }
2976         } else {
2977                 if ((pte->device->output == OUTPUT_HANDSET) &&
2978                         (pte->device->receiver_state == STATE_ONHOOK)) {
2979                         send_select_output(pte, OUTPUT_SPEAKER, pte->device->volume, MUTE_OFF);
2980                 } else {
2981                         send_select_output(pte, pte->device->output, pte->device->volume, MUTE_OFF);
2982                 }
2983                 send_dial_tone(pte);
2984
2985                 if (pte->device->height > 1) {
2986                         send_text(TEXT_LINE0, TEXT_NORMAL, pte, ustmtext("Enter the number to dial", pte));
2987                         send_text(TEXT_LINE1, TEXT_NORMAL, pte, ustmtext("and press Call", pte));
2988                 }
2989                 if (ast_strlen_zero(pte->device->redial_number)) {
2990                         send_text_status(pte, ustmtext("Call          BackSp Erase", pte));
2991                 } else {
2992                         send_text_status(pte, ustmtext("Call   Redial BackSp Erase", pte));
2993                 }
2994         }
2995
2996         pte->device->size_phone_number = 0;
2997         pte->device->phone_number[0] = 0;
2998         show_phone_number(pte);
2999         change_favorite_icon(pte, FAV_ICON_PHONE_BLACK);
3000         send_icon(TEXT_LINE0, FAV_ICON_NONE, pte);
3001         pte->device->missed_call = 0;
3002         send_led_update(pte, LED_BAR_OFF);
3003         pte->device->lastmsgssent = -1;
3004         return;
3005 }
3006
3007 static void swap_subs(struct unistim_subchannel *a, struct unistim_subchannel *b)
3008 {
3009         struct ast_rtp_instance *rtp;
3010         int fds;
3011
3012         if (unistimdebug) {
3013                 ast_verb(0, "Swapping %p and %p\n", a, b);
3014         }
3015         if ((!a->owner) || (!b->owner)) {
3016                 ast_log(LOG_WARNING,
3017                                 "Attempted to swap subchannels with a null owner : sub #%p=%p sub #%p=%p\n",
3018                                 a, a->owner, b, b->owner);
3019                 return;
3020         }
3021         rtp = a->rtp;
3022         a->rtp = b->rtp;
3023         b->rtp = rtp;
3024
3025         fds = ast_channel_fd(a->owner, 0);
3026         ast_channel_internal_fd_set(a->owner, 0, ast_channel_fd(b->owner, 0));
3027         ast_channel_internal_fd_set(b->owner, 0, fds);
3028
3029         fds = ast_channel_fd(a->owner, 1);
3030         ast_channel_internal_fd_set(a->owner, 1, ast_channel_fd(b->owner, 1));
3031         ast_channel_internal_fd_set(b->owner, 1, fds);
3032 }
3033
3034 /* Step 1 : Music On Hold for peer, Dialing screen for us */
3035 static void transfer_call_step1(struct unistimsession *pte)
3036 {
3037         struct unistim_subchannel *sub /*, *sub_trans */;
3038         struct unistim_device *d = pte->device;
3039
3040         sub = get_sub(d, SUB_REAL);
3041         /* sub_trans = get_sub(d, SUB_THREEWAY); */
3042
3043         if (!sub || !sub->owner) {
3044                 ast_log(LOG_WARNING, "Unable to find subchannel for music on hold\n");
3045                 return;
3046         }
3047         /* Start music on hold if appropriate */
3048         if (sub->moh) {
3049                 ast_log(LOG_WARNING, "Transfer with peer already listening music on hold\n");
3050         } else {
3051                 ast_queue_hold(sub->owner, sub->parent->musicclass);
3052                 sub->moh = 1;
3053                 sub->subtype = SUB_THREEWAY;
3054         }
3055         sub_start_silence(pte, sub);
3056         handle_dial_page(pte);
3057 }
3058
3059 static void transfer_cancel_step2(struct unistimsession *pte)
3060 {
3061         struct unistim_subchannel *sub, *sub_trans;
3062         struct unistim_device *d = pte->device;
3063
3064         sub = get_sub(d, SUB_REAL);
3065         sub_trans = get_sub(d, SUB_THREEWAY);
3066
3067         if (!sub || !sub->owner) {
3068                 ast_log(LOG_WARNING, "Unable to find subchannel for music on hold\n");
3069                 return;
3070         }
3071         if (sub_trans) {
3072                 if (unistimdebug) {
3073                         ast_verb(0, "Transfer canceled, hangup our threeway channel\n");
3074                 }
3075                 if (sub->owner) {
3076                         swap_subs(sub, sub_trans);
3077                         ast_queue_unhold(sub_trans->owner);
3078                         sub_trans->moh = 0;
3079                         sub_trans->subtype = SUB_REAL;
3080                         sub->subtype = SUB_THREEWAY;
3081                         ast_queue_hangup_with_cause(sub->owner, AST_CAUSE_NORMAL_CLEARING);
3082                 } else {
3083                         ast_log(LOG_WARNING, "Canceling a threeway channel without owner\n");
3084                 }
3085                 return;
3086         }
3087 }
3088
3089 /* From phone to PBX */
3090 static void handle_call_outgoing(struct unistimsession *s)
3091 {
3092         struct ast_channel *c;
3093         struct unistim_subchannel *sub;
3094         int softkey;
3095
3096         s->state = STATE_CALL;
3097
3098         sub = get_sub(s->device, SUB_THREEWAY);
3099         if (sub) {
3100                 /* If sub for threway call created than we use transfer behaviuor */
3101                 struct unistim_subchannel *sub_trans = NULL;
3102                 struct unistim_device *d = s->device;
3103
3104                 sub_trans = get_sub(d, SUB_REAL);
3105                 if (sub_trans) {
3106                         ast_log(LOG_WARNING, "Can't transfer while active subchannel exists!\n");
3107                         return;