示例#1
0
    def _check(self) -> bool:
        try:
            if not os_path.exists(self.log_file):
                Path(self.log_dir).mkdir(parents=True, exist_ok=True)
                sleep(0.1)
                os_chown(path=self.log_dir,
                         uid=os_getuid(),
                         gid=getgrnam(config.GA_GROUP)[2])
                os_chmod(path=self.log_dir,
                         mode=int(f'{config.LOG_DIR_PERMS}', base=8))

                with open(self.log_file, 'a+') as logfile:
                    logfile.write('init\n')

            try:
                os_chown(path=self.log_file,
                         uid=os_getuid(),
                         gid=getgrnam(config.GA_GROUP)[2])
                os_chmod(path=self.log_file,
                         mode=int(f'{config.LOG_FILE_PERMS}', base=8))

            except PermissionError:
                # if web tries to change core log-file permissions
                pass

            return True

        except PermissionError as error:
            print(f"LOG ERROR: {censor(error)}")
            return False
 def platformDetect(self):
     printDBG("IPTVSetupImpl.platformDetect")
     self.setInfo(_("Detection of the platform."), _("Plugin can be run on one of the following platforms: sh4, mipsel, i686, arm."))
     if 'j00zekFork' in globals():
         from Plugins.Extensions.IPTVPlayer.j00zekScripts.j00zekToolSet import getPlatform
         platform = getPlatform()
         if platform != 'unknown':
             self.platform = platform
             config.plugins.iptvplayer.plarform.value = self.platform
             printDBG("IPTVSetupImpl.j00zekFork platform[%s]" % self.platform)
             config.plugins.iptvplayer.plarform.save()
             configfile.save()
             self.setOpenSSLVersion()
             return
     cmdTabs = []
     for platform in self.supportedPlatforms:
         platformtesterPath = resolveFilename(SCOPE_PLUGINS, "Extensions/IPTVPlayer/bin/%s/platformtester" % platform)
         try: os_chmod(platformtesterPath, 0777)
         except: printExc()
         cmdTabs.append(platformtesterPath + "  2>&1 ")
     def _platformValidator(code, data):
         printDBG("IPTVSetupImpl._platformValidator")
         if "Test platform OK" in data: return True,False
         else: return False,True
     self.workingObj = CCmdValidator(self.platformDetectFinished, _platformValidator, cmdTabs)
     self.workingObj.start()
示例#3
0
	def render_POST(self, req):
		data = req.args['file'][0]
		print "[filename req.args]", req.args['filename'][0]
		filename = mbasename(req.args['filename'][0])
		print "[filename]", filename
		if not filename.endswith(".ipk"):
			return self.res % (_("wrong filetype!") ,_("Close"), _("Add"))
		
		if not data:
			req.setResponseCode(http.OK)
			return self.res % ( _("filesize was 0, not uploaded") ,
					_("Close"),
					 _("Add")
					)
		
		fd,fn = mkstemp(dir = "/tmp/")
		cnt = os_write(fd, data)
		os_close(fd)
		os_chmod(fn, 0755)
		
		if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all
			try:
				os_unlink(fn)
			except OSError, oe:
				pass
			req.setResponseCode(http.OK)
			return  self.res % (_("error writing to disk, not uploaded"),_("Close"), _("Add"))
示例#4
0
	def render_POST(self, req):
		uploaddir = self.default_uploaddir
		if req.args['path'][0]:
			if os_path.isdir(req.args['path'][0]):
				uploaddir = req.args['path'][0]
				if uploaddir[-1] != "/":
					uploaddir += "/"
			else:
				req.setResponseCode(http.OK)
				req.setHeader('Content-type', 'text/html')
				return "path '%s' to upload not existing!" % req.args['path'][0]

		data = req.args['file'][0]
		if not data:
			req.setResponseCode(http.OK)
			req.setHeader('Content-type', 'text/html')
			return "filesize was 0, not uploaded"

		fd, fn = mkstemp(dir = uploaddir)
		cnt = os_write(fd, data)
		os_close(fd)
		os_chmod(fn, 0755)
		
		if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all
			try:
				os_unlink(fn)
			except OSError, oe:
				pass
			req.setResponseCode(http.OK)
			req.setHeader('Content-type', 'text/html')
			return "error writing to disk, not uploaded"
