summaryrefslogtreecommitdiffstats
path: root/avahi-compat-libdns_sd/compat.c
blob: e6b60421fb35ea12e759d958bcc35da986fce3be (plain)
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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
/* $Id$ */

/***
  This file is part of avahi.
 
  avahi is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1 of the
  License, or (at your option) any later version.
 
  avahi 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 Lesser General
  Public License for more details.
 
  You should have received a copy of the GNU Lesser General Public
  License along with avahi; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  USA.
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <pthread.h>
#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <netinet/in.h>
#include <fcntl.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <avahi-common/simple-watch.h>
#include <avahi-common/malloc.h>
#include <avahi-common/error.h>
#include <avahi-common/domain.h>
#include <avahi-common/alternative.h>

#include <avahi-client/client.h>
#include <avahi-client/publish.h>
#include <avahi-client/lookup.h>

#include "warn.h"
#include "dns_sd.h"

enum {
    COMMAND_POLL = 'p',
    COMMAND_QUIT = 'q',
    COMMAND_POLL_DONE = 'P',
    COMMAND_POLL_FAILED = 'F'
};

struct type_info {
    char *type;
    AvahiStringList *subtypes;
    int n_subtypes;
};

struct _DNSServiceRef_t {
    int n_ref;
    
    AvahiSimplePoll *simple_poll;

    int thread_fd, main_fd;

    pthread_t thread;
    int thread_running;

    pthread_mutex_t mutex;
    
    void *context;
    DNSServiceBrowseReply service_browser_callback;
    DNSServiceResolveReply service_resolver_callback;
    DNSServiceDomainEnumReply domain_browser_callback;
    DNSServiceRegisterReply service_register_callback;

    AvahiClient *client;
    AvahiServiceBrowser *service_browser;
    AvahiServiceResolver *service_resolver;
    AvahiDomainBrowser *domain_browser;

    struct type_info type_info;
    char *service_name, *service_name_chosen, *service_domain, *service_host;
    uint16_t service_port;
    AvahiIfIndex service_interface;
    AvahiStringList *service_txt;

    AvahiEntryGroup *entry_group;
};

#define ASSERT_SUCCESS(r) { int __ret = (r); assert(__ret == 0); }

static DNSServiceErrorType map_error(int error) {
    switch (error) {
        case AVAHI_OK :
            return kDNSServiceErr_NoError;
            
        case AVAHI_ERR_BAD_STATE :
            return kDNSServiceErr_BadState;
            
        case AVAHI_ERR_INVALID_HOST_NAME:
        case AVAHI_ERR_INVALID_DOMAIN_NAME:
        case AVAHI_ERR_INVALID_TTL:
        case AVAHI_ERR_IS_PATTERN:
        case AVAHI_ERR_INVALID_RECORD:
        case AVAHI_ERR_INVALID_SERVICE_NAME:
        case AVAHI_ERR_INVALID_SERVICE_TYPE:
        case AVAHI_ERR_INVALID_PORT:
        case AVAHI_ERR_INVALID_KEY:
        case AVAHI_ERR_INVALID_ADDRESS:
        case AVAHI_ERR_INVALID_SERVICE_SUBTYPE:
            return kDNSServiceErr_BadParam;


        case AVAHI_ERR_COLLISION:
            return kDNSServiceErr_NameConflict;

        case AVAHI_ERR_TOO_MANY_CLIENTS:
        case AVAHI_ERR_TOO_MANY_OBJECTS:
        case AVAHI_ERR_TOO_MANY_ENTRIES:
        case AVAHI_ERR_ACCESS_DENIED:
            return kDNSServiceErr_Refused;

        case AVAHI_ERR_INVALID_OPERATION:
        case AVAHI_ERR_INVALID_OBJECT:
            return kDNSServiceErr_Invalid;

        case AVAHI_ERR_NO_MEMORY:
            return kDNSServiceErr_NoMemory;

        case AVAHI_ERR_INVALID_INTERFACE:
        case AVAHI_ERR_INVALID_PROTOCOL:
            return kDNSServiceErr_BadInterfaceIndex;
        
        case AVAHI_ERR_INVALID_FLAGS:
            return kDNSServiceErr_BadFlags;
            
        case AVAHI_ERR_NOT_FOUND:
            return kDNSServiceErr_NoSuchName;
            
        case AVAHI_ERR_VERSION_MISMATCH:
            return kDNSServiceErr_Incompatible;

        case AVAHI_ERR_NO_NETWORK:
        case AVAHI_ERR_OS:
        case AVAHI_ERR_INVALID_CONFIG:
        case AVAHI_ERR_TIMEOUT:
        case AVAHI_ERR_DBUS_ERROR:
        case AVAHI_ERR_DISCONNECTED:
        case AVAHI_ERR_NO_DAEMON:
            break;

    }

    return kDNSServiceErr_Unknown;
}

static void type_info_init(struct type_info *i) {
    assert(i);
    i->type = NULL;
    i->subtypes = NULL;
    i->n_subtypes = 0;
}

static void type_info_free(struct type_info *i) {
    assert(i);

    avahi_free(i->type);
    avahi_string_list_free(i->subtypes);

    type_info_init(i);
}

static int type_info_parse(struct type_info *i, const char *t) {
    char *token = NULL;
    
    assert(i);
    assert(t);

    type_info_init(i);

    for (;;) {
        size_t l;

        if (*t == 0)
            break;
        
        l = strcspn(t, ",");

        if (l <= 0)
            goto fail;
        
        token = avahi_strndup(t, l);

        if (!token)
            goto fail;

        if (!i->type) {
            /* This is the first token, hence the main type */

            if (!avahi_is_valid_service_type_strict(token))
                goto fail;

            i->type = token;
            token = NULL;
        } else {
            char *fst;
            
            /* This is not the first token, hence a subtype */

            if (!(fst = avahi_strdup_printf("%s._sub.%s", token, i->type)))
                goto fail;

            if (!avahi_is_valid_service_subtype(fst)) {
                avahi_free(fst);
                goto fail;
            }

            i->subtypes = avahi_string_list_add(i->subtypes, fst);
            avahi_free(fst);

            avahi_free(token);
            token = NULL;

            i->n_subtypes++;
        }

        t += l;

        if (*t == ',')
            t++;
    }

    if (i->type)
        return 0;
    
