be1bb28fb6ff8cc02ef8b71f855a50000b20fe42
[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 <pthread.h>
17 #include <string.h>
18 #include <sys/time.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
22 #include <signal.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <asterisk/channel.h>
26 #include <asterisk/file.h>
27 #include <asterisk/manager.h>
28 #include <asterisk/config.h>
29 #include <asterisk/lock.h>
30 #include <asterisk/logger.h>
31 #include <asterisk/options.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/app.h>
34 #include <asterisk/pbx.h>
35 #include <asterisk/md5.h>
36
37 static int enabled = 0;
38 static int portno = DEFAULT_MANAGER_PORT;
39 static int asock = -1;
40 static pthread_t t;
41 static pthread_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
42
43 static struct permalias {
44         int num;
45         char *label;
46 } perms[] = {
47         { EVENT_FLAG_SYSTEM, "system" },
48         { EVENT_FLAG_CALL, "call" },
49         { EVENT_FLAG_LOG, "log" },
50         { EVENT_FLAG_VERBOSE, "verbose" },
51         { EVENT_FLAG_COMMAND, "command" },
52         { EVENT_FLAG_AGENT, "agent" },
53         { -1, "all" },
54 };
55
56 static struct mansession *sessions = NULL;
57 static struct manager_action *first_action = NULL;
58 static pthread_mutex_t actionlock = AST_MUTEX_INITIALIZER;
59
60 static int handle_showmancmds(int fd, int argc, char *argv[])
61 {
62         struct manager_action *cur = first_action;
63
64         ast_pthread_mutex_lock(&actionlock);
65         while(cur) { /* Walk the list of actions */
66                 ast_cli(fd, "\t%s  %s\r\n",cur->action, cur->synopsis);
67                 cur = cur->next;
68         }
69
70         ast_pthread_mutex_unlock(&actionlock);
71         return RESULT_SUCCESS;
72 }
73
74 static int handle_showmanconn(int fd, int argc, char *argv[])
75 {
76         struct mansession *s;
77
78         ast_pthread_mutex_lock(&sessionlock);
79         s = sessions;
80         ast_cli(fd, "  Username\tIP Address\n");
81         while(s) {
82                 ast_cli(fd, "  %s\t\t%s\r\n",s->username, inet_ntoa(s->sin.sin_addr));
83                 s = s->next;
84         }
85
86         ast_pthread_mutex_unlock(&sessionlock);
87         return RESULT_SUCCESS;
88 }
89
90 static char showmancmds_help[] = 
91 "Usage: show manager commands\n"
92 "       Prints a listing of all the available manager commands.\n";
93
94 static char showmanconn_help[] = 
95 "Usage: show manager connected\n"
96 "       Prints a listing of the users that are connected to the\n"
97 "manager interface.\n";
98
99 static struct ast_cli_entry show_mancmds_cli =
100         { { "show", "manager", "commands", NULL },
101         handle_showmancmds, "Show manager commands", showmancmds_help };
102
103 static struct ast_cli_entry show_manconn_cli =
104         { { "show", "manager", "connected", NULL },
105         handle_showmanconn, "Show connected manager users", showmanconn_help };
106
107 static void destroy_session(struct mansession *s)
108 {
109         struct mansession *cur, *prev = NULL;
110         ast_pthread_mutex_lock(&sessionlock);
111         cur = sessions;
112         while(cur) {
113                 if (cur == s)
114                         break;
115                 prev = cur;
116                 cur = cur->next;
117         }
118         if (cur) {
119                 if (prev)
120                         prev->next = cur->next;
121                 else
122                         sessions = cur->next;
123                 if (s->fd > -1)
124                         close(s->fd);
125                 free(s);
126         } else
127                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
128         ast_pthread_mutex_unlock(&sessionlock);
129         
130 }
131
132 static char *get_header(struct message *m, char *var)
133 {
134         char cmp[80];
135         int x;
136         snprintf(cmp, sizeof(cmp), "%s: ", var);
137         for (x=0;x<m->hdrcount;x++)
138                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
139                         return m->headers[x] + strlen(cmp);
140         return "";
141 }
142
143 static void send_error(struct mansession *s, char *error)
144 {
145         ast_pthread_mutex_lock(&s->lock);
146         ast_cli(s->fd, "Response: Error\r\n");
147         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
148         ast_pthread_mutex_unlock(&s->lock);
149 }
150
151 static void send_response(struct mansession *s, char *resp, char *msg)
152 {
153         ast_pthread_mutex_lock(&s->lock);
154         ast_cli(s->fd, "Response: %s\r\n", resp);
155         if (msg)
156                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
157         else
158                 ast_cli(s->fd, "\r\n");
159         ast_pthread_mutex_unlock(&s->lock);
160 }
161
162 static void send_ack(struct mansession *s, char *msg)
163 {
164         send_response(s, "Success", msg);
165 }
166
167 static int get_perm(char *instr)
168 {
169         char tmp[256];
170         char *c;
171         int x;
172         int ret = 0;
173         char *stringp=NULL;
174         if (!instr)
175                 return 0;
176         strncpy(tmp, instr, sizeof(tmp) - 1);
177         stringp=tmp;
178         c = strsep(&stringp, ",");
179         while(c) {
180                 for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
181                         if (!strcasecmp(perms[x].label, c)) 
182                                 ret |= perms[x].num;
183                 }
184                 c = strsep(&stringp, ",");
185         }
186         return ret;
187 }
188
189 static int authenticate(struct mansession *s, struct message *m)
190 {
191         struct ast_config *cfg;
192         char *cat;
193         char *user = get_header(m, "Username");
194         char *pass = get_header(m, "Secret");
195         char *authtype = get_header(m, "AuthType");
196         char *key = get_header(m, "Key");
197
198         cfg = ast_load("manager.conf");
199         if (!cfg)
200                 return -1;
201         cat = ast_category_browse(cfg, NULL);
202         while(cat) {
203                 if (strcasecmp(cat, "general")) {
204                         /* This is a user */
205                         if (!strcasecmp(cat, user)) {
206                                 char *password = ast_variable_retrieve(cfg, cat, "secret");
207                                 if (!strcasecmp(authtype, "MD5")) {
208                                         if (key && strlen(key) && s->challenge) {
209                                                 int x;
210                                                 int len=0;
211                                                 char md5key[256] = "";
212                                                 struct MD5Context md5;
213                                                 unsigned char digest[16];
214                                                 MD5Init(&md5);
215                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
216                                                 MD5Update(&md5, password, strlen(password));
217                                                 MD5Final(digest, &md5);
218                                                 for (x=0;x<16;x++)
219                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
220                                                 if (!strcmp(md5key, key))
221                                                         break;
222                                                 else {
223                                                         ast_destroy(cfg);
224                                                         return -1;
225                                                 }
226                                         }
227                                 } else if (password && !strcasecmp(password, pass)) {
228                                         break;
229                                 } else {
230                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
231                                         ast_destroy(cfg);
232                                         return -1;
233                                 }       
234                         }
235                 }
236                 cat = ast_category_browse(cfg, cat);
237         }
238         if (cat) {
239                 strncpy(s->username, cat, sizeof(s->username) - 1);
240                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
241                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
242                 ast_destroy(cfg);
243                 return 0;
244         }
245         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
246         ast_destroy(cfg);
247         return -1;
248 }
249
250 static int action_ping(struct mansession *s, struct message *m)
251 {
252         send_response(s, "Pong", NULL);
253         return 0;
254 }
255
256 static int action_logoff(struct mansession *s, struct message *m)
257 {
258         send_response(s, "Goodbye", "Thanks for all the fish.");
259         return -1;
260 }
261
262 static int action_hangup(struct mansession *s, struct message *m)
263 {
264         struct ast_channel *c = NULL;
265         char *name = get_header(m, "Channel");
266         if (!strlen(name)) {
267                 send_error(s, "No channel specified");
268                 return 0;
269         }
270         c = ast_channel_walk(NULL);
271         while(c) {
272                 if (!strcasecmp(c->name, name)) {
273                         break;
274                 }
275                 c = ast_channel_walk(c);
276         }
277         if (!c) {
278                 send_error(s, "No such channel");
279                 return 0;
280         }
281         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
282         send_ack(s, "Channel Hungup");
283         return 0;
284 }
285
286 static int action_status(struct mansession *s, struct message *m)
287 {
288         struct ast_channel *c;
289         char bridge[256];
290         send_ack(s, "Channel status will follow");
291         c = ast_channel_walk(NULL);
292         while(c) {
293                 if (c->bridge)
294                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
295                 else
296                         strcpy(bridge, "");
297                 if (c->pbx) {
298                         ast_cli(s->fd,
299                         "Event: Status\r\n"
300                         "Channel: %s\r\n"
301                         "CallerID: %s\r\n"
302                         "State: %s\r\n"
303                         "Context: %s\r\n"
304                         "Extension: %s\r\n"
305                         "Priority: %d\r\n"
306                         "%s"
307                         "\r\n",
308                         c->name, c->callerid ? c->callerid : "<unknown>", 
309                         ast_state2str(c->_state), c->context,
310                         c->exten, c->priority, bridge);
311                 } else {
312                         ast_cli(s->fd,
313                         "Event: Status\r\n"
314                         "Channel: %s\r\n"
315                         "CallerID: %s\r\n"
316                         "State: %s\r\n"
317                         "%s"
318                         "\r\n",
319                         c->name, c->callerid ? c->callerid : "<unknown>", 
320                         ast_state2str(c->_state), bridge);
321                 }
322                 c = ast_channel_walk(c);
323         }
324         return 0;
325 }
326
327 static int action_redirect(struct mansession *s, struct message *m)
328 {
329         char *name = get_header(m, "Channel");
330         char *name2 = get_header(m, "ExtraChannel");
331         char *exten = get_header(m, "Exten");
332         char *context = get_header(m, "Context");
333         char *priority = get_header(m, "Priority");
334         int pi = 0;
335         int res;
336         if (!name || !strlen(name)) {
337                 send_error(s, "Channel not specified");
338                 return 0;
339         }
340         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
341                 send_error(s, "Invalid priority\n");
342                 return 0;
343         }
344         res = ast_async_goto_by_name(name, context, exten, pi);
345         if (!res) {
346                 if (strlen(name2)) {
347                         res = ast_async_goto_by_name(name2, context, exten, pi);
348                         if (!res)
349                                 send_ack(s, "Dual Redirect successful");
350                         else
351                                 send_error(s, "Secondary redirect failed");
352                 } else
353                         send_ack(s, "Redirect successful");
354         } else
355                 send_error(s, "Redirect failed");
356         return 0;
357 }
358
359 static int action_command(struct mansession *s, struct message *m)
360 {
361         char *cmd = get_header(m, "Command");
362         ast_pthread_mutex_lock(&s->lock);
363         s->blocking = 1;
364         ast_pthread_mutex_unlock(&s->lock);
365         ast_cli(s->fd, "Response: Follows\r\n");
366         ast_cli_command(s->fd, cmd);
367         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
368         ast_pthread_mutex_lock(&s->lock);
369         s->blocking = 0;
370         ast_pthread_mutex_unlock(&s->lock);
371         return 0;
372 }
373
374 static int action_originate(struct mansession *s, struct message *m)
375 {
376         char *name = get_header(m, "Channel");
377         char *exten = get_header(m, "Exten");
378         char *context = get_header(m, "Context");
379         char *priority = get_header(m, "Priority");
380         char *timeout = get_header(m, "Timeout");
381         char *callerid = get_header(m, "CallerID");
382         char *tech, *data;
383         int pi = 0;
384         int res;
385         int to = 30000;
386         int reason = 0;
387         char tmp[256];
388         if (!name) {
389                 send_error(s, "Channel not specified");
390                 return 0;
391         }
392         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
393                 send_error(s, "Invalid priority\n");
394                 return 0;
395         }
396         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
397                 send_error(s, "Invalid timeout\n");
398                 return 0;
399         }
400         strncpy(tmp, name, sizeof(tmp) - 1);
401         tech = tmp;
402         data = strchr(tmp, '/');
403         if (!data) {
404                 send_error(s, "Invalid channel\n");
405                 return 0;
406         }
407         *data = '\0';
408         data++;
409         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, NULL );
410         if (!res)
411                 send_ack(s, "Originate successfully queued");
412         else
413                 send_error(s, "Originate failed");
414         return 0;
415 }
416
417 static int action_mailboxstatus(struct mansession *s, struct message *m)
418 {
419         char *mailbox = get_header(m, "Mailbox");
420         if (!mailbox || !strlen(mailbox)) {
421                 send_error(s, "Mailbox not specified");
422                 return 0;
423         }
424         send_ack(s, "Mailbox status will follow");
425         manager_event(EVENT_FLAG_CALL, "MessageWaiting", "Mailbox: %s\r\nWaiting:%d\r\n", mailbox, ast_app_has_voicemail(mailbox));
426         return 0;
427 }
428
429 static int process_message(struct mansession *s, struct message *m)
430 {
431         char action[80];
432         struct manager_action *tmp = first_action;
433
434         strncpy(action, get_header(m, "Action"), sizeof(action));
435
436         if (!strlen(action)) {
437                 send_error(s, "Missing action in request");
438                 return 0;
439         }
440         if (!s->authenticated) {
441                 if (!strcasecmp(action, "Challenge")) {
442                         char *authtype;
443                         authtype = get_header(m, "AuthType");
444                         if (!strcasecmp(authtype, "MD5")) {
445                                 if (!s->challenge || !strlen(s->challenge)) {
446                                         ast_pthread_mutex_lock(&s->lock);
447                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
448                                         ast_pthread_mutex_unlock(&s->lock);
449                                 }
450                                 ast_cli(s->fd, "Response: Success\r\nChallenge: %s\r\n\r\n", s->challenge);
451                                 return 0;
452                         } else {
453                                 send_error(s, "Must specify AuthType");
454                                 return 0;
455                         }
456                 } else if (!strcasecmp(action, "Login")) {
457                         if (authenticate(s, m)) {
458                                 sleep(1);
459                                 send_error(s, "Authentication failed");
460                                 return -1;
461                         } else {
462                                 s->authenticated = 1;
463                                 if (option_verbose > 1) 
464                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
465                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
466                                 send_ack(s, "Authentication accepted");
467                         }
468                 } else 
469                         send_error(s, "Authentication Required");
470         } else {
471                 while( tmp ) {          
472                         if (!strcasecmp(action, tmp->action)) {
473                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
474                                         if (tmp->func(s, m))
475                                                 return -1;
476                                 } else {
477                                         send_error(s, "Permission denied");
478                                 }
479                                 return 0;
480                         }
481                         tmp = tmp->next;
482                 }
483                 send_error(s, "Invalid/unknown command");
484         }
485         return 0;
486 }
487
488 static int get_input(struct mansession *s, char *output)
489 {
490         /* output must have at least sizeof(s->inbuf) space */
491         int res;
492         int x;
493         fd_set fds;
494         for (x=1;x<s->inlen;x++) {
495                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
496                         /* Copy output data up to and including \r\n */
497                         memcpy(output, s->inbuf, x + 1);
498                         /* Add trailing \0 */
499                         output[x+1] = '\0';
500                         /* Move remaining data back to the front */
501                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
502                         s->inlen -= (x + 1);
503                         return 1;
504                 }
505         } 
506         if (s->inlen >= sizeof(s->inbuf) - 1) {
507                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
508                 s->inlen = 0;
509         }
510         FD_ZERO(&fds);
511         FD_SET(s->fd, &fds);
512         res = select(s->fd + 1, &fds, NULL, NULL, NULL);
513         if (res < 0) {
514                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
515         } else if (res > 0) {
516                 ast_pthread_mutex_lock(&s->lock);
517                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
518                 ast_pthread_mutex_unlock(&s->lock);
519                 if (res < 1)
520                         return -1;
521         }
522         s->inlen += res;
523         s->inbuf[s->inlen] = '\0';
524         return 0;
525 }
526
527 static void *session_do(void *data)
528 {
529         struct mansession *s = data;
530         struct message m;
531         int res;
532         
533         ast_pthread_mutex_lock(&s->lock);
534         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
535         ast_pthread_mutex_unlock(&s->lock);
536         memset(&m, 0, sizeof(&m));
537         for (;;) {
538                 res = get_input(s, m.headers[m.hdrcount]);
539                 if (res > 0) {
540                         /* Strip trailing \r\n */
541                         if (strlen(m.headers[m.hdrcount]) < 2)
542                                 continue;
543                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
544                         if (!strlen(m.headers[m.hdrcount])) {
545                                 if (process_message(s, &m))
546                                         break;
547                                 memset(&m, 0, sizeof(&m));
548                         } else if (m.hdrcount < MAX_HEADERS - 1)
549                                 m.hdrcount++;
550                 } else if (res < 0)
551                         break;
552         }
553         if (s->authenticated) {
554                 if (option_verbose > 1) 
555                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
556                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
557         } else {
558                 if (option_verbose > 1)
559                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
560                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
561         }
562         destroy_session(s);
563         return NULL;
564 }
565
566 static void *accept_thread(void *ignore)
567 {
568         int as;
569         struct sockaddr_in sin;
570         int sinlen;
571         struct mansession *s;
572         pthread_attr_t attr;
573
574         pthread_attr_init(&attr);
575         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
576         for (;;) {
577                 sinlen = sizeof(sin);
578                 as = accept(asock, &sin, &sinlen);
579                 if (as < 0) {
580                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
581                         continue;
582                 }
583                 s = malloc(sizeof(struct mansession));
584                 if (!s) {
585                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
586                         continue;
587                 } 
588                 memset(s, 0, sizeof(struct mansession));
589                 memcpy(&s->sin, &sin, sizeof(sin));
590                 ast_pthread_mutex_init(&s->lock);
591                 s->fd = as;
592                 ast_pthread_mutex_lock(&sessionlock);
593                 s->next = sessions;
594                 sessions = s;
595                 ast_pthread_mutex_unlock(&sessionlock);
596                 if (pthread_create(&t, &attr, session_do, s))
597                         destroy_session(s);
598         }
599         pthread_attr_destroy(&attr);
600         return NULL;
601 }
602
603 int manager_event(int category, char *event, char *fmt, ...)
604 {
605         struct mansession *s;
606         char tmp[4096];
607         va_list ap;
608
609         ast_pthread_mutex_lock(&sessionlock);
610         s = sessions;
611         while(s) {
612                 if ((s->readperm & category) == category) {
613                         ast_pthread_mutex_lock(&s->lock);
614                         if (!s->blocking) {
615                                 ast_cli(s->fd, "Event: %s\r\n", event);
616                                 va_start(ap, fmt);
617                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
618                                 va_end(ap);
619                                 write(s->fd, tmp, strlen(tmp));
620                                 ast_cli(s->fd, "\r\n");
621                         }
622                         ast_pthread_mutex_unlock(&s->lock);
623                 }
624                 s = s->next;
625         }
626         ast_pthread_mutex_unlock(&sessionlock);
627         return 0;
628 }
629
630 int ast_manager_unregister( char *action ) {
631         struct manager_action *cur = first_action, *prev = first_action;
632
633         ast_pthread_mutex_lock(&actionlock);
634         while( cur ) {          
635                 if (!strcasecmp(action, cur->action)) {
636                         prev->next = cur->next;
637                         free(cur);
638                         if (option_verbose > 1) 
639                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
640                         ast_pthread_mutex_unlock(&actionlock);
641                         return 0;
642                 }
643                 prev = cur;
644                 cur = cur->next;
645         }
646         ast_pthread_mutex_unlock(&actionlock);
647         return 0;
648 }
649
650 int ast_manager_register( char *action, int auth, 
651         int (*func)(struct mansession *s, struct message *m), char *synopsis)
652 {
653         struct manager_action *cur = first_action, *prev = NULL;
654
655         ast_pthread_mutex_lock(&actionlock);
656         while(cur) { /* Walk the list of actions */
657                 prev = cur; 
658                 cur = cur->next;
659         }
660         cur = malloc( sizeof(struct manager_action) );
661         if( !cur ) {
662                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
663                 ast_pthread_mutex_unlock(&actionlock);
664                 return -1;
665         }
666         strncpy( cur->action, action, 255 );
667         cur->authority = auth;
668         cur->func = func;
669         cur->synopsis = synopsis;
670         cur->next = NULL;
671
672         if( prev ) prev->next = cur;
673         else first_action = cur;
674
675         if (option_verbose > 1) 
676                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
677         ast_pthread_mutex_unlock(&actionlock);
678         return 0;
679 }
680
681 static int registered = 0;
682
683 int init_manager(void)
684 {
685         struct ast_config *cfg;
686         char *val;
687         int oldportno = portno;
688         static struct sockaddr_in ba;
689         int x = 1;
690         if (!registered) {
691                 /* Register default actions */
692                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
693                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
694                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
695                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
696                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
697                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
698                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
699                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
700
701                 ast_cli_register(&show_mancmds_cli);
702                 ast_cli_register(&show_manconn_cli);
703                 registered = 1;
704         }
705         portno = DEFAULT_MANAGER_PORT;
706         cfg = ast_load("manager.conf");
707         if (!cfg) {
708                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
709                 return 0;
710         }
711         memset(&ba, 0, sizeof(ba));
712         val = ast_variable_retrieve(cfg, "general", "enabled");
713         if (val)
714                 enabled = ast_true(val);
715
716         if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
717                 if (sscanf(val, "%d", &portno) != 1) {
718                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
719                         portno = DEFAULT_MANAGER_PORT;
720                 }
721         }
722         
723         ba.sin_family = AF_INET;
724         ba.sin_port = htons(portno);
725         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
726         
727         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
728                 if (!inet_aton(val, &ba.sin_addr)) { 
729                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
730                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
731                 }
732         }
733
734         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
735 #if 0
736                 /* Can't be done yet */
737                 close(asock);
738                 asock = -1;
739 #else
740                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
741 #endif
742         }
743         /* If not enabled, do nothing */
744         if (!enabled)
745                 return 0;
746         if (asock < 0) {
747                 asock = socket(AF_INET, SOCK_STREAM, 0);
748                 if (asock < 0) {
749                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
750                         return -1;
751                 }
752                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
753                 if (bind(asock, &ba, sizeof(ba))) {
754                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
755                         close(asock);
756                         asock = -1;
757                         return -1;
758                 }
759                 if (listen(asock, 2)) {
760                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
761                         close(asock);
762                         asock = -1;
763                         return -1;
764                 }
765                 if (option_verbose)
766                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
767                 pthread_create(&t, NULL, accept_thread, NULL);
768         }
769         ast_destroy(cfg);
770         return 0;
771 }
772
773 int reload_manager(void)
774 {
775         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
776         return init_manager();
777 }