示例#5
0
 def lchmod(path, mode):
     try:
         os_chmod(path, mode, follow_symlinks=False)
     except (TypeError, NotImplementedError, SystemError):
         # On systems that don't allow permissions on symbolic links, skip
         # links entirely.
         if not islink(path):
             os_chmod(path, mode)
 def requestRefresh(self):
     if self.underClosing: return
     if self.underRefreshing: return
     self.underRefreshing = True
     self.tmpList = []
     self.tmpData = ''
     lsdirPath = GetBinDir("lsdir")
     try: os_chmod(lsdirPath, 0777)
     except: printExc()
     cmd = '%s "%s" dl d' % (lsdirPath, self.currDir)
     printDBG("IPTVDirectorySelectorWidget.requestRefresh cmd[%s]" % cmd)
     self.console.execute( cmd )
示例#7
0
    def saveConfigClassToJson(self):
        with open(self.getFilePath(), mode='w') as config_class_json_file:
            uBelt.log('writeConfigClassToJson... Preparing Json',
                      isVerbose=True)
            json.dump(vars(self.config_class),
                      fp=config_class_json_file,
                      indent=2)
            uBelt.log('writeConfigClassToJson... Wrote Json', isVerbose=True)

        try:
            os_chmod(self.getFilePath(), 0o755)
        except Exception as e:
            uBelt.log('writeConfigClassToJson...' + str(e), isVerbose=True)
示例#8
0
    def render_POST(self, req):
        isXml = 'xml' in req.args and req.args['xml'][0] == 'True'
        uploaddir = self.default_uploaddir
        if req.args['path'][0]:
            if os_path.isdir(req.args['path'][0]):
                uploaddir = req.args['path'][0]
                if uploaddir[-1] != "/":
                    uploaddir += "/"
            else:
                return self.out_POST(
                    req, False,
                    "path '%s' to upload not existing!" % req.args['path'][0],
                    isXml)

        data = req.args['file'][0]
        if not data:
            return self.out_POST(req, False, "filesize was 0, not uploaded",
                                 isXml)

        # allw to overwrite files (if the user requests it), but not in critical directories
        overwrite = 'overwrite' in req.args and req.args['overwrite'][
            0] == 'True'
        if overwrite and uploaddir in self.restricted_paths:
            overwrite = False

        try:
            matches = search('.*?filename="(.*?)"\r\n.*?',
                             req.content.getvalue())
            fn = os_path.join(uploaddir, matches.group(1))
        except Exception as e:
            fn = None

        # NOTE: we only accept the given filename if no such file exists yet or the user requested it AND we think its safe
        if fn and (overwrite or not os_path.exists(fn)):
            fd = os_open(fn, O_WRONLY | O_CREAT)
        else:
            fd, fn = mkstemp(dir=uploaddir)
        cnt = os_write(fd, data)
        os_close(fd)
        os_chmod(fn, 0o755)

        if cnt <= 0:  # well, actually we should check against len(data) but lets assume we fail big time or not at all
            try:
                os_unlink(fn)
            except OSError as oe:
                pass
            return self.out_POST(req, False,
                                 "error writing to disk, not uploaded", isXml)
        else:
            statetext = fn if isXml else "uploaded to %s" % fn
            return self.out_POST(req, True, statetext, isXml)
示例#9
0
 def platformDetect(self):
     printDBG("IPTVSetupImpl.platformDetect")
     self.setInfo(_("Detection of the platform."), _("Plugin can be run on one of the following platforms: sh4, mipsel, i686, armv7, armv5t."))
     cmdTabs = []
     for platform in self.supportedPlatforms:
         platformtesterPath = resolveFilename(SCOPE_PLUGINS, "Extensions/IPTVPlayer/bin/%s/platformtester" % platform)
         try: os_chmod(platformtesterPath, 0777)
         except: printExc()
         cmdTabs.append(platformtesterPath + "  2>&1 ")
     def _platformValidator(code, data):
         printDBG("IPTVSetupImpl._platformValidator")
         if "Test platform OK" in data: return True,False
         else: return False,True
     self.workingObj = CCmdValidator(self.platformDetectFinished, _platformValidator, cmdTabs)
     self.workingObj.start()
