Ejemplo n.º 1
0
bool CaMuleExternalConnector::OnInit()
{
#ifndef __WINDOWS__ 
	#if wxUSE_ON_FATAL_EXCEPTION
		// catch fatal exceptions
		wxHandleFatalExceptions(true);
	#endif
#endif

	// If we didn't know that OnInit is called only once when creating the
	// object, it could cause a memory leak. The two pointers below should
	// be free()'d before assigning the new value.
	// cppcheck-suppress publicAllocationError
	m_strFullVersion = strdup((const char *)unicode2char(GetMuleVersion()));
	m_strOSDescription = strdup((const char *)unicode2char(wxGetOsDescription()));

	// Handle uncaught exceptions
	InstallMuleExceptionHandler();

	bool retval = wxApp::OnInit();
	OnInitCommandSet();
	InitCustomLanguages();
	SetLocale(m_language);
	return retval;
}
Ejemplo n.º 2
0
void CSocks4StateMachine::process_send_command_request(bool entry)
{
	if (entry) {
		// Prepare the request command buffer
		m_buffer[0] = SOCKS4_VERSION;
		switch (m_proxyCommand) {
		case PROXY_CMD_CONNECT:
			m_buffer[1] = SOCKS4_CMD_CONNECT;
			break;
			
		case PROXY_CMD_BIND:
			m_buffer[1] = SOCKS4_CMD_BIND;
			break;
			
		case PROXY_CMD_UDP_ASSOCIATE:
			m_ok = false;
			return;
			break;
		}
		RawPokeUInt16(m_buffer+2, ENDIAN_HTONS(m_peerAddress->Service()));
		// Special processing for SOCKS4a
		switch (m_proxyData.m_proxyType) {
		case PROXY_SOCKS4a:
			PokeUInt32(m_buffer+4, StringIPtoUint32(wxT("0.0.0.1")));
			break;
		case PROXY_SOCKS4:
		default:
			PokeUInt32(m_buffer+4, StringIPtoUint32(m_peerAddress->IPAddress()));
			break;
		}
		// Common processing for SOCKS4/SOCKS4a
		unsigned int offsetUser = 8;
		unsigned char lenUser = m_proxyData.m_userName.Len();
		memcpy(m_buffer + offsetUser, 
			unicode2char(m_proxyData.m_userName), lenUser);
		m_buffer[offsetUser + lenUser] = 0;
		// Special processing for SOCKS4a
		switch (m_proxyData.m_proxyType) {
		case PROXY_SOCKS4a: {
			unsigned int offsetDomain = offsetUser + lenUser + 1;
			unsigned char lenDomain = m_peerAddress->Hostname().Len();
			memcpy(m_buffer + offsetDomain, 
				unicode2char(m_peerAddress->Hostname()), lenDomain);
			m_buffer[offsetDomain + lenDomain] = 0;
			m_packetLenght = 1 + 1 + 2 + 4 + lenUser + 1 + lenDomain + 1;
			break;
		}
		case PROXY_SOCKS4:
		default:
			m_packetLenght = 1 + 1 + 2 + 4 + lenUser + 1;
			break;
		}
		// Send the command packet
		ProxyWrite(*m_proxyClientSocket, m_buffer, m_packetLenght);
	}
}
Ejemplo n.º 3
0
wxString CamulewebApp::SetLocale(const wxString& language)
{
	wxString lang = CaMuleExternalConnector::SetLocale(language); // will call setlocale() for us

	// SetLocale() may indeed return an empty string, when no locale has been selected yet and
	// no locale change was requested, or, in the worst case, if the last locale change didn't succeed.
	if (!lang.IsEmpty()) {
		DebugShow(wxT("*** Language set to: ") + lang + wxT(" ***\n"));
#ifdef ENABLE_NLS
		wxString domain = wxT("amuleweb-") + m_TemplateName;
		Unicode2CharBuf domainBuf = unicode2char(domain);
		const char *c_domain = (const char *)domainBuf;

		// Try to find a message catalog
		// First look in ~/.aMule/webserver/<template>, but only if a local template was used
		wxString dir;
		if (m_localTemplate) {
			dir = JoinPaths(JoinPaths(JoinPaths(GetConfigDir(), wxT("webserver")), m_TemplateName), wxT("locale"));
			DebugShow(wxT("looking for message catalogs in ") + dir + wxT("... "));
		}
		if (!m_localTemplate || !DirHasMessageCatalog(dir, lang, domain)) {
			if (m_localTemplate) {
				DebugShow(wxT("no\n"));
			}
#if defined __WXMAC__  || defined __WXMSW__
			// on Mac, the bundle may be tried, too
			dir = wxStandardPaths::Get().GetDataDir();
#elif defined(__UNIX__)
			dir = JoinPaths(static_cast<wxStandardPaths&>(wxStandardPaths::Get()).GetInstallPrefix(), JoinPaths(wxT("share"), wxT("locale")));
#endif
			DebugShow(wxT("looking for message catalogs in ") + dir + wxT("... "));
			if (!DirHasMessageCatalog(dir, lang, domain)) {
				DebugShow(wxT("no\n"));
				dir = wxEmptyString;
			} else {
				DebugShow(wxT("yes\n"));
			}
		} else {
			DebugShow(wxT("yes\n"));
		}
		// If we found something, then use it otherwise it may still be present at the system default location
		if (!dir.IsEmpty()) {
			Unicode2CharBuf buffer = unicode2char(dir);
			const char *c_dir = (const char *)buffer;
			bindtextdomain(c_domain, c_dir);
		}
		// We need to have the returned messages in UTF-8
		bind_textdomain_codeset(c_domain, "UTF-8");
		// And finally select the message catalog
		textdomain(c_domain);
#endif /* ENABLE_NLS */
	}

	return lang;
}
Ejemplo n.º 4
0
void CaMuleExternalConnector::GetCommand(const wxString &prompt, char* buffer, size_t buffer_size)
{
#ifdef HAVE_LIBREADLINE
		char *text = readline(unicode2char(prompt + wxT("$ ")));
		if (text && *text && 
		    (m_InputLine == 0 || strcmp(text,m_InputLine) != 0)) {
		  add_history (text);
		}
		if (m_InputLine)
		  free(m_InputLine);
		m_InputLine = text;
#else
		Show(prompt + wxT("$ "));
		const char *text = fgets(buffer, buffer_size, stdin);	// == buffer if ok, NULL if eof
#endif /* HAVE_LIBREADLINE */
		if ( text ) {
			size_t len = strlen(text);
			if (len > buffer_size - 1) {
				len = buffer_size - 1;
			}
			if (buffer != text) {
				strncpy(buffer, text, len);
			}
			buffer[len] = 0;
		} else {
			strncpy(buffer, "quit", buffer_size);
		}
}
Ejemplo n.º 5
0
void CaMuleExternalConnector::GetCommand(const wxString &prompt, char* buffer, size_t buffer_size)
{
#ifdef HAVE_LIBREADLINE
		char *text = readline(unicode2char(prompt + wxT("$ ")));
		if (text && *text && 
		    (m_InputLine == 0 || strcmp(text,m_InputLine) != 0)) {
		  add_history (text);
		}
		if (m_InputLine)
		  free(m_InputLine);
		m_InputLine = text;
#else
		Show(prompt + wxT("$ "));
		fflush(stdin);
		if (fgets(buffer, buffer_size, stdin)){}	// prevent GCC warning
		const char *text = buffer;
#endif /* HAVE_LIBREADLINE */
		if ( text ) {
			size_t len = strlen(text);
			if (len > buffer_size - 2) {
				len = buffer_size - 2;
			}
			strncpy(buffer, text, len);
			buffer[len] = '\n';
			buffer[len + 1] = 0;
		} else {
			strncpy(buffer, "quit", buffer_size);
		}
}
Ejemplo n.º 6
0
const CountryData& CIP2Country::GetCountryData(const wxString &ip)
{
	// Should prevent the crash if the GeoIP database does not exists
	if (m_geoip == NULL) {
		CountryDataMap::iterator it = m_CountryDataMap.find(wxString(wxT("unknown")));
		it->second.Name = wxT("?");
		return it->second;	
	}
	
	const wxString CCode = wxString(char2unicode(GeoIP_country_code_by_addr(m_geoip, unicode2char(ip)))).MakeLower();
	
	CountryDataMap::iterator it = m_CountryDataMap.find(CCode);
	if (it == m_CountryDataMap.end()) { 
		// Show the code and ?? flag
		it = m_CountryDataMap.find(wxString(wxT("unknown")));
		wxASSERT(it != m_CountryDataMap.end());
		if (CCode.IsEmpty()) {
			it->second.Name = wxT("?");
		} else{
			it->second.Name = CCode;			
		}
	}
	
	return it->second;	
}
Ejemplo n.º 7
0
void CLogger::AddLogLine(
	const wxString &file,
	int line,
	bool critical,
	DebugType /* type */,
	const wxString &str,
	bool /*  toStdout */,
	bool /* toGUI */)
{
	std::string s;
	if (critical) {
		s = "Critical message: ";
	}
	printf("%s(%d): %s%s\n",
		(const char *)unicode2char(file),
		line, s.c_str(), (const char *)unicode2char(str));
}
Ejemplo n.º 8
0
void CaMuleExternalConnector::Show(const wxString &s)
{
	if( !m_KeepQuiet ) {
		printf("%s", (const char *)unicode2char(s));
#ifdef __WXMSW__
		fflush(stdout);
#endif
	}
}
Ejemplo n.º 9
0
void CHttpStateMachine::process_send_command_request(bool entry)
{
	if (entry) {
		// Prepare the request command buffer
		wxString ip = m_peerAddress->IPAddress();
		uint16 port = m_peerAddress->Service();
		wxString userPass;
		wxString userPassEncoded;
		if (m_proxyData.m_enablePassword) {
			userPass = m_proxyData.m_userName + wxT(":") + m_proxyData.m_password;
			userPassEncoded =
				EncodeBase64(unicode2char(userPass), userPass.Length());
		}
		wxString msg;
		
		switch (m_proxyCommand) {
		case PROXY_CMD_CONNECT:
			msg <<
			wxT("CONNECT ") << ip << wxT(":") << port << wxT(" HTTP/1.1\r\n") <<
			wxT("Host: ")   << ip << wxT(":") << port << wxT("\r\n");
			if (m_proxyData.m_enablePassword) {
				msg << 
				wxT("Authorization: Basic ")       << userPassEncoded << wxT("\r\n") <<
				wxT("Proxy-Authorization: Basic ") << userPassEncoded << wxT("\r\n");
			}
			msg << wxT("\r\n");
			break;
			
		case PROXY_CMD_BIND:
			m_ok = false;	
			break;
			
		case PROXY_CMD_UDP_ASSOCIATE:
			m_ok = false;
			return;
			break;
		}
		// Send the command packet
		m_packetLenght = msg.Len();
		memcpy(m_buffer, unicode2char(msg), m_packetLenght+1);
		ProxyWrite(*m_proxyClientSocket, m_buffer, m_packetLenght);
	}
}
Ejemplo n.º 10
0
void CSocks5StateMachine::process_send_authentication_username_password(bool entry)
{
	if (entry) {
		unsigned char lenUser = m_proxyData.m_userName.Len();
		unsigned char lenPassword = m_proxyData.m_password.Len();
		m_packetLenght = 1 + 1 + lenUser + 1 + lenPassword;
		unsigned int offsetUser = 2;
		unsigned int offsetPassword = offsetUser + lenUser + 1;
		
		// Prepare username/password buffer
		m_buffer[0] = SOCKS5_AUTH_VERSION_USERNAME_PASSWORD;
		m_buffer[offsetUser-1] = lenUser;
		memcpy(m_buffer+offsetUser, unicode2char(m_proxyData.m_userName),
			lenUser);
		m_buffer[offsetPassword-1] = lenPassword;
		memcpy(m_buffer+offsetPassword, unicode2char(m_proxyData.m_password),
			lenPassword);
		
		// Send the username/password packet
		ProxyWrite(*m_proxyClientSocket, m_buffer, m_packetLenght);
	}
}
Ejemplo n.º 11
0
bool CamulecmdApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
	m_HasCmdOnCmdLine = parser.Found(wxT("command"), &m_CmdString);
	if (m_CmdString.Lower().StartsWith(wxT("help")))
	{
		OnInitCommandSet();
		printf("%s %s\n", m_appname, (const char *)unicode2char(GetMuleVersion()));
		Parse_Command(m_CmdString);
		exit(0);
	}
	m_interactive = !m_HasCmdOnCmdLine;
	return CaMuleExternalConnector::OnCmdLineParsed(parser);
}
Ejemplo n.º 12
0
void CIP2Country::Enable()
{
	Disable();

	if (m_CountryDataMap.empty()) {
		LoadFlags();
	}

	if (!CPath::FileExists(m_DataBasePath)) {
		Update();
		return;
	}

	m_geoip = GeoIP_open(unicode2char(m_DataBasePath), GEOIP_STANDARD);
}
Ejemplo n.º 13
0
void CLogger::AddLogLine(
	const wxString &file,
	int line,
	bool critical,
	DebugType /*type*/,
	const std::ostringstream &msg)
{
	std::string s;
	if (critical) {
		s = "Critical message: ";
	}
	printf("%s(%d): %s%s\n",
		(const char *)unicode2char(file),
		line, s.c_str(), msg.str().c_str());
}
Ejemplo n.º 14
0
void CaMuleExternalConnector::OnAssertFailure(const wxChar *file, int line, const wxChar *func, const wxChar *cond, const wxChar *msg)
{
#if !defined wxUSE_STACKWALKER || !wxUSE_STACKWALKER
	wxString errmsg = CFormat( wxT("%s:%s:%d: Assertion '%s' failed. %s") ) % file % func % line % cond % ( msg ? msg : wxT("") );

	fprintf(stderr, "Assertion failed: %s\n", (const char*)unicode2char(errmsg));

	// Skip the function-calls directly related to the assert call.
	fprintf(stderr, "\nBacktrace follows:\n");
	print_backtrace(3);
	fprintf(stderr, "\n");
#else
	wxApp::OnAssertFailure(file, line, func, cond, msg);
#endif
}
Ejemplo n.º 15
0
void CLogger::DoLine(const wxString & line, bool toStdout, bool GUI_ONLY(toGUI))
{
	++m_count;

	// write to logfile
	m_ApplogBuf += line;
	FlushApplog();

	// write to Stdout
	if (m_StdoutLog || toStdout) {
		printf("%s", (const char*)unicode2char(line));
	}
#ifndef AMULE_DAEMON
	// write to Listcontrol
	if (toGUI) {
		theApp->AddGuiLogLine(line);
	}
#endif
}
Ejemplo n.º 16
0
void CStateMachine::Clock()
{
	t_sm_state old_state;
	t_sm_event event;
	bool state_entry;

	old_state = m_state;

	/* Process state change acording to event */
	if (!m_queue.empty()) {
		event = m_queue.front();
		m_queue.pop();
	} else {
		event = 0;
	}
	
	/* State changes can only happen here */
	wxMutexLocker lock(m_stateMutex);
	m_state = next_state( event );

//#if 0
	/* Debug */
	++m_clockCounter;
	state_entry = ( m_state != old_state ) || ( m_clockCounter == 1 );
	if( state_entry )
	{
		m_clocksInCurrentState = 0;
		printf( "%s(%04d): %d -> %d\n",
			(const char *)unicode2char(m_name),
			m_clockCounter, old_state, m_state);
	}
	++m_clocksInCurrentState;
//#endif

	/* Process new state entry */
	if( m_state < m_maxStates )
	{
		/* It should be ok to call Clock() recursively inside this
		 * procedure because state change has already happened. Also
		 * the m_state mutex is recursive. */
		process_state(m_state, state_entry);
	}
}
Ejemplo n.º 17
0
 /*
 * Method to show the results in the console
 */
