1
0
mirror of https://github.com/ArcticFoxes-net/ONC-Converter synced 2024-09-19 16:14:43 -04:00
ONC-Converter/js/parser.js

92 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-11-17 16:58:24 -05:00
/**
* Parse *.ovpn file.
*/
2017-11-15 12:31:02 -05:00
export function decode (str) {
2017-11-17 16:58:24 -05:00
let ovpn = {}
let keys = {}
2017-11-15 12:31:02 -05:00
const re = /^([^ ]+)( (.*))?$/i
const xmlOpen = /^<([^\/].*)>$/i
const xmlClose = /^<\/(.*)>$/i
let xmlTag = ''
let inXml = false
let xmlContent = ''
let lines = str.split(/[\r\n]+/g)
for (let line of lines) {
if (!line || line.match(/^\s*[;#]/)) continue
if (inXml) {
const xmlMatch = line.match(xmlClose)
if (!xmlMatch) {
xmlContent += line + '\n'
continue
}
const tag = xmlMatch[1]
if (tag !== xmlTag) {
throw 'bad xml tag'
}
2017-11-17 16:58:24 -05:00
const name = unsafe(xmlTag)
2017-11-15 12:31:02 -05:00
const value = unsafe(xmlContent)
2017-11-17 16:58:24 -05:00
keys[name] = value
ovpn[name] = name
2017-11-15 12:31:02 -05:00
xmlContent = ''
inXml = false
continue
}
const xmlMatch = line.match(xmlOpen)
if (xmlMatch) {
inXml = true
xmlTag = xmlMatch[1]
continue
}
const match = line.match(re)
if (!match) continue
const key = unsafe(match[1])
const value = match[2] ? unsafe((match[3] || '')) : true
2017-11-17 16:58:24 -05:00
ovpn[key] = value
2017-11-15 12:31:02 -05:00
}
2017-11-17 16:58:24 -05:00
return [ovpn, keys]
2017-11-15 12:31:02 -05:00
}
function isQuoted (val) {
2017-11-17 09:53:06 -05:00
return ((val.charAt(0) === '"' && val.slice(-1) === '"') ||
(val.charAt(0) === "'" && val.slice(-1) === "'"))
2017-11-15 12:31:02 -05:00
}
function unsafe (val, doUnesc) {
val = (val || '').trim()
if (isQuoted(val)) {
// remove the single quotes before calling JSON.parse
if (val.charAt(0) === "'") {
val = val.substr(1, val.length - 2)
}
try { val = JSON.parse(val) } catch (_) {}
} else {
// walk the val to find the first not-escaped ; character
var esc = false
var unesc = ''
for (var i = 0, l = val.length; i < l; i++) {
var c = val.charAt(i)
if (esc) {
if ('\\;#'.indexOf(c) !== -1) {
unesc += c
} else {
unesc += '\\' + c
}
esc = false
} else if (';#'.indexOf(c) !== -1) {
break
} else if (c === '\\') {
esc = true
} else {
unesc += c
}
}
if (esc) {
unesc += '\\'
}
return unesc
}
return val
}