Пример #1
0
static void doChildren(int argc, char **argv)
{
    const char *arguments = "debugger children last";
    struct child_blackbox blackbox;
    const char *blackbox_file, *p;
    char event_name[MAX_PATH];
    PROCESS_INFORMATION pi;
    STARTUPINFOA si;
    HANDLE event;
    char *cmd;
    BOOL ret;

    if (!strcmp(argv[3], "last")) return;

    blackbox_file = argv[3];

    p = strrchr(blackbox_file, '\\');
    p = p ? p+1 : blackbox_file;
    strcpy(event_name, p);
    strcat(event_name, "_init");
    event = OpenEventA(EVENT_ALL_ACCESS, FALSE, event_name);
    child_ok(event != NULL, "OpenEvent failed, last error %d.\n", GetLastError());
    SetEvent(event);
    CloseHandle(event);

    p = strrchr(blackbox_file, '\\');
    p = p ? p+1 : blackbox_file;
    strcpy(event_name, p);
    strcat(event_name, "_attach");
    event = OpenEventA(EVENT_ALL_ACCESS, FALSE, event_name);
    child_ok(event != NULL, "OpenEvent failed, last error %d.\n", GetLastError());
    WaitForSingleObject(event, INFINITE);
    CloseHandle(event);

    cmd = HeapAlloc(GetProcessHeap(), 0, strlen(argv[0]) + strlen(arguments) + 2);
    sprintf(cmd, "%s %s", argv[0], arguments);

    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);
    ret = CreateProcessA(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
    child_ok(ret, "CreateProcess failed, last error %d.\n", GetLastError());

    child_ok(WaitForSingleObject(pi.hProcess, 10000) == WAIT_OBJECT_0,
            "Timed out waiting for the child to exit\n");

    ret = CloseHandle(pi.hThread);
    child_ok(ret, "CloseHandle failed, last error %d.\n", GetLastError());
    ret = CloseHandle(pi.hProcess);
    child_ok(ret, "CloseHandle failed, last error %d.\n", GetLastError());

    blackbox.failures = child_failures;
    save_blackbox(blackbox_file, &blackbox, sizeof(blackbox));

    HeapFree(GetProcessHeap(), 0, cmd);
}
Пример #2
0
BOOL __stdcall ProcessRequest(HWND hwnd, LPARAM param)
{
	char szBuf[MAX_PATH];

	TEnumData *lParam = (TEnumData*)param;
	DWORD pid = 0;
	GetWindowThreadProcessId(hwnd, &pid);
	if (pid != 0) {
		// old system would get a window's pid and the module handle that created it
		// and try to OpenEvent() a event object name to it (prefixed with a string)
		// this was fine for most Oses (not the best way) but now actually compares
		// the class string (a bit slower) but should get rid of those bugs finally.
		HANDLE hMirandaWorkEvent = OpenEventA(EVENT_ALL_ACCESS, false, CreateProcessUID(pid, szBuf, sizeof(szBuf)));
		if (hMirandaWorkEvent != 0) {
			GetClassNameA(hwnd, szBuf, sizeof(szBuf));
			if ( lstrcmpA(szBuf, MIRANDACLASS) != 0) {
				// opened but not valid.
				logA("ProcessRequest(%d, %p): class %s differs from %s\n", pid, hwnd, szBuf, MIRANDACLASS);
				CloseHandle(hMirandaWorkEvent);
				return true;
			}
		}
		// if the event object exists,  a shlext.dll running in the instance must of created it.
		if (hMirandaWorkEvent != 0) {
			logA("ProcessRequest(%d, %p): window found\n", pid, hwnd);
			// prep the request
			ipcPrepareRequests(IPC_PACKET_SIZE, lParam->ipch, REQUEST_ICONS | REQUEST_GROUPS | REQUEST_CONTACTS | REQUEST_NEWICONS);

			// slots will be in the order of icon data, groups  contacts, the first
			// slot will contain the profile name
			DWORD replyBits = ipcSendRequest(hMirandaWorkEvent, lParam->hWaitFor, lParam->ipch, 1000);

			// replyBits will be REPLY_FAIL if the wait timed out, or it'll be the request
			// bits as sent or a series of *_NOTIMPL bits where the request bit were, if there are no
			// contacts to speak of,  don't bother showing this instance of Miranda }
			if (replyBits != REPLY_FAIL && lParam->ipch->ContactsBegin != NULL) {
				logA("ProcessRequest(%d, %p): IPC succeeded\n", pid, hwnd);
				// load the address again, the server side will always overwrite it
				lParam->ipch->pClientBaseAddress = lParam->ipch;
				// fixup all the pointers to be relative to the memory map
				// the base pointer of the client side version of the mapped file
				ipcFixupAddresses(lParam->ipch);
				// store the PID used to create the work event object
				// that got replied to -- this is needed since each contact
				// on the final menu maybe on a different instance and another OpenEvent() will be needed.
				lParam->pid = pid;
				// check out the user options from the server
				lParam->bShouldOwnerDraw = (lParam->ipch->dwFlags & HIPC_NOICONS) == 0;
				// process the icons
				BuildSkinIcons(lParam);
				// process other replies
				BuildMenus(lParam);
			}
			// close the work object
			CloseHandle(hMirandaWorkEvent);
		}
	}
	return true;
}
HOOKFUNC HANDLE WINAPI MyOpenEventA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName)
{
	HANDLE rv = OpenEventA(dwDesiredAccess, bInheritHandle, lpName);
	debuglog(LCF_SYNCOBJ, __FUNCTION__ " returned 0x%X.\n", rv);
	EnterCriticalSection(&s_handleCS);
	std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
	handles.insert(rv);
	LeaveCriticalSection(&s_handleCS);
	return rv;
}
Пример #4
0
static int event_exists(int sig)
{
	char name[EVT_NAME_LEN];
	HANDLE h;
	make_name(name, sig);
	if (!(h = OpenEventA(EVENT_MODIFY_STATE, FALSE, name)))
		return 0;
	CloseHandle(h);
	return 1;
}
Пример #5
0
static inline bool capture_alive(void)
{
	HANDLE event = OpenEventA(EVENT_ALL_ACCESS, false, keepalive_name);
	if (event) {
		CloseHandle(event);
		return true;
	}

	return false;
}
Пример #6
0
 HOOKFUNC HANDLE WINAPI MyOpenEventA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName)
 {
     ENTER();
     HANDLE rv = OpenEventA(dwDesiredAccess, bInheritHandle, lpName);
     LEAVE(rv);
     EnterCriticalSection(&s_handleCS);
     std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
     handles.insert(rv);
     LeaveCriticalSection(&s_handleCS);
     return rv;
 }
