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