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