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