/ fixed up timers for ring back and busy tones
[asterisk/asterisk.git] / callerid.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * CallerID Generation support 
5  * 
6  * Copyright (C) 2001, Linux Support Services, Inc.
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License.
12  *
13  * Includes code and algorithms from the Zapata library.
14  *
15  */
16
17 #include <time.h>
18 #include <string.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <math.h>
23 #include <asterisk/ulaw.h>
24 #include <asterisk/alaw.h>
25 #include <asterisk/frame.h>
26 #include <asterisk/callerid.h>
27 #include <asterisk/logger.h>
28 #include <asterisk/fskmodem.h>
29 #include <asterisk/utils.h>
30
31 struct callerid_state {
32         fsk_data fskd;
33         char rawdata[256];
34         short oldstuff[160];
35         int oldlen;
36         int pos;
37         int type;
38         int cksum;
39         char name[64];
40         char number[64];
41         int flags;
42         int sawflag;
43         int len;
44 };
45
46
47 float cid_dr[4], cid_di[4];
48 float clidsb = 8000.0 / 1200.0;
49 float sasdr, sasdi;
50 float casdr1, casdi1, casdr2, casdi2;
51
52 #define CALLERID_SPACE  2200.0          /* 2200 hz for "0" */
53 #define CALLERID_MARK   1200.0          /* 1200 hz for "1" */
54 #define SAS_FREQ                 440.0
55 #define CAS_FREQ1               2130.0
56 #define CAS_FREQ2               2750.0
57
58 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)
59 {
60         int x;
61         float t;
62         for (x=0;x<len;x++) {
63                 t = *cr1 * ddr1 - *ci1 * ddi1;
64                 *ci1 = *cr1 * ddi1 + *ci1 * ddr1;
65                 *cr1 = t;
66                 t = 2.0 - (*cr1 * *cr1 + *ci1 * *ci1);
67                 *cr1 *= t;
68                 *ci1 *= t;      
69
70                 t = *cr2 * ddr2 - *ci2 * ddi2;
71                 *ci2 = *cr2 * ddi2 + *ci2 * ddr2;
72                 *cr2 = t;
73                 t = 2.0 - (*cr2 * *cr2 + *ci2 * *ci2);
74                 *cr2 *= t;
75                 *ci2 *= t;      
76                 buf[x] = AST_LIN2X((*cr1 + *cr2) * 8192.0);
77         }
78 }
79
80 static inline void gen_tone(unsigned char *buf, int len, int codec, float ddr1, float ddi1, float *cr1, float *ci1)
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                 buf[x] = AST_LIN2X(*cr1 * 8192.0);
92         }
93 }
94
95 void callerid_init(void)
96 {
97         /* Initialize stuff for inverse FFT */
98         cid_dr[0] = cos(CALLERID_SPACE * 2.0 * M_PI / 8000.0);
99         cid_di[0] = sin(CALLERID_SPACE * 2.0 * M_PI / 8000.0);
100         cid_dr[1] = cos(CALLERID_MARK * 2.0 * M_PI / 8000.0);
101         cid_di[1] = sin(CALLERID_MARK * 2.0 * M_PI / 8000.0);
102         sasdr = cos(SAS_FREQ * 2.0 * M_PI / 8000.0);
103         sasdi = sin(SAS_FREQ * 2.0 * M_PI / 8000.0);
104         casdr1 = cos(CAS_FREQ1 * 2.0 * M_PI / 8000.0);
105         casdi1 = sin(CAS_FREQ1 * 2.0 * M_PI / 8000.0);
106         casdr2 = cos(CAS_FREQ2 * 2.0 * M_PI / 8000.0);
107         casdi2 = sin(CAS_FREQ2 * 2.0 * M_PI / 8000.0);
108 }
109
110 struct callerid_state *callerid_new(void)
111 {
112         struct callerid_state *cid;
113         cid = malloc(sizeof(struct callerid_state));
114         if (cid) {
115                 memset(cid, 0, sizeof(struct callerid_state));
116                 cid->fskd.spb = 7;              /* 1200 baud */
117                 cid->fskd.hdlc = 0;             /* Async */
118                 cid->fskd.nbit = 8;             /* 8 bits */
119                 cid->fskd.nstop = 1;    /* 1 stop bit */
120                 cid->fskd.paridad = 0;  /* No parity */
121                 cid->fskd.bw=1;                 /* Filter 800 Hz */
122                 cid->fskd.f_mark_idx =  2;      /* 1200 Hz */
123                 cid->fskd.f_space_idx = 3;      /* 2200 Hz */
124                 cid->fskd.pcola = 0;            /* No clue */
125                 cid->fskd.cont = 0;                     /* Digital PLL reset */
126                 cid->fskd.x0 = 0.0;
127                 cid->fskd.state = 0;
128                 memset(cid->name, 0, sizeof(cid->name));
129                 memset(cid->number, 0, sizeof(cid->number));
130                 cid->flags = CID_UNKNOWN_NAME | CID_UNKNOWN_NUMBER;
131                 cid->pos = 0;
132         } else
133                 ast_log(LOG_WARNING, "Out of memory\n");
134         return cid;
135 }
136
137 void callerid_get(struct callerid_state *cid, char **name, char **number, int *flags)
138 {
139         *flags = cid->flags;
140         if (cid->flags & (CID_UNKNOWN_NAME | CID_PRIVATE_NUMBER))
141                 *name = NULL;
142         else
143                 *name = cid->name;
144         if (cid->flags & (CID_UNKNOWN_NUMBER | CID_PRIVATE_NUMBER))
145                 *number = NULL;
146         else
147                 *number = cid->number;
148 }
149
150 int ast_gen_cas(unsigned char *outbuf, int sendsas, int len, int codec)
151 {
152         int pos = 0;
153         int saslen=2400;
154         float cr1 = 1.0;
155         float ci1 = 0.0;
156         float cr2 = 1.0;
157         float ci2 = 0.0;
158         if (sendsas) {
159                 if (len < saslen)
160                         return -1;
161                 gen_tone(outbuf, saslen, codec, sasdr, sasdi, &cr1, &ci1);
162                 len -= saslen;
163                 pos += saslen;
164                 cr2 = cr1;
165                 ci2 = ci1;
166         }
167         gen_tones(outbuf + pos, len, codec, casdr1, casdi1, casdr2, casdi2, &cr1, &ci1, &cr2, &ci2);
168         return 0;
169 }
170
171 int callerid_feed(struct callerid_state *cid, unsigned char *ubuf, int len, int codec)
172 {
173         int mylen = len;
174         int olen;
175         int b = 'X';
176         int res;
177         int x;
178         short *buf = malloc(2 * len + cid->oldlen);
179         short *obuf = buf;
180         if (!buf) {
181                 ast_log(LOG_WARNING, "Out of memory\n");
182                 return -1;
183         }
184         memset(buf, 0, 2 * len + cid->oldlen);
185         memcpy(buf, cid->oldstuff, cid->oldlen);
186         mylen += cid->oldlen/2;
187         for (x=0;x<len;x++) 
188                 buf[x+cid->oldlen/2] = AST_XLAW(ubuf[x]);
189         while(mylen >= 80) {
190                 olen = mylen;
191                 res = fsk_serie(&cid->fskd, buf, &mylen, &b);
192                 if (mylen < 0) {
193                         ast_log(LOG_ERROR, "fsk_serie made mylen < 0 (%d)\n", mylen);
194                         return -1;
195                 }
196                 buf += (olen - mylen);
197                 if (res < 0) {
198                         ast_log(LOG_NOTICE, "fsk_serie failed\n");
199                         return -1;
200                 }
201                 if (res == 1) {
202                         /* Ignore invalid bytes */
203                         if (b > 0xff)
204                                 continue;
205                         switch(cid->sawflag) {
206                         case 0: /* Look for flag */
207                                 if (b == 'U')
208                                         cid->sawflag = 2;
209                                 break;
210                         case 2: /* Get lead-in */
211                                 if ((b == 0x04) || (b == 0x80)) {
212                                         cid->type = b;
213                                         cid->sawflag = 3;
214                                         cid->cksum = b;
215                                 }
216                                 break;
217                         case 3: /* Get length */
218                                 /* Not a lead in.  We're ready  */
219                                 cid->sawflag = 4;
220                                 cid->len = b;
221                                 cid->pos = 0;
222                                 cid->cksum += b;
223                                 break;
224                         case 4: /* Retrieve message */
225                                 if (cid->pos >= 128) {
226                                         ast_log(LOG_WARNING, "Caller ID too long???\n");
227                                         return -1;
228                                 }
229                                 cid->rawdata[cid->pos++] = b;
230                                 cid->len--;
231                                 cid->cksum += b;
232                                 if (!cid->len) {
233                                         cid->rawdata[cid->pos] = '\0';
234                                         cid->sawflag = 5;
235                                 }
236                                 break;
237                         case 5: /* Check checksum */
238                                 if (b != (256 - (cid->cksum & 0xff))) {
239                                         ast_log(LOG_NOTICE, "Caller*ID failed checksum\n");
240                                         /* Try again */
241                                         cid->sawflag = 0;
242                                         break;
243                                 }
244                 
245                                 strcpy(cid->number, "");
246                                 strcpy(cid->name, "");
247                                 /* If we get this far we're fine.  */
248                                 if (cid->type == 0x80) {
249                                         /* MDMF */
250                                         /* Go through each element and process */
251                                         for (x=0;x< cid->pos;) {
252                                                 switch(cid->rawdata[x++]) {
253                                                 case 1:
254                                                         /* Date */
255                                                         break;
256                                                 case 2: /* Number */
257                                                 case 3: /* Number (for Zebble) */
258                                                 case 4: /* Number */
259                                                         res = cid->rawdata[x];
260                                                         if (res > 32) {
261                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID number from %d bytes to 32\n", cid->rawdata[x]);
262                                                                 res = 32; 
263                                                         }
264                                                         memcpy(cid->number, cid->rawdata + x + 1, res);
265                                                         /* Null terminate */
266                                                         cid->number[res] = '\0';
267                                                         break;
268                                                 case 7: /* Name */
269                                                 case 8: /* Name */
270                                                         res = cid->rawdata[x];
271                                                         if (res > 32) {
272                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID name from %d bytes to 32\n", cid->rawdata[x]);
273                                                                 res = 32; 
274                                                         }
275                                                         memcpy(cid->name, cid->rawdata + x + 1, res);
276                                                         cid->name[res] = '\0';
277                                                         break;
278                                                 case 22: /* Something French */
279                                                         break;
280                                                 default:
281                                                         ast_log(LOG_NOTICE, "Unknown IE %d\n", cid->rawdata[x-1]);
282                                                 }
283                                                 x += cid->rawdata[x];
284                                                 x++;
285                                         }
286                                 } else {
287                                         /* SDMF */
288                                         strncpy(cid->number, cid->rawdata + 8, sizeof(cid->number)-1);
289                                 }
290                                 /* Update flags */
291                                 cid->flags = 0;
292                                 if (!strcmp(cid->number, "P")) {
293                                         strcpy(cid->number, "");
294                                         cid->flags |= CID_PRIVATE_NUMBER;
295                                 } else if (!strcmp(cid->number, "O") || ast_strlen_zero(cid->number)) {
296                                         strcpy(cid->number, "");
297                                         cid->flags |= CID_UNKNOWN_NUMBER;
298                                 }
299                                 if (!strcmp(cid->name, "P")) {
300                                         strcpy(cid->name, "");
301                                         cid->flags |= CID_PRIVATE_NAME;
302                                 } else if (!strcmp(cid->name, "O") || ast_strlen_zero(cid->name)) {
303                                         strcpy(cid->name, "");
304                                         cid->flags |= CID_UNKNOWN_NAME;
305                                 }
306                                 return 1;
307                                 break;
308                         default:
309                                 ast_log(LOG_ERROR, "Dunno what to do with a digit in sawflag %d\n", cid->sawflag);
310                         }
311                 }
312         }
313         if (mylen) {
314                 memcpy(cid->oldstuff, buf, mylen * 2);
315                 cid->oldlen = mylen * 2;
316         } else
317                 cid->oldlen = 0;
318         free(obuf);
319         return 0;
320 }
321
322 void callerid_free(struct callerid_state *cid)
323 {
324         free(cid);
325 }
326
327 static int callerid_genmsg(char *msg, int size, char *number, char *name, int flags)
328 {
329         time_t t;
330         struct tm tm;
331         char *ptr;
332         int res;
333         int i,x;
334         /* Get the time */
335         time(&t);
336         localtime_r(&t,&tm);
337         
338         ptr = msg;
339         
340         /* Format time and message header */
341         res = snprintf(ptr, size, "\001\010%02d%02d%02d%02d", tm.tm_mon + 1,
342                                 tm.tm_mday, tm.tm_hour, tm.tm_min);
343         size -= res;
344         ptr += res;
345         if (!number || ast_strlen_zero(number) || (flags & CID_UNKNOWN_NUMBER)) {
346                 /* Indicate number not known */
347                 res = snprintf(ptr, size, "\004\001O");
348                 size -= res;
349                 ptr += res;
350         } else if (flags & CID_PRIVATE_NUMBER) {
351                 /* Indicate number is private */
352                 res = snprintf(ptr, size, "\004\001P");
353                 size -= res;
354                 ptr += res;
355         } else {
356                 /* Send up to 16 digits of number MAX */
357                 i = strlen(number);
358                 if (i > 16) i = 16;
359                 res = snprintf(ptr, size, "\002%c", i);
360                 size -= res;
361                 ptr += res;
362                 for (x=0;x<i;x++)
363                         ptr[x] = number[x];
364                 ptr[i] = '\0';
365                 ptr += i;
366                 size -= i;
367         }
368
369         if (!name || ast_strlen_zero(name) || (flags & CID_UNKNOWN_NAME)) {
370                 /* Indicate name not known */
371                 res = snprintf(ptr, size, "\010\001O");
372                 size -= res;
373                 ptr += res;
374         } else if (flags & CID_PRIVATE_NAME) {
375                 /* Indicate name is private */
376                 res = snprintf(ptr, size, "\010\001P");
377                 size -= res;
378                 ptr += res;
379         } else {
380                 /* Send up to 16 digits of name MAX */
381                 i = strlen(name);
382                 if (i > 16) i = 16;
383                 res = snprintf(ptr, size, "\007%c", i);
384                 size -= res;
385                 ptr += res;
386                 for (x=0;x<i;x++)
387                         ptr[x] = name[x];
388                 ptr[i] = '\0';
389                 ptr += i;
390                 size -= i;
391         }
392         return (ptr - msg);
393         
394 }
395
396 int vmwi_generate(unsigned char *buf, int active, int mdmf, int codec)
397 {
398         unsigned char msg[256];
399         int len=0;
400         int sum;
401         int x;
402         int bytes = 0;
403         float cr = 1.0;
404         float ci = 0.0;
405         float scont = 0.0;
406         if (mdmf) {
407                 /* MDMF Message waiting */
408                 msg[len++] = 0x82;
409                 /* Length is 3 */
410                 msg[len++] = 3;
411                 /* IE is "Message Waiting Parameter" */
412                 msg[len++] = 0xb;
413                 /* Length of IE is one */
414                 msg[len++] = 1;
415                 /* Active or not */
416                 if (active)
417                         msg[len++] = 0xff;
418                 else
419                         msg[len++] = 0x00;
420         } else {
421                 /* SDMF Message waiting */
422                 msg[len++] = 0x6;
423                 /* Length is 3 */
424                 msg[len++] = 3;
425                 if (active) {
426                         msg[len++] = 0x42;
427                         msg[len++] = 0x42;
428                         msg[len++] = 0x42;
429                 } else {
430                         msg[len++] = 0x6f;
431                         msg[len++] = 0x6f;
432                         msg[len++] = 0x6f;
433                 }
434         }
435         sum = 0;
436         for (x=0;x<len;x++)
437                 sum += msg[x];
438         sum = (256 - (sum & 255));
439         msg[len++] = sum;
440         /* Wait a half a second */
441         for (x=0;x<4000;x++)
442                 PUT_BYTE(0x7f);
443         /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
444         for (x=0;x<30;x++)
445                 PUT_CLID(0x55);
446         /* Send 170ms of callerid marks */
447         for (x=0;x<170;x++)
448                 PUT_CLID_MARKMS;
449         for (x=0;x<len;x++) {
450                 PUT_CLID(msg[x]);
451         }
452         /* Send 50 more ms of marks */
453         for (x=0;x<50;x++)
454                 PUT_CLID_MARKMS;
455         return bytes;
456 }
457
458 int callerid_generate(unsigned char *buf, char *number, char *name, int flags, int callwaiting, int codec)
459 {
460         int bytes=0;
461         int x, sum;
462         int len;
463         /* Initial carriers (real/imaginary) */
464         float cr = 1.0;
465         float ci = 0.0;
466         float scont = 0.0;
467         unsigned char msg[256];
468         len = callerid_genmsg(msg, sizeof(msg), number, name, flags);
469         if (!callwaiting) {
470                 /* Wait a half a second */
471                 for (x=0;x<4000;x++)
472                         PUT_BYTE(0x7f);
473                 /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
474                 for (x=0;x<30;x++)
475                         PUT_CLID(0x55);
476         }
477         /* Send 150ms of callerid marks */
478         for (x=0;x<150;x++)
479                 PUT_CLID_MARKMS;
480         /* Send 0x80 indicating MDMF format */
481         PUT_CLID(0x80);
482         /* Put length of whole message */
483         PUT_CLID(len);
484         sum = 0x80 + strlen(msg);
485         /* Put each character of message and update checksum */
486         for (x=0;x<len; x++) {
487                 PUT_CLID(msg[x]);
488                 sum += msg[x];
489         }
490         /* Send 2's compliment of sum */
491         PUT_CLID(256 - (sum & 255));
492
493         /* Send 50 more ms of marks */
494         for (x=0;x<50;x++)
495                 PUT_CLID_MARKMS;
496         
497         return bytes;
498 }
499
500 void ast_shrink_phone_number(char *n)
501 {
502         int x,y=0;
503         for (x=0;n[x];x++)
504                 if (!strchr("( )-.", n[x]))
505                         n[y++] = n[x];
506         n[y] = '\0';
507 }
508
509 int ast_isphonenumber(char *n)
510 {
511         int x;
512         if (!n || ast_strlen_zero(n))
513                 return 0;
514         for (x=0;n[x];x++)
515                 if (!strchr("0123456789*#+", n[x]))
516                         return 0;
517         return 1;
518 }
519
520 int ast_callerid_parse(char *instr, char **name, char **location)
521 {
522         char *ns, *ne;
523         char *ls, *le;
524         char tmp[256];
525         /* Try for "name" <location> format or 
526            name <location> format */
527         if ((ls = strchr(instr, '<')) && (le = strchr(ls, '>'))) {
528                 /* Found the location */
529                 *le = '\0';
530                 *ls = '\0';
531                 *location = ls + 1;
532                 if ((ns = strchr(instr, '\"')) && (ne = strchr(ns + 1, '\"'))) {
533                         /* Get name out of quotes */
534                         *ns = '\0';
535                         *ne = '\0';
536                         *name = ns + 1;
537                         return 0;
538                 } else {
539                         /* Just trim off any trailing spaces */
540                         *name = instr;
541                         while(!ast_strlen_zero(instr) && (instr[strlen(instr) - 1] < 33))
542                                 instr[strlen(instr) - 1] = '\0';
543                         /* And leading spaces */
544                         while(**name && (**name < 33))
545                                 (*name)++;
546                         return 0;
547                 }
548         } else {
549                 strncpy(tmp, instr, sizeof(tmp)-1);
550                 ast_shrink_phone_number(tmp);
551                 if (ast_isphonenumber(tmp)) {
552                         /* Assume it's just a location */
553                         *name = NULL;
554                         *location = instr;
555                 } else {
556                         /* Assume it's just a name.  Make sure it's not quoted though */
557                         *name = instr;
558                         while(*(*name) && ((*(*name) < 33) || (*(*name) == '\"'))) (*name)++;
559                         ne = *name + strlen(*name) - 1;
560                         while((ne > *name) && ((*ne < 33) || (*ne == '\"'))) { *ne = '\0'; ne--; }
561                         *location = NULL;
562                 }
563                 return 0;
564         }
565         return -1;
566 }
567
568 static int __ast_callerid_generate(unsigned char *buf, char *callerid, int callwaiting, int codec)
569 {
570         char tmp[256];
571         char *n, *l;
572         if (!callerid)
573                 return callerid_generate(buf, NULL, NULL, 0, callwaiting, codec);
574         strncpy(tmp, callerid, sizeof(tmp)-1);
575         if (ast_callerid_parse(tmp, &n, &l)) {
576                 ast_log(LOG_WARNING, "Unable to parse '%s' into CallerID name & number\n", callerid);
577                 return callerid_generate(buf, NULL, NULL, 0, callwaiting, codec);
578         }
579         if (l)
580                 ast_shrink_phone_number(l);
581         if (!ast_isphonenumber(l))
582                 return callerid_generate(buf, NULL, n, 0, callwaiting, codec);
583         return callerid_generate(buf, l, n, 0, callwaiting, codec);
584 }
585
586 int ast_callerid_generate(unsigned char *buf, char *callerid, int codec)
587 {
588         return __ast_callerid_generate(buf, callerid, 0, codec);
589 }
590
591 int ast_callerid_callwaiting_generate(unsigned char *buf, char *callerid, int codec)
592 {
593         return __ast_callerid_generate(buf, callerid, 1, codec);
594 }