示例#1
0
/*
 * vislib::sys::Path::GetUserHomeDirectoryA
 */
vislib::StringA vislib::sys::Path::GetUserHomeDirectoryA(void) {
#ifdef _WIN32
    StringA retval;

    if (FAILED(::SHGetFolderPathA(NULL, CSIDL_PERSONAL, NULL, 0, 
            retval.AllocateBuffer(MAX_PATH)))) {
        throw SystemException(ERROR_NOT_FOUND, __FILE__, __LINE__);
    }

#else /* _WIN32 */
    char *path = getenv("HOME"); // Crowbar

    if (path == NULL) {
        throw SystemException(ENOENT, __FILE__, __LINE__);
    }

    StringA retval(path);
#endif /* _WIN32 */

    if (!retval.EndsWith(SEPARATOR_A)) {
        retval += SEPARATOR_A;
    }

    return retval;
}
void NewsAccount::GetList()
{
	char* request = "LIST\r\n";
	m_pSocket->Write(request, strlen(request));
	StringA response = m_pSocket->ReadLine();

	while (1)
	{
		StringA line = m_pSocket->ReadLine();
		if (!strcmp(line.c_str(), "."))
		{
			break;
		}

		char group[1024];
		int last;
		int first;
		char p;
		sscanf(line.c_str(), "%s", group, &last, &first, &p);

		TRACE("%s\n", group);

		Record pRecord = m_list.NewRecord();

		pRecord.get_Fields()[1].SetData(group);

		pRecord.Update();
	}
}
示例#3
0
//---------------------------------------------------------------------------
static void _FileIterator_BuildFilePathIfNeeded (StringA& strFilePath, const StringA& strDir, const StringA& strName)
{
  if (strFilePath.isEmpty())
  {
    strFilePath.grow(strDir.length() + strName.length() + 2, false);
    strFilePath = strDir;
    strFilePath.pathAppend(strName);
  }
}
示例#4
0
/*
 * vislib::sys::Path::IsRelative
 */
bool vislib::sys::Path::IsRelative(const StringA& path) {
#ifdef _WIN32
    return (::PathIsRelativeA(path.PeekBuffer()) != FALSE)
        || path.IsEmpty()
        || ((path.PeekBuffer()[0] == SEPARATOR_A) && (path.PeekBuffer()[1] != SEPARATOR_A));
#else /* _WIN32 */
    return !path.StartsWith(SEPARATOR_A);
#endif /* _WIN32 */
}
示例#5
0
/*
 * vislib::net::Socket::BindToDevice
 */
void vislib::net::Socket::BindToDevice(const StringA& name) {
#ifndef _WIN32
    struct ifreq interface;

    ::strncpy(interface.ifr_ifrn.ifrn_name, name.PeekBuffer(), 
        name.Length() + 1);

    if (::setsockopt(this->handle, SOL_SOCKET, SO_BINDTODEVICE, &interface,
            sizeof(interface)) == -1) {
        throw SocketException(__FILE__, __LINE__);
    }
#endif /* !_WIN32 */
}
示例#6
0
//---------------------------------------------------------------------------
void ConfigFileRo::load (const char* pszPath)
{
  StringAVec vecLines;

  // reset
  m_Settings.clear();

  // check file
  if (!FileSystem::doesExist(pszPath))
    GLB_THROWEXCODE(EXCODE_FILE_DOESNTEXIST);
  if (FileSystem::getSize(pszPath) > std::numeric_limits<uint32>::max())
    GLB_THROWEXCODE(EXCODE_MEMORY); // file is too big

  // extract file content
  {
    uint32  uiSize = (uint32)FileSystem::getSize(pszPath); // it is safe to cast-down here
    StringA strLines;
    byte*   pBuffer;

    pBuffer = (byte*)strLines.acquireBuffer(uiSize, false);
    FileSystem::extractContent(pszPath, pBuffer, uiSize);
    strLines.releaseBuffer();

    strLines.trimWhitespaces();
    strLines.explodeWithOneOf(vecLines, "\r\n");
  }

  // parse lines
  for (uint i = 0; i < vecLines.size(); ++i)
  {
    StringAVec vecL;

    // skip empty and comment lines
    vecLines[i].trimWhitespaces();
    if (vecLines[i].isEmpty() || vecLines[i][0] == '#')
      continue;

    // break key-value pair
    vecLines[i].explodeWithOneOf(vecL, "\t ", 2);
    if (vecL.size() >= 1)
    {
      if (vecL.size() < 2)
        vecL.push_back(StringA());
      if (m_Settings.find(vecL[0]) != m_Settings.end())
        GLB_LOGWARN("Duplicated setting name \"%s\" in config file \"%s\" !", vecL[0].c_str(), pszPath);

      m_Settings.insert(Settings::value_type(vecL[0], vecL[1]));
    }
  }
}
	StringA ReadLine()
	{
		StringA str;

		while (1)
		{
			char c;
			if (Read(&c, 1) != 1)
				break;
			if (c == '\r')
			{
				char c2;
				if (Read(&c2, 1) != 1)
					break;
				if (c2 == '\n')
				{
					break;
				}
				else
				{
					/*
					if (str.length() == 512)
						throw -1;
						*/
					str += c;

					/*
					if (str.length() == 512)
						throw -1;
						*/
					str += c2;
				}
			}
			else
			{
				/*
				if (str.length() == 4096)
					throw -1;
					*/
				str += c;
			}
		}

		TRACE("%s\n", str.c_str());
		return str;
	}
示例#8
0
/*
 * vislib::sys::Path::Concatenate
 */
