BSD portability enhancements (bug #234)
[asterisk/asterisk.git] / channels / chan_modem.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * A/Open ITU-56/2 Voice Modem Driver (Rockwell, IS-101, and others)
5  * 
6  * Copyright (C) 1999, Mark Spencer
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
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <string.h>
17 #include <asterisk/lock.h>
18 #include <asterisk/channel.h>
19 #include <asterisk/channel_pvt.h>
20 #include <asterisk/config.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/module.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/options.h>
25 #include <asterisk/vmodem.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <fcntl.h>
34 #include <sys/ioctl.h>
35 #include <sys/termios.h>
36 #include <sys/signal.h>
37 #include <ctype.h>
38
39 /* Up to 10 seconds for an echo to arrive */
40 #define ECHO_TIMEOUT 10
41
42 static char *desc = "Generic Voice Modem Driver";
43 static char *tdesc = "Generic Voice Modem Channel Driver";
44 static char *type = "Modem";
45 static char *config = "modem.conf";
46 static char dialtype = 'T';
47 static int gmode = MODEM_MODE_IMMEDIATE;
48
49 /* Default modem type */
50 static char mtype[80] = "autodetect";
51 /* Default context for incoming calls */
52 static char context[AST_MAX_EXTENSION]= "default";
53
54 /* Default language */
55 static char language[MAX_LANGUAGE] = "";
56
57 /* Initialization String */
58 static char initstr[AST_MAX_INIT_STR] = "ATE0Q0";
59
60 /* Default MSN */
61 static char msn[AST_MAX_EXTENSION]="";
62
63 /* Default Listen */
64 static char incomingmsn[AST_MAX_EXTENSION]="";
65
66 /* Default group */
67 static unsigned int cur_group = 0;
68
69 static int usecnt =0;
70
71 static int baudrate = 115200;
72
73 static int stripmsd = 0;
74
75 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
76
77 /* Protect the interface list (of ast_modem_pvt's) */
78 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
79
80 /* Protect the monitoring thread, so only one process can kill or start it, and not
81    when it's doing something critical. */
82 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
83
84 /* This is the thread for the monitor which checks for input on the channels
85    which are not currently in use.  */
86 static pthread_t monitor_thread = (pthread_t) -1;
87
88 static int restart_monitor(void);
89
90 /* The private structures of the Phone Jack channels are linked for
91    selecting outgoing channels */
92    
93 static struct ast_modem_pvt  *iflist = NULL;
94
95 static int modem_digit(struct ast_channel *ast, char digit)
96 {
97         struct ast_modem_pvt *p;
98         p = ast->pvt->pvt;
99         if (p->mc->dialdigit)
100                 return p->mc->dialdigit(p, digit);
101         ast_log(LOG_DEBUG, "Channel %s lacks digit dialing\n", ast->name);
102         return -1;
103 }
104
105 static struct ast_modem_driver *drivers = NULL;
106
107 static struct ast_frame *modem_read(struct ast_channel *);
108
109 static struct ast_modem_driver *find_capability(char *ident)
110 {
111         struct ast_modem_driver *mc;
112         int x;
113         mc = drivers;
114         while(mc) {
115                 for (x=0;mc->idents[x];x++) {
116                         if (!strcmp(ident, mc->idents[x])) 
117                                 break;
118                 }
119                 if (mc->idents[x])
120                         break;
121                 mc = mc->next;
122         }
123         if (mc) {
124                 if (mc->incusecnt)
125                         mc->incusecnt();
126         }
127         return mc;
128 }
129
130 static struct ast_modem_driver *find_driver(char *drv)
131 {
132         struct ast_modem_driver *mc;
133         mc = drivers;
134         while(mc) {
135                 if (!strcasecmp(mc->name, drv)) 
136                         break;
137                 mc = mc->next;
138         }
139         if (mc) {
140                 if (mc->incusecnt)
141                         mc->incusecnt();
142         }
143         return mc;
144 }
145
146 int ast_register_modem_driver(struct ast_modem_driver *mc)
147 {
148         mc->next = drivers;
149         drivers = mc;
150         return 0;
151 }
152
153 int ast_unregister_modem_driver(struct ast_modem_driver *mc)
154 {
155         struct ast_modem_driver *last = NULL, *cur;
156         cur = drivers;
157         while(cur) {
158                 if (cur == mc) {
159                         if (last)
160                                 last->next = mc->next;
161                         else
162                                 drivers = mc->next;
163                         return 0;
164                 }
165                 cur = cur->next;
166         }
167         return -1;
168 }
169
170 static int modem_call(struct ast_channel *ast, char *idest, int timeout)
171 {
172         struct ast_modem_pvt *p;
173         int ms = timeout;
174         char rdest[80], *where, dstr[100];
175         char *stringp=NULL;
176         strncpy(rdest, idest, sizeof(rdest)-1);
177         stringp=rdest;
178         strsep(&stringp, ":");
179         where = strsep(&stringp, ":");
180         if (!where) {
181                 ast_log(LOG_WARNING, "Destination %s requres a real destination (device:destination)\n", idest);
182                 return -1;
183         }
184         p = ast->pvt->pvt;
185         strcpy(dstr,where + p->stripmsd);
186         /* if not a transfer or just sending tones, must be in correct state */
187         if (strcasecmp(rdest, "transfer") && strcasecmp(rdest,"sendtones")) {
188                 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
189                         ast_log(LOG_WARNING, "modem_call called on %s, neither down nor reserved\n", ast->name);
190                         return -1;
191                 }
192         } 
193         if (!strcasecmp(rdest,"transfer")) /* if a transfer, put in transfer stuff */
194         {
195                 sprintf(dstr,"!,%s",where + p->stripmsd);
196         }
197         if (!strcasecmp(where, "handset")) {
198                 if (p->mc->setdev)
199                         if (p->mc->setdev(p, MODEM_DEV_HANDSET))
200                                 return -1;
201                 /* Should be immediately up */
202                 ast_setstate(ast, AST_STATE_UP);
203         } else {
204                 if (p->mc->setdev)
205                         if (p->mc->setdev(p, MODEM_DEV_TELCO_SPK))
206                                 return -1;
207                 if (p->mc->dial)
208                         p->mc->dial(p, dstr);
209                 ast_setstate(ast, AST_STATE_DIALING);
210                 while((ast->_state != AST_STATE_UP) && (ms > 0)) {
211                         ms = ast_waitfor(ast, ms);
212                         /* Just read packets and watch what happens */
213                         if (ms > 0) {
214                                 if (!modem_read(ast))
215                                         return -1;
216                         }
217                 }
218                 if (ms < 0)     
219                         return -1;
220         }
221         return 0;
222 }
223
224 int ast_modem_send(struct ast_modem_pvt *p, char *cmd, int len)
225 {
226         int i;
227         usleep(5000);
228         if (!len) {
229                 for(i = 0; cmd[i];)
230                    {
231                         if (fwrite(cmd + i,1,1,p->f) != 1)
232                            {
233                                 if (errno == EWOULDBLOCK) continue;
234                                 return -1;
235                            }
236                         i++;
237                    }
238                 tcdrain(fileno(p->f)); 
239                 fprintf(p->f,"\r\n");
240                 return 0;
241         } else {
242                 if (fwrite(cmd, 1, len, p->f) < len)
243                         return -1;
244                 return 0;
245         }
246 }
247
248 int ast_modem_read_response(struct ast_modem_pvt *p, int timeout)
249 {
250         int res = -1,c,i;
251         timeout *= 1000;
252         p->response[0] = 0;
253         c = i = 0;
254         do {
255                 res = ast_waitfor_n_fd(&p->fd, 1, &timeout, NULL);
256                 if (res < 0) {
257                         strncpy(p->response, "(No Response)", sizeof(p->response)-1);
258                         return -1;
259                 }
260                   /* get no more then buffer length */
261                 while(i < sizeof(p->response) - 1)
262                 {
263                         c = fgetc(p->f);  /* get a char */
264                         if (c < 1) /* if error */
265                         {
266                                   /* if nothing in buffer, go back into timeout stuff */
267                                 if (errno == EWOULDBLOCK) break;
268                                 /* return as error */
269                                 strncpy(p->response, "(No Response)", sizeof(p->response)-1);
270                                 return -1;
271                         }
272                           /* save char */
273                         p->response[i++] = c;
274                         p->response[i] = 0;                     
275                           /* if end of input */
276                         if (c == '\n') break;
277                 }
278                 if (c >= 0)  /* if input terminated normally */
279                 {
280                           /* ignore just CR/LF */
281                         if (!strcmp(p->response,"\r\n"))
282                         {
283                                   /* reset input buffer stuff */
284                                 i = 0; 
285                                 p->response[0] = 0;
286                         }
287                         else /* otherwise return with info in buffer */
288                         {
289                                 return 0;
290                         }
291                 }
292         } while(timeout > 0);
293         strncpy(p->response, "(No Response)", sizeof(p->response)-1);
294         return -1;
295 }
296
297 int ast_modem_expect(struct ast_modem_pvt *p, char *result, int timeout)
298 {
299         int res = -1;
300         timeout *= 1000;
301         strncpy(p->response, "(No Response)", sizeof(p->response)-1);
302         do {
303                 res = ast_waitfor_n_fd(&p->fd, 1, &timeout, NULL);
304                 if (res < 0) {
305                         return -1;
306                 }
307                 /* Read a response */
308                 fgets(p->response, sizeof(p->response), p->f);
309 #if     0
310                 fprintf(stderr, "Modem said: %s", p->response);
311 #endif
312                 if (!strncasecmp(p->response, result, strlen(result))) 
313                         return 0;
314         } while(timeout > 0);
315         return -1;
316 }
317
318 void ast_modem_trim(char *s)
319 {
320         int x;
321         x = strlen(s) - 1;
322         while(x >= 0) {
323                 if ((s[x] != '\r') && (s[x] != '\n') && (s[x] != ' '))
324                         break;
325                 s[x] = '\0';
326                 x--;
327         }
328 }
329
330 static int modem_setup(struct ast_modem_pvt *p, int baudrate)
331 {
332
333         /* Make sure there's a modem there and that it's in a reasonable 
334            mode.  Set the baud rate, etc.  */
335         char identity[256];
336         char *ident = NULL;
337         char etx[2] = { 0x10, '!' }; 
338         if (option_debug)
339                 ast_log(LOG_DEBUG, "Setting up modem %s\n", p->dev);
340         if (ast_modem_send(p, etx, 2)) {
341                 ast_log(LOG_WARNING, "Failed to send ETX?\n");
342                 return -1;
343         }
344         if (ast_modem_send(p, "\r\n", 2)) {
345                 ast_log(LOG_WARNING, "Failed to send enter?\n");
346                 return -1;
347         }
348         usleep(10000);
349         /* Read any outstanding stuff */
350         while(!ast_modem_read_response(p, 0));
351         if (ast_modem_send(p, "ATZ", 0)) {
352                 ast_log(LOG_WARNING, "Modem not responding on %s\n", p->dev);
353                 return -1;
354         }
355         if (ast_modem_expect(p, "OK", ECHO_TIMEOUT)) {
356                 ast_log(LOG_WARNING, "Modem reset failed: %s\n", p->response);
357                 return -1;
358         }
359         if (ast_modem_send(p, p->initstr, 0)) {
360                 ast_log(LOG_WARNING, "Modem not responding on %s\n", p->dev);
361                 return -1;
362         }
363         if (ast_modem_expect(p, "OK", ECHO_TIMEOUT)) {
364                 ast_log(LOG_WARNING, "Modem initialization failed: %s\n", p->response);
365                 return -1;
366         }
367         if (ast_modem_send(p, "ATI3", 0)) {
368                 ast_log(LOG_WARNING, "Modem not responding on %s\n", p->dev);
369                 return -1;
370         }
371         if (ast_modem_read_response(p, ECHO_TIMEOUT)) {
372                 ast_log(LOG_WARNING, "Modem did not provide identification\n");
373                 return -1;
374         }
375         strncpy(identity, p->response, sizeof(identity)-1);
376         ast_modem_trim(identity);
377         if (ast_modem_expect(p, "OK", ECHO_TIMEOUT)) {
378                 ast_log(LOG_WARNING, "Modem did not provide identification\n");
379                 return -1;
380         }
381         if (!strcasecmp(mtype, "autodetect")) {
382                 p->mc = find_capability(identity);
383                 if (!p->mc) {
384                         ast_log(LOG_WARNING, "Unable to autodetect modem.  You'll need to specify a driver in modem.conf.  Please report modem identification (%s) and which driver works to markster@linux-support.net.\n", identity); 
385                         return -1;
386                 }
387         } else {
388                 p->mc = find_driver(mtype);
389                 if (!p->mc) {
390                         ast_log(LOG_WARNING, "No driver for modem type '%s'\n", mtype);
391                         return -1;
392                 }
393         }
394         if (p->mc->init) {
395                 if (p->mc->init(p)) {
396                         ast_log(LOG_WARNING, "Modem Initialization Failed on '%s', driver %s.\n", p->dev, p->mc->name);
397                         p->mc->decusecnt();
398                         return -1;
399                 }
400         }                       
401         if (option_verbose > 2) {
402                 ast_verbose(VERBOSE_PREFIX_3 "Configured modem %s with driver %s (%s)\n", p->dev, p->mc->name, p->mc->identify ? (ident = p->mc->identify(p)) : "No identification");
403         }
404         if (ident)
405                 free(ident);
406         return 0;
407 }
408
409 static int modem_hangup(struct ast_channel *ast)
410 {
411         struct ast_modem_pvt *p;
412         if (option_debug)
413                 ast_log(LOG_DEBUG, "modem_hangup(%s)\n", ast->name);
414         p = ast->pvt->pvt;
415         /* Hang up */
416         if (p->mc->hangup)
417                 p->mc->hangup(p);
418         /* Re-initialize */
419         if (p->mc->init)
420                 p->mc->init(p);
421         ast_setstate(ast, AST_STATE_DOWN);
422         memset(p->cid, 0, sizeof(p->cid));
423         memset(p->dnid, 0, sizeof(p->dnid));
424         ((struct ast_modem_pvt *)(ast->pvt->pvt))->owner = NULL;
425         ast_mutex_lock(&usecnt_lock);
426         usecnt--;
427         if (usecnt < 0) 
428                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
429         ast_mutex_unlock(&usecnt_lock);
430         ast_update_use_count();
431         if (option_verbose > 2) 
432                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
433         ast->pvt->pvt = NULL;
434         ast_setstate(ast, AST_STATE_DOWN);
435         restart_monitor();
436         return 0;
437 }
438
439 static int modem_answer(struct ast_channel *ast)
440 {
441         struct ast_modem_pvt *p;
442         int res=0;
443         if (option_debug)
444                 ast_log(LOG_DEBUG, "modem_answer(%s)\n", ast->name);
445         p = ast->pvt->pvt;
446         if (p->mc->answer) {
447                 res = p->mc->answer(p);
448         }
449         if (!res) {
450                 ast->rings = 0;
451                 ast_setstate(ast, AST_STATE_UP);
452         }
453         return res;
454 }
455
456 #if     0
457 static char modem_2digit(char c)
458 {
459         if (c == 12)
460                 return '#';
461         else if (c == 11)
462                 return '*';
463         else if ((c < 10) && (c >= 0))
464                 return '0' + c - 1;
465         else
466                 return '?';
467 }
468 #endif
469 static struct ast_frame *modem_read(struct ast_channel *ast)
470 {
471         struct ast_modem_pvt *p = ast->pvt->pvt;
472         struct ast_frame *fr=NULL;
473         if (p->mc->read)
474                 fr = p->mc->read(p);
475         return fr;
476 }
477
478 static int modem_write(struct ast_channel *ast, struct ast_frame *frame)
479 {
480         int res=0;
481         long flags;
482         struct ast_modem_pvt *p = ast->pvt->pvt;
483
484         /* Modems tend to get upset when they receive data whilst in
485          * command mode. This makes esp. dial commands short lived.
486          *     Pauline Middelink - 2002-09-24 */
487         if (ast->_state != AST_STATE_UP)
488                 return 0;
489
490         /* Temporarily make non-blocking */
491         flags = fcntl(ast->fds[0], F_GETFL);
492         fcntl(ast->fds[0], F_SETFL, flags | O_NONBLOCK);
493
494         if (p->mc->write)
495                 res = p->mc->write(p, frame);
496
497         /* Block again */
498         fcntl(ast->fds[0], F_SETFL, flags);
499         return 0;
500 }
501
502 struct ast_channel *ast_modem_new(struct ast_modem_pvt *i, int state)
503 {
504         struct ast_channel *tmp;
505         tmp = ast_channel_alloc(1);
506         if (tmp) {
507                 snprintf(tmp->name, sizeof(tmp->name), "Modem[%s]/%s", i->mc->name, i->dev + 5);
508                 tmp->type = type;
509                 tmp->fds[0] = i->fd;
510                 tmp->nativeformats = i->mc->formats;
511                 ast_setstate(tmp, state);
512                 if (state == AST_STATE_RING)
513                         tmp->rings = 1;
514                 tmp->pvt->pvt = i;
515                 tmp->pvt->send_digit = modem_digit;
516                 tmp->pvt->call = modem_call;
517                 tmp->pvt->hangup = modem_hangup;
518                 tmp->pvt->answer = modem_answer;
519                 tmp->pvt->read = modem_read;
520                 tmp->pvt->write = modem_write;
521                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
522                 if (strlen(i->cid))
523                         tmp->callerid = strdup(i->cid);
524                 if (strlen(i->language))
525                         strncpy(tmp->language,i->language, sizeof(tmp->language)-1);
526                 if (strlen(i->dnid))
527                         strncpy(tmp->exten, i->dnid, sizeof(tmp->exten) - 1);
528                 i->owner = tmp;
529                 ast_mutex_lock(&usecnt_lock);
530                 usecnt++;
531                 ast_mutex_unlock(&usecnt_lock);
532                 ast_update_use_count();
533                 if (state != AST_STATE_DOWN) {
534                         if (ast_pbx_start(tmp)) {
535                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
536                                 ast_hangup(tmp);
537                                 tmp = NULL;
538                         }
539                 }
540         } else
541                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
542         return tmp;
543 }
544
545 static void modem_mini_packet(struct ast_modem_pvt *i)
546 {
547         struct ast_frame *fr;
548         fr = i->mc->read(i);
549         if (!fr) return;
550         if (fr->frametype == AST_FRAME_CONTROL) {
551                 if (fr->subclass == AST_CONTROL_RING) {
552                         ast_modem_new(i, AST_STATE_RING);
553                 }
554         }
555 }
556
557 static void *do_monitor(void *data)
558 {
559         fd_set rfds, efds;
560         int n, res;
561         struct ast_modem_pvt *i;
562         /* This thread monitors all the frame relay interfaces which are not yet in use
563            (and thus do not have a separate thread) indefinitely */
564         /* From here on out, we die whenever asked */
565 #if 0
566         if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
567                 ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
568                 return NULL;
569         }
570 #endif
571         for(;;) {
572                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
573                    and wait for the monitor list, but the other way around is okay. */
574                 if (ast_mutex_lock(&monlock)) {
575                         ast_log(LOG_ERROR, "Unable to grab monitor lock\n");
576                         return NULL;
577                 }
578                 /* Lock the interface list */
579                 if (ast_mutex_lock(&iflock)) {
580                         ast_log(LOG_ERROR, "Unable to grab interface lock\n");
581                         ast_mutex_unlock(&monlock);
582                         return NULL;
583                 }
584                 /* Build the stuff we're going to select on, that is the socket of every
585                    ast_modem_pvt that does not have an associated owner channel */
586                 n = -1;
587                 FD_ZERO(&rfds);
588                 FD_ZERO(&efds);
589                 i = iflist;
590                 while(i) {
591                         if (FD_ISSET(i->fd, &rfds)) 
592                                 ast_log(LOG_WARNING, "Descriptor %d appears twice (%s)?\n", i->fd, i->dev);
593                         if (!i->owner) {
594                                 /* This needs to be watched, as it lacks an owner */
595                                 FD_SET(i->fd, &rfds);
596                                 FD_SET(i->fd, &efds);
597                                 if (i->fd > n)
598                                         n = i->fd;
599                         }
600                         
601                         i = i->next;
602                 }
603                 /* Okay, now that we know what to do, release the interface lock */
604                 ast_mutex_unlock(&iflock);
605                 
606                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
607                 ast_mutex_unlock(&monlock);
608 #if 0
609                 ast_log(LOG_DEBUG, "In monitor, n=%d, pid=%d\n", n, getpid());
610 #endif
611                 /* Wait indefinitely for something to happen */
612                 pthread_testcancel();
613                 res = ast_select(n + 1, &rfds, NULL, &efds, NULL);
614                 pthread_testcancel();
615                 /* Okay, select has finished.  Let's see what happened.  */
616                 if (res < 1) {
617                         ast_log(LOG_WARNING, "select return %d: %s\n", res, strerror(errno));
618                         continue;
619                 }
620                 /* Alright, lock the interface list again, and let's look and see what has
621                    happened */
622                 if (ast_mutex_lock(&iflock)) {
623                         ast_log(LOG_WARNING, "Unable to lock the interface list\n");
624                         continue;
625                 }
626                 i = iflist;
627                 while(i) {
628                         if (FD_ISSET(i->fd, &rfds) || FD_ISSET(i->fd, &efds)) {
629                                 if (i->owner) {
630                                         ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d, %s)...\n", i->fd, i->dev);
631                                         i = i->next;
632                                         continue;
633                                 }
634                                 modem_mini_packet(i);
635                         }
636                         i=i->next;
637                 }
638                 ast_mutex_unlock(&iflock);
639         }
640         /* Never reached */
641         return NULL;
642         
643 }
644
645 static int restart_monitor()
646 {
647         /* If we're supposed to be stopped -- stay stopped */
648         if (monitor_thread == (pthread_t) -2)
649                 return 0;
650         if (ast_mutex_lock(&monlock)) {
651                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
652                 return -1;
653         }
654         if (monitor_thread == pthread_self()) {
655                 ast_mutex_unlock(&monlock);
656                 ast_log(LOG_WARNING, "Cannot kill myself\n");
657                 return -1;
658         }
659         if (monitor_thread != (pthread_t) -1) {
660                 pthread_cancel(monitor_thread);
661                 /* Nudge it a little, as it's probably stuck in select */
662                 pthread_kill(monitor_thread, SIGURG);
663                 pthread_join(monitor_thread, NULL);
664         }
665         /* Start a new monitor */
666         if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
667                 ast_mutex_unlock(&monlock);
668                 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
669                 return -1;
670         }
671         ast_mutex_unlock(&monlock);
672         return 0;
673 }
674
675 static void stty(struct ast_modem_pvt *p)
676 {
677         struct termios mode;
678         memset(&mode, 0, sizeof(mode));
679         if (tcgetattr(p->fd, &mode)) {
680                 ast_log(LOG_WARNING, "Unable to get serial parameters on %s: %s\n", p->dev, strerror(errno));
681                 return;
682         }
683         cfmakeraw(&mode);
684         cfsetspeed(&mode, B115200);
685         if (tcsetattr(p->fd, TCSANOW, &mode)) 
686                 ast_log(LOG_WARNING, "Unable to set serial parameters on %s: %s\n", p->dev, strerror(errno));
687         
688 }
689
690 static struct ast_modem_pvt *mkif(char *iface)
691 {
692         /* Make a ast_modem_pvt structure for this interface */
693         struct ast_modem_pvt *tmp;
694 #if 0
695         int flags;      
696 #endif
697         
698         tmp = malloc(sizeof(struct ast_modem_pvt));
699         memset(tmp, 0, sizeof(struct ast_modem_pvt));
700         if (tmp) {
701                 tmp->fd = open(iface, O_RDWR | O_NONBLOCK);
702                 if (tmp->fd < 0) {
703                         ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
704                         free(tmp);
705                         return NULL;
706                 }
707                 strncpy(tmp->language, language, sizeof(tmp->language)-1);
708                 strncpy(tmp->msn, msn, sizeof(tmp->msn)-1);
709                 strncpy(tmp->incomingmsn, incomingmsn, sizeof(tmp->incomingmsn)-1);
710                 strncpy(tmp->dev, iface, sizeof(tmp->dev)-1);
711                 /* Maybe in the future we want to allow variable
712                    serial settings */
713                 stty(tmp);
714                 tmp->f = fdopen(tmp->fd, "w+");
715                 /* Disable buffering */
716                 setvbuf(tmp->f, NULL, _IONBF,0);
717                 if (tmp->f < 0) {
718                         ast_log(LOG_WARNING, "Unable to fdopen '%s'\n", iface);
719                         free(tmp);
720                         return NULL;
721                 }
722                 tmp->owner = NULL;
723                 tmp->ministate = 0;
724                 tmp->stripmsd = stripmsd;
725                 tmp->dialtype = dialtype;
726                 tmp->mode = gmode;
727                 tmp->group = cur_group;
728                 memset(tmp->cid, 0, sizeof(tmp->cid));
729                 strncpy(tmp->context, context, sizeof(tmp->context)-1);
730                 strncpy(tmp->initstr, initstr, sizeof(tmp->initstr)-1);
731                 tmp->next = NULL;
732                 tmp->obuflen = 0;
733                 
734                 if (modem_setup(tmp, baudrate) < 0) {
735                         ast_log(LOG_WARNING, "Unable to configure modem '%s'\n", iface);
736                         free(tmp);
737                         return NULL;
738                 }
739         }
740         return tmp;
741 }
742
743 static struct ast_channel *modem_request(char *type, int format, void *data)
744 {
745         int oldformat;
746         struct ast_modem_pvt *p;
747         struct ast_channel *tmp = NULL;
748         char dev[80];
749         unsigned int group = 0;
750         char *stringp=NULL;
751         strncpy(dev, (char *)data, sizeof(dev)-1);
752         stringp=dev;
753         strsep(&stringp, ":");
754         oldformat = format;
755
756         if (dev[0]=='g' && isdigit(dev[1])) {
757                 /* Retrieve the group number */
758                 if (sscanf(dev+1, "%u", &group) < 1) {
759                         ast_log(LOG_WARNING, "Unable to determine group from [%s]\n", (char *)data);
760                         return NULL;
761                 }
762                 group = 1 << group;
763         }
764
765         /* Search for an unowned channel */
766         if (ast_mutex_lock(&iflock)) {
767                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
768                 return NULL;
769         }
770         p = iflist;
771         while(p) {
772                 if (group) {
773                         /* if it belongs to the proper group, and the format matches
774                          * and it is not in use, we found a candidate! */
775                         if (p->group & group &&
776                             p->mc->formats & format &&
777                             !p->owner) {
778                                 /* XXX Not quite sure that not having an owner is
779                                  * sufficient evidence of beeing a free device XXX */
780                                 tmp = ast_modem_new(p, AST_STATE_DOWN);
781                                 restart_monitor();
782                                 break;
783                         }
784                 } else {
785                         if (!strcmp(dev, p->dev + 5)) {
786                                 if (p->mc->formats & format) {
787                                         if (!p->owner) {
788                                                 tmp = ast_modem_new(p, AST_STATE_DOWN);
789                                                 restart_monitor();
790                                                 break;
791                                         } else
792                                                 ast_log(LOG_WARNING, "Device '%s' is busy\n", p->dev);
793                                 } else 
794                                         ast_log(LOG_WARNING, "Asked for a format %s line on %s\n", ast_getformatname(format), p->dev);
795                                 break;
796                         }
797                 }
798                 p = p->next;
799         }
800         if (!p) 
801                 ast_log(LOG_WARNING, "Requested device '%s' does not exist\n", dev);
802         
803         ast_mutex_unlock(&iflock);
804         return tmp;
805 }
806
807 static unsigned int get_group(char *s)
808 {
809         char *piece;
810         int start, finish,x;
811         unsigned int group = 0;
812         char *copy = ast_strdupa(s);
813         char *stringp=NULL;
814         if (!copy) {
815                 ast_log(LOG_ERROR, "Out of memory\n");
816                 return 0;
817         }
818         stringp=copy;
819         piece = strsep(&stringp, ",");
820         while(piece) {
821                 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
822                         /* Range */
823                 } else if (sscanf(piece, "%d", &start)) {
824                         /* Just one */
825                         finish = start;
826                 } else {
827                         ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'.  Using '0'\n", s,piece);
828                         return 0;
829                 }
830                 piece = strsep(&stringp, ",");
831
832                 for (x=start;x<=finish;x++) {
833                         if ((x > 31) || (x < 0)) {
834                                 ast_log(LOG_WARNING, "Ignoring invalid group %d\n", x);
835                                 break;
836                         }
837                         group |= (1 << x);
838                 }
839         }
840         return group;
841 }
842
843 int load_module()
844 {
845         struct ast_config *cfg;
846         struct ast_variable *v;
847         struct ast_modem_pvt *tmp;
848         char driver[80];
849         cfg = ast_load(config);
850
851         /* We *must* have a config file otherwise stop immediately */
852         if (!cfg) {
853                 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
854                 return -1;
855         }
856         if (ast_mutex_lock(&iflock)) {
857                 /* It's a little silly to lock it, but we mind as well just to be sure */
858                 ast_log(LOG_ERROR, "Unable to lock interface list???\n");
859                 return -1;
860         }
861         v = ast_variable_browse(cfg, "interfaces");
862         while(v) {
863                 /* Create the interface list */
864                 if (!strcasecmp(v->name, "device")) {
865                                 tmp = mkif(v->value);
866                                 if (tmp) {
867                                         tmp->next = iflist;
868                                         iflist = tmp;
869                                         
870                                 } else {
871                                         ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
872                                         ast_destroy(cfg);
873                                         ast_mutex_unlock(&iflock);
874                                         unload_module();
875                                         return -1;
876                                 }
877                 } else if (!strcasecmp(v->name, "driver")) {
878                         snprintf(driver, sizeof(driver), "chan_modem_%s.so", v->value);
879                         if (option_verbose > 1) 
880                                 ast_verbose(VERBOSE_PREFIX_2 "Loading modem driver %s", driver);
881                                 
882                         if (ast_load_resource(driver)) {
883                                 ast_log(LOG_ERROR, "Failed to load driver %s\n", driver);
884                                 ast_destroy(cfg);
885                                 ast_mutex_unlock(&iflock);
886                                 unload_module();
887                                 return -1;
888                         }
889                 } else if (!strcasecmp(v->name, "mode")) {
890                         if (!strncasecmp(v->value, "ri", 2)) 
891                                 gmode = MODEM_MODE_WAIT_RING;
892                         else if (!strncasecmp(v->value, "im", 2))
893                                 gmode = MODEM_MODE_IMMEDIATE;
894                         else if (!strncasecmp(v->value, "an", 2))
895                                 gmode = MODEM_MODE_WAIT_ANSWER;
896                         else
897                                 ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
898                 } else if (!strcasecmp(v->name, "stripmsd")) {
899                         stripmsd = atoi(v->value);
900                 } else if (!strcasecmp(v->name, "type")) {
901                         strncpy(mtype, v->value, sizeof(mtype)-1);
902                 } else if (!strcasecmp(v->name, "initstr")) {
903                         strncpy(initstr, v->value, sizeof(initstr)-1);
904                 } else if (!strcasecmp(v->name, "dialtype")) {
905                         dialtype = toupper(v->value[0]);
906                 } else if (!strcasecmp(v->name, "context")) {
907                         strncpy(context, v->value, sizeof(context)-1);
908                 } else if (!strcasecmp(v->name, "msn")) {
909                         strncpy(msn, v->value, sizeof(msn)-1);
910                 } else if (!strcasecmp(v->name, "incomingmsn")) {
911                         strncpy(incomingmsn, v->value, sizeof(incomingmsn)-1);
912                 } else if (!strcasecmp(v->name, "language")) {
913                         strncpy(language, v->value, sizeof(language)-1);
914                 } else if (!strcasecmp(v->name, "group")) {
915                         cur_group = get_group(v->value);
916                 }
917                 v = v->next;
918         }
919         ast_mutex_unlock(&iflock);
920         if (ast_channel_register(type, tdesc, /* XXX Don't know our types -- maybe we should register more than one XXX */ 
921                                                 AST_FORMAT_SLINEAR, modem_request)) {
922                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
923                 ast_destroy(cfg);
924                 unload_module();
925                 return -1;
926         }
927         ast_destroy(cfg);
928         /* And start the monitor for the first time */
929         restart_monitor();
930         return 0;
931 }
932
933 int unload_module()
934 {
935         struct ast_modem_pvt *p, *pl;
936         /* First, take us out of the channel loop */
937         ast_channel_unregister(type);
938         if (!ast_mutex_lock(&iflock)) {
939                 /* Hangup all interfaces if they have an owner */
940                 p = iflist;
941                 while(p) {
942                         if (p->owner)
943                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
944                         p = p->next;
945                 }
946                 iflist = NULL;
947                 ast_mutex_unlock(&iflock);
948         } else {
949                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
950                 return -1;
951         }
952         if (!ast_mutex_lock(&monlock)) {
953                 if (monitor_thread != (pthread_t) -1 && monitor_thread != (pthread_t) -2) {
954                         pthread_cancel(monitor_thread);
955                         pthread_join(monitor_thread, NULL);
956                 }
957                 monitor_thread = (pthread_t) -2;
958                 ast_mutex_unlock(&monlock);
959         } else {
960                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
961                 return -1;
962         }
963
964         if (!ast_mutex_lock(&iflock)) {
965                 /* Destroy all the interfaces and free their memory */
966                 p = iflist;
967                 while(p) {
968                         /* Close the socket, assuming it's real */
969                         if (p->fd > -1)
970                                 close(p->fd);
971                         pl = p;
972                         p = p->next;
973                         /* Free associated memory */
974                         free(pl);
975                 }
976                 iflist = NULL;
977                 ast_mutex_unlock(&iflock);
978         } else {
979                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
980                 return -1;
981         }
982                 
983         return 0;
984 }
985
986 int usecount(void)
987 {
988         int res;
989         ast_mutex_lock(&usecnt_lock);
990         res = usecnt;
991         ast_mutex_unlock(&usecnt_lock);
992         return res;
993 }
994
995 char *description()
996 {
997         return desc;
998 }
999
1000 char *key()
1001 {
1002         return ASTERISK_GPL_KEY;
1003 }
1004