eb4d22937dcfe5cb76dab27b8f7bc58c4ac5198f
[asterisk/asterisk.git] / manager.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * The Asterisk Management Interface - AMI
5  *
6  * Channel Management and more
7  * 
8  * Copyright (C) 1999 - 2005, Digium, Inc.
9  *
10  * Mark Spencer <markster@digium.com>
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License
14  */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <netdb.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
25 #include <arpa/inet.h>
26 #include <signal.h>
27 #include <errno.h>
28 #include <unistd.h>
29
30 #include "asterisk/channel.h"
31 #include "asterisk/file.h"
32 #include "asterisk/manager.h"
33 #include "asterisk/config.h"
34 #include "asterisk/callerid.h"
35 #include "asterisk/lock.h"
36 #include "asterisk/logger.h"
37 #include "asterisk/options.h"
38 #include "asterisk/cli.h"
39 #include "asterisk/app.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/md5.h"
42 #include "asterisk/acl.h"
43 #include "asterisk/utils.h"
44
45 struct fast_originate_helper
46 {
47         char tech[256];
48         char data[256];
49         int timeout;
50         char app[256];
51         char appdata[256];
52         char cid_name[256];
53         char cid_num[256];
54         char variable[256];
55         char account[256];
56         char context[256];
57         char exten[256];
58         char idtext[256];
59         int priority;
60 };
61
62 static int enabled = 0;
63 static int portno = DEFAULT_MANAGER_PORT;
64 static int asock = -1;
65 static int displayconnects = 1;
66
67 static pthread_t t;
68 AST_MUTEX_DEFINE_STATIC(sessionlock);
69 static int block_sockets = 0;
70
71 static struct permalias {
72         int num;
73         char *label;
74 } perms[] = {
75         { EVENT_FLAG_SYSTEM, "system" },
76         { EVENT_FLAG_CALL, "call" },
77         { EVENT_FLAG_LOG, "log" },
78         { EVENT_FLAG_VERBOSE, "verbose" },
79         { EVENT_FLAG_COMMAND, "command" },
80         { EVENT_FLAG_AGENT, "agent" },
81         { EVENT_FLAG_USER, "user" },
82         { -1, "all" },
83         { 0, "none" },
84 };
85
86 static struct mansession *sessions = NULL;
87 static struct manager_action *first_action = NULL;
88 AST_MUTEX_DEFINE_STATIC(actionlock);
89
90 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
91 {
92         /* Try to write string, but wait no more than ms milliseconds
93            before timing out */
94         int res=0;
95         struct pollfd fds[1];
96         while(len) {
97                 res = write(fd, s, len);
98                 if ((res < 0) && (errno != EAGAIN)) {
99                         return -1;
100                 }
101                 if (res < 0) res = 0;
102                 len -= res;
103                 s += res;
104                 fds[0].fd = fd;
105                 fds[0].events = POLLOUT;
106                 /* Wait until writable again */
107                 res = poll(fds, 1, timeoutms);
108                 if (res < 1)
109                         return -1;
110         }
111         return res;
112 }
113
114 /*--- authority_to_str: Convert authority code to string with serveral options */
115 static char *authority_to_str(int authority, char *res, int reslen)
116 {
117         int running_total = 0, i;
118         memset(res, 0, reslen);
119         for (i=0; i<sizeof(perms) / sizeof(perms[0]) - 1; i++) {
120                 if (authority & perms[i].num) {
121                         if (*res) {
122                                 strncat(res, ",", (reslen > running_total) ? reslen - running_total : 0);
123                                 running_total++;
124                         }
125                         strncat(res, perms[i].label, (reslen > running_total) ? reslen - running_total : 0);
126                         running_total += strlen(perms[i].label);
127                 }
128         }
129         if (ast_strlen_zero(res)) {
130                 strncpy(res, "<none>", reslen);
131         }
132         return res;
133 }
134
135 static char *complete_show_mancmd(char *line, char *word, int pos, int state)
136 {
137         struct manager_action *cur = first_action;
138         int which = 0;
139
140         ast_mutex_lock(&actionlock);
141         while (cur) { /* Walk the list of actions */
142                 if (!strncasecmp(word, cur->action, strlen(word))) {
143                         if (++which > state) {
144                                 char *ret = strdup(cur->action);
145                                 ast_mutex_unlock(&actionlock);
146                                 return ret;
147                         }
148                 }
149                 cur = cur->next;
150         }
151         ast_mutex_unlock(&actionlock);
152         return NULL;
153 }
154
155 static int handle_showmancmd(int fd, int argc, char *argv[])
156 {
157         struct manager_action *cur = first_action;
158         char authority[80];
159         int num;
160
161         if (argc != 4)
162                 return RESULT_SHOWUSAGE;
163         ast_mutex_lock(&actionlock);
164         while (cur) { /* Walk the list of actions */
165                 for (num = 3; num < argc; num++) {
166                         if (!strcasecmp(cur->action, argv[num])) {
167                                 ast_cli(fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n", cur->action, cur->synopsis, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->description ? cur->description : "");
168                         }
169                 }
170                 cur = cur->next;
171         }
172
173         ast_mutex_unlock(&actionlock);
174         return RESULT_SUCCESS;
175 }
176
177 /*--- handle_showmancmds: CLI command */
178 /* Should change to "manager show commands" */
179 static int handle_showmancmds(int fd, int argc, char *argv[])
180 {
181         struct manager_action *cur = first_action;
182         char authority[80];
183         char *format = "  %-15.15s  %-15.15s  %-55.55s\n";
184
185         ast_mutex_lock(&actionlock);
186         ast_cli(fd, format, "Action", "Privilege", "Synopsis");
187         ast_cli(fd, format, "------", "---------", "--------");
188         while (cur) { /* Walk the list of actions */
189                 ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
190                 cur = cur->next;
191         }
192
193         ast_mutex_unlock(&actionlock);
194         return RESULT_SUCCESS;
195 }
196
197 /*--- handle_showmanconn: CLI command show manager connected */
198 /* Should change to "manager show connected" */
199 static int handle_showmanconn(int fd, int argc, char *argv[])
200 {
201         struct mansession *s;
202         char iabuf[INET_ADDRSTRLEN];
203         char *format = "  %-15.15s  %-15.15s\n";
204         ast_mutex_lock(&sessionlock);
205         s = sessions;
206         ast_cli(fd, format, "Username", "IP Address");
207         while (s) {
208                 ast_cli(fd, format,s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
209                 s = s->next;
210         }
211
212         ast_mutex_unlock(&sessionlock);
213         return RESULT_SUCCESS;
214 }
215
216 static char showmancmd_help[] = 
217 "Usage: show manager command <actionname>\n"
218 "       Shows the detailed description for a specific Asterisk manager interface command.\n";
219
220 static char showmancmds_help[] = 
221 "Usage: show manager commands\n"
222 "       Prints a listing of all the available Asterisk manager interface commands.\n";
223
224 static char showmanconn_help[] = 
225 "Usage: show manager connected\n"
226 "       Prints a listing of the users that are currently connected to the\n"
227 "Asterisk manager interface.\n";
228
229 static struct ast_cli_entry show_mancmd_cli =
230         { { "show", "manager", "command", NULL },
231         handle_showmancmd, "Show a manager interface command", showmancmd_help, complete_show_mancmd };
232
233 static struct ast_cli_entry show_mancmds_cli =
234         { { "show", "manager", "commands", NULL },
235         handle_showmancmds, "List manager interface commands", showmancmds_help };
236
237 static struct ast_cli_entry show_manconn_cli =
238         { { "show", "manager", "connected", NULL },
239         handle_showmanconn, "Show connected manager interface users", showmanconn_help };
240
241 static void destroy_session(struct mansession *s)
242 {
243         struct mansession *cur, *prev = NULL;
244         ast_mutex_lock(&sessionlock);
245         cur = sessions;
246         while(cur) {
247                 if (cur == s)
248                         break;
249                 prev = cur;
250                 cur = cur->next;
251         }
252         if (cur) {
253                 if (prev)
254                         prev->next = cur->next;
255                 else
256                         sessions = cur->next;
257                 if (s->fd > -1)
258                         close(s->fd);
259                 ast_mutex_destroy(&s->lock);
260                 free(s);
261         } else
262                 ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
263         ast_mutex_unlock(&sessionlock);
264         
265 }
266
267 char *astman_get_header(struct message *m, char *var)
268 {
269         char cmp[80];
270         int x;
271         snprintf(cmp, sizeof(cmp), "%s: ", var);
272         for (x=0;x<m->hdrcount;x++)
273                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
274                         return m->headers[x] + strlen(cmp);
275         return "";
276 }
277
278 void astman_send_error(struct mansession *s, struct message *m, char *error)
279 {
280         char *id = astman_get_header(m,"ActionID");
281         ast_mutex_lock(&s->lock);
282         ast_cli(s->fd, "Response: Error\r\n");
283         if (id && !ast_strlen_zero(id))
284                 ast_cli(s->fd, "ActionID: %s\r\n",id);
285         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
286         ast_mutex_unlock(&s->lock);
287 }
288
289 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
290 {
291         char *id = astman_get_header(m,"ActionID");
292         ast_mutex_lock(&s->lock);
293         ast_cli(s->fd, "Response: %s\r\n", resp);
294         if (id && !ast_strlen_zero(id))
295                 ast_cli(s->fd, "ActionID: %s\r\n",id);
296         if (msg)
297                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
298         else
299                 ast_cli(s->fd, "\r\n");
300         ast_mutex_unlock(&s->lock);
301 }
302
303 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
304 {
305         astman_send_response(s, m, "Success", msg);
306 }
307
308 /* Tells you if smallstr exists inside bigstr
309    which is delim by delim and uses no buf or stringsep
310    ast_instring("this|that|more","this",',') == 1;
311
312    feel free to move this to app.c -anthm */
313 static int ast_instring(char *bigstr, char *smallstr, char delim) 
314 {
315         char *val = bigstr, *next;
316
317         do {
318                 if ((next = strchr(val, delim))) {
319                         if (!strncmp(val, smallstr, (next - val)))
320                                 return 1;
321                         else
322                                 continue;
323                 } else
324                         return !strcmp(smallstr, val);
325
326         } while (*(val = (next + 1)));
327
328         return 0;
329 }
330
331 static int get_perm(char *instr)
332 {
333         int x = 0, ret = 0;
334
335         if (!instr)
336                 return 0;
337
338         for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
339                 if (ast_instring(instr, perms[x].label, ','))
340                         ret |= perms[x].num;
341         
342         return ret;
343 }
344
345 static int ast_is_number(char *string) 
346 {
347         int ret = 1, x = 0;
348
349         if (!string)
350                 return 0;
351
352         for (x=0; x < strlen(string); x++) {
353                 if (!(string[x] >= 48 && string[x] <= 57)) {
354                         ret = 0;
355                         break;
356                 }
357         }
358         
359         return ret ? atoi(string) : 0;
360 }
361
362 static int ast_strings_to_mask(char *string) 
363 {
364         int x = 0, ret = -1;
365         
366         x = ast_is_number(string);
367
368         if (x) 
369                 ret = x;
370         else if (!string || ast_strlen_zero(string))
371                 ret = -1;
372         else if (!strcasecmp(string, "off") || ast_false(string))
373                 ret = 0;
374         else if (!strcasecmp(string, "on") || ast_true(string))
375                 ret = -1;
376         else {
377                 ret = 0;
378                 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
379                         if (ast_instring(string, perms[x].label, ',')) 
380                                 ret |= perms[x].num;            
381                 }
382         }
383
384         return ret;
385 }
386
387 /* 
388    Rather than braindead on,off this now can also accept a specific int mask value 
389    or a ',' delim list of mask strings (the same as manager.conf) -anthm
390 */
391
392 static int set_eventmask(struct mansession *s, char *eventmask)
393 {
394         int maskint = ast_strings_to_mask(eventmask);
395
396         ast_mutex_lock(&s->lock);
397         s->send_events = maskint;
398         ast_mutex_unlock(&s->lock);
399         
400         return s->send_events;
401 }
402
403 static int authenticate(struct mansession *s, struct message *m)
404 {
405         struct ast_config *cfg;
406         char iabuf[INET_ADDRSTRLEN];
407         char *cat;
408         char *user = astman_get_header(m, "Username");
409         char *pass = astman_get_header(m, "Secret");
410         char *authtype = astman_get_header(m, "AuthType");
411         char *key = astman_get_header(m, "Key");
412         char *events = astman_get_header(m, "Events");
413         
414         cfg = ast_config_load("manager.conf");
415         if (!cfg)
416                 return -1;
417         cat = ast_category_browse(cfg, NULL);
418         while(cat) {
419                 if (strcasecmp(cat, "general")) {
420                         /* This is a user */
421                         if (!strcasecmp(cat, user)) {
422                                 struct ast_variable *v;
423                                 struct ast_ha *ha = NULL;
424                                 char *password = NULL;
425                                 v = ast_variable_browse(cfg, cat);
426                                 while (v) {
427                                         if (!strcasecmp(v->name, "secret")) {
428                                                 password = v->value;
429                                         } else if (!strcasecmp(v->name, "permit") ||
430                                                    !strcasecmp(v->name, "deny")) {
431                                                 ha = ast_append_ha(v->name, v->value, ha);
432                                         }       
433                                                 
434                                         v = v->next;
435                                 }
436                                 if (ha && !ast_apply_ha(ha, &(s->sin))) {
437                                         ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
438                                         ast_free_ha(ha);
439                                         ast_config_destroy(cfg);
440                                         return -1;
441                                 } else if (ha)
442                                         ast_free_ha(ha);
443                                 if (!strcasecmp(authtype, "MD5")) {
444                                         if (key && !ast_strlen_zero(key) && s->challenge) {
445                                                 int x;
446                                                 int len=0;
447                                                 char md5key[256] = "";
448                                                 struct MD5Context md5;
449                                                 unsigned char digest[16];
450                                                 MD5Init(&md5);
451                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
452                                                 MD5Update(&md5, password, strlen(password));
453                                                 MD5Final(digest, &md5);
454                                                 for (x=0;x<16;x++)
455                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
456                                                 if (!strcmp(md5key, key))
457                                                         break;
458                                                 else {
459                                                         ast_config_destroy(cfg);
460                                                         return -1;
461                                                 }
462                                         }
463                                 } else if (password && !strcasecmp(password, pass)) {
464                                         break;
465                                 } else {
466                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
467                                         ast_config_destroy(cfg);
468                                         return -1;
469                                 }       
470                         }
471                 }
472                 cat = ast_category_browse(cfg, cat);
473         }
474         if (cat) {
475                 strncpy(s->username, cat, sizeof(s->username) - 1);
476                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
477                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
478                 ast_config_destroy(cfg);
479                 if (events)
480                         set_eventmask(s, events);
481                 return 0;
482         }
483         ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
484         ast_config_destroy(cfg);
485         return -1;
486 }
487
488 static char mandescr_ping[] = 
489 "Description: A 'Ping' action will ellicit a 'Pong' response.  Used to keep the "
490 "  manager connection open.\n"
491 "Variables: NONE\n";
492
493 static int action_ping(struct mansession *s, struct message *m)
494 {
495         astman_send_response(s, m, "Pong", NULL);
496         return 0;
497 }
498
499 static char mandescr_listcommands[] = 
500 "Description: Returns the action name and synopsis for every\n"
501 "  action that is available to the user\n"
502 "Variables: NONE\n";
503
504 static int action_listcommands(struct mansession *s, struct message *m)
505 {
506         struct manager_action *cur = first_action;
507         char idText[256] = "";
508         char temp[BUFSIZ];
509         char *id = astman_get_header(m,"ActionID");
510
511         if (id && !ast_strlen_zero(id))
512                 snprintf(idText,256,"ActionID: %s\r\n",id);
513         ast_cli(s->fd, "Response: Success\r\n%s", idText);
514         ast_mutex_lock(&s->lock);
515         ast_mutex_lock(&actionlock);
516         while (cur) { /* Walk the list of actions */
517                 if ((s->writeperm & cur->authority) == cur->authority)
518                         ast_cli(s->fd, "%s: %s (Priv: %s)\r\n", cur->action, cur->synopsis, authority_to_str(cur->authority, temp, sizeof(temp)) );
519                 cur = cur->next;
520         }
521         ast_mutex_unlock(&actionlock);
522         ast_cli(s->fd, "\r\n");
523         ast_mutex_unlock(&s->lock);
524
525         return 0;
526 }
527
528 static char mandescr_events[] = 
529 "Description: Enable/Disable sending of events to this manager\n"
530 "  client.\n"
531 "Variables:\n"
532 "       EventMask: 'on' if all events should be sent,\n"
533 "               'off' if no events should be sent,\n"
534 "               'system,call,log' to select which flags events should have to be sent.\n";
535
536 static int action_events(struct mansession *s, struct message *m)
537 {
538         char *mask = astman_get_header(m, "EventMask");
539         int res;
540
541         res = set_eventmask(s, mask);
542         if (res > 0)
543                 astman_send_response(s, m, "Events On", NULL);
544         else if (res == 0)
545                 astman_send_response(s, m, "Events Off", NULL);
546
547         return 0;
548 }
549
550 static char mandescr_logoff[] = 
551 "Description: Logoff this manager session\n"
552 "Variables: NONE\n";
553
554 static int action_logoff(struct mansession *s, struct message *m)
555 {
556         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
557         return -1;
558 }
559
560 static char mandescr_hangup[] = 
561 "Description: Hangup a channel\n"
562 "Variables: \n"
563 "       Channel: The channel name to be hungup\n";
564
565 static int action_hangup(struct mansession *s, struct message *m)
566 {
567         struct ast_channel *c = NULL;
568         char *name = astman_get_header(m, "Channel");
569         if (ast_strlen_zero(name)) {
570                 astman_send_error(s, m, "No channel specified");
571                 return 0;
572         }
573         c = ast_channel_walk_locked(NULL);
574         while(c) {
575                 if (!strcasecmp(c->name, name)) {
576                         break;
577                 }
578                 ast_mutex_unlock(&c->lock);
579                 c = ast_channel_walk_locked(c);
580         }
581         if (!c) {
582                 astman_send_error(s, m, "No such channel");
583                 return 0;
584         }
585         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
586         ast_mutex_unlock(&c->lock);
587         astman_send_ack(s, m, "Channel Hungup");
588         return 0;
589 }
590
591 static char mandescr_setvar[] = 
592 "Description: Set a local channel variable.\n"
593 "Variables: (Names marked with * are required)\n"
594 "       *Channel: Channel to set variable for\n"
595 "       *Variable: Variable name\n"
596 "       *Value: Value\n";
597
598 static int action_setvar(struct mansession *s, struct message *m)
599 {
600         struct ast_channel *c = NULL;
601         char *name = astman_get_header(m, "Channel");
602         char *varname = astman_get_header(m, "Variable");
603         char *varval = astman_get_header(m, "Value");
604         
605         if (!strlen(name)) {
606                 astman_send_error(s, m, "No channel specified");
607                 return 0;
608         }
609         if (!strlen(varname)) {
610                 astman_send_error(s, m, "No variable specified");
611                 return 0;
612         }
613
614         c = ast_channel_walk_locked(NULL);
615         while(c) {
616                 if (!strcasecmp(c->name, name)) {
617                         break;
618                 }
619                 ast_mutex_unlock(&c->lock);
620                 c = ast_channel_walk_locked(c);
621         }
622         if (!c) {
623                 astman_send_error(s, m, "No such channel");
624                 return 0;
625         }
626         
627         pbx_builtin_setvar_helper(c,varname,varval);
628           
629         ast_mutex_unlock(&c->lock);
630         astman_send_ack(s, m, "Variable Set");
631         return 0;
632 }
633
634 static char mandescr_getvar[] = 
635 "Description: Get the value of a local channel variable.\n"
636 "Variables: (Names marked with * are required)\n"
637 "       *Channel: Channel to read variable from\n"
638 "       *Variable: Variable name\n"
639 "       ActionID: Optional Action id for message matching.\n";
640
641 static int action_getvar(struct mansession *s, struct message *m)
642 {
643         struct ast_channel *c = NULL;
644         char *name = astman_get_header(m, "Channel");
645         char *varname = astman_get_header(m, "Variable");
646         char *id = astman_get_header(m,"ActionID");
647         char *varval;
648         char *varval2=NULL;
649
650         if (!strlen(name)) {
651                 astman_send_error(s, m, "No channel specified");
652                 return 0;
653         }
654         if (!strlen(varname)) {
655                 astman_send_error(s, m, "No variable specified");
656                 return 0;
657         }
658
659         c = ast_channel_walk_locked(NULL);
660         while(c) {
661                 if (!strcasecmp(c->name, name)) {
662                         break;
663                 }
664                 ast_mutex_unlock(&c->lock);
665                 c = ast_channel_walk_locked(c);
666         }
667         if (!c) {
668                 astman_send_error(s, m, "No such channel");
669                 return 0;
670         }
671         
672         varval=pbx_builtin_getvar_helper(c,varname);
673         if (varval)
674                 varval2 = ast_strdupa(varval);
675         if (!varval2)
676                 varval2 = "";
677         ast_mutex_unlock(&c->lock);
678         ast_mutex_lock(&s->lock);
679         ast_cli(s->fd, "Response: Success\r\n"
680                 "%s: %s\r\n" ,varname,varval2);
681         if (id && !ast_strlen_zero(id))
682                 ast_cli(s->fd, "ActionID: %s\r\n",id);
683         ast_cli(s->fd, "\r\n");
684         ast_mutex_unlock(&s->lock);
685
686         return 0;
687 }
688
689
690 /*--- action_status: Manager "status" command to show channels */
691 /* Needs documentation... */
692 static int action_status(struct mansession *s, struct message *m)
693 {
694         char *id = astman_get_header(m,"ActionID");
695         char *name = astman_get_header(m,"Channel");
696         char idText[256] = "";
697         struct ast_channel *c;
698         char bridge[256];
699         struct timeval now;
700         long elapsed_seconds=0;
701
702         gettimeofday(&now, NULL);
703         astman_send_ack(s, m, "Channel status will follow");
704         c = ast_channel_walk_locked(NULL);
705         if (id && !ast_strlen_zero(id))
706                 snprintf(idText,256,"ActionID: %s\r\n",id);
707         if (name && !ast_strlen_zero(name)) {
708                 while (c) {
709                         if (!strcasecmp(c->name, name)) {
710                                 break;
711                         }
712                         ast_mutex_unlock(&c->lock);
713                         c = ast_channel_walk_locked(c);
714                 }
715                 if (!c) {
716                         astman_send_error(s, m, "No such channel");
717                         return 0;
718                 }
719         }
720         while(c) {
721                 if (c->_bridge)
722                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->_bridge->name);
723                 else
724                         bridge[0] = '\0';
725                 ast_mutex_lock(&s->lock);
726                 if (c->pbx) {
727                         if (c->cdr) {
728                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
729                         }
730                         ast_cli(s->fd,
731                         "Event: Status\r\n"
732                         "Privilege: Call\r\n"
733                         "Channel: %s\r\n"
734                         "CallerID: %s\r\n"
735                         "CallerIDName: %s\r\n"
736                         "Account: %s\r\n"
737                         "State: %s\r\n"
738                         "Context: %s\r\n"
739                         "Extension: %s\r\n"
740                         "Priority: %d\r\n"
741                         "Seconds: %ld\r\n"
742                         "%s"
743                         "Uniqueid: %s\r\n"
744                         "%s"
745                         "\r\n",
746                         c->name, 
747                         c->cid.cid_num ? c->cid.cid_num : "<unknown>", 
748                         c->cid.cid_name ? c->cid.cid_name : "<unknown>", 
749                         c->accountcode,
750                         ast_state2str(c->_state), c->context,
751                         c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
752                 } else {
753                         ast_cli(s->fd,
754                         "Event: Status\r\n"
755                         "Privilege: Call\r\n"
756                         "Channel: %s\r\n"
757                         "CallerID: %s\r\n"
758                         "CallerIDName: %s\r\n"
759                         "Account: %s\r\n"
760                         "State: %s\r\n"
761                         "%s"
762                         "Uniqueid: %s\r\n"
763                         "%s"
764                         "\r\n",
765                         c->name, 
766                         c->cid.cid_num ? c->cid.cid_num : "<unknown>", 
767                         c->cid.cid_name ? c->cid.cid_name : "<unknown>", 
768                         c->accountcode,
769                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
770                 }
771                 ast_mutex_unlock(&s->lock);
772                 ast_mutex_unlock(&c->lock);
773                 if (name && !ast_strlen_zero(name)) {
774                         break;
775                 }
776                 c = ast_channel_walk_locked(c);
777         }
778         ast_mutex_lock(&s->lock);
779         ast_cli(s->fd,
780         "Event: StatusComplete\r\n"
781         "%s"
782         "\r\n",idText);
783         ast_mutex_unlock(&s->lock);
784         return 0;
785 }
786
787 static char mandescr_redirect[] = 
788 "Description: Redirect (transfer) a call.\n"
789 "Variables: (Names marked with * are required)\n"
790 "       *Channel: Channel to redirect\n"
791 "       ExtraChannel: Second call leg to transfer (optional)\n"
792 "       *Exten: Extension to transfer to\n"
793 "       *Context: Context to transfer to\n"
794 "       *Priority: Priority to transfer to\n"
795 "       ActionID: Optional Action id for message matching.\n";
796
797 /*--- action_redirect: The redirect manager command */
798 static int action_redirect(struct mansession *s, struct message *m)
799 {
800         char *name = astman_get_header(m, "Channel");
801         char *name2 = astman_get_header(m, "ExtraChannel");
802         char *exten = astman_get_header(m, "Exten");
803         char *context = astman_get_header(m, "Context");
804         char *priority = astman_get_header(m, "Priority");
805         struct ast_channel *chan, *chan2 = NULL;
806         int pi = 0;
807         int res;
808
809         if (!name || ast_strlen_zero(name)) {
810                 astman_send_error(s, m, "Channel not specified");
811                 return 0;
812         }
813         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
814                 astman_send_error(s, m, "Invalid priority\n");
815                 return 0;
816         }
817         chan = ast_get_channel_by_name_locked(name);
818         if (!chan) {
819                 char buf[BUFSIZ];
820                 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
821                 astman_send_error(s, m, buf);
822                 return 0;
823         }
824         if (!ast_strlen_zero(name2))
825                 chan2 = ast_get_channel_by_name_locked(name2);
826         res = ast_async_goto(chan, context, exten, pi);
827         if (!res) {
828                 if (!ast_strlen_zero(name2)) {
829                         if (chan2)
830                                 res = ast_async_goto(chan2, context, exten, pi);
831                         else
832                                 res = -1;
833                         if (!res)
834                                 astman_send_ack(s, m, "Dual Redirect successful");
835                         else
836                                 astman_send_error(s, m, "Secondary redirect failed");
837                 } else
838                         astman_send_ack(s, m, "Redirect successful");
839         } else
840                 astman_send_error(s, m, "Redirect failed");
841         if (chan)
842                 ast_mutex_unlock(&chan->lock);
843         if (chan2)
844                 ast_mutex_unlock(&chan2->lock);
845         return 0;
846 }
847
848 static char mandescr_command[] = 
849 "Description: Run a CLI command.\n"
850 "Variables: (Names marked with * are required)\n"
851 "       *Command: Asterisk CLI command to run\n"
852 "       ActionID: Optional Action id for message matching.\n";
853
854 /*--- action_command: Manager command "command" - execute CLI command */
855 static int action_command(struct mansession *s, struct message *m)
856 {
857         char *cmd = astman_get_header(m, "Command");
858         char *id = astman_get_header(m, "ActionID");
859         ast_mutex_lock(&s->lock);
860         s->blocking = 1;
861         ast_mutex_unlock(&s->lock);
862         ast_cli(s->fd, "Response: Follows\r\nPrivilege: Command\r\n");
863         if (id && !ast_strlen_zero(id))
864                 ast_cli(s->fd, "ActionID: %s\r\n", id);
865         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
866         ast_cli_command(s->fd, cmd);
867         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
868         ast_mutex_lock(&s->lock);
869         s->blocking = 0;
870         ast_mutex_unlock(&s->lock);
871         return 0;
872 }
873
874 static void *fast_originate(void *data)
875 {
876         struct fast_originate_helper *in = data;
877         int res;
878         int reason = 0;
879         struct ast_channel *chan = NULL;
880
881         if (!ast_strlen_zero(in->app)) {
882                 res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, 
883                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
884                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
885                         in->variable, in->account, &chan);
886         } else {
887                 res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, 
888                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
889                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
890                         in->variable, in->account, &chan);
891         }   
892         if (!res)
893                 manager_event(EVENT_FLAG_CALL,
894                         "OriginateSuccess",
895                         "%s"
896                         "Channel: %s/%s\r\n"
897                         "Context: %s\r\n"
898                         "Exten: %s\r\n"
899                         "Reason: %i\r\n"
900                         "Uniqueid: %s\r\n",
901                         in->idtext, in->tech, in->data, in->context, in->exten, reason, chan ? chan->uniqueid : "<null>");
902         else
903                 manager_event(EVENT_FLAG_CALL,
904                         "OriginateFailure",
905                         "%s"
906                         "Channel: %s/%s\r\n"
907                         "Context: %s\r\n"
908                         "Exten: %s\r\n"
909                         "Reason: %i\r\n"
910                         "Uniqueid: %s\r\n",
911                         in->idtext, in->tech, in->data, in->context, in->exten, reason, chan ? chan->uniqueid : "<null>");
912
913         /* Locked by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
914         if (chan)
915                 ast_mutex_unlock(&chan->lock);
916         free(in);
917         return NULL;
918 }
919
920 static char mandescr_originate[] = 
921 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
922 "  Application/Data\n"
923 "Variables: (Names marked with * are required)\n"
924 "       *Channel: Channel name to call\n"
925 "       Exten: Extension to use (requires 'Context' and 'Priority')\n"
926 "       Context: Context to use (requires 'Exten' and 'Priority')\n"
927 "       Priority: Priority to use (requires 'Exten' and 'Context')\n"
928 "       Application: Application to use\n"
929 "       Data: Data to use (requires 'Application')\n"
930 "       Timeout: How long to wait for call to be answered (in ms)\n"
931 "       CallerID: Caller ID to be set on the outgoing channel\n"
932 "       Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
933 "       Account: Account code\n"
934 "       Async: Set to 'true' for fast origination\n";
935
936 static int action_originate(struct mansession *s, struct message *m)
937 {
938         char *name = astman_get_header(m, "Channel");
939         char *exten = astman_get_header(m, "Exten");
940         char *context = astman_get_header(m, "Context");
941         char *priority = astman_get_header(m, "Priority");
942         char *timeout = astman_get_header(m, "Timeout");
943         char *callerid = astman_get_header(m, "CallerID");
944         char *variable = astman_get_header(m, "Variable");
945         char *account = astman_get_header(m, "Account");
946         char *app = astman_get_header(m, "Application");
947         char *appdata = astman_get_header(m, "Data");
948         char *async = astman_get_header(m, "Async");
949         char *id = astman_get_header(m, "ActionID");
950         char *tech, *data;
951         char *l=NULL, *n=NULL;
952         int pi = 0;
953         int res;
954         int to = 30000;
955         int reason = 0;
956         char tmp[256];
957         char tmp2[256]="";
958         
959         pthread_t th;
960         pthread_attr_t attr;
961         if (!name) {
962                 astman_send_error(s, m, "Channel not specified");
963                 return 0;
964         }
965         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
966                 astman_send_error(s, m, "Invalid priority\n");
967                 return 0;
968         }
969         if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
970                 astman_send_error(s, m, "Invalid timeout\n");
971                 return 0;
972         }
973         strncpy(tmp, name, sizeof(tmp) - 1);
974         tech = tmp;
975         data = strchr(tmp, '/');
976         if (!data) {
977                 astman_send_error(s, m, "Invalid channel\n");
978                 return 0;
979         }
980         *data = '\0';
981         data++;
982         strncpy(tmp2, callerid, sizeof(tmp2) - 1);
983         ast_callerid_parse(tmp2, &n, &l);
984         if (n) {
985                 if (ast_strlen_zero(n))
986                         n = NULL;
987         }
988         if (l) {
989                 ast_shrink_phone_number(l);
990                 if (ast_strlen_zero(l))
991                         l = NULL;
992         }
993         if (ast_true(async)) {
994                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
995                 if (!fast) {
996                         res = -1;
997                 } else {
998                         memset(fast, 0, sizeof(struct fast_originate_helper));
999                         if (id && !ast_strlen_zero(id))
1000                                 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
1001                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
1002                         strncpy(fast->data, data, sizeof(fast->data) - 1);
1003                         strncpy(fast->app, app, sizeof(fast->app) - 1);
1004                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
1005                         if (l)
1006                                 strncpy(fast->cid_num, l, sizeof(fast->cid_num) - 1);
1007                         if (n)
1008                                 strncpy(fast->cid_name, n, sizeof(fast->cid_name) - 1);
1009                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
1010                         strncpy(fast->account, account, sizeof(fast->account) - 1);
1011                         strncpy(fast->context, context, sizeof(fast->context) - 1);
1012                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
1013                         fast->timeout = to;
1014                         fast->priority = pi;
1015                         pthread_attr_init(&attr);
1016                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1017                         if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
1018                                 res = -1;
1019                         } else {
1020                                 res = 0;
1021                         }
1022                 }
1023         } else if (!ast_strlen_zero(app)) {
1024                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 1, l, n, variable, account, NULL);
1025         } else {
1026                 if (exten && context && pi)
1027                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 1, l, n, variable, account, NULL);
1028                 else {
1029                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
1030                         return 0;
1031                 }
1032         }   
1033         if (!res)
1034                 astman_send_ack(s, m, "Originate successfully queued");
1035         else
1036                 astman_send_error(s, m, "Originate failed");
1037         return 0;
1038 }
1039
1040 static char mandescr_mailboxstatus[] = 
1041 "Description: Checks a voicemail account for status.\n"
1042 "Variables: (Names marked with * are required)\n"
1043 "       *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
1044 "       ActionID: Optional ActionID for message matching.\n"
1045 "Returns number of messages.\n"
1046 "       Message: Mailbox Status\n"
1047 "       Mailbox: <mailboxid>\n"
1048 "       Waiting: <count>\n"
1049 "\n";
1050 static int action_mailboxstatus(struct mansession *s, struct message *m)
1051 {
1052         char *mailbox = astman_get_header(m, "Mailbox");
1053         char *id = astman_get_header(m,"ActionID");
1054         char idText[256] = "";
1055         int ret;
1056         if (!mailbox || ast_strlen_zero(mailbox)) {
1057                 astman_send_error(s, m, "Mailbox not specified");
1058                 return 0;
1059         }
1060         if (id && !ast_strlen_zero(id))
1061                 snprintf(idText,256,"ActionID: %s\r\n",id);
1062         ret = ast_app_has_voicemail(mailbox, NULL);
1063         ast_mutex_lock(&s->lock);
1064         ast_cli(s->fd, "Response: Success\r\n"
1065                                    "%s"
1066                                    "Message: Mailbox Status\r\n"
1067                                    "Mailbox: %s\r\n"
1068                                    "Waiting: %d\r\n\r\n", idText, mailbox, ret);
1069         ast_mutex_unlock(&s->lock);
1070         return 0;
1071 }
1072
1073 static char mandescr_mailboxcount[] = 
1074 "Description: Checks a voicemail account for new messages.\n"
1075 "Variables: (Names marked with * are required)\n"
1076 "       *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
1077 "       ActionID: Optional ActionID for message matching.\n"
1078 "Returns number of new and old messages.\n"
1079 "       Message: Mailbox Message Count\n"
1080 "       Mailbox: <mailboxid>\n"
1081 "       NewMessages: <count>\n"
1082 "       OldMessages: <count>\n"
1083 "\n";
1084 static int action_mailboxcount(struct mansession *s, struct message *m)
1085 {
1086         char *mailbox = astman_get_header(m, "Mailbox");
1087         char *id = astman_get_header(m,"ActionID");
1088         char idText[256] = "";
1089         int newmsgs = 0, oldmsgs = 0;
1090         if (!mailbox || ast_strlen_zero(mailbox)) {
1091                 astman_send_error(s, m, "Mailbox not specified");
1092                 return 0;
1093         }
1094         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
1095         if (id && !ast_strlen_zero(id)) {
1096                 snprintf(idText,256,"ActionID: %s\r\n",id);
1097         }
1098         ast_mutex_lock(&s->lock);
1099         ast_cli(s->fd, "Response: Success\r\n"
1100                                    "%s"
1101                                    "Message: Mailbox Message Count\r\n"
1102                                    "Mailbox: %s\r\n"
1103                                    "NewMessages: %d\r\n"
1104                                    "OldMessages: %d\r\n" 
1105                                    "\r\n",
1106                                     idText,mailbox, newmsgs, oldmsgs);
1107         ast_mutex_unlock(&s->lock);
1108         return 0;
1109 }
1110
1111 static char mandescr_extensionstate[] = 
1112 "Description: Report the extension state for given extension.\n"
1113 "  If the extension has a hint, will use devicestate to check\n"
1114 "  the status of the device connected to the extension.\n"
1115 "Variables: (Names marked with * are required)\n"
1116 "       *Exten: Extension to check state on\n"
1117 "       *Context: Context for extension\n"
1118 "       ActionId: Optional ID for this transaction\n"
1119 "Will return an \"Extension Status\" message.\n"
1120 "The response will include the hint for the extension and the status.\n";
1121
1122 static int action_extensionstate(struct mansession *s, struct message *m)
1123 {
1124         char *exten = astman_get_header(m, "Exten");
1125         char *context = astman_get_header(m, "Context");
1126         char *id = astman_get_header(m,"ActionID");
1127         char idText[256] = "";
1128         char hint[256] = "";
1129         int status;
1130         if (!exten || ast_strlen_zero(exten)) {
1131                 astman_send_error(s, m, "Extension not specified");
1132                 return 0;
1133         }
1134         if (!context || ast_strlen_zero(context))
1135                 context = "default";
1136         status = ast_extension_state(NULL, context, exten);
1137         ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
1138         if (id && !ast_strlen_zero(id)) {
1139                 snprintf(idText,256,"ActionID: %s\r\n",id);
1140         }
1141         ast_mutex_lock(&s->lock);
1142         ast_cli(s->fd, "Response: Success\r\n"
1143                                    "%s"
1144                                    "Message: Extension Status\r\n"
1145                                    "Exten: %s\r\n"
1146                                    "Context: %s\r\n"
1147                                    "Hint: %s\r\n"
1148                                    "Status: %d\r\n\r\n",
1149                                    idText,exten, context, hint, status);
1150         ast_mutex_unlock(&s->lock);
1151         return 0;
1152 }
1153
1154 static char mandescr_timeout[] = 
1155 "Description: Hangup a channel after a certain time.\n"
1156 "Variables: (Names marked with * are required)\n"
1157 "       *Channel: Channel name to hangup\n"
1158 "       *Timeout: Maximum duration of the call (sec)\n"
1159 "Acknowledges set time with 'Timeout Set' message\n";
1160
1161 static int action_timeout(struct mansession *s, struct message *m)
1162 {
1163         struct ast_channel *c = NULL;
1164         char *name = astman_get_header(m, "Channel");
1165         int timeout = atoi(astman_get_header(m, "Timeout"));
1166         if (ast_strlen_zero(name)) {
1167                 astman_send_error(s, m, "No channel specified");
1168                 return 0;
1169         }
1170         if (!timeout) {
1171                 astman_send_error(s, m, "No timeout specified");
1172                 return 0;
1173         }
1174         c = ast_channel_walk_locked(NULL);
1175         while(c) {
1176                 if (!strcasecmp(c->name, name)) {
1177                         break;
1178                 }
1179                 ast_mutex_unlock(&c->lock);
1180                 c = ast_channel_walk_locked(c);
1181         }
1182         if (!c) {
1183                 astman_send_error(s, m, "No such channel");
1184                 return 0;
1185         }
1186         ast_channel_setwhentohangup(c, timeout);
1187         ast_mutex_unlock(&c->lock);
1188         astman_send_ack(s, m, "Timeout Set");
1189         return 0;
1190 }
1191
1192 static int process_message(struct mansession *s, struct message *m)
1193 {
1194         char action[80] = "";
1195         struct manager_action *tmp = first_action;
1196         char *id = astman_get_header(m,"ActionID");
1197         char idText[256] = "";
1198         char iabuf[INET_ADDRSTRLEN];
1199
1200         strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1201         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1202
1203         if (ast_strlen_zero(action)) {
1204                 astman_send_error(s, m, "Missing action in request");
1205                 return 0;
1206         }
1207         if (id && !ast_strlen_zero(id)) {
1208                 snprintf(idText,256,"ActionID: %s\r\n",id);
1209         }
1210         if (!s->authenticated) {
1211                 if (!strcasecmp(action, "Challenge")) {
1212                         char *authtype;
1213                         authtype = astman_get_header(m, "AuthType");
1214                         if (!strcasecmp(authtype, "MD5")) {
1215                                 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1216                                         ast_mutex_lock(&s->lock);
1217                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1218                                         ast_mutex_unlock(&s->lock);
1219                                 }
1220                                 ast_mutex_lock(&s->lock);
1221                                 ast_cli(s->fd, "Response: Success\r\n"
1222                                                 "%s"
1223                                                 "Challenge: %s\r\n\r\n",
1224                                                 idText,s->challenge);
1225                                 ast_mutex_unlock(&s->lock);
1226                                 return 0;
1227                         } else {
1228                                 astman_send_error(s, m, "Must specify AuthType");
1229                                 return 0;
1230                         }
1231                 } else if (!strcasecmp(action, "Login")) {
1232                         if (authenticate(s, m)) {
1233                                 sleep(1);
1234                                 astman_send_error(s, m, "Authentication failed");
1235                                 return -1;
1236                         } else {
1237                                 s->authenticated = 1;
1238                                 if (option_verbose > 1) {
1239                                         if ( displayconnects ) {
1240                                                 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1241                                         }
1242                                 }
1243                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1244                                 astman_send_ack(s, m, "Authentication accepted");
1245                         }
1246                 } else if (!strcasecmp(action, "Logoff")) {
1247                         astman_send_ack(s, m, "See ya");
1248                         return -1;
1249                 } else
1250                         astman_send_error(s, m, "Authentication Required");
1251         } else {
1252                 while( tmp ) {          
1253                         if (!strcasecmp(action, tmp->action)) {
1254                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
1255                                         if (tmp->func(s, m))
1256                                                 return -1;
1257                                 } else {
1258                                         astman_send_error(s, m, "Permission denied");
1259                                 }
1260                                 return 0;
1261                         }
1262                         tmp = tmp->next;
1263                 }
1264                 astman_send_error(s, m, "Invalid/unknown command");
1265         }
1266         return 0;
1267 }
1268
1269 static int get_input(struct mansession *s, char *output)
1270 {
1271         /* output must have at least sizeof(s->inbuf) space */
1272         int res;
1273         int x;
1274         struct pollfd fds[1];
1275         char iabuf[INET_ADDRSTRLEN];
1276         for (x=1;x<s->inlen;x++) {
1277                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1278                         /* Copy output data up to and including \r\n */
1279                         memcpy(output, s->inbuf, x + 1);
1280                         /* Add trailing \0 */
1281                         output[x+1] = '\0';
1282                         /* Move remaining data back to the front */
1283                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1284                         s->inlen -= (x + 1);
1285                         return 1;
1286                 }
1287         } 
1288         if (s->inlen >= sizeof(s->inbuf) - 1) {
1289                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), s->inbuf);
1290                 s->inlen = 0;
1291         }
1292         fds[0].fd = s->fd;
1293         fds[0].events = POLLIN;
1294         res = poll(fds, 1, -1);
1295         if (res < 0) {
1296                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1297         } else if (res > 0) {
1298                 ast_mutex_lock(&s->lock);
1299                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1300                 ast_mutex_unlock(&s->lock);
1301                 if (res < 1)
1302                         return -1;
1303         }
1304         s->inlen += res;
1305         s->inbuf[s->inlen] = '\0';
1306         return 0;
1307 }
1308
1309 static void *session_do(void *data)
1310 {
1311         struct mansession *s = data;
1312         struct message m;
1313         char iabuf[INET_ADDRSTRLEN];
1314         int res;
1315         
1316         ast_mutex_lock(&s->lock);
1317         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1318         ast_mutex_unlock(&s->lock);
1319         memset(&m, 0, sizeof(&m));
1320         for (;;) {
1321                 res = get_input(s, m.headers[m.hdrcount]);
1322                 if (res > 0) {
1323                         /* Strip trailing \r\n */
1324                         if (strlen(m.headers[m.hdrcount]) < 2)
1325                                 continue;
1326                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1327                         if (ast_strlen_zero(m.headers[m.hdrcount])) {
1328                                 if (process_message(s, &m))
1329                                         break;
1330                                 memset(&m, 0, sizeof(&m));
1331                         } else if (m.hdrcount < MAX_HEADERS - 1)
1332                                 m.hdrcount++;
1333                 } else if (res < 0)
1334                         break;
1335         }
1336         if (s->authenticated) {
1337                 if (option_verbose > 1) {
1338                         if (displayconnects) 
1339                                 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));    
1340                 }
1341                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1342         } else {
1343                 if (option_verbose > 1) {
1344                         if ( displayconnects )
1345                                 ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1346                 }
1347                 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1348         }
1349         destroy_session(s);
1350         return NULL;
1351 }
1352
1353 static void *accept_thread(void *ignore)
1354 {
1355         int as;
1356         struct sockaddr_in sin;
1357         int sinlen;
1358         struct mansession *s;
1359         struct protoent *p;
1360         int arg = 1;
1361         int flags;
1362         pthread_attr_t attr;
1363
1364         pthread_attr_init(&attr);
1365         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1366
1367         for (;;) {
1368                 sinlen = sizeof(sin);
1369                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1370                 if (as < 0) {
1371                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1372                         continue;
1373                 }
1374                 p = getprotobyname("tcp");
1375                 if (p) {
1376                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1377                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1378                         }
1379                 }
1380                 s = malloc(sizeof(struct mansession));
1381                 if (!s) {
1382                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1383                         continue;
1384                 } 
1385                 memset(s, 0, sizeof(struct mansession));
1386                 memcpy(&s->sin, &sin, sizeof(sin));
1387
1388                 if(! block_sockets) {
1389                         /* For safety, make sure socket is non-blocking */
1390                         flags = fcntl(as, F_GETFL);
1391                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
1392                 }
1393                 ast_mutex_init(&s->lock);
1394                 s->fd = as;
1395                 s->send_events = -1;
1396                 ast_mutex_lock(&sessionlock);
1397                 s->next = sessions;
1398                 sessions = s;
1399                 ast_mutex_unlock(&sessionlock);
1400                 if (ast_pthread_create(&t, &attr, session_do, s))
1401                         destroy_session(s);
1402         }
1403         pthread_attr_destroy(&attr);
1404         return NULL;
1405 }
1406
1407 /*--- manager_event: Send AMI event to client */
1408 int manager_event(int category, char *event, char *fmt, ...)
1409 {
1410         struct mansession *s;
1411         char tmp[4096];
1412         va_list ap;
1413
1414         ast_mutex_lock(&sessionlock);
1415         s = sessions;
1416         while(s) {
1417                 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1418                         ast_mutex_lock(&s->lock);
1419                         if (!s->blocking) {
1420                                 ast_cli(s->fd, "Event: %s\r\n", event);
1421                                 ast_cli(s->fd, "Privilege: %s\r\n", authority_to_str(category, tmp, sizeof(tmp)));
1422                                 va_start(ap, fmt);
1423                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1424                                 va_end(ap);
1425                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1426                                 ast_cli(s->fd, "\r\n");
1427                         }
1428                         ast_mutex_unlock(&s->lock);
1429                 }
1430                 s = s->next;
1431         }
1432         ast_mutex_unlock(&sessionlock);
1433         return 0;
1434 }
1435
1436 int ast_manager_unregister( char *action ) {
1437         struct manager_action *cur = first_action, *prev = first_action;
1438
1439         ast_mutex_lock(&actionlock);
1440         while( cur ) {          
1441                 if (!strcasecmp(action, cur->action)) {
1442                         prev->next = cur->next;
1443                         free(cur);
1444                         if (option_verbose > 1) 
1445                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1446                         ast_mutex_unlock(&actionlock);
1447                         return 0;
1448                 }
1449                 prev = cur;
1450                 cur = cur->next;
1451         }
1452         ast_mutex_unlock(&actionlock);
1453         return 0;
1454 }
1455
1456 static int manager_state_cb(char *context, char *exten, int state, void *data)
1457 {
1458         /* Notify managers of change */
1459         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1460         return 0;
1461 }
1462
1463 static int ast_manager_register_struct(struct manager_action *act)
1464 {
1465         struct manager_action *cur = first_action, *prev = NULL;
1466         int ret;
1467
1468         ast_mutex_lock(&actionlock);
1469         while(cur) { /* Walk the list of actions */
1470                 ret = strcasecmp(cur->action, act->action);
1471                 if (ret == 0) {
1472                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1473                         ast_mutex_unlock(&actionlock);
1474                         return -1;
1475                 } else if (ret > 0) {
1476                         /* Insert these alphabetically */
1477                         if (prev) {
1478                                 act->next = prev->next;
1479                                 prev->next = act;
1480                         } else {
1481                                 act->next = first_action;
1482                                 first_action = act;
1483                         }
1484                         break;
1485                 }
1486                 prev = cur; 
1487                 cur = cur->next;
1488         }
1489         
1490         if (!cur) {
1491                 if (prev)
1492                         prev->next = act;
1493                 else
1494                         first_action = act;
1495                 act->next = NULL;
1496         }
1497
1498         if (option_verbose > 1) 
1499                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1500         ast_mutex_unlock(&actionlock);
1501         return 0;
1502 }
1503
1504 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, struct message *m), const char *synopsis, const char *description)
1505 {
1506         struct manager_action *cur;
1507
1508         cur = malloc(sizeof(struct manager_action));
1509         if (!cur) {
1510                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1511                 ast_mutex_unlock(&actionlock);
1512                 return -1;
1513         }
1514         cur->action = action;
1515         cur->authority = auth;
1516         cur->func = func;
1517         cur->synopsis = synopsis;
1518         cur->description = description;
1519         cur->next = NULL;
1520
1521         ast_manager_register_struct(cur);
1522
1523         return 0;
1524 }
1525
1526 static int registered = 0;
1527
1528 int init_manager(void)
1529 {
1530         struct ast_config *cfg;
1531         char *val;
1532         int oldportno = portno;
1533         static struct sockaddr_in ba;
1534         int x = 1;
1535         if (!registered) {
1536                 /* Register default actions */
1537                 ast_manager_register2("Ping", 0, action_ping, "Keepalive command", mandescr_ping);
1538                 ast_manager_register2("Events", 0, action_events, "Control Event Flow", mandescr_events);
1539                 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1540                 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1541                 ast_manager_register("Status", EVENT_FLAG_CALL, action_status, "Lists channel status" );
1542                 ast_manager_register2("Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar );
1543                 ast_manager_register2("Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable", mandescr_getvar );
1544                 ast_manager_register2("Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect (transfer) a call", mandescr_redirect );
1545                 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1546                 ast_manager_register2("Command", EVENT_FLAG_COMMAND, action_command, "Execute Asterisk CLI Command", mandescr_command );
1547                 ast_manager_register2("ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
1548                 ast_manager_register2("AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
1549                 ast_manager_register2("MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
1550                 ast_manager_register2("MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
1551                 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1552
1553                 ast_cli_register(&show_mancmd_cli);
1554                 ast_cli_register(&show_mancmds_cli);
1555                 ast_cli_register(&show_manconn_cli);
1556                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1557                 registered = 1;
1558         }
1559         portno = DEFAULT_MANAGER_PORT;
1560         displayconnects = 1;
1561         cfg = ast_config_load("manager.conf");
1562         if (!cfg) {
1563                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1564                 return 0;
1565         }
1566         memset(&ba, 0, sizeof(ba));
1567         val = ast_variable_retrieve(cfg, "general", "enabled");
1568         if (val)
1569                 enabled = ast_true(val);
1570
1571         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1572         if(val)
1573                 block_sockets = ast_true(val);
1574
1575         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1576                 if (sscanf(val, "%d", &portno) != 1) {
1577                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1578                         portno = DEFAULT_MANAGER_PORT;
1579                 }
1580         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1581                 if (sscanf(val, "%d", &portno) != 1) {
1582                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1583                         portno = DEFAULT_MANAGER_PORT;
1584                 }
1585                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1586         }
1587         /* Parsing the displayconnects */
1588         if ((val = ast_variable_retrieve(cfg, "general", "displayconnects"))) {
1589                         displayconnects = ast_true(val);;
1590         }
1591                                 
1592         
1593         ba.sin_family = AF_INET;
1594         ba.sin_port = htons(portno);
1595         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1596         
1597         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1598                 if (!inet_aton(val, &ba.sin_addr)) { 
1599                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1600                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1601                 }
1602         }
1603         
1604         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1605 #if 0
1606                 /* Can't be done yet */
1607                 close(asock);
1608                 asock = -1;
1609 #else
1610                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1611 #endif
1612         }
1613         ast_config_destroy(cfg);
1614         
1615         /* If not enabled, do nothing */
1616         if (!enabled) {
1617                 return 0;
1618         }
1619         if (asock < 0) {
1620                 asock = socket(AF_INET, SOCK_STREAM, 0);
1621                 if (asock < 0) {
1622                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1623                         return -1;
1624                 }
1625                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1626                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1627                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1628                         close(asock);
1629                         asock = -1;
1630                         return -1;
1631                 }
1632                 if (listen(asock, 2)) {
1633                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1634                         close(asock);
1635                         asock = -1;
1636                         return -1;
1637                 }
1638                 if (option_verbose)
1639                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1640                 ast_pthread_create(&t, NULL, accept_thread, NULL);
1641         }
1642         return 0;
1643 }
1644
1645 int reload_manager(void)
1646 {
1647         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1648         return init_manager();
1649 }