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