/** Change the owner and group of a file */
int nphfuse_chown(const char *path, uid_t uid, gid_t gid){
    log_msg("Entry into CHOWN.\n");
    npheap_store *inode = NULL;
    struct timeval currTime;

    if(strcmp (path,"/")==0){
        log_msg("Calling getRootDirectory() in CHOWN.\n");
        
        inode = getRootDirectory();
        if(inode==NULL)
        {
            log_msg("Root directory not found. in CHOWN.\n");
            return -ENOENT;
        }
        else
        {
            log_msg("Root directory found. in CHOWN.\n");
            //Check if accessibilty can be given
            int flag = checkAccess(inode);
            //Deny the access
            if(flag == 0){
                return -EACCES;
            }
            //else set correct value
            log_msg("Owner of root  changed in CHOWN.\n", path);
            gettimeofday(&currTime, NULL);
            inode->mystat.st_uid = uid;
            inode->mystat.st_gid = gid;
            inode->mystat.st_ctime = currTime.tv_sec;
            log_msg("Exit from CHOWN.\n");
            return 0;
        }
    }
    
    inode = retrieve_inode(path);
    
    if(inode == NULL){
        log_msg("Couldn't find path - %s - in CHOWN.\n", path);
        return -ENOENT;
    }
    //Check Accessibility
    int flag1 = checkAccess(inode);
    
    //Deny the access
    if(flag1 == 0){
        return -EACCES;
    }
    
    //else set correct value
    log_msg("Owner of path - %s - changed in CHOWN.\n", path);
    gettimeofday(&currTime, NULL);
    inode->mystat.st_uid = uid;
    inode->mystat.st_gid = gid;
    inode->mystat.st_ctime = currTime.tv_sec;
    log_msg("Exit from CHOWN.\n");
    return 0;
}
/** Change the access and/or modification times of a file */
int nphfuse_utime(const char *path, struct utimbuf *ubuf){
    log_msg("Into utime.\n");
    npheap_store *temp = NULL;

    if(strcmp(path,"/")==0){
        temp = getRootDirectory();
        if(temp==NULL)
        {
            log_msg("Root directory not found in utime.\n");
            return -ENOENT;
        }
        else
        {
            int flag = checkAccess(temp);
            if(flag==0){
                log_msg("Cannot access in root.\n");
                return - EACCES;
            }

            // Set from ubuf
            if(ubuf->actime){
                temp->mystat.st_atime = ubuf->actime;
            }
            if(ubuf->modtime){
                temp->mystat.st_mtime = ubuf->modtime;
            }
            log_msg("Ubuf ran successfully.! \n");
            return 0;
        }
    }

    temp = retrieve_inode(path);

    if(temp==0){
        log_msg("Cannot find the inode in ubuf.\n");
        return -ENOENT;
    }

    int flag1 = checkAccess(temp);
    if(flag1==0){
        log_msg("Cannot access the asked inode.\n");
        return - EACCES;
    }

    if(ubuf->actime){
        temp->mystat.st_atime = ubuf->actime;
    }
    if(ubuf->modtime){
        temp->mystat.st_mtime = ubuf->modtime;
    }
    log_msg("Ubuf ran successfully.! \n");
    return 0;

}
Exemple #3
0
/****************************************
 * Check access to d for expression e.d
 * Returns true if the declaration is not accessible.
 */
bool checkAccess(Loc loc, Scope *sc, Expression *e, Declaration *d)
{
    if (sc->flags & SCOPEnoaccesscheck)
        return false;

#if LOG
    if (e)
    {
        printf("checkAccess(%s . %s)\n", e->toChars(), d->toChars());
        printf("\te->type = %s\n", e->type->toChars());
    }
    else
    {
        printf("checkAccess(%s)\n", d->toPrettyChars());
    }
#endif
    if(d->isUnitTestDeclaration()) 
    {
        // Unittests are always accessible.
        return false;
    }
    if (!e)
    {
        if (d->prot().kind == PROTprivate && d->getAccessModule() != sc->module ||
            d->prot().kind == PROTpackage && !hasPackageAccess(sc, d))
        {
            error(loc, "%s %s is not accessible from module %s",
                d->kind(), d->toPrettyChars(), sc->module->toChars());
            return true;
        }
    }
    else if (e->type->ty == Tclass)
    {
        // Do access check
        ClassDeclaration *cd = (ClassDeclaration *)(((TypeClass *)e->type)->sym);
        if (e->op == TOKsuper)
        {
            ClassDeclaration *cd2 = sc->func->toParent()->isClassDeclaration();
            if (cd2)
                cd = cd2;
        }
        return checkAccess(cd, loc, sc, d);
    }
    else if (e->type->ty == Tstruct)
    {
        // Do access check
        StructDeclaration *cd = (StructDeclaration *)(((TypeStruct *)e->type)->sym);
        return checkAccess(cd, loc, sc, d);
    }
    return false;
}
void FileTransferRequestHandler::dirSizeRequested()
{
  WinFilePath fullPathName;

  {
    m_input->readUTF8(&fullPathName);
  } // end of reading block.

  m_log->message(_T("Size of folder '%s\' requested"),
               fullPathName.getString());

  checkAccess();

  UINT64 directorySize = 0;

  if (!getDirectorySize(fullPathName.getString(), &directorySize)) {
    throw SystemException();
  }

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::DIRSIZE_REPLY);
    m_output->writeUInt64(directorySize);

    m_output->flush();
  }
} // void
void FileTransferRequestHandler::mvFileRequested()
{
  WinFilePath oldFileName;
  WinFilePath newFileName;

  {
    m_input->readUTF8(&oldFileName);
    m_input->readUTF8(&newFileName);
  } // end of reading block.

  m_log->message(_T("move \"%s\" \"%s\" command requested"), oldFileName.getString(), newFileName.getString());

  checkAccess();

  File srcFile(oldFileName.getString());
  File dstFile(newFileName.getString());

  if (!srcFile.renameTo(&dstFile)) {
    throw SystemException();
  }

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::RENAME_REPLY);

    m_output->flush();
  }
}
void FileTransferRequestHandler::rmFileRequested()
{
  WinFilePath fullPathName;

  {
    m_input->readUTF8(&fullPathName);
  } // end of reading block.

  m_log->message(_T("rm \"%s\" command requested"), fullPathName.getString());

  checkAccess();

  File file(fullPathName.getString());

  if (!file.exists()) {
    throw SystemException();
  } // file file does not exists

  if (!file.remove()) {
    throw SystemException();
  } // if cannot delete file

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::REMOVE_REPLY);

    m_output->flush();
  }
} // void
void FileTransferRequestHandler::mkDirRequested()
{
  WinFilePath folderPath;

  {
    m_input->readUTF8(&folderPath);
  } // end of reading block.

  m_log->message(_T("mkdir \"%s\" command requested"), folderPath.getString());

  checkAccess();

  if (folderPath.parentPathIsRoot()) {
    throw FileTransferException(_T("Cannot create folder in root folder"));
  }

  File folder(folderPath.getString());

  if (folder.exists()) {
    throw FileTransferException(_T("Directory already exists"));
  }

  if (!folder.mkdir()) {
    throw SystemException();
  }

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::MKDIR_REPLY);

    m_output->flush();
  }
}
/** File open operation
 *
 * No creation, or truncation flags (O_CREAT, O_EXCL, O_TRUNC)
 * will be passed to open().  Open should check if the operation
 * is permitted for the given flags.  Optionally open may also
 * return an arbitrary filehandle in the fuse_file_info structure,
 * which will be passed to all file operations.
 *
 * Changed in version 2.2
 */
