Parses a RFC822 message into a structured object (JSON compatible)

@constructor
@param {String|Buffer} rfc822 Raw body of the message
329924
function Parser(rfc822) {

    // ensure the input is a binary string
    this.rfc822 = (rfc822 || "").toString("binary");

    this._br = "";
    this._pos = 0;

    this.rawBody = "";

    this.tree = {
        childNodes: []
    };
    this._node = this.createNode(this.tree);
}
39179
function parseBodyParam (req, res, next) {
  let params = getParams(req);

  params.some((param) => {
    if (param.in === "body") {
      util.debug('    Parsing the "%s" body parameter', param.name);

      if (_.isPlainObject(req.body) && _.isEmpty(req.body)) {
        if (param.type === "string" || (param.schema && param.schema.type === "string")) {
          // Convert {} to ""
          req.body = "";
        }
        else {
          // Convert {} to undefined
          req.body = undefined;
        }
      }

      // Parse the body
      req.body = parseParameter(param, req.body, param.schema);

      // There can only be one "body" parameter, so skip the rest
      return true;
    }
  });

  // If there are no body/formData parameters, then reset `req.body` to undefined
  if (params.length > 0) {
    let hasBody = params.some((param) => {
      return param.in === "body" || param.in === "formData";
    });

    if (!hasBody) {
      req.body = undefined;
    }
  }

  next();
}
759216
function parse_plain(&$p, $body = null)
    {
        $part = $p['structure'];

        // Get message body from IMAP server
        if ($body === null) {
            $body = $this->get_part_body($p['object'], $part);
        }

        // In this way we can use fgets on string as on file handle
        // Don't use php://temp for security (body may come from an encrypted part)
        $fd = fopen('php://memory', 'r+');
        if (!$fd) {
            return;
        }

        fwrite($fd, $body);
        rewind($fd);

        $body   = '';
        $prefix = '';
        $mode   = '';
        $tokens = array(
            'BEGIN PGP SIGNED MESSAGE' => 'signed-start',
            'END PGP SIGNATURE'        => 'signed-end',
            'BEGIN PGP MESSAGE'        => 'encrypted-start',
            'END PGP MESSAGE'          => 'encrypted-end',
        );
        $regexp = '/^-----(' . implode('|', array_keys($tokens)) . ')-----[\r\n]*/';

        while (($line = fgets($fd)) !== false) {
            if ($line[0] === '-' && $line[4] === '-' && preg_match($regexp, $line, $m)) {
                switch ($tokens[$m[1]]) {
                case 'signed-start':
                    $body = $line;
                    $mode = 'signed';
                    break;

                case 'signed-end':
                    if ($mode === 'signed') {
                        $body .= $line;
                    }
                    break 2; // ignore anything after this line

                case 'encrypted-start':
                    $body = $line;
                    $mode = 'encrypted';
                    break;

                case 'encrypted-end':
                    if ($mode === 'encrypted') {
                        $body .= $line;
                    }
                    break 2; // ignore anything after this line
                }

                continue;
            }

            if ($mode === 'signed') {
                $body .= $line;
            }
            else if ($mode === 'encrypted') {
                $body .= $line;
            }
            else {
                $prefix .= $line;
            }
        }

        fclose($fd);

        if ($mode === 'signed') {
            $this->parse_plain_signed($p, $body, $prefix);
        }
        else if ($mode === 'encrypted') {
            $this->parse_plain_encrypted($p, $body, $prefix);
        }
    }
1131523
function parse (string) {
  if (!string) {
    throw new TypeError('argument string is required')
  }

  // support req/res-like objects as argument
  var header = typeof string === 'object'
    ? getcontenttype(string)
    : string

  if (typeof header !== 'string') {
    throw new TypeError('argument string is required to be a string')
  }

  var index = header.indexOf(';')
  var type = index !== -1
    ? header.substr(0, index).trim()
    : header.trim()

  if (!TYPE_REGEXP.test(type)) {
    throw new TypeError('invalid media type')
  }

  var obj = new ContentType(type.toLowerCase())

  // parse parameters
  if (index !== -1) {
    var key
    var match
    var value

    PARAM_REGEXP.lastIndex = index

    while ((match = PARAM_REGEXP.exec(header))) {
      if (match.index !== index) {
        throw new TypeError('invalid parameter format')
      }

      index += match[0].length
      key = match[1].toLowerCase()
      value = match[2]

      if (value[0] === '"') {
        // remove quotes and escapes
        value = value
          .substr(1, value.length - 2)
          .replace(QESC_REGEXP, '$1')
      }

      obj.parameters[key] = value
    }

    if (index !== header.length) {
      throw new TypeError('invalid parameter format')
    }
  }

  return obj
}
1088394
function (body, next) {
                parseString(body, function (err, json) {
                    if (err) {
                        return next(err);
                    }
                    next(null, json);
                });
            }
