예제 #1
0
파일: file_storage.py 프로젝트: JT-a/pillar
def index(file_name=None):
    # GET file -> read it
    if request.method == 'GET':
        return send_from_directory(current_app.config['STORAGE_DIR'], file_name)

    # POST file -> save it

    # Sanitize the filename; source: http://stackoverflow.com/questions/7406102/
    file_name = request.form['name']
    keepcharacters = {' ', '.', '_'}
    file_name = ''.join(
        c for c in file_name if c.isalnum() or c in keepcharacters).strip()
    file_name = file_name.lstrip('.')

    # Determine & create storage directory
    folder_name = file_name[:2]
    file_folder_path = helpers.safe_join(current_app.config['STORAGE_DIR'], folder_name)
    if not os.path.exists(file_folder_path):
        log.info('Creating folder path %r', file_folder_path)
        os.mkdir(file_folder_path)

    # Save uploaded file
    file_path = helpers.safe_join(file_folder_path, file_name)
    log.info('Saving file %r', file_path)
    request.files['data'].save(file_path)

    # TODO: possibly nicer to just return a redirect to the file's URL.
    return jsonify({'url': url_for('file_storage.index', file_name=file_name)})
예제 #2
0
파일: index.py 프로젝트: CaptainBerg/me
def theme_file(theme, filename):
    filename = "themes/%s/%s" % (theme, filename)

    if RUNTIME_ENV not in ("gae", "gae_dev"):
        # GAE can not access static folder because the files will go to CDN instead of GAE instance
        real_file = safe_join(app.static_folder, filename)
        if not os.path.isfile(real_file):
            return ""

    return "%s/%s" % (app.static_url_path, filename)
예제 #3
0
파일: index.py 프로젝트: amania88/lite-mms
def _resize_file(filename, size=(180, 180)):
    _dir = app.config['UPLOAD_FOLDER']
    new_filename = filename.replace(".", "-%d%d." % size)
    import os

    if not os.path.exists(safe_join(_dir, new_filename)):
        from PIL import Image

        try:
            im = Image.open(safe_join(_dir, filename))
            ori_w, ori_h = im.size
            if ori_w > ori_h:
                _size = size[0], ori_h * size[1] / ori_w
            else:
                _size = ori_w * size[0] / ori_h, size[1]
            im.resize(_size, Image.ANTIALIAS).save(safe_join(_dir, new_filename), "JPEG")
        except IOError:
            pass
    return new_filename
예제 #4
0
def replication_hourly(packet_number):
    directory = current_app.config['REPLICATION_PACKETS_DIR']
    filename = 'replication-%s.tar.bz2' % packet_number
    if not os.path.isfile(safe_join(directory, filename)):
        return Response("Can't find specified replication packet!\n", status=404)

    if 'USE_NGINX_X_ACCEL' in current_app.config and current_app.config['USE_NGINX_X_ACCEL']:
        return _redirect_to_nginx(os.path.join(NGINX_INTERNAL_LOCATION, filename))
    else:
        return send_from_directory(directory, filename, mimetype=MIMETYPE_ARCHIVE)
예제 #5
0
def replication_weekly_signature(packet_number):
    directory = os.path.join(current_app.config['REPLICATION_PACKETS_DIR'], WEEKLY_SUBDIR)
    filename = 'replication-weekly-%s.tar.bz2.asc' % packet_number
    if not os.path.isfile(safe_join(directory, filename)):
        return Response("Can't find signature for a specified replication packet!\n", status=404)

    if 'USE_NGINX_X_ACCEL' in current_app.config and current_app.config['USE_NGINX_X_ACCEL']:
        return _redirect_to_nginx(os.path.join(NGINX_INTERNAL_LOCATION, WEEKLY_SUBDIR, filename))
    else:
        return send_from_directory(directory, filename, mimetype=MIMETYPE_SIGNATURE)
예제 #6
0
파일: views.py 프로젝트: semprix/CTFIgniter
def file_handler(path):
    f = Files.query.filter_by(location=path).first_or_404()
    if f.chal:
        if not utils.is_admin():
            if not utils.ctftime():
                if utils.view_after_ctf() and utils.ctf_started():
                    pass
                else:
                    abort(403)
    upload_folder = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
    return send_file(safe_join(upload_folder, f.location))
