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