summaryrefslogtreecommitdiffstats
path: root/netwerk/dns/mdns/libmdns/MDNSResponderOperator.cpp
blob: 72b557774905edf7527fe262c75cb657cbf03842 (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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "MDNSResponderOperator.h"
#include "MDNSResponderReply.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/Logging.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Unused.h"
#include "nsComponentManagerUtils.h"
#include "nsCOMPtr.h"
#include "nsDebug.h"
#include "nsDNSServiceInfo.h"
#include "nsHashPropertyBag.h"
#include "nsIProperty.h"
#include "nsISimpleEnumerator.h"
#include "nsIVariant.h"
#include "nsServiceManagerUtils.h"
#include "nsNetAddr.h"
#include "nsNetCID.h"
#include "nsSocketTransportService2.h"
#include "nsThreadUtils.h"
#include "nsXPCOMCID.h"
#include "private/pprio.h"

#include "nsASocketHandler.h"

namespace mozilla {
namespace net {

static LazyLogModule gMDNSLog("MDNSResponderOperator");
#undef LOG_I
#define LOG_I(...) MOZ_LOG(mozilla::net::gMDNSLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
#undef LOG_E
#define LOG_E(...) MOZ_LOG(mozilla::net::gMDNSLog, mozilla::LogLevel::Error, (__VA_ARGS__))

class MDNSResponderOperator::ServiceWatcher final
  : public nsASocketHandler
{
public:
  NS_DECL_THREADSAFE_ISUPPORTS

  // nsASocketHandler methods
  virtual void OnSocketReady(PRFileDesc* fd, int16_t outFlags) override
  {
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
    MOZ_ASSERT(fd == mFD);

    if (outFlags & (PR_POLL_ERR | PR_POLL_HUP | PR_POLL_NVAL)) {
      LOG_E("error polling on listening socket (%p)", fd);
      mCondition = NS_ERROR_UNEXPECTED;
    }

    if (!(outFlags & PR_POLL_READ)) {
      return;
    }

    DNSServiceProcessResult(mService);
  }

  virtual void OnSocketDetached(PRFileDesc *fd) override
  {
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
    MOZ_ASSERT(mThread);
    MOZ_ASSERT(fd == mFD);

    if (!mFD) {
      return;
    }

    // Bug 1175387: do not double close the handle here.
    PR_ChangeFileDescNativeHandle(mFD, -1);
    PR_Close(mFD);
    mFD = nullptr;

    mThread->Dispatch(NewRunnableMethod(this, &ServiceWatcher::Deallocate),
                      NS_DISPATCH_NORMAL);
  }

  virtual void IsLocal(bool *aIsLocal) override { *aIsLocal = true; }

  virtual void KeepWhenOffline(bool *aKeepWhenOffline) override
  {
    *aKeepWhenOffline = true;
  }

  virtual uint64_t ByteCountSent() override { return 0; }
  virtual uint64_t ByteCountReceived() override { return 0; }

  explicit ServiceWatcher(DNSServiceRef aService,
                          MDNSResponderOperator* aOperator)
    : mThread(nullptr)
    , mSts(nullptr)
    , mOperatorHolder(aOperator)
    , mService(aService)
    , mFD(nullptr)
    , mAttached(false)
  {
    if (!gSocketTransportService)
    {
      nsCOMPtr<nsISocketTransportService> sts =
        do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID);
    }
  }

  nsresult Init()
  {
    MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread);
    mThread = NS_GetCurrentThread();

    if (!mService) {
      return NS_OK;
    }

    if (!gSocketTransportService) {
      return NS_ERROR_FAILURE;
    }
    mSts = gSocketTransportService;

    int osfd = DNSServiceRefSockFD(mService);
    if (osfd == -1) {
      return NS_ERROR_FAILURE;
    }

    mFD = PR_ImportFile(osfd);
    return PostEvent(&ServiceWatcher::OnMsgAttach);
  }

  void Close()
  {
    MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread);

    if (!gSocketTransportService) {
      Deallocate();
      return;
    }

    PostEvent(&ServiceWatcher::OnMsgClose);
  }

private:
  ~ServiceWatcher() = default;

  void Deallocate()
  {
    if (mService) {
      DNSServiceRefDeallocate(mService);
      mService = nullptr;
    }
    mOperatorHolder = nullptr;
  }

  nsresult PostEvent(void(ServiceWatcher::*func)(void))
  {
    return gSocketTransportService->Dispatch(NewRunnableMethod(this, func),
                                             NS_DISPATCH_NORMAL);
  }

  void OnMsgClose()
  {
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

    if (NS_FAILED(mCondition)) {
      return;
    }

    // tear down socket. this signals the STS to detach our socket handler.
    mCondition = NS_BINDING_ABORTED;

    // if we are attached, then socket transport service will call our
    // OnSocketDetached method automatically. Otherwise, we have to call it
    // (and thus close the socket) manually.
    if (!mAttached) {
      OnSocketDetached(mFD);
    }
  }

  void OnMsgAttach()
  {
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

    if (NS_FAILED(mCondition)) {
      return;
    }

    mCondition = TryAttach();

    // if we hit an error while trying to attach then bail...
    if (NS_FAILED(mCondition)) {
      NS_ASSERTION(!mAttached, "should not be attached already");
      OnSocketDetached(mFD);
    }

  }

  nsresult TryAttach()
  {
    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

    nsresult rv;

    if (!gSocketTransportService) {
      return NS_ERROR_FAILURE;
    }

    //
    // find out if it is going to be ok to attach another socket to the STS.
    // if not then we have to wait for the STS to tell us that it is ok.
    // the notification is asynchronous, which means that when we could be
    // in a race to call AttachSocket once notified.  for this reason, when
    // we get notified, we just re-enter this function.  as a result, we are
    // sure to ask again before calling AttachSocket.  in this way we deal
    // with the race condition.  though it isn't the most elegant solution,
    // it is far simpler than trying to build a system that would guarantee
    // FIFO ordering (which wouldn't even be that valuable IMO).  see bug
    // 194402 for more info.
    //
    if (!gSocketTransportService->CanAttachSocket()) {
      nsCOMPtr<nsIRunnable> event =
        NewRunnableMethod(this, &ServiceWatcher::OnMsgAttach);

      nsresult rv = gSocketTransportService->NotifyWhenCanAttachSocket(event);
      if (NS_FAILED(rv)) {
        return rv;
      }
    }

    //
    // ok, we can now attach our socket to the STS for polling
    //
    rv = gSocketTransportService->AttachSocket(mFD, this);
    if (NS_FAILED(rv)) {
      return rv;
    }

    mAttached = true;

    //
    // now, configure our poll flags for listening...
    //
    mPollFlags = (PR_POLL_READ | PR_POLL_EXCEPT);

    return NS_OK;
  }

  nsCOMPtr<nsIThread> mThread;
  RefPtr<nsSocketTransportService> mSts;
  RefPtr<MDNSResponderOperator> mOperatorHolder;
  DNSServiceRef mService;
  PRFileDesc* mFD;
  bool mAttached;
};