예제 #7
0
파일: views.py 프로젝트: satan1a/CTFd
def file_handler(path):
    f = Files.query.filter_by(location=path).first_or_404()
    if f.chal:
        if not utils.is_admin():
            if not utils.ctftime():
                if utils.view_after_ctf() and utils.ctf_started():
                    pass
                else:
                    abort(403)
    upload_folder = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
    return send_file(safe_join(upload_folder, f.location))
예제 #8
0
def well_known(path):
    """
    Return a well known path from the well-known directory
    :param path:
    :return:
    """
    filename = safe_join(app.root_path, "well-known", path)
    if os.path.isfile(filename):
        return send_file(filename)
    else:
        abort(404)
예제 #9
0
파일: __init__.py 프로젝트: manhg/flaskit
 def static_hash(endpoint, values):
     """ Add hash to static url for validating cache """
     if endpoint == "static" and "filename" in values:
         filepath = safe_join(app.static_folder, values["filename"])
         if os.path.isfile(filepath):
             if not app.STATIC_HASHES.get(filepath):
                 h = hashlib.md5()
                 with contextlib.closing(open(filepath, "rb")) as f:
                     h.update(f.read())
                 app.STATIC_HASHES[filepath] = h.hexdigest()[:6]
             values["v"] = app.STATIC_HASHES[filepath]
예제 #10
0
def generator(filedir_path, token):
        m = hashlib.md5()   
        m.update(token)   
        mtoken = m.hexdigest()
        teamdir_path = safe_join(filedir_path, mtoken)
	os.mkdir(teamdir_path)

        pwn_text = r'''#include <stdio.h>
int main(int argc, char** argv)
{
    int modified;
    char buffer[10];
    modified = 0;
    printf("Please fill the buffer:\n");
    fflush(stdout);
    gets(buffer);
    if (modified != 0)
    {
        printf("Congratulations, you got the shell.\n");
        printf("Remember you can only read your own team's flag!\n");
        fflush(stdout);
        system("/bin/sh");
        exit(0);
    }
    else
    {
        printf("Please try again.\n");
    }
    return 0;
}'''
        pwn_path = safe_join(teamdir_path, "pwn.c")
        with open(pwn_path, 'w') as f:
		f.write(pwn_text)

        teamfile_path = safe_join(filedir_path, mtoken+".zip")
	with zipfile.ZipFile(teamfile_path, 'w', zipfile.ZIP_DEFLATED) as mzip:
		for dirpath, dirnames, filenames in os.walk(teamdir_path):
			fpath = dirpath.replace(teamdir_path,'') 
			fpath = fpath and fpath + os.sep or ''
			for filename in filenames:
				mzip.write(os.path.join(dirpath, filename),fpath+filename)
예제 #11
0
파일: webui.py 프로젝트: item4/lektor
    def resolve_artifact(self, path, pad=None, redirect_slash=True):
        """Resolves an artifact and also triggers a build if necessary.
        Returns a tuple in the form ``(artifact_name, filename)`` where
        `artifact_name` can be `None` in case a file was targeted explicitly.
        """
        if pad is None:
            pad = self.get_pad()

        artifact_name = filename = None

        # We start with trying to resolve a source and then use the
        # primary
        source = pad.resolve_url_path(path)
        if source is not None:
            # If the request path does not end with a slash but we
            # requested a URL that actually wants a trailing slash, we
            # append it.  This is consistent with what apache and nginx do
            # and it ensures our relative urls work.
            if not path.endswith('/') and \
               source.url_path != '/' and \
               source.url_path != path:
                return abort(append_slash_redirect(request.environ))

            with CliReporter(self.env, verbosity=self.verbosity):
                builder = self.get_builder(pad)
                prog, _ = builder.build(source)

            artifact = prog.primary_artifact
            if artifact is not None:
                artifact_name = artifact.artifact_name
                filename = artifact.dst_filename

        if filename is None:
            filename = safe_join(self.output_path, path.strip('/'))
            if os.path.isdir(filename):
                if os.path.isfile(safe_join(filename, 'index.html')):
                    filename = safe_join(filename, 'index.html')
                elif os.path.isfile(safe_join(filename, 'index.htm')):
                    filename = safe_join(filename, 'index.htm')

        return artifact_name, filename
