Пример #1
0
/* Get file modification time using FileTimeToUnixTime()
 *
 * INPUTS:
 *      LPCTSTR name:   the file name
 */
BOOL GetUTCFileModTime ( LPCTSTR name, time_t * utc_mod_time )
{
    WIN32_FIND_DATA find_buf;
    FILETIME mod_time;
    HANDLE find_handle;
    BOOL success = FALSE;

    * utc_mod_time = 0L;

    find_handle = FindFirstFile ( name, &find_buf );
    success = ( find_handle != INVALID_HANDLE_VALUE );
    if (success)
    {
        /* Originally I thought that I needed to apply a correction 
         * LocalTimeToFileTime() to files from FAT volumes, but the 
         * FindFirstFile() system call thoughtfully applies this 
         * correction itself.
         *
         * Thus, the file time returned is allegedly in UTC.
         *
         * However, the correction from local to UTC is applied 
         * incorrectly (Thanks a lot, Microsoft!). As documented in the 
         * Win32 API (see MSDN or the PSDK), DST is applied if and only 
         * if the computer's system time is in DST at the time we call 
         * FindFirstFile(), irrespective or whether DST applied at the 
         * time the file was modified!
         *
         * Thus, we have to call FileTimeToLocalFileTime() to undo
         * Windows's good intentions. We correctly translate the time
         * In FileTimeToUnixTime().
         *
         */
        if ( IsUTCVolume ( name ) ) 
        {
            mod_time = find_buf.ftLastWriteTime;
            success = FileTimeToUnixTime ( &mod_time, utc_mod_time, FALSE );
        }
        else 
        { 
            // See notes above...
            success = FileTimeToLocalFileTime ( &find_buf.ftLastWriteTime, &mod_time );
            success = success && FileTimeToUnixTime ( &mod_time, utc_mod_time, TRUE );
        }        
    }
    FindClose ( find_handle );
    return success;
}
Пример #2
0
//---------------------------------------------------------------------
// add a file to the dir content - if not already there
void Server::insertFile(bstring const & remotePath, FILETIME * ft, unsigned long szLo, unsigned long szHi, char kind, bstring const & chmod) {
	bstring path, file;
	file = splitPath(path, remotePath);
	DirCache::iterator i = dirCache.find(path);
	if (i == dirCache.end())
		return;

	my_fxp_names * dir = i->second;	

	int count = dir->nnames;
	for (int i = 0; i < count; ++i) {
		fxp_name * fn = dir->names[i];
		if (file == fn->filename) {
			// already there
			return;
		}
	}
	// create a new structure and fill it
	my_fxp_names * ndir = (my_fxp_names *) malloc(sizeof(my_fxp_names));
	ndir->names = (fxp_name **)malloc(sizeof(fxp_name*) * (count + 1));
	
	fxp_name * n = ndir->names[0] = (fxp_name *)malloc(sizeof(fxp_name));
	RtlZeroMemory(n, sizeof(fxp_name));

	FILETIME ft2;
	SYSTEMTIME st;
	if (ft) {
		FileTimeToSystemTime(ft, &st);
	} else {
		GetSystemTime(&st);
		SystemTimeToFileTime(&st, &ft2);
		ft = &ft2;
	}

	char buffer[32];
	sprintf(buffer, "%d ", szLo);
#ifdef UNICODE
	char * chmod2;
	BCONVERT(char, 32, chmod2, chmod.c_str());
	char * file2;
	BCONVERT(char, 256, file2, file.c_str());
	std::string ln = kind + chmod2 + std::string(" 1 ? ? ") + buffer + " Jan  1 1990 " + file2; 
#else
	std::string ln = kind + chmod + std::string(" 1 ? ? ") + buffer + " Jan  1 1990 " + file; 
#endif
	n->longname = strdup(ln.c_str());
	n->filename = bstrdup(file.c_str());

	n->attrs.size.hi = szHi;
	n->attrs.size.lo = szLo;	
	n->attrs.mtime = FileTimeToUnixTime(ft);

	for (int i = 0; i < count; ++i) {
		ndir->names[i + 1] = dir->names[i];
	}
	ndir->nnames = count + 1;
	
	i->second = ndir;
}
Пример #3
0
static void CalcTsOffset(MIM_TIMEZONE *tz)
{
	SYSTEMTIME st, stl;
	GetSystemTime(&st);

	FILETIME ft;
	SystemTimeToFileTime(&st, &ft);
	mir_time ts1 = FileTimeToUnixTime(&ft);

	if (!SystemTimeToTzSpecificLocalTime(&tz->tzi, &st, &stl))
		return;

	SystemTimeToFileTime(&stl, &ft);
	mir_time ts2 = FileTimeToUnixTime(&ft);

	tz->offset = ts2 - ts1;
}
Пример #4
0
bool touchmind::util::TimeUtil::SystemTimeToUnixTime(SYSTEMTIME systemTime, time_t* t)
{
    FILETIME fileTime;
    if (SystemTimeToFileTime(&systemTime, &fileTime) == 0) {
        return false;
    }
    FileTimeToUnixTime(fileTime, t);
    return true;
}
Пример #5
0
/*
 * @implemented
 */
int _tfindnext(intptr_t handle, struct _tfinddata_t* result)
{
    WIN32_FIND_DATA FindFileData;

    if (!FindNextFile((HANDLE)handle, &FindFileData)) {
    	_dosmaperr(GetLastError());
        return -1;
	}

    result->attrib = FindFileData.dwFileAttributes;
    result->time_create = (time_t)FileTimeToUnixTime(&FindFileData.ftCreationTime,NULL);
    result->time_access = (time_t)FileTimeToUnixTime(&FindFileData.ftLastAccessTime,NULL);
    result->time_write = (time_t)FileTimeToUnixTime(&FindFileData.ftLastWriteTime,NULL);
    result->size = (((__int64)FindFileData.nFileSizeHigh)<<32) + FindFileData.nFileSizeLow;
    _tcsncpy(result->name,FindFileData.cFileName, MAX_PATH);

    return 0;
}
Пример #6
0
/******************************************************************************
 * \name clock
 * \brief Returns the current process's elapsed time.
 */
clock_t
clock(void)
{
    ULARGE_INTEGER Time;

    GetSystemTimeAsFileTime((FILETIME*)&Time);
    Time.QuadPart -= g_StartupTime.QuadPart;
    return (clock_t)FileTimeToUnixTime((FILETIME*)&Time, NULL);
};
Пример #7
0
time_t GetLastWriteTime(const char *filename) {
    WIN32_FILE_ATTRIBUTE_DATA fattribs;

    if (!GetFileAttributesEx(".", GetFileExInfoStandard, &fattribs)) {
        printerr("GetFileAttributesEx");
        return 0;
    }

    return FileTimeToUnixTime(fattribs.ftLastWriteTime);
}
Пример #8
0
/*
 * @implemented
 */