NS_IMPL_ISUPPORTS(MDNSResponderOperator::ServiceWatcher, nsISupports)

MDNSResponderOperator::MDNSResponderOperator()
  : mService(nullptr)
  , mWatcher(nullptr)
  , mThread(NS_GetCurrentThread())
  , mIsCancelled(false)
{
}

MDNSResponderOperator::~MDNSResponderOperator()
{
  Stop();
}

nsresult
MDNSResponderOperator::Start()
{
  if (mIsCancelled) {
    return NS_OK;
  }

  if (IsServing()) {
    Stop();
  }

  return NS_OK;
}

nsresult
MDNSResponderOperator::Stop()
{
  return ResetService(nullptr);
}

nsresult
MDNSResponderOperator::ResetService(DNSServiceRef aService)
{
  nsresult rv;

  if (aService != mService) {
    if (mWatcher) {
      mWatcher->Close();
      mWatcher = nullptr;
    }

    if (aService) {
      RefPtr<ServiceWatcher> watcher = new ServiceWatcher(aService, this);
      if (NS_WARN_IF(NS_FAILED(rv = watcher->Init()))) {
        return rv;
      }
      mWatcher = watcher;
    }

    mService = aService;
  }
  return NS_OK;
}

BrowseOperator::BrowseOperator(const nsACString& aServiceType,
                               nsIDNSServiceDiscoveryListener* aListener)
  : MDNSResponderOperator()
  , mServiceType(aServiceType)
  , mListener(aListener)
{
}

