Exemplo n.º 1
0
static HRESULT WINAPI PngDecoder_Initialize(IWICBitmapDecoder *iface, IStream *pIStream,
    WICDecodeOptions cacheOptions)
{
    PngDecoder *This = impl_from_IWICBitmapDecoder(iface);
    LARGE_INTEGER seek;
    HRESULT hr=S_OK;
    png_bytep *row_pointers=NULL;
    UINT image_size;
    UINT i;
    int color_type, bit_depth;
    png_bytep trans;
    int num_trans;
    png_uint_32 transparency;
    png_color_16p trans_values;
    jmp_buf jmpbuf;

    TRACE("(%p,%p,%x)\n", iface, pIStream, cacheOptions);

    EnterCriticalSection(&This->lock);

    /* initialize libpng */
    This->png_ptr = ppng_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!This->png_ptr)
    {
        hr = E_FAIL;
        goto end;
    }

    This->info_ptr = ppng_create_info_struct(This->png_ptr);
    if (!This->info_ptr)
    {
        ppng_destroy_read_struct(&This->png_ptr, NULL, NULL);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }

    This->end_info = ppng_create_info_struct(This->png_ptr);
    if (!This->info_ptr)
    {
        ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, NULL);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }

    /* set up setjmp/longjmp error handling */
    if (setjmp(jmpbuf))
    {
        ppng_destroy_read_struct(&This->png_ptr, &This->info_ptr, &This->end_info);
        HeapFree(GetProcessHeap(), 0, row_pointers);
        This->png_ptr = NULL;
        hr = E_FAIL;
        goto end;
    }
    ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);

    /* seek to the start of the stream */
    seek.QuadPart = 0;
    hr = IStream_Seek(pIStream, seek, STREAM_SEEK_SET, NULL);
    if (FAILED(hr)) goto end;

    /* set up custom i/o handling */
    ppng_set_read_fn(This->png_ptr, pIStream, user_read_data);

    /* read the header */
    ppng_read_info(This->png_ptr, This->info_ptr);

    /* choose a pixel format */
    color_type = ppng_get_color_type(This->png_ptr, This->info_ptr);
    bit_depth = ppng_get_bit_depth(This->png_ptr, This->info_ptr);

    /* check for color-keyed alpha */
    transparency = ppng_get_tRNS(This->png_ptr, This->info_ptr, &trans, &num_trans, &trans_values);

    if (transparency && color_type != PNG_COLOR_TYPE_PALETTE)
    {
        /* expand to RGBA */
        if (color_type == PNG_COLOR_TYPE_GRAY)
        {
            if (bit_depth < 8)
            {
#if HAVE_PNG_SET_EXPAND_GRAY_1_2_4_TO_8
                ppng_set_expand_gray_1_2_4_to_8(This->png_ptr);
#else
                ppng_set_gray_1_2_4_to_8(This->png_ptr);
#endif
                bit_depth = 8;
            }
            ppng_set_gray_to_rgb(This->png_ptr);
        }
        ppng_set_tRNS_to_alpha(This->png_ptr);
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;
    }

    switch (color_type)
    {
    case PNG_COLOR_TYPE_GRAY:
        This->bpp = bit_depth;
        switch (bit_depth)
        {
        case 1: This->format = &GUID_WICPixelFormatBlackWhite; break;
        case 2: This->format = &GUID_WICPixelFormat2bppGray; break;
        case 4: This->format = &GUID_WICPixelFormat4bppGray; break;
        case 8: This->format = &GUID_WICPixelFormat8bppGray; break;
        case 16: This->format = &GUID_WICPixelFormat16bppGray; break;
        default:
            ERR("invalid grayscale bit depth: %i\n", bit_depth);
            hr = E_FAIL;
            goto end;
        }
        break;
    case PNG_COLOR_TYPE_GRAY_ALPHA:
        /* WIC does not support grayscale alpha formats so use RGBA */
        ppng_set_gray_to_rgb(This->png_ptr);
        /* fall through */
    case PNG_COLOR_TYPE_RGB_ALPHA:
        This->bpp = bit_depth * 4;
        switch (bit_depth)
        {
        case 8:
            ppng_set_bgr(This->png_ptr);
            This->format = &GUID_WICPixelFormat32bppBGRA;
            break;
        case 16: This->format = &GUID_WICPixelFormat64bppRGBA; break;
        default:
            ERR("invalid RGBA bit depth: %i\n", bit_depth);
            hr = E_FAIL;
            goto end;
        }
        break;
    case PNG_COLOR_TYPE_PALETTE:
        This->bpp = bit_depth;
        switch (bit_depth)
        {
        case 1: This->format = &GUID_WICPixelFormat1bppIndexed; break;
        case 2: This->format = &GUID_WICPixelFormat2bppIndexed; break;
        case 4: This->format = &GUID_WICPixelFormat4bppIndexed; break;
        case 8: This->format = &GUID_WICPixelFormat8bppIndexed; break;
        default:
            ERR("invalid indexed color bit depth: %i\n", bit_depth);
            hr = E_FAIL;
            goto end;
        }
        break;
    case PNG_COLOR_TYPE_RGB:
        This->bpp = bit_depth * 3;
        switch (bit_depth)
        {
        case 8:
            ppng_set_bgr(This->png_ptr);
            This->format = &GUID_WICPixelFormat24bppBGR;
            break;
        case 16: This->format = &GUID_WICPixelFormat48bppRGB; break;
        default:
            ERR("invalid RGB color bit depth: %i\n", bit_depth);
            hr = E_FAIL;
            goto end;
        }
        break;
    default:
        ERR("invalid color type %i\n", color_type);
        hr = E_FAIL;
        goto end;
    }

    /* read the image data */
    This->width = ppng_get_image_width(This->png_ptr, This->info_ptr);
    This->height = ppng_get_image_height(This->png_ptr, This->info_ptr);
    This->stride = This->width * This->bpp;
    image_size = This->stride * This->height;

    This->image_bits = HeapAlloc(GetProcessHeap(), 0, image_size);
    if (!This->image_bits)
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }

    row_pointers = HeapAlloc(GetProcessHeap(), 0, sizeof(png_bytep)*This->height);
    if (!row_pointers)
    {
        hr = E_OUTOFMEMORY;
        goto end;
    }

    for (i=0; i<This->height; i++)
        row_pointers[i] = This->image_bits + i * This->stride;

    ppng_read_image(This->png_ptr, row_pointers);

    HeapFree(GetProcessHeap(), 0, row_pointers);
    row_pointers = NULL;

    ppng_read_end(This->png_ptr, This->end_info);

    This->initialized = TRUE;