示例#10
0
    def render_POST(self, req):
        uploaddir = self.default_uploaddir
        print "[UploadTextResource] req.args ", req.args
        if req.args["path"][0]:
            if os_path.isdir(req.args["path"][0]):
                uploaddir = req.args["path"][0]
                if uploaddir[-1] != "/":
                    uploaddir += "/"
            else:
                print "[UploadTextResource] not a dir", req.args["path"][0]
                req.setResponseCode(http.OK)
                req.setHeader("Content-type", "text/html")
                return "path '%s' to upload not existing!" % req.args["path"][0]

            if uploaddir[:10] == "/etc/opkg/" or uploaddir[:12] == "/usr/script/":
                pass
            else:
                req.setResponseCode(http.OK)
                req.setHeader("Content-type", "text/html")
                return "illegal upload directory: " + req.args["path"][0]

            data = req.args["text"][0].replace("\r\n", "\n")
        if not data:
            req.setResponseCode(http.OK)
            req.setHeader("Content-type", "text/html")
            return "filesize was 0, not uploaded"
        else:
            print "[UploadTextResource] text:", data

        filename = req.args["filename"][0]

        fd, fn = mkstemp(dir=uploaddir)
        cnt = os_write(fd, data)
        os_close(fd)
        os_chmod(fn, 0755)

        if cnt <= 0:  # well, actually we should check against len(data) but lets assume we fail big time or not at all
            try:
                os_unlink(fn)
            except OSError, oe:
                pass
            req.setResponseCode(http.OK)
            req.setHeader("Content-type", "text/html")
            return "error writing to disk, not uploaded"
示例#11
0
    def yellow_pressed(self):
        if self.iptvclosing:
            return
        if not self.underRefreshing:
            self.underRefreshing = True
            self.tmpList = []
            self.tmpData = ""
            lsdirPath = GetBinDir("lsdir")
            try:
                os_chmod(lsdirPath, 0777)
            except:
                printExc()
            cmd = '%s "%s" rl r' % (lsdirPath, config.plugins.iptvplayer.NaszaSciezka.value)
            printDBG("cmd[%s]" % cmd)
            self.console.execute(E2PrioFix(cmd))

        self.localMode = True
        self.reloadList(True)
        return
示例#12
0
    def render_POST(self, req):
        data = req.args['file'][0]
        print("[filename req.args]", req.args['filename'][0])
        filename = mbasename(req.args['filename'][0])
        print("[filename]", filename)
        if not filename.endswith(".ipk"):
            return self.res % (_("wrong filetype!"), _("Close"), _("Add"))

        if not data:
            req.setResponseCode(http.OK)
            return self.res % (_("filesize was 0, not uploaded"), _("Close"),
                               _("Add"))

        fd, fn = mkstemp(dir="/tmp/")
        cnt = os_write(fd, data)
        os_close(fd)
        os_chmod(fn, 0o755)

        if cnt <= 0:  # well, actually we should check against len(data) but lets assume we fail big time or not at all
            try:
                os_unlink(fn)
            except OSError as oe:
                pass
            req.setResponseCode(http.OK)
            return self.res % (_("error writing to disk, not uploaded"),
                               _("Close"), _("Add"))

        else:
            file = "/tmp/" + filename
            os_rename(fn, (file))
            if file is not None:
                out = os_popen("opkg install %s" % file)
                debug = ""
                for line in out:
                    debug += line
            else:
                return self.res % (_("error writing to disk, not uploaded"),
                                   _("Close"), _("Add"))

            req.setResponseCode(http.OK)
            return self.res % ((debug), _("Close"), _("Add"))
示例#13
0
 def prepareCmd(self, path, start, end):
     lsdirPath = GetBinDir("lsdir")
     try: os_chmod(lsdirPath, 0777)
     except: printExc()
     if config.plugins.iptvplayer.local_showhiddensdir.value:
         dWildcards = '[^.]*|.[^.]*|..[^.]*'
     else: dWildcards = '[^.]*'
     
     fWildcards = []
     extensions = self.VIDEO_FILE_EXTENSIONS + self.AUDIO_FILES_EXTENSIONS + self.PICTURE_FILES_EXTENSIONS + self.M3U_FILES_EXTENSIONS
     for ext in extensions:
         if config.plugins.iptvplayer.local_showhiddensfiles.value:
             wilcard = ''
         else: wilcard = '[^.]*'
         insensitiveExt=''
         for l in ext:
             insensitiveExt += '[%s%s]' % (l.upper(), l.lower())
         wilcard += '.' + insensitiveExt
         fWildcards.append(wilcard)
     cmd = '%s "%s" rdl rd %d %d "%s" "%s"' % (lsdirPath, path, start, end, '|'.join(fWildcards), dWildcards)
     return cmd
