cbb3c626465874e806ebbb7b0f5b294958d08ac0
[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 char *astman_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 void astman_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 void astman_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 void astman_send_ack(struct mansession *s, char *msg)
166 {
167         astman_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 = astman_get_header(m, "Username");
197         char *pass = astman_get_header(m, "Secret");
198         char *authtype = astman_get_header(m, "AuthType");
199         char *key = astman_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         astman_send_response(s, "Pong", NULL);
256         return 0;
257 }
258
259 static int action_logoff(struct mansession *s, struct message *m)
260 {
261         astman_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 = astman_get_header(m, "Channel");
269         if (!strlen(name)) {
270                 astman_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                 astman_send_error(s, "No such channel");
282                 return 0;
283         }
284         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
285         astman_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         astman_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 = astman_get_header(m, "Channel");
333         char *name2 = astman_get_header(m, "ExtraChannel");
334         char *exten = astman_get_header(m, "Exten");
335         char *context = astman_get_header(m, "Context");
336         char *priority = astman_get_header(m, "Priority");
337         int pi = 0;
338         int res;
339         if (!name || !strlen(name)) {
340                 astman_send_error(s, "Channel not specified");
341                 return 0;
342         }
343         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
344                 astman_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                                 astman_send_ack(s, "Dual Redirect successful");
353                         else
354                                 astman_send_error(s, "Secondary redirect failed");
355                 } else
356                         astman_send_ack(s, "Redirect successful");
357         } else
358                 astman_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 = astman_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 = astman_get_header(m, "Channel");
380         char *exten = astman_get_header(m, "Exten");
381         char *context = astman_get_header(m, "Context");
382         char *priority = astman_get_header(m, "Priority");
383         char *timeout = astman_get_header(m, "Timeout");
384         char *callerid = astman_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                 astman_send_error(s, "Channel not specified");
393                 return 0;
394         }
395         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
396                 astman_send_error(s, "Invalid priority\n");
397                 return 0;
398         }
399         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
400                 astman_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                 astman_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                 astman_send_ack(s, "Originate successfully queued");
415         else
416                 astman_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 = astman_get_header(m, "Mailbox");
423         if (!mailbox || !strlen(mailbox)) {
424                 astman_send_error(s, "Mailbox not specified");
425                 return 0;
426         }
427         astman_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 action_extensionstate(struct mansession *s, struct message *m)
433 {
434         char *exten = astman_get_header(m, "Exten");
435         char *context = astman_get_header(m, "Context");
436         int status;
437         if (!exten || !strlen(exten)) {
438                 astman_send_error(s, "Extension not specified");
439                 return 0;
440         }
441         if (!context || !strlen(context))
442                 context = "default";
443         astman_send_ack(s, "Extension status will follow");
444         status = ast_extension_state(NULL, context, exten);
445         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, status);
446         return 0;
447 }
448
449 static int process_message(struct mansession *s, struct message *m)
450 {
451         char action[80];
452         struct manager_action *tmp = first_action;
453
454         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
455         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
456
457         if (!strlen(action)) {
458                 astman_send_error(s, "Missing action in request");
459                 return 0;
460         }
461         if (!s->authenticated) {
462                 if (!strcasecmp(action, "Challenge")) {
463                         char *authtype;
464                         authtype = astman_get_header(m, "AuthType");
465                         if (!strcasecmp(authtype, "MD5")) {
466                                 if (!s->challenge || !strlen(s->challenge)) {
467                                         ast_pthread_mutex_lock(&s->lock);
468                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
469                                         ast_pthread_mutex_unlock(&s->lock);
470                                 }
471                                 ast_cli(s->fd, "Response: Success\r\nChallenge: %s\r\n\r\n", s->challenge);
472                                 return 0;
473                         } else {
474                                 astman_send_error(s, "Must specify AuthType");
475                                 return 0;
476                         }
477                 } else if (!strcasecmp(action, "Login")) {
478                         if (authenticate(s, m)) {
479                                 sleep(1);
480                                 astman_send_error(s, "Authentication failed");
481                                 return -1;
482                         } else {
483                                 s->authenticated = 1;
484                                 if (option_verbose > 1) 
485                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
486                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
487                                 astman_send_ack(s, "Authentication accepted");
488                         }
489                 } else 
490                         astman_send_error(s, "Authentication Required");
491         } else {
492                 while( tmp ) {          
493                         if (!strcasecmp(action, tmp->action)) {
494                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
495                                         if (tmp->func(s, m))
496                                                 return -1;
497                                 } else {
498                                         astman_send_error(s, "Permission denied");
499                                 }
500                                 return 0;
501                         }
502                         tmp = tmp->next;
503                 }
504                 astman_send_error(s, "Invalid/unknown command");
505         }
506         return 0;
507 }
508
509 static int get_input(struct mansession *s, char *output)
510 {
511         /* output must have at least sizeof(s->inbuf) space */
512         int res;
513         int x;
514         fd_set fds;
515         for (x=1;x<s->inlen;x++) {
516                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
517                         /* Copy output data up to and including \r\n */
518                         memcpy(output, s->inbuf, x + 1);
519                         /* Add trailing \0 */
520                         output[x+1] = '\0';
521                         /* Move remaining data back to the front */
522                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
523                         s->inlen -= (x + 1);
524                         return 1;
525                 }
526         } 
527         if (s->inlen >= sizeof(s->inbuf) - 1) {
528                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
529                 s->inlen = 0;
530         }
531         FD_ZERO(&fds);
532         FD_SET(s->fd, &fds);
533         res = select(s->fd + 1, &fds, NULL, NULL, NULL);
534         if (res < 0) {
535                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
536         } else if (res > 0) {
537                 ast_pthread_mutex_lock(&s->lock);
538                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
539                 ast_pthread_mutex_unlock(&s->lock);
540                 if (res < 1)
541                         return -1;
542         }
543         s->inlen += res;
544         s->inbuf[s->inlen] = '\0';
545         return 0;
546 }
547
548 static void *session_do(void *data)
549 {
550         struct mansession *s = data;
551         struct message m;
552         int res;
553         
554         ast_pthread_mutex_lock(&s->lock);
555         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
556         ast_pthread_mutex_unlock(&s->lock);
557         memset(&m, 0, sizeof(&m));
558         for (;;) {
559                 res = get_input(s, m.headers[m.hdrcount]);
560                 if (res > 0) {
561                         /* Strip trailing \r\n */
562                         if (strlen(m.headers[m.hdrcount]) < 2)
563                                 continue;
564                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
565                         if (!strlen(m.headers[m.hdrcount])) {
566                                 if (process_message(s, &m))
567                                         break;
568                                 memset(&m, 0, sizeof(&m));
569                         } else if (m.hdrcount < MAX_HEADERS - 1)
570                                 m.hdrcount++;
571                 } else if (res < 0)
572                         break;
573         }
574         if (s->authenticated) {
575                 if (option_verbose > 1) 
576                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
577                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
578         } else {
579                 if (option_verbose > 1)
580                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
581                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
582         }
583         destroy_session(s);
584         return NULL;
585 }
586
587 static void *accept_thread(void *ignore)
588 {
589         int as;
590         struct sockaddr_in sin;
591         int sinlen;
592         struct mansession *s;
593         struct protoent *p;
594         int arg = 1;
595         pthread_attr_t attr;
596
597         pthread_attr_init(&attr);
598         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
599
600         for (;;) {
601                 sinlen = sizeof(sin);
602                 as = accept(asock, &sin, &sinlen);
603                 if (as < 0) {
604                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
605                         continue;
606                 }
607                 p = getprotobyname("tcp");
608                 if( p ) {
609                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
610                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
611                         }
612                 }
613                 s = malloc(sizeof(struct mansession));
614                 if (!s) {
615                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
616                         continue;
617                 } 
618                 memset(s, 0, sizeof(struct mansession));
619                 memcpy(&s->sin, &sin, sizeof(sin));
620                 ast_pthread_mutex_init(&s->lock);
621                 s->fd = as;
622                 ast_pthread_mutex_lock(&sessionlock);
623                 s->next = sessions;
624                 sessions = s;
625                 ast_pthread_mutex_unlock(&sessionlock);
626                 if (pthread_create(&t, &attr, session_do, s))
627                         destroy_session(s);
628         }
629         pthread_attr_destroy(&attr);
630         return NULL;
631 }
632
633 int manager_event(int category, char *event, char *fmt, ...)
634 {
635         struct mansession *s;
636         char tmp[4096];
637         va_list ap;
638
639         ast_pthread_mutex_lock(&sessionlock);
640         s = sessions;
641         while(s) {
642                 if ((s->readperm & category) == category) {
643                         ast_pthread_mutex_lock(&s->lock);
644                         if (!s->blocking) {
645                                 ast_cli(s->fd, "Event: %s\r\n", event);
646                                 va_start(ap, fmt);
647                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
648                                 va_end(ap);
649                                 write(s->fd, tmp, strlen(tmp));
650                                 ast_cli(s->fd, "\r\n");
651                         }
652                         ast_pthread_mutex_unlock(&s->lock);
653                 }
654                 s = s->next;
655         }
656         ast_pthread_mutex_unlock(&sessionlock);
657         return 0;
658 }
659
660 int ast_manager_unregister( char *action ) {
661         struct manager_action *cur = first_action, *prev = first_action;
662
663         ast_pthread_mutex_lock(&actionlock);
664         while( cur ) {          
665                 if (!strcasecmp(action, cur->action)) {
666                         prev->next = cur->next;
667                         free(cur);
668                         if (option_verbose > 1) 
669                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
670                         ast_pthread_mutex_unlock(&actionlock);
671                         return 0;
672                 }
673                 prev = cur;
674                 cur = cur->next;
675         }
676         ast_pthread_mutex_unlock(&actionlock);
677         return 0;
678 }
679
680 static int manager_state_cb(char *context, char *exten, int state, void *data)
681 {
682         /* Notify managers of change */
683         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
684         return 0;
685 }
686
687 int ast_manager_register( char *action, int auth, 
688         int (*func)(struct mansession *s, struct message *m), char *synopsis)
689 {
690         struct manager_action *cur = first_action, *prev = NULL;
691
692         ast_pthread_mutex_lock(&actionlock);
693         while(cur) { /* Walk the list of actions */
694                 prev = cur; 
695                 cur = cur->next;
696         }
697         cur = malloc( sizeof(struct manager_action) );
698         if( !cur ) {
699                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
700                 ast_pthread_mutex_unlock(&actionlock);
701                 return -1;
702         }
703         strncpy( cur->action, action, 255 );
704         cur->authority = auth;
705         cur->func = func;
706         cur->synopsis = synopsis;
707         cur->next = NULL;
708
709         if( prev ) prev->next = cur;
710         else first_action = cur;
711
712         if (option_verbose > 1) 
713                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
714         ast_pthread_mutex_unlock(&actionlock);
715         return 0;
716 }
717
718 static int registered = 0;
719
720 int init_manager(void)
721 {
722         struct ast_config *cfg;
723         char *val;
724         int oldportno = portno;
725         static struct sockaddr_in ba;
726         int x = 1;
727         if (!registered) {
728                 /* Register default actions */
729                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
730                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
731                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
732                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
733                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
734                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
735                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
736                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
737                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
738
739                 ast_cli_register(&show_mancmds_cli);
740                 ast_cli_register(&show_manconn_cli);
741                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
742                 registered = 1;
743         }
744         portno = DEFAULT_MANAGER_PORT;
745         cfg = ast_load("manager.conf");
746         if (!cfg) {
747                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
748                 return 0;
749         }
750         memset(&ba, 0, sizeof(ba));
751         val = ast_variable_retrieve(cfg, "general", "enabled");
752         if (val)
753                 enabled = ast_true(val);
754
755         if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
756                 if (sscanf(val, "%d", &portno) != 1) {
757                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
758                         portno = DEFAULT_MANAGER_PORT;
759                 }
760         }
761         
762         ba.sin_family = AF_INET;
763         ba.sin_port = htons(portno);
764         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
765         
766         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
767                 if (!inet_aton(val, &ba.sin_addr)) { 
768                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
769                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
770                 }
771         }
772
773         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
774 #if 0
775                 /* Can't be done yet */
776                 close(asock);
777                 asock = -1;
778 #else
779                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
780 #endif
781         }
782         /* If not enabled, do nothing */
783         if (!enabled)
784                 return 0;
785         if (asock < 0) {
786                 asock = socket(AF_INET, SOCK_STREAM, 0);
787                 if (asock < 0) {
788                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
789                         return -1;
790                 }
791                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
792                 if (bind(asock, &ba, sizeof(ba))) {
793                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
794                         close(asock);
795                         asock = -1;
796                         return -1;
797                 }
798                 if (listen(asock, 2)) {
799                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
800                         close(asock);
801                         asock = -1;
802                         return -1;
803                 }
804                 if (option_verbose)
805                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
806                 pthread_create(&t, NULL, accept_thread, NULL);
807         }
808         ast_destroy(cfg);
809         return 0;
810 }
811
812 int reload_manager(void)
813 {
814         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
815         return init_manager();
816 }