fail:
    type_info_free(i);
    avahi_free(token);
    return -1;
}

static const char *add_trailing_dot(const char *s, char *buf, size_t buf_len) {
    if (!s)
        return NULL;

    if (*s == 0)
        return s;

    if (s[strlen(s)-1] == '.')
        return s;

    snprintf(buf, buf_len, "%s.", s);
    return buf;
}

static int read_command(int fd) {
    ssize_t r;
    char command;

    assert(fd >= 0);
    
    if ((r = read(fd, &command, 1)) != 1) {
        fprintf(stderr, __FILE__": read() failed: %s\n", r < 0 ? strerror(errno) : "EOF");
        return -1;
    }

    return command;
}

static int write_command(int fd, char reply) {
    assert(fd >= 0);

    if (write(fd, &reply, 1) != 1) {
        fprintf(stderr, __FILE__": write() failed: %s\n", strerror(errno));
        return -1;
    }

    return 0;
}

static int poll_func(struct pollfd *ufds, unsigned int nfds, int timeout, void *userdata) {
    DNSServiceRef sdref = userdata;
    int ret;
    
    assert(sdref);
    
    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));

/*     fprintf(stderr, "pre-syscall\n"); */
    ret = poll(ufds, nfds, timeout);
/*     fprintf(stderr, "post-syscall\n"); */
    
    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));

    return ret;
}

static void * thread_func(void *data) {
    DNSServiceRef sdref = data;
    sigset_t mask;

    sigfillset(&mask);
    pthread_sigmask(SIG_BLOCK, &mask, NULL);
    
    sdref->thread = pthread_self();
    sdref->thread_running = 1;

    for (;;) {
        char command;

        if ((command = read_command(sdref->thread_fd)) < 0)
            break;

/*         fprintf(stderr, "Command: %c\n", command); */
        
        switch (command) {

            case COMMAND_POLL: {
                int ret;

                ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));

                for (;;) {
                    errno = 0;
                    
                    if ((ret = avahi_simple_poll_run(sdref->simple_poll)) < 0) {

                        if (errno == EINTR)
                            continue;
                        
                        fprintf(stderr, __FILE__": avahi_simple_poll_run() failed: %s\n", strerror(errno));
                    }

                    break;
                }

                ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));

                if (write_command(sdref->thread_fd, ret < 0 ? COMMAND_POLL_FAILED : COMMAND_POLL_DONE) < 0)
                    break;
                
                break;
            }

            case COMMAND_QUIT:
                return NULL;
        }
        
    }

    return NULL;
}

