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