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