vislib::StringA vislib::sys::Path::Concatenate(const StringA& lhs,
        const StringA& rhs, const bool canonicalise) {
    StringA retval(lhs);

    if (lhs.EndsWith(SEPARATOR_A) && rhs.StartsWith(SEPARATOR_A)) {
        retval.Append(rhs.PeekBuffer() + 1);

    } else if (!lhs.EndsWith(SEPARATOR_A) && !rhs.StartsWith(SEPARATOR_A)) {
        retval.Append(SEPARATOR_A);
        retval.Append(rhs);

    } else {
        retval.Append(rhs);
    }

    return canonicalise ? Path::Canonicalise(retval) : retval;
}
void ViewOfCollection2::Build()
{
	ASSERT(0);
#if 0
	UI::TreeControl* pTree = new UI::TreeControl;

	pTree->AddColumn(new UI::TextString(WSTR("Name")));
	//pTree->m_treeHeader->AddColumn(new UI::TextString(L"Value"));

	UI::TreeItemChildren* children = new UI::TreeItemChildren(pTree);
	unsigned long count = m_pCollection->GetCount();
	for (int i = 0; i < count; i++)
	{
		Object* child = m_pCollection->GetItem(i);

		StringA* classname = child->GetType()->m_qname;
		/*
		{
			void* vtable = *(void**)child.m_p;
			rti* p3 = ((rti**)vtable)[-1];

			int count = p3->m_classHierarchyDescriptor->count;
			BaseClassDescriptor** table = p3->m_classHierarchyDescriptor->m_baseClassArray;

			Type_Info* ti = (Type_Info*)table[0]->typedesc;
			classname = ti->name() + strlen("class ");
		}
		*/

		UI::TreeItem* row = new UI::TreeItem(pTree);

		m_rows.Add(row);

		row->AppendColumnCell(new UI::TextString(classname->ToStringW()));

		children->AppendItem(row);
	}

	pTree->set_Children(children);

	set_VisualTree(pTree);
#endif
}
示例#10
0
void NewsAccount::Connect()
{
	int port = 119;
	m_pSocket = new NNTPClient;
	m_pSocket->Create();
	m_pSocket->Connect(m_server.c_str(), port);

	{
		StringA response = m_pSocket->ReadLine();
	}
};
示例#11
0
void Server::loadConfig(const IniConfig::Section& sect) {
	StringA clientPage;
	StringA helpdir;
	StringA rpclogfile;


	FilePath p(App::current().getAppPathname());
	Config cfg;

	sect.get(clientPage, "clientPage");
	if (!clientPage.empty()) {
		cfg.clientPage = p / clientPage;
	}
	sect.get(helpdir,"helpDir");
	if (!helpdir.empty()) {
		cfg.helpDir = p / helpdir;
	}
	sect.get(rpclogfile,"rpcLog");
	if (!rpclogfile.empty()) {
		cfg.logFile = p / rpclogfile;
	}


	StringA corsOrigin;
	bool corsEnable = sect.get(corsOrigin, "allowCORSOrigins");
	if (corsEnable) cfg.corsOrigin = corsOrigin;
	sect.get(cfg.developMode, "developMode");
	sect.get(cfg.enableMulticall, "multicall");
	sect.get(cfg.enableListMethods, "listMethods");
	sect.get(cfg.enableStats, "enableStats");
	sect.get(cfg.enableWebSockets, "enableWebsockets");

	loadConfig(cfg);

}
示例#12
0
/*
 * vislib::sys::Path::PurgeDirectory
 */
void vislib::sys::Path::PurgeDirectory(const StringA& path, bool recursive) {
    StringA fullpath = Resolve(path);
    if (!fullpath.EndsWith(SEPARATOR_A)) fullpath += SEPARATOR_A;
    DirectoryIteratorA iter(fullpath);

    while (iter.HasNext()) {
        DirectoryEntryA entry = iter.Next();
        if (entry.Type == DirectoryEntryA::FILE) {
            vislib::sys::File::Delete(fullpath + entry.Path);

        } else
        if (entry.Type == DirectoryEntryA::DIRECTORY) {
            if (recursive) {
                DeleteDirectory(fullpath + entry.Path, true);
            }

        } else {
            ASSERT(false); // DirectoryEntry is something unknown to this 
                           // implementation. Check DirectoryIterator for 
                           // changes.
        }
    }
}
示例#13
0
/*
 * vislib::sys::Path::Resolve
 */
vislib::StringA vislib::sys::Path::Resolve(StringA path, StringA basepath) {
    // TODO: Windows shell API resolve does not work in the expected
    // way, so we use the same manual approach for Windows and Linux.

#ifdef _WIN32
    /* Replace unchefmäßige path separators. */
    basepath.Replace('/', SEPARATOR_A);
    path.Replace('/', SEPARATOR_A);
#endif /* _WIN32 */

    if (Path::IsRelative(basepath)) {
        basepath = Resolve(basepath);
    }

    if (path.IsEmpty()) {
        /* Path is empty, i. e. return current working directory. */
        return Path::Canonicalise(basepath);
    
    } else if (Path::IsAbsolute(path)) {
        /* Path is absolute, just return it. */
        return Path::Canonicalise(path);

    } else if ((path[0] == MYDOCUMENTS_MARKER_A) 
            && ((path.Length() == 1) || path[1] == SEPARATOR_A)) {
        /*
         * replace leading ~ with users home directory
         */
        path.Replace(MYDOCUMENTS_MARKER_A, Path::GetUserHomeDirectoryA(), 1);
        return Path::Canonicalise(path);

    } else if ((path[0] == SEPARATOR_A) && (path[1] != SEPARATOR_A)) {
        /*
         * Concatenate current drive and relative path, and canonicalise
         * the result.
         */
        return Path::Concatenate(basepath.Substring(0, 2), path, true);

    } else {
        /*
         * Concatenate current directory and relative path, and canonicalise
         * the result.
         */
        return Path::Concatenate(basepath, path, true);
    }
}
示例#14
0
		Void Hash::ComputeHash(const StringA& string)
		{
			ComputeHash((PCByte)string.GetBuffer(), string.GetSize() * sizeof(Char));
		}