Пример #7
0
static void dummy_process(char *event_name)
{
    HANDLE event = OpenEventA(EVENT_ALL_ACCESS, FALSE, event_name);

    while (TRUE)
    {
        SetEvent(event);
        OutputDebugStringA("test");
        Sleep(5);
    }
}
Пример #8
0
static int sig_event(int sig)
{
	char name[EVT_NAME_LEN];
	HANDLE h;
	make_name(name, sig);
	if (!(h = OpenEventA(EVENT_MODIFY_STATE, FALSE, name))) {
		make_name(name, EVT_RUNNING);
		if (!(h = OpenEvent(EVENT_MODIFY_STATE, FALSE, name)))
			return -1;
		CloseHandle(h);
		return 0;
	}
	SetEvent(h);
	CloseHandle(h);
	return 1;
}
Пример #9
0
      inline void kill_wrapper( ProcessId pid, int sig, int port, const BSONObj& opt ) {
#ifdef _WIN32
            if (sig == SIGKILL || port == 0) {
                verify( registry._handles.count(pid) );
                TerminateProcess(registry._handles[pid], 1); // returns failure for "zombie" processes.
                return;
            }

            std::string eventName = getShutdownSignalName(pid.asUInt32());

            HANDLE event = OpenEventA(EVENT_MODIFY_STATE, FALSE, eventName.c_str());
            if (event == NULL) {
                int gle = GetLastError();
                if (gle != ERROR_FILE_NOT_FOUND) {
                    warning() << "kill_wrapper OpenEvent failed: " << errnoWithDescription();
                }
                else {
                    log() << "kill_wrapper OpenEvent failed to open event to the process "
                        << pid.asUInt32() << ". It has likely died already";
                }
                return;
            }

            ON_BLOCK_EXIT(CloseHandle, event);

            bool result = SetEvent(event);
            if (!result) {
                error() << "kill_wrapper SetEvent failed: " << errnoWithDescription();
                return;
            }
#else
            int x = kill( pid.toNative(), sig );
            if ( x ) {
                if ( errno == ESRCH ) {
                }
                else {
                    log() << "killFailed: " << errnoWithDescription() << endl;
                    verify( x == 0 );
                }
            }

#endif
        }
Пример #10
0
BOOL CNameEvent::OpenEvent()
{
	assert(ISNULL(m_hEvent));
	if (ISNOTNULL(m_hEvent))
	{
		DOLOG("the Event already opened!");
		return FALSE;
	}
	
	m_hEvent = OpenEventA(EVENT_MODIFY_STATE, FALSE, m_cbEventName);
	
	assert(ISNOTNULL(m_hEvent));
	if (ISNULL(m_hEvent))
	{
		DOLOG("open Event failed! " + GetLastError());
		return FALSE;
	}

	return TRUE;
}
Пример #11
0
/*
 * ::createIpcEvent
 */
int createIpcEvent(IpcEvent *evt, const int reserved, const int isInitiallySet,
        const int isCreateOnly, const char *name) {
    int retval = 0;

#ifdef _WIN32
    if ((*evt = CreateEventA(NULL, reserved, isInitiallySet, name)) == NULL) {
        retval = GetLastError();

        /* If event already exists and open is allowed, try to open it. */
        if ((retval == ERROR_ALREADY_EXISTS) && !isCreateOnly) {
            if ((*evt = OpenEventA(EVENT_MODIFY_STATE | SYNCHRONIZE, FALSE, name))
                    != NULL) {
                retval = 0;
            } else {
                retval = GetLastError();
            }
        }
    }

#else /* _WIN32 */
    char *n = (char *) malloc(strlen(name) + 2);

    if (n != NULL) {
        strcpy(n, "/");
        strcat(n, name);

        if ((*evt = sem_open(n, (isCreateOnly ? O_CREAT : 0), 0666, 
                (isInitiallySet ? 1 : 0))) == SEM_FAILED) {
            retval = errno;
        }

        free(n);
    } else {
        retval = ENOMEM;
    }
#endif /* _WIN32 */

    return retval;
}
Пример #12
0
/** Send a kill signal to a windows version of GridLAB-D
    @return 0 on successfull completion, -1 on error (e.g., no such signal, no such process)
 **/