static DNSServiceRef sdref_new(void) {
    int fd[2] = { -1, -1 };
    DNSServiceRef sdref = NULL;
    pthread_mutexattr_t mutex_attr;

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0)
        goto fail;

    if (!(sdref = avahi_new(struct _DNSServiceRef_t, 1)))
        goto fail;

    sdref->n_ref = 1;
    sdref->thread_fd = fd[0];
    sdref->main_fd = fd[1];

    sdref->client = NULL;
    sdref->service_browser = NULL;
    sdref->service_resolver = NULL;
    sdref->domain_browser = NULL;
    sdref->entry_group = NULL;

    sdref->service_name = sdref->service_name_chosen = sdref->service_domain = sdref->service_host = NULL;
    sdref->service_txt = NULL;

    type_info_init(&sdref->type_info);

    ASSERT_SUCCESS(pthread_mutexattr_init(&mutex_attr));
    pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
    ASSERT_SUCCESS(pthread_mutex_init(&sdref->mutex, &mutex_attr));

    sdref->thread_running = 0;

    if (!(sdref->simple_poll = avahi_simple_poll_new()))
        goto fail;

    avahi_simple_poll_set_func(sdref->simple_poll, poll_func, sdref);

    /* Start simple poll */
    if (avahi_simple_poll_prepare(sdref->simple_poll, -1) < 0)
        goto fail;

    /* Queue an initial POLL command for the thread */
    if (write_command(sdref->main_fd, COMMAND_POLL) < 0)
        goto fail;
    
    if (pthread_create(&sdref->thread, NULL, thread_func, sdref) != 0)
        goto fail;

    sdref->thread_running = 1;
    
    return sdref;

fail:

    if (sdref)
        DNSServiceRefDeallocate(sdref);

    return NULL;
}

static void sdref_free(DNSServiceRef sdref) {
    assert(sdref);
    
    if (sdref->thread_running) {
        ASSERT_SUCCESS(write_command(sdref->main_fd, COMMAND_QUIT));
        avahi_simple_poll_wakeup(sdref->simple_poll);
        ASSERT_SUCCESS(pthread_join(sdref->thread, NULL));
    }

    if (sdref->client)
        avahi_client_free(sdref->client);

    if (sdref->simple_poll)
        avahi_simple_poll_free(sdref->simple_poll);

    if (sdref->thread_fd >= 0)
        close(sdref->thread_fd);

    if (sdref->main_fd >= 0)
        close(sdref->main_fd);

    ASSERT_SUCCESS(pthread_mutex_destroy(&sdref->mutex));

    avahi_free(sdref->service_name);
    avahi_free(sdref->service_name_chosen);
    avahi_free(sdref->service_domain);
    avahi_free(sdref->service_host);

    type_info_free(&sdref->type_info);
    
    avahi_string_list_free(sdref->service_txt);
    
    avahi_free(sdref);
}

static void sdref_ref(DNSServiceRef sdref) {
    assert(sdref);
    assert(sdref->n_ref >= 1);

    sdref->n_ref++;
}

static void sdref_unref(DNSServiceRef sdref) {
    assert(sdref);
    assert(sdref->n_ref >= 1);

    if (--(sdref->n_ref) <= 0)
        sdref_free(sdref);
}

int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdref) {
    if (!sdref || sdref->n_ref <= 0)
        return -1;

    AVAHI_WARN_LINKAGE;
    
    return sdref->main_fd;
}

DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdref) {
    DNSServiceErrorType ret = kDNSServiceErr_Unknown;

    assert(sdref);
    assert(sdref->n_ref >= 1);
    
    AVAHI_WARN_LINKAGE;

    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));

    sdref_ref(sdref);
    
    /* Cleanup notification socket */
    if (read_command(sdref->main_fd) != COMMAND_POLL_DONE)
        goto finish;
    
    if (avahi_simple_poll_dispatch(sdref->simple_poll) < 0)
        goto finish;

    if (sdref->n_ref > 1) /* Perhaps we should die */

        /* Dispatch events */
        if (avahi_simple_poll_prepare(sdref->simple_poll, -1) < 0)
            goto finish;

    if (sdref->n_ref > 1)

        /* Request the poll */
        if (write_command(sdref->main_fd, COMMAND_POLL) < 0)
            goto finish;
    
    ret = kDNSServiceErr_NoError;
    