void CamulecmdApp::ShowResults(CResultMap results_map)
{
	unsigned int name_max = 80;
	unsigned int mb_max = 5;
	unsigned int nr_max = 5;
	unsigned long int id = 0;
	wxString output, name, sources, mb , kb;

	printf("Nr.    Filename:                                                                        Size(MB):  Sources: \n");
	printf("-----------------------------------------------------------------------------------------------------------\n");

	for( std::map<unsigned long int,SearchFile*>::iterator iter = results_map.begin(); iter != results_map.end(); ++iter ) {
		id = (*iter).first;
		SearchFile* file = (*iter).second;

		output.Printf(wxT("%i.      "), id);
		output = output.SubString(0, nr_max).Append(file->sFileName).Append(' ', name_max);
		mb.Printf(wxT("     %d"), file->lFileSize/1024/1024);
		kb.Printf(wxT(".%d"), file->lFileSize/1024%1024);
		output = output.SubString(0, nr_max + name_max + mb_max - mb.Length() ).Append(mb).Append(kb);
		printf("%s     %ld\n",(const char*)unicode2char(output), file->lSourceCount );
	}
}
Ejemplo n.º 18
0
const CountryData& CIP2Country::GetCountryData(const wxString &ip)
{
	// Should prevent the crash if the GeoIP database does not exists
	if (m_geoip == NULL) {
		CountryDataMap::iterator it = m_CountryDataMap.find(wxString(wxT("unknown")));
		it->second.Name = wxT("?");
		return it->second;
	}

	// wxString::MakeLower() fails miserably in Turkish localization with their dotted/non-dotted 'i's
	// So fall back to some good ole C string processing.
	std::string strCode;
	const char * c = GeoIP_country_code_by_addr(m_geoip, unicode2char(ip));
	if (!c) {
		c = "unknown";
	}
	for ( ; *c; c++) {
		strCode += ((*c >= 'A' && *c <= 'Z') ? *c + 'a' - 'A' : *c);
	}

	const wxString CCode(strCode.c_str(), wxConvISO8859_1);

	CountryDataMap::iterator it = m_CountryDataMap.find(CCode);
	if (it == m_CountryDataMap.end()) {
		// Show the code and ?? flag
		it = m_CountryDataMap.find(wxString(wxT("unknown")));
		wxASSERT(it != m_CountryDataMap.end());
		if (CCode.IsEmpty()) {
			it->second.Name = wxT("?");
		} else{
			it->second.Name = CCode;
		}
	}

	return it->second;
}
Ejemplo n.º 19
0
/// Set Ed2k hash from a file
// returns false if aborted
bool Ed2kHash::SetED2KHashFromFile(const wxFileName& filename, MD4Hook hook)
{
  // Open file and let wxFFile destructor close the file
  // Closing it explicitly may crash on Win32 ...
  wxFFile file(filename.GetFullPath(), wxT("rbS"));
  if (! file.IsOpened())
    {
      wxLogError (_("Unable to open %s"),unicode2char(filename.GetFullPath()));
      return (false);
    }
  else
    {
      unsigned char ret[MD4_HASHLEN_BYTE];
      MD4Context hdc;

      size_t read;
      size_t partcount;
      size_t dataread;
      wxFileOffset totalread;

      char *buf = new char[BUFSIZE];

      bool goAhead = true;

#ifdef WANT_STRING_IMPLEMENTATION

      wxString tmpHash(wxEmptyString);
#else

      unsigned char* tmpCharHash = NULL;
#endif
      // Clear Ed2k Hash
      m_ed2kArrayOfHashes.Clear();

      // Processing each block
      totalread=0;
      partcount = 0;
      while (!file.Eof())
        {
          dataread = 0;
          MD4Init(&hdc);
          while (dataread < PARTSIZE && !file.Eof())
            {
              if (hook)
                {
                  goAhead = hook((int)((double)(100.0 * totalread) / file.Length()));
                }
              if (goAhead)
                {
                  if ((dataread + BUFSIZE) > PARTSIZE)
                    {
                      read = file.Read(buf, PARTSIZE - dataread);
                    }
                  else
                    {
                      read = file.Read(buf, BUFSIZE);
                    }
                  dataread += read;
                  totalread += read;
                  MD4Update(&hdc, reinterpret_cast<unsigned char const *>(buf),
                            read);
                }
              else
                {
                  return (false);
                }

            }
          MD4Final(&hdc, ret);

          // Add part-hash
          m_ed2kArrayOfHashes.Add(charToHex(reinterpret_cast<const char *>(ret),
                                            MD4_HASHLEN_BYTE));

          partcount++;

#ifdef WANT_STRING_IMPLEMENTATION
          // MD4_HASHLEN_BYTE is ABSOLUTLY needed as we dont want NULL
          // character to be interpreted as the end of the parthash string
#if wxUSE_UNICODE

          tmpHash += wxString(reinterpret_cast<const wchar_t *>(ret),MD4_HASHLEN_BYTE);
#else

          tmpHash += wxString(reinterpret_cast<const char *>(ret),MD4_HASHLEN_BYTE);
#endif
#else

          tmpCharHash = (unsigned char*)realloc(tmpCharHash,
                                                sizeof(unsigned char) * (MD4_HASHLEN_BYTE * partcount));
          memcpy ( tmpCharHash + MD4_HASHLEN_BYTE * (partcount - 1), ret, MD4_HASHLEN_BYTE );
#endif

        }

      delete [] buf;

      // hash == hash of concatenned parthashes
      if (partcount > 1)
        {
          wxString finalHash;

#ifdef WANT_STRING_IMPLEMENTATION

          finalHash=calcMd4FromString(tmpHash);
#else

          MD4Init(&hdc);
          MD4Update(&hdc, tmpCharHash, MD4_HASHLEN_BYTE * partcount);
          MD4Final(&hdc, ret);

          finalHash = charToHex(reinterpret_cast<const char *>(ret),
                                MD4_HASHLEN_BYTE);
#endif

          m_ed2kArrayOfHashes.Add(finalHash);
        }

#ifndef WANT_STRING_IMPLEMENTATION
      free(tmpCharHash);
      tmpCharHash=NULL;
#endif

      m_ed2kArrayOfHashes.Shrink();

      // Set members
      m_fileSize = file.Length();
      m_filename = filename.GetFullName();

      return true;
    }
}
Ejemplo n.º 20
0
bool CFile::Open(const wxString& fileName, OpenMode mode, int accessMode)
{
	MULE_VALIDATE_PARAMS(!fileName.IsEmpty(), wxT("CFile: Cannot open, empty path."));

#ifdef __linux__
	int flags = O_BINARY | O_LARGEFILE;
#else
	int flags = O_BINARY;
#endif

	switch ( mode ) {
		case read:
			flags |= O_RDONLY;
			break;
	
		case write_append:
			if (CheckFileExists(fileName))
			{
				flags |= O_WRONLY | O_APPEND;
				break;
			}
			//else: fall through as write_append is the same as write if the
			//      file doesn't exist
	
		case write:
			flags |= O_WRONLY | O_CREAT | O_TRUNC;
			break;
	
		case write_excl:
			flags |= O_WRONLY | O_CREAT | O_EXCL;
			break;

		case read_write:
			flags |= O_RDWR;
        	break;
	}

	if (IsOpened()) {
		Close();	
	}

	
	// When opening files, we will always first try to create an ANSI file name,
	// even if that means an extended ANSI file name. Only if it is not possible
	// to do that, we fall back to  UTF-8 file names. This is unicode safe and is
	// the only way to guarantee that we can open any file in the file system,
	// even if it is not an UTF-8 valid sequence.
	//
	
	
	// Test if it is possible to use an ANSI name
	Unicode2CharBuf tmpFileName = unicode2char(fileName);
	if (tmpFileName) {
		// Use an ANSI name
		m_fd = open(tmpFileName, flags, accessMode);
	} 
	
	if (m_fd == fd_invalid) { // Wrong conversion or can't open.
		// Try an UTF-8 name
		m_fd = open(unicode2UTF8(fileName), flags, accessMode);
	}
	
	m_filePath = fileName;

	SYSCALL_CHECK(m_fd != fd_invalid, wxT("opening file"));	
      
    return IsOpened();
}
Ejemplo n.º 21
0
bool CaMuleExternalConnector::OnCmdLineParsed(wxCmdLineParser& parser)
{
	if (parser.Found(wxT("version"))) {
		printf("%s %s\n", m_appname, (const char *)unicode2char(GetMuleVersion()));
		return false;
	}

	if (!parser.Found(wxT("config-file"), &m_configFileName)) {
		m_configFileName = GetConfigDir() + wxT("remote.conf");
	}

	wxString aMuleConfigFile;
	if (parser.Found(wxT("create-config-from"), &aMuleConfigFile)) {
		aMuleConfigFile = FinalizeFilename(aMuleConfigFile);
		if (!::wxFileExists(aMuleConfigFile)) {
			fprintf(stderr, "%s\n", (const char *)unicode2char(wxT("FATAL ERROR: File does not exist: ") + aMuleConfigFile));
			exit(1);
		}
		CECFileConfig aMuleConfig(aMuleConfigFile);
		LoadAmuleConfig(aMuleConfig);
		SaveConfigFile();
		m_configFile->Flush();
		exit(0);
	}

	LoadConfigFile();

	if ( !parser.Found(wxT("host"), &m_host) ) {
		if ( m_host.IsEmpty() ) {
			m_host = wxT("localhost");
		}
	}

	long port;
	if (parser.Found(wxT("port"), &port)) {
		m_port = port;
	}

	wxString pass_plain;
	if (parser.Found(wxT("password"), &pass_plain)) {
		if (!pass_plain.IsEmpty()) {
			m_password.Decode(MD5Sum(pass_plain).GetHash());
		} else {
			m_password.Clear();
		}
	}

	if (parser.Found(wxT("write-config"))) {
		m_NeedsConfigSave = true;
	}

	parser.Found(wxT("locale"), &m_language);

	if (parser.Found(wxT("help"))) {
		parser.Usage();
		return false;
	}

	m_KeepQuiet = parser.Found(wxT("quiet"));
	m_Verbose = parser.Found(wxT("verbose"));

	return true;
}
Ejemplo n.º 22
0
bool CamulewebApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
	wxString aMuleConfigFile;
	if (parser.Found(wxT("amule-config-file"), &aMuleConfigFile)) {
		aMuleConfigFile = FinalizeFilename(aMuleConfigFile);
		if (!::wxFileExists(aMuleConfigFile)) {
			fprintf(stderr, "FATAL ERROR: file '%s' does not exist.\n",
				(const char*)unicode2char(aMuleConfigFile));
			return false;
		}
		CECFileConfig cfg(aMuleConfigFile);
		LoadAmuleConfig(cfg);
		// do not process any other command-line parameters, use defaults instead

		if (!(m_TemplateOk = GetTemplateDir(m_TemplateName, m_TemplateDir))) {
			// no reason to run webserver without a template
			fprintf(stderr, "FATAL ERROR: Cannot find template: %s\n",
				(const char *)unicode2char(m_TemplateName));
			return true;
		}
		m_Verbose = false;
		m_KeepQuiet = true;
		m_LoadSettingsFromAmule = true;
		return true;
	}

	if (CaMuleExternalConnector::OnCmdLineParsed(parser)) {
		if ( parser.Found(wxT("no-php")) ) {
			fprintf(stderr, "WARNING: --no-php switch have no effect. Long live PHP\n");
		}

		parser.Found(wxT("template"), &m_TemplateName);
		if (m_TemplateName.IsEmpty()) {
			m_TemplateName = wxT("default");
		}
		if (!(m_TemplateOk = GetTemplateDir(m_TemplateName, m_TemplateDir))) {
			// no reason to run webserver without a template
			fprintf(stderr, "FATAL ERROR: Cannot find template: %s\n",
				(const char *)unicode2char(m_TemplateName));
			return true;
		}

		long port;
		if (parser.Found(wxT("server-port"), &port)) {
			m_WebserverPort = port;
		}
		if (parser.Found(wxT("enable-upnp"))) {
			m_UPnPWebServerEnabled = true;
		}
		if (parser.Found(wxT("upnp-port"), &port)) {
			m_UPnPTCPPort = port;
		}
		if (parser.Found(wxT("enable-gzip"))) {
			m_UseGzip = true;
		}
		if (parser.Found(wxT("disable-gzip"))) {
			m_UseGzip = false;
		}

		if (parser.Found(wxT("allow-guest"))) {
			m_AllowGuest = true;
		}
		if (parser.Found(wxT("deny-guest"))) {
			m_AllowGuest = false;
		}

		wxString tmp;
		if ( parser.Found(wxT("admin-pass"), &tmp) ) {
			if (tmp.IsEmpty()) {
				m_AdminPass.Clear();
			} else {
				m_AdminPass.Decode(MD5Sum(tmp).GetHash());
			}
		}
		if ( parser.Found(wxT("guest-pass"), &tmp) ) {
			if (tmp.IsEmpty()) {
				m_GuestPass.Clear();
			} else {
				m_GuestPass.Decode(MD5Sum(tmp).GetHash());
			}
		}

		m_LoadSettingsFromAmule = parser.Found(wxT("load-settings"));
		return true;
	} else {
		return false;
	}
}
Ejemplo n.º 23
0
int CamulecmdApp::ProcessCommand(int CmdId)
{
	wxString args = GetCmdArgs();
	CECPacket *request = 0;
	std::list<CECPacket *> request_list;
	int tmp_int = 0;
	EC_SEARCH_TYPE search_type = EC_SEARCH_KAD;

	// Implementation of the deprecated command 'SetIPFilter'.
	if (CmdId == CMD_ID_SET_IPFILTER) {
		if ( ! args.IsEmpty() ) {
			if (args.IsSameAs(wxT("ON"), false)) {
				CmdId = CMD_ID_SET_IPFILTER_ON;
			} else if (args.IsSameAs(wxT("OFF"), false)) {
				CmdId = CMD_ID_SET_IPFILTER_OFF;
			} else {
				return CMD_ERR_INVALID_ARG;
			}
		} else {
			CmdId = CMD_ID_GET_IPFILTER_STATE;
		}
	}

	switch (CmdId) {
		case CMD_ID_STATUS:
			request_list.push_back(new CECPacket(EC_OP_STAT_REQ, EC_DETAIL_CMD));
			break;

		case CMD_ID_SHUTDOWN:
			request_list.push_back(new CECPacket(EC_OP_SHUTDOWN));
			break;

		case CMD_ID_CONNECT:
			if ( !args.IsEmpty() ) {
				unsigned int ip[4];
				unsigned int port;
				// Not much we can do against this unicode2char.
				int result = sscanf(unicode2char(args), "%3d.%3d.%3d.%3d:%5d", &ip[0], &ip[1], &ip[2], &ip[3], &port);
				if (result != 5) {
					// Try to resolve DNS -- good for dynamic IP servers
					wxString serverName(args.BeforeFirst(wxT(':')));
					long lPort;
					bool ok = args.AfterFirst(wxT(':')).ToLong(&lPort);
					port = (unsigned int)lPort;
					amuleIPV4Address a;
					a.Hostname(serverName);
					a.Service(port);
					result = sscanf(unicode2char(a.IPAddress()), "%3d.%3d.%3d.%3d", &ip[0], &ip[1], &ip[2], &ip[3]);
					if (serverName.IsEmpty() || !ok || (result != 4)) {
						Show(_("Invalid IP format. Use xxx.xxx.xxx.xxx:xxxx\n"));
						return 0;
					}
				}
				EC_IPv4_t addr;
				addr.m_ip[0] = ip[0];
				addr.m_ip[1] = ip[1];
				addr.m_ip[2] = ip[2];
				addr.m_ip[3] = ip[3];
				addr.m_port = port;
				request = new CECPacket(EC_OP_SERVER_CONNECT);
				request->AddTag(CECTag(EC_TAG_SERVER, addr));
				request_list.push_back(request);
			} else {
				request_list.push_back(new CECPacket(EC_OP_CONNECT));
			}
			break;

		case CMD_ID_CONNECT_ED2K:
			request_list.push_back(new CECPacket(EC_OP_SERVER_CONNECT));
			break;

		case CMD_ID_CONNECT_KAD:
			request_list.push_back(new CECPacket(EC_OP_KAD_START));
			break;

		case CMD_ID_DISCONNECT:
			request_list.push_back(new CECPacket(EC_OP_DISCONNECT));
			break;

		case CMD_ID_DISCONNECT_ED2K:
			request_list.push_back(new CECPacket(EC_OP_SERVER_DISCONNECT));
			break;

		case CMD_ID_DISCONNECT_KAD:
			request_list.push_back(new CECPacket(EC_OP_KAD_STOP));
			break;

		case CMD_ID_RELOAD_SHARED:
			request_list.push_back(new CECPacket(EC_OP_SHAREDFILES_RELOAD));
			break;

		case CMD_ID_RELOAD_IPFILTER_LOCAL:
			request_list.push_back(new CECPacket(EC_OP_IPFILTER_RELOAD));
			break;

		case CMD_ID_RELOAD_IPFILTER_NET:
			request = new CECPacket(EC_OP_IPFILTER_UPDATE);
			request->AddTag(EC_TAG_STRING, args);
			request_list.push_back(request);
			break;

		case CMD_ID_SET_IPFILTER_ON:
		case CMD_ID_SET_IPFILTER_CLIENTS_ON:
		case CMD_ID_SET_IPFILTER_SERVERS_ON:
			tmp_int = 1;
		case CMD_ID_SET_IPFILTER_OFF:
		case CMD_ID_SET_IPFILTER_CLIENTS_OFF:
		case CMD_ID_SET_IPFILTER_SERVERS_OFF:
			{
				if (CmdId == CMD_ID_SET_IPFILTER_CLIENTS_ON || CmdId == CMD_ID_SET_IPFILTER_CLIENTS_OFF) {
					CmdId = CMD_ID_GET_IPFILTER_STATE_CLIENTS;
				} else if (CmdId == CMD_ID_SET_IPFILTER_SERVERS_ON || CmdId == CMD_ID_SET_IPFILTER_SERVERS_OFF) {
					CmdId = CMD_ID_GET_IPFILTER_STATE_SERVERS;
				} else {
					CmdId = CMD_ID_GET_IPFILTER_STATE;
				}

				request = new CECPacket(EC_OP_SET_PREFERENCES);
				CECEmptyTag prefs(EC_TAG_PREFS_SECURITY);
				if (CmdId != CMD_ID_GET_IPFILTER_STATE_SERVERS) {
					prefs.AddTag(CECTag(EC_TAG_IPFILTER_CLIENTS, (uint8)tmp_int));
				}
				if (CmdId != CMD_ID_GET_IPFILTER_STATE_CLIENTS) {
					prefs.AddTag(CECTag(EC_TAG_IPFILTER_SERVERS, (uint8)tmp_int));
				}
				request->AddTag(prefs);
				request_list.push_back(request);
			}
		case CMD_ID_GET_IPFILTER:
		case CMD_ID_GET_IPFILTER_STATE:
		case CMD_ID_GET_IPFILTER_STATE_CLIENTS:
		case CMD_ID_GET_IPFILTER_STATE_SERVERS:
			request = new CECPacket(EC_OP_GET_PREFERENCES);
			request->AddTag(CECTag(EC_TAG_SELECT_PREFS, (uint32)EC_PREFS_SECURITY));
			request_list.push_back(request);
			break;

		case CMD_ID_SET_IPFILTER_LEVEL:
			if (!args.IsEmpty()) // This 'if' must stay as long as we support the deprecated 'IPLevel' command.
			{
				unsigned long int level = 0;
				if (args.ToULong(&level) == true && level < 256) {
					request = new CECPacket(EC_OP_SET_PREFERENCES);
					CECEmptyTag prefs(EC_TAG_PREFS_SECURITY);
					prefs.AddTag(CECTag(EC_TAG_IPFILTER_LEVEL, (uint8)level));
					request->AddTag(prefs);
					request_list.push_back(request);
				} else {
					return CMD_ERR_INVALID_ARG;
				}
			}
			CmdId = CMD_ID_GET_IPFILTER_LEVEL;
		case CMD_ID_GET_IPFILTER_LEVEL:
			request = new CECPacket(EC_OP_GET_PREFERENCES);
			request->AddTag(CECTag(EC_TAG_SELECT_PREFS, (uint32)EC_PREFS_SECURITY));
			request_list.push_back(request);
			break;

		case CMD_ID_PAUSE:
		case CMD_ID_CANCEL:
		case CMD_ID_RESUME:
		{
			if ( args.IsEmpty() ) {
				Show(_("This command requires an argument. Valid arguments: 'all', filename, or a number.\n"));
				return 0;
			} else {
				wxStringTokenizer argsTokenizer(args);
				wxString token;
				CMD4Hash hash;

				// Grab the entire dl queue right away
				CECPacket request_all(EC_OP_GET_DLOAD_QUEUE, EC_DETAIL_CMD);
				const CECPacket *reply_all = SendRecvMsg_v2(&request_all);

				if (reply_all) {
					switch(CmdId) {
						case CMD_ID_PAUSE:
								request = new CECPacket(EC_OP_PARTFILE_PAUSE); break;
						case CMD_ID_CANCEL:
								request = new CECPacket(EC_OP_PARTFILE_DELETE); break;
						case CMD_ID_RESUME:
								request = new CECPacket(EC_OP_PARTFILE_RESUME); break;
						default: wxFAIL;
					}

					// We loop through all the arguments
					while(argsTokenizer.HasMoreTokens()) {
						token=argsTokenizer.GetNextToken();

						// If the user requested all, then we select all files and exit the loop
						// since there is little point to add anything more to "everything"
						if( token == wxT("all") ) {
							for (CECPacket::const_iterator it = reply_all->begin(); it != reply_all->end(); ++it) {
								const CEC_PartFile_Tag *tag = static_cast<const CEC_PartFile_Tag *>(&*it);
								request->AddTag(CECTag(EC_TAG_PARTFILE, tag->FileHash()));
							}
							break;
						} else if ( hash.Decode(token.Trim(false).Trim(true)) ) {
							if ( !hash.IsEmpty() ) {
								Show(_("Processing by hash: "+token+wxT("\n")));
								request->AddTag(CECTag(EC_TAG_PARTFILE, hash));
							}
						} else {
							 // Go through the dl queue and look at each filename
							for (CECPacket::const_iterator it = reply_all->begin(); it != reply_all->end(); ++it) {
								const CEC_PartFile_Tag *tag = static_cast<const CEC_PartFile_Tag *>(&*it);
								wxString partmetname = tag->PartMetName();

								// We check for filename, XXX.pat.met, XXX.part, XXX
								if( tag->FileName() == token ||
									partmetname == token ||
									partmetname.Truncate(partmetname.Len()-4) == token ||
									partmetname.Truncate(partmetname.Len()-5) == token) {
									Show(_("Processing by filename: "+token+wxT("\n")));
									request->AddTag(CECTag(EC_TAG_PARTFILE, tag->FileHash()));
								}
							}
						} // End of filename check else
					} // End of argument token loop

				request_list.push_back(request);

				delete reply_all;

				} // End of dl queue processing

			} // end of command processing
			break;
		}

		case CMD_ID_PRIORITY_LOW:
		case CMD_ID_PRIORITY_NORMAL:
		case CMD_ID_PRIORITY_HIGH:
		case CMD_ID_PRIORITY_AUTO:
			if ( args.IsEmpty() ) {
				Show(_("This command requires an argument. Valid arguments: a file hash.\n"));
				return 0;
			} else {
				CMD4Hash hash;
				if (hash.Decode(args.Trim(false).Trim(true))) {
					if (!hash.IsEmpty()) {
						request = new CECPacket(EC_OP_PARTFILE_PRIO_SET);
						CECTag hashtag(EC_TAG_PARTFILE, hash);
						switch(CmdId) {
							case CMD_ID_PRIORITY_LOW:
								hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, (uint8)PR_LOW));
								break;
							case CMD_ID_PRIORITY_NORMAL:
								hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, (uint8)PR_NORMAL));
								break;
							case CMD_ID_PRIORITY_HIGH:
								hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, (uint8)PR_HIGH));
								break;
							case CMD_ID_PRIORITY_AUTO:
								hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, (uint8)PR_AUTO));
								break;
							default: wxFAIL;
						}
						request->AddTag(hashtag);
						request_list.push_back(request);
					} else {
						Show(_("Not a valid number\n"));
						return 0;
					}
				} else {
						Show(_("Not a valid hash (length should be exactly 32 chars)\n"));
						return 0;
				}
			}
			break;

		case CMD_ID_SHOW_UL:
			request_list.push_back(new CECPacket(EC_OP_GET_ULOAD_QUEUE));
			break;

		case CMD_ID_SHOW_DL:
			request_list.push_back(new CECPacket(EC_OP_GET_DLOAD_QUEUE));
			break;

		case CMD_ID_SHOW_LOG:
			request_list.push_back(new CECPacket(EC_OP_GET_LOG));
			break;

		case CMD_ID_SHOW_SERVERS:
			request_list.push_back(new CECPacket(EC_OP_GET_SERVER_LIST, EC_DETAIL_CMD));
			break;

		case CMD_ID_SHOW_SHARED:
			request_list.push_back(new CECPacket(EC_OP_GET_SHARED_FILES));
			break;

		case CMD_ID_RESET_LOG:
			request_list.push_back(new CECPacket(EC_OP_RESET_LOG));
			break;

		case CMD_ID_ADDLINK:
			if (args.StartsWith(wxT("ed2k://"))) {
				//aMule doesn't like AICH links without |/| in front of h=
				if (args.Find(wxT("|h=")) > -1 && args.Find(wxT("|/|h=")) == -1) {
					args.Replace(wxT("|h="),wxT("|/|h="));
				}
				// repair links where | is replaced with %7C (Firefox)
				if (args.StartsWith(wxT("ed2k://%7C"))) {
					args.Replace(wxT("%7C"),wxT("|"));
				}
			}
			request = new CECPacket(EC_OP_ADD_LINK);
			request->AddTag(CECTag(EC_TAG_STRING, args));
			request_list.push_back(request);
			break;

		case CMD_ID_SET_BWLIMIT_UP:
			tmp_int = EC_TAG_CONN_MAX_UL - EC_TAG_CONN_MAX_DL;
		case CMD_ID_SET_BWLIMIT_DOWN:
			tmp_int += EC_TAG_CONN_MAX_DL;
			{
				unsigned long int limit;
				if (args.ToULong(&limit)) {
					request = new CECPacket(EC_OP_SET_PREFERENCES);
					CECEmptyTag prefs(EC_TAG_PREFS_CONNECTIONS);
					prefs.AddTag(CECTag(tmp_int, (uint16)limit));
					request->AddTag(prefs);
					request_list.push_back(request);
				} else {
					return CMD_ERR_INVALID_ARG;
				}
			}
		case CMD_ID_GET_BWLIMITS:
			request = new CECPacket(EC_OP_GET_PREFERENCES);
			request->AddTag(CECTag(EC_TAG_SELECT_PREFS, (uint32)EC_PREFS_CONNECTIONS));
			request_list.push_back(request);
			break;

		case CMD_ID_STATTREE:
			request = new CECPacket(EC_OP_GET_STATSTREE);
			if (!args.IsEmpty()) {
				unsigned long int max_versions;
				if (args.ToULong(&max_versions)) {
					if (max_versions < 256) {
						request->AddTag(CECTag(EC_TAG_STATTREE_CAPPING, (uint8)max_versions));
					} else {
						delete request;
						return CMD_ERR_INVALID_ARG;
					}
				} else {
					delete request;
					return CMD_ERR_INVALID_ARG;
				}
			}
			request_list.push_back(request);
			break;
		case CMD_ID_SEARCH_GLOBAL:
			search_type = EC_SEARCH_GLOBAL;
		case CMD_ID_SEARCH_LOCAL:
			if (search_type != EC_SEARCH_GLOBAL){
				search_type = EC_SEARCH_LOCAL;
			}
		case CMD_ID_SEARCH_KAD:
			if (search_type != EC_SEARCH_GLOBAL && search_type != EC_SEARCH_LOCAL){
				search_type = EC_SEARCH_KAD;
			}
			if (!args.IsEmpty())
			{
				wxString search = args;
				wxString type;
				wxString extention;
				uint32 avail = 0;
				uint32 min_size = 0;
				uint32 max_size = 0;

				request = new CECPacket(EC_OP_SEARCH_START);
				request->AddTag(CEC_Search_Tag (search, search_type, type, extention, avail, min_size, max_size));
				request_list.push_back(request);
			}
			break;
		case CMD_ID_SEARCH:
			/* TRANSLATORS:
			   'help search' is a command to the program, do not translate it. */
			Show(_("No search type defined.\nType 'help search' to get more help.\n"));
			break;


		case CMD_ID_SEARCH_RESULTS:
			request_list.push_back(new CECPacket(EC_OP_SEARCH_RESULTS, EC_DETAIL_FULL));
			break;

		case CMD_ID_SEARCH_PROGRESS:
			request_list.push_back(new CECPacket(EC_OP_SEARCH_PROGRESS));
			break;

		case CMD_ID_DOWNLOAD:
			if (!args.IsEmpty())
			{
				unsigned long int id = 0;
				if (args.ToULong(&id) == true && id < m_Results_map.size()) {

					SearchFile* file = m_Results_map[id];
					Show(CFormat(_("Download File: %lu %s\n")) % id % file->sFileName);
					request = new CECPacket(EC_OP_DOWNLOAD_SEARCH_RESULT);
					// get with id the hash and category=0
					uint32 category = 0;
					CECTag hashtag(EC_TAG_PARTFILE, file->nHash);
					hashtag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, category));
					request->AddTag(hashtag);
					request_list.push_back(request);
				} else {
					return CMD_ERR_INVALID_ARG;
				}
			}
			break;

		default:
			return CMD_ERR_PROCESS_CMD;
	}

	m_last_cmd_id = CmdId;

	if ( ! request_list.empty() ) {
		std::list<CECPacket *>::iterator it = request_list.begin();
		while ( it != request_list.end() ) {
			CECPacket *curr = *it++;
			if (curr->GetOpCode() == EC_OP_SHUTDOWN) {
				SendPacket(curr);
				delete curr;
				return CMD_ID_QUIT;
			}
			const CECPacket *reply = SendRecvMsg_v2(curr);
			delete curr;
			if ( reply ) {
				Process_Answer_v2(reply);
				delete reply;
			}
		}
		request_list.resize(0);
	}

	return CMD_OK;
}