File: sipwitch.cpp

package info (click to toggle)
sipwitch 1.2.4-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,768 kB
  • sloc: cpp: 16,534; sh: 11,336; makefile: 206; xml: 24; ansic: 20
file content (1065 lines) | stat: -rw-r--r-- 29,983 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
// Copyright (C) 2008-2010 David Sugar, Tycho Softworks.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "sipwitch/sipwitch.h"
#include "ucommon/secure.h"
#ifdef _MSWINDOWS_
#include <windows.h>
#include <io.h>
#else
#include <signal.h>
#include <pwd.h>
#include <grp.h>
#include <fcntl.h>
#endif
#include <config.h>

#if !defined(_MSWINDOWS_)
#include <sys/un.h>
#endif

using namespace SIPWITCH_NAMESPACE;
using namespace UCOMMON_NAMESPACE;

static string_t statmap = STAT_MAP;
static string_t callmap = CALL_MAP;
static string_t regmap = REGISTRY_MAP;

#ifdef  _MSWINDOWS_
static char *getpass(const char *prompt)
{
    static char buf[128];
    size_t i;

    fputs(prompt, stderr);
    fflush(stderr);
    for (i = 0; i < sizeof(buf) - 1; i++) {
        buf[i] = fgetc(stdin);
        if (buf[i] == '\r' || buf[i] == '\n')
            break;
        fputs("*", stderr);
        fflush(stderr);
    }
    buf[i] = 0;
    fputs("\n", stderr);
    fflush(stderr);
    return buf;
}
#endif

static void capture(void)
{
#ifndef _MSWINDOWS_
    char buffer[512];
    FILE *fp;

    snprintf(buffer, sizeof(buffer), "/tmp/.sipwitch.%ld", (long)getpid());
    fp = fopen(buffer, "r");
    remove(buffer);
    while(fp && fgets(buffer, sizeof(buffer), fp) != NULL)
        fputs(buffer, stdout);
    if(fp)
        fclose(fp);
#endif
}

static void paddress(struct sockaddr_internet *a1, struct sockaddr_internet *a2)
{
    assert(a1 != NULL);

    char sep = '\n';
    char buf[64];
    unsigned p1 = 0, p2 = 0;

    if(!a1)
        return;

    Socket::getaddress((struct sockaddr *)a1, buf, sizeof(buf));
    switch(a1->address.sa_family) {
    case AF_INET:
        p1 = (unsigned)ntohs(a1->ipv4.sin_port);
        break;
#ifdef  AF_INET6
    case AF_INET6:
        p1 = (unsigned)ntohs(a1->ipv6.sin6_port);
        break;
#endif
    }

    if(a2) {
        switch(a2->address.sa_family) {
        case AF_INET:
            p2 = (unsigned)ntohs(a2->ipv4.sin_port);
            break;
#ifdef  AF_INET6
        case AF_INET6:
            p2 = (unsigned)ntohs(a2->ipv6.sin6_port);
            break;
#endif
        }
    }

    if(a2 && p2)
        sep = ',';

    if(p1)
        printf("%s:%u%c", buf, p1, sep);
    else
        printf("none%c", sep);

    if(!a2 || !p2)
        return;

    Socket::getaddress((struct sockaddr *)a2, buf, sizeof(buf));
    printf("%s:%u\n", buf, p2);
}

static void mapinit(void)
{
#ifndef _MSWINDOWS_
    struct passwd *pwd = getpwuid(getuid());

    fd_t fd = ::open(DEFAULT_VARPATH "/run/sipwitch/control", O_WRONLY | O_NONBLOCK);
    if(fd < 0) {
        if(!pwd)
            shell::errexit(4, "*** sipwitch: maps: invalid login\n");

        statmap = str(STAT_MAP "-") + str(pwd->pw_name);
        callmap = str(CALL_MAP "-") + str(pwd->pw_name);
        regmap = str(REGISTRY_MAP "-") + str(pwd->pw_name);
    }
    else
        ::close(fd);
#endif
}