finish:

    sdref_unref(sdref);

    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
    
    return ret;
}

void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdref) {
    AVAHI_WARN_LINKAGE;

    if (sdref)
        sdref_unref(sdref);
}

static void service_browser_callback(
    AvahiServiceBrowser *b,
    AvahiIfIndex interface,
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
    AvahiBrowserEvent event,
    const char *name,
    const char *type,
    const char *domain,
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
    void *userdata) {

    DNSServiceRef sdref = userdata;
    char type_fixed[AVAHI_DOMAIN_NAME_MAX], domain_fixed[AVAHI_DOMAIN_NAME_MAX];
    assert(b);
    assert(sdref);
    assert(sdref->n_ref >= 1);

    type = add_trailing_dot(type, type_fixed, sizeof(type_fixed));
    domain  = add_trailing_dot(domain, domain_fixed, sizeof(domain_fixed));
    
    switch (event) {
        case AVAHI_BROWSER_NEW:
            sdref->service_browser_callback(sdref, kDNSServiceFlagsAdd, interface, kDNSServiceErr_NoError, name, type, domain, sdref->context);
            break;

        case AVAHI_BROWSER_REMOVE:
            sdref->service_browser_callback(sdref, 0, interface, kDNSServiceErr_NoError, name, type, domain, sdref->context);
            break;

        case AVAHI_BROWSER_FAILURE:
            sdref->service_browser_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), NULL, NULL, NULL, sdref->context);
            break;
            
        case AVAHI_BROWSER_CACHE_EXHAUSTED:
        case AVAHI_BROWSER_ALL_FOR_NOW:
            break;
    }
}

static void generic_client_callback(AvahiClient *s, AvahiClientState state, void* userdata) {
    DNSServiceRef sdref = userdata;
    int error = kDNSServiceErr_Unknown;
        
    assert(s);
    assert(sdref);
    assert(sdref->n_ref >= 1);

    switch (state) {

        case AVAHI_CLIENT_FAILURE:

            if (sdref->service_browser_callback)
                sdref->service_browser_callback(sdref, 0, 0, error, NULL, NULL, NULL, sdref->context);
            else if (sdref->service_resolver_callback)
                sdref->service_resolver_callback(sdref, 0, 0, error, NULL, NULL, 0, 0, NULL, sdref->context);
            else if (sdref->domain_browser_callback)
                sdref->domain_browser_callback(sdref, 0, 0, error, NULL, sdref->context);

            break;

        case AVAHI_CLIENT_S_RUNNING:
        case AVAHI_CLIENT_S_COLLISION:
        case AVAHI_CLIENT_S_REGISTERING:
        case AVAHI_CLIENT_CONNECTING:
            break;
    }
}

DNSServiceErrorType DNSSD_API DNSServiceBrowse(
        DNSServiceRef *ret_sdref,
        DNSServiceFlags flags,
        uint32_t interface,
        const char *regtype,
        const char *domain,
        DNSServiceBrowseReply callback,
        void *context) {

    DNSServiceErrorType ret = kDNSServiceErr_Unknown;
    int error;
    DNSServiceRef sdref = NULL;
    AvahiIfIndex ifindex;
    struct type_info type_info;
    
    AVAHI_WARN_LINKAGE;
    
    assert(ret_sdref);
    assert(regtype);
    assert(callback);

    if (interface == kDNSServiceInterfaceIndexLocalOnly || flags != 0) {
        AVAHI_WARN_UNSUPPORTED;
        return kDNSServiceErr_Unsupported;
    }

    type_info_init(&type_info);
    
    if (type_info_parse(&type_info, regtype) < 0 || type_info.n_subtypes > 1) {
        type_info_free(&type_info);

        if (!avahi_is_valid_service_type_generic(regtype))
            return kDNSServiceErr_Unsupported;
    } else
        regtype = type_info.subtypes ? (char*) type_info.subtypes->text : type_info.type;
    
    if (!(sdref = sdref_new())) {
        type_info_free(&type_info);
        return kDNSServiceErr_Unknown;
    }

    sdref->context = context;
    sdref->service_browser_callback = callback;

    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
    
    if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), 0, generic_client_callback, sdref, &error))) {
        ret =  map_error(error);
        goto finish;
    }

    ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
    
    if (!(sdref->service_browser = avahi_service_browser_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, regtype, domain, 0, service_browser_callback, sdref))) {
        ret = map_error(avahi_client_errno(sdref->client));
        goto finish;
    }
    
    ret = kDNSServiceErr_NoError;
    *ret_sdref = sdref;
                                                              
