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