示例#15
0
void CallStackWnd::OnRender(UI::Graphics* pGraphics)
{
//	HFONT hOldFont = dc.SelectFont((HFONT)GetStockObject(ANSI_FIXED_FONT));

	{
		LDraw::SolidBrush* brush = new LDraw::SolidBrush(LDraw::Color(255, 255, 255));
		pGraphics->FillRectangle(brush, 0, 0, m_computedSize.Width, m_computedSize.Height);
	}

	for (int i = 0; i < m_callstack.size(); i++)
	{
		DebugFrame* pDebugFrame = m_callstack[i];

	//	if (m_pFrame->m_Eip >= line->u.instr.address && m_pFrame->m_Eip < line->u.instr.address+line->u.instr.nbytes)
	//	{
	//	}
		if (i == 0)
		{
			DrawYellowArrow(pGraphics, i*16 + 8);
		}

		if (m_selected == i)
		{
			if (i != 0)
			{
				DrawGreenArrow(pGraphics, i*16 + 8);
			}
		}

		pGraphics->DrawString(pDebugFrame->m_str, GetFont(), LDraw::PointF(14, i*16), new LDraw::SolidBrush(LDraw::Color::Black));
	}

//	dc.SelectFont(hOldFont);

#if 0
	if (g_pt)
	{
		if (m_pFrame->m_ctx && m_pFrame->m_ctx->m_pDebugProcess && !m_pFrame->m_ctx->m_pDebugProcess->m_bRunning)
		{
			HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_pFrame->m_dwProcessId);

			int n = 0;
		//	DWORD eip = g_pt->m_context.Eip;
		//	DWORD ebp = g_pt->m_context.Ebp;

			STACK_FRAME frame;
			frame.Ebp = (STACK_FRAME*)g_pt->m_context.Ebp;
			frame.Ret_Addr = (PBYTE)g_pt->m_context.Eip;

			while (frame.Ebp)
			{
				StringA str = "";
				for (int i = 0; i < m_pFrame->m_ctx->m_modules.size(); i++)
				{
					DebugModule* pModule = m_pFrame->m_ctx->m_modules[i];

					if ((ULONG)frame.Ret_Addr >= pModule->base && (ULONG)frame.Ret_Addr < pModule->base + pModule->size)
					{
						str = pModule->name.c_str();

						tysymbolmap::iterator psymi = NULL;
						tysymbolmap::iterator symi = pModule->symbols.begin();
						while (symi != pModule->symbols.end())
						{
							if ((*symi).first > (ULONG)frame.Ret_Addr)
							{
								break;
							}
							psymi = symi;
							symi++;
						}

						if (psymi != NULL)
						{
							char s[512];
							sprintf(s, "%s + %X", (*psymi).second->m_name.c_str(), frame.Ret_Addr - (*psymi).first);
							str += s;
						}
						
						break;
					}
				}

				if (str.length()==0)
				{
					char buf[64];
					sprintf(buf, "%X", frame.Ret_Addr);
					str = buf;
				}		

				/*
				for (i = 0; i < m_pFrame->m_ctx->sourceFiles.size(); i++)
				{
					SourceFile* sourceFile = m_pFrame->m_ctx->sourceFiles[i];

					if (eip >= sourceFile->startAddress &&
						eip < sourceFile->endAddress)
					{
					//	sprintf(str, "%s() - %X", sourceFile->sourceFileName, eip);
					//	break;
					}
				}
				*/

				dc.TextOut(10, n*16, str.c_str());

			//	if (frame.Ebp == NULL)
			//		break;

				DWORD nRead;
				ReadProcessMemory(hProcess, frame.Ebp, &frame, 8, &nRead);
				if (nRead == 0)
					break;

				//frame eip = oldeip;
				n++;
			}
			//while (n < 20);

			CloseHandle(hProcess);
		}
	}
#endif
}
示例#16
0
/*
 * vislib::sys::Path::MakeDirectory
 */
