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