static void showrealm(void)
{
    fsys_t fs;
    char buffer[256];

    fsys::open(fs, DEFAULT_CFGPATH "/siprealm", fsys::ACCESS_RDONLY);
    if(!is(fs))
        fsys::open(fs, DEFAULT_VARPATH "/lib/sipwitch/uuid", fsys::ACCESS_RDONLY);

    if(!is(fs))
error:
        shell::errexit(1, "*** sipwitch: realm: no public realm known\n");

    memset(buffer, 0, sizeof(buffer));
    fsys::read(fs, buffer, sizeof(buffer) - 1);
    fsys::close(fs);

    char *cp = strchr(buffer, '\n');
    if(cp)
        *cp = 0;

    cp = strchr(buffer, ':');
    if(cp)
        *cp = 0;

    if(!buffer[0])
        goto error;

    printf("%s\n", buffer);
    exit(0);
}

static void compute(char **argv)
{
    char *realm = NULL;
    const char *user, *secret;
    const char *mode = "md5";
    char buffer[128];
    string_t digestbuf;

    user = argv[1];
    if(!user)
        shell::errexit(3, "*** sipwitch: digest: userid missing\n");

    secret = getpass("Enter new SIP secret: ");
    if(!secret || !*secret) {
        printf("no password supplied\n");
        exit(0);
    }

    realm = argv[2];
    if(realm) {
        if(argv[3])
            mode = argv[3];
    }
    else {
        fsys_t fs;
        fsys::open(fs, DEFAULT_CFGPATH "/siprealm", fsys::ACCESS_RDONLY);
        if(!is(fs))
            fsys::open(fs, DEFAULT_VARPATH "/lib/sipwitch/uuid", fsys::ACCESS_RDONLY);

        if(!is(fs))
            shell::errexit(4, "*** sipwitch: digest: no public realm known\n");

        memset(buffer, 0, sizeof(buffer));
        fsys::read(fs, buffer, sizeof(buffer) - 1);
        fsys::close(fs);

        char *cp = strchr(buffer, '\n');
        if(cp)
            *cp = 0;

        cp = strchr(buffer, ':');
        if(cp)
            *(cp++) = 0;

        if(cp && *cp)
            mode = cp;
        realm = strdup(buffer);
    }

    digest_t digest = mode;
    if(digest.puts((string_t)user + ":" + (string_t)realm + ":" + (string_t)secret))
        digestbuf = *digest;
    else
        shell::errexit(6, "** sipwitch: digest: unsupported computation");

    printf("%s\n", *digestbuf);
    exit(0);
}

static void realm(char **argv)
{
    char *realm = NULL;
    const char *mode = NULL;
    fsys_t fs;
    char buffer[256];
    char replace[256];
    char *cp = NULL;
    FILE *fp;

#ifdef  _MSWINDOWS_
    const char *control = "\\\\.\\mailslot\\sipwitch_ctrl";
#else
    const char *control = DEFAULT_VARPATH "/run/sipwitch/control";
#endif

    if(!argv[1])
        showrealm();

    mode = argv[2];
    if(!mode)
        mode = "md5";

    fsys::open(fs, DEFAULT_CFGPATH "/siprealm", fsys::ACCESS_RDONLY);
    memset(buffer, 0, sizeof(buffer));
    if(is(fs)) {
        fsys::read(fs, buffer, sizeof(buffer) - 1);
        fsys::close(fs);
        cp = strchr(buffer, ':');
        if(cp)
            *(cp++) = 0;
    }

    realm = argv[1];
    if(!realm)
        realm = buffer;

    if(!cp || !*cp)
        cp = (char *)"md5";

    // make sure we have a valid mode, default is md5...
    if(!mode && cp && *cp)
        mode = cp;

    if(!mode)
        mode = "md5";

    // if unchanged, we leave alone...
    if(eq(buffer, realm) && eq(cp, mode))
        goto exit;

    // create replacement realm string...
    if(eq(mode, "md5"))
        String::set(replace, sizeof(replace), realm);
    else
        snprintf(replace, sizeof(replace), "%s:%s", realm, mode);

    ::remove(DEFAULT_CFGPATH "/siprealm");
    fsys::create(fs, DEFAULT_CFGPATH "/siprealm", fsys::ACCESS_WRONLY, 0644);
    if(is(fs)) {
        fsys::write(fs, replace, strlen(replace));
        fsys::close(fs);
    }
    else
        shell::errexit(3, "*** sipwitch: realm: root permission required\n");

    // if previous digests cached, clear them as they are now invalid...
    ::remove(DEFAULT_VARPATH "/lib/sipwitch/digests.db");

    // if server is up, also sync server with realm change...
    fp = fopen(control, "w");
    if(fp) {
        fprintf(fp, "realm %s\n", realm);
        fclose(fp);
    }

exit:
    printf("%s\n", realm);
    exit(0);
}

