Merge fabeman's extensive meetme improvements (bug #1624)
[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_locked(NULL);
380         while(c) {
381                 if (!strcasecmp(c->name, name)) {
382                         break;
383                 }
384                 ast_mutex_unlock(&c->lock);
385                 c = ast_channel_walk_locked(c);
386         }
387         if (!c) {
388                 astman_send_error(s, m, "No such channel");
389                 return 0;
390         }
391         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
392         ast_mutex_unlock(&c->lock);
393         astman_send_ack(s, m, "Channel Hungup");
394         return 0;
395 }
396
397 static int action_status(struct mansession *s, struct message *m)
398 {
399         char *id = astman_get_header(m,"ActionID");
400         char idText[256] = "";
401         struct ast_channel *c;
402         char bridge[256];
403         astman_send_ack(s, m, "Channel status will follow");
404         c = ast_channel_walk_locked(NULL);
405         if (id && strlen(id))
406                 snprintf(idText,256,"ActionID: %s\r\n",id);
407         while(c) {
408                 if (c->bridge)
409                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
410                 else
411                         strcpy(bridge, "");
412                 if (c->pbx) {
413                         ast_cli(s->fd,
414                         "Event: Status\r\n"
415                         "Channel: %s\r\n"
416                         "CallerID: %s\r\n"
417                         "State: %s\r\n"
418                         "Context: %s\r\n"
419                         "Extension: %s\r\n"
420                         "Priority: %d\r\n"
421                         "%s"
422                         "Uniqueid: %s\r\n"
423                         "%s"
424                         "\r\n",
425                         c->name, c->callerid ? c->callerid : "<unknown>", 
426                         ast_state2str(c->_state), c->context,
427                         c->exten, c->priority, bridge, c->uniqueid, idText);
428                 } else {
429                         ast_cli(s->fd,
430                         "Event: Status\r\n"
431                         "Channel: %s\r\n"
432                         "CallerID: %s\r\n"
433                         "State: %s\r\n"
434                         "%s"
435                         "Uniqueid: %s\r\n"
436                         "%s"
437                         "\r\n",
438                         c->name, c->callerid ? c->callerid : "<unknown>", 
439                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
440                 }
441                 ast_mutex_unlock(&c->lock);
442                 c = ast_channel_walk_locked(c);
443         }
444         ast_cli(s->fd,
445         "Event: StatusComplete\r\n"
446         "%s"
447         "\r\n",idText);
448         return 0;
449 }
450
451 static int action_redirect(struct mansession *s, struct message *m)
452 {
453         char *name = astman_get_header(m, "Channel");
454         char *name2 = astman_get_header(m, "ExtraChannel");
455         char *exten = astman_get_header(m, "Exten");
456         char *context = astman_get_header(m, "Context");
457         char *priority = astman_get_header(m, "Priority");
458         struct ast_channel *chan, *chan2 = NULL;
459         int pi = 0;
460         int res;
461         if (!name || !strlen(name)) {
462                 astman_send_error(s, m, "Channel not specified");
463                 return 0;
464         }
465         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
466                 astman_send_error(s, m, "Invalid priority\n");
467                 return 0;
468         }
469         chan = ast_get_channel_by_name_locked(name);
470         if (strlen(name2))
471                 chan2 = ast_get_channel_by_name_locked(name2);
472         res = ast_async_goto(chan, context, exten, pi);
473         if (!res) {
474                 if (strlen(name2)) {
475                         if (chan2)
476                                 res = ast_async_goto(chan2, context, exten, pi);
477                         else
478                                 res = -1;
479                         if (!res)
480                                 astman_send_ack(s, m, "Dual Redirect successful");
481                         else
482                                 astman_send_error(s, m, "Secondary redirect failed");
483                 } else
484                         astman_send_ack(s, m, "Redirect successful");
485         } else
486                 astman_send_error(s, m, "Redirect failed");
487         if (chan)
488                 ast_mutex_unlock(&chan->lock);
489         if (chan2)
490                 ast_mutex_unlock(&chan2->lock);
491         return 0;
492 }
493
494 static int action_command(struct mansession *s, struct message *m)
495 {
496         char *cmd = astman_get_header(m, "Command");
497         char *id = astman_get_header(m, "ActionID");
498         ast_mutex_lock(&s->lock);
499         s->blocking = 1;
500         ast_mutex_unlock(&s->lock);
501         ast_cli(s->fd, "Response: Follows\r\n");
502         if (id && strlen(id))
503                 ast_cli(s->fd, "ActionID: %s\r\n", id);
504         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
505         ast_cli_command(s->fd, cmd);
506         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
507         ast_mutex_lock(&s->lock);
508         s->blocking = 0;
509         ast_mutex_unlock(&s->lock);
510         return 0;
511 }
512
513 static void *fast_originate(void *data)
514 {
515         struct fast_originate_helper *in = data;
516         int res;
517         int reason = 0;
518         if (strlen(in->app)) {
519                 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);
520         } else {
521                 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);
522         }   
523         free(in);
524         return NULL;
525 }
526
527 static int action_originate(struct mansession *s, struct message *m)
528 {
529         char *name = astman_get_header(m, "Channel");
530         char *exten = astman_get_header(m, "Exten");
531         char *context = astman_get_header(m, "Context");
532         char *priority = astman_get_header(m, "Priority");
533         char *timeout = astman_get_header(m, "Timeout");
534         char *callerid = astman_get_header(m, "CallerID");
535         char *variable = astman_get_header(m, "Variable");
536         char *account = astman_get_header(m, "Account");
537         char *app = astman_get_header(m, "Application");
538         char *appdata = astman_get_header(m, "Data");
539         char *async = astman_get_header(m, "Async");
540         char *tech, *data;
541         int pi = 0;
542         int res;
543         int to = 30000;
544         int reason = 0;
545         char tmp[256];
546         pthread_t th;
547         pthread_attr_t attr;
548         if (!name) {
549                 astman_send_error(s, m, "Channel not specified");
550                 return 0;
551         }
552         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
553                 astman_send_error(s, m, "Invalid priority\n");
554                 return 0;
555         }
556         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
557                 astman_send_error(s, m, "Invalid timeout\n");
558                 return 0;
559         }
560         strncpy(tmp, name, sizeof(tmp) - 1);
561         tech = tmp;
562         data = strchr(tmp, '/');
563         if (!data) {
564                 astman_send_error(s, m, "Invalid channel\n");
565                 return 0;
566         }
567         *data = '\0';
568         data++;
569         if (ast_true(async))
570         {
571                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
572                 if (!fast)
573                 {
574                         res = -1;
575                 }
576                 else
577                 {
578                         memset(fast, 0, sizeof(struct fast_originate_helper));
579                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
580                         strncpy(fast->data, data, sizeof(fast->data) - 1);
581                         strncpy(fast->app, app, sizeof(fast->app) - 1);
582                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
583                         strncpy(fast->callerid, callerid, sizeof(fast->callerid) - 1);
584                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
585                         strncpy(fast->account, account, sizeof(fast->account) - 1);
586                         strncpy(fast->context, context, sizeof(fast->context) - 1);
587                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
588                         fast->timeout = to;
589                         fast->priority = pi;
590                         pthread_attr_init(&attr);
591                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
592                         if (pthread_create(&th, &attr, fast_originate, fast))
593                         {
594                                 res = -1;
595                         }
596                         else
597                         {
598                                 res = 0;
599                         }
600                 }
601         } else if (strlen(app)) {
602                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
603         } else {
604                 if (exten && context && pi)
605                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
606                 else {
607                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
608                         return 0;
609                 }
610         }   
611         if (!res)
612                 astman_send_ack(s, m, "Originate successfully queued");
613         else
614                 astman_send_error(s, m, "Originate failed");
615         return 0;
616 }
617
618 static int action_mailboxstatus(struct mansession *s, struct message *m)
619 {
620         char *mailbox = astman_get_header(m, "Mailbox");
621         char *id = astman_get_header(m,"ActionID");
622         char idText[256] = "";
623         if (!mailbox || !strlen(mailbox)) {
624                 astman_send_error(s, m, "Mailbox not specified");
625                 return 0;
626         }
627         if (id && strlen(id))
628                 snprintf(idText,256,"ActionID: %s\r\n",id);
629         ast_cli(s->fd, "Response: Success\r\n"
630                                    "%s"
631                                    "Message: Mailbox Status\r\n"
632                                    "Mailbox: %s\r\n"
633                                    "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
634         return 0;
635 }
636
637 static int action_mailboxcount(struct mansession *s, struct message *m)
638 {
639         char *mailbox = astman_get_header(m, "Mailbox");
640         char *id = astman_get_header(m,"ActionID");
641         char idText[256] = "";
642         int newmsgs = 0, oldmsgs = 0;
643         if (!mailbox || !strlen(mailbox)) {
644                 astman_send_error(s, m, "Mailbox not specified");
645                 return 0;
646         }
647         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
648         if (id && strlen(id)) {
649                 snprintf(idText,256,"ActionID: %s\r\n",id);
650         }
651         ast_cli(s->fd, "Response: Success\r\n"
652                                    "%s"
653                                    "Message: Mailbox Message Count\r\n"
654                                    "Mailbox: %s\r\n"
655                                    "NewMessages: %d\r\n"
656                                    "OldMessages: %d\r\n" 
657                                    "\r\n",
658                                     idText,mailbox, newmsgs, oldmsgs);
659         return 0;
660 }
661
662 static int action_extensionstate(struct mansession *s, struct message *m)
663 {
664         char *exten = astman_get_header(m, "Exten");
665         char *context = astman_get_header(m, "Context");
666         char *id = astman_get_header(m,"ActionID");
667         char idText[256] = "";
668         char hint[256] = "";
669         int status;
670         if (!exten || !strlen(exten)) {
671                 astman_send_error(s, m, "Extension not specified");
672                 return 0;
673         }
674         if (!context || !strlen(context))
675                 context = "default";
676         status = ast_extension_state(NULL, context, exten);
677         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
678         if (id && strlen(id)) {
679                 snprintf(idText,256,"ActionID: %s\r\n",id);
680         }
681         ast_cli(s->fd, "Response: Success\r\n"
682                                    "%s"
683                                    "Message: Extension Status\r\n"
684                                    "Exten: %s\r\n"
685                                    "Context: %s\r\n"
686                                    "Hint: %s\r\n"
687                                    "Status: %d\r\n\r\n",
688                                    idText,exten, context, hint, status);
689         return 0;
690 }
691
692 static int action_timeout(struct mansession *s, struct message *m)
693 {
694         struct ast_channel *c = NULL;
695         char *name = astman_get_header(m, "Channel");
696         int timeout = atoi(astman_get_header(m, "Timeout"));
697         if (!strlen(name)) {
698                 astman_send_error(s, m, "No channel specified");
699                 return 0;
700         }
701         if (!timeout) {
702                 astman_send_error(s, m, "No timeout specified");
703                 return 0;
704         }
705         c = ast_channel_walk_locked(NULL);
706         while(c) {
707                 if (!strcasecmp(c->name, name)) {
708                         break;
709                 }
710                 ast_mutex_unlock(&c->lock);
711                 c = ast_channel_walk_locked(c);
712         }
713         if (!c) {
714                 astman_send_error(s, m, "No such channel");
715                 return 0;
716         }
717         ast_channel_setwhentohangup(c, timeout);
718         ast_mutex_unlock(&c->lock);
719         astman_send_ack(s, m, "Timeout Set");
720         return 0;
721 }
722
723 static int process_message(struct mansession *s, struct message *m)
724 {
725         char action[80];
726         struct manager_action *tmp = first_action;
727         char *id = astman_get_header(m,"ActionID");
728         char idText[256] = "";
729
730         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
731         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
732
733         if (!strlen(action)) {
734                 astman_send_error(s, m, "Missing action in request");
735                 return 0;
736         }
737         if (id && strlen(id)) {
738                 snprintf(idText,256,"ActionID: %s\r\n",id);
739         }
740         if (!s->authenticated) {
741                 if (!strcasecmp(action, "Challenge")) {
742                         char *authtype;
743                         authtype = astman_get_header(m, "AuthType");
744                         if (!strcasecmp(authtype, "MD5")) {
745                                 if (!s->challenge || !strlen(s->challenge)) {
746                                         ast_mutex_lock(&s->lock);
747                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
748                                         ast_mutex_unlock(&s->lock);
749                                 }
750                                 ast_cli(s->fd, "Response: Success\r\n"
751                                                 "%s"
752                                                 "Challenge: %s\r\n\r\n",
753                                                 idText,s->challenge);
754                                 return 0;
755                         } else {
756                                 astman_send_error(s, m, "Must specify AuthType");
757                                 return 0;
758                         }
759                 } else if (!strcasecmp(action, "Login")) {
760                         if (authenticate(s, m)) {
761                                 sleep(1);
762                                 astman_send_error(s, m, "Authentication failed");
763                                 return -1;
764                         } else {
765                                 s->authenticated = 1;
766                                 if (option_verbose > 1) 
767                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
768                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
769                                 astman_send_ack(s, m, "Authentication accepted");
770                         }
771                 } else if (!strcasecmp(action, "Logoff")) {
772                         astman_send_ack(s, m, "See ya");
773                         return -1;
774                 } else
775                         astman_send_error(s, m, "Authentication Required");
776         } else {
777                 while( tmp ) {          
778                         if (!strcasecmp(action, tmp->action)) {
779                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
780                                         if (tmp->func(s, m))
781                                                 return -1;
782                                 } else {
783                                         astman_send_error(s, m, "Permission denied");
784                                 }
785                                 return 0;
786                         }
787                         tmp = tmp->next;
788                 }
789                 astman_send_error(s, m, "Invalid/unknown command");
790         }
791         return 0;
792 }
793
794 static int get_input(struct mansession *s, char *output)
795 {
796         /* output must have at least sizeof(s->inbuf) space */
797         int res;
798         int x;
799         struct pollfd fds[1];
800         for (x=1;x<s->inlen;x++) {
801                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
802                         /* Copy output data up to and including \r\n */
803                         memcpy(output, s->inbuf, x + 1);
804                         /* Add trailing \0 */
805                         output[x+1] = '\0';
806                         /* Move remaining data back to the front */
807                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
808                         s->inlen -= (x + 1);
809                         return 1;
810                 }
811         } 
812         if (s->inlen >= sizeof(s->inbuf) - 1) {
813                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
814                 s->inlen = 0;
815         }
816         fds[0].fd = s->fd;
817         fds[0].events = POLLIN;
818         res = poll(fds, 1, -1);
819         if (res < 0) {
820                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
821         } else if (res > 0) {
822                 ast_mutex_lock(&s->lock);
823                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
824                 ast_mutex_unlock(&s->lock);
825                 if (res < 1)
826                         return -1;
827         }
828         s->inlen += res;
829         s->inbuf[s->inlen] = '\0';
830         return 0;
831 }
832
833 static void *session_do(void *data)
834 {
835         struct mansession *s = data;
836         struct message m;
837         int res;
838         
839         ast_mutex_lock(&s->lock);
840         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
841         ast_mutex_unlock(&s->lock);
842         memset(&m, 0, sizeof(&m));
843         for (;;) {
844                 res = get_input(s, m.headers[m.hdrcount]);
845                 if (res > 0) {
846                         /* Strip trailing \r\n */
847                         if (strlen(m.headers[m.hdrcount]) < 2)
848                                 continue;
849                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
850                         if (!strlen(m.headers[m.hdrcount])) {
851                                 if (process_message(s, &m))
852                                         break;
853                                 memset(&m, 0, sizeof(&m));
854                         } else if (m.hdrcount < MAX_HEADERS - 1)
855                                 m.hdrcount++;
856                 } else if (res < 0)
857                         break;
858         }
859         if (s->authenticated) {
860                 if (option_verbose > 1) 
861                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
862                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
863         } else {
864                 if (option_verbose > 1)
865                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
866                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
867         }
868         destroy_session(s);
869         return NULL;
870 }
871
872 static void *accept_thread(void *ignore)
873 {
874         int as;
875         struct sockaddr_in sin;
876         int sinlen;
877         struct mansession *s;
878         struct protoent *p;
879         int arg = 1;
880         int flags;
881         pthread_attr_t attr;
882
883         pthread_attr_init(&attr);
884         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
885
886         for (;;) {
887                 sinlen = sizeof(sin);
888                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
889                 if (as < 0) {
890                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
891                         continue;
892                 }
893                 p = getprotobyname("tcp");
894                 if( p ) {
895                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
896                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
897                         }
898                 }
899                 s = malloc(sizeof(struct mansession));
900                 if (!s) {
901                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
902                         continue;
903                 } 
904                 memset(s, 0, sizeof(struct mansession));
905                 memcpy(&s->sin, &sin, sizeof(sin));
906
907                 if(! block_sockets) {
908                         /* For safety, make sure socket is non-blocking */
909                         flags = fcntl(as, F_GETFL);
910                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
911                 }
912                 ast_mutex_init(&s->lock);
913                 s->fd = as;
914                 s->send_events = 1;
915                 ast_mutex_lock(&sessionlock);
916                 s->next = sessions;
917                 sessions = s;
918                 ast_mutex_unlock(&sessionlock);
919                 if (pthread_create(&t, &attr, session_do, s))
920                         destroy_session(s);
921         }
922         pthread_attr_destroy(&attr);
923         return NULL;
924 }
925
926 int manager_event(int category, char *event, char *fmt, ...)
927 {
928         struct mansession *s;
929         char tmp[4096];
930         va_list ap;
931
932         ast_mutex_lock(&sessionlock);
933         s = sessions;
934         while(s) {
935                 if (((s->readperm & category) == category) && s->send_events) {
936                         ast_mutex_lock(&s->lock);
937                         if (!s->blocking) {
938                                 ast_cli(s->fd, "Event: %s\r\n", event);
939                                 va_start(ap, fmt);
940                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
941                                 va_end(ap);
942                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
943                                 ast_cli(s->fd, "\r\n");
944                         }
945                         ast_mutex_unlock(&s->lock);
946                 }
947                 s = s->next;
948         }
949         ast_mutex_unlock(&sessionlock);
950         return 0;
951 }
952
953 int ast_manager_unregister( char *action ) {
954         struct manager_action *cur = first_action, *prev = first_action;
955
956         ast_mutex_lock(&actionlock);
957         while( cur ) {          
958                 if (!strcasecmp(action, cur->action)) {
959                         prev->next = cur->next;
960                         free(cur);
961                         if (option_verbose > 1) 
962                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
963                         ast_mutex_unlock(&actionlock);
964                         return 0;
965                 }
966                 prev = cur;
967                 cur = cur->next;
968         }
969         ast_mutex_unlock(&actionlock);
970         return 0;
971 }
972
973 static int manager_state_cb(char *context, char *exten, int state, void *data)
974 {
975         /* Notify managers of change */
976         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
977         return 0;
978 }
979
980 int ast_manager_register( char *action, int auth, 
981         int (*func)(struct mansession *s, struct message *m), char *synopsis)
982 {
983         struct manager_action *cur = first_action, *prev = NULL;
984
985         ast_mutex_lock(&actionlock);
986         while(cur) { /* Walk the list of actions */
987                 if (!strcasecmp(cur->action, action)) {
988                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", action);
989                         ast_mutex_unlock(&actionlock);
990                         return -1;
991                 }
992                 prev = cur; 
993                 cur = cur->next;
994         }
995         cur = malloc( sizeof(struct manager_action) );
996         if( !cur ) {
997                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
998                 ast_mutex_unlock(&actionlock);
999                 return -1;
1000         }
1001         strncpy( cur->action, action, 255 );
1002         cur->authority = auth;
1003         cur->func = func;
1004         cur->synopsis = synopsis;
1005         cur->next = NULL;
1006
1007         if( prev ) prev->next = cur;
1008         else first_action = cur;
1009
1010         if (option_verbose > 1) 
1011                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
1012         ast_mutex_unlock(&actionlock);
1013         return 0;
1014 }
1015
1016 static int registered = 0;
1017
1018 int init_manager(void)
1019 {
1020         struct ast_config *cfg;
1021         char *val;
1022         int oldportno = portno;
1023         static struct sockaddr_in ba;
1024         int x = 1;
1025         if (!registered) {
1026                 /* Register default actions */
1027                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
1028                 ast_manager_register( "Events", 0, action_events, "Contol Event Flow" );
1029                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
1030                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
1031                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
1032                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
1033                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
1034                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
1035                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
1036                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
1037                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
1038                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
1039
1040                 ast_cli_register(&show_mancmds_cli);
1041                 ast_cli_register(&show_manconn_cli);
1042                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1043                 registered = 1;
1044         }
1045         portno = DEFAULT_MANAGER_PORT;
1046         cfg = ast_load("manager.conf");
1047         if (!cfg) {
1048                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1049                 return 0;
1050         }
1051         memset(&ba, 0, sizeof(ba));
1052         val = ast_variable_retrieve(cfg, "general", "enabled");
1053         if (val)
1054                 enabled = ast_true(val);
1055
1056         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1057         if(val)
1058                 block_sockets = ast_true(val);
1059
1060         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1061                 if (sscanf(val, "%d", &portno) != 1) {
1062                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1063                         portno = DEFAULT_MANAGER_PORT;
1064                 }
1065         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1066                 if (sscanf(val, "%d", &portno) != 1) {
1067                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1068                         portno = DEFAULT_MANAGER_PORT;
1069                 }
1070                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1071         }
1072         
1073         ba.sin_family = AF_INET;
1074         ba.sin_port = htons(portno);
1075         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1076         
1077         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1078                 if (!inet_aton(val, &ba.sin_addr)) { 
1079                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1080                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1081                 }
1082         }
1083         
1084         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1085 #if 0
1086                 /* Can't be done yet */
1087                 close(asock);
1088                 asock = -1;
1089 #else
1090                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1091 #endif
1092         }
1093         ast_destroy(cfg);
1094         
1095         /* If not enabled, do nothing */
1096         if (!enabled) {
1097                 return 0;
1098         }
1099         if (asock < 0) {
1100                 asock = socket(AF_INET, SOCK_STREAM, 0);
1101                 if (asock < 0) {
1102                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1103                         return -1;
1104                 }
1105                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1106                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1107                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1108                         close(asock);
1109                         asock = -1;
1110                         return -1;
1111                 }
1112                 if (listen(asock, 2)) {
1113                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1114                         close(asock);
1115                         asock = -1;
1116                         return -1;
1117                 }
1118                 if (option_verbose)
1119                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1120                 pthread_create(&t, NULL, accept_thread, NULL);
1121         }
1122         return 0;
1123 }
1124
1125 int reload_manager(void)
1126 {
1127         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1128         return init_manager();
1129 }