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