int kill(pid_t pid,	/**< the window process id */
		 int sig)				/**< the signal id (see signal.h) */
{
	char name[32];
	HANDLE hEvent;
	sprintf(name,"gridlabd.%u.%u",pid,sig==0?SIGINT:sig); /* use INT for sig==0 just to check */
	hEvent = OpenEventA(EVENT_MODIFY_STATE,FALSE,name);
	
	/* existence check only */
	if ( sig==0 )
	{
		if ( hEvent!=NULL )
		{
			CloseHandle(hEvent);
			return 0;
		}
		else
		{
			errno = ESRCH;
			return -1;
		}
	}

	/* valid signal needs to be sent */
	else if (hEvent==NULL)
	{
		errno = EINVAL; // TODO distinguish between bad signal and bad pid
		output_error("unable to signal gridlabd process %d with signal %d (error %d)", pid, sig, GetLastError());
		return -1;
	}
	else 
	{
		SetEvent(hEvent);
		output_verbose("signal %d sent to gridlabd process %d", sig, pid);
		CloseHandle(hEvent);
		return 0;
	}
}
Пример #13
0
static HANDLE open_event(int sig)
{
	char name[EVT_NAME_LEN];
	make_name(name, sig);
	return OpenEventA(EVENT_MODIFY_STATE, FALSE, name);
}
Пример #14
0
BOOL InitDataSharer(PDataSharer p_data_sharer,TCHAR *shared_memory_name,int shared_memory_size,BOOL is_server)
{
	HANDLE MapFileHandle=INVALID_HANDLE_VALUE;
	PBYTE shared_buffer;
#define READ_EVENT_POSTIFX TEXT("_read")
#define WRITE_EVENT_POSTIFX TEXT("_write")
	int event_name_len=(_tcslen(shared_memory_name)+max(_tcslen(READ_EVENT_POSTIFX),_tcslen(WRITE_EVENT_POSTIFX))+10)*sizeof(TCHAR);
	char *event_name=(char *)malloc(event_name_len);
	memset(event_name,0,event_name_len);
#ifdef UNICODE
	_snprintf(event_name,event_name_len/sizeof(TCHAR)-1,"%ws%ws",shared_memory_name,READ_EVENT_POSTIFX);
#else
	_snprintf(event_name,event_name_len-1,"%s%s",shared_memory_name,READ_EVENT_POSTIFX);
#endif
	dprintf(TEXT("%s: Creating Event[%s]\n"),__FUNCTION__,event_name);
	//Init R/W Event
	if(1 || is_server)
	{
		p_data_sharer->EventHandleForReading=CreateEventA(NULL,TRUE,FALSE,(LPCSTR)event_name);
	}else
	{
		p_data_sharer->EventHandleForReading=OpenEventA(EVENT_ALL_ACCESS,TRUE,(LPCSTR)event_name);
	}

	if (!p_data_sharer->EventHandleForReading) 
	{
		//error
		dprintf(TEXT("%s: Creating Event Failed\n"), __FUNCTION__);
		return FALSE;
	}

	memset(event_name,0,event_name_len);
#ifdef UNICODE
	_snprintf(event_name,(event_name_len)/sizeof(TCHAR)-1,"%ws%ws",shared_memory_name,WRITE_EVENT_POSTIFX);
#else
	_snprintf(event_name,event_name_len-1,"%s%s",shared_memory_name,WRITE_EVENT_POSTIFX);	
#endif
	dprintf(TEXT("Creating Event[%s]\n"),event_name);
	if(1 || is_server)
	{
		p_data_sharer->EventHandleForWriting= CreateEventA(NULL,TRUE,FALSE,(LPCSTR)event_name);
	}else
	{
		p_data_sharer->EventHandleForWriting=OpenEventA(EVENT_ALL_ACCESS,TRUE,(LPCSTR)event_name);
	}

	free(event_name);
	if (!p_data_sharer->EventHandleForWriting) 
	{ 
		//error
		dprintf(TEXT("%s: Creating Event Failed\n"), __FUNCTION__);
		return FALSE;
	}

	if(!is_server)
	{
		//Creates Map
		MapFileHandle=OpenFileMappingA(
			FILE_MAP_ALL_ACCESS,	// read/write access
			FALSE,					// do not inherit the name
			(LPCSTR)shared_memory_name);	// name of mapping object
	}
	if(MapFileHandle==INVALID_HANDLE_VALUE || !MapFileHandle)
	{
		//Creates Map
		MapFileHandle=CreateFileMappingA(
			INVALID_HANDLE_VALUE,
			NULL,
			PAGE_READWRITE,
			0,
			shared_memory_size+sizeof(MemoryHeader),
			(LPCSTR)shared_memory_name);
	}

	if (MapFileHandle!=INVALID_HANDLE_VALUE && MapFileHandle)  
	{
		dprintf(TEXT("%s: Created Shared Memory[%s]\n"),__FUNCTION__,shared_memory_name);
	
		shared_buffer=(PBYTE)MapViewOfFile(
			MapFileHandle,
			FILE_MAP_ALL_ACCESS,	// read/write permission
			0,
			0,
			shared_memory_size+sizeof(MemoryHeader)); 

		if(shared_buffer)
		{
			dprintf(TEXT("%s: shared_buffer=%X\n"),
				__FUNCTION__,
				shared_buffer);
		
			//Init Shared Memory Header(R/W Pointer,Size)
			p_data_sharer->MemoryHeaderPtr=(PMemoryHeader)shared_buffer;
			if(is_server && p_data_sharer->MemoryHeaderPtr)
			{
				p_data_sharer->MemoryHeaderPtr->BufferSize=shared_memory_size;
				p_data_sharer->MemoryHeaderPtr->ReadPoint=p_data_sharer->MemoryHeaderPtr->WritePoint=0;
			}
			dprintf(TEXT("%s: p_data_sharer->MemoryHeaderPtr->Data=%X\n"),
				__FUNCTION__,
				p_data_sharer->MemoryHeaderPtr->Data);
#ifndef USE_SINGLE_THREAD_FOR_SHARED_MEMORY
			InitializeCriticalSection(&p_data_sharer->critical_section);
#endif
			return TRUE;
		}
	}
	dprintf(TEXT("%s: Returning False\n"), __FUNCTION__);
	return FALSE;	
}
Пример #15
0
HRESULT RequestTransfer(TShellExt *Self, int idxCmd)
{
	// get the contact information
	MENUITEMINFOA mii = { 0 };
	mii.cbSize = sizeof(mii);
	mii.fMask = MIIM_ID | MIIM_DATA;
	if ( !GetMenuItemInfoA(Self->hRootMenu, Self->idCmdFirst + idxCmd, false, &mii))
		return E_INVALIDARG;

	// get the pointer
	TMenuDrawInfo *psd = (TMenuDrawInfo*)mii.dwItemData;
	// the ID stored in the item pointer and the ID for the menu must match
	if (psd == NULL || psd->wID != mii.wID)
		return E_INVALIDARG;

	// is there an IDataObject instance?
	HRESULT hr = E_INVALIDARG;
	if (Self->pDataObject != NULL) {
		// OpenEvent() the work object to see if the instance is still around
		char szBuf[100];
		HANDLE hTransfer = OpenEventA(EVENT_ALL_ACCESS, false, CreateProcessUID(psd->pid, szBuf, sizeof(szBuf)));
		if (hTransfer != 0) {
			// map the ipc file again
			HANDLE hMap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, IPC_PACKET_SIZE, IPC_PACKET_NAME);
			if (hMap != 0 && GetLastError() != ERROR_ALREADY_EXISTS) {
				// map it to process
				THeaderIPC *pipch = (THeaderIPC*)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
				if (pipch != NULL) {
					// create the name of the object to be signalled by the ST
					lstrcpyA(pipch->SignalEventName, CreateUID(szBuf, sizeof(szBuf)));
					// create it
					HANDLE hReply = CreateEventA(NULL, false, false, pipch->SignalEventName);
					if (hReply != 0) {
						if (psd->fTypes & dtCommand) {
							if (psd->MenuCommandCallback) 
								hr = psd->MenuCommandCallback(pipch, hTransfer, hReply);
						}
						else {
							// prepare the buffer
							ipcPrepareRequests(IPC_PACKET_SIZE, pipch, REQUEST_XFRFILES);
							// get all the files into the packet
							if (ipcGetFiles(pipch, Self->pDataObject, psd->hContact) == S_OK) {
								// need to wait for the ST to open the mapping object
								// since if we close it before it's opened it the data it
								// has will be undefined
								int replyBits = ipcSendRequest(hTransfer, hReply, pipch, 200);
								if (replyBits != REPLY_FAIL) // they got the files!
									hr = S_OK;
							}
						}
						// close the work object name
						CloseHandle(hReply);
					}
					// unmap it from this process
					UnmapViewOfFile(pipch);
				}
				// close the map
				CloseHandle(hMap);
			}
			// close the handle to the ST object name
			CloseHandle(hTransfer);
		}
	}
	return hr;
}
Пример #16
0
void am_log_init(int id, int status) {
    int i;
    char opened = 0;

    am_agent_instance_init_init(id);

    if (am_log_handle == NULL) {
        am_log_handle = (struct am_shared_log *) malloc(sizeof (struct am_shared_log));
        if (am_log_handle == NULL) {
            return;
        }
    } else if (am_log_handle->reader_pid == getpid()) {
        return;
    }

    am_log_handle->reader_pid = getpid();
    snprintf(am_log_handle->area_file_name, sizeof (am_log_handle->area_file_name),
#ifdef __sun
            "/am_log_%d"
#else
            AM_GLOBAL_PREFIX"am_log_%d"
#endif
            , id);
    am_log_handle->area_size = page_size(sizeof (struct am_log));

#ifdef _WIN32
    am_log_handle->area_file_id = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
            0, (DWORD) am_log_handle->area_size, am_log_handle->area_file_name);

    if (am_log_handle->area_file_id == NULL) return;
    if (NULL != am_log_handle->area_file_id && GetLastError() == ERROR_ALREADY_EXISTS) {
        opened = 1;
    }

    if (am_log_handle->area_file_id != NULL) {
        am_log_handle->area = MapViewOfFile(am_log_handle->area_file_id, FILE_MAP_ALL_ACCESS,
                0, 0, am_log_handle->area_size);
    }
    if (am_log_handle->area != NULL) {
        if (status == AM_SUCCESS || status == AM_EAGAIN) {
            struct am_log *log = (struct am_log *) am_log_handle->area;

            memset(log, 0, am_log_handle->area_size);

            log->bucket_count = AM_LOG_QUEUE_SIZE;
            log->bucket_size = AM_LOG_MESSAGE_SIZE;
            log->in = log->out = log->read_count = log->write_count = 0;

            for (i = 0; i < AM_MAX_INSTANCES; i++) {
                struct log_files *f = &log->files[i];
                f->fd_audit = f->fd_debug = -1;
                f->used = AM_FALSE;
                f->instance_id = 0;
                f->level_debug = f->level_audit = AM_LOG_LEVEL_NONE;
                f->max_size_debug = f->max_size_audit = 0;
            }

            am_log_lck.exit = CreateEvent(NULL, FALSE, FALSE, get_global_name(AM_GLOBAL_PREFIX"am_log_exit", id));
            if (am_log_lck.exit == NULL && GetLastError() == ERROR_ACCESS_DENIED) {
                am_log_lck.exit = OpenEventA(SYNCHRONIZE, TRUE, get_global_name(AM_GLOBAL_PREFIX"am_log_exit", id));
            }
            am_log_lck.lock = CreateMutex(NULL, FALSE, get_global_name(AM_GLOBAL_PREFIX"am_log_lock", id));
            if (am_log_lck.lock == NULL && GetLastError() == ERROR_ACCESS_DENIED) {
                am_log_lck.lock = OpenMutexA(SYNCHRONIZE, TRUE, get_global_name(AM_GLOBAL_PREFIX"am_log_lock", id));
            }
            am_log_lck.new_data_cond = CreateEvent(NULL, FALSE, FALSE, get_global_name(AM_GLOBAL_PREFIX"am_log_queue_empty", id));
            if (am_log_lck.new_data_cond == NULL && GetLastError() == ERROR_ACCESS_DENIED) {
                am_log_lck.new_data_cond = OpenEventA(SYNCHRONIZE, TRUE, get_global_name(AM_GLOBAL_PREFIX"am_log_queue_empty", id));
            }
            am_log_lck.new_space_cond = CreateEvent(NULL, FALSE, FALSE, get_global_name(AM_GLOBAL_PREFIX"am_log_queue_overflow", id));
            if (am_log_lck.new_space_cond == NULL && GetLastError() == ERROR_ACCESS_DENIED) {
                am_log_lck.new_space_cond = OpenEventA(SYNCHRONIZE, TRUE, get_global_name(AM_GLOBAL_PREFIX"am_log_queue_overflow", id));
            }

            log->owner = getpid();
            am_log_handle->reader_thr = CreateThread(NULL, 0,
                    (LPTHREAD_START_ROUTINE) am_log_worker, NULL, 0, NULL);
        }
    }

