OSStatus
CConfigPropertySheet::SetupRegistryNotifications()
{
	unsigned int	threadId;
	OSStatus		err;

	check( m_threadExited == NULL );
	check( m_thread == NULL );

	err = RegCreateKey( HKEY_LOCAL_MACHINE, kServiceParametersNode L"\\DynDNS\\State\\Hostnames", &m_statusKey );
	require_noerr( err, exit );
	
	m_threadExited = CreateEvent( NULL, FALSE, FALSE, NULL );
	err = translate_errno( m_threadExited, (OSStatus) GetLastError(), kUnknownErr );
	require_noerr( err, exit );

	// Create thread with _beginthreadex() instead of CreateThread() to avoid memory leaks when using static run-time 
	// libraries. See <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createthread.asp>.
	
	m_thread = (HANDLE) _beginthreadex_compat( NULL, 0, WatchRegistry, this, 0, &threadId );
	err = translate_errno( m_thread, (OSStatus) GetLastError(), kUnknownErr );
	require_noerr( err, exit );

exit:

	if ( err )
	{
		TearDownRegistryNotifications();
	}

	return err;
}
Пример #2
0
DEBUG_LOCAL OSStatus	EnableNSP( const char *inGUID, BOOL inEnable )
{
	OSStatus		err;
	WSADATA			wsd;
	GUID			guid;
	
	require_action( inGUID && ( *inGUID != '\0' ), exit, err = kParamErr );
	
	err = StringToGUID( inGUID, &guid );
	require_noerr( err, exit );
	
	err = WSAStartup( MAKEWORD( 2, 2 ), &wsd );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	
	err = WSCEnableNSProvider( &guid, inEnable );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	WSACleanup();
	require_noerr( err, exit );
	
	if (!gToolQuietMode)
	{
		fprintf( stderr, "Removed NSP %s\n", inGUID );
	}
		
exit:
	if( err != kNoErr )
	{
		fprintf( stderr, "### FAILED (%d) to remove %s Name Space Provider\n", err, inGUID );
	}
	return( err );
}
Пример #3
0
mDNSlocal OSStatus
MakeUTF8StringFromLsaString( char * output, size_t len, PLSA_UNICODE_STRING input )
{
    size_t		size;
    OSStatus	err = kNoErr;

    // The Length field of this structure holds the number of bytes,
    // but WideCharToMultiByte expects the number of wchar_t's. So
    // we divide by sizeof(wchar_t) to get the correct number.

    size = (size_t) WideCharToMultiByte(CP_UTF8, 0, input->Buffer, ( input->Length / sizeof( wchar_t ) ), NULL, 0, NULL, NULL);
    err = translate_errno( size != 0, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    // Ensure that we have enough space (Add one for trailing '\0')

    require_action( ( size + 1 ) <= len, exit, err = mStatus_NoMemoryErr );

    // Convert the string

    size = (size_t) WideCharToMultiByte( CP_UTF8, 0, input->Buffer, ( input->Length / sizeof( wchar_t ) ), output, (int) size, NULL, NULL);
    err = translate_errno( size != 0, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    // have to add the trailing 0 because WideCharToMultiByte doesn't do it,
    // although it does return the correct size

    output[size] = '\0';

exit:

    return err;
}
Пример #4
0
OSStatus
CSecondPage::LoadPrinterNames()
{
	PBYTE		buffer	=	NULL;
	OSStatus	err		= 0;

	//
	// rdar://problem/3701926 - Printer can't be installed twice
	//
	// First thing we want to do is make sure the printer isn't already installed.
	// If the printer name is found, we'll try and rename it until we
	// find a unique name
	//
	DWORD dwNeeded = 0, dwNumPrinters = 0;

	BOOL ok = EnumPrinters(PRINTER_ENUM_LOCAL, NULL, 4, NULL, 0, &dwNeeded, &dwNumPrinters);
	err = translate_errno( ok, errno_compat(), kUnknownErr );

	if ((err == ERROR_INSUFFICIENT_BUFFER) && (dwNeeded > 0))
	{
		try
		{
			buffer = new unsigned char[dwNeeded];
		}
		catch (...)
		{
			buffer = NULL;
		}
	
		require_action( buffer, exit, kNoMemoryErr );
		ok = EnumPrinters(PRINTER_ENUM_LOCAL, NULL, 4, buffer, dwNeeded, &dwNeeded, &dwNumPrinters);
		err = translate_errno( ok, errno_compat(), kUnknownErr );
		require_noerr( err, exit );

		for (DWORD index = 0; index < dwNumPrinters; index++)
		{
			PRINTER_INFO_4 * lppi4 = (PRINTER_INFO_4*) (buffer + index * sizeof(PRINTER_INFO_4));

			m_printerNames[lppi4->pPrinterName] = lppi4->pPrinterName;
		}
	}

exit:

	if (buffer != NULL)
	{
		delete [] buffer;
	}

	return err;
}
Пример #5
0
int storage_file_set_size(struct storage_msg *msg,
                          const void *r, size_t req_len)
{
    const struct storage_file_set_size_req *req = r;

    if (req_len != sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd != %zd)\n",
              __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    int fd = lookup_fd(req->handle, true);
    int rc = TEMP_FAILURE_RETRY(ftruncate(fd, req->size));
    if (rc < 0) {
        rc = errno;
        ALOGE("%s: error truncating file (fd=%d): %s\n",
              __func__, fd, strerror(errno));
        msg->result = translate_errno(rc);
        goto err_response;
    }

    msg->result = STORAGE_NO_ERROR;

err_response:
    return ipc_respond(msg, NULL, 0);
}
OSStatus
CPrinterSetupWizardSheet::InstallPrinterIPP(Printer * printer, Service * service)
{
	DEBUG_UNUSED( service );

	HANDLE			hPrinter = NULL;
	PRINTER_INFO_2	pInfo;
	OSStatus		err;
	
	//
	// add the printer
	//
	ZeroMemory(&pInfo, sizeof(PRINTER_INFO_2));
	
	pInfo.pPrinterName		= printer->actualName.GetBuffer();
	pInfo.pPortName			= printer->portName.GetBuffer();
	pInfo.pDriverName		= printer->model.GetBuffer();
	pInfo.pPrintProcessor	= L"winprint";
	pInfo.pLocation			= service->location.GetBuffer();
	pInfo.Attributes		= PRINTER_ATTRIBUTE_NETWORK | PRINTER_ATTRIBUTE_LOCAL;
	
	hPrinter = AddPrinter(NULL, 2, (LPBYTE)&pInfo);
	err = translate_errno( hPrinter, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

exit:

	if ( hPrinter != NULL )
	{
		ClosePrinter(hPrinter);
	}

	return err;
}
Пример #7
0
int storage_file_get_size(struct storage_msg *msg,
                          const void *r, size_t req_len)
{
    const struct storage_file_get_size_req *req = r;
    struct storage_file_get_size_resp resp = {0};

    if (req_len != sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd != %zd)\n",
              __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    struct stat stat;
    int fd = lookup_fd(req->handle, false);
    int rc = fstat(fd, &stat);
    if (rc < 0) {
        rc = errno;
        ALOGE("%s: error stat'ing file (fd=%d): %s\n",
              __func__, fd, strerror(errno));
        msg->result = translate_errno(rc);
        goto err_response;
    }

    resp.size = stat.st_size;
    msg->result = STORAGE_NO_ERROR;
    return ipc_respond(msg, &resp, sizeof(resp));

err_response:
    return ipc_respond(msg, NULL, 0);
}
Пример #8
0
int storage_file_write(struct storage_msg *msg,
                       const void *r, size_t req_len)
{
    int rc;
    const struct storage_file_write_req *req = r;

    if (req_len < sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd < %zd)\n",
              __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    int fd = lookup_fd(req->handle, true);
    if (write_with_retry(fd, &req->data[0], req_len - sizeof(*req),
                         req->offset) < 0) {
        rc = errno;
        ALOGW("%s: error writing file (fd=%d): %s\n",
              __func__, fd, strerror(errno));
        msg->result = translate_errno(rc);
        goto err_response;
    }

    msg->result = STORAGE_NO_ERROR;

err_response:
    return ipc_respond(msg, NULL, 0);
}
Пример #9
0
OSStatus	InstallNSP( const char *inName, const char *inGUID, const char *inPath )
{
	OSStatus		err;
	size_t			size;
	WSADATA			wsd;
	WCHAR			name[ 256 ];
	GUID			guid;
	WCHAR			path[ MAX_PATH ];
	
	require_action( inName && ( *inName != '\0' ), exit, err = kParamErr );
	require_action( inGUID && ( *inGUID != '\0' ), exit, err = kParamErr );
	require_action( inPath && ( *inPath != '\0' ), exit, err = kParamErr );
	
	size = strlen( inName );
	require_action( size < sizeof_array( name ), exit, err = kSizeErr );
	CharToWCharString( inName, name );
	
	err = StringToGUID( inGUID, &guid );
	require_noerr( err, exit );
	
	size = strlen( inPath );
	require_action( size < sizeof_array( path ), exit, err = kSizeErr );
	CharToWCharString( inPath, path );
	
	err = WSAStartup( MAKEWORD( 2, 2 ), &wsd );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	
	err = WSCInstallNameSpace( name, path, NS_DNS, 1, &guid );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	WSACleanup();
	require_noerr( err, exit );
	
	if (!gToolQuietMode)
	{
		fprintf( stderr, "Installed NSP \"%s\" (%s) at %s\n", inName, inGUID, inPath );
	}
	
exit:
	if( err != kNoErr )
	{
		fprintf( stderr, "### FAILED (%d) to install \"%s\" (%s) Name Space Provider at %s\n", err, inName, inGUID, inPath );
	}
	return( err );
}
Пример #10
0
int storage_file_delete(struct storage_msg *msg,
                        const void *r, size_t req_len)
{
    char *path = NULL;
    const struct storage_file_delete_req *req = r;

    if (req_len < sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd < %zd)\n",
              __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    size_t fname_len = strlen(req->name);
    if (fname_len != req_len - sizeof(*req)) {
        ALOGE("%s: invalid filename length (%zd != %zd)\n",
              __func__, fname_len, req_len - sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    int rc = asprintf(&path, "%s/%s", ssdir_name, req->name);
    if (rc < 0) {
        ALOGE("%s: asprintf failed\n", __func__);
        msg->result = STORAGE_ERR_GENERIC;
        goto err_response;
    }

    dir_state = SS_DIRTY;
    rc = unlink(path);
    if (rc < 0) {
        rc = errno;
        if (errno == ENOENT) {
            ALOGV("%s: error (%d) unlinking file '%s'\n",
                  __func__, rc, path);
        } else {
            ALOGE("%s: error (%d) unlinking file '%s'\n",
                  __func__, rc, path);
        }
        msg->result = translate_errno(rc);
        goto err_response;
    }

    ALOGV("%s: \"%s\"\n", __func__, path);
    msg->result = STORAGE_NO_ERROR;

err_response:
    if (path)
        free(path);
    return ipc_respond(msg, NULL, 0);
}
Пример #11
0
mDNSlocal OSStatus
MakeLsaStringFromUTF8String( PLSA_UNICODE_STRING output, const char * input )
{
    int			size;
    OSStatus	err;

    check( input );
    check( output );

    output->Buffer = NULL;

    size = MultiByteToWideChar( CP_UTF8, 0, input, -1, NULL, 0 );
    err = translate_errno( size > 0, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    output->Length = (USHORT)( size * sizeof( wchar_t ) );
    output->Buffer = (PWCHAR) malloc( output->Length );
    require_action( output->Buffer, exit, err = mStatus_NoMemoryErr );
    size = MultiByteToWideChar( CP_UTF8, 0, input, -1, output->Buffer, size );
    err = translate_errno( size > 0, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    // We're going to subtrace one wchar_t from the size, because we didn't
    // include it when we encoded the string

    output->MaximumLength = output->Length;
    output->Length		-= sizeof( wchar_t );

exit:

    if ( err && output->Buffer )
    {
        free( output->Buffer );
        output->Buffer = NULL;
    }

    return( err );
}
Пример #12
0
int storage_file_close(struct storage_msg *msg,
                       const void *r, size_t req_len)
{
    const struct storage_file_close_req *req = r;

    if (req_len != sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd != %zd)\n",
              __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    int fd = remove_fd(req->handle);
    ALOGV("%s: handle = %u: fd = %u\n", __func__, req->handle, fd);

    int rc = fsync(fd);
    if (rc < 0) {
        rc = errno;
        ALOGE("%s: fsync failed for fd=%u: %s\n",
              __func__, fd, strerror(errno));
        msg->result = translate_errno(rc);
        goto err_response;
    }

    rc = close(fd);
    if (rc < 0) {
        rc = errno;
        ALOGE("%s: close failed for fd=%u: %s\n",
              __func__, fd, strerror(errno));
        msg->result = translate_errno(rc);
        goto err_response;
    }

    msg->result = STORAGE_NO_ERROR;

err_response:
    return ipc_respond(msg, NULL, 0);
}
OSStatus
StringObjectToUTF8String( CString &inObject, char* outUTF8, size_t outUTF8Len )
{
    OSStatus err = kNoErr;

	memset( outUTF8, 0, outUTF8Len );

	if ( inObject.GetLength() > 0 )
    {
		size_t size;

		size = (size_t) WideCharToMultiByte( CP_UTF8, 0, inObject.GetBuffer(), inObject.GetLength(), outUTF8, (int) outUTF8Len, NULL, NULL);
        err = translate_errno( size != 0, GetLastError(), kUnknownErr );
        require_noerr( err, exit );
    }

exit:

	return err;
}
Пример #14
0
int storage_file_read(struct storage_msg *msg,
                      const void *r, size_t req_len)
{
    int rc;
    const struct storage_file_read_req *req = r;

    if (req_len != sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd != %zd)\n",
              __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    if (req->size > MAX_READ_SIZE) {
        ALOGW("%s: request is too large (%u > %d) - refusing\n",
              __func__, req->size, MAX_READ_SIZE);
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    int fd = lookup_fd(req->handle, false);
    ssize_t read_res = read_with_retry(fd, read_rsp.hdr.data, req->size,
                                       (off_t)req->offset);
    if (read_res < 0) {
        rc = errno;
        ALOGW("%s: error reading file (fd=%d): %s\n",
              __func__, fd, strerror(errno));
        msg->result = translate_errno(rc);
        goto err_response;
    }

    msg->result = STORAGE_NO_ERROR;
    return ipc_respond(msg, &read_rsp, read_res + sizeof(read_rsp.hdr));

err_response:
    return ipc_respond(msg, NULL, 0);
}
Пример #15
0
CThirdPage::CThirdPage()
    : CPropertyPage(CThirdPage::IDD),
      m_manufacturerSelected( NULL ),
      m_modelSelected( NULL ),
      m_genericPostscript( NULL ),
      m_genericPCL( NULL ),
      m_initialized(false),
      m_printerImage( NULL )
{
    static const int	bufferSize	= 32768;
    TCHAR				windowsDirectory[bufferSize];
    CString				header;
    WIN32_FIND_DATA		findFileData;
    HANDLE				findHandle;
    CString				prnFiles;
    CString				ntPrint;
    OSStatus			err;
    BOOL				ok;

    m_psp.dwFlags &= ~(PSP_HASHELP);
    m_psp.dwFlags |= PSP_DEFAULT|PSP_USEHEADERTITLE|PSP_USEHEADERSUBTITLE;

    m_psp.pszHeaderTitle = MAKEINTRESOURCE(IDS_INSTALL_TITLE);
    m_psp.pszHeaderSubTitle = MAKEINTRESOURCE(IDS_INSTALL_SUBTITLE);

    //
    // load printers from ntprint.inf
    //
    ok = GetWindowsDirectory( windowsDirectory, bufferSize );
    err = translate_errno( ok, errno_compat(), kUnknownErr );
    require_noerr( err, exit );

    //
    // <rdar://problem/4826126>
    //
    // If there are no *prn.inf files, we'll assume that the information
    // is in ntprint.inf
    //
    prnFiles.Format( L"%s\\%s", windowsDirectory, kVistaPrintFiles );
    findHandle = FindFirstFile( prnFiles, &findFileData );

    if ( findHandle != INVALID_HANDLE_VALUE )
    {
        CString absolute;

        absolute.Format( L"%s\\inf\\%s", windowsDirectory, findFileData.cFileName );
        err = LoadPrintDriverDefsFromFile( m_manufacturers, absolute, false );
        require_noerr( err, exit );

        while ( FindNextFile( findHandle, &findFileData ) )
        {
            absolute.Format( L"%s\\inf\\%s", windowsDirectory, findFileData.cFileName );
            err = LoadPrintDriverDefsFromFile( m_manufacturers, absolute, false );
            require_noerr( err, exit );
        }

        FindClose( findHandle );
    }
    else
    {
        ntPrint.Format(L"%s\\%s", windowsDirectory, kNTPrintFile);
        err = LoadPrintDriverDefsFromFile( m_manufacturers, ntPrint, false );
        require_noerr(err, exit);
    }

    //
    // load printer drivers that have been installed on this machine
    //
    err = LoadPrintDriverDefs( m_manufacturers );
    require_noerr(err, exit);

    //
    // load our own special generic printer defs
    //
    err = LoadGenericPrintDriverDefs( m_manufacturers );
    require_noerr( err, exit );

exit:

    return;
}
Пример #16
0
// -------------------------------------------------------
// LoadPrintDriverDefs
//
// This function is responsible for loading the print driver
// definitions of all print drivers that have been installed
// on this machine.
// -------------------------------------------------------
OSStatus
CThirdPage::LoadPrintDriverDefs( Manufacturers & manufacturers )
{
    BYTE	*	buffer			=	NULL;
    DWORD		bytesReceived	=	0;
    DWORD		numPrinters		=	0;
    OSStatus	err				=	0;
    BOOL		ok;

    //
    // like a lot of win32 calls, we call this first to get the
    // size of the buffer we need.
    //
    EnumPrinterDrivers(NULL, L"all", 6, NULL, 0, &bytesReceived, &numPrinters);

    if (bytesReceived > 0)
    {
        try
        {
            buffer = new BYTE[bytesReceived];
        }
        catch (...)
        {
            buffer = NULL;
        }

        require_action( buffer, exit, err = kNoMemoryErr );

        //
        // this call gets the real info
        //
        ok = EnumPrinterDrivers(NULL, L"all", 6, buffer, bytesReceived, &bytesReceived, &numPrinters);
        err = translate_errno( ok, errno_compat(), kUnknownErr );
        require_noerr( err, exit );

        DRIVER_INFO_6 * info = (DRIVER_INFO_6*) buffer;

        for (DWORD i = 0; i < numPrinters; i++)
        {
            Manufacturer	*	manufacturer;
            Model			*	model;
            CString				name;

            //
            // skip over anything that doesn't have a manufacturer field.  This
            // fixes a bug that I noticed that occurred after I installed
            // ProComm.  This program add a print driver with no manufacturer
            // that screwed up this wizard.
            //
            if (info[i].pszMfgName == NULL)
            {
                continue;
            }

            //
            // look for manufacturer
            //
            Manufacturers::iterator iter;

            //
            // save the name
            //
            name = NormalizeManufacturerName( info[i].pszMfgName );

            iter = manufacturers.find(name);

            if (iter != manufacturers.end())
            {
                manufacturer = iter->second;
            }
            else
            {
                try
                {
                    manufacturer = new Manufacturer;
                }
                catch (...)
                {
                    manufacturer = NULL;
                }

                require_action( manufacturer, exit, err = kNoMemoryErr );

                manufacturer->name	=	name;

                manufacturers[name]	=	manufacturer;
            }

            //
            // now look to see if we have already seen this guy.  this could
            // happen if we have already installed printers that are described
            // in ntprint.inf.  the extant drivers will show up in EnumPrinterDrivers
            // but we have already loaded their info
            //
            //
            if ( MatchModel( manufacturer, ConvertToModelName( info[i].pName ) ) == NULL )
            {
                try
                {
                    model = new Model;
                }
                catch (...)
                {
                    model = NULL;
                }

                require_action( model, exit, err = kNoMemoryErr );

                model->displayName		=	info[i].pName;
                model->name				=	info[i].pName;
                model->driverInstalled	=	true;

                manufacturer->models.push_back(model);
            }
        }
    }

exit:

    if (buffer != NULL)
    {
        delete [] buffer;
    }

    return err;
}
Пример #17
0
OSStatus
CThirdPage::LoadPrintDriverDefsFromFile(Manufacturers & manufacturers, const CString & filename, bool checkForDuplicateModels )
{
    HINF			handle	= INVALID_HANDLE_VALUE;
    const TCHAR *	section = TEXT( "Manufacturer" );
    LONG			sectionCount;
    TCHAR			line[ 1000 ];
    CString			klass;
    INFCONTEXT		manufacturerContext;
    BOOL			ok;
    OSStatus		err		= 0;

    // Make sure we can open the file
    handle = SetupOpenInfFile( filename, NULL, INF_STYLE_WIN4, NULL );
    translate_errno( handle != INVALID_HANDLE_VALUE, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    // Make sure it's a printer file
    ok = SetupGetLineText( NULL, handle, TEXT( "Version" ), TEXT( "Class" ), line, sizeof( line ), NULL );
    translate_errno( ok, GetLastError(), kUnknownErr );
    require_noerr( err, exit );
    klass = line;
    require_action( klass == TEXT( "Printer" ), exit, err = kUnknownErr );

    sectionCount = SetupGetLineCount( handle, section );
    translate_errno( sectionCount != -1, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    memset( &manufacturerContext, 0, sizeof( manufacturerContext ) );

    for ( LONG i = 0; i < sectionCount; i++ )
    {
        Manufacturers::iterator	iter;
        Manufacturer	*	manufacturer;
        CString				manufacturerName;
        CString				temp;
        CStringList			modelSectionNameDecl;
        CString				modelSectionName;
        CString				baseModelName;
        CString				model;
        INFCONTEXT			modelContext;
        LONG				modelCount;
        POSITION			p;

        if ( i == 0 )
        {
            ok = SetupFindFirstLine( handle, section, NULL, &manufacturerContext );
            err = translate_errno( ok, GetLastError(), kUnknownErr );
            require_noerr( err, exit );
        }
        else
        {
            ok = SetupFindNextLine( &manufacturerContext, &manufacturerContext );
            err = translate_errno( ok, GetLastError(), kUnknownErr );
            require_noerr( err, exit );
        }

        ok = SetupGetStringField( &manufacturerContext, 0, line, sizeof( line ), NULL );
        err = translate_errno( ok, GetLastError(), kUnknownErr );
        require_noerr( err, exit );
        manufacturerName = line;

        ok = SetupGetLineText( &manufacturerContext, handle, NULL, NULL, line, sizeof( line ), NULL );
        err = translate_errno( ok, GetLastError(), kUnknownErr );
        require_noerr( err, exit );

        // Try to find some model section name that has entries. Explanation of int file structure
        // can be found at:
        //
        // <http://msdn.microsoft.com/en-us/library/ms794359.aspx>
        Split( line, ',', modelSectionNameDecl );

        p					= modelSectionNameDecl.GetHeadPosition();
        modelSectionName	= modelSectionNameDecl.GetNext( p );
        modelCount			= SetupGetLineCount( handle, modelSectionName );
        baseModelName		= modelSectionName;

        while ( modelCount <= 0 && p )
        {
            CString targetOSVersion;

            targetOSVersion		= modelSectionNameDecl.GetNext( p );
            modelSectionName	= baseModelName + TEXT( "." ) + targetOSVersion;
            modelCount			= SetupGetLineCount( handle, modelSectionName );
        }

        if ( modelCount > 0 )
        {
            manufacturerName = NormalizeManufacturerName( manufacturerName );

            iter = manufacturers.find( manufacturerName );

            if ( iter != manufacturers.end() )
            {
                manufacturer = iter->second;
                require_action( manufacturer, exit, err = kUnknownErr );
            }
            else
            {
                try
                {
                    manufacturer = new Manufacturer;
                }
                catch (...)
                {
                    manufacturer = NULL;
                }

                require_action( manufacturer, exit, err = kNoMemoryErr );

                manufacturer->name					= manufacturerName;
                manufacturers[ manufacturerName ]	= manufacturer;
            }

            memset( &modelContext, 0, sizeof( modelContext ) );

            for ( LONG j = 0; j < modelCount; j++ )
            {
                CString modelName;
                Model * model;

                if ( j == 0 )
                {
                    ok = SetupFindFirstLine( handle, modelSectionName, NULL, &modelContext );
                    err = translate_errno( ok, GetLastError(), kUnknownErr );
                    require_noerr( err, exit );
                }
                else
                {
                    SetupFindNextLine( &modelContext, &modelContext );
                    err = translate_errno( ok, GetLastError(), kUnknownErr );
                    require_noerr( err, exit );
                }

                ok = SetupGetStringField( &modelContext, 0, line, sizeof( line ), NULL );
                err = translate_errno( ok, GetLastError(), kUnknownErr );
                require_noerr( err, exit );

                modelName = line;

                if (checkForDuplicateModels == true)
                {
                    if ( MatchModel( manufacturer, ConvertToModelName( modelName ) ) != NULL )
                    {
                        continue;
                    }
                }

                //
                // Stock Vista printer inf files embed guids in the model
                // declarations for Epson printers. Let's ignore those.
                //
                if ( modelName.Find( TEXT( "{" ), 0 ) != -1 )
                {
                    continue;
                }

                try
                {
                    model = new Model;
                }
                catch (...)
                {
                    model = NULL;
                }

                require_action( model, exit, err = kNoMemoryErr );

                model->infFileName		=	filename;
                model->displayName		=	modelName;
                model->name				=	modelName;
                model->driverInstalled	=	false;

                manufacturer->models.push_back(model);
            }
        }
    }

exit:

    if ( handle != INVALID_HANDLE_VALUE )
    {
        SetupCloseInfFile( handle );
        handle = NULL;
    }

    return err;
}
Пример #18
0
DEBUG_LOCAL OSStatus	ReorderNameSpaces( void )
{
	OSStatus				err;
	WSADATA					wsd;
	bool					started;
	int						n;
	int						i;
	DWORD					size;
	WSANAMESPACE_INFO *		array;
	WCHAR					name[ 256 ];
	WCHAR					path[ MAX_PATH ];
	
	array 	= NULL;
	started	= false;
		
	err = WSAStartup( MAKEWORD( 2, 2 ), &wsd );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	started = true;
	
	// Build an array of all the NSPs. Call it first with NULL to get the size, allocate a buffer, then get them into it.
	
	size = 0;
	n = WSAEnumNameSpaceProviders( &size, NULL );
	err = translate_errno( n != SOCKET_ERROR, (OSStatus) GetLastError(), kUnknownErr );
	require_action( err == WSAEFAULT, exit, err = kUnknownErr );
	
	array = (WSANAMESPACE_INFO *) malloc( size );
	require_action( array, exit, err = kNoMemoryErr );
	
	n = WSAEnumNameSpaceProviders( &size, array );
	err = translate_errno( n != SOCKET_ERROR, (OSStatus) GetLastError(), kUnknownErr );
	require_noerr( err, exit );
	
	// Find the "Tcpip" NSP.
	
	for( i = 0; i < n; ++i )
	{
		if( strcmp( array[ i ].lpszIdentifier, "Tcpip" ) == 0 )
		{
			break;
		}
	}
	require_action( i < n, exit, err = kNotFoundErr );
	
	// Uninstall it then re-install it to move it to the end.
	
	size = (DWORD) strlen( array[ i ].lpszIdentifier );
	require_action( size < sizeof_array( name ), exit, err = kSizeErr );
	CharToWCharString( array[ i ].lpszIdentifier, name );
	
	size = (DWORD) strlen( "%SystemRoot%\\System32\\mswsock.dll" );
	require_action( size < sizeof_array( path ), exit, err = kSizeErr );
	CharToWCharString( "%SystemRoot%\\System32\\mswsock.dll", path );
	
	err = WSCUnInstallNameSpace( &array[ i ].NSProviderId );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	
	err = WSCInstallNameSpace( name, path, NS_DNS, array[ i ].dwVersion, &array[ i ].NSProviderId );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
		
	// Success!
	
	fprintf( stderr, "Reordered \"Tcpip\" NSP to to the bottom of the NSP chain\n" );	
	err = kNoErr;
	
exit:
	if( array )
	{
		free( array );
	}
	if( started )
	{
		WSACleanup();
	}
	if( err != kNoErr )
	{
		fprintf( stderr, "### FAILED (%d) to reorder Name Space Providers\n", err );
	}
	return( err );
}
Пример #19
0
DEBUG_LOCAL OSStatus	ListNameSpaces( void )
{
	OSStatus				err;
	WSADATA					wsd;
	bool					started;
	int						n;
	int						i;
	DWORD					size;
	WSANAMESPACE_INFO *		array;
	char					s[ 256 ];
	
	array 	= NULL;
	started	= false;
	
	err = WSAStartup( MAKEWORD( 2, 2 ), &wsd );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	started = true;
	
	// Build an array of all the NSPs. Call it first with NULL to get the size, allocate a buffer, then get them into it.
	
	size = 0;
	n = WSAEnumNameSpaceProviders( &size, NULL );
	err = translate_errno( n != SOCKET_ERROR, (OSStatus) GetLastError(), kUnknownErr );
	require_action( err == WSAEFAULT, exit, err = kUnknownErr );
	
	array = (WSANAMESPACE_INFO *) malloc( size );
	require_action( array, exit, err = kNoMemoryErr );
	
	n = WSAEnumNameSpaceProviders( &size, array );
	err = translate_errno( n != SOCKET_ERROR, (OSStatus) GetLastError(), kUnknownErr );
	require_noerr( err, exit );
	
	fprintf( stdout, "\n" );
	for( i = 0; i < n; ++i )
	{
		fprintf( stdout, "Name Space %d\n", i + 1 );
		fprintf( stdout, "    NSProviderId:   %s\n", GUIDtoString( &array[ i ].NSProviderId, sizeof( s ), s ) );
		fprintf( stdout, "    dwNameSpace:    %d\n", array[ i ].dwNameSpace );
		fprintf( stdout, "    fActive:        %s\n", array[ i ].fActive ? "YES" : "NO" );
		fprintf( stdout, "    dwVersion:      %d\n", array[ i ].dwVersion );
		fprintf( stdout, "    lpszIdentifier: \"%s\"\n", array[ i ].lpszIdentifier );
		fprintf( stdout, "\n" );
	}
	err = kNoErr;
	
exit:
	if( array )
	{
		free( array );
	}
	if( started )
	{
		WSACleanup();
	}
	if( err != kNoErr )
	{
		fprintf( stderr, "### FAILED (%d) to list Name Space Providers\n", err );
	}
	return( err );
}
Пример #20
0
int storage_file_open(struct storage_msg *msg,
                      const void *r, size_t req_len)
{
    char *path = NULL;
    const struct storage_file_open_req *req = r;
    struct storage_file_open_resp resp = {0};

    if (req_len < sizeof(*req)) {
        ALOGE("%s: invalid request length (%zd < %zd)\n",
               __func__, req_len, sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    size_t fname_len = strlen(req->name);
    if (fname_len != req_len - sizeof(*req)) {
        ALOGE("%s: invalid filename length (%zd != %zd)\n",
              __func__, fname_len, req_len - sizeof(*req));
        msg->result = STORAGE_ERR_NOT_VALID;
        goto err_response;
    }

    int rc = asprintf(&path, "%s/%s", ssdir_name, req->name);
    if (rc < 0) {
        ALOGE("%s: asprintf failed\n", __func__);
        msg->result = STORAGE_ERR_GENERIC;
        goto err_response;
    }

    int open_flags = O_RDWR;

    if (req->flags & STORAGE_FILE_OPEN_TRUNCATE)
        open_flags |= O_TRUNC;

    if (req->flags & STORAGE_FILE_OPEN_CREATE) {
        /* open or create */
        if (req->flags & STORAGE_FILE_OPEN_CREATE_EXCLUSIVE) {
            /* create exclusive */
            open_flags |= O_CREAT | O_EXCL;
            rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
        } else {
            /* try open first */
            rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
            if (rc == -1 && errno == ENOENT) {
                /* then try open with O_CREATE */
                open_flags |= O_CREAT;
                rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
            }

        }
    } else {
        /* open an existing file */
        rc = TEMP_FAILURE_RETRY(open(path, open_flags, S_IRUSR | S_IWUSR));
    }

    if (rc < 0) {
        rc = errno;
        if (errno == EEXIST || errno == ENOENT) {
            ALOGV("%s: failed to open file \"%s\": %s\n",
                  __func__, path, strerror(errno));
        } else {
            ALOGE("%s: failed to open file \"%s\": %s\n",
                  __func__, path, strerror(errno));
        }
        msg->result = translate_errno(rc);
        goto err_response;
    }
    free(path);

    /* at this point rc contains storage file fd */
    msg->result = STORAGE_NO_ERROR;
    resp.handle = insert_fd(open_flags, rc);
    ALOGV("%s: \"%s\": fd = %u: handle = %d\n",
          __func__, path, rc, resp.handle);

    return ipc_respond(msg, &resp, sizeof(resp));

err_response:
    if (path)
        free(path);
    return ipc_respond(msg, NULL, 0);
}
Пример #21
0
STDMETHODIMP	ExplorerBar::GetBandInfo( DWORD inBandID, DWORD inViewMode, DESKBANDINFO *outInfo )
{
	HRESULT		err;
	
	require_action( outInfo, exit, err = E_INVALIDARG );
	
	mBandID   = inBandID;
	mViewMode = inViewMode;
	
	if( outInfo->dwMask & DBIM_MINSIZE )
	{
		outInfo->ptMinSize.x = 100;
		outInfo->ptMinSize.y = 100;
	}
	if( outInfo->dwMask & DBIM_MAXSIZE )
	{
		// Unlimited max size.
		
		outInfo->ptMaxSize.x = -1;
		outInfo->ptMaxSize.y = -1;
	}
	if( outInfo->dwMask & DBIM_INTEGRAL )
	{
		outInfo->ptIntegral.x = 1;
		outInfo->ptIntegral.y = 1;
	}
	if( outInfo->dwMask & DBIM_ACTUAL )
	{
		outInfo->ptActual.x = 0;
		outInfo->ptActual.y = 0;
	}
	if( outInfo->dwMask & DBIM_TITLE )
	{
		CString		s;
		BOOL		ok;
		
		ok = s.LoadString( IDS_NAME );
		require_action( ok, exit, err = kNoResourcesErr );
		
		#ifdef UNICODE
			lstrcpyn( outInfo->wszTitle, s, sizeof_array( outInfo->wszTitle ) );
		#else
			DWORD		nChars;
			
			nChars = MultiByteToWideChar( CP_ACP, 0, s, -1, outInfo->wszTitle, sizeof_array( outInfo->wszTitle ) );
			err = translate_errno( nChars > 0, (OSStatus) GetLastError(), kUnknownErr );
			require_noerr( err, exit );
		#endif
	}
	if( outInfo->dwMask & DBIM_MODEFLAGS )
	{
		outInfo->dwModeFlags = DBIMF_NORMAL | DBIMF_VARIABLEHEIGHT;
	}
	
	// Force the default background color.
	
	outInfo->dwMask &= ~DBIM_BKCOLOR;
	err = S_OK;
	
exit:
	return( err );
}
BOOL CPrinterSetupWizardApp::InitInstance()
{
	CString		errorMessage;
	CString		errorCaption;
	wchar_t		resource[MAX_PATH];
	int			res;
	OSStatus	err = kNoErr;

	//
	// initialize the debugging framework
	//
	debug_initialize( kDebugOutputTypeWindowsDebugger, "PrinterSetupWizard", NULL );
	debug_set_property( kDebugPropertyTagPrintLevel, kDebugLevelTrace );

	// Before we load the resources, let's load the error string

	errorMessage.LoadString( IDS_REINSTALL );
	errorCaption.LoadString( IDS_REINSTALL_CAPTION );

	// Load Resources

	res = PathForResource( NULL, L"RendezvousPrinterWizard.dll", resource, MAX_PATH );
	err = translate_errno( res != 0, kUnknownErr, kUnknownErr );
	require_noerr( err, exit );

	g_nonLocalizedResources = LoadLibrary( resource );
	translate_errno( g_nonLocalizedResources, GetLastError(), kUnknownErr );
	require_noerr( err, exit );

	res = PathForResource( NULL, L"RendezvousPrinterWizardLocalized.dll", resource, MAX_PATH );
	err = translate_errno( res != 0, kUnknownErr, kUnknownErr );
	require_noerr( err, exit );

	g_localizedResources = LoadLibrary( resource );
	translate_errno( g_localizedResources, GetLastError(), kUnknownErr );
	require_noerr( err, exit );
		
	AfxSetResourceHandle( g_localizedResources );

	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	InitCommonControls();

	CWinApp::InitInstance();

	AfxEnableControlContainer();

	{
		CPrinterSetupWizardSheet dlg(IDS_CAPTION);

		m_pMainWnd = &dlg;

		try
		{
			INT_PTR nResponse = dlg.DoModal();
		
			if (nResponse == IDOK)
			{
				// TODO: Place code here to handle when the dialog is
				//  dismissed with OK
			}
			else if (nResponse == IDCANCEL)
			{
				// TODO: Place code here to handle when the dialog is
				//  dismissed with Cancel
			}
		}
		catch (CPrinterSetupWizardSheet::WizardException & exc)
		{
			MessageBox(NULL, exc.text, exc.caption, MB_OK|MB_ICONEXCLAMATION);
		}
	}

exit:

	if ( err )
	{
		MessageBox( NULL, errorMessage, errorCaption, MB_ICONERROR | MB_OK );
	}

	if ( g_nonLocalizedResources )
	{
		FreeLibrary( g_nonLocalizedResources );
	}

	if ( g_localizedResources )
	{
		FreeLibrary( g_localizedResources );
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Пример #23
0
OSStatus
CPrinterSetupWizardSheet::InstallPrinter(Printer * printer)
{
	Service	*	service;
	BOOL		ok;
	OSStatus	err;

	service = printer->services.front();
	check( service );

	//
	// if the driver isn't installed, then install it
	//

	if ( !printer->driverInstalled )
	{
		DWORD		dwResult;
		HANDLE		hThread;
		unsigned	threadID;

		m_driverThreadFinished = false;
	
		//
		// create the thread
		//
		hThread = (HANDLE) _beginthreadex_compat( NULL, 0, InstallDriverThread, printer, 0, &threadID );
		err = translate_errno( hThread, (OSStatus) GetLastError(), kUnknownErr );
		require_noerr( err, exit );
			
		//
		// go modal
		//
		while (!m_driverThreadFinished)
		{
			MSG msg;
	
			GetMessage( &msg, m_hWnd, 0, 0 );
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	
		//
		// Wait until child process exits.
		//
		dwResult = WaitForSingleObject( hThread, INFINITE );
		err = translate_errno( dwResult == WAIT_OBJECT_0, errno_compat(), err = kUnknownErr );
		require_noerr( err, exit );

		//
		// check the return value of thread
		//
		require_noerr( m_driverThreadExitCode, exit );

		//
		// now we know that the driver was successfully installed
		//
		printer->driverInstalled = true;
	}

	if ( service->type == kPDLServiceType )
	{
		err = InstallPrinterPDLAndLPR( printer, service, PROTOCOL_RAWTCP_TYPE );
		require_noerr( err, exit );
	}
	else if ( service->type == kLPRServiceType )
	{
		err = InstallPrinterPDLAndLPR( printer, service, PROTOCOL_LPR_TYPE );
		require_noerr( err, exit );
	}
	else if ( service->type == kIPPServiceType )
	{
		err = InstallPrinterIPP( printer, service );
		require_noerr( err, exit );
	}
	else
	{
		err = kUnknownErr;
		require_noerr( err, exit );
	}

	printer->installed = true;

	//
	// if the user specified a default printer, set it
	//
	if (printer->deflt)
	{
		ok = SetDefaultPrinter( printer->actualName );
		err = translate_errno( ok, errno_compat(), err = kUnknownErr );
		require_noerr( err, exit );
	}

exit:

	return err;
}
Пример #24
0
unsigned WINAPI
CPrinterSetupWizardSheet::InstallDriverThread( LPVOID inParam )
{	
	Printer			*	printer = (Printer*) inParam;
	DWORD				exitCode = 0;
	DWORD				dwResult;
	OSStatus			err;
	STARTUPINFO			si;
	PROCESS_INFORMATION pi;
	BOOL				ok;

	check( printer );
	check( m_self );

	//
	// because we're calling endthreadex(), C++ objects won't be cleaned up
	// correctly.  we'll nest the CString 'command' inside a block so
	// that it's destructor will be invoked.
	//
	{
		CString command;

		ZeroMemory( &si, sizeof(si) );
		si.cb = sizeof(si);
		ZeroMemory( &pi, sizeof(pi) );

		command.Format(L"rundll32.exe printui.dll,PrintUIEntry /ia /m \"%s\" /f \"%s\"", (LPCTSTR) printer->modelName, (LPCTSTR) printer->infFileName );

		ok = CreateProcess(NULL, command.GetBuffer(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
		err = translate_errno( ok, errno_compat(), kUnknownErr );
		require_noerr( err, exit );

		dwResult = WaitForSingleObject( pi.hProcess, INFINITE );
		translate_errno( dwResult == WAIT_OBJECT_0, errno_compat(), err = kUnknownErr );
		require_noerr( err, exit );

		ok = GetExitCodeProcess( pi.hProcess, &exitCode );
		err = translate_errno( ok, errno_compat(), kUnknownErr );
		require_noerr( err, exit );
	}

exit:

	//
	// Close process and thread handles. 
	//
	if ( pi.hProcess )
	{
		CloseHandle( pi.hProcess );
	}

	if ( pi.hThread )
	{
		CloseHandle( pi.hThread );
	}

	//
	// alert the main thread
	//
	m_self->PostMessage( WM_PROCESS_EVENT, err, exitCode );

	_endthreadex_compat( 0 );

	return 0;
}
Пример #25
0
mDNSBool
LsaSetSecret( const char * inDomain, const char * inKey, const char * inSecret )
{
    size_t					inDomainLength;
    size_t					inKeyLength;
    char					domain[ 1024 ];
    char					key[ 1024 ];
    LSA_OBJECT_ATTRIBUTES	attrs;
    LSA_HANDLE				handle = NULL;
    NTSTATUS				res;
    LSA_UNICODE_STRING		lucZoneName;
    LSA_UNICODE_STRING		lucKeyName;
    LSA_UNICODE_STRING		lucSecretName;
    BOOL					ok = TRUE;
    OSStatus				err;

    require_action( inDomain != NULL, exit, ok = FALSE );
    require_action( inKey != NULL, exit, ok = FALSE );
    require_action( inSecret != NULL, exit, ok = FALSE );

    // If there isn't a trailing dot, add one because the mDNSResponder
    // presents names with the trailing dot.

    ZeroMemory( domain, sizeof( domain ) );
    inDomainLength = strlen( inDomain );
    require_action( inDomainLength > 0, exit, ok = FALSE );
    err = strcpy_s( domain, sizeof( domain ) - 2, inDomain );
    require_action( !err, exit, ok = FALSE );

    if ( domain[ inDomainLength - 1 ] != '.' )
    {
        domain[ inDomainLength++ ] = '.';
        domain[ inDomainLength ] = '\0';
    }

    // <rdar://problem/4192119>
    //
    // Prepend "$" to the key name, so that there will
    // be no conflict between the zone name and the key
    // name

    ZeroMemory( key, sizeof( key ) );
    inKeyLength = strlen( inKey );
    require_action( inKeyLength > 0 , exit, ok = FALSE );
    key[ 0 ] = '$';
    err = strcpy_s( key + 1, sizeof( key ) - 3, inKey );
    require_action( !err, exit, ok = FALSE );
    inKeyLength++;

    if ( key[ inKeyLength - 1 ] != '.' )
    {
        key[ inKeyLength++ ] = '.';
        key[ inKeyLength ] = '\0';
    }

    // attrs are reserved, so initialize to zeroes.

    ZeroMemory( &attrs, sizeof( attrs ) );

    // Get a handle to the Policy object on the local system

    res = LsaOpenPolicy( NULL, &attrs, POLICY_ALL_ACCESS, &handle );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

    // Intializing PLSA_UNICODE_STRING structures

    err = MakeLsaStringFromUTF8String( &lucZoneName, domain );
    require_noerr( err, exit );

    err = MakeLsaStringFromUTF8String( &lucKeyName, key );
    require_noerr( err, exit );

    err = MakeLsaStringFromUTF8String( &lucSecretName, inSecret );
    require_noerr( err, exit );

    // Store the private data.

    res = LsaStorePrivateData( handle, &lucZoneName, &lucKeyName );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

    res = LsaStorePrivateData( handle, &lucKeyName, &lucSecretName );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

exit:

    if ( handle )
    {
        LsaClose( handle );
        handle = NULL;
    }

    return ok;
}
Пример #26
0
OSStatus
CPrinterSetupWizardSheet::InstallPrinterPDLAndLPR(Printer * printer, Service * service, DWORD protocol )
{
	PRINTER_DEFAULTS	printerDefaults =	{ NULL,  NULL, SERVER_ACCESS_ADMINISTER };
	DWORD				dwStatus;
	DWORD				cbInputData		=	100;
	PBYTE				pOutputData		=	NULL;
	DWORD				cbOutputNeeded	=	0;
	PORT_DATA_1			portData;
	PRINTER_INFO_2		pInfo;
	HANDLE				hXcv			=	NULL;
	HANDLE				hPrinter		=	NULL;
	Queue			*	q;
	BOOL				ok;
	OSStatus			err;

	check(printer != NULL);
	check(printer->installed == false);

	q = service->queues.front();
	check( q );

	ok = OpenPrinter(L",XcvMonitor Standard TCP/IP Port", &hXcv, &printerDefaults);
	err = translate_errno( ok, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

	//
	// BUGBUG: MSDN said this is not required, but my experience shows it is required
	//
	try
	{
		pOutputData = new BYTE[cbInputData];
	}
	catch (...)
	{
		pOutputData = NULL;
	}

	require_action( pOutputData, exit, err = kNoMemoryErr );
	
	//
	// setup the port
	//
	ZeroMemory(&portData, sizeof(PORT_DATA_1));
	wcscpy(portData.sztPortName, printer->portName);
    	
	portData.dwPortNumber	=	service->portNumber;
	portData.dwVersion		=	1;
    	
	portData.dwProtocol	= protocol;
	portData.cbSize		= sizeof PORT_DATA_1;
	portData.dwReserved	= 0L;
    	
	wcscpy(portData.sztQueue, q->name);
	wcscpy(portData.sztIPAddress, service->hostname); 
	wcscpy(portData.sztHostAddress, service->hostname);

	ok = XcvData(hXcv, L"AddPort", (PBYTE) &portData, sizeof(PORT_DATA_1), pOutputData, cbInputData,  &cbOutputNeeded, &dwStatus);
	err = translate_errno( ok, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

	//
	// add the printer
	//
	ZeroMemory(&pInfo, sizeof(pInfo));
		
	pInfo.pPrinterName			=	printer->actualName.GetBuffer();
	pInfo.pServerName			=	NULL;
	pInfo.pShareName			=	NULL;
	pInfo.pPortName				=	printer->portName.GetBuffer();
	pInfo.pDriverName			=	printer->modelName.GetBuffer();
	pInfo.pComment				=	printer->displayModelName.GetBuffer();
	pInfo.pLocation				=	q->location.GetBuffer();
	pInfo.pDevMode				=	NULL;
	pInfo.pDevMode				=	NULL;
	pInfo.pSepFile				=	L"";
	pInfo.pPrintProcessor		=	L"winprint";
	pInfo.pDatatype				=	L"RAW";
	pInfo.pParameters			=	L"";
	pInfo.pSecurityDescriptor	=	NULL;
	pInfo.Attributes			=	PRINTER_ATTRIBUTE_QUEUED;
	pInfo.Priority				=	0;
	pInfo.DefaultPriority		=	0;
	pInfo.StartTime				=	0;
	pInfo.UntilTime				=	0;

	hPrinter = AddPrinter(NULL, 2, (LPBYTE) &pInfo);
	err = translate_errno( hPrinter, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

exit:

	if (hPrinter != NULL)
	{
		ClosePrinter(hPrinter);
	}

	if (hXcv != NULL)
	{
		ClosePrinter(hXcv);
	}

	if (pOutputData != NULL)
	{
		delete [] pOutputData;
	}

	return err;
}
Пример #27
0
static int action_format(int arg)
{
	struct crypt_device *cd = NULL;
	struct crypt_params_integrity params = {
		.journal_size = opt_journal_size,
		.interleave_sectors = opt_interleave_sectors,
		/* in bitmap mode we have to overload these values... */
		.journal_watermark = opt_integrity_bitmap ? opt_bitmap_sectors_per_bit : opt_journal_watermark,
		.journal_commit_time = opt_integrity_bitmap ? opt_bitmap_flush_time : opt_journal_commit_time,
		.buffer_sectors = opt_buffer_sectors,
		.tag_size = opt_tag_size,
		.sector_size = opt_sector_size ?: SECTOR_SIZE,
	};
	char integrity[MAX_CIPHER_LEN], journal_integrity[MAX_CIPHER_LEN], journal_crypt[MAX_CIPHER_LEN];
	char *integrity_key = NULL, *msg = NULL;
	int r;
	size_t signatures;

	if (opt_integrity) {
		r = crypt_parse_hash_integrity_mode(opt_integrity, integrity);
		if (r < 0) {
			log_err(_("No known integrity specification pattern detected."));
			return r;
		}
		params.integrity = integrity;
	}

	if (opt_journal_integrity) {
		r = crypt_parse_hash_integrity_mode(opt_journal_integrity, journal_integrity);
		if (r < 0) {
			log_err(_("No known integrity specification pattern detected."));
			return r;
		}
		params.journal_integrity = journal_integrity;
	}

	if (opt_journal_crypt) {
		r = crypt_parse_hash_integrity_mode(opt_journal_crypt, journal_crypt);
		if (r < 0) {
			log_err(_("No known integrity specification pattern detected."));
			return r;
		}
		params.journal_crypt = journal_crypt;
	}

	r = _read_keys(&integrity_key, &params);
	if (r)
		goto out;

	r = crypt_init_data_device(&cd, action_argv[0], opt_data_device);
	if (r < 0)
		goto out;

	r = asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]);
	if (r == -1) {
		r = -ENOMEM;
		goto out;
	}

	r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
	free(msg);
	if (r < 0)
		goto out;

	r = tools_detect_signatures(action_argv[0], 0, &signatures);
	if (r < 0)
		goto out;

	/* Signature candidates found */
	if (signatures && ((r =	tools_wipe_all_signatures(action_argv[0])) < 0))
		goto out;

	r = crypt_format(cd, CRYPT_INTEGRITY, NULL, NULL, NULL, NULL, 0, &params);
	if (r < 0) /* FIXME: call wipe signatures again */
		goto out;

	if (!opt_batch_mode)
		log_std(_("Formatted with tag size %u, internal integrity %s.\n"), opt_tag_size, opt_integrity);

	if (!opt_no_wipe)
		r = _wipe_data_device(cd, integrity_key);
out:
	crypt_safe_free(integrity_key);
	crypt_safe_free(CONST_CAST(void*)params.journal_integrity_key);
	crypt_safe_free(CONST_CAST(void*)params.journal_crypt_key);
	crypt_free(cd);
	return r;
}

static int action_open(int arg)
{
	struct crypt_device *cd = NULL;
	struct crypt_params_integrity params = {
		/* in bitmap mode we have to overload these values... */
		.journal_watermark = opt_integrity_bitmap ? opt_bitmap_sectors_per_bit : opt_journal_watermark,
		.journal_commit_time = opt_integrity_bitmap ? opt_bitmap_flush_time : opt_journal_commit_time,
		.buffer_sectors = opt_buffer_sectors,
	};
	uint32_t activate_flags = 0;
	char integrity[MAX_CIPHER_LEN], journal_integrity[MAX_CIPHER_LEN], journal_crypt[MAX_CIPHER_LEN];
	char *integrity_key = NULL;
	int r;

	if (opt_integrity) {
		r = crypt_parse_hash_integrity_mode(opt_integrity, integrity);
		if (r < 0) {
			log_err(_("No known integrity specification pattern detected."));
			return r;
		}
		params.integrity = integrity;
	}

	if (opt_journal_integrity) {
		r = crypt_parse_hash_integrity_mode(opt_journal_integrity, journal_integrity);
		if (r < 0) {
			log_err(_("No known integrity specification pattern detected."));
			return r;

		}
		params.journal_integrity = journal_integrity;
	}

	if (opt_journal_crypt) {
		r = crypt_parse_hash_integrity_mode(opt_journal_crypt, journal_crypt);
		if (r < 0) {
			log_err(_("No known integrity specification pattern detected."));
			return r;
		}
		params.journal_crypt = journal_crypt;
	}

	if (opt_integrity_nojournal || opt_integrity_bitmap)
		activate_flags |= CRYPT_ACTIVATE_NO_JOURNAL;
	if (opt_integrity_recovery)
		activate_flags |= CRYPT_ACTIVATE_RECOVERY;
	if (opt_integrity_bitmap)
		activate_flags |= CRYPT_ACTIVATE_NO_JOURNAL_BITMAP;

	if (opt_integrity_recalculate)
		activate_flags |= CRYPT_ACTIVATE_RECALCULATE;

	r = _read_keys(&integrity_key, &params);
	if (r)
		goto out;

	if ((r = crypt_init_data_device(&cd, action_argv[0], opt_data_device)))
		goto out;

	r = crypt_load(cd, CRYPT_INTEGRITY, &params);
	if (r)
		goto out;

	r = crypt_activate_by_volume_key(cd, action_argv[1], integrity_key,
					 opt_integrity_key_size, activate_flags);
out:
	crypt_safe_free(integrity_key);
	crypt_safe_free(CONST_CAST(void*)params.journal_integrity_key);
	crypt_safe_free(CONST_CAST(void*)params.journal_crypt_key);
	crypt_free(cd);
	return r;
}

static int action_close(int arg)
{
	struct crypt_device *cd = NULL;
	int r;

	r = crypt_init_by_name(&cd, action_argv[0]);
	if (r == 0)
		r = crypt_deactivate(cd, action_argv[0]);

	crypt_free(cd);
	return r;
}

static int action_status(int arg)
{
	crypt_status_info ci;
	struct crypt_active_device cad;
	struct crypt_params_integrity ip = {};
	struct crypt_device *cd = NULL;
	char *backing_file;
	const char *device, *metadata_device;
	int path = 0, r = 0;

	/* perhaps a path, not a dm device name */
	if (strchr(action_argv[0], '/'))
		path = 1;

	ci = crypt_status(NULL, action_argv[0]);
	switch (ci) {
	case CRYPT_INVALID:
		r = -EINVAL;
		break;
	case CRYPT_INACTIVE:
		if (path)
			log_std("%s is inactive.\n", action_argv[0]);
		else
			log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
		r = -ENODEV;
		break;
	case CRYPT_ACTIVE:
	case CRYPT_BUSY:
		if (path)
			log_std("%s is active%s.\n", action_argv[0],
				ci == CRYPT_BUSY ? " and is in use" : "");
		else
			log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
				ci == CRYPT_BUSY ? " and is in use" : "");

		r = crypt_init_by_name_and_header(&cd, action_argv[0], NULL);
		if (r < 0)
			goto out;

		log_std("  type:    %s\n", crypt_get_type(cd) ?: "n/a");

		r = crypt_get_active_device(cd, action_argv[0], &cad);
		if (r < 0)
			goto out;

		r = crypt_get_integrity_info(cd, &ip);
		if (r < 0)
			goto out;

		log_std("  tag size: %u\n", ip.tag_size);
		log_std("  integrity: %s\n", ip.integrity ?: "(none)");
		device = crypt_get_device_name(cd);
		metadata_device = crypt_get_metadata_device_name(cd);
		log_std("  device:  %s%s\n", device, metadata_device ? " (detached)" : "");
		if (crypt_loop_device(device)) {
			backing_file = crypt_loop_backing_file(device);
			log_std("  loop:    %s\n", backing_file);
			free(backing_file);
		}
		if (metadata_device) {
			log_std("  metadata device:  %s\n", metadata_device);
			if (crypt_loop_device(metadata_device)) {
				backing_file = crypt_loop_backing_file(metadata_device);
				log_std("  loop:    %s\n", backing_file);
				free(backing_file);
			}
		}
		log_std("  sector size:  %u bytes\n", crypt_get_sector_size(cd));
		log_std("  interleave sectors: %u\n", ip.interleave_sectors);
		log_std("  size:    %" PRIu64 " sectors\n", cad.size);
		log_std("  mode:    %s%s\n",
			cad.flags & CRYPT_ACTIVATE_READONLY ? "readonly" : "read/write",
			cad.flags & CRYPT_ACTIVATE_RECOVERY ? " recovery" : "");
		log_std("  failures: %" PRIu64 "\n",
			crypt_get_active_integrity_failures(cd, action_argv[0]));
		if (cad.flags & CRYPT_ACTIVATE_NO_JOURNAL_BITMAP) {
			log_std("  bitmap 512-byte sectors per bit: %u\n", ip.journal_watermark);
			log_std("  bitmap flush interval: %u ms\n", ip.journal_commit_time);
		} if (cad.flags & CRYPT_ACTIVATE_NO_JOURNAL) {
			log_std("  journal: not active\n");
		} else {
			log_std("  journal size: %" PRIu64 " bytes\n", ip.journal_size);
			log_std("  journal watermark: %u%%\n", ip.journal_watermark);
			log_std("  journal commit time: %u ms\n", ip.journal_commit_time);
			if (ip.journal_integrity)
				log_std("  journal integrity MAC: %s\n", ip.journal_integrity);
			if (ip.journal_crypt)
				log_std("  journal encryption: %s\n", ip.journal_crypt);
		}
	}
out:
	crypt_free(cd);
	if (r == -ENOTSUP)
		r = 0;
	return r;
	return -EINVAL;
}

static int action_dump(int arg)
{
	struct crypt_device *cd = NULL;
	struct crypt_params_integrity params = {};
	int r;

	if ((r = crypt_init(&cd, action_argv[0])))
		return r;

	r = crypt_load(cd, CRYPT_INTEGRITY, &params);
	if (!r)
		crypt_dump(cd);

	crypt_free(cd);
	return r;
}

static struct action_type {
	const char *type;
	int (*handler)(int);
	int required_action_argc;
	const char *arg_desc;
	const char *desc;
} action_types[] = {
	{ "format",	action_format, 1, N_("<integrity_device>"),N_("format device") },
	{ "open",	action_open,   2, N_("<integrity_device> <name>"),N_("open device as <name>") },
	{ "close",	action_close,  1, N_("<name>"),N_("close device (deactivate and remove mapping)") },
	{ "status",	action_status, 1, N_("<name>"),N_("show active device status") },
	{ "dump",	action_dump,   1, N_("<integrity_device>"),N_("show on-disk information") },
	{ NULL, NULL, 0, NULL, NULL }
};

static void help(poptContext popt_context,
		 enum poptCallbackReason reason __attribute__((unused)),
		 struct poptOption *key,
		 const char *arg __attribute__((unused)),
		 void *data __attribute__((unused)))
{
	struct action_type *action;

	if (key->shortName == '?') {
		log_std("%s %s\n", PACKAGE_INTEGRITY, PACKAGE_VERSION);
		poptPrintHelp(popt_context, stdout, 0);
		log_std(_("\n"
			 "<action> is one of:\n"));
		for(action = action_types; action->type; action++)
			log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
		log_std(_("\n"
			 "<name> is the device to create under %s\n"
			 "<integrity_device> is the device containing data with integrity tags\n"),
			crypt_get_dir());

		log_std(_("\nDefault compiled-in dm-integrity parameters:\n"
			  "\tTag size: %u bytes, Checksum algorithm: %s\n"),
			  DEFAULT_TAG_SIZE, DEFAULT_ALG_NAME);
		exit(EXIT_SUCCESS);
	} else
		usage(popt_context, EXIT_SUCCESS, NULL, NULL);
}

static int run_action(struct action_type *action)
{
	int r;

	log_dbg("Running command %s.", action->type);

	r = action->handler(0);

	show_status(r);
	return translate_errno(r);
}
Пример #28
0
mDNSBool
LsaGetSecret( const char * inDomain, char * outDomain, unsigned outDomainSize, char * outKey, unsigned outKeySize, char * outSecret, unsigned outSecretSize )
{
    PLSA_UNICODE_STRING		domainLSA;
    PLSA_UNICODE_STRING		keyLSA;
    PLSA_UNICODE_STRING		secretLSA;
    size_t					i;
    size_t					dlen;
    LSA_OBJECT_ATTRIBUTES	attrs;
    LSA_HANDLE				handle = NULL;
    NTSTATUS				res;
    OSStatus				err;

    check( inDomain );
    check( outDomain );
    check( outKey );
    check( outSecret );

    // Initialize

    domainLSA	= NULL;
    keyLSA		= NULL;
    secretLSA	= NULL;

    // Make sure we have enough space to add trailing dot

    dlen = strlen( inDomain );
    err = strcpy_s( outDomain, outDomainSize - 2, inDomain );
    require_noerr( err, exit );

    // If there isn't a trailing dot, add one because the mDNSResponder
    // presents names with the trailing dot.

    if ( outDomain[ dlen - 1 ] != '.' )
    {
        outDomain[ dlen++ ] = '.';
        outDomain[ dlen ] = '\0';
    }

    // Canonicalize name by converting to lower case (keychain and some name servers are case sensitive)

    for ( i = 0; i < dlen; i++ )
    {
        outDomain[i] = (char) tolower( outDomain[i] );  // canonicalize -> lower case
    }

    // attrs are reserved, so initialize to zeroes.

    ZeroMemory( &attrs, sizeof( attrs ) );

    // Get a handle to the Policy object on the local system

    res = LsaOpenPolicy( NULL, &attrs, POLICY_GET_PRIVATE_INFORMATION, &handle );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr( err, exit );

    // Get the encrypted data

    domainLSA = ( PLSA_UNICODE_STRING ) malloc( sizeof( LSA_UNICODE_STRING ) );
    require_action( domainLSA != NULL, exit, err = mStatus_NoMemoryErr );
    err = MakeLsaStringFromUTF8String( domainLSA, outDomain );
    require_noerr( err, exit );

    // Retrieve the key

    res = LsaRetrievePrivateData( handle, domainLSA, &keyLSA );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr_quiet( err, exit );

    // <rdar://problem/4192119> Lsa secrets use a flat naming space.  Therefore, we will prepend "$" to the keyname to
    // make sure it doesn't conflict with a zone name.
    // Strip off the "$" prefix.

    err = MakeUTF8StringFromLsaString( outKey, outKeySize, keyLSA );
    require_noerr( err, exit );
    require_action( outKey[0] == '$', exit, err = kUnknownErr );
    memcpy( outKey, outKey + 1, strlen( outKey ) );

    // Retrieve the secret

    res = LsaRetrievePrivateData( handle, keyLSA, &secretLSA );
    err = translate_errno( res == 0, LsaNtStatusToWinError( res ), kUnknownErr );
    require_noerr_quiet( err, exit );

    // Convert the secret to UTF8 string

    err = MakeUTF8StringFromLsaString( outSecret, outSecretSize, secretLSA );
    require_noerr( err, exit );

exit:

    if ( domainLSA != NULL )
    {
        if ( domainLSA->Buffer != NULL )
        {
            free( domainLSA->Buffer );
        }

        free( domainLSA );
    }

    if ( keyLSA != NULL )
    {
        LsaFreeMemory( keyLSA );
    }

    if ( secretLSA != NULL )
    {
        LsaFreeMemory( secretLSA );
    }

    if ( handle )
    {
        LsaClose( handle );
        handle = NULL;
    }

    return ( !err ) ? TRUE : FALSE;
}
BOOL
CCPApp::InitInstance()
{
    CCommandLineInfo	commandLine;
    wchar_t				resource[MAX_PATH];
    CString				errorMessage;
    CString				errorCaption;
    int					res;
    OSStatus			err = kNoErr;

    HeapSetInformation( NULL, HeapEnableTerminationOnCorruption, NULL, 0 );

    //
    // initialize the debugging framework
    //
    debug_initialize( kDebugOutputTypeWindowsDebugger, "ControlPanel", NULL );
    debug_set_property( kDebugPropertyTagPrintLevel, kDebugLevelTrace );

    // Before we load the resources, let's load the error string

    errorMessage.LoadString( IDS_REINSTALL );
    errorCaption.LoadString( IDS_REINSTALL_CAPTION );

    res = PathForResource( NULL, L"ControlPanelResources.dll", resource, MAX_PATH );
    err = translate_errno( res != 0, kUnknownErr, kUnknownErr );
    require_noerr( err, exit );

    g_nonLocalizedResources = LoadLibrary( resource );
    translate_errno( g_nonLocalizedResources, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    res = PathForResource( NULL, L"ControlPanelLocalized.dll", resource, MAX_PATH );
    err = translate_errno( res != 0, kUnknownErr, kUnknownErr );
    require_noerr( err, exit );

    g_localizedResources = LoadLibrary( resource );
    translate_errno( g_localizedResources, GetLastError(), kUnknownErr );
    require_noerr( err, exit );

    AfxSetResourceHandle( g_localizedResources );

    // InitCommonControls() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.

    InitCommonControls();

    CWinApp::InitInstance();

    AfxEnableControlContainer();

    ParseCommandLine( commandLine );

    if ( commandLine.m_nShellCommand == CCommandLineInfo::AppRegister )
    {
        CString		localizedName;
        CString		toolTip;
        TCHAR		iconPath[ MAX_PATH + 12 ]	= TEXT( "" );
        TCHAR		exePath[ MAX_PATH ]			= TEXT( "" );
        DWORD		nChars;
        OSStatus	err;

        nChars = GetModuleFileName( NULL, exePath, sizeof_array( exePath ) );

        err = translate_errno( nChars > 0, (OSStatus) GetLastError(), kUnknownErr );

        require_noerr( err, exit );

        wsprintf( iconPath, L"%s,-%d", exePath, IDR_APPLET );

        localizedName.LoadString( IDS_APPLET_NAME );
        toolTip.LoadString( IDS_APPLET_TOOLTIP );

        Register( g_controlPanelGUID, g_controlPanelName, g_controlPanelCanonicalName, g_controlPanelCategory, localizedName, toolTip, iconPath, exePath );
    }
    else if ( commandLine.m_nShellCommand == CCommandLineInfo::AppUnregister )
    {
        Unregister( g_controlPanelGUID );
    }
    else
    {
        CString					name;
        CConfigPropertySheet	dlg;

        name.LoadString( IDR_APPLET );
        dlg.Construct( name, NULL, 0 );

        m_pMainWnd = &dlg;

        try
        {
            INT_PTR nResponse = dlg.DoModal();

            if (nResponse == IDOK)
            {
                // TODO: Place code here to handle when the dialog is
                //  dismissed with OK
            }
            else if (nResponse == IDCANCEL)
            {
                // TODO: Place code here to handle when the dialog is
                //  dismissed with Cancel
            }
        }
        catch (...)
        {
            MessageBox(NULL, L"", L"", MB_OK|MB_ICONEXCLAMATION);
        }
    }

    if ( err )
    {
        MessageBox( NULL, L"", L"", MB_ICONERROR | MB_OK );
    }

exit:

    if ( err )
    {
        MessageBox( NULL, errorMessage, errorCaption, MB_ICONERROR | MB_OK );
    }

    // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
}