Additional TDD changes (preparing for SIP changes - adding TDD support to SIP)
[asterisk/asterisk.git] / main / callerid.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief CallerID Generation support 
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <time.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <math.h>
36 #include <ctype.h>
37
38 #include "asterisk/ulaw.h"
39 #include "asterisk/alaw.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/callerid.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/fskmodem.h"
45 #include "asterisk/options.h"
46 #include "asterisk/utils.h"
47
48 struct callerid_state {
49         fsk_data fskd;
50         char rawdata[256];
51         short oldstuff[160];
52         int oldlen;
53         int pos;
54         int type;
55         int cksum;
56         char name[64];
57         char number[64];
58         int flags;
59         int sawflag;
60         int len;
61
62         int skipflag; 
63         unsigned short crc;
64 };
65
66
67 float cid_dr[4], cid_di[4];
68 float clidsb = 8000.0 / 1200.0;
69 float sasdr, sasdi;
70 float casdr1, casdi1, casdr2, casdi2;
71
72 #define CALLERID_SPACE  2200.0          /*!< 2200 hz for "0" */
73 #define CALLERID_MARK   1200.0          /*!< 1200 hz for "1" */
74 #define SAS_FREQ                 440.0
75 #define CAS_FREQ1               2130.0
76 #define CAS_FREQ2               2750.0
77
78 #define AST_CALLERID_UNKNOWN    "<unknown>"
79
80 static inline void gen_tones(unsigned char *buf, int len, int codec, float ddr1, float ddi1, float ddr2, float ddi2, float *cr1, float *ci1, float *cr2, float *ci2)
81 {
82         int x;
83         float t;
84         for (x = 0; x < len; x++) {
85                 t = *cr1 * ddr1 - *ci1 * ddi1;
86                 *ci1 = *cr1 * ddi1 + *ci1 * ddr1;
87                 *cr1 = t;
88                 t = 2.0 - (*cr1 * *cr1 + *ci1 * *ci1);
89                 *cr1 *= t;
90                 *ci1 *= t;      
91
92                 t = *cr2 * ddr2 - *ci2 * ddi2;
93                 *ci2 = *cr2 * ddi2 + *ci2 * ddr2;
94                 *cr2 = t;
95                 t = 2.0 - (*cr2 * *cr2 + *ci2 * *ci2);
96                 *cr2 *= t;
97                 *ci2 *= t;      
98                 buf[x] = AST_LIN2X((*cr1 + *cr2) * 2048.0);
99         }
100 }
101
102 static inline void gen_tone(unsigned char *buf, int len, int codec, float ddr1, float ddi1, float *cr1, float *ci1)
103 {
104         int x;
105         float t;
106         for (x = 0; x < len; x++) {
107                 t = *cr1 * ddr1 - *ci1 * ddi1;
108                 *ci1 = *cr1 * ddi1 + *ci1 * ddr1;
109                 *cr1 = t;
110                 t = 2.0 - (*cr1 * *cr1 + *ci1 * *ci1);
111                 *cr1 *= t;
112                 *ci1 *= t;      
113                 buf[x] = AST_LIN2X(*cr1 * 8192.0);
114         }
115 }
116
117 /*! \brief Initialize stuff for inverse FFT */
118 void callerid_init(void)
119 {
120         cid_dr[0] = cos(CALLERID_SPACE * 2.0 * M_PI / 8000.0);
121         cid_di[0] = sin(CALLERID_SPACE * 2.0 * M_PI / 8000.0);
122         cid_dr[1] = cos(CALLERID_MARK * 2.0 * M_PI / 8000.0);
123         cid_di[1] = sin(CALLERID_MARK * 2.0 * M_PI / 8000.0);
124         sasdr = cos(SAS_FREQ * 2.0 * M_PI / 8000.0);
125         sasdi = sin(SAS_FREQ * 2.0 * M_PI / 8000.0);
126         casdr1 = cos(CAS_FREQ1 * 2.0 * M_PI / 8000.0);
127         casdi1 = sin(CAS_FREQ1 * 2.0 * M_PI / 8000.0);
128         casdr2 = cos(CAS_FREQ2 * 2.0 * M_PI / 8000.0);
129         casdi2 = sin(CAS_FREQ2 * 2.0 * M_PI / 8000.0);
130 }
131
132 struct callerid_state *callerid_new(int cid_signalling)
133 {
134         struct callerid_state *cid;
135
136         if ((cid = ast_calloc(1, sizeof(*cid)))) {
137                 cid->fskd.ispb = 7;             /* 1200 baud */ 
138                 /* Set up for 1200 / 8000 freq *32 to allow ints */
139                 cid->fskd.pllispb  = (int)(8000 * 32  / 1200);
140                 cid->fskd.pllids   = cid->fskd.pllispb/32;
141                 cid->fskd.pllispb2 = cid->fskd.pllispb/2;
142                 
143                 cid->fskd.icont = 0;           /* PLL REset */
144                 /* cid->fskd.hdlc = 0; */       /* Async */
145                 cid->fskd.nbit = 8;             /* 8 bits */
146                 cid->fskd.instop = 1;           /* 1 stop bit */
147                 /* cid->fskd.paridad = 0; */    /* No parity */
148                 cid->fskd.bw = 1;               /* Filter 800 Hz */
149                 if (cid_signalling == 2) {      /* v23 signalling */
150                         cid->fskd.f_mark_idx  = 4;      /* 1300 Hz */
151                         cid->fskd.f_space_idx = 5;      /* 2100 Hz */
152                 } else {                        /* Bell 202 signalling as default */
153                         cid->fskd.f_mark_idx  = 2;      /* 1200 Hz */
154                         cid->fskd.f_space_idx = 3;      /* 2200 Hz */
155                 }
156                 /* cid->fskd.pcola = 0; */      /* No clue */
157                 /* cid->fskd.cont = 0.0; */     /* Digital PLL reset */
158                 /* cid->fskd.x0 = 0.0; */
159                 /* cid->fskd.state = 0; */
160                 cid->flags = CID_UNKNOWN_NAME | CID_UNKNOWN_NUMBER;
161                 /* cid->pos = 0; */
162
163                 fskmodem_init(&cid->fskd);
164         }
165
166         return cid;
167 }
168
169 void callerid_get(struct callerid_state *cid, char **name, char **number, int *flags)
170 {
171         *flags = cid->flags;
172         if (cid->flags & (CID_UNKNOWN_NAME | CID_PRIVATE_NAME))
173                 *name = NULL;
174         else
175                 *name = cid->name;
176         if (cid->flags & (CID_UNKNOWN_NUMBER | CID_PRIVATE_NUMBER))
177                 *number = NULL;
178         else
179                 *number = cid->number;
180 }
181
182 void callerid_get_dtmf(char *cidstring, char *number, int *flags)
183 {
184         int i;
185         int code;
186
187         /* "Clear" the number-buffer. */
188         number[0] = 0;
189
190         if (strlen(cidstring) < 2) {
191                 ast_debug(1, "No cid detected\n");
192                 *flags = CID_UNKNOWN_NUMBER;
193                 return;
194         }
195         
196         /* Detect protocol and special types */
197         if (cidstring[0] == 'B') {
198                 /* Handle special codes */
199                 code = atoi(&cidstring[1]);
200                 if (code == 0)
201                         *flags = CID_UNKNOWN_NUMBER;
202                 else if (code == 10) 
203                         *flags = CID_PRIVATE_NUMBER;
204                 else
205                         ast_debug(1, "Unknown DTMF code %d\n", code);
206         } else if (cidstring[0] == 'D' && cidstring[2] == '#') {
207                 /* .DK special code */
208                 if (cidstring[1] == '1')
209                         *flags = CID_PRIVATE_NUMBER;
210                 if (cidstring[1] == '2' || cidstring[1] == '3')
211                         *flags = CID_UNKNOWN_NUMBER;
212         } else if (cidstring[0] == 'D' || cidstring[0] == 'A') {
213                 /* "Standard" callerid */
214                 for (i = 1; i < strlen(cidstring); i++) {
215                         if (cidstring[i] == 'C' || cidstring[i] == '#')
216                                 break;
217                         if (isdigit(cidstring[i]))
218                                 number[i-1] = cidstring[i];
219                         else
220                                 ast_debug(1, "Unknown CID digit '%c'\n",
221                                         cidstring[i]);
222                 }
223                 number[i-1] = 0;
224         } else if (isdigit(cidstring[0])) {
225                 /* It begins with a digit, so we parse it as a number and hope
226                  * for the best */
227                 ast_log(LOG_WARNING, "Couldn't detect start-character. CID "
228                         "parsing might be unreliable\n");
229                 for (i = 0; i < strlen(cidstring); i++) {
230                         if (isdigit(cidstring[i]))
231                                 number[i] = cidstring[i];
232                         else
233                                 break;
234                 }
235                 number[i] = 0;
236         } else {
237                 ast_debug(1, "Unknown CID protocol, start digit '%c'\n", cidstring[0]);
238                 *flags = CID_UNKNOWN_NUMBER;
239         }
240 }
241
242 int ast_gen_cas(unsigned char *outbuf, int sendsas, int len, int codec)
243 {
244         int pos = 0;
245         int saslen = 2400;
246         float cr1 = 1.0;
247         float ci1 = 0.0;
248         float cr2 = 1.0;
249         float ci2 = 0.0;
250
251         if (sendsas) {
252                 if (len < saslen)
253                         return -1;
254                 gen_tone(outbuf, saslen, codec, sasdr, sasdi, &cr1, &ci1);
255                 len -= saslen;
256                 pos += saslen;
257                 cr2 = cr1;
258                 ci2 = ci1;
259         }
260         gen_tones(outbuf + pos, len, codec, casdr1, casdi1, casdr2, casdi2, &cr1, &ci1, &cr2, &ci2);
261         return 0;
262 }
263
264 static unsigned short calc_crc(unsigned short crc, unsigned char data)
265 {
266         unsigned int i, j, org, dst;
267         org = data;
268         dst = 0;
269
270         for (i = 0; i < CHAR_BIT; i++) {
271                 org <<= 1;
272                 dst >>= 1;
273                 if (org & 0x100) 
274                         dst |= 0x80;
275         }
276         data = (unsigned char) dst;
277         crc ^= (unsigned int) data << (16 - CHAR_BIT);
278         for (j = 0; j < CHAR_BIT; j++) {
279                 if (crc & 0x8000U)
280                         crc = (crc << 1) ^ 0x1021U ;
281                 else
282                         crc <<= 1 ;
283         }
284         return crc;
285 }
286
287 int callerid_feed_jp(struct callerid_state *cid, unsigned char *ubuf, int len, int codec)
288 {
289         int mylen = len;
290         int olen;
291         int b = 'X';
292         int b2;
293         int res;
294         int x;
295         short *buf;
296
297         buf = alloca(2 * len + cid->oldlen);
298
299         memcpy(buf, cid->oldstuff, cid->oldlen);
300         mylen += cid->oldlen / 2;
301
302         for (x = 0; x < len; x++) 
303                 buf[x+cid->oldlen/2] = AST_XLAW(ubuf[x]);
304
305         while (mylen >= 160) {
306                 b = b2 = 0;
307                 olen = mylen;
308                 res = fsk_serial(&cid->fskd, buf, &mylen, &b);
309
310                 if (mylen < 0) {
311                         ast_log(LOG_ERROR, "fsk_serial made mylen < 0 (%d)\n", mylen);
312                         return -1;
313                 }
314
315                 buf += (olen - mylen);
316
317                 if (res < 0) {
318                         ast_log(LOG_NOTICE, "fsk_serial failed\n");
319                         return -1;
320                 }
321
322                 if (res == 1) {
323                         b2 = b;
324                         b  &= 0x7f;
325
326                         /* crc checksum calculation */
327                         if (cid->sawflag > 1)
328                                 cid->crc = calc_crc(cid->crc, (unsigned char) b2);
329
330                         /* Ignore invalid bytes */
331                         if (b > 0xff)
332                                 continue;
333
334                         /* skip DLE if needed */
335                         if (cid->sawflag > 0) {
336                                 if (cid->sawflag != 5 && cid->skipflag == 0 && b == 0x10) {
337                                         cid->skipflag = 1 ;
338                                         continue ;
339                                 }
340                         }
341                         if (cid->skipflag == 1)
342                                 cid->skipflag = 0 ;
343
344                         /* caller id retrieval */
345                         switch (cid->sawflag) {
346                         case 0: /* DLE */
347                                 if (b == 0x10) {
348                                         cid->sawflag = 1;
349                                         cid->skipflag = 0;
350                                         cid->crc = 0;
351                                 }
352                                 break;
353                         case 1: /* SOH */
354                                 if (b == 0x01) 
355                                         cid->sawflag = 2;
356                                 break ;
357                         case 2: /* HEADER */
358                                 if (b == 0x07) 
359                                         cid->sawflag = 3;
360                                 break;
361                         case 3: /* STX */
362                                 if (b == 0x02) 
363                                         cid->sawflag = 4;
364                                 break;
365                         case 4: /* SERVICE TYPE */
366                                 if (b == 0x40) 
367                                         cid->sawflag = 5;
368                                 break;
369                         case 5: /* Frame Length */
370                                 cid->sawflag = 6;
371                                 break;  
372                         case 6: /* NUMBER TYPE */
373                                 cid->sawflag = 7;
374                                 cid->pos = 0;
375                                 cid->rawdata[cid->pos++] = b;
376                                 break;
377                         case 7: /* NUMBER LENGTH */
378                                 cid->sawflag = 8;
379                                 cid->len = b;
380                                 if ((cid->len+2) >= sizeof(cid->rawdata)) {
381                                         ast_log(LOG_WARNING, "too long caller id string\n") ;
382                                         return -1;
383                                 }
384                                 cid->rawdata[cid->pos++] = b;
385                                 break;
386                         case 8: /* Retrieve message */
387                                 cid->rawdata[cid->pos++] = b;
388                                 cid->len--;
389                                 if (cid->len<=0) {
390                                         cid->rawdata[cid->pos] = '\0';
391                                         cid->sawflag = 9;
392                                 }
393                                 break;
394                         case 9: /* ETX */
395                                 cid->sawflag = 10;
396                                 break;
397                         case 10: /* CRC Checksum 1 */
398                                 cid->sawflag = 11;
399                                 break;
400                         case 11: /* CRC Checksum 2 */
401                                 cid->sawflag = 12;
402                                 if (cid->crc != 0) {
403                                         ast_log(LOG_WARNING, "crc checksum error\n") ;
404                                         return -1;
405                                 } 
406                                 /* extract caller id data */
407                                 for (x = 0; x < cid->pos;) {
408                                         switch (cid->rawdata[x++]) {
409                                         case 0x02: /* caller id  number */
410                                                 cid->number[0] = '\0';
411                                                 cid->name[0] = '\0';
412                                                 cid->flags = 0;
413                                                 res = cid->rawdata[x++];
414                                                 ast_copy_string(cid->number, &cid->rawdata[x], res+1);
415                                                 x += res;
416                                                 break;
417                                         case 0x21: /* additional information */
418                                                 /* length */
419                                                 x++; 
420                                                 /* number type */
421                                                 switch (cid->rawdata[x]) { 
422                                                 case 0x00: /* unknown */
423                                                 case 0x01: /* international number */
424                                                 case 0x02: /* domestic number */
425                                                 case 0x03: /* network */
426                                                 case 0x04: /* local call */
427                                                 case 0x06: /* short dial number */
428                                                 case 0x07: /* reserved */
429                                                 default:   /* reserved */
430                                                         ast_debug(2, "cid info:#1=%X\n", cid->rawdata[x]);
431                                                         break ;
432                                                 }
433                                                 x++; 
434                                                 /* numbering plan octed 4 */
435                                                 x++; 
436                                                 /* numbering plan octed 5 */
437                                                 switch (cid->rawdata[x]) { 
438                                                 case 0x00: /* unknown */
439                                                 case 0x01: /* recommendation E.164 ISDN */
440                                                 case 0x03: /* recommendation X.121 */
441                                                 case 0x04: /* telex dial plan */
442                                                 case 0x08: /* domestic dial plan */
443                                                 case 0x09: /* private dial plan */
444                                                 case 0x05: /* reserved */
445                                                 default:   /* reserved */
446                                                         ast_debug(2, "cid info:#2=%X\n", cid->rawdata[x]);
447                                                         break ;
448                                                 }
449                                                 x++; 
450                                                 break ;
451                                         case 0x04: /* no callerid reason */
452                                                 /* length */
453                                                 x++; 
454                                                 /* no callerid reason code */
455                                                 switch (cid->rawdata[x]) {
456                                                 case 'P': /* caller id denied by user */
457                                                 case 'O': /* service not available */
458                                                 case 'C': /* pay phone */
459                                                 case 'S': /* service congested */
460                                                                 cid->flags |= CID_UNKNOWN_NUMBER;
461                                                         ast_debug(2, "no cid reason:%c\n",cid->rawdata[x]);
462                                                         break ;
463                                                 }
464                                                 x++; 
465                                                 break ;
466                                         case 0x09: /* dialed number */
467                                                 /* length */
468                                                 res = cid->rawdata[x++];
469                                                 /* dialed number */
470                                                 x += res;
471                                                 break ;
472                                         case 0x22: /* dialed number additional information */
473                                                 /* length */
474                                                 x++;
475                                                 /* number type */
476                                                 switch (cid->rawdata[x]) {
477                                                 case 0x00: /* unknown */
478                                                 case 0x01: /* international number */
479                                                 case 0x02: /* domestic number */
480                                                 case 0x03: /* network */
481                                                 case 0x04: /* local call */
482                                                 case 0x06: /* short dial number */
483                                                 case 0x07: /* reserved */
484                                                 default:   /* reserved */
485                                                         if (option_debug > 1)
486                                                                 ast_log(LOG_NOTICE, "did info:#1=%X\n", cid->rawdata[x]);
487                                                         break ;
488                                                 }
489                                                 x++;
490                                                 /* numbering plan octed 4 */
491                                                 x++;
492                                                 /* numbering plan octed 5 */
493                                                 switch (cid->rawdata[x]) {
494                                                 case 0x00: /* unknown */
495                                                 case 0x01: /* recommendation E.164 ISDN */
496                                                 case 0x03: /* recommendation X.121 */
497                                                 case 0x04: /* telex dial plan */
498                                                 case 0x08: /* domestic dial plan */
499                                                 case 0x09: /* private dial plan */
500                                                 case 0x05: /* reserved */
501                                                 default:   /* reserved */
502                                                         ast_debug(2, "did info:#2=%X\n", cid->rawdata[x]);
503                                                         break ;
504                                                 }
505                                                 x++;
506                                                 break ;
507                                         }
508                                 }
509                                 return 1;
510                                 break;
511                         default:
512                                 ast_log(LOG_ERROR, "invalid value in sawflag %d\n", cid->sawflag);
513                         }
514                 }
515         }
516         if (mylen) {
517                 memcpy(cid->oldstuff, buf, mylen * 2);
518                 cid->oldlen = mylen * 2;
519         } else
520                 cid->oldlen = 0;
521         
522         return 0;
523 }
524
525
526 int callerid_feed(struct callerid_state *cid, unsigned char *ubuf, int len, int codec)
527 {
528         int mylen = len;
529         int olen;
530         int b = 'X';
531         int res;
532         int x;
533         short *buf;
534
535         buf = alloca(2 * len + cid->oldlen);
536
537         memcpy(buf, cid->oldstuff, cid->oldlen);
538         mylen += cid->oldlen/2;
539
540         for (x = 0; x < len; x++) 
541                 buf[x+cid->oldlen/2] = AST_XLAW(ubuf[x]);
542         while (mylen >= 160) {
543                 olen = mylen;
544                 res = fsk_serial(&cid->fskd, buf, &mylen, &b);
545                 if (mylen < 0) {
546                         ast_log(LOG_ERROR, "fsk_serial made mylen < 0 (%d)\n", mylen);
547                         return -1;
548                 }
549                 buf += (olen - mylen);
550                 if (res < 0) {
551                         ast_log(LOG_NOTICE, "fsk_serial failed\n");
552                         return -1;
553                 }
554                 if (res == 1) {
555                         /* Ignore invalid bytes */
556                         if (b > 0xff)
557                                 continue;
558                         switch (cid->sawflag) {
559                         case 0: /* Look for flag */
560                                 if (b == 'U')
561                                         cid->sawflag = 2;
562                                 break;
563                         case 2: /* Get lead-in */
564                                 if ((b == 0x04) || (b == 0x80)) {
565                                         cid->type = b;
566                                         cid->sawflag = 3;
567                                         cid->cksum = b;
568                                 }
569                                 break;
570                         case 3: /* Get length */
571                                 /* Not a lead in.  We're ready  */
572                                 cid->sawflag = 4;
573                                 cid->len = b;
574                                 cid->pos = 0;
575                                 cid->cksum += b;
576                                 break;
577                         case 4: /* Retrieve message */
578                                 if (cid->pos >= 128) {
579                                         ast_log(LOG_WARNING, "Caller ID too long???\n");
580                                         return -1;
581                                 }
582                                 cid->rawdata[cid->pos++] = b;
583                                 cid->len--;
584                                 cid->cksum += b;
585                                 if (!cid->len) {
586                                         cid->rawdata[cid->pos] = '\0';
587                                         cid->sawflag = 5;
588                                 }
589                                 break;
590                         case 5: /* Check checksum */
591                                 if (b != (256 - (cid->cksum & 0xff))) {
592                                         ast_log(LOG_NOTICE, "Caller*ID failed checksum\n");
593                                         /* Try again */
594                                         cid->sawflag = 0;
595                                         break;
596                                 }
597                 
598                                 cid->number[0] = '\0';
599                                 cid->name[0] = '\0';
600                                 /* If we get this far we're fine.  */
601                                 if (cid->type == 0x80) {
602                                         /* MDMF */
603                                         /* Go through each element and process */
604                                         for (x = 0; x < cid->pos;) {
605                                                 switch (cid->rawdata[x++]) {
606                                                 case 1:
607                                                         /* Date */
608                                                         break;
609                                                 case 2: /* Number */
610                                                 case 3: /* Number (for Zebble) */
611                                                 case 4: /* Number */
612                                                         res = cid->rawdata[x];
613                                                         if (res > 32) {
614                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID number from %d bytes to 32\n", cid->rawdata[x]);
615                                                                 res = 32; 
616                                                         }
617                                                         if (ast_strlen_zero(cid->number)) {
618                                                                 memcpy(cid->number, cid->rawdata + x + 1, res);
619                                                                 /* Null terminate */
620                                                                 cid->number[res] = '\0';
621                                                         }
622                                                         break;
623                                                 case 6: /* Stentor Call Qualifier (ie. Long Distance call) */
624                                                         break;
625                                                 case 7: /* Name */
626                                                 case 8: /* Name */
627                                                         res = cid->rawdata[x];
628                                                         if (res > 32) {
629                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID name from %d bytes to 32\n", cid->rawdata[x]);
630                                                                 res = 32; 
631                                                         }
632                                                         memcpy(cid->name, cid->rawdata + x + 1, res);
633                                                         cid->name[res] = '\0';
634                                                         break;
635                                                 case 17: /* UK: Call type, 1=Voice Call, 2=Ringback when free, 129=Message waiting  */
636                                                 case 19: /* UK: Network message system status (Number of messages waiting) */
637                                                 case 22: /* Something French */
638                                                         break;
639                                                 default:
640                                                         ast_log(LOG_NOTICE, "Unknown IE %d\n", cid->rawdata[x - 1]);
641                                                 }
642                                                 res = cid->rawdata[x];
643                                                 if (0 > res){   /* Negative offset in the CID Spill */
644                                                         ast_log(LOG_NOTICE, "IE %d has bad field length of %d at offset %d\n", cid->rawdata[x-1], cid->rawdata[x], x);
645                                                         /* Try again */
646                                                         cid->sawflag = 0;
647                                                         break;  /* Exit the loop */
648                                                 }
649                                                 x += cid->rawdata[x];
650                                                 x++;
651                                         }
652                                 } else {
653                                         /* SDMF */
654                                         ast_copy_string(cid->number, cid->rawdata + 8, sizeof(cid->number));
655                                 }
656                                 /* Update flags */
657                                 cid->flags = 0;
658                                 if (!strcmp(cid->number, "P")) {
659                                         strcpy(cid->number, "");
660                                         cid->flags |= CID_PRIVATE_NUMBER;
661                                 } else if (!strcmp(cid->number, "O") || ast_strlen_zero(cid->number)) {
662                                         strcpy(cid->number, "");
663                                         cid->flags |= CID_UNKNOWN_NUMBER;
664                                 }
665                                 if (!strcmp(cid->name, "P")) {
666                                         strcpy(cid->name, "");
667                                         cid->flags |= CID_PRIVATE_NAME;
668                                 } else if (!strcmp(cid->name, "O") || ast_strlen_zero(cid->name)) {
669                                         strcpy(cid->name, "");
670                                         cid->flags |= CID_UNKNOWN_NAME;
671                                 }
672                                 return 1;
673                                 break;
674                         default:
675                                 ast_log(LOG_ERROR, "Dunno what to do with a digit in sawflag %d\n", cid->sawflag);
676                         }
677                 }
678         }
679         if (mylen) {
680                 memcpy(cid->oldstuff, buf, mylen * 2);
681                 cid->oldlen = mylen * 2;
682         } else
683                 cid->oldlen = 0;
684
685         return 0;
686 }
687
688 void callerid_free(struct callerid_state *cid)
689 {
690         ast_free(cid);
691 }
692
693 static int callerid_genmsg(char *msg, int size, const char *number, const char *name, int flags)
694 {
695         struct timeval tv = ast_tvnow();
696         struct ast_tm tm;
697         char *ptr;
698         int res;
699         int i, x;
700
701         /* Get the time */
702         ast_localtime(&tv, &tm, NULL);
703         
704         ptr = msg;
705         
706         /* Format time and message header */
707         res = snprintf(ptr, size, "\001\010%02d%02d%02d%02d", tm.tm_mon + 1,
708                                 tm.tm_mday, tm.tm_hour, tm.tm_min);
709         size -= res;
710         ptr += res;
711         if (ast_strlen_zero(number) || (flags & CID_UNKNOWN_NUMBER)) {
712                 /* Indicate number not known */
713                 res = snprintf(ptr, size, "\004\001O");
714                 size -= res;
715                 ptr += res;
716         } else if (flags & CID_PRIVATE_NUMBER) {
717                 /* Indicate number is private */
718                 res = snprintf(ptr, size, "\004\001P");
719                 size -= res;
720                 ptr += res;
721         } else {
722                 /* Send up to 16 digits of number MAX */
723                 i = strlen(number);
724                 if (i > 16)
725                         i = 16;
726                 res = snprintf(ptr, size, "\002%c", i);
727                 size -= res;
728                 ptr += res;
729                 for (x = 0; x < i; x++)
730                         ptr[x] = number[x];
731                 ptr[i] = '\0';
732                 ptr += i;
733                 size -= i;
734         }
735
736         if (ast_strlen_zero(name) || (flags & CID_UNKNOWN_NAME)) {
737                 /* Indicate name not known */
738                 res = snprintf(ptr, size, "\010\001O");
739                 size -= res;
740                 ptr += res;
741         } else if (flags & CID_PRIVATE_NAME) {
742                 /* Indicate name is private */
743                 res = snprintf(ptr, size, "\010\001P");
744                 size -= res;
745                 ptr += res;
746         } else {
747                 /* Send up to 16 digits of name MAX */
748                 i = strlen(name);
749                 if (i > 16)
750                         i = 16;
751                 res = snprintf(ptr, size, "\007%c", i);
752                 size -= res;
753                 ptr += res;
754                 for (x = 0; x < i; x++)
755                         ptr[x] = name[x];
756                 ptr[i] = '\0';
757                 ptr += i;
758                 size -= i;
759         }
760         return (ptr - msg);
761         
762 }
763
764 int vmwi_generate(unsigned char *buf, int active, int mdmf, int codec)
765 {
766         unsigned char msg[256];
767         int len=0;
768         int sum;
769         int x;
770         int bytes = 0;
771         float cr = 1.0;
772         float ci = 0.0;
773         float scont = 0.0;
774
775         if (mdmf) {
776                 /* MDMF Message waiting */
777                 msg[len++] = 0x82;
778                 /* Length is 3 */
779                 msg[len++] = 3;
780                 /* IE is "Message Waiting Parameter" */
781                 msg[len++] = 0xb;
782                 /* Length of IE is one */
783                 msg[len++] = 1;
784                 /* Active or not */
785                 if (active)
786                         msg[len++] = 0xff;
787                 else
788                         msg[len++] = 0x00;
789         } else {
790                 /* SDMF Message waiting */
791                 msg[len++] = 0x6;
792                 /* Length is 3 */
793                 msg[len++] = 3;
794                 if (active) {
795                         msg[len++] = 0x42;
796                         msg[len++] = 0x42;
797                         msg[len++] = 0x42;
798                 } else {
799                         msg[len++] = 0x6f;
800                         msg[len++] = 0x6f;
801                         msg[len++] = 0x6f;
802                 }
803         }
804         sum = 0;
805         for (x = 0; x < len; x++)
806                 sum += msg[x];
807         sum = (256 - (sum & 255));
808         msg[len++] = sum;
809         /* Wait a half a second */
810         for (x = 0; x < 4000; x++)
811                 PUT_BYTE(0x7f);
812         /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
813         for (x = 0; x < 30; x++)
814                 PUT_CLID(0x55);
815         /* Send 170ms of callerid marks */
816         for (x = 0; x < 170; x++)
817                 PUT_CLID_MARKMS;
818         for (x = 0; x < len; x++) {
819                 PUT_CLID(msg[x]);
820         }
821         /* Send 50 more ms of marks */
822         for (x = 0; x < 50; x++)
823                 PUT_CLID_MARKMS;
824         return bytes;
825 }
826
827 int callerid_generate(unsigned char *buf, const char *number, const char *name, int flags, int callwaiting, int codec)
828 {
829         int bytes=0;
830         int x, sum;
831         int len;
832
833         /* Initial carriers (real/imaginary) */
834         float cr = 1.0;
835         float ci = 0.0;
836         float scont = 0.0;
837         char msg[256];
838         len = callerid_genmsg(msg, sizeof(msg), number, name, flags);
839         if (!callwaiting) {
840                 /* Wait a half a second */
841                 for (x = 0; x < 4000; x++)
842                         PUT_BYTE(0x7f);
843                 /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
844                 for (x = 0; x < 30; x++)
845                         PUT_CLID(0x55);
846         }
847         /* Send 150ms of callerid marks */
848         for (x = 0; x < 150; x++)
849                 PUT_CLID_MARKMS;
850         /* Send 0x80 indicating MDMF format */
851         PUT_CLID(0x80);
852         /* Put length of whole message */
853         PUT_CLID(len);
854         sum = 0x80 + strlen(msg);
855         /* Put each character of message and update checksum */
856         for (x = 0; x < len; x++) {
857                 PUT_CLID(msg[x]);
858                 sum += msg[x];
859         }
860         /* Send 2's compliment of sum */
861         PUT_CLID(256 - (sum & 255));
862
863         /* Send 50 more ms of marks */
864         for (x = 0; x < 50; x++)
865                 PUT_CLID_MARKMS;
866         
867         return bytes;
868 }
869
870 /*! \brief Clean up phone string
871  * remove '(', ' ', ')', non-trailing '.', and '-' not in square brackets.
872  * Basically, remove anything that could be invalid in a pattern.
873  */
874 void ast_shrink_phone_number(char *n)
875 {
876         int x, y=0;
877         int bracketed = 0;
878
879         for (x = 0; n[x]; x++) {
880                 switch (n[x]) {
881                 case '[':
882                         bracketed++;
883                         n[y++] = n[x];
884                         break;
885                 case ']':
886                         bracketed--;
887                         n[y++] = n[x];
888                         break;
889                 case '-':
890                         if (bracketed)
891                                 n[y++] = n[x];
892                         break;
893                 case '.':
894                         if (!n[x+1])
895                                 n[y++] = n[x];
896                         break;
897                 default:
898                         /* ignore parenthesis and whitespace */
899                         if (!strchr("( )", n[x]))
900                                 n[y++] = n[x];
901                 }
902         }
903         n[y] = '\0';
904 }
905
906 /*! \brief Checks if phone number consists of valid characters 
907         \param exten    String that needs to be checked
908         \param valid    Valid characters in string
909         \return 1 if valid string, 0 if string contains invalid characters
910 */
911 static int ast_is_valid_string(const char *exten, const char *valid)
912 {
913         int x;
914
915         if (ast_strlen_zero(exten))
916                 return 0;
917         for (x = 0; exten[x]; x++)
918                 if (!strchr(valid, exten[x]))
919                         return 0;
920         return 1;
921 }
922
923 /*! \brief checks if string consists only of digits and * \# and + 
924         \return 1 if string is valid AST phone number
925         \return 0 if not
926 */
927 int ast_isphonenumber(const char *n)
928 {
929         return ast_is_valid_string(n, "0123456789*#+");
930 }
931
932 /*! \brief checks if string consists only of digits and ( ) - * \# and + 
933         Pre-qualifies the string for ast_shrink_phone_number()
934         \return 1 if string is valid AST shrinkable phone number
935         \return 0 if not
936 */
937 int ast_is_shrinkable_phonenumber(const char *exten)
938 {
939         return ast_is_valid_string(exten, "0123456789*#+()-.");
940 }
941
942 /*! \brief parse string for caller id information 
943         \return always returns 0, as the code always returns something.
944   XXX note that 'name' is not parsed consistently e.g. we have
945
946         input                   location        name
947         " foo bar " <123>       123             ' foo bar ' (with spaces around)
948         " foo bar "             NULL            'foo bar' (without spaces around)
949         " foo bar  <123>"       123             '" foo bar'
950   The parsing of leading and trailing space/quotes should be more consistent.
951 */
952 int ast_callerid_parse(char *instr, char **name, char **location)
953 {
954         char *ns, *ne, *ls, *le;
955
956         /* Try "name" <location> format or name <location> format */
957         if ((ls = strchr(instr, '<')) && (le = strchr(ls, '>'))) {
958                 *ls = *le = '\0';       /* location found, trim off the brackets */
959                 *location = ls + 1;     /* and this is the result */
960                 if ((ns = strchr(instr, '"')) && (ne = strchr(ns + 1, '"'))) {
961                         *ns = *ne = '\0';       /* trim off the quotes */
962                         *name = ns + 1;         /* and this is the name */
963                 } else { /* no quotes, trim off leading and trailing spaces */
964                         *name = ast_skip_blanks(instr);
965                         ast_trim_blanks(*name);
966                 }
967         } else {        /* no valid brackets */
968                 char tmp[256];
969
970                 ast_copy_string(tmp, instr, sizeof(tmp));
971                 ast_shrink_phone_number(tmp);
972                 if (ast_isphonenumber(tmp)) {   /* Assume it's just a location */
973                         *name = NULL;
974                         strcpy(instr, tmp); /* safe, because tmp will always be the same size or smaller than instr */
975                         *location = instr;
976                 } else { /* Assume it's just a name. */
977                         *location = NULL;
978                         if ((ns = strchr(instr, '"')) && (ne = strchr(ns + 1, '"'))) {
979                                 *ns = *ne = '\0';       /* trim off the quotes */
980                                 *name = ns + 1;         /* and this is the name */
981                         } else { /* no quotes, trim off leading and trailing spaces */
982                                 *name = ast_skip_blanks(instr);
983                                 ast_trim_blanks(*name);
984                         }
985                 }
986         }
987         return 0;
988 }
989
990 static int __ast_callerid_generate(unsigned char *buf, const char *name, const char *number, int callwaiting, int codec)
991 {
992         if (ast_strlen_zero(name))
993                 name = NULL;
994         if (ast_strlen_zero(number))
995                 number = NULL;
996         return callerid_generate(buf, number, name, 0, callwaiting, codec);
997 }
998
999 int ast_callerid_generate(unsigned char *buf, const char *name, const char *number, int codec)
1000 {
1001         return __ast_callerid_generate(buf, name, number, 0, codec);
1002 }
1003
1004 int ast_callerid_callwaiting_generate(unsigned char *buf, const char *name, const char *number, int codec)
1005 {
1006         return __ast_callerid_generate(buf, name, number, 1, codec);
1007 }
1008
1009 char *ast_callerid_merge(char *buf, int bufsiz, const char *name, const char *num, const char *unknown)
1010 {
1011         if (!unknown)
1012                 unknown = "<unknown>";
1013         if (name && num)
1014                 snprintf(buf, bufsiz, "\"%s\" <%s>", name, num);
1015         else if (name) 
1016                 ast_copy_string(buf, name, bufsiz);
1017         else if (num)
1018                 ast_copy_string(buf, num, bufsiz);
1019         else
1020                 ast_copy_string(buf, unknown, bufsiz);
1021         return buf;
1022 }
1023
1024 int ast_callerid_split(const char *buf, char *name, int namelen, char *num, int numlen)
1025 {
1026         char *tmp;
1027         char *l = NULL, *n = NULL;
1028
1029         tmp = ast_strdupa(buf);
1030         ast_callerid_parse(tmp, &n, &l);
1031         if (n)
1032                 ast_copy_string(name, n, namelen);
1033         else
1034                 name[0] = '\0';
1035         if (l) {
1036                 ast_shrink_phone_number(l);
1037                 ast_copy_string(num, l, numlen);
1038         } else
1039                 num[0] = '\0';
1040         return 0;
1041 }
1042
1043 /*! \brief Translation table for Caller ID Presentation settings */
1044 static struct {
1045         int val;
1046         const char *name;
1047         const char *description;
1048 } pres_types[] = {
1049         {  AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED, "allowed_not_screened", "Presentation Allowed, Not Screened"},
1050         {  AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, "allowed_passed_screen", "Presentation Allowed, Passed Screen"},
1051         {  AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN, "allowed_failed_screen", "Presentation Allowed, Failed Screen"},
1052         {  AST_PRES_ALLOWED_NETWORK_NUMBER, "allowed", "Presentation Allowed, Network Number"},
1053         {  AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED, "prohib_not_screened", "Presentation Prohibited, Not Screened"},
1054         {  AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN, "prohib_passed_screen", "Presentation Prohibited, Passed Screen"},
1055         {  AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN, "prohib_failed_screen", "Presentation Prohibited, Failed Screen"},
1056         {  AST_PRES_PROHIB_NETWORK_NUMBER, "prohib", "Presentation Prohibited, Network Number"},
1057         {  AST_PRES_NUMBER_NOT_AVAILABLE, "unavailable", "Number Unavailable"},
1058 };
1059
1060 /*! \brief Convert caller ID text code to value 
1061         used in config file parsing
1062         \param data text string
1063         \return value AST_PRES_ from callerid.h 
1064 */
1065 int ast_parse_caller_presentation(const char *data)
1066 {
1067         int i;
1068
1069         for (i = 0; i < ((sizeof(pres_types) / sizeof(pres_types[0]))); i++) {
1070                 if (!strcasecmp(pres_types[i].name, data))
1071                         return pres_types[i].val;
1072         }
1073
1074         return -1;
1075 }
1076
1077 /*! \brief Convert caller ID pres value to explanatory string 
1078         \param data value (see callerid.h AST_PRES_ ) 
1079         \return string for human presentation
1080 */
1081 const char *ast_describe_caller_presentation(int data)
1082 {
1083         int i;
1084
1085         for (i = 0; i < ((sizeof(pres_types) / sizeof(pres_types[0]))); i++) {
1086                 if (pres_types[i].val == data)
1087                         return pres_types[i].description;
1088         }
1089
1090         return "unknown";
1091 }
1092
1093 /*! \brief Convert caller ID pres value to text code
1094         \param data text string
1095         \return string for config file
1096 */
1097 const char *ast_named_caller_presentation(int data)
1098 {
1099         int i;
1100
1101         for (i = 0; i < ((sizeof(pres_types) / sizeof(pres_types[0]))); i++) {
1102                 if (pres_types[i].val == data)
1103                         return pres_types[i].name;
1104         }
1105
1106         return "unknown";
1107 }