721032
function raw (options) {
  var opts = options || {}

  var inflate = opts.inflate !== false
  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var type = opts.type || 'application/octet-stream'
  var verify = opts.verify || false

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  // create the appropriate type checking function
  var shouldParse = typeof type !== 'function'
    ? typeChecker(type)
    : type

  function parse (buf) {
    return buf
  }

  return function rawParser (req, res, next) {
    if (req._body) {
      debug('body already parsed')
      next()
      return
    }

    req.body = req.body || {}

    // skip requests without bodies
    if (!typeis.hasBody(req)) {
      debug('skip empty body')
      next()
      return
    }

    debug('content-type %j', req.headers['content-type'])

    // determine if request should be parsed
    if (!shouldParse(req)) {
      debug('skip parsing')
      next()
      return
    }

    // read
    read(req, res, next, parse, debug, {
      encoding: null,
      inflate: inflate,
      limit: limit,
      verify: verify
    })
  }
}
890352
function json (options) {
  var opts = options || {}

  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var inflate = opts.inflate !== false
  var reviver = opts.reviver
  var strict = opts.strict !== false
  var type = opts.type || 'application/json'
  var verify = opts.verify || false

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  // create the appropriate type checking function
  var shouldParse = typeof type !== 'function'
    ? typeChecker(type)
    : type

  function parse (body) {
    if (body.length === 0) {
      // special-case empty json body, as it's a common client-side mistake
      // TODO: maybe make this configurable or part of "strict" option
      return {}
    }

    if (strict) {
      var first = firstchar(body)

      if (first !== '{' && first !== '[') {
        debug('strict violation')
        throw new SyntaxError('Unexpected token ' + first)
      }
    }

    debug('parse json')
    return JSON.parse(body, reviver)
  }

  return function jsonParser (req, res, next) {
    if (req._body) {
      debug('body already parsed')
      next()
      return
    }

    req.body = req.body || {}

    // skip requests without bodies
    if (!typeis.hasBody(req)) {
      debug('skip empty body')
      next()
      return
    }

    debug('content-type %j', req.headers['content-type'])

    // determine if request should be parsed
    if (!shouldParse(req)) {
      debug('skip parsing')
      next()
      return
    }

    // assert charset per RFC 7159 sec 8.1
    var charset = getCharset(req) || 'utf-8'
    if (charset.substr(0, 4) !== 'utf-') {
      debug('invalid charset')
      next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
        charset: charset
      }))
      return
    }

    // read
    read(req, res, next, parse, debug, {
      encoding: charset,
      inflate: inflate,
      limit: limit,
      verify: verify
    })
  }
}
23698
function(text) {
			var result = text;
			try {
				switch (this._headers.Accept) {
					case "application/json":
						result = JSON.parse(text);
						break;
					case "text/xml":
						result = new DOMParser().parseFromString(text, "text/xml");
						break;
				}
			} catch (exception) {
				if (gui.debug) {
					console.error(
						this._headers.Accept + " dysfunction at " + this._url
					);
				}
			}
			return result;
		}
662747
def parse(cls, line, encoding=pydle.protocol.DEFAULT_ENCODING):
        
        valid = True
        # Decode message.
        try:
            message = line.decode(encoding)
        except UnicodeDecodeError:
            # Try our fallback encoding.
            message = line.decode(pydle.protocol.FALLBACK_ENCODING)

        # Sanity check for message length.
        if len(message) > TAGGED_MESSAGE_LENGTH_LIMIT:
            valid = False

        # Strip message separator.
        if message.endswith(rfc1459.protocol.LINE_SEPARATOR):
            message = message[:-len(rfc1459.protocol.LINE_SEPARATOR)]
        elif message.endswith(rfc1459.protocol.MINIMAL_LINE_SEPARATOR):
            message = message[:-len(rfc1459.protocol.MINIMAL_LINE_SEPARATOR)]
        raw = message

        # Parse tags.
        tags = {}
        if message.startswith(TAG_INDICATOR):
            message = message[len(TAG_INDICATOR):]
            raw_tags, message = message.split(' ', 1)

            for raw_tag in raw_tags.split(TAG_SEPARATOR):
                if TAG_VALUE_SEPARATOR in raw_tag:
                    tag, value = raw_tag.split(TAG_VALUE_SEPARATOR, 1)
                else:
                    tag = raw_tag
                    value = True
                tags[tag] = value

        # Parse rest of message.
        message = super().parse(message.lstrip().encode(encoding), encoding=encoding)
        return TaggedMessage(_raw=raw, _valid=message._valid and valid, tags=tags, **message._kw)
