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