Blocking POST handler for file submission.
    Runs snort on supplied file and returns results as rendered html.
518080
def submit_and_render():
    
    data = request.files.file
    template = env.get_template("results.html")
    if not data:
        pass
    results = analyse_pcap(data.file, data.filename)
    results.update(base)
    return template.render(results)
757919
def handle_register_or_upload(post_data, files, user, repository):
    
    name = post_data.get('name')
    version = post_data.get('version')

    if settings.LOCALSHOP_VERSIONING_TYPE:
        scheme = get_versio_versioning_scheme(settings.LOCALSHOP_VERSIONING_TYPE)
        try:
            Version(version, scheme=scheme)
        except AttributeError:
            response = HttpResponseBadRequest(
                reason="Invalid version supplied '{!s}' for '{!s}' scheme.".format(
                    version, settings.LOCALSHOP_VERSIONING_TYPE))
            return response

    if not name or not version:
        logger.info("Missing name or version for package")
        return HttpResponseBadRequest('No name or version given')

    try:
        condition = Q()
        for search_name in get_search_names(name):
            condition |= Q(name__iexact=search_name)

        package = repository.packages.get(condition)

        # Error out when we try to override a mirror'ed package for now
        # not sure what the best thing is
        if not package.is_local:
            return HttpResponseBadRequest(
                '%s is a pypi package!' % package.name)

        try:
            release = package.releases.get(version=version)
        except ObjectDoesNotExist:
            release = None
    except ObjectDoesNotExist:
        package = None
        release = None

    # Validate the data
    form = forms.ReleaseForm(post_data, instance=release)
    if not form.is_valid():
        return HttpResponseBadRequest(reason=form.errors.values()[0][0])

    if not package:
        pkg_form = forms.PackageForm(post_data, repository=repository)
        if not pkg_form.is_valid():
            return HttpResponseBadRequest(
                reason=six.next(six.itervalues(pkg_form.errors))[0])
        package = pkg_form.save()

    release = form.save(commit=False)
    release.package = package
    release.save()

    # If this is an upload action then process the uploaded file
    if files:
        files = {
            'distribution': files['content']
        }
        filename = files['distribution']._name
        try:
            release_file = release.files.get(filename=filename)
            if settings.LOCALSHOP_RELEASE_OVERWRITE is False:
                message = 'That it already released, please bump version.'
                return HttpResponseBadRequest(message)
        except ObjectDoesNotExist:
            release_file = models.ReleaseFile(
                release=release, filename=filename)

        form_file = forms.ReleaseFileForm(
            post_data, files, instance=release_file)
        if not form_file.is_valid():
            return HttpResponseBadRequest('ERRORS %s' % form_file.errors)
        release_file = form_file.save(commit=False)
        release_file.save()

    return HttpResponse()
622715
def handle_submit(self):
        
        form = self.request.form
        # Selected AR UIDs
        uids = form.get("uids")
        container_mapping = self.get_container_mapping()
        for uid in uids:
            src_pos = container_mapping[uid]
            self.context.addDuplicateAnalyses(src_pos)
        redirect_url = "{}/{}".format(
            api.get_url(self.context), "manage_results")
        self.request.response.redirect(redirect_url)