finish:

    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
    
    if (ret != kDNSServiceErr_NoError)
        DNSServiceRefDeallocate(sdref);

    type_info_free(&type_info);

    return ret;
}

static void service_resolver_callback(
    AvahiServiceResolver *r,
    AvahiIfIndex interface,
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
    AvahiResolverEvent event,
    const char *name,
    const char *type,
    const char *domain,
    const char *host_name,
    AVAHI_GCC_UNUSED const AvahiAddress *a,
    uint16_t port,
    AvahiStringList *txt,
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
    void *userdata) {

    DNSServiceRef sdref = userdata;

    assert(r);
    assert(sdref);
    assert(sdref->n_ref >= 1);

    switch (event) {
        case AVAHI_RESOLVER_FOUND: {

            char host_name_fixed[AVAHI_DOMAIN_NAME_MAX];
            char full_name[AVAHI_DOMAIN_NAME_MAX];
            int ret;
            char *p = NULL;
            size_t l = 0;

            host_name = add_trailing_dot(host_name, host_name_fixed, sizeof(host_name_fixed));

            if ((p = avahi_new0(char, (l = avahi_string_list_serialize(txt, NULL, 0))+1)))
                avahi_string_list_serialize(txt, p, l);

            ret = avahi_service_name_join(full_name, sizeof(full_name), name, type, domain);
            assert(ret == AVAHI_OK);

            strcat(full_name, ".");
            
            sdref->service_resolver_callback(sdref, 0, interface, kDNSServiceErr_NoError, full_name, host_name, htons(port), l, (unsigned char*) p, sdref->context);

            avahi_free(p);
            break;
        }

        case AVAHI_RESOLVER_FAILURE:
            sdref->service_resolver_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), NULL, NULL, 0, 0, NULL, sdref->context);
            break;
    }
}

DNSServiceErrorType DNSSD_API DNSServiceResolve(
    DNSServiceRef *ret_sdref,
    DNSServiceFlags flags,
    uint32_t interface,
    const char *name,
    const char *regtype,
    const char *domain,
    DNSServiceResolveReply callback,
    void *context) {

    DNSServiceErrorType ret = kDNSServiceErr_Unknown;
    int error;
    DNSServiceRef sdref = NULL;
    AvahiIfIndex ifindex;

    AVAHI_WARN_LINKAGE;

    assert(ret_sdref);
    assert(name);
    assert(regtype);
    assert(domain);
    assert(callback);

    if (interface == kDNSServiceInterfaceIndexLocalOnly || flags != 0) {
        AVAHI_WARN_UNSUPPORTED;
        return kDNSServiceErr_Unsupported;
    }

    if (!(sdref = sdref_new()))
        return kDNSServiceErr_Unknown;

    sdref->context = context;
    sdref->service_resolver_callback = callback;

    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
    
    if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), 0, generic_client_callback, sdref, &error))) {
        ret =  map_error(error);
        goto finish;
    }

    ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
    
    if (!(sdref->service_resolver = avahi_service_resolver_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, name, regtype, domain, AVAHI_PROTO_UNSPEC, 0, service_resolver_callback, sdref))) {
        ret = map_error(avahi_client_errno(sdref->client));
        goto finish;
    }
    

    ret = kDNSServiceErr_NoError;
    *ret_sdref = sdref;
                                                              
finish:

    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
    
    if (ret != kDNSServiceErr_NoError)
        DNSServiceRefDeallocate(sdref);

    return ret;
}

int DNSSD_API DNSServiceConstructFullName (
    char *fullName,
    const char *service,   
    const char *regtype,
    const char *domain) {

    AVAHI_WARN_LINKAGE;

    assert(fullName);
    assert(regtype);
    assert(domain);

    if (avahi_service_name_join(fullName, kDNSServiceMaxDomainName, service, regtype, domain) < 0)
        return -1;
    
    return 0;
}