예제 #12
0
파일: views.py 프로젝트: kenz-g147/CTFd-1
def themes(theme, path):
    """
    General static file handler
    :param theme:
    :param path:
    :return:
    """
    filename = safe_join(app.root_path, "themes", theme, "static", path)
    if os.path.isfile(filename):
        return send_file(filename)
    else:
        abort(404)
예제 #13
0
파일: api.py 프로젝트: pkuchta/prepcase-gui
def run_script_in_case(case_path, script, parameters):
    """
    Run script in case directory.
    Parameters are accepted as array of strings.
    """
    executables = []
    if auth.user['cesm_env_script']:
        executables.append('source ' + auth.user['cesm_env_script'] +
                           ' >/dev/null')
    executables.append('cd ' + case_path)
    executables.append(safe_join(case_path, script))
    return globals.ssh.ssh_execute(' && '.join(executables), parameters)
예제 #14
0
def photo(type, filename):
    photosize = request.args.get('size')
    sub_path = os.path.join(type, filename)
    filepath = safe_join(app.config['UPLOAD_FOLDER'], sub_path)
    if not os.path.isabs(filepath):
        filepath = os.path.join(app.root_path, filepath)
    if not os.path.isfile(filepath):
        raise NotFound()
    if photosize is not None:
        photosize = int(photosize)
        filepath = photo_utils.scaled_cached(filepath, photosize)
    return send_file(filepath)
예제 #15
0
파일: api.py 프로젝트: pkuchta/prepcase-gui
def run_tool(tool, parameters):
    """
    Run one of the supported command line tools.
    Parameters are accepted as array of strings.
    """
    executables = []
    if auth.user['cesm_env_script']:
        executables.append('source ' + auth.user['cesm_env_script'] +
                           ' >/dev/null')
    executables.append(
        safe_join(auth.user['cesm_path'], 'cime', "scripts", tool))
    return globals.ssh.ssh_execute(' && '.join(executables), parameters)
예제 #16
0
파일: store.py 프로젝트: 4myPAL/snapstore
def read_meta(name):
    try:
        fname = safe_join(FILES, name + '.meta')
        with open(fname, 'r') as meta:
            # replace download URLs
            pkg = json.loads(meta.read())
            pkg['download_url'] = url_for('download',
                                          name=name + '.snap',
                                          _external=True)
            pkg['anon_download_url'] = pkg['download_url']
            return pkg
    except Exception as e:
        return None
예제 #17
0
def _render_rst_to_jinja_templating(course, page_path, content):
    cache_pages = syllabus.get_config()["caching"]["cache_pages"]
    toc = syllabus.get_toc(course)
    print_mode = session.get("print_mode", False)
    # look if we have a cached version of this content
    if cache_pages and toc.has_cached_content(content, print_mode):
        with open(safe_join(syllabus.get_pages_path(course), content.cached_path(print_mode)), "r") as f:
            rendered = f.read()
    else:
        # render the content
        with open(safe_join(syllabus.get_pages_path(course), page_path), "r") as f:
            rendered = publish_string(f.read(), writer_name='html', settings_overrides=default_rst_opts)
        if cache_pages:  # cache the content if needed
            if type(content) is Page:
                parent = toc.get_parent_of(content)
                os.makedirs(safe_join(toc.cached_path(print_mode), parent.path if parent is not None else ""),
                            exist_ok=True)
            else:
                os.makedirs(safe_join(toc.cached_path(print_mode), content.path), exist_ok=True)
            with open(safe_join(syllabus.get_pages_path(course), content.cached_path(print_mode)), "w") as cached_content:
                cached_content.write(rendered)
    return rendered
예제 #18
0
 def get_source(self, environment, template):
     # Refuse to load `admin/*` from a loader not for the admin theme
     # Because there is a single template loader, themes can essentially
     # provide files for other themes. This could end up causing issues if
     # an admin theme references a file that doesn't exist that a malicious
     # theme provides.
     if template.startswith(self._ADMIN_THEME_PREFIX):
         if self.theme_name != ADMIN_THEME:
             raise jinja2.TemplateNotFound(template)
         template = template[len(self._ADMIN_THEME_PREFIX):]
     theme_name = self.theme_name or str(utils.get_config("ctf_theme"))
     template = safe_join(theme_name, "templates", template)
     return super(ThemeLoader, self).get_source(environment, template)