836259
def _handle_POST(self, env, start_response):
        
        input = env['wsgi.input']
        data = input.read( int(env['CONTENT_LENGTH']) )
        mimeType = "text/xml"
        if self.encoding is not None:
            mimeType = 'text/xml; charset="%s"' % self.encoding

        request = None
        resource = self.delegate or self
        chain = self.factory.newInstance()
        try:
            pyobj = chain.processRequest(data, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]

        try:
            soap = chain.processResponse(pyobj, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
        
        start_response("200 OK", [('Content-Type',mimeType)])
        return [soap]
289552
function hotDownloadUpdateChunk(chunkId) {
		var filename = require("path").join(__dirname, $hotChunkFilename$);
		require("fs").readFile(filename, "utf-8", function(err, content) {
			if (err) {
				if ($require$.onError) return $require$.oe(err);
				throw err;
			}
			var chunk = {};
			require("vm").runInThisContext(
				"(function(exports) {" + content + "\n})",
				{ filename: filename }
			)(chunk);
			hotAddUpdateChunk(chunk.id, chunk.modules);
		});
	}
1139463
def handleDat(self, pkt):
        """"""
        log.info("Handling DAT packet - block %d" % pkt.blocknumber)
        log.debug("Expecting block %s", self.context.next_block)
        if pkt.blocknumber == self.context.next_block:
            log.debug("Good, received block %d in sequence", pkt.blocknumber)

            self.sendACK()
            self.context.next_block += 1

            log.debug("Writing %d bytes to output file", len(pkt.data))
            self.context.fileobj.write(pkt.data)
            self.context.metrics.bytes += len(pkt.data)
            # Check for end-of-file, any less than full data packet.
            if len(pkt.data) < self.context.getBlocksize():
                log.info("End of file detected")
                return None

        elif pkt.blocknumber < self.context.next_block:
            if pkt.blocknumber == 0:
                log.warning("There is no block zero!")
                self.sendError(TftpErrors.IllegalTftpOp)
                raise TftpException("There is no block zero!")
            log.warning("Dropping duplicate block %d" % pkt.blocknumber)
            self.context.metrics.add_dup(pkt)
            log.debug("ACKing block %d again, just in case", pkt.blocknumber)
            self.sendACK(pkt.blocknumber)

        else:
            # FIXME: should we be more tolerant and just discard instead?
            msg = "Whoa! Received future block %d but expected %d" \
                % (pkt.blocknumber, self.context.next_block)
            log.error(msg)
            raise TftpException(msg)

        # Default is to ack
        return TftpStateExpectDAT(self.context)
799158
def block_before(self):
        
        # To avoid unnecessary database queries, ignore the IP check for
        # requests for static files
        if request.path.startswith(url_for('static', filename='')):
            return

        # Some static files might be served from the root path (e.g.
        # favicon.ico, robots.txt, etc.). Ignore the IP check for most
        # common extensions of those files.
        ignored_extensions = ('ico', 'png', 'txt', 'xml')
        if request.path.rsplit('.', 1)[-1] in ignored_extensions:
            return

        ips = request.headers.getlist('X-Forwarded-For')
        if not ips:
            return

        # If the X-Forwarded-For header contains multiple comma-separated
        # IP addresses, we're only interested in the last one.
        ip = ips[0].strip()
        if ip[-1] == ',':
            ip = ip[:-1]
        ip = ip.rsplit(',', 1)[-1].strip()

        if self.matches_ip(ip):
            if self.logger is not None:
                self.logger.info("IPBlock: matched {}, {}".format(ip, self.block_msg))
            if self.blocking_enabled:
                return 'IP Blocked', 200
1169787
function processFile(filePath, callback) {
  /*jshint validthis:true */
  var processor = this;
  processor.emit('processing.start', {
    file: filePath
  });

  encoder.detectBom(filePath, function(err, bomName) {
    var status = 'good';

    if (err) {
      status = 'error';
      processor.emit('processing.error', {
        file: filePath,
        message: 'Skipping file with errors during encoding detection: ' + err
      });
      return callback(null, status);
    }
    else {
      var needsFixing = false;
      var lastByteSequenceWasCR = false;
      var bytesPerBom = encoder.getBytesPerBom(bomName);
      var bytesPerControlChar = encoder.getBytesPerControlChar(bomName);

      var transformBuffer = [];
      var tempBuffer = null;

      // Fast-forward past the BOM if present
      var onFirstReadable = function() {
        var bomBuffer = this.read(bytesPerBom);
        if (bomBuffer == null || bomBuffer.length !== bytesPerBom) {
          status = 'error';
          processor.emit('processing.error', {
            file: filePath,
            message: 'Skipping file with errors during read: Unable to read past the expected BOM'
          });
          return callback(null, status);
        }
      };
      var onReadable = function() {
        var data = this.read(),
            i = 0,
            len = data.length,
            cursor = i,
            buffer;
        for ( ; i < len; i += bytesPerControlChar) {
          buffer = slicer.call(data, i, i + bytesPerControlChar);

          // If we read less bytes than the minimum number necessary to register
          // as a complete character in this encoding, put them back on the front
          // of the read queue for the next read and then bail out.
          if (buffer.length < bytesPerControlChar) {
            if (!tempBuffer || !arraysMatch(buffer, tempBuffer)) {
              tempBuffer = buffer;
              // Save these rogue bytes to inspect on the next time around
              this.unshift(data.slice(i, i + buffer.length));
              // Break out of the loop
              break;
            }
            else {
              // This will prevent an infinite loop if the number of bytes in the file
              // is erroneous/irregular, e.g. a total of 7 bytes in a UTF-16 file.
              status = 'error';

              // Send a signal to cause early termination (i.e. trigger the 'end' event)
              this.push(null);
              // Break out of the loop
              break;
            }
          }
          tempBuffer = null;

          if (encoder.doesByteSequenceSuggestBinary(buffer, bomName)) {
            status = 'skip';
            processor.emit('processing.skip', {
              file: filePath,
              message: 'Skipping suspected binary file'
            });
            // Send a signal to cause early termination (i.e. trigger the 'end' event)
            this.push(null);
            // Break out of the loop
            break;
          }
          else {
            if (encoder.isByteSequenceCR(buffer, bomName)) {
              lastByteSequenceWasCR = true;
            }
            else {
              if (lastByteSequenceWasCR && encoder.isByteSequenceLF(buffer, bomName)) {
                needsFixing = true;

                // Push everything (except for CRs) into the outgoing buffer
                transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(slicer.call(data, cursor, i - bytesPerControlChar)));
                cursor = i;
              }

              // If this is the last byte of the buffer, push the remaining data into the outgoing buffer
              if (i + bytesPerControlChar === len && needsFixing) {
                // Push everything (except for CRs) into the outgoing buffer
                transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(slicer.call(data, cursor)));
              }

              // Reset
              lastByteSequenceWasCR = false;
            }
          }
        }
      };
      var onError = function(err) {
        status = 'error';
        processor.emit('processing.error', {
          file: filePath,
          message: 'Skipping file with errors during read: ' + err
        });
        return callback(null, status);
      };
      var onEnd = function() {
        if (status === 'good') {
          if (needsFixing) {
            status = 'bad';
            this.on('close', function() {
              // Overwrite the existing file with the fixed data
              process.nextTick(function() {
                processor.emit('convert.start', {
                  file: filePath
                });

                //
                // TODO: Is there a more optimal way to do this?
                //       e.g. TransformStream, write to temp then move, etc.
                //
                fs.writeFile(filePath, new Buffer(transformBuffer), function(err) {
                  if (err) {
                    status = 'error';
                    processor.emit('convert.error', {
                      file: filePath,
                      message: 'Unexpected error during conversion process: ' + err
                    });
                  }
                  else {
                    status = 'fix';
                    processor.emit('convert.end', {
                      file: filePath
                    });
                  }

                  processor.emit('processing.end', {
                    file: filePath
                  });
                  return callback(null, status);
                });
              });
            });
          }
          else {
            status = 'skip';
            processor.emit('processing.skip', {
              file: filePath,
              message: 'Skipping file with all correct line endings'
            });
          }
        }

        if (status === 'skip') {
          processor.emit('processing.end', {
            file: filePath
          });
        }
        if (status !== 'bad') {
          return callback(null, status);
        }
      };

      var reader = new Readable();
      reader.wrap(fs.createReadStream(filePath));

      if (bytesPerBom > 0) {
        reader.once('readable', onFirstReadable);
      }
      reader
        .on('readable', onReadable)
        .on('error', onError)
        .on('end', onEnd);
    }
  });
}
110619
private Handler<Message<Buffer>> handleUpload(final AsyncFile file, final String address) {
    final AtomicLong position = new AtomicLong();
    return new Handler<Message<Buffer>>() {
      @Override
      public void handle(final Message<Buffer> message) {
        final Handler<Message<Buffer>> handler = this;
        final Buffer buffer = message.body();
        if (buffer.length() > 0) {
          file.write(buffer, position.get(), new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                file.close();
                message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
                vertx.eventBus().unregisterHandler(address, handler);
              } else {
                position.addAndGet(buffer.length());
                message.reply(new JsonObject().putString("status", "ok"));
              }
            }
          });
        } else {
          file.flush(new Handler<AsyncResult<Void>>() {
            @Override
            public void handle(AsyncResult<Void> result) {
              if (result.failed()) {
                message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
                vertx.eventBus().unregisterHandler(address, handler);
              } else {
                file.close(new Handler<AsyncResult<Void>>() {
                  @Override
                  public void handle(AsyncResult<Void> result) {
                    if (result.failed()) {
                      message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
                      vertx.eventBus().unregisterHandler(address, handler);
                    } else {
                      vertx.eventBus().unregisterHandler(address, handler, new Handler<AsyncResult<Void>>() {
                        @Override
                        public void handle(AsyncResult<Void> result) {
                          message.reply(new JsonObject().putString("status", "ok"));
                        }
                      });
                    }
                  }
                });
              }
            }
          });
        }
      }
    };
  }