static void domain_browser_callback(
    AvahiDomainBrowser *b,
    AvahiIfIndex interface,
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
    AvahiBrowserEvent event,
    const char *domain,
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
    void *userdata) {

    DNSServiceRef sdref = userdata;
    static char domain_fixed[AVAHI_DOMAIN_NAME_MAX];

    assert(b);
    assert(sdref);
    assert(sdref->n_ref >= 1);

    domain  = add_trailing_dot(domain, domain_fixed, sizeof(domain_fixed));

    switch (event) {
        case AVAHI_BROWSER_NEW:
            sdref->domain_browser_callback(sdref, kDNSServiceFlagsAdd, interface, kDNSServiceErr_NoError, domain, sdref->context);
            break;

        case AVAHI_BROWSER_REMOVE:
            sdref->domain_browser_callback(sdref, 0, interface, kDNSServiceErr_NoError, domain, sdref->context);
            break;

        case AVAHI_BROWSER_FAILURE:
            sdref->domain_browser_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), domain, sdref->context);
            break;
            
        case AVAHI_BROWSER_CACHE_EXHAUSTED:
        case AVAHI_BROWSER_ALL_FOR_NOW:
            break;
    }
}

DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains(
    DNSServiceRef *ret_sdref,
    DNSServiceFlags flags,
    uint32_t interface,
    DNSServiceDomainEnumReply callback,
    void *context) {

    DNSServiceErrorType ret = kDNSServiceErr_Unknown;
    int error;
    DNSServiceRef sdref = NULL;
    AvahiIfIndex ifindex;

    AVAHI_WARN_LINKAGE;

    assert(ret_sdref);
    assert(callback);

    if (interface == kDNSServiceInterfaceIndexLocalOnly ||
        (flags != kDNSServiceFlagsBrowseDomains &&  flags != kDNSServiceFlagsRegistrationDomains)) {
        AVAHI_WARN_UNSUPPORTED;
        return kDNSServiceErr_Unsupported;
    }

    if (!(sdref = sdref_new()))
        return kDNSServiceErr_Unknown;

    sdref->context = context;
    sdref->domain_browser_callback = callback;

    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
    
    if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), 0, generic_client_callback, sdref, &error))) {
        ret =  map_error(error);
        goto finish;
    }

    ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
    
    if (!(sdref->domain_browser = avahi_domain_browser_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, "local",
                                                           flags == kDNSServiceFlagsRegistrationDomains ? AVAHI_DOMAIN_BROWSER_REGISTER : AVAHI_DOMAIN_BROWSER_BROWSE,
                                                           0, domain_browser_callback, sdref))) {
        ret = map_error(avahi_client_errno(sdref->client));
        goto finish;
    }
    
    ret = kDNSServiceErr_NoError;
    *ret_sdref = sdref;
                                                              
finish:

    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
    
    if (ret != kDNSServiceErr_NoError)
        DNSServiceRefDeallocate(sdref);

    return ret;
}

static void reg_report_error(DNSServiceRef sdref, DNSServiceErrorType error) {
    char regtype_fixed[AVAHI_DOMAIN_NAME_MAX], domain_fixed[AVAHI_DOMAIN_NAME_MAX];
    const char *regtype, *domain;
    assert(sdref);
    assert(sdref->n_ref >= 1);

    if (!sdref->service_register_callback)
        return;

    regtype = add_trailing_dot(sdref->type_info.type, regtype_fixed, sizeof(regtype_fixed));
    domain = add_trailing_dot(sdref->service_domain, domain_fixed, sizeof(domain_fixed));
    
    sdref->service_register_callback(
        sdref, 0, error,
        sdref->service_name_chosen ? sdref->service_name_chosen : sdref->service_name,
        regtype,
        domain,
        sdref->context);
}

static int reg_create_service(DNSServiceRef sdref) {
    int ret;
    AvahiStringList *l;
    
    assert(sdref);
    assert(sdref->n_ref >= 1);

    if ((ret = avahi_entry_group_add_service_strlst(
        sdref->entry_group,
        sdref->service_interface,
        AVAHI_PROTO_UNSPEC,
        0,
        sdref->service_name_chosen,
        sdref->type_info.type,
        sdref->service_domain,
        sdref->service_host,
        sdref->service_port,
        sdref->service_txt)) < 0)
        return ret;

    for (l = sdref->type_info.subtypes; l; l = l->next) {
        /* Create a subtype entry */

        if (avahi_entry_group_add_service_subtype(
                sdref->entry_group,
                sdref->service_interface,
                AVAHI_PROTO_UNSPEC,
                0,
                sdref->service_name_chosen,
                sdref->type_info.type,
                sdref->service_domain,
                (const char*) l->text) < 0)
            return ret;
    }

    if ((ret = avahi_entry_group_commit(sdref->entry_group)) < 0)
        return ret;

    return 0;
}

