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