1358439
def _handle_stderr_event(self, fd, events):
        """"""

        assert fd == self.fd_stderr

        if events & self.ioloop.READ:
            # got data ready
            if not self.headers_sent:
                payload = self.process.stderr.read()

                data = 'HTTP/1.1 500 Internal Server Error\r\nDate: %s\r\nContent-Length: %d\r\n\r\n' % (get_date_header(), len(payload))
                self.headers_sent = True
                data += payload
            else:
                # see stdout
                logger.error("This should not happen (stderr)")
                data = self.process.stderr.read()

            logger.debug('Sending stderr to client: %r', data)
            self.request.write(data)

        if events & self.ioloop.ERROR:
            logger.debug('Error on stderr')
            # ensure file is closed
            if not self.process.stderr.closed:
                self.process.stderr.close()
            # remove handler
            self.ioloop.remove_handler(self.fd_stderr)
            # if all fds are closed, we can finish
            return self._graceful_finish()
605475
function processFileResponse(req, res, next) {
  var fileDetails = req.appformsResultPayload.data;
  if (fileDetails.stream) {
    var headers = {};
    headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler.
    headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name;
    res.writeHead(200, headers);
    fileDetails.stream.pipe(res);
    fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler
  } else {
    return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails));
  }
}
1154741
def render_POST(self, request):
        
        try:
            d = self.getAndSubmitChanges(request)
        except Exception:
            d = defer.fail()

        def ok(_):
            request.setResponseCode(202)
            request.finish()

        def err(why):
            code = 500
            if why.check(ValueError):
                code = 400
                msg = unicode2bytes(why.getErrorMessage())
            else:
                log.err(why, "adding changes from web hook")
                msg = b'Error processing changes.'
            request.setResponseCode(code, msg)
            request.write(msg)
            request.finish()

        d.addCallbacks(ok, err)

        return server.NOT_DONE_YET