nsresult
BrowseOperator::Start()
{
  nsresult rv;
  if (NS_WARN_IF(NS_FAILED(rv = MDNSResponderOperator::Start()))) {
    return rv;
  }

  DNSServiceRef service = nullptr;
  DNSServiceErrorType err = DNSServiceBrowse(&service,
                                             0,
                                             kDNSServiceInterfaceIndexAny,
                                             mServiceType.get(),
                                             nullptr,
                                             &BrowseReplyRunnable::Reply,
                                             this);
  NS_WARNING_ASSERTION(kDNSServiceErr_NoError == err, "DNSServiceBrowse fail");

  if (mListener) {
    if (kDNSServiceErr_NoError == err) {
      mListener->OnDiscoveryStarted(mServiceType);
    } else {
      mListener->OnStartDiscoveryFailed(mServiceType, err);
    }
  }

  if (NS_WARN_IF(kDNSServiceErr_NoError != err)) {
    return NS_ERROR_FAILURE;
  }

  return ResetService(service);
}

nsresult
BrowseOperator::Stop()
{
  bool isServing = IsServing();
  nsresult rv = MDNSResponderOperator::Stop();

  if (isServing && mListener) {
    if (NS_SUCCEEDED(rv)) {
      mListener->OnDiscoveryStopped(mServiceType);
    } else {
      mListener->OnStopDiscoveryFailed(mServiceType,
                                       static_cast<uint32_t>(rv));
    }
  }

  return rv;
}

void
BrowseOperator::Reply(DNSServiceRef aSdRef,
                      DNSServiceFlags aFlags,
                      uint32_t aInterfaceIndex,
                      DNSServiceErrorType aErrorCode,
                      const nsACString& aServiceName,
                      const nsACString& aRegType,
                      const nsACString& aReplyDomain)
{
  MOZ_ASSERT(GetThread() == NS_GetCurrentThread());

  if (NS_WARN_IF(kDNSServiceErr_NoError != aErrorCode)) {
    LOG_E("BrowseOperator::Reply (%d)", aErrorCode);
    if (mListener) {
      mListener->OnStartDiscoveryFailed(mServiceType, aErrorCode);
    }
    return;
  }

  if (!mListener) { return; }
  nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo();

  if (NS_WARN_IF(!info)) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetServiceName(aServiceName)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetServiceType(aRegType)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetDomainName(aReplyDomain)))) { return; }

  if (aFlags & kDNSServiceFlagsAdd) {
    mListener->OnServiceFound(info);
  } else {
    mListener->OnServiceLost(info);
  }
}

RegisterOperator::RegisterOperator(nsIDNSServiceInfo* aServiceInfo,
                                   nsIDNSRegistrationListener* aListener)
  : MDNSResponderOperator()
  , mServiceInfo(aServiceInfo)
  , mListener(aListener)
{
}