#else
    am_log_handle->area_file_id = shm_open(am_log_handle->area_file_name, O_CREAT | O_EXCL | O_RDWR, 0666);
    if (am_log_handle->area_file_id == -1 && EEXIST != errno) {
        return;
    }
    if (am_log_handle->area_file_id == -1) {
        /* already there, open without O_EXCL and go; if
         * something goes wrong, close and cleanup */
        am_log_handle->area_file_id = shm_open(am_log_handle->area_file_name, O_RDWR, 0666);
        if (am_log_handle->area_file_id == -1) {
            fprintf(stderr, "am_log_init() shm_open failed (%d)\n", errno);
            free(am_log_handle);
            am_log_handle = NULL;
            return;
        } else {
            opened = 1;
        }
    } else {
        /* we just created the shm area, must setup; if
         * something goes wrong, delete the shm area and
         * cleanup
         */
        if (ftruncate(am_log_handle->area_file_id, am_log_handle->area_size) == -1) {
            fprintf(stderr, "am_log_init() ftruncate failed\n");
            return;
        }
    }
    if (am_log_handle->area_file_id != -1) {
        am_log_handle->area = mmap(NULL, am_log_handle->area_size,
                PROT_READ | PROT_WRITE, MAP_SHARED, am_log_handle->area_file_id, 0);
        if (am_log_handle->area == MAP_FAILED) {
            fprintf(stderr, "am_log_init() mmap failed (%d)\n", errno);
            free(am_log_handle);
            am_log_handle = NULL;
        } else {
            pthread_mutexattr_t exit_attr, lock_attr;
            pthread_condattr_t new_data_attr, new_space_attr;

            struct am_log *log = (struct am_log *) am_log_handle->area;

            pthread_mutexattr_init(&exit_attr);
            pthread_mutexattr_init(&lock_attr);
            pthread_condattr_init(&new_data_attr);
            pthread_condattr_init(&new_space_attr);
            pthread_mutexattr_setpshared(&exit_attr, PTHREAD_PROCESS_SHARED);
            pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED);
            pthread_condattr_setpshared(&new_data_attr, PTHREAD_PROCESS_SHARED);
            pthread_condattr_setpshared(&new_space_attr, PTHREAD_PROCESS_SHARED);

            if (status == AM_SUCCESS || status == AM_EAGAIN) {

                memset(log, 0, am_log_handle->area_size);

                log->bucket_count = AM_LOG_QUEUE_SIZE;
                log->bucket_size = AM_LOG_MESSAGE_SIZE;
                log->in = log->out = log->read_count = log->write_count = 0;

                for (i = 0; i < AM_MAX_INSTANCES; i++) {
                    struct log_files *f = &log->files[i];
                    f->fd_audit = f->fd_debug = -1;
                    f->used = AM_FALSE;
                    f->instance_id = 0;
                    f->level_debug = f->level_audit = AM_LOG_LEVEL_NONE;
                    f->max_size_debug = f->max_size_audit = 0;
                }

                pthread_mutex_init(&log->exit, &exit_attr);
                pthread_mutex_init(&log->lock, &lock_attr);
                pthread_cond_init(&log->new_data_cond, &new_data_attr);
                pthread_cond_init(&log->new_space_cond, &new_space_attr);

                pthread_mutex_lock(&log->exit);
                pthread_create(&am_log_handle->reader_thr, NULL, am_log_worker, NULL);
                log->owner = getpid();
            }

            pthread_mutexattr_destroy(&exit_attr);
            pthread_mutexattr_destroy(&lock_attr);
            pthread_condattr_destroy(&new_data_attr);
            pthread_condattr_destroy(&new_space_attr);
        }
    }