1254416
function POST_FILE(uri, params, filepath) {
	var form = new FormData();

	for (var i in params) {
		form.append(i, params[i]);
	}

	let contenttype = 'INVALID';

	if(filepath.split('.').pop().toLowerCase() == 'jpg') { contenttype = 'image/jpg' }
	if(filepath.split('.').pop().toLowerCase() == 'png') { contenttype = 'image/png' }
	if(filepath.split('.').pop().toLowerCase() == 'gif') { contenttype = 'image/gif' }

	if(contenttype == 'INVALID') { throw 'Invalid image type.' }

	let imageData = fs.readFileSync(filepath);

	form.append('image', imageData, {
		filename: filepath.split('/').pop(),
		filepath: filepath,
		contentType: contenttype,
		knownLength: imageData.length
	});

	const requestURL = `${uri}`;
	log(`request URL: ${requestURL}`);

	return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
    .then(function handleRequest(res) {
			const status = res.status;
			if (status != 200) {
				const error = new Error(`Request failed: ${status}`);
				error.status = status;
				throw error;
			}
			return res.json();
		})
		.catch(error => {
			log(`error: ${error}`);
			throw error;
		});
}
86944
public void process(File input) throws IOException {
        File filtered = getFilteredVersion(input);
        if (filtered == null) {
            // It was not copied.
            getLog().warn("Cannot find the filtered version of " + input.getAbsolutePath() + ", " +
                    "using source file.");
            filtered = input;
        }

        // Actual processing.
        String result = instance.markdownToHtml(FileUtils.readFileToString(filtered));

        FileUtils.write(getOutputFile(input, "html"), result);
    }
348494
def render_GET(self, request):
        
        request.setHeader(b'accept-ranges', b'bytes')

        producer = self.makeProducer(request, self.fileObject)

        if request.method == b'HEAD':
            return b''

        def done(ign):
            producer.stopProducing()

        request.notifyFinish().addCallbacks(done, done)
        producer.start()
        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET
1005509
async def multipart_parser(request, file_handler=default_file_handler):
    
    multipart_data = {
        'files': {},
        'data': {}
    }
    if request.content_type == 'multipart/form-data':
        reader = MultipartReader.from_response(request)

        while True:
            part = await reader.next()
            if part is None:
                break
            if isinstance(part, BodyPartReader):
                if part.filename:
                    # if body is binary file
                    if file_handler:
                        # in case we just want to parse data and not save file actually e.g. in validator
                        file_data = await part.read(decode=True)
                        file_data = part.decode(file_data)
                        file_path = await file_handler(part.filename, file_data, part.headers[CONTENT_TYPE])
                    else:
                        file_path = part.filename
                    multipart_data['files'][part.name] = file_path
                elif part.text():
                    # if body is text
                    text = await part.text()
                    multipart_data['data'][part.name] = text
                else:
                    # if body is json or form (not text), not handling this
                    continue
            else:
                # if part is recursive multipart , not handling this right now
                # TODO: do recursive call to handle this
                continue
    else:
        try:
            multipart_data['data'] = await request.json()
        except json.JSONDecodeError:
            pass
    return multipart_data
1353717
function (filename, callbackFn) {
                    var self = this,
                        url = self.options.hostAndPort + '/page/functions/render';

                    self.options.debug && console.log('calling url: %s', url);
                    request.post(url, {form:{ args:JSON.stringify(
                            [
                                filename
                            ], null, 4)}},
                        function (error, response, body) {
                            error && console.error(error);
                            if (response && response.statusCode === 200) {
                                callbackFn && callbackFn.call(self, !!body);
                            }
                            else {
                                console.error(body);
                                callbackFn && callbackFn.call(self, body);
                            }
                        }
                    );
                }