예제 #1
0
int my_open( const char *path, int mode, ... )
{
	DISABLE_ERRORS;
	int result;
	auto tpath = tstr(path);
	LPCTSTR p = MRP(tpath.get());

	// Windows "open" does not handle _O_CREAT and _O_BINARY as it should
	if(mode & _O_CREAT) {
		if(exists(p)) {
			result = _topen( p, mode & ~_O_CREAT );
			D(bug(TEXT("open-nocreat(%s,%s,%d) = %d\n"), tpath.get(), p, mode, result));
		} else {
			result = _tcreat( p, _S_IWRITE|_S_IREAD );
			if(result < 0) {
				make_folders(p);
				result = _tcreat( p, _S_IWRITE|_S_IREAD );
			}
			D(bug(TEXT("open-creat(%s,%s,%d) = %d\n"), tpath.get(), p, mode, result));
		}
	} else {
		result = _topen( p, mode );
		D(bug(TEXT("open(%s,%s,%d) = %d\n"), tpath.get(), p, mode, result));
	}
	if(result < 0) {
		my_errno = errno;
	} else {
		setmode(result, _O_BINARY);
		my_errno = 0;
	}
	RESTORE_ERRORS;
	return result;
}
예제 #2
0
파일: filesys.c 프로젝트: ctubio/alpine
int
our_open(char *path, int flags, mode_t mode)
{
#ifdef _WINDOWS
    LPTSTR p = NULL;
    int ret = -1;

    /*
     * Setting the _O_WTEXT flag when opening a file for reading
     * will cause us to read the first few bytes to check for
     * a BOM and to translate from that encoding if we find it.
     * This only works with stream I/O, not low-level read/write.
     *
     * When opening for writing the flag _O_U8TEXT will cause
     * us to put a UTF-8 BOM at the start of the file.
     *
     * O_TEXT will cause LF -> CRLF on output, opposite on input
     * O_BINARY suppresses that.
     * _O_U8TEXT implies O_TEXT.
     */

    p = utf8_to_lptstr((LPSTR) path);

    if(p){
	ret = _topen(p, flags, mode);
	fs_give((void **) &p);
    }

    return ret;
#else /* UNIX */
    return(open(fname_to_locale(path), flags, mode));
#endif /* UNIX */
}
예제 #3
0
// on PC Windows we must convert UTF8 filename into WCHAR* and use _wopen
int winpc_open(zzip_char_t* filename, int flags, ...)
{
  TCHAR wpath[MAX_PATH];
  utf2TCHAR(filename, wpath, MAX_PATH);
  
  return(_topen(wpath, flags));
}
예제 #4
0
void CAimProto::avatar_retrieval_handler(const char* sn, const char* hash, const char* data, int data_len)
{
	bool res = false;
	PROTO_AVATAR_INFORMATIONT AI = {0};
	AI.cbSize = sizeof(AI);

	AI.hContact = contact_from_sn(sn);
	
	if (data_len > 0)
	{
		const TCHAR *type; 
		AI.format = detect_image_type(data, type);
		get_avatar_filename(AI.hContact, AI.filename, SIZEOF(AI.filename), type);

		int fileId = _topen(AI.filename, _O_CREAT | _O_TRUNC | _O_WRONLY | O_BINARY,  _S_IREAD | _S_IWRITE);
		if (fileId >= 0)
		{
			_write(fileId, data, data_len);
			_close(fileId);
			res = true;

			char *my_sn = getSetting(AIM_KEY_SN);
			if (!_strcmps(sn, my_sn))
				CallService(MS_AV_REPORTMYAVATARCHANGED, (WPARAM)m_szModuleName, 0);
			mir_free(my_sn);
		}
//            else
//			    ShowError("Cannot set avatar. File '%s' could not be created/overwritten", file);
	}
	else
		LOG("AIM sent avatar of zero length for %s.(Usually caused by repeated request for the same icon)", sn);

	sendBroadcast(AI.hContact, ACKTYPE_AVATAR, res ? ACKRESULT_SUCCESS : ACKRESULT_FAILED, &AI, 0);
}
예제 #5
0
int filetransfer::create()
{
	if (fileId != -1)
		return fileId;

	TCHAR filefull[MAX_PATH];
	mir_sntprintf(filefull, _countof(filefull), _T("%s\\%s"), std.tszWorkingDir, std.tszCurrentFile);
	replaceStrT(std.tszCurrentFile, filefull);

	if (hWaitEvent != INVALID_HANDLE_VALUE)
		CloseHandle(hWaitEvent);
	hWaitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	if (ppro->ProtoBroadcastAck(std.hContact, ACKTYPE_FILE, ACKRESULT_FILERESUME, this, (LPARAM)&std))
		WaitForSingleObject(hWaitEvent, INFINITE);

	if (fileId == -1) {
		ppro->debugLog(_T("Saving to [%s]"), std.tszCurrentFile);
		fileId = _topen(std.tszCurrentFile, _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY, _S_IREAD | _S_IWRITE);
	}

	if (fileId == -1)
		ppro->debugLog(_T("Cannot create file '%s' during a file transfer"), filefull);
	else if (std.currentFileSize != 0)
		_chsize(fileId, std.currentFileSize);

	return fileId;
}
예제 #6
0
bool
File::ReadString(Path path, char *buffer, size_t size)
{
  assert(path != nullptr);
  assert(buffer != nullptr);
  assert(size > 0);

  int flags = O_RDONLY;
#ifdef O_NOCTTY
  flags |= O_NOCTTY;
#endif
#ifdef O_CLOEXEC
  flags |= O_CLOEXEC;
#endif

  int fd = _topen(path.c_str(), flags);
  if (fd < 0)
    return false;

  ssize_t nbytes = read(fd, buffer, size - 1);
  close(fd);
  if (nbytes < 0)
    return false;

  buffer[nbytes] = '\0';
  return true;
}
예제 #7
0
int
__gsh_open (char *path, int kind)
{
  int fd;
  int mode;
  int perm;
  TCHAR wpath[32768];

  if (kind > READ_MODE)
    {
      mode = O_WRONLY | O_CREAT | O_BINARY | O_NOINHERIT;
      if (kind == APPEND_MODE)
	{
	  mode = mode | O_APPEND;
	}
      perm = S_IWRITE;
    }
  else
    {
      perm = S_IREAD;
      mode = O_RDONLY | O_BINARY | O_NOINHERIT;
    }

  S2WSC (wpath, path, 32768);
  fd = _topen (wpath, mode, perm);
  return fd < 0 ? -1 : fd;
}
예제 #8
0
파일: creat.c 프로젝트: chunhualiu/OpenNT
int __cdecl _tcreat (
	const _TSCHAR *path,
	int pmode
	)
{
	/* creat is just the same as open... */
	return _topen(path, _O_CREAT + _O_TRUNC + _O_RDWR, pmode);
}
예제 #9
0
int filetransfer::create(void)
{
	fileId = _topen(std.tszCurrentFile, _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY, _S_IREAD | _S_IWRITE);

	if (fileId == -1)
		proto->MSN_ShowError("Cannot create file '%s' during a file transfer", std.tszCurrentFile);
	//	else if (std.currentFileSize != 0)
	//		_chsize(fileId, std.currentFileSize);

	return fileId;
}
예제 #10
0
int __cdecl _open_utf8(const char *path, int oflag, ...)
{
	va_list ap;
	int pmode = 0;
	CString strPath = DataToCString(path, -1, DTC_CODE_UTF8);
	
	va_start(ap, oflag);
	pmode = va_arg(ap, int);
	va_end(ap);
	
	return _topen(strPath, oflag, pmode);
}
예제 #11
0
bool ReadFile (const _TCHAR* FileName, std::string* pFileImage)
{

	if (!FileName || !pFileImage)
	{
		return (false);
	}

	pFileImage->erase ();

	int file = _topen (FileName, O_RDONLY | O_BINARY);
	
	if (-1 == file) 
	{
		return (false);
	}
	
	long f_size = _lseek (file, 0, SEEK_END);
	
	
	if (-1 == f_size) 
	{
		_close (file);
		return (false);
	}
	
	char* s =  new char[(static_cast<unsigned int>(f_size))];
	
	if (!s) 
	{
		_close (file);
		return (false);
	}
	
	int size = static_cast<unsigned int> (f_size);
	
	_lseek (file, 0, SEEK_SET);
	
	int r = static_cast<int> (_read (file, s, size));
	
	_close (file);

	if (r)
	{
		pFileImage->assign (s, size);
	}

	delete [] s;
	
	return (r != 0);
	
}
예제 #12
0
 CLIPPER  LLIBOPEN( void ){
    WORD i;
    if (PCOUNT() >= 1 && ISCHAR(1) && wLib == 0xffff){
       if ((wLib=_topen(_parc(1),0))!=0xffff){
          if (ScanLibOffsets()){
             _retl(TRUE);
             return;
          }
       }
    }
    _retl(FALSE);
    return;
 }