nsresult
RegisterOperator::Start()
{
  nsresult rv;

  rv = MDNSResponderOperator::Start();
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  uint16_t port;
  if (NS_WARN_IF(NS_FAILED(rv = mServiceInfo->GetPort(&port)))) {
    return rv;
  }
  nsAutoCString type;
  if (NS_WARN_IF(NS_FAILED(rv = mServiceInfo->GetServiceType(type)))) {
    return rv;
  }

  TXTRecordRef txtRecord;
  char buf[TXT_BUFFER_SIZE] = { 0 };
  TXTRecordCreate(&txtRecord, TXT_BUFFER_SIZE, buf);

  nsCOMPtr<nsIPropertyBag2> attributes;
  if (NS_FAILED(rv = mServiceInfo->GetAttributes(getter_AddRefs(attributes)))) {
    LOG_I("register: no attributes");
  } else {
    nsCOMPtr<nsISimpleEnumerator> enumerator;
    if (NS_WARN_IF(NS_FAILED(rv =
        attributes->GetEnumerator(getter_AddRefs(enumerator))))) {
      return rv;
    }

    bool hasMoreElements;
    while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMoreElements)) &&
           hasMoreElements) {
      nsCOMPtr<nsISupports> element;
      MOZ_ALWAYS_SUCCEEDS(enumerator->GetNext(getter_AddRefs(element)));
      nsCOMPtr<nsIProperty> property = do_QueryInterface(element);
      MOZ_ASSERT(property);

      nsAutoString name;
      nsCOMPtr<nsIVariant> value;
      MOZ_ALWAYS_SUCCEEDS(property->GetName(name));
      MOZ_ALWAYS_SUCCEEDS(property->GetValue(getter_AddRefs(value)));

      nsAutoCString str;
      if (NS_WARN_IF(NS_FAILED(value->GetAsACString(str)))) {
        continue;
      }

      TXTRecordSetValue(&txtRecord,
                        /* it's safe because key name is ASCII only. */
                        NS_LossyConvertUTF16toASCII(name).get(),
                        str.Length(),
                        str.get());
    }
  }

  nsAutoCString host;
  nsAutoCString name;
  nsAutoCString domain;

  DNSServiceRef service = nullptr;
  DNSServiceErrorType err =
    DNSServiceRegister(&service,
                       0,
                       0,
                       NS_SUCCEEDED(mServiceInfo->GetServiceName(name)) ?
                         name.get() : nullptr,
                       type.get(),
                       NS_SUCCEEDED(mServiceInfo->GetDomainName(domain)) ?
                         domain.get() : nullptr,
                       NS_SUCCEEDED(mServiceInfo->GetHost(host)) ?
                         host.get() : nullptr,
                       NativeEndian::swapToNetworkOrder(port),
                       TXTRecordGetLength(&txtRecord),
                       TXTRecordGetBytesPtr(&txtRecord),
                       &RegisterReplyRunnable::Reply,
                       this);
  NS_WARNING_ASSERTION(kDNSServiceErr_NoError == err,
                       "DNSServiceRegister fail");

  TXTRecordDeallocate(&txtRecord);

  if (NS_WARN_IF(kDNSServiceErr_NoError != err)) {
    if (mListener) {
      mListener->OnRegistrationFailed(mServiceInfo, err);
    }
    return NS_ERROR_FAILURE;
  }

  return ResetService(service);
}

nsresult
RegisterOperator::Stop()
{
  bool isServing = IsServing();
  nsresult rv = MDNSResponderOperator::Stop();

  if (isServing && mListener) {
    if (NS_SUCCEEDED(rv)) {
      mListener->OnServiceUnregistered(mServiceInfo);
    } else {
      mListener->OnUnregistrationFailed(mServiceInfo,
                                        static_cast<uint32_t>(rv));
    }
  }

  return rv;
}

