8017da7d075c4eaa3fb688797f2092e1fbd894f7
[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_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_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_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_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_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_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                         in->idtext, in->tech, in->data, in->context, in->exten);
845         else
846                 manager_event(EVENT_FLAG_CALL,
847                         "OriginateFailure",
848                         "%s"
849                         "Channel: %s/%s\r\n"
850                         "Context: %s\r\n"
851                         "Exten: %s\r\n",
852                         in->idtext, in->tech, in->data, in->context, in->exten);
853
854         free(in);
855         return NULL;
856 }
857
858 static char mandescr_originate[] = 
859 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
860 "  Application/Data\n"
861 "Variables: (Names marked with * are required)\n"
862 "       *Channel: Channel name to call\n"
863 "       Exten: Extension to use (requires 'Context' and 'Priority')\n"
864 "       Context: Context to use (requires 'Exten' and 'Priority')\n"
865 "       Priority: Priority to use (requires 'Exten' and 'Context')\n"
866 "       Application: Application to use\n"
867 "       Data: Data to use (requires 'Application')\n"
868 "       Timeout: How long to wait for call to be answered (in ms)\n"
869 "       CallerID: Caller ID to be set on the outgoing channel\n"
870 "       Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
871 "       Account: Account code\n"
872 "       Async: Set to 'true' for fast origination\n";
873
874 static int action_originate(struct mansession *s, struct message *m)
875 {
876         char *name = astman_get_header(m, "Channel");
877         char *exten = astman_get_header(m, "Exten");
878         char *context = astman_get_header(m, "Context");
879         char *priority = astman_get_header(m, "Priority");
880         char *timeout = astman_get_header(m, "Timeout");
881         char *callerid = astman_get_header(m, "CallerID");
882     char *variable = astman_get_header(m, "Variable");
883     char *account = astman_get_header(m, "Account");
884         char *app = astman_get_header(m, "Application");
885         char *appdata = astman_get_header(m, "Data");
886         char *async = astman_get_header(m, "Async");
887         char *id = astman_get_header(m, "ActionID");
888         char *tech, *data;
889         char *l=NULL, *n=NULL;
890         int pi = 0;
891         int res;
892         int to = 30000;
893         int reason = 0;
894         char tmp[256];
895         char tmp2[256]="";
896         
897         pthread_t th;
898         pthread_attr_t attr;
899         if (!name) {
900                 astman_send_error(s, m, "Channel not specified");
901                 return 0;
902         }
903         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
904                 astman_send_error(s, m, "Invalid priority\n");
905                 return 0;
906         }
907         if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
908                 astman_send_error(s, m, "Invalid timeout\n");
909                 return 0;
910         }
911         strncpy(tmp, name, sizeof(tmp) - 1);
912         tech = tmp;
913         data = strchr(tmp, '/');
914         if (!data) {
915                 astman_send_error(s, m, "Invalid channel\n");
916                 return 0;
917         }
918         *data = '\0';
919         data++;
920         strncpy(tmp2, callerid, sizeof(tmp2) - 1);
921         ast_callerid_parse(tmp2, &n, &l);
922         if (n) {
923                 if (ast_strlen_zero(n))
924                         n = NULL;
925         }
926         if (l) {
927                 ast_shrink_phone_number(l);
928                 if (ast_strlen_zero(l))
929                         l = NULL;
930         }
931         if (ast_true(async)) {
932                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
933                 if (!fast) {
934                         res = -1;
935                 } else {
936                         memset(fast, 0, sizeof(struct fast_originate_helper));
937                         if (id && !ast_strlen_zero(id))
938                                 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
939                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
940                         strncpy(fast->data, data, sizeof(fast->data) - 1);
941                         strncpy(fast->app, app, sizeof(fast->app) - 1);
942                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
943                         if (l)
944                                 strncpy(fast->cid_num, l, sizeof(fast->cid_num) - 1);
945                         if (n)
946                                 strncpy(fast->cid_name, n, sizeof(fast->cid_name) - 1);
947                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
948                         strncpy(fast->account, account, sizeof(fast->account) - 1);
949                         strncpy(fast->context, context, sizeof(fast->context) - 1);
950                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
951                         fast->timeout = to;
952                         fast->priority = pi;
953                         pthread_attr_init(&attr);
954                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
955                         if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
956                                 res = -1;
957                         } else {
958                                 res = 0;
959                         }
960                 }
961         } else if (!ast_strlen_zero(app)) {
962                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, l, n, variable, account);
963         } else {
964                 if (exten && context && pi)
965                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, l, n, variable, account);
966                 else {
967                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
968                         return 0;
969                 }
970         }   
971         if (!res)
972                 astman_send_ack(s, m, "Originate successfully queued");
973         else
974                 astman_send_error(s, m, "Originate failed");
975         return 0;
976 }
977
978 static int action_mailboxstatus(struct mansession *s, struct message *m)
979 {
980         char *mailbox = astman_get_header(m, "Mailbox");
981         char *id = astman_get_header(m,"ActionID");
982         char idText[256] = "";
983         int ret;
984         if (!mailbox || ast_strlen_zero(mailbox)) {
985                 astman_send_error(s, m, "Mailbox not specified");
986                 return 0;
987         }
988         if (id && !ast_strlen_zero(id))
989                 snprintf(idText,256,"ActionID: %s\r\n",id);
990         ret = ast_app_has_voicemail(mailbox, NULL);
991         ast_mutex_lock(&s->lock);
992         ast_cli(s->fd, "Response: Success\r\n"
993                                    "%s"
994                                    "Message: Mailbox Status\r\n"
995                                    "Mailbox: %s\r\n"
996                                    "Waiting: %d\r\n\r\n", idText, mailbox, ret);
997         ast_mutex_unlock(&s->lock);
998         return 0;
999 }
1000
1001 static int action_mailboxcount(struct mansession *s, struct message *m)
1002 {
1003         char *mailbox = astman_get_header(m, "Mailbox");
1004         char *id = astman_get_header(m,"ActionID");
1005         char idText[256] = "";
1006         int newmsgs = 0, oldmsgs = 0;
1007         if (!mailbox || ast_strlen_zero(mailbox)) {
1008                 astman_send_error(s, m, "Mailbox not specified");
1009                 return 0;
1010         }
1011         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
1012         if (id && !ast_strlen_zero(id)) {
1013                 snprintf(idText,256,"ActionID: %s\r\n",id);
1014         }
1015         ast_mutex_lock(&s->lock);
1016         ast_cli(s->fd, "Response: Success\r\n"
1017                                    "%s"
1018                                    "Message: Mailbox Message Count\r\n"
1019                                    "Mailbox: %s\r\n"
1020                                    "NewMessages: %d\r\n"
1021                                    "OldMessages: %d\r\n" 
1022                                    "\r\n",
1023                                     idText,mailbox, newmsgs, oldmsgs);
1024         ast_mutex_unlock(&s->lock);
1025         return 0;
1026 }
1027
1028 static int action_extensionstate(struct mansession *s, struct message *m)
1029 {
1030         char *exten = astman_get_header(m, "Exten");
1031         char *context = astman_get_header(m, "Context");
1032         char *id = astman_get_header(m,"ActionID");
1033         char idText[256] = "";
1034         char hint[256] = "";
1035         int status;
1036         if (!exten || ast_strlen_zero(exten)) {
1037                 astman_send_error(s, m, "Extension not specified");
1038                 return 0;
1039         }
1040         if (!context || ast_strlen_zero(context))
1041                 context = "default";
1042         status = ast_extension_state(NULL, context, exten);
1043         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
1044         if (id && !ast_strlen_zero(id)) {
1045                 snprintf(idText,256,"ActionID: %s\r\n",id);
1046         }
1047         ast_mutex_lock(&s->lock);
1048         ast_cli(s->fd, "Response: Success\r\n"
1049                                    "%s"
1050                                    "Message: Extension Status\r\n"
1051                                    "Exten: %s\r\n"
1052                                    "Context: %s\r\n"
1053                                    "Hint: %s\r\n"
1054                                    "Status: %d\r\n\r\n",
1055                                    idText,exten, context, hint, status);
1056         ast_mutex_unlock(&s->lock);
1057         return 0;
1058 }
1059
1060 static int action_timeout(struct mansession *s, struct message *m)
1061 {
1062         struct ast_channel *c = NULL;
1063         char *name = astman_get_header(m, "Channel");
1064         int timeout = atoi(astman_get_header(m, "Timeout"));
1065         if (ast_strlen_zero(name)) {
1066                 astman_send_error(s, m, "No channel specified");
1067                 return 0;
1068         }
1069         if (!timeout) {
1070                 astman_send_error(s, m, "No timeout specified");
1071                 return 0;
1072         }
1073         c = ast_channel_walk_locked(NULL);
1074         while(c) {
1075                 if (!strcasecmp(c->name, name)) {
1076                         break;
1077                 }
1078                 ast_mutex_unlock(&c->lock);
1079                 c = ast_channel_walk_locked(c);
1080         }
1081         if (!c) {
1082                 astman_send_error(s, m, "No such channel");
1083                 return 0;
1084         }
1085         ast_channel_setwhentohangup(c, timeout);
1086         ast_mutex_unlock(&c->lock);
1087         astman_send_ack(s, m, "Timeout Set");
1088         return 0;
1089 }
1090
1091 static int process_message(struct mansession *s, struct message *m)
1092 {
1093         char action[80] = "";
1094         struct manager_action *tmp = first_action;
1095         char *id = astman_get_header(m,"ActionID");
1096         char idText[256] = "";
1097         char iabuf[INET_ADDRSTRLEN];
1098
1099         strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1100         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1101
1102         if (ast_strlen_zero(action)) {
1103                 astman_send_error(s, m, "Missing action in request");
1104                 return 0;
1105         }
1106         if (id && !ast_strlen_zero(id)) {
1107                 snprintf(idText,256,"ActionID: %s\r\n",id);
1108         }
1109         if (!s->authenticated) {
1110                 if (!strcasecmp(action, "Challenge")) {
1111                         char *authtype;
1112                         authtype = astman_get_header(m, "AuthType");
1113                         if (!strcasecmp(authtype, "MD5")) {
1114                                 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1115                                         ast_mutex_lock(&s->lock);
1116                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1117                                         ast_mutex_unlock(&s->lock);
1118                                 }
1119                                 ast_mutex_lock(&s->lock);
1120                                 ast_cli(s->fd, "Response: Success\r\n"
1121                                                 "%s"
1122                                                 "Challenge: %s\r\n\r\n",
1123                                                 idText,s->challenge);
1124                                 ast_mutex_unlock(&s->lock);
1125                                 return 0;
1126                         } else {
1127                                 astman_send_error(s, m, "Must specify AuthType");
1128                                 return 0;
1129                         }
1130                 } else if (!strcasecmp(action, "Login")) {
1131                         if (authenticate(s, m)) {
1132                                 sleep(1);
1133                                 astman_send_error(s, m, "Authentication failed");
1134                                 return -1;
1135                         } else {
1136                                 s->authenticated = 1;
1137                                 if (option_verbose > 1) {
1138                                         if ( displayconnects ) {
1139                                                 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1140                                         }
1141                                 }
1142                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1143                                 astman_send_ack(s, m, "Authentication accepted");
1144                         }
1145                 } else if (!strcasecmp(action, "Logoff")) {
1146                         astman_send_ack(s, m, "See ya");
1147                         return -1;
1148                 } else
1149                         astman_send_error(s, m, "Authentication Required");
1150         } else {
1151                 while( tmp ) {          
1152                         if (!strcasecmp(action, tmp->action)) {
1153                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
1154                                         if (tmp->func(s, m))
1155                                                 return -1;
1156                                 } else {
1157                                         astman_send_error(s, m, "Permission denied");
1158                                 }
1159                                 return 0;
1160                         }
1161                         tmp = tmp->next;
1162                 }
1163                 astman_send_error(s, m, "Invalid/unknown command");
1164         }
1165         return 0;
1166 }
1167
1168 static int get_input(struct mansession *s, char *output)
1169 {
1170         /* output must have at least sizeof(s->inbuf) space */
1171         int res;
1172         int x;
1173         struct pollfd fds[1];
1174         char iabuf[INET_ADDRSTRLEN];
1175         for (x=1;x<s->inlen;x++) {
1176                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1177                         /* Copy output data up to and including \r\n */
1178                         memcpy(output, s->inbuf, x + 1);
1179                         /* Add trailing \0 */
1180                         output[x+1] = '\0';
1181                         /* Move remaining data back to the front */
1182                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1183                         s->inlen -= (x + 1);
1184                         return 1;
1185                 }
1186         } 
1187         if (s->inlen >= sizeof(s->inbuf) - 1) {
1188                 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);
1189                 s->inlen = 0;
1190         }
1191         fds[0].fd = s->fd;
1192         fds[0].events = POLLIN;
1193         res = poll(fds, 1, -1);
1194         if (res < 0) {
1195                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1196         } else if (res > 0) {
1197                 ast_mutex_lock(&s->lock);
1198                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1199                 ast_mutex_unlock(&s->lock);
1200                 if (res < 1)
1201                         return -1;
1202         }
1203         s->inlen += res;
1204         s->inbuf[s->inlen] = '\0';
1205         return 0;
1206 }
1207
1208 static void *session_do(void *data)
1209 {
1210         struct mansession *s = data;
1211         struct message m;
1212         char iabuf[INET_ADDRSTRLEN];
1213         int res;
1214         
1215         ast_mutex_lock(&s->lock);
1216         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1217         ast_mutex_unlock(&s->lock);
1218         memset(&m, 0, sizeof(&m));
1219         for (;;) {
1220                 res = get_input(s, m.headers[m.hdrcount]);
1221                 if (res > 0) {
1222                         /* Strip trailing \r\n */
1223                         if (strlen(m.headers[m.hdrcount]) < 2)
1224                                 continue;
1225                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1226                         if (ast_strlen_zero(m.headers[m.hdrcount])) {
1227                                 if (process_message(s, &m))
1228                                         break;
1229                                 memset(&m, 0, sizeof(&m));
1230                         } else if (m.hdrcount < MAX_HEADERS - 1)
1231                                 m.hdrcount++;
1232                 } else if (res < 0)
1233                         break;
1234         }
1235         if (s->authenticated) {
1236                 if (option_verbose > 1) {
1237                         if (displayconnects) 
1238                                 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));    
1239                 }
1240                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1241         } else {
1242                 if (option_verbose > 1) {
1243                         if ( displayconnects )
1244                                 ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1245                 }
1246                 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1247         }
1248         destroy_session(s);
1249         return NULL;
1250 }
1251
1252 static void *accept_thread(void *ignore)
1253 {
1254         int as;
1255         struct sockaddr_in sin;
1256         int sinlen;
1257         struct mansession *s;
1258         struct protoent *p;
1259         int arg = 1;
1260         int flags;
1261         pthread_attr_t attr;
1262
1263         pthread_attr_init(&attr);
1264         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1265
1266         for (;;) {
1267                 sinlen = sizeof(sin);
1268                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1269                 if (as < 0) {
1270                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1271                         continue;
1272                 }
1273                 p = getprotobyname("tcp");
1274                 if( p ) {
1275                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1276                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1277                         }
1278                 }
1279                 s = malloc(sizeof(struct mansession));
1280                 if (!s) {
1281                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1282                         continue;
1283                 } 
1284                 memset(s, 0, sizeof(struct mansession));
1285                 memcpy(&s->sin, &sin, sizeof(sin));
1286
1287                 if(! block_sockets) {
1288                         /* For safety, make sure socket is non-blocking */
1289                         flags = fcntl(as, F_GETFL);
1290                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
1291                 }
1292                 ast_mutex_init(&s->lock);
1293                 s->fd = as;
1294                 s->send_events = -1;
1295                 ast_mutex_lock(&sessionlock);
1296                 s->next = sessions;
1297                 sessions = s;
1298                 ast_mutex_unlock(&sessionlock);
1299                 if (ast_pthread_create(&t, &attr, session_do, s))
1300                         destroy_session(s);
1301         }
1302         pthread_attr_destroy(&attr);
1303         return NULL;
1304 }
1305
1306 int manager_event(int category, char *event, char *fmt, ...)
1307 {
1308         struct mansession *s;
1309         char tmp[4096];
1310         va_list ap;
1311
1312         ast_mutex_lock(&sessionlock);
1313         s = sessions;
1314         while(s) {
1315                 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1316                         ast_mutex_lock(&s->lock);
1317                         if (!s->blocking) {
1318                                 ast_cli(s->fd, "Event: %s\r\n", event);
1319                                 va_start(ap, fmt);
1320                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1321                                 va_end(ap);
1322                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1323                                 ast_cli(s->fd, "\r\n");
1324                         }
1325                         ast_mutex_unlock(&s->lock);
1326                 }
1327                 s = s->next;
1328         }
1329         ast_mutex_unlock(&sessionlock);
1330         return 0;
1331 }
1332
1333 int ast_manager_unregister( char *action ) {
1334         struct manager_action *cur = first_action, *prev = first_action;
1335
1336         ast_mutex_lock(&actionlock);
1337         while( cur ) {          
1338                 if (!strcasecmp(action, cur->action)) {
1339                         prev->next = cur->next;
1340                         free(cur);
1341                         if (option_verbose > 1) 
1342                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1343                         ast_mutex_unlock(&actionlock);
1344                         return 0;
1345                 }
1346                 prev = cur;
1347                 cur = cur->next;
1348         }
1349         ast_mutex_unlock(&actionlock);
1350         return 0;
1351 }
1352
1353 static int manager_state_cb(char *context, char *exten, int state, void *data)
1354 {
1355         /* Notify managers of change */
1356         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1357         return 0;
1358 }
1359
1360 static int ast_manager_register_struct(struct manager_action *act)
1361 {
1362         struct manager_action *cur = first_action, *prev = NULL;
1363         int ret;
1364
1365         ast_mutex_lock(&actionlock);
1366         while(cur) { /* Walk the list of actions */
1367                 ret = strcasecmp(cur->action, act->action);
1368                 if (ret == 0) {
1369                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1370                         ast_mutex_unlock(&actionlock);
1371                         return -1;
1372                 } else if (ret > 0) {
1373                         /* Insert these alphabetically */
1374                         if (prev) {
1375                                 act->next = prev->next;
1376                                 prev->next = act;
1377                         } else {
1378                                 act->next = first_action;
1379                                 first_action = act;
1380                         }
1381                         break;
1382                 }
1383                 prev = cur; 
1384                 cur = cur->next;
1385         }
1386         
1387         if (!cur) {
1388                 if (prev)
1389                         prev->next = act;
1390                 else
1391                         first_action = act;
1392                 act->next = NULL;
1393         }
1394
1395         if (option_verbose > 1) 
1396                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1397         ast_mutex_unlock(&actionlock);
1398         return 0;
1399 }
1400
1401 int ast_manager_register2(char *action, int auth, int (*func)(struct mansession *s, struct message *m), char *synopsis, char *description)
1402 {
1403         struct manager_action *cur;
1404
1405         cur = malloc(sizeof(struct manager_action));
1406         if (!cur) {
1407                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1408                 ast_mutex_unlock(&actionlock);
1409                 return -1;
1410         }
1411         cur->action = action;
1412         cur->authority = auth;
1413         cur->func = func;
1414         cur->synopsis = synopsis;
1415         cur->description = description;
1416         cur->next = NULL;
1417
1418         ast_manager_register_struct(cur);
1419
1420         return 0;
1421 }
1422
1423 static int registered = 0;
1424
1425 int init_manager(void)
1426 {
1427         struct ast_config *cfg;
1428         char *val;
1429         int oldportno = portno;
1430         static struct sockaddr_in ba;
1431         int x = 1;
1432         if (!registered) {
1433                 /* Register default actions */
1434                 ast_manager_register2("Ping", 0, action_ping, "Ping", mandescr_ping);
1435                 ast_manager_register2("Events", 0, action_events, "Contol Event Flow", mandescr_events);
1436                 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1437                 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1438                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
1439                 ast_manager_register( "Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable" );
1440                 ast_manager_register( "Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable" );
1441                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
1442                 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1443                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
1444                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
1445                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
1446                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
1447                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
1448                 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1449
1450                 ast_cli_register(&show_mancmd_cli);
1451                 ast_cli_register(&show_mancmds_cli);
1452                 ast_cli_register(&show_manconn_cli);
1453                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1454                 registered = 1;
1455         }
1456         portno = DEFAULT_MANAGER_PORT;
1457         displayconnects = 1;
1458         cfg = ast_load("manager.conf");
1459         if (!cfg) {
1460                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1461                 return 0;
1462         }
1463         memset(&ba, 0, sizeof(ba));
1464         val = ast_variable_retrieve(cfg, "general", "enabled");
1465         if (val)
1466                 enabled = ast_true(val);
1467
1468         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1469         if(val)
1470                 block_sockets = ast_true(val);
1471
1472         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1473                 if (sscanf(val, "%d", &portno) != 1) {
1474                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1475                         portno = DEFAULT_MANAGER_PORT;
1476                 }
1477         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1478                 if (sscanf(val, "%d", &portno) != 1) {
1479                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1480                         portno = DEFAULT_MANAGER_PORT;
1481                 }
1482                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1483         }
1484         /* Parsing the displayconnects */
1485         if ((val = ast_variable_retrieve(cfg, "general", "displayconnects"))) {
1486                         displayconnects = ast_true(val);;
1487         }
1488                                 
1489         
1490         ba.sin_family = AF_INET;
1491         ba.sin_port = htons(portno);
1492         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1493         
1494         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1495                 if (!inet_aton(val, &ba.sin_addr)) { 
1496                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1497                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1498                 }
1499         }
1500         
1501         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1502 #if 0
1503                 /* Can't be done yet */
1504                 close(asock);
1505                 asock = -1;
1506 #else
1507                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1508 #endif
1509         }
1510         ast_destroy(cfg);
1511         
1512         /* If not enabled, do nothing */
1513         if (!enabled) {
1514                 return 0;
1515         }
1516         if (asock < 0) {
1517                 asock = socket(AF_INET, SOCK_STREAM, 0);
1518                 if (asock < 0) {
1519                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1520                         return -1;
1521                 }
1522                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1523                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1524                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1525                         close(asock);
1526                         asock = -1;
1527                         return -1;
1528                 }
1529                 if (listen(asock, 2)) {
1530                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1531                         close(asock);
1532                         asock = -1;
1533                         return -1;
1534                 }
1535                 if (option_verbose)
1536                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1537                 ast_pthread_create(&t, NULL, accept_thread, NULL);
1538         }
1539         return 0;
1540 }
1541
1542 int reload_manager(void)
1543 {
1544         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1545         return init_manager();
1546 }