void vislib::sys::Path::MakeDirectory(const StringA& path) {
    Stack<StringA> missingParts;
    StringA firstBuilt;
    StringA curPath = Resolve(path);

    while (!File::Exists(curPath)) {
        StringA::Size pos = curPath.FindLast(SEPARATOR_A);
        if (pos != StringA::INVALID_POS) {
            missingParts.Push(curPath.Substring(pos + 1));
            if (missingParts.Peek()->IsEmpty()) {
                // Remove empty directories as the incremental directory 
                // creation later on will fail for these.
                missingParts.Pop();
            }
            curPath.Truncate(pos);

        } else {
            // Problem: No Separators left, but directory still does not exist.
#ifdef _WIN32
            throw vislib::sys::SystemException(ERROR_INVALID_NAME, __FILE__, __LINE__);
#else /* _WIN32 */
            throw vislib::sys::SystemException(EINVAL, __FILE__, __LINE__);
#endif /* _WIN32 */
        }
    }

    // curPath exists
    if (!File::IsDirectory(curPath)) {
        // the latest existing directory is not a directory (may be a file?)
#ifdef _WIN32
        throw vislib::sys::SystemException(ERROR_DIRECTORY, __FILE__, __LINE__);
#else /* _WIN32 */
        throw vislib::sys::SystemException(EEXIST, __FILE__, __LINE__);
#endif /* _WIN32 */
    }

    while (!missingParts.IsEmpty()) {
        curPath += SEPARATOR_A;
        curPath += missingParts.Pop();

#ifdef _WIN32
        if (CreateDirectoryA(curPath, NULL) != 0) {
#else /* _WIN32 */
        if (mkdir(curPath, S_IRWXG | S_IRWXO | S_IRWXU) == 0) { // TODO: Check
#endif /* _WIN32 */
            // success, so go on.
            if (firstBuilt.IsEmpty()) {
                firstBuilt = curPath;
            }

        } else {
            DWORD errorCode = GetLastError();

            try {
                // failure, so try to remove already created paths and throw exception.
                DeleteDirectory(firstBuilt, true);
            } catch(...) {
            }

            throw vislib::sys::SystemException(errorCode, __FILE__, __LINE__);
        }
    }
    // we are done!
}


/*
 * vislib::sys::Path::MakeDirectory
 */
void vislib::sys::Path::MakeDirectory(const StringW& path) {
#ifdef _WIN32
    Stack<StringW> missingParts;
    StringW firstBuilt;
    StringW curPath = Resolve(path);

    while (!File::Exists(curPath)) {
        StringW::Size pos = curPath.FindLast(SEPARATOR_W);
        if (pos != StringW::INVALID_POS) {
            missingParts.Push(curPath.Substring(pos + 1));
            if (missingParts.Peek()->IsEmpty()) {
                // Remove empty directories as the incremental directory 
                // creation later on will fail for these.
                missingParts.Pop();
            }
            curPath.Truncate(pos);

        } else {
            // Problem: No Separators left, but directory still does not exist.
            throw vislib::sys::SystemException(ERROR_INVALID_NAME, __FILE__, __LINE__);
        }
    }

    // curPath exists
    if (!File::IsDirectory(curPath)) {
        // the latest existing directory is not a directory (may be a file?)
        throw vislib::sys::SystemException(ERROR_DIRECTORY, __FILE__, __LINE__);
    }

    while (!missingParts.IsEmpty()) {
        curPath += SEPARATOR_W;
        curPath += missingParts.Pop();

        if (CreateDirectoryW(curPath, NULL) != 0) {
            // success, so go on.
            if (firstBuilt.IsEmpty()) {
                firstBuilt = curPath;
            }

        } else {
            DWORD errorCode = GetLastError();

            try {
                // failure, so try to remove already created paths and throw exception.
                DeleteDirectory(firstBuilt, true);
            } catch(...) {
            }

            throw vislib::sys::SystemException(errorCode, __FILE__, __LINE__);
        }
    }
    // we are done!

#else /* _WIN32 */
    // linux is stupid
    MakeDirectory(W2A(path));

#endif /* _WIN32 */
}
示例#17
0
int CGnutellaSocket::ParseHandshake()
{
	const char* p = m_strHandshake.c_str();
	const char* pend = p+m_strHandshake.length();

	if (!strncmp(p, "GNUTELLA/0.6", 12))
	{
		p += 12;
		p++;
		long code = strtol(p, (char**)&p, 10);
		p++;

		StringA codemsg;
		while (p < pend)
		{
			if (p[0] == '\r' && p[1] == '\n')
			{
				break;
			}

			codemsg += *p;
			p++;
		}

		if (*p++ != '\r') ASSERT(0);
		if (*p++ != '\n') ASSERT(0);

	//	HttpHeaders headers;
		m_headers.AddHeaders(p);

		/*
		while (p < pend)
		{
			std::string header;
			while (p < pend)
			{
				if (p[0] == '\r' && p[1] == '\n')
				{
					break;
				}

				header += *p;
				p++;
			}

			if (*p++ != '\r') ASSERT(0);
			if (*p++ != '\n') ASSERT(0);

			m_headers.push_back(header);
		}
		ASSERT(*p == 0);
		*/

		return code;
	}
	else
	{
		ASSERT(0);
		return 0;
	}
}
示例#18
0
void CGnutellaSocket::OnReceive(int nErrorCode)
{
	TRACE("OnRead\n");
	/*
	if (nErrorCode)
	{
		ASSERT(0);
		return;
	}
	*/

	if (m_state == 0 || m_state == 1)
	{
		/*
		time_t timer1;
		time(&timer1);

		double diff = difftime(timer1, m_timer0);

		m_timer0 = timer1;

		ATLTRACE("", diff);
		*/

		ULONG n;
		ioctlsocket(m_socket, FIONREAD, &n);

		char buf[256+1];
		while (n)
		{
			int len = 256;
			if (len > n)
				len = n;

			int nread = Receive(buf, len);
			//if (nread == SOCKET_ERROR)
			if (nread < len)
			{
				m_state = -1;
				Close();
				return;
			}

			n -= nread;

			buf[nread] = 0;
			m_strHandshake += buf;
		}

		/*
		std::string line;
		while (1)
		{
			line = ReadLine();
			m_strHandshake += line + "\r\n";
			if (line.length() == 0)
				break;
		}
		*/

		if (m_strHandshake.length() > 4096)
		{
			// Handshake overflow
			ASSERT(0);
			m_state = -1;
			Close();
			return;//break;
		}

		if (m_state == 0)
		{
			if (m_strHandshake.length() >= 12)
			{
				if (strncmp(m_strHandshake.c_str(), "GNUTELLA/0.6", 12))
				{
					// Not a gnutella peer (disconnect)
					m_state = -1;
					Close();
					return;//break;
				}

				m_state = 1;	// Now we know it's a gnutella peer (keep receiving handshake)
			}
		}

		if (m_state == 1)
		{
			if (strstr(m_strHandshake.c_str(), "\r\n\r\n"))
			{
				m_state = 2;	// Have read entire handshake string
			}
		}

		if (m_state == 2)
		{
			int m_code = ParseHandshake();

			m_pComm->ProcessHeaders(this);

			if (m_code == 200)	// OK
			{
				m_state = 3;

				char* str =
					"GNUTELLA/0.6 200 OK\r\n"
					"\r\n";
			//	char* str = "GNUTELLA OK\n\n";
				int nWritten = Send(str, strlen(str));

				if (nWritten != strlen(str))
				{
					ASSERT(0);
				}

			//	PostMessage(m_pComm->m_hWnd, WM_USER+102, (LPARAM)(IConnection*)this, m_code);
			//	m_pComm->m_client->OnConnection(this);

				// Ping
				{
					GnutellaHeader ping;

					CoCreateGuid(&ping.Guid);	// ???
					ping.PayloadType = GnutellaPing;
					ping.TTL = 7;
					ping.Hops = 0;
					ping.PayloadLength = 0;

					int wrote = Send((const char*)&ping, sizeof(ping));
				}

			}
			else
			{
				Close();


				/*
				char* str =
					"GNUTELLA/0.6 503 FAIL\r\n"
					"\r\n";
				int nWritten = Send(str, strlen(str));

				if (nWritten != strlen(str))
				{
					ASSERT(0);
				}
*/
			}
		}
	}
	else if (m_state == 3)
	{
		int nread = Receive(m_packetbuf+m_nbufbytes, 32768-m_nbufbytes);
		if (nread == -1)
		{
			m_state = -1;
			Close();
			return;
		}

		int nbufbytes = m_nbufbytes + nread;

		// Process all complete packets
		bool bContinue;

		int offset = 0;
		int bytesleft;
		do
		{
			bytesleft = nbufbytes - offset;

			if (bytesleft < sizeof(GnutellaHeader))
			{
				// Incomplete packet
				bContinue = false;
			}
			else
			{
				GnutellaHeader* hdr = (GnutellaHeader*)(m_packetbuf+offset);

				if((hdr->PayloadType == 0x00 && hdr->PayloadLength < 32768)					  ||
					(hdr->PayloadType == 0x01 && hdr->PayloadLength >= 14 && hdr->PayloadLength < 32768)  ||
					(hdr->PayloadType == 0x02 && hdr->PayloadLength > 0 && hdr->PayloadLength < 32768)	||
					(hdr->PayloadType == 0x30 && hdr->PayloadLength > 2 && hdr->PayloadLength < 32768)   ||
					(hdr->PayloadType == 0x31 && hdr->PayloadLength < 32768)   ||
					(hdr->PayloadType == 0x32 && hdr->PayloadLength < 32768)   ||
					(hdr->PayloadType == 0x40 && hdr->PayloadLength >= 26 && hdr->PayloadLength < 32768)  ||
					(hdr->PayloadType == 0x80 && hdr->PayloadLength >  2 && hdr->PayloadLength <= 230)   ||
					(hdr->PayloadType == 0x81 && hdr->PayloadLength > 26 && hdr->PayloadLength <= 32768))
				{
					DWORD packetlen = sizeof(GnutellaHeader) + hdr->PayloadLength;

					if (bytesleft < packetlen)
					{
						// Incomplete packet
						bContinue = false;
					}
					else
					{
						ProcessPacket(hdr);

						offset += packetlen;

						bContinue = true;
					}
				}
				else
				{
					bContinue = false;

					m_state = -1;
					Close();
					return;
				}
			}
		}
		while (bContinue);

		// Move the leftover bytes to the beginning of the buffer
		if (bytesleft)
		{
			memmove(m_packetbuf, m_packetbuf+offset, bytesleft);
		}
		m_nbufbytes = bytesleft;
	}
}
示例#19
0
/*
 * vislib::sys::Path::Canonicalise
 */
vislib::StringA vislib::sys::Path::Canonicalise(const StringA& path) {
    const StringA DOUBLE_SEPARATOR(Path::SEPARATOR_A, 2);

#ifdef _WIN32
    StringA retval;

    if (::PathCanonicalizeA(retval.AllocateBuffer(MAX_PATH), path) != TRUE) {
        throw SystemException(__FILE__, __LINE__);
    }

    retval.Replace(DOUBLE_SEPARATOR.PeekBuffer(), SEPARATOR_A);
    retval.Replace(DOUBLE_SEPARATOR.PeekBuffer(), SEPARATOR_A);

    /* Ensure that a UNC path remains a UNC path. */
    if (path.StartsWith(DOUBLE_SEPARATOR)) {
        // Note: Double separator replacement above leaves at least one 
        // separator, so we must only prepend one additional one.
        retval.Prepend(SEPARATOR_A);
    }

    return retval;

#else /* _WIN32 */
    const char *BACK_REF = "/..";
    const char *CUR_REF = "/.";             // Note: "./" does not work
    StringA::Size BACK_REF_LEN = ::strlen(BACK_REF);
    StringA::Size bwRefPos = 0;             // Position of back reference.
    StringA::Size remDirPos = 0;            // Position of directory to erase.
    StringA retval(path);
    

    /* Remove backward references, first. */
    while ((bwRefPos = retval.Find(BACK_REF)) != StringA::INVALID_POS) {

        if ((bwRefPos > 0) 
                && (remDirPos = retval.FindLast(SEPARATOR_A, bwRefPos - 1))
                != StringA::INVALID_POS) {
            /* Found inner backward reference, so remove some parts. */
            retval.Remove(remDirPos, bwRefPos - remDirPos + BACK_REF_LEN);

        } else {
            /* 
             * No other path separator is before this one, so we can remove
             * everything before 'bwRefPos'.
             */
            retval.Remove(0, bwRefPos + BACK_REF_LEN);
        }
    }

    /*
     * Remove references to the current directory. This must be done after
     * removing backward references.
     */
    retval.Remove(CUR_REF);
    
    /* Remove odd and even number of repeated path separators. */
    retval.Replace(DOUBLE_SEPARATOR.PeekBuffer(), SEPARATOR_A);
    retval.Replace(DOUBLE_SEPARATOR.PeekBuffer(), SEPARATOR_A);

    return retval;
#endif /* _WIN32 */
}
	Void SymmetricCipher::Compute(const StringA& string)
	{
		Compute((PCByte)string.GetBuffer(), string.GetSize() * sizeof(Char));
	}
示例#21
0
int main(int argc, char* argv[])
{
	printf("main()\n");

#if WIN32
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/ncrt0.o"));
	//linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/main.o"));
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/OBJ/Browser/Browser.o"));
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/OBJ/Browser/BrowserFrame.o"));
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/libui.a"));
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/libdraw.a"));
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/libxmlparse.a"));
	linker.m_files.push_back(new StringA("C:/MMStudio/Amiga68k/liblfc.a"));
	linker.m_files.push_back(new StringA("C:/cygwin/usr/local/amiga/lib/gcc/m68k-amigaos/3.4.0/libgcc.a"));
	linker.m_files.push_back(new StringA("C:/cygwin/usr/local/amiga/m68k-amigaos/lib/libstdc++.a"));
	linker.m_files.push_back(new StringA("C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libm.a"));
	linker.m_files.push_back(new StringA("C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libnix.a"));
	linker.m_files.push_back(new StringA("C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libnixmain.a"));
//	linker.m_files.push_back(new StringA("C:/cygwin/usr/local/amiga/m68k-amigaos/lib/libamiga.a"));
	linker.m_files.push_back(new StringA("C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libstubs.a"));
#else


	if (true)
	{
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/ncrt0.o"));
	//	linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/main.o"));

		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/LDebugger.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/mainfrm.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/SourceEdit.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/SourceEditFrame.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/DisassemblyWnd.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/WatchWnd.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/CallStackWnd.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/FileDialog.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/LDebugger/DebugSession.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libui.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libdraw.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libxmlparse.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libcode.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/liblfc.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/usr/local/amiga/lib/gcc/m68k-amigaos/3.4.0/libgcc.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/usr/local/amiga/m68k-amigaos/lib/libstdc++.a"));

		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libm.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libnix.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libnixmain.a"));
	//	linker.m_files.push_back(new StringA("WinHD_C:/cygwin/usr/local/amiga/m68k-amigaos/lib/libamiga.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libstubs.a"));
	}
	else
	{
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/ncrt0.o"));
	//	linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/main.o"));

		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/Browser/Browser.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/OBJ/Browser/BrowserFrame.o"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libui.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libdraw.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libxmlparse.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/libcode.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/liblfc.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/usr/local/amiga/lib/gcc/m68k-amigaos/3.4.0/libgcc.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/usr/local/amiga/m68k-amigaos/lib/libstdc++.a"));

		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libm.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libnix.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libnixmain.a"));
	//	linker.m_files.push_back(new StringA("WinHD_C:/cygwin/usr/local/amiga/m68k-amigaos/lib/libamiga.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libm020/libnix/libstubs.a"));

		/*
		linker.m_files.push_back(new StringA("WinHD_C:/MMStudio/Amiga68k/ncrt0.o"));
		linker.m_files.push_back(new StringA("WINHD_C:/MMStudio/Amiga68k/main.o"));
		linker.m_files.push_back(new StringA("WINHD_C:/cygwin/home/Sigurd Lerstad/lib/libnix/libnix.a"));
		linker.m_files.push_back(new StringA("WINHD_C:/cygwin/home/Sigurd Lerstad/lib/libnix/libnixmain.a"));
		linker.m_files.push_back(new StringA("WinHD_C:/cygwin/home/Sigurd Lerstad/lib/libnix/libstubs.a"));
		*/
	}