예제 #19
0
파일: views.py 프로젝트: sarthak7g/storeS3
def download_file():
    if request.method == "GET":
        if "file_name" in request.args:
            file_name = request.args["file_name"]
            filename_new = safe_join(app.root_path, "static", file_name)

            if os.path.isfile(filename_new):
                try:
                    return send_file(filename_new, as_attachment=True)
                except Exception as e:
                    return jsonify(f"your path exists with error:{e}")
            else:
                return jsonify(f"{filename_new} does not exists")
예제 #20
0
def file_handler(path):
    f = Files.query.filter_by(location=path).first_or_404()
    if f.chal:
        if not utils.is_admin():
            if not utils.ctftime():
                if utils.view_after_ctf() and utils.ctf_started():
                    pass
                else:
                    abort(403)
    upload_folder = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
    if not f.dynamic:
        return send_file(safe_join(upload_folder, f.location))
    filedir_path = safe_join(upload_folder, f.location.split('/')[0])
    m = hashlib.md5()
    m.update(session['token'])
    teamfile_name = m.hexdigest() + ".zip"
    teamfile_path = safe_join(filedir_path, teamfile_name)
    if not os.path.exists(teamfile_path):
        os.system("python %s %s %s %s" %
                  (safe_join(upload_folder, f.location), filedir_path,
                   session['token'], app.root_path))
    return send_file(teamfile_path, cache_timeout=0)
예제 #21
0
파일: views.py 프로젝트: polambakhaz/CTFd
def themes(theme, path):
    """
    General static file handler
    :param theme:
    :param path:
    :return:
    """
    for cand_path in (
            safe_join(app.root_path, "themes", cand_theme, "static", path)
            # The `theme` value passed in may not be the configured one, e.g. for
            # admin pages, so we check that first
            for cand_theme in (theme, *config.ctf_theme_candidates())):
        if os.path.isfile(cand_path):
            return send_file(cand_path)
    abort(404)
예제 #22
0
def send_static_files(path):
    safe = safe_join(app.config['UPLOAD_FOLDER'], path)
    # Read the file
    with open(safe, "rb") as f:
        b = f.read()
    # Elaborate response. jQuery fileDownload requires setting two cookies
    r = Response(b, status=200, mimetype="application/octet-stream")
    r.set_cookie("fileDownload", "true")
    r.set_cookie("path", "/")
    # file_type = magic.from_buffer(b, mime=True)
    # file_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet "
    # r.headers["Content-type"] = file_type
    r.headers["Content-Disposition"] = "attachment; filename=" + path
    r.headers["Content-Length"] = len(b)
    return r
예제 #23
0
def replication_hourly(packet_number):
    directory = current_app.config['REPLICATION_PACKETS_DIR']
    filename = 'replication-%s.tar.bz2' % packet_number
    if not os.path.isfile(safe_join(directory, filename)):
        return Response("Can't find specified replication packet!\n",
                        status=404)

    if 'USE_NGINX_X_ACCEL' in current_app.config and current_app.config[
            'USE_NGINX_X_ACCEL']:
        return _redirect_to_nginx(
            os.path.join(NGINX_INTERNAL_LOCATION, filename))
    else:
        return send_from_directory(directory,
                                   filename,
                                   mimetype=MIMETYPE_ARCHIVE)
 def send_static(filename):
     """Sends a file from the static folder if a given file exist.
     Otherwise, tries additional folders as a fallback.
     """
     try:
         return current_app.send_static_file(filename)
     except NotFound:
         for prefix, folder in locations:
             if prefix:
                 prefix = '{}{}'.format(prefix, os.sep)
                 if filename.startswith(prefix):
                     filename = filename[len(prefix):]
             filepath = safe_join(folder, filename)
             if os.path.isfile(filepath):
                 return send_file(filepath)
         raise NotFound()