int nphfuse_open(const char *path, struct fuse_file_info *fi){
    struct timeval currTime;
    npheap_store *temp = NULL;

    //Check for root directory
    if(strcmp(path,"/")==0){
        temp = getRootDirectory();
        if(temp==NULL)
        {
            log_msg("Root directory not found in open.\n");
            return -ENOENT;
        }
        else
        {
            int flag = checkAccess(temp);

            //If cannot access
            if(flag == 0){
                log_msg("Root access denied.\n");
                return -EACCES;
            }
            // Worked fine
            log_msg("Access granted to root.\n");
            return 0;
        }
    }

    temp = retrieve_inode(path);
    if(temp == NULL){
        return -ENOENT;
    }

    int flag1 = checkAccess(temp);

    //if cannot access
    if(flag1 == 0){
        log_msg("Access denied.\n");
        return -EACCES;
    }
    //Everything worked fine
    fi->fh = temp->mystat.st_ino;
    gettimeofday(&currTime, NULL);
    temp->mystat.st_atime = currTime.tv_sec;
    return 0;
}
/** Open directory
 *
 * This method should check if the open operation is permitted for
 * this directory
 *
 * Introduced in version 2.3
 */
int nphfuse_opendir(const char *path, struct fuse_file_info *fi){
    // char *filename, *dir;
    // extract_directory_file(&dir,&filename,path);
    npheap_store *inode = NULL;
    log_msg("Entry into OPENDIR.\n");
    if(strcmp (path,"/")==0){
        inode = getRootDirectory();
        if(inode==NULL)
        {
            log_msg("Root directory not found in opendir.\n");
            return -ENOENT;
        }
        else
        {
            //Check if accessibilty can be given
            int flag = checkAccess(inode);
            //Deny the access
            log_msg("Root access %d (if 1 then yes)",flag);
            if(flag == 0){
                return -EACCES;
            }
            return 0;
        }
    }

    inode = retrieve_inode(path);

    if(inode == NULL){
        log_msg("Couldn't find path - %s - in OPENDIR.\n", path);
        return -ENOENT;
    }
    //Check Accessibility
    int flag1 = checkAccess(inode);

    //Deny the access
    log_msg("Normal access %d (if 1 then yes)",flag1);
    if(flag1 == 0){
        return -EACCES;
    }
    //else return correct value
    log_msg("Exit into OPENDIR.\n");
    return 0;
}
BlockIO InterpreterInsertQuery::execute()
{
    ASTInsertQuery & query = typeid_cast<ASTInsertQuery &>(*query_ptr);
    checkAccess(query);
    StoragePtr table = getTable();

    auto table_lock = table->lockStructure(true, __PRETTY_FUNCTION__);

    NamesAndTypesList required_columns = table->getColumnsList();

    /// We create a pipeline of several streams, into which we will write data.
    BlockOutputStreamPtr out;

    out = std::make_shared<PushingToViewsBlockOutputStream>(query.database, query.table, table, context, query_ptr, query.no_destination);

    out = std::make_shared<MaterializingBlockOutputStream>(out);

    out = std::make_shared<AddingDefaultBlockOutputStream>(
        out, required_columns, table->column_defaults, context, static_cast<bool>(context.getSettingsRef().strict_insert_defaults));

    if (!allow_materialized)
        out = std::make_shared<ProhibitColumnsBlockOutputStream>(out, table->materialized_columns);

    out = std::make_shared<SquashingBlockOutputStream>(
        out, context.getSettingsRef().min_insert_block_size_rows, context.getSettingsRef().min_insert_block_size_bytes);

    auto out_wrapper = std::make_shared<CountingBlockOutputStream>(out);
    out_wrapper->setProcessListElement(context.getProcessListElement());
    out = std::move(out_wrapper);

    BlockIO res;
    res.out_sample = getSampleBlock();

    /// What type of query: INSERT or INSERT SELECT?
    if (!query.select)
    {
        res.out = out;
    }
    else
    {
        InterpreterSelectQuery interpreter_select{query.select, context};
        res.in_sample = interpreter_select.getSampleBlock();

        res.in = interpreter_select.execute().in;

        res.in = std::make_shared<NullableAdapterBlockInputStream>(res.in, res.in_sample, res.out_sample);
        res.in = std::make_shared<CastTypeBlockInputStream>(context, res.in, res.out_sample);
        res.in = std::make_shared<NullAndDoCopyBlockInputStream>(res.in, out);
    }

    return res;
}
void FileTransferRequestHandler::downloadStartRequested()
{
  WinFilePath fullPathName;
  UINT64 initialOffset;

  //
  // Reading command arguments
  //

  {
    m_input->readUTF8(&fullPathName);
    initialOffset = m_input->readUInt64();
  } // end of reading block.

  m_log->message(_T("download of \"%s\" file (offset = %d) requested"), fullPathName.getString(), initialOffset);

  checkAccess();

  //
  // Ending previous download if it was broken
  //

  if (m_fileInputStream != 0) {
    delete m_fileInputStream;
    m_fileInputStream = 0;
  }
  if (m_downloadFile != 0) {
    delete m_downloadFile;
    m_downloadFile = 0;
  }

  m_downloadFile = new File(fullPathName.getString());


  //
  // Try to open file for reading and seek to initial
  // file position.
  //

  m_fileInputStream = new WinFileChannel(fullPathName.getString(), F_READ,
                                         FM_OPEN);
  m_fileInputStream->seek(initialOffset);

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::DOWNLOAD_START_REPLY);

    m_output->flush();
  }
}
int ConfigCtx::checkPath(char *pPath, const char *desc, int follow)
{
    char achOld[MAX_PATH_LEN];
    struct stat st;
    int ret = ls_fio_stat(pPath, &st);

    if (ret == -1)
    {
        logErrorPath(desc,  pPath);
        return LS_FAIL;
    }

    memccpy(achOld, pPath, 0, MAX_PATH_LEN - 1);
    ret = GPath::checkSymLinks(pPath, pPath + strlen(pPath),
                               pPath + MAX_PATH_LEN, pPath, follow);

    if (ret == -1)
    {
        if (errno == EACCES)
        {
            LS_ERROR(this, "Path of %s contains symbolic link or"
                     " ownership does not match:%s",
                     desc, pPath);
        }
        else
            logErrorPath(desc,  pPath);

        return LS_FAIL;
    }

    if (S_ISDIR(st.st_mode))
    {
        if (* (pPath + ret - 1) != '/')
        {
            * (pPath + ret) = '/';
            * (pPath + ret + 1) = 0;
        }
    }

    if (strcmp(achOld, pPath) != 0)
        LS_DBG_L("the real path of %s is %s.", achOld, pPath);

    if (ServerProcessConfig::getInstance().getChroot() != NULL)
        pPath += ServerProcessConfig::getInstance().getChroot()->len();

    if (checkAccess(pPath))
        return LS_FAIL;

    return 0;
}
BlockIO InterpreterCreateQuery::execute()
{
    ASTCreateQuery & create = typeid_cast<ASTCreateQuery &>(*query_ptr);
    checkAccess(create);
    ASTQueryWithOutput::resetOutputASTIfExist(create);

    /// CREATE|ATTACH DATABASE
    if (!create.database.empty() && create.table.empty())
    {
        return createDatabase(create);
    }
    else
        return createTable(create);
}
// both path and newpath are fs-relative
int nphfuse_rename(const char *path, const char *newpath)
{
    log_msg("RENAME called for %s path to %s newpath\n", path, newpath);
    struct timeval currTime;
    npheap_store *inode = NULL;
    char dir[236];
    char filename[128];

    //Root directory cannot be changed.
    if(strcmp(path,"/")==0){
        return -EACCES;
    }

    //Get inode into path
    inode = retrieve_inode(path);
    if(inode == NULL){
        log_msg("Inode was not found in rename.\n");
        return -ENOENT;
    }

    //Check if newpath is valid
    int extract = extract_directory_file(dir, filename, newpath);
    if(extract == 1){
        log_msg("Newpath is invalid.\n");
        return -EINVAL;
    }

    //Check if user has access
    int flag = checkAccess(inode);
    if(flag==0){
        log_msg("Cannot access the directory.\n");
        return - EACCES;
    }

    //memset the dirname and filename
    //memset(inode->dirname, 0, 236);
    //memset(inode->filename, 0, 128);

    //copy the new path
    strcpy(inode->dirname, dir);
    strcpy(inode->filename, filename);

    //Change the changetime
    gettimeofday(&currTime, NULL);
    inode->mystat.st_ctime = currTime.tv_sec;

    log_msg("Exiting from RENAME.\n");
    return 0;
}
void FileTransferRequestHandler::uploadDataRequested()
{
  //
  // Request input variables.
  //

  UINT8 compressionLevel;
  UINT32 compressedSize;
  UINT32 uncompressedSize;

  compressionLevel = m_input->readUInt8();
  compressedSize = m_input->readUInt32();
  uncompressedSize = m_input->readUInt32();
  std::vector<char> buffer(compressedSize);
  if (compressedSize != 0) {
    m_input->readFully(&buffer.front(), compressedSize);
  }

  m_log->info(_T("upload data (cs = %d, us = %d) requested"), compressedSize, uncompressedSize);

  checkAccess();

  if (m_uploadFile == NULL) {
    throw FileTransferException(_T("No active upload at the moment"));
  }

  if (compressedSize != 0) {
    if (compressionLevel == 0) {
      DataOutputStream dataOutStream(m_fileOutputStream);
      dataOutStream.writeFully(&buffer.front(), uncompressedSize);
    } else {
      m_inflater.setInput(&buffer.front(), compressedSize);
      m_inflater.setUnpackedSize(uncompressedSize);
      m_inflater.inflate();

      DataOutputStream dataOutStream(m_fileOutputStream);

      dataOutStream.writeFully(m_inflater.getOutput(), m_inflater.getOutputSize());
    } // if using compression
  }

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::UPLOAD_DATA_REPLY);

    m_output->flush();
  }
}
int nphfuse_access(const char *path, int mask){

    npheap_store *inode = NULL;
    
    if(strcmp(path,"/")==0){
        inode = getRootDirectory();
        if(inode==NULL)
        {
            log_msg("Root directory not found in access.\n");
            return -ENOENT;
        }
        else
        {
            log_msg("Checking Access of root\n");
            int flag = checkAccess(inode);
            if(flag==0){
                log_msg("Cannot access the directory\n");
                return -EACCES;
            }
            return 0;
        }
    }

    inode = retrieve_inode(path);

    if(inode == NULL){
        return -ENOENT;
    }
    int flag = checkAccess(inode);
    if(flag==0){
        log_msg("Cannot access the directory\n");
        return -EACCES;
    }
    
    return 0;
}
bool KConfigBackEnd::checkConfigFilesWritable(bool warnUser)
{
    // WARNING: Do NOT use the event loop as it may not exist at this time.
    bool allWritable = true;
    QString errorMsg;
    if(!mLocalFileName.isEmpty() && !bFileImmutable && !checkAccess(mLocalFileName, W_OK))
    {
        errorMsg = i18n("Will not save configuration.\n");
        allWritable = false;
        errorMsg += i18n("Configuration file \"%1\" not writable.\n").arg(mLocalFileName);
    }
    // We do not have an immutability flag for kdeglobals. However, making kdeglobals mutable while making
    // the local config file immutable is senseless.
    if(!mGlobalFileName.isEmpty() && useKDEGlobals && !bFileImmutable && !checkAccess(mGlobalFileName, W_OK))
    {
        if(errorMsg.isEmpty())
            errorMsg = i18n("Will not save configuration.\n");
        errorMsg += i18n("Configuration file \"%1\" not writable.\n").arg(mGlobalFileName);
        allWritable = false;
    }

    if(warnUser && !allWritable)
    {
        // Note: We don't ask the user if we should not ask this question again because we can't save the answer.
        errorMsg += i18n("Please contact your system administrator.");
        QString cmdToExec = KStandardDirs::findExe(QString("kdialog"));
        KApplication *app = kapp;
        if(!cmdToExec.isEmpty() && app)
        {
            KProcess lprocess;
            lprocess << cmdToExec << "--title" << app->instanceName() << "--msgbox" << errorMsg.local8Bit();
            lprocess.start(KProcess::Block);
        }
    }
    return allWritable;
}
BlockIO InterpreterDropQuery::execute()
{
    ASTDropQuery & drop = typeid_cast<ASTDropQuery &>(*query_ptr);

    checkAccess(drop);

    if (!drop.cluster.empty())
        return executeDDLQueryOnCluster(query_ptr, context, {drop.database});

    if (!drop.table.empty())
        return executeToTable(drop.database, drop.table, drop.kind, drop.if_exists, drop.temporary);
    else if (!drop.database.empty())
        return executeToDatabase(drop.database, drop.kind, drop.if_exists);
    else
        throw Exception("Database and table names is empty.", ErrorCodes::LOGICAL_ERROR);
}
/** Remove a directory */
int nphfuse_rmdir(const char *path){
    //unlink is also called
    log_msg("Into RMDIR.\n");
    char dir[236];
    char filename[128];
    npheap_store *inode = NULL;
    uint64_t offset = 2;
    int index = 0;

    int extract = extract_directory_file(dir,filename,path);

    if(extract==1){
        log_msg("Cannot extraxt path in rmdir.\n");
        return -ENOENT;
    }

    for(offset = 2; offset < 502; offset++){
        inode= (npheap_store *)npheap_alloc(npheap_fd, offset, BLOCK_SIZE);
        if(inode==NULL)
        {
            log_msg("NPheap alloc failed for offset : %d",offset);
        }
        for (index = 0; index <16; index++)
        {
            if ((!strcmp (inode[index].dirname, dir)) &&
                (!strcmp (inode[index].filename, filename))){
                    log_msg("%s directory and %s filename \n", dir, filename);

                    int flag = checkAccess(inode);
                    if(flag==0){
                        log_msg("Cannot access the directory\n");
                        return - EACCES;
                    }
                    
                    inode[index].dirname[0] = '\0';
                    inode[index].filename[0] = '\0';
                    memset(&inode[index], 0, sizeof(npheap_store));
                    log_msg("Directory deleted\n");
                    return 0;
            }
        }
    }
    return -1;
}
/*
    Searches for plugin, that implements the indicator of type \a indicatorType.
    Creates and stores the indicator.
    Does nothing, if indicator is already added.
    Returns true on success and false on failure.
*/
HbIndicatorInterface *HbIndicatorPluginManager::addIndicator(const QString &indicatorType,
    const QVariantMap &securityCredentials, int *errorCode)
{
    TRACE_ENTRY
    int error = HbDeviceDialogNoError;
    if (!errorCode) {
        errorCode = &error;
    }
    HbIndicatorInterface *indicator = 0;
    bool loaded = false;
    bool added = false;
    *errorCode = HbDeviceDialogNoError;

    //search indicator 1. among already loaded plugins.
    int index = findPlugin(indicatorType);
    if (index < 0) {
        //2. search and load the correct plugin.
        index = loadPlugin(indicatorType);
        loaded = true;
    }
    // Allow plugin to do access control
    if (index >= 0) {
        if (!checkAccess(index, indicatorType, securityCredentials)) {
            if (loaded) {
                mPlugins.removeAt(index);
            }
            *errorCode = HbDeviceDialogAccessDeniedError;
            index = -1;
        }
    }
    if (index >= 0) {
        PluginInfo &pluginInfo = mPlugins[index];
        if (!loaded) {
            //check is the indicator is already created.
            foreach(const IndicatorInfo &indicatorInfo,
                     pluginInfo.mAddedIndicators) {
                if (indicatorInfo.indicator->indicatorType() ==
                        indicatorType) {
                    indicator = indicatorInfo.indicator;
                    added = true;
                    break;
                }
            }
        }
Exemple #21
0
Expression *EnumMember::getVarExp(Loc loc, Scope *sc)
{
    semantic(sc);
    if (errors)
        return new ErrorExp();
    if (!vd)
    {
        assert(value);
        vd = new VarDeclaration(loc, type, ident, new ExpInitializer(loc, value->copy()));

        vd->storage_class = STCmanifest;
        vd->semantic(sc);

        vd->protection = ed->isAnonymous() ? ed->protection : Prot(PROTpublic);
        vd->parent = ed->isAnonymous() ? ed->parent : ed;
        vd->userAttribDecl = ed->isAnonymous() ? ed->userAttribDecl : NULL;
    }
    checkAccess(loc, sc, NULL, vd);
    Expression *e = new VarExp(loc, vd);
    return e->semantic(sc);
}
int HttpListener::addConnection( struct conn_data * pCur, int *iCount )
{
    int fd = pCur->fd;
    if ( checkAccess( pCur ))
    {
        no_timewait( fd );
        close( fd );
        --(*iCount);
        return 0;
    }
    HttpConnection* pConn = HttpConnPool::getConnection();
    if ( !pConn )
    {
        ERR_NO_MEM( "HttpConnPool::getConnection()" );
        close( fd );
        --(*iCount);
        return -1;
    }
    VHostMap * pMap;
    if ( m_pSubIpMap )
    {
        pMap = getSubMap( fd );
    }
    else
        pMap = getVHostMap();
    pConn->setVHostMap( pMap );
    pConn->setLogger( getLogger());
    pConn->setRemotePort( ntohs( ((sockaddr_in *)(pCur->achPeerAddr))->sin_port) );
    if ( pConn->setLink( pCur->fd, pCur->pInfo, pMap->getSSLContext() ) )
    {
        HttpConnPool::recycle( pConn );
        close( fd );
        --(*iCount);
        return -1;
    }
    fcntl( fd, F_SETFD, FD_CLOEXEC );
    fcntl( fd, F_SETFL, HttpGlobals::getMultiplexer()->getFLTag() );
    //pConn->tryRead();
    return 0;
}
/** Remove a file */
int nphfuse_unlink(const char *path){
    //Individual file delete
    npheap_store *inode = NULL;
    log_msg("Into UNLINK for %s\n", path);

    //Root directory cannot be deleted.
    if(strcmp(path,"/")==0){
        return -EACCES;
    }

    inode = retrieve_inode(path);

    if(inode==NULL){
        return -ENOENT;
    }

    //Check for permission
    int flag = checkAccess(inode);
    if(flag==0){
        log_msg("Cannot access the directory\n");
        return - EACCES;
    }

    //Check for dirname and filename
    if(npheap_getsize(npheap_fd, inode->offset) != 0){
        log_msg("Data offset exist. for %d data off\n", inode->offset);
        npheap_delete(npheap_fd, inode->offset);
    }

    inode->dirname[0] = '\0';
    inode->filename[0] = '\0';
    blk_array[inode->offset] == NULL;
    memset(inode, 0, sizeof(npheap_store));
    log_msg("Exiting UNLINK.\n");
    return 0;
}
void KConfigINIBackEnd::sync(bool bMerge)
{
    // write-sync is only necessary if there are dirty entries
    if(!pConfig->isDirty())
        return;

    bool bEntriesLeft = true;

    // find out the file to write to (most specific writable file)
    // try local app-specific file first

    if(!mfileName.isEmpty())
    {
        // Create the containing dir if needed
        if((resType != "config") && !QDir::isRelativePath(mLocalFileName))
        {
            KURL path;
            path.setPath(mLocalFileName);
            QString dir = path.directory();
            KStandardDirs::makeDir(dir);
        }

        // Can we allow the write? We can, if the program
        // doesn't run SUID. But if it runs SUID, we must
        // check if the user would be allowed to write if
        // it wasn't SUID.
        if(checkAccess(mLocalFileName, W_OK))
        {
            // File is writable
            KLockFile::Ptr lf;

            bool mergeLocalFile = bMerge;
            // Check if the file has been updated since.
            if(mergeLocalFile)
            {
                lf = lockFile(false); // Lock file for local file
                if(lf && lf->isLocked())
                    lf = 0; // Already locked, we don't need to lock/unlock again

                if(lf)
                {
                    lf->lock(KLockFile::LockForce);
                    // But what if the locking failed? Ignore it for now...
                }

                QFileInfo info(mLocalFileName);
                if((d->localLastSize == info.size()) && (d->localLastModified == info.lastModified()))
                {
                    // Not changed, don't merge.
                    mergeLocalFile = false;
                }
                else
                {
                    // Changed...
                    d->localLastModified = QDateTime();
                    d->localLastSize = 0;
                }
            }

            bEntriesLeft = writeConfigFile(mLocalFileName, false, mergeLocalFile);

            // Only if we didn't have to merge anything can we use our in-memory state
            // the next time around. Otherwise the config-file may contain entries
            // that are different from our in-memory state which means we will have to
            // do a merge from then on.
            // We do not automatically update the in-memory state with the on-disk
            // state when writing the config to disk. We only do so when
            // KCOnfig::reparseConfiguration() is called.
            // For KDE 4.0 we may wish to reconsider that.
            if(!mergeLocalFile)
            {
                QFileInfo info(mLocalFileName);
                d->localLastModified = info.lastModified();
                d->localLastSize = info.size();
            }
            if(lf)
                lf->unlock();
        }
    }

    // only write out entries to the kdeglobals file if there are any
    // entries marked global (indicated by bEntriesLeft) and
    // the useKDEGlobals flag is set.
    if(bEntriesLeft && useKDEGlobals)
    {

        // can we allow the write? (see above)
        if(checkAccess(mGlobalFileName, W_OK))
        {
            KLockFile::Ptr lf = lockFile(true); // Lock file for global file
            if(lf && lf->isLocked())
                lf = 0; // Already locked, we don't need to lock/unlock again

            if(lf)
            {
                lf->lock(KLockFile::LockForce);
                // But what if the locking failed? Ignore it for now...
            }
            writeConfigFile(mGlobalFileName, true, bMerge); // Always merge
            if(lf)
                lf->unlock();
        }
    }
}
void FileTransferRequestHandler::uploadEndRequested()
{
  UINT16 fileFlags;
  UINT64 modificationTime;

  {
    fileFlags = m_input->readUInt16();
    modificationTime = m_input->readUInt64();
  } // end of reading block.

  m_log->message(_T("%s"), _T("end of upload requested\n"));

  checkAccess();

  //
  // No active uploads at the moment.
  // Client is "bad" if send to us this message
  //

  if (m_uploadFile == NULL) {
    throw FileTransferException(_T("No active upload at the moment"));
  }

  //
  // Close file output stream
  //

  try {
    m_fileOutputStream->close();
  } catch (...) { }

  //
  // Trying to set modification time
  //

  if (!m_uploadFile->setLastModified(modificationTime)) {
    throw FileTransferException(_T("Cannot change last write file time"));
  } // if cannot set modification time

  //
  // Send reply
  //

  {
    AutoLock l(m_output);

    m_output->writeUInt32(FTMessage::UPLOAD_END_REPLY);

    m_output->flush();
  }

  //
  // Cleanup
  //

  if (m_fileOutputStream != NULL) {
    delete m_fileOutputStream;
    m_fileOutputStream = NULL;
  }

  if (m_uploadFile != NULL) {
    delete m_uploadFile;
    m_uploadFile = NULL;
  }

} // void
int HttpListener::batchAddConn( struct conn_data * pBegin,
                            struct conn_data *pEnd, int *iCount )
{
    struct conn_data * pCur = pBegin;
    int n = pEnd - pBegin;
    while( pCur < pEnd )
    {
        if ( checkAccess( pCur))
        {
            no_timewait( pCur->fd );
            close( pCur->fd );
            pCur->fd = -1;
            --(*iCount);
            --n;
        }
        ++pCur;
    }
    if ( n <= 0 )
        return 0;
    HttpConnection* pConns[CONN_BATCH_SIZE];
    int ret = HttpConnPool::getConnections( pConns, n);
    pCur = pBegin;
    if ( ret <= 0 )
    {
        ERR_NO_MEM( "HttpConnPool::getConnections()" );
        LOG_ERR(( "need %d connections, allocated %d connections!", n, ret ));
        while( pCur < pEnd )
        {
            if ( pCur->fd != -1 )
            {
                close( pCur->fd );
                --(*iCount);
            }
            ++pCur;
        }
        return -1;
    }
    HttpConnection** pConnEnd = &pConns[ret];
    HttpConnection** pConnCur = pConns;
    VHostMap * pMap;
    int flag = HttpGlobals::getMultiplexer()->getFLTag();
    while( pCur < pEnd )
    {
        register int fd = pCur->fd;
        if ( fd != -1 )
        {
            assert( pConnCur < pConnEnd );
            HttpConnection * pConn = *pConnCur;

            if ( m_pSubIpMap )
            {
                pMap = getSubMap( fd );
            }
            else
                pMap = getVHostMap();

            pConn->setVHostMap( pMap );
            pConn->setLogger( getLogger());
            pConn->setRemotePort( ntohs( ((sockaddr_in *)(pCur->achPeerAddr))->sin_port) );

        //    if ( getDedicated() )
        //    {
        //        //pConn->accessGranted();
        //    }
            if ( !pConn->setLink( fd, pCur->pInfo, pMap->getSSLContext() ) )
            {
                fcntl( fd, F_SETFD, FD_CLOEXEC );
                fcntl( fd, F_SETFL, flag );
                ++pConnCur;
                //pConn->tryRead();
            }
            else
            {
                close( fd );
                --(*iCount);
            }
        }
        ++pCur;
    }
    if ( pConnCur < pConnEnd )
    {
        HttpConnPool::recycle( pConnCur, pConnEnd - pConnCur);
    }

    return 0;
}
// I don't fully understand the documentation above -- it doesn't
// match the documentation for the read() system call which says it
// can return with anything up to the amount of data requested. nor
// with the fusexmp code which returns the amount of data also
// returned by read.
int nphfuse_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi){
    log_msg("Into READ function.\n");
    //Variables needed
    npheap_store *inode = NULL;
    struct timeval currTime;
    char *blk_data = NULL;

    //Root is not the file, so throw error
    if(strcmp(path,"/")==0){
        return -ENOENT;
    }

    inode = retrieve_inode(path);
    if(inode==NULL){
        log_msg("Couldn't find file.\n");
        return -ENOENT;
    }

    //Check for the access
    int flag = checkAccess(inode);
    if(flag==0){
        log_msg("Cannot access in root.\n");
        return - EACCES;
    }

    blk_data = (char *)blk_array[inode->offset];
    if(blk_data==NULL){
        return -ENOENT;
    }

    size_t left_to_read = size;
    size_t offset_read = offset;
    size_t rem = 0;
    size_t curr_buff = 0;
    uint64_t curr_offset = 0;
    uint64_t pos_in_offset = 0;
    size_t curr_size = 0;

    curr_size = npheap_getsize(npheap_fd, inode->offset);
    if(curr_size == 0){
        return 0;
    }

    log_msg("Reading started.\n");

    while(left_to_read != 0){
        //log_msg("Reached here\n");
        pos_in_offset = offset_read/BLOCK_SIZE;
        curr_offset = inode->offset;

        while(pos_in_offset != 0){
            curr_offset = dt_link[curr_offset-FIXED_VALUE];
            pos_in_offset--;
        }

        blk_data = blk_array[curr_offset];  
        if(blk_data==NULL){
            return -ENOENT;
        }
        log_msg("Reached with %s block data\n", blk_data);
        if(npheap_getsize(npheap_fd, curr_offset) == 0){
           return -EINVAL;
        }

        curr_size = npheap_getsize(npheap_fd, curr_offset);
        rem = offset_read % BLOCK_SIZE;

        if(curr_size <= left_to_read + rem){
            log_msg("Reading still left.\n");
            memcpy(buf + curr_buff, blk_data + rem, curr_size - rem);
            offset_read = offset_read + curr_size - rem;
            curr_buff = curr_buff + curr_size - rem;
            left_to_read = left_to_read - curr_size + rem;
        }else{
            log_msg("Last read in the data block.\n");
            memcpy(buf + curr_buff, blk_data + rem, left_to_read);
            offset_read = offset_read + left_to_read;
            curr_buff = curr_buff + left_to_read;
            left_to_read = 0;
        }
    }

    gettimeofday(&currTime, NULL);
    inode->mystat.st_atime = currTime.tv_sec;

    return curr_buff;
}
void FileTransferRequestHandler::downloadDataRequested()
{
  //
  // Request input variables.
  //

  UINT8 requestedCompressionLevel;
  UINT32 dataSize;

  {
    requestedCompressionLevel = m_input->readUInt8();
    dataSize = m_input->readUInt32();
  } // end of reading block.

  m_log->info(_T("download %d bytes (comp flag = %d) requested"), dataSize, requestedCompressionLevel);

  checkAccess();

  //
  // Data download reply variables.
  //

  UINT8 compressionLevel = requestedCompressionLevel;
  UINT32 compressedSize;
  UINT32 uncompressedSize;

  //
  // Client cannot send this request cause there is no
  // active download at the moment
  //

  if (m_downloadFile == NULL) {
    throw FileTransferException(_T("No active download at the moment"));
  }

  std::vector<char> buffer(dataSize);

  DWORD read = 0;

  try {
    if (dataSize != 0) {
      size_t portion = m_fileInputStream->read(&buffer.front(), dataSize);
      read = (DWORD)portion;
      _ASSERT(read == portion);
    }
  } catch (EOFException) {

    //
    // End of file detected
    //

    try { m_fileInputStream->close(); } catch (...) { }

    UINT8 fileFlags = 0;

    {
      AutoLock l(m_output);

      m_output->writeUInt32(FTMessage::DOWNLOAD_END_REPLY);
      m_output->writeUInt8(fileFlags);
      m_output->writeUInt64(m_downloadFile->lastModified());

      m_output->flush();
    } // rfb io handle block

    m_log->message(_T("%s"), _T("downloading has finished\n"));

    delete m_fileInputStream;
    delete m_downloadFile;

    m_fileInputStream = NULL;
    m_downloadFile = NULL;

    return ;

  } catch (IOException &ioEx) {
    throw FileTransferException(&ioEx);
  } // try / catch

  compressedSize = read;
  uncompressedSize = read;

  if (compressionLevel != 0) {
    if (dataSize != 0) {
      m_deflater.setInput(&buffer.front(), uncompressedSize);
      m_deflater.deflate();
      _ASSERT((UINT32)m_deflater.getOutputSize() == m_deflater.getOutputSize());
      compressedSize = (UINT32)m_deflater.getOutputSize();
    }
  }

  //
  // Send download data reply
  //

  AutoLock l(m_output);

  m_output->writeUInt32(FTMessage::DOWNLOAD_DATA_REPLY);
  m_output->writeUInt8(compressionLevel);
  m_output->writeUInt32(compressedSize);
  m_output->writeUInt32(uncompressedSize);

  if (compressionLevel == 0) {
    if (dataSize != 0) {
      m_output->writeFully(&buffer.front(), uncompressedSize);
    }
  } else {
    m_output->writeFully((const char *)m_deflater.getOutput(), compressedSize);
  }

  m_output->flush();
}
void UpdateInstaller::run() throw ()
{
	if (!m_script || !m_script->isValid())
	{
		reportError("Unable to read update script");
		return;
	}
	if (m_installDir.empty())
	{
		reportError("No installation directory specified");
		return;
	}

	std::string updaterPath;
	try
	{
		updaterPath = ProcessUtils::currentProcessPath();
	}
	catch (const FileUtils::IOException&)
	{
		LOG(Error,"error reading process path with mode " + intToStr(m_mode));
		reportError("Unable to determine path of updater");
		return;
	}

	if (m_mode == Setup)
	{
		if (m_waitPid != 0)
		{
			LOG(Info,"Waiting for main app process to finish");
			ProcessUtils::waitForProcess(m_waitPid);
		}

		std::list<std::string> args = updaterArgs();
		args.push_back("--mode");
		args.push_back("main");
		args.push_back("--wait");
		args.push_back(intToStr(ProcessUtils::currentProcessId()));

		int installStatus = 0;
		if (m_forceElevated || !checkAccess())
		{
			LOG(Info,"Insufficient rights to install app to " + m_installDir + " requesting elevation");

			// start a copy of the updater with admin rights
			installStatus = ProcessUtils::runElevated(updaterPath,args,AppInfo::name());
		}
		else
		{
			LOG(Info,"Sufficient rights to install app - restarting with same permissions");
			installStatus = ProcessUtils::runSync(updaterPath,args);
		}

		if (installStatus == 0)
		{
			LOG(Info,"Update install completed");
		}
		else
		{
			LOG(Error,"Update install failed with status " + intToStr(installStatus));
		}

		// restart the main application - this is currently done
		// regardless of whether the installation succeeds or not
		restartMainApp();

		// clean up files created by the updater
		cleanup();
	}
	else if (m_mode == Main)
	{
		LOG(Info,"Starting update installation");

		// the detailed error string returned by the OS
		std::string error;
		// the message to present to the user.  This may be the same
		// as 'error' or may be different if a more helpful suggestion
		// can be made for a particular problem
		std::string friendlyError;

		try
		{
			LOG(Info,"Installing new and updated files");
			installFiles();

			LOG(Info,"Uninstalling removed files");
			uninstallFiles();

			LOG(Info,"Removing backups");
			removeBackups();

			postInstallUpdate();
		}
		catch (const FileUtils::IOException& exception)
		{
			error = exception.what();
			friendlyError = friendlyErrorForError(exception);
		}
		catch (const std::string& genericError)
		{
			error = genericError;
		}

		if (!error.empty())
		{
			LOG(Error,std::string("Error installing update ") + error);

			try
			{
				revert();
			}
			catch (const FileUtils::IOException& exception)
			{
				LOG(Error,"Error reverting partial update " + std::string(exception.what()));
			}

			if (m_observer)
			{
				if (friendlyError.empty())
				{
					friendlyError = error;
				}
				m_observer->updateError(friendlyError);
			}
		}

		if (m_observer)
		{
			m_observer->updateFinished();
		}
	}
}
bool KConfigINIBackEnd::parseConfigFiles()
{
    // Check if we can write to the local file.
    mConfigState = KConfigBase::ReadOnly;
    if(!mLocalFileName.isEmpty() && !pConfig->isReadOnly())
    {
        if(checkAccess(mLocalFileName, W_OK))
        {
            mConfigState = KConfigBase::ReadWrite;
        }
        else
        {
            // Create the containing dir, maybe it wasn't there
            KURL path;
            path.setPath(mLocalFileName);
            QString dir = path.directory();
            KStandardDirs::makeDir(dir);

            if(checkAccess(mLocalFileName, W_OK))
            {
                mConfigState = KConfigBase::ReadWrite;
            }
        }
        QFileInfo info(mLocalFileName);
        d->localLastModified = info.lastModified();
        d->localLastSize = info.size();
    }

    // Parse all desired files from the least to the most specific.
    bFileImmutable = false;

    // Parse the general config files
    if(useKDEGlobals)
    {
        QStringList kdercs = KGlobal::dirs()->findAllResources("config", QString::fromLatin1("kdeglobals"));

        QString etc_kderc = QString::fromLatin1("/etc/kderc");

        if(checkAccess(etc_kderc, R_OK))
            kdercs += etc_kderc;

        kdercs += KGlobal::dirs()->findAllResources("config", QString::fromLatin1("system.kdeglobals"));

        QStringList::ConstIterator it;

        for(it = kdercs.fromLast(); it != kdercs.end(); --it)
        {

            QFile aConfigFile(*it);
            if(!aConfigFile.open(IO_ReadOnly))
                continue;
            parseSingleConfigFile(aConfigFile, 0L, true, (*it != mGlobalFileName));
            aConfigFile.close();
            if(bFileImmutable)
                break;
        }
    }

    bool bReadFile = !mfileName.isEmpty();
    while(bReadFile)
    {
        bReadFile = false;
        QString bootLanguage;
        if(useKDEGlobals && localeString.isEmpty() && !KGlobal::_locale)
        {
            // Boot strap language
            bootLanguage = KLocale::_initLanguage(pConfig);
            setLocaleString(bootLanguage.utf8());
        }

        bFileImmutable = false;
        QStringList list;
        if(!QDir::isRelativePath(mfileName))
            list << mfileName;
        else
            list = KGlobal::dirs()->findAllResources(resType, mfileName);

        QStringList::ConstIterator it;

        for(it = list.fromLast(); it != list.end(); --it)
        {

            QFile aConfigFile(*it);
            // we can already be sure that this file exists
            bool bIsLocal = (*it == mLocalFileName);
            if(aConfigFile.open(IO_ReadOnly))
            {
                parseSingleConfigFile(aConfigFile, 0L, false, !bIsLocal);
                aConfigFile.close();
                if(bFileImmutable)
                    break;
            }
        }
        if(KGlobal::dirs()->isRestrictedResource(resType, mfileName))
            bFileImmutable = true;
        QString currentLanguage;
        if(!bootLanguage.isEmpty())
        {
            currentLanguage = KLocale::_initLanguage(pConfig);
            // If the file changed the language, we need to read the file again
            // with the new language setting.
            if(bootLanguage != currentLanguage)
            {
                bReadFile = true;
                setLocaleString(currentLanguage.utf8());
            }
        }
    }
    if(bFileImmutable)
        mConfigState = KConfigBase::ReadOnly;

    return true;
}