Пример #1
0
static void simopen(const char *const *action) {
  const char *processid = action[0];
  const char *worktime = action[3];
  double sleeptime;
  const char *index = action[4];
  char full_name[1024];
  msg_file_t file = NULL;
  double clock = MSG_get_clock();       /* this "call" is free thanks to inlining */
  //Because the action open is too fast ,to catch up with the clock of the simulator, we let it to sleep for a while.
  sleeptime = atof(worktime);
  MSG_process_sleep(sleeptime);
  //open slow filename
  const char *file_name = action[2];
  char fn[200];
   strcpy(fn,file_name);
  ReplaceStr(fn,"/home","/slow");
  sprintf(full_name, "%s:%s:%s:%s","slow",file_name,MSG_process_get_name(MSG_process_self()),index);
  ACT_DEBUG("Entering Open: %s (filename: %s)", NAME, file_name);
  file = MSG_file_open(fn, NULL);
  xbt_dict_set(opened_files, full_name, file, NULL);
  //open fast filename
   strcpy(fn,file_name);
  ReplaceStr(fn,"/home","/fast");
  sprintf(full_name, "%s:%s:%s:%s","fast",file_name,MSG_process_get_name(MSG_process_self()),index);
  ACT_DEBUG("Entering Open: %s (filename: %s)", NAME, file_name);
  file = MSG_file_open(fn, NULL);
  xbt_dict_set(opened_files, full_name, file, NULL);
 
  log_action(action, MSG_get_clock() - clock);
  XBT_INFO("open worker %s%s is done",processid,index);
}
Пример #2
0
static int SelectExecRegexMatch(char *filename, char *crit, char *prog)
{
    char line[CF_BUFSIZE];
    FILE *pp;
    char buf[CF_MAXVARSIZE];

// insert real value of $(this.promiser) in command

    ReplaceStr(prog, buf, sizeof(buf), "$(this.promiser)", filename);
    ReplaceStr(prog, buf, sizeof(buf), "${this.promiser}", filename);

    if ((pp = cf_popen(buf, "r")) == NULL)
    {
        CfOut(cf_error, "cf_popen", "Couldn't open pipe to command %s\n", buf);
        return false;
    }

    while (!feof(pp))
    {
        line[0] = '\0';
        CfReadLine(line, CF_BUFSIZE, pp);       /* One buffer only */

        if (FullTextMatch(crit, line))
        {
            cf_pclose(pp);
            return true;
        }
    }

    cf_pclose(pp);
    return false;
}
Пример #3
0
static void simcreat(const char *const *action) {
  const char *processid = action[0];
  const char *worktime = action[3];
  double sleeptime;
  const char *index = action[4];
  char full_name[1024];
  msg_file_t file = NULL;
  double clock = MSG_get_clock();       /* this "call" is free thanks to inlining */
  sleeptime = atof(worktime);
  MSG_process_sleep(sleeptime);
  //open slow file
  const char *file_name = action[2];
  char fn[200];
   strcpy(fn,file_name);
  ReplaceStr(fn,"/home","/slow");
  sprintf(full_name, "%s:%s:%s:%s","slow",file_name,MSG_process_get_name(MSG_process_self()), index);
  ACT_DEBUG("Entering Creat: %s (filename: %s)", NAME, file_name);
  file = MSG_file_open(fn, NULL);
  xbt_dict_set(opened_files, full_name, file, NULL);
  //open fast version of file
  strcpy(fn,file_name);
  ReplaceStr(fn,"/home","/fast");
  sprintf(full_name, "%s:%s:%s:%s","fast",file_name,MSG_process_get_name(MSG_process_self()), index);
  ACT_DEBUG("Entering Creat: %s (filename: %s)", NAME, file_name);
  file = MSG_file_open(fn, NULL);
  xbt_dict_set(opened_files, full_name, file, NULL);
  
  log_action(action, MSG_get_clock() - clock);
  XBT_INFO("creat worker %s %s is done",processid,index);
}
Пример #4
0
const WORD* CResModule::CountMemReplaceMenuResource(const WORD * res, size_t * wordcount, WORD * newMenu)
{
	WORD		flags;
	WORD		id = 0;

	//struct PopupMenuItem { 
	//	WORD   fItemFlags; 
	//	WCHAR  szItemText[]; 
	//}; 
	//struct NormalMenuItem { 
	//	WORD   fItemFlags; 
	//	WORD   wMenuID; 
	//	WCHAR  szItemText[]; 
	//}; 

	do
	{
		flags = GET_WORD(res);
		res++;
		if (newMenu == NULL)
			(*wordcount)++;
		else
			newMenu[(*wordcount)++] = flags;
		if (!(flags & MF_POPUP))
		{
			id = GET_WORD(res);	//normal menu item
			res++;
			if (newMenu == NULL)
				(*wordcount)++;
			else
				newMenu[(*wordcount)++] = id;
		}
		else
			id = (WORD)-1;			//popup menu item

		if (flags & MF_POPUP)
		{
			ReplaceStr((LPCWSTR)res, newMenu, wordcount, &m_bTranslatedMenuStrings, &m_bDefaultMenuStrings);
			res += wcslen((LPCWSTR)res) + 1;

			if ((res = CountMemReplaceMenuResource(res, wordcount, newMenu))==0)
				return NULL;
		}
		else if (id != 0)
		{
			ReplaceStr((LPCWSTR)res, newMenu, wordcount, &m_bTranslatedMenuStrings, &m_bDefaultMenuStrings);
			res += wcslen((LPCWSTR)res) + 1;
		}
		else
		{
			if (newMenu)
				wcscpy((wchar_t *)&newMenu[(*wordcount)], (LPCWSTR)res);
			(*wordcount) += wcslen((LPCWSTR)res) + 1;
			res += wcslen((LPCWSTR)res) + 1;
		}
	} while (!(flags & MF_END));
	return res;
}
Пример #5
0
// Get network connection name from Ethernet device name
void GetEthNetworkConnectionName(wchar_t *dst, UINT size, char *device_name)
{
	WP_ADAPTER *t;
	char *tmp = NULL, guid[MAX_SIZE];
	wchar_t *ncname = NULL;

	UniStrCpy(dst, size, L"");

	// Validate arguments
	if (device_name == NULL || IsEthSupported() == false || 
		IsNt() == false || MsIsWin2000OrGreater() == false)
	{
		return;
	}

	Lock(eth_list_lock);

	InitEthAdaptersList();

	t = Win32EthSearch(device_name);

	if (t == NULL)
	{
		Unlock(eth_list_lock);
		return;
	}

	tmp = CopyStr(t->Name);
	Unlock(eth_list_lock);

	if (IsEmptyStr(t->Guid) == false)
	{
		StrCpy(guid, sizeof(guid), t->Guid);

		Free(tmp);
	}
	else
	{
		ReplaceStr(guid, sizeof(guid), tmp, "\\Device\\SEE_", "");
		Free(tmp);

		ReplaceStr(guid, sizeof(guid), guid, "\\Device\\NPF_", "");
		ReplaceStr(guid, sizeof(guid), guid, "\\Device\\PCD_", "");
	}

	if(guid == NULL)
	{
		return;
	}

	ncname = MsGetNetworkConnectionName(guid);
	if(ncname != NULL)
	{
		UniStrCpy(dst, size, ncname);
	}
	Free(ncname);
}
Пример #6
0
void __fastcall BrowseForExecutableT(T * Control, UnicodeString Title,
  UnicodeString Filter, bool FileNameCommand, bool Escape)
{
  UnicodeString Executable, Program, Params, Dir;
  Executable = Control->Text;
  if (FileNameCommand)
  {
    ReformatFileNameCommand(Executable);
  }
  SplitCommand(Executable, Program, Params, Dir);

  TOpenDialog * FileDialog = new TOpenDialog(Application);
  try
  {
    if (Escape)
    {
      Program = ReplaceStr(Program, L"\\\\", L"\\");
    }
    UnicodeString ExpandedProgram = ExpandEnvironmentVariables(Program);
    FileDialog->FileName = ExpandedProgram;
    UnicodeString InitialDir = ExtractFilePath(ExpandedProgram);
    if (!InitialDir.IsEmpty())
    {
      FileDialog->InitialDir = InitialDir;
    }
    FileDialog->Filter = Filter;
    FileDialog->Title = Title;

    if (FileDialog->Execute())
    {
      TNotifyEvent PrevOnChange = Control->OnChange;
      Control->OnChange = NULL;
      try
      {
        // preserve unexpanded file, if the destination has not changed actually
        if (!CompareFileName(ExpandedProgram, FileDialog->FileName))
        {
          Program = FileDialog->FileName;
          if (Escape)
          {
            Program = ReplaceStr(Program, L"\\", L"\\\\");
          }
        }
        Control->Text = FormatCommand(Program, Params);
      }
      __finally
      {
        Control->OnChange = PrevOnChange;
      }

      if (Control->OnExit != NULL)
      {
        Control->OnExit(Control);
      }
    }
  }
Пример #7
0
UnicodeString __fastcall TSrvResponse::ReadString(TSrvResponseValID ID,
	UnicodeString DefVal, bool MultiLine)
{
	UnicodeString val = this->Read(ID);
	if (MultiLine) {
		val = ReplaceStr(val, L"<br />", "\n");
		val = ReplaceStr(val, L"<br>", "\n");
		val = ReplaceStr(val, L"<BR>", "\n");
	}

	return val.IsEmpty()? DefVal : val;
}
Пример #8
0
int _tmain(int argc, _TCHAR* argv[])
{
	char szTem1[MAX_PATH] = {"abcd-efgh-ijklm-nopq ABCD-EFGH-IJKLM-NOPQ"};
	char szTem2[MAX_PATH] = {0};
	char* pTem = strlwr(szTem1);  //字符串中字符的大小写转换(strlwr和strupr) 
	char szTemp1[MAX_PATH] = {"abcd-efgh-ijklm-nopq"};
	char szTemp2[MAX_PATH] = {"D:\\360data\\重要数据\\桌面\\工作相关项目"};
	ReplaceStr(szTemp1,"-","");//把字符串中的“-”删除掉!

	ReplaceStr(szTemp2,"\\","/");
	return 0;
}
Пример #9
0
//---------------------------------------------------------------------------
//WARNING: Do not change the argument to a reference. It will crash the IDE
void __fastcall TRecent::SetHint(String Str)
{
  FHint = Str;
  for(unsigned I = 0; I < FileList.size(); I++)
    if(FileList[I].second)
      static_cast<TCustomAction*>(FileList[I].second->Action)->Hint = ReplaceStr(FHint, "%s", FileList[I].first);
}
Пример #10
0
bool mz::JSON2SQLite::Action()
{
	mz::JSONParser* parser = (mz::JSONParser*)mp_json;
	mz::JSONParser::Node* tables = parser->GetRootNode();

	if( tables == NULL ) return false;

	while( mz::JSONParser::Node* table = tables->Next() )
	{
		std::string tableName;
		table->GetNodeName(tableName);
		while( mz::JSONParser::Node* row = table->Next() )
		{
			std::string fields = "";
			std::string values = "";
			bool first = true;
			_FieldInfoTable myTable = table_info[tableName];
			while( mz::JSONParser::Node* col = row->Next() )
			{
				std::string field;
				std::string value;

				col->GetNodeName(field);
				col->GetNodeValue(value);

				if(myTable[field] == 'T')
				{
					ReplaceStr(value, "'", "''");
					value = "'" + value + "'";
				}

				if(first)
				{
					fields = field;
					values = value;
					first = false;
				}
				else
				{
					fields += ',' + field;
					values += ',' + value;
				}

				delete col;
			}
			delete row;

			if(first == false)
			{
				std::string sql = "INSERT INTO " + tableName + " (" + fields + ") VALUES (" + values + ");";
				std::cout<<sql<<std::endl;
			}
		}
		delete table;
	}
	delete tables;

	return true;
}
bool PathManager::ReplaceAppPakNameInXml(QString &srcPath, QString &fileName, QString &oldName, QString &newName)
{
	QString oldNmSpace = "\"http://schemas.android.com/apk/res/" + oldName + "\"";
	QString newNmSpace = "\"http://schemas.android.com/apk/res/" + newName + "\"";
	if (!ReplaceStr(fileName, oldNmSpace, newNmSpace)){
		return false;
	}
	return true;
}
Пример #12
0
//---------------------------------------------------------------------------
static TStrings * __fastcall StackInfoListToStrings(
  TJclStackInfoList * StackInfoList)
{
  std::unique_ptr<TStrings> StackTrace(new TStringList());
  StackInfoList->AddToStrings(StackTrace.get(), true, false, true, false);
  // get rid of __fastcall declarations that are included in .map
  StackTrace->Text = ReplaceStr(StackTrace->Text, L"__fastcall ", L"");
  return StackTrace.release();
}
Пример #13
0
//---------------------------------------------------------------------------
void __fastcall TSynchronizeDialog::DoLogInternal(
  TSynchronizeLogEntry Entry, const UnicodeString & Message,
  TStrings * MoreMessages, TQueryType Type, const UnicodeString & HelpKeyword)
{
  LogView->Items->BeginUpdate();
  try
  {
    TListItem * Item = LogView->Items->Add();

    TLogItemData * LogItemData = new TLogItemData();
    Item->Data = LogItemData;
    LogItemData->Entry = Entry;
    LogItemData->Message = Message;
    if (MoreMessages != NULL)
    {
      LogItemData->MoreMessages.reset(new TStringList());
      LogItemData->MoreMessages->Assign(MoreMessages);
    }
    LogItemData->Type = Type;
    LogItemData->HelpKeyword = HelpKeyword;

    Item->Caption = Now().TimeString();

    UnicodeString UnformattedMessage = UnformatMessage(Message);
    UnformattedMessage = ReplaceStr(UnformattedMessage, L"\r", L"");
    UnformattedMessage = ReplaceStr(UnformattedMessage, L"\n", L" ");

    Item->SubItems->Add(UnformattedMessage);
    Item->MakeVisible(false);
    while (LogView->Items->Count > MaxLogItems)
    {
      LogView->Items->Delete(0);
    }
  }
  __finally
  {
    LogView->Items->EndUpdate();
    if (Entry == slScan)
    {
      // redraw log before the scanning block update
      LogView->Repaint();
    }
  }
}
Пример #14
0
static bool SelectExecRegexMatch(EvalContext *ctx, char *filename, char *crit, char *prog)
{
    char line[CF_BUFSIZE];
    FILE *pp;
    char buf[CF_MAXVARSIZE];

// insert real value of $(this.promiser) in command

    ReplaceStr(prog, buf, sizeof(buf), "$(this.promiser)", filename);
    ReplaceStr(prog, buf, sizeof(buf), "${this.promiser}", filename);

    if ((pp = cf_popen(buf, "r", true)) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open pipe to command '%s'. (cf_popen: %s)", buf, GetErrorStr());
        return false;
    }

    for (;;)
    {
        ssize_t res = CfReadLine(line, CF_BUFSIZE, pp);
        if (res == -1)
        {
            Log(LOG_LEVEL_ERR, "Error reading output from command '%s'. (fgets: %s)", buf, GetErrorStr());
            cf_pclose(pp);
            return false;
        }

        if (res == 0)
        {
            cf_pclose(pp);
            return false;
        }

        if (FullTextMatch(ctx, crit, line))
        {
            cf_pclose(pp);
            return true;
        }
    }

    cf_pclose(pp);
    return false;
}
bool PathManager::ReplaceAppPakNameInSmali(QString &fileName, QString &oldName, QString &newName)
{
	if (fileName.toLower().endsWith(".smali")){
		QString oldNameTmp = oldName;
		QString newNameTmp = newName;
		oldNameTmp.replace(".", "/");
		newNameTmp.replace(".", "/");
		return ReplaceStr(fileName, oldNameTmp, newNameTmp);
	}
	return true;
}
Пример #16
0
static int SelectExecProgram(char *filename, char *command)
  /* command can include $(this.promiser) for the name of the file */
{
    char buf[CF_MAXVARSIZE];

// insert real value of $(this.promiser) in command

    ReplaceStr(command, buf, sizeof(buf), "$(this.promiser)", filename);
    ReplaceStr(command, buf, sizeof(buf), "${this.promiser}", filename);

    if (ShellCommandReturnsZero(buf, false))
    {
        CfDebug(" - ? Select ExecProgram match for %s\n", buf);
        return true;
    }
    else
    {
        return false;
    }
}
Пример #17
0
static int SelectExecProgram(char *filename, char *command)
  /* command can include $(this.promiser) for the name of the file */
{
    char buf[CF_MAXVARSIZE];

// insert real value of $(this.promiser) in command

    ReplaceStr(command, buf, sizeof(buf), "$(this.promiser)", filename);
    ReplaceStr(command, buf, sizeof(buf), "${this.promiser}", filename);

    if (ShellCommandReturnsZero(buf, SHELL_TYPE_NONE))
    {
        Log(LOG_LEVEL_DEBUG, "Select ExecProgram match for '%s'", buf);
        return true;
    }
    else
    {
        return false;
    }
}
Пример #18
0
UnicodeString UnMungeIniName(const UnicodeString & Str)
{
  intptr_t P = Str.Pos(L"%3D");
  // make this fast for now
  if (P > 0)
  {
    return ReplaceStr(Str, L"%3D", L"=");
  }
  else
  {
    return Str;
  }
}
Пример #19
0
void EvalXReplace(const void *data, qCtx *ctx, qStr *out, qArgAry *args) {
	int i = 1;
	CStr in = (*args)[0];
	while (i < args->Count()) {
		CStr from = (*args)[i];
		if (!in.IsEmpty() && !from.IsEmpty()) {
			CStr to = (*args)[i+1];
			in = ReplaceStr(in, from, to);
		}
		i += 2;
	}
	out->PutS(in);
}
Пример #20
0
//---------------------------------------------------------------------------
//This function shows file names in the menu
void __fastcall TRecent::ShowMenuItems(void)
{
  if(!FFileMenu || FileList.empty() || !Enabled)//If nowhere to show or nothing to show
    return;

  Seperator1 = FFileMenu->Add();
  Seperator1->Caption = '-';//Make seperator

  for(unsigned I = 0; I < FileList.size(); I++)
  {
    //Loop through all file names
    //Add menu item at the bottom
    TActionClientItem *MenuItem = FFileMenu->Add();
    TOpenFileAction *Action = new TOpenFileAction(FileList[I].first, this);
    MenuItem->Action = Action;
    MenuItem->Caption = "&" + String(I+1) + " " + CompactPath(FileList[I].first, FMaxPathLen);
    //Set hint and substitute %s with the filename
    Action->Hint = ReplaceStr(FHint, "%s", FileList[I].first);
    FileList[I].second = MenuItem;//Add pointer to menu item to FileList
  }
}
Пример #21
0
//
//  関数: WndProc(HWND, unsigned, WORD, LONG)
//
//  用途: メイン ウィンドウのメッセージを処理します。
//
//  WM_COMMAND	- アプリケーション メニューの処理
//  WM_PAINT	- メイン ウィンドウの描画
//  WM_DESTROY	- 終了メッセージの通知とリターン
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int ret;
	char szMsg[512];
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	TCHAR szHello[MAX_LOADSTRING];
	LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

	switch (message) {
	case WM_COMMAND:
		wmId    = LOWORD(wParam); 
		wmEvent = HIWORD(wParam); 
		// メニュー選択の解析:
		switch (wmId) {
		case IDM_ABOUT:
			DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		case IDM_TEST_ISLAYERED:
			try
			{
				wsprintf(szMsg, "IsLayered = %d", IsLayered(hWnd));
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			catch(DWORD e)
			{
				wsprintf(szMsg, "IsLayered error %d", e);
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			break;
		case IDM_TEST_SETLAYERED_A:
			ret = SetLayered(hWnd, true);
			if (ret != 0) {
				wsprintf(szMsg, "SetLayered(true) error %d", ret);
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			break;
		case IDM_TEST_SETLAYERED_B:
			ret = SetLayered(hWnd, false);
			if (ret != 0) {
				wsprintf(szMsg, "SetLayered(false) error %d", ret);
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			break;
		case IDM_TEST_OPACITY50:
			ret = SetOpacity(hWnd, 0.5);
			if (ret != 0) {
				wsprintf(szMsg, "SetOpacity error %d", ret);
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			break;
		case IDM_TEST_OPACITY100:
			ret = SetOpacity(hWnd, 1.0);
			if (ret != 0) {
				wsprintf(szMsg, "SetOpacity error %d", ret);
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			break;
		case IDM_TEST_REPLACE1:
			{
				char* pszSrc = "c:\\表示\\データ.txt";
				std::string ret = ReplaceStr(pszSrc, "\\", "");
				if (!ret.empty()) {
					wsprintf(szMsg, "%s => %s", pszSrc, ret.c_str());
				} else {
					wsprintf(szMsg, "エラー");
				}
				MessageBox(hWnd, szMsg, NULL, MB_OK);
			}
			break;

		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;

	case WM_PAINT:
		hdc = BeginPaint (hWnd, &ps);
		// TODO: この位置に描画用のコードを追加してください...
		RECT rt;
		GetClientRect(hWnd, &rt);
		DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
		EndPaint(hWnd, &ps);
		break;

	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
   }

   return 0;
}
Пример #22
0
void qObjProto::EvalSmtpMail(qCtx *ctx, qStr *out, qArgAry *args)
{
    if (args->Count() >= 4) {
        qMailOpts qmop;

        qmop.host = (*args)[0];
        qmop.smtp = qmop.host;
        qmop.user = (*args)[1].GetBuffer();
        qmop.from = (*args)[2];
        qmop.subj = (*args)[4];

        qmop.subj = ReplaceStr(qmop.subj, "\n", "");
        qmop.subj = ReplaceStr(qmop.subj, "\r", "");
        qmop.from = ReplaceStr(qmop.from, "\n", "");
        qmop.from = ReplaceStr(qmop.from, "\r", "");
        qmop.host = ReplaceStr(qmop.host, "\n", "");
        qmop.host = ReplaceStr(qmop.host, "\r", "");

        qmop.body.Add("'" << (*args)[5]);

        if (qsUnreg)
            qmop.unreg = true;

        int i = 6;
        while (args->GetAt(i)) {
            qmop.body.Add((*args)[i++]);
        }

        // FIX QMAIL LACK OF MULTIPLE -TO- HEADERS!

        CStr rcpt = (*args)[3];
        ReplaceStr(rcpt, "\n", "");
        ReplaceStr(rcpt, "\r", "");

        char * rx = rcpt.GetBuffer();
        char * tok = rx;
        char * p   = strchr(tok, ';');
        if (p) *p = '\0';
        while (tok) {
            while (isspace(*tok))
                ++tok;
            if (*tok) {
                qmop.rcpt = tok;
                qmop.to = tok;

                try {
                    int errVal = qsmtp(&qmop);
                    if (errVal)
                        ctx->ThrowF(out, errVal+600, "Mail error #%d.", errVal);
                } catch (CEx ex) {
                    ctx->Throw(out, ex.id+600, ex.msg);
                }
            }
            if (p) {
                tok = p + 1;
                p   = strchr(tok, ';');
                if (p) *p = '\0';
            } else
                tok = NULL;
        }
    } else {
        ctx->Throw(out, 655, "USAGE: %smtp-mail(host, user, from, to, subj, body...)");
    }

    return;
}
Пример #23
0
void LocalExec(const ExecConfig *config)
{
    FILE *pp;
    char line[CF_BUFSIZE], line_escaped[sizeof(line) * 2], filename[CF_BUFSIZE], *sp;
    char cmd[CF_BUFSIZE], esc_command[CF_BUFSIZE];
    int print, count = 0;
    void *thread_name;
    time_t starttime = time(NULL);
    char starttime_str[64];
    FILE *fp;
    char canonified_fq_name[CF_BUFSIZE];

    thread_name = ThreadUniqueName();

    cf_strtimestamp_local(starttime, starttime_str);

    CfOut(cf_verbose, "", "------------------------------------------------------------------\n\n");
    CfOut(cf_verbose, "", "  LocalExec(%sscheduled) at %s\n", config->scheduled_run ? "" : "not ", starttime_str);
    CfOut(cf_verbose, "", "------------------------------------------------------------------\n");

/* Need to make sure we have LD_LIBRARY_PATH here or children will die  */

    if (strlen(config->exec_command) > 0)
    {
        strncpy(cmd, config->exec_command, CF_BUFSIZE - 1);

        if (!strstr(cmd, "-Dfrom_cfexecd"))
        {
            strcat(cmd, " -Dfrom_cfexecd");
        }
    }
    else
    {
        ConstructFailsafeCommand(config->scheduled_run, cmd);
    }

    strncpy(esc_command, MapName(cmd), CF_BUFSIZE - 1);

    snprintf(line, CF_BUFSIZE - 1, "_%jd_%s", (intmax_t) starttime, CanonifyName(cf_ctime(&starttime)));

    strlcpy(canonified_fq_name, config->fq_name, CF_BUFSIZE);
    CanonifyNameInPlace(canonified_fq_name);

    snprintf(filename, CF_BUFSIZE - 1, "%s/outputs/cf_%s_%s_%p", CFWORKDIR, canonified_fq_name, line, thread_name);
    MapName(filename);

/* What if no more processes? Could sacrifice and exec() - but we need a sentinel */

    if ((fp = fopen(filename, "w")) == NULL)
    {
        CfOut(cf_error, "fopen", "!! Couldn't open \"%s\" - aborting exec\n", filename);
        return;
    }

#if !defined(__MINGW32__)
/*
 * Don't inherit this file descriptor on fork/exec
 */

    if (fileno(fp) != -1)
    {
        fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
    }
#endif

    CfOut(cf_verbose, "", " -> Command => %s\n", cmd);

    if ((pp = cf_popen_sh(esc_command, "r")) == NULL)
    {
        CfOut(cf_error, "cf_popen", "!! Couldn't open pipe to command \"%s\"\n", cmd);
        fclose(fp);
        return;
    }

    CfOut(cf_verbose, "", " -> Command is executing...%s\n", esc_command);

    while (!feof(pp))
    {
        if(!IsReadReady(fileno(pp), (config->agent_expireafter * SECONDS_PER_MINUTE)))
        {
            char errmsg[CF_MAXVARSIZE];
            snprintf(errmsg, sizeof(errmsg), "cf-execd: !! Timeout waiting for output from agent (agent_expireafter=%d) - terminating it",
                     config->agent_expireafter);

            CfOut(cf_error, "", "%s", errmsg);
            fprintf(fp, "%s\n", errmsg);
            count++;

            pid_t pid_agent;

            if(PipeToPid(&pid_agent, pp))
            {
                ProcessSignalTerminate(pid_agent);
            }
            else
            {
                CfOut(cf_error, "", "!! Could not get PID of agent");
            }

            break;
        }

        {
            ssize_t num_read = CfReadLine(line, CF_BUFSIZE, pp);
            if (num_read == -1)
            {
                FatalError("Cannot continue on CfReadLine error");
            }
            else if (num_read == 0)
            {
                break;
            }
        }

        if(!CfReadLine(line, CF_BUFSIZE, pp))
        {
            break;
        }

        if (ferror(pp))
        {
            fflush(pp);
            break;
        }

        print = false;

        for (sp = line; *sp != '\0'; sp++)
        {
            if (!isspace((int) *sp))
            {
                print = true;
                break;
            }
        }

        if (print)
        {
            // we must escape print format chars (%) from output

            ReplaceStr(line, line_escaped, sizeof(line_escaped), "%", "%%");

            fprintf(fp, "%s\n", line_escaped);
            count++;

            /* If we can't send mail, log to syslog */

            if (strlen(config->mail_to_address) == 0)
            {
                strncat(line_escaped, "\n", sizeof(line_escaped) - 1 - strlen(line_escaped));
                if ((strchr(line_escaped, '\n')) == NULL)
                {
                    line_escaped[sizeof(line_escaped) - 2] = '\n';
                }

                CfOut(cf_inform, "", "%s", line_escaped);
            }

            line[0] = '\0';
            line_escaped[0] = '\0';
        }
    }

    cf_pclose(pp);
    CfDebug("Closing fp\n");
    fclose(fp);

    CfOut(cf_verbose, "", " -> Command is complete\n");

    if (count)
    {
        CfOut(cf_verbose, "", " -> Mailing result\n");
        MailResult(config, filename);
    }
    else
    {
        CfOut(cf_verbose, "", " -> No output\n");
        unlink(filename);
    }
}
Пример #24
0
static bool IsReadReady(int fd, int timeout_sec)
{
    fd_set  rset;
    FD_ZERO(&rset);
    FD_SET(fd, &rset);

    struct timeval tv = {
        .tv_sec = timeout_sec,
        .tv_usec = 0,
    };

    int ret = select(fd + 1, &rset, NULL, NULL, &tv);

    if(ret < 0)
    {
        Log(LOG_LEVEL_ERR, "IsReadReady: Failed checking for data. (select: %s)", GetErrorStr());
        return false;
    }

    if(FD_ISSET(fd, &rset))
    {
        return true;
    }

    if(ret == 0)  // timeout
    {
        return false;
    }

    // can we get here?
    Log(LOG_LEVEL_ERR, "IsReadReady: Unknown outcome (ret > 0 but our only fd is not set). (select: %s)", GetErrorStr());

    return false;
}
#if defined(__hpux) && defined(__GNUC__)
#pragma GCC diagnostic warning "-Wstrict-aliasing"
#endif

#endif  /* __MINGW32__ */

void LocalExec(const ExecConfig *config)
{
    time_t starttime = time(NULL);

    void *thread_name = ThreadUniqueName();

    {
        char starttime_str[64];
        cf_strtimestamp_local(starttime, starttime_str);

        if (LEGACY_OUTPUT)
        {
            Log(LOG_LEVEL_VERBOSE, "------------------------------------------------------------------");
            Log(LOG_LEVEL_VERBOSE, "  LocalExec(%sscheduled) at %s", config->scheduled_run ? "" : "not ", starttime_str);
            Log(LOG_LEVEL_VERBOSE, "------------------------------------------------------------------");
        }
        else
        {
            Log(LOG_LEVEL_VERBOSE, "LocalExec(%sscheduled) at %s", config->scheduled_run ? "" : "not ", starttime_str);
        }
    }

/* Need to make sure we have LD_LIBRARY_PATH here or children will die  */

    char cmd[CF_BUFSIZE];
    if (strlen(config->exec_command) > 0)
    {
        strncpy(cmd, config->exec_command, CF_BUFSIZE - 1);

        if (!strstr(cmd, "-Dfrom_cfexecd"))
        {
            strcat(cmd, " -Dfrom_cfexecd");
        }
    }
    else
    {
        ConstructFailsafeCommand(config->scheduled_run, cmd);
    }

    char esc_command[CF_BUFSIZE];
    strncpy(esc_command, MapName(cmd), CF_BUFSIZE - 1);

    char line[CF_BUFSIZE];
    snprintf(line, CF_BUFSIZE - 1, "_%jd_%s", (intmax_t) starttime, CanonifyName(ctime(&starttime)));

    char filename[CF_BUFSIZE];
    {
        char canonified_fq_name[CF_BUFSIZE];

        strlcpy(canonified_fq_name, config->fq_name, CF_BUFSIZE);
        CanonifyNameInPlace(canonified_fq_name);


        snprintf(filename, CF_BUFSIZE - 1, "%s/outputs/cf_%s_%s_%p", CFWORKDIR, canonified_fq_name, line, thread_name);
        MapName(filename);
    }


/* What if no more processes? Could sacrifice and exec() - but we need a sentinel */

    FILE *fp = fopen(filename, "w");
    if (!fp)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open '%s' - aborting exec. (fopen: %s)", filename, GetErrorStr());
        return;
    }

#if !defined(__MINGW32__)
/*
 * Don't inherit this file descriptor on fork/exec
 */

    if (fileno(fp) != -1)
    {
        fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
    }
#endif

    Log(LOG_LEVEL_VERBOSE, "Command => %s", cmd);

    FILE *pp = cf_popen_sh(esc_command, "r");
    if (!pp)
    {
        Log(LOG_LEVEL_ERR, "Couldn't open pipe to command '%s'. (cf_popen: %s)", cmd, GetErrorStr());
        fclose(fp);
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Command is executing...%s", esc_command);

    int count = 0;
    for (;;)
    {
        if(!IsReadReady(fileno(pp), (config->agent_expireafter * SECONDS_PER_MINUTE)))
        {
            char errmsg[CF_MAXVARSIZE];
            snprintf(errmsg, sizeof(errmsg), "cf-execd: !! Timeout waiting for output from agent (agent_expireafter=%d) - terminating it",
                     config->agent_expireafter);

            Log(LOG_LEVEL_ERR, "%s", errmsg);
            fprintf(fp, "%s\n", errmsg);
            count++;

            pid_t pid_agent;

            if(PipeToPid(&pid_agent, pp))
            {
                ProcessSignalTerminate(pid_agent);
            }
            else
            {
                Log(LOG_LEVEL_ERR, "Could not get PID of agent");
            }

            break;
        }

        ssize_t res = CfReadLine(line, CF_BUFSIZE, pp);

        if (res == 0)
        {
            break;
        }

        if (res == -1)
        {
            Log(LOG_LEVEL_ERR, "Unable to read output from command '%s'. (cfread: %s)", cmd, GetErrorStr());
            cf_pclose(pp);
            return;
        }

        bool print = false;

        for (const char *sp = line; *sp != '\0'; sp++)
        {
            if (!isspace((int) *sp))
            {
                print = true;
                break;
            }
        }

        if (print)
        {
            char line_escaped[sizeof(line) * 2];

            // we must escape print format chars (%) from output

            ReplaceStr(line, line_escaped, sizeof(line_escaped), "%", "%%");

            fprintf(fp, "%s\n", line_escaped);
            count++;

            /* If we can't send mail, log to syslog */

            if (strlen(config->mail_to_address) == 0)
            {
                strncat(line_escaped, "\n", sizeof(line_escaped) - 1 - strlen(line_escaped));
                if ((strchr(line_escaped, '\n')) == NULL)
                {
                    line_escaped[sizeof(line_escaped) - 2] = '\n';
                }

                Log(LOG_LEVEL_INFO, "%s", line_escaped);
            }

            line[0] = '\0';
            line_escaped[0] = '\0';
        }
    }

    cf_pclose(pp);
    Log(LOG_LEVEL_DEBUG, "Closing fp");
    fclose(fp);

    Log(LOG_LEVEL_VERBOSE, "Command is complete");

    if (count)
    {
        Log(LOG_LEVEL_VERBOSE, "Mailing result");
        MailResult(config, filename);
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "No output");
        unlink(filename);
    }
}
Пример #25
0
bool UserCmd_BountyAddTo(uint iClientID, const wstring &wscCmd, const wstring &wscParam, const wchar_t *usage)
{
	if (!bPluginEnabled)
	{
		PrintUserCmdText(iClientID, L"BountyTracker is disabled.");
		return true;
	}

	// Get the parameters from the user command.
	wstring wscName = GetParam(wscParam, L' ', 0);
	wstring wscCash = GetParam(wscParam, L' ', 1);
	wstring wscxTimes = GetParam(wscParam, L' ', 2);
	wscCash = ReplaceStr(wscCash, L".", L"");
	wscCash = ReplaceStr(wscCash, L",", L"");
	wscCash = ReplaceStr(wscCash, L"$", L"");
	wscCash = ReplaceStr(wscCash, L"e6", L"000000");

	if (wscName == L"")
	{
		PrintUserCmdText(iClientID, L"ERR invalid name\n");
		return false;
	}
	if (HkGetAccountByCharname(wscName) == 0)
	{
		PrintUserCmdText(iClientID, L"ERR Player does not exist");
		return true;
	}
	if (wscCash == L"")
	{
		PrintUserCmdText(iClientID, L"ERR invalid cash amount\n");
		return false;
	}
	if (stoi(wscCash) < 1000000)
	{
		PrintUserCmdText(iClientID, L"ERR bounty cannot be less than 1,000,000 s.c");
		return true;
	}
	//get bounty 
	BountyTargetInfo BTIat = mapBountyTargets[ToLower(wscName)];
	//check if it is active
	if (!BTIat.active)
	{
		PrintUserCmdText(iClientID, L"ERR bounty not currently active");
		return true;
	}
	//check user has enough money for the bounty
	int iCash;
	HkGetCash(stows(ToLower(wstos((wchar_t*)Players.GetActiveCharacterName(iClientID)))), iCash);
	if (iCash < (stoi(wscCash) * stoi(BTIat.xTimes)))
	{
		PrintUserCmdText(iClientID, L"ERR Not enough cash for bounty.");
		return true;
	}
	HkAddCash((wchar_t*)Players.GetActiveCharacterName(iClientID), 0 - (stoi(wscCash) * stoi(BTIat.xTimes)));
	if (deleteBountyCfg(BTIat))
	{
		//ConPrint(L"bounty removed from cfg\n");
	}
	else
	{
		ConPrint(L"BOUNTYTRACKER: Err removing from cfg. is server admin?\n");
	}
	BTIat.Cash = itos(stoi(BTIat.Cash) + stoi(wscCash));//update cash bounty
	PrintUserCmdText(iClientID, L"Uploading to Neural Net...");
	mapBountyTargets[ToLower(wscName)] = BTIat;
	if (appendBountyCfg(BTIat))
	{
		//ConPrint(L"cfg saved\n");
	}
	else
	{
		ConPrint(L"BOUNTYTRACKER: Err saving to cfg. is serevr admin?\n");
	}
	PrintUserCmdText(iClientID, L"OK");
	return true;
}
Пример #26
0
int ScriptEngine::ParseParam(PARAM *param)
{
    USES_CONVERSION;

    if (NULL == param) return -1;

    if (param->valueStr != NULL)
    {
        ReplaceStr(param->valueStr, param->size, _T("\\n"), _T("\n"));
    }

    while (param->valueStr != NULL) 
    {
        LPCTSTR end = NULL;
        LPCTSTR begin = _tcsstr(param->valueStr, _T("##"));

        if (NULL == begin) return -2;

        end = _tcsstr(begin+1, _T("##"));

        if (NULL == end) return -3;

        TCHAR name[MAX_PATH] = _T("");
        _tcsncpy_s(name, ARRAYSIZE(name), &begin[2], (end-begin) / sizeof(TCHAR) - 2);

        TCHAR name1[MAX_PATH] = _T("");
        _stprintf_s(name1, ARRAYSIZE(name1), _T("##%s##"), name);

        PARAM *p1 = scriptParam_.getParam(name);

        if (NULL == p1) continue;

        switch(p1->type)
        {
        case PARAM_INT:
        case PARAM_VOID_PTR:
        case PARAM_VOID_PTR_PTR:
            {
                TCHAR value[MAX_PATH] = _T("");
                _stprintf_s(value, ARRAYSIZE(value), _T("%d"), p1->getInt());
                ReplaceStr(param->valueStr, param->size, name1, value);
                break;
            }
        case PARAM_FLOAT:
            {
                TCHAR value[MAX_PATH] = _T("");
                _stprintf_s(value, ARRAYSIZE(value), _T("%f"), p1->getFloat());
                ReplaceStr(param->valueStr, param->size, name1, value);
                break;
            }
        case PARAM_DOUBLE:
            {
                TCHAR value[MAX_PATH] = _T("");
                _stprintf_s(value, ARRAYSIZE(value), _T("%lf"), p1->getDouble());
                ReplaceStr(param->valueStr, param->size, name1, value);
                break;
            }
        case PARAM_TCHAR:
            {
                ReplaceStr(param->valueStr, param->size, name1, p1->getTchar());
                break;
            }
        case PARAM_CAHR:
            {
                ReplaceStr(param->valueStr, param->size, name1, A2T((LPSTR)p1->getChar()));
                break;
            }
        case PARAM_WCHAR:
            {
                ReplaceStr(param->valueStr, param->size, name1, W2T(p1->getWchar()));
                break;
            }
        case PARAM_STD_STRING:
            {
                std::string *str = p1->getString();
                ReplaceStr(param->valueStr, param->size, name1, A2T((LPSTR)str->c_str()));
                break;
            }
        case PARAM_STD_WSTRING:
            {
                std::wstring *str = p1->getWstring();
                ReplaceStr(param->valueStr, param->size, name1, W2T(str->c_str()));
                break;
            }
        }
    }

    return 0;
}
Пример #27
0
const WORD * CResModule::CountMemReplaceDialogResource(const WORD * res, size_t * wordcount, WORD * newDialog)
{
	BOOL bEx = FALSE;
	DWORD style = GET_DWORD(res);
	if (newDialog)
	{
		newDialog[(*wordcount)++] = GET_WORD(res++);
		newDialog[(*wordcount)++] = GET_WORD(res++);
	}
	else
	{
		res += 2;
		(*wordcount) += 2;
	}

	if (style == 0xffff0001)	// DIALOGEX resource
	{
		bEx = TRUE;
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);	//help id
			newDialog[(*wordcount)++] = GET_WORD(res++);	//help id
			newDialog[(*wordcount)++] = GET_WORD(res++);	//exStyle
			newDialog[(*wordcount)++] = GET_WORD(res++);	//exStyle
			style = GET_DWORD(res);
			newDialog[(*wordcount)++] = GET_WORD(res++);	//style
			newDialog[(*wordcount)++] = GET_WORD(res++);	//style
		}
		else
		{
			res += 4;
			style = GET_DWORD(res);
			res += 2;
			(*wordcount) += 6;
		}
	}
	else
	{
		bEx = FALSE;
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);	//exStyle
			newDialog[(*wordcount)++] = GET_WORD(res++);	//exStyle
			//style = GET_DWORD(res);
			//newDialog[(*wordcount)++] = GET_WORD(res++);	//style
			//newDialog[(*wordcount)++] = GET_WORD(res++);	//style
		}
		else
		{
			res += 2;
			(*wordcount) += 2;
		}
	}

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res);
	WORD nbItems = GET_WORD(res);
	(*wordcount)++;
	res++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res); //x
	(*wordcount)++;
	res++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res); //y
	(*wordcount)++;
	res++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res); //cx
	(*wordcount)++;
	res++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res); //cy
	(*wordcount)++;
	res++;

	// Get the menu name

	switch (GET_WORD(res))
	{
	case 0x0000:
		if (newDialog)
			newDialog[(*wordcount)] = GET_WORD(res);
		(*wordcount)++;
		res++;
		break;
	case 0xffff:
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);
			newDialog[(*wordcount)++] = GET_WORD(res++);
		}
		else
		{
			(*wordcount) += 2;
			res += 2;
		}
		break;
	default:
		if (newDialog)
		{
			wcscpy((LPWSTR)&newDialog[(*wordcount)], (LPCWSTR)res);
		}
		(*wordcount) += wcslen((LPCWSTR) res) + 1;
		res += wcslen((LPCWSTR) res) + 1;
		break;
	}

	// Get the class name

	switch (GET_WORD(res))
	{
	case 0x0000:
		if (newDialog)
			newDialog[(*wordcount)] = GET_WORD(res);
		(*wordcount)++;
		res++;
		break;
	case 0xffff:
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);
			newDialog[(*wordcount)++] = GET_WORD(res++);
		}
		else
		{
			(*wordcount) += 2;
			res += 2;
		}
		break;
	default:
		if (newDialog)
		{
			wcscpy((LPWSTR)&newDialog[(*wordcount)], (LPCWSTR)res);
		}
		(*wordcount) += wcslen((LPCWSTR) res) + 1;
		res += wcslen((LPCWSTR) res) + 1;
		break;
	}

	// Get the window caption

	ReplaceStr((LPCWSTR)res, newDialog, wordcount, &m_bTranslatedDialogStrings, &m_bDefaultDialogStrings);
	res += wcslen((LPCWSTR)res) + 1;

	// Get the font name

	if (style & DS_SETFONT)
	{
		if (newDialog)
			newDialog[(*wordcount)] = GET_WORD(res);
		res++;
		(*wordcount)++;

		if (bEx)
		{
			if (newDialog)
			{
				newDialog[(*wordcount)++] = GET_WORD(res++);
				newDialog[(*wordcount)++] = GET_WORD(res++);
			}
			else
			{
				res += 2;
				(*wordcount) += 2;
			}
		}

		if (newDialog)
			wcscpy((LPWSTR)&newDialog[(*wordcount)], (LPCWSTR)res);
		(*wordcount) += wcslen((LPCWSTR)res) + 1;
		res += wcslen((LPCWSTR)res) + 1;
	}
	// First control is on DWORD boundary
	while ((*wordcount)%2)
		(*wordcount)++;
	while ((ULONG)res % 4)
		res++;

	while (nbItems--)
	{
		res = ReplaceControlInfo(res, wordcount, newDialog, bEx);
	}
	return res;
}
Пример #28
0
LIST *GetEthAdapterListInternal()
{
	LIST *o;
	LIST *ret;
	UINT size;
	char *buf;
	UINT i, j;
	char *qos_tag = " (Microsoft's Packet Scheduler)";
	SU *su = NULL;
	LIST *su_adapter_list = NULL;

	// Try to use SeLow
	if (enable_selow)
	{
		su = SuInit();
	}

	o = NewListFast(CompareWpAdapter);

	size = 200000;
	buf = ZeroMalloc(size);

	// Try to enumerate with SeLow
	if (su != NULL)
	{
		su_adapter_list = SuGetAdapterList(su);

		if (su_adapter_list == NULL)
		{
			// Fail to enumerate
			SuFree(su);
			su = NULL;
			//WHERE;
			is_using_selow = false;
		}
		else
		{
			//WHERE;
			is_using_selow = true;
		}
	}
	else
	{
		is_using_selow = false;
	}

	if (su_adapter_list != NULL)
	{
		// If 1 or more adapters are enumerated by SeLow, create adapter list object
		UINT i;

		for (i = 0;i < LIST_NUM(su_adapter_list);i++)
		{
			SU_ADAPTER_LIST *t = LIST_DATA(su_adapter_list, i);
			WP_ADAPTER *a = ZeroMalloc(sizeof(WP_ADAPTER));

			StrCpy(a->Name, sizeof(a->Name), t->Name);
			StrCpy(a->Guid, sizeof(a->Guid), t->Guid);
			StrCpy(a->Title, sizeof(a->Title), t->Info.FriendlyName);

			TrimCrlf(a->Title);
			Trim(a->Title);
			TrimCrlf(a->Title);
			Trim(a->Title);

			if (EndWith(a->Title, qos_tag))
			{
				a->Title[StrLen(a->Title) - StrLen(qos_tag)] = 0;
				TrimCrlf(a->Title);
				Trim(a->Title);
				TrimCrlf(a->Title);
				Trim(a->Title);
			}

			Add(o, a);
		}
	}
	else
	{
		// When SeLow is not used, create adapter list with SEE or WinPcap
		if (wp->PacketGetAdapterNames(buf, &size) == false)
		{
			Free(buf);
			return o;
		}

		i = 0;

		if (OS_IS_WINDOWS_NT(GetOsInfo()->OsType))
		{
			// Windows NT
			if (size >= 2 && buf[0] != 0 && buf[1] != 0)
			{
				goto ANSI_STR;
			}

			while (true)
			{
				wchar_t tmp[MAX_SIZE];
				WP_ADAPTER *a;
				UniStrCpy(tmp, sizeof(tmp), L"");

				if (*((wchar_t *)(&buf[i])) == 0)
				{
					i += sizeof(wchar_t);
					break;
				}

				for (;*((wchar_t *)(&buf[i])) != 0;i += sizeof(wchar_t))
				{
					wchar_t str[2];
					str[0] = *((wchar_t *)(&buf[i]));
					str[1] = 0;
					UniStrCat(tmp, sizeof(tmp), str);
				}

				i += sizeof(wchar_t);

				a = ZeroMalloc(sizeof(WP_ADAPTER));
				UniToStr(a->Name, sizeof(a->Name), tmp);

				Add(o, a);
			}
		}
		else
		{
			// Windows 9x
ANSI_STR:
			while (true)
			{
				char tmp[MAX_SIZE];
				WP_ADAPTER *a;
				StrCpy(tmp, sizeof(tmp), "");

				if (*((char *)(&buf[i])) == 0)
				{
					i += sizeof(char);
					break;
				}

				for (;*((char *)(&buf[i])) != 0;i += sizeof(char))
				{
					char str[2];
					str[0] = *((char *)(&buf[i]));
					str[1] = 0;
					StrCat(tmp, sizeof(tmp), str);
				}

				i += sizeof(char);

				a = ZeroMalloc(sizeof(WP_ADAPTER));
				StrCpy(a->Name, sizeof(a->Name), tmp);

				Add(o, a);
			}
		}

		for (j = 0;j < LIST_NUM(o);j++)
		{
			WP_ADAPTER *a = LIST_DATA(o, j);

			StrCpy(a->Title, sizeof(a->Title), &buf[i]);
			i += StrSize(a->Title);

			// If device description is "Unknown" in Win9x, skip 1 byte
			if (OS_IS_WINDOWS_9X(GetOsInfo()->OsType))
			{
				if (StrCmp(a->Title, "Unknown") == 0)
				{
					if (buf[i] == 0)
					{
						i+=sizeof(char);
					}
				}
			}

			TrimCrlf(a->Title);
			Trim(a->Title);
			TrimCrlf(a->Title);
			Trim(a->Title);

			if (EndWith(a->Title, qos_tag))
			{
				a->Title[StrLen(a->Title) - StrLen(qos_tag)] = 0;
				TrimCrlf(a->Title);
				Trim(a->Title);
				TrimCrlf(a->Title);
				Trim(a->Title);
			}
		}
	}

	for (j = 0;j < LIST_NUM(o);j++)
	{
		// Extract GUID
		WP_ADAPTER *a = LIST_DATA(o, j);

		if (IsEmptyStr(a->Guid))
		{
			StrCpy(a->Guid, sizeof(a->Guid), a->Name);
			ReplaceStr(a->Guid, sizeof(a->Guid), a->Guid, "\\Device\\SEE_", "");
			ReplaceStr(a->Guid, sizeof(a->Guid), a->Guid, "\\Device\\NPF_", "");
			ReplaceStr(a->Guid, sizeof(a->Guid), a->Guid, "\\Device\\PCD_", "");
		}
	}

	// Sort
	if (su_adapter_list != NULL)
	{
		// Since adapter list made by SeLow is already sorted, don't sort here
		Sort(o);
	}

	ret = NewListFast(CompareWpAdapter);

	for (i = 0;i < LIST_NUM(o);i++)
	{
		WP_ADAPTER *a = LIST_DATA(o, i);
		ADAPTER *ad;
		bool is_ethernet = false;
		bool ok = false;

		if (SearchStrEx(a->Title, "ppp", 0, false) != INFINITE ||
			SearchStrEx(a->Title, "wan", 0, false) != INFINITE ||
			SearchStrEx(a->Title, "dialup", 0, false) != INFINITE ||
			SearchStrEx(a->Title, "pptp", 0, false) != INFINITE ||
			SearchStrEx(a->Title, "telepho", 0, false) != INFINITE ||
			SearchStrEx(a->Title, "modem", 0, false) != INFINITE ||
			SearchStrEx(a->Title, "ras", 0, false) != INFINITE)
		{
			Free(a);
			continue;
		}

		// Determine whether the adapter type is Ethernet
		if (su == NULL)
		{
			// Determine with See
			ad = wp->PacketOpenAdapter(a->Name);
			if (ad != NULL)
			{
				NetType type;
				if (wp->PacketGetNetType(ad, &type))
				{
					if (type.LinkType == 0)
					{
						is_ethernet = true;
					}
				}

				wp->PacketCloseAdapter(ad);
			}
		}
		else
		{
			// In using SeLow, all devices should be Ethernet device
			is_ethernet = true;
		}

		if (is_ethernet)
		{
			// Add only Ethernet device
			char tmp[MAX_SIZE];
			UINT k;

			StrCpy(tmp, sizeof(tmp), a->Title);

			for (k = 0;;k++)
			{
				if (k == 0)
				{
					StrCpy(tmp, sizeof(tmp), a->Title);
				}
				else
				{
					Format(tmp, sizeof(tmp), "%s (%u)", a->Title, k + 1);
				}

				ok = true;
				for (j = 0;j < LIST_NUM(ret);j++)
				{
					WP_ADAPTER *aa = LIST_DATA(ret, j);
					if (StrCmpi(aa->Title, tmp) == 0)
					{
						ok = false;
					}
				}

				if (ok)
				{
					break;
				}
			}

			StrCpy(a->Title, sizeof(a->Title), tmp);
			a->Id = Win32EthGenIdFromGuid(a->Guid);
			Add(ret, a);
		}

		if (ok == false)
		{
			Free(a);
		}
	}

	Free(buf);

	Sort(ret);

	ReleaseList(o);

	if (su != NULL)
	{
		SuFreeAdapterList(su_adapter_list);

		SuFree(su);
	}

	return ret;
}
Пример #29
0
const WORD* CResModule::ReplaceControlInfo(const WORD * res, size_t * wordcount, WORD * newDialog, BOOL bEx)
{
	if (bEx)
	{
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);	//helpid
			newDialog[(*wordcount)++] = GET_WORD(res++);	//helpid
		}
		else
		{
			res += 2;
			(*wordcount) += 2;
		}
	}
	if (newDialog)
	{
		LONG * exStyle = (LONG*)&newDialog[(*wordcount)];
		newDialog[(*wordcount)++] = GET_WORD(res++);	//exStyle
		newDialog[(*wordcount)++] = GET_WORD(res++);	//exStyle
		if (m_bRTL)
			*exStyle |= WS_EX_RTLREADING;
	}
	else
	{
		res += 2;
		(*wordcount) += 2;
	}

	if (newDialog)
	{
		newDialog[(*wordcount)++] = GET_WORD(res++);	//style
		newDialog[(*wordcount)++] = GET_WORD(res++);	//style
	}
	else
	{
		res += 2;
		(*wordcount) += 2;
	}

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res);	//x
	res++;
	(*wordcount)++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res);	//y
	res++;
	(*wordcount)++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res);	//cx
	res++;
	(*wordcount)++;

	if (newDialog)
		newDialog[(*wordcount)] = GET_WORD(res);	//cy
	res++;
	(*wordcount)++;

	if (bEx)
	{
		// ID is a DWORD for DIALOGEX
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);
			newDialog[(*wordcount)++] = GET_WORD(res++);
		}
		else
		{
			res += 2;
			(*wordcount) += 2;
		}
	}
	else
	{
		if (newDialog)
			newDialog[(*wordcount)] = GET_WORD(res);
		res++;
		(*wordcount)++;
	}

	if (GET_WORD(res) == 0xffff)	//classID
	{
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);
			newDialog[(*wordcount)++] = GET_WORD(res++);
		}
		else
		{
			res += 2;
			(*wordcount) += 2;
		}
	}
	else
	{
		if (newDialog)
			wcscpy((LPWSTR)&newDialog[(*wordcount)], (LPCWSTR)res);
		(*wordcount) += wcslen((LPCWSTR) res) + 1;
		res += wcslen((LPCWSTR) res) + 1;
	}

	if (GET_WORD(res) == 0xffff)	// an integer ID?
	{
		if (newDialog)
		{
			newDialog[(*wordcount)++] = GET_WORD(res++);
			newDialog[(*wordcount)++] = GET_WORD(res++);
		}
		else
		{
			res += 2;
			(*wordcount) += 2;
		}
	}
	else
	{
		ReplaceStr((LPCWSTR)res, newDialog, wordcount, &m_bTranslatedDialogStrings, &m_bDefaultDialogStrings);
		res += wcslen((LPCWSTR)res) + 1;
	}

	if (newDialog)
		memcpy(&newDialog[(*wordcount)], res, (GET_WORD(res)+1)*sizeof(WORD));
	(*wordcount) += (GET_WORD(res)+1);
	res += (GET_WORD(res)+1);
	// Next control is on DWORD boundary
	while ((*wordcount) % 2)
		(*wordcount)++;
	return (const WORD *)((((long)res) + 3) & ~3);
}
Пример #30
0
const WORD* CResModule::CountMemReplaceMenuExResource(const WORD * res, size_t * wordcount, WORD * newMenu)
{
	DWORD dwType, dwState, menuId;
	WORD bResInfo;
	WORD *p0;

	//struct MenuExItem {
	//    DWORD dwType;
	//    DWORD dwState;
	//    DWORD menuId;
	//    WORD bResInfo;
	//    WCHAR szText[];
	//    DWORD dwHelpId; - Popup menu only
	//};

	do
	{
		p0 = (WORD *)res;
		dwType = GET_DWORD(res);
		res += 2;
		dwState = GET_DWORD(res);
		res += 2;
		menuId = GET_DWORD(res);
		res += 2;
		bResInfo = GET_WORD(res);
		res++;

		if (newMenu != NULL) {
			CopyMemory(&newMenu[*wordcount], p0, 7 * sizeof(WORD));
		}
		(*wordcount) += 7;

		if (dwType & MFT_SEPARATOR) {
			// Align to DWORD
			(*wordcount)++;
			res++;
			continue;
		}

		if (bResInfo & 0x01)
		{
			ReplaceStr((LPCWSTR)res, newMenu, wordcount, &m_bTranslatedMenuStrings, &m_bDefaultMenuStrings);
			res += wcslen((LPCWSTR)res) + 1;
			// Align to DWORD
			res += ((((WORD)res + 3) & ~3) - (WORD)res)/sizeof(WORD);
			if ((*wordcount) & 0x01)
				(*wordcount)++;

			if (newMenu != NULL)
				CopyMemory(&newMenu[*wordcount], res, sizeof(DWORD));  // Copy Help ID

			res += 2;
			(*wordcount) += 2;

			if ((res = CountMemReplaceMenuExResource(res, wordcount, newMenu)) == 0)
				return NULL;
		}
		else if (menuId != 0)
		{
			ReplaceStr((LPCWSTR)res, newMenu, wordcount, &m_bTranslatedMenuStrings, &m_bDefaultMenuStrings);
			res += wcslen((LPCWSTR)res) + 1;
		}
		else
		{
			if (newMenu)
				wcscpy((wchar_t *)&newMenu[(*wordcount)], (LPCWSTR)res);
			(*wordcount) += wcslen((LPCWSTR)res) + 1;
			res += wcslen((LPCWSTR)res) + 1;
		}
		// Align to DWORD
		res += ((((WORD)res + 3) & ~3) - (WORD)res)/sizeof(WORD);
		if ((*wordcount) & 0x01)
			(*wordcount)++;
	} while (!(bResInfo & 0x80));
	return res;
}