예제 #25
0
def themes_beta(theme, path):
    """
    This is a copy of the above themes route used to avoid
    the current appending of .dev and .min for theme assets.

    In CTFd 4.0 this url_for behavior and this themes_beta
    route will be removed.
    """
    for cand_path in (
        safe_join(app.root_path, "themes", cand_theme, "static", path)
        # The `theme` value passed in may not be the configured one, e.g. for
        # admin pages, so we check that first
        for cand_theme in (theme, *config.ctf_theme_candidates())
    ):
        if os.path.isfile(cand_path):
            return send_file(cand_path)
    abort(404)
예제 #26
0
def replication_weekly_signature(packet_number):
    directory = os.path.join(current_app.config['REPLICATION_PACKETS_DIR'],
                             WEEKLY_SUBDIR)
    filename = 'replication-weekly-%s.tar.bz2.asc' % packet_number
    if not os.path.isfile(safe_join(directory, filename)):
        return Response(
            "Can't find signature for a specified replication packet!\n",
            status=404)

    if 'USE_NGINX_X_ACCEL' in current_app.config and current_app.config[
            'USE_NGINX_X_ACCEL']:
        return _redirect_to_nginx(
            os.path.join(NGINX_INTERNAL_LOCATION, WEEKLY_SUBDIR, filename))
    else:
        return send_from_directory(directory,
                                   filename,
                                   mimetype=MIMETYPE_SIGNATURE)
예제 #27
0
def files(filepath):
    doc = models.Document.query.filter_by(file=filepath).first()
    if doc is None:
        abort(404)
    if current_user.is_anonymous() and doc.featured is not True:
        abort(404)
    file_parts = filepath.rsplit('/', 1)
    if len(file_parts) == 1:
        file_parts = ['.'] + file_parts
    folder, filename = file_parts
    path = os.path.join(app.config['UPLOAD_FOLDER'], 'documents', folder)
    print(path)
    filepath = safe_join(path, filename)
    if not os.path.isabs(filepath):
        filepath = os.path.join(app.root_path, filepath)
    if not os.path.isfile(filepath):
        raise NotFound()
    return send_file(filepath)
예제 #28
0
 def inject_url_defaults(self, endpoint, values):
     super(AddStaticFileHashFlask, self).inject_url_defaults(endpoint, values)
     if endpoint == "static" and "filename" in values:
         filepath = safe_join(self.static_folder, values["filename"])
         if os.path.isfile(filepath):
             cache = self._file_hash_cache.get(filepath)
             mtime = os.path.getmtime(filepath)
             if cache != None:
                 cached_mtime, cached_hash = cache
                 if cached_mtime == mtime:
                     values["h"] = cached_hash
                     return
             h = hashlib.md5()
             with contextlib.closing(open(filepath, "rb")) as f:
                 h.update(f.read())
             h = h.hexdigest()
             self._file_hash_cache[filepath] = (mtime, h)
             values["h"] = h
예제 #29
0
def static_html(route):
    """
    Route in charge of routing users to Pages.
    :param route:
    :return:
    """
    page = get_page(route)
    if page is None:
        if (ctftime() or current_user.is_admin()
                or (ctf_ended() and view_after_ctf())):
            filename = safe_join(app.root_path, "static", route)
            if os.path.isfile(filename):
                return send_file(filename)
        abort(404)
    else:
        if page.auth_required and authed() is False:
            return redirect(url_for("auth.login", next=request.full_path))

        return render_template("page.html", content=markdown(page.content))
예제 #30
0
        def hashed_url_for_static_file(endpoint, values):
            if 'static' == endpoint or endpoint.endswith('.static'):
                filename = values.get('filename')
                if filename:
                    # has higher priority
                    blueprint = endpoint.rsplit('.', 1)[0] \
                        if '.' in endpoint else request.blueprint

                    # file from blueprint or project?
                    static_folder = app.blueprints[blueprint].static_folder \
                        if blueprint else app.static_folder

                    # avoids querystring key collision
                    param_name = 'h'
                    while param_name in values:
                        param_name = '_' + param_name

                    filepath = safe_join(static_folder, filename)
                    values[param_name] = self.get_file_hash(filepath)
