BOOL DriverUnload ()
{
	SC_HANDLE hManager = NULL, hService = NULL;
	BOOL bRet = FALSE;
	SERVICE_STATUS status = {0};
	int x = 0;

	hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (hManager == NULL)
		goto error;

	hService = OpenService (hManager, L"Bluefisher", SERVICE_ALL_ACCESS);
	if (hService == NULL)
	{
		wprintf( L"Open Service for Bluefisher was failed. Error: %d.\n", GetLastError() );
		SetLastError(0);
		goto error;
	}

	bRet = QueryServiceStatus (hService, &status);
	if (bRet != TRUE)
	{
		wprintf( L"Query Service status failed. Error: %d.\n", GetLastError() );
		SetLastError(0);
		goto error;
	}

	if (status.dwCurrentState != SERVICE_STOPPED)
	{
		ControlService (hService, SERVICE_CONTROL_STOP, &status);

		for (x = 0; x < 5; x++)
		{
			bRet = QueryServiceStatus (hService, &status);
			if (bRet != TRUE)
			{
				wprintf( L"Query Service status failed. Loop %d. Error: %d.\n", x, GetLastError() );
				SetLastError(0);
				goto error;
			}
			
			if (status.dwCurrentState == SERVICE_STOPPED)
				break;

			Sleep (200);
		}
	}

	DeleteService( hService );

error:
	if (hService != NULL)
		CloseServiceHandle (hService);

	if (hManager != NULL)
		CloseServiceHandle (hManager);

	if (status.dwCurrentState == SERVICE_STOPPED)
	{
		//hDriver = INVALID_HANDLE_VALUE;
		return TRUE;
	}

	return FALSE;
}
int main() {

	SOCKET master = INVALID_SOCKET;
	struct sockaddr_in server, client;
	struct sockaddr_in broadcast;
	char recvbuf[BUFLEN] = "";
	int iResult;
	WSADATA wsaData;
	int count;
	char str[INET_ADDRSTRLEN];
	char *message = "I am server";
	int addrlen = sizeof(client);
	int clientListenPorts[CLIENTS],cp;
	int i;
	fd_set read;

	for (i = 0; i < CLIENTS; i++) {

		clientListenPorts[i] = 0;
	}

	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != NO_ERROR) {
		wprintf(L"WSAStartup failed with error: %d\n", iResult);
		return 1;
	}

	printf("Winsock initialized\n");

	//create socket
	master = socket(AF_INET, SOCK_DGRAM, 0);
	if (master == INVALID_SOCKET) {
		wprintf(L"master socket failed with error: %ld\n", WSAGetLastError());
		WSACleanup();
		return 1;
	}
	printf("Socket created\n");

	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons(SERVER_PORT);

	//bind 
	if (bind(master, (struct sockaddr *)&server, sizeof(server)) < 0) {

		printf("bind() failed : %d\n", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	printf("Binding done\n");

	while (TRUE) {

		fflush(stdout);

			//clear the buffer
			memset(recvbuf, '\0', BUFLEN);

			//receive data
			if ((count = recvfrom(master, recvbuf, BUFLEN, 0, (struct sockaddr *) &client, &addrlen))
				== SOCKET_ERROR)
			{
				printf("recvfrom() failed with error code : %d", WSAGetLastError());
				exit(EXIT_FAILURE);
			}
			printf("Received from client , ip %s,  port %d \n",
				inet_ntop(AF_INET, &(client.sin_addr), str, INET_ADDRSTRLEN), ntohs(client.sin_port));

			printf("My listening port is: %s\n", recvbuf);

			sscanf_s(recvbuf, "%d", &cp);

			for (i = 0; i < CLIENTS; i++)
			{
				if (clientListenPorts[i] == 0)
				{
					clientListenPorts[i] = cp;
					printf("Adding to list of client listen ports at index %d \n", i);
					break;
				}
			}//end for



			 /*iResult = sendto(master, (char*)clientListenPorts, CLIENTS*sizeof(int), 0, (struct sockaddr *)&client,
			 addrlen);


			 if (iResult == SOCKET_ERROR)
			 {
			 printf("sendto() failed with error code : %d", WSAGetLastError());
			 exit(EXIT_FAILURE);
			 }*/

			 //create socket

			 //broadcast
			int options = 1;
			if ((setsockopt(master, SOL_SOCKET, SO_BROADCAST, (void *)&options, sizeof(options))) < 0) {
				printf("%d", WSAGetLastError());
			}

			memset(&broadcast, 0, sizeof(broadcast));        //zero out structure
			broadcast.sin_family = AF_INET;                 // Internet address family 
			broadcast.sin_addr.s_addr = htonl(-1);          //send message to 255.255.255.255
			broadcast.sin_port = htons(BROADCAST_PORT);     // Broadcast port 



			iResult = sendto(master, (char*)clientListenPorts, CLIENTS*sizeof(int), 0, (struct sockaddr *)
				&broadcast, sizeof(broadcast));

			if (iResult == SOCKET_ERROR)
			{
				printf("sendto() failed with error code : %d", WSAGetLastError());
				exit(EXIT_FAILURE);
			}
		

	}//end while

	 // close the socket
	iResult = closesocket(master);
	if (iResult == SOCKET_ERROR) {
		wprintf(L"close failed with error: %d\n", WSAGetLastError());
		WSACleanup();
		return 1;
	}

	WSACleanup();

	return 0;
}//end main
void
MonitorPrintUsage()
{
   wprintf(L"Usage: monitor ( addcallouts | delcallouts | monitor <targetApp.exe> )\n");
}
Example #4
0
File: www.c Project: clflush/tty64
__inline__ void httpd_www_conf_dialog(int fd, char *action, int confidx, char *curval, char *submit_cpt) {

    	wprintf(fd, "<FORM ACTION=\"%s\" METHOD=\"GET\">\n", action);

	wprintf(fd, "<TABLE BORDER=\"0\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "<TR><TD ALIGN=\"CENTER\">Current value: %s</TD></TR>\n", curval);
	wprintf(fd, "</TABLE>\n");
	wprintf(fd, "<BR>\n");

 	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\"35%\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD COLSPAN=\"2\">\n");
	wprintf(fd, "New value: <INPUT SIZE=\"24\" TYPE=\"TEXT\" NAME=\"newval\">\n");
	wprintf(fd, "<INPUT READONLY TYPE=\"HIDDEN\" NAME=\"idx\" VALUE=\"%d\">\n", confidx);
	wprintf(fd, "</TD>\n");
	wprintf(fd, "</TR>\n");

	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD ALIGN=\"CENTER\"><INPUT TYPE=SUBMIT VALUE=\"%s\"></TD>\n", submit_cpt);
	wprintf(fd, "<TD ALIGN=\"CENTER\"><INPUT TYPE=RESET VALUE=\"clear\"></TD>\n");
	wprintf(fd, "</FORM>\n");
	wprintf(fd, "</TD>\n");
	wprintf(fd, "</TR>\n");

	wprintf(fd, "</TABLE>\n");
	
	return ;
}
Example #5
0
File: www.c Project: clflush/tty64
int httpd_www_about(int fd, char *raw, char *cgi) {
	
	httpd_start_hmenu(fd, NULL);
	httpd_end_hmenu(fd);

	wprintf(fd, "<BR>\n");

	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" ALIGN=\"CENTER\" VALIGN=\"TOP\">\n");
	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "Ghost (v/%s)\n", GHOST_VERSION);
	wprintf(fd, "</TD>\n");
	wprintf(fd, "</TR>\n");
	wprintf(fd, "</TABLE>\n");	

	wprintf(fd, "<BR>\n");

	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" ALIGN=\"CENTER\" VALIGN=\"BOTTOM\">\n");
	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "<A HREF=\"http://www.ikotler.org\">http://www.ikotler.org</A>\n");
	wprintf(fd, "</TD>\n");
	wprintf(fd, "</TR>\n");
	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "<A HREF=\"mailto:[email protected]\">[email protected]</A>\n");
	wprintf(fd, "</TR>\n");
	wprintf(fd, "</TABLE>\n");		

	wprintf(fd, "<BR>\n");

	return 1;
}
Example #6
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*prevInstance*/,
				   PSTR /*cmdLine*/, int /*showCmd*/)
{
	//notify user if heap is corrupt
	#if defined _DEBUG
	HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
    #endif

    #pragma region junk
    //***********************
    //get command line params
	//LPCWSTR
	int numArgs=0;
	WCHAR **sArgList =  CommandLineToArgvW(GetCommandLineW(), &numArgs);
	//print arguments
	if( NULL == sArgList )
	{
		wprintf(L"CommandLineToArgvW failed\n");
		return 0;
	}
	else 
	{
		wstringstream strstr;
		for(int  i=0; i < numArgs; i++) 
		{
			strstr << i <<  sArgList[i] << _T("\n");
		}
		OutputDebugStringW(strstr.str().c_str());
	}

	LocalFree(sArgList);//free memory
    //end of parameters experiment
    //****************************
    #pragma endregion

	//create game singleton object
	Engine* pEngine = new Engine(hInstance);
	MainGame* pGame = new MainGame();

	#if defined DEBUG || _DEBUG
	cout << "-Engine & Game created\n";
	#endif

	pEngine->SetGame(pGame);
	pEngine->Initialize();

	#if defined DEBUG || _DEBUG
	cout << "------------------------\n:::Engine Initialized:::\n------------------------\n\n";
	#endif

	int ret = pEngine->Run();

	//destroy objects
	delete pGame;
	delete pEngine;

    cout << "\n\n";
    cout << "   Happy Engine wishes you a happy day!   \n";
    cout << "--------------\\Press any key/-------------\n";
    cin.get();
    
	#if defined _DEBUG
    _CrtDumpMemoryLeaks();
    #endif

	return ret;

}
Example #7
0
File: www.c Project: clflush/tty64
int httpd_www_proxies(int fd, char *raw, char *cgi) {
	int idx, p_counter;
	proxy_entry *cur_proxy;
	proxy_db_stats *cur_db;

	cur_db = proxy_get_stats();
		
	if (!cur_db) {
		httpd_www_syserr(fd, "calloc", raw);
		return 0;
	}

	httpd_start_hmenu(fd, proxies_menu);
	httpd_end_hmenu(fd);

	if (cur_db->index < 1) {

		httpd_www_label(fd, "There are no proxies in the database!", 45);
		free(cur_db);
		return 1;
	}

	httpd_www_label(fd, "Proxies Database", 80);

 	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\"85%\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "\t<TR>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">#</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">proxy address</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">proxy port</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">proxy rank</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">proxy strikes</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">proxy jobs</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\" COLSPAN=\"3\">proxy options</TD>\n");
	wprintf(fd, "\t</TR>\n");

	p_counter = 1;

	for (idx = 0; idx < cur_db->index; idx++) {

		cur_proxy = proxy_querydb(idx);

		if (!cur_proxy) {
			continue;
		}

		wprintf(fd, "\t<TR>\n");
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", p_counter);
		wprintf(fd, "\t\t<TD>%s</TD>\n", cur_proxy->addr);
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_proxy->port);
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%s</TD>\n", proxy_getrank(cur_proxy));
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_proxy->strikes);
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_proxy->jobs);
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\"><A HREF=\"/proxy-checkup.cgi?id=%d\">validate</A></TD>\n", idx);
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\"><A HREF=\"/proxy-modifier.cgi?id=%d\">modify</A></TD>\n", idx);
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\"><A HREF=\"/delete-proxy.cgi?id=%d\">delete</A></TD>\n", idx);
		wprintf(fd, "\t</TR>\n");

		p_counter++;

		free(cur_proxy);
	}

	wprintf(fd, "</TABLE>\r\n");
	
	free(cur_db);

	return 1;
}
Example #8
0
BOOL CALLBACK MyMiniDumpCallback(
	PVOID                            pParam, 
	const PMINIDUMP_CALLBACK_INPUT   pInput, 
	PMINIDUMP_CALLBACK_OUTPUT        pOutput 
) 
{
	BOOL bRet = FALSE; 


	// Check parameters 

	if( pInput == 0 ) 
		return FALSE; 

	if( pOutput == 0 ) 
		return FALSE; 


	// Process callbacks 

	switch( pInput->CallbackType ) 
	{
		case IncludeModuleCallback: 
		{
			// Include the module into the dump 
			_tprintf( _T("IncludeModuleCallback (module: %08I64x) \n"), 
				pInput->IncludeModule.BaseOfImage); 
			bRet = TRUE; 
		}
		break; 

		case IncludeThreadCallback: 
		{
			// Include the thread into the dump 
			_tprintf( _T("IncludeThreadCallback (thread: %x) \n"), 
				pInput->IncludeThread.ThreadId); 
			bRet = TRUE; 
		}
		break; 

		case ModuleCallback: 
		{
			// Include all available information 
			wprintf( L"ModuleCallback (module: %s) \n", pInput->Module.FullPath ); 
			bRet = TRUE; 
		}
		break; 

		case ThreadCallback: 
		{
			// Include all available information 
			_tprintf( _T("ThreadCallback (thread: %x) \n"), pInput->Thread.ThreadId ); 
			bRet = TRUE;  
		}
		break; 

		case ThreadExCallback: 
		{
			// Include all available information 
			_tprintf( _T("ThreadExCallback (thread: %x) \n"), pInput->ThreadEx.ThreadId ); 
			bRet = TRUE;  
		}
		break; 

		case MemoryCallback: 
		{
			// Let CancelCallback know where to stop 
			MemoryCallbackCalled = true; 

			// We do not include any information here -> return FALSE 
			_tprintf( _T("MemoryCallback\n") ); 
			bRet = FALSE; 
		}
		break; 

		/* no longer valid option? erno 08-01
		case CancelCallback: 
		{
			_tprintf( _T("CancelCallback\n") ); 

			if( !MemoryCallbackCalled) 
			{
				// Continue receiving CancelCallback callbacks 
				pOutput->Cancel       = FALSE; 
				pOutput->CheckCancel  = TRUE; 
			}
			else 
			{
				// No cancel callbacks anymore 
				pOutput->Cancel       = FALSE; 
				pOutput->CheckCancel  = FALSE; 
			}
			bRet = TRUE; 
		}
		break; 
		*/
	}


	return bRet; 

}
Example #9
0
BOOL ParseCommandLine( int argc, wchar_t *argv[ ])
{
/*
     ** PARSE the FOLLOWING ARGUMENTS:
    /LDAP <Path of container>
        ADsPath of the container for placing the new group
    
    /UNAME <NT 5 User Name>
        This is the name for the new group
    
    /SAMNAME <Downlevel NT 4 Sam Account name>
        Cannot exceed 20 characters and must be globally unique

    <*> Detailed New User information <*>
    /FILE < Info File >
    
        Filename for file to contain new user information

    <*> OPTIONAL Binding Information <*>
    /USER <User name used for binding to the DC>
    
    /PASS <Password used for binding to the DC>
    (If these are passed, binding is done with ADsOpenObject())
*/        
	if (argc == 1)
	{
        _putws(pwszUsage);
        return FALSE;
    }
    for (int x= 1; x < argc; x++)
    {
        if (_wcsicmp(argv[x],L"/LDAP")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsLDAP = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/UNAME")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsUNAME = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/SAMNAME")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsSAMNAME = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/FILE")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsFILE = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/USER")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsUSER = SysAllocString(argv[x]);                
        }
        else if (_wcsicmp(argv[x],L"/PASS")==0)
        {
            if (argc == x) // Make sure the parameter was passed
            {
                wprintf(L"\nERROR: %s Missing parameter!!!!\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
            }
            // Go to the next argument and save it in module level variable
            x++;
            bsPASS = SysAllocString(argv[x]);                
        }
        else
        {
                wprintf(L"\nERROR: %s UNknown Argument\n\n",argv[x]);
                _putws(pwszUsage);
                return FALSE;
        }
    }
    // Check if User is poassed, then password is required:
    if (bsUSER || bsPASS)
        if (!bsUSER || !bsPASS) // if either one is missing complain
        {
            _putws(L"\nERROR: If /USER is specified /PASS is required!");
            return FALSE;
        }                    
      
    return TRUE;
}
Example #10
0
//////////////////////////////////////////////////////////////////////////////////////////
// NAOMI JAMMA DMA
// ---------------
u32 FASTCALL ControllerDMA_NAOMI(void* device_instance,u32 Command,u32* buffer_in,u32 buffer_in_len,u32* buffer_out,u32& buffer_out_len)
{
	u8*buffer_out_b=(u8*)buffer_out;
	u8*buffer_in_b=(u8*)buffer_in;
	buffer_out_len=0;

	u16 kcode[4]={0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};

	if(joysticks[0].enabled)
		GetJoyStatus(0);
	else
		memset(joystate[0].control, 0, sizeof(joystate[0].control));

	if(joysticks[1].enabled)	
		GetJoyStatus(1);
	else
		memset(joystate[1].control, 0, sizeof(joystate[1].control));

	switch (Command)
	{
	case 0x86:
		{
			u32 subcode=*(u8*)buffer_in;

			switch(subcode)
			{
			case 0x15:
			case 0x33:
				{
					buffer_out[0]=0xffffffff;
					buffer_out[1]=0xffffffff;					

					if(joystate[0].control[CTLN_SERVICE2] || 
					   joystate[1].control[CTLN_SERVICE2])	buffer_out[0]&=~(1<<0x1b);
					
					if(joystate[0].control[CTLN_TEST2] || 
					   joystate[1].control[CTLN_TEST2])		buffer_out[0]&=~(1<<0x1a);
					
					if(State.Mode==0 && subcode!=0x33)	//Get Caps
					{
						buffer_out_b[0x11+1]=0x8E;	//Valid data check
						buffer_out_b[0x11+2]=0x01;
						buffer_out_b[0x11+3]=0x00;
						buffer_out_b[0x11+4]=0xFF;
						buffer_out_b[0x11+5]=0xE0;
						buffer_out_b[0x11+8]=0x01;

						switch(State.Cmd)
						{
							//Reset, in : 2 bytes, out : 0
							case 0xF0:
								break;

							//Find nodes?
							//In addressing Slave address, in : 2 bytes, out : 1
							case 0xF1:
								{
									buffer_out_len=4*4;
								}
								break;

							//Speed Change, in : 2 bytes, out : 0
							case 0xF2:
								break;

							//Name
							//"In the I / O ID" "Reading each slave ID data"
							//"NAMCO LTD.; I / O PCB-1000; ver1.0; for domestic only, no analog input"
							//in : 1 byte, out : max 102
							case 0x10:
								{
									static char ID1[102]="nullDC Team; I/O Plugin-1; ver0.2; for nullDC or other emus";
									buffer_out_b[0x8+0x10]=(BYTE)strlen(ID1)+3;
									for(int i=0;ID1[i]!=0;++i)
									{
										buffer_out_b[0x8+0x13+i]=ID1[i];
									}
								}
								break;

							//CMD Version
							//REV in command|Format command to read the (revision)|One|Two 
							//in : 1 byte, out : 2 bytes
							case 0x11:
								{
									buffer_out_b[0x8+0x13]=0x13;
								}
								break;

							//JVS Version
							//In JV REV|JAMMA VIDEO standard reading (revision)|One|Two 
							//in : 1 byte, out : 2 bytes
							case 0x12:
								{
									buffer_out_b[0x8+0x13]=0x30;
								}
								break;

							//COM Version
							//VER in the communication system|Read a communication system compliant version of |One|Two
							//in : 1 byte, out : 2 bytes
							case 0x13:
								{
									buffer_out_b[0x8+0x13]=0x10;
								}
								break;

							//Features
							//Check in feature |Each features a slave to read |One |6 to
							//in : 1 byte, out : 6 + (?)
							case 0x14:
								{
									unsigned char *FeatPtr=buffer_out_b+0x8+0x13;
									buffer_out_b[0x8+0x9+0x3]=0x0;
									buffer_out_b[0x8+0x9+0x9]=0x1;
									#define ADDFEAT(Feature,Count1,Count2,Count3)	*FeatPtr++=Feature; *FeatPtr++=Count1; *FeatPtr++=Count2; *FeatPtr++=Count3;
									ADDFEAT(1,2,12,0);	//Feat 1=Digital Inputs.  2 Players. 10 bits
									ADDFEAT(2,2,0,0);	//Feat 2=Coin inputs. 2 Inputs
									ADDFEAT(3,2,0,0);	//Feat 3=Analog. 2 Chans

									ADDFEAT(0,0,0,0);	//End of list
								}
								break;

							default:
								printf("unknown CAP %X\n",State.Cmd);
							return 0;
						}
						buffer_out_len=4*4;
					}
					else if(State.Mode==1 || State.Mode==2 || subcode==0x33)	//Get Data
					{
						unsigned char glbl=0x00;
						unsigned char p1_1=0x00;
						unsigned char p1_2=0x00;
						unsigned char p2_1=0x00;
						unsigned char p2_2=0x00;	
						static unsigned char LastKey[256];
						static unsigned short coin1=0x0000;
						static unsigned short coin2=0x0000;	
						
						if(joystate[0].control[CTLN_TEST1] || 
						   joystate[1].control[CTLN_TEST1])   glbl|=0x80;

						if(joystate[0].control[CTLN_SERVICE1])	  p1_1|=0x40;																										
						if(joystate[0].control[CTLN_START])   p1_1|=0x80; 
						
						if(joystate[0].control[CTLN_D_UP]   ) p1_1|=0x20;
						if(joystate[0].control[CTLN_D_DOWN] ) p1_1|=0x10;
						if(joystate[0].control[CTLN_D_LEFT] ) p1_1|=0x08;
						if(joystate[0].control[CTLN_D_RIGHT]) p1_1|=0x04;						
												
						if(joystate[0].control[CTLN_BUTTON1]) p1_1|=0x02;
						if(joystate[0].control[CTLN_BUTTON2]) p1_1|=0x01;
						if(joystate[0].control[CTLN_BUTTON3]) p1_2|=0x80;
						if(joystate[0].control[CTLN_BUTTON4]) p1_2|=0x40;																			
						if(joystate[0].control[CTLN_BUTTON5]) p1_2|=0x20;
						if(joystate[0].control[CTLN_BUTTON6]) p1_2|=0x10;

						// Player 2
						if(joystate[1].control[CTLN_SERVICE1])	  p2_1|=0x40;																										
						if(joystate[1].control[CTLN_START])   p2_1|=0x80; 
						
						if(joystate[1].control[CTLN_D_UP]   ) p2_1|=0x20;
						if(joystate[1].control[CTLN_D_DOWN] ) p2_1|=0x10;
						if(joystate[1].control[CTLN_D_LEFT] ) p2_1|=0x08;
						if(joystate[1].control[CTLN_D_RIGHT]) p2_1|=0x04;						
												
						if(joystate[1].control[CTLN_BUTTON1]) p2_1|=0x02;
						if(joystate[1].control[CTLN_BUTTON2]) p2_1|=0x01;
						if(joystate[1].control[CTLN_BUTTON3]) p2_2|=0x80;
						if(joystate[1].control[CTLN_BUTTON4]) p2_2|=0x40;																			
						if(joystate[1].control[CTLN_BUTTON5]) p2_2|=0x20;
						if(joystate[1].control[CTLN_BUTTON6]) p2_2|=0x10;
							
						static bool old_coin1 = false;
						static bool old_coin2 = false;

						if(!old_coin1 && joystate[0].control[CTLN_COIN]) // Coin key
						{
							coin1++;
							old_coin1 = true;
						}	
						else if(old_coin1 && !joystate[0].control[CTLN_COIN]) // Coin key
							old_coin1 = false;
						
						if(!old_coin2 && joystate[1].control[CTLN_COIN]) // Coin key
						{
							coin2++;
							old_coin2 = true;
						}
						else if(old_coin2 && !joystate[1].control[CTLN_COIN]) // Coin key													
							old_coin2 = false;
						

						buffer_out_b[0x11+0]=0x00;
						buffer_out_b[0x11+1]=0x8E;	//Valid data check
						buffer_out_b[0x11+2]=0x01;
						buffer_out_b[0x11+3]=0x00;
						buffer_out_b[0x11+4]=0xFF;
						buffer_out_b[0x11+5]=0xE0;
						buffer_out_b[0x11+8]=0x01;

						//memset(OutData+8+0x11,0x00,0x100);

						buffer_out_b[8+0x12+0]=1;
						buffer_out_b[8+0x12+1]=glbl;
						buffer_out_b[8+0x12+2]=p1_1;
						buffer_out_b[8+0x12+3]=p1_2;						
						buffer_out_b[8+0x12+4]=p2_1;
						buffer_out_b[8+0x12+5]=p2_2;	
						buffer_out_b[8+0x12+6]=1;
						buffer_out_b[8+0x12+7]=coin1>>8;
						buffer_out_b[8+0x12+8]=coin1&0xff;						
						buffer_out_b[8+0x12+9]=coin2>>8;
						buffer_out_b[8+0x12+10]=coin2&0xff;						
						buffer_out_b[8+0x12+11]=1;
						buffer_out_b[8+0x12+12]=0x00;
						buffer_out_b[8+0x12+13]=0x00;
						buffer_out_b[8+0x12+14]=0x00;
						buffer_out_b[8+0x12+15]=0x00;
						buffer_out_b[8+0x12+16]=0x00;
						buffer_out_b[8+0x12+17]=0x00;
						buffer_out_b[8+0x12+18]=0x00;
						buffer_out_b[8+0x12+19]=0x00;
						buffer_out_b[8+0x12+20]=0x00;						

						if(State.Mode==1)
						{
							buffer_out_b[0x11+0x7]=19;
							buffer_out_b[0x11+0x4]=19+5;
						}
						else
						{
							buffer_out_b[0x11+0x7]=17;
							buffer_out_b[0x11+0x4]=17-1;
						}

						//OutLen=8+0x11+16;
						buffer_out_len=8+0x12+20;
					}
				}
				return 8;
					
			case 0x17:	//Select Subdevice
				{
					State.Mode=0;
					State.Cmd=buffer_in_b[8];
					State.Node=buffer_in_b[9];
					buffer_out_len=0;
				}
				return (7);
				
			case 0x27:	//Transfer request
				{
					State.Mode=1;
					State.Cmd=buffer_in_b[8];
					State.Node=buffer_in_b[9];
					buffer_out_len=0;
				}
				return (7);
			case 0x21:		//Transfer request with repeat
				{
					State.Mode=2;
					State.Cmd=buffer_in_b[8];
					State.Node=buffer_in_b[9];
					buffer_out_len=0;
				}
				return (7);

			case 0x0B:	//EEPROM write
				{
					int address=buffer_in_b[1];
					int size=buffer_in_b[2];
					//printf("EEprom write %08X %08X\n",address,size);
					//printState(Command,buffer_in,buffer_in_len);
					memcpy(EEPROM+address,buffer_in_b+4,size);

					wchar eeprom_file[512];
					host.ConfigLoadStr(L"emu",L"gamefile",eeprom_file,L"");
					wcscat_s(eeprom_file,L".eeprom");
					FILE* f;
					_wfopen_s(&f,eeprom_file,L"wb");
					if (f)
					{
						fwrite(EEPROM,1,0x80,f);
						fclose(f);
						wprintf(L"SAVED EEPROM to %s\n",eeprom_file);
					}
				}
				return (7);
			case 0x3:	//EEPROM read
				{
					if (!EEPROM_loaded)
					{
						EEPROM_loaded=true;
						wchar eeprom_file[512];
						host.ConfigLoadStr(L"emu",L"gamefile",eeprom_file,L"");
						wcscat_s(eeprom_file,L".eeprom");
						FILE* f;
						_wfopen_s(&f,eeprom_file,L"rb");
						if (f)
						{
							fread(EEPROM,1,0x80,f);
							fclose(f);
							wprintf(L"LOADED EEPROM from %s\n",eeprom_file);
						}
					}
					//printf("EEprom READ ?\n");
					int address=buffer_in_b[1];
					//printState(Command,buffer_in,buffer_in_len);
					memcpy(buffer_out,EEPROM+address,0x80);
					buffer_out_len=0x80;
				}
				return 8;
				//IF I return all FF, then board runs in low res
			case 0x31:
				{
					buffer_out[0]=0xffffffff;
					buffer_out[1]=0xffffffff;
				}
				return (8);
								
			default:
				printf("PuruPuru => Unknown 0x86: Sub 0x%X - State: 0x%X Mode: 0x%X Node: 0x%X\n",subcode,State.Cmd,State.Mode,State.Node);
				printState(Command,buffer_in,buffer_in_len);
			}

			return 8;//MAPLE_RESPONSE_DATATRF
		}
		break;
	case 0x82:
		{
			const char *ID="315-6149    COPYRIGHT SEGA E\x83\x00\x20\x05NTERPRISES CO,LTD.  ";
			memset(buffer_out_b,0x20,256);
			memcpy(buffer_out_b,ID,0x38-4);
			buffer_out_len=256;
			return (0x83);
		}
	/*typedef struct {
		DWORD		func;//4
		DWORD		function_data[3];//3*4
		u8		area_code;//1
		u8		connector_direction;//1
		char		product_name[30];//30*1
		char		product_license[60];//60*1
		WORD		standby_power;//2
		WORD		max_power;//2
	} maple_devinfo_t;*/
	case 1: 
		{			
			w32(1 << 24); // Caps						
			w32( 0xfe060f00); //struct data
			w32( 0);
			w32( 0);			
			w8(0xFF); //1	area code
			
			w8(0); //1	direction
			
			wStrings(Joy_strName, Joy_strBrand_2);
			
			//ptr_out += 60;			
			w16(0xAE01); //2			
			w16(0xF401); //2
		}
		return 5;

	case 9:
		{
			w32(1 << 24); //struct data
						
			w16(kcode[0] | 0xF901); //2
							
			w8(0x0); //triggers
			w8(0x0); 
						
			w8(0x80); // Analog XY
			w8(0x80); 
						
			w8(0x80); // XY2
			w8(0x80); 

			//are these needed ?
			//1
			//WriteMem8(ptr_out, 10); ptr_out += 1;
			//1
			//WriteMem8(ptr_out, 10); ptr_out += 1;
		}
		return 8;

	default:
		printf("PuruPuru => unknown MAPLE Frame: ");
		printState(Command,buffer_in,buffer_in_len);
		return 7;		
	}
Example #11
0
VOID
Usage()
{

        wprintf(
			L"httpcfg ACTION STORENAME [OPTIONS] \n"
			L"ACTION                             -set | query  | delete \n" 
			L"STORENAME                       -ssl | urlacl | iplisten \n"
			L"[OPTIONS]                         -See Below\n"
			L"\n"
			L"Options for ssl:\n"
			L"    -i IP-Address               - IP:port for the SSL certificate (record key)\n"
			L"\n"
			L"    -h SslHash                   - Hash of the Certificate.\n"
			L"\n"
			L"    -g GUID                       - GUID to identify the owning application.\n"
			L"\n"
			L"    -c CertStoreName           - Store name for the certificate. Defaults to\n"
			L"                                MY. Certificate must be stored in the\n"
			L"                                LOCAL_MACHINE context.\n"
			L"\n"
			L"    -m CertCheckMode           - Bit Flag\n"
			L"                                    0x00000001 - Client certificate will not be\n"
			L"                                                 verified for revocation.\n"
			L"                                    0x00000002 - Only cached client certificate\n"
			L"                                                 revocation will be used.\n"
			L"                                    0x00000004 - Enable use of the Revocation\n"
			L"                                                 freshness time setting.\n"
			L"                                    0x00010000 - No usage check.\n"
			L"\n"
			L"    -r RevocationFreshnessTime - How often to check for an updated certificate\n"
			L"                                 revocation list (CRL). If this value is 0,\n"
			L"                                 then the new CRL is updated only if the\n"
			L"                                 previous one expires. Time is specified in\n"
			L"                                 seconds.\n"
			L"\n"
			L"    -x UrlRetrievalTimeout     - Timeout on attempt to retrieve certificate\n"
			L"                                 revocation list from the remote URL.\n"
			L"                                 Timeout is specified in Milliseconds.\n"
			L"\n"
			L"    -t SslCtlIdentifier        - Restrict the certificate issuers that can be\n"
			L"                                 trusted. Can be a subset of the certificate\n"
			L"                                 issuers that are trusted by the machine.\n"
			L"\n"
			L"    -n SslCtlStoreName         - Store name under LOCAL_MACHINE where\n"
			L"                                 SslCtlIdentifier is stored.\n"
			L"\n"
			L"    -f Flags                   - Bit Field\n"
			L"                                    0x00000001 - Use DS Mapper.\n"
			L"                                    0x00000002 - Negotiate Client certificate.\n"
			L"                                    0x00000004 - Do not route to Raw ISAPI\n"
			L"                                                 filters.\n"
			L"\n"
			L"Options for urlacl:\n"
			L"    -u Url                     - Fully Qualified URL. (record key)\n"
			L"    -a ACL                     - ACL specified as a SDDL string.\n"
			L"\n"
			L"Options for iplisten:\n"
			L"    -i IPAddress               - IPv4 or IPv6 address. (for set/delete only)\n");

}
void printUsage()
{
	wprintf(L"\nUSAGE:");
	wprintf(L"\n WCNConfigure.exe"); 
    wprintf(L"\n  Scenario=[DeviceConfigPin | DeviceConfigPushButton | RouterConfig |");
	wprintf(L"\n            PCConfigPushButton | PCConfigPin ]");
	wprintf(L"\n  [UUID=<uuid of device> | SEARCHSSID=<ssid of device to find>]");
	wprintf(L"\n  [PIN=<pin of device>]"); 
	wprintf(L"\n  [PROFILESSID=<ssid to use in profile>]");
	wprintf(L"\n  [PROFILEPASSPHRASE=<passphrase to use in profile>]");
	wprintf(L"\n");		
	wprintf(L"\nParameters:");
	wprintf(L"\n Scenario - choose the operation you wish to perform ");
	wprintf(L"\n     DeviceConfigPushButton - Configure a WCN enabled device, such as a picture");
	wprintf(L"\n                              frame using the button on the device");
	wprintf(L"\n     DeviceConfigPin - Configure a WCN enabled device, such as a picture frame");
	wprintf(L"\n                       using the device supplied pin");
	wprintf(L"\n     RouterConfig - Configure a WCN enabled Wireless Router");
	wprintf(L"\n     PCConfigPushButton - Get the wireless profile from a WCN enabled router");
	wprintf(L"\n                          using the Push Button on the device.");
	wprintf(L"\n     PCConfigPin - Get the wireless profile from a WCN enabled rotuer using the");
	wprintf(L"\n                   supplied pin.");
	wprintf(L"\n");
	wprintf(L"\n UUID - Enter a device UUID in the following format xxxx-xxxx-xxxx-xxxxxxxxxxxx");
	wprintf(L"\n        UUID is necessary for the DeviceConfigPushButton and DeviceConfigPin");
	wprintf(L"\n        scenarios. Use either UUID or SEARCHSSID for the RouterConfig, PCConfigPin");
	wprintf(L"\n        and PCConfigPushButton scenarios.");
	wprintf(L"\n");
	wprintf(L"\n SEARCHSSID - Enter in the SSID for the Router you are looking to configure.");
	wprintf(L"\n              SEARCHSSID is only valid in the RouterConfig, PCConfigPushButton and ");
	wprintf(L"\n              PCConfigPin scenarios. Use either UUID or SEARCHSSID for the these");
	wprintf(L"\n              scenarios. NOTE: Using SSID will return the first device");
	wprintf(L"\n              found with that ssid.  If there is more than one device with the");
	wprintf(L"\n              same ssid use the UUID instead");
	wprintf(L"\n");
	wprintf(L"\n PIN  - Enter the pin of the device");
	wprintf(L"\n        PIN is only valid when using the RouterConfig and DeviceConfigPIN");
	wprintf(L"\n        Scenarios.");
	wprintf(L"\n");
	wprintf(L"\n PROFILESSID - When present this SSID will be used in the WLAN profile that is");
	wprintf(L"\n               pushed to the router/device otherwise a default SSID of WCNSSID ");
	wprintf(L"\n               will be used");
	wprintf(L"\n");
	wprintf(L"\n PROFILEPASSPHRASE - when present this passphrase will be used in the wlan");
	wprintf(L"\n                     profile that is pushed to the router/device. Otherwise, a");
	wprintf(L"\n                     random default passphrase will be used\n\n");
}
HRESULT GetWCNDeviceInformation(__in IWCNDevice* pDevice, __out WCN_DEVICE_INFO_PARAMETERS* pWCNDeviceInformation)
{
	HRESULT hr = ERROR_SUCCESS;
	
	//A WCN device can have a variety of attributes.  (These attributes generally correspond
	//to TLVs in the WPS specification, although not all WPS TLVs are available as WCN attributes).
	//You can use the IWCNDevice::Get*Attribute to read  these attributes.  Not all devices send 
	//all attributes -- if the device did not send a particular attribute, the Get*Attribute API 
	//will return HRESULT_FROM_WIN32(ERROR_NOT_FOUND).
	//
	//This sample demonstrates how to get the most common attributes that would be useful for
	//displaying in a user interface.


	//
	// WCN_TYPE_DEVICE_NAME
	//

	//The IWCNDevice::GetStringAttribute method gets a cached attribute from the device as a string.
	hr = pDevice->GetStringAttribute(
									WCN_TYPE_DEVICE_NAME, 
									ARRAYSIZE(pWCNDeviceInformation->wszDeviceName), 
									pWCNDeviceInformation->wszDeviceName);
	if (hr != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR:  Failed to get the Device Name from the IWCNDevice instance.  hr=[0x%x]", hr);
		goto cleanup;
	}

	wprintf(L"\nINFO: Device Name: [%s]",pWCNDeviceInformation->wszDeviceName);


	//
	// WCN_TYPE_MANUFACTURER
	//

	hr = pDevice->GetStringAttribute(
									WCN_TYPE_MANUFACTURER, 
									ARRAYSIZE(pWCNDeviceInformation->wszManufacturerName), 
									pWCNDeviceInformation->wszManufacturerName);
	if (hr != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: Failed to get the device manufacturer from the ICWNDevice instance, hr=[0x%x]", hr);
		goto cleanup;
	}

	wprintf(L"\nINFO: Manufacturer Name: [%s]", pWCNDeviceInformation->wszManufacturerName);


	//
	// WCN_TYPE_MODEL_NAME
	//

	hr = pDevice->GetStringAttribute(
										WCN_TYPE_MODEL_NAME, 
										ARRAYSIZE(pWCNDeviceInformation->wszModelName), 
										pWCNDeviceInformation->wszModelName);
	if (hr != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: Failed to get the device model name from the ICWNDevice instance, hr=[0x%x]", hr);
		goto cleanup;				
	}

	wprintf(L"\nINFO: Model Name: [%s]", pWCNDeviceInformation->wszModelName);


	//
	// WCN_TYPE_MODEL_NUMBER
	// Note that the Model Number is actually a string.  Most devices have alpha-numeric
	// model numbers, like "AB1234CD".

	hr = pDevice->GetStringAttribute(
										WCN_TYPE_MODEL_NUMBER, 
										ARRAYSIZE(pWCNDeviceInformation->wszModelNumber), 
										pWCNDeviceInformation->wszModelNumber);
	if (hr != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: Failed to get the device model name from the ICWNDevice instance, hr=[0x%x]", hr);
		goto cleanup;				
	}
	
	wprintf(L"\nINFO: Model Number: [%s]", pWCNDeviceInformation->wszModelNumber);


	//
	// WCN_TYPE_SERIAL_NUMBER
	// Note that the Serial Number is actually a string.  Some devices send strings that
	// aren't meaningful, like "(none)" or just the empty string.

	hr = pDevice->GetStringAttribute(
										WCN_TYPE_SERIAL_NUMBER, 
										ARRAYSIZE(pWCNDeviceInformation->wszSerialNumber), 
										pWCNDeviceInformation->wszSerialNumber);
	if (hr != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: Failed to get the device model name from the ICWNDevice instance, hr=[0x%x]", hr);
		goto cleanup;				
	}

	wprintf(L"\nINFO: Serial Number: [%s]", pWCNDeviceInformation->wszSerialNumber);


	//
	// WCN_TYPE_CONFIG_METHODS
	// This is a bit mask of the values from WCN_VALUE_TYPE_CONFIG_METHODS.
	// For example, a devices indicates support for pushbutton if its Config
	// Methods value includes the WCN_VALUE_CM_PUSHBUTTON flag.

	//The GetIntegerAttribute method gets a cached attribute from the device as an integer.
	hr = pDevice->GetIntegerAttribute(
										WCN_TYPE_CONFIG_METHODS, 
										&pWCNDeviceInformation->uConfigMethods);
	if (hr != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: Failed to get the device model name from the ICWNDevice instance, hr=[0x%x]", hr);
		goto cleanup;				
	}
		
cleanup:
	return hr;
}
HRESULT RunScenario(__in CONFIGURATION_PARAMETERS* configParams)
{
	//common declarations
	UINT status = ERROR_SUCCESS;	
	HRESULT hr = S_OK;
	UINT pinLen = Pin_Length_8;

	//pin needs to be a null terminated ascii char[] for the IWCNDevice::SetPassword function 
	char pin[Pin_Length_8 + 1] = {0};

	
	int result = 0;

	//WCN declarations
	CComPtr<IWCNDevice> pDevice;
	CComObject<WcnConnectNotification>* pWcnConNotif = NULL;	
	CComObject<CWcnFdDiscoveryNotify> * wcnFdDiscoveryNotify = NULL;	

	//Wlan variable declarations
	WCHAR profileBuffer[WCN_API_MAX_BUFFER_SIZE] = {0}; 
	HANDLE wlanHandle = 0;
	DWORD negVersion = 0;
	GUID interfaceGuid = {0};		
	WLAN_INTERFACE_INFO_LIST* pInterfaceList = 0;
	DWORD wlanResult = 0;		
	WLAN_CONNECTION_PARAMETERS connParams;
	ZeroMemory(&connParams,sizeof(connParams));
	WCN_DEVICE_INFO_PARAMETERS WCNDeviceInformation;
	PWSTR pWlanProfileXml = NULL;
	DWORD dwFlags = WLAN_PROFILE_GET_PLAINTEXT_KEY; 


	//The following wlan profile xml is used to configure an unconfigured WCN enabled Router or device.
	//See http://msdn.microsoft.com/en-us/library/bb525370(VS.85).aspx on how to generate a wlan profile.
	//Alternatively, you can read an existing network profile by calling WlanGetProfile.
	WCHAR WCNConnectionProfileTemplate[] =
		L"<?xml version=\"1.0\" ?>"
		L""
		L"<WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">"
		L"    <name>%s</name>"
		L""
		L"    <SSIDConfig>"
		L"        <SSID>"
		L"            <name>%s</name>"
		L"        </SSID>"
		L"    </SSIDConfig>"
		L"    "
		L"    <connectionType>ESS</connectionType>"
		L"    <connectionMode>auto</connectionMode>"
		L""
		L"    <MSM>"
		L"        <security>"
		L"            <authEncryption>"
		L"                <authentication>WPA2PSK</authentication>"
		L"                <encryption>AES</encryption>"
		L"            </authEncryption>"
		L""
		L""
		L"            <sharedKey>"
		L"                <keyType>passPhrase</keyType>"
		L"                <protected>false</protected>"
		L"                <keyMaterial>%s</keyMaterial>"
		L"            </sharedKey>"
		L""
		L"        </security>"
		L"    </MSM>"
		L"</WLANProfile>";


	std::wstring profileXML;

	//open a wlan handle - this will be used later for saving the profile to the system
	status = WlanOpenHandle(
							WLAN_API_VERSION_2_0,
							NULL,
							&negVersion,
							&wlanHandle);

	if (status != ERROR_SUCCESS)
	{
		wprintf(L"\nERROR: WlanOpenHandle failed with the following error code [%d]", status);
		hr = S_FALSE;
		goto cleanup;
	}

	// Get the first wlan device
	// ideally you would want to be able to choose the wireless device you want to use
	status = WlanEnumInterfaces(
								wlanHandle,
								NULL,
								&pInterfaceList);

	if(status != ERROR_SUCCESS)
	{				
		wprintf(L"\nERROR: WlanEnumInterfaces failed with the following error code [0x%d]",status);
		hr = S_FALSE;
		goto cleanup;		
	}

	//Make sure there is at least one wlan interface on the system
	if (pInterfaceList == 0 || pInterfaceList->dwNumberOfItems == 0)
	{
		wprintf(L"\nERROR: No wireless network adapters on the system");
		hr = S_FALSE;
		goto cleanup;
	}

	//get the wlan interface GUID
	interfaceGuid = pInterfaceList->InterfaceInfo[0].InterfaceGuid;

	//Create an instance of the IWCNConnectNotify Interface
	hr = CComObject<WcnConnectNotification>::CreateInstance(&pWcnConNotif);
	if (hr != S_OK)
	{
		wprintf(L"\nERROR: Creating an instance of WcnConnectNotification failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}
	pWcnConNotif->AddRef();

	hr = CComObject<CWcnFdDiscoveryNotify>::CreateInstance(&wcnFdDiscoveryNotify);
	if (hr != S_OK)
	{
		wprintf(L"\nERROR: Creating an instance of CWcnFdDiscoveryNotify failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}
	wcnFdDiscoveryNotify->AddRef();

	//initialize WcnConnectNotification
	hr = pWcnConNotif->Init();
	if(hr !=S_OK)
	{
		wprintf(L"\nERROR: Creating a connection notification event failed with the following error hr=[0x%x]", hr);
		goto cleanup;
	}

	//initialize CWcnFdDiscoveryNotify 
	hr = wcnFdDiscoveryNotify->Init(configParams->bTurnOnSoftAP);
	if(hr != S_OK)
	{
		wprintf(L"\nERROR: Initializing Function Discovery notify failed with the following error hr=[0x%x].",hr);
		goto cleanup;
	}

	//Search for WCN device with function discovery
	hr = wcnFdDiscoveryNotify->WcnFDSearchStart(&configParams->pDeviceUUID, configParams->pSearchSSID);		
	if(hr != S_OK)
	{
		wprintf(L"\nERROR: Function Discovery search failed to start with the following error hr=[0x%x].",hr);
		goto cleanup;
	}

	//Wait for Function Discovery to complete
	wcnFdDiscoveryNotify->WaitForAnyDiscoveryEvent(Discovery_Event_Wait_Time_MS);

	//Attempt to get the IWCNDevice instance
	if(wcnFdDiscoveryNotify->GetWCNDeviceInstance(&pDevice))
	{
		//get information about the device from the IWCNDevice instance
		wprintf(L"\nINFO: The following Device was found by Function Discovery.");
		hr = GetWCNDeviceInformation(pDevice, &WCNDeviceInformation);
		if (hr != S_OK)
		{
			wprintf(L"\nERROR: Failed to get the Device information from the IWCNDevice Instance, hr=[0x%x]", hr);
			goto cleanup;
		}
	}
	else
	{
		wprintf(L"\nERROR: Device was NOT found by Function Discovery.");
		hr = S_FALSE;
		goto cleanup;
	}
	
	

	//The following segment generates a WLAN profile from the template above then saves it to the
	//WLAN store. It the retrieves the profile from the WLAN store for use in configuring a router
	//or device.
	if (configParams->enumConfigScenario != PCConfigPin 
		&& configParams->enumConfigScenario != PCConfigPushButton)
	{
		//add the profiles ssid and passphrase to the wlan profile template
		swprintf_s(
				profileBuffer, 
				WCNConnectionProfileTemplate, 
				configParams->pProfileSSID, 
				configParams->pProfileSSID, 
				configParams->pProfilePassphrase);


		//Add the created profile to the wlan store
		status = WlanSetProfile(
								wlanHandle, 
								&interfaceGuid, 
								0,				//all-user profile
								profileBuffer, 
								NULL,			// Default Security - All user profile
								TRUE,			// Overwrite profile
								NULL,			// reserved
								&wlanResult);

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: Failed to save the profile return code was [0x%x]", wlanResult);
			hr = S_FALSE;
			goto cleanup;
		}
		else
		{
			wprintf(L"\nINFO: Successfully saved the profile to the wlan store");
		}

		//Here is where the profile is retrieved from the wlan store to be used in the configuration
		//of the device.  
		//If so desired a list of available profiles could be presented to the user so that 
		//they could decied which profile will be used to configure the device
		//The wlan profile must be retrieved in plain text inorder for the IWCNDEVICE::SetNetWorkProfile
		// method to succeede.  In order to do this you need to be elevated to get the wlan profile
		// in plain text.
		status = WlanGetProfile(
								wlanHandle,
								&interfaceGuid,
								configParams->pProfileSSID,
								NULL,						//reserved
								&pWlanProfileXml,
								&dwFlags,					// Flags - get profile in plain text 
								NULL);						// GrantedAccess - none

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: WlanGetprofile Failed to get profile [%s] with error code [0x%x]", configParams->pProfileSSID, status);
			hr = S_FALSE;
			goto cleanup;
		}
		else
		{
			wprintf(L"\nINFO: Successfully retrieved profile [%s] from the wlan store.", configParams->pProfileSSID);
		}

		//check to make sure the profile from the wlan store is not a Group Policy profile
		if (WLAN_PROFILE_GROUP_POLICY & dwFlags)
		{
			wprintf(L"\nERROR: Profile [%s] is a group policy WLAN profile which is not supported by WCN", configParams->pProfileSSID);
			hr = S_FALSE;
			goto cleanup;
		}


		//The IWCNDevice::SetNetworkProfile method queues an XML WLAN profile to be 
		//provisioned to the device. This method may only be called prior to IWCNDevice::Connect.
		hr = pDevice->SetNetworkProfile(pWlanProfileXml);
		if(hr != S_OK)
		{
			wprintf(L"\nERROR: IWCNDevice::SetNetworkProfile failed with error code [0x%x]", hr);
			goto cleanup;
		}
		else
		{				
			wprintf(L"\nINFO: IWCNDevice::SetNetworkProfile() succeeded with result [0x%x]", hr);
		}
	}
	
	switch (configParams->enumConfigScenario)
	{
		case DeviceConfigPushButton:
			
			pinLen = 0;
			break;

		case DeviceConfigPin:
		case RouterConfig:
			if (configParams->pDevicePin == 0)
			{
				wprintf(L"\nERROR: Pin must not be 0 when doing a pin configuration");
				hr = S_FALSE;
				goto cleanup;
			}


			 result = WideCharToMultiByte(
							CP_UTF8,
							0,
							configParams->pDevicePin,
							-1,
							(LPSTR)pin,
							sizeof(pin),
							NULL,
							NULL);
			if (result == 0 )
			{
				wprintf(L"\nERROR: Failed to convert the pin to multibyte.");
				goto cleanup;
			}


			pinLen = sizeof(pin) - 1 ;
			break;

		case PCConfigPushButton:
			//check to make sure the device supports push button before doing the push button configuration
			if (WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_PUSHBUTTON) 
			{
				//set the pin length to 0 this is necessary for a Push button configuration scenario				
				pinLen = 0;
			}
			else
			{
				wprintf(L"ERROR: The [%s] device does not support the Push Button Method", WCNDeviceInformation.wszDeviceName);
				hr = S_FALSE;
				goto cleanup;
			}
			break;
			
		case PCConfigPin:
			//check to make sure the device supports pin before doing the pin configuration
			if ((WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_LABEL)|| 
				(WCNDeviceInformation.uConfigMethods & WCN_VALUE_CM_DISPLAY))
			{
				if (configParams->pDevicePin == 0)
				{
					wprintf(L"\nERROR: Pin must not be 0 when doing a pin configuration");
					hr = S_FALSE;
					goto cleanup;
				}
			
				result = WideCharToMultiByte(
							CP_UTF8,					//CodePage
							0,							//Unmapped character flags
							configParams->pDevicePin,
							-1,							//null terminated string
							(LPSTR)pin,
							sizeof(pin),
							NULL,						//lpDefaultChar - use system default value
							NULL);						//lpUsedDefaultChar ignored
				if (result == 0 )
				{
					wprintf(L"\nERROR: Failed to convert the pin to multibyte.");
					goto cleanup;
				}

				pinLen = sizeof(pin) - 1 ;

			}
			else
			{
				wprintf(L"\nERROR: The [%s] device does not supprot the pin method", WCNDeviceInformation.wszDeviceName);
				hr = S_FALSE;
				goto cleanup;
			}
			break;

		default:
			break;
	}
	
	//The IWCNDevice::SetPassword method configures the authentication method value, and if required, 
	//a password used for the pending session. This method may only be called prior to IWCNDevice::Connect.
	hr = pDevice->SetPassword(
								configParams->enumConfigType, 
								pinLen,
								(BYTE*)pin);

	if(hr != S_OK)
	{	
		wprintf(L"\nERROR: IWCNDevice::SetPassword failed with error code [0x%x]", hr);
		goto cleanup;
	}
	else
	{
		wprintf(L"\nINFO: IWCNDevice::SetPassword succeeded with result [0x%x]", hr);
	}


	//The IWCNDevice::Connect method initiates the session.
	hr = pDevice->Connect(pWcnConNotif);
	if(hr != S_OK)
	{
		//Device Push button configuration is only supported on SoftAP capable wireless Nics 
		if (hr == HRESULT_FROM_WIN32(ERROR_CONNECTION_UNAVAIL) 
			&& 	configParams->enumConfigScenario == DeviceConfigPushButton)
		{
			wprintf(L"\nERROR: PushButton Configuration of non AP devices is only supported on");
			wprintf(L"\n       SoftAP capable wireless network cards.");
		}
		else
		{
			wprintf(L"\nERROR: IWCNDevice::Connect failed with error code [0x%x]", hr);
		}
		goto cleanup;
	}
	else
	{
		wprintf(L"\nINFO: IWCNDevice::Connect succeeded with result [0x%x]", hr);
	}

	//wait for the configuration result
	hr = pWcnConNotif->WaitForConnectionResult();
	if (hr != S_OK)
	{
		wprintf(L"ERROR: WaitforconnectionResult returned the following error [ox%x]", hr);
		goto cleanup;
	}

	//check to see which connection callbacks were called
	if(pWcnConNotif->connectSucceededCallBackInvoked)
	{
		wprintf(L"\nINFO: IWCNConnectNotify::ConnectSucceeded was invoked");		
	}
	else if(pWcnConNotif->connectFailedCallBackInvoked)
	{
		wprintf(L"\nERROR: IWCNConnectNotify::ConnectFailed was invoked");
		hr = S_FALSE;
		goto cleanup;
	}

	
	//save the profile from the IWCNDevice instance to the WLAN store if doing a PCConfigPushButton 
	//or a PCConfigPin scenario

	// this is the profile that was received from the router
	if (configParams->enumConfigScenario == PCConfigPushButton  || configParams->enumConfigScenario == PCConfigPin)
	{	
		//The IWCNDevice::GetNetworkProfile method gets a network profile from the device.
		hr = pDevice->GetNetworkProfile(ARRAYSIZE(profileBuffer), profileBuffer);		
		if(hr != S_OK)
		{
			wprintf(L"\nERROR: IWCNDevice::GetNetworkProfile failed with  [0x%x]", hr);
			goto cleanup;
		}

		//save the profile to the system if doing a RouterConfig or a pushbutton scenario
		//The SoftapConfig and DeviceConfig scenarios will generally use a profile that is already on the system
		//save the profile to the wlan interface			
		status = WlanSetProfile(
								wlanHandle, 
								&interfaceGuid, 
								0,				//Flags - none
								profileBuffer, 
								NULL,			// Default Security - All user profile
								TRUE,			// Overwrite profile
								NULL,			// reserved
								&wlanResult);

		if (status != ERROR_SUCCESS)
		{
			wprintf(L"\nERROR: Failed to save the profile to the WLAN store, return code was [0x%x]", wlanResult);
			hr = S_FALSE;
		}
		else
		{
			wprintf(L"\nINFO: Successfully saved the profile to the WLAN store");
		}
	}
	
	//Display the SSID and passphrase used to configure the Router or device
	if (configParams->enumConfigScenario != PCConfigPin && configParams->enumConfigScenario != PCConfigPushButton)
	{
		wprintf(L"\nINFO: Profile SSID Used: [%s]", configParams->pProfileSSID);
		wprintf(L"\nINFO: Profile Passphrase Used: [%s]", configParams->pProfilePassphrase);
	}

cleanup:

	if(pWcnConNotif)
	{
		pWcnConNotif->Release();
		pWcnConNotif = 0;
	}

	if(wcnFdDiscoveryNotify)
	{
		wcnFdDiscoveryNotify->Release();
		wcnFdDiscoveryNotify = 0;
	}

	if (wlanHandle != NULL)
	{
		WlanCloseHandle(wlanHandle,NULL);
	}

	if (pInterfaceList != NULL)
	{
		WlanFreeMemory(pInterfaceList);
	}

	return hr;
}
void CBase::Foo()
{
    wprintf(L"CBase::Foo\n");
}
Example #16
0
/*  PopulateADSAttrInfo()   - Populates the passed ADS_ATTR_INFO from the passed attribute and Value
    
    Parameters

    ADS_ATTR_INFO * pattrInfo   - Pointer to Element to be added
    LPWSTR pwszAttrib           - Name of the Attribute
    LPWSTR pwszValue            - Value of the Attribute

*/
BOOL PopulateADSAttrInfo(ADS_ATTR_INFO * pattrInfo,LPWSTR pwszAttrib,LPWSTR pwszValue)
{
    // Look up the attribute name and get the TYPE string for this attribute
    LPWSTR pwszType;
    LPWSTR  pwszSingleMulti;
    BOOL bAttribIsSingle = TRUE;

    BOOL bret;
    
    bret = MapUserAttribToType(pwszAttrib,&pwszType,&pwszSingleMulti);
    if (!bret)
    {
        wprintf(L"\n!!!Error: unable to map %s\n",pwszAttrib);
        return FALSE;
    }

    if (_wcsicmp(pwszSingleMulti,L"MV")==0)
        bAttribIsSingle = FALSE;
    else
        bAttribIsSingle = TRUE;        

    // Look up the string and get the corrosponding ADSVALUE...
    ADSTYPE adType = MapTypeToADSTYPE(pwszType);

    if (adType == ADSTYPE_UNKNOWN)
    {
        wprintf(L"\n!!!Error: unable to map %s ADS_TYPE unknown\n",pwszAttrib);
        return FALSE;
    }
    // FIll in the Attribute Name
	unsigned int attrNameLen = wcslen(pwszAttrib)+1;
    pattrInfo->pszAttrName = new WCHAR [attrNameLen];
    wcscpy_s(pattrInfo->pszAttrName,attrNameLen,pwszAttrib);
    pattrInfo->dwControlCode  = ADS_ATTR_UPDATE;
    pattrInfo->dwADsType = ADSTYPE_CASE_IGNORE_STRING;

    pattrInfo->pADsValues = new ADSVALUE;
    pattrInfo->pADsValues->dwType = adType;
    pattrInfo->dwNumValues = 1;
    
    // Fill in the VALUE:
    switch (adType )
    {

        case ADSTYPE_DN_STRING:	            
        case ADSTYPE_CASE_EXACT_STRING:	    
        case ADSTYPE_CASE_IGNORE_STRING:	    
        case ADSTYPE_PRINTABLE_STRING:	    
        case ADSTYPE_NUMERIC_STRING:	        
        case ADSTYPE_TYPEDNAME:	            
        case ADSTYPE_FAXNUMBER:	            
        case ADSTYPE_PATH:	                
        case ADSTYPE_OBJECT_CLASS:
        {
            pattrInfo->pADsValues->CaseIgnoreString = new WCHAR [wcslen(pwszValue)+1];
            wcscpy_s(pattrInfo->pADsValues->CaseIgnoreString,wcslen(pwszValue)+1,pwszValue);

            break;
        }
        case ADSTYPE_BOOLEAN:
            if (_wcsicmp(pwszValue,L"TRUE")==0)
                pattrInfo->pADsValues->Boolean = 1;
            else if (_wcsicmp(pwszValue,L"FALSE")==0)
                pattrInfo->pADsValues->Boolean = 0;
            else if (_wtoi(pwszValue)>0)
                pattrInfo->pADsValues->Boolean = 1;
            else
                pattrInfo->pADsValues->Boolean = 0;
            break;
        case ADSTYPE_INTEGER:
        {
            pattrInfo->pADsValues->Integer = _wtoi(pwszValue);
            break;
        }
        case ADSTYPE_OCTET_STRING:	        
        {
            // Read the string into an actualy binary blob
            HRESULT hr = MakeOctetADSVALUE(pattrInfo->pADsValues ,pwszValue);    
            if (FAILED(hr))
                return FALSE;                    
            break;
        }                                                                        
        case ADSTYPE_UTC_TIME:	            
        {
            SYSTEMTIME pst;
            
            HRESULT hr = ConvertUTCFromStringToUTCTime( pwszValue,&pst );
            
            if (FAILED(hr))
                return FALSE;                    

            pattrInfo->pADsValues->UTCTime = pst;

            break;
        }
        case ADSTYPE_LARGE_INTEGER:	        
        {
            pattrInfo->pADsValues->dwType = ADSTYPE_LARGE_INTEGER;
            swscanf_s (pwszValue, L"%I64d", &pattrInfo->pADsValues->LargeInteger);
            break;
        }

        default:
        {
            wprintf(L"\n\n!!!ERROR Unrecognized Type for atrib: %s",pwszAttrib);
            return FALSE;
        }
    }
    return TRUE;
}
void CDerived2::Foo()
{
    wprintf(L"CDerived2::Foo\n");
}
Example #18
0
/*  CreateUserFromFile()   - Function for creating a basic User
    
    Parameters

        IDirectoryObject *pDirObject    -   Parent Directory Object for the new User
        LPWSTR pwCommonName             -   Common Name for the new User
        IDirectoryObject ** ppDirObjRet -   Pointer to the Pointer which will receive the new User
        int iUserType                  -   Bitflags for new User:
                                                                    ADS_User_TYPE_GLOBAL_User, 
                                                                    ADS_User_TYPE_DOMAIN_LOCAL_User, 
                                                                    ADS_User_TYPE_UNIVERSAL_User, 
                                                                    ADS_User_TYPE_SECURITY_ENABLED 
*/
HRESULT CreateUserFromFile(IDirectoryObject *pDirObject, LPWSTR pwCommonName,LPWSTR pwSamAcctName,IDirectoryObject ** ppDirObjRet,LPWSTR pwszFileName)
{
    // To simply things, allocate a fixed array:
    ADS_ATTR_INFO   attrInfo [MAX_ATTRIBS+1];

    HRESULT         hr = S_OK;
    DWORD           dwNumPopulated;
    LPDISPATCH      pDisp;
    *ppDirObjRet     = NULL;
    WCHAR           pwCommonNameFull[MAX_PATH*2];
    BOOL    bRet = FALSE;
    FILE * fpInput = NULL;
    WCHAR  pwszLine[4096];
    dwNumPopulated = 0;
	errno_t status = 0;

	if( (status = _wfopen_s( &fpInput, pwszFileName, L"r" )) == NULL )
	{
		wprintf(L"\nError Opening Input File:%s",pwszFileName);
		return FALSE;
	}

    while (GetNextLine(fpInput,pwszLine,4096) && SUCCEEDED(hr))
    {
        Trim(pwszLine);
        
        BSTR bsAttrib;
        BSTR bsValue;

        // Read the line into our BSTRS
        // if S_FALSE is returned, then we do not have a line
        // if E_FAIL is returned, then we have an error condition
        hr = ReadDataFromLine(pwszLine,&bsAttrib,&bsValue);

        if (hr == S_OK) 
        {
            wprintf(L" attrib:%s value:%s\n",bsAttrib,bsValue);
            
            // Take the attribute and value and add them to the Array
            if (!PopulateADSAttrInfo(&attrInfo[dwNumPopulated],bsAttrib,bsValue))
            {
                hr = E_FAIL;
                break;
            }

            SysFreeString(bsAttrib);
            SysFreeString(bsValue);
            dwNumPopulated++;
        }
    }
	fclose(fpInput);

    wsprintfW(pwCommonNameFull,L"CN=%s",pwCommonName);

    hr = pDirObject->CreateDSObject( pwCommonNameFull,  attrInfo, 
    dwNumPopulated, &pDisp );

    if (SUCCEEDED(hr))
    {
        hr = pDisp->QueryInterface(IID_IDirectoryObject,(void**) ppDirObjRet);

        pDisp->Release();
        pDisp = NULL;
    }

    //FreeAttrInfo(attrInfo);

	return hr;
}
Example #19
0
File: www.c Project: clflush/tty64
int httpd_www_config(int fd, char *raw, char *cgi) {
	int idx;
	char *refer_cgi, *a_retval, *retval;

	if (!alt_cfg) {

		alt_cfg = hashtable_create(_MAX_CONF_OPTS);

		if (!alt_cfg) {
			httpd_www_syserr_msg(fd, "hashtable_create", raw);
			return 0;
		}
	}

	httpd_start_hmenu(fd, config_menu);
	httpd_end_hmenu(fd);

	httpd_www_label(fd, "Configuration", 80);

 	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\"85%\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "\t<TR>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">option</TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">value</TD>\n");
	wprintf(fd, "\t</TR>\n");

	for (idx = 0; cfg_truthtable[idx].tag != NULL; idx++) {

		if (cfg_truthtable[idx].tag_mode) {

			wprintf(fd, "\t<TR>\n");
			wprintf(fd, "\t\t<TD>%s</TD>\n", cfg_truthtable[idx].tag);

			refer_cgi = "config-newval.cgi";

			if (cfg_truthtable[idx].tag_type == IS_BOOLEAN) {
					refer_cgi = "config-flipflop.cgi";
			}	
			
			a_retval = hashtable_lookup(alt_cfg, cfg_truthtable[idx].tag);

			retval = hashtable_lookup(cfg, cfg_truthtable[idx].tag);

			if (!retval) {
				retval = "no value";
			}

			if (a_retval) {

				wprintf(fd, "\t\t<TD ALIGN=\"CENTER\"><A HREF=\"/%s?id=%d\">%s (%s)</A></TD>\n",
					refer_cgi, idx, retval, a_retval);

			} else {

				wprintf(fd, "\t\t<TD ALIGN=\"CENTER\"><A HREF=\"/%s?id=%d\">%s</A></TD>\n",
					refer_cgi, idx, retval);
			}

			wprintf(fd, "\t</TR>\n");
		}
	}

	wprintf(fd, "</TABLE>\r\n");
	
	return 1;	
}
Example #20
0
static bool OnCrash(const wchar_t * dumpPath,
                    const wchar_t * miniDumpId,
                    void * context,
                    EXCEPTION_POINTERS * exinfo,
                    MDRawAssertionInfo * assertion,
                    bool succeeded)
{
    if (!succeeded)
    {
        constexpr const char * DumpFailedMessage = "Failed to create the dump. Please file an issue with OpenRCT2 on GitHub and provide latest save, and provide information about what you did before the crash occured.";
        printf("%s\n", DumpFailedMessage);
        if (!gOpenRCT2SilentBreakpad)
        {
            MessageBoxA(NULL, DumpFailedMessage, OPENRCT2_NAME, MB_OK | MB_ICONERROR);
        }
        return succeeded;
    }

    // Get filenames
    wchar_t dumpFilePath[MAX_PATH];
    wchar_t saveFilePath[MAX_PATH];
    swprintf_s(dumpFilePath, sizeof(dumpFilePath), L"%s%s.dmp", dumpPath, miniDumpId);
    swprintf_s(saveFilePath, sizeof(saveFilePath), L"%s%s.sv6", dumpPath, miniDumpId);

    // Try to rename the files
    wchar_t dumpFilePathNew[MAX_PATH];
    swprintf_s(dumpFilePathNew, sizeof(dumpFilePathNew), L"%s%s(%s_%s).dmp", dumpPath, miniDumpId, _wszCommitSha1Short, _wszArchitecture);
    if (_wrename(dumpFilePath, dumpFilePathNew) == 0)
    {
        std::wcscpy(dumpFilePath, dumpFilePathNew);
    }

    // Log information to output
    wprintf(L"Dump Path: %s\n", dumpPath);
    wprintf(L"Dump File Path: %s\n", dumpFilePath);
    wprintf(L"Dump Id: %s\n", miniDumpId);
    wprintf(L"Version: %s\n", WSZ(OPENRCT2_VERSION));
    wprintf(L"Commit: %s\n", _wszCommitSha1Short);

    utf8 * saveFilePathUTF8 = widechar_to_utf8(saveFilePath);
    SDL_RWops * rw = SDL_RWFromFile(saveFilePathUTF8, "wb+");
    free(saveFilePathUTF8);

    bool savedGameDumped = false;
    if (rw != NULL) {
        scenario_save(rw, 0x80000000);
        savedGameDumped = true;
        SDL_RWclose(rw);
    }

    if (gOpenRCT2SilentBreakpad)
    {
        return succeeded;
    }
    constexpr const wchar_t * MessageFormat = L"A crash has occurred and a dump was created at\n%s.\n\nPlease file an issue with OpenRCT2 on GitHub, and provide the dump and saved game there.\n\nVersion: %s\nCommit: %s";
    wchar_t message[MAX_PATH * 2];
    swprintf_s(message,
               MessageFormat,
               dumpFilePath,
               WSZ(OPENRCT2_VERSION),
               _wszCommitSha1Short);

    // Cannot use platform_show_messagebox here, it tries to set parent window already dead.
    MessageBoxW(NULL, message, WSZ(OPENRCT2_NAME), MB_OK | MB_ICONERROR);
    HRESULT coInitializeResult = CoInitialize(NULL);
    if (SUCCEEDED(coInitializeResult))
    {
        LPITEMIDLIST pidl = ILCreateFromPathW(dumpPath);
        LPITEMIDLIST files[2];
        uint32 numFiles = 0;

        files[numFiles++] = ILCreateFromPathW(dumpFilePath);
        if (savedGameDumped)
        {
            files[numFiles++] = ILCreateFromPathW(saveFilePath);
        }
        if (pidl != nullptr) {
            HRESULT result = SHOpenFolderAndSelectItems(pidl, numFiles, (LPCITEMIDLIST *)files, 0);
            ILFree(pidl);
            for (uint32 i = 0; i < numFiles; i++)
            {
                ILFree(files[i]);
            }
        }
        CoUninitialize();
    }

    // Return whether the dump was successful
    return succeeded;
}
Example #21
0
File: www.c Project: clflush/tty64
__inline__ void httpd_www_proxy_dialog(int fd, char *action, int proxyidx, char *proxyaddr, int proxyport, char *submit_cpt) {

 	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\"35%\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD COLSPAN=\"2\">\n");
    	wprintf(fd, "<FORM ACTION=\"%s\" METHOD=\"GET\">\n", action);

	if (proxyaddr) {
		wprintf(fd, "proxy address: <INPUT SIZE=\"24\" TYPE=\"TEXT\" VALUE=\"%s\" NAME=\"proxyaddr\">\n", proxyaddr);
	        wprintf(fd, "<BR>\n");
		wprintf(fd, "proxy port: <INPUT SIZE=\"6\" TYPE=\"TEXT\" VALUE=\"%d\" NAME=\"proxyport\">\n", proxyport);
	} else {
		wprintf(fd, "proxy address: <INPUT SIZE=\"24\" TYPE=\"TEXT\" NAME=\"proxyaddr\">\n");
	        wprintf(fd, "<BR>\n");
		wprintf(fd, "proxy port: <INPUT SIZE=\"6\" TYPE=\"TEXT\" NAME=\"proxyport\">\n");
	}

	wprintf(fd, "<INPUT READONLY TYPE=\"HIDDEN\" NAME=\"proxyidx\" VALUE=\"%d\">\n", proxyidx);
        wprintf(fd, "<BR>\n");
	wprintf(fd, "</TD>\n");
	wprintf(fd, "</TR>\n");
	wprintf(fd, "<TR>\n");
	wprintf(fd, "<TD ALIGN=\"CENTER\"><INPUT TYPE=SUBMIT VALUE=\"%s\"></TD>\n", submit_cpt);
	wprintf(fd, "<TD ALIGN=\"CENTER\"><INPUT TYPE=RESET VALUE=\"clear\"></TD>\n");
	wprintf(fd, "</FORM>\n");
	wprintf(fd, "</TD>\n");
	wprintf(fd, "</TR>\n");
	wprintf(fd, "</TABLE>\n");
	
	return ;
}
//------------------------------------------------------------------
// Displays the native Print Dialog
static nsresult 
ShowNativePrintDialog(HWND              aHWnd,
                      nsIPrintSettings* aPrintSettings)
{
  //NS_ENSURE_ARG_POINTER(aHWnd);
  NS_ENSURE_ARG_POINTER(aPrintSettings);

  gDialogWasExtended  = false;

  // Get the Print Name to be used
  nsXPIDLString printerName;
  aPrintSettings->GetPrinterName(getter_Copies(printerName));

  // If there is no name then use the default printer
  if (printerName.IsEmpty()) {
    GetDefaultPrinterNameFromGlobalPrinters(printerName);
  } else {
    HANDLE hPrinter = nullptr;
    if(!::OpenPrinterW(const_cast<wchar_t*>(static_cast<const wchar_t*>(printerName.get())),
                       &hPrinter, nullptr)) {
      // If the last used printer is not found, we should use default printer.
      GetDefaultPrinterNameFromGlobalPrinters(printerName);
    } else {
      ::ClosePrinter(hPrinter);
    }
  }

  // Now create a DEVNAMES struct so the the dialog is initialized correctly.

  uint32_t len = printerName.Length();
  nsHGLOBAL hDevNames = ::GlobalAlloc(GHND, sizeof(wchar_t) * (len + 1)
                                      + sizeof(DEVNAMES));
  nsAutoGlobalMem autoDevNames(hDevNames);
  if (!hDevNames) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  DEVNAMES* pDevNames = (DEVNAMES*)::GlobalLock(hDevNames);
  if (!pDevNames) {
    return NS_ERROR_FAILURE;
  }
  pDevNames->wDriverOffset = sizeof(DEVNAMES)/sizeof(wchar_t);
  pDevNames->wDeviceOffset = sizeof(DEVNAMES)/sizeof(wchar_t);
  pDevNames->wOutputOffset = sizeof(DEVNAMES)/sizeof(wchar_t)+len;
  pDevNames->wDefault      = 0;

  memcpy(pDevNames+1, printerName, (len + 1) * sizeof(wchar_t));
  ::GlobalUnlock(hDevNames);

  // Create a Moveable Memory Object that holds a new DevMode
  // from the Printer Name
  // The PRINTDLG.hDevMode requires that it be a moveable memory object
  // NOTE: autoDevMode is automatically freed when any error occurred
  nsAutoGlobalMem autoDevMode(CreateGlobalDevModeAndInit(printerName, aPrintSettings));

  // Prepare to Display the Print Dialog
  PRINTDLGW  prntdlg;
  memset(&prntdlg, 0, sizeof(PRINTDLGW));

  prntdlg.lStructSize = sizeof(prntdlg);
  prntdlg.hwndOwner   = aHWnd;
  prntdlg.hDevMode    = autoDevMode.get();
  prntdlg.hDevNames   = hDevNames;
  prntdlg.hDC         = nullptr;
  prntdlg.Flags       = PD_ALLPAGES | PD_RETURNIC | 
                        PD_USEDEVMODECOPIESANDCOLLATE | PD_COLLATE;

  // if there is a current selection then enable the "Selection" radio button
  int16_t howToEnableFrameUI = nsIPrintSettings::kFrameEnableNone;
  bool isOn;
  aPrintSettings->GetPrintOptions(nsIPrintSettings::kEnableSelectionRB, &isOn);
  if (!isOn) {
    prntdlg.Flags |= PD_NOSELECTION;
  }
  aPrintSettings->GetHowToEnableFrameUI(&howToEnableFrameUI);

  int32_t pg = 1;
  aPrintSettings->GetStartPageRange(&pg);
  prntdlg.nFromPage           = pg;
  
  aPrintSettings->GetEndPageRange(&pg);
  prntdlg.nToPage             = pg;

  prntdlg.nMinPage            = 1;
  prntdlg.nMaxPage            = 0xFFFF;
  prntdlg.nCopies             = 1;
  prntdlg.lpfnSetupHook       = nullptr;
  prntdlg.lpSetupTemplateName = nullptr;
  prntdlg.hPrintTemplate      = nullptr;
  prntdlg.hSetupTemplate      = nullptr;

  prntdlg.hInstance           = nullptr;
  prntdlg.lpPrintTemplateName = nullptr;

  if (!ShouldExtendPrintDialog()) {
    prntdlg.lCustData         = 0;
    prntdlg.lpfnPrintHook     = nullptr;
  } else {
    // Set up print dialog "hook" procedure for extending the dialog
    prntdlg.lCustData         = (DWORD)howToEnableFrameUI;
    prntdlg.lpfnPrintHook     = (LPPRINTHOOKPROC)PrintHookProc;
    prntdlg.Flags            |= PD_ENABLEPRINTHOOK;
  }

  BOOL result;
  {
    mozilla::widget::WinUtils::AutoSystemDpiAware dpiAwareness;
    result = ::PrintDlgW(&prntdlg);
  }

  if (TRUE == result) {
    // check to make sure we don't have any nullptr pointers
    NS_ENSURE_TRUE(aPrintSettings && prntdlg.hDevMode, NS_ERROR_FAILURE);

    if (prntdlg.hDevNames == nullptr) {
      return NS_ERROR_FAILURE;
    }
    // Lock the deviceNames and check for nullptr
    DEVNAMES *devnames = (DEVNAMES *)::GlobalLock(prntdlg.hDevNames);
    if (devnames == nullptr) {
      return NS_ERROR_FAILURE;
    }

    char16_t* device = &(((char16_t *)devnames)[devnames->wDeviceOffset]);
    char16_t* driver = &(((char16_t *)devnames)[devnames->wDriverOffset]);

    // Check to see if the "Print To File" control is checked
    // then take the name from devNames and set it in the PrintSettings
    //
    // NOTE:
    // As per Microsoft SDK documentation the returned value offset from
    // devnames->wOutputOffset is either "FILE:" or nullptr
    // if the "Print To File" checkbox is checked it MUST be "FILE:"
    // We assert as an extra safety check.
    if (prntdlg.Flags & PD_PRINTTOFILE) {
      char16ptr_t fileName = &(((wchar_t *)devnames)[devnames->wOutputOffset]);
      NS_ASSERTION(wcscmp(fileName, L"FILE:") == 0, "FileName must be `FILE:`");
      aPrintSettings->SetToFileName(fileName);
      aPrintSettings->SetPrintToFile(true);
    } else {
      // clear "print to file" info
      aPrintSettings->SetPrintToFile(false);
      aPrintSettings->SetToFileName(nullptr);
    }

    nsCOMPtr<nsIPrintSettingsWin> psWin(do_QueryInterface(aPrintSettings));
    if (!psWin) {
      return NS_ERROR_FAILURE;
    }

    // Setup local Data members
    psWin->SetDeviceName(device);
    psWin->SetDriverName(driver);

#if defined(DEBUG_rods) || defined(DEBUG_dcone)
    wprintf(L"printer: driver %s, device %s  flags: %d\n", driver, device, prntdlg.Flags);
#endif
    // fill the print options with the info from the dialog

    aPrintSettings->SetPrinterName(device);

    if (prntdlg.Flags & PD_SELECTION) {
      aPrintSettings->SetPrintRange(nsIPrintSettings::kRangeSelection);

    } else if (prntdlg.Flags & PD_PAGENUMS) {
      aPrintSettings->SetPrintRange(nsIPrintSettings::kRangeSpecifiedPageRange);
      aPrintSettings->SetStartPageRange(prntdlg.nFromPage);
      aPrintSettings->SetEndPageRange(prntdlg.nToPage);

    } else { // (prntdlg.Flags & PD_ALLPAGES)
      aPrintSettings->SetPrintRange(nsIPrintSettings::kRangeAllPages);
    }

    if (howToEnableFrameUI != nsIPrintSettings::kFrameEnableNone) {
      // make sure the dialog got extended
      if (gDialogWasExtended) {
        // check to see about the frame radio buttons
        switch (gFrameSelectedRadioBtn) {
          case rad4: 
            aPrintSettings->SetPrintFrameType(nsIPrintSettings::kFramesAsIs);
            break;
          case rad5: 
            aPrintSettings->SetPrintFrameType(nsIPrintSettings::kSelectedFrame);
            break;
          case rad6: 
            aPrintSettings->SetPrintFrameType(nsIPrintSettings::kEachFrameSep);
            break;
        } // switch
      } else {
        // if it didn't get extended then have it default to printing
        // each frame separately
        aPrintSettings->SetPrintFrameType(nsIPrintSettings::kEachFrameSep);
      }
    } else {
      aPrintSettings->SetPrintFrameType(nsIPrintSettings::kNoFrames);
    }
    // Unlock DeviceNames
    ::GlobalUnlock(prntdlg.hDevNames);

    // Transfer the settings from the native data to the PrintSettings
    LPDEVMODEW devMode = (LPDEVMODEW)::GlobalLock(prntdlg.hDevMode);
    if (!devMode || !prntdlg.hDC) {
      return NS_ERROR_FAILURE;
    }
    psWin->SetDevMode(devMode); // copies DevMode
    psWin->CopyFromNative(prntdlg.hDC, devMode);
    ::GlobalUnlock(prntdlg.hDevMode);
    ::DeleteDC(prntdlg.hDC);

#if defined(DEBUG_rods) || defined(DEBUG_dcone)
    bool    printSelection = prntdlg.Flags & PD_SELECTION;
    bool    printAllPages  = prntdlg.Flags & PD_ALLPAGES;
    bool    printNumPages  = prntdlg.Flags & PD_PAGENUMS;
    int32_t fromPageNum    = 0;
    int32_t toPageNum      = 0;

    if (printNumPages) {
      fromPageNum = prntdlg.nFromPage;
      toPageNum   = prntdlg.nToPage;
    } 
    if (printSelection) {
      printf("Printing the selection\n");

    } else if (printAllPages) {
      printf("Printing all the pages\n");

    } else {
      printf("Printing from page no. %d to %d\n", fromPageNum, toPageNum);
    }
#endif
    
  } else {
    ::SetFocus(aHWnd);
    aPrintSettings->SetIsCancelled(true);
    return NS_ERROR_ABORT;
  }

  return NS_OK;
}
Example #23
0
File: www.c Project: clflush/tty64
int httpd_www_main(int fd, char *raw, char *cgi) {
	proxy_db_stats *cur_db;
	int frag_level;

	cur_db = proxy_get_stats();

	if (!cur_db) {
		httpd_www_syserr(fd, "calloc", raw);
		return 0;
	}

	httpd_start_hmenu(fd, NULL);
	httpd_end_hmenu(fd);

	raw[strlen(raw)-3] = '\0';

	httpd_www_label(fd, "Proxies Status", 17);

 	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\"15%\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");

	if (cur_db->valids) {
		wprintf(fd, "\t<TR>\n");
		wprintf(fd, "\t\t<TD>Valids Proxies </TD>\n");
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_db->valids);
		wprintf(fd, "\t</TR>\n");
		wprintf(fd, "\t<TR>\n");
	}

	if (cur_db->deads) {
		wprintf(fd, "\t\t<TD>Dead Proxies </TD>\n");
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_db->deads);
		wprintf(fd, "\t</TR>\n");
		wprintf(fd, "\t<TR>\n");
	}

	if (cur_db->broken) {
		wprintf(fd, "\t\t<TD>Broken Proxies </TD>\n");
		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_db->broken);
		wprintf(fd, "\t</TR>\n");
		wprintf(fd, "\t<TR>\n");
	}

	wprintf(fd, "\t\t<TD>Total Proxies </TD>\n");
	wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d</TD>\n", cur_db->valids + cur_db->deads + cur_db->unknowns + cur_db->broken);
	wprintf(fd, "\t</TR>\n");

	if (cur_db->index) {
		wprintf(fd, "\t<TR>\n");
		wprintf(fd, "\t\t<TD>Fragmentation </TD>\n");

		frag_level = 100;

		if (cur_db->holes || cur_db->deads || cur_db->broken) {
			frag_level = ((cur_db->holes + cur_db->deads + cur_db->broken)  * 100 / cur_db->index);
		}

		wprintf(fd, "\t\t<TD ALIGN=\"CENTER\">%d%%</TD>\n", frag_level);
		wprintf(fd, "\t</TR>\n");
	}

	wprintf(fd, "</TABLE>\n");

	httpd_www_label(fd, "Your Browser HTTP Headers", 45);

 	wprintf(fd, "<TABLE BORDER=\"1\" CELLPADDING=\"0\" CELLSPACING=\"0\" WIDTH=\"45%\" ALIGN=\"CENTER\" VALIGN=\"MIDDLE\">\n");
	wprintf(fd, "\t<TR>\n");
	wprintf(fd, "\t\t<TD>\n");
	wprintf(fd, "\t\t\t<PRE>%s</PRE>\n", raw);
	wprintf(fd, "\t\t</TD>\n");
	wprintf(fd, "\t</TR>\n");
	wprintf(fd, "</TABLE>\r\n");

	free(cur_db);

	return 1;
}
Example #24
0
File: main.c Project: jpassing/cfix
static VOID CfixrunsOutputConsole(
	__in PCWSTR Text 
	)
{
	wprintf( L"%s", Text );
}
Example #25
0
static int wxDoVsnprintf(CharType *buf, size_t lenMax,
                         const CharType *format, va_list argptr)
{
    // useful for debugging, to understand if we are really using this function
    // rather than the system implementation
#if 0
    wprintf(L"Using wxCRT_VsnprintfW\n");
#endif

    wxPrintfConvSpecParser<CharType> parser(format);

    wxPrintfArg argdata[wxMAX_SVNPRINTF_ARGUMENTS];

    size_t i;

    // number of characters in the buffer so far, must be less than lenMax
    size_t lenCur = 0;

    if (parser.posarg_present && parser.nonposarg_present)
    {
        buf[0] = 0;
        return -1;      // format strings with both positional and
    }                   // non-positional conversion specifier are unsupported !!

    // on platforms where va_list is an array type, it is necessary to make a
    // copy to be able to pass it to LoadArg as a reference.
    bool ok = true;
    va_list ap;
    wxVaCopy(ap, argptr);

    // now load arguments from stack
    for (i=0; i < parser.nargs && ok; i++)
    {
        // !pspec[i] means that the user forgot a positional parameter (e.g. %$1s %$3s);
        // LoadArg == false means that wxPrintfConvSpec::Parse failed to set the
        // conversion specifier 'type' to a valid value...
        ok = parser.pspec[i] && parser.pspec[i]->LoadArg(&argdata[i], ap);
    }

    va_end(ap);

    // something failed while loading arguments from the variable list...
    // (e.g. the user repeated twice the same positional argument)
    if (!ok)
    {
        buf[0] = 0;
        return -1;
    }

    // finally, process each conversion specifier with its own argument
    const CharType *toparse = format;
    for (i=0; i < parser.nspecs; i++)
    {
        wxPrintfConvSpec<CharType>& spec = parser.specs[i];

        // skip any asterisks, they're processed as part of the conversion they
        // apply to
        if ( spec.m_type == wxPAT_STAR )
            continue;

        // copy in the output buffer the portion of the format string between
        // last specifier and the current one
        size_t tocopy = ( spec.m_pArgPos - toparse );

        lenCur += wxCopyStrWithPercents(lenMax - lenCur, buf + lenCur,
                                        tocopy, toparse);
        if (lenCur == lenMax)
        {
            buf[lenMax - 1] = 0;
            return lenMax+1;      // not enough space in the output buffer !
        }

        // process this specifier directly in the output buffer
        int n = spec.Process(buf+lenCur, lenMax - lenCur,
                                      &argdata[spec.m_pos], lenCur);
        if (n == -1)
        {
            buf[lenMax-1] = wxT('\0');  // be sure to always NUL-terminate the string
            return lenMax+1;      // not enough space in the output buffer !
        }
        lenCur += n;

        // the +1 is because wxPrintfConvSpec::m_pArgEnd points to the last character
        // of the format specifier, but we are not interested to it...
        toparse = spec.m_pArgEnd + 1;
    }

    // copy portion of the format string after last specifier
    // NOTE: toparse is pointing to the character just after the last processed
    //       conversion specifier
    // NOTE2: the +1 is because we want to copy also the '\0'
    size_t tocopy = wxStrlen(format) + 1  - ( toparse - format ) ;

    lenCur += wxCopyStrWithPercents(lenMax - lenCur, buf + lenCur,
                                    tocopy, toparse) - 1;
    if (buf[lenCur])
    {
        buf[lenCur] = 0;
        return lenMax+1;     // not enough space in the output buffer !
    }

    // Don't do:
    //      wxASSERT(lenCur == wxStrlen(buf));
    // in fact if we embedded NULLs in the output buffer (using %c with a '\0')
    // such check would fail

    return lenCur;
}
void Logger::PlatformLog(eLogLevel ll, const char16* text)
{
	wprintf(L"%s", text);
}
Example #27
0
bool cfgOpen()
{
	wchar * tmpPath = GetEmuPath(L"");
	wcscpy(appPath, tmpPath);
	free(tmpPath);

	if (cfgPath[0]==0)
		swprintf(cfgPath,L"%snullDC.cfg", appPath);

	swprintf(dataPath,L"%sdata\\", appPath);
	swprintf(pluginPath,L"%splugins\\", appPath);

	ConfigSection* cs= cfgdb.GetEntry(L"emu");

	cs->SetEntry(L"AppPath",appPath,CEM_VIRTUAL | CEM_READONLY);
	cs->SetEntry(L"PluginPath",pluginPath,CEM_VIRTUAL | CEM_READONLY);
	cs->SetEntry(L"DataPath",dataPath,CEM_VIRTUAL | CEM_READONLY);
	cs->SetEntry(L"FullName",VER_FULLNAME,CEM_VIRTUAL | CEM_READONLY);
	cs->SetEntry(L"ShortName",VER_SHORTNAME,CEM_VIRTUAL | CEM_READONLY);
	cs->SetEntry(L"Name",VER_EMUNAME,CEM_VIRTUAL | CEM_READONLY);

	FILE* cfgfile = _tfopen(cfgPath,L"r");
	if(!cfgfile) {
		cfgfile = _tfopen(cfgPath,L"wt");
		if(!cfgfile) 
			log("Unable to open the config file for reading or writing\nfile : %s\n",cfgPath);
		else
		{
			fprintf(cfgfile,";; nullDC cfg file ;;\n\n");
			fseek(cfgfile,0,SEEK_SET);
			fclose(cfgfile);
			cfgfile = _tfopen(cfgPath,L"r");
			if(!cfgfile) 
				log("Unable to open the config file for reading\nfile : %s\n",cfgPath);
		}
	}

	wchar line[512];
	wchar cur_sect[512]={0};
	int cline=0;
	while(cfgfile && !feof(cfgfile))
	{
		cline++;
		fgetws(line,512,cfgfile);
		if (wcslen(line)<3)
			continue;
		if (line[wcslen(line)-1]=='\r' || line[wcslen(line)-1]=='\n')
			line[wcslen(line)-1]=0;

		wchar* tl=trim_ws(line);
		if (tl[0]=='[' && tl[wcslen(tl)-1]==']')
		{
			tl[wcslen(tl)-1]=0;
			wcscpy(cur_sect,tl+1);
			trim_ws(cur_sect);
		}
		else
		{
			if (cur_sect[0]==0)
				continue;//no open section
			wchar* str1=wcsstr(tl,L"=");
			if (!str1)
			{
				wprintf(L"Malformed entry on cfg,  ignoring @ %d(%s)\n",cline,tl);
				continue;
			}
			*str1=0;
			str1++;
			wchar* v=trim_ws(str1);
			wchar* k=trim_ws(tl);
			if (v && k)
			{
				ConfigSection*cs=cfgdb.GetEntry(cur_sect);
				
				//if (!cs->FindEntry(k))
				cs->SetEntry(k,v,CEM_SAVE|CEM_LOAD);
			}
			else
			{
				wprintf(L"Malformed entry on cfg,  ignoring @ %d(%s)\n",cline,tl);
			}
		}
	}

	for (size_t i=0;i<vlist.size();i++)
	{
		cfgdb.GetEntry(vlist[i].s)->SetEntry(vlist[i].n,vlist[i].v,CEM_VIRTUAL);
	}
	if (cfgfile)
	{
		cfgdb.SaveFile(cfgfile);
		fclose(cfgfile);
	}
	return true;
}
///////////////////////////////////////////////////////////////////////////////
// ProcessCommandLine
//
// In non-dialog based app, this function would be in CWinApp module, and
// would be called from InitInstance() like this:
//          ProcessCommandLine(__argc, __argv);
//
BOOL CEDKIIBuildDataViewerApp::ProcessCommandLine(int argc, TCHAR *argv[])
{
#if OUTPUT_USAGE_TO_CONSOLE > 0
	FILE	*fh_stdout = NULL;
	BOOL	bDialog = (AfxGetMainWnd() != NULL);
	if (!bDialog) {
		AttachConsole(ATTACH_PARENT_PROCESS);
		int		hCrt = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
		if (hCrt != -1) {
			fh_stdout = _fdopen(hCrt, "w");
			FILE	*stdoutOld = stdout;
			*stdout = *fh_stdout;
			int		i = setvbuf(stdout, NULL, _IONBF, 0);
		}
	}
#endif

	CString		errorStr;

	// In the following loop you would set/unset any global command 
	// line flags and option arguments (usually in the CWinApp object) 
	// as each option was found in the command line.  
	//
	// In general it is probably best to let ProcessCommandLine's caller
	// sort out the command line arguments that were used, and whether 
	// they are consistent.  In ProcessCommandLine, you want to save the
	// options and the arguments, doing any conversion (atoi, etc.) that
	// is necessary.
	//
	// Normally you would have a case statement for each option letter.

	int c;
	while ((c = getopt(argc, argv, _T("l:s:dih"))) != EOF)
	{
		switch (c)
		{
			case _T('l'):
				{
					FILE	*fp;
					_tfopen_s(&fp, optarg, _T("rt"));
					if (fp == NULL) {
#if OUTPUT_USAGE_TO_CONSOLE == 0
						CString msg;
						msg.Format(_T("ERROR: build log %s couldn't be opened for read\n"), optarg);
						AfxMessageBox(msg, MB_ICONERROR);
#else
						wprintf(_T("\n\nERROR: build log %s couldn't be opened for read\n"), optarg);
#endif
						return FALSE;
					}

					fclose(fp);
					m_commandLineData.buildLog = optarg;
				}
				break;

			case _T('s'):
				{
					FILE	*fp;
					_tfopen_s(&fp, optarg, _T("wt"));
					if (fp == NULL) {
#if OUTPUT_USAGE_TO_CONSOLE == 0
						CString msg;
						msg.Format(_T("ERROR: source list file %s couldn't be opened for write\n"), optarg);
						AfxMessageBox(msg, MB_ICONERROR);
#else
						wprintf(_T("\n\nERROR: source list file %s couldn't be opened for write\n"), optarg);
#endif
						return FALSE;
					}

					fclose(fp);
					m_commandLineData.sourceFileList = optarg;
				}
				break;

			case _T('d'):
				m_commandLineData.bSourceUseDoxygenFormat = TRUE;
				break;

			case _T('i'):
				m_commandLineData.bSourceIncludeInf = TRUE;
				break;

			case _T('?'):
#if OUTPUT_USAGE_TO_CONSOLE == 0
				errorStr.Format(_T("ERROR: illegal option %s\n\n"), argv[optind-1]);
#else
				errorStr.Format(_T("\n\nERROR: illegal option %s\n\n"), argv[optind-1]);
#endif

			case _T('h'):
#if OUTPUT_USAGE_TO_CONSOLE == 0
				// output help to dialog
				{
					CString str;
					str.Format(_T("%s"), m_pszExeName);
					CString msg;
					if (!errorStr.IsEmpty())
						msg = errorStr;
					msg += _T("Usage: ") + str + _T(" -l buildLog [-s] sourceFileList [-d] [-i]\n");
					msg += _T("-l buildLog\tfilename for BIOS build log to open\n");
					msg += _T("-s sourceFileList\tfilename for source list file to create\n");
					msg += _T("-d\t\tsource list file, use doxygen format\n");
					msg += _T("-i\t\tsource list file, include INF files\n");
					msg += _T("\nApp errorlevel is 0 for ERROR, or 1 for SUCCESS\n");
					if (!errorStr.IsEmpty())
						AfxMessageBox(msg, MB_ICONERROR);
					else
						AfxMessageBox(msg, MB_ICONINFORMATION);
				}
#else
				// output help to console
				{
					if (!errorStr.IsEmpty())
						wprintf(_T("%s"), errorStr.GetBuffer());
					wprintf(_T("Usage: %s -l buildLog [-s] sourceFileList [-d] [-i]\n"), m_pszExeName);
					wprintf(_T("-l buildLog        filename for BIOS build log to open\n"));
					wprintf(_T("-s sourceFileList  filename for source list file to create\n"));
					wprintf(_T("-d                 source list file, use doxygen format\n"));
					wprintf(_T("-i                 source list file, include INF files\n"));
					wprintf(_T("\nApp errorlevel is 0 for ERROR, or 1 for SUCCESS\n"));
				}
#endif
				return FALSE;
				break;
				
			default:
				break;
		}
	}

	// ensure all necessary command line parameters have been specified
	if (argc > 1 && (m_commandLineData.buildLog.IsEmpty() || m_commandLineData.sourceFileList.IsEmpty())) {
#if OUTPUT_USAGE_TO_CONSOLE == 0
		AfxMessageBox(_T("ERROR: must specify build log and source list filenames"), MB_ICONERROR);
#else
		wprintf(_T("\n\nERROR: must specify build log and source list filenames\n"));
#endif
		m_commandLineData.bCommandLineActive = FALSE;
		return FALSE;
	}
	// if command line parameters have been specified, then set flag to TRUE
	if (argc > 1)
		m_commandLineData.bCommandLineActive = TRUE;

#if OUTPUT_USAGE_TO_CONSOLE > 0
	if (fh_stdout != NULL) {
		fclose(fh_stdout);
		FreeConsole();
	}
#endif

	// all options processed, return success
	return TRUE;
}
Example #29
0
/////////////////////////
// 表示
void CLog::Log(std::wstring str)
{
	str += L"\n";
	::OutputDebugStringW(str.c_str());
	wprintf(str.c_str());
}
Example #30
0
// Install and start driver service and mark it for removal (non-install mode)
static int DriverLoad ()
{
	HANDLE file = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA find = {0};
	SC_HANDLE hManager = NULL, hService = NULL;
	WCHAR driverPath[MAX_PATH*2] = {0};
	BOOL res = FALSE;
	WCHAR *tmp;

	GetModuleFileName (NULL, driverPath, sizeof (driverPath));
	tmp = wcsrchr (driverPath, '\\');
	if (!tmp)
	{
		wcscpy_s(driverPath, MAX_PATH * 2, L".");
		tmp = driverPath + 1;
	}

	wcscpy_s (tmp, MAX_PATH, !Is64BitOs () ? L"\\Bluefish.sys" : L"\\Bluefish-x64.sys");

	file = FindFirstFile (driverPath, &find);

	if (file == INVALID_HANDLE_VALUE)
	{
		wprintf (L"DRIVER_NOT_FOUND, was the driver stored in %s?\n", driverPath );
		return ERR_DONT_REPORT;
	}

	FindClose (file);

	hManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if (hManager == NULL)
	{
		if (GetLastError () == ERROR_ACCESS_DENIED)
		{
			
			wprintf (L"ADMIN_PRIVILEGES_DRIVER No admin privileges of this driver.\n", 0);
			return ERR_DONT_REPORT;
		}

		return ERR_OS_ERROR;
	}

	hService = OpenService (hManager, L"Bluefisher", SERVICE_ALL_ACCESS);
	if (hService != NULL)
	{
		// Remove stale service (driver is not loaded but service exists)
		wprintf(L"Driver is not loaded but the service exits.\n");
		DeleteService (hService);
		CloseServiceHandle (hService);
		Sleep (500);
	}
	//Clear the Error
	SetLastError(0);

	wprintf( L"Installing Bluefisher driver...\n");
	wprintf( L"Driver Path: %s\n", driverPath );

	hService = CreateService (hManager, L"Bluefisher", L"Bluefisher",
		SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
		driverPath, NULL, NULL, NULL, NULL, NULL);

	if (hService == NULL)
	{
		wprintf(L"Bluefisher was not created. Error: %d.\n", GetLastError() );
		SetLastError(0);
		CloseServiceHandle (hManager);
		return ERR_OS_ERROR;
	}

	CloseServiceHandle (hService);

	hService = OpenService (hManager, L"Bluefisher", SERVICE_ALL_ACCESS);

	if (hService == NULL)
	{
		wprintf(L"Bluefisher was not opened. Error: %d.\n", GetLastError() );
		SetLastError(0);
		CloseServiceHandle (hManager);
		return ERR_OS_ERROR;
	}

	if( !StartService (hService, 0, NULL) )
	{
		wprintf(L"Bluefisher was not started. Error: %d.\n", GetLastError() );
		SetLastError(0);
		CloseServiceHandle (hManager);
	}

	//DeleteService (hService);

	CloseServiceHandle (hManager);
	CloseServiceHandle (hService);

	if( GetLastError() != 0 )
	{
		wprintf(L"Error: %d.\n", GetLastError() );
	}else
	{
		wprintf(L"Bluefisher driver installed successfully.\n" );
	}

	return !res ? ERR_OS_ERROR : ERROR_SUCCESS;
}