예제 #1
0
파일: mount.cpp 프로젝트: presto53/porto
TError TMount::Move(TPath destination) {
    int ret = mount(Target.ToString().c_str(), destination.ToString().c_str(), NULL, MS_MOVE, NULL);
    if (ret)
        return TError(EError::Unknown, errno, "mount(" + Target.ToString() + ", " + destination.ToString() + ", MS_MOVE)");
    Target = destination;
    return TError::Success();
}
// ---------------------------------------------------------------------------
// CAknMemorySelectionDialogMultiDrive::AddDrivePathsL
// ---------------------------------------------------------------------------
//
EXPORT_C TInt CAknMemorySelectionDialogMultiDrive::AddDrivePathsL(
    const TDesC& aRootPath,
    const TDesC& aDefaultFolder
    )
    {
    // TODO: Verify paramters if they are valid.
    TInt rootPathCount=iRootPathArray.Count();
    TInt result = KErrNone;
    TPath path;
    for ( TInt i=0;i<rootPathCount;i++ )
        {
        path.Copy( iRootPathArray[i] );
        path.Append( aRootPath );
        AknCFDUtility::AddTrailingBackslash( path );
        iRootPathArray.Delete(i);
        iRootPathArray.Compress();
        iRootPathArray.InsertL( i, path );
        path.Copy( aDefaultFolder );
        AknCFDUtility::AddTrailingBackslash( path );
        iDefaultFolderArray.Delete(i);
        iDefaultFolderArray.Compress();
        iDefaultFolderArray.InsertL( i, path );
        }
    return result;
    }