#endif

	printf("pass1\n");
	linker.pass1();

/*
	GlobalSymbol* pSymbol = linker.m_globsyms[new StringA("_main")];
	pSymbol->m_defined = true;
	pSymbol->ResolvedValue = (DWORD)MyMain;
*/
//	linker.AddSymbol(new StringA("_main"), (DWORD)MyMain);

	printf("loading first object file\n");
#if 1
	linker.LoadObjectFile(linker.m_objectFiles[0]);
	if (true)
	{
		for (int i = 1; i < linker.m_objectFiles.size(); i++)
		{
			printf("loading %d object file\n", i);
			linker.LoadObjectFile(linker.m_objectFiles[i]);
		}
	}

	printf("Here\n");
	TRACE("\n\n");

	{
		for (int i = 0; i < linker.m_loadedObjectFiles.size(); i++)
		{
			OFile2* ofile = linker.m_loadedObjectFiles[i];

			if (ofile->m_afilename)
				TRACE("%s:%s\n", ofile->m_afilename->c_str(), ofile->m_ofilename->c_str());
			else
				TRACE("%s\n", ofile->m_ofilename->c_str());
		}
	}
#endif

	printf("before sets\n");

	linker.sets();

	printf("LoadObjectfile2\n");

	OFile* pOFile = linker.LoadObjectFile2(linker.m_objectFiles[0]);

	if (true)
	{
		for (int i = 1; i < linker.m_objectFiles.size(); i++)
		{
			linker.LoadObjectFile2(linker.m_objectFiles[i]);
		}
	}