end:

    LeaveCriticalSection(&This->lock);

    return hr;
}
int __cdecl main(void)
{
    LPDHCP_POLICY       pPolicy                    = NULL;                 // Policy structure
    DWORD               dwError                    = ERROR_SUCCESS;        // It stores the error code
    DWORD               dwExprIdx                  = 0;                    // Expression Index
    DWORD               dwOptionId                 = OPTION_USER_CLASS;    // Option ID for UserClass
    DWORD               dwSubOptionId              = 0;                    // Sub Option ID for UserClass
    DWORD               dwConditionIdx             = 0;                    // Condition index which will be returned from DhcpHlprAddV4PolicyCondition
    DWORD               dwBytesLength              = 0;                    // Number of bytes of user data in pUserClassCondValueInBytes
    LPBYTE              pUserClassCondValueInBytes = NULL;                 // Bytes containing condition value (user class based in the current example)
    DHCP_IP_ADDRESS     dwSubnet                   = 0xa000000;            // Subnet Address (10.0.0.0)
    LPWSTR              pwszName                   = L"testPolicy";        //Name of the policy to be created
    LPWSTR              pwszDescription            = L"PolicyDescription"; // Description of the policy to be created
    char*               szUserClassConditionValue  = {"RRAS.Microsoft"};   // Default Routing and Remote Access Class
    DHCP_POL_LOGIC_OPER policyOperator             = DhcpLogicalOr;        // Root operator for the conditions and expressions
    DHCP_POL_ATTR_TYPE  policyAttrType             = DhcpAttrOption;       // Policy attribute type
    DHCP_POL_COMPARATOR conditionOper              = DhcpCompEqual;        // Condition operator
    DHCP_IP_RANGE       range                      = {0};                  // Variable to hold range values
    DWORD               dwStartAddress             = 0xa00000a;            //(10.0.0.10) Start Address of the range
    DWORD               dwEndAddress               = 0xa000032;            //(10.0.0.50) End Address of the range

    range.StartAddress = dwStartAddress;
    range.EndAddress   = dwEndAddress;


    // Invokes helper API to create/fill policy structure.
    dwError=DhcpHlprCreateV4Policy(
        pwszName,        // Policy Name
        (dwSubnet == 0), // fGloabalPolicy, if scope is zero, this means it is a global policy else it is for a specific scope
        dwSubnet,        // Scope
        0,               // Processing order
        policyOperator,  // Logical operator, possible values are: DhcpLogicalOr, DhcpLogicalAnd
        pwszDescription, // Policy description
        TRUE,            // Policy active or not
        &pPolicy         // This is the actual structure that holds the policy
    );

    if(ERROR_SUCCESS != dwError)
    {
        wprintf(L"DhcpHlprCreateV4Policy failed with Error = %d\n", dwError);
        goto cleanup;
    }

    // Fill in pUserClassCondValueInBytes and dwBytesLength
    dwBytesLength = (DWORD)strlen(szUserClassConditionValue);
    pUserClassCondValueInBytes = (LPBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesLength);
    if(NULL == pUserClassCondValueInBytes)
    {
        wprintf(L"Not Enough memory, HeapAllocFailed !!\n");
        goto cleanup;
    }
    // Copies the bytes for condition values from pUserClassCondValueInBytes
    memcpy(pUserClassCondValueInBytes, szUserClassConditionValue, dwBytesLength);

    // Invokes helper API to create/fill the structure for adding conditions for the policy.
    // The condition in this case is "user class" equals "Default Routing and Remote Access Class"
    dwError = DhcpHlprAddV4PolicyCondition(
        pPolicy,                    // Policy where conditions need to be added
        dwExprIdx,                  // Parent expression index
        policyAttrType,             // Policy attribute type, possible values can be: DhcpAttrHWAddr, DhcpAttrOption and DhcpAttrSubOption
        dwOptionId,                 // Option ID
        dwSubOptionId,              // Sub Option ID
        NULL,                       // Vendor Name
        conditionOper,              // Policy comparator operator
        pUserClassCondValueInBytes, // Condition values in bytes
        dwBytesLength,              // Number of bytes in the condition value
        &dwConditionIdx             // Condition index
    );
    if(ERROR_SUCCESS != dwError)
    {
        wprintf(L"DhcpHlprAddV4PolicyCondition failed with Error = %d\n", dwError);
        goto cleanup;
    }
    // Helper class for adding policy ip range is invoked from below.
    dwError = DhcpHlprAddV4PolicyRange(pPolicy,&range);
    if(ERROR_SUCCESS != dwError)
    {
        wprintf(L"DhcpHlprAddV4PolicyRange failed with Error = %d\n",dwError);
    }
cleanup:

    // Frees the variable holding the condition values in bytes
    if(NULL != pUserClassCondValueInBytes)
    {
        HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, pUserClassCondValueInBytes);
        pUserClassCondValueInBytes = NULL;
    }

    // Frees the variable holding the policy.
    if(NULL != pPolicy)
    {
        DhcpHlprFreeV4Policy(pPolicy);
    }

    return 0;
}
Exemplo n.º 3
0
static HRESULT WINAPI PngFrameEncode_WritePixels(IWICBitmapFrameEncode *iface,
    UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
{
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
    png_byte **row_pointers=NULL;
    UINT i;
    jmp_buf jmpbuf;
    TRACE("(%p,%u,%u,%u,%p)\n", iface, lineCount, cbStride, cbBufferSize, pbPixels);

    EnterCriticalSection(&This->lock);

    if (!This->frame_initialized || !This->width || !This->height || !This->format)
    {
        LeaveCriticalSection(&This->lock);
        return WINCODEC_ERR_WRONGSTATE;
    }

    if (lineCount == 0 || lineCount + This->lines_written > This->height)
    {
        LeaveCriticalSection(&This->lock);
        return E_INVALIDARG;
    }

    /* set up setjmp/longjmp error handling */
    if (setjmp(jmpbuf))
    {
        LeaveCriticalSection(&This->lock);
        HeapFree(GetProcessHeap(), 0, row_pointers);
        return E_FAIL;
    }
    ppng_set_error_fn(This->png_ptr, jmpbuf, user_error_fn, user_warning_fn);

    if (!This->info_written)
    {
        ppng_set_IHDR(This->png_ptr, This->info_ptr, This->width, This->height,
            This->format->bit_depth, This->format->color_type, PNG_INTERLACE_NONE,
            PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

        if (This->xres != 0.0 && This->yres != 0.0)
        {
            ppng_set_pHYs(This->png_ptr, This->info_ptr, (This->xres+0.0127) / 0.0254,
                (This->yres+0.0127) / 0.0254, PNG_RESOLUTION_METER);
        }

        ppng_write_info(This->png_ptr, This->info_ptr);

        if (This->format->remove_filler)
            ppng_set_filler(This->png_ptr, 0, PNG_FILLER_AFTER);

        if (This->format->swap_rgb)
            ppng_set_bgr(This->png_ptr);

        This->info_written = TRUE;
    }

    row_pointers = HeapAlloc(GetProcessHeap(), 0, lineCount * sizeof(png_byte*));
    if (!row_pointers)
    {
        LeaveCriticalSection(&This->lock);
        return E_OUTOFMEMORY;
    }

    for (i=0; i<lineCount; i++)
        row_pointers[i] = pbPixels + cbStride * i;

    ppng_write_rows(This->png_ptr, row_pointers, lineCount);
    This->lines_written += lineCount;

    LeaveCriticalSection(&This->lock);

    HeapFree(GetProcessHeap(), 0, row_pointers);

    return S_OK;
}
Exemplo n.º 4
0
static HRESULT WINAPI PngFrameEncode_WriteSource(IWICBitmapFrameEncode *iface,
    IWICBitmapSource *pIBitmapSource, WICRect *prc)
{
    PngEncoder *This = impl_from_IWICBitmapFrameEncode(iface);
    HRESULT hr;
    WICRect rc;
    WICPixelFormatGUID guid;
    UINT stride;
    BYTE *pixeldata;
    TRACE("(%p,%p,%p)\n", iface, pIBitmapSource, prc);

    if (!This->frame_initialized || !This->width || !This->height)
        return WINCODEC_ERR_WRONGSTATE;

    if (!This->format)
    {
        hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
        if (FAILED(hr)) return hr;
        hr = IWICBitmapFrameEncode_SetPixelFormat(iface, &guid);
        if (FAILED(hr)) return hr;
    }

    hr = IWICBitmapSource_GetPixelFormat(pIBitmapSource, &guid);
    if (FAILED(hr)) return hr;
    if (memcmp(&guid, This->format->guid, sizeof(GUID)) != 0)
    {
        /* FIXME: should use WICConvertBitmapSource to convert */
        ERR("format %s unsupported\n", debugstr_guid(&guid));
        return E_FAIL;
    }

    if (This->xres == 0.0 || This->yres == 0.0)
    {
        double xres, yres;
        hr = IWICBitmapSource_GetResolution(pIBitmapSource, &xres, &yres);
        if (FAILED(hr)) return hr;
        hr = IWICBitmapFrameEncode_SetResolution(iface, xres, yres);
        if (FAILED(hr)) return hr;
    }

    if (!prc)
    {
        UINT width, height;
        hr = IWICBitmapSource_GetSize(pIBitmapSource, &width, &height);
        if (FAILED(hr)) return hr;
        rc.X = 0;
        rc.Y = 0;
        rc.Width = width;
        rc.Height = height;
        prc = &rc;
    }

    if (prc->Width != This->width) return E_INVALIDARG;

    stride = (This->format->bpp * This->width + 7)/8;

    pixeldata = HeapAlloc(GetProcessHeap(), 0, stride * prc->Height);
    if (!pixeldata) return E_OUTOFMEMORY;

    hr = IWICBitmapSource_CopyPixels(pIBitmapSource, prc, stride,
        stride*prc->Height, pixeldata);

    if (SUCCEEDED(hr))
    {
        hr = IWICBitmapFrameEncode_WritePixels(iface, prc->Height, stride,
            stride*prc->Height, pixeldata);
    }

    HeapFree(GetProcessHeap(), 0, pixeldata);

    return hr;
}
//-----------------------------------------------------------------------------
static void load_paths_to_watch(LPCTSTR path, HANDLE completion_port_h) {
//-----------------------------------------------------------------------------
    FILE * stream_p;
    wchar_t *get_result;
    HANDLE create_result;
    size_t line_len;
    struct watch_entry **link_p;
    struct watch_entry * next_p;

    if (_wfopen_s(&stream_p, path, L"r, ccs=UTF-8")) {
        _wfopen_s(&error_file, error_path, L"w");
        _wcserror_s(error_buffer, ARRAYSIZE(error_buffer), errno); 
        fwprintf(
            error_file, 
            L"_wfopen(%s) failed: (%d) %s\n",  
            path,
            errno,
            error_buffer 
        );
        fclose(error_file);
        ExitProcess(2);
    }

    link_p = &watch_entry_list_p;
   
    while (1) {

        // create a watch entry
        next_p = (struct watch_entry *) HeapAlloc(
            GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct watch_entry)
        );
		if (next_p == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(200);
			}
        // read in the path to watch from config.txt
        get_result = \
            fgetws(full_file_name, ARRAYSIZE(full_file_name), stream_p);

        if (NULL == get_result) {
            if (0 == ferror(stream_p)) {
                HeapFree(GetProcessHeap(), 0, next_p);
                break;
            } 
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t) , errno
            ); 
            fwprintf(
                error_file, 
                L"fgetws(%s) failed: (%d) %s\n",  
                path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(2);
        }

        // clean out the newline, if there is one
        line_len = wcslen(full_file_name);
		if (line_len && full_file_name[line_len-1] == L'\n'){
			full_file_name[line_len-1] = L'\0';
			line_len--;
			}
        if (full_file_name[0] == L'\0')
           continue;
		next_p->dir_path_len = line_len;
		next_p->dir_path = (wchar_t *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			(line_len + 1) * sizeof(wchar_t));
		if (next_p->dir_path == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(201);
		}
		wcsncpy_s(next_p->dir_path, line_len+1, full_file_name, line_len);
		next_p->changes_buffer = (BYTE *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			CHANGES_BUFFER_SIZE);
		if (next_p->changes_buffer == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(202);
		}
        // 2020-09-05 dougfort -- we don't clean out trailing slash here
        // because if they are backing up something like c:\\, we need
        // the trailing slash. This will come back to bite us when we are
        // checking for excludes

        // open a file handle to watch the directory in overlapped mode
        next_p->hDirectory = CreateFile(
            next_p->dir_path,
            FILE_LIST_DIRECTORY,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            NULL,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
            NULL
        );

        // 2009-03-11 dougfort -- if we can't create this file, 
        // assume it is a top-level directory
        // which no longer exists; so ignore it and move on.
        if (INVALID_HANDLE_VALUE == next_p->hDirectory) {
            report_error(L"CreateFile", GetLastError());
            continue;
        }

        // add this file handle to the IO Complete port
        create_result = CreateIoCompletionPort(
            next_p->hDirectory,         // FileHandle,
            completion_port_h,          // ExistingCompletionPort,
            0,                          // CompletionKey,
            0                           // NumberOfConcurrentThreads
        );

        if (NULL == create_result) {
            report_error(L"CreateIOCompletionPort (add)", GetLastError());
            ExitProcess(102);
        }

        if (create_result != completion_port_h) {
            ExitProcess(103);
        }

        start_watch(next_p);

        // add this entry to the list
        *link_p = next_p;

        // point to the new entry's next pointer 
        link_p = &(*link_p)->next_p;
    } // while(1)

    fclose(stream_p);

} // load_paths_to_watch
//-----------------------------------------------------------------------------
static void load_paths_to_exclude(LPCTSTR path) {
//-----------------------------------------------------------------------------
    FILE * stream_p;
    wchar_t *get_result;
    size_t line_len;
    struct exclude_entry **link_p;
    struct exclude_entry * next_p;

    if (_wfopen_s(&stream_p, path, L"r, ccs=UTF-8")) {
        _wfopen_s(&error_file, error_path, L"w");
        _wcserror_s(error_buffer, sizeof error_buffer/sizeof(wchar_t), errno); 
        fwprintf(
            error_file, 
            L"_wfopen(%s) failed: (%d) %s\n",  
            path,
            errno,
            error_buffer 
        );
        fclose(error_file);
        ExitProcess(2);
    }

    link_p = &exclude_entry_list_p;
   
    while (1) {

        // create an exclude entry
        next_p = (struct exclude_entry *) HeapAlloc(
            GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct exclude_entry)
        );
		if (next_p == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(203);
			}
        // read in the path to watch from config.txt
        get_result = \
            fgetws(full_file_name, ARRAYSIZE(full_file_name), stream_p);

        if (NULL == get_result) {
            if (0 == ferror(stream_p)) {
                HeapFree(GetProcessHeap(), 0, next_p);
                break;
            } 
            _wfopen_s(&error_file, error_path, L"w");
            _wcserror_s(
               error_buffer, sizeof error_buffer/sizeof(wchar_t) , errno
            ); 
            fwprintf(
                error_file, 
                L"fgetws(%s) failed: (%d) %s\n",  
                path,
                errno,
                error_buffer 
            );
            fclose(error_file);
            ExitProcess(2);
        }

        // clean out the newline, if there is one
        line_len = wcslen(full_file_name);
		if (line_len && full_file_name[line_len-1] == L'\n'){
			full_file_name[line_len-1] = L'\0';
			line_len--;
			}
        if (full_file_name[0] == L'\0')
           continue;
		next_p->dir_path_len = line_len;
		next_p->dir_path = (wchar_t *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
			(line_len + 1) * sizeof(wchar_t));
		if (next_p->dir_path == NULL){
			report_error(L"HeapAlloc failed to allocate memory", GetLastError());
			ExitProcess(204);
		}
		wcsncpy_s(next_p->dir_path, line_len+1, full_file_name, line_len);
   
        // add this entry to the list
        *link_p = next_p;

        // point to the new entry's next pointer 
        link_p = &(*link_p)->next_p;
    } // while(1)

    fclose(stream_p);

} // load_paths_to_exclude
Exemplo n.º 7
0
void
SharedPortEndpoint::DoListenerAccept(ReliSock *return_remote_sock)
{
#ifdef WIN32
	dprintf(D_FULLDEBUG, "SharedPortEndpoint: Entered DoListenerAccept Win32 path.\n");
	ReliSock *remote_sock = return_remote_sock;
	if(!remote_sock)
	{
		remote_sock = new ReliSock;
	}
	EnterCriticalSection(&received_lock);
	if(!received_sockets.empty())
	{
		WSAPROTOCOL_INFO *received_socket = received_sockets.front();
		received_sockets.pop();
		LeaveCriticalSection(&received_lock);

		remote_sock->assign(received_socket);
		remote_sock->enter_connected_state();
		remote_sock->isClient(false);
		if(!return_remote_sock)
			daemonCore->HandleReqAsync(remote_sock);
		HeapFree(GetProcessHeap(), NULL, received_socket);
	}
	else
	{
		LeaveCriticalSection(&received_lock);
		dprintf(D_ALWAYS, "SharedPortEndpoint: DoListenerAccept: No connections, error.\n");
	}
#else
	ReliSock *accepted_sock = m_listener_sock.accept();

	if( !accepted_sock ) {
		dprintf(D_ALWAYS,
				"SharedPortEndpoint: failed to accept connection on %s\n",
				m_full_name.Value());
		return;
	}

		// Currently, instead of having daemonCore handle the command
		// for us, we read it here.  This means we only support the raw
		// command protocol.

	accepted_sock->decode();
	int cmd;
	if( !accepted_sock->get(cmd) ) {
		dprintf(D_ALWAYS,
				"SharedPortEndpoint: failed to read command on %s\n",
				m_full_name.Value());
		delete accepted_sock;
		return;
	}

	if( cmd != SHARED_PORT_PASS_SOCK ) {
		dprintf(D_ALWAYS,
				"SharedPortEndpoint: received unexpected command %d (%s) on named socket %s\n",
				cmd,
				getCommandString(cmd),
				m_full_name.Value());
		delete accepted_sock;
		return;
	}

	if( !accepted_sock->end_of_message() ) {
		dprintf(D_ALWAYS,
				"SharedPortEndpoint: failed to read end of message for cmd %s on %s\n",
				getCommandString(cmd),
				m_full_name.Value());
		delete accepted_sock;
		return;
	}

	dprintf(D_COMMAND|D_FULLDEBUG,
			"SharedPortEndpoint: received command %d SHARED_PORT_PASS_SOCK on named socket %s\n",
			cmd,
			m_full_name.Value());

	ReceiveSocket(accepted_sock,return_remote_sock);

	delete accepted_sock;
#endif
}
Exemplo n.º 8
0
/*
  The following function runs in its own thread.  We must therefore be
  very careful about what we do here.  Much of condor code is not
  thread-safe, so we cannot use it.

  Unfortunately, we observed deadlocks when dprintf() was used in the
  following function.  Therefore, dprintf is commented out.
*/
void
SharedPortEndpoint::PipeListenerThread()
{
	while(true)
	{
		// a bit wierd, but ConnectNamedPipe returns true on success. OR it
		// returns false and sets the error code to ERROR_PIPE_CONNECTED.
		if(!ConnectNamedPipe(pipe_end, NULL) && (GetLastError() != ERROR_PIPE_CONNECTED))
		{
			ThreadSafeLogError("SharedPortEndpoint: Client failed to connect", GetLastError());
			continue;
		}

		EnterCriticalSection(&kill_lock);
		if(kill_thread)
		{
			LeaveCriticalSection(&kill_lock);
			ThreadSafeLogError("SharedPortEndpoint: Listener thread received kill request.", 0);
			DisconnectNamedPipe(pipe_end);
			CloseHandle(pipe_end);
			DeleteCriticalSection(&kill_lock);
			return;
		}

		LeaveCriticalSection(&kill_lock);

		ThreadSafeLogError("SharedPortEndpoint: Pipe connected", 0);
		DWORD pID = GetProcessId(GetCurrentProcess());

		DWORD bytes_written;
		BOOL written = WriteFile(pipe_end,
			&pID,
			sizeof(DWORD),
			&bytes_written,
			0);
		
		if(!written || bytes_written != sizeof(DWORD))
		{
			DWORD error = GetLastError();
			//TODO: DO SOMETHING THREADSAFE HERE IN PLACE OF EXCEPT!!!!!!!!!!!!!!!!
			EXCEPT("SharedPortEndpoint: Failed to write PID, error value: %d", error);
		}
		//FlushFileBuffers(pipe_end);

		int expected = sizeof(WSAPROTOCOL_INFO) + sizeof(int);
		int buffSize = expected;
		char *readBuff = new char[buffSize];
		char *storeBuff = new char[buffSize];
		ZeroMemory(storeBuff, buffSize);
		DWORD bytes = 0;
		int total_received = 0;
		while(total_received < expected)
		{
//			dprintf(D_ALWAYS, "SharedPortEndpoint: Inside while loop trying to read data.\n");
			if(!ReadFile(pipe_end, readBuff, buffSize, &bytes, NULL))
			{
//				dprintf(D_ALWAYS, "SharedPortEndpoint: Failed to read data from named pipe: %d\n", GetLastError());
				break;
			}
			if(bytes < buffSize)
			{
//				dprintf(D_ALWAYS, "SharedPortEndpoint: Partial read: %d\n", bytes);
				memcpy_s(storeBuff + (expected - buffSize), buffSize, readBuff, bytes);
				total_received += bytes;
				buffSize -= bytes;
				delete [] readBuff;
				readBuff = new char[buffSize];
				continue;
			}

			//dprintf(D_ALWAYS, "SharedPortEndpoint: Read entirety of WSAPROTOCOL_INFO\n");

			//total_received += bytes;
			int destOffset = expected - buffSize;
			int destLeft = expected - total_received;
			//dprintf(D_ALWAYS, "SharedPortEndpoint: Read: %d Offset: %d Left: %d\n", bytes, destOffset, destLeft);
			memcpy_s(storeBuff + destOffset, destLeft, readBuff, bytes);
			int cmd;
			memcpy_s(&cmd, sizeof(int), storeBuff, sizeof(int));
			if( cmd != SHARED_PORT_PASS_SOCK ) {
				ThreadSafeLogError("SharedPortEndpoint: received unexpected command", cmd);
				break;
			}

			//WSAPROTOCOL_INFO protocol_info;
			WSAPROTOCOL_INFO *last_rec = (WSAPROTOCOL_INFO *)HeapAlloc(GetProcessHeap(), 0, sizeof(WSAPROTOCOL_INFO));
			memcpy_s(last_rec, sizeof(WSAPROTOCOL_INFO), storeBuff+sizeof(int), sizeof(WSAPROTOCOL_INFO));
			ThreadSafeLogError("SharedPortEndpoint: Copied WSAPROTOCOL_INFO", wake_select_dest ? 1 : 0);
			
			EnterCriticalSection(&received_lock);
			received_sockets.push(last_rec);
			LeaveCriticalSection(&received_lock);
			
			if(!wake_select_dest)
			{
				ThreadSafeLogError("SharedPortEndpoint: Registering Pump worker to move the socket", 0);
				int status = daemonCore->Register_PumpWork_TS(SharedPortEndpoint::PipeListenerHelper, this, NULL);
				ThreadSafeLogError("SharedPortEndpoint: back from Register_PumpWork_TS with status", status);
			}
			else
			{
				char wake[1];
				wake[0] = 'A';
				//wake_select_source->put_bytes(&wake, sizeof(int));
				//wake_select_source->end_of_message();
				int sock_fd = wake_select_source->get_file_desc();
				ThreadSafeLogError("SharedPortEndpoint:CCB client, writing to socket to wake select", sock_fd);
				int write_success = send(sock_fd, wake, sizeof(char), 0);
				//TODO: DO SOMETHING THREADSAFE HERE IN PLACE OF EXCEPT!!!!!!!!!!!!!!!!
				if(write_success == SOCKET_ERROR)
					EXCEPT("SharedPortEndpoint: Failed to write to select wakeup: %d", WSAGetLastError());
			}
			
			ThreadSafeLogError("SharedPortEndpoint: Finished reading from pipe", cmd);


			break;
		}
		delete [] readBuff;
		delete [] storeBuff;

		DisconnectNamedPipe(pipe_end);
	}
}
Exemplo n.º 9
0
/******************************************************************************
 * SetBitmapBits [GDI32.@]
 *
 * Sets bits of color data for a bitmap.
 *
 * RETURNS
 *    Success: Number of bytes used in setting the bitmap bits
 *    Failure: 0
 */
