Update Iot.js
[platform/upstream/iotjs.git] / tools / src / js / dns.js
1 /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 var util = require('util');
17 var dnsBuiltin = process.binding(process.binding.dns);
18
19 function dnsException(err, syscall, hostname) {
20   var ex = new Error(syscall + ' ' + err + (hostname ? ' ' + hostname : ''));
21   // TODO(hanjoung.lee@samsung.com) err should be a string (currently a number)
22   ex.code = err;
23   ex.errno = err;
24   ex.syscall = syscall;
25   if (hostname) {
26     ex.hostname = hostname;
27   }
28   return ex;
29 }
30
31
32 exports.lookup = function lookup(hostname, options, callback) {
33   var hints = 0;
34   var family = -1;
35
36   // Parse arguments
37   if (!util.isString(hostname)) {
38     throw TypeError('invalid argument: hostname must be a string');
39   }
40   if (util.isFunction(options)) {
41     callback = options;
42     family = 0;
43   } else if (!util.isFunction(callback)) {
44     throw TypeError('invalid argument: callback must be passed');
45   } else if (util.isObject(options)) {
46     hints = options.hints >>> 0;
47     family = options.family >>> 0;
48
49     if (hints < 0 || hints > (exports.ADDRCONFIG | exports.V4MAPPED)) {
50       throw new TypeError('invalid argument: invalid hints flags');
51     }
52   } else if (util.isNumber(options)) {
53     family = ~~options;
54   } else {
55     throw TypeError(
56         'invalid argument: options must be either an object or number');
57   }
58
59   if (family !== 0 && family !== 4 && family !== 6)
60     throw new TypeError('invalid argument: family must be 4 or 6');
61
62   var err = dnsBuiltin.getaddrinfo(
63       hostname,
64       family,
65       hints,
66       function(err, address, family) {
67         var errObj = null;
68         if (err) {
69           errObj = dnsException(err, 'getaddrinfo', hostname);
70         }
71         return callback(errObj, address, family);
72       });
73   return err;
74 };
75
76
77 // uv_getaddrinfo flags
78 exports.ADDRCONFIG = dnsBuiltin.AI_ADDRCONFIG;
79 exports.V4MAPPED = dnsBuiltin.AI_V4MAPPED;