BOOL UsbDevice::ClaimInterface(DWORD dwInterfaceValue, LPVOID Context) { WriteLocker lock(mCloseMutex); if (Closed()) { // Don't allow closed devices to be claimed SetLastError(ERROR_INVALID_HANDLE); return FALSE; } for (DWORD i = 0; i < mInterfaceClaimersCount; ++i) { if (mInterfaceClaimers[i].InterfaceValue() == dwInterfaceValue) { BOOL IsFirst = FALSE; if (!mInterfaceClaimers[i].Claim(Context, IsFirst)) { return FALSE; } // If this was the first claim then need to open pipes if (IsFirst) { if (!OpenPipes(mInterfaceClaimers[i])) { ClosePipes(mInterfaceClaimers[i]); SetLastError(ERROR_INTERNAL_ERROR); return FALSE; } } return TRUE; } } SetLastError(ERROR_INVALID_PARAMETER); return FALSE; }
void Done(int restart, char *command) { MenuRoot *mr; #ifndef NON_VIRTUAL MoveViewport(0, 0, False); #endif mr = FindPopup("ExitFunction"); if (mr != NULL) ExecuteFunction("Function ExitFunction", NULL, &Event, C_ROOT, -1); /* Close all my pipes */ ClosePipes(); Reborder(); if (restart) { SaveDesktopState(); /* I wonder why ... */ /* Really make sure that the connection is closed and cleared! */ XSelectInput(dpy, Scr.Root, 0); XSync(dpy, 0); XCloseDisplay(dpy); { char *my_argv[10]; int i, done, j; i = 0; j = 0; done = 0; while ((g_argv[j] != NULL) && (i < 8)) { if (strcmp(g_argv[j], "-s") != 0) { my_argv[i] = g_argv[j]; i++; j++; } else j++; } if (strstr(command, "fvwm") != NULL) my_argv[i++] = "-s"; while (i < 10) my_argv[i++] = NULL; /* really need to destroy all windows, explicitly, * not sleep, but this is adequate for now */ sleep(1); ReapChildren(); execvp(command, my_argv); } fvwm_msg(ERR, "Done", "Call of '%s' failed!!!!", command); execvp(g_argv[0], g_argv); /* that _should_ work */ fvwm_msg(ERR, "Done", "Call of '%s' failed!!!!", g_argv[0]); } else { XCloseDisplay(dpy); exit(0); } }
int main(int argc, char* argv[]) { PrintHello(); if (ProcessCmdLine(argc, argv) != 0) return -1; OpenUsbDevice(); if (dwRC == USBIO_ERR_SUCCESS) { GetDeviceDescriptor(); } if (dwRC == USBIO_ERR_SUCCESS) { GetConfigurationDescriptor(); } if (dwRC == USBIO_ERR_SUCCESS) { GetStringDescriptor(); } if (dwRC == USBIO_ERR_SUCCESS) { SetConfiguration(); } if (dwRC == USBIO_ERR_SUCCESS) { // In order to give the USB device-side program (t_usb) // enough time after getting configured to carry out // some device tests, we wait here for a short while // before proceeding: Delay(2000); GetConfigurationInfo(); } if (dwRC == USBIO_ERR_SUCCESS) { OpenPipes(); } if (dwRC == USBIO_ERR_SUCCESS) { ExchangeVersions(); } if (dwRC == USBIO_ERR_SUCCESS) { DoTransfers(); } if (dwRC == USBIO_ERR_SUCCESS) { ClosePipes(); } CloseUsbDevice(); return 0; }
XIOErrorHandler CatchFatal(Display *dpy) { /* No action is taken because usually this action is caused by someone using "xlogout" to be able to switch between multiple window managers */ #if 0 Done(0, NULL); #else ClosePipes(); exit(0); #endif }
DWORD CSTDevice::Close() { if (!m_bDeviceIsOpen) return STDEVICE_NOERROR; // 1- Close the pipes, if needed ClosePipes(); // 2- Release the descriptors ReleaseDescriptors(); // 3- Close the device CloseDevice(); m_bDeviceIsOpen=FALSE; return STDEVICE_NOERROR; }
void UsbDevice::Close() { WriteLocker lock(mCloseMutex); if (mRegistered && mUsbFuncs && mDevice) { DEVLIFETIME_MSG(( TEXT("USBKWrapperDrv!UsbDevice::Close() mDevice: 0x%08x mBus: %d mAddress: %d\r\n"), mDevice, mBus, mAddress)); // Provide notification to userland that this USB device has disappeared AdvertiseDevice(FALSE); mUsbFuncs->lpUnRegisterNotificationRoutine( mDevice, UsbDeviceNotifyRoutine, this); // Close any pipes in claimed interfaces for (DWORD i = 0; i < mInterfaceClaimersCount; ++i) { ClosePipes(mInterfaceClaimers[i]); } mRegistered = FALSE; mUsbFuncs = NULL; mDevice = NULL; } }
void CTCPStunThread::Reset() { _spPolling.ReleaseAndClear(); CloseListenSockets(); ClosePipes(); _fListenSocketsOnEpoll = false; memset(&_tsaListen, '\0', sizeof(_tsaListen)); _fNeedToExit = false; _spAuth.ReleaseAndClear(); _role = RolePP; memset(&_tsa, '\0', sizeof(_tsa)); _maxConnections = c_MaxNumberOfConnectionsDefault; _pthread = (pthread_t)-1; _fThreadIsValid = false; _connectionpool.Reset(); // the thread should have closed all the connections ASSERT(_hashConnections1.Size() == 0); ASSERT(_hashConnections2.Size() == 0); _hashConnections1.ResetTable(); _hashConnections2.ResetTable(); _pNewConnList = &_hashConnections1; _pOldConnList = &_hashConnections2; _timeLastSweep = time(NULL); }
BOOL DLL_EXPORT FormatDrive(BYTE DriveLetter, LPSTR szLabel, DWORD dwFileSystem, HWND hWnd) { HANDLE hChildStdinRd, hChildStdinWr,hChildStdinWrDup, hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, hChildStderrRd, hChildStderrWr, hChildStderrRdDup; TCHAR szCommand[MAX_PATH]; DWORD dwExitCode, dwWrited;; TCHAR szEnter[] = "\x0d\x0a"; TCHAR szDrive[] = "X:"; TCHAR szYes[] = "y\x0d\x0a"; TCHAR szFileSystem[16]; TCHAR sz[MAX_PATH]; PROCESS_INFORMATION pi; STARTUPINFO si; if(!( ( DriveLetter >= 'A' && DriveLetter <= 'Z') || ( DriveLetter >= 'a' && DriveLetter <= 'z') )) { return FALSE; }else { szDrive[0] = DriveLetter; } switch(dwFileSystem) { // case FORMAT_FAT_12: // strcpy(szFileSystem,"FAT"); // break; case FORMAT_FAT_16: strcpy(szFileSystem,"FAT"); break; case FORMAT_FAT_32: strcpy(szFileSystem,"FAT32"); break; case FORMAT_NTFS: strcpy(szFileSystem,"NTFS"); break; default: //un known format return FALSE; } ZeroMemory(szCommand, MAX_PATH* sizeof(TCHAR)); //construct format command // sprintf(szCommand,"format.com %s /q /x /v:\"%s\" /fs:%s",szDrive,szLabel,szFileSystem); sprintf(szCommand,"format.com %s /q /x /fs:%s",szDrive,szFileSystem); if(!CreatePipes(hChildStdinRd,hChildStdinWr,hChildStdinWrDup, hChildStdoutRd,hChildStdoutWr,hChildStdoutRdDup, hChildStderrRd,hChildStderrWr,hChildStderrRdDup)) return FALSE; //create format process ZeroMemory(&pi,sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.hStdInput = hChildStdinRd; si.hStdOutput = hChildStdoutWr; si.hStdError = hChildStderrWr; si.dwFlags = STARTF_USESTDHANDLES; CreateProcess(NULL,szCommand,NULL,NULL,TRUE, // 0,NULL,NULL,&si,&pi); CREATE_NO_WINDOW,NULL,NULL,&si,&pi); //write format input ZeroMemory(sz,MAX_PATH); GetVolumeInformation(szDrive,sz,MAX_PATH, NULL, NULL, NULL, NULL, NULL); if(strlen(sz)>0) { strcat(sz,szEnter); WriteFile(hChildStdinWrDup,sz,strlen(sz),&dwWrited,NULL); } WriteFile(hChildStdinWrDup,szYes,strlen(szYes),&dwWrited,NULL); //set label WriteFile(hChildStdinWrDup,szLabel,strlen(szLabel),&dwWrited,NULL); WriteFile(hChildStdinWrDup,szEnter,strlen(szEnter),&dwWrited,NULL); #ifdef _DEBUG ReadFile(hChildStdoutRdDup,sz,MAX_PATH,&dwWrited,NULL); #endif //write additional Enter to avoid invalid volume label WriteFile(hChildStdinWrDup,szEnter,strlen(szEnter),&dwWrited,NULL); WriteFile(hChildStdinWrDup,szEnter,strlen(szEnter),&dwWrited,NULL); //wait for format dwExitCode = QueryFormatProcess(hChildStdoutRdDup, pi.hProcess,hWnd); //close all pipes handle ClosePipes( hChildStdinRd,hChildStdinWr, hChildStdoutRd,hChildStdoutWr, hChildStderrRd,hChildStderrWr); //close duplicate handles CloseHandle(hChildStdinWrDup); CloseHandle(hChildStdoutRdDup); CloseHandle(hChildStderrRdDup); if(dwExitCode == 0) return TRUE; else return FALSE; }
/** Executes a command in a child process. */ static pid_t ExecuteProcess(JNIEnv* env, char** commands, char** environment, const char* workingDirectory, jobject inDescriptor, jobject outDescriptor, jobject errDescriptor, jboolean redirectErrorStream) { // Create 4 pipes: stdin, stdout, stderr, and an exec() status pipe. int pipes[PIPE_COUNT * 2] = { -1, -1, -1, -1, -1, -1, -1, -1 }; for (int i = 0; i < PIPE_COUNT; i++) { if (pipe(pipes + i * 2) == -1) { jniThrowIOException(env, errno); ClosePipes(pipes, -1); return -1; } } int stdinIn = pipes[0]; int stdinOut = pipes[1]; int stdoutIn = pipes[2]; int stdoutOut = pipes[3]; int stderrIn = pipes[4]; int stderrOut = pipes[5]; int statusIn = pipes[6]; int statusOut = pipes[7]; pid_t childPid = fork(); // If fork() failed... if (childPid == -1) { jniThrowIOException(env, errno); ClosePipes(pipes, -1); return -1; } // If this is the child process... if (childPid == 0) { // Note: We cannot malloc(3) or free(3) after this point! // A thread in the parent that no longer exists in the child may have held the heap lock // when we forked, so an attempt to malloc(3) or free(3) would result in deadlock. // Replace stdin, out, and err with pipes. dup2(stdinIn, 0); dup2(stdoutOut, 1); if (redirectErrorStream) { dup2(stdoutOut, 2); } else { dup2(stderrOut, 2); } // Close all but statusOut. This saves some work in the next step. ClosePipes(pipes, statusOut); // Make statusOut automatically close if execvp() succeeds. fcntl(statusOut, F_SETFD, FD_CLOEXEC); // Close remaining unwanted open fds. CloseNonStandardFds(statusOut); // Switch to working directory. if (workingDirectory != NULL) { if (chdir(workingDirectory) == -1) { AbortChild(statusOut); } } // Set up environment. if (environment != NULL) { extern char** environ; // Standard, but not in any header file. environ = environment; } // Execute process. By convention, the first argument in the arg array // should be the command itself. execvp(commands[0], commands); AbortChild(statusOut); } // This is the parent process. // Close child's pipe ends. close(stdinIn); close(stdoutOut); close(stderrOut); close(statusOut); // Check status pipe for an error code. If execvp(2) succeeds, the other // end of the pipe should automatically close, in which case, we'll read // nothing. int child_errno; ssize_t count = TEMP_FAILURE_RETRY(read(statusIn, &child_errno, sizeof(int))); close(statusIn); if (count > 0) { // chdir(2) or execvp(2) in the child failed. // TODO: track which so we can be more specific in the detail message. jniThrowIOException(env, child_errno); close(stdoutIn); close(stdinOut); close(stderrIn); // Reap our zombie child right away. int status; int rc = TEMP_FAILURE_RETRY(waitpid(childPid, &status, 0)); if (rc == -1) { ALOGW("waitpid on failed exec failed: %s", strerror(errno)); } return -1; } // Fill in file descriptor wrappers. jniSetFileDescriptorOfFD(env, inDescriptor, stdoutIn); jniSetFileDescriptorOfFD(env, outDescriptor, stdinOut); jniSetFileDescriptorOfFD(env, errDescriptor, stderrIn); return childPid; }
DWORD CSTDevice::SelectCurrentConfiguration(UINT ConfigIdx, UINT InterfaceIdx, UINT AltSetIdx) { DWORD nRet; BYTE TheConfig[3]; DWORD ByteCount; USB_INTERFACE_DESCRIPTOR Desc; PUSB_CONFIGURATION_DESCRIPTOR pConfDesc; // Put the InterfaceIdx to -1 if it should not be a search criterion. // Put the AltSetIdx to -1 if it should not be a search criterion. if (!m_bDeviceIsOpen) return STDEVICE_DRIVERISCLOSED; if (m_pPipeHandles) return STDEVICE_PIPESAREOPEN; pConfDesc=(PUSB_CONFIGURATION_DESCRIPTOR)(m_pConfigs[ConfigIdx]); nRet=GetInterfaceDescriptor(ConfigIdx, InterfaceIdx, AltSetIdx, &Desc); if (nRet!=STDEVICE_NOERROR) return nRet; m_bDeviceIsOpen=FALSE; // 1- Release the descriptors ReleaseDescriptors(); // 2- Set the config m_CurrentConfig=ConfigIdx; m_CurrentInterf=InterfaceIdx; m_CurrentAltSet=AltSetIdx; // 3- Get the descriptors nRet=AllocDescriptors(); // 4- Change the current config in the driver if (nRet==STDEVICE_NOERROR) { TheConfig[0]=pConfDesc->bConfigurationValue-1; TheConfig[1]=Desc.bInterfaceNumber; TheConfig[2]=Desc.bAlternateSetting; if (DeviceIoControl(m_DeviceHandle, PU_CONFIG, TheConfig, 3, NULL, 0, &ByteCount, NULL)) nRet=STDEVICE_NOERROR; else nRet=STDEVICE_BADPARAMETER; } if (nRet==STDEVICE_NOERROR) m_bDeviceIsOpen=TRUE; else { ClosePipes(); // 2- Release the descriptors ReleaseDescriptors(); // 3- Close the device CloseDevice(); m_bDeviceIsOpen=FALSE; } return nRet; }
DWORD CSTDevice::OpenPipes() { CString PipeSymbName; int i; DWORD nRet; BOOL bTmp; UINT _uiNbOfInterfaces = 0; UINT _uiNbOfEndpointsTmp = 0; UINT _j = 0, _k = 0; ClosePipes(); // Fake open bTmp=m_bDeviceIsOpen; m_bDeviceIsOpen=TRUE; /*### ===> DE-1184 du 08/03/2009 ML */ // We must open all the endpoints available on all the configured interfaces nRet = GetNbOfInterfaces(m_CurrentConfig, &_uiNbOfInterfaces); if (nRet!=STDEVICE_NOERROR) { m_bDeviceIsOpen=bTmp; return nRet; } for(_j=0; _j<_uiNbOfInterfaces; _j++) { nRet=GetNbOfEndPoints(m_CurrentConfig, _j, m_CurrentAltSet, &_uiNbOfEndpointsTmp); if (nRet!=STDEVICE_NOERROR) { m_bDeviceIsOpen=bTmp; return nRet; } m_nbEndPoints += _uiNbOfEndpointsTmp; } m_pPipeHandles=new HANDLE[m_nbEndPoints]; for(_j=0; _j<_uiNbOfInterfaces; _j++) { nRet=GetNbOfEndPoints(m_CurrentConfig, _j, m_CurrentAltSet, &_uiNbOfEndpointsTmp); if (nRet!=STDEVICE_NOERROR) { m_bDeviceIsOpen=bTmp; return nRet; } for (i=0;i<(int)_uiNbOfEndpointsTmp;i++) { // Get endpoint description to see if it's an input or output pipe, and get its address USB_ENDPOINT_DESCRIPTOR Desc; nRet=GetEndPointDescriptor(m_CurrentConfig, m_CurrentInterf, m_CurrentAltSet, _k, &Desc); if (nRet==STDEVICE_NOERROR) { PipeSymbName.Format("%s\\%02x", m_SymbolicName, Desc.bEndpointAddress); m_pPipeHandles[_k]= CreateFile( PipeSymbName, (USB_ENDPOINT_DIRECTION_IN(Desc.bEndpointAddress))?GENERIC_READ:GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if ( (!m_pPipeHandles[_k]) || (m_pPipeHandles[_k]==INVALID_HANDLE_VALUE) ) { while (_k>0) { _k--; CloseHandle(m_pPipeHandles[_k]); m_pPipeHandles[_k]=INVALID_HANDLE_VALUE; } delete[] m_pPipeHandles; m_pPipeHandles=NULL; nRet=STDEVICE_PIPECREATIONERROR; break; } else { // reset the pipe BYTE InBuffer[2]; DWORD ByteCount; InBuffer[0]=Desc.bEndpointAddress; InBuffer[1]=1; // Reset pipe if (!DeviceIoControl(m_DeviceHandle, PU_PIPE_CONTROL, InBuffer, 2, NULL, 0, &ByteCount, NULL)) { while (_k>0) { _k--; CloseHandle(m_pPipeHandles[_k]); m_pPipeHandles[_k]=INVALID_HANDLE_VALUE; } delete[] m_pPipeHandles; m_pPipeHandles=NULL; nRet=STDEVICE_PIPERESETERROR; break; } else { // Abort any transfer BYTE InBuffer[2]; DWORD ByteCount; InBuffer[0]=Desc.bEndpointAddress; InBuffer[1]=0; // Abort if (!DeviceIoControl(m_DeviceHandle, PU_PIPE_CONTROL, InBuffer, 2, NULL, 0, &ByteCount, NULL)) { while (_k>0) { _k--; CloseHandle(m_pPipeHandles[_k]); m_pPipeHandles[_k]=INVALID_HANDLE_VALUE; } delete[] m_pPipeHandles; m_pPipeHandles=NULL; nRet=STDEVICE_PIPEABORTERROR; break; } } } } else { while (_k>0) { _k--; CloseHandle(m_pPipeHandles[_k]); m_pPipeHandles[_k]=INVALID_HANDLE_VALUE; } delete[] m_pPipeHandles; m_pPipeHandles=NULL; nRet=STDEVICE_PIPECREATIONERROR; break; } _k++; } } /*### <=== DE-1184 */ m_bDeviceIsOpen=bTmp; return nRet; }