-
Notifications
You must be signed in to change notification settings - Fork 37
/
uds_daemon.c
4716 lines (4156 loc) · 193 KB
/
uds_daemon.c
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
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2003-2006 Apple Computer, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined(_WIN32)
#include <process.h>
#define usleep(X) Sleep(((X)+999)/1000)
#else
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include "mDNSEmbeddedAPI.h"
#include "DNSCommon.h"
#include "uDNS.h"
#include "uds_daemon.h"
// Normally we append search domains only for queries with a single label that are not
// fully qualified. This can be overridden to apply search domains for queries (that are
// not fully qualified) with any number of labels e.g., moon, moon.cs, moon.cs.be, etc.
mDNSBool AlwaysAppendSearchDomains = mDNSfalse;
// Apple-specific functionality, not required for other platforms
#if APPLE_OSX_mDNSResponder
#include <sys/ucred.h>
#ifndef PID_FILE
#define PID_FILE ""
#endif
#endif
#if APPLE_OSX_mDNSResponder
#include <WebFilterDNS/WebFilterDNS.h>
#if ! NO_WCF
int WCFIsServerRunning(WCFConnection *conn) __attribute__((weak_import));
int WCFNameResolvesToAddr(WCFConnection *conn, char* domainName, struct sockaddr* address, uid_t userid) __attribute__((weak_import));
int WCFNameResolvesToName(WCFConnection *conn, char* fromName, char* toName, uid_t userid) __attribute__((weak_import));
// Do we really need to define a macro for "if"?
#define CHECK_WCF_FUNCTION(X) if (X)
#endif // ! NO_WCF
#else
#define NO_WCF 1
#endif // APPLE_OSX_mDNSResponder
// User IDs 0-500 are system-wide processes, not actual users in the usual sense
// User IDs for real user accounts start at 501 and count up from there
#define SystemUID(X) ((X) <= 500)
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Types and Data Structures
#endif
typedef enum
{
t_uninitialized,
t_morecoming,
t_complete,
t_error,
t_terminated
} transfer_state;
typedef struct request_state request_state;
typedef void (*req_termination_fn)(request_state *request);
typedef struct registered_record_entry
{
struct registered_record_entry *next;
mDNSu32 key;
client_context_t regrec_client_context;
request_state *request;
mDNSBool external_advertise;
mDNSInterfaceID origInterfaceID;
AuthRecord *rr; // Pointer to variable-sized AuthRecord (Why a pointer? Why not just embed it here?)
} registered_record_entry;
// A single registered service: ServiceRecordSet + bookkeeping
// Note that we duplicate some fields from parent service_info object
// to facilitate cleanup, when instances and parent may be deallocated at different times.
typedef struct service_instance
{
struct service_instance *next;
request_state *request;
AuthRecord *subtypes;
mDNSBool renameonmemfree; // Set on config change when we deregister original name
mDNSBool clientnotified; // Has client been notified of successful registration yet?
mDNSBool default_local; // is this the "local." from an empty-string registration?
mDNSBool external_advertise; // is this is being advertised externally?
domainname domain;
ServiceRecordSet srs; // note -- variable-sized object -- must be last field in struct
} service_instance;
// for multi-domain default browsing
typedef struct browser_t
{
struct browser_t *next;
domainname domain;
DNSQuestion q;
} browser_t;
struct request_state
{
request_state *next;
request_state *primary; // If this operation is on a shared socket, pointer to primary
// request_state for the original DNSServiceCreateConnection() operation
dnssd_sock_t sd;
dnssd_sock_t errsd;
mDNSu32 uid;
void * platform_data;
// Note: On a shared connection these fields in the primary structure, including hdr, are re-used
// for each new request. This is because, until we've read the ipc_msg_hdr to find out what the
// operation is, we don't know if we're going to need to allocate a new request_state or not.
transfer_state ts;
mDNSu32 hdr_bytes; // bytes of header already read
ipc_msg_hdr hdr;
mDNSu32 data_bytes; // bytes of message data already read
char *msgbuf; // pointer to data storage to pass to free()
const char *msgptr; // pointer to data to be read from (may be modified)
char *msgend; // pointer to byte after last byte of message
// reply, termination, error, and client context info
int no_reply; // don't send asynchronous replies to client
mDNSs32 time_blocked; // record time of a blocked client
int unresponsiveness_reports;
struct reply_state *replies; // corresponding (active) reply list
req_termination_fn terminate;
DNSServiceFlags flags;
union
{
registered_record_entry *reg_recs; // list of registrations for a connection-oriented request
struct
{
mDNSInterfaceID interface_id;
mDNSBool default_domain;
mDNSBool ForceMCast;
domainname regtype;
browser_t *browsers;
} browser;
struct
{
mDNSInterfaceID InterfaceID;
mDNSu16 txtlen;
void *txtdata;
mDNSIPPort port;
domainlabel name;
char type_as_string[MAX_ESCAPED_DOMAIN_NAME];
domainname type;
mDNSBool default_domain;
domainname host;
mDNSBool autoname; // Set if this name is tied to the Computer Name
mDNSBool autorename; // Set if this client wants us to automatically rename on conflict
mDNSBool allowremotequery; // Respond to unicast queries from outside the local link?
int num_subtypes;
service_instance *instances;
} servicereg;
struct
{
mDNSInterfaceID interface_id;
mDNSu32 flags;
mDNSu32 protocol;
DNSQuestion q4;
DNSQuestion *q42;
DNSQuestion q6;
DNSQuestion *q62;
} addrinfo;
struct
{
mDNSIPPort ReqExt; // External port we originally requested, for logging purposes
NATTraversalInfo NATinfo;
} pm;
struct
{
#if 0
DNSServiceFlags flags;
#endif
DNSQuestion q_all;
DNSQuestion q_default;
} enumeration;
struct
{
DNSQuestion q;
DNSQuestion *q2;
} queryrecord;
struct
{
DNSQuestion qtxt;
DNSQuestion qsrv;
const ResourceRecord *txt;
const ResourceRecord *srv;
mDNSs32 ReportTime;
mDNSBool external_advertise;
} resolve;
} u;
};
// struct physically sits between ipc message header and call-specific fields in the message buffer
typedef struct
{
DNSServiceFlags flags; // Note: This field is in NETWORK byte order
mDNSu32 ifi; // Note: This field is in NETWORK byte order
DNSServiceErrorType error; // Note: This field is in NETWORK byte order
} reply_hdr;
typedef struct reply_state
{
struct reply_state *next; // If there are multiple unsent replies
mDNSu32 totallen;
mDNSu32 nwriten;
ipc_msg_hdr mhdr[1];
reply_hdr rhdr[1];
} reply_state;
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - Globals
#endif
// globals
mDNSexport mDNS mDNSStorage;
mDNSexport const char ProgramName[] = "mDNSResponder";
static dnssd_sock_t listenfd = dnssd_InvalidSocket;
static request_state *all_requests = NULL;
// Note asymmetry here between registration and browsing.
// For service registrations we only automatically register in domains that explicitly appear in local configuration data
// (so AutoRegistrationDomains could equally well be called SCPrefRegDomains)
// For service browsing we also learn automatic browsing domains from the network, so for that case we have:
// 1. SCPrefBrowseDomains (local configuration data)
// 2. LocalDomainEnumRecords (locally-generated local-only PTR records -- equivalent to slElem->AuthRecs in uDNS.c)
// 3. AutoBrowseDomains, which is populated by tracking add/rmv events in AutomaticBrowseDomainChange, the callback function for our mDNS_GetDomains call.
// By creating and removing our own LocalDomainEnumRecords, we trigger AutomaticBrowseDomainChange callbacks just like domains learned from the network would.
mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations
static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network
mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network
#define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
// n get_string() calls w/o buffer overrun
// initialization, setup/teardown functions
// If a platform specifies its own PID file name, we use that
#ifndef PID_FILE
#define PID_FILE "/var/run/mDNSResponder.pid"
#endif
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - General Utility Functions
#endif
mDNSlocal void FatalError(char *errmsg)
{
LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno));
*(long*)0 = 0; // On OS X abort() doesn't generate a crash log, but writing to zero does
abort(); // On platforms where writing to zero doesn't generate an exception, abort instead
}
mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l)
{
mDNSu32 ret;
char *data = (char*) &ret;
put_uint32(l, &data);
return ret;
}
// hack to search-replace perror's to LogMsg's
mDNSlocal void my_perror(char *errmsg)
{
LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno));
}
mDNSlocal void abort_request(request_state *req)
{
if (req->terminate == (req_termination_fn)~0)
{ LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; }
// First stop whatever mDNSCore operation we were doing
// If this is actually a shared connection operation, then its req->terminate function will scan
// the all_requests list and terminate any subbordinate operations sharing this file descriptor
if (req->terminate) req->terminate(req);
if (!dnssd_SocketValid(req->sd))
{ LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; }
// Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
if (!req->primary)
{
if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd);
else LogOperation("%3d: Removing FD", req->sd);
udsSupportRemoveFDFromEventLoop(req->sd, req->platform_data); // Note: This also closes file descriptor req->sd for us
if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; }
while (req->replies) // free pending replies
{
reply_state *ptr = req->replies;
req->replies = req->replies->next;
freeL("reply_state (abort)", ptr);
}
}
// Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
// Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
// for detecting when the memory for an object is inadvertently freed while the object is still on some list
req->sd = req->errsd = -2;
#else
req->sd = req->errsd = dnssd_InvalidSocket;
#endif
// We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
req->terminate = (req_termination_fn)~0;
}
mDNSlocal void AbortUnlinkAndFree(request_state *req)
{
request_state **p = &all_requests;
abort_request(req);
while (*p && *p != req) p=&(*p)->next;
if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); }
else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req);
}
mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request)
{
reply_state *reply;
if ((unsigned)datalen < sizeof(reply_hdr))
{
LogMsg("ERROR: create_reply - data length less than length of required fields");
return NULL;
}
reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr));
if (!reply) FatalError("ERROR: malloc");
reply->next = mDNSNULL;
reply->totallen = (mDNSu32)datalen + sizeof(ipc_msg_hdr);
reply->nwriten = 0;
reply->mhdr->version = VERSION;
reply->mhdr->datalen = (mDNSu32)datalen;
reply->mhdr->ipc_flags = 0;
reply->mhdr->op = op;
reply->mhdr->client_context = request->hdr.client_context;
reply->mhdr->reg_index = 0;
return reply;
}
// Append a reply to the list in a request object
// If our request is sharing a connection, then we append our reply_state onto the primary's list
mDNSlocal void append_reply(request_state *req, reply_state *rep)
{
request_state *r = req->primary ? req->primary : req;
reply_state **ptr = &r->replies;
while (*ptr) ptr = &(*ptr)->next;
*ptr = rep;
rep->next = NULL;
}
// Generates a response message giving name, type, domain, plus interface index,
// suitable for a browse result or service registration result.
// On successful completion rep is set to point to a malloc'd reply_state struct
mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id,
request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
{
domainlabel name;
domainname type, dom;
*rep = NULL;
if (!DeconstructServiceName(servicename, &name, &type, &dom))
return kDNSServiceErr_Invalid;
else
{
char namestr[MAX_DOMAIN_LABEL+1];
char typestr[MAX_ESCAPED_DOMAIN_NAME];
char domstr [MAX_ESCAPED_DOMAIN_NAME];
int len;
char *data;
ConvertDomainLabelToCString_unescaped(&name, namestr);
ConvertDomainNameToCString(&type, typestr);
ConvertDomainNameToCString(&dom, domstr);
// Calculate reply data length
len = sizeof(DNSServiceFlags);
len += sizeof(mDNSu32); // if index
len += sizeof(DNSServiceErrorType);
len += (int) (strlen(namestr) + 1);
len += (int) (strlen(typestr) + 1);
len += (int) (strlen(domstr) + 1);
// Build reply header
*rep = create_reply(op, len, request);
(*rep)->rhdr->flags = dnssd_htonl(flags);
(*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
(*rep)->rhdr->error = dnssd_htonl(err);
// Build reply body
data = (char *)&(*rep)->rhdr[1];
put_string(namestr, &data);
put_string(typestr, &data);
put_string(domstr, &data);
return mStatus_NoError;
}
}
// Special support to enable the DNSServiceBrowse call made by Bonjour Browser
// Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
mDNSlocal void GenerateBonjourBrowserResponse(const domainname *const servicename, const mDNSInterfaceID id,
request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err)
{
char namestr[MAX_DOMAIN_LABEL+1];
char typestr[MAX_ESCAPED_DOMAIN_NAME];
static const char domstr[] = ".";
int len;
char *data;
*rep = NULL;
// 1. Put first label in namestr
ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr);
// 2. Put second label and "local" into typestr
mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename));
// Calculate reply data length
len = sizeof(DNSServiceFlags);
len += sizeof(mDNSu32); // if index
len += sizeof(DNSServiceErrorType);
len += (int) (strlen(namestr) + 1);
len += (int) (strlen(typestr) + 1);
len += (int) (strlen(domstr) + 1);
// Build reply header
*rep = create_reply(op, len, request);
(*rep)->rhdr->flags = dnssd_htonl(flags);
(*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id, mDNSfalse));
(*rep)->rhdr->error = dnssd_htonl(err);
// Build reply body
data = (char *)&(*rep)->rhdr[1];
put_string(namestr, &data);
put_string(typestr, &data);
put_string(domstr, &data);
}
// Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
// Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
// (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags)
{
DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend);
mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend);
char name[256];
int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name));
mDNSu16 type = get_uint16(&request->msgptr, request->msgend);
mDNSu16 class = get_uint16(&request->msgptr, request->msgend);
mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend);
const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen);
mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0;
int storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody);
AuthRecord *rr;
mDNSInterfaceID InterfaceID;
AuthRecType artype;
request->flags = flags;
if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; }
if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; }
if (validate_flags &&
!((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) &&
!((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique))
{
LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
return NULL;
}
rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size);
if (!rr) FatalError("ERROR: malloc");
InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex);
if (InterfaceID == mDNSInterface_LocalOnly)
artype = AuthRecordLocalOnly;
else if (InterfaceID == mDNSInterface_P2P)
artype = AuthRecordP2P;
else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
artype = AuthRecordAnyIncludeP2P;
else
artype = AuthRecordAny;
mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, type, 0,
(mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), artype, mDNSNULL, mDNSNULL);
if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name))
{
LogMsg("ERROR: bad name: %s", name);
freeL("AuthRecord/read_rr_from_ipc_msg", rr);
return NULL;
}
if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue;
rr->resrec.rrclass = class;
rr->resrec.rdlength = rdlen;
rr->resrec.rdata->MaxRDLength = rdlen;
mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen);
if (GetTTL) rr->resrec.rroriginalttl = ttl;
rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
return rr;
}
mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain)
{
domainlabel n;
domainname d, t;
if (!MakeDomainLabelFromLiteralString(&n, name)) return -1;
if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1;
if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1;
if (!ConstructServiceName(srv, &n, &t, &d)) return -1;
return 0;
}
mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len)
{
int n = send(s, ptr, len, 0);
// On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
// (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
// If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
if (n < len)
LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno));
}
#if 0
mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms)
{
const DNameListElem *delem = mDNSNULL;
int bestDelta = -1; // the delta of the best match, lower is better
int dLabels = 0;
mDNSBool allow = mDNSfalse;
if (SystemUID(request->uid)) return mDNStrue;
dLabels = CountLabels(d);
for (delem = doms; delem; delem = delem->next)
{
if (delem->uid)
{
int delemLabels = CountLabels(&delem->name);
int delta = dLabels - delemLabels;
if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta)))
{
bestDelta = delta;
allow = (allow || (delem->uid == request->uid));
}
}
}
return bestDelta == -1 ? mDNStrue : allow;
}
#endif
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - external helpers
#endif
mDNSlocal void external_start_advertising_helper(service_instance *const instance)
{
AuthRecord *st = instance->subtypes;
ExtraResourceRecord *e;
int i;
if (mDNSIPPortIsZero(instance->request->u.servicereg.port))
{
LogInfo("external_start_advertising_helper: Not registering service with port number zero");
return;
}
#if APPLE_OSX_mDNSResponder
// Update packet filter if p2p interface already exists, otherwise,
// if will be updated when we get the KEV_DL_IF_ATTACHED event for
// the interface. Called here since we don't call external_start_advertising_service()
// with the SRV record when advertising a service.
mDNSInitPacketFilter();
#endif // APPLE_OSX_mDNSResponder
if (instance->external_advertise) LogMsg("external_start_advertising_helper: external_advertise already set!");
for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
external_start_advertising_service(&st[i].resrec);
external_start_advertising_service(&instance->srs.RR_PTR.resrec);
external_start_advertising_service(&instance->srs.RR_TXT.resrec);
for (e = instance->srs.Extras; e; e = e->next)
external_start_advertising_service(&e->r.resrec);
instance->external_advertise = mDNStrue;
}
mDNSlocal void external_stop_advertising_helper(service_instance *const instance)
{
AuthRecord *st = instance->subtypes;
ExtraResourceRecord *e;
int i;
if (!instance->external_advertise) return;
LogInfo("external_stop_advertising_helper: calling external_stop_advertising_service");
for ( i = 0; i < instance->request->u.servicereg.num_subtypes; i++)
external_stop_advertising_service(&st[i].resrec);
external_stop_advertising_service(&instance->srs.RR_PTR.resrec);
external_stop_advertising_service(&instance->srs.RR_TXT.resrec);
for (e = instance->srs.Extras; e; e = e->next)
external_stop_advertising_service(&e->r.resrec);
instance->external_advertise = mDNSfalse;
}
// ***************************************************************************
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - DNSServiceRegister
#endif
mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result)
{
ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext;
(void)m; // Unused
if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; }
LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec));
if (rr->resrec.rdata != &rr->rdatastorage)
freeL("Extra RData", rr->resrec.rdata);
freeL("ExtraResourceRecord/FreeExtraRR", extra);
}
mDNSlocal void unlink_and_free_service_instance(service_instance *srv)
{
ExtraResourceRecord *e = srv->srs.Extras, *tmp;
external_stop_advertising_helper(srv);
// clear pointers from parent struct
if (srv->request)
{
service_instance **p = &srv->request->u.servicereg.instances;
while (*p)
{
if (*p == srv) { *p = (*p)->next; break; }
p = &(*p)->next;
}
}
while (e)
{
e->r.RecordContext = e;
tmp = e;
e = e->next;
FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
}
if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage)
freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata);
if (srv->subtypes) { freeL("ServiceSubTypes", srv->subtypes); srv->subtypes = NULL; }
freeL("service_instance", srv);
}
// Count how many other service records we have locally with the same name, but different rdata.
// For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
// the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
mDNSexport int CountPeerRegistrations(mDNS *const m, ServiceRecordSet *const srs)
{
int count = 0;
ResourceRecord *r = &srs->RR_SRV.resrec;
AuthRecord *rr;
for (rr = m->ResourceRecords; rr; rr=rr->next)
if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r))
count++;
verbosedebugf("%d peer registrations for %##s", count, r->name->c);
return(count);
}
mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port)
{
int count = 0;
AuthRecord *rr;
for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
if (rr->resrec.rrtype == kDNSType_SRV &&
mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) &&
SameDomainName(rr->resrec.name, srv))
count++;
return(count);
}
mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs)
{
reply_state *rep;
service_instance *instance = srs->ServiceContext;
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError)
LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; }
}
// service registration callback performs three duties - frees memory for deregistered services,
// handles name conflicts, and delivers completed registration information to the client
mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
{
mStatus err;
mDNSBool SuppressError = mDNSfalse;
service_instance *instance;
reply_state *rep;
(void)m; // Unused
if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; }
instance = srs->ServiceContext;
if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; }
// don't send errors up to client for wide-area, empty-string registrations
if (instance->request &&
instance->request->u.servicereg.default_domain &&
!instance->default_local)
SuppressError = mDNStrue;
if (mDNS_LoggingEnabled)
{
const char *const fmt =
(result == mStatus_NoError) ? "%s DNSServiceRegister(%##s, %u) REGISTERED" :
(result == mStatus_MemFree) ? "%s DNSServiceRegister(%##s, %u) DEREGISTERED" :
(result == mStatus_NameConflict) ? "%s DNSServiceRegister(%##s, %u) NAME CONFLICT" :
"%s DNSServiceRegister(%##s, %u) %s %d";
char prefix[16] = "---:";
if (instance->request) mDNS_snprintf(prefix, sizeof(prefix), "%3d:", instance->request->sd);
LogOperation(fmt, prefix, srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port),
SuppressError ? "suppressed error" : "CALLBACK", result);
}
if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; }
if (result == mStatus_NoError)
{
if (instance->request->u.servicereg.allowremotequery)
{
ExtraResourceRecord *e;
srs->RR_ADV.AllowRemoteQuery = mDNStrue;
srs->RR_PTR.AllowRemoteQuery = mDNStrue;
srs->RR_SRV.AllowRemoteQuery = mDNStrue;
srs->RR_TXT.AllowRemoteQuery = mDNStrue;
for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue;
}
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
if (instance->request->u.servicereg.InterfaceID == mDNSInterface_P2P || (!instance->request->u.servicereg.InterfaceID && SameDomainName(&instance->domain, &localdomain) && (instance->request->flags & kDNSServiceFlagsIncludeP2P)))
{
LogInfo("regservice_callback: calling external_start_advertising_helper()");
external_start_advertising_helper(instance);
}
if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
RecordUpdatedNiceLabel(m, 0); // Successfully got new name, tell user immediately
}
else if (result == mStatus_MemFree)
{
if (instance->request && instance->renameonmemfree)
{
external_stop_advertising_helper(instance);
instance->renameonmemfree = 0;
err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name);
if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err);
// error should never happen - safest to log and continue
}
else
unlink_and_free_service_instance(instance);
}
else if (result == mStatus_NameConflict)
{
if (instance->request->u.servicereg.autorename)
{
external_stop_advertising_helper(instance);
if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0)
{
// On conflict for an autoname service, rename and reregister *all* autoname services
IncrementLabelSuffix(&m->nicelabel, mDNStrue);
mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange()
}
else // On conflict for a non-autoname service, rename and reregister just that one service
{
if (instance->clientnotified) SendServiceRemovalNotification(srs);
mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
}
}
else
{
if (!SuppressError)
{
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
}
unlink_and_free_service_instance(instance);
}
}
else // Not mStatus_NoError, mStatus_MemFree, or mStatus_NameConflict
{
if (!SuppressError)
{
if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError)
LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c);
else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; }
}
}
}
mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result)
{
(void)m; // Unused
if (!rr->RecordContext) // parent struct already freed by termination callback
{
if (result == mStatus_NoError)
LogMsg("Error: regrecord_callback: successful registration of orphaned record %s", ARDisplayString(m, rr));
else
{
if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result);
// We come here when the record is being deregistered either from DNSServiceRemoveRecord or connection_termination.
// If the record has been updated, we need to free the rdata. Everytime we call mDNS_Update, it calls update_callback
// with the old rdata (so that we can free it) and stores the new rdata in "rr->resrec.rdata". This means, we need
// to free the latest rdata for which the update_callback was never called with.
if (rr->resrec.rdata != &rr->rdatastorage) freeL("RData/regrecord_callback", rr->resrec.rdata);
freeL("AuthRecord/regrecord_callback", rr);
}
}
else
{
registered_record_entry *re = rr->RecordContext;
request_state *request = re->request;
if (mDNS_LoggingEnabled)
{
char *fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegisterRecord(%u %s) REGISTERED" :
(result == mStatus_MemFree) ? "%3d: DNSServiceRegisterRecord(%u %s) DEREGISTERED" :
(result == mStatus_NameConflict) ? "%3d: DNSServiceRegisterRecord(%u %s) NAME CONFLICT" :
"%3d: DNSServiceRegisterRecord(%u %s) %d";
LogOperation(fmt, request->sd, re->key, RRDisplayString(m, &rr->resrec), result);
}
if (result != mStatus_MemFree)
{
int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType);
reply_state *reply = create_reply(reg_record_reply_op, len, request);
reply->mhdr->client_context = re->regrec_client_context;
reply->rhdr->flags = dnssd_htonl(0);
reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID, mDNSfalse));
reply->rhdr->error = dnssd_htonl(result);
append_reply(request, reply);
}
if (result)
{
// unlink from list, free memory
registered_record_entry **ptr = &request->u.reg_recs;
while (*ptr && (*ptr) != re) ptr = &(*ptr)->next;
if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; }
*ptr = (*ptr)->next;
freeL("registered_record_entry AuthRecord regrecord_callback", re->rr);
freeL("registered_record_entry regrecord_callback", re);
}
else
{
if (re->external_advertise) LogMsg("regrecord_callback: external_advertise already set!");
if (re->origInterfaceID == mDNSInterface_P2P || (!re->origInterfaceID && IsLocalDomain(&rr->namestorage) && (request->flags & kDNSServiceFlagsIncludeP2P)))
{
LogInfo("regrecord_callback: calling external_start_advertising_service");
external_start_advertising_service(&rr->resrec);
re->external_advertise = mDNStrue;
}
}
}
}
mDNSlocal void connection_termination(request_state *request)
{
// When terminating a shared connection, we need to scan the all_requests list
// and terminate any subbordinate operations sharing this file descriptor
request_state **req = &all_requests;
LogOperation("%3d: DNSServiceCreateConnection STOP", request->sd);
while (*req)
{
if ((*req)->primary == request)
{
// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
request_state *tmp = *req;
if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd);
if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd);
abort_request(tmp);
*req = tmp->next;
freeL("request_state/connection_termination", tmp);
}
else
req = &(*req)->next;
}
while (request->u.reg_recs)
{
registered_record_entry *ptr = request->u.reg_recs;
LogOperation("%3d: DNSServiceRegisterRecord(%u %s) STOP", request->sd, ptr->key, RRDisplayString(&mDNSStorage, &ptr->rr->resrec));
request->u.reg_recs = request->u.reg_recs->next;
ptr->rr->RecordContext = NULL;
if (ptr->external_advertise)
{
ptr->external_advertise = mDNSfalse;
external_stop_advertising_service(&ptr->rr->resrec);
}
mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us
freeL("registered_record_entry/connection_termination", ptr);
}
}
mDNSlocal void handle_cancel_request(request_state *request)
{
request_state **req = &all_requests;
LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]);
while (*req)
{
if ((*req)->primary == request &&
(*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] &&
(*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1])
{
// Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
request_state *tmp = *req;
abort_request(tmp);
*req = tmp->next;
freeL("request_state/handle_cancel_request", tmp);
}
else
req = &(*req)->next;
}
}
mDNSlocal mStatus handle_regrecord_request(request_state *request)
{
mStatus err = mStatus_BadParamErr;
AuthRecord *rr = read_rr_from_ipc_msg(request, 1, 1);
if (rr)
{
registered_record_entry *re;
// Don't allow non-local domains to be regsitered as LocalOnly. Allowing this would permit
// clients to register records such as www.bigbank.com A w.x.y.z to redirect Safari.
if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly && !IsLocalDomain(rr->resrec.name) &&