#endif
}
Пример #17
0
      inline void kill_wrapper( ProcessId pid, int sig, int port, const BSONObj& opt ) {
#ifdef _WIN32
            if (sig == SIGKILL || port == 0) {
                verify( registry._handles.count(pid) );
                TerminateProcess(registry._handles[pid], 1); // returns failure for "zombie" processes.
                return;
            }

            std::string eventName = getShutdownSignalName(pid.asUInt32());

            HANDLE event = OpenEventA(EVENT_MODIFY_STATE, FALSE, eventName.c_str());
            if (event == NULL) {
                int gle = GetLastError();
                if (gle != ERROR_FILE_NOT_FOUND) {
                    warning() << "kill_wrapper OpenEvent failed: " << errnoWithDescription();
                }
                else {
                    log() << "kill_wrapper OpenEvent failed to open event to the process "
                        << pid.asUInt32()
                        << ". It has likely died already or server is running an older version."
                        << " Attempting to shutdown through admin command.";

                    // Back-off to the old way of shutting down the server on Windows, in case we
                    // are managing a pre-2.6.0rc0 service, which did not have the event.
                    //
                    try {
                        DBClientConnection conn;
                        conn.connect("127.0.0.1:" + BSONObjBuilder::numStr(port));

                        BSONElement authObj = opt["auth"];

                        if (!authObj.eoo()){
                            string errMsg;
                            conn.auth("admin", authObj["user"].String(),
                                authObj["pwd"].String(), errMsg);

                            if (!errMsg.empty()) {
                                cout << "Failed to authenticate before shutdown: "
                                    << errMsg << endl;
                            }
                        }

                        BSONObj info;
                        BSONObjBuilder b;
                        b.append("shutdown", 1);
                        b.append("force", 1);
                        conn.runCommand("admin", b.done(), info);
                    }
                    catch (...) {
                        // Do nothing. This command never returns data to the client and the driver
                        // doesn't like that.
                        //
                    }
                }
                return;
            }

            ON_BLOCK_EXIT(CloseHandle, event);

            bool result = SetEvent(event);
            if (!result) {
                error() << "kill_wrapper SetEvent failed: " << errnoWithDescription();
                return;
            }
#else
            int x = kill( pid.toNative(), sig );
            if ( x ) {
                if ( errno == ESRCH ) {
                }
                else {
                    log() << "killFailed: " << errnoWithDescription() << endl;
                    verify( x == 0 );
                }
            }

#endif
        }
