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