Version 0.1.9 from FTP
[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/callerid.h>
25 #include <asterisk/logger.h>
26 #include <asterisk/fskmodem.h>
27 #include "sas.h"
28 #include "cas.h"
29
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 static float dr[4], di[4];
47 static float clidsb = 8000.0 / 1200.0;
48
49 #define CALLERID_SPACE  2200.0          /* 2200 hz for "0" */
50 #define CALLERID_MARK   1200.0          /* 1200 hz for "1" */
51
52 void callerid_init(void)
53 {
54         /* Initialize stuff for inverse FFT */
55         dr[0] = cos(CALLERID_SPACE * 2.0 * M_PI / 8000.0);
56         di[0] = sin(CALLERID_SPACE * 2.0 * M_PI / 8000.0);
57         dr[1] = cos(CALLERID_MARK * 2.0 * M_PI / 8000.0);
58         di[1] = sin(CALLERID_MARK * 2.0 * M_PI / 8000.0);
59 }
60
61 struct callerid_state *callerid_new(void)
62 {
63         struct callerid_state *cid;
64         cid = malloc(sizeof(struct callerid_state));
65         memset(cid, 0, sizeof(struct callerid_state));
66         if (cid) {
67                 cid->fskd.spb = 7;              /* 1200 baud */
68                 cid->fskd.hdlc = 0;             /* Async */
69                 cid->fskd.nbit = 8;             /* 8 bits */
70                 cid->fskd.nstop = 1;    /* 1 stop bit */
71                 cid->fskd.paridad = 0;  /* No parity */
72                 cid->fskd.bw=1;                 /* Filter 800 Hz */
73                 cid->fskd.f_mark_idx =  2;      /* 1200 Hz */
74                 cid->fskd.f_space_idx = 3;      /* 2200 Hz */
75                 cid->fskd.pcola = 0;            /* No clue */
76                 cid->fskd.cont = 0;                     /* Digital PLL reset */
77                 cid->fskd.x0 = 0.0;
78                 cid->fskd.state = 0;
79                 memset(cid->name, 0, sizeof(cid->name));
80                 memset(cid->number, 0, sizeof(cid->number));
81                 cid->flags = CID_UNKNOWN_NAME | CID_UNKNOWN_NUMBER;
82                 cid->pos = 0;
83         } else
84                 ast_log(LOG_WARNING, "Out of memory\n");
85         return cid;
86 }
87
88 void callerid_get(struct callerid_state *cid, char **name, char **number, int *flags)
89 {
90         *flags = cid->flags;
91         if (cid->flags & (CID_UNKNOWN_NAME | CID_PRIVATE_NUMBER))
92                 *name = NULL;
93         else
94                 *name = cid->name;
95         if (cid->flags & (CID_UNKNOWN_NUMBER | CID_PRIVATE_NUMBER))
96                 *number = NULL;
97         else
98                 *number = cid->number;
99 }
100
101 int ast_callerid_gen_cas(unsigned char *outbuf, int len)
102 {
103         int pos = 0;
104         int cnt;
105         int saslen=2400;
106         if (len < saslen)
107                 return -1;
108         while(saslen) {
109                 cnt = saslen;
110                 if (cnt > sizeof(sas))
111                         cnt = sizeof(sas);
112                 memcpy(outbuf + pos, sas, cnt);
113                 pos += cnt;
114                 len -= cnt;
115                 saslen -= cnt;
116         }
117         while(len) {
118                 cnt = len;
119                 if (cnt > sizeof(cas))
120                         cnt = sizeof(cas);
121                 memcpy(outbuf + pos, cas, cnt);
122                 pos += cnt;
123                 len -= cnt;
124         }
125         return 0;
126 }
127
128 int callerid_feed(struct callerid_state *cid, unsigned char *ubuf, int len)
129 {
130         int mylen = len;
131         int olen;
132         int b = 'X';
133         int res;
134         int x;
135         short *buf = malloc(2 * len + cid->oldlen);
136         short *obuf = buf;
137         if (!buf) {
138                 ast_log(LOG_WARNING, "Out of memory\n");
139                 return -1;
140         }
141         memset(buf, 0, 2 * len + cid->oldlen);
142         memcpy(buf, cid->oldstuff, cid->oldlen);
143         mylen += cid->oldlen/2;
144         for (x=0;x<len;x++) 
145                 buf[x+cid->oldlen/2] = ast_mulaw[ubuf[x]];
146         while(mylen >= 80) {
147                 olen = mylen;
148                 res = fsk_serie(&cid->fskd, buf, &mylen, &b);
149                 if (mylen < 0) {
150                         ast_log(LOG_ERROR, "fsk_serie made mylen < 0 (%d)\n", mylen);
151                         return -1;
152                 }
153                 buf += (olen - mylen);
154                 if (res < 0) {
155                         ast_log(LOG_NOTICE, "fsk_serie failed\n");
156                         return -1;
157                 }
158                 if (res == 1) {
159                         /* Ignore invalid bytes */
160                         if (b > 0xff)
161                                 continue;
162                         switch(cid->sawflag) {
163                         case 0: /* Look for flag */
164                                 if (b == 'U')
165                                         cid->sawflag = 2;
166                                 break;
167                         case 2: /* Get lead-in */
168                                 if ((b == 0x04) || (b == 0x80)) {
169                                         cid->type = b;
170                                         cid->sawflag = 3;
171                                         cid->cksum = b;
172                                 }
173                                 break;
174                         case 3: /* Get length */
175                                 /* Not a lead in.  We're ready  */
176                                 cid->sawflag = 4;
177                                 cid->len = b;
178                                 cid->pos = 0;
179                                 cid->cksum += b;
180                                 break;
181                         case 4: /* Retrieve message */
182                                 if (cid->pos >= 128) {
183                                         ast_log(LOG_WARNING, "Caller ID too long???\n");
184                                         return -1;
185                                 }
186                                 cid->rawdata[cid->pos++] = b;
187                                 cid->len--;
188                                 cid->cksum += b;
189                                 if (!cid->len) {
190                                         cid->rawdata[cid->pos] = '\0';
191                                         cid->sawflag = 5;
192                                 }
193                                 break;
194                         case 5: /* Check checksum */
195                                 if (b != (256 - (cid->cksum & 0xff))) {
196                                         ast_log(LOG_NOTICE, "Caller*ID failed checksum\n");
197                                         /* Try again */
198                                         cid->sawflag = 0;
199                                         break;
200                                 }
201                 
202                                 strcpy(cid->number, "");
203                                 strcpy(cid->name, "");
204                                 /* If we get this far we're fine.  */
205                                 if (cid->type == 0x80) {
206                                         /* MDMF */
207                                         /* Go through each element and process */
208                                         for (x=0;x< cid->pos;) {
209                                                 switch(cid->rawdata[x++]) {
210                                                 case 1:
211                                                         /* Date */
212                                                         break;
213                                                 case 2: /* Number */
214                                                 case 4: /* Number */
215                                                         res = cid->rawdata[x];
216                                                         if (res > 32) {
217                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID number from %d bytes to 32\n", cid->rawdata[x]);
218                                                                 res = 32; 
219                                                         }
220                                                         memcpy(cid->number, cid->rawdata + x + 1, res);
221                                                         /* Null terminate */
222                                                         cid->number[res] = '\0';
223                                                         break;
224                                                 case 7: /* Name */
225                                                 case 8: /* Name */
226                                                         res = cid->rawdata[x];
227                                                         if (res > 32) {
228                                                                 ast_log(LOG_NOTICE, "Truncating long caller ID name from %d bytes to 32\n", cid->rawdata[x]);
229                                                                 res = 32; 
230                                                         }
231                                                         memcpy(cid->name, cid->rawdata + x + 1, res);
232                                                         cid->name[res] = '\0';
233                                                         break;
234                                                 default:
235                                                         ast_log(LOG_NOTICE, "Unknown IE %d\n", cid->rawdata[x-1]);
236                                                 }
237                                                 x += cid->rawdata[x];
238                                                 x++;
239                                         }
240                                 } else {
241                                         /* SDMF */
242                                         strncpy(cid->number, cid->rawdata + 8, sizeof(cid->number));
243                                 }
244                                 /* Update flags */
245                                 cid->flags = 0;
246                                 if (!strcmp(cid->number, "P")) {
247                                         strcpy(cid->number, "");
248                                         cid->flags |= CID_PRIVATE_NUMBER;
249                                 } else if (!strcmp(cid->number, "O") || !strlen(cid->number)) {
250                                         strcpy(cid->number, "");
251                                         cid->flags |= CID_UNKNOWN_NUMBER;
252                                 }
253                                 if (!strcmp(cid->name, "P")) {
254                                         strcpy(cid->name, "");
255                                         cid->flags |= CID_PRIVATE_NAME;
256                                 } else if (!strcmp(cid->name, "O") || !strlen(cid->name)) {
257                                         strcpy(cid->name, "");
258                                         cid->flags |= CID_UNKNOWN_NAME;
259                                 }
260                                 return 1;
261                                 break;
262                         default:
263                                 ast_log(LOG_ERROR, "Dunno what to do with a digit in sawflag %d\n", cid->sawflag);
264                         }
265                 }
266         }
267         if (mylen) {
268                 memcpy(cid->oldstuff, buf, mylen * 2);
269                 cid->oldlen = mylen * 2;
270         } else
271                 cid->oldlen = 0;
272         free(obuf);
273         return 0;
274 }
275
276 void callerid_free(struct callerid_state *cid)
277 {
278         free(cid);
279 }
280
281 static void callerid_genmsg(char *msg, int size, char *number, char *name, int flags)
282 {
283         time_t t;
284         struct tm *tm;
285         char *ptr;
286         int res;
287         int i,x;
288         /* Get the time */
289         time(&t);
290         tm = localtime(&t);
291         
292         ptr = msg;
293         
294         /* Format time and message header */
295         res = snprintf(ptr, size, "\001\010%02d%02d%02d%02d", tm->tm_mon + 1,
296                                 tm->tm_mday, tm->tm_hour, tm->tm_min);
297         size -= res;
298         ptr += res;
299         if (!number || !strlen(number) || (flags & CID_UNKNOWN_NUMBER)) {
300                 /* Indicate number not known */
301                 res = snprintf(ptr, size, "\004\001O");
302                 size -= res;
303                 ptr += res;
304         } else if (flags & CID_PRIVATE_NUMBER) {
305                 /* Indicate number is private */
306                 res = snprintf(ptr, size, "\004\001P");
307                 size -= res;
308                 ptr += res;
309         } else {
310                 /* Send up to 10 digits of number MAX */
311                 i = strlen(number);
312                 if (i > 10) i = 10;
313                 res = snprintf(ptr, size, "\002%c", i);
314                 size -= res;
315                 ptr += res;
316                 for (x=0;x<i;x++)
317                         ptr[x] = number[x];
318                 ptr[i] = '\0';
319                 ptr += i;
320                 size -= i;
321         }
322
323         if (!name || !strlen(name) || (flags & CID_UNKNOWN_NAME)) {
324                 /* Indicate name not known */
325                 res = snprintf(ptr, size, "\010\001O");
326                 size -= res;
327                 ptr += res;
328         } else if (flags & CID_PRIVATE_NAME) {
329                 /* Indicate name is private */
330                 res = snprintf(ptr, size, "\010\001P");
331                 size -= res;
332                 ptr += res;
333         } else {
334                 /* Send up to 10 digits of number MAX */
335                 i = strlen(name);
336                 if (i > 16) i = 16;
337                 res = snprintf(ptr, size, "\007%c", i);
338                 size -= res;
339                 ptr += res;
340                 for (x=0;x<i;x++)
341                         ptr[x] = name[x];
342                 ptr[i] = '\0';
343                 ptr += i;
344                 size -= i;
345         }
346         
347 }
348
349 static inline float callerid_getcarrier(float *cr, float *ci, int bit)
350 {
351         /* Move along.  There's nothing to see here... */
352         float t;
353         t = *cr * dr[bit] - *ci * di[bit];
354         *ci = *cr * di[bit] + *ci * dr[bit];
355         *cr = t;
356         
357         t = 2.0 - (*cr * *cr + *ci * *ci);
358         *cr *= t;
359         *ci *= t;
360         return *cr;
361 }       
362
363 #define PUT_BYTE(a) do { \
364         *(buf++) = (a); \
365         bytes++; \
366 } while(0)
367
368 #define PUT_AUDIO_SAMPLE(y) do { \
369         int index = (short)(rint(8192.0 * (y))); \
370         *(buf++) = ast_lin2mu[index + 32768]; \
371         bytes++; \
372 } while(0)
373         
374 #define PUT_CLID_MARKMS do { \
375         int x; \
376         for (x=0;x<8;x++) \
377                 PUT_AUDIO_SAMPLE(callerid_getcarrier(&cr, &ci, 1)); \
378 } while(0)
379
380 #define PUT_CLID_BAUD(bit) do { \
381         while(scont < clidsb) { \
382                 PUT_AUDIO_SAMPLE(callerid_getcarrier(&cr, &ci, bit)); \
383                 scont += 1.0; \
384         } \
385         scont -= clidsb; \
386 } while(0)
387
388
389 #define PUT_CLID(byte) do { \
390         int z; \
391         unsigned char b = (byte); \
392         PUT_CLID_BAUD(0);       /* Start bit */ \
393         for (z=0;z<8;z++) { \
394                 PUT_CLID_BAUD(b & 1); \
395                 b >>= 1; \
396         } \
397         PUT_CLID_BAUD(1);       /* Stop bit */ \
398 } while(0);     
399
400 int callerid_generate(unsigned char *buf, char *number, char *name, int flags, int callwaiting)
401 {
402         int bytes=0;
403         int x, sum;
404         /* Initial carriers (real/imaginary) */
405         float cr = 1.0;
406         float ci = 0.0;
407         float scont = 0.0;
408         char msg[256];
409         callerid_genmsg(msg, sizeof(msg), number, name, flags);
410         if (!callwaiting) {
411                 /* Wait a half a second */
412                 for (x=0;x<4000;x++)
413                         PUT_BYTE(0x7f);
414                 /* Transmit 30 0x55's (looks like a square wave) for channel seizure */
415                 for (x=0;x<30;x++)
416                         PUT_CLID(0x55);
417         }
418         /* Send 150ms of callerid marks */
419         for (x=0;x<150;x++)
420                 PUT_CLID_MARKMS;
421         /* Send 0x80 indicating MDMF format */
422         PUT_CLID(0x80);
423         /* Put length of whole message */
424         PUT_CLID(strlen(msg));
425         sum = 0x80 + strlen(msg);
426         /* Put each character of message and update checksum */
427         for (x=0;x<strlen(msg); x++) {
428                 PUT_CLID(msg[x]);
429                 sum += msg[x];
430         }
431         /* Send 2's compliment of sum */
432         PUT_CLID(256 - (sum & 255));
433         /* Send 50 more ms of marks */
434         for (x=0;x<50;x++)
435                 PUT_CLID_MARKMS;
436         
437         return bytes;
438 }
439
440 void ast_shrink_phone_number(char *n)
441 {
442         int x,y=0;
443         for (x=0;n[x];x++)
444                 if (!strchr("( )-.", n[x]))
445                         n[y++] = n[x];
446         n[y] = '\0';
447 }
448
449 int ast_isphonenumber(char *n)
450 {
451         int x;
452         if (!n || !strlen(n))
453                 return 0;
454         for (x=0;n[x];x++)
455                 if (!strchr("0123456789", n[x]))
456                         return 0;
457         return 1;
458 }
459
460 int ast_callerid_parse(char *instr, char **name, char **location)
461 {
462         char *ns, *ne;
463         char *ls, *le;
464         char tmp[256];
465         /* Try for "name" <location> format or 
466            name <location> format */
467         if ((ls = strchr(instr, '<')) && (le = strchr(ls, '>'))) {
468                 /* Found the location */
469                 *le = '\0';
470                 *ls = '\0';
471                 *location = ls + 1;
472                 if ((ns = strchr(instr, '\"')) && (ne = strchr(ns + 1, '\"'))) {
473                         /* Get name out of quotes */
474                         *ns = '\0';
475                         *ne = '\0';
476                         *name = ns + 1;
477                         return 0;
478                 } else {
479                         /* Just trim off any trailing spaces */
480                         *name = instr;
481                         while(strlen(instr) && (instr[strlen(instr) - 1] < 33))
482                                 instr[strlen(instr) - 1] = '\0';
483                         /* And leading spaces */
484                         while(**name && (**name < 33))
485                                 name++;
486                         return 0;
487                 }
488         } else {
489                 strncpy(tmp, instr, sizeof(tmp));
490                 ast_shrink_phone_number(tmp);
491                 if (ast_isphonenumber(tmp)) {
492                         /* Assume it's just a location */
493                         *name = NULL;
494                         *location = instr;
495                 } else {
496                         /* Assume it's just a name */
497                         *name = instr;
498                         *location = NULL;
499                 }
500                 return 0;
501         }
502         return -1;
503 }
504
505 static int __ast_callerid_generate(unsigned char *buf, char *callerid, int callwaiting)
506 {
507         char tmp[256];
508         char *n, *l;
509         if (!callerid)
510                 return callerid_generate(buf, NULL, NULL, 0, callwaiting);
511         strncpy(tmp, callerid, sizeof(tmp));
512         if (ast_callerid_parse(tmp, &n, &l)) {
513                 ast_log(LOG_WARNING, "Unable to parse '%s' into CallerID name & number\n", callerid);
514                 return callerid_generate(buf, NULL, NULL, 0, callwaiting);
515         }
516         if (l)
517                 ast_shrink_phone_number(l);
518         if (!ast_isphonenumber(l))
519                 return callerid_generate(buf, NULL, n, 0, callwaiting);
520         return callerid_generate(buf, l, n, 0, callwaiting);
521 }
522
523 int ast_callerid_generate(unsigned char *buf, char *callerid)
524 {
525         return __ast_callerid_generate(buf, callerid, 0);
526 }
527
528 int ast_callerid_callwaiting_generate(unsigned char *buf, char *callerid)
529 {
530         return __ast_callerid_generate(buf, callerid, 1);
531 }