void
RegisterOperator::Reply(DNSServiceRef aSdRef,
                        DNSServiceFlags aFlags,
                        DNSServiceErrorType aErrorCode,
                        const nsACString& aName,
                        const nsACString& aRegType,
                        const nsACString& aDomain)
{
  MOZ_ASSERT(GetThread() == NS_GetCurrentThread());

  if (kDNSServiceErr_NoError != aErrorCode) {
    LOG_E("RegisterOperator::Reply (%d)", aErrorCode);
  }

  if (!mListener) { return; }
  nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo(mServiceInfo);
  if (NS_WARN_IF(NS_FAILED(info->SetServiceName(aName)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetServiceType(aRegType)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetDomainName(aDomain)))) { return; }

  if (kDNSServiceErr_NoError == aErrorCode) {
    if (aFlags & kDNSServiceFlagsAdd) {
      mListener->OnServiceRegistered(info);
    } else {
      // If a successfully-registered name later suffers a name conflict
      // or similar problem and has to be deregistered, the callback will
      // be invoked with the kDNSServiceFlagsAdd flag not set.
      LOG_E("RegisterOperator::Reply: deregister");
      if (NS_WARN_IF(NS_FAILED(Stop()))) {
        return;
      }
    }
  } else {
    mListener->OnRegistrationFailed(info, aErrorCode);
  }
}

ResolveOperator::ResolveOperator(nsIDNSServiceInfo* aServiceInfo,
                                 nsIDNSServiceResolveListener* aListener)
  : MDNSResponderOperator()
  , mServiceInfo(aServiceInfo)
  , mListener(aListener)
{
}

nsresult
ResolveOperator::Start()
{
  nsresult rv;
  if (NS_WARN_IF(NS_FAILED(rv = MDNSResponderOperator::Start()))) {
    return rv;
  }

  nsAutoCString name;
  mServiceInfo->GetServiceName(name);
  nsAutoCString type;
  mServiceInfo->GetServiceType(type);
  nsAutoCString domain;
  mServiceInfo->GetDomainName(domain);

  LOG_I("Resolve: (%s), (%s), (%s)", name.get(), type.get(), domain.get());

  DNSServiceRef service = nullptr;
  DNSServiceErrorType err =
    DNSServiceResolve(&service,
                      0,
                      kDNSServiceInterfaceIndexAny,
                      name.get(),
                      type.get(),
                      domain.get(),
                      (DNSServiceResolveReply)&ResolveReplyRunnable::Reply,
                      this);

  if (NS_WARN_IF(kDNSServiceErr_NoError != err)) {
    if (mListener) {
      mListener->OnResolveFailed(mServiceInfo, err);
    }
    return NS_ERROR_FAILURE;
  }

  return ResetService(service);
}

void
ResolveOperator::Reply(DNSServiceRef aSdRef,
                       DNSServiceFlags aFlags,
                       uint32_t aInterfaceIndex,
                       DNSServiceErrorType aErrorCode,
                       const nsACString& aFullName,
                       const nsACString& aHostTarget,
                       uint16_t aPort,
                       uint16_t aTxtLen,
                       const unsigned char* aTxtRecord)
{
  MOZ_ASSERT(GetThread() == NS_GetCurrentThread());

  auto guard = MakeScopeExit([&] {
    Unused << NS_WARN_IF(NS_FAILED(Stop()));
  });

  if (NS_WARN_IF(kDNSServiceErr_NoError != aErrorCode)) {
    LOG_E("ResolveOperator::Reply (%d)", aErrorCode);
    return;
  }

  // Resolve TXT record
  int count = TXTRecordGetCount(aTxtLen, aTxtRecord);
  LOG_I("resolve: txt count = %d, len = %d", count, aTxtLen);
  nsCOMPtr<nsIWritablePropertyBag2> attributes = new nsHashPropertyBag();
  if (NS_WARN_IF(!attributes)) {
    return;
  }
  if (count) {
    for (int i = 0; i < count; ++i) {
      char key[TXT_BUFFER_SIZE] = { '\0' };
      uint8_t vSize = 0;
      const void* value = nullptr;
      if (kDNSServiceErr_NoError !=
          TXTRecordGetItemAtIndex(aTxtLen,
                                  aTxtRecord,
                                  i,
                                  TXT_BUFFER_SIZE,
                                  key,
                                  &vSize,
                                  &value)) {
        break;
      }

      nsAutoCString str(reinterpret_cast<const char*>(value), vSize);
      LOG_I("resolve TXT: (%d) %s=%s", vSize, key, str.get());

      if (NS_WARN_IF(NS_FAILED(attributes->SetPropertyAsACString(
          /* it's safe to convert because key name is ASCII only. */
          NS_ConvertASCIItoUTF16(key),
          str)))) {
        break;
      }
    }
  }

  if (!mListener) { return; }
  nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo(mServiceInfo);
  if (NS_WARN_IF(NS_FAILED(info->SetHost(aHostTarget)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetPort(aPort)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetAttributes(attributes)))) { return; }

  if (kDNSServiceErr_NoError == aErrorCode) {
    GetAddrInfor(info);
  }
  else {
    mListener->OnResolveFailed(info, aErrorCode);
    Unused << NS_WARN_IF(NS_FAILED(Stop()));
  }
}