911034
function processRFC822Node(node, options) {
    options = options || {};
    var message = mimeParser(node.body || ''),
        data = [].concat(getBasicFields(node, options));

    data.push(envelope(message.parsedHeader));
    data.push(createBodystructure(message, options));
    data = data.concat(
            node.lineCount
        ).
        concat(getExtensionFields(node, options));

    node.text = message.text;

    data.node = node;
    return data;
}
693145
function parseBODYSTRUCTURE(node, path = []) {
  let curNode = {};
  let i = 0;
  let part = 0;

  if (path.length) {
    curNode.part = path.join('.');
  }

  // multipart
  if (Array.isArray(node[0])) {
    curNode.childNodes = [];
    while (Array.isArray(node[i])) {
      curNode.childNodes.push(parseBODYSTRUCTURE(node[i], path.concat(++part)));
      i++;
    }

    // multipart type
    curNode.type = 'multipart/' + ((node[i++] || {}).value || '').toString().toLowerCase();

    // extension data (not available for BODY requests)

    // body parameter parenthesized list
    if (i < node.length - 1) {
      if (node[i]) {
        curNode.parameters = attributesToObject(node[i]);
      }
      i++;
    }
  } else {
    // content type
    curNode.type = [((node[i++] || {}).value || '').toString().toLowerCase(), ((node[i++] || {}).value || '').toString().toLowerCase()].join('/');

    // body parameter parenthesized list
    if (node[i]) {
      curNode.parameters = attributesToObject(node[i]);
    }
    i++;

    // id
    if (node[i]) {
      curNode.id = ((node[i] || {}).value || '').toString();
    }
    i++;

    // description
    if (node[i]) {
      curNode.description = ((node[i] || {}).value || '').toString();
    }
    i++;

    // encoding
    if (node[i]) {
      curNode.encoding = ((node[i] || {}).value || '').toString().toLowerCase();
    }
    i++;

    // size
    if (node[i]) {
      curNode.size = Number((node[i] || {}).value || 0) || 0;
    }
    i++;

    if (curNode.type === 'message/rfc822') {
      // message/rfc adds additional envelope, bodystructure and line count values

      // envelope
      if (node[i]) {
        curNode.envelope = parseENVELOPE([].concat(node[i] || []));
      }
      i++;

      if (node[i]) {
        curNode.childNodes = [
        // rfc822 bodyparts share the same path, difference is between MIME and HEADER
        // path.MIME returns message/rfc822 header
        // path.HEADER returns inlined message header
        parseBODYSTRUCTURE(node[i], path)];
      }
      i++;

      // line count
      if (node[i]) {
        curNode.lineCount = Number((node[i] || {}).value || 0) || 0;
      }
      i++;
    } else if (/^text\//.test(curNode.type)) {
      // text/* adds additional line count values

      // line count
      if (node[i]) {
        curNode.lineCount = Number((node[i] || {}).value || 0) || 0;
      }
      i++;
    }

    // extension data (not available for BODY requests)

    // md5
    if (i < node.length - 1) {
      if (node[i]) {
        curNode.md5 = ((node[i] || {}).value || '').toString().toLowerCase();
      }
      i++;
    }
  }

  // the following are shared extension values (for both multipart and non-multipart parts)
  // not available for BODY requests

  // body disposition
  if (i < node.length - 1) {
    if (Array.isArray(node[i]) && node[i].length) {
      curNode.disposition = ((node[i][0] || {}).value || '').toString().toLowerCase();
      if (Array.isArray(node[i][1])) {
        curNode.dispositionParameters = attributesToObject(node[i][1]);
      }
    }
    i++;
  }

  // body language
  if (i < node.length - 1) {
    if (node[i]) {
      curNode.language = [].concat(node[i]).map(val => (0, _ramda.propOr)('', 'value', val).toLowerCase());
    }
    i++;
  }

  // body location
  // NB! defined as a "string list" in RFC3501 but replaced in errata document with "string"
  // Errata: http://www.rfc-editor.org/errata_search.php?rfc=3501
  if (i < node.length - 1) {
    if (node[i]) {
      curNode.location = ((node[i] || {}).value || '').toString();
    }
    i++;
  }

  return curNode;
}
874018
def parse(self, mimetypes):
        

        self._parse_top_level_content_type()

        link = 'tools.ietf.org/html/rfc2388'
        parts = cgi.FieldStorage(
            fp=self.req.stream,
            environ=self.req.env,
        )

        if not parts:
            self.fail('A payload in the body of your request is required '
                      '& must be encapsulated by the boundary with proper '
                      'headers according to RFC 2388', link)
        elif len(parts) > 1:
            self.fail('Currently, only 1 upload at a time is allowed. Please '
                      'break up your request into %s individual requests & '
                      'retry' % len(parts), link)
        else:
            self._parse_part(parts.list[0], mimetypes)
            return parts
