Add the ability to dynamically specify weights for responses to DUNDi queries.
[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_NAME))
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                 if (option_debug)
230                         ast_log(LOG_DEBUG, "Unknown CID protocol, start digit '%c'\n", 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
244         if (sendsas) {
245                 if (len < saslen)
246                         return -1;
247                 gen_tone(outbuf, saslen, codec, sasdr, sasdi, &cr1, &ci1);
248                 len -= saslen;
249                 pos += saslen;
250                 cr2 = cr1;
251                 ci2 = ci1;
252         }
253         gen_tones(outbuf + pos, len, codec, casdr1, casdi1, casdr2, casdi2, &cr1, &ci1, &cr2, &ci2);
254         return 0;
255 }
256
257 static unsigned short calc_crc(unsigned short crc, unsigned char data)
258 {
259         unsigned int i, j, org, dst;
260         org = data;
261         dst = 0;
262
263         for (i = 0; i < CHAR_BIT; i++) {
264                 org <<= 1;
265                 dst >>= 1;
266                 if (org & 0x100) 
267                         dst |= 0x80;
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_serial(&cid->fskd, buf, &mylen, &b);
302
303                 if (mylen < 0) {
304                         ast_log(LOG_ERROR, "fsk_serial 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_serial failed\n");
312                         return -1;
313                 }
314
315                 if (res == 1) {
316                         b2 = b;
317                         b  &= 0x7f;
318
319                         /* crc checksum calculation */
320                         if (cid->sawflag > 1)
321                                 cid->crc = calc_crc(cid->crc, (unsigned char) b2);
322
323                         /* Ignore invalid bytes */
324                         if (b > 0xff)
325                                 continue;
326
327                         /* skip DLE if needed */
328                         if (cid->sawflag > 0) {
329                                 if (cid->sawflag != 5 && cid->skipflag == 0 && b == 0x10) {
330                                         cid->skipflag = 1 ;
331                                         continue ;
332                                 }
333                         }
334                         if (cid->skipflag == 1)
335                                 cid->skipflag = 0 ;
336
337                         /* caller id retrieval */
338                         switch (cid->sawflag) {
339                         case 0: /* DLE */
340                                 if (b == 0x10) {
341                                         cid->sawflag = 1;
342                                         cid->skipflag = 0;
343                                         cid->crc = 0;
344                                 }
345                                 break;
346                         case 1: /* SOH */
347                                 if (b == 0x01) 
348                                         cid->sawflag = 2;
349                                 break ;
350                         case 2: /* HEADER */
351                                 if (b == 0x07) 
352                                         cid->sawflag = 3;
353                                 break;
354                         case 3: /* STX */
355                                 if (b == 0x02) 
356                                         cid->sawflag = 4;
357                                 break;
358                         case 4: /* SERVICE TYPE */
359                                 if (b == 0x40) 
360                                         cid->sawflag = 5;
361                                 break;
362                         case 5: /* Frame Length */
363                                 cid->sawflag = 6;
364                                 break;  
365                         case 6: /* NUMBER TYPE */
366                                 cid->sawflag = 7;
367                                 cid->pos = 0;
368                                 cid->rawdata[cid->pos++] = b;
369                                 break;
370                         case 7: /* NUMBER LENGTH */
371                                 cid->sawflag = 8;
372                                 cid->len = b;
373                                 if ((cid->len+2) >= sizeof(cid->rawdata)) {
374                                         ast_log(LOG_WARNING, "too long caller id string\n") ;
375                                         return -1;
376                                 }
377                                 cid->rawdata[cid->pos++] = b;
378                                 break;
379                         case 8: /* Retrieve message */
380                                 cid->rawdata[cid->pos++] = b;
381                                 cid->len--;
382                                 if (cid->len<=0) {
383                                         cid->rawdata[cid->pos] = '\0';
384                                         cid->sawflag = 9;
385                                 }
386                                 break;
387                         case 9: /* ETX */
388                                 cid->sawflag = 10;
389                                 break;
390                         case 10: /* CRC Checksum 1 */
391                                 cid->sawflag = 11;
392                                 break;
393                         case 11: /* CRC Checksum 2 */
394                                 cid->sawflag = 12;
395                                 if (cid->crc != 0) {
396                                         ast_log(LOG_WARNING, "crc checksum error\n") ;
397                                         return -1;
398                                 } 
399                                 /* extract caller id data */
400                                 for (x = 0; x < cid->pos;) {
401                                         switch (cid->rawdata[x++]) {
402                                         case 0x02: /* caller id  number */
403                                                 cid->number[0] = '\0';
404                                                 cid->name[0] = '\0';
405                                                 cid->flags = 0;
406                                                 res = cid->rawdata[x++];
407                                                 ast_copy_string(cid->number, &cid->rawdata[x], res+1);
408                                                 x += res;
409                                                 break;
410                                         case 0x21: /* additional information */
411                                                 /* length */
412                                                 x++; 
413                                                 /* number type */
414                                                 switch (cid->rawdata[x]) { 
415                                                 case 0x00: /* unknown */
416                                                 case 0x01: /* international number */
417                                                 case 0x02: /* domestic number */
418                                                 case 0x03: /* network */
419                                                 case 0x04: /* local call */
420                                                 case 0x06: /* short dial number */
421                                                 case 0x07: /* reserved */
422                                                 default:   /* reserved */
423                                                         if (option_debug > 1)
424                                                                 ast_log(LOG_DEBUG, "cid info:#1=%X\n", cid->rawdata[x]);
425                                                         break ;
426                                                 }
427                                                 x++; 
428                                                 /* numbering plan octed 4 */
429                                                 x++; 
430                                                 /* numbering plan octed 5 */
431                                                 switch (cid->rawdata[x]) { 
432                                                 case 0x00: /* unknown */
433                                                 case 0x01: /* recommendation E.164 ISDN */
434                                                 case 0x03: /* recommendation X.121 */
435                                                 case 0x04: /* telex dial plan */
436                                                 case 0x08: /* domestic dial plan */
437                                                 case 0x09: /* private dial plan */
438                                                 case 0x05: /* reserved */
439                                                 default:   /* reserved */
440                                                         if (option_debug > 1)
441                                                                 ast_log(LOG_DEBUG, "cid info:#2=%X\n", cid->rawdata[x]);
442                                                         break ;
443                                                 }
444                                                 x++; 
445                                                 break ;
446                                         case 0x04: /* no callerid reason */
447                                                 /* length */
448                                                 x++; 
449                                                 /* no callerid reason code */
450                                                 switch (cid->rawdata[x]) {
451                                                 case 'P': /* caller id denied by user */
452                                                 case 'O': /* service not available */
453                                                 case 'C': /* pay phone */
454                                                 case 'S': /* service congested */
455                                                                 cid->flags |= CID_UNKNOWN_NUMBER;
456                                                         if (option_debug > 1)
457                                                                 ast_log(LOG_DEBUG, "no cid reason:%c\n",cid->rawdata[x]);
458                                                         break ;
459                                                 }
460                                                 x++; 
461                                                 break ;
462                                         case 0x09: /* dialed number */
463                                                 /* length */
464                                                 res = cid->rawdata[x++];
465                                                 /* dialed number */
466                                                 x += res;
467                                                 break ;
468                                         case 0x22: /* dialed number additional information */
469                                                 /* length */
470                                                 x++;
471                                                 /* number type */
472                                                 switch (cid->rawdata[x]) {
473                                                 case 0x00: /* unknown */
474                                                 case 0x01: /* international number */
475                                                 case 0x02: /* domestic number */
476                                                 case 0x03: /* network */
477                                                 case 0x04: /* local call */
478                                                 case 0x06: /* short dial number */
479                                                 case 0x07: /* reserved */
480                                                 default:   /* reserved */
481                                                         if (option_debug > 1)
482                                                                 ast_log(LOG_NOTICE, "did info:#1=%X\n", cid->rawdata[x]);
483                                                         break ;
484                                                 }
485                                                 x++;
486                                                 /* numbering plan octed 4 */
487                                                 x++;
488                                                 /* numbering plan octed 5 */
489                                                 switch (cid->rawdata[x]) {
490                                                 case 0x00: /* unknown */
491                                                 case 0x01: /* recommendation E.164 ISDN */
492                                                 case 0x03: /* recommendation X.121 */
493                                                 case 0x04: /* telex dial plan */
494                                                 case 0x08: /* domestic dial plan */
495                                                 case 0x09: /* private dial plan */
496                                                 case 0x05: /* reserved */
497                                                 default:   /* reserved */
498                                                         if (option_debug > 1)
499                                                                 ast_log(LOG_DEBUG, "did info:#2=%X\n", cid->rawdata[x]);
500                                                         break ;
501                                                 }
502                                                 x++;
503                                                 break ;
504                                         }
505                                 }
506                                 return 1;
507                                 break;
508                         default:
509                                 ast_log(LOG_ERROR, "invalid value in sawflag %d\n", cid->sawflag);
510                         }
511                 }
512         }
513         if (mylen) {
514                 memcpy(cid->oldstuff, buf, mylen * 2);
515                 cid->oldlen = mylen * 2;
516         } else
517                 cid->oldlen = 0;
518         
519         return 0;
520 }
521
522
523 int callerid_feed(struct callerid_state *cid, unsigned char *ubuf, int len, int codec)
524 {
525         int mylen = len;
526         int olen;
527         int b = 'X';
528         int res;
529         int x;
530         short *buf;
531
532         buf = alloca(2 * len + cid->oldlen);
533
534         memcpy(buf, cid->oldstuff, cid->oldlen);
535         mylen += cid->oldlen/2;
536
537         for (x = 0; x < len; x++) 
538                 buf[x+cid->oldlen/2] = AST_XLAW(ubuf[x]);
539         while (mylen >= 160) {
540                 olen = mylen;
541                 res = fsk_serial(&cid->fskd, buf, &mylen, &b);
542                 if (mylen < 0) {
543                         ast_log(LOG_ERROR, "fsk_serial made mylen < 0 (%d)\n", mylen);
544                         return -1;
545                 }
546                 buf += (olen - mylen);
547                 if (res < 0) {
548                         ast_log(LOG_NOTICE, "fsk_serial failed\n");
549                         return -1;
550                 }
551                 if (res == 1) {
552                         /* Ignore invalid bytes */
553                         if (b > 0xff)
554                                 continue;
555                         switch (cid->sawflag) {
556                         case 0: /* Look for flag */
557                                 if (b == 'U')
558                                         cid->sawflag = 2;
559                                 break;
560                         case 2: /* Get lead-in */
561                                 if ((b == 0x04) || (b == 0x80)) {
562                                         cid->type = b;
563                                         cid->sawflag = 3;
564                                         cid->cksum = b;
565                                 }
566                                 break;
567                         case 3: /* Get length */
568                                 /* Not a lead in.  We're ready  */
569                                 cid->sawflag = 4;
570                                 cid->len = b;
571                                 cid->pos = 0;
572                                 cid->cksum += b;
573                                 break;
574                         case 4: /* Retrieve message */
575                                 if (cid->pos >= 128) {
576                                         ast_log(LOG_WARNING, "Caller ID too long???\n");
577                                         return -1;
578                                 }
579                                 cid->rawdata[cid->pos++] = b;
580                                 cid->len--;
581                                 cid->cksum += b;
582                                 if (!cid->len) {
583                                         cid->rawdata[cid->pos] = '\0';
584                                         cid->sawflag = 5;
585                                 }
586                                 break;
587                         case 5: /* Check checksum */
588                                 if (b != (256 - (cid->cksum & 0xff))) {
589                                         ast_log(LOG_NOTICE, "Caller*ID failed checksum\n");
590                                         /* Try again */
591                                         cid->sawflag = 0;
592                                         break;
593                                 }
594                 
595                                 cid->number[0] = '\0';
596                                 cid->name[0] = '\0';
597                                 /* If we get this far we're fine.  */
598                                 if (cid->type == 0x80) {
599                                         /* MDMF */
600                                         /* Go through each element and process */
601                                         for (x = 0; x < cid->pos;) {
602                                                 switch (cid->rawdata[x++]) {
603                                                 case 1:
604                                                         /* Date */
605                                                         break;
606                                                 case 2: /* Number */
607                                                 case 3: /* Number (for Zebble) */
608                                                 case 4: /* Number */
609                                                         res = cid->rawdata[x];
610                                                         if (res > 32) {
611                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID number from %d bytes to 32\n", cid->rawdata[x]);
612                                                                 res = 32; 
613                                                         }
614                                                         if (ast_strlen_zero(cid->number)) {
615                                                                 memcpy(cid->number, cid->rawdata + x + 1, res);
616                                                                 /* Null terminate */
617                                                                 cid->number[res] = '\0';
618                                                         }
619                                                         break;
620                                                 case 6: /* Stentor Call Qualifier (ie. Long Distance call) */
621                                                         break;
622                                                 case 7: /* Name */
623                                                 case 8: /* Name */
624                                                         res = cid->rawdata[x];
625                                                         if (res > 32) {
626                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID name from %d bytes to 32\n", cid->rawdata[x]);
627                                                                 res = 32; 
628                                                         }
629                                                         memcpy(cid->name, cid->rawdata + x + 1, res);
630                                                         cid->name[res] = '\0';
631                                                         break;
632                                                 case 17: /* UK: Call type, 1=Voice Call, 2=Ringback when free, 129=Message waiting  */
633                                                 case 19: /* UK: Network message system status (Number of messages waiting) */
634                                                 case 22: /* Something French */
635                                                         break;
636                                                 default:
637                                                         ast_log(LOG_NOTICE, "Unknown IE %d\n", cid->rawdata[x - 1]);
638                                                 }
639                                                 x += cid->rawdata[x];
640                                                 x++;
641                                         }
642                                 } else {
643                                         /* SDMF */
644                                         ast_copy_string(cid->number, cid->rawdata + 8, sizeof(cid->number));
645                                 }
646                                 /* Update flags */
647                                 cid->flags = 0;
648                                 if (!strcmp(cid->number, "P")) {
649                                         strcpy(cid->number, "");
650                                         cid->flags |= CID_PRIVATE_NUMBER;
651                                 } else if (!strcmp(cid->number, "O") || ast_strlen_zero(cid->number)) {
652                                         strcpy(cid->number, "");
653                                         cid->flags |= CID_UNKNOWN_NUMBER;
654                                 }
655                                 if (!strcmp(cid->name, "P")) {
656                                         strcpy(cid->name, "");
657                                         cid->flags |= CID_PRIVATE_NAME;
658                                 } else if (!strcmp(cid->name, "O") || ast_strlen_zero(cid->name)) {
659                                         strcpy(cid->name, "");
660                                         cid->flags |= CID_UNKNOWN_NAME;
661                                 }
662                                 return 1;
663                                 break;
664                         default:
665                                 ast_log(LOG_ERROR, "Dunno what to do with a digit in sawflag %d\n", cid->sawflag);
666                         }
667                 }
668         }
669         if (mylen) {
670                 memcpy(cid->oldstuff, buf, mylen * 2);
671                 cid->oldlen = mylen * 2;
672         } else
673                 cid->oldlen = 0;
674
675         return 0;
676 }
677
678 void callerid_free(struct callerid_state *cid)
679 {
680         free(cid);
681 }
682
683 static int callerid_genmsg(char *msg, int size, const char *number, const char *name, int flags)
684 {
685         time_t t;
686         struct tm tm;
687         char *ptr;
688         int res;
689         int i, x;
690
691         /* Get the time */
692         time(&t);
693         localtime_r(&t,&tm);
694         
695         ptr = msg;
696         
697         /* Format time and message header */
698         res = snprintf(ptr, size, "\001\010%02d%02d%02d%02d", tm.tm_mon + 1,
699                                 tm.tm_mday, tm.tm_hour, tm.tm_min);
700         size -= res;
701         ptr += res;
702         if (ast_strlen_zero(number) || (flags & CID_UNKNOWN_NUMBER)) {
703                 /* Indicate number not known */
704                 res = snprintf(ptr, size, "\004\001O");
705                 size -= res;
706                 ptr += res;
707         } else if (flags & CID_PRIVATE_NUMBER) {
708                 /* Indicate number is private */
709                 res = snprintf(ptr, size, "\004\001P");
710                 size -= res;
711                 ptr += res;
712         } else {
713                 /* Send up to 16 digits of number MAX */
714                 i = strlen(number);
715                 if (i > 16)
716                         i = 16;
717                 res = snprintf(ptr, size, "\002%c", i);
718                 size -= res;
719                 ptr += res;
720                 for (x = 0; x < i; x++)
721                         ptr[x] = number[x];
722                 ptr[i] = '\0';
723                 ptr += i;
724                 size -= i;
725         }
726
727         if (ast_strlen_zero(name) || (flags & CID_UNKNOWN_NAME)) {
728                 /* Indicate name not known */
729                 res = snprintf(ptr, size, "\010\001O");
730                 size -= res;
731                 ptr += res;
732         } else if (flags & CID_PRIVATE_NAME) {
733                 /* Indicate name is private */
734                 res = snprintf(ptr, size, "\010\001P");
735                 size -= res;
736                 ptr += res;
737         } else {
738                 /* Send up to 16 digits of name MAX */
739                 i = strlen(name);
740                 if (i > 16)
741                         i = 16;
742                 res = snprintf(ptr, size, "\007%c", i);
743                 size -= res;
744                 ptr += res;
745                 for (x = 0; x < i; x++)
746                         ptr[x] = name[x];
747                 ptr[i] = '\0';
748                 ptr += i;
749                 size -= i;
750         }
751         return (ptr - msg);
752         
753 }
754
755 int vmwi_generate(unsigned char *buf, int active, int mdmf, int codec)
756 {
757         unsigned char msg[256];
758         int len=0;
759         int sum;
760         int x;
761         int bytes = 0;
762         float cr = 1.0;
763         float ci = 0.0;
764         float scont = 0.0;
765
766         if (mdmf) {
767                 /* MDMF Message waiting */
768                 msg[len++] = 0x82;
769                 /* Length is 3 */
770                 msg[len++] = 3;
771                 /* IE is "Message Waiting Parameter" */
772                 msg[len++] = 0xb;
773                 /* Length of IE is one */
774                 msg[len++] = 1;
775                 /* Active or not */
776                 if (active)
777                         msg[len++] = 0xff;
778                 else
779                         msg[len++] = 0x00;
780         } else {
781                 /* SDMF Message waiting */
782                 msg[len++] = 0x6;
783                 /* Length is 3 */
784                 msg[len++] = 3;
785                 if (active) {
786                         msg[len++] = 0x42;
787                         msg[len++] = 0x42;
788                         msg[len++] = 0x42;
789                 } else {
790                         msg[len++] = 0x6f;
791                         msg[len++] = 0x6f;
792                         msg[len++] = 0x6f;
793                 }
794         }
795         sum = 0;
796         for (x = 0; x < len; x++)
797                 sum += msg[x];
798         sum = (256 - (sum & 255));
799         msg[len++] = sum;
800         /* Wait a half a second */
801         for (x = 0; x < 4000; x++)
802                 PUT_BYTE(0x7f);
803         /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
804         for (x = 0; x < 30; x++)
805                 PUT_CLID(0x55);
806         /* Send 170ms of callerid marks */
807         for (x = 0; x < 170; x++)
808                 PUT_CLID_MARKMS;
809         for (x = 0; x < len; x++) {
810                 PUT_CLID(msg[x]);
811         }
812         /* Send 50 more ms of marks */
813         for (x = 0; x < 50; x++)
814                 PUT_CLID_MARKMS;
815         return bytes;
816 }
817
818 int callerid_generate(unsigned char *buf, const char *number, const char *name, int flags, int callwaiting, int codec)
819 {
820         int bytes=0;
821         int x, sum;
822         int len;
823
824         /* Initial carriers (real/imaginary) */
825         float cr = 1.0;
826         float ci = 0.0;
827         float scont = 0.0;
828         char msg[256];
829         len = callerid_genmsg(msg, sizeof(msg), number, name, flags);
830         if (!callwaiting) {
831                 /* Wait a half a second */
832                 for (x = 0; x < 4000; x++)
833                         PUT_BYTE(0x7f);
834                 /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
835                 for (x = 0; x < 30; x++)
836                         PUT_CLID(0x55);
837         }
838         /* Send 150ms of callerid marks */
839         for (x = 0; x < 150; x++)
840                 PUT_CLID_MARKMS;
841         /* Send 0x80 indicating MDMF format */
842         PUT_CLID(0x80);
843         /* Put length of whole message */
844         PUT_CLID(len);
845         sum = 0x80 + strlen(msg);
846         /* Put each character of message and update checksum */
847         for (x = 0; x < len; x++) {
848                 PUT_CLID(msg[x]);
849                 sum += msg[x];
850         }
851         /* Send 2's compliment of sum */
852         PUT_CLID(256 - (sum & 255));
853
854         /* Send 50 more ms of marks */
855         for (x = 0; x < 50; x++)
856                 PUT_CLID_MARKMS;
857         
858         return bytes;
859 }
860
861 /*! \brief Clean up phone string
862  * remove '(', ' ', ')', non-trailing '.', and '-' not in square brackets.
863  * Basically, remove anything that could be invalid in a pattern.
864  */
865 void ast_shrink_phone_number(char *n)
866 {
867         int x, y=0;
868         int bracketed = 0;
869
870         for (x = 0; n[x]; x++) {
871                 switch (n[x]) {
872                 case '[':
873                         bracketed++;
874                         n[y++] = n[x];
875                         break;
876                 case ']':
877                         bracketed--;
878                         n[y++] = n[x];
879                         break;
880                 case '-':
881                         if (bracketed)
882                                 n[y++] = n[x];
883                         break;
884                 case '.':
885                         if (!n[x+1])
886                                 n[y++] = n[x];
887                         break;
888                 default:
889                         if (!strchr("()", n[x]))
890                                 n[y++] = n[x];
891                 }
892         }
893         n[y] = '\0';
894 }
895
896 /*! \brief Checks if phone number consists of valid characters 
897         \param exten    String that needs to be checked
898         \param valid    Valid characters in string
899         \return 1 if valid string, 0 if string contains invalid characters
900 */
901 static int ast_is_valid_string(const char *exten, const char *valid)
902 {
903         int x;
904
905         if (ast_strlen_zero(exten))
906                 return 0;
907         for (x = 0; exten[x]; x++)
908                 if (!strchr(valid, exten[x]))
909                         return 0;
910         return 1;
911 }
912
913 /*! \brief checks if string consists only of digits and * \# and + 
914         \return 1 if string is valid AST phone number
915         \return 0 if not
916 */
917 int ast_isphonenumber(const char *n)
918 {
919         return ast_is_valid_string(n, "0123456789*#+");
920 }
921
922 /*! \brief checks if string consists only of digits and ( ) - * \# and + 
923         Pre-qualifies the string for ast_shrink_phone_number()
924         \return 1 if string is valid AST shrinkable phone number
925         \return 0 if not
926 */
927 int ast_is_shrinkable_phonenumber(const char *exten)
928 {
929         return ast_is_valid_string(exten, "0123456789*#+()-.");
930 }
931
932 /*! \brief parse string for caller id information 
933         \return always returns 0, as the code always returns something.
934   XXX note that 'name' is not parsed consistently e.g. we have
935
936         input                   location        name
937         " foo bar " <123>       123             ' foo bar ' (with spaces around)
938         " foo bar "             NULL            'foo bar' (without spaces around)
939         " foo bar  <123>"       123             '" foo bar'
940   The parsing of leading and trailing space/quotes should be more consistent.
941 */
942 int ast_callerid_parse(char *instr, char **name, char **location)
943 {
944         char *ns, *ne, *ls, *le;
945
946         /* Try "name" <location> format or name <location> format */
947         if ((ls = strchr(instr, '<')) && (le = strchr(ls, '>'))) {
948                 *ls = *le = '\0';       /* location found, trim off the brackets */
949                 *location = ls + 1;     /* and this is the result */
950                 if ((ns = strchr(instr, '"')) && (ne = strchr(ns + 1, '"'))) {
951                         *ns = *ne = '\0';       /* trim off the quotes */
952                         *name = ns + 1;         /* and this is the name */
953                 } else { /* no quotes, trim off leading and trailing spaces */
954                         *name = ast_skip_blanks(instr);
955                         ast_trim_blanks(*name);
956                 }
957         } else {        /* no valid brackets */
958                 char tmp[256];
959
960                 ast_copy_string(tmp, instr, sizeof(tmp));
961                 ast_shrink_phone_number(tmp);
962                 if (ast_isphonenumber(tmp)) {   /* Assume it's just a location */
963                         *name = NULL;
964                         strcpy(instr, tmp); /* safe, because tmp will always be the same size or smaller than instr */
965                         *location = instr;
966                 } else { /* Assume it's just a name. */
967                         *location = NULL;
968                         if ((ns = strchr(instr, '"')) && (ne = strchr(ns + 1, '"'))) {
969                                 *ns = *ne = '\0';       /* trim off the quotes */
970                                 *name = ns + 1;         /* and this is the name */
971                         } else { /* no quotes, trim off leading and trailing spaces */
972                                 *name = ast_skip_blanks(instr);
973                                 ast_trim_blanks(*name);
974                         }
975                 }
976         }
977         return 0;
978 }
979
980 static int __ast_callerid_generate(unsigned char *buf, const char *name, const char *number, int callwaiting, int codec)
981 {
982         if (ast_strlen_zero(name))
983                 name = NULL;
984         if (ast_strlen_zero(number))
985                 number = NULL;
986         return callerid_generate(buf, number, name, 0, callwaiting, codec);
987 }
988
989 int ast_callerid_generate(unsigned char *buf, const char *name, const char *number, int codec)
990 {
991         return __ast_callerid_generate(buf, name, number, 0, codec);
992 }
993
994 int ast_callerid_callwaiting_generate(unsigned char *buf, const char *name, const char *number, int codec)
995 {
996         return __ast_callerid_generate(buf, name, number, 1, codec);
997 }
998
999 char *ast_callerid_merge(char *buf, int bufsiz, const char *name, const char *num, const char *unknown)
1000 {
1001         if (!unknown)
1002                 unknown = "<unknown>";
1003         if (name && num)
1004                 snprintf(buf, bufsiz, "\"%s\" <%s>", name, num);
1005         else if (name) 
1006                 ast_copy_string(buf, name, bufsiz);
1007         else if (num)
1008                 ast_copy_string(buf, num, bufsiz);
1009         else
1010                 ast_copy_string(buf, unknown, bufsiz);
1011         return buf;
1012 }
1013
1014 int ast_callerid_split(const char *buf, char *name, int namelen, char *num, int numlen)
1015 {
1016         char *tmp;
1017         char *l = NULL, *n = NULL;
1018
1019         tmp = ast_strdupa(buf);
1020         ast_callerid_parse(tmp, &n, &l);
1021         if (n)
1022                 ast_copy_string(name, n, namelen);
1023         else
1024                 name[0] = '\0';
1025         if (l) {
1026                 ast_shrink_phone_number(l);
1027                 ast_copy_string(num, l, numlen);
1028         } else
1029                 num[0] = '\0';
1030         return 0;
1031 }
1032
1033 /*! \brief Translation table for Caller ID Presentation settings */
1034 static struct {
1035         int val;
1036         const char *name;
1037         const char *description;
1038 } pres_types[] = {
1039         {  AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED, "allowed_not_screened", "Presentation Allowed, Not Screened"},
1040         {  AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, "allowed_passed_screen", "Presentation Allowed, Passed Screen"},
1041         {  AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN, "allowed_failed_screen", "Presentation Allowed, Failed Screen"},
1042         {  AST_PRES_ALLOWED_NETWORK_NUMBER, "allowed", "Presentation Allowed, Network Number"},
1043         {  AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED, "prohib_not_screened", "Presentation Prohibited, Not Screened"},
1044         {  AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN, "prohib_passed_screen", "Presentation Prohibited, Passed Screen"},
1045         {  AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN, "prohib_failed_screen", "Presentation Prohibited, Failed Screen"},
1046         {  AST_PRES_PROHIB_NETWORK_NUMBER, "prohib", "Presentation Prohibited, Network Number"},
1047         {  AST_PRES_NUMBER_NOT_AVAILABLE, "unavailable", "Number Unavailable"},
1048 };
1049
1050 /*! \brief Convert caller ID text code to value 
1051         used in config file parsing
1052         \param data text string
1053         \return value AST_PRES_ from callerid.h 
1054 */
1055 int ast_parse_caller_presentation(const char *data)
1056 {
1057         int i;
1058
1059         for (i = 0; i < ((sizeof(pres_types) / sizeof(pres_types[0]))); i++) {
1060                 if (!strcasecmp(pres_types[i].name, data))
1061                         return pres_types[i].val;
1062         }
1063
1064         return -1;
1065 }
1066
1067 /*! \brief Convert caller ID pres value to explanatory string 
1068         \param data value (see callerid.h AST_PRES_ ) 
1069         \return string for human presentation
1070 */
1071 const char *ast_describe_caller_presentation(int data)
1072 {
1073         int i;
1074
1075         for (i = 0; i < ((sizeof(pres_types) / sizeof(pres_types[0]))); i++) {
1076                 if (pres_types[i].val == data)
1077                         return pres_types[i].description;
1078         }
1079
1080         return "unknown";
1081 }
1082
1083 /*! \brief Convert caller ID pres value to text code
1084         \param data text string
1085         \return string for config file
1086 */
1087 const char *ast_named_caller_presentation(int data)
1088 {
1089         int i;
1090
1091         for (i = 0; i < ((sizeof(pres_types) / sizeof(pres_types[0]))); i++) {
1092                 if (pres_types[i].val == data)
1093                         return pres_types[i].name;
1094         }
1095
1096         return "unknown";
1097 }