LONG WINAPI SetBitmapBits(
    HBITMAP hbitmap, /* [in] Handle to bitmap */
    LONG count,        /* [in] Number of bytes in bitmap array */
    LPCVOID bits)      /* [in] Address of array with bitmap bits */
{
    char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
    BITMAPINFO *info = (BITMAPINFO *)buffer;
    BITMAPOBJ *bmp;
    DWORD err;
    int i, src_stride, dst_stride;
    struct bitblt_coords src, dst;
    struct gdi_image_bits src_bits;
    HRGN clip = NULL;

    if (!bits) return 0;

    bmp = GDI_GetObjPtr( hbitmap, OBJ_BITMAP );
    if (!bmp) return 0;

    if (count < 0) {
	WARN("(%d): Negative number of bytes passed???\n", count );
	count = -count;
    }

    src_stride = get_bitmap_stride( bmp->dib.dsBm.bmWidth, bmp->dib.dsBm.bmBitsPixel );
    count = min( count, src_stride * bmp->dib.dsBm.bmHeight );

    dst_stride = get_dib_stride( bmp->dib.dsBm.bmWidth, bmp->dib.dsBm.bmBitsPixel );

    src.visrect.left   = src.x = 0;
    src.visrect.top    = src.y = 0;
    src.visrect.right  = src.width = bmp->dib.dsBm.bmWidth;
    src.visrect.bottom = src.height = (count + src_stride - 1 ) / src_stride;
    dst = src;

    if (count % src_stride)
    {
        HRGN last_row;
        int extra_pixels = ((count % src_stride) << 3) / bmp->dib.dsBm.bmBitsPixel;

        if ((count % src_stride << 3) % bmp->dib.dsBm.bmBitsPixel)
            FIXME( "Unhandled partial pixel\n" );
        clip = CreateRectRgn( src.visrect.left, src.visrect.top,
                              src.visrect.right, src.visrect.bottom - 1 );
        last_row = CreateRectRgn( src.visrect.left, src.visrect.bottom - 1,
                                  src.visrect.left + extra_pixels, src.visrect.bottom );
        CombineRgn( clip, clip, last_row, RGN_OR );
        DeleteObject( last_row );
    }

    TRACE("(%p, %d, %p) %dx%d %d bpp fetched height: %d\n",
          hbitmap, count, bits, bmp->dib.dsBm.bmWidth, bmp->dib.dsBm.bmHeight,
          bmp->dib.dsBm.bmBitsPixel, src.height );

    if (src_stride == dst_stride)
    {
        src_bits.ptr = (void *)bits;
        src_bits.is_copy = FALSE;
        src_bits.free = NULL;
    }
    else
    {
        if (!(src_bits.ptr = HeapAlloc( GetProcessHeap(), 0, dst.height * dst_stride )))
        {
            GDI_ReleaseObj( hbitmap );
            return 0;
        }
        src_bits.is_copy = TRUE;
        src_bits.free = free_heap_bits;
        for (i = 0; i < count / src_stride; i++)
            memcpy( (char *)src_bits.ptr + i * dst_stride, (char *)bits + i * src_stride, src_stride );
        if (count % src_stride)
            memcpy( (char *)src_bits.ptr + i * dst_stride, (char *)bits + i * src_stride, count % src_stride );
    }

    /* query the color info */
    info->bmiHeader.biSize          = sizeof(info->bmiHeader);
    info->bmiHeader.biPlanes        = 1;
    info->bmiHeader.biBitCount      = bmp->dib.dsBm.bmBitsPixel;
    info->bmiHeader.biCompression   = BI_RGB;
    info->bmiHeader.biXPelsPerMeter = 0;
    info->bmiHeader.biYPelsPerMeter = 0;
    info->bmiHeader.biClrUsed       = 0;
    info->bmiHeader.biClrImportant  = 0;
    info->bmiHeader.biWidth         = 0;
    info->bmiHeader.biHeight        = 0;
    info->bmiHeader.biSizeImage     = 0;
    err = put_image_into_bitmap( bmp, 0, info, NULL, NULL, NULL );

    if (!err || err == ERROR_BAD_FORMAT)
    {
        info->bmiHeader.biWidth     = bmp->dib.dsBm.bmWidth;
        info->bmiHeader.biHeight    = -dst.height;
        info->bmiHeader.biSizeImage = dst.height * dst_stride;
        err = put_image_into_bitmap( bmp, clip, info, &src_bits, &src, &dst );
    }
    if (err) count = 0;

    if (clip) DeleteObject( clip );
    if (src_bits.free) src_bits.free( &src_bits );
    GDI_ReleaseObj( hbitmap );
    return count;
}
Exemplo n.º 10
0
/******************************************************************************
 * CreateBitmapIndirect [GDI32.@]
 *
 * Creates a bitmap with the specified info.
 *
 * PARAMS
 *  bmp [I] Pointer to the bitmap info describing the bitmap
 *
 * RETURNS
 *    Success: Handle to bitmap
 *    Failure: NULL. Use GetLastError() to determine the cause.
 *
 * NOTES
 *  If a width or height of 0 are given, a 1x1 monochrome bitmap is returned.
 */