示例#14
0
 def keySave(self): #openpliPC - F2 emuluje green
     myContent = "### Utworzono za pomocą konfiguratora ustawień GOS @j00zek ###\n"
     for x in self["config"].list:
         for GOSsetting in GOSsettings_list:
             if GOSsetting[0] == x[1]:
                 opcja = GOSsetting[1]
                 wartosc = x[1].getValue()
                 if GOSsetting[2] == "CONFIG": # do konfiguracji, tylko konfiguracje
                     # wymuszenie wartosci standardowych
                     if str(opcja) == "usePeriod" and str(wartosc) == 130: wartosc=0
                     elif str(opcja) == "useDelay" and str(wartosc) == 20: wartosc=0
                     
                     if str(wartosc) not in ["0" , "lircd.conf"]: # tu ewentualnie dopisac, jakie zmienne są defaultowe
                         myContent += str(opcja) + '=' + str(wartosc) + '\n'
                 elif GOSsetting[2] == "DEF": # musimy zalatwic procedurą
                     print str(opcja)
                     #opkg
                     if str(opcja) == "opkg":
                         if wartosc != "NA": #NA to nasz defaultowy release, po prostu not available ;)
                             self.session.openWithCallback(self.opkg2test,MessageBox,_("Are you sure, you want to switch opkg branch to UNSTABLE %s?") % wartosc, MessageBox.TYPE_YESNO)
                     #reportGS
                     elif str(opcja) == "ReportGS":
                         if config.GOSsettings.ReportGS.value == "off" and fileExists("/etc/rc.d/rc5.d/S90reportGS"):
                             os_remove("/etc/rc.d/rc5.d/S90reportGS")
                         elif config.GOSsettings.ReportGS.value == "on" and not fileExists("/etc/rc.d/rc5.d/S90reportGS"):
                             os_chmod(resolveFilename(SCOPE_PLUGINS, 'Extensions/GOSmanager/components/reportGS'), 0775)
                             os_symlink(resolveFilename(SCOPE_PLUGINS, 'Extensions/GOSmanager/components/reportGS'),"/etc/rc.d/rc5.d/S90reportGS")
                             
         x[1].save()
     #zapis konfiguracji gos
     with open (self.MySetupFile, "w") as myconfigfile:
         myconfigfile.write(myContent)
         myconfigfile.flush()
         os_fsync(myconfigfile.fileno())
         myconfigfile.close()
     configfile.save()
     self.close()
示例#15
0
 def createFile(self):
     file = open("/etc/rc3.d/S30rcsetup", "w")
     m = 'echo ' + config.plugins.RCSetup.mode.value + ' > /proc/stb/ir/rc/type'
     file.write(m)
     file.close()
     os_chmod("/etc/rc3.d/S30rcsetup", 0o755)
示例#16
0
    def _check_file(self, files: dict) -> bool:
        result_dict = {}

        for file, config in files.items():
            path = config['path']
            result_dict[file] = False

            if not os_path.exists(path) and not config['exists']:
                result_dict[file] = True

            elif os_path.exists(path):
                perms = int(oct(os_stat(path).st_mode)[-3:])
                owner_perm, group_perm, other_perm = [
                    int(num) for num in str(perms)
                ]

                owner = os_stat(path).st_uid
                group = os_stat(path).st_gid

                if perms != config['perms'] or owner != config[
                        'owner'] or group != config['group']:
                    self._log(
                        f"Permissions for file \"{path}\" are not set as expected"
                    )
                    self._log(
                        f"Permissions for file \"{path}\" are \"{owner = }, {group = }, {perms= }\" "
                        f"but should be \"owner = {config['owner']}, group = {config['group']}, perms = {config['perms']}\"",
                        level=6)

                    # extended check
                    if config['access'] == 'rw':
                        target_perm = 6

                    else:
                        target_perm = 4

                    sub_check_dict = {
                        'owner': False,
                        'group': False,
                        'other': False
                    }

                    if owner == config['owner'] and owner_perm == target_perm:
                        sub_check_dict['owner'] = True

                    if owner == config['group'] and group_perm == target_perm:
                        sub_check_dict['group'] = True

                    if other_perm == target_perm:
                        sub_check_dict['other'] = True

                    if not all(sub_check_dict.values()):
                        try:
                            os_chown(path=path,
                                     uid=config['owner'],
                                     gid=config['group'])
                            os_chmod(path=path,
                                     mode=int(f"{config['perms']}", base=8))
                            result_dict[file] = True

                        except PermissionError:
                            self._log(
                                f"Failed to set permissions for file \"{path}\""
                            )
                            self._log(
                                f"{format_exc(limit=config.LOG_MAX_TRACEBACK_LENGTH)}"
                            )
                            result_dict[file] = False

                if 'type' in config and config['type'] == 'text':
                    if config['access'] == 'rw':
                        try:
                            with open(path, 'r+') as _:
                                _data = _.read()

                            result_dict[file] = True

                        except PermissionError:
                            self._log(
                                f"Failed to open file \"{path}\" for writing")
                            self._log(
                                f"{format_exc(limit=config.LOG_MAX_TRACEBACK_LENGTH)}"
                            )
                            continue

                    if config['access'] == 'r':
                        try:
                            with open(path, 'r') as _:
                                _data = _.read()

                            result_dict[file] = True

                        except PermissionError:
                            self._log(
                                f"Failed to open file \"{path}\" for reading")
                            self._log(
                                f"{format_exc(limit=config.LOG_MAX_TRACEBACK_LENGTH)}"
                            )
                            continue

        if all(result_dict.values()):
            return True

        return False
 def prepareCmd(self):
     lsdirPath = GetBinDir("lsdir")
     try: os_chmod(lsdirPath, 0777)
     except: printExc()
     cmd = '%s "%s" drl dr' % (lsdirPath, self.currDir)
     return cmd