Пример #18
0
static void test_event(void)
{
    HANDLE handle, handle2;
    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sd;
    ACL acl;
    DWORD ret;
    BOOL val;

    /* no sd */
    handle = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = &sd;
    sa.bInheritHandle = FALSE;

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);

    /* blank sd */
    handle = CreateEventA(&sa, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    /* sd with NULL dacl */
    SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);
    handle = CreateEventA(&sa, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    /* sd with empty dacl */
    InitializeAcl(&acl, sizeof(acl), ACL_REVISION);
    SetSecurityDescriptorDacl(&sd, TRUE, &acl, FALSE);
    handle = CreateEventA(&sa, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    /* test case sensitivity */

    SetLastError(0xdeadbeef);
    handle = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    ok( handle != NULL, "CreateEvent failed with error %u\n", GetLastError());
    ok( GetLastError() == 0, "wrong error %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    handle2 = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    ok( handle2 != NULL, "CreateEvent failed with error %d\n", GetLastError());
    ok( GetLastError() == ERROR_ALREADY_EXISTS, "wrong error %u\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": TEST EVENT");
    ok( handle2 != NULL, "CreateEvent failed with error %d\n", GetLastError());
    ok( GetLastError() == 0, "wrong error %u\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = OpenEventA( EVENT_ALL_ACCESS, FALSE, __FILE__ ": Test Event");
    ok( handle2 != NULL, "OpenEvent failed with error %d\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = OpenEventA( EVENT_ALL_ACCESS, FALSE, __FILE__ ": TEST EVENT");
    ok( !handle2, "OpenEvent succeeded\n");
    ok( GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());

    CloseHandle( handle );

    /* resource notifications are events too */

    if (!pCreateMemoryResourceNotification || !pQueryMemoryResourceNotification)
    {
        trace( "memory resource notifications not supported\n" );
        return;
    }
    handle = pCreateMemoryResourceNotification( HighMemoryResourceNotification + 1 );
    ok( !handle, "CreateMemoryResourceNotification succeeded\n" );
    ok( GetLastError() == ERROR_INVALID_PARAMETER, "wrong error %u\n", GetLastError() );
    ret = pQueryMemoryResourceNotification( handle, &val );
    ok( !ret, "QueryMemoryResourceNotification succeeded\n" );
    ok( GetLastError() == ERROR_INVALID_PARAMETER, "wrong error %u\n", GetLastError() );

    handle = pCreateMemoryResourceNotification( LowMemoryResourceNotification );
    ok( handle != 0, "CreateMemoryResourceNotification failed err %u\n", GetLastError() );
    ret = WaitForSingleObject( handle, 10 );
    ok( ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT, "WaitForSingleObject wrong ret %u\n", ret );

    val = ~0;
    ret = pQueryMemoryResourceNotification( handle, &val );
    ok( ret, "QueryMemoryResourceNotification failed err %u\n", GetLastError() );
    ok( val == FALSE || val == TRUE, "wrong value %u\n", val );
    ret = CloseHandle( handle );
    ok( ret, "CloseHandle failed err %u\n", GetLastError() );

    handle = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    val = ~0;
    ret = pQueryMemoryResourceNotification( handle, &val );
    ok( ret, "QueryMemoryResourceNotification failed err %u\n", GetLastError() );
    ok( val == FALSE || val == TRUE, "wrong value %u\n", val );
    CloseHandle( handle );
}
Пример #19
0
static void test_event(void)
{
    HANDLE handle, handle2;
    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sd;
    ACL acl;

    /* no sd */
    handle = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = &sd;
    sa.bInheritHandle = FALSE;

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);

    /* blank sd */
    handle = CreateEventA(&sa, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    /* sd with NULL dacl */
    SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE);
    handle = CreateEventA(&sa, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    /* sd with empty dacl */
    InitializeAcl(&acl, sizeof(acl), ACL_REVISION);
    SetSecurityDescriptorDacl(&sd, TRUE, &acl, FALSE);
    handle = CreateEventA(&sa, FALSE, FALSE, __FILE__ ": Test Event");
    ok(handle != NULL, "CreateEventW with blank sd failed with error %d\n", GetLastError());
    CloseHandle(handle);

    /* test case sensitivity */

    SetLastError(0xdeadbeef);
    handle = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    ok( handle != NULL, "CreateEvent failed with error %u\n", GetLastError());
    ok( GetLastError() == 0, "wrong error %u\n", GetLastError());

    SetLastError(0xdeadbeef);
    handle2 = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": Test Event");
    ok( handle2 != NULL, "CreateEvent failed with error %d\n", GetLastError());
    ok( GetLastError() == ERROR_ALREADY_EXISTS, "wrong error %u\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = CreateEventA(NULL, FALSE, FALSE, __FILE__ ": TEST EVENT");
    ok( handle2 != NULL, "CreateEvent failed with error %d\n", GetLastError());
    ok( GetLastError() == 0, "wrong error %u\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = OpenEventA( EVENT_ALL_ACCESS, FALSE, __FILE__ ": Test Event");
    ok( handle2 != NULL, "OpenEvent failed with error %d\n", GetLastError());
    CloseHandle( handle2 );

    SetLastError(0xdeadbeef);
    handle2 = OpenEventA( EVENT_ALL_ACCESS, FALSE, __FILE__ ": TEST EVENT");
    ok( !handle2, "OpenEvent succeeded\n");
    ok( GetLastError() == ERROR_FILE_NOT_FOUND ||
        GetLastError() == ERROR_INVALID_NAME, /* win9x */
        "wrong error %u\n", GetLastError());

    CloseHandle( handle );
}
Пример #20
0
// this function is called from an APC into the main thread
void __stdcall ipcService(ULONG_PTR dwParam)
{
	HANDLE hSignal;
	TSlotIPC *pct;
	LPSTR szBuf;
	char szGroupStr[32];
	DBVARIANT dbv;
	LPSTR szMiranda;

	// try to open the file mapping object the caller must make sure no other
	// running instance is using this file
	HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, false, IPC_PACKET_NAME);
	if (hMap == 0)
		return;

	// map the file to this process
	THeaderIPC *pMMT = (THeaderIPC*)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	// if it fails the caller should of had some timeout in wait
	if (pMMT != NULL && pMMT->cbSize == sizeof(THeaderIPC) && pMMT->dwVersion == PLUGIN_MAKE_VERSION(2, 0, 1, 2)) {
		// toggle the right bits
		int *bits = &pMMT->fRequests;
		// jump right to a worker thread for file processing?
		if (*bits & REQUEST_XFRFILES) {
			THeaderIPC *cloned = (THeaderIPC*)mir_alloc(IPC_PACKET_SIZE);
			// translate from client space to cloned heap memory
			pMMT->pServerBaseAddress = pMMT->pClientBaseAddress;
			pMMT->pClientBaseAddress = cloned;
			CopyMemory(cloned, pMMT, IPC_PACKET_SIZE);
			ipcFixupAddresses(true, cloned);
			DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &cloned->Param, THREAD_SET_CONTEXT, false, 0);
			mir_forkthread(&IssueTransferThread, cloned);
			goto Reply;
		}
		// the request was to clear the MRU entries, we have no return data
		if (*bits & REQUEST_CLEARMRU) {
			mir_forkthread(&ClearMRUThread, NULL);
			goto Reply;
		}
		// the IPC header may have pointers that need to be translated
		// in either case the supplied data area pointers has to be
		// translated to this address space.
		// the server base address is always removed to get an offset
		// to which the client base is added, this is what ipcFixupAddresses() does
		pMMT->pServerBaseAddress = pMMT->pClientBaseAddress;
		pMMT->pClientBaseAddress = pMMT;
		// translate to the server space map
		ipcFixupAddresses(true, pMMT);
		// store the address map offset so the caller can retranslate
		pMMT->pServerBaseAddress = pMMT;
		// return some options to the client
		if (db_get_b(0, SHLExt_Name, SHLExt_ShowNoIcons, 0) != 0)
			pMMT->dwFlags = HIPC_NOICONS;

		// see if we have a custom string for 'Miranda'
		szMiranda = "Miranda";
		lstrcpynA(pMMT->MirandaName, szMiranda, sizeof(pMMT->MirandaName) - 1);

		// for the MRU menu
		szBuf = Translate("Recently");
		lstrcpynA(pMMT->MRUMenuName, szBuf, sizeof(pMMT->MRUMenuName) - 1);

		// and a custom string for "clear entries"
		szBuf = Translate("Clear entries");
		lstrcpynA(pMMT->ClearEntries, szBuf, sizeof(pMMT->ClearEntries) - 1);

		// if the group mode is on, check if they want the CList setting
		bool bGroupMode = (BST_CHECKED == db_get_b(0, SHLExt_Name, SHLExt_UseGroups, BST_UNCHECKED));
		if (bGroupMode && BST_CHECKED == db_get_b(0, SHLExt_Name, SHLExt_UseCListSetting, BST_UNCHECKED)) 
			bGroupMode = db_get_b(0, "CList", "UseGroups", true) != 0;

		int iSlot = 0;
		// return profile if set
		if (BST_UNCHECKED == db_get_b(0, SHLExt_Name, SHLExt_ShowNoProfile, BST_UNCHECKED)) {
			pct = ipcAlloc(pMMT, 50);
			if (pct != NULL) {
				// will actually return with .dat if there's space for it, not what the docs say
				pct->Status = STATUS_PROFILENAME;
				CallService(MS_DB_GETPROFILENAME, 49, UINT_PTR(pct) + sizeof(TSlotIPC));
			}
		}
		if (*bits & REQUEST_NEWICONS)
			ipcGetSkinIcons(pMMT);

		if (*bits & REQUEST_GROUPS) {
			// return contact's grouping if it's present
			while (bGroupMode) {
				_itoa(iSlot, szGroupStr, 10);
				if ( db_get_s(0, "CListGroups", szGroupStr, &dbv) != 0)
					break;
				pct = ipcAlloc(pMMT, lstrlenA(dbv.pszVal + 1) + 1);
				// first byte has flags, need null term
				if (pct != NULL) {
					if (pMMT->GroupsBegin == NULL)
						pMMT->GroupsBegin = pct;
					pct->fType = REQUEST_GROUPS;
					pct->hContact = 0;
					szBuf = LPSTR(pct) + sizeof(TSlotIPC); // get the end of the slot
					lstrcpyA(szBuf, dbv.pszVal + 1);
					pct->hGroup = 0;
					db_free(&dbv); // free the string
				}
				else {
					// outta space
					db_free(&dbv);
					break;
				}
				iSlot++;
			}
			// if there was no space left, it'll } on null
			if (pct == NULL)
				*bits = (*bits | GROUPS_NOTIMPL) & ~REQUEST_GROUPS;
		}
		// SHOULD check slot space.
		if (*bits & REQUEST_CONTACTS) {
			if (!ipcGetSortedContacts(pMMT, &iSlot, bGroupMode))
				// fail if there were no contacts AT ALL
				*bits = (*bits | CONTACTS_NOTIMPL) & ~REQUEST_CONTACTS;
		}
		// store the number of slots allocated
		pMMT->Slots = iSlot;
Reply:
		// get the handle the caller wants to be signalled on 
		hSignal = OpenEventA(EVENT_ALL_ACCESS, false, pMMT->SignalEventName);
		if (hSignal != 0) {
			SetEvent(hSignal);
			CloseHandle(hSignal);
		}

		UnmapViewOfFile(pMMT);
	}
	CloseHandle(hMap);
}