static void reg_client_callback(AvahiClient *s, AvahiClientState state, void* userdata) {
    DNSServiceRef sdref = userdata;

    assert(s);
    assert(sdref);
    assert(sdref->n_ref >= 1);

    /* We've not been setup completely */
    if (!sdref->entry_group)
        return;
    
    switch (state) {
        case AVAHI_CLIENT_FAILURE:
            reg_report_error(sdref, kDNSServiceErr_Unknown);
            break;

        case AVAHI_CLIENT_S_RUNNING: {
            int ret;

            if (!sdref->service_name) {
                const char *n;
                /* If the service name is taken from the host name, copy that */

                avahi_free(sdref->service_name_chosen);
                sdref->service_name_chosen = NULL;

                if (!(n = avahi_client_get_host_name(sdref->client))) {
                    reg_report_error(sdref, map_error(avahi_client_errno(sdref->client)));
                    return;
                }

                if (!(sdref->service_name_chosen = avahi_strdup(n))) {
                    reg_report_error(sdref, kDNSServiceErr_NoMemory);
                    return;
                }
            }
            
            /* Register the service */

            if ((ret = reg_create_service(sdref)) < 0) {
                reg_report_error(sdref, map_error(ret));
                return;
            }
            
            break;
        }
            
        case AVAHI_CLIENT_S_COLLISION:
        case AVAHI_CLIENT_S_REGISTERING:

            /* Remove our entry */
            avahi_entry_group_reset(sdref->entry_group);
            
            break;

        case AVAHI_CLIENT_CONNECTING:
            /* Ignore */
            break;
    }

}

static void reg_entry_group_callback(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) {
    DNSServiceRef sdref = userdata;

    assert(g);

    switch (state) {
        case AVAHI_ENTRY_GROUP_ESTABLISHED:

            /* Inform the user */
            reg_report_error(sdref, kDNSServiceErr_NoError);

            break;

        case AVAHI_ENTRY_GROUP_COLLISION: {
            char *n;
            int ret;
            
            /* Remove our entry */
            avahi_entry_group_reset(sdref->entry_group);

            assert(sdref->service_name_chosen);

            /* Pick a new name */
            if (!(n = avahi_alternative_service_name(sdref->service_name_chosen))) {
                reg_report_error(sdref, kDNSServiceErr_NoMemory);
                return;
            }
            avahi_free(sdref->service_name_chosen);
            sdref->service_name_chosen = n;

            /* Register the service with that new name */
            if ((ret = reg_create_service(sdref)) < 0) {
                reg_report_error(sdref, map_error(ret));
                return;
            }
            
            break;
        }

        case AVAHI_ENTRY_GROUP_REGISTERING:
        case AVAHI_ENTRY_GROUP_UNCOMMITED:
            /* Ignore */
            break;

        case AVAHI_ENTRY_GROUP_FAILURE:
            /* Inform the user */
            reg_report_error(sdref, map_error(avahi_client_errno(sdref->client)));
            break;
            
    }
}

