Allow manager.conf to use port and portno, but log that portno is deprecated.
[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 #include <asterisk/acl.h>
40
41 static int enabled = 0;
42 static int portno = DEFAULT_MANAGER_PORT;
43 static int asock = -1;
44 static pthread_t t;
45 static ast_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
46 static int block_sockets = 0;
47
48 static struct permalias {
49         int num;
50         char *label;
51 } perms[] = {
52         { EVENT_FLAG_SYSTEM, "system" },
53         { EVENT_FLAG_CALL, "call" },
54         { EVENT_FLAG_LOG, "log" },
55         { EVENT_FLAG_VERBOSE, "verbose" },
56         { EVENT_FLAG_COMMAND, "command" },
57         { EVENT_FLAG_AGENT, "agent" },
58         { EVENT_FLAG_USER, "user" },
59         { -1, "all" },
60 };
61
62 static struct mansession *sessions = NULL;
63 static struct manager_action *first_action = NULL;
64 static ast_mutex_t actionlock = AST_MUTEX_INITIALIZER;
65
66 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
67 {
68         /* Try to write string, but wait no more than ms milliseconds
69            before timing out */
70         int res=0;
71         struct timeval tv;
72         fd_set fds;
73         while(len) {
74                 res = write(fd, s, len);
75                 if ((res < 0) && (errno != EAGAIN)) {
76                         return -1;
77                 }
78                 if (res < 0) res = 0;
79                 len -= res;
80                 s += res;
81                 tv.tv_sec = timeoutms / 1000;
82                 tv.tv_usec = timeoutms % 1000;
83                 FD_ZERO(&fds);
84                 FD_SET(fd, &fds);
85                 /* Wait until writable again */
86                 res = select(fd + 1, NULL, &fds, NULL, &tv);
87                 if (res < 1)
88                         return -1;
89         }
90         return res;
91 }
92
93 static int handle_showmancmds(int fd, int argc, char *argv[])
94 {
95         struct manager_action *cur = first_action;
96         char *format = "  %-15.15s  %-45.45s\n";
97
98         ast_mutex_lock(&actionlock);
99         ast_cli(fd, format, "Action", "Synopsis");
100         while(cur) { /* Walk the list of actions */
101                 ast_cli(fd, format, cur->action, cur->synopsis);
102                 cur = cur->next;
103         }
104
105         ast_mutex_unlock(&actionlock);
106         return RESULT_SUCCESS;
107 }
108
109 static int handle_showmanconn(int fd, int argc, char *argv[])
110 {
111         struct mansession *s;
112         char *format = "  %-15.15s  %-15.15s\n";
113         ast_mutex_lock(&sessionlock);
114         s = sessions;
115         ast_cli(fd, format, "Username", "IP Address");
116         while(s) {
117                 ast_cli(fd, format,s->username, inet_ntoa(s->sin.sin_addr));
118                 s = s->next;
119         }
120
121         ast_mutex_unlock(&sessionlock);
122         return RESULT_SUCCESS;
123 }
124
125 static char showmancmds_help[] = 
126 "Usage: show manager commands\n"
127 "       Prints a listing of all the available manager commands.\n";
128
129 static char showmanconn_help[] = 
130 "Usage: show manager connected\n"
131 "       Prints a listing of the users that are connected to the\n"
132 "manager interface.\n";
133
134 static struct ast_cli_entry show_mancmds_cli =
135         { { "show", "manager", "commands", NULL },
136         handle_showmancmds, "Show manager commands", showmancmds_help };
137
138 static struct ast_cli_entry show_manconn_cli =
139         { { "show", "manager", "connected", NULL },
140         handle_showmanconn, "Show connected manager users", showmanconn_help };
141
142 static void destroy_session(struct mansession *s)
143 {
144         struct mansession *cur, *prev = NULL;
145         ast_mutex_lock(&sessionlock);
146         cur = sessions;
147         while(cur) {
148                 if (cur == s)
149                         break;
150                 prev = cur;
151                 cur = cur->next;
152         }
153         if (cur) {
154                 if (prev)
155                         prev->next = cur->next;
156                 else
157                         sessions = cur->next;
158                 if (s->fd > -1)
159                         close(s->fd);
160                 free(s);
161         } else
162                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
163         ast_mutex_unlock(&sessionlock);
164         
165 }
166
167 char *astman_get_header(struct message *m, char *var)
168 {
169         char cmp[80];
170         int x;
171         snprintf(cmp, sizeof(cmp), "%s: ", var);
172         for (x=0;x<m->hdrcount;x++)
173                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
174                         return m->headers[x] + strlen(cmp);
175         return "";
176 }
177
178 void astman_send_error(struct mansession *s, struct message *m, char *error)
179 {
180         char *id = astman_get_header(m,"ActionID");
181         ast_mutex_lock(&s->lock);
182         ast_cli(s->fd, "Response: Error\r\n");
183         if (id && strlen(id))
184                 ast_cli(s->fd, "ActionID: %s\r\n",id);
185         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
186         ast_mutex_unlock(&s->lock);
187 }
188
189 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
190 {
191         char *id = astman_get_header(m,"ActionID");
192         ast_mutex_lock(&s->lock);
193         ast_cli(s->fd, "Response: %s\r\n", resp);
194         if (id && strlen(id))
195                 ast_cli(s->fd, "ActionID: %s\r\n",id);
196         if (msg)
197                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
198         else
199                 ast_cli(s->fd, "\r\n");
200         ast_mutex_unlock(&s->lock);
201 }
202
203 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
204 {
205         astman_send_response(s, m, "Success", msg);
206 }
207
208 static int get_perm(char *instr)
209 {
210         char tmp[256];
211         char *c;
212         int x;
213         int ret = 0;
214         char *stringp=NULL;
215         if (!instr)
216                 return 0;
217         strncpy(tmp, instr, sizeof(tmp) - 1);
218         stringp=tmp;
219         c = strsep(&stringp, ",");
220         while(c) {
221                 for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
222                         if (!strcasecmp(perms[x].label, c)) 
223                                 ret |= perms[x].num;
224                 }
225                 c = strsep(&stringp, ",");
226         }
227         return ret;
228 }
229
230 static int set_eventmask(struct mansession *s, char *eventmask)
231 {
232         if (!eventmask)
233                 return -1;
234         if (!strcasecmp(eventmask, "on") || ast_true(eventmask)) {
235                 ast_mutex_lock(&s->lock);
236                 s->send_events = 1;
237                 ast_mutex_unlock(&s->lock);
238                 return 1;
239         } else if (!strcasecmp(eventmask, "off") || ast_false(eventmask)) {
240                 ast_mutex_lock(&s->lock);
241                 s->send_events = 0;
242                 ast_mutex_unlock(&s->lock);
243                 return 0;
244         }
245         return -1;
246 }
247
248 static int authenticate(struct mansession *s, struct message *m)
249 {
250         struct ast_config *cfg;
251         char *cat;
252         char *user = astman_get_header(m, "Username");
253         char *pass = astman_get_header(m, "Secret");
254         char *authtype = astman_get_header(m, "AuthType");
255         char *key = astman_get_header(m, "Key");
256         char *events = astman_get_header(m, "Events");
257         
258         cfg = ast_load("manager.conf");
259         if (!cfg)
260                 return -1;
261         cat = ast_category_browse(cfg, NULL);
262         while(cat) {
263                 if (strcasecmp(cat, "general")) {
264                         /* This is a user */
265                         if (!strcasecmp(cat, user)) {
266                                 struct ast_variable *v;
267                                 struct ast_ha *ha = NULL;
268                                 char *password = NULL;
269                                 v = ast_variable_browse(cfg, cat);
270                                 while (v) {
271                                         if (!strcasecmp(v->name, "secret")) {
272                                                 password = v->value;
273                                         } else if (!strcasecmp(v->name, "permit") ||
274                                                    !strcasecmp(v->name, "deny")) {
275                                                         ha = ast_append_ha(v->name, v->value, ha);
276                                         }                                               
277                                         v = v->next;
278                                 }
279                                 if (ha && !ast_apply_ha(ha, &(s->sin))) {
280                                         ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
281                                         ast_free_ha(ha);
282                                         ast_destroy(cfg);
283                                         return -1;
284                                 } else if (ha)
285                                         ast_free_ha(ha);
286                                 if (!strcasecmp(authtype, "MD5")) {
287                                         if (key && strlen(key) && s->challenge) {
288                                                 int x;
289                                                 int len=0;
290                                                 char md5key[256] = "";
291                                                 struct MD5Context md5;
292                                                 unsigned char digest[16];
293                                                 MD5Init(&md5);
294                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
295                                                 MD5Update(&md5, password, strlen(password));
296                                                 MD5Final(digest, &md5);
297                                                 for (x=0;x<16;x++)
298                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
299                                                 if (!strcmp(md5key, key))
300                                                         break;
301                                                 else {
302                                                         ast_destroy(cfg);
303                                                         return -1;
304                                                 }
305                                         }
306                                 } else if (password && !strcasecmp(password, pass)) {
307                                         break;
308                                 } else {
309                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
310                                         ast_destroy(cfg);
311                                         return -1;
312                                 }       
313                         }
314                 }
315                 cat = ast_category_browse(cfg, cat);
316         }
317         if (cat) {
318                 strncpy(s->username, cat, sizeof(s->username) - 1);
319                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
320                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
321                 ast_destroy(cfg);
322                 if (events)
323                         set_eventmask(s, events);
324                 return 0;
325         }
326         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
327         ast_destroy(cfg);
328         return -1;
329 }
330
331 static int action_ping(struct mansession *s, struct message *m)
332 {
333         astman_send_response(s, m, "Pong", NULL);
334         return 0;
335 }
336
337 static int action_events(struct mansession *s, struct message *m)
338 {
339         char *mask = astman_get_header(m, "EventMask");
340         int res;
341
342         res = set_eventmask(s, mask);
343         if (res > 0)
344                 astman_send_response(s, m, "Events On", NULL);
345         else if (res == 0)
346                 astman_send_response(s, m, "Events Off", NULL);
347         else
348                 astman_send_response(s, m, "EventMask parse error", NULL);
349         return 0;
350 }
351
352 static int action_logoff(struct mansession *s, struct message *m)
353 {
354         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
355         return -1;
356 }
357
358 static int action_hangup(struct mansession *s, struct message *m)
359 {
360         struct ast_channel *c = NULL;
361         char *name = astman_get_header(m, "Channel");
362         if (!strlen(name)) {
363                 astman_send_error(s, m, "No channel specified");
364                 return 0;
365         }
366         c = ast_channel_walk(NULL);
367         while(c) {
368                 if (!strcasecmp(c->name, name)) {
369                         break;
370                 }
371                 c = ast_channel_walk(c);
372         }
373         if (!c) {
374                 astman_send_error(s, m, "No such channel");
375                 return 0;
376         }
377         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
378         astman_send_ack(s, m, "Channel Hungup");
379         return 0;
380 }
381
382 static int action_status(struct mansession *s, struct message *m)
383 {
384         char *id = astman_get_header(m,"ActionID");
385         char idText[256] = "";
386         struct ast_channel *c;
387         char bridge[256];
388         astman_send_ack(s, m, "Channel status will follow");
389         c = ast_channel_walk(NULL);
390         if (id && strlen(id))
391                 snprintf(idText,256,"ActionID: %s\r\n",id);
392         while(c) {
393                 if (c->bridge)
394                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
395                 else
396                         strcpy(bridge, "");
397                 if (c->pbx) {
398                         ast_cli(s->fd,
399                         "Event: Status\r\n"
400                         "Channel: %s\r\n"
401                         "CallerID: %s\r\n"
402                         "State: %s\r\n"
403                         "Context: %s\r\n"
404                         "Extension: %s\r\n"
405                         "Priority: %d\r\n"
406                         "%s"
407                         "Uniqueid: %s\r\n"
408                         "%s"
409                         "\r\n",
410                         c->name, c->callerid ? c->callerid : "<unknown>", 
411                         ast_state2str(c->_state), c->context,
412                         c->exten, c->priority, bridge, c->uniqueid, idText);
413                 } else {
414                         ast_cli(s->fd,
415                         "Event: Status\r\n"
416                         "Channel: %s\r\n"
417                         "CallerID: %s\r\n"
418                         "State: %s\r\n"
419                         "%s"
420                         "Uniqueid: %s\r\n"
421                         "%s"
422                         "\r\n",
423                         c->name, c->callerid ? c->callerid : "<unknown>", 
424                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
425                 }
426                 c = ast_channel_walk(c);
427         }
428         ast_cli(s->fd,
429         "Event: StatusComplete\r\n"
430         "%s"
431         "\r\n",idText);
432         return 0;
433 }
434
435 static int action_redirect(struct mansession *s, struct message *m)
436 {
437         char *name = astman_get_header(m, "Channel");
438         char *name2 = astman_get_header(m, "ExtraChannel");
439         char *exten = astman_get_header(m, "Exten");
440         char *context = astman_get_header(m, "Context");
441         char *priority = astman_get_header(m, "Priority");
442         int pi = 0;
443         int res;
444         if (!name || !strlen(name)) {
445                 astman_send_error(s, m, "Channel not specified");
446                 return 0;
447         }
448         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
449                 astman_send_error(s, m, "Invalid priority\n");
450                 return 0;
451         }
452         res = ast_async_goto_by_name(name, context, exten, pi);
453         if (!res) {
454                 if (strlen(name2)) {
455                         res = ast_async_goto_by_name(name2, context, exten, pi);
456                         if (!res)
457                                 astman_send_ack(s, m, "Dual Redirect successful");
458                         else
459                                 astman_send_error(s, m, "Secondary redirect failed");
460                 } else
461                         astman_send_ack(s, m, "Redirect successful");
462         } else
463                 astman_send_error(s, m, "Redirect failed");
464         return 0;
465 }
466
467 static int action_command(struct mansession *s, struct message *m)
468 {
469         char *cmd = astman_get_header(m, "Command");
470         ast_mutex_lock(&s->lock);
471         s->blocking = 1;
472         ast_mutex_unlock(&s->lock);
473         ast_cli(s->fd, "Response: Follows\r\n");
474         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
475         ast_cli_command(s->fd, cmd);
476         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
477         ast_mutex_lock(&s->lock);
478         s->blocking = 0;
479         ast_mutex_unlock(&s->lock);
480         return 0;
481 }
482
483 static int action_originate(struct mansession *s, struct message *m)
484 {
485         char *name = astman_get_header(m, "Channel");
486         char *exten = astman_get_header(m, "Exten");
487         char *context = astman_get_header(m, "Context");
488         char *priority = astman_get_header(m, "Priority");
489         char *timeout = astman_get_header(m, "Timeout");
490         char *callerid = astman_get_header(m, "CallerID");
491         char *variable = astman_get_header(m, "Variable");
492         char *account = astman_get_header(m, "Account");
493         char *app = astman_get_header(m, "Application");
494         char *appdata = astman_get_header(m, "Data");
495         char *tech, *data;
496         int pi = 0;
497         int res;
498         int to = 30000;
499         int reason = 0;
500         char tmp[256];
501         if (!name) {
502                 astman_send_error(s, m, "Channel not specified");
503                 return 0;
504         }
505         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
506                 astman_send_error(s, m, "Invalid priority\n");
507                 return 0;
508         }
509         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
510                 astman_send_error(s, m, "Invalid timeout\n");
511                 return 0;
512         }
513         strncpy(tmp, name, sizeof(tmp) - 1);
514         tech = tmp;
515         data = strchr(tmp, '/');
516         if (!data) {
517                 astman_send_error(s, m, "Invalid channel\n");
518                 return 0;
519         }
520         *data = '\0';
521         data++;
522         if (strlen(app)) {
523                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
524         } else {
525                 if (exten && context && pi)
526                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
527                 else {
528                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
529                         return 0;
530                 }
531         }   
532         if (!res)
533                 astman_send_ack(s, m, "Originate successfully queued");
534         else
535                 astman_send_error(s, m, "Originate failed");
536         return 0;
537 }
538
539 static int action_mailboxstatus(struct mansession *s, struct message *m)
540 {
541         char *mailbox = astman_get_header(m, "Mailbox");
542         char *id = astman_get_header(m,"ActionID");
543         char idText[256] = "";
544         if (!mailbox || !strlen(mailbox)) {
545                 astman_send_error(s, m, "Mailbox not specified");
546                 return 0;
547         }
548         if (id && strlen(id))
549                 snprintf(idText,256,"ActionID: %s\r\n",id);
550         ast_cli(s->fd, "Response: Success\r\n"
551                                    "%s"
552                                    "Message: Mailbox Status\r\n"
553                                    "Mailbox: %s\r\n"
554                                    "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
555         return 0;
556 }
557
558 static int action_mailboxcount(struct mansession *s, struct message *m)
559 {
560         char *mailbox = astman_get_header(m, "Mailbox");
561         char *id = astman_get_header(m,"ActionID");
562         char idText[256] = "";
563         int newmsgs = 0, oldmsgs = 0;
564         if (!mailbox || !strlen(mailbox)) {
565                 astman_send_error(s, m, "Mailbox not specified");
566                 return 0;
567         }
568         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
569         if (id && strlen(id)) {
570                 snprintf(idText,256,"ActionID: %s\r\n",id);
571         }
572         ast_cli(s->fd, "Response: Success\r\n"
573                                    "%s"
574                                    "Message: Mailbox Message Count\r\n"
575                                    "Mailbox: %s\r\n"
576                                    "NewMessages: %d\r\n"
577                                    "OldMessages: %d\r\n" 
578                                    "\r\n",
579                                     idText,mailbox, newmsgs, oldmsgs);
580         return 0;
581 }
582
583 static int action_extensionstate(struct mansession *s, struct message *m)
584 {
585         char *exten = astman_get_header(m, "Exten");
586         char *context = astman_get_header(m, "Context");
587         char *id = astman_get_header(m,"ActionID");
588         char idText[256] = "";
589         char hint[256] = "";
590         int status;
591         if (!exten || !strlen(exten)) {
592                 astman_send_error(s, m, "Extension not specified");
593                 return 0;
594         }
595         if (!context || !strlen(context))
596                 context = "default";
597         status = ast_extension_state(NULL, context, exten);
598         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
599         if (id && strlen(id)) {
600                 snprintf(idText,256,"ActionID: %s\r\n",id);
601         }
602         ast_cli(s->fd, "Response: Success\r\n"
603                                    "%s"
604                                    "Message: Extension Status\r\n"
605                                    "Exten: %s\r\n"
606                                    "Context: %s\r\n"
607                                    "Hint: %s\r\n"
608                                    "Status: %d\r\n\r\n",
609                                    idText,exten, context, hint, status);
610         return 0;
611 }
612
613 static int action_timeout(struct mansession *s, struct message *m)
614 {
615         struct ast_channel *c = NULL;
616         char *name = astman_get_header(m, "Channel");
617         int timeout = atoi(astman_get_header(m, "Timeout"));
618         if (!strlen(name)) {
619                 astman_send_error(s, m, "No channel specified");
620                 return 0;
621         }
622         if (!timeout) {
623                 astman_send_error(s, m, "No timeout specified");
624                 return 0;
625         }
626         c = ast_channel_walk(NULL);
627         while(c) {
628                 if (!strcasecmp(c->name, name)) {
629                         break;
630                 }
631                 c = ast_channel_walk(c);
632         }
633         if (!c) {
634                 astman_send_error(s, m, "No such channel");
635                 return 0;
636         }
637         ast_channel_setwhentohangup(c, timeout);
638         astman_send_ack(s, m, "Timeout Set");
639         return 0;
640 }
641
642 static int process_message(struct mansession *s, struct message *m)
643 {
644         char action[80];
645         struct manager_action *tmp = first_action;
646         char *id = astman_get_header(m,"ActionID");
647         char idText[256] = "";
648
649         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
650         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
651
652         if (!strlen(action)) {
653                 astman_send_error(s, m, "Missing action in request");
654                 return 0;
655         }
656         if (id && strlen(id)) {
657                 snprintf(idText,256,"ActionID: %s\r\n",id);
658         }
659         if (!s->authenticated) {
660                 if (!strcasecmp(action, "Challenge")) {
661                         char *authtype;
662                         authtype = astman_get_header(m, "AuthType");
663                         if (!strcasecmp(authtype, "MD5")) {
664                                 if (!s->challenge || !strlen(s->challenge)) {
665                                         ast_mutex_lock(&s->lock);
666                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
667                                         ast_mutex_unlock(&s->lock);
668                                 }
669                                 ast_cli(s->fd, "Response: Success\r\n"
670                                                 "%s"
671                                                 "Challenge: %s\r\n\r\n",
672                                                 idText,s->challenge);
673                                 return 0;
674                         } else {
675                                 astman_send_error(s, m, "Must specify AuthType");
676                                 return 0;
677                         }
678                 } else if (!strcasecmp(action, "Login")) {
679                         if (authenticate(s, m)) {
680                                 sleep(1);
681                                 astman_send_error(s, m, "Authentication failed");
682                                 return -1;
683                         } else {
684                                 s->authenticated = 1;
685                                 if (option_verbose > 1) 
686                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
687                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
688                                 astman_send_ack(s, m, "Authentication accepted");
689                         }
690                 } else if (!strcasecmp(action, "Logoff")) {
691                         astman_send_ack(s, m, "See ya");
692                         return -1;
693                 } else
694                         astman_send_error(s, m, "Authentication Required");
695         } else {
696                 while( tmp ) {          
697                         if (!strcasecmp(action, tmp->action)) {
698                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
699                                         if (tmp->func(s, m))
700                                                 return -1;
701                                 } else {
702                                         astman_send_error(s, m, "Permission denied");
703                                 }
704                                 return 0;
705                         }
706                         tmp = tmp->next;
707                 }
708                 astman_send_error(s, m, "Invalid/unknown command");
709         }
710         return 0;
711 }
712
713 static int get_input(struct mansession *s, char *output)
714 {
715         /* output must have at least sizeof(s->inbuf) space */
716         int res;
717         int x;
718         fd_set fds;
719         for (x=1;x<s->inlen;x++) {
720                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
721                         /* Copy output data up to and including \r\n */
722                         memcpy(output, s->inbuf, x + 1);
723                         /* Add trailing \0 */
724                         output[x+1] = '\0';
725                         /* Move remaining data back to the front */
726                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
727                         s->inlen -= (x + 1);
728                         return 1;
729                 }
730         } 
731         if (s->inlen >= sizeof(s->inbuf) - 1) {
732                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
733                 s->inlen = 0;
734         }
735         FD_ZERO(&fds);
736         FD_SET(s->fd, &fds);
737         res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);
738         if (res < 0) {
739                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
740         } else if (res > 0) {
741                 ast_mutex_lock(&s->lock);
742                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
743                 ast_mutex_unlock(&s->lock);
744                 if (res < 1)
745                         return -1;
746         }
747         s->inlen += res;
748         s->inbuf[s->inlen] = '\0';
749         return 0;
750 }
751
752 static void *session_do(void *data)
753 {
754         struct mansession *s = data;
755         struct message m;
756         int res;
757         
758         ast_mutex_lock(&s->lock);
759         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
760         ast_mutex_unlock(&s->lock);
761         memset(&m, 0, sizeof(&m));
762         for (;;) {
763                 res = get_input(s, m.headers[m.hdrcount]);
764                 if (res > 0) {
765                         /* Strip trailing \r\n */
766                         if (strlen(m.headers[m.hdrcount]) < 2)
767                                 continue;
768                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
769                         if (!strlen(m.headers[m.hdrcount])) {
770                                 if (process_message(s, &m))
771                                         break;
772                                 memset(&m, 0, sizeof(&m));
773                         } else if (m.hdrcount < MAX_HEADERS - 1)
774                                 m.hdrcount++;
775                 } else if (res < 0)
776                         break;
777         }
778         if (s->authenticated) {
779                 if (option_verbose > 1) 
780                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
781                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
782         } else {
783                 if (option_verbose > 1)
784                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
785                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
786         }
787         destroy_session(s);
788         return NULL;
789 }
790
791 static void *accept_thread(void *ignore)
792 {
793         int as;
794         struct sockaddr_in sin;
795         int sinlen;
796         struct mansession *s;
797         struct protoent *p;
798         int arg = 1;
799         int flags;
800         pthread_attr_t attr;
801
802         pthread_attr_init(&attr);
803         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
804
805         for (;;) {
806                 sinlen = sizeof(sin);
807                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
808                 if (as < 0) {
809                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
810                         continue;
811                 }
812                 p = getprotobyname("tcp");
813                 if( p ) {
814                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
815                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
816                         }
817                 }
818                 s = malloc(sizeof(struct mansession));
819                 if (!s) {
820                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
821                         continue;
822                 } 
823                 memset(s, 0, sizeof(struct mansession));
824                 memcpy(&s->sin, &sin, sizeof(sin));
825
826                 if(! block_sockets) {
827                         /* For safety, make sure socket is non-blocking */
828                         flags = fcntl(as, F_GETFL);
829                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
830                 }
831                 ast_mutex_init(&s->lock);
832                 s->fd = as;
833                 s->send_events = 1;
834                 ast_mutex_lock(&sessionlock);
835                 s->next = sessions;
836                 sessions = s;
837                 ast_mutex_unlock(&sessionlock);
838                 if (pthread_create(&t, &attr, session_do, s))
839                         destroy_session(s);
840         }
841         pthread_attr_destroy(&attr);
842         return NULL;
843 }
844
845 int manager_event(int category, char *event, char *fmt, ...)
846 {
847         struct mansession *s;
848         char tmp[4096];
849         va_list ap;
850
851         ast_mutex_lock(&sessionlock);
852         s = sessions;
853         while(s) {
854                 if (((s->readperm & category) == category) && s->send_events) {
855                         ast_mutex_lock(&s->lock);
856                         if (!s->blocking) {
857                                 ast_cli(s->fd, "Event: %s\r\n", event);
858                                 va_start(ap, fmt);
859                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
860                                 va_end(ap);
861                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
862                                 ast_cli(s->fd, "\r\n");
863                         }
864                         ast_mutex_unlock(&s->lock);
865                 }
866                 s = s->next;
867         }
868         ast_mutex_unlock(&sessionlock);
869         return 0;
870 }
871
872 int ast_manager_unregister( char *action ) {
873         struct manager_action *cur = first_action, *prev = first_action;
874
875         ast_mutex_lock(&actionlock);
876         while( cur ) {          
877                 if (!strcasecmp(action, cur->action)) {
878                         prev->next = cur->next;
879                         free(cur);
880                         if (option_verbose > 1) 
881                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
882                         ast_mutex_unlock(&actionlock);
883                         return 0;
884                 }
885                 prev = cur;
886                 cur = cur->next;
887         }
888         ast_mutex_unlock(&actionlock);
889         return 0;
890 }
891
892 static int manager_state_cb(char *context, char *exten, int state, void *data)
893 {
894         /* Notify managers of change */
895         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
896         return 0;
897 }
898
899 int ast_manager_register( char *action, int auth, 
900         int (*func)(struct mansession *s, struct message *m), char *synopsis)
901 {
902         struct manager_action *cur = first_action, *prev = NULL;
903
904         ast_mutex_lock(&actionlock);
905         while(cur) { /* Walk the list of actions */
906                 if (!strcasecmp(cur->action, action)) {
907                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", action);
908                         ast_mutex_unlock(&actionlock);
909                         return -1;
910                 }
911                 prev = cur; 
912                 cur = cur->next;
913         }
914         cur = malloc( sizeof(struct manager_action) );
915         if( !cur ) {
916                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
917                 ast_mutex_unlock(&actionlock);
918                 return -1;
919         }
920         strncpy( cur->action, action, 255 );
921         cur->authority = auth;
922         cur->func = func;
923         cur->synopsis = synopsis;
924         cur->next = NULL;
925
926         if( prev ) prev->next = cur;
927         else first_action = cur;
928
929         if (option_verbose > 1) 
930                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
931         ast_mutex_unlock(&actionlock);
932         return 0;
933 }
934
935 static int registered = 0;
936
937 int init_manager(void)
938 {
939         struct ast_config *cfg;
940         char *val;
941         int oldportno = portno;
942         static struct sockaddr_in ba;
943         int x = 1;
944         if (!registered) {
945                 /* Register default actions */
946                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
947                 ast_manager_register( "Events", 0, action_events, "Contol Event Flow" );
948                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
949                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
950                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
951                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
952                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
953                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
954                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
955                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
956                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
957                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
958
959                 ast_cli_register(&show_mancmds_cli);
960                 ast_cli_register(&show_manconn_cli);
961                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
962                 registered = 1;
963         }
964         portno = DEFAULT_MANAGER_PORT;
965         cfg = ast_load("manager.conf");
966         if (!cfg) {
967                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
968                 return 0;
969         }
970         memset(&ba, 0, sizeof(ba));
971         val = ast_variable_retrieve(cfg, "general", "enabled");
972         if (val)
973                 enabled = ast_true(val);
974
975         val = ast_variable_retrieve(cfg, "general", "block-sockets");
976         if(val)
977                 block_sockets = ast_true(val);
978
979         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
980                 if (sscanf(val, "%d", &portno) != 1) {
981                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
982                         portno = DEFAULT_MANAGER_PORT;
983                 }
984         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
985                 if (sscanf(val, "%d", &portno) != 1) {
986                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
987                         portno = DEFAULT_MANAGER_PORT;
988                 }
989                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
990         }
991         
992         ba.sin_family = AF_INET;
993         ba.sin_port = htons(portno);
994         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
995         
996         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
997                 if (!inet_aton(val, &ba.sin_addr)) { 
998                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
999                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1000                 }
1001         }
1002         
1003         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1004 #if 0
1005                 /* Can't be done yet */
1006                 close(asock);
1007                 asock = -1;
1008 #else
1009                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1010 #endif
1011         }
1012         ast_destroy(cfg);
1013         
1014         /* If not enabled, do nothing */
1015         if (!enabled) {
1016                 return 0;
1017         }
1018         if (asock < 0) {
1019                 asock = socket(AF_INET, SOCK_STREAM, 0);
1020                 if (asock < 0) {
1021                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1022                         return -1;
1023                 }
1024                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1025                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1026                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1027                         close(asock);
1028                         asock = -1;
1029                         return -1;
1030                 }
1031                 if (listen(asock, 2)) {
1032                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1033                         close(asock);
1034                         asock = -1;
1035                         return -1;
1036                 }
1037                 if (option_verbose)
1038                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1039                 pthread_create(&t, NULL, accept_thread, NULL);
1040         }
1041         return 0;
1042 }
1043
1044 int reload_manager(void)
1045 {
1046         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1047         return init_manager();
1048 }