void
ResolveOperator::GetAddrInfor(nsIDNSServiceInfo* aServiceInfo)
{
  RefPtr<GetAddrInfoOperator> getAddreOp = new GetAddrInfoOperator(aServiceInfo,
                                                                   mListener);
  Unused << NS_WARN_IF(NS_FAILED(getAddreOp->Start()));
}

GetAddrInfoOperator::GetAddrInfoOperator(nsIDNSServiceInfo* aServiceInfo,
                                         nsIDNSServiceResolveListener* aListener)
  : MDNSResponderOperator()
  , mServiceInfo(aServiceInfo)
  , mListener(aListener)
{
}

nsresult
GetAddrInfoOperator::Start()
{
  nsresult rv;
  if (NS_WARN_IF(NS_FAILED(rv = MDNSResponderOperator::Start()))) {
    return rv;
  }

  nsAutoCString host;
  mServiceInfo->GetHost(host);

  LOG_I("GetAddrInfo: (%s)", host.get());

  DNSServiceRef service = nullptr;
  DNSServiceErrorType err =
    DNSServiceGetAddrInfo(&service,
                          kDNSServiceFlagsForceMulticast,
                          kDNSServiceInterfaceIndexAny,
                          kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6,
                          host.get(),
                          (DNSServiceGetAddrInfoReply)&GetAddrInfoReplyRunnable::Reply,
                          this);

  if (NS_WARN_IF(kDNSServiceErr_NoError != err)) {
    if (mListener) {
      mListener->OnResolveFailed(mServiceInfo, err);
    }
    return NS_ERROR_FAILURE;
  }

  return ResetService(service);
}

void
GetAddrInfoOperator::Reply(DNSServiceRef aSdRef,
                           DNSServiceFlags aFlags,
                           uint32_t aInterfaceIndex,
                           DNSServiceErrorType aErrorCode,
                           const nsACString& aHostName,
                           const NetAddr& aAddress,
                           uint32_t aTTL)
{
  MOZ_ASSERT(GetThread() == NS_GetCurrentThread());

  auto guard = MakeScopeExit([&] {
    Unused << NS_WARN_IF(NS_FAILED(Stop()));
  });

  if (NS_WARN_IF(kDNSServiceErr_NoError != aErrorCode)) {
    LOG_E("GetAddrInfoOperator::Reply (%d)", aErrorCode);
    return;
  }

  if (!mListener) { return; }

  NetAddr addr = aAddress;
  nsCOMPtr<nsINetAddr> address = new nsNetAddr(&addr);
  nsCString addressStr;
  if (NS_WARN_IF(NS_FAILED(address->GetAddress(addressStr)))) { return; }

  nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo(mServiceInfo);
  if (NS_WARN_IF(NS_FAILED(info->SetAddress(addressStr)))) { return; }

  /**
   * |kDNSServiceFlagsMoreComing| means this callback will be one or more
   * callback events later, so this instance should be kept alive until all
   * follow-up events are processed.
   */
  if (aFlags & kDNSServiceFlagsMoreComing) {
    guard.release();
  }

  if (kDNSServiceErr_NoError == aErrorCode) {
    mListener->OnServiceResolved(info);
  } else {
    mListener->OnResolveFailed(info, aErrorCode);
  }
}

} // namespace net
} // namespace mozilla