1'use strict'; 2 3const { 4 RegExp, 5 RegExpPrototypeTest, 6 Symbol, 7} = primordials; 8 9const Buffer = require('buffer').Buffer; 10const { writeBuffer } = internalBinding('fs'); 11const errors = require('internal/errors'); 12 13// IPv4 Segment 14const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'; 15const v4Str = `(${v4Seg}[.]){3}${v4Seg}`; 16const IPv4Reg = new RegExp(`^${v4Str}$`); 17 18// IPv6 Segment 19const v6Seg = '(?:[0-9a-fA-F]{1,4})'; 20const IPv6Reg = new RegExp('^(' + 21 `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + 22 `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + 23 `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + 24 `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + 25 `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + 26 `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + 27 `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + 28 `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + 29')(%[0-9a-zA-Z-.:]{1,})?$'); 30 31function isIPv4(s) { 32 // TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it 33 // no longer creates a perf regression in the dns benchmark. 34 // eslint-disable-next-line node-core/avoid-prototype-pollution 35 return RegExpPrototypeTest(IPv4Reg, s); 36} 37 38function isIPv6(s) { 39 // TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it 40 // no longer creates a perf regression in the dns benchmark. 41 // eslint-disable-next-line node-core/avoid-prototype-pollution 42 return RegExpPrototypeTest(IPv6Reg, s); 43} 44 45function isIP(s) { 46 if (isIPv4(s)) return 4; 47 if (isIPv6(s)) return 6; 48 return 0; 49} 50 51function makeSyncWrite(fd) { 52 return function(chunk, enc, cb) { 53 if (enc !== 'buffer') 54 chunk = Buffer.from(chunk, enc); 55 56 this._handle.bytesWritten += chunk.length; 57 58 const ctx = {}; 59 writeBuffer(fd, chunk, 0, chunk.length, null, undefined, ctx); 60 if (ctx.errno !== undefined) { 61 const ex = errors.uvException(ctx); 62 ex.errno = ctx.errno; 63 return cb(ex); 64 } 65 cb(); 66 }; 67} 68 69module.exports = { 70 kReinitializeHandle: Symbol('reinitializeHandle'), 71 isIP, 72 isIPv4, 73 isIPv6, 74 makeSyncWrite, 75 normalizedArgsSymbol: Symbol('normalizedArgs'), 76}; 77