233137
function parseResponse(body) {
  var pgt = '';
  var result = body.match(/action="([\s\S]*?)"/);
  if (result) {
    result = result[1];

    var uri = url.parse(result, true);
    var pathname = uri.pathname;

    pgt = pathname.substr(pathname.lastIndexOf('/') + 1);
  }

  return pgt;
}
819016
function parse(primus, raw, res) {
  var called = 0
    , data
    , err;

  try {
    data = JSON.parse(raw);
  } catch (e) {
    err = e;
  }

  if (
       err                              // No error..
    || 'object' !== typeof data         // Should be an object.
    || Array.isArray(data)              // A real object, not array.
    || !data.msg                        // The data we send should be defined.
  ) {
    res.statusCode = 500;
    res.setHeader('Content-Type', 'application/json');
    return res.end('{ "ok": false, "reason": "invalid data structure" }');
  }

  //
  // Process the incoming messages in three different modes:
  //
  // Sparks: The data.sparks is an array with spark id's which we should write
  //         the data to.
  // Spark:  The data.sparks is the id of one single individual spark which
  //         should receive the data.
  // All:    Broadcast the message to every single connected spark if no
  //         `data.sparks` has been provided.
  //
  if (Array.isArray(data.sparks)) {
    data.sparks.forEach(function each(id) {
      var spark = primus.spark(id);

      if (spark) {
        spark.write(data.msg);
        called++;
      }
    });
  } else if ('string' === typeof data.sparks && data.sparks) {
    var spark = primus.spark(data.sparks);

    if (spark) {
      spark.write(data.msg);
      called++;
    }
  } else {
    primus.forEach(function each(spark) {
      spark.write(data.msg);
      called++;
    });
  }

  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.end('{ "ok": true, "send":'+ called +' }');
}
466013
function Request_parse() {
        var that = this, url = this.url;
        if (this.isForwarded) {
            return this._process()
                .then(function destroy() {
                    logger.info('Request.destroy', {
                        url: that.url,
                        status: that.statusCode,
                        id: that.id,
                        isRendered: that.isRendered,
                        content_type: that.getHeader('content-type')
                    });
                    that._destroy();
                })
                .catch(function error(e) {
                    logger.error('Request.destroy', {error: e, url: url});
                });
        }
        // receive body as buffer
        this.request.on('data', this.body.push.bind(this.body));

        return new Promise(this.request.on.bind(this.request, 'end'))
            .then(this._process.bind(this))
            .then(function destroy() {
                logger.info('Request.destroy', {
                    url: that.url,
                    status: that.statusCode,
                    id: that.id,
                    isRendered: that.isRendered,
                    content_type: that.getHeader('content-type')
                });
                that._destroy();
            })
            .catch(function error(e) {
                logger.error('Request.destroy', {error: e, url: url});
            });

    }
753217
function parseWebSocketEvent(event) {
      try {
        var params = JSON.parse(event.data);

        if (typeof params.data === 'string') {
          try {
            params.data = JSON.parse(params.data);
          } catch (e) {
            if (!(e instanceof SyntaxError)) {
              throw e;
            }
          }
        }

        return params;
      } catch (e) {
        self.emit('error', {type: 'MessageParseError', error: e, data: event.data});
      }
    }
202665
function parseResponseHeaders (headers) {
  var parsed = {};

  if (headers) {
    headers.split('\n').forEach(function (line) {
      var separatorIndex = line.indexOf(':');
      var key = line.substr(0, separatorIndex).trim().toLowerCase();
      var value = line.substr(separatorIndex + 1).trim().toLowerCase();

      if (key) {
        parsed[key] = value;
      }
    });
  }

  return parsed;
}