static void status(char **argv)
{
    if(argv[1])
        shell::errexit(1, "*** sipwitch: status: no arguments used\n");

    mapinit();

    mapped_view<MappedCall> calls(*callmap);
    unsigned count = calls.getCount();
    unsigned index = 0;
    const volatile MappedCall *map;

    if(!count)
        shell::errexit(10, "*** sipwitch: status: offline\n");

    while(index < count) {
        map = (const volatile MappedCall *)(calls(index++));
        if(map->state[0])
            fputc(map->state[0], stdout);
        else
            fputc(' ', stdout);
    }
    fputc('\n', stdout);
    fflush(stdout);
    exit(0);
}

static void calls(char **argv)
{
    if(argv[1])
        shell::errexit(1, "*** sipwitch: calls: no arguments used\n");

    mapinit();

    mapped_view<MappedCall> calls(*callmap);
    unsigned count = calls.getCount();
    unsigned index = 0;
    const volatile MappedCall *map;
    time_t now;

    if(!count)
        shell::errexit(10, "*** sipwitch: calls: offline\n");

    time(&now);
    while(index < count) {
        map = (const volatile MappedCall *)(calls(index++));

        if(!map->created || !map->source[0])
            continue;

        if(map->active)
            printf("%08x:%d %s %s \"%s\" -> %s; %ld sec(s)\n", map->sequence, map->cid, map->state + 1, map->source, map->display, map->target, (long)(now - map->active));
        else
            printf("%08x:%d %s %s \"%s\" -> none; %ld secs\n", map->sequence, map->cid, map->state + 1, map->source, map->display, (long)(now - map->created));
    }
    exit(0);
}

static void periodic(char **argv)
{
    char text[80];

    if(argv[1])
        shell::errexit(1, "*** sipwitch: pstats: no arguments used\n");

    mapinit();

    mapped_view<stats> sta(*statmap);
    unsigned count = sta.getCount();
    unsigned index = 0;
    const volatile stats *map;

    if(!count)
        shell::errexit(10, "*** sipwitch: pstats: offline\n");

    while(index < count) {
        map = (const volatile stats *)(sta(index++));

        if(!map->id[0])
            continue;

        if(map->limit)
            snprintf(text, sizeof(text), "%-12s %05hu", map->id, map->limit);
        else
            snprintf(text, sizeof(text), "%-12s -    ", map->id);

        for(unsigned entry = 0; entry < 2; ++entry) {
            size_t len = strlen(text);
            snprintf(text + len, sizeof(text) - len, " %07lu %05hu %05hu",
                map->data[entry].pperiod,
                map->data[entry].pmin,
                map->data[entry].pmax);
        }
        printf("%s\n", text);
    }
    exit(0);
}