intptr_t _tfindfirst(const _TCHAR* _name, struct _tfinddata_t* result)
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFindFile;

    hFindFile = FindFirstFile(_name, &FindFileData);
    if (hFindFile == INVALID_HANDLE_VALUE) {
        _dosmaperr(GetLastError());
        return -1;
    }

    result->attrib = FindFileData.dwFileAttributes;
    result->time_create = (time_t)FileTimeToUnixTime(&FindFileData.ftCreationTime,NULL);
    result->time_access = (time_t)FileTimeToUnixTime(&FindFileData.ftLastAccessTime,NULL);
    result->time_write = (time_t)FileTimeToUnixTime(&FindFileData.ftLastWriteTime,NULL);
    result->size = (((__int64)FindFileData.nFileSizeHigh)<<32) + FindFileData.nFileSizeLow;
    _tcsncpy(result->name,FindFileData.cFileName,MAX_PATH);

    return (intptr_t)hFindFile;
}
Пример #9
0
VOID Push_FormatTime( WCHAR* Buffer )
{
    __int64 rawtime;
    FILETIME Now;
    TIME_INFORMATION timeInfo;


    NtGetSystemTimeAsFileTime(&Now);
    rawtime = FileTimeToUnixTime(&Now);

    GetTimeUnits(&timeInfo, rawtime);
    String_Format(Buffer, 20, L"%i:%i:%i", timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);
}
Пример #10
0
int csync_vio_local_stat(const char *uri, csync_vio_file_stat_t *buf) {
    /* Almost nothing to do since csync_vio_local_readdir already filled up most of the information
       But we still need to fetch the file ID.
       Possible optimisation: only fetch the file id when we need it (for new files)
      */

    HANDLE h;
    BY_HANDLE_FILE_INFORMATION fileInfo;
    ULARGE_INTEGER FileIndex;
    mbchar_t *wuri = c_utf8_path_to_locale( uri );

    h = CreateFileW( wuri, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                     FILE_ATTRIBUTE_NORMAL+FILE_FLAG_BACKUP_SEMANTICS+FILE_FLAG_OPEN_REPARSE_POINT, NULL );
    if( h == INVALID_HANDLE_VALUE ) {
        CSYNC_LOG(CSYNC_LOG_PRIORITY_CRIT, "CreateFileW failed on %s", uri );
        errno = GetLastError();
        c_free_locale_string(wuri);
        return -1;
    }

    if(!GetFileInformationByHandle( h, &fileInfo ) ) {
        CSYNC_LOG(CSYNC_LOG_PRIORITY_CRIT, "GetFileInformationByHandle failed on %s", uri );
        errno = GetLastError();
        c_free_locale_string(wuri);
        CloseHandle(h);
        return -1;
    }

    /* Get the Windows file id as an inode replacement. */
    FileIndex.HighPart = fileInfo.nFileIndexHigh;
    FileIndex.LowPart = fileInfo.nFileIndexLow;
    FileIndex.QuadPart &= 0x0000FFFFFFFFFFFF;
    /* printf("Index: %I64i\n", FileIndex.QuadPart); */
    buf->inode = FileIndex.QuadPart;

    if (!(buf->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) {
        buf->size = (fileInfo.nFileSizeHigh * ((int64_t)(MAXDWORD)+1)) + fileInfo.nFileSizeLow;
        buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_SIZE;
    }
    if (!(buf->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) {
        DWORD rem;
        buf->mtime = FileTimeToUnixTime(&fileInfo.ftLastWriteTime, &rem);
        /* CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Local File MTime: %llu", (unsigned long long) buf->mtime ); */
        buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_MTIME;
    }

    c_free_locale_string(wuri);
    CloseHandle(h);
    return 0;
}
Пример #11
0
LONG FileTimeToAmiga( CFileItem * item, ULONG *AmigaTime )
{
	CArchiveFileTime * ft;
	ULONG time = 0;
	
	if((ft = FileTimeDefined(item)) == 0)
		return -1; // undefined
	
	if(!FileTimeToUnixTime( ft, &time))
		return -2; // overflow, this should be fixed...
	
	if(time) // adjust unix time to amiga
		time -= UTOF;
	
	(*AmigaTime) = time;
	
	return 0; // suceesful
}
Пример #12
0
bool LoadSessionData(
    IN MRABase& _db,
    IN MAKFC_CString databaseKey, 
    OUT MAKFC_CString& sDevId, 
    OUT MAKFC_CString& sA, 
    OUT MAKFC_CString& sSessionKey, 
    OUT MAKFC_CString& ts)
{
    gigabase::dbArray<gigabase::byte> data;
    if ( !_db.ReadRawData( tstring(databaseKey.NetStrW()), L"", ICQ_PARTNERS_LOGIN_DATA, data ) )
    {
        return false;
    }

    MAKFC_CString sCookies = (LPCWSTR) data.get();
    if ( !sCookies.Len() )
        return false;

    int iStart1 = 0;
    MAKFC_CString sToken1;

    while ( ( sToken1 = sCookies.Tokenize( L";", iStart1 ) ).GetLength() )
    {
        int iStart2 = 0;
        MAKFC_CString sLeft = sToken1.Tokenize( L"=", iStart2 );
        MAKFC_CString sRight = sToken1.Mid( iStart2 );

        if ( sLeft == L"k" )
            sDevId = sRight;
        else if ( sLeft == L"a" )
            sA = sRight;
        else if ( sLeft == L"session_key" )
            sSessionKey = sRight;
        else if ( sLeft == L"time_offset" )
        {
            __int64 offset = _wtoi64( sRight );
            time_t tt = 0;
            FileTimeToUnixTime( &tt, CFileTime( CFileTime::GetCurrentTime().GetTime() - offset ) );
            ts.Format( L"%d", (DWORD) tt );
        }
    }

    return true;
}
Пример #13
0
// @rootdir: 欲遍历的根目录
// @subdir: 此次要遍历的除去根目录的部分的子目录.
void walk_subdir_win32(const char* rootdir, char *subdir, int deepen, fn_walk_dir fn, uint32_t *ctx)
{
	HANDLE				hFind;
	WIN32_FIND_DATA		finddata;
	BOOL				fOk;
	int64_t				timestamp = 0;
	char				cFileNameComp[_MAX_PATH];
	
	hFind = FindFirstFile("*.*", &finddata);
	fOk = (hFind != INVALID_HANDLE_VALUE);

	while (fOk) {
		sprintf(cFileNameComp, "%s\\%s", subdir, finddata.cFileName);
		timestamp = FileTimeToUnixTime(finddata.ftLastWriteTime);
		if (finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			// 目录
			if ((strcmp(finddata.cFileName, ".") != 0) && (strcmp(finddata.cFileName, "..") != 0)) {
				if (deepen && fn) {
					// 由浅到深: 是先调用fn,再去在该目上递归
					fn(cFileNameComp, FILE_ATTRIBUTE_DIRECTORY, posix_mku64(finddata.nFileSizeLow, finddata.nFileSizeHigh), timestamp, ctx);
				}
				SetCurrentDirectory(formatstr("%s\\%s\\", rootdir, cFileNameComp));
				walk_subdir_win32(rootdir, cFileNameComp, deepen, fn, ctx);
				if (!deepen && fn) {
					// 由深到浅: 是先在该目上递归,再去调动fn
					fn(cFileNameComp, FILE_ATTRIBUTE_DIRECTORY, posix_mku64(finddata.nFileSizeLow, finddata.nFileSizeHigh), timestamp, ctx);
				}
			}
		} else {
			// 文件
			if (fn) {
				fn(cFileNameComp, 0, posix_mku64(finddata.nFileSizeLow, finddata.nFileSizeHigh), timestamp, ctx);
			}
		}
		fOk = FindNextFile(hFind, &finddata);
	}
	if (hFind != INVALID_HANDLE_VALUE) {
		FindClose(hFind);
	}

	return;
}
Пример #14
0
static time_t timeapiTimeStampToTimeZoneTimeStamp(HANDLE hTZ, time_t ts)
{
	MIM_TIMEZONE *tz = (MIM_TIMEZONE*)hTZ;
	
	if (tz == NULL) tz = &myInfo.myTZ; 
	if (tz == NULL)
	{
		FILETIME ft, lft;

		UnixTimeToFileTime(ts, &ft);
		FileTimeToLocalFileTime(&ft, &lft);
		return FileTimeToUnixTime(&lft);
	}
	else if (tz == UTC_TIME_HANDLE)
		return ts;
	
	if (tz->offset == INT_MIN)
		CalcTsOffset(tz);

	return ts + tz->offset;
}
Пример #15
0
// @rootdir: 欲遍历的根目录
// @subfolders: 是否要遍历子目录. 0: 不遍历
// @deepen: 遍历, 调用fn时给的参数是, 1: 浅到深, 0: 由深到浅
// 注:
//  1.靠这种FindFirstFile方法删除目录是不行的.当检测到是目时,调用RemoveDirectory将返回总是失败(错误码:32,指示另有进行在使用)
//    FindClose后才可以,而这时close时不可能的事.要删目录改调用SHFileOperation.
BOOL walk_dir_win32(const char* rootdir, int subfolders, int deepen, fn_walk_dir fn, uint32_t *ctx, int del)
{
	char				szCurrDir[_MAX_PATH], text[_MAX_PATH];
	HANDLE				hFind;
	WIN32_FIND_DATA		finddata;
	BOOL				fOk, fRet = TRUE;
	int64_t				timestamp = 0;
		
	GetCurrentDirectory(_MAX_PATH, szCurrDir);
	SetCurrentDirectory(appendbackslash(rootdir));
	hFind = FindFirstFile("*.*", &finddata);
	fOk = (hFind != INVALID_HANDLE_VALUE);

	while (fOk) {
		timestamp = FileTimeToUnixTime(finddata.ftLastWriteTime);
		if (finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			// 目录
			if ((strcmp(finddata.cFileName, ".") != 0) && (strcmp(finddata.cFileName, "..") != 0)) {
				if (deepen && fn) {
					// 由浅到深: 是先调用fn,再去在该目上递归
					if (!fn(finddata.cFileName, FILE_ATTRIBUTE_DIRECTORY, posix_mku64(finddata.nFileSizeLow, finddata.nFileSizeHigh), timestamp, ctx)) {
						fRet = FALSE;
						break;
					}
				}
				sprintf(text, "%s\\%s\\", rootdir, finddata.cFileName);
				if (subfolders) {
					SetCurrentDirectory(text);
					walk_subdir_win32(rootdir, finddata.cFileName, deepen, fn, ctx);
				}
				if (!deepen && fn) {
					// 由深到浅: 是先在该目上递归,再去调动fn
					if (!fn(finddata.cFileName, FILE_ATTRIBUTE_DIRECTORY, posix_mku64(finddata.nFileSizeLow, finddata.nFileSizeHigh), timestamp, ctx)) {
						fRet = FALSE;
						break;
					}
				}
				if (del) {
					RemoveDirectory(text);
					DWORD err = GetLastError();
				}
			}
		} else {
			// 文件
			if (fn) {
				if (!fn(finddata.cFileName, 0, posix_mku64(finddata.nFileSizeLow, finddata.nFileSizeHigh), timestamp, ctx)) {
					fRet = FALSE;
					break;
				}
			}
			if (del) {
				sprintf(text, "%s\\%s", rootdir, finddata.cFileName);
				delfile(text);
			}
		}
		fOk = FindNextFile(hFind, &finddata);
	}
	if (hFind != INVALID_HANDLE_VALUE) {
		FindClose(hFind);
	}

	SetCurrentDirectory(szCurrDir);
	return fRet;
}
Пример #16
0
ECRESULT ECUserStoreTable::Load() {
	ECRESULT er = erSuccess;
	ECListIntIterator i;
    ECDatabase *lpDatabase = NULL;
    DB_RESULT 	lpDBResult = NULL;
    DB_ROW		lpDBRow = NULL;
    DB_LENGTHS	lpDBLength = NULL;
	std::string strQuery;
    std::list<unsigned int> lstObjIds;
	ECUserStore sUserStore;
	int iRowId;
	ECUserManagement *lpUserManagement = lpSession->GetUserManagement();
	ECSecurity *lpSecurity = lpSession->GetSecurity();
	objectdetails_t sUserDetails;
	GUID sZeroGuid = {0};
	objectclass_t objclass;
	objectdetails_t sDetails;

	enum cols { USERID = 0, EXTERNID, OBJCLASS, UCOMPANY, STOREGUID, STORETYPE, USERNAME, SCOMPANY, HIERARCHYID, STORESIZE, MODTIME_HI, MODTIME_LO };

	er = lpSession->GetDatabase(&lpDatabase);
	if (er != erSuccess)
		goto exit;

    Clear();

	/*
	 * The next query will first get the list of all users with their primary store details or NULL if
	 * no primary store was found. Secondly it will get the list of all stores with their owner or NULL
	 * if they're detached.
	 * The most important difference id that the first query will return no store for users without a
	 * primary store, even if they do have an archive store attached, while the second query will
	 * return all stores types.
	 */
	strQuery =
		" SELECT u.id, u.externid, u.objectclass, u.company, s.guid, s.type, s.user_name, s.company, s.hierarchy_id, p.val_longint, m.val_hi, m.val_lo FROM users AS u"
		"  LEFT JOIN stores AS s ON s.user_id=u.id AND s.type=" + stringify(ECSTORE_TYPE_PRIVATE) + " LEFT JOIN hierarchy AS h ON h.id=s.hierarchy_id"
		"  LEFT JOIN properties AS p ON p.hierarchyid=s.hierarchy_id and p.tag=0x0E08 and p.type=0x14"
		"  LEFT JOIN properties AS m ON m.hierarchyid=s.hierarchy_id and m.tag=0x66A2 and m.type=0x40"
		" UNION"
		" SELECT u.id, u.externid, u.objectclass, u.company, s.guid, s.type, s.user_name, s.company, s.hierarchy_id, p.val_longint, m.val_hi, m.val_lo FROM users AS u"
		"  RIGHT JOIN stores AS s ON s.user_id=u.id LEFT JOIN hierarchy AS h ON h.id=s.hierarchy_id"
		"  LEFT JOIN properties AS p ON p.hierarchyid=s.hierarchy_id and p.tag=0x0E08 and p.type=0x14"
		"  LEFT JOIN properties AS m ON m.hierarchyid=s.hierarchy_id and m.tag=0x66A2 and m.type=0x40";

	er = lpDatabase->DoSelect(strQuery, &lpDBResult);
	if(er != erSuccess)
		goto exit;

	iRowId = 0;
	while(1) {
		lpDBRow = lpDatabase->FetchRow(lpDBResult);

		if(lpDBRow == NULL)
			break;

		lpDBLength = lpDatabase->FetchRowLengths(lpDBResult);

		if (lpDBRow[OBJCLASS]) {
			objclass = (objectclass_t)atoi(lpDBRow[OBJCLASS]);
			if (objclass != ACTIVE_USER && objclass != NONACTIVE_USER &&
				objclass != NONACTIVE_ROOM && objclass != NONACTIVE_EQUIPMENT)
				continue;
		}

		if (lpDBRow[USERID]) {
			sUserStore.ulUserId = atoi(lpDBRow[USERID]);
			if (sUserStore.ulUserId == ZARAFA_UID_SYSTEM) // everyone already filtered by object type
				continue;
		} else {
			sUserStore.ulUserId = -1;
		}

		sUserStore.ulCompanyId = 0;
		if (lpDBRow[UCOMPANY])
			sUserStore.ulCompanyId = atoi(lpDBRow[UCOMPANY]);
		if (lpDBRow[SCOMPANY])
			sUserStore.ulCompanyId = atoi(lpDBRow[SCOMPANY]); // might override from user.company
		// check if we're admin over this company
		if (lpSecurity->IsAdminOverUserObject(sUserStore.ulCompanyId) != erSuccess)
			continue;

		if (lpDBRow[EXTERNID]) {
			sUserStore.sExternId.id.assign(lpDBRow[EXTERNID], lpDBLength[EXTERNID]);
			sUserStore.sExternId.objclass = objclass;
		} else {
			sUserStore.sExternId.id.clear();
			sUserStore.sExternId.objclass = OBJECTCLASS_UNKNOWN;
		}

		sUserStore.strUsername.clear();
		// find and override real username if possible
		if (sUserStore.ulUserId != -1 && lpUserManagement->GetObjectDetails(sUserStore.ulUserId, &sUserDetails) == erSuccess) {
			if (lpSession->GetSessionManager()->IsDistributedSupported()) {
				if (sUserDetails.GetPropString(OB_PROP_S_SERVERNAME).compare(lpSession->GetSessionManager()->GetConfig()->GetSetting("server_name")) != 0)
					continue;		// user not on this server
			}

			sUserStore.strUsername = sUserDetails.GetPropString(OB_PROP_S_LOGIN);
		}

		sUserStore.sGuid = sZeroGuid;
		if (lpDBRow[STOREGUID])
			memcpy(&sUserStore.sGuid, lpDBRow[STOREGUID], lpDBLength[STOREGUID]);

		if (lpDBRow[STORETYPE])
			sUserStore.ulStoreType = atoi(lpDBRow[STORETYPE]);
		else
			sUserStore.ulStoreType = ECSTORE_TYPE_PRIVATE; // or invalid value?
			
		if (lpDBRow[USERNAME])
			sUserStore.strGuessname = lpDBRow[USERNAME];
		else
			sUserStore.strGuessname.clear();

		if (sUserStore.ulCompanyId > 0 && lpUserManagement->GetObjectDetails(sUserStore.ulCompanyId, &sDetails) == erSuccess) {
			sUserStore.strCompanyName = sDetails.GetPropString(OB_PROP_S_LOGIN);
		}

		if(lpDBRow[HIERARCHYID])
			sUserStore.ulObjId = atoui(lpDBRow[HIERARCHYID]);
		else
			sUserStore.ulObjId = 0;

		sUserStore.tModTime = 0;
		if(lpDBRow[MODTIME_HI] && lpDBRow[MODTIME_LO]) {
			FILETIME ft;
			ft.dwHighDateTime = atoui(lpDBRow[MODTIME_HI]);
			ft.dwLowDateTime =  atoui(lpDBRow[MODTIME_LO]);
			sUserStore.tModTime = 0;
			FileTimeToUnixTime(ft, &sUserStore.tModTime);
		}

		if(lpDBRow[STORESIZE])
			sUserStore.ullStoreSize = atoll(lpDBRow[STORESIZE]);
		else
			sUserStore.ullStoreSize = 0;

		// add to table
		lstObjIds.push_back(iRowId);
		// remember details
		m_mapUserStoreData.insert(std::pair<unsigned int, ECUserStore>(iRowId++, sUserStore));
	}

	LoadRows(&lstObjIds, 0);

exit:	
	if (lpDBResult) {
		lpDatabase->FreeResult(lpDBResult);
		lpDBResult = NULL;
	}

	return er;
}
Пример #17
0
bool CLHttpUser::bProcessGetRequest(char * pszRequest, bool bIsGetCommand) {
	//LogEvent("Request", pszRequest);

	int nUriLength = nUnescapedURI(pszRequest);
	if (nUriLength <= 0)
		return false;

	CLFileShareListAccess clCritSection;

	if (bShutdownInProgress)
		return false;

	static char szTempfile[MAX_PATH+1];
	szTempfile[0] = '\0';

	if (!bReadGetParameters(pszRequest)) {
		SendError(400, "Bad Request");
		return false;
	}

	DWORD dwRemoteIP = ntohl(stAddr.S_un.S_addr);
	for (CLFileShareNode * pclCur = pclFirstNode; pclCur ; pclCur = pclCur->pclNext) {
		if ((pclCur->st.dwAllowedIP ^ dwRemoteIP) & pclCur->st.dwAllowedMask)
			continue; // Not an allowed IP address

		if (!pclCur->bIsDirectory() && pclCur->nGetSrvPathLen() != nUriLength)
			continue; // not the right length, quickly move on to the next.

		if (pclCur->bIsDirectory() ?
		    (strncmp(pclCur->st.pszSrvPath, pszRequest, pclCur->nGetSrvPathLen() - 1) == 0) :
		    (strncmp(pclCur->st.pszSrvPath, pszRequest, pclCur->nGetSrvPathLen()) == 0)) {
			/*OutputDebugString( "Request for file OK : ");
			OutputDebugString( pclCur->st.pszSrvPath );
			OutputDebugString( "\n" );*/

			static char szSrvPath[MAX_PATH+1];
			static char szRealPath[MAX_PATH+1];
			char* pszSrvPath  = pclCur->st.pszSrvPath;
			char* pszRealPath = pclCur->st.pszRealPath;

			if (pclCur->bIsDirectory()) {
				strcpy(szRealPath, pclCur->st.pszRealPath);
				strcpy(szSrvPath, pclCur->st.pszSrvPath);
				pszRealPath = szRealPath;
				pszSrvPath = szSrvPath;

				if (nUriLength > MAX_PATH)
					nUriLength = MAX_PATH;

				pszRequest[nUriLength] = '\0';

				if (pclCur->nGetSrvPathLen() - nUriLength == 1) {
					SendRedir(302, "Found", "The document has moved", pszRequest);
					return false;
				} else {
					strmcat(pszRealPath, &pszRequest[pclCur->nGetSrvPathLen()], MAX_PATH);
					strmcat(pszSrvPath,  &pszRequest[pclCur->nGetSrvPathLen()], MAX_PATH);
				}
				pszRequest[nUriLength] = ' ';

				// hacker protection - should be removed by the browser
				if (strstr(pszRealPath, "..")) {
					SendError(404, "Not Found", "The requested URL was not found on this server.");
					return false;
				}

				char* pszTmp = pszRealPath;
				while (pszTmp = strchr(pszTmp, '/'))
					* pszTmp = '\\';

				hFile = CreateFile(pszRealPath, GENERIC_READ ,
				    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

				if (hFile == INVALID_HANDLE_VALUE) {
					if (pszSrvPath[strlen(pszSrvPath)-1] != '/') {
						strmcat(pszRealPath, "\\", MAX_PATH);
						strmcat(pszSrvPath,  "/", MAX_PATH);
					}

					// a directory with index.htm
					strmcat(szRealPath, "index.htm", MAX_PATH);

					hFile = CreateFile(pszRealPath, GENERIC_READ ,
					    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN, NULL);

					if (hFile == INVALID_HANDLE_VALUE) {
						// a directory with index.html
						strmcat(szRealPath, "l", MAX_PATH);

						hFile = CreateFile(pszRealPath, GENERIC_READ ,
						    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN, NULL);

						if (hFile == INVALID_HANDLE_VALUE) {
							// generate directory index in temporary file
							if (*szTempfile == '\0') {
								GetTempPath(MAX_PATH, szTempfile);
								strmcat(szTempfile, "\\HttpServerTemp", MAX_PATH);
								strmcat(szTempfile, pszSrvPath, MAX_PATH);
								char* pszTmp = szTempfile;
								while (pszTmp = strchr(pszTmp, '/'))
									* pszTmp = '~';
							}
							pszRealPath[strlen(pszRealPath) - 10] = '\0';

							// detecting browser function removed
							// every browser should support it by now
							bool BrowserSupportsXML = true; 
							  //(apszParam[eUserAgent] != NULL) &&
							  //  (strstr(apszParam[eUserAgent], "Firefox") ||
							  //   (strstr(apszParam[eUserAgent], "MSIE") && !strstr(apszParam[eUserAgent], "Opera")));

							if ((indexCreationMode == INDEX_CREATION_XML ||
							     (indexCreationMode == INDEX_CREATION_DETECT && BrowserSupportsXML)) &&
							    bCreateIndexXML(pszRealPath, szTempfile, pszSrvPath, dwRemoteIP)) {
								hFile = CreateFile(szTempfile, GENERIC_READ ,
								    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

								strcpy(szRealPath, "a.xml"); // restore .xml for mime type
							} else if ((indexCreationMode == INDEX_CREATION_HTML ||
							    indexCreationMode == INDEX_CREATION_DETECT) &&
							    bCreateIndexHTML(pszRealPath, szTempfile, pszSrvPath, dwRemoteIP)) {
								hFile = CreateFile(szTempfile, GENERIC_READ,
								    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

								strcpy(szRealPath, "a.html"); // restore .html for mime type
							} else {
								continue;
							}
						} else {
							strmcat(pszSrvPath, "index.html", MAX_PATH);
							szTempfile[0] = '\0';
						}
					} else {
						strmcat(pszSrvPath, "index.htm", MAX_PATH);
						szTempfile[0] = '\0';
					}
				} else {
					szTempfile[0] = '\0';
				}
			} else {
				hFile = CreateFile(pszRealPath, GENERIC_READ ,
				    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

				if (hFile == INVALID_HANDLE_VALUE) {
					SendError(404, "Not Found", "HTTP server failed to open local file");
					return false;
				}
			}

			strcpy(this->szCurrentDLSrvPath, pszSrvPath);

			DWORD nDataSize = GetFileSize(hFile, NULL);
			dwTotalSize = nDataSize;

			FILETIME stFileTime;
			GetFileTime(hFile, NULL, NULL, &stFileTime);

			char szCurTime[ 100 ];
			time_t ltime;
			time(&ltime);
			strftime(szCurTime, sizeof(szCurTime), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&ltime));

			char szFileTime[ 100 ];
			FileTimeToUnixTime(&stFileTime, &ltime);
			strftime(szFileTime, sizeof(szFileTime), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&ltime));
			
			if (apszParam[eIfModifiedSince] && strcmp(apszParam[eIfModifiedSince], szFileTime) == 0) {
				SendError(304, "Not Modified" );
				return true;
			}
	
			// we found match send file !!
			if (bIsGetCommand) {
				if (! pclCur->bAddUser(this)) {
					SendError(403, "Forbidden", "Access has been denied because there are too many connections");
					return false;
				}
			}

			if (*(ULONG*)(&stAddr) != 0x0100007F && // do not show popup of 127.0.0.1
			    strstr(pszRealPath, "\\@") == NULL) { // and of shares which start with an @
				ShowPopupWindow(inet_ntoa(stAddr), pszSrvPath);
			}

			clCritSection.Unlock();

			DWORD dwFileStart = 0;
			DWORD dwDataToSend = nDataSize;

			char szETag[ 50 ];
			{
				int nETagLen = mir_snprintf(szETag, SIZEOF(szETag), "\"%x-%x-%x\"",
				    nDataSize, stFileTime.dwHighDateTime, stFileTime.dwLowDateTime);

				if (!apszParam[eIfRange] || (strncmp(szETag, apszParam[eIfRange], nETagLen) == 0)) {
					char * pszRange = apszParam[eRange];
					if (pszRange) {
						if (strncmp(pszRange, "bytes=", 6) == 0) {
							pszRange += 6;
							// Do resume !!!
							char *pszEnd;
							if (pszRange[0] == '-') {
								// its a suffix-byte-range-spec
								DWORD dwLen = strtol(pszRange + 1, &pszEnd, 10);
								if (dwLen < nDataSize)
									dwFileStart = nDataSize - dwLen;
							} else {
								DWORD dwLen = strtol(pszRange, &pszEnd, 10);
								if (*pszEnd == '-' && dwLen < nDataSize) {
									dwFileStart = dwLen;
									pszRange = pszEnd + 1;
									if (*pszRange != 0) {
										dwLen = strtol(pszEnd + 1, &pszEnd, 10);
										if (dwLen > dwFileStart)
											dwDataToSend = (dwLen + 1) - dwFileStart;
										else
											dwFileStart = 0;
									}
								} else {
									SendError(400, "Bad Request");
									return false;
								}
							}
						}
					}
				}
			}

			if (dwFileStart >= nDataSize)
				dwFileStart = 0;

			if (dwFileStart + dwDataToSend >= nDataSize)
				dwDataToSend = nDataSize - dwFileStart;


			DWORD dwBytesToWrite = 0;
			// To optimize send speed it it ideal to always send larges size packages
			// But this size depended on network media but on Ethernet it is 1518 bytes.
			// Ethernet, IP and TCP headers use some of this space and leaves 1460 bytes
			// for data transfer.
			// We will use a multiply of this to always send optimal sized packages.
			char szBuf[1460 * 4];

			if (dwFileStart > 0 || dwDataToSend != nDataSize) {
				if (SetFilePointer(hFile, dwFileStart, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
					SendError(416, "Requested Range Not Satisfiable");
					return true;
				}

				const char szHttpPartial[] = "HTTP/1.1 206 Partial Content\r\n"
				    "Connection: Keep-Alive\r\n"
				    "Date: %s\r\n"
				    "Server: MirandaWeb/%s\r\n"
				    "Accept-Ranges: bytes\r\n"
				    "ETag: %s\r\n"
				    "Content-Length: %d\r\n"
				    "Content-Type: %s\r\n"
				    "Content-Range: bytes %d-%d/%d\r\n"
				    "Last-Modified: %s\r\n"
				    "\r\n";

				dwBytesToWrite = mir_snprintf(szBuf, SIZEOF(szBuf), szHttpPartial,
				    szCurTime,
				    PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM),
				    szETag,
				    dwDataToSend,
				    pszGetMimeType(pszRealPath),
				    dwFileStart,
				    (dwFileStart + dwDataToSend - 1),
				    nDataSize,
				    szFileTime);
			} else {
				const char szHttpOk[] = "HTTP/1.1 200 OK\r\n"
				    "Connection: Keep-Alive\r\n"
				    "Date: %s\r\n"
				    "Server: MirandaWeb/%s\r\n"
				    "Accept-Ranges: bytes\r\n"
				    "ETag: %s\r\n"
				    "Content-Length: %d\r\n"
				    "Content-Type: %s\r\n"
				    "Last-Modified: %s\r\n"
				    "\r\n";

				dwBytesToWrite = mir_snprintf(szBuf, SIZEOF(szBuf), szHttpOk,
				    szCurTime,
				    PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM),
				    szETag,
				    nDataSize,
				    pszGetMimeType(pszRealPath),
				    szFileTime);
			}

			Netlib_Send(hConnection, szBuf, dwBytesToWrite, 0);

			if (bIsGetCommand) {
				static int nThreadCount = 0;
				nThreadCount++;

				DWORD dwLastUpdate = GetTickCount();
				DWORD dwLastCurrentDL = 0;
				/*

				dwLastDLSTickCount = dwCurTick;
				dwCurrentDL;*/

				//DWORD dwMaxSpeed = 8192;// Byte pr Sek
				//DWORD dwMaxSpeed = 20000;// Byte pr Sek
				//DWORD dwMaxSpeed = 163840;// Byte pr Sek
				//DWORD dwMaxSpeed = 4096;// Byte pr Sek

				DWORD dwLastResetTime = GetTickCount();
				int nMaxBytesToSend = nMaxUploadSpeed / nThreadCount;

				for (;;) {
					{
						DWORD dwCurTick = GetTickCount();
						if (dwCurTick - dwLastUpdate >= 1000) {
							dwSpeed = ((dwCurrentDL - dwLastCurrentDL) * 1000) / (dwCurTick - dwLastUpdate);
							dwLastUpdate = dwCurTick;
							dwLastCurrentDL = dwCurrentDL;
						}
					}

					if (nMaxUploadSpeed == 0) {
						Sleep(1000);
						continue;
					}

					bool bSpeedLimit = (nMaxUploadSpeed >= 0) && (bIsOnline || !bLimitOnlyWhenOnline);

					DWORD dwCurOpr = sizeof(szBuf);
					if (bSpeedLimit)
						dwCurOpr = min(nMaxBytesToSend, sizeof(szBuf));

					if (!ReadFile(hFile, szBuf, dwCurOpr, &dwBytesToWrite, NULL))
						break;

					if (dwBytesToWrite <= 0)
						break;

					if (dwCurrentDL + dwBytesToWrite > dwDataToSend)
						dwBytesToWrite = dwDataToSend - dwCurrentDL;

					if (bSpeedLimit)
						nMaxBytesToSend -= dwBytesToWrite;

					DWORD dwSend = Netlib_Send(hConnection, szBuf, dwBytesToWrite, MSG_NODUMP);
					if (dwSend == SOCKET_ERROR)
						break;
					dwCurrentDL += dwSend;
					if (dwSend != dwBytesToWrite)
						break;

					if (dwCurrentDL >= dwDataToSend)
						break;

					if (bSpeedLimit && nMaxBytesToSend <= 0) {
						// we have reached the limmit
						DWORD dwTimeUsed = GetTickCount() - dwLastResetTime;
						if (dwTimeUsed < 1000)
							Sleep(1000 - dwTimeUsed);
						dwLastResetTime = GetTickCount();
						nMaxBytesToSend = nMaxUploadSpeed / nThreadCount;
					}
				}

				// file is always closed in destructor 
				if (szTempfile[0] != '\0') {
					// and here - since it is a temporary index which as to be deleted
					CloseHandle(hFile);
					hFile = INVALID_HANDLE_VALUE;

					DeleteFile(szTempfile);
				}
				clCritSection.Lock();
				nThreadCount--;

				bool bNeedToWriteConfig = false;

				if (dwCurrentDL == nDataSize) {
					if (pclCur->st.nMaxDownloads > 0) {
						pclCur->st.nMaxDownloads--;
						bNeedToWriteConfig = true;
					}
				}

				pclCur->bRemoveUser(this);

				// nMaxDownloads can have been decreesed by another thread.
				// Therefore we test it even if we did'en decreese it
				if (pclCur->st.nMaxDownloads == 0 && !pclCur->bAnyUsers()) {
					CLFileShareNode **pclPrev = &pclFirstNode;
					for (CLFileShareNode * pcl = pclFirstNode ; pcl ; pcl = pcl->pclNext) {
						if (pcl == pclCur) {
							*pclPrev = pclCur->pclNext;
							ShowPopupWindow(Translate("Share removed"), pclCur->st.pszSrvPath, RGB(255, 189, 189));
							delete pclCur;
							bNeedToWriteConfig = true;
							break;
						}
						pclPrev = &pcl->pclNext;
					}
				}

				if (bNeedToWriteConfig) {
					bWriteConfigurationFile();
				}
			}

			return true;
		}
	}


#ifdef _DEBUG
	OutputDebugString("###########   Request Failed   ###########\n");
	OutputDebugString(pszRequest);
#endif

	pszRequest[nUriLength] = 0;

	if ((nUriLength != 12 || strncmp(pszRequest, "/favicon.ico", nUriLength)) &&  // do not show popup of favicon.ico
	    *(ULONG*)(&stAddr) != 0x0100007F) { // do not show popup of 127.0.0.1
		ShowPopupWindow(inet_ntoa(stAddr), pszRequest, RGB(255, 189, 189));
	}

	SendError(404, "Not Found", "The requested URL was not found on this server.");

	return false;
}
Пример #18
0
int main(int argc, char **argv) {
  DBX *dbx, *folders;
  DBXFOLDER *x = NULL;
  DBXEMAIL *z = NULL;
  time_t date;
  int y,a, c, quiet = 0, totalEmails = 0;
  char *fname = NULL;
  FILE *outfile;
  char *indir = NULL, *outdir = NULL;
  
  while ((c = getopt(argc, argv, "hVi:o:q")) != EOF) {
    switch (c) {
    case 'V': //Version
      printf("readoe v%s - Implementing libdbx v%s\n", VERSION, LIBDBX_VERSION);
      exit(0);
    case 'h': //help
      usage(0);
    case 'i': //input directory
      indir = optarg;
      break;
    case 'o': //output directory
      outdir = optarg;
      break;
    case 'q': //quiet
      quiet = 1;
      break;
    default:
      usage(1);
    }
  }

  if (indir == NULL || outdir == NULL) {
    printf("readoe: must specify BOTH input directory and output directory\n");
    usage(2);
  }

  fname = (char*) realloc(fname, strlen(indir)+strlen("Folders.dbx")+2);
  sprintf(fname, "%s/%s", indir, "Folders.dbx");
  folders = dbx_open(fname);
  
  if (folders == NULL){
    dbx_perror("Folder file open");
    return 1;
  }
  
  if (folders->type != DBX_TYPE_FOLDER) {
    printf("File Folders.dbx doesn't appear to contain the correct stuff\n");
    return 2;
  }
  
  for (y = folders->indexCount-1; y >= 0; y--) {
    dbx_free(folders, x);
    x=(DBXFOLDER*)dbx_get(folders, y, 0);
    
    if (dbx_errno != DBX_NOERROR) {
      dbx_perror("Folder Read");
      return 2;
    }
    
    if (x) {
      if (!quiet) {
	printf("\nFolder Name: %s\n", x->name);
      }
    } else
      continue;
    
    if (x->fname != NULL) {
      fname = (char*) realloc (fname, strlen(indir)+strlen(x->fname)+2);
      sprintf(fname, "%s/%s", indir, x->fname);

      dbx = dbx_open(fname);
      if (dbx == NULL) {
	dbx_perror("Email Folder Open");
	continue;
      }
      if (dbx->type != DBX_TYPE_EMAIL) {
	printf("Folder %s doesn't contain emails like I expect\n", fname);
	continue;
      }
      
      fname = (char*) realloc (fname, strlen(outdir)+strlen(x->fname)+2);
      sprintf(fname, "%s/%s", outdir, x->fname);
      
      if ((outfile = fopen (fname, "w")) == NULL) {
	printf("Cannot open output file %s\n", fname);
	continue;
      }
      
      for (a = dbx->indexCount-1; a >= 0; a--) {
	dbx_free(dbx, z);
	z = (DBXEMAIL*)dbx_get(dbx,a, DBX_FLAG_BODY);
	if (dbx_errno != DBX_NOERROR) {
	  dbx_perror("Email Read");
	  break;
	}
	if (z && z->email != NULL) {
	  date = FileTimeToUnixTime(&(z->date), NULL);
	  fprintf(outfile, "From %s %s", z->sender_address, ctime(&date)); //ctime adds \n
	  write_email(outfile, z->email);
	  fprintf(outfile, "\n\n");
	} else if (z == NULL) {
	  printf("DBX returned a NULL email\n");
	} else {
	  if (!quiet)
	    printf("Email has no body\n");
	}
      }
      if (!quiet)
	printf("%d emails processed\n", dbx->indexCount+1);
      totalEmails += (dbx->indexCount+1);
      fclose(outfile);
      dbx_close(dbx);
    }
  }

  if (!quiet)
    printf("Total Emails processed: %d\n", totalEmails);

  dbx_close(folders);
  return 0;
}
Пример #19
0
/*:   PrintSummaryInfo()
 *
 *
 ******************************************************************************/
void pascal PrintSummaryInfo( KVSummaryInfoEx *pSI, FILE *fpOut )
{
    int n;

   for ( n=0; n < pSI->nElem; ++n )
   {
      fprintf( fpOut, "%d %d ", pSI->pElem[n].isValid, pSI->pElem[n].type );

      switch( pSI->pElem[n].type )
      {
         case KV_String:
         {
            fprintf( fpOut, "\"%s\"", pSI->pElem[n].data );
         }
         break;

         case KV_Int4:
         {
            fprintf( fpOut, "%d", pSI->pElem[n].data );
         }
         break;

         case KV_DateTime:
         {
#if defined (_HPUX64i) || (_LNX64i) || (_XLNX64)
            long        rtnValue = 0;
#else
            LONGLONG    rtnValue = 0;
#endif  
            memcpy(&rtnValue, pSI->pElem[n].data, 8); 

            if(n == 9)
            {
#if !defined (_WINDOWS) && !defined(_ILNX21) && !defined(_LNX64i) && !defined(_XLNX64) && !defined (_FBSD32i)
  
                  /* if it is big endian, swap bytes */
                  LONGLONG NN = 0;
                  unsigned char *a, *b, *c;
                  a = (unsigned char *) &rtnValue;
                  b = a+ sizeof(LONGLONG) -1;
                  c = (unsigned char *) &NN;
 
                  while (a <= b)
                  {
                     *c = *b;
                     b--;
                     c++;
                  }
                  rtnValue = NN;
#endif
                 fprintf(fpOut, "%ld Minutes", (long)(rtnValue / 600000000));
            }
            else
            {
                 time_t timer;
                 char * timeStr = NULL;
                 char * linefeed = NULL;
                 FileTimeToUnixTime(rtnValue, &timer);
                 timeStr = ctime(&timer);
                 if ( timeStr )
                    linefeed = strchr(timeStr, '\012');
                 if ( linefeed != NULL)
                    *linefeed = '\0';
                 if ( timeStr )
                    fprintf(fpOut,"%s", timeStr);

            }
         }
         break;

         case KV_ClipBoard:
         {
            fprintf( fpOut, "Clipboard data" );
         }
         break;

         case KV_Bool:
         {
            fprintf( fpOut, "%s", pSI->pElem[n].data? "true": "false" );
         }
         break;

         case KV_Unicode:
         {
            int len = 0;
            BYTE *p = (BYTE *)pSI->pElem[n].data;

            if (p)
            {
               for (; *p!= 0 || *(p+1) != 0; p+=2,len+=2);
            }
                    
            fprintf( fpOut, "\"");
            if (p)
            {
               fwrite(pSI->pElem[n].data, 1, len+2, fpOut);
            }
            fprintf( fpOut, "\"");

         }
         break;

         case KV_IEEE8:
         {
            fprintf( fpOut, "%lf", *((double *)pSI->pElem[n].data) );
         }
         break;

         case KV_Other:
         {
            fprintf( fpOut, "other" );
         }
         break;

         default:
         {
            if ( pSI->pElem[n].isValid )
            {
               fprintf( fpOut, "Bad element type!" );
            }
         }
         break;
      }

      fprintf( fpOut, " %s\n", pSI->pElem[n].isValid? pSI->pElem[n].pcType : "(null)");

   }
}
Пример #20
0
STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
    IArchiveUpdateCallback *updateCallback)
{
  if (numItems != 1)
    return E_INVALIDARG;

  UInt64 size;
  Int32 newData;
  Int32 newProperties;
  UInt32 indexInArchive;
  UInt32 itemIndex = 0;
  if (!updateCallback)
    return E_FAIL;
  RINOK(updateCallback->GetUpdateItemInfo(0, &newData, &newProperties, &indexInArchive));

  CItem newItem = m_Item;
  newItem.ExtraFlags = 0;
  newItem.Flags = 0;
  if (IntToBool(newProperties))
  {
    FILETIME utcTime;
    UString name;
    {
      NCOM::CPropVariant prop;
      RINOK(updateCallback->GetProperty(itemIndex, kpidMTime, &prop));
      if (prop.vt != VT_FILETIME)
        return E_INVALIDARG;
      utcTime = prop.filetime;
    }
    {
      NCOM::CPropVariant prop;
      RINOK(updateCallback->GetProperty(itemIndex, kpidPath, &prop));
      if (prop.vt == VT_EMPTY)
        name.Empty();
      else if (prop.vt != VT_BSTR)
        return E_INVALIDARG;
      else
        name = prop.bstrVal;
    }
    {
      NCOM::CPropVariant prop;
      RINOK(updateCallback->GetProperty(itemIndex, kpidIsDir, &prop));
      if (prop.vt == VT_BOOL)
      {
        if (prop.boolVal != VARIANT_FALSE)
          return E_INVALIDARG;
      }
      else if (prop.vt != VT_EMPTY)
        return E_INVALIDARG;
    }
    if(!FileTimeToUnixTime(utcTime, newItem.Time))
      return E_INVALIDARG;
    newItem.Name = UnicodeStringToMultiByte(name, CP_ACP);
    int dirDelimiterPos = newItem.Name.ReverseFind(CHAR_PATH_SEPARATOR);
    if (dirDelimiterPos >= 0)
      newItem.Name = newItem.Name.Mid(dirDelimiterPos + 1);
    
    newItem.SetNameIsPresentFlag(!newItem.Name.IsEmpty());
  }

  if (IntToBool(newData))
  {
    {
      NCOM::CPropVariant prop;
      RINOK(updateCallback->GetProperty(itemIndex, kpidSize, &prop));
      if (prop.vt != VT_UI8)
        return E_INVALIDARG;
      size = prop.uhVal.QuadPart;
    }
    newItem.UnPackSize32 = (UInt32)size;

    UInt32 level = m_Level;
    if (level == 0xFFFFFFFF)
      level = 5;
    if (m_Method.NumPasses == 0xFFFFFFFF)
      m_Method.NumPasses = (level >= 9 ? kNumPassesX9 :
                           (level >= 7 ? kNumPassesX7 :
                                         kNumPassesX1));
    if (m_Method.NumFastBytes == 0xFFFFFFFF)
      m_Method.NumFastBytes = (level >= 9 ? kNumFastBytesX9 :
                              (level >= 7 ? kNumFastBytesX7 :
                                            kNumFastBytesX1));
    if (m_Method.Algo == 0xFFFFFFFF)
      m_Method.Algo =
                    (level >= 5 ? kAlgoX5 :
                                  kAlgoX1);

    return UpdateArchive(
        EXTERNAL_CODECS_VARS
        m_Stream, size, outStream, newItem, m_Method, itemIndex, updateCallback);
  }
    
  if (indexInArchive != 0)
    return E_INVALIDARG;

  if (IntToBool(newProperties))
  {
    COutArchive outArchive;
    outArchive.Create(outStream);
    outArchive.WriteHeader(newItem);
    RINOK(m_Stream->Seek(m_StreamStartPosition + m_DataOffset, STREAM_SEEK_SET, NULL));
  }
  else
  {
    RINOK(m_Stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL));
  }
  return CopyStreams(m_Stream, outStream);
}
Пример #21
0
    void next(size_t maxfilenamesize, char *outfilename, bool &isdir, rfs_fpos_t &filesizeout, time_t &outmodifiedtime)
    {
#ifdef _WIN32
        WIN32_FIND_DATA info;
        bool nocase = true;
#else
        struct dirent *entry;
        bool nocase = false;
#endif
        while (1) {
            *outfilename = 0;
            if (level<0)
                return;
            if (first) {
                first = false;
                handles = (_Handle *)realloc(handles,sizeof(_Handle)*(level+1));
#ifdef _WIN32
                path.appendc('*');
                handles[level] = FindFirstFile(path.str(), &info);
                path.decLength();
#else
                handles[level] = opendir(path.str());
                if (handles[level])
                    entry = readdir(handles[level]);  // don't need _r here
#endif
            }
            else {
#ifdef _WIN32
                if (!FindNextFile(handles[level], &info)) {
                    FindClose(handles[level]);
#else
                entry = readdir(handles[level]);  // don't need _r here
                if (!entry) {
                    closedir(handles[level]);
#endif
                    handles[level] = INVALID_HANDLE_VALUE;
                }
            }
            if (handles[level]!=INVALID_HANDLE_VALUE) {
                free(tail);
#ifdef _WIN32
                tail = _strdup(info.cFileName);
                isdir = ((info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0);
#else
                tail = _strdup(entry->d_name);
#endif
                size_t hs = path.length()-pathhead;
                size_t ts = strlen(tail);
                if (hs>=maxfilenamesize)
                    hs = maxfilenamesize-1;
                if (hs+ts>=maxfilenamesize)
                    ts = maxfilenamesize-1-hs;
                memcpy(outfilename,path.str()+pathhead,hs);
                memcpy(outfilename+hs,tail,ts);
                outfilename[hs+ts] = 0;
#ifndef _WIN32
                struct stat info;
                if (stat(outfilename, &info) != 0)  // will follow link
                    continue;
                isdir = S_ISDIR(info.st_mode);
#endif

                if ((strcmp(tail,".")==0)||(strcmp(tail,"..")==0))
                    continue;
                bool matched = (mask&&*mask)?WildMatch(tail,mask,nocase):false;
                if (!matched&&(!recursive||!isdir))
                    continue;
                if (isdir&&!recursive&&!includedirs)
                    continue;
                if (isdir) {
                    if (recursive) {
                        // add name
                        path.appends(tail);
                        if (path.lastChar()!='\\')
                            path.appendc('\\');
                        first = true;
                        level++;
                    }
                    if (!includedirs||!matched)
                        continue;
                    filesizeout = (rfs_fpos_t)0;
                }
                else {
#ifdef _WIN32
                    LARGE_INTEGER x;
                    x.LowPart = info.nFileSizeLow;
                    x.HighPart = info.nFileSizeHigh;
                    filesizeout = (rfs_fpos_t)x.QuadPart;
                }
                outmodifiedtime = FileTimeToUnixTime(&info.ftLastWriteTime);
#else
                    filesizeout = info.st_size;
                }
                outmodifiedtime = info.st_mtime;
#endif
                break;
            }
            level--;
            if (level<0)
                return;
            if (path.lastChar()=='\\')
                path.decLength();
            while (path.length()) {
                if (path.lastChar()=='\\')
                    break;
                path.decLength();

            }
        }
    }
Пример #22
0
int csync_vio_local_stat(const char *uri, csync_vio_file_stat_t *buf) {
    HANDLE h, hFind;
    FILETIME ftCreate, ftAccess, ftWrite;
    BY_HANDLE_FILE_INFORMATION fileInfo;
    WIN32_FIND_DATAW FindFileData;
    ULARGE_INTEGER FileIndex;
    mbchar_t *wuri = c_utf8_to_locale( uri );

    h = CreateFileW( wuri, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                     FILE_ATTRIBUTE_NORMAL+FILE_FLAG_BACKUP_SEMANTICS, NULL );
    if( h == INVALID_HANDLE_VALUE ) {
        CSYNC_LOG(CSYNC_LOG_PRIORITY_CRIT, "CreateFileW failed on %s", uri );
        errno = GetLastError();
        c_free_locale_string(wuri);
        return -1;
    }

    if(!GetFileInformationByHandle( h, &fileInfo ) ) {
        CSYNC_LOG(CSYNC_LOG_PRIORITY_CRIT, "GetFileInformationByHandle failed on %s", uri );
        errno = GetLastError();
        c_free_locale_string(wuri);
        CloseHandle(h);
        return -1;
    }

    buf->flags = CSYNC_VIO_FILE_FLAGS_NONE;
    do {
        // Check first if it is a symlink (code from c_islink)
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
            hFind = FindFirstFileW(wuri, &FindFileData );
            if (hFind !=  INVALID_HANDLE_VALUE) {
                if( (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
                        (FindFileData.dwReserved0 & IO_REPARSE_TAG_SYMLINK) ) {
                    buf->flags = CSYNC_VIO_FILE_FLAGS_SYMLINK;
                    buf->type = CSYNC_VIO_FILE_TYPE_SYMBOLIC_LINK;
                    break;
                }
            }
            FindClose(hFind);
        }
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DEVICE
                || fileInfo.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE
                || fileInfo.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
            buf->type = CSYNC_VIO_FILE_TYPE_UNKNOWN;
            break;
        }
        if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            buf->type = CSYNC_VIO_FILE_TYPE_DIRECTORY;
            break;
        }
        // fallthrough:
        buf->type = CSYNC_VIO_FILE_TYPE_REGULAR;
        break;
    } while (0);
    buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_FLAGS;
    buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;

    buf->device = fileInfo.dwVolumeSerialNumber;
    buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_DEVICE;

    /* Get the Windows file id as an inode replacement. */
    FileIndex.HighPart = fileInfo.nFileIndexHigh;
    FileIndex.LowPart = fileInfo.nFileIndexLow;
    FileIndex.QuadPart &= 0x0000FFFFFFFFFFFF;
    /* printf("Index: %I64i\n", FileIndex.QuadPart); */
    buf->inode = FileIndex.QuadPart;

    buf->size = (fileInfo.nFileSizeHigh * (int64_t)(MAXDWORD+1)) + fileInfo.nFileSizeLow;
    buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_SIZE;

    /* Get the file time with a win32 call rather than through stat. See
      * http://www.codeproject.com/Articles/1144/Beating-the-Daylight-Savings-Time-bug-and-getting
      * for deeper explanation.
      */
    if( GetFileTime(h, &ftCreate, &ftAccess, &ftWrite) ) {
        DWORD rem;
        buf->atime = FileTimeToUnixTime(&ftAccess, &rem);
        buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_ATIME;

        buf->mtime = FileTimeToUnixTime(&ftWrite, &rem);
        /* CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Local File MTime: %llu", (unsigned long long) buf->mtime ); */
        buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_MTIME;

        buf->ctime = FileTimeToUnixTime(&ftCreate, &rem);
        buf->fields |= CSYNC_VIO_FILE_STAT_FIELDS_CTIME;
    }

    CloseHandle(h);

    return 0;
}
Пример #23
0
csync_vio_file_stat_t *csync_vio_local_readdir(csync_vio_handle_t *dhandle) {

  dhandle_t *handle = NULL;
  csync_vio_file_stat_t *file_stat = NULL;
  ULARGE_INTEGER FileIndex;
  DWORD rem;

  handle = (dhandle_t *) dhandle;

  errno = 0;
  file_stat = csync_vio_file_stat_new();
  if (file_stat == NULL) {
      errno = ENOMEM;
      goto err;
  }
  file_stat->fields = CSYNC_VIO_FILE_STAT_FIELDS_NONE;

  // the win32 functions get the first valid entry with the opendir
  // thus we must not jump to next entry if it was the first find.
  if( handle->firstFind ) {
      handle->firstFind = 0;
  } else {
      if( FindNextFile(handle->hFind, &(handle->ffd)) == 0 ) {
          // might be error, check!
          int dwError = GetLastError();
          if (dwError != ERROR_NO_MORE_FILES) {
              errno = EACCES; // no more files is fine. Otherwise EACCESS
          }
          goto err;
      }
  }
  file_stat->name = c_utf8_from_locale(handle->ffd.cFileName);

  file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;
  if (handle->ffd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT
            && handle->ffd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) {
        file_stat->flags = CSYNC_VIO_FILE_FLAGS_SYMLINK;
        file_stat->type = CSYNC_VIO_FILE_TYPE_SYMBOLIC_LINK;
    } else if (handle->ffd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE
                || handle->ffd.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE
                || handle->ffd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
        file_stat->type = CSYNC_VIO_FILE_TYPE_UNKNOWN;
    } else if (handle->ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        file_stat->type = CSYNC_VIO_FILE_TYPE_DIRECTORY;
    } else {
        file_stat->type = CSYNC_VIO_FILE_TYPE_REGULAR;
    }

    file_stat->flags = CSYNC_VIO_FILE_FLAGS_NONE;
    /* Check for the hidden flag */
    if( handle->ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN ) {
        file_stat->flags |= CSYNC_VIO_FILE_FLAGS_HIDDEN;
    }

    file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_FLAGS;
    file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;

    file_stat->size = (handle->ffd.nFileSizeHigh * ((int64_t)(MAXDWORD)+1)) + handle->ffd.nFileSizeLow;
    file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_SIZE;

    file_stat->atime = FileTimeToUnixTime(&handle->ffd.ftLastAccessTime, &rem);
    file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_ATIME;

    file_stat->mtime = FileTimeToUnixTime(&handle->ffd.ftLastWriteTime, &rem);
      /* CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "Local File MTime: %llu", (unsigned long long) buf->mtime ); */
    file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_MTIME;

    file_stat->ctime = FileTimeToUnixTime(&handle->ffd.ftCreationTime, &rem);
    file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_CTIME;

    return file_stat;

err:
  SAFE_FREE(file_stat);

  return NULL;
}
Пример #24
0
void _ThumbCacheUpdateDirScan(FILE *tc, const char *dir) {
	unsigned int status;
	LPTCRECORD ptcrec;
	char *fn, relfn[MAX_PATH];
	int dirlen, len;
	time_t mtime;
#ifdef _WIN32
	HANDLE hFindFile;
	WIN32_FIND_DATA ffd;
#else
	DIR *dirp;
	struct stat st;
	struct dirent *entry;
#endif

	dirlen = strlen(dir);
	if (dirlen + 3 >= MAX_PATH) {
		fprintf(stderr, "ERROR: filename too long\n");
		return;
	}

	strcpy(relfn, dir);
#ifdef _WIN32
	strcpy(relfn + dirlen, "*");
	hFindFile = FindFirstFile(relfn, &ffd);
	if (hFindFile == INVALID_HANDLE_VALUE) {
		status = GetLastError();
		if (status != ERROR_FILE_NOT_FOUND)
			printerr("FindFirstFile");
		return;
	}

	do {
		fn = ffd.cFileName;
		if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && scan_recursive) {
#else
	dirp = opendir(relfn);
	if (!dirp) {
		perror("opendir");
		return;
	}

	while ((entry = readdir(dirp))) {
		if (lstat(entry->d_name, &st) == -1) {
			fprintf(stderr, "ERROR: couldn't stat %s, skipping\n", fn);
			continue;
		}

		fn = entry->d_name;
		if (S_ISDIR(st.st_mode) && scan_recursive) {
#endif
			if (!(fn[0] == '.' && (!fn[1] || (fn[1] == '.' && !fn[2])))) {
				len = dirlen + strlen(fn);
				if (len + 1 >= MAX_PATH) {
					fprintf(stderr, "ERROR: total rel path len of "
						"%s too long, skipping\n", fn);
					continue;
				}

				strcpy(relfn + dirlen, fn);
				relfn[len]     = PATH_SEPARATOR;
				relfn[len + 1] = '\0';

				_ThumbCacheUpdateDirScan(tc, relfn);
			}
		} else if (ImgIsImageFile(fn)) {
			len = dirlen + strlen(fn);
			if (len >= MAX_PATH) {
				fprintf(stderr, "ERROR: total rel path len of "
					"%s too long, skipping\n", fn);
				continue;
			}

#ifdef _WIN32
			mtime = FileTimeToUnixTime(ffd.ftLastWriteTime);
#else
			mtime = st.st_mtime;
#endif
			strcpy(relfn + dirlen, fn);
			fn = HtGetItem(cacheht, relfn);
			if (fn) {
				ptcrec = (LPTCRECORD)(fn - sizeof(TCRECORD));
				if (mtime != ptcrec->ent.mtime) {
					if (verbose)
						printf("Updating %s...\n", relfn);
					if (!ThumbCacheReplace(tc, relfn, ptcrec, mtime))
						printerr("ThumbCacheReplace");
				}
			} else {
				if (verbose)
					printf("Adding %s to thumb cache...\n", relfn);
				if (!ThumbCacheAdd(tc, relfn, mtime))
					printerr("ThumbCacheAdd");
				else
					nadded++;
			}
		}
#ifdef _WIN32
	} while (FindNextFile(hFindFile, &ffd));
	
	FindClose(hFindFile);
#else
	}

	if (closedir(dirp) == -1)
		perror("closedir");
#endif
}