DNSServiceErrorType DNSSD_API DNSServiceRegister (
        DNSServiceRef *ret_sdref,
        DNSServiceFlags flags,
        uint32_t interface,
        const char *name,        
        const char *regtype,
        const char *domain,      
        const char *host,        
        uint16_t port,
        uint16_t txtLen,
        const void *txtRecord,   
        DNSServiceRegisterReply callback,    
        void *context) {

    DNSServiceErrorType ret = kDNSServiceErr_Unknown;
    int error;
    DNSServiceRef sdref = NULL;
    AvahiStringList *txt = NULL;
    struct type_info type_info;

    AVAHI_WARN_LINKAGE;

    assert(ret_sdref);
    assert(regtype);
    assert(txtRecord || txtLen == 0);

    if (interface == kDNSServiceInterfaceIndexLocalOnly || flags) {
        AVAHI_WARN_UNSUPPORTED;
        return kDNSServiceErr_Unsupported;
    }

    if (txtLen > 0) 
        if (avahi_string_list_parse(txtRecord, txtLen, &txt) < 0)
            return kDNSServiceErr_Invalid;

    if (type_info_parse(&type_info, regtype) < 0) {
        avahi_string_list_free(txt);
        return kDNSServiceErr_Invalid;
    }
    
    if (!(sdref = sdref_new())) {
        avahi_string_list_free(txt);
        type_info_free(&type_info);
        return kDNSServiceErr_Unknown;
    }

    sdref->context = context;
    sdref->service_register_callback = callback;

    sdref->type_info = type_info;
    sdref->service_name = avahi_strdup(name);
    sdref->service_domain = domain ? avahi_normalize_name_strdup(domain) : NULL;
    sdref->service_host = host ? avahi_normalize_name_strdup(host) : NULL;
    sdref->service_interface = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
    sdref->service_port = ntohs(port);
    sdref->service_txt = txt;

    /* Some OOM checking would be cool here */
    
    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
    
    if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), 0, reg_client_callback, sdref, &error))) {
        ret =  map_error(error);
        goto finish;
    }

    if (!sdref->service_domain) {
        const char *d;

        if (!(d = avahi_client_get_domain_name(sdref->client))) {
            ret = map_error(avahi_client_errno(sdref->client));
            goto finish;
        }

        if (!(sdref->service_domain = avahi_strdup(d))) {
            ret = kDNSServiceErr_NoMemory;
            goto finish;
        }
    }

    if (!(sdref->entry_group = avahi_entry_group_new(sdref->client, reg_entry_group_callback, sdref))) {
        ret = map_error(avahi_client_errno(sdref->client));
        goto finish;
    }

    if (avahi_client_get_state(sdref->client) == AVAHI_CLIENT_S_RUNNING) {
        const char *n;

        if (sdref->service_name)
            n = sdref->service_name;
        else {
            if (!(n = avahi_client_get_host_name(sdref->client))) {
                ret = map_error(avahi_client_errno(sdref->client));
                goto finish;
            }
        }

        if (!(sdref->service_name_chosen = avahi_strdup(n))) {
            ret = kDNSServiceErr_NoMemory;
            goto finish;
        }

            
        if ((error = reg_create_service(sdref)) < 0) {
            ret = map_error(error);
            goto finish;
        }
    }
    
    ret = kDNSServiceErr_NoError;
    *ret_sdref = sdref;
                                                              
finish:

    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
    
    if (ret != kDNSServiceErr_NoError)
        DNSServiceRefDeallocate(sdref);

    return ret;
}

DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord(
         DNSServiceRef sdref,
         DNSRecordRef rref,     
         DNSServiceFlags flags,
         uint16_t rdlen,
         const void *rdata,
         AVAHI_GCC_UNUSED uint32_t ttl) {

    int ret = kDNSServiceErr_Unknown;
    AvahiStringList *txt = NULL;
    assert(sdref);

    AVAHI_WARN_LINKAGE;

    if (flags || rref) {
        AVAHI_WARN_UNSUPPORTED;
        return kDNSServiceErr_Unsupported;
    }

    if (rdlen > 0) 
        if (avahi_string_list_parse(rdata, rdlen, &txt) < 0)
            return kDNSServiceErr_Invalid;

    ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));

    if (!avahi_string_list_equal(txt, sdref->service_txt)) {

        avahi_string_list_free(sdref->service_txt);
        sdref->service_txt = txt;

        if (avahi_client_get_state(sdref->client) == AVAHI_CLIENT_S_RUNNING &&
            sdref->entry_group &&
            (avahi_entry_group_get_state(sdref->entry_group) == AVAHI_ENTRY_GROUP_ESTABLISHED ||
            avahi_entry_group_get_state(sdref->entry_group) == AVAHI_ENTRY_GROUP_REGISTERING))

            if (avahi_entry_group_update_service_txt_strlst(
                        sdref->entry_group,
                        sdref->service_interface,
                        AVAHI_PROTO_UNSPEC,
                        0,
                        sdref->service_name_chosen,
                        sdref->type_info.type,
                        sdref->service_domain,
                        sdref->service_txt) < 0) {
                
                ret = map_error(avahi_client_errno(sdref->client));
                goto finish;
            }

    } else
        avahi_string_list_free(txt);

    ret = kDNSServiceErr_NoError;
    
finish:
    ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
    
    return ret;
}