예제 #31
0
 def generate_sitemap_xml(self, postlist, baseurl="http://localhost:5000"):
     """
     Generate the Sitemap XML format output with all the posts in postdir
     :param postlist: list with all the posts for the sitemapxml.
     :return: return the xml output for the Sitemap.xml file.
     """
     root = ET.Element(
         "urlset",
         attrib={"xmlns": "http://www.sitemaps.org/schemas/sitemap/0.9"})
     rpostlist = self._listdirectoriesrecursive(postlist)
     rpostlist.remove("index.md")
     rpostlist = list(map(lambda l: path.splitext(l)[0], rpostlist))
     rpostlist = list(map(lambda l: self.renderfile(l), rpostlist))
     # add index
     urlindex = ET.SubElement(root, "url")
     locindex = ET.SubElement(urlindex, "loc")
     locindex.text = baseurl
     lastmodif = ET.SubElement(urlindex, "lastmod")
     tmp = path.getmtime(path.join(postlist, "index.md"))
     lastmodif.text = datetime.fromtimestamp(tmp).strftime("%Y-%m-%d")
     changefreq = ET.SubElement(urlindex, "changefreq")
     changefreq.text = "monthly"
     priority = ET.SubElement(urlindex, "priority")
     priority.text = "0.5"
     for post in rpostlist:
         if post.name:
             title = post.name
         purlindex = ET.SubElement(root, "url")
         plocindex = ET.SubElement(purlindex, "loc")
         plocindex.text = baseurl + title
         plastmodif = ET.SubElement(purlindex, "lastmod")
         filetitle = f"{post.name}.md"
         tmp = path.getmtime(safe_join(self.postdir, filetitle))
         plastmodif.text = datetime.fromtimestamp(tmp).strftime("%Y-%m-%d")
         pchangefreq = ET.SubElement(purlindex, "changefreq")
         if post.periodicity:
             pchangefreq.text = post.periodicity
         else:
             pchangefreq.text = "monthly"
         priority = ET.SubElement(purlindex, "priority")
         priority.text = "0.5"
     return ET.tostring(root, encoding="UTF-8", method="xml")
예제 #32
0
    def __call__(self, file):
        if os.path.isabs(file):
            raise RuntimeWarning("XAccel only accepts relative file path")

        headers = {}
        if self.redirect_base:
            headers["X-Accel-Redirect"] = safe_join(self.redirect_base,
                                                    file).encode("utf-8")
        if self.charset:
            headers["X-Accel-Charset"] = self.charset
        if self.buffering:
            headers["X-Accel-Buffering"] = self.buffering
        if self.expires:
            headers["X-Accel-Expires"] = self.expires
        if self.limit_rate:
            headers["X-Accel-Limit-Rate"] = self.limit_rate

        # let front-end auto detect mime type
        headers["Content-Type"] = ""
        return "", 200, headers
예제 #33
0
파일: store.py 프로젝트: kyrofa/snapstore
def search():
    ''' note in 2.0.9 snap install uses the search endpoint
    for package details as well as for snap find '''
    name = request.args.get('q')
    # hackity hack hack: find passes q=package_name:"foo"
    if 'package_name' in name:
        name = name.split(':')[1].replace('"', '')

    try:
        fname = safe_join(FILES, name + '.meta')
        with open(fname, 'r') as meta:
            # replace download URLs
            data = json.loads(meta.read())
            pkg = data['_embedded']['clickindex:package'][0]
            pkg['download_url'] = url_for('download', name=name + '.snap',
                                          _external=True)
            pkg['anon_download_url'] = pkg['download_url']
            return Response(json.dumps(data), mimetype='application/hal+json')
    except Exception as e:
        return Response('{}', mimetype='application/hal+json')
예제 #34
0
파일: store.py 프로젝트: scm/snapstore
def search():
    ''' note in 2.0.9 snap install uses the search endpoint
    for package details as well as for snap find '''
    name = request.args.get('q')
    # hackity hack hack: find passes q=package_name:"foo"
    if 'package_name' in name:
        name = name.split(':')[1].replace('"', '')

    try:
        fname = safe_join(FILES, name + '.meta')
        with open(fname, 'r') as meta:
            # replace download URLs
            data = json.loads(meta.read())
            pkg = data['_embedded']['clickindex:package'][0]
            pkg['download_url'] = url_for('download', name=name + '.snap',
                                          _external=True)
            pkg['anon_download_url'] = pkg['download_url']
            return Response(json.dumps(data), mimetype='application/hal+json')
    except Exception as e:
        return Response('{}', mimetype='application/hal+json')