示例#18
0
def write_ca(request, cert_id):
    """ Function called when a new Trusted CA certificate is imported.
     It will write-it on disk.

    :param request: Django request object
    :param cert_id: String id of certificate to write on disk
    :return:
    """

    try:
        certificate = SSLCertificate(ObjectId(cert_id))
    except Exception as e:
        logger.error(
            "API::write_ca: CA Certificate '{}' not found : {}".format(
                cert_id, e))
        return JsonResponse({
            'status':
            0,
            'error':
            "CA Certificate '{}' not found : {}".format(cert_id, str(e))
        })

    try:
        cert_content = json_loads(request.body)['certificate']
    except Exception as e:
        logger.error(
            "API::write_ca: CA certificate content not found in api request : {}"
            .format(str(e)))
        return JsonResponse({
            'status':
            0,
            'error':
            "CA certificate content null : {}".format(str(e))
        })

    # Write the certificate on disk
    certificate_path = "{}/{}.crt".format(certs_dir, str(cert_id))
    try:
        with open(certificate_path, "w") as certificate_fd:
            certificate_fd.write(str(cert_content))
    except Exception as e:
        logger.error(
            "API::write_ca: Cannot write CA certificate '{}' on disk : {}".
            format(certificate_path, e))
        return JsonResponse({
            'status':
            0,
            'error':
            "Cannot write CA certificate '{}' on disk : {}".format(
                certificate_path, str(e))
        })

    # Set permissions
    try:
        os_chmod(certificate_path, 664)
        os_system("/usr/bin/chgrp vlt-web {}".format(certificate_path))
    except Exception as e:
        logger.error(
            "API::write_ca: Failed to set permissions on '{}' file : {}".
            format(certificate_path, str(e)))

    os_system("/usr/local/bin/c_rehash /home/vlt-sys/Engine/conf/certs")
    logger.info("API::write_ca: Ca certificate successfully written on disk")

    return JsonResponse({'status': 1})
示例#19
0
	def createFile(self):
		file = open("/etc/rc3.d/S30rcsetup", "w")
		m = 'echo ' + config.plugins.RCSetup.mode.value + ' > /proc/stb/ir/rc/type'
		file.write(m)
		file.close()
		os_chmod("/etc/rc3.d/S30rcsetup", 0755)
