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