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