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