summaryrefslogtreecommitdiffstats
path: root/netwerk/base/nsNetworkInfoService.cpp
blob: 91354a80bbf3ca92495ebc06c5892911f60b061f (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */

#if defined(XP_MACOSX) || defined(XP_LINUX)
#  include <unistd.h>
#elif defined(XP_WIN)
#  include <winsock2.h>
#endif

#include "nsNetworkInfoService.h"

#if defined(XP_MACOSX) || defined(XP_WIN) || defined(XP_LINUX)
#  include "NetworkInfoServiceImpl.h"
#else
#  error "Unsupported platform for nsNetworkInfoService!  Check moz.build"
#endif

namespace mozilla::net {

NS_IMPL_ISUPPORTS(nsNetworkInfoService, nsINetworkInfoService)

nsNetworkInfoService::nsNetworkInfoService() = default;

nsresult nsNetworkInfoService::Init() { return NS_OK; }

nsresult nsNetworkInfoService::ListNetworkAddresses(
    nsIListNetworkAddressesListener* aListener) {
  nsresult rv;

  AddrMapType addrMap;
  rv = DoListAddresses(addrMap);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    aListener->OnListNetworkAddressesFailed();
    return NS_OK;
  }

  uint32_t addrCount = addrMap.Count();
  nsTArray<nsCString> addrStrings;
  if (!addrStrings.SetCapacity(addrCount, fallible)) {
    aListener->OnListNetworkAddressesFailed();
    return NS_OK;
  }

  for (const auto& data : addrMap.Values()) {
    addrStrings.AppendElement(data);
  }
  aListener->OnListedNetworkAddresses(addrStrings);
  return NS_OK;
}

// TODO: Bug 1275373: https://bugzilla.mozilla.org/show_bug.cgi?id=1275373
// Use platform-specific implementation of DoGetHostname on Cocoa and Windows.
static nsresult DoGetHostname(nsACString& aHostname) {
  char hostnameBuf[256];
  int result = gethostname(hostnameBuf, 256);
  if (result == -1) {
    return NS_ERROR_FAILURE;
  }

  // Ensure that there is always a terminating NUL byte.
  hostnameBuf[255] = '\0';

  // Find the first '.', terminate string there.
  char* dotLocation = strchr(hostnameBuf, '.');
  if (dotLocation) {
    *dotLocation = '\0';
  }

  if (strlen(hostnameBuf) == 0) {
    return NS_ERROR_FAILURE;
  }

  aHostname.AssignASCII(hostnameBuf);
  return NS_OK;
}

nsresult nsNetworkInfoService::GetHostname(nsIGetHostnameListener* aListener) {
  nsresult rv;
  nsCString hostnameStr;
  rv = DoGetHostname(hostnameStr);
  if (NS_FAILED(rv)) {
    aListener->OnGetHostnameFailed();
    return NS_OK;
  }

  aListener->OnGotHostname(hostnameStr);

  return NS_OK;
}

}  // namespace mozilla::net