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