/*
	{
		GlobalSymbol* psym = linker.m_globsyms[new StringA("_DOSBase")];
		int x = *(long*)psym->ResolvedValue;
	}
*/
	printf("done\n");

	if (linker.m_undefinedReferenceCount)
	{
		printf("undefined reference count: %d\n", linker.m_undefinedReferenceCount);
		TRACE("undefined reference count: %d\n", linker.m_undefinedReferenceCount);
	}
	else
	{
#if AMIGA
		GlobalSymbol* sym = linker.m_globsyms[new StringA("_plinker")];
		ASSERT(sym);
		ASSERT(sym->m_syms.size());

		*(Linker**)sym->m_syms[0]->ResolvedValue = &linker;
#endif

#if WIN32
		/*
		{
			gsymmap_t::iterator it2 = linker.m_globsyms.begin();
			while (it2 != linker.m_globsyms.end())
			{
// "__ZTI14red_black_nodeIPN6System7StringAEPNS0_9NamespaceEE"

				GlobalSymbol* sym = (*it2).second;
				if (strstr(sym->m_name->c_str(), "TI") && strstr(sym->m_name->c_str(), "red_black_node") && strstr(sym->m_name->c_str(), "StringA"))
				{
					MessageBeep(-1);
				}

				++it2;
			}
		}
		*/

		TypeArchive* ar = new TypeArchive(TypeArchive::Mode_Load, new FileByteStream(new StringA("C:/test.typeinfo"), FileMode_Read));

		int ntypes;
		*ar >> ntypes;

		printf("%d\n", ntypes);

		for (int i = 0; i < ntypes; i++)
		{
			NamedType* pType;
			*ar >> pType;

			BufferImp<char> buffer;
			StringBuilderA strbuilder(&buffer);
			pType->Write(strbuilder);
			pType->m_qname = buffer.DetachToString();

			if (*pType->m_qname == "second_argument_type")
			{
				MessageBeep(-1);
			}

			//if (pType->m_qname)
			{
				StringBuilderA strbuilder(&buffer);
				strbuilder << "__ZTI";	// type info

				Mangler mangler;
				mangler.MangleType(pType, strbuilder);

				StringA* name = buffer.DetachToString();

				gsymmap_t::iterator it2 = linker.m_globsyms.find(name);
				//map<StringA*, DWORD, Ref_Less<StringA> >::iterator it2 = symbols.find(name);
				if (it2 != linker.m_globsyms.end())
				{
					GlobalSymbol* globsym = (*it2).second;

					//TRACE("%s\n", name->c_str());

					if (!strcmp(globsym->m_name->c_str(), "__ZTI9IAddChild"))
					{
						MessageBeep(-1);

					}

					for (int j = 0; j < globsym->m_syms.size(); j++)
					{
						Symbol* sym = globsym->m_syms[j];

					}

#if AMIGA
					__type_info2* ti = (__type_info2*)sym->ResolvedValue;
					printf("%s\n", ti->__type_name);

				//	int len = strlen(ti->__type_name);
						/*
						char* newname = malloc(len+1+4);
						strcpy(newname+4, ti->__type_name);
						ti->__type_name = newname+4;
						*(Type**)newname = pType;
						*/
#endif
#if 0
					TypeDescriptor* typedesc = (TypeDescriptor*)(*it2).second;

					//VERIFY(typedesc->_m_data == NULL);

					if (pType->GetKind() == type_class)
					{
						((ClassType*)pType)->m_typedesc = (Type_Info*)typedesc;
					}
					else if (pType->GetKind() == type_enum)
					{
						((EnumType*)pType)->m_typedesc = (Type_Info*)typedesc;
					}

					typedesc->_m_data = pType2;

					AddPersistentLiveRoot((Object**)&typedesc->_m_data);
#endif
				}
				else
				{
					TRACE("-----%s\n", name->c_str());
				}
			}
		}
#endif

	{
#if 1
		ULONG heapsize = heap->m_next - (heap->m_data);
#else
		ULONG heapsize = heap->m_next - (heap->m_data+heap->m_size);
#endif

		printf("heapsize: %f MB\n", heapsize / (1024.0*1024));
	}

	#if AMIGA

		printf("Calling");

		char* line = strdup("programname parameter0 parameter1");
		entrypoint_hook(pOFile->m_textdata, line, strlen(line));
	#endif
	}

#if 0
	if (argc <= 1)
	{
		printf("Usage:\n");
		printf("loader objectfile\n");
		return -10;
	}

	Linker linker;

	for (int i = 1; i < argc; i++)
	{
		linker.m_files.Add(new StringA(argv[i]));
	}

	printf("pass1...");
	linker.pass1();
//	linker.pass2();

	/*
	GlobalSymbol* globsym = linker.globsyms["_main2"];

	FileByteStream file(globsym->m_filename);
	linker.LoadObjectFile(file);

	printf("Calling...");
	((dllentrypoint)globsym->Value)();
	printf("done\n");
	*/

	printf("done\n");

	printf("loading...");
	fflush(stdout);

//	FileByteStream* file = new FileByteStream(linker.m_files[0]);
//	printf("sdfsdf\n");
//	fflush(stdout);
	linker.LoadObjectFile(linker.m_objectFiles[0]);

	linker.sets();

	OFile* pOFile = linker.LoadObjectFile2(linker.m_objectFiles[0]);

	printf("done\n");

	if (linker.m_undefinedReferenceCount)
	{
		printf("undefined reference count: %d\n", linker.m_undefinedReferenceCount);
		TRACE("undefined reference count: %d\n", linker.m_undefinedReferenceCount);
	}
	else
	{
	#if AMIGA
		char* line = strdup("programname parameter0 parameter1");
		entrypoint_hook(pOFile->m_textdata, line, strlen(line));
	#endif
	}