static void showevents(char **argv)
{
#ifdef  _MSWINDOWS_
    socket_t ipc = ::socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
#else
    socket_t ipc = ::socket(AF_UNIX, SOCK_STREAM, 0);
    struct sockaddr_un addr;
    struct passwd *pwd = getpwuid(getuid());
#endif

    if(argv[1])
        shell::errexit(1, "*** sipwitch: events: no arguments used\n");

    if(ipc == INVALID_SOCKET)
        shell::errexit(9, "*** sipwitch: events: cannot create event socket\n");

    memset(&addr, 0, sizeof(addr));

#ifdef  _MSWINDOWS_
    DWORD port = 0, pid = 0;
    DWORD plen;
    DWORD index = 0;
    TCHAR keyname[128];
    TCHAR keyvalue[128];
    DWORD size = sizeof(keyname), vsize = sizeof(keyvalue), vtype;
    DWORD *dp;

    plen = sizeof(port);
    HKEY keys = HKEY_LOCAL_MACHINE, subkey;
    if(RegOpenKeyEx(keys, "SOFTWARE\\sipwitch", 0, KEY_READ, &subkey) != ERROR_SUCCESS)
        shell::errexit(10, "*** sipwitch: events: no service found\n");
    while((RegEnumValue(subkey, index++, keyname, &size, NULL, &vtype, (BYTE *)keyvalue, &vsize) == ERROR_SUCCESS) && (vtype == REG_DWORD) && (keyname[0] != 0)) {
        dp = (DWORD *)&keyvalue;
        if(eq("port", keyname))
            port = *dp;
        else if(eq("pid", keyname))
            pid = *dp;
        vsize = sizeof(keyvalue);
        size = sizeof(keyname);
    }
    RegCloseKey(subkey);
    if(!port)
        shell::errexit(10, "*** sipwitch: events: server missing\n");
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_port = htons((unsigned short)port);
    if(::connect(ipc, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        shell::errexit(10, "*** sipwitch: events: server offline\n");
#else
    addr.sun_family = AF_UNIX;
    String::set(addr.sun_path, sizeof(addr.sun_path), DEFAULT_VARPATH "/run/sipwitch/events");
    if(::connect(ipc, (struct sockaddr *)&addr, SUN_LEN(&addr)) < 0) {
        if(!pwd)
            shell::errexit(4, "*** sipwitch: events: invalid login\n");

        memset(&addr, 0, sizeof(addr));
        addr.sun_family = AF_UNIX;
        snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/sipwitch-%s/events", pwd->pw_name);
        if(::connect(ipc, (struct sockaddr *)&addr, SUN_LEN(&addr)) < 0)
            shell::errexit(10, "*** sipwitch: events: server offline\n");
    }
#endif

    event_t event;
    while(::recv(ipc, (char *)&event, sizeof(event), 0) == sizeof(event)) {
        switch(event.type) {
        case events::FAILURE:
            printf("failure: %s\n", event.reason);
            break;
        case events::WARNING:
            printf("warning: %s\n", event.reason);
            break;
        case events::NOTICE:
            printf("notice:  %s\n", event.reason);
            break;
        case events::WELCOME:
            printf("server version %s %s\n",
                event.server.version, event.server.state);
            break;
        case events::TERMINATE:
            printf("exiting: %s\n", event.reason);
            exit(0);
        case events::CALL:
            printf("connecting %s to %s on %s\n",
                event.call.caller, event.call.dialed, event.call.network);
            break;
        case events::DROP:
            printf("disconnect %s from %s, reason=%s\n",
                event.call.caller, event.call.dialed, event.call.reason);
            break;
        case events::RELEASE:
            if(event.user.extension)
                printf("releasing %s, extension %d\n",
                    event.user.id, event.user.extension);
            else
                printf("releasing %s\n", event.user.id);
            break;
        case events::ACTIVATE:
            if(event.user.extension)
                printf("activating %s, extension %d\n",
                    event.user.id, event.user.extension);
            else
                printf("activating %s\n", event.user.id);
            break;
        case events::STATE:
            printf("changing state to %s\n", event.server.state);
            break;
        case events::REALM:
            printf("changing realm to %s\n", event.server.realm);
            break;
        case events::SYNC:
            if(event.period)
                printf("housekeeping period %d\n", event.period);
            break;
        }
    }
    shell::errexit(11, "*** sipwitch: events: connection lost\n");
}

static void dumpstats(char **argv)
{
    char text[80];
    time_t now;

    if(argv[1])
        shell::errexit(1, "*** sipwitch: stats: no arguments used\n");

    mapinit();

    mapped_view<stats> sta(*statmap);
    unsigned count = sta.getCount();
    unsigned index = 0;
    const stats *map;
    unsigned current;
    stats buffer;

    if(!count)
        shell::errexit(10, "*** sipwitch: stats: offline\n");

    time(&now);
    while(index < count) {
        map = const_cast<const stats *>(sta(index++));

        if(!map->id[0])
            continue;

        do {
            memcpy(&buffer, map, sizeof(buffer));
        } while(memcmp(&buffer, map, sizeof(buffer)));
        map = &buffer;

        if(map->limit)
            snprintf(text, sizeof(text), "%-12s %05hu", map->id, map->limit);
        else
            snprintf(text, sizeof(text), "%-12s -    ", map->id);

        for(unsigned entry = 0; entry < 2; ++entry) {
            size_t len = strlen(text);
            snprintf(text + len, sizeof(text) - len, " %09lu %05hu %05hu",
                map->data[entry].total,
                map->data[entry].current,
                map->data[entry].peak);
        }
        current = map->data[0].current + map->data[1].current;
        if(current)
            printf("%s 0s\n", text);
        else if(!map->lastcall)
            printf("%s -\n", text);
        else if(now - map->lastcall > (3600l * 99l))
            printf("%s %ld%c\n", text, (now - map->lastcall) / (3600l * 24l), 'd');
        else if(now - map->lastcall > (60l * 120l))
            printf("%s %ld%c\n", text, (now - map->lastcall) / 3600l, 'h');
        else if(now - map->lastcall > 120l)
            printf("%s %ld%c\n", text, (now - map->lastcall) / 60l, 'm');
        else
            printf("%s %ld%c\n", text, (long)(now - map->lastcall), 's');
    }
    exit(0);
}

static void registry(char **argv)
{
    mapinit();

    mapped_view<MappedRegistry> reg(*regmap);
    unsigned count = reg.getCount();
    unsigned found = 0, index = 0;
    volatile const MappedRegistry *member;
    MappedRegistry buffer;
    time_t now;
    char ext[8], exp[8], use[8];
    const char *type;

    if(argv[1])
        shell::errexit(1, "*** sipwitch: registry: too many arguments\n");

    if(!count)
        shell::errexit(10, "*** sipwitch: registry: offline\n");

    time(&now);
    while(index < count) {
        member = (const volatile MappedRegistry *)(reg(index++));
        do {
            memcpy(&buffer, (const void *)member, sizeof(buffer));
        } while(memcmp(&buffer, (const void *)member, sizeof(buffer)));
        if(buffer.type == MappedRegistry::EXPIRED)
            continue;
        else if(buffer.type == MappedRegistry::TEMPORARY && !buffer.inuse)
            continue;

        if(!found++)
            printf("%7s %-30s type %-30s  use expires address\n", "ext", "user", "profile");
        ext[0] = 0;
        if(buffer.ext)
            snprintf(ext, sizeof(ext), "%7d", buffer.ext);
        exp[0] = '-';
        exp[1] = 0;
        snprintf(use, sizeof(use), "%u", buffer.inuse);
        if(buffer.expires && buffer.type != MappedRegistry::TEMPORARY)
            snprintf(exp, sizeof(exp), "%ld", (long)(buffer.expires - now));
        switch(buffer.type) {
        case MappedRegistry::REJECT:
            type = "rej";
            break;
        case MappedRegistry::REFER:
            type = "ref";
            break;
        case MappedRegistry::GATEWAY:
            type = "gw";
            break;
        case MappedRegistry::SERVICE:
            type = "svc";
            break;
        case MappedRegistry::TEMPORARY:
            type = "temp";
            break;
        default:
            type = "user";
        };
        printf("%7s %-30s %-4s %-30s %4s %7s ", ext, buffer.userid, type, buffer.profile.id, use, exp);
        paddress(&buffer.contact, NULL);
        fflush(stdout);
    }

    printf("found %d entries active of %d\n", found, count);
    exit(0);
}

static void command(char **argv, unsigned timeout)
{
    char buffer[512];
    size_t len;
    fd_t fd;

#ifdef  _MSWINDOWS_
    snprintf(buffer, sizeof(buffer), "\\\\.\\mailslot\\sipwitch_ctrl");
    fd = CreateFile(buffer, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#else
    sigset_t sigs;
    int signo;
    struct passwd *pwd = getpwuid(getuid());

    sigemptyset(&sigs);
    sigaddset(&sigs, SIGUSR1);
    sigaddset(&sigs, SIGUSR2);
    sigaddset(&sigs, SIGALRM);
    pthread_sigmask(SIG_BLOCK, &sigs, NULL);

    fd = ::open(DEFAULT_VARPATH "/run/sipwitch/control", O_WRONLY | O_NONBLOCK);
    if(fd < 0) {
        if(!pwd)
            shell::errexit(4, "*** sipwitch: events: invalid login\n");

        snprintf(buffer, sizeof(buffer), "/tmp/sipwitch-%s/control", pwd->pw_name);
        fd = ::open(buffer, O_WRONLY | O_NONBLOCK);
    }
#endif

    if(fd == INVALID_HANDLE_VALUE)
        shell::errexit(10, "*** sipwitch: command: offline\n");

#ifndef _MSWINDOWS_
    if(timeout)
        snprintf(buffer, sizeof(buffer), "%ld", (long)getpid());
    else
#endif
        buffer[0] = 0;

    while(*argv) {
        len = strlen(buffer);
        snprintf(buffer + len, sizeof(buffer) - len - 1, " %s", *(argv++));
    }

#ifdef  _MSWINDOWS_
    if(!WriteFile(fd, buffer, (DWORD)strlen(buffer) + 1, NULL, NULL))
        shell::errexit(11, "*** sipwitch: control failed\n");
#else
    len = strlen(buffer);
    buffer[len++] = '\n';
    buffer[len] = 0;

    if(::write(fd, buffer, len) < (int)len)
        shell::errexit(11, "*** sipwitch: control failed\n");

    if(!timeout)
        exit(0);

    alarm(timeout);
#ifdef  HAVE_SIGWAIT2
    sigwait(&sigs, &signo);
#else
    signo = sigwait(&sigs);
#endif
    if(signo == SIGUSR1) {
        capture();
        exit(0);
    }
    if(signo == SIGALRM)
        shell::errexit(12, "*** sipwitch: command: timed out\n");

    shell::errexit(20, "*** sipwitch: command: request failed\n");
#endif
}

static void version(void)
{
    printf("SIP Witch " VERSION "\n"
        "Copyright (C) 2007,2008,2009 David Sugar, Tycho Softworks\n"
        "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n"
        "This is free software: you are free to change and redistribute it.\n"
        "There is NO WARRANTY, to the extent permitted by law.\n");
    exit(0);
}

static void usage(void)
{
    printf("usage: sipwitch command\n"
        "Commands:\n"
        "  abort                    Force daemon abort\n"
        "  activate <ext> <ipaddr>  Assign registration\n"
        "  address <ipaddr>         Set public ip address\n"
        "  calls                    List active calls on server\n"
        "  check                    Server deadlock check\n"
        "  concurrency <level>      Server concurrency level\n"
        "  digest id [realm [type]] Compute a digest\n"
        "  disable conf-id...       Disable configurations\n"
        "  down                     Shut down server\n"
        "  drop <user|callid>       Drop an active call\n"
        "  dump                     Dump server configuration\n"
        "  enable conf-id...        Enable configurations\n"
        "  events                   Display server events\n"
        "  grant <group>            Grant dir access to system group\n"
        "  history [bufsize]        Set buffer or dump error log\n"
        "  ifup <iface>             Notify interface came up\n"
        "  ifdown <iface>           Notify interface went down\n"
        "  message <ext> <text>     Send text message to extension\n"
        "  peering                  Print peering (published) address\n"
        "  period <interval>        Collect periodic statistics\n"
        "  pstats                   Dump periodic statistics\n"
        "  realm [text [digest]]    Show or set new server realm\n"
        "  registry                 Dump registry\n"
        "  release <ext>            Release registration\n"
        "  reload                   Reload configuration\n"
        "  restart                  Server restart\n"
        "  siplog                   Dump sip log when tracing\n"
        "  snapshot                 Server snapshot\n"
        "  stats                    Dump server statistics\n"
        "  state <selection>        Change server state\n"
        "  status                   Dump status string\n"
        "  trace <on|off|clear>     Set sip message tracing\n"
        "  usercache                Dump user cache\n"
        "  verbose <level>          Server verbose logging level\n"
    );

    printf("Report bugs to sipwitch-devel@gnu.org\n");
    exit(0);
}

static void single(char **argv, int timeout)
{
    if(argv[1])
        shell::errexit(1, "*** sipwitch: %s: too many arguments\n", *argv);

    command(argv, timeout);
}

static void level(char **argv, int timeout)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: %s: level missing\n", *argv);

    if(argv[2])
        shell::errexit(1, "*** sipwitch: %s: too many arguments\n", *argv);

    command(argv, timeout);
}

static void period(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: period: interval missing\n");

    if(argv[2])
        shell::errexit(1, "*** sipwitch: period: too many arguments\n");

    command(argv, 10);
}

static void address(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: address: ipaddr missing\n");

    if(argv[2])
        shell::errexit(1, "*** sipwitch: address: too many arguments\n");

    command(argv, 10);
}

static void state(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: state: value missing\n");

    if(argv[2])
        shell::errexit(1, "*** sipwitch: state: too many arguments\n");

    command(argv, 10);
}

static void iface(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: %s: interface missing\n", *argv);

    if(argv[2])
        shell::errexit(1, "*** sipwitch: %s: too many arguments\n", *argv);

    command(argv, 20);
}

static void drop(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: drop: user or callid missing\n");

    if(argv[2])
        shell::errexit(1, "*** sipwitch: drop: too many arguments\n");

    command(argv, 10);
}

static void release(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: release: extension missing\n");

    if(argv[2])
        shell::errexit(1, "*** sipwitch: release: too many arguments\n");

    command(argv, 10);
}

static void activate(char **argv)
{
    if(!argv[1])
        shell::errexit(1, "*** sipwitch: activate: extension missing\n");

    if(!argv[2])
        shell::errexit(1, "*** sipwitch: activate: ipaddr missing\n");

    if(argv[3])
        shell::errexit(1, "*** sipwitch: activate: too many arguments\n");

    command(argv, 10);
}

static void message(char **argv)
{
    char buffer[500];

    if(!argv[1])
        shell::errexit(1, "*** sipwitch: message: extension missing\n");

    if(!argv[2])
        shell::errexit(1, "*** sipwitch: message: \"text\" missing\n");

    if(argv[3])
        shell::errexit(1, "*** sipwitch: message: too many arguments\n");

    if(argv[2][0] != '{') {
        snprintf(buffer, sizeof(buffer), "{%s}", argv[2]);
        argv[2] = buffer;
    }
    command(argv, 10);
}

#ifdef  HAVE_PWD_H
static void grant(char **argv)
{
    gid_t gid = -1;
    struct group *grp;
    fsys::fileinfo_t ino;

    if(!argv[1])
        shell::errexit(1, "*** sipwitch: grant: no group specified\n");
    if(argv[2])
        shell::errexit(1, "*** sipwitch: grant: not more than one group\n");

    grp = getgrnam(argv[1]);
    if(grp)
        gid = grp->gr_gid;
    else if(atol(argv[1]))
        gid = atol(argv[1]);
    else
        shell::errexit(2, "*** sipwitch: grant: %s: unknown group\n", argv[1]);

    fsys::fileinfo(DEFAULT_VARPATH "/lib/sipwitch", &ino);
    chmod(DEFAULT_VARPATH "/lib/sipwitch", ino.st_mode | 070);
    chown(DEFAULT_VARPATH "/lib/sipwitch", ino.st_uid, gid);

    fsys::fileinfo(DEFAULT_VARPATH "/cache/sipwitch", &ino);
    chmod(DEFAULT_VARPATH "/cache/sipwitch", ino.st_mode | 070);
    chown(DEFAULT_VARPATH "/cache/sipwitch", ino.st_uid, gid);

    exit(0);
}
#else
static void grant(char **argv)
{
    shell::errexit(9, "*** sipwitch: grant: unsupported platform");
}
#endif

#ifdef  _MSWINDOWS_

static void enable(char **argv)
{
    shell::errexit(9, "*** sipwitch: enable: unsupported platform");
}

static void disable(char **argv)
{
    shell::errexit(9, "*** sipwitch: disable: unsupported platform");
}

#else

static void enable(char **argv)
{
    char source[128], target[128];

    if(!argv[1])
        shell::errexit(1, "*** sipwitch: enable: no configs specified\n");

    while(*(++argv)) {
        snprintf(source, sizeof(source), "%s/sipwitch.d/%s.xml", DEFAULT_CFGPATH, *argv);
        snprintf(target, sizeof(target), "%s/lib/sipwitch/%s.xml", DEFAULT_VARPATH, *argv);
        fsys::link(source, target);
    }
    exit(0);
}

static void disable(char **argv)
{
    char target[128];

    if(!argv[1])
        shell::errexit(1, "*** sipwitch: disable: no configs specified\n");

    while(*(++argv)) {
        snprintf(target, sizeof(target), "%s/lib/sipwitch/%s.xml", DEFAULT_VARPATH, *argv);
        fsys::remove(target);
    }
    exit(0);
}

#endif

PROGRAM_MAIN(argc, argv)
{
    if(argc < 2)
        usage();

    ++argv;
    if(eq(*argv, "version") || eq(*argv, "-version") || eq(*argv, "--version"))
        version();
    else if(eq(*argv, "help") || eq(*argv, "-help") || eq(*argv, "--help"))
        usage();
    else if(eq(*argv, "reload") || eq(*argv, "check") || eq(*argv, "snapshot") || eq(*argv, "dump") || eq(*argv, "siplog") || eq(*argv, "usercache") || eq(*argv, "policy"))
        single(argv, 30);
    else if(eq(*argv, "history")) {
        if(argc == 2)
            single(argv, 30);
        else
            level(argv, 10);
    }
    else if(eq(*argv, "down") || eq(*argv, "restart") || eq(*argv, "abort"))
        single(argv, 0);
    else if(eq(*argv, "verbose") || eq(*argv, "concurrency") || eq(*argv, "trace"))
        level(argv, 10);
    else if(eq(*argv, "message"))
        message(argv);
    else if(eq(*argv, "registry"))
        registry(argv);
    else if(eq(*argv, "stats"))
        dumpstats(argv);
    else if(eq(*argv, "calls"))
        calls(argv);
    else if(eq(*argv, "digest"))
        compute(argv);
    else if(eq(*argv, "pstats"))
        periodic(argv);
    else if(eq(*argv, "address"))
        address(argv);
    else if(eq(*argv, "period"))
        period(argv);
    else if(eq(*argv, "activate"))
        activate(argv);
    else if(eq(*argv, "release"))
        release(argv);
    else if(eq(*argv, "state"))
        state(argv);
    else if(eq(*argv, "status"))
        status(argv);
    else if(eq(*argv, "ifdown") || eq(*argv, "ifup"))
        iface(argv);
    else if(eq(*argv, "realm"))
            realm(argv);
    else if(eq(*argv, "drop"))
        drop(argv);
    else if(eq(*argv, "grant"))
        grant(argv);
    else if(eq(*argv, "enable"))
        enable(argv);
    else if(eq(*argv, "disable"))
        disable(argv);
    else if(eq(*argv, "events"))
        showevents(argv);

    if(!argv[1])
        shell::errexit(1, "use: sipwitch command [arguments...]\n");
    else
        shell::errexit(1, "*** sipwitch: %s: unknown command or option\n", argv[0]);
    PROGRAM_EXIT(1);
}