예제 #35
0
    def load_file(self, filename):
        """
        Load the filename from the local directory. The type of the returned
        object depends on if the filename corresponds to a file or a directory.
        If it's a file, a flask Response object containing the file's data will
        be returned. If it's a directory, a gopher menu will be returned.

        This method uses the flask application context, which means that it
        can only be invoked from inside of a flask view.
        """
        abs_filename = safe_join(self.local_directory, filename)
        if not os.path.isabs(abs_filename):
            abs_filename = os.path.join(current_app.root_path, abs_filename)

        if os.path.isfile(abs_filename):
            return self.result_class(False, send_file(abs_filename))
        elif os.path.isdir(abs_filename):
            data = self._parse_directory(filename, abs_filename)
            return self.result_class(True, data)
        else:
            raise BadRequest()
예제 #36
0
    def resolve_artifact(self, path, pad=None, redirect_slash=True):
        """Resolves an artifact and also triggers a build if necessary.
        Returns a tuple in the form ``(artifact_name, filename)`` where
        `artifact_name` can be `None` in case a file was targeted explicitly.
        """
        if pad is None:
            pad = self.get_pad()

        artifact_name = filename = None

        # We start with trying to resolve a source and then use the
        # primary
        source = pad.resolve_url_path(path)
        if source is not None:
            # If the request path does not end with a slash but we
            # requested a URL that actually wants a trailing slash, we
            # append it.  This is consistent with what apache and nginx do
            # and it ensures our relative urls work.
            if not path.endswith('/') and \
               source.url_path != '/' and \
               source.url_path != path:
                return abort(append_slash_redirect(request.environ))

            with CliReporter(self.env, verbosity=self.verbosity):
                builder = self.get_builder(pad)
                prog, _ = builder.build(source)

            artifact = prog.primary_artifact
            if artifact is not None:
                artifact_name = artifact.artifact_name
                filename = artifact.dst_filename

        if filename is None:
            path_list = path.strip('/').split('/')
            if sys.platform == 'win32':
                filename = os.path.join(self.output_path, *path_list)
            else:
                filename = safe_join(self.output_path, *path_list)

        return artifact_name, filename
예제 #37
0
def _send_from_directories(directories, filename, **options):
    """
    Send a file from a given directory with :func:`send_file`.  This
    is a secure way to quickly expose static files from an upload folder
    or something similar.

    Example usage::

        @app.route('/uploads/<path:filename>')
        def download_file(filename):
            return send_from_directory(app.config.UPLOAD_FOLDER,
                                       filename, as_attachment=True)

    .. admonition:: Sending files and Performance

       It is strongly recommended to activate either ``X-Sendfile`` support in
       your webserver or (if no authentication happens) to tell the webserver
       to serve files for the given path on its own without calling into the
       web application for improved performance.

    :param directories: the list of directories to look for filename.
    :param filename: the filename relative to that directory to
                     download.
    :param options: optional keyword arguments that are directly
                    forwarded to :func:`send_file`.
    """
    for directory in directories:
        filename = safe_join(directory, filename)
        if not os.path.isabs(filename):
            filename = os.path.join(current_app.root_path, filename)
        try:
            if not os.path.isfile(filename):
                continue
        except (TypeError, ValueError):
            raise BadRequest()
        options.setdefault('conditional', True)
        return send_file(filename, **options)
    raise NotFound()
예제 #38
0
 def test_safe_join_toplevel_pardir(self):
     from flask.helpers import safe_join
     with self.assert_raises(NotFound):
         safe_join('/foo', '..')
예제 #39
0
파일: uploaders.py 프로젝트: elfreki/CTFd
 def download(self, filename):
     return send_file(safe_join(self.base_path, filename),
                      as_attachment=True)
예제 #40
0
def page_not_found(error):
    return send_from_memory(safe_join(app.config['STATIC_PATH'], 'error.html'))
예제 #41
0
파일: __init__.py 프로젝트: crobarcro/BOLTS
def static_version(filename):
	return send_from_directory(docs.static_folder,safe_join(g.version,filename))