#endif

	return 0;
}
示例#22
0
HRESULT WINAPI CZipFs::ReCreate(__in_opt void* handle, __in_opt ULONG const flags /*= 0*/)
{
	if (flags)
		m_flags = flags;

	if ((HANDLE)handle == m_handle)
		return S_OK;

	m_handle = (HANDLE)handle;

	StringA strNameA = UnicodeToAnsi(m_FileName);

	if (UNZ_OK != unzGetFilePos64((unzFile)m_handle, &m_currentFilePos))
		return E_NOT_SET;

	if (unzLocateFile((unzFile)m_handle, strNameA.c_str(), 0) != UNZ_OK)
		return E_FAIL;

	HRESULT hr = (unzOpenCurrentFile((unzFile)m_handle) == UNZ_OK) ? S_OK : E_FAIL;
	if (FAILED(hr))
	{
		m_handle = INVALID_HANDLE_VALUE;
		return hr;
	}

	if (m_stream)
	{
		m_stream->Release();
		m_stream = NULL;
	}
	m_stream = new CBufferedStream();
	if (m_stream == NULL)
	{
		Close();
		return E_OUTOFMEMORY;
	}

	int err = 0;
	unsigned char *pTemp = new unsigned char[WRITEBUFFERSIZE];
	if (pTemp)
	{
		do
		{
			err = unzReadCurrentFile((unzFile)m_handle, pTemp, WRITEBUFFERSIZE);
			if (err < 0)
			{
				break;
			}
			if (err > 0)
			{
				ULONG writtenSize;
				if (FAILED(m_stream->Write(pTemp, (ULONG)err, &writtenSize)))
					break;
				if (writtenSize == 0)
					break;
			}
		} while (err > 0);
		delete[] pTemp;
	}

	// goto the beginning of file
	ULARGE_INTEGER pos = {};
	LARGE_INTEGER distanceToMove = {};
	m_stream->Seek(&pos, distanceToMove, IFsStream::FsStreamBegin);
	m_attribute->SetFilePath(m_FileName.c_str(), handle);
	return S_OK;
}
示例#23
0
	void expand_macro_one(StringA& str)
	{
		if( str.IsBlockNull() )
			return ;

		//loop
		do {
			//find
			uintptr uCount = 0;
			uintptr uStart = 0;
			do {
				auto iter(StringHelper::Find(str, '{', uStart));
				if( iter.IsNull() )
					break;
				intptr delta = iter.CalcDelta(str.GetAt(uStart));
				if( iter != str.GetBegin() ) {
					auto iter1(iter);
					iter1.MovePrev();
					// \{
					if( iter1.get_Value() == '\\' ) {
						uStart += (delta + 1);
						continue;
					}
				}
				uStart += (delta + 1);
				uCount ++;
				uintptr uLeftC = uStart;
				do {
					auto iterE(StringHelper::Find(str, '}', uStart));
					if( iterE.IsNull() ) {
						uCount --;
						break;
					}
					delta = iterE.CalcDelta(str.GetAt(uStart));
					auto iter1(iterE);
					iter1.MovePrev();
					// \}
					if( iter1.get_Value() == '\\' ) {
						uStart += (delta + 1);
						continue;
					}
					uStart += (delta + 1);
					intptr len = iterE.CalcDelta(iter);
					//empty
					if( len <= 1 ) {
						uCount --;
						break;
					}
					//macro name
					StringA strMacro(StringHelper::MakeEmptyString<CharA>(MemoryHelper::GetCrtMemoryManager()));  //may throw
					StringUtilHelper::Sub(str, uLeftC, len - 1, strMacro);  //may throw
					ConstStringA c_macro_name(StringUtilHelper::To_ConstString(strMacro));
					StringA strV;
					uint id = m_macro_table.get_ID(c_macro_name);
					if( id == 0 ) {
						id = m_token_table.get_ID(c_macro_name);
						if( id == 0 ) {
							uCount --;
							break;
						}
						strV = m_token_regex[id - m_token_table.GetMinID()].get_Value();
					}
					else {
						strV = m_macro_regex[id - m_macro_table.GetMinID()].get_Value();
					}
					iter.get_Value() = '(';
					iterE.get_Value() = ')';
					StringHelper::Delete(uLeftC, len - 1, str);
					StringUtilHelper::Insert(uLeftC, strV, str);  //may throw
					//now iterators are invalid
					uStart = uLeftC + strV.GetLength() + 1;
					break;
				} while(true);
			} while(true);
			if( uCount == 0 )
				break;
		} while(true);
	}
示例#24
0
/*
 * vislib::sys::Path::DeleteDirectory
 */