float _ThumbCalcKey(int **tpixels) {
	unsigned int tr, tg, tb;
	float avg_r, avg_g, avg_b;
	int pixel, x, y;

	tr = 0;
	tg = 0;
	tb = 0;

	for (y = 0; y != THUMB_CY; y++) {
		for (x = 0; x != THUMB_CX; x++) {
			pixel = tpixels[y][x];
			tr += gdTrueColorGetRed(pixel);
			tg += gdTrueColorGetGreen(pixel);
			tb += gdTrueColorGetBlue(pixel);

		}
	}

	avg_r = (float)tr / (float)THUMB_NPIXELS;
	avg_g = (float)tg / (float)THUMB_NPIXELS;
	avg_b = (float)tb / (float)THUMB_NPIXELS;

	return (avg_r * avg_r) + (avg_g * avg_g) + (avg_b * avg_b);
}
Пример #25
0
//---------------------------------------------------------------------
// remove a file of the dir content - if present
fxp_name * Server::removeFile(bstring const & remotePath) {
  bstring path, file;
  file = splitPath(path, remotePath);
  DirCache::iterator i = dirCache.find(path);
  if (i == dirCache.end())
    return 0;

  my_fxp_names * dir = i->second;

  int count = dir->nnames;
  for (int i = 0; i < count; ++i) {
    fxp_name * fn = dir->names[i];
#ifdef UNICODE
    if (file == fn->ucFilename) {
#else
    if (file == fn->filename) {
#endif
      // not last -> replace current with last
      if (i + 1 < count) {
        dir->names[i] = dir->names[count - 1];
      }
      // and one less now
      --dir->nnames;

      return fn; // done
    }
  }

  return 0;
}

//---------------------------------------------------------------------
// add a file to the dir content - if not already there
void Server::insertFile(bstring const & remotePath, FILETIME * ft, unsigned long szLo, unsigned long szHi, char kind,
    bstring const & chmod) {
  bstring path, file;
  file = splitPath(path, remotePath);
  DirCache::iterator i = dirCache.find(path);
  if (i == dirCache.end())
    return;

#ifdef UNICODE
  dirCache.erase(i);
#else

  my_fxp_names * dir = i->second;

  int count = dir->nnames;
  for (int i = 0; i < count; ++i) {
    fxp_name * fn = dir->names[i];
    if (file == fn->filename) {
      // already there
      return;
    }
  }
  // create a new structure and fill it
  my_fxp_names * ndir = (my_fxp_names *) malloc(sizeof(my_fxp_names));
  ndir->names = (fxp_name **) malloc(sizeof(fxp_name*) * (count + 1));

  fxp_name * n = ndir->names[0] = (fxp_name *) malloc(sizeof(fxp_name));
  RtlZeroMemory(n, sizeof(fxp_name));

  FILETIME ft2;
  SYSTEMTIME st;
  if (ft) {
    FileTimeToSystemTime(ft, &st);
  } else {
    GetSystemTime(&st);
    SystemTimeToFileTime(&st, &ft2);
    ft = &ft2;
  }

  char buffer[32];
  sprintf(buffer, "%d ", szLo);
  std::string ln = kind + chmod + std::string(" 1 ? ? ") + buffer + " Jan  1 1990 " + file;
  n->longname = strdup(ln.c_str());
  n->filename = strdup(file.c_str());

  n->attrs.size.hi = szHi;
  n->attrs.size.lo = szLo;
  n->attrs.mtime = FileTimeToUnixTime(ft);

  for (int i = 0; i < count; ++i) {
    ndir->names[i + 1] = dir->names[i];
  }
  ndir->nnames = count + 1;

  i->second = ndir;
#endif
}