예제 #3
0
파일: path.cpp 프로젝트: noxiouz/porto
bool TPath::HasAccess(const TCred &cred, enum Access mask) const {
    struct stat st;
    int mode;

    if (!cred.Uid && !access(c_str(), mask & TPath::RWX))
        return true;

    if (stat(c_str(), &st)) {
        if (!(mask & TPath::P) || errno != ENOENT)
            return false;
        TPath dir = DirName();
        while (stat(dir.c_str(), &st)) {
            if (errno != ENOENT)
                return false;
            if (dir.Path.size() <= 1)
                return false;
            dir = dir.DirName();
        }
    }

    if ((mask & TPath::U) && cred.Uid == st.st_uid)
        return true;

    if (cred.Uid == st.st_uid)
        mode = st.st_mode >> 6;
    else if (cred.IsMemberOf(st.st_gid))
예제 #4
0
TError TNamespaceFd::Open(TPath path) {
    Close();
    Fd = open(path.c_str(), O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
    if (Fd < 0)
        return TError(EError::Unknown, errno, "Cannot open " + path.ToString());
    return TError::Success();
}
예제 #5
0
void T_CntImageRescaler::testRescaleImageSuccefully()
    {
    test.Next(_L("Rescale image"));

    TPath dest;
    dest.Append(KDestDir());
    dest.Append(_L("test.jpg"));

    TTime time;
    time.UniversalTime();

    TRAPD(err, iRescaler->ResizeImageL(KSrcImage(), dest));

    TTime time2;
    time2.UniversalTime();

    TInt seconds = time2.MicroSecondsFrom( time ).Int64() / 1000000;

    test.Printf(_L("rescaled in %d seconds\n"), seconds);

    test(err == KErrNone);
    test(BaflUtils::FileExists(iFs, dest));

    TEntry file;
    if (iFs.Entry(dest, file) == KErrNone)
        {
        test(file.iSize <= KMaxImageSize);
        }
    }
예제 #6
0
	TString GetNewNameForFileDigit(const TPath &oldPath, const TString &nameWithoutDigit, __int64 & counter, size_t & leadingZeros, const TPath &pathForRename)
    {
		TString pathWithDigit;
		const int BUFFER_SIZE = 65;
		char buffer[BUFFER_SIZE];
		TString leadingZeroString;

		counter++;
		if (leadingZeros > 0)
		{
			if (LengthOfLong(counter) > LengthOfLong(counter - 1)) //если цифра удленилась
               leadingZeros--;
			for (size_t i = 0; i < leadingZeros; i++)
				leadingZeroString.push_back('0');
		}

		if (_i64toa_s(counter, buffer, BUFFER_SIZE, 10) == 0)
		{
			pathWithDigit = CreatePath(oldPath.GetDirectory(), nameWithoutDigit + leadingZeroString + TString(buffer) + oldPath.GetExtension());
			if(TPath::EqualByNameWithExtension(pathWithDigit, pathForRename))
				return pathForRename.Original();
			if (IsFileExists(pathWithDigit.c_str())) //если такой файл уже есть, то не увеличиваем номер, а добавляем _2
				return GetNewNameForFileAdd(oldPath);
		}
		else
			return GetNewNameForFileAdd(oldPath);
		return pathWithDigit;
    }
예제 #7
0
파일: test.cpp 프로젝트: noxiouz/porto
std::string ReadLink(const std::string &path) {
    TPath lnk;

    TPath f(path);
    TError error = f.ReadLink(lnk);
    if (error)
        throw error.GetMsg();

    return lnk.ToString();
}
예제 #8
0
파일: task.cpp 프로젝트: presto53/porto
TError TTask::CreateTmpDir(const TPath &path, std::shared_ptr<TFolder> &dir) const {
    bool cleanup = path.ToString().find(config().container().tmp_dir()) == 0;

    dir = std::make_shared<TFolder>(path, cleanup);
    if (!dir->Exists()) {
        TError error = dir->Create(0755, true);
        if (error)
            return error;
        error = path.Chown(Env->Cred.Uid, Env->Cred.Gid);
        if (error)
            return error;
    }

    return TError::Success();
}
예제 #9
0
	// Перименовываем, добавляя _2 к имени файла.
	TString GetNewNameForFileAdd(const TPath &oldPath)
    {
		TString uniquePath;
		const int SIMILAR_PREFIX_SIZE = 16;
		const TChar *SIMILAR_PREFIX_FORMAT = TEXT("_%u");
		TChar buffer[SIMILAR_PREFIX_SIZE];
		unsigned long counter = 2;

		do 
		{
			_stprintf_s(buffer, SIMILAR_PREFIX_FORMAT, counter++);
			uniquePath = CreatePath(oldPath.GetDirectory(), oldPath.GetName(false) + TString(buffer) + oldPath.GetExtension());
		} 
		while (IsFileExists(uniquePath.c_str()));

        return uniquePath;
    }
예제 #10
0
파일: task.cpp 프로젝트: presto53/porto
TError TTask::ChildMountDev() {
    struct {
        const std::string path;
        unsigned int mode;
        unsigned int dev;
    } node[] = {
        { "/dev/null",    0666 | S_IFCHR, MKDEV(1, 3) },
        { "/dev/zero",    0666 | S_IFCHR, MKDEV(1, 5) },
        { "/dev/full",    0666 | S_IFCHR, MKDEV(1, 7) },
        { "/dev/random",  0666 | S_IFCHR, MKDEV(1, 8) },
        { "/dev/urandom", 0666 | S_IFCHR, MKDEV(1, 9) },
    };

    TMount dev("tmpfs", Env->Root + "/dev", "tmpfs", { "mode=755", "size=32m" });
    TError error = dev.MountDir(MS_NOSUID | MS_STRICTATIME);
    if (error)
        return error;

    TMount devpts("devpts", Env->Root + "/dev/pts", "devpts",
                  { "newinstance", "ptmxmode=0666", "mode=620" ,"gid=5" });
    error = devpts.MountDir(MS_NOSUID | MS_NOEXEC);
    if (error)
        return error;

    for (size_t i = 0; i < sizeof(node) / sizeof(node[0]); i++) {
        error = ChildCreateNode(Env->Root + node[i].path,
                           node[i].mode, node[i].dev);
        if (error)
            return error;
    }

    TPath ptmx = Env->Root + "/dev/ptmx";
    if (symlink("pts/ptmx", ptmx.ToString().c_str()) < 0)
        return TError(EError::Unknown, errno, "symlink(/dev/pts/ptmx)");

    TPath fd = Env->Root + "/dev/fd";
    if (symlink("/proc/self/fd", fd.ToString().c_str()) < 0)
        return TError(EError::Unknown, errno, "symlink(/dev/fd)");

    TFile f(Env->Root + "/dev/console", 0755);
    (void)f.Touch();

    return TError::Success();
}
예제 #11
0
파일: mount.cpp 프로젝트: presto53/porto
TError TMount::Snapshot(std::vector<std::shared_ptr<TMount>> &result, const TPath mounts) {
    FILE* f = setmntent(mounts.c_str(), "r");
    if (!f)
        return TError(EError::Unknown, errno, "setmntent(" + mounts.ToString() + ")");

    struct mntent* m, mntbuf;
    TScopedMem buf(4096);
    while ((m = getmntent_r(f, &mntbuf, (char *)buf.GetData(), buf.GetSize()))) {
        vector<string> flags;
        TError error = SplitString(m->mnt_opts, ',', flags);
        if (error) {
            endmntent(f);
            return error;
        }
        result.push_back(std::make_shared<TMount>(m->mnt_fsname, m->mnt_dir, m->mnt_type, flags));
    }
    endmntent(f);
    return TError::Success();
}
// ---------------------------------------------------------------------------
// CAknMemorySelectionModelMultiDrive::ReadUserDefinedDataL
// ---------------------------------------------------------------------------
//
void CAknMemorySelectionModelMultiDrive::ReadUserDefinedDataL(
    TResourceReader& aReader, TInt aLocations )
    {
    if ( aLocations <= 0)
        {
        return;
        }
    
    iDefDriveArray = new ( ELeave ) CDesCArrayFlat( aLocations );
    iDefDefaultFolderArray = new ( ELeave ) CDesCArrayFlat( aLocations );
    for ( TInt i = 0; i < aLocations; i++ )
        {
        // read the location, save path and default folder in array
        TPath temp;
        temp.Copy( aReader.ReadTPtrC() );
        iDefDriveArray->AppendL( temp );
        temp.Copy( aReader.ReadTPtrC() );
        iDefDefaultFolderArray->AppendL( temp );
        }
    }
예제 #13
0
파일: task.cpp 프로젝트: presto53/porto
TError TTask::ChildOpenStdFile(const TPath &path, int expected) {
    int ret = open(path.ToString().c_str(), O_CREAT | O_WRONLY | O_APPEND, 0660);
    if (ret < 0)
        return TError(EError::InvalidValue, errno,
                      "open(" + path.ToString() + ") -> " +
                      std::to_string(expected));

    if (ret != expected)
        return TError(EError::Unknown, EINVAL,
                      "open(" + path.ToString() + ") -> " +
                      std::to_string(expected) + ": unexpected fd " +
                      std::to_string(ret));

    ret = fchown(ret, Env->Cred.Uid, Env->Cred.Gid);
    if (ret < 0)
        return TError(EError::Unknown, errno,
                      "fchown(" + path.ToString() + ") -> " +
                      std::to_string(expected));

    return TError::Success();
}
예제 #14
0
파일: mount.cpp 프로젝트: presto53/porto
TError TMount::Find(TPath path, const TPath mounts) {

    path = path.NormalPath();
    auto device = path.GetDev();
    if (!device)
        return TError(EError::Unknown, "device not found: " + path.ToString() + ")");

    FILE* f = setmntent(mounts.c_str(), "r");
    if (!f)
        return TError(EError::Unknown, errno, "setmntent(" + mounts.ToString() + ")");

    struct mntent* m, mntbuf;
    TScopedMem buf(4096);
    TError error(EError::Unknown, "mountpoint not found: " + path.ToString() + ")");

    while ((m = getmntent_r(f, &mntbuf, (char *)buf.GetData(), buf.GetSize()))) {

        TPath source(m->mnt_fsname);
        TPath target(m->mnt_dir);

        if (target.InnerPath(path).IsEmpty() ||
                source.GetBlockDev() != device)
            continue;

        Source = source;
        Target = target;
        Type = m->mnt_type;
        Data.clear();
        error = SplitString(m->mnt_opts, ',', Data);
        break;
    }
    endmntent(f);

    return error;
}
예제 #15
0
파일: task.cpp 프로젝트: presto53/porto
TError TTask::ChildBindDirectores() {
    for (auto &bindMap : Env->BindMap) {
        TPath dest;

        if (bindMap.Dest.IsAbsolute())
            dest = Env->Root / bindMap.Dest;
        else
            dest = Env->Root / Env->Cwd / bindMap.Dest;

        if (!StringStartsWith(dest.RealPath().ToString(), Env->Root.ToString()))
            return TError(EError::InvalidValue, "Container bind mount "
                          + bindMap.Source.ToString() + " resolves to root "
                          + dest.RealPath().ToString()
                          + " (" + Env->Root.ToString() + ")");

        TMount mnt(bindMap.Source, dest, "none", {});

        TError error;
        if (bindMap.Source.GetType() == EFileType::Directory)
            error = mnt.BindDir(bindMap.Rdonly);
        else
            error = mnt.BindFile(bindMap.Rdonly);
        if (error)
            return error;

        // drop nosuid,noexec,nodev from volumes
        if (Env->NewMountNs) {
            error = TMount::Remount(dest, MS_REMOUNT | MS_BIND |
                                    (bindMap.Rdonly ? MS_RDONLY : 0));
            if (error)
                return error;
        }
    }

    return TError::Success();
}
예제 #16
0
파일: test.cpp 프로젝트: noxiouz/porto
void BootstrapCommand(const std::string &cmd, const TPath &path, bool remove) {
    if (remove)
        (void)path.RemoveAll();

    vector<string> lines;
    ExpectSuccess(Popen("ldd " + cmd, lines));

    for (auto &line : lines) {
        vector<string> tokens;
        TError error = SplitString(line, ' ', tokens);
        if (error)
            throw error.GetMsg();

        TPath from;
        string name;
        if (tokens.size() == 2) {
            from = StringTrim(tokens[0]);
            TPath p(tokens[0]);
            name = p.BaseName();
        } else if (tokens.size() == 4) {
            if (tokens[2] == "")
                continue;

            from = StringTrim(tokens[2]);
            name = StringTrim(tokens[0]);
        } else {
            continue;
        }

        TPath dest = path / from.DirName();
        if (!dest.Exists()) {
            error = dest.MkdirAll(0755);
            if (error)
                throw error.GetMsg();
        }

        Expect(system(("cp " + from.ToString() + " " + dest.ToString() + "/" + name).c_str()) == 0);
    }
    Expect(system(("cp " + cmd + " " + path.ToString()).c_str()) == 0);
}
예제 #17
0
/**
Copy or resize if need be a source image to the internal folder

@return A file path of the new destination of the rescaled image

@param aSourceFile Source image path to be resized
@param aItem Contact item to help naming the new image
*/
TPath CImageRescaler::ResizeAndCopyImage(const TDesC& aSourceFile, const CContactItem& aItem)
    {
    TPtrC guid = const_cast<CContactItem&>(aItem).Guid();
    
    // Remove the old file. An empty guid means that this contact is new and
    // does not have any image associated with it in the images dir
    if (guid.Length())
        {
        TPath oldFile;
        oldFile.Append(iImagesDirPath);
        oldFile.Append(guid);
        oldFile.Append(_L("*"));
        
        // Remove previous file(s)
        BaflUtils::DeleteFile(iFs, oldFile); // Error value not necessary
        }
    
    TPath destFile = GenerateDestPath(aSourceFile);
    
    // Check the size of the image
    if (IsImageTooLarge(aSourceFile))
        {
        // Resize image
        TRAPD(err, ResizeImageL(aSourceFile, destFile));
        if (err != KErrNone && err != KErrArgument)
            {
            // Copy original image to the images directory to ensure
            // the contact keeps a copy of the image
            if (BaflUtils::CopyFile(iFs, aSourceFile, destFile) != KErrNone)
                {
                destFile.Zero();
                }
            }
        }
    else
        {
        // Copy image to the images directory if the image is not to big
        if (BaflUtils::CopyFile(iFs, aSourceFile, destFile) != KErrNone)
            {
            destFile.Zero();
            }
        }
    
    return destFile;
    }
예제 #18
0
	// Ищет цифры в имени файла с конца.
	__int64 GetDigitInFileName(const TPath &path, TString & nameWithoutDigit, size_t & leadingZeros)
	{
		TString name = path.GetName(false);
		size_t length = name.length();
        //Находим первый не числовой символ с конца
        bool canRename;
        size_t digitPos = length;

		for (ptrdiff_t i = length - 1; i >= 0; digitPos = i, i-- )
        {
            if (!iswdigit(name[i])) //если не цифра выходим
                break;
        }

        if (digitPos <= length - 1) //если цифра найдена
            canRename = true;
        else
            canRename = false;

		__int64 result = -1;
        int numOfZero = 0;
        if (canRename)
        {
			TString forParsing = name.substr(digitPos, length - digitPos);
			result = _wtoi64(forParsing.c_str());
			if (result == _I64_MAX) //слишком длинный
			{
				digitPos = 0;
				result = -1;
			}
            leadingZeros = forParsing.length() - LengthOfLong(result);
        }

		if (digitPos > 0 && digitPos < length)
            nameWithoutDigit = name.substr(0, digitPos);
        else
            nameWithoutDigit = TString();
        return result;
	}
예제 #19
0
파일: task.cpp 프로젝트: presto53/porto
TError TTask::ChildRemountRootRo() {
    if (!Env->RootRdOnly || !Env->Loop.IsEmpty())
        return TError::Success();

    // remount everything except binds to ro
    std::vector<std::shared_ptr<TMount>> snapshot;
    TError error = TMount::Snapshot(snapshot);
    if (error)
        return error;

    for (auto mnt : snapshot) {
        TPath path = Env->Root.InnerPath(mnt->GetMountpoint());
        if (path.IsEmpty())
            continue;

        bool skip = false;
        for (auto dir : roproc) {
            if (!path.InnerPath(dir).IsEmpty()) {
                skip = true;
                break;
            }
        }
        if (skip)
            continue;

        for (auto &bindMap : Env->BindMap) {
            TPath dest = bindMap.Dest;

            if (dest.NormalPath() == path.NormalPath()) {
                skip = true;
                break;
            }
        }

        if (skip)
            continue;

        L_ACT() << "Remount " << path << " ro" << std::endl;
        error =  TMount::Remount(mnt->GetMountpoint(),
                                 MS_REMOUNT | MS_BIND | MS_RDONLY);
        if (error)
            return error;
    }

    return TError::Success();
}
예제 #20
0
TPath CImageRescaler::GenerateDestPath(const TDesC& aSrcPath)
    {
    // Image file type
    TParse p;
    TInt err = p.Set(aSrcPath, NULL, NULL);
    TPath destFile;
    
    if (err == KErrNone)
        {
        // Generate the image path
        // Format <path>_timestamp_filename.ext
        destFile.Append(iImagesDirPath);
        destFile.Append(_L("_"));
        
        TTime time;
        time.UniversalTime();
        destFile.AppendNum(time.Int64());
        destFile.Append(_L("_"));
        destFile.Append(p.NameAndExt());
        }
    
    return destFile;
    }
예제 #21
0
파일: mount.cpp 프로젝트: presto53/porto
TError SetupLoopDevice(TPath image, int &dev)
{
    static std::mutex BigLoopLock;
    int control_fd, image_fd, loop_nr, loop_fd;
    struct loop_info64 info;
    std::string loop;
    int retry = 10;
    TError error;

    image_fd = open(image.c_str(), O_RDWR | O_CLOEXEC);
    if (image_fd < 0) {
        error = TError(EError::Unknown, errno, "open(" + image.ToString() + ")");
        goto err_image;
    }

    control_fd = open("/dev/loop-control", O_RDWR | O_CLOEXEC);
    if (control_fd < 0) {
        error = TError(EError::Unknown, errno, "open(/dev/loop-control)");
        goto err_control;
    }

    BigLoopLock.lock();

again:
    loop_nr = ioctl(control_fd, LOOP_CTL_GET_FREE);
    if (loop_nr < 0) {
        error = TError(EError::Unknown, errno, "ioctl(LOOP_CTL_GET_FREE)");
        goto err_get_free;
    }

    loop = "/dev/loop" + std::to_string(loop_nr);
    loop_fd = open(loop.c_str(), O_RDWR | O_CLOEXEC);
    if (loop_fd < 0) {
        error = TError(EError::Unknown, errno, "open(" + loop + ")");
        goto err_loop_open;
    }

    if (ioctl(loop_fd, LOOP_SET_FD, image_fd) < 0) {
        error = TError(EError::Unknown, errno, "ioctl(LOOP_SET_FD)");
        if (errno == EBUSY) {
            if (!ioctl(loop_fd, LOOP_GET_STATUS64, &info) || errno == ENXIO) {
                if (--retry > 0) {
                    close(loop_fd);
                    goto again;
                }
            }
        }
        goto err_set_fd;
    }

    memset(&info, 0, sizeof(info));
    strncpy((char *)info.lo_file_name, image.c_str(), LO_NAME_SIZE);

    if (ioctl(loop_fd, LOOP_SET_STATUS64, &info) < 0) {
        error = TError(EError::Unknown, errno, "ioctl(LOOP_SET_STATUS64)");
        ioctl(loop_fd, LOOP_CLR_FD, 0);
        goto err_set_status;
    }

    dev = loop_nr;
    error = TError::Success();
err_set_status:
err_set_fd:
    close(loop_fd);
err_loop_open:
err_get_free:
    BigLoopLock.unlock();
    close(control_fd);
err_control:
    close(image_fd);
err_image:
    return error;
}
// ---------------------------------------------------------------------------
// 2nd phase constructor
// ---------------------------------------------------------------------------
//
void CCatalogsHttpDownloadManager::ConstructL( TBool aCleanup )
{
    DLTRACEIN((""));
    User::LeaveIfError( iFs.Connect() );

    // shared so that RFiles can be given to Download manager
    User::LeaveIfError( iFs.ShareProtected() );

    QString DmgrUid(QString::number(KNCDEngineAppID));
    iDmgr =  new DownloadManager(DmgrUid);
    iDmgr->initialize();
    iQTmgr = new CCatalogsHttpQTDownloadManager(this,iDmgr);

    TUid sessionId( TUid::Uid( iSessionId ) );
    if ( aCleanup )
    {
        DLTRACE(("Cleaning download manager before connecting"));
        TUidName client( CleanUidName( sessionId ) );
        TPath path;
        path.Format( KCatalogsDownloadMgrPath, &client );

        CFileMan* fileman = CFileMan::NewL( iFs );
        CleanupStack::PushL( fileman );
        DLINFO(( _L("Clearing directory: %S"), &path ));
        // Ignoring errors
        fileman->Delete( path );
        CleanupStack::PopAndDestroy( fileman );
    }

    // Connect with the download manager
    // If the 3rd parameter == ETrue, this session inherits downloads
    // from other sessions that have the same UID.
    TInt err = KErrNone;
    TInt retries = KCatalogsDlMgrConnectRetryAttempts;

    do
    {
        if ( err != KErrNone )
        {
            DLERROR(("DL manager connection failed with err: %d, retry attempts left",
                     err, retries ));
            // This halts the whole thread which is not nice but shouldn't
            // be a problem since this should occur only when the download
            // manager is being shutdown when we try to connect to it
            User::After( KCatalogsDlMgrConnectRetryInterval );
        }
    }
    while ( err != KErrNone && retries-- );

    if( err != KErrNone )
    {
        DLINFO(("Leaving.. DL manager connection failed with: %d", err ));
        User::Leave( err );
    }

    DLTRACE(("ConnectL ok"));

    iDefaultConfig = CCatalogsHttpConfig::NewL();

    iNetworkManager = &CCatalogsHttpSessionManager::NetworkManagerL();
    iNetworkManager->AddObserverL( *this );

    // Restore downloads from previous sessions
//    RestoreDownloadsL();

    DLTRACEOUT((""));

}
// ---------------------------------------------------------------------------
// CAknMemorySelectionModelMultiDrive::UpdateDataArraysL
// ---------------------------------------------------------------------------
//
void CAknMemorySelectionModelMultiDrive::UpdateDataArraysL()
    {
    TDriveList driveList;
    TInt driveCount;
    User::LeaveIfError( DriveInfo::GetUserVisibleDrives(
        iCoeEnv->FsSession(), driveList, driveCount, KDriveAttAll ) );
    TPath rootPath;
    TDriveNumber driveNumber;
    AknCommonDialogsDynMem::TMemoryTypes memoryType;
    
    CDesCArrayFlat* driveArray = STATIC_CAST( CDesCArrayFlat*, iDriveArray );
    CDesCArrayFlat* defaultFolderArray =
        STATIC_CAST( CDesCArrayFlat*, iDefaultFolderArray );
    driveArray->Reset();
    defaultFolderArray->Reset();
    
    if ( iDefDriveArray != NULL && iDefDefaultFolderArray != NULL )
        {
        for ( TInt i = 0; i < KMaxDrives; i++ )
            {
            TInt driveExist = driveList[i];
            if ( driveExist )
                {
                driveNumber = TDriveNumber( i );
                rootPath.Zero();
                memoryType = AknCFDUtility::DriveMemoryTypeL( driveNumber );
                if( memoryType & iIncludedMedias )
                    {
                    User::LeaveIfError(
                    PathInfo::GetRootPath( rootPath, driveNumber ) );
                    }
                else
                    {
                    continue;
                    }
                
                TBool isUserDefined = EFalse;
                // add right location even user's location with wrong sequence
                for ( TInt j = 0; j < iDefDriveArray->MdcaCount(); j++ )
                    {
                    // same drive info and user's root path must under c:\data\.
                    // try to get the location
                    if ( ( *iDefDriveArray )[j].FindC( rootPath ) == 0 )
                        {
                        // Use user's root path, part of user definiens
                        // (lowercase) may be replaced by system rootPath
                        rootPath.Append( ( *iDefDriveArray )[j].Right( 
                            ( *iDefDriveArray )[j].Length() - rootPath.Length() ) );
                        driveArray->AppendL( rootPath );
                        defaultFolderArray->AppendL( ( *iDefDefaultFolderArray )[j] );
                        isUserDefined = ETrue;
                        break;
                        }
                    }
                if ( !isUserDefined )
                    {
                    // user does not define location for this drive
                    // use the default
                    driveArray->AppendL( rootPath );
                    defaultFolderArray->AppendL( KNullDesC );
                    }
                }
            }
        }
    else
        {
        for ( TInt i=0; i<KMaxDrives; i++ )
            {
            TInt drive = driveList[i];
            driveNumber = TDriveNumber( i );
            if (drive)
                {
                memoryType = AknCFDUtility::DriveMemoryTypeL( driveNumber );
                if( memoryType & iIncludedMedias )
                    {
                    User::LeaveIfError(
                        PathInfo::GetRootPath( rootPath, driveNumber ) );
                    driveArray->AppendL( rootPath );
                    defaultFolderArray->AppendL( KNullDesC );
                    }
                }
            }
        }
    }
예제 #24
0
파일: task.cpp 프로젝트: presto53/porto
TError TTask::ChildCreateNode(const TPath &path, unsigned int mode, unsigned int dev) {
    if (mknod(path.ToString().c_str(), mode, dev) < 0)
        return TError(EError::Unknown, errno, "mknod(" + path.ToString() + ")");

    return TError::Success();
}
void CHttpCacheManager::ApplyCacheOverridesL(CRepository& aRepository, const TUint32& aSecIdInt, TBool& aCacheEnabled, TInt& aCacheSize, TBool& aOpCacheEnabled, TBool& aVssCacheEnabled, TDes& aPath, const TDesC& aDefaultDrive)
    {
    TDriveUnit drive(aDefaultDrive);
    
    // set defaults
    if(aSecIdInt == KUIDBROWSERNG)       // for the browser, force use of Operator and VSS caches
        {
        aOpCacheEnabled = ETrue;
        aVssCacheEnabled = ETrue;
        }
    
    // read override string from centrep
    HBufC16 *overrideBuf = HBufC16::NewLC(64);
    TPtr overrideStr(overrideBuf->Des());
    TInt strLen;
    TInt err = aRepository.Get(KCacheManagerHttpCacheProcessOverride, overrideStr, strLen);
    if(strLen > overrideBuf->Length())
        {
        overrideBuf = overrideBuf->ReAllocL(strLen);
        // make sure cleanup stack contains correct pointer since ReAllocL always allocates a new des for larger space.
        CleanupStack::Pop();
        CleanupStack::PushL(overrideBuf);
        // reassign the TPtr
        overrideStr.Set(overrideBuf->Des());
        // pull in the whole string
        aRepository.Get(KCacheManagerHttpCacheProcessOverride, overrideStr, strLen);
        }
    // if we failed to load an override string, use the default.
    if( overrideStr.Length() == 0 )
        {
        CleanupStack::PopAndDestroy( overrideBuf );
        overrideBuf = KDefaultOverrideString().AllocLC();
        overrideStr.Set( overrideBuf->Des() );
        }
    // Built in Lex likes white space to separate strings, but easier to enter with ; separators.  Replace all ; with spaces.
    TInt pos=0;
    do{
        if(overrideStr[pos] == ';')
            {
            overrideStr[pos] = ' ';
            }
        pos++;
    }while(pos < overrideStr.Length());
    
    TLex overrideLex(overrideStr);
    do{
        TUint32 tempId;
        User::LeaveIfError(overrideLex.BoundedVal(tempId,EHex,KMaxTUint32));
        if(overrideLex.TokenLength() != 8)  // if we're not pointing at an SID in the string, we are incorrect and the override is broken.
            User::Leave(KErrCorrupt);
        overrideLex.SkipSpace();
        TInt32 tempCacheEnabled;
        User::LeaveIfError(overrideLex.BoundedVal(tempCacheEnabled,KMaxTInt32));
        overrideLex.SkipSpace();
        TInt32 tempCacheSize;
        User::LeaveIfError(overrideLex.BoundedVal(tempCacheSize,KMaxTInt32));
        overrideLex.SkipSpace();
        TDriveUnit tempDrive(overrideLex.NextToken());
        overrideLex.SkipSpaceAndMark();
        // found a hex SID matching ours, use the parameters.
        if(tempId == aSecIdInt)
            {
            aCacheEnabled = tempCacheEnabled;
            aCacheSize = tempCacheSize * 1024; // conf is in KB
            drive = tempDrive;
            break;
            }
    }while(!overrideLex.Eos());

    // Modify drive letter on aPath to match
    TParsePtr parsePath(aPath);
    TPtrC pathStr(parsePath.Path());
    TPath tempPath;
    tempPath.Format(_L("%c:%S"), TInt(drive)+'A', &pathStr);
    aPath.Copy(tempPath);
    HttpCacheUtil::EnsureTrailingSlash( aPath );
    
    CleanupStack::PopAndDestroy(overrideBuf);
    }
LOCAL_C void TestCreateContactWithoutImagesFoldeL()
{
    test.Next(_L("TestCreateContactWithoutImagesFoldeL"));

    SETUP;

    // Delete the images folder and all contents
    TInt drive;

#ifdef __WINS__
    TInt err = DriveInfo::GetDefaultDrive(DriveInfo::EDefaultPhoneMemory, drive);
#else
    TInt err = DriveInfo::GetDefaultDrive(DriveInfo::EDefaultMassStorage, drive);
#endif

    // Do not leave with this error. The phone does not have to have this support
    if (err == KErrNone)
    {
        // Get the root path in this drive to create
        // to create the images directory
        TPath dir;
        User::LeaveIfError(PathInfo::GetRootPath(dir, drive));
        dir.Append(KImagesFolder);

        CFileMan* fileMan = CFileMan::NewL(fs);
        err = fileMan->RmDir(dir); // err not used
        delete fileMan;
    }
    else
    {
        test.Printf(_L("Could not remove the images folder\n"));
        return;
    }

    // Create an image and store an image without the images dir available
    CContactItem *contact = CContactItem::NewLC(KUidContactCard);

    CContactItemField *newField = CContactItemField::NewLC(KStorageTypeText, KUidContactFieldCodImage);
    newField->SetMapping(KUidContactFieldVCardMapUnknown);
    newField->TextStorage()->SetTextL(KSrcImage());
    contact->AddFieldL(*newField); // Takes ownership
    CleanupStack::Pop(newField);

    TContactItemId id = cntClient.CreateContactL(*contact);
    CleanupStack::PopAndDestroy(contact);

    // View definition to read image field
    CContactItemViewDef *imageViewDef = CContactItemViewDef::NewLC(CContactItemViewDef::EIncludeFields, CContactItemViewDef::EMaskHiddenFields);
    imageViewDef->AddL(KUidContactFieldCodImage);

    contact = cntClient.ReadContactL(imageViewDef ,id);
    CleanupStack::PopAndDestroy(imageViewDef);  //  imageViewDef

    TInt index = contact->CardFields().Find(KUidContactFieldCodImage, KUidContactFieldVCardMapUnknown);

    // Test image field found
    test(index != KErrNotFound);

    CContactItemField& field = contact->CardFields()[index];
    TPtrC imagePtr = field.TextStorage()->Text();

    // Image path should not change
    test(imagePtr.Compare(KSrcImage()) == 0);

    cntClient.CloseContact(id);
    delete contact;

    TEAR_DOWN;
}
예제 #27
0
bool
CIMIContext::_backTracePaths(const std::vector<TLatticeState>& tail_states,
                             int rank, TPath& path, TPath& segmentPath)
{
    path.clear();
    segmentPath.clear();

    if (rank >= (int) tail_states.size()) {
        // rank out of bounds, only return the segment path
        return false;
    }

    const TLatticeState *bs = &(tail_states[rank]);

    while (bs->m_pBackTraceNode) {
        unsigned start = bs->m_pBackTraceNode->m_frIdx;
        unsigned end = bs->m_frIdx;
        CLatticeFrame & end_fr = m_lattice[end];

        if (!(end_fr.m_bwType & CLatticeFrame::USER_SELECTED)) {
            const TWCHAR* cwstr = NULL;
            if (end_fr.m_wstr.empty()) {
                cwstr = _getWstr(bs->m_backTraceWordId);
            } else {
                cwstr = end_fr.m_wstr.c_str();
            }

            CCandidate candi(start, end, bs->m_pLexiconState, cwstr,
                             bs->m_backTraceWordId);

            end_fr.m_bwType |= CLatticeFrame::BESTWORD;
            end_fr.m_bestWords[rank] = candi;
            if (rank == 0) {
                end_fr.m_selWord = candi; // select the first by default.
            }
        }

        if (bs->m_pBackTraceNode->m_pLexiconState) {
            std::vector<unsigned> seg_path =
                bs->m_pBackTraceNode->m_pLexiconState->m_seg_path;
            std::vector<unsigned>::reverse_iterator it = seg_path.rbegin();

            for (; it != seg_path.rend(); ++it) {
                if (segmentPath.empty() || segmentPath.back() != *it)
                    segmentPath.push_back(*it);
            }
        }

        path.push_back(end);
        bs = bs->m_pBackTraceNode;
    }

    std::reverse(path.begin(), path.end());
    std::reverse(segmentPath.begin(), segmentPath.end());

#ifdef DEBUG
    std::vector<unsigned>::iterator it;

    printf("trace lattice path[%d]: ", rank);
    for (it = path.begin(); it != path.end(); ++it)
        printf("%d ", *it);
    printf("\n");

    printf("trace segments path[%d]: ", rank);
    for (it = segmentPath.begin(); it != segmentPath.end(); ++it)
        printf("%d ", *it);
    printf("\n");
#endif

    return true;
}
예제 #28
0
파일: mount.cpp 프로젝트: presto53/porto
TError TMount::Remount(TPath path, unsigned long flags) {
    if (mount(NULL, path.c_str(), NULL, flags, NULL))
        return TError(EError::Unknown, errno, "mount(NULL, " + path.ToString() + ", NULL, " + std::to_string(flags) + ", NULL)");
    return TError::Success();
}
예제 #29
0
// ---------------------------------------------------------------------------
// RArray compare function to compare strings
// ---------------------------------------------------------------------------
//
static TInt CompareString(const TPath& aFirst,
                          const TPath& aSecond)
    {
    return aFirst.Compare( aSecond );
    }
예제 #30
0
void T_CntImageRescaler::testRescaleUtility()
{
    // delete the possible image directory, it must not leave
    // even if the folder was not found. 
    TRAPD( err, TCntImageRescaleUtility::DeleteImageDirectoryL() );
    test( err == KErrNone );
    
    // path for image directory, existense of the directory is not
    // checked
    TPath path = TCntImageRescaleUtility::ImageDirectoryL();
    test( path.Length() > 0 );
    test( path.Find(KImagesFolder) != KErrNotFound );
    
    TPath dir = TCntImageRescaleUtility::CreateImageDirectoryL();
    test( dir.Length() > 0 );
    test( dir.Find( KImagesFolder) != KErrNotFound );
  
    // make a test image file (empty file) 
    RFs fs;
    CleanupClosePushL( fs );
    User::LeaveIfError( fs.Connect() );
    
    TPath imagePath;
    imagePath.Append( dir );
    imagePath.Append( KImageName );
    
    RFile file;
    CleanupClosePushL(file);
    User::LeaveIfError(file.Create( fs, imagePath, EFileWrite ));
    CleanupStack::PopAndDestroy();
    
    CContactItem* item  = CContactItem::NewLC(KUidContactCard);
    CContactItemField* field = CContactItemField::NewL( KStorageTypeText, KUidContactFieldCodImage );
    field->SetMapping( KUidContactFieldVCardMapUnknown );
    item->AddFieldL( *field );

    // add image without GUID
    TRAPD( err2, TCntImageRescaleUtility::StoreImageFieldL( *item, imagePath ) );
    test( err2 == KErrNone );
    
    // then update with GUID value
    _LIT(KGuid, "guid");
    TBufC<4> buffer ( KGuid );
    item->SetUidStringL( buffer );
    
    TRAPD( err3, TCntImageRescaleUtility::UpdateImageNameL( *item ) );
    test( err3 == KErrNone );
    
    CContactItemFieldSet& fields = item->CardFields();
    TInt privateImageIndex = fields.Find( KUidContactFieldCodImage, KUidContactFieldVCardMapUnknown );
    test( privateImageIndex != KErrNotFound );
    
    TPtrC fieldText = fields[privateImageIndex].TextStorage()->Text();
    
    // how it should look like
    TPath newPath;
    newPath.Append( TCntImageRescaleUtility::ImageDirectoryL() );
    newPath.Append( buffer );
    newPath.Append( KImageName );
    RDebug::Print( _L("%S"), &newPath );
    RDebug::Print( _L("%S"), &fieldText );
    
    test( newPath.Compare(fieldText) == 0 );
    BaflUtils::DeleteFile( fs, newPath );
    CleanupStack::PopAndDestroy(2); // item, RFs
}