void vislib::sys::Path::DeleteDirectory(const StringA& path, bool recursive) {
    if (!File::Exists(path)) return; // we don't delete non-existing stuff
    StringA fullPath = Resolve(path);
    if (!fullPath.EndsWith(SEPARATOR_A)) fullPath += SEPARATOR_A;

    if (recursive) {
        // remove files and directory
        PurgeDirectory(fullPath, true);
    }

#ifdef _WIN32
    if (RemoveDirectoryA(fullPath) == 0) {
#else /* _WIN32 */
    if (rmdir(fullPath) != 0) {
#endif /* _WIN32 */
        throw vislib::sys::SystemException(__FILE__, __LINE__);
    }

}


/*
 * vislib::sys::Path::DeleteDirectory
 */
void vislib::sys::Path::DeleteDirectory(const StringW& path, bool recursive) {
#ifdef _WIN32
    if (!File::Exists(path)) return; // we don't delete non-existing stuff
    StringW fullPath = Resolve(path);
    if (!fullPath.EndsWith(SEPARATOR_W)) fullPath += SEPARATOR_W;

    if (recursive) {
        // remove files and directory
        PurgeDirectory(fullPath, true);
    }

    if (RemoveDirectoryW(fullPath) == 0) {
        throw vislib::sys::SystemException(__FILE__, __LINE__);
    }

#else /* _WIN32 */
    // linux is stupid
    DeleteDirectory(W2A(path), recursive);

#endif /* _WIN32 */
}


/*
 * vislib::sys::Path::FindExecutablePath
 */
vislib::StringA vislib::sys::Path::FindExecutablePath(
        const vislib::StringA& filename) {
#ifdef _WIN32
    bool found = false;
    DWORD bufSize = MAX_PATH;
    char *buffer = new char[bufSize];

    // first try: "SearchPath"
    DWORD rv = ::SearchPathA(NULL, filename.PeekBuffer(), NULL, bufSize,
        buffer, NULL);
    if (rv > 0) {
        found = true;
        if (rv + 1 > bufSize) {
            bufSize = rv + 1;
            delete[] buffer;
            buffer = new char[bufSize];
            rv = ::SearchPathA(NULL, filename.PeekBuffer(), NULL, bufSize,
                buffer, NULL);
            if (rv == 0) { // failed
                found = false;
            }
        }
    }

    if (!found) {
        // second try: "AssocQueryString"
        // NOTE:
        //  AssocQueryString does not work as specified! It is not possible to ask
        // for the size of the string buffer holding the value returned. Therefore
        // this implementation increases the buffersize until the returned strings
        // no longer grow.
        DWORD bufLen = MAX_PATH;
        HRESULT hr;
        bufSize = MAX_PATH;
        
        do {
            hr = ::AssocQueryStringA(ASSOCF_INIT_BYEXENAME, ASSOCSTR_EXECUTABLE,
                filename.PeekBuffer(), NULL, buffer, &bufSize);
            if ((hr != E_POINTER) && (hr != S_OK)) { // error
                break;
            }
            if (bufSize == bufLen) {
                bufLen += MAX_PATH;
                bufSize = bufLen;
                delete[] buffer;
                buffer = new char[bufSize];
            } else {
                found = true;
            }
        } while (bufSize == bufLen);
    }

    if (found) {
        vislib::StringA retval(buffer);
        delete[] buffer;
        return retval;
    } else {
        return "";
    }
#else /* _WIN32 */

    // Note:
    //  Do not use "Console::Run" or "Process" methods because they might use
    // this method to determine the full path of their binaries. So we avoid
    // calling cycles by just using "popen" directly
    vislib::StringA cmd("which ");
    vislib::StringA ret;
    cmd += filename;
    cmd += " 2> /dev/null";
    const int bufferSize = 1024;
    char buffer[bufferSize];
    FILE *which = ::popen(cmd.PeekBuffer(), "r");
    if (which == NULL) {
        return "";
    }
    while (!::feof(which)) {
        ret += fgets(buffer, bufferSize, which);
    }
    ::pclose(which);

    vislib::StringA::Size end = ret.Find('\n');
    if (end != vislib::StringA::INVALID_POS) {
        ret.Truncate(end);
    }
    if (ret.EndsWith(filename)) {
        return ret;
    } else {
        return "";
    }

#endif /* _WIN32 */
}
示例#25
0
void MailAccount::GetNewMail(ITable* pTable)
{
	int port = 110;
	POP3Client* pSocket = new POP3Client;
	pSocket->Create();
	pSocket->Connect(m_server.c_str(), port);

	StringA greeting = pSocket->ReadLine();
	if (strncmp(greeting.c_str(), "+OK", 3))
		throw -1;

	{
		char msg[512];
		sprintf(msg, "USER %s\r\n", m_username.c_str());
		pSocket->Write(msg, strlen(msg));
		StringA response = pSocket->ReadLine();
		if (strncmp(response.c_str(), "+OK", 3))
			throw -1;
	}

	{
		char msg[512];
		sprintf(msg, "PASS %s\r\n", m_password.c_str());
		pSocket->Write(msg, strlen(msg));
		StringA response = pSocket->ReadLine();
		if (strncmp(response.c_str(), "+OK", 3))
			throw -1;
	}

	CArray<int, int> message_numbers;
	{
		char* msg = "LIST\r\n";
		pSocket->Write(msg, strlen(msg));
		StringA response = pSocket->ReadLine();
		if (strncmp(response.c_str(), "+OK", 3))
			throw -1;
		while (1)
		{
			StringA line = pSocket->ReadLine();
			if (!strcmp(line.c_str(), "."))
			{
				break;
			}

			int message_number;
			int message_size;

			sscanf(line.c_str(), "%d %d", &message_number, &message_size);
			message_numbers.Add(message_number);

			TRACE("%s\n", line.c_str());
		}

	//	FILE* fp_text = fopen("C:\\mail_text", "a+b");
	//	FILE* fp_index = fopen("C:\\mail_index", "a+b");

		for (int i = 0; i < message_numbers.size(); i++)
		{
			IRecord* pMessage = pTable->NewRecord();

			pMessage->GetField((int)0)->SetValue((long)0);//m_ID;
			pMessage->GetField(5)->SetValue((long)0);
			pMessage->GetField(6)->SetValue(time(NULL));
			pMessage->GetField(7)->SetValue(m_ID);

			{
				char msg[256];
				sprintf(msg, "RETR %d\r\n", message_numbers[i]);
				TRACE(msg);
				pSocket->Write(msg, strlen(msg));
				StringA response = pSocket->ReadLine();
				if (strncmp(response.c_str(), "+OK", 3))
					throw -1;
			}

			// Read the message
			StringA lines;

			while (1)
			{
				StringA line = pSocket->ReadLine();
				if (!strcmp(line.c_str(), "."))	// Multiline message ends with '.\r\n'
				{
					break;
				}

				lines += line;
				lines += "\r\n";
			}

			const char *p = lines.c_str();

			while (*p)
			{
				if (p[0] == '\r' && p[1] == '\n')	// End of headers
					break;

				// field name
				StringA fieldName;
				while (*p)
				{
					if (isspace(*p) || *p == ':')
						break;

					fieldName += *p;
					p++;
				}
				while (isspace(*p)) p++;
				if (*p++ != ':') throw -1;
				while (isspace(*p)) p++;

				// field body
				StringA fieldBody;
				while (*p)
				{
					if (p[0] == '\r' && p[1] == '\n')
					{
						if (p[2] == '\t' || p[2] == ' ')	// continuation on next line
						{
							p += 3;
						}
						else
						{
							p += 2;
							break;	// End of this field
						}
					}
					else
					{
						fieldBody += *p;
						p++;
					}
				}

				if (!stricmp(fieldName.c_str(), "Subject"))
				{
					pMessage->GetField(1)->SetData(fieldBody.c_str(), fieldBody.length());
				}
				else if (!stricmp(fieldName.c_str(), "From"))
				{
					pMessage->GetField(2)->SetData(fieldBody.c_str(), fieldBody.length());
				}
			}

			pMessage->GetField(3)->SetData(lines.c_str(), p - lines.c_str());

			if (p[0] != '\r' || p[1] != '\n')
				throw -1;
			p += 2;

			pMessage->GetField(4)->SetData(p, lines.length() - (p - lines.c_str()));

			pMessage->Write();

			// The message isn't actually deleted from the server until we issue a QUIT command
			{
				char msg[256];
				sprintf(msg, "DELE %d\r\n", message_numbers[i]);
				TRACE(msg);
				pSocket->Write(msg, strlen(msg));
				StringA response = pSocket->ReadLine();
				if (strncmp(response.c_str(), "+OK", 3))
					throw -1;
			}
		}

		/*
		fclose(fp_index);
		fclose(fp_text);
		*/
	}

	{
		char* msg = "QUIT\r\n";
		pSocket->Write(msg, strlen(msg));
		StringA response = pSocket->ReadLine();
		if (strncmp(response.c_str(), "+OK", 3))
			throw -1;
	}
}