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