示例#20
0
 def create_start_or_stop_script(self, if_start):
     # PREPARE VARIABLES #
     data_for_file = ''.join(
         [config.header_script_declaration, style.sing_newline])
     if if_start:
         start_or_stop_message = text.text_21
         script_name = os_path.join(config.path_to_script,
                                    config.start_script_name)
         final_message = ''.join([
             style.sing_newline, text.text_23, style.sing_newline,
             script_name, style.sing_newline
         ])
     elif not if_start:
         start_or_stop_message = text.text_22
         script_name = os_path.join(config.path_to_script,
                                    config.stop_script_name)
         final_message = ''.join([
             style.sing_newline, text.text_24, style.sing_newline,
             script_name, style.sing_newline
         ])
         self.list_of_processes_to_check.reverse()
     # CREATE DATA FOR SCRIPT #
     for process_group in self.list_of_processes_to_check:
         data_for_file += ''.join([
             config.command_echo, style.sign_space, style.sign_apostrophe,
             process_group.group_name, style.sign_minus_space,
             start_or_stop_message, style.sign_apostrophe,
             style.sing_newline
         ])
         if not if_start: process_group.processes_list.reverse()
         for process in process_group.processes_list:
             if process.start_command and if_start:
                 data_for_file += ''.join(
                     [process.start_command, style.sing_newline])
             elif process.end_command and not if_start:
                 data_for_file += ''.join(
                     [process.end_command, style.sing_newline])
             if config.break_between_each_start_stop_command_in_seconds > 0:
                 data_for_file += ''.join([
                     config.command_sleep, style.sign_space,
                     str(config.
                         break_between_each_start_stop_command_in_seconds),
                     style.sing_newline
                 ])
     data_for_file += ''.join([
         config.command_echo, style.sign_space, style.sign_apostrophe,
         text.text_25, style.sign_apostrophe, style.sing_newline
     ])
     # SAVE DATA TO FILE #
     try:
         with open(script_name, 'w') as created_script_file:
             created_script_file.write(data_for_file)
     except:
         sys_exit(''.join([
             style.sing_newline, text.text_6, style.sing_newline,
             script_name, style.sing_newline
         ]))
     # SET PERMISSIONS TO SCRIPT #
     if config.owner_of_the_script:
         try:
             os_chown(script_name,
                      getpwnam(config.owner_of_the_script).pw_uid, 0)
         except:
             sys_exit(''.join([
                 style.sing_newline, text.text_1, style.sing_newline,
                 script_name, style.sing_newline, text.text_3,
                 style.sing_newline
             ]))
     os_chmod(script_name, config.access_rights_to_scipt)
     print(final_message)
示例#21
0
 def lchmod(path, mode):
     # On systems that don't allow permissions on symbolic links, skip
     # links entirely.
     if not islink(path):
         os_chmod(path, mode)
示例#22
0
    def render_POST(self, req):
        uploaddir = self.default_uploaddir
        print("[UploadTextResource] req.args ", req.args)
        if req.args['path'][0]:
            if os_path.isdir(req.args['path'][0]):
                uploaddir = req.args['path'][0]
                if uploaddir[-1] != "/":
                    uploaddir += "/"
            else:
                print("[UploadTextResource] not a dir", req.args['path'][0])
                req.setResponseCode(http.OK)
                req.setHeader('Content-type', 'text/html')
                return "path '%s' to upload not existing!" % req.args['path'][0]

            if uploaddir[:
                         10] == "/etc/opkg/" or uploaddir[:
                                                          12] == "/usr/script/":
                pass
            else:
                req.setResponseCode(http.OK)
                req.setHeader('Content-type', 'text/html')
                return "illegal upload directory: " + req.args['path'][0]

            data = req.args['text'][0].replace('\r\n', '\n')
        if not data:
            req.setResponseCode(http.OK)
            req.setHeader('Content-type', 'text/html')
            return "filesize was 0, not uploaded"
        else:
            print("[UploadTextResource] text:", data)

        filename = req.args['filename'][0]

        fd, fn = mkstemp(dir=uploaddir)
        cnt = os_write(fd, data)
        os_close(fd)
        os_chmod(fn, 0o755)

        if cnt <= 0:  # well, actually we should check against len(data) but lets assume we fail big time or not at all
            try:
                os_unlink(fn)
            except OSError as oe:
                pass
            req.setResponseCode(http.OK)
            req.setHeader('Content-type', 'text/html')
            return "error writing to disk, not uploaded"
        else:
            file = uploaddir + filename
            os_rename(fn, file)
            return """
					<?xml version="1.0" encoding="UTF-8"?>
					<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
							"http://www.w3.org/TR/html4/loose.dtd">
					<html>

					<head>
					<meta content="text/html; charset=UTF-8" http-equiv="content-type">

					<link href="/web-data/tpl/default/style.min.css" type="text/css" rel="stylesheet">
					<link rel="shortcut icon" type="image/x-icon" href="/web-data/img/favicon.ico">
					</head>
					<body onunload="javascript:opener.location.reload()" >
						<hr>
						<p align="left">
						uploaded to %s
						</p>
						<hr>
						<form>
							<input type="button" value="%s" onClick="window.close();">
						</form>
					</body>
					</html>""" % (file, _("Close"))