HBITMAP WINAPI CreateBitmapIndirect( const BITMAP *bmp )
{
    BITMAP bm;
    BITMAPOBJ *bmpobj;
    HBITMAP hbitmap;

    if (!bmp || bmp->bmType)
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return NULL;
    }

    if (bmp->bmWidth > 0x7ffffff || bmp->bmHeight > 0x7ffffff)
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }

    bm = *bmp;

    if (!bm.bmWidth || !bm.bmHeight)
    {
        return GetStockObject( DEFAULT_BITMAP );
    }
    else
    {
        if (bm.bmHeight < 0)
            bm.bmHeight = -bm.bmHeight;
        if (bm.bmWidth < 0)
            bm.bmWidth = -bm.bmWidth;
    }

    if (bm.bmPlanes != 1)
    {
        FIXME("planes = %d\n", bm.bmPlanes);
        SetLastError( ERROR_INVALID_PARAMETER );
        return NULL;
    }

    /* Windows only uses 1, 4, 8, 16, 24 and 32 bpp */
    if(bm.bmBitsPixel == 1)         bm.bmBitsPixel = 1;
    else if(bm.bmBitsPixel <= 4)    bm.bmBitsPixel = 4;
    else if(bm.bmBitsPixel <= 8)    bm.bmBitsPixel = 8;
    else if(bm.bmBitsPixel <= 16)   bm.bmBitsPixel = 16;
    else if(bm.bmBitsPixel <= 24)   bm.bmBitsPixel = 24;
    else if(bm.bmBitsPixel <= 32)   bm.bmBitsPixel = 32;
    else {
        WARN("Invalid bmBitsPixel %d, returning ERROR_INVALID_PARAMETER\n", bm.bmBitsPixel);
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }

    /* Windows ignores the provided bm.bmWidthBytes */
    bm.bmWidthBytes = get_bitmap_stride( bm.bmWidth, bm.bmBitsPixel );
    /* XP doesn't allow to create bitmaps larger than 128 Mb */
    if (bm.bmHeight > 128 * 1024 * 1024 / bm.bmWidthBytes)
    {
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
        return 0;
    }

    /* Create the BITMAPOBJ */
    if (!(bmpobj = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*bmpobj) )))
    {
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
        return 0;
    }

    bmpobj->dib.dsBm = bm;
    bmpobj->dib.dsBm.bmBits = NULL;

    if (!(hbitmap = alloc_gdi_handle( bmpobj, OBJ_BITMAP, &bitmap_funcs )))
    {
        HeapFree( GetProcessHeap(), 0, bmpobj );
        return 0;
    }

    if (bm.bmBits)
        SetBitmapBits( hbitmap, bm.bmHeight * bm.bmWidthBytes, bm.bmBits );

    TRACE("%dx%d, bpp %d planes %d: returning %p\n", bm.bmWidth, bm.bmHeight,
          bm.bmBitsPixel, bm.bmPlanes, hbitmap);

    return hbitmap;
}
Exemplo n.º 11
0
static void NoStatStreamImpl_Destroy(NoStatStreamImpl* This)
{
  GlobalFree(This->supportHandle);
  This->supportHandle=0;
  HeapFree(GetProcessHeap(), 0, This);
}