Allow "fast" asynchronous manager initiation of events (bug #772)
[asterisk/asterisk.git] / manager.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management and more
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 <stdlib.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <sys/time.h>
19 #include <sys/types.h>
20 #include <netdb.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <arpa/inet.h>
25 #include <signal.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <sys/poll.h>
29 #include <asterisk/channel.h>
30 #include <asterisk/file.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/config.h>
33 #include <asterisk/lock.h>
34 #include <asterisk/logger.h>
35 #include <asterisk/options.h>
36 #include <asterisk/cli.h>
37 #include <asterisk/app.h>
38 #include <asterisk/pbx.h>
39 #include <asterisk/md5.h>
40 #include <asterisk/acl.h>
41
42 struct fast_originate_helper
43 {
44         char tech[256];
45         char data[256];
46         int timeout;
47         char app[256];
48         char appdata[256];
49         char callerid[256];
50         char variable[256];
51         char account[256];
52         char context[256];
53         char exten[256];
54         int priority;
55 };
56
57 static int enabled = 0;
58 static int portno = DEFAULT_MANAGER_PORT;
59 static int asock = -1;
60 static pthread_t t;
61 static ast_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
62 static int block_sockets = 0;
63
64 static struct permalias {
65         int num;
66         char *label;
67 } perms[] = {
68         { EVENT_FLAG_SYSTEM, "system" },
69         { EVENT_FLAG_CALL, "call" },
70         { EVENT_FLAG_LOG, "log" },
71         { EVENT_FLAG_VERBOSE, "verbose" },
72         { EVENT_FLAG_COMMAND, "command" },
73         { EVENT_FLAG_AGENT, "agent" },
74         { EVENT_FLAG_USER, "user" },
75         { -1, "all" },
76 };
77
78 static struct mansession *sessions = NULL;
79 static struct manager_action *first_action = NULL;
80 static ast_mutex_t actionlock = AST_MUTEX_INITIALIZER;
81
82 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
83 {
84         /* Try to write string, but wait no more than ms milliseconds
85            before timing out */
86         int res=0;
87         struct pollfd fds[1];
88         while(len) {
89                 res = write(fd, s, len);
90                 if ((res < 0) && (errno != EAGAIN)) {
91                         return -1;
92                 }
93                 if (res < 0) res = 0;
94                 len -= res;
95                 s += res;
96                 fds[0].fd = fd;
97                 fds[0].events = POLLOUT;
98                 /* Wait until writable again */
99                 res = poll(fds, 1, timeoutms);
100                 if (res < 1)
101                         return -1;
102         }
103         return res;
104 }
105
106 static int handle_showmancmds(int fd, int argc, char *argv[])
107 {
108         struct manager_action *cur = first_action;
109         char *format = "  %-15.15s  %-45.45s\n";
110
111         ast_mutex_lock(&actionlock);
112         ast_cli(fd, format, "Action", "Synopsis");
113         while(cur) { /* Walk the list of actions */
114                 ast_cli(fd, format, cur->action, cur->synopsis);
115                 cur = cur->next;
116         }
117
118         ast_mutex_unlock(&actionlock);
119         return RESULT_SUCCESS;
120 }
121
122 static int handle_showmanconn(int fd, int argc, char *argv[])
123 {
124         struct mansession *s;
125         char *format = "  %-15.15s  %-15.15s\n";
126         ast_mutex_lock(&sessionlock);
127         s = sessions;
128         ast_cli(fd, format, "Username", "IP Address");
129         while(s) {
130                 ast_cli(fd, format,s->username, inet_ntoa(s->sin.sin_addr));
131                 s = s->next;
132         }
133
134         ast_mutex_unlock(&sessionlock);
135         return RESULT_SUCCESS;
136 }
137
138 static char showmancmds_help[] = 
139 "Usage: show manager commands\n"
140 "       Prints a listing of all the available manager commands.\n";
141
142 static char showmanconn_help[] = 
143 "Usage: show manager connected\n"
144 "       Prints a listing of the users that are connected to the\n"
145 "manager interface.\n";
146
147 static struct ast_cli_entry show_mancmds_cli =
148         { { "show", "manager", "commands", NULL },
149         handle_showmancmds, "Show manager commands", showmancmds_help };
150
151 static struct ast_cli_entry show_manconn_cli =
152         { { "show", "manager", "connected", NULL },
153         handle_showmanconn, "Show connected manager users", showmanconn_help };
154
155 static void destroy_session(struct mansession *s)
156 {
157         struct mansession *cur, *prev = NULL;
158         ast_mutex_lock(&sessionlock);
159         cur = sessions;
160         while(cur) {
161                 if (cur == s)
162                         break;
163                 prev = cur;
164                 cur = cur->next;
165         }
166         if (cur) {
167                 if (prev)
168                         prev->next = cur->next;
169                 else
170                         sessions = cur->next;
171                 if (s->fd > -1)
172                         close(s->fd);
173                 free(s);
174         } else
175                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
176         ast_mutex_unlock(&sessionlock);
177         
178 }
179
180 char *astman_get_header(struct message *m, char *var)
181 {
182         char cmp[80];
183         int x;
184         snprintf(cmp, sizeof(cmp), "%s: ", var);
185         for (x=0;x<m->hdrcount;x++)
186                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
187                         return m->headers[x] + strlen(cmp);
188         return "";
189 }
190
191 void astman_send_error(struct mansession *s, struct message *m, char *error)
192 {
193         char *id = astman_get_header(m,"ActionID");
194         ast_mutex_lock(&s->lock);
195         ast_cli(s->fd, "Response: Error\r\n");
196         if (id && strlen(id))
197                 ast_cli(s->fd, "ActionID: %s\r\n",id);
198         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
199         ast_mutex_unlock(&s->lock);
200 }
201
202 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
203 {
204         char *id = astman_get_header(m,"ActionID");
205         ast_mutex_lock(&s->lock);
206         ast_cli(s->fd, "Response: %s\r\n", resp);
207         if (id && strlen(id))
208                 ast_cli(s->fd, "ActionID: %s\r\n",id);
209         if (msg)
210                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
211         else
212                 ast_cli(s->fd, "\r\n");
213         ast_mutex_unlock(&s->lock);
214 }
215
216 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
217 {
218         astman_send_response(s, m, "Success", msg);
219 }
220
221 static int get_perm(char *instr)
222 {
223         char tmp[256];
224         char *c;
225         int x;
226         int ret = 0;
227         char *stringp=NULL;
228         if (!instr)
229                 return 0;
230         strncpy(tmp, instr, sizeof(tmp) - 1);
231         stringp=tmp;
232         c = strsep(&stringp, ",");
233         while(c) {
234                 for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
235                         if (!strcasecmp(perms[x].label, c)) 
236                                 ret |= perms[x].num;
237                 }
238                 c = strsep(&stringp, ",");
239         }
240         return ret;
241 }
242
243 static int set_eventmask(struct mansession *s, char *eventmask)
244 {
245         if (!eventmask)
246                 return -1;
247         if (!strcasecmp(eventmask, "on") || ast_true(eventmask)) {
248                 ast_mutex_lock(&s->lock);
249                 s->send_events = 1;
250                 ast_mutex_unlock(&s->lock);
251                 return 1;
252         } else if (!strcasecmp(eventmask, "off") || ast_false(eventmask)) {
253                 ast_mutex_lock(&s->lock);
254                 s->send_events = 0;
255                 ast_mutex_unlock(&s->lock);
256                 return 0;
257         }
258         return -1;
259 }
260
261 static int authenticate(struct mansession *s, struct message *m)
262 {
263         struct ast_config *cfg;
264         char *cat;
265         char *user = astman_get_header(m, "Username");
266         char *pass = astman_get_header(m, "Secret");
267         char *authtype = astman_get_header(m, "AuthType");
268         char *key = astman_get_header(m, "Key");
269         char *events = astman_get_header(m, "Events");
270         
271         cfg = ast_load("manager.conf");
272         if (!cfg)
273                 return -1;
274         cat = ast_category_browse(cfg, NULL);
275         while(cat) {
276                 if (strcasecmp(cat, "general")) {
277                         /* This is a user */
278                         if (!strcasecmp(cat, user)) {
279                                 struct ast_variable *v;
280                                 struct ast_ha *ha = NULL;
281                                 char *password = NULL;
282                                 v = ast_variable_browse(cfg, cat);
283                                 while (v) {
284                                         if (!strcasecmp(v->name, "secret")) {
285                                                 password = v->value;
286                                         } else if (!strcasecmp(v->name, "permit") ||
287                                                    !strcasecmp(v->name, "deny")) {
288                                                         ha = ast_append_ha(v->name, v->value, ha);
289                                         }                                               
290                                         v = v->next;
291                                 }
292                                 if (ha && !ast_apply_ha(ha, &(s->sin))) {
293                                         ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
294                                         ast_free_ha(ha);
295                                         ast_destroy(cfg);
296                                         return -1;
297                                 } else if (ha)
298                                         ast_free_ha(ha);
299                                 if (!strcasecmp(authtype, "MD5")) {
300                                         if (key && strlen(key) && s->challenge) {
301                                                 int x;
302                                                 int len=0;
303                                                 char md5key[256] = "";
304                                                 struct MD5Context md5;
305                                                 unsigned char digest[16];
306                                                 MD5Init(&md5);
307                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
308                                                 MD5Update(&md5, password, strlen(password));
309                                                 MD5Final(digest, &md5);
310                                                 for (x=0;x<16;x++)
311                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
312                                                 if (!strcmp(md5key, key))
313                                                         break;
314                                                 else {
315                                                         ast_destroy(cfg);
316                                                         return -1;
317                                                 }
318                                         }
319                                 } else if (password && !strcasecmp(password, pass)) {
320                                         break;
321                                 } else {
322                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
323                                         ast_destroy(cfg);
324                                         return -1;
325                                 }       
326                         }
327                 }
328                 cat = ast_category_browse(cfg, cat);
329         }
330         if (cat) {
331                 strncpy(s->username, cat, sizeof(s->username) - 1);
332                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
333                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
334                 ast_destroy(cfg);
335                 if (events)
336                         set_eventmask(s, events);
337                 return 0;
338         }
339         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
340         ast_destroy(cfg);
341         return -1;
342 }
343
344 static int action_ping(struct mansession *s, struct message *m)
345 {
346         astman_send_response(s, m, "Pong", NULL);
347         return 0;
348 }
349
350 static int action_events(struct mansession *s, struct message *m)
351 {
352         char *mask = astman_get_header(m, "EventMask");
353         int res;
354
355         res = set_eventmask(s, mask);
356         if (res > 0)
357                 astman_send_response(s, m, "Events On", NULL);
358         else if (res == 0)
359                 astman_send_response(s, m, "Events Off", NULL);
360         else
361                 astman_send_response(s, m, "EventMask parse error", NULL);
362         return 0;
363 }
364
365 static int action_logoff(struct mansession *s, struct message *m)
366 {
367         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
368         return -1;
369 }
370
371 static int action_hangup(struct mansession *s, struct message *m)
372 {
373         struct ast_channel *c = NULL;
374         char *name = astman_get_header(m, "Channel");
375         if (!strlen(name)) {
376                 astman_send_error(s, m, "No channel specified");
377                 return 0;
378         }
379         c = ast_channel_walk(NULL);
380         while(c) {
381                 if (!strcasecmp(c->name, name)) {
382                         break;
383                 }
384                 c = ast_channel_walk(c);
385         }
386         if (!c) {
387                 astman_send_error(s, m, "No such channel");
388                 return 0;
389         }
390         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
391         astman_send_ack(s, m, "Channel Hungup");
392         return 0;
393 }
394
395 static int action_status(struct mansession *s, struct message *m)
396 {
397         char *id = astman_get_header(m,"ActionID");
398         char idText[256] = "";
399         struct ast_channel *c;
400         char bridge[256];
401         astman_send_ack(s, m, "Channel status will follow");
402         c = ast_channel_walk(NULL);
403         if (id && strlen(id))
404                 snprintf(idText,256,"ActionID: %s\r\n",id);
405         while(c) {
406                 if (c->bridge)
407                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
408                 else
409                         strcpy(bridge, "");
410                 if (c->pbx) {
411                         ast_cli(s->fd,
412                         "Event: Status\r\n"
413                         "Channel: %s\r\n"
414                         "CallerID: %s\r\n"
415                         "State: %s\r\n"
416                         "Context: %s\r\n"
417                         "Extension: %s\r\n"
418                         "Priority: %d\r\n"
419                         "%s"
420                         "Uniqueid: %s\r\n"
421                         "%s"
422                         "\r\n",
423                         c->name, c->callerid ? c->callerid : "<unknown>", 
424                         ast_state2str(c->_state), c->context,
425                         c->exten, c->priority, bridge, c->uniqueid, idText);
426                 } else {
427                         ast_cli(s->fd,
428                         "Event: Status\r\n"
429                         "Channel: %s\r\n"
430                         "CallerID: %s\r\n"
431                         "State: %s\r\n"
432                         "%s"
433                         "Uniqueid: %s\r\n"
434                         "%s"
435                         "\r\n",
436                         c->name, c->callerid ? c->callerid : "<unknown>", 
437                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
438                 }
439                 c = ast_channel_walk(c);
440         }
441         ast_cli(s->fd,
442         "Event: StatusComplete\r\n"
443         "%s"
444         "\r\n",idText);
445         return 0;
446 }
447
448 static int action_redirect(struct mansession *s, struct message *m)
449 {
450         char *name = astman_get_header(m, "Channel");
451         char *name2 = astman_get_header(m, "ExtraChannel");
452         char *exten = astman_get_header(m, "Exten");
453         char *context = astman_get_header(m, "Context");
454         char *priority = astman_get_header(m, "Priority");
455         int pi = 0;
456         int res;
457         if (!name || !strlen(name)) {
458                 astman_send_error(s, m, "Channel not specified");
459                 return 0;
460         }
461         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
462                 astman_send_error(s, m, "Invalid priority\n");
463                 return 0;
464         }
465         res = ast_async_goto_by_name(name, context, exten, pi);
466         if (!res) {
467                 if (strlen(name2)) {
468                         res = ast_async_goto_by_name(name2, context, exten, pi);
469                         if (!res)
470                                 astman_send_ack(s, m, "Dual Redirect successful");
471                         else
472                                 astman_send_error(s, m, "Secondary redirect failed");
473                 } else
474                         astman_send_ack(s, m, "Redirect successful");
475         } else
476                 astman_send_error(s, m, "Redirect failed");
477         return 0;
478 }
479
480 static int action_command(struct mansession *s, struct message *m)
481 {
482         char *cmd = astman_get_header(m, "Command");
483         char *id = astman_get_header(m, "ActionID");
484         ast_mutex_lock(&s->lock);
485         s->blocking = 1;
486         ast_mutex_unlock(&s->lock);
487         ast_cli(s->fd, "Response: Follows\r\n");
488         if (id && strlen(id))
489                 ast_cli(s->fd, "ActionID: %s\r\n", id);
490         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
491         ast_cli_command(s->fd, cmd);
492         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
493         ast_mutex_lock(&s->lock);
494         s->blocking = 0;
495         ast_mutex_unlock(&s->lock);
496         return 0;
497 }
498
499 static void *fast_originate(void *data)
500 {
501         struct fast_originate_helper *in = data;
502         int res;
503         int reason = 0;
504         if (strlen(in->app)) {
505                 res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, strlen(in->callerid) ? in->callerid : NULL, in->variable, in->account);
506         } else {
507                 res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, strlen(in->callerid) ? in->callerid : NULL, in->variable, in->account);
508         }   
509         free(in);
510         return NULL;
511 }
512
513 static int action_originate(struct mansession *s, struct message *m)
514 {
515         char *name = astman_get_header(m, "Channel");
516         char *exten = astman_get_header(m, "Exten");
517         char *context = astman_get_header(m, "Context");
518         char *priority = astman_get_header(m, "Priority");
519         char *timeout = astman_get_header(m, "Timeout");
520         char *callerid = astman_get_header(m, "CallerID");
521         char *variable = astman_get_header(m, "Variable");
522         char *account = astman_get_header(m, "Account");
523         char *app = astman_get_header(m, "Application");
524         char *appdata = astman_get_header(m, "Data");
525         char *async = astman_get_header(m, "Async");
526         char *tech, *data;
527         int pi = 0;
528         int res;
529         int to = 30000;
530         int reason = 0;
531         char tmp[256];
532         pthread_t th;
533         pthread_attr_t attr;
534         if (!name) {
535                 astman_send_error(s, m, "Channel not specified");
536                 return 0;
537         }
538         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
539                 astman_send_error(s, m, "Invalid priority\n");
540                 return 0;
541         }
542         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
543                 astman_send_error(s, m, "Invalid timeout\n");
544                 return 0;
545         }
546         strncpy(tmp, name, sizeof(tmp) - 1);
547         tech = tmp;
548         data = strchr(tmp, '/');
549         if (!data) {
550                 astman_send_error(s, m, "Invalid channel\n");
551                 return 0;
552         }
553         *data = '\0';
554         data++;
555         if (ast_true(async))
556         {
557                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
558                 if (!fast)
559                 {
560                         res = -1;
561                 }
562                 else
563                 {
564                         memset(fast, 0, sizeof(struct fast_originate_helper));
565                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
566                         strncpy(fast->data, data, sizeof(fast->data) - 1);
567                         strncpy(fast->app, app, sizeof(fast->app) - 1);
568                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
569                         strncpy(fast->callerid, callerid, sizeof(fast->callerid) - 1);
570                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
571                         strncpy(fast->account, account, sizeof(fast->account) - 1);
572                         strncpy(fast->context, context, sizeof(fast->context) - 1);
573                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
574                         fast->timeout = to;
575                         fast->priority = pi;
576                         pthread_attr_init(&attr);
577                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
578                         if (pthread_create(&th, &attr, fast_originate, fast))
579                         {
580                                 res = -1;
581                         }
582                         else
583                         {
584                                 res = 0;
585                         }
586                 }
587         } else if (strlen(app)) {
588                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
589         } else {
590                 if (exten && context && pi)
591                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
592                 else {
593                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
594                         return 0;
595                 }
596         }   
597         if (!res)
598                 astman_send_ack(s, m, "Originate successfully queued");
599         else
600                 astman_send_error(s, m, "Originate failed");
601         return 0;
602 }
603
604 static int action_mailboxstatus(struct mansession *s, struct message *m)
605 {
606         char *mailbox = astman_get_header(m, "Mailbox");
607         char *id = astman_get_header(m,"ActionID");
608         char idText[256] = "";
609         if (!mailbox || !strlen(mailbox)) {
610                 astman_send_error(s, m, "Mailbox not specified");
611                 return 0;
612         }
613         if (id && strlen(id))
614                 snprintf(idText,256,"ActionID: %s\r\n",id);
615         ast_cli(s->fd, "Response: Success\r\n"
616                                    "%s"
617                                    "Message: Mailbox Status\r\n"
618                                    "Mailbox: %s\r\n"
619                                    "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
620         return 0;
621 }
622
623 static int action_mailboxcount(struct mansession *s, struct message *m)
624 {
625         char *mailbox = astman_get_header(m, "Mailbox");
626         char *id = astman_get_header(m,"ActionID");
627         char idText[256] = "";
628         int newmsgs = 0, oldmsgs = 0;
629         if (!mailbox || !strlen(mailbox)) {
630                 astman_send_error(s, m, "Mailbox not specified");
631                 return 0;
632         }
633         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
634         if (id && strlen(id)) {
635                 snprintf(idText,256,"ActionID: %s\r\n",id);
636         }
637         ast_cli(s->fd, "Response: Success\r\n"
638                                    "%s"
639                                    "Message: Mailbox Message Count\r\n"
640                                    "Mailbox: %s\r\n"
641                                    "NewMessages: %d\r\n"
642                                    "OldMessages: %d\r\n" 
643                                    "\r\n",
644                                     idText,mailbox, newmsgs, oldmsgs);
645         return 0;
646 }
647
648 static int action_extensionstate(struct mansession *s, struct message *m)
649 {
650         char *exten = astman_get_header(m, "Exten");
651         char *context = astman_get_header(m, "Context");
652         char *id = astman_get_header(m,"ActionID");
653         char idText[256] = "";
654         char hint[256] = "";
655         int status;
656         if (!exten || !strlen(exten)) {
657                 astman_send_error(s, m, "Extension not specified");
658                 return 0;
659         }
660         if (!context || !strlen(context))
661                 context = "default";
662         status = ast_extension_state(NULL, context, exten);
663         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
664         if (id && strlen(id)) {
665                 snprintf(idText,256,"ActionID: %s\r\n",id);
666         }
667         ast_cli(s->fd, "Response: Success\r\n"
668                                    "%s"
669                                    "Message: Extension Status\r\n"
670                                    "Exten: %s\r\n"
671                                    "Context: %s\r\n"
672                                    "Hint: %s\r\n"
673                                    "Status: %d\r\n\r\n",
674                                    idText,exten, context, hint, status);
675         return 0;
676 }
677
678 static int action_timeout(struct mansession *s, struct message *m)
679 {
680         struct ast_channel *c = NULL;
681         char *name = astman_get_header(m, "Channel");
682         int timeout = atoi(astman_get_header(m, "Timeout"));
683         if (!strlen(name)) {
684                 astman_send_error(s, m, "No channel specified");
685                 return 0;
686         }
687         if (!timeout) {
688                 astman_send_error(s, m, "No timeout specified");
689                 return 0;
690         }
691         c = ast_channel_walk(NULL);
692         while(c) {
693                 if (!strcasecmp(c->name, name)) {
694                         break;
695                 }
696                 c = ast_channel_walk(c);
697         }
698         if (!c) {
699                 astman_send_error(s, m, "No such channel");
700                 return 0;
701         }
702         ast_channel_setwhentohangup(c, timeout);
703         astman_send_ack(s, m, "Timeout Set");
704         return 0;
705 }
706
707 static int process_message(struct mansession *s, struct message *m)
708 {
709         char action[80];
710         struct manager_action *tmp = first_action;
711         char *id = astman_get_header(m,"ActionID");
712         char idText[256] = "";
713
714         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
715         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
716
717         if (!strlen(action)) {
718                 astman_send_error(s, m, "Missing action in request");
719                 return 0;
720         }
721         if (id && strlen(id)) {
722                 snprintf(idText,256,"ActionID: %s\r\n",id);
723         }
724         if (!s->authenticated) {
725                 if (!strcasecmp(action, "Challenge")) {
726                         char *authtype;
727                         authtype = astman_get_header(m, "AuthType");
728                         if (!strcasecmp(authtype, "MD5")) {
729                                 if (!s->challenge || !strlen(s->challenge)) {
730                                         ast_mutex_lock(&s->lock);
731                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
732                                         ast_mutex_unlock(&s->lock);
733                                 }
734                                 ast_cli(s->fd, "Response: Success\r\n"
735                                                 "%s"
736                                                 "Challenge: %s\r\n\r\n",
737                                                 idText,s->challenge);
738                                 return 0;
739                         } else {
740                                 astman_send_error(s, m, "Must specify AuthType");
741                                 return 0;
742                         }
743                 } else if (!strcasecmp(action, "Login")) {
744                         if (authenticate(s, m)) {
745                                 sleep(1);
746                                 astman_send_error(s, m, "Authentication failed");
747                                 return -1;
748                         } else {
749                                 s->authenticated = 1;
750                                 if (option_verbose > 1) 
751                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
752                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
753                                 astman_send_ack(s, m, "Authentication accepted");
754                         }
755                 } else if (!strcasecmp(action, "Logoff")) {
756                         astman_send_ack(s, m, "See ya");
757                         return -1;
758                 } else
759                         astman_send_error(s, m, "Authentication Required");
760         } else {
761                 while( tmp ) {          
762                         if (!strcasecmp(action, tmp->action)) {
763                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
764                                         if (tmp->func(s, m))
765                                                 return -1;
766                                 } else {
767                                         astman_send_error(s, m, "Permission denied");
768                                 }
769                                 return 0;
770                         }
771                         tmp = tmp->next;
772                 }
773                 astman_send_error(s, m, "Invalid/unknown command");
774         }
775         return 0;
776 }
777
778 static int get_input(struct mansession *s, char *output)
779 {
780         /* output must have at least sizeof(s->inbuf) space */
781         int res;
782         int x;
783         struct pollfd fds[1];
784         for (x=1;x<s->inlen;x++) {
785                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
786                         /* Copy output data up to and including \r\n */
787                         memcpy(output, s->inbuf, x + 1);
788                         /* Add trailing \0 */
789                         output[x+1] = '\0';
790                         /* Move remaining data back to the front */
791                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
792                         s->inlen -= (x + 1);
793                         return 1;
794                 }
795         } 
796         if (s->inlen >= sizeof(s->inbuf) - 1) {
797                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
798                 s->inlen = 0;
799         }
800         fds[0].fd = s->fd;
801         fds[0].events = POLLIN;
802         res = poll(fds, 1, -1);
803         if (res < 0) {
804                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
805         } else if (res > 0) {
806                 ast_mutex_lock(&s->lock);
807                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
808                 ast_mutex_unlock(&s->lock);
809                 if (res < 1)
810                         return -1;
811         }
812         s->inlen += res;
813         s->inbuf[s->inlen] = '\0';
814         return 0;
815 }
816
817 static void *session_do(void *data)
818 {
819         struct mansession *s = data;
820         struct message m;
821         int res;
822         
823         ast_mutex_lock(&s->lock);
824         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
825         ast_mutex_unlock(&s->lock);
826         memset(&m, 0, sizeof(&m));
827         for (;;) {
828                 res = get_input(s, m.headers[m.hdrcount]);
829                 if (res > 0) {
830                         /* Strip trailing \r\n */
831                         if (strlen(m.headers[m.hdrcount]) < 2)
832                                 continue;
833                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
834                         if (!strlen(m.headers[m.hdrcount])) {
835                                 if (process_message(s, &m))
836                                         break;
837                                 memset(&m, 0, sizeof(&m));
838                         } else if (m.hdrcount < MAX_HEADERS - 1)
839                                 m.hdrcount++;
840                 } else if (res < 0)
841                         break;
842         }
843         if (s->authenticated) {
844                 if (option_verbose > 1) 
845                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
846                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
847         } else {
848                 if (option_verbose > 1)
849                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
850                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
851         }
852         destroy_session(s);
853         return NULL;
854 }
855
856 static void *accept_thread(void *ignore)
857 {
858         int as;
859         struct sockaddr_in sin;
860         int sinlen;
861         struct mansession *s;
862         struct protoent *p;
863         int arg = 1;
864         int flags;
865         pthread_attr_t attr;
866
867         pthread_attr_init(&attr);
868         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
869
870         for (;;) {
871                 sinlen = sizeof(sin);
872                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
873                 if (as < 0) {
874                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
875                         continue;
876                 }
877                 p = getprotobyname("tcp");
878                 if( p ) {
879                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
880                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
881                         }
882                 }
883                 s = malloc(sizeof(struct mansession));
884                 if (!s) {
885                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
886                         continue;
887                 } 
888                 memset(s, 0, sizeof(struct mansession));
889                 memcpy(&s->sin, &sin, sizeof(sin));
890
891                 if(! block_sockets) {
892                         /* For safety, make sure socket is non-blocking */
893                         flags = fcntl(as, F_GETFL);
894                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
895                 }
896                 ast_mutex_init(&s->lock);
897                 s->fd = as;
898                 s->send_events = 1;
899                 ast_mutex_lock(&sessionlock);
900                 s->next = sessions;
901                 sessions = s;
902                 ast_mutex_unlock(&sessionlock);
903                 if (pthread_create(&t, &attr, session_do, s))
904                         destroy_session(s);
905         }
906         pthread_attr_destroy(&attr);
907         return NULL;
908 }
909
910 int manager_event(int category, char *event, char *fmt, ...)
911 {
912         struct mansession *s;
913         char tmp[4096];
914         va_list ap;
915
916         ast_mutex_lock(&sessionlock);
917         s = sessions;
918         while(s) {
919                 if (((s->readperm & category) == category) && s->send_events) {
920                         ast_mutex_lock(&s->lock);
921                         if (!s->blocking) {
922                                 ast_cli(s->fd, "Event: %s\r\n", event);
923                                 va_start(ap, fmt);
924                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
925                                 va_end(ap);
926                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
927                                 ast_cli(s->fd, "\r\n");
928                         }
929                         ast_mutex_unlock(&s->lock);
930                 }
931                 s = s->next;
932         }
933         ast_mutex_unlock(&sessionlock);
934         return 0;
935 }
936
937 int ast_manager_unregister( char *action ) {
938         struct manager_action *cur = first_action, *prev = first_action;
939
940         ast_mutex_lock(&actionlock);
941         while( cur ) {          
942                 if (!strcasecmp(action, cur->action)) {
943                         prev->next = cur->next;
944                         free(cur);
945                         if (option_verbose > 1) 
946                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
947                         ast_mutex_unlock(&actionlock);
948                         return 0;
949                 }
950                 prev = cur;
951                 cur = cur->next;
952         }
953         ast_mutex_unlock(&actionlock);
954         return 0;
955 }
956
957 static int manager_state_cb(char *context, char *exten, int state, void *data)
958 {
959         /* Notify managers of change */
960         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
961         return 0;
962 }
963
964 int ast_manager_register( char *action, int auth, 
965         int (*func)(struct mansession *s, struct message *m), char *synopsis)
966 {
967         struct manager_action *cur = first_action, *prev = NULL;
968
969         ast_mutex_lock(&actionlock);
970         while(cur) { /* Walk the list of actions */
971                 if (!strcasecmp(cur->action, action)) {
972                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", action);
973                         ast_mutex_unlock(&actionlock);
974                         return -1;
975                 }
976                 prev = cur; 
977                 cur = cur->next;
978         }
979         cur = malloc( sizeof(struct manager_action) );
980         if( !cur ) {
981                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
982                 ast_mutex_unlock(&actionlock);
983                 return -1;
984         }
985         strncpy( cur->action, action, 255 );
986         cur->authority = auth;
987         cur->func = func;
988         cur->synopsis = synopsis;
989         cur->next = NULL;
990
991         if( prev ) prev->next = cur;
992         else first_action = cur;
993
994         if (option_verbose > 1) 
995                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
996         ast_mutex_unlock(&actionlock);
997         return 0;
998 }
999
1000 static int registered = 0;
1001
1002 int init_manager(void)
1003 {
1004         struct ast_config *cfg;
1005         char *val;
1006         int oldportno = portno;
1007         static struct sockaddr_in ba;
1008         int x = 1;
1009         if (!registered) {
1010                 /* Register default actions */
1011                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
1012                 ast_manager_register( "Events", 0, action_events, "Contol Event Flow" );
1013                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
1014                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
1015                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
1016                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
1017                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
1018                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
1019                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
1020                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
1021                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
1022                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
1023
1024                 ast_cli_register(&show_mancmds_cli);
1025                 ast_cli_register(&show_manconn_cli);
1026                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1027                 registered = 1;
1028         }
1029         portno = DEFAULT_MANAGER_PORT;
1030         cfg = ast_load("manager.conf");
1031         if (!cfg) {
1032                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1033                 return 0;
1034         }
1035         memset(&ba, 0, sizeof(ba));
1036         val = ast_variable_retrieve(cfg, "general", "enabled");
1037         if (val)
1038                 enabled = ast_true(val);
1039
1040         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1041         if(val)
1042                 block_sockets = ast_true(val);
1043
1044         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1045                 if (sscanf(val, "%d", &portno) != 1) {
1046                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1047                         portno = DEFAULT_MANAGER_PORT;
1048                 }
1049         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1050                 if (sscanf(val, "%d", &portno) != 1) {
1051                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1052                         portno = DEFAULT_MANAGER_PORT;
1053                 }
1054                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1055         }
1056         
1057         ba.sin_family = AF_INET;
1058         ba.sin_port = htons(portno);
1059         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1060         
1061         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1062                 if (!inet_aton(val, &ba.sin_addr)) { 
1063                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1064                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1065                 }
1066         }
1067         
1068         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1069 #if 0
1070                 /* Can't be done yet */
1071                 close(asock);
1072                 asock = -1;
1073 #else
1074                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1075 #endif
1076         }
1077         ast_destroy(cfg);
1078         
1079         /* If not enabled, do nothing */
1080         if (!enabled) {
1081                 return 0;
1082         }
1083         if (asock < 0) {
1084                 asock = socket(AF_INET, SOCK_STREAM, 0);
1085                 if (asock < 0) {
1086                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1087                         return -1;
1088                 }
1089                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1090                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1091                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1092                         close(asock);
1093                         asock = -1;
1094                         return -1;
1095                 }
1096                 if (listen(asock, 2)) {
1097                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1098                         close(asock);
1099                         asock = -1;
1100                         return -1;
1101                 }
1102                 if (option_verbose)
1103                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1104                 pthread_create(&t, NULL, accept_thread, NULL);
1105         }
1106         return 0;
1107 }
1108
1109 int reload_manager(void)
1110 {
1111         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1112         return init_manager();
1113 }