예제 #13
0
INT_PTR CMsnProto::SetAvatar(WPARAM, LPARAM lParam)
{
	TCHAR* szFileName = (TCHAR*)lParam;

	TCHAR tFileName[MAX_PATH];
	MSN_GetAvatarFileName(NULL, tFileName, _countof(tFileName), NULL);
	_tremove(tFileName);

	if (szFileName == NULL) {
		delSetting("PictObject");
		delSetting("AvatarHash");
		ForkThread(&CMsnProto::msn_storeAvatarThread, NULL);
	}
	else {
		int fileId = _topen(szFileName, _O_RDONLY | _O_BINARY, _S_IREAD);
		if (fileId < 0) return 1;

		size_t dwPngSize = _filelengthi64(fileId);
		unsigned char* pData = (unsigned char*)mir_alloc(dwPngSize);
		if (pData == NULL) {
			_close(fileId);
			return 2;
		}

		_read(fileId, pData, (unsigned)dwPngSize);
		_close(fileId);

		TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT];
		_tsplitpath(szFileName, drive, dir, fname, ext);

		MSN_SetMyAvatar(fname, pData, dwPngSize);

		StoreAvatarData* par = (StoreAvatarData*)mir_alloc(sizeof(StoreAvatarData));
		par->szName = mir_tstrdup(fname);
		par->data = pData;
		par->dataSize = dwPngSize;
		par->szMimeType = "image/png";

		ForkThread(&CMsnProto::msn_storeAvatarThread, par);
	}

	MSN_SetServerStatus(m_iStatus);
	return 0;
}
예제 #14
0
static void download_a_file( const char* local, void **state, const char *durl)
{
    char buffer[BUFSIZE+1];
    char path[256];
    char src_path[256];
    int  did;
    _TCHAR tlocal[256];

    csync_vio_method_handle_t *handle;
    ssize_t count;
    ssize_t overall_size = 0;
    csync_stat_t sb;

    /* Create the target path */
    strcpy( path, _credentials.oc_server );
    strcat( path, "/");
    strcat( path, (const char*) *state );
    strcat( path, "/");
    strcat( path, durl );

    strcpy( tlocal, "/tmp/");
    strcat( tlocal, local );
    did = _topen(tlocal, O_RDWR|O_CREAT, 0644);
    assert_true( did > -1 );

    handle = owncloud_open( path, O_RDONLY, 0644 );
    assert_int_not_equal( handle, NULL );

    while( (count = owncloud_read(handle, buffer, BUFSIZE)) > 0 ) {
        write( did, buffer, count );
        overall_size += count;
    }
    assert_int_equal( owncloud_close(handle), 0 );
    close(did);

    strcpy(src_path, TESTFILES_DIR);
    strcat(src_path, local);
    stat_local_file( &sb, src_path );

    /* assert the download size, it has to be the same. */
    assert_true( overall_size == sb.st_size );

}
예제 #15
0
파일: FileUtil.cpp 프로젝트: MindMil/XCSoar
bool
File::WriteExisting(const TCHAR *path, const char *value)
{
  assert(path != nullptr);
  assert(value != nullptr);

  int flags = O_WRONLY;
#ifdef O_NOCTTY
  flags |= O_NOCTTY;
#endif

  int fd = _topen(path, flags);
  if (fd < 0)
    return false;

  const size_t length = strlen(value);
  ssize_t nbytes = write(fd, value, length);
  return close(fd) == 0 && nbytes == (ssize_t)length;
}
예제 #16
0
int filetransfer::openNext(void)
{
	if (fileId != -1)
	{
		close();
		++std.currentFileNumber;
		++cf;
	}

	while (std.ptszFiles && std.ptszFiles[cf])
	{
		struct _stati64 statbuf;
		if (_tstati64(std.ptszFiles[cf], &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) == 0)
			break;

		++cf;
	}

	if (std.ptszFiles && std.ptszFiles[cf])
	{
		bCompleted = false;
		replaceStrT(std.tszCurrentFile, std.ptszFiles[cf]);
		fileId = _topen(std.tszCurrentFile, _O_BINARY | _O_RDONLY, _S_IREAD);
		if (fileId != -1)
		{
			std.currentFileSize = _filelengthi64(fileId);
			std.currentFileProgress = 0;

			p2p_sendmsgid = 0;
			p2p_byemsgid = 0;
			tType = SERVER_NOTIFICATION;
			bAccepted = false;

			mir_free(p2p_branch); p2p_branch = NULL;
			mir_free(p2p_callID); p2p_callID = NULL;
		}
		else
			proto->MSN_ShowError("Unable to open file '%s' for the file transfer, error %d", std.tszCurrentFile, errno);
	}

	return fileId;
}
예제 #17
0
bool
File::CreateExclusive(Path path)
{
  assert(path != nullptr);

  int flags = O_WRONLY | O_CREAT | O_EXCL;
#ifdef O_NOCTTY
  flags |= O_NOCTTY;
#endif
#ifdef O_CLOEXEC
  flags |= O_CLOEXEC;
#endif

  int fd = _topen(path.c_str(), flags, 0666);
  if (fd < 0)
    return false;

  close(fd);
  return true;
}
예제 #18
0
const char *TemplateHTMLBuilder::getFlashAvatar(const TCHAR *file, int index) {
	if (time(NULL) - flashAvatarsTime[index] > 600 || flashAvatars[index] == NULL) {
		if (flashAvatars[index] != NULL) {
			delete flashAvatars[index];
			flashAvatars[index] = NULL;
		}
		flashAvatarsTime[index] = time(NULL);
		int src = _topen(file, _O_BINARY | _O_RDONLY);
		if (src != -1) {
			char pBuf[2048];
			char *urlBuf;
			_read(src, pBuf, 2048);
			_close(src);
			urlBuf = strstr(pBuf, "<URL>");
			if(urlBuf) {
				flashAvatars[index]  = Utils::dupString(strtok(urlBuf + 5, "<\t\n\r"));
			}
		}
	}
	return flashAvatars[index];
}
예제 #19
0
bool RenameSync(const std::string &srcFilename, const std::string &destFilename)
{
	if (!Rename(srcFilename, destFilename))
		return false;
#ifdef _WIN32
	int fd = _topen(UTF8ToTStr(srcFilename).c_str(), _O_RDONLY);
	if (fd != -1)
	{
		_commit(fd);
		close(fd);
	}
#else
	char *path = strdup(srcFilename.c_str());
	FSyncPath(path);
	FSyncPath(dirname(path));
	free(path);
	path = strdup(destFilename.c_str());
	FSyncPath(dirname(path));
	free(path);
#endif
	return true;
}
예제 #20
0
const TCHAR* GetImageExt(CMString &fname)
{
	const TCHAR* ext = _T("");

	int fileId = _topen(fname.c_str(), O_RDONLY | _O_BINARY);
	if (fileId != -1) {
		BYTE buf[6];

		int bytes = _read(fileId, buf, sizeof(buf));
		if (bytes > 4) {
			if ( *(unsigned short*)buf == 0xd8ff )
				ext = _T("jpg");
			else if ( *(unsigned short*)buf == 0x4d42 )
				ext = _T("bmp");
			else if ( *(unsigned*)buf == 0x474e5089 )
				ext = _T("png");
			else if ( *(unsigned*)buf == 0x38464947 )
				ext = _T("gif");
		}
		_close(fileId);
	}
	return ext;
}
예제 #21
0
파일: dbgprint.cpp 프로젝트: kaina/sandbox
void init(int ot)
{
	m_dout = ot;

	if (m_dout == DOUT_FILE)
	{
		if (m_fd > 0)
			_close(m_fd);

#if _MSC_VER >= 1400
		errno_t e = _tsopen_s(&m_fd, _T("./debuglog.txt"), _O_APPEND|_O_CREAT|_O_TEXT|_O_WRONLY, _SH_DENYWR, _S_IWRITE);
		if (e != 0)
		{
			m_dout = DOUT_API;
			m_fd = -1;
		}
#else
		m_fd = _topen(_T("./debuglog.txt"), _O_APPEND|_O_CREAT|_O_TEXT|_O_WRONLY, _S_IWRITE);
		if (m_fd == -1)
			m_dout = DOUT_API;
#endif
	}
}
예제 #22
0
bool get_avatar_hash(const TCHAR* file, char* hash, char** data, unsigned short &size)
{
	int fileId = _topen(file, _O_RDONLY | _O_BINARY, _S_IREAD);
	if (fileId == -1) return false;

	long  lAvatar = _filelength(fileId);
	if (lAvatar <= 0)
	{
		_close(fileId);
		return false;
	}

	char* pResult = (char*)mir_alloc(lAvatar);
	int res = _read(fileId, pResult, lAvatar);
	_close(fileId);

	if (res <= 0)
	{
		mir_free(pResult);
		return false;
	}

	mir_md5_state_t state;
	mir_md5_init(&state);
	mir_md5_append(&state, (unsigned char*)pResult, lAvatar);
	mir_md5_finish(&state, (unsigned char*)hash);

	if (data)
	{
		*data = pResult;
		size = (unsigned short)lAvatar;
	}
	else
		mir_free(pResult);

	return true;
}
예제 #23
0
INT_PTR __cdecl CJabberProto::JabberSetAvatar(WPARAM, LPARAM lParam)
{
	TCHAR *tszFileName = (TCHAR*)lParam;

	if (m_bJabberOnline) {
		SetServerVcard(TRUE, tszFileName);
		SendPresence(m_iDesiredStatus, false);
	}
	else if (tszFileName == NULL || tszFileName[0] == 0) {
		// Remove avatar
		TCHAR tFileName[ MAX_PATH ];
		GetAvatarFileName(NULL, tFileName, MAX_PATH);
		DeleteFile(tFileName);

		delSetting("AvatarSaved");
		delSetting("AvatarHash");
	}
	else {
		int fileIn = _topen(tszFileName, O_RDWR | O_BINARY, S_IREAD | S_IWRITE);
		if (fileIn == -1) {
			mir_free(tszFileName);
			return 1;
		}

		long dwPngSize = _filelength(fileIn);
		char *pResult = new char[ dwPngSize ];
		if (pResult == NULL) {
			_close(fileIn);
			mir_free(tszFileName);
			return 2;
		}

		_read(fileIn, pResult, dwPngSize);
		_close(fileIn);

		BYTE digest[MIR_SHA1_HASH_SIZE];
		mir_sha1_ctx sha1ctx;
		mir_sha1_init(&sha1ctx);
		mir_sha1_append(&sha1ctx, (BYTE*)pResult, dwPngSize);
		mir_sha1_finish(&sha1ctx, digest);

		TCHAR tFileName[MAX_PATH];
		GetAvatarFileName(NULL, tFileName, MAX_PATH);
		DeleteFile(tFileName);

		char buf[MIR_SHA1_HASH_SIZE*2+1];
		bin2hex(digest, sizeof(digest), buf);

		m_options.AvatarType = ProtoGetBufferFormat(pResult);

		GetAvatarFileName(NULL, tFileName, MAX_PATH);
		FILE *out = _tfopen(tFileName, _T("wb"));
		if (out != NULL) {
			fwrite(pResult, dwPngSize, 1, out);
			fclose(out);
		}
		delete[] pResult;

		setString("AvatarSaved", buf);
	}

	return 0;
}
예제 #24
0
bool SmileyPackType::LoadSmileyFile(const CMString& filename, const CMString& packname, bool onlyInfo, bool noerr)
{
	Clear();

	if (filename.IsEmpty()) {
		m_Name = _T("Nothing loaded");
		return false;
	}

	CMString modpath;
	pathToAbsolute(filename, modpath);

	// Load xep file
	int fh = _topen(modpath.c_str(), _O_BINARY | _O_RDONLY);
	if (fh == -1) {
		if (!noerr) {
			static const TCHAR errmsg[] = LPGENT("Smiley pack %s for category \"%s\" not found.\nSelect correct smiley pack in the Options -> Customize -> Smileys.");
			TCHAR msgtxt[1024];
			mir_sntprintf(msgtxt, TranslateTS(errmsg), modpath.c_str(), packname);
			ReportError(msgtxt);
		}

		m_Name = _T("Nothing loaded");
		return false;
	}

	m_Filename = filename;

	// Find file size
	const long flen = _filelength(fh);

	// Allocate file buffer
	char* buf = new char[flen + sizeof(wchar_t)];

	// Read xep file in
	int len = _read(fh, buf, flen);
	*(wchar_t*)(buf + len) = 0;

	// Close file
	_close(fh);

	CMString tbuf;

	if (len > 2 && *(wchar_t*)buf == 0xfeff)
		tbuf = W2T_SM((wchar_t*)buf + 1);
	else if (len > 3 && buf[0] == '\xef' && buf[1] == '\xbb' && buf[2] == '\xbf')
		tbuf = W2T_SM(A2W_SM(buf + 3, CP_UTF8));
	else
		tbuf = A2T_SM(buf);

	delete[] buf;

	bool res;
	if (filename.Find(_T(".xep")) == -1)
		res = LoadSmileyFileMSL(tbuf, onlyInfo, modpath);
	else
		res = LoadSmileyFileXEP(tbuf, onlyInfo, modpath);

	if (errorFound)
		ReportError(TranslateT("There were problems loading smiley pack (it should be corrected).\nSee network log for details."));

	return res;
}
예제 #25
0
int CJabberProto::FileSendParse(JABBER_SOCKET s, filetransfer *ft, char* buffer, int datalen)
{
	char* p, *q, *t, *eob;
	char* str;
	int num;
	int currentFile;
	int fileId;
	int numRead;

	eob = buffer + datalen;
	p = buffer;
	num = 0;
	while (ft->state == FT_CONNECTING || ft->state == FT_INITIALIZING) {
		for (q = p; q + 1 < eob && (*q != '\r' || *(q + 1) != '\n'); q++);
		if (q + 1 >= eob)
			break;
		if ((str = (char*)mir_alloc(q - p + 1)) == NULL) {
			ft->state = FT_ERROR;
			break;
		}
		strncpy_s(str, q - p, p, _TRUNCATE);
		str[q - p] = '\0';
		debugLogA("FT Got: %s", str);
		if (ft->state == FT_CONNECTING) {
			// looking for "GET filename.ext HTTP/1.1"
			if (!strncmp(str, "GET ", 4)) {
				for (t = str + 4; *t != '\0' && *t != ' '; t++);
				*t = '\0';
				for (t = str + 4; *t != '\0' && *t == '/'; t++);
				ft->httpPath = mir_a2t(t);
				JabberHttpUrlDecode(ft->httpPath);
				ft->state = FT_INITIALIZING;
				debugLogA("Change to FT_INITIALIZING");
			}
		}
		else {	// FT_INITIALIZING
			if (str[0] == '\0') {
				struct _stati64 statbuf;

				mir_free(str);
				num += 2;

				currentFile = ft->std.currentFileNumber;
				TCHAR *t = _tcsrchr(ft->std.ptszFiles[currentFile], '\\');
				if (t != NULL)
					t++;
				else
					t = ft->std.ptszFiles[currentFile];

				if (ft->httpPath == NULL || mir_tstrcmp(ft->httpPath, t)) {
					if (ft->httpPath == NULL)
						debugLogA("Requested file name does not matched (httpPath == NULL)");
					else
						debugLog(_T("Requested file name does not matched ('%s' vs. '%s')"), ft->httpPath, t);
					ft->state = FT_ERROR;
					break;
				}
				debugLog(_T("Sending [%s]"), ft->std.ptszFiles[currentFile]);
				_tstati64(ft->std.ptszFiles[currentFile], &statbuf);	// file size in statbuf.st_size
				if ((fileId = _topen(ft->std.ptszFiles[currentFile], _O_BINARY | _O_RDONLY)) < 0) {
					debugLogA("File cannot be opened");
					ft->state = FT_ERROR;
					mir_free(ft->httpPath);
					ft->httpPath = NULL;
					break;
				}

				char fileBuffer[2048];
				int bytes = mir_snprintf(fileBuffer, _countof(fileBuffer), "HTTP/1.1 200 OK\r\nContent-Length: %I64u\r\n\r\n", statbuf.st_size);
				WsSend(s, fileBuffer, bytes, MSG_DUMPASTEXT);

				ft->std.flags |= PFTS_SENDING;
				ft->std.currentFileProgress = 0;
				debugLogA("Sending file data...");

				while ((numRead = _read(fileId, fileBuffer, 2048)) > 0) {
					if (Netlib_Send(s, fileBuffer, numRead, 0) != numRead) {
						ft->state = FT_ERROR;
						break;
					}
					ft->std.currentFileProgress += numRead;
					ft->std.totalProgress += numRead;
					ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std);
				}
				_close(fileId);
				if (ft->state != FT_ERROR)
					ft->state = FT_DONE;
				debugLogA("Finishing this file...");
				mir_free(ft->httpPath);
				ft->httpPath = NULL;
				break;
		}	}

		mir_free(str);
		q += 2;
		num += (q-p);
		p = q;
	}

	return num;
}
예제 #26
0
파일: file.cpp 프로젝트: Seldom/miranda-ng
int CAimProto::sending_file(file_transfer *ft, HANDLE hServerPacketRecver, NETLIBPACKETRECVER &packetRecv)
{
	debugLogA("P2P: Entered file sending thread.");

	bool failed = true;
	bool failed_conn = false;

	if (!setup_next_file_send(ft)) return 2;

	debugLogA("Sent file information to buddy.");
	//start listen for packets stuff

	for (;;) {
		int recvResult = packetRecv.bytesAvailable - packetRecv.bytesUsed;
		if (recvResult <= 0)
			recvResult = CallService(MS_NETLIB_GETMOREPACKETS, (WPARAM)hServerPacketRecver, (LPARAM)&packetRecv);
		if (recvResult == 0) {
			debugLogA("P2P: File transfer connection Error: 0");
			break;
		}
		if (recvResult == SOCKET_ERROR) {
			failed_conn = true;
			debugLogA("P2P: File transfer connection Error: -1");
			break;
		}
		if (recvResult > 0) {
			if (recvResult < 0x100) continue;

			oft2* recv_ft = (oft2*)&packetRecv.buffer[packetRecv.bytesUsed];

			unsigned short pkt_len = _htons(recv_ft->length);
			if (recvResult < pkt_len) continue;

			packetRecv.bytesUsed += pkt_len;
			unsigned short type = _htons(recv_ft->type);
			if (type == 0x0202 || type == 0x0207) {
				debugLogA("P2P: Buddy Accepts our file transfer.");

				int fid = _topen(ft->pfts.tszCurrentFile, _O_RDONLY | _O_BINARY, _S_IREAD);
				if (fid < 0) {
					report_file_error(ft->pfts.tszCurrentFile);
					return 2;
				}

				if (ft->pfts.currentFileProgress) _lseeki64(fid, ft->pfts.currentFileProgress, SEEK_SET);

				NETLIBSELECT tSelect = { 0 };
				tSelect.cbSize = sizeof(tSelect);
				tSelect.hReadConns[0] = ft->hConn;

				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);

				clock_t lNotify = clock();
				for (;;) {
					char buffer[4096];
					int bytes = _read(fid, buffer, sizeof(buffer));
					if (bytes <= 0) break;

					if (Netlib_Send(ft->hConn, buffer, bytes, MSG_NODUMP) <= 0) break;
					ft->pfts.currentFileProgress += bytes;
					ft->pfts.totalProgress += bytes;

					if (clock() >= lNotify) {
						ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
						if (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&tSelect)) break;

						lNotify = clock() + 500;
					}
				}
				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
				debugLogA("P2P: Finished sending file bytes.");
				_close(fid);
			}
			else if (type == 0x0204) {
				// Handle file skip case
				if (ft->pfts.currentFileProgress == 0) {
					ft->pfts.totalProgress += ft->pfts.currentFileSize;
				}

				debugLogA("P2P: Buddy says they got the file successfully");
				if ((ft->pfts.currentFileNumber + 1) < ft->pfts.totalFiles) {
					ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
					++ft->pfts.currentFileNumber; ++ft->cf;

					if (!setup_next_file_send(ft)) {
						report_file_error(ft->pfts.tszCurrentFile);
						return 2;
					}
				}
				else {
					failed = _htonl(recv_ft->recv_bytes) != ft->pfts.currentFileSize;
					break;
				}
			}
			else if (type == 0x0205) {
				recv_ft = (oft2*)packetRecv.buffer;
				recv_ft->type = _htons(0x0106);

				ft->pfts.currentFileProgress = _htonl(recv_ft->recv_bytes);
				if (aim_oft_checksum_file(ft->pfts.tszCurrentFile, ft->pfts.currentFileProgress) != _htonl(recv_ft->recv_checksum)) {
					ft->pfts.currentFileProgress = 0;
					recv_ft->recv_bytes = 0;
				}

				debugLogA("P2P: Buddy wants us to start sending at a specified file point. (%I64u)", ft->pfts.currentFileProgress);
				if (Netlib_Send(ft->hConn, (char*)recv_ft, _htons(recv_ft->length), 0) <= 0) break;

				ft->pfts.totalProgress += ft->pfts.currentFileProgress;
				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
			}
		}
	}

	ft->success = !failed;
	return failed ? (failed_conn ? 1 : 2) : 0;
}
예제 #27
0
파일: file.cpp 프로젝트: Seldom/miranda-ng
int CAimProto::receiving_file(file_transfer *ft, HANDLE hServerPacketRecver, NETLIBPACKETRECVER &packetRecv)
{
	debugLogA("P2P: Entered file receiving thread.");
	bool failed = true;
	bool failed_conn = false;
	bool accepted_file = false;
	int fid = -1;

	oft2 *oft = NULL;

	ft->pfts.tszWorkingDir = mir_utf8decodeT(ft->file);

	//start listen for packets stuff
	for (;;) {
		int recvResult = packetRecv.bytesAvailable - packetRecv.bytesUsed;
		if (recvResult <= 0)
			recvResult = CallService(MS_NETLIB_GETMOREPACKETS, (WPARAM)hServerPacketRecver, (LPARAM)&packetRecv);
		if (recvResult == 0) {
			debugLogA("P2P: File transfer connection Error: 0");
			break;
		}
		if (recvResult == SOCKET_ERROR) {
			failed_conn = true;
			debugLogA("P2P: File transfer connection Error: -1");
			break;
		}
		if (recvResult > 0) {
			if (!accepted_file) {
				if (recvResult < 0x100) continue;

				oft2* recv_ft = (oft2*)&packetRecv.buffer[packetRecv.bytesUsed];
				unsigned short pkt_len = _htons(recv_ft->length);

				if (recvResult < pkt_len) continue;
				packetRecv.bytesUsed += pkt_len;

				unsigned short type = _htons(recv_ft->type);
				if (type == 0x0101) {
					debugLogA("P2P: Buddy Ready to begin transfer.");
					oft = (oft2*)mir_realloc(oft, pkt_len);
					memcpy(oft, recv_ft, pkt_len);
					memcpy(oft->icbm_cookie, ft->icbm_cookie, 8);

					int buflen = pkt_len - 0x100 + 64;
					char *buf = (char*)mir_calloc(buflen + 2);
					unsigned short enc;

					ft->pfts.currentFileSize = _htonl(recv_ft->size);
					ft->pfts.totalBytes = _htonl(recv_ft->total_size);
					ft->pfts.currentFileTime = _htonl(recv_ft->mod_time);
					memcpy(buf, recv_ft->filename, buflen);
					enc = _htons(recv_ft->encoding);

					TCHAR *name;
					if (enc == 2) {
						wchar_t* wbuf = (wchar_t*)buf;
						wcs_htons(wbuf);
						for (wchar_t *p = wbuf; *p; ++p) { if (*p == 1) *p = '\\'; }
						name = mir_u2t(wbuf);
					}
					else {
						for (char *p = buf; *p; ++p) { if (*p == 1) *p = '\\'; }
						name = mir_a2t(buf);
					}

					mir_free(buf);

					TCHAR fname[256];
					mir_sntprintf(fname, _T("%s%s"), ft->pfts.tszWorkingDir, name);
					mir_free(name);
					mir_free(ft->pfts.tszCurrentFile);
					ft->pfts.tszCurrentFile = mir_tstrdup(fname);

					ResetEvent(ft->hResumeEvent);
					if (ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FILERESUME, ft, (LPARAM)&ft->pfts))
						WaitForSingleObject(ft->hResumeEvent, INFINITE);

					if (ft->pfts.tszCurrentFile) {
						TCHAR* dir = get_dir(ft->pfts.tszCurrentFile);
						CreateDirectoryTreeT(dir);
						mir_free(dir);

						oft->type = _htons(ft->pfts.currentFileProgress ? 0x0205 : 0x0202);

						const int flag = ft->pfts.currentFileProgress ? 0 : _O_TRUNC;
						fid = _topen(ft->pfts.tszCurrentFile, _O_CREAT | _O_WRONLY | _O_BINARY | flag, _S_IREAD | _S_IWRITE);

						if (fid < 0) {
							report_file_error(fname);
							break;
						}

						accepted_file = ft->pfts.currentFileProgress == 0;

						if (ft->pfts.currentFileProgress) {
							bool the_same;
							oft->recv_bytes = _htonl(ft->pfts.currentFileProgress);
							oft->recv_checksum = _htonl(aim_oft_checksum_file(ft->pfts.tszCurrentFile));
							the_same = oft->size == oft->recv_bytes && oft->checksum == oft->recv_checksum;
							if (the_same) {
								ft->pfts.totalProgress += ft->pfts.currentFileProgress;
								oft->type = _htons(0x0204);
								_close(fid);

								ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
								++ft->pfts.currentFileNumber;
								ft->pfts.currentFileProgress = 0;
							}
						}
					}
					else {
						oft->type = _htons(0x0204);

						ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
						++ft->pfts.currentFileNumber;
						ft->pfts.currentFileProgress = 0;
					}

					if (Netlib_Send(ft->hConn, (char*)oft, pkt_len, 0) == SOCKET_ERROR)
						break;

					if (ft->pfts.currentFileNumber >= ft->pfts.totalFiles && _htons(oft->type) == 0x0204) {
						failed = false;
						break;
					}
				}
				else if (type == 0x0106) {
					oft = (oft2*)mir_realloc(oft, pkt_len);
					memcpy(oft, recv_ft, pkt_len);

					ft->pfts.currentFileProgress = _htonl(oft->recv_bytes);
					ft->pfts.totalProgress += ft->pfts.currentFileProgress;

					_lseeki64(fid, ft->pfts.currentFileProgress, SEEK_SET);
					accepted_file = true;

					oft->type = _htons(0x0207);
					if (Netlib_Send(ft->hConn, (char*)oft, pkt_len, 0) == SOCKET_ERROR)
						break;
				}
				else break;
			}
			else {
				packetRecv.bytesUsed = packetRecv.bytesAvailable;
				_write(fid, packetRecv.buffer, packetRecv.bytesAvailable);
				ft->pfts.currentFileProgress += packetRecv.bytesAvailable;
				ft->pfts.totalProgress += packetRecv.bytesAvailable;
				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
				if (ft->pfts.currentFileSize == ft->pfts.currentFileProgress) {
					oft->type = _htons(0x0204);
					oft->recv_bytes = _htonl(ft->pfts.currentFileProgress);
					oft->recv_checksum = _htonl(aim_oft_checksum_file(ft->pfts.tszCurrentFile));

					debugLogA("P2P: We got the file successfully");
					Netlib_Send(ft->hConn, (char*)oft, _htons(oft->length), 0);
					if (_htons(oft->num_files_left) == 1) {
						failed = false;
						break;
					}
					else {
						accepted_file = false;
						_close(fid);

						ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
						++ft->pfts.currentFileNumber;
						ft->pfts.currentFileProgress = 0;
					}
				}
			}
		}
	}

	if (accepted_file) _close(fid);
	mir_free(oft);

	ft->success = !failed;
	return failed ? (failed_conn ? 1 : 2) : 0;
}
예제 #28
0
INT_PTR CAimProto::SetAvatar(WPARAM, LPARAM lParam)
{
	TCHAR *szFileName = (TCHAR*)lParam;

	if (m_state != 1)
		return 1;

	if (szFileName == NULL) {
		aim_ssi_update(m_hServerConn, m_seqno, true);
		aim_delete_avatar_hash(m_hServerConn, m_seqno, 1, 1, m_avatar_id_sm);
		aim_delete_avatar_hash(m_hServerConn, m_seqno, 1, 12, m_avatar_id_lg);
		aim_ssi_update(m_hServerConn, m_seqno, false);

		avatar_request_handler(NULL, NULL, 0);
	}
	else {
		char hash[16], hash1[16], *data, *data1 = NULL;
		unsigned short size, size1 = 0;

		if (!get_avatar_hash(szFileName, hash, &data, size)) {
			mir_free(hash);
			return 1;
		}

		rescale_image(data, size, data1, size1);

		if (size1) {
			mir_md5_state_t state;
			mir_md5_init(&state);
			mir_md5_append(&state, (unsigned char*)data1, size1);
			mir_md5_finish(&state, (unsigned char*)hash1);

			mir_free(m_hash_lg); m_hash_lg = bytes_to_string(hash, sizeof(hash));
			mir_free(m_hash_sm); m_hash_sm = bytes_to_string(hash1, sizeof(hash1));

			aim_ssi_update(m_hServerConn, m_seqno, true);
			aim_set_avatar_hash(m_hServerConn, m_seqno, 1, 1, m_avatar_id_sm, 16, hash1);
			aim_set_avatar_hash(m_hServerConn, m_seqno, 1, 12, m_avatar_id_lg, 16, hash);
			aim_ssi_update(m_hServerConn, m_seqno, false);
		}
		else {
			mir_free(m_hash_lg); m_hash_lg = NULL;
			mir_free(m_hash_sm); m_hash_sm = bytes_to_string(hash, sizeof(hash1));

			aim_ssi_update(m_hServerConn, m_seqno, true);
			aim_set_avatar_hash(m_hServerConn, m_seqno, 1, 1, m_avatar_id_sm, 16, hash);
			aim_delete_avatar_hash(m_hServerConn, m_seqno, 1, 12, m_avatar_id_lg);
			aim_ssi_update(m_hServerConn, m_seqno, false);
		}

		avatar_request_handler(NULL, NULL, 0);

		avatar_up_req *req = new avatar_up_req(data, size, data1, size1);
		ForkThread(&CAimProto::avatar_upload_thread, req);

		TCHAR tFileName[MAX_PATH];
		TCHAR *ext = _tcsrchr(szFileName, '.');
		get_avatar_filename(NULL, tFileName, _countof(tFileName), ext);
		int fileId = _topen(tFileName, _O_CREAT | _O_TRUNC | _O_WRONLY | O_BINARY, _S_IREAD | _S_IWRITE);
		if (fileId < 0) {
			char errmsg[512];
			mir_snprintf(errmsg, "Cannot store avatar. File '%s' could not be created/overwritten", tFileName);
			ShowPopup(errmsg, ERROR_POPUP);
			return 1;
		}
		_write(fileId, data, size);
		_close(fileId);
	}
	return 0;
}
예제 #29
0
int csync_exclude_load(const char *fname, c_strlist_t **list) {
  int fd = -1;
  int i = 0;
  int rc = -1;
  int64_t size;
  char *buf = NULL;
  char *entry = NULL;
  mbchar_t *w_fname;

  if (fname == NULL) {
      return -1;
  }

#ifdef _WIN32
  _fmode = _O_BINARY;
#endif

  w_fname = c_utf8_path_to_locale(fname);
  if (w_fname == NULL) {
      return -1;
  }

  fd = _topen(w_fname, O_RDONLY);
  c_free_locale_string(w_fname);
  if (fd < 0) {
    return -1;
  }

  size = lseek(fd, 0, SEEK_END);
  if (size < 0) {
    rc = -1;
    goto out;
  }
  lseek(fd, 0, SEEK_SET);
  if (size == 0) {
    rc = 0;
    goto out;
  }
  buf = c_malloc(size + 1);
  if (read(fd, buf, size) != size) {
    rc = -1;
    goto out;
  }
  buf[size] = '\0';

  /* FIXME: Use fgets and don't add duplicates */
  entry = buf;
  for (i = 0; i < size; i++) {
    if (buf[i] == '\n' || buf[i] == '\r') {
      if (entry != buf + i) {
        buf[i] = '\0';
        if (*entry != '#') {
          const char *unescaped = csync_exclude_expand_escapes(entry);
          rc = _csync_exclude_add(list, unescaped);
          if( rc == 0 ) {
              CSYNC_LOG(CSYNC_LOG_PRIORITY_TRACE, "Adding entry: %s", unescaped);
          }
          SAFE_FREE(unescaped);
          if (rc < 0) {
              goto out;
          }
        }
      }
      entry = buf + i + 1;
    }
  }

  rc = 0;
out:
  SAFE_FREE(buf);
  close(fd);
  return rc;
}
예제 #30
0
static INT_PTR makeAvatar(WPARAM wParam, LPARAM)
{
	debug("Searching for flash avatar...\n");
	FLASHAVATAR* hFA = (FLASHAVATAR*)wParam;

	PROTO_AVATAR_INFORMATIONT AI = {0};
	AI.cbSize = sizeof(AI);
	AI.hContact = hFA->hContact;
	AI.format = PA_FORMAT_UNKNOWN;

	flash_avatar_item key(hFA->hContact, *hFA, NULL);

	bool avatarOK = false;
	if(hFA->hContact)
		avatarOK = (int)CallProtoService(key.getProto(), PS_GETAVATARINFOT, 0, (LPARAM)&AI) == GAIR_SUCCESS;
	else {
		avatarOK = (int)CallProtoService(key.getProto(), PS_GETMYAVATART, (WPARAM)AI.filename, (LPARAM)255) == 0;
		if(avatarOK) {
			TCHAR* ext = _tcsrchr(AI.filename, _T('.'));
			if(ext && (_tcsicmp(ext, _T(".xml")) == 0))
				AI.format = PA_FORMAT_XML;
		}
	}

	if (!avatarOK) return 0;
	debug("Avatar found...\n");

	TCHAR url[MAX_PATH];
	switch(AI.format) {
		case PA_FORMAT_SWF:
			_tcsncpy(url, AI.filename, SIZEOF(url));
			break;
		case PA_FORMAT_XML: {
			int src = _topen(AI.filename, _O_BINARY | _O_RDONLY);
			if(src != -1) {
				char pBuf[2048];
				char* urlBuf;
				_read(src, pBuf, sizeof(pBuf));
				_close(src);

				urlBuf = strstr(pBuf, "<URL>");
				if(urlBuf)
					_tcsncpy(url, _A2T(strtok(urlBuf + 5, "\r\n <")), SIZEOF(url));
 				else
 					return 0;
 			} else {
 				return 0;
 			}
 			break;
 		}
 		default:
 			destroyAvatar(wParam, 0);
 			return 0;
	}

	Lock l(cs);
	flash_avatar_item *item = FlashList.find(&key);
	if (item) {
		debug("Flash already exists...\n");
		hFA->hWindow = item->hFA.hWindow;
		ShowWindow(hFA->hWindow, SW_SHOW);

		if ( _tcsicmp(item->hFA.cUrl, url) != 0) {
			debug("Refreshing flash...\n");
			IShockwaveFlash* flash = item->pFlash;
			mir_free(item->hFA.cUrl);
			FlashList.remove(item);
			delete item;

			prepareFlash(key.getProto(), url, *hFA, flash);
		}
	}
	else {
		debug("Creating new flash...\n");
		RECT rc;
		GetWindowRect(hFA->hParentWindow, &rc);
		hFA->hWindow = CreateWindowEx(WS_EX_TOPMOST, _T("AtlAxWin"), _T(""), WS_VISIBLE | WS_CHILD, 0, 0, rc.right - rc.left, rc.bottom - rc.top, hFA->hParentWindow, (HMENU) 0, g_hInst, NULL);

		IShockwaveFlash* flash = NULL;
		debug("Creating flash instance...\n");
		CoCreateInstance(__uuidof(ShockwaveFlash),0,CLSCTX_ALL, __uuidof(IShockwaveFlash), (void **)&flash);
		debug("Initialized.\n");

		prepareFlash(key.getProto(), url, *hFA, flash);
	}
	return 0;
}