예제 #42
0
def custom_static(filename):
    return send_from_memory(safe_join(app.config['STATIC_PATH'], filename))
예제 #43
0
def test_safe_join_toplevel_pardir():
    from flask.helpers import safe_join
    with pytest.raises(NotFound):
        safe_join('/foo', '..')
예제 #44
0
    def test_safe_join_toplevel_pardir(self):
        from flask.helpers import safe_join

        with self.assert_raises(NotFound):
            safe_join('/foo', '..')
예제 #45
0
def index():
    return send_from_memory(safe_join(app.config['STATIC_PATH'], 'index.html'))
예제 #46
0
파일: views.py 프로젝트: sarthak7g/storeS3
def upload_file():
    if request.method == "POST":

        if "contact_name" and "contact_email" and "uuid" in request.args:
            email_val = request.args["contact_email"]
            name_val = request.args["contact_name"]
            uuid = request.args["uuid"]

            if request.files:

                uploadFile = request.files['filename']

                if uploadFile.filename == "":
                    print("File must have a filename")
                    return jsonify("File must have a filename")

                if not allowedFile(uploadFile.filename):

                    # only blob
                    if uploadFile.filename.upper() == "BLOB":
                        video_stream = uploadFile.read()
                        with open(
                                os.path.join(app.config['file_uploads'],
                                             f"{uuid}_file.webm"),
                                'wb') as f_vid:
                            f_vid.write(video_stream)
                            f_vid.close()

                        # send to kafka
                        # file_url = safe_join(app.root_path, "static", f"{uuid}_file.webm")
                        file_url = "http://103.107.66.31:9008/upload-file?file_name=" + uuid + "_file.webm"
                        sendtoKafka(file_url, uuid, email_val)
                        return jsonify("success")

                    print("That files extensions are not allowed")
                    return jsonify("That files extensions are not allowed")
                else:
                    ext = uploadFile.filename.rsplit(".", 1)[1]
                    uploadFile.save(
                        os.path.join(app.config['file_uploads'],
                                     f'{uuid}_file.{ext}'))

                    # send to kafka
                    file_url = "http://103.107.66.31:9008/upload-file?file_name=" + uuid + "_file." + ext
                    sendtoKafka(file_url, uuid, email_val)

                print("file saved")
                return jsonify("success")

    if request.method == "GET":
        if "file_name" in request.args:
            file_name = request.args["file_name"]
            filename_new = safe_join(app.root_path, "static", file_name)

            if os.path.isfile(filename_new):
                try:
                    return send_file(filename_new)
                except Exception as e:
                    return jsonify(f"your path exists with error:{e}")
            else:
                return jsonify(f"{filename_new} does not exists")

    return render_template("index.html")
예제 #47
0
 def send_static_file(self, filename):
     fname = helpers.safe_join(self._static_folder, filename)
     f = pkg_resources.resource_stream(self.PACKAGENAME, fname)
     return helpers.send_file(f, attachment_filename=filename)
예제 #48
0
파일: views.py 프로젝트: Code4HR/brigade
def free_software_show(software):
    template_path = safe_join("free_software/", software + ".html")
    return render_template(template_path)
예제 #49
0
def themes_handler(path):
    filename = safe_join(app.root_path, 'html', 'user', 'static', path)
    if os.path.isfile(filename):
        return send_file(filename)
    else:
        abort(404)
예제 #50
0
def free_software_show(software):
    template_path = safe_join("free_software/", software + ".html")
    return render_template(template_path)
예제 #51
0
def test_safe_join_toplevel_pardir():
    from flask.helpers import safe_join
    with pytest.raises(NotFound):
        safe_join('/foo', '..')
예제 #52
0
파일: __init__.py 프로젝트: CibolaDuo/BOLTS
def drawing(filename,coll):
	return send_from_directory(join(environ['OPENSHIFT_REPO_DIR'],'drawings'),safe_join(coll,filename))
예제 #53
0
파일: views.py 프로젝트: semprix/CTFIgniter
def themes_handler(theme, path):
    filename = safe_join(app.root_path, 'themes', theme, 'static', path)
    if os.path.isfile(filename):
        return send_file(filename)
    else:
        abort(404)