diff --git a/.gitignore b/.gitignore index 2f789c6fa..98ca450a2 100644 --- a/.gitignore +++ b/.gitignore @@ -94,6 +94,7 @@ client/X11/xfreerdp client/Mac/xcode client/Sample/sfreerdp client/DirectFB/dfreerdp +client/Wayland/wlfreerdp server/Sample/sfreerdp-server server/X11/xfreerdp-server xcode @@ -132,6 +133,9 @@ TAGS # packaging related files !packaging/scripts/prepare_deb_freerdp-nightly.sh +packaging/deb/freerdp-nightly/freerdp-nightly +packaging/deb/freerdp-nightly/freerdp-nightly-dev +packaging/deb/freerdp-nightly/freerdp-nightly-dbg # .idea diff --git a/CMakeLists.txt b/CMakeLists.txt index 02aefd4e0..b050a3a1d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -229,7 +229,7 @@ if(CMAKE_COMPILER_IS_GNUCC) endif() endif() -if("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang") +if(${CMAKE_C_COMPILER_ID} STREQUAL "Clang") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-parameter") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-macros -Wno-padded") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-c11-extensions -Wno-gnu") @@ -651,17 +651,6 @@ set(FREERDP_EXTENSION_PATH "${CMAKE_INSTALL_FULL_LIBDIR}/freerdp/extensions") include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) -if(BSD) - if(IS_DIRECTORY /usr/local/include) - include_directories(/usr/local/include) - link_directories(/usr/local/lib) - endif() - if(OPENBSD) - if(IS_DIRECTORY /usr/X11R6/include) - include_directories(/usr/X11R6/include) - endif() - endif() -endif() # Configure files add_definitions("-DHAVE_CONFIG_H") @@ -722,10 +711,6 @@ add_subdirectory(include) add_subdirectory(libfreerdp) -if(WITH_CHANNELS) - add_subdirectory(channels) -endif() - if (IOS) set(CMAKE_OSX_DEPLOYMENT_TARGET "") if (IOS_PLATFORM MATCHES "SIMULATOR") @@ -741,6 +726,22 @@ include_directories("${CMAKE_BINARY_DIR}/rdtk/include") add_subdirectory(rdtk) +if(BSD) + if(IS_DIRECTORY /usr/local/include) + include_directories(/usr/local/include) + link_directories(/usr/local/lib) + endif() + if(OPENBSD) + if(IS_DIRECTORY /usr/X11R6/include) + include_directories(/usr/X11R6/include) + endif() + endif() +endif() + +if(WITH_CHANNELS) + add_subdirectory(channels) +endif() + if(WITH_CLIENT) add_subdirectory(client) endif() @@ -749,6 +750,7 @@ if(WITH_SERVER) add_subdirectory(server) endif() + # Exporting if(${CMAKE_VERSION} VERSION_GREATER "2.8.10") diff --git a/channels/audin/client/audin_main.c b/channels/audin/client/audin_main.c index 6aaa8c27c..39cc3a882 100644 --- a/channels/audin/client/audin_main.c +++ b/channels/audin/client/audin_main.c @@ -102,7 +102,7 @@ static WIN32ERROR audin_process_version(IWTSVirtualChannelCallback* pChannelCall Stream_Read_UINT32(s, Version); - DEBUG_DVC("process_version: Version=%d", Version); + DEBUG_DVC("Version=%d", Version); out = Stream_New(NULL, 5); @@ -142,7 +142,7 @@ static WIN32ERROR audin_process_formats(IWTSVirtualChannelCallback* pChannelCall UINT32 cbSizeFormatsPacket; Stream_Read_UINT32(s, NumFormats); - DEBUG_DVC("process_formats: NumFormats %d", NumFormats); + DEBUG_DVC("NumFormats %d", NumFormats); if ((NumFormats < 1) || (NumFormats > 1000)) { WLog_ERR(TAG, "bad NumFormats %d", NumFormats); @@ -182,7 +182,7 @@ static WIN32ERROR audin_process_formats(IWTSVirtualChannelCallback* pChannelCall format.data = Stream_Pointer(s); Stream_Seek(s, format.cbSize); - DEBUG_DVC("process_formats: wFormatTag=%d nChannels=%d nSamplesPerSec=%d " + DEBUG_DVC("wFormatTag=%d nChannels=%d nSamplesPerSec=%d " "nBlockAlign=%d wBitsPerSample=%d cbSize=%d", format.wFormatTag, format.nChannels, format.nSamplesPerSec, format.nBlockAlign, format.wBitsPerSample, format.cbSize); @@ -195,7 +195,7 @@ static WIN32ERROR audin_process_formats(IWTSVirtualChannelCallback* pChannelCall continue; if (audin->device && audin->device->FormatSupported(audin->device, &format)) { - DEBUG_DVC("process_formats: format ok"); + DEBUG_DVC("format ok"); /* Store the agreed format in the corresponding index */ callback->formats[callback->formats_count++] = format; @@ -321,7 +321,7 @@ static WIN32ERROR audin_process_open(IWTSVirtualChannelCallback* pChannelCallbac Stream_Read_UINT32(s, FramesPerPacket); Stream_Read_UINT32(s, initialFormat); - DEBUG_DVC("process_open: FramesPerPacket=%d initialFormat=%d", + DEBUG_DVC("FramesPerPacket=%d initialFormat=%d", FramesPerPacket, initialFormat); if (initialFormat >= (UINT32) callback->formats_count) @@ -370,7 +370,7 @@ static WIN32ERROR audin_process_format_change(IWTSVirtualChannelCallback* pChann Stream_Read_UINT32(s, NewFormat); - DEBUG_DVC("process_format_change: NewFormat=%d", NewFormat); + DEBUG_DVC("NewFormat=%d", NewFormat); if (NewFormat >= (UINT32) callback->formats_count) { @@ -416,7 +416,7 @@ static WIN32ERROR audin_on_data_received(IWTSVirtualChannelCallback* pChannelCal Stream_Read_UINT8(data, MessageId); - DEBUG_DVC("on_data_received: MessageId=0x%x", MessageId); + DEBUG_DVC("MessageId=0x%x", MessageId); switch (MessageId) { @@ -451,7 +451,7 @@ static WIN32ERROR audin_on_close(IWTSVirtualChannelCallback* pChannelCallback) AUDIN_PLUGIN* audin = (AUDIN_PLUGIN*) callback->plugin; WIN32ERROR error = CHANNEL_RC_OK; - DEBUG_DVC("on_close"); + DEBUG_DVC("..."); if (audin->device) { @@ -476,7 +476,7 @@ static WIN32ERROR audin_on_new_channel_connection(IWTSListenerCallback* pListene AUDIN_CHANNEL_CALLBACK* callback; AUDIN_LISTENER_CALLBACK* listener_callback = (AUDIN_LISTENER_CALLBACK*) pListenerCallback; - DEBUG_DVC("on_new_channel_connection"); + DEBUG_DVC("..."); callback = (AUDIN_CHANNEL_CALLBACK*) calloc(1, sizeof(AUDIN_CHANNEL_CALLBACK)); if (!callback) @@ -500,7 +500,7 @@ static WIN32ERROR audin_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChanne { AUDIN_PLUGIN* audin = (AUDIN_PLUGIN*) pPlugin; - DEBUG_DVC("plugin_initialize"); + DEBUG_DVC("..."); audin->listener_callback = (AUDIN_LISTENER_CALLBACK*) calloc(1, sizeof(AUDIN_LISTENER_CALLBACK)); if (!audin->listener_callback) @@ -522,7 +522,7 @@ static WIN32ERROR audin_plugin_terminated(IWTSPlugin* pPlugin) AUDIN_PLUGIN* audin = (AUDIN_PLUGIN*) pPlugin; WIN32ERROR error = CHANNEL_RC_OK; - DEBUG_DVC("plugin_terminated"); + DEBUG_DVC("..."); if (audin->device) { @@ -557,7 +557,7 @@ static WIN32ERROR audin_register_device_plugin(IWTSPlugin* pPlugin, IAudinDevice return ERROR_ALREADY_EXISTS; } - DEBUG_DVC("register_device_plugin: device registered."); + DEBUG_DVC("device registered."); audin->device = device; return CHANNEL_RC_OK; diff --git a/channels/audin/client/opensles/audin_opensl_es.c b/channels/audin/client/opensles/audin_opensl_es.c index 4db37ce06..bbe147eaa 100644 --- a/channels/audin/client/opensles/audin_opensl_es.c +++ b/channels/audin/client/opensles/audin_opensl_es.c @@ -190,7 +190,9 @@ static WIN32ERROR audin_opensles_free(IAudinDevice* device) static BOOL audin_opensles_format_supported(IAudinDevice* device, audinFormat* format) { +#ifdef WITH_DEBUG_DVC AudinOpenSLESDevice* opensles = (AudinOpenSLESDevice*) device; +#endif DEBUG_DVC("device=%p, format=%p", opensles, format); diff --git a/channels/audin/client/oss/audin_oss.c b/channels/audin/client/oss/audin_oss.c index b8b54b1b5..5fa6cb727 100644 --- a/channels/audin/client/oss/audin_oss.c +++ b/channels/audin/client/oss/audin_oss.c @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -40,9 +41,9 @@ #include #include #if defined(__OpenBSD__) - #include +#include #else - #include +#include #endif #include @@ -52,14 +53,15 @@ #include "audin_main.h" -typedef struct _AudinOSSDevice { +typedef struct _AudinOSSDevice +{ IAudinDevice iface; FREERDP_DSP_CONTEXT* dsp_context; HANDLE thread; HANDLE stopEvent; - + audinFormat format; UINT32 FramesPerPacket; int dev_unit; @@ -75,86 +77,101 @@ typedef struct _AudinOSSDevice { WLog_ERR(TAG, "%s: %i - %s\n", _text, _error, strerror(_error)); -static int audin_oss_get_format(audinFormat *format) { +static int audin_oss_get_format(audinFormat* format) +{ + switch (format->wFormatTag) + { + case WAVE_FORMAT_PCM: - switch (format->wFormatTag) { - case WAVE_FORMAT_PCM: - switch (format->wBitsPerSample) { - case 8: - return AFMT_S8; - case 16: - return AFMT_S16_LE; - } - break; - case WAVE_FORMAT_ALAW: - return AFMT_A_LAW; + switch (format->wBitsPerSample) + { + case 8: + return AFMT_S8; + case 16: + return AFMT_S16_LE; + } + + break; + case WAVE_FORMAT_ALAW: + return AFMT_A_LAW; #if 0 /* This does not work on my desktop. */ - case WAVE_FORMAT_MULAW: - return AFMT_MU_LAW; + case WAVE_FORMAT_MULAW: + return AFMT_MU_LAW; #endif - case WAVE_FORMAT_ADPCM: - case WAVE_FORMAT_DVI_ADPCM: - return AFMT_S16_LE; + case WAVE_FORMAT_ADPCM: + case WAVE_FORMAT_DVI_ADPCM: + return AFMT_S16_LE; } return 0; } -static BOOL audin_oss_format_supported(IAudinDevice *device, audinFormat *format) { +static BOOL audin_oss_format_supported(IAudinDevice* device, audinFormat* format) +{ int req_fmt = 0; if (device == NULL || format == NULL) return FALSE; - switch (format->wFormatTag) { - case WAVE_FORMAT_PCM: - if (format->cbSize != 0 || - format->nSamplesPerSec > 48000 || - (format->wBitsPerSample != 8 && format->wBitsPerSample != 16) || - (format->nChannels != 1 && format->nChannels != 2)) - return FALSE; - break; - case WAVE_FORMAT_ADPCM: - case WAVE_FORMAT_DVI_ADPCM: - if (format->nSamplesPerSec > 48000 || - format->wBitsPerSample != 4 || - (format->nChannels != 1 && format->nChannels != 2)) - return FALSE; - break; + switch (format->wFormatTag) + { + case WAVE_FORMAT_PCM: + + if (format->cbSize != 0 || + format->nSamplesPerSec > 48000 || + (format->wBitsPerSample != 8 && format->wBitsPerSample != 16) || + (format->nChannels != 1 && format->nChannels != 2)) + return FALSE; + + break; + case WAVE_FORMAT_ADPCM: + case WAVE_FORMAT_DVI_ADPCM: + + if (format->nSamplesPerSec > 48000 || + format->wBitsPerSample != 4 || + (format->nChannels != 1 && format->nChannels != 2)) + return FALSE; + + break; } - + req_fmt = audin_oss_get_format(format); + if (req_fmt == 0) return FALSE; return TRUE; } -static WIN32ERROR audin_oss_set_format(IAudinDevice *device, audinFormat *format, UINT32 FramesPerPacket) { - AudinOSSDevice *oss = (AudinOSSDevice*)device; +static WIN32ERROR audin_oss_set_format(IAudinDevice* device, audinFormat* format, UINT32 FramesPerPacket) +{ + AudinOSSDevice* oss = (AudinOSSDevice*)device; if (device == NULL || format == NULL) return ERROR_INVALID_PARAMETER; - + oss->FramesPerPacket = FramesPerPacket; CopyMemory(&(oss->format), format, sizeof(audinFormat)); - switch (format->wFormatTag) { - case WAVE_FORMAT_ADPCM: - case WAVE_FORMAT_DVI_ADPCM: - oss->FramesPerPacket *= 4; /* Compression ratio. */ - oss->format.wBitsPerSample *= 4; - break; + + switch (format->wFormatTag) + { + case WAVE_FORMAT_ADPCM: + case WAVE_FORMAT_DVI_ADPCM: + oss->FramesPerPacket *= 4; /* Compression ratio. */ + oss->format.wBitsPerSample *= 4; + break; } return CHANNEL_RC_OK; } -static void *audin_oss_thread_func(void *arg) +static void* audin_oss_thread_func(void* arg) { char dev_name[PATH_MAX] = "/dev/dsp"; - int pcm_handle = -1; - BYTE *buffer = NULL, *encoded_data; + char mixer_name[PATH_MAX] = "/dev/mixer"; + int pcm_handle = -1, mixer_handle; + BYTE* buffer = NULL, *encoded_data; int tmp, buffer_size, encoded_size; - AudinOSSDevice *oss = (AudinOSSDevice*)arg; + AudinOSSDevice* oss = (AudinOSSDevice*)arg; WIN32ERROR error; if (arg == NULL) @@ -164,54 +181,102 @@ static void *audin_oss_thread_func(void *arg) } if (oss->dev_unit != -1) - snprintf(dev_name, (PATH_MAX - 1), "/dev/dsp%i", oss->dev_unit); + { + sprintf_s(dev_name, (PATH_MAX - 1), "/dev/dsp%i", oss->dev_unit); + sprintf_s(mixer_name, PATH_MAX - 1, "/dev/mixer%i", oss->dev_unit); + } + WLog_INFO(TAG, "open: %s", dev_name); - if ((pcm_handle = open(dev_name, O_RDONLY)) < 0) { + + if ((pcm_handle = open(dev_name, O_RDONLY)) < 0) + { OSS_LOG_ERR("sound dev open failed", errno); error = (WIN32ERROR)errno; goto err_out; } + + /* Set rec volume to 100%. */ + if ((mixer_handle = open(mixer_name, O_RDWR)) < 0) + { + OSS_LOG_ERR("mixer open failed, not critical", errno); + } + else + { + tmp = (100 | (100 << 8)); + + if (ioctl(mixer_handle, MIXER_WRITE(SOUND_MIXER_MIC), &tmp) == -1) + OSS_LOG_ERR("WRITE_MIXER - SOUND_MIXER_MIC, not critical", errno); + + tmp = (100 | (100 << 8)); + + if (ioctl(mixer_handle, MIXER_WRITE(SOUND_MIXER_RECLEV), &tmp) == -1) + OSS_LOG_ERR("WRITE_MIXER - SOUND_MIXER_RECLEV, not critical", errno); + + close(mixer_handle); + } + #if 0 /* FreeBSD OSS implementation at this moment (2015.03) does not set PCM_CAP_INPUT flag. */ tmp = 0; - if (ioctl(pcm_handle, SNDCTL_DSP_GETCAPS, &tmp) == -1) { + + if (ioctl(pcm_handle, SNDCTL_DSP_GETCAPS, &tmp) == -1) + { OSS_LOG_ERR("SNDCTL_DSP_GETCAPS failed, try ignory", errno); - } else if ((tmp & PCM_CAP_INPUT) == 0) { + } + else if ((tmp & PCM_CAP_INPUT) == 0) + { OSS_LOG_ERR("Device does not supports playback", EOPNOTSUPP); goto err_out; } + #endif /* Set format. */ tmp = audin_oss_get_format(&oss->format); + if (ioctl(pcm_handle, SNDCTL_DSP_SETFMT, &tmp) == -1) OSS_LOG_ERR("SNDCTL_DSP_SETFMT failed", errno); + tmp = oss->format.nChannels; + if (ioctl(pcm_handle, SNDCTL_DSP_CHANNELS, &tmp) == -1) OSS_LOG_ERR("SNDCTL_DSP_CHANNELS failed", errno); + tmp = oss->format.nSamplesPerSec; + if (ioctl(pcm_handle, SNDCTL_DSP_SPEED, &tmp) == -1) OSS_LOG_ERR("SNDCTL_DSP_SPEED failed", errno); + tmp = oss->format.nBlockAlign; + if (ioctl(pcm_handle, SNDCTL_DSP_SETFRAGMENT, &tmp) == -1) OSS_LOG_ERR("SNDCTL_DSP_SETFRAGMENT failed", errno); - buffer_size = (oss->FramesPerPacket * oss->format.nChannels * (oss->format.wBitsPerSample / 8)); - buffer = (BYTE*)calloc(1, (buffer_size + sizeof(void*))); - if (NULL == buffer) { + buffer_size = (oss->FramesPerPacket * oss->format.nChannels * (oss->format.wBitsPerSample / 8)); + buffer = (BYTE*)malloc((buffer_size + sizeof(void*))); + + if (NULL == buffer) + { OSS_LOG_ERR("malloc() fail", errno); error = ERROR_NOT_ENOUGH_MEMORY; goto err_out; } + ZeroMemory(buffer, buffer_size); freerdp_dsp_context_reset_adpcm(oss->dsp_context); - while (WaitForSingleObject(oss->stopEvent, 0) != WAIT_OBJECT_0) { + while (WaitForSingleObject(oss->stopEvent, 0) != WAIT_OBJECT_0) + { tmp = read(pcm_handle, buffer, buffer_size); - if (tmp < 0) { /* Error happen. */ + + /* Error happen. */ + if (tmp < 0) + { OSS_LOG_ERR("read() error", errno); continue; } + if (tmp < buffer_size) /* Not enouth data. */ continue; + /* Process. */ switch (oss->format.wFormatTag) { case WAVE_FORMAT_ADPCM: @@ -253,11 +318,13 @@ err_out: setChannelError(oss->rdpcontext, error, "audin_oss_thread_func reported an error"); if (pcm_handle != -1) + { + WLog_INFO(TAG, "close: %s", dev_name); close(pcm_handle); + } + free(buffer); - ExitThread(0); - return NULL; } @@ -284,19 +351,19 @@ static WIN32ERROR audin_oss_open(IAudinDevice *device, AudinReceive receive, voi return CHANNEL_RC_OK; } -static WIN32ERROR audin_oss_close(IAudinDevice *device) { +static WIN32ERROR audin_oss_close(IAudinDevice *device) +{ AudinOSSDevice *oss = (AudinOSSDevice*)device; if (device == NULL) return ERROR_INVALID_PARAMETER; - if (oss->stopEvent != NULL) { + if (oss->stopEvent != NULL) + { SetEvent(oss->stopEvent); WaitForSingleObject(oss->thread, INFINITE); - CloseHandle(oss->stopEvent); oss->stopEvent = NULL; - CloseHandle(oss->thread); oss->thread = NULL; } @@ -307,7 +374,8 @@ static WIN32ERROR audin_oss_close(IAudinDevice *device) { return CHANNEL_RC_OK; } -static WIN32ERROR audin_oss_free(IAudinDevice *device) { +static WIN32ERROR audin_oss_free(IAudinDevice* device) +{ AudinOSSDevice *oss = (AudinOSSDevice*)device; int error; @@ -320,39 +388,40 @@ static WIN32ERROR audin_oss_free(IAudinDevice *device) { WLog_ERR(TAG, "audin_oss_close failed with error code %d!", error); } freerdp_dsp_context_free(oss->dsp_context); - free(oss); return CHANNEL_RC_OK; } -COMMAND_LINE_ARGUMENT_A audin_oss_args[] = { +COMMAND_LINE_ARGUMENT_A audin_oss_args[] = +{ { "dev", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "audio device name" }, { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } }; -static WIN32ERROR audin_oss_parse_addin_args(AudinOSSDevice *device, ADDIN_ARGV *args) { +static WIN32ERROR audin_oss_parse_addin_args(AudinOSSDevice *device, ADDIN_ARGV *args) +{ int status; - char *str_num, *eptr; + char* str_num, *eptr; DWORD flags; - COMMAND_LINE_ARGUMENT_A *arg; - AudinOSSDevice *oss = (AudinOSSDevice*)device; - + COMMAND_LINE_ARGUMENT_A* arg; + AudinOSSDevice* oss = (AudinOSSDevice*)device; flags = COMMAND_LINE_SIGIL_NONE | COMMAND_LINE_SEPARATOR_COLON | COMMAND_LINE_IGN_UNKNOWN_KEYWORD; - status = CommandLineParseArgumentsA(args->argc, (const char**)args->argv, audin_oss_args, flags, oss, NULL, NULL); + if (status < 0) return ERROR_INVALID_PARAMETER; arg = audin_oss_args; - do { + do + { if (!(arg->Flags & COMMAND_LINE_VALUE_PRESENT)) continue; CommandLineSwitchStart(arg) - - CommandLineSwitchCase(arg, "dev") { + CommandLineSwitchCase(arg, "dev") + { str_num = _strdup(arg->Value); if (!str_num) { @@ -360,14 +429,15 @@ static WIN32ERROR audin_oss_parse_addin_args(AudinOSSDevice *device, ADDIN_ARGV return CHANNEL_RC_NO_MEMORY; } oss->dev_unit = strtol(str_num, &eptr, 10); + if (oss->dev_unit < 0 || *eptr != '\0') oss->dev_unit = -1; + free(str_num); } - CommandLineSwitchEnd(arg) - } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); - + } + while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); return CHANNEL_RC_OK; } @@ -375,7 +445,8 @@ static WIN32ERROR audin_oss_parse_addin_args(AudinOSSDevice *device, ADDIN_ARGV #define freerdp_audin_client_subsystem_entry oss_freerdp_audin_client_subsystem_entry #endif -WIN32ERROR freerdp_audin_client_subsystem_entry(PFREERDP_AUDIN_DEVICE_ENTRY_POINTS pEntryPoints) { +WIN32ERROR freerdp_audin_client_subsystem_entry(PFREERDP_AUDIN_DEVICE_ENTRY_POINTS pEntryPoints) +{ ADDIN_ARGV *args; AudinOSSDevice *oss; WIN32ERROR error; @@ -395,7 +466,6 @@ WIN32ERROR freerdp_audin_client_subsystem_entry(PFREERDP_AUDIN_DEVICE_ENTRY_POIN oss->rdpcontext = pEntryPoints->rdpcontext; oss->dev_unit = -1; - args = pEntryPoints->args; if ((error = audin_oss_parse_addin_args(oss, args))) diff --git a/channels/cliprdr/client/cliprdr_main.c b/channels/cliprdr/client/cliprdr_main.c index 6deb30160..aca4ded8b 100644 --- a/channels/cliprdr/client/cliprdr_main.c +++ b/channels/cliprdr/client/cliprdr_main.c @@ -548,7 +548,7 @@ WIN32ERROR cliprdr_temp_directory(CliprdrClientContext* context, CLIPRDR_TEMP_DI if (length > 520) length = 520; - Stream_Write(s, tempDirectory->szTempDir, length * 2); + Stream_Write(s, wszTempDir, length * 2); Stream_Zero(s, (520 - length) * 2); free(wszTempDir); diff --git a/channels/drive/client/drive_main.c b/channels/drive/client/drive_main.c index b71a2f119..2c0e8aa57 100644 --- a/channels/drive/client/drive_main.c +++ b/channels/drive/client/drive_main.c @@ -38,6 +38,7 @@ #include #include +#include #include #include #include @@ -846,7 +847,7 @@ WIN32ERROR DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints) /* Special case: path[0] == '%' -> user home dir */ if (strcmp(drive->Path, "%") == 0) { - _snprintf(buf, sizeof(buf), "%s\\", getenv("USERPROFILE")); + sprintf_s(buf, sizeof(buf), "%s\\", getenv("USERPROFILE")); free(drive->Path); drive->Path = _strdup(buf); if (!drive->Path) @@ -868,7 +869,7 @@ WIN32ERROR DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints) if (*dev > 'B') { /* Suppress disk drives A and B to avoid pesty messages */ - len = _snprintf(buf, sizeof(buf) - 4, "%s", drive->Name); + len = sprintf_s(buf, sizeof(buf) - 4, "%s", drive->Name); buf[len] = '_'; buf[len + 1] = dev[0]; buf[len + 2] = 0; diff --git a/channels/printer/client/printer_cups.c b/channels/printer/client/printer_cups.c index efef804f8..cd40aeb70 100644 --- a/channels/printer/client/printer_cups.c +++ b/channels/printer/client/printer_cups.c @@ -32,6 +32,7 @@ #include #include +#include #include @@ -72,7 +73,7 @@ static void printer_cups_get_printjob_name(char* buf, int size) tt = time(NULL); t = localtime(&tt); - snprintf(buf, size - 1, "FreeRDP Print Job %d%02d%02d%02d%02d%02d", + sprintf_s(buf, size - 1, "FreeRDP Print Job %d%02d%02d%02d%02d%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); } @@ -94,6 +95,7 @@ static WIN32ERROR printer_cups_write_printjob(rdpPrintJob* printjob, BYTE* data, if (fwrite(data, 1, size, fp) < size) { return ERROR_INTERNAL_ERROR; + // FIXME once this function doesn't return void anymore! } fclose(fp); diff --git a/channels/printer/client/printer_main.c b/channels/printer/client/printer_main.c index b479c600f..db1e7cefd 100644 --- a/channels/printer/client/printer_main.c +++ b/channels/printer/client/printer_main.c @@ -28,6 +28,7 @@ #include #include +#include #include #include #include @@ -288,7 +289,7 @@ WIN32ERROR printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, rdpPrinte WLog_ERR(TAG, "malloc failed!"); return CHANNEL_RC_NO_MEMORY; } - snprintf(port, 10, "PRN%d", printer->id); + sprintf_s(port, 10, "PRN%d", printer->id); printer_dev = (PRINTER_DEVICE*) calloc(1, sizeof(PRINTER_DEVICE)); if (!printer_dev) diff --git a/channels/printer/client/printer_win.c b/channels/printer/client/printer_win.c index 0953b9aaa..efecb5f88 100644 --- a/channels/printer/client/printer_win.c +++ b/channels/printer/client/printer_win.c @@ -24,6 +24,7 @@ #endif #include +#include #include #include @@ -71,7 +72,7 @@ static void printer_win_get_printjob_name(char* buf, int size) tt = time(NULL); t = localtime(&tt); - snprintf(buf, size - 1, "FreeRDP Print Job %d%02d%02d%02d%02d%02d", + sprintf_s(buf, size - 1, "FreeRDP Print Job %d%02d%02d%02d%02d%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); } diff --git a/channels/printer/client/printer_win.h b/channels/printer/client/printer_win.h index 7f0660af5..fbd1dbc35 100644 --- a/channels/printer/client/printer_win.h +++ b/channels/printer/client/printer_win.h @@ -33,7 +33,3 @@ rdpPrinterDriver* printer_win_get_driver(void); #endif -#ifdef WIN32 -#define snprintf _snprintf -#endif - diff --git a/channels/rdpgfx/client/rdpgfx_main.c b/channels/rdpgfx/client/rdpgfx_main.c index 580f25689..d9e6866b5 100644 --- a/channels/rdpgfx/client/rdpgfx_main.c +++ b/channels/rdpgfx/client/rdpgfx_main.c @@ -43,6 +43,8 @@ #include "rdpgfx_main.h" +#define TAG CHANNELS_TAG("rdpgfx.client") + WIN32ERROR rdpgfx_send_caps_advertise_pdu(RDPGFX_CHANNEL_CALLBACK* callback) { WIN32ERROR error; @@ -87,7 +89,7 @@ WIN32ERROR rdpgfx_send_caps_advertise_pdu(RDPGFX_CHANNEL_CALLBACK* callback) header.pduLength = RDPGFX_HEADER_SIZE + 2 + (pdu.capsSetCount * RDPGFX_CAPSET_SIZE); - WLog_Print(gfx->log, WLOG_DEBUG, "SendCapsAdvertisePdu"); + WLog_DBG(TAG, "SendCapsAdvertisePdu"); s = Stream_New(NULL, header.pduLength); if (!s) @@ -144,7 +146,7 @@ WIN32ERROR rdpgfx_recv_caps_confirm_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wStre /*TODO: interpret this answer*/ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvCapsConfirmPdu: version: 0x%04X flags: 0x%04X", + WLog_DBG(TAG, "RecvCapsConfirmPdu: version: 0x%04X flags: 0x%04X", capsSet.version, capsSet.flags); return CHANNEL_RC_OK; @@ -161,7 +163,7 @@ WIN32ERROR rdpgfx_send_frame_acknowledge_pdu(RDPGFX_CHANNEL_CALLBACK* callback, header.cmdId = RDPGFX_CMDID_FRAMEACKNOWLEDGE; header.pduLength = RDPGFX_HEADER_SIZE + 12; - WLog_Print(gfx->log, WLOG_DEBUG, "SendFrameAcknowledgePdu: %d", pdu->frameId); + WLog_DBG(TAG, "SendFrameAcknowledgePdu: %d", pdu->frameId); s = Stream_New(NULL, header.pduLength); if (!s) @@ -244,7 +246,7 @@ WIN32ERROR rdpgfx_recv_reset_graphics_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wSt Stream_Seek(s, pad); /* pad (total size is 340 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvResetGraphicsPdu: width: %d height: %d count: %d", + WLog_DBG(TAG, "RecvResetGraphicsPdu: width: %d height: %d count: %d", pdu.width, pdu.height, pdu.monitorCount); if (context) @@ -274,7 +276,7 @@ WIN32ERROR rdpgfx_recv_evict_cache_entry_pdu(RDPGFX_CHANNEL_CALLBACK* callback, Stream_Read_UINT16(s, pdu.cacheSlot); /* cacheSlot (2 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvEvictCacheEntryPdu: cacheSlot: %d", pdu.cacheSlot); + WLog_DBG(TAG, "RecvEvictCacheEntryPdu: cacheSlot: %d", pdu.cacheSlot); if (context) { @@ -321,7 +323,7 @@ WIN32ERROR rdpgfx_recv_cache_import_reply_pdu(RDPGFX_CHANNEL_CALLBACK* callback, Stream_Read_UINT16(s, pdu.cacheSlots[index]); /* cacheSlot (2 bytes) */ } - WLog_Print(gfx->log, WLOG_DEBUG, "RecvCacheImportReplyPdu: importedEntriesCount: %d", + WLog_DBG(TAG, "RecvCacheImportReplyPdu: importedEntriesCount: %d", pdu.importedEntriesCount); if (context) @@ -354,7 +356,7 @@ WIN32ERROR rdpgfx_recv_create_surface_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wSt Stream_Read_UINT16(s, pdu.height); /* height (2 bytes) */ Stream_Read_UINT8(s, pdu.pixelFormat); /* RDPGFX_PIXELFORMAT (1 byte) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvCreateSurfacePdu: surfaceId: %d width: %d height: %d pixelFormat: 0x%02X", + WLog_DBG(TAG, "RecvCreateSurfacePdu: surfaceId: %d width: %d height: %d pixelFormat: 0x%02X", pdu.surfaceId, pdu.width, pdu.height, pdu.pixelFormat); if (context) @@ -382,7 +384,7 @@ WIN32ERROR rdpgfx_recv_delete_surface_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wSt Stream_Read_UINT16(s, pdu.surfaceId); /* surfaceId (2 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvDeleteSurfacePdu: surfaceId: %d", pdu.surfaceId); + WLog_DBG(TAG, "RecvDeleteSurfacePdu: surfaceId: %d", pdu.surfaceId); if (context) { @@ -410,7 +412,7 @@ WIN32ERROR rdpgfx_recv_start_frame_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wStrea Stream_Read_UINT32(s, pdu.timestamp); /* timestamp (4 bytes) */ Stream_Read_UINT32(s, pdu.frameId); /* frameId (4 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvStartFramePdu: frameId: %d timestamp: 0x%04X", + WLog_DBG(TAG, "RecvStartFramePdu: frameId: %d timestamp: 0x%04X", pdu.frameId, pdu.timestamp); if (context) @@ -441,7 +443,7 @@ WIN32ERROR rdpgfx_recv_end_frame_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wStream* Stream_Read_UINT32(s, pdu.frameId); /* frameId (4 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvEndFramePdu: frameId: %d", pdu.frameId); + WLog_DBG(TAG, "RecvEndFramePdu: frameId: %d", pdu.frameId); if (context) { @@ -503,7 +505,7 @@ WIN32ERROR rdpgfx_recv_wire_to_surface_1_pdu(RDPGFX_CHANNEL_CALLBACK* callback, pdu.bitmapData = Stream_Pointer(s); Stream_Seek(s, pdu.bitmapDataLength); - WLog_Print(gfx->log, WLOG_DEBUG, "RecvWireToSurface1Pdu: surfaceId: %d codecId: %s (0x%04X) pixelFormat: 0x%04X " + WLog_DBG(TAG, "RecvWireToSurface1Pdu: surfaceId: %d codecId: %s (0x%04X) pixelFormat: 0x%04X " "destRect: left: %d top: %d right: %d bottom: %d bitmapDataLength: %d", (int) pdu.surfaceId, rdpgfx_get_codec_id_string(pdu.codecId), pdu.codecId, pdu.pixelFormat, pdu.destRect.left, pdu.destRect.top, pdu.destRect.right, pdu.destRect.bottom, @@ -564,9 +566,10 @@ WIN32ERROR rdpgfx_recv_wire_to_surface_2_pdu(RDPGFX_CHANNEL_CALLBACK* callback, pdu.bitmapData = Stream_Pointer(s); Stream_Seek(s, pdu.bitmapDataLength); - WLog_Print(gfx->log, WLOG_DEBUG, "RecvWireToSurface2Pdu: surfaceId: %d codecId: 0x%04X " + WLog_DBG(TAG, "RecvWireToSurface2Pdu: surfaceId: %d codecId: %s (0x%04X) " "codecContextId: %d pixelFormat: 0x%04X bitmapDataLength: %d", - (int) pdu.surfaceId, pdu.codecId, pdu.codecContextId, pdu.pixelFormat, pdu.bitmapDataLength); + (int) pdu.surfaceId, rdpgfx_get_codec_id_string(pdu.codecId), pdu.codecId, + pdu.codecContextId, pdu.pixelFormat, pdu.bitmapDataLength); cmd.surfaceId = pdu.surfaceId; cmd.codecId = pdu.codecId; @@ -607,7 +610,7 @@ WIN32ERROR rdpgfx_recv_delete_encoding_context_pdu(RDPGFX_CHANNEL_CALLBACK* call Stream_Read_UINT16(s, pdu.surfaceId); /* surfaceId (2 bytes) */ Stream_Read_UINT32(s, pdu.codecContextId); /* codecContextId (4 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvDeleteEncodingContextPdu: surfaceId: %d codecContextId: %d", + WLog_DBG(TAG, "RecvDeleteEncodingContextPdu: surfaceId: %d codecContextId: %d", pdu.surfaceId, pdu.codecContextId); if (context) @@ -668,7 +671,7 @@ WIN32ERROR rdpgfx_recv_solid_fill_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wStream } } - WLog_Print(gfx->log, WLOG_DEBUG, "RecvSolidFillPdu: surfaceId: %d fillRectCount: %d", + WLog_DBG(TAG, "RecvSolidFillPdu: surfaceId: %d fillRectCount: %d", pdu.surfaceId, pdu.fillRectCount); if (context) @@ -733,7 +736,7 @@ WIN32ERROR rdpgfx_recv_surface_to_surface_pdu(RDPGFX_CHANNEL_CALLBACK* callback, } } - WLog_Print(gfx->log, WLOG_DEBUG, "RecvSurfaceToSurfacePdu: surfaceIdSrc: %d surfaceIdDest: %d " + WLog_DBG(TAG, "RecvSurfaceToSurfacePdu: surfaceIdSrc: %d surfaceIdDest: %d " "left: %d top: %d right: %d bottom: %d destPtsCount: %d", pdu.surfaceIdSrc, pdu.surfaceIdDest, pdu.rectSrc.left, pdu.rectSrc.top, pdu.rectSrc.right, pdu.rectSrc.bottom, @@ -773,7 +776,7 @@ WIN32ERROR rdpgfx_recv_surface_to_cache_pdu(RDPGFX_CHANNEL_CALLBACK* callback, w return error; } - WLog_Print(gfx->log, WLOG_DEBUG, "RecvSurfaceToCachePdu: surfaceId: %d cacheKey: 0x%08X cacheSlot: %d " + WLog_DBG(TAG, "RecvSurfaceToCachePdu: surfaceId: %d cacheKey: 0x%08X cacheSlot: %d " "left: %d top: %d right: %d bottom: %d", pdu.surfaceId, (int) pdu.cacheKey, pdu.cacheSlot, pdu.rectSrc.left, pdu.rectSrc.top, @@ -833,7 +836,7 @@ WIN32ERROR rdpgfx_recv_cache_to_surface_pdu(RDPGFX_CHANNEL_CALLBACK* callback, w } } - WLog_Print(gfx->log, WLOG_DEBUG, "RdpGfxRecvCacheToSurfacePdu: cacheSlot: %d surfaceId: %d destPtsCount: %d", + WLog_DBG(TAG, "RdpGfxRecvCacheToSurfacePdu: cacheSlot: %d surfaceId: %d destPtsCount: %d", pdu.cacheSlot, (int) pdu.surfaceId, pdu.destPtsCount); if (context) @@ -866,7 +869,7 @@ WIN32ERROR rdpgfx_recv_map_surface_to_output_pdu(RDPGFX_CHANNEL_CALLBACK* callba Stream_Read_UINT32(s, pdu.outputOriginX); /* outputOriginX (4 bytes) */ Stream_Read_UINT32(s, pdu.outputOriginY); /* outputOriginY (4 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvMapSurfaceToOutputPdu: surfaceId: %d outputOriginX: %d outputOriginY: %d", + WLog_DBG(TAG, "RecvMapSurfaceToOutputPdu: surfaceId: %d outputOriginX: %d outputOriginY: %d", (int) pdu.surfaceId, pdu.outputOriginX, pdu.outputOriginY); if (context) @@ -897,7 +900,7 @@ WIN32ERROR rdpgfx_recv_map_surface_to_window_pdu(RDPGFX_CHANNEL_CALLBACK* callba Stream_Read_UINT32(s, pdu.mappedWidth); /* mappedWidth (4 bytes) */ Stream_Read_UINT32(s, pdu.mappedHeight); /* mappedHeight (4 bytes) */ - WLog_Print(gfx->log, WLOG_DEBUG, "RecvMapSurfaceToWindowPdu: surfaceId: %d windowId: 0x%04X mappedWidth: %d mappedHeight: %d", + WLog_DBG(TAG, "RecvMapSurfaceToWindowPdu: surfaceId: %d windowId: 0x%04X mappedWidth: %d mappedHeight: %d", pdu.surfaceId, (int) pdu.windowId, pdu.mappedWidth, pdu.mappedHeight); if (context && context->MapSurfaceToWindow) @@ -926,7 +929,7 @@ WIN32ERROR rdpgfx_recv_pdu(RDPGFX_CHANNEL_CALLBACK* callback, wStream* s) } #if 1 - WLog_Print(gfx->log, WLOG_DEBUG, "cmdId: %s (0x%04X) flags: 0x%04X pduLength: %d", + WLog_DBG(TAG, "cmdId: %s (0x%04X) flags: 0x%04X pduLength: %d", rdpgfx_get_cmd_id_string(header.cmdId), header.cmdId, header.flags, header.pduLength); #endif @@ -1076,9 +1079,6 @@ static WIN32ERROR rdpgfx_on_data_received(IWTSVirtualChannelCallback* pChannelCa } Stream_Free(s, TRUE); - - //free(Stream_Buffer(data)); - //Stream_Free(data,TRUE); return error; } @@ -1088,7 +1088,7 @@ static WIN32ERROR rdpgfx_on_open(IWTSVirtualChannelCallback* pChannelCallback) RDPGFX_CHANNEL_CALLBACK* callback = (RDPGFX_CHANNEL_CALLBACK*) pChannelCallback; RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*) callback->plugin; - WLog_Print(gfx->log, WLOG_DEBUG, "OnOpen"); + WLog_DBG(TAG, "OnOpen"); return rdpgfx_send_caps_advertise_pdu(callback); } @@ -1098,7 +1098,7 @@ static WIN32ERROR rdpgfx_on_close(IWTSVirtualChannelCallback* pChannelCallback) RDPGFX_CHANNEL_CALLBACK* callback = (RDPGFX_CHANNEL_CALLBACK*) pChannelCallback; RDPGFX_PLUGIN* gfx = (RDPGFX_PLUGIN*) callback->plugin; - WLog_Print(gfx->log, WLOG_DEBUG, "OnClose"); + WLog_DBG(TAG, "OnClose"); free(callback); @@ -1155,7 +1155,7 @@ static WIN32ERROR rdpgfx_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChann gfx->listener->pInterface = gfx->iface.pInterface; - WLog_Print(gfx->log, WLOG_DEBUG, "Initialize"); + WLog_DBG(TAG, "Initialize"); return error; } @@ -1169,7 +1169,7 @@ static WIN32ERROR rdpgfx_plugin_terminated(IWTSPlugin* pPlugin) RdpgfxClientContext* context = (RdpgfxClientContext*) gfx->iface.pInterface; WIN32ERROR error = CHANNEL_RC_OK; - WLog_Print(gfx->log, WLOG_DEBUG, "Terminated"); + WLog_DBG(TAG, "Terminated"); if (gfx->listener_callback) { @@ -1351,7 +1351,6 @@ WIN32ERROR DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints) return CHANNEL_RC_NO_MEMORY; } - gfx->log = WLog_Get(TAG); gfx->settings = (rdpSettings*) pEntryPoints->GetRdpSettings(pEntryPoints); gfx->iface.Initialize = rdpgfx_plugin_initialize; @@ -1360,6 +1359,7 @@ WIN32ERROR DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints) gfx->iface.Terminated = rdpgfx_plugin_terminated; gfx->SurfaceTable = HashTable_New(TRUE); + if (!gfx->SurfaceTable) { free (gfx); diff --git a/channels/rdpgfx/client/rdpgfx_main.h b/channels/rdpgfx/client/rdpgfx_main.h index 380292d10..31663bf3e 100644 --- a/channels/rdpgfx/client/rdpgfx_main.h +++ b/channels/rdpgfx/client/rdpgfx_main.h @@ -32,8 +32,6 @@ #include #include -#define TAG CHANNELS_TAG("rdpgfx.client") - struct _RDPGFX_CHANNEL_CALLBACK { IWTSVirtualChannelCallback iface; @@ -61,7 +59,6 @@ struct _RDPGFX_PLUGIN IWTSListener* listener; RDPGFX_LISTENER_CALLBACK* listener_callback; - wLog* log; rdpSettings* settings; BOOL ThinClient; diff --git a/channels/rdpsnd/client/opensles/opensl_io.h b/channels/rdpsnd/client/opensles/opensl_io.h index c26aa0795..3a6762ffd 100644 --- a/channels/rdpsnd/client/opensles/opensl_io.h +++ b/channels/rdpsnd/client/opensles/opensl_io.h @@ -77,7 +77,7 @@ typedef struct opensl_stream { /* * Set the volume input level. */ - void android_SetOutputVolume(OPENSL_STREAM *p, int level); + void android_SetInputVolume(OPENSL_STREAM *p, int level); /* * Get the current output mute setting. */ diff --git a/channels/rdpsnd/client/oss/rdpsnd_oss.c b/channels/rdpsnd/client/oss/rdpsnd_oss.c index df99c46e9..4f1e913e8 100644 --- a/channels/rdpsnd/client/oss/rdpsnd_oss.c +++ b/channels/rdpsnd/client/oss/rdpsnd_oss.c @@ -28,6 +28,7 @@ #include #include +#include #include #include #include @@ -39,9 +40,9 @@ #include #include #if defined(__OpenBSD__) - #include +#include #else - #include +#include #endif #include @@ -53,7 +54,8 @@ typedef struct rdpsnd_oss_plugin rdpsndOssPlugin; -struct rdpsnd_oss_plugin { +struct rdpsnd_oss_plugin +{ rdpsndDevicePlugin device; int pcm_handle; @@ -65,68 +67,85 @@ struct rdpsnd_oss_plugin { int latency; AUDIO_FORMAT format; - FREERDP_DSP_CONTEXT *dsp_context; + FREERDP_DSP_CONTEXT* dsp_context; }; #define OSS_LOG_ERR(_text, _error) \ - if (_error != 0) \ - WLog_ERR(TAG, "%s: %i - %s", _text, _error, strerror(_error)); + { \ + if (_error != 0) \ + WLog_ERR(TAG, "%s: %i - %s", _text, _error, strerror(_error)); \ + } -static int rdpsnd_oss_get_format(AUDIO_FORMAT *format) { +static int rdpsnd_oss_get_format(AUDIO_FORMAT* format) +{ + switch (format->wFormatTag) + { + case WAVE_FORMAT_PCM: - switch (format->wFormatTag) { - case WAVE_FORMAT_PCM: - switch (format->wBitsPerSample) { - case 8: - return AFMT_S8; - case 16: - return AFMT_S16_LE; - } - break; - case WAVE_FORMAT_ALAW: - return AFMT_A_LAW; + switch (format->wBitsPerSample) + { + case 8: + return AFMT_S8; + case 16: + return AFMT_S16_LE; + } + + break; + case WAVE_FORMAT_ALAW: + return AFMT_A_LAW; #if 0 /* This does not work on my desktop. */ - case WAVE_FORMAT_MULAW: - return AFMT_MU_LAW; + case WAVE_FORMAT_MULAW: + return AFMT_MU_LAW; #endif - case WAVE_FORMAT_ADPCM: - case WAVE_FORMAT_DVI_ADPCM: - return AFMT_S16_LE; + case WAVE_FORMAT_ADPCM: + case WAVE_FORMAT_DVI_ADPCM: + return AFMT_S16_LE; } return 0; } -static BOOL rdpsnd_oss_format_supported(rdpsndDevicePlugin *device, AUDIO_FORMAT *format) { +static BOOL rdpsnd_oss_format_supported(rdpsndDevicePlugin* device, AUDIO_FORMAT* format) +{ int req_fmt = 0; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL || format == NULL) return FALSE; - switch (format->wFormatTag) { - case WAVE_FORMAT_PCM: - if (format->cbSize != 0 || - format->nSamplesPerSec > 48000 || - (format->wBitsPerSample != 8 && format->wBitsPerSample != 16) || - (format->nChannels != 1 && format->nChannels != 2)) - return FALSE; - break; - case WAVE_FORMAT_ADPCM: - case WAVE_FORMAT_DVI_ADPCM: - if (format->nSamplesPerSec > 48000 || - format->wBitsPerSample != 4 || - (format->nChannels != 1 && format->nChannels != 2)) - return FALSE; - break; + switch (format->wFormatTag) + { + case WAVE_FORMAT_PCM: + + if (format->cbSize != 0 || + format->nSamplesPerSec > 48000 || + (format->wBitsPerSample != 8 && format->wBitsPerSample != 16) || + (format->nChannels != 1 && format->nChannels != 2)) + return FALSE; + + break; + case WAVE_FORMAT_ADPCM: + case WAVE_FORMAT_DVI_ADPCM: + + if (format->nSamplesPerSec > 48000 || + format->wBitsPerSample != 4 || + (format->nChannels != 1 && format->nChannels != 2)) + return FALSE; + + break; } - + req_fmt = rdpsnd_oss_get_format(format); - if (oss->pcm_handle != -1) { /* Check really supported formats by dev. */ + + /* Check really supported formats by dev. */ + if (oss->pcm_handle != -1) + { if ((req_fmt & oss->supported_formats) == 0) return FALSE; - } else { + } + else + { if (req_fmt == 0) return FALSE; } @@ -134,17 +153,18 @@ static BOOL rdpsnd_oss_format_supported(rdpsndDevicePlugin *device, AUDIO_FORMAT return TRUE; } -static BOOL rdpsnd_oss_set_format(rdpsndDevicePlugin *device, AUDIO_FORMAT *format, int latency) { +static BOOL rdpsnd_oss_set_format(rdpsndDevicePlugin* device, AUDIO_FORMAT* format, int latency) +{ int tmp; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL || oss->pcm_handle == -1 || format == NULL) return FALSE; - + oss->latency = latency; CopyMemory(&(oss->format), format, sizeof(AUDIO_FORMAT)); - tmp = rdpsnd_oss_get_format(format); + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SETFMT, &tmp) == -1) { OSS_LOG_ERR("SNDCTL_DSP_SETFMT failed", errno); @@ -152,6 +172,7 @@ static BOOL rdpsnd_oss_set_format(rdpsndDevicePlugin *device, AUDIO_FORMAT *form } tmp = format->nChannels; + if (ioctl(oss->pcm_handle, SNDCTL_DSP_CHANNELS, &tmp) == -1) { OSS_LOG_ERR("SNDCTL_DSP_CHANNELS failed", errno); @@ -159,6 +180,7 @@ static BOOL rdpsnd_oss_set_format(rdpsndDevicePlugin *device, AUDIO_FORMAT *form } tmp = format->nSamplesPerSec; + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SPEED, &tmp) == -1) { OSS_LOG_ERR("SNDCTL_DSP_SPEED failed", errno); @@ -166,6 +188,7 @@ static BOOL rdpsnd_oss_set_format(rdpsndDevicePlugin *device, AUDIO_FORMAT *form } tmp = format->nBlockAlign; + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SETFRAGMENT, &tmp) == -1) { OSS_LOG_ERR("SNDCTL_DSP_SETFRAGMENT failed", errno); @@ -175,21 +198,26 @@ static BOOL rdpsnd_oss_set_format(rdpsndDevicePlugin *device, AUDIO_FORMAT *form return TRUE; } -static void rdpsnd_oss_open_mixer(rdpsndOssPlugin *oss) { +static void rdpsnd_oss_open_mixer(rdpsndOssPlugin* oss) +{ int devmask = 0; - char mixer[PATH_MAX] = "/dev/mixer"; + char mixer_name[PATH_MAX] = "/dev/mixer"; if (oss->mixer_handle != -1) return; if (oss->dev_unit != -1) - snprintf(mixer, PATH_MAX - 1, "/dev/mixer%i", oss->dev_unit); - if ((oss->mixer_handle = open(mixer, O_RDWR)) < 0) { + sprintf_s(mixer_name, PATH_MAX - 1, "/dev/mixer%i", oss->dev_unit); + + if ((oss->mixer_handle = open(mixer_name, O_RDWR)) < 0) + { OSS_LOG_ERR("mixer open failed", errno); oss->mixer_handle = -1; return; } - if (ioctl(oss->mixer_handle, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) { + + if (ioctl(oss->mixer_handle, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) + { OSS_LOG_ERR("SOUND_MIXER_READ_DEVMASK failed", errno); close(oss->mixer_handle); oss->mixer_handle = -1; @@ -197,18 +225,21 @@ static void rdpsnd_oss_open_mixer(rdpsndOssPlugin *oss) { } } -static BOOL rdpsnd_oss_open(rdpsndDevicePlugin *device, AUDIO_FORMAT *format, int latency) { +static BOOL rdpsnd_oss_open(rdpsndDevicePlugin* device, AUDIO_FORMAT* format, int latency) +{ char dev_name[PATH_MAX] = "/dev/dsp"; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL || oss->pcm_handle != -1) return TRUE; if (oss->dev_unit != -1) - snprintf(dev_name, PATH_MAX - 1, "/dev/dsp%i", oss->dev_unit); + sprintf_s(dev_name, PATH_MAX - 1, "/dev/dsp%i", oss->dev_unit); WLog_INFO(TAG, "open: %s", dev_name); - if ((oss->pcm_handle = open(dev_name, O_WRONLY)) < 0) { + + if ((oss->pcm_handle = open(dev_name, O_WRONLY)) < 0) + { OSS_LOG_ERR("sound dev open failed", errno); oss->pcm_handle = -1; return FALSE; @@ -217,17 +248,22 @@ static BOOL rdpsnd_oss_open(rdpsndDevicePlugin *device, AUDIO_FORMAT *format, in #if 0 /* FreeBSD OSS implementation at this moment (2015.03) does not set PCM_CAP_OUTPUT flag. */ int mask = 0; - if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETCAPS, &mask) == -1) { + if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETCAPS, &mask) == -1) + { OSS_LOG_ERR("SNDCTL_DSP_GETCAPS failed, try ignory", errno); - } else if ((mask & PCM_CAP_OUTPUT) == 0) { + } + else if ((mask & PCM_CAP_OUTPUT) == 0) + { OSS_LOG_ERR("Device does not supports playback", EOPNOTSUPP); close(oss->pcm_handle); oss->pcm_handle = -1; return; } + #endif - if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETFMTS, &oss->supported_formats) == -1) { + if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETFMTS, &oss->supported_formats) == -1) + { OSS_LOG_ERR("SNDCTL_DSP_GETFMTS failed", errno); close(oss->pcm_handle); oss->pcm_handle = -1; @@ -240,81 +276,89 @@ static BOOL rdpsnd_oss_open(rdpsndDevicePlugin *device, AUDIO_FORMAT *format, in return TRUE; } -static void rdpsnd_oss_close(rdpsndDevicePlugin *device) { - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; +static void rdpsnd_oss_close(rdpsndDevicePlugin* device) +{ + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL) return; - if (oss->pcm_handle != -1) { + if (oss->pcm_handle != -1) + { + WLog_INFO(TAG, "close: dsp"); close(oss->pcm_handle); oss->pcm_handle = -1; } - if (oss->mixer_handle != -1) { + if (oss->mixer_handle != -1) + { + WLog_INFO(TAG, "close: mixer"); close(oss->mixer_handle); oss->mixer_handle = -1; } } -static void rdpsnd_oss_free(rdpsndDevicePlugin *device) { - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; +static void rdpsnd_oss_free(rdpsndDevicePlugin* device) +{ + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL) return; rdpsnd_oss_close(device); freerdp_dsp_context_free(oss->dsp_context); - free(oss); } -static UINT32 rdpsnd_oss_get_volume(rdpsndDevicePlugin *device) { +static UINT32 rdpsnd_oss_get_volume(rdpsndDevicePlugin* device) +{ int vol; UINT32 dwVolume; UINT16 dwVolumeLeft, dwVolumeRight; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; - + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; /* On error return 50% volume. */ dwVolumeLeft = ((50 * 0xFFFF) / 100); /* 50% */ dwVolumeRight = ((50 * 0xFFFF) / 100); /* 50% */ dwVolume = ((dwVolumeLeft << 16) | dwVolumeRight); - + if (device == NULL || oss->mixer_handle == -1) return dwVolume; - - if (ioctl(oss->mixer_handle, MIXER_READ(SOUND_MIXER_VOLUME), &vol) == -1) { + + if (ioctl(oss->mixer_handle, MIXER_READ(SOUND_MIXER_VOLUME), &vol) == -1) + { OSS_LOG_ERR("MIXER_READ", errno); return dwVolume; } - + dwVolumeLeft = (((vol & 0x7f) * 0xFFFF) / 100); dwVolumeRight = ((((vol >> 8) & 0x7f) * 0xFFFF) / 100); dwVolume = ((dwVolumeLeft << 16) | dwVolumeRight); - return dwVolume; } -static BOOL rdpsnd_oss_set_volume(rdpsndDevicePlugin *device, UINT32 value) { +static BOOL rdpsnd_oss_set_volume(rdpsndDevicePlugin* device, UINT32 value) +{ int left, right; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL || oss->mixer_handle == -1) return FALSE; - left = (value & 0xFFFF); - right = ((value >> 16) & 0xFFFF); + left = (((value & 0xFFFF) * 100) / 0xFFFF); + right = ((((value >> 16) & 0xFFFF) * 100) / 0xFFFF); if (left < 0) left = 0; else if (left > 100) left = 100; + if (right < 0) right = 0; else if (right > 100) right = 100; left |= (right << 8); + if (ioctl(oss->mixer_handle, MIXER_WRITE(SOUND_MIXER_VOLUME), &left) == -1) { OSS_LOG_ERR("WRITE_MIXER", errno); @@ -324,45 +368,36 @@ static BOOL rdpsnd_oss_set_volume(rdpsndDevicePlugin *device, UINT32 value) { return TRUE; } -static BOOL rdpsnd_oss_wave_decode(rdpsndDevicePlugin *device, RDPSND_WAVE *wave) { - int size; - BYTE *data; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; +static BOOL rdpsnd_oss_wave_decode(rdpsndDevicePlugin* device, RDPSND_WAVE* wave) +{ + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL || wave == NULL) return FALSE; - switch (oss->format.wFormatTag) { - case WAVE_FORMAT_ADPCM: - oss->dsp_context->decode_ms_adpcm(oss->dsp_context, - wave->data, wave->length, oss->format.nChannels, oss->format.nBlockAlign); - size = oss->dsp_context->adpcm_size; - data = oss->dsp_context->adpcm_buffer; - break; - case WAVE_FORMAT_DVI_ADPCM: - oss->dsp_context->decode_ima_adpcm(oss->dsp_context, - wave->data, wave->length, oss->format.nChannels, oss->format.nBlockAlign); - size = oss->dsp_context->adpcm_size; - data = oss->dsp_context->adpcm_buffer; - break; - default: - size = wave->length; - data = wave->data; + switch (oss->format.wFormatTag) + { + case WAVE_FORMAT_ADPCM: + oss->dsp_context->decode_ms_adpcm(oss->dsp_context, + wave->data, wave->length, oss->format.nChannels, oss->format.nBlockAlign); + wave->length = oss->dsp_context->adpcm_size; + wave->data = oss->dsp_context->adpcm_buffer; + break; + case WAVE_FORMAT_DVI_ADPCM: + oss->dsp_context->decode_ima_adpcm(oss->dsp_context, + wave->data, wave->length, oss->format.nChannels, oss->format.nBlockAlign); + wave->length = oss->dsp_context->adpcm_size; + wave->data = oss->dsp_context->adpcm_buffer; + break; } - - wave->data = (BYTE*)malloc(size); - if (!wave->data) - return FALSE; - - CopyMemory(wave->data, data, size); - wave->length = size; return TRUE; } -static void rdpsnd_oss_wave_play(rdpsndDevicePlugin *device, RDPSND_WAVE *wave) { - BYTE *data; - int offset, size, status; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; +static void rdpsnd_oss_wave_play(rdpsndDevicePlugin* device, RDPSND_WAVE* wave) +{ + BYTE* data; + int offset, size, status, latency; + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; if (device == NULL || wave == NULL) return; @@ -370,64 +405,72 @@ static void rdpsnd_oss_wave_play(rdpsndDevicePlugin *device, RDPSND_WAVE *wave) offset = 0; data = wave->data; size = wave->length; + latency = oss->latency; - while (offset < size) { + while (offset < size) + { status = write(oss->pcm_handle, &data[offset], (size - offset)); - if (status < 0) { + + if (status < 0) + { OSS_LOG_ERR("write fail", errno); rdpsnd_oss_close(device); - rdpsnd_oss_open(device, NULL, 0); + rdpsnd_oss_open(device, NULL, latency); break; } + offset += status; } - /* From rdpsnd_main.c */ - wave->wTimeStampB = wave->wTimeStampA + wave->wAudioLength + 65; - wave->wLocalTimeB = wave->wLocalTimeA + wave->wAudioLength + 65; - free(data); + /* From rdpsnd_main.c */ + wave->wTimeStampB = wave->wTimeStampA + wave->wAudioLength + 65 + latency; + wave->wLocalTimeB = wave->wLocalTimeA + wave->wAudioLength + 65 + latency; } -static COMMAND_LINE_ARGUMENT_A rdpsnd_oss_args[] = { +static COMMAND_LINE_ARGUMENT_A rdpsnd_oss_args[] = +{ { "dev", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "device" }, { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } }; -static int rdpsnd_oss_parse_addin_args(rdpsndDevicePlugin *device, ADDIN_ARGV *args) { +static int rdpsnd_oss_parse_addin_args(rdpsndDevicePlugin* device, ADDIN_ARGV* args) +{ int status; - char *str_num, *eptr; + char* str_num, *eptr; DWORD flags; - COMMAND_LINE_ARGUMENT_A *arg; - rdpsndOssPlugin *oss = (rdpsndOssPlugin*)device; - + COMMAND_LINE_ARGUMENT_A* arg; + rdpsndOssPlugin* oss = (rdpsndOssPlugin*)device; flags = COMMAND_LINE_SIGIL_NONE | COMMAND_LINE_SEPARATOR_COLON | COMMAND_LINE_IGN_UNKNOWN_KEYWORD; - status = CommandLineParseArgumentsA(args->argc, (const char**)args->argv, rdpsnd_oss_args, flags, oss, NULL, NULL); + if (status < 0) return status; arg = rdpsnd_oss_args; - do { + do + { if (!(arg->Flags & COMMAND_LINE_VALUE_PRESENT)) continue; CommandLineSwitchStart(arg) - - CommandLineSwitchCase(arg, "dev") { + CommandLineSwitchCase(arg, "dev") + { str_num = _strdup(arg->Value); if (!str_num) return ERROR_OUTOFMEMORY; oss->dev_unit = strtol(str_num, &eptr, 10); + if (oss->dev_unit < 0 || *eptr != '\0') oss->dev_unit = -1; + free(str_num); } - CommandLineSwitchEnd(arg) - } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + } + while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); return status; } @@ -436,14 +479,13 @@ static int rdpsnd_oss_parse_addin_args(rdpsndDevicePlugin *device, ADDIN_ARGV *a #define freerdp_rdpsnd_client_subsystem_entry oss_freerdp_rdpsnd_client_subsystem_entry #endif -WIN32ERROR freerdp_rdpsnd_client_subsystem_entry(PFREERDP_RDPSND_DEVICE_ENTRY_POINTS pEntryPoints) { - ADDIN_ARGV *args; - rdpsndOssPlugin *oss; - +WIN32ERROR freerdp_rdpsnd_client_subsystem_entry(PFREERDP_RDPSND_DEVICE_ENTRY_POINTS pEntryPoints) +{ + ADDIN_ARGV* args; + rdpsndOssPlugin* oss; oss = (rdpsndOssPlugin*)calloc(1, sizeof(rdpsndOssPlugin)); if (!oss) return CHANNEL_RC_NO_MEMORY; - oss->device.Open = rdpsnd_oss_open; oss->device.FormatSupported = rdpsnd_oss_format_supported; oss->device.SetFormat = rdpsnd_oss_set_format; @@ -453,14 +495,11 @@ WIN32ERROR freerdp_rdpsnd_client_subsystem_entry(PFREERDP_RDPSND_DEVICE_ENTRY_PO oss->device.WavePlay = rdpsnd_oss_wave_play; oss->device.Close = rdpsnd_oss_close; oss->device.Free = rdpsnd_oss_free; - oss->pcm_handle = -1; oss->mixer_handle = -1; oss->dev_unit = -1; - args = pEntryPoints->args; rdpsnd_oss_parse_addin_args((rdpsndDevicePlugin*)oss, args); - oss->dsp_context = freerdp_dsp_context_new(); if (!oss->dsp_context) { diff --git a/channels/remdesk/client/remdesk_main.c b/channels/remdesk/client/remdesk_main.c index 4f3707711..9b25042de 100644 --- a/channels/remdesk/client/remdesk_main.c +++ b/channels/remdesk/client/remdesk_main.c @@ -40,7 +40,7 @@ RemdeskClientContext* remdesk_get_client_interface(remdeskPlugin* remdesk) return pInterface; } -WIN32ERROR remdesk_virtual_channel_write(remdeskPlugin* remdesk, wStream* s) +static WIN32ERROR remdesk_virtual_channel_write(remdeskPlugin* remdesk, wStream* s) { UINT32 status; diff --git a/channels/remdesk/server/remdesk_main.c b/channels/remdesk/server/remdesk_main.c index 1b3b4907e..9f85100fa 100644 --- a/channels/remdesk/server/remdesk_main.c +++ b/channels/remdesk/server/remdesk_main.c @@ -29,7 +29,7 @@ #include "remdesk_main.h" -WIN32ERROR remdesk_virtual_channel_write(RemdeskServerContext* context, wStream* s) +static WIN32ERROR remdesk_virtual_channel_write(RemdeskServerContext* context, wStream* s) { BOOL status; ULONG BytesWritten = 0; diff --git a/channels/tsmf/client/CMakeLists.txt b/channels/tsmf/client/CMakeLists.txt index 462ce246c..b47a616a2 100644 --- a/channels/tsmf/client/CMakeLists.txt +++ b/channels/tsmf/client/CMakeLists.txt @@ -62,6 +62,10 @@ if(WITH_GSTREAMER_0_10 OR WITH_GSTREAMER_1_0) endif() endif() +if(WITH_OSS) + add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "oss" "audio") +endif() + if(WITH_ALSA) add_channel_client_subsystem(${MODULE_PREFIX} ${CHANNEL_NAME} "alsa" "audio") endif() diff --git a/channels/tsmf/client/alsa/tsmf_alsa.c b/channels/tsmf/client/alsa/tsmf_alsa.c index 5d8b68575..91af225a8 100644 --- a/channels/tsmf/client/alsa/tsmf_alsa.c +++ b/channels/tsmf/client/alsa/tsmf_alsa.c @@ -68,8 +68,7 @@ static BOOL tsmf_alsa_open(ITSMFAudioDevice *audio, const char *device) TSMFAlsaAudioDevice *alsa = (TSMFAlsaAudioDevice *) audio; if(!device) { - if(!alsa->device[0]) - strncpy(alsa->device, "default", sizeof(alsa->device)); + strncpy(alsa->device, "default", sizeof(alsa->device)); } else { diff --git a/channels/tsmf/client/gstreamer/tsmf_X11.c b/channels/tsmf/client/gstreamer/tsmf_X11.c index c3950f066..0ea6a166f 100644 --- a/channels/tsmf/client/gstreamer/tsmf_X11.c +++ b/channels/tsmf/client/gstreamer/tsmf_X11.c @@ -25,7 +25,11 @@ #include #include +#include +#include +#include #include +#include #include #if GST_VERSION_MAJOR > 0 @@ -61,8 +65,8 @@ struct X11Handle static const char* get_shm_id() { - static char shm_id[64]; - snprintf(shm_id, sizeof(shm_id), "com.freerdp.xfreerdp.tsmf_%016X", GetCurrentProcessId()); + static char shm_id[128]; + sprintf_s(shm_id, sizeof(shm_id), "/com.freerdp.xfreerdp.tsmf_%016X", GetCurrentProcessId()); return shm_id; } @@ -87,7 +91,6 @@ int tsmf_platform_create(TSMFGstreamerDecoder* decoder) return -1; hdl = calloc(1, sizeof(struct X11Handle)); - if (!hdl) { WLog_ERR(TAG, "Could not allocate handle."); @@ -95,26 +98,21 @@ int tsmf_platform_create(TSMFGstreamerDecoder* decoder) } decoder->platform = hdl; - hdl->shmid = shm_open(get_shm_id(), O_RDWR, PROT_READ | PROT_WRITE);; - - if (hdl->shmid < 0) + hdl->shmid = shm_open(get_shm_id(), (O_RDWR | O_CREAT), (PROT_READ | PROT_WRITE)); + if (hdl->shmid == -1) { - WLog_ERR(TAG, "failed to get access to shared memory - shmget()"); + WLog_ERR(TAG, "failed to get access to shared memory - shmget(%s): %i - %s", get_shm_id(), errno, strerror(errno)); return -2; } - else - { - hdl->xfwin = mmap(0, sizeof(void *), PROT_READ | PROT_WRITE, MAP_SHARED, hdl->shmid, 0); - } - if (hdl->xfwin == (int*)-1) + hdl->xfwin = mmap(0, sizeof(void *), PROT_READ | PROT_WRITE, MAP_SHARED, hdl->shmid, 0); + if (hdl->xfwin == MAP_FAILED) { WLog_ERR(TAG, "shmat failed!"); return -3; } hdl->disp = XOpenDisplay(NULL); - if (!hdl->disp) { WLog_ERR(TAG, "Failed to open display"); diff --git a/channels/tsmf/client/gstreamer/tsmf_gstreamer.c b/channels/tsmf/client/gstreamer/tsmf_gstreamer.c index 56a3d1ef5..fac74c12a 100644 --- a/channels/tsmf/client/gstreamer/tsmf_gstreamer.c +++ b/channels/tsmf/client/gstreamer/tsmf_gstreamer.c @@ -31,6 +31,8 @@ #include #include +#include + #include #include #include @@ -422,9 +424,9 @@ BOOL tsmf_gstreamer_pipeline_build(TSMFGstreamerDecoder* mdecoder) * The only fixed elements necessary are appsrc and the volume element for audio streams. * The rest could easily be provided in gstreamer pipeline notation from command line. */ if (mdecoder->media_type == TSMF_MAJOR_TYPE_VIDEO) - snprintf(pipeline, sizeof(pipeline), "%s %s %s name=outsink", appsrc, video, tsmf_platform_get_video_sink()); + sprintf_s(pipeline, sizeof(pipeline), "%s %s %s name=outsink", appsrc, video, tsmf_platform_get_video_sink()); else - snprintf(pipeline, sizeof(pipeline), "%s %s %s name=outsink", appsrc, audio, tsmf_platform_get_audio_sink()); + sprintf_s(pipeline, sizeof(pipeline), "%s %s %s name=outsink", appsrc, audio, tsmf_platform_get_audio_sink()); DEBUG_TSMF("pipeline=%s", pipeline); mdecoder->pipe = gst_parse_launch(pipeline, NULL); diff --git a/channels/tsmf/client/oss/CMakeLists.txt b/channels/tsmf/client/oss/CMakeLists.txt new file mode 100644 index 000000000..b0d39b6a9 --- /dev/null +++ b/channels/tsmf/client/oss/CMakeLists.txt @@ -0,0 +1,32 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright (c) 2015 Rozhuk Ivan +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +define_channel_client_subsystem("tsmf" "oss" "audio") + +set(${MODULE_PREFIX}_SRCS + tsmf_oss.c) + +include_directories(..) +include_directories(${OSS_INCLUDE_DIRS}) + +add_channel_client_subsystem_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} "" TRUE "") + + + +target_link_libraries(${MODULE_NAME} freerdp ${OSS_LIBRARIES}) + +install(TARGETS ${MODULE_NAME} DESTINATION ${FREERDP_ADDIN_PATH} EXPORT FreeRDPTargets) diff --git a/channels/tsmf/client/oss/tsmf_oss.c b/channels/tsmf/client/oss/tsmf_oss.c new file mode 100644 index 000000000..2ae4713b8 --- /dev/null +++ b/channels/tsmf/client/oss/tsmf_oss.c @@ -0,0 +1,251 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Redirection Virtual Channel - OSS Audio Device + * + * Copyright (c) 2015 Rozhuk Ivan + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "tsmf_audio.h" + + +typedef struct _TSMFOSSAudioDevice +{ + ITSMFAudioDevice iface; + + char dev_name[PATH_MAX]; + int pcm_handle; + + UINT32 sample_rate; + UINT32 channels; + UINT32 bits_per_sample; + + UINT32 data_size_last; +} TSMFOssAudioDevice; + + +#define OSS_LOG_ERR(_text, _error) \ + if (_error != 0) \ + WLog_ERR(TAG, "%s: %i - %s", _text, _error, strerror(_error)); + + +static BOOL tsmf_oss_open(ITSMFAudioDevice* audio, const char* device) +{ + int tmp; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL || oss->pcm_handle != -1) + return FALSE; + + if (device == NULL) /* Default device. */ + { + strncpy(oss->dev_name, "/dev/dsp", sizeof(oss->dev_name)); + } + else + { + strncpy(oss->dev_name, device, sizeof(oss->dev_name)); + } + + if ((oss->pcm_handle = open(oss->dev_name, O_WRONLY)) < 0) + { + OSS_LOG_ERR("sound dev open failed", errno); + oss->pcm_handle = -1; + return FALSE; + } + +#if 0 /* FreeBSD OSS implementation at this moment (2015.03) does not set PCM_CAP_OUTPUT flag. */ + tmp = 0; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETCAPS, &mask) == -1) + { + OSS_LOG_ERR("SNDCTL_DSP_GETCAPS failed, try ignory", errno); + } + else if ((mask & PCM_CAP_OUTPUT) == 0) + { + OSS_LOG_ERR("Device does not supports playback", EOPNOTSUPP); + close(oss->pcm_handle); + oss->pcm_handle = -1; + return FALSE; + } + +#endif + tmp = 0; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_GETFMTS, &tmp) == -1) + { + OSS_LOG_ERR("SNDCTL_DSP_GETFMTS failed", errno); + close(oss->pcm_handle); + oss->pcm_handle = -1; + return FALSE; + } + + if ((AFMT_S16_LE & tmp) == 0) + { + OSS_LOG_ERR("SNDCTL_DSP_GETFMTS - AFMT_S16_LE", EOPNOTSUPP); + close(oss->pcm_handle); + oss->pcm_handle = -1; + return FALSE; + } + + WLog_INFO(TAG, "open: %s", oss->dev_name); + return TRUE; +} + +static BOOL tsmf_oss_set_format(ITSMFAudioDevice* audio, UINT32 sample_rate, UINT32 channels, UINT32 bits_per_sample) +{ + int tmp; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL || oss->pcm_handle == -1) + return FALSE; + + oss->sample_rate = sample_rate; + oss->channels = channels; + oss->bits_per_sample = bits_per_sample; + tmp = AFMT_S16_LE; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SETFMT, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_SETFMT failed", errno); + + tmp = channels; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_CHANNELS, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_CHANNELS failed", errno); + + tmp = sample_rate; + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SPEED, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_SPEED failed", errno); + + tmp = ((bits_per_sample / 8) * channels * sample_rate); + + if (ioctl(oss->pcm_handle, SNDCTL_DSP_SETFRAGMENT, &tmp) == -1) + OSS_LOG_ERR("SNDCTL_DSP_SETFRAGMENT failed", errno); + + DEBUG_TSMF("sample_rate %d channels %d bits_per_sample %d", + sample_rate, channels, bits_per_sample); + return TRUE; +} + +static BOOL tsmf_oss_play(ITSMFAudioDevice* audio, BYTE* data, UINT32 data_size) +{ + int status; + UINT32 offset; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + DEBUG_TSMF("tsmf_oss_play: data_size %d", data_size); + + if (oss == NULL || oss->pcm_handle == -1) + return FALSE; + + if (data == NULL || data_size == 0) + { + free(data); + return TRUE; + } + + offset = 0; + oss->data_size_last = data_size; + + while (offset < data_size) + { + status = write(oss->pcm_handle, &data[offset], (data_size - offset)); + + if (status < 0) + { + OSS_LOG_ERR("write fail", errno); + free(data); + return FALSE; + } + + offset += status; + } + + free(data); + return TRUE; +} + +static UINT64 tsmf_oss_get_latency(ITSMFAudioDevice* audio) +{ + UINT64 latency = 0; + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL) + return 0; + + //latency = ((oss->data_size_last / (oss->bits_per_sample / 8)) * oss->sample_rate); + //WLog_INFO(TAG, "latency: %zu", latency); + return latency; +} + +static void tsmf_oss_flush(ITSMFAudioDevice* audio) +{ +} + +static void tsmf_oss_free(ITSMFAudioDevice* audio) +{ + TSMFOssAudioDevice* oss = (TSMFOssAudioDevice*)audio; + + if (oss == NULL) + return; + + if (oss->pcm_handle != -1) + { + WLog_INFO(TAG, "close: %s", oss->dev_name); + close(oss->pcm_handle); + } + + free(oss); +} + +#ifdef STATIC_CHANNELS +#define freerdp_tsmf_client_audio_subsystem_entry oss_freerdp_tsmf_client_audio_subsystem_entry +#endif + +ITSMFAudioDevice* freerdp_tsmf_client_audio_subsystem_entry(void) +{ + TSMFOssAudioDevice* oss; + oss = (TSMFOssAudioDevice*)malloc(sizeof(TSMFOssAudioDevice)); + ZeroMemory(oss, sizeof(TSMFOssAudioDevice)); + oss->iface.Open = tsmf_oss_open; + oss->iface.SetFormat = tsmf_oss_set_format; + oss->iface.Play = tsmf_oss_play; + oss->iface.GetLatency = tsmf_oss_get_latency; + oss->iface.Flush = tsmf_oss_flush; + oss->iface.Free = tsmf_oss_free; + oss->pcm_handle = -1; + return (ITSMFAudioDevice*)oss; +} diff --git a/channels/tsmf/client/tsmf_audio.c b/channels/tsmf/client/tsmf_audio.c index 5b4e7fdb9..a71b016b3 100644 --- a/channels/tsmf/client/tsmf_audio.c +++ b/channels/tsmf/client/tsmf_audio.c @@ -49,6 +49,11 @@ static ITSMFAudioDevice* tsmf_load_audio_device_by_name(const char* name, const { audio->Free(audio); audio = NULL; + WLog_ERR(TAG, "failed to open, name: %s, device: %s", name, device); + } + else + { + WLog_DBG(TAG, "name: %s, device: %s", name, device); } return audio; @@ -56,7 +61,7 @@ static ITSMFAudioDevice* tsmf_load_audio_device_by_name(const char* name, const ITSMFAudioDevice* tsmf_load_audio_device(const char* name, const char* device) { - ITSMFAudioDevice* audio; + ITSMFAudioDevice* audio = NULL; if (name) { @@ -64,10 +69,29 @@ ITSMFAudioDevice* tsmf_load_audio_device(const char* name, const char* device) } else { - audio = tsmf_load_audio_device_by_name("pulse", device); +#if defined(WITH_PULSE) + if (!audio) + audio = tsmf_load_audio_device_by_name("pulse", device); +#endif +#if defined(WITH_OSS) + if (!audio) + audio = tsmf_load_audio_device_by_name("oss", device); +#endif + +#if defined(WITH_ALSA) if (!audio) audio = tsmf_load_audio_device_by_name("alsa", device); +#endif + } + + if (audio == NULL) + { + WLog_ERR(TAG, "no sound device."); + } + else + { + WLog_DBG(TAG, "name: %s, device: %s", name, device); } return audio; diff --git a/channels/tsmf/client/tsmf_main.c b/channels/tsmf/client/tsmf_main.c index 648774a9a..9a336c85c 100644 --- a/channels/tsmf/client/tsmf_main.c +++ b/channels/tsmf/client/tsmf_main.c @@ -399,8 +399,8 @@ static WIN32ERROR tsmf_plugin_terminated(IWTSPlugin* pPlugin) COMMAND_LINE_ARGUMENT_A tsmf_args[] = { - { "audio", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "audio subsystem" }, - { "audio-dev", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "audio device name" }, + { "sys", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "audio subsystem" }, + { "dev", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "audio device name" }, { "decoder", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "decoder subsystem" }, { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } }; @@ -426,13 +426,13 @@ static WIN32ERROR tsmf_process_addin_args(IWTSPlugin *pPlugin, ADDIN_ARGV *args) if (!(arg->Flags & COMMAND_LINE_VALUE_PRESENT)) continue; CommandLineSwitchStart(arg) - CommandLineSwitchCase(arg, "audio") + CommandLineSwitchCase(arg, "sys") { tsmf->audio_name = _strdup(arg->Value); if (!tsmf->audio_name) return ERROR_OUTOFMEMORY; } - CommandLineSwitchCase(arg, "audio-dev") + CommandLineSwitchCase(arg, "dev") { tsmf->audio_device = _strdup(arg->Value); if (!tsmf->audio_device) diff --git a/channels/tsmf/client/tsmf_media.c b/channels/tsmf/client/tsmf_media.c index f6e045fd5..3ccfbb426 100644 --- a/channels/tsmf/client/tsmf_media.c +++ b/channels/tsmf/client/tsmf_media.c @@ -39,6 +39,7 @@ #include #include +#include #include #include #include @@ -320,7 +321,7 @@ static char* guid_to_string(const BYTE* guid, char* str, size_t len) return NULL; for (i=0; i 2*i; i++) - snprintf(str + (2*i), len - 2*i, "%02X", guid[i]); + sprintf_s(str + (2*i), len - 2*i, "%02X", guid[i]); return str; } @@ -397,10 +398,10 @@ static BOOL tsmf_sample_playback_video(TSMF_SAMPLE* sample) if ((frame_id % 30) == 0) { - snprintf(buf, sizeof(buf), "/tmp/FreeRDP_Frame_%d.ppm", frame_id); + sprintf_s(buf, sizeof(buf), "/tmp/FreeRDP_Frame_%d.ppm", frame_id); fp = fopen(buf, "wb"); fwrite("P5\n", 1, 3, fp); - snprintf(buf, sizeof(buf), "%d %d\n", sample->stream->width, sample->stream->height); + sprintf_s(buf, sizeof(buf), "%d %d\n", sample->stream->width, sample->stream->height); fwrite(buf, 1, strlen(buf), fp); fwrite("255\n", 1, 4, fp); fwrite(sample->data, 1, sample->stream->width * sample->stream->height, fp); @@ -432,13 +433,13 @@ static BOOL tsmf_sample_playback_audio(TSMF_SAMPLE* sample) DEBUG_TSMF("MessageId %d EndTime %d consumed.", sample->sample_id, (int)sample->end_time); - if (sample->stream->audio && sample->data) + if (stream->audio && sample->data) { ret = sample->stream->audio->Play(sample->stream->audio, sample->data, sample->decoded_size); sample->data = NULL; sample->decoded_size = 0; - if (stream->audio && stream->audio->GetLatency) + if (stream->audio->GetLatency) latency = stream->audio->GetLatency(stream->audio); } else diff --git a/channels/urbdrc/CMakeLists.txt b/channels/urbdrc/CMakeLists.txt index 2e10bd89b..995c63b71 100644 --- a/channels/urbdrc/CMakeLists.txt +++ b/channels/urbdrc/CMakeLists.txt @@ -18,15 +18,28 @@ define_channel("urbdrc") if(NOT WIN32) + find_package(DevD) find_package(UDev) find_package(UUID) find_package(DbusGlib) find_package(libusb-1.0) endif() -if(UDEV_FOUND AND UUID_FOUND AND DBUS_GLIB_FOUND AND LIBUSB_1_FOUND) - set(URBDRC_DEPENDENCIES_FOUND TRUE) - message(STATUS "Found all URBDRC dependencies") +if(DEVD_FOUND OR UDEV_FOUND) + if(UUID_FOUND AND DBUS_GLIB_FOUND AND LIBUSB_1_FOUND) + set(URBDRC_DEPENDENCIES_FOUND TRUE) + message(STATUS "Found all URBDRC dependencies") + else() + if(NOT UUID_FOUND) + message(STATUS "URBDRC dependencie not found: UUID") + endif() + if(NOT DBUS_GLIB_FOUND) + message(STATUS "URBDRC dependencie not found: DBUS_GLIB") + endif() + if(NOT LIBUSB_1_FOUND) + message(STATUS "URBDRC dependencie not found: LIBUSB_1") + endif() + endif() endif() if(WITH_CLIENT_CHANNELS) diff --git a/channels/urbdrc/client/CMakeLists.txt b/channels/urbdrc/client/CMakeLists.txt index 4ad1f27c0..5b0bc314a 100644 --- a/channels/urbdrc/client/CMakeLists.txt +++ b/channels/urbdrc/client/CMakeLists.txt @@ -39,8 +39,10 @@ add_channel_client_library(${MODULE_PREFIX} ${MODULE_NAME} ${CHANNEL_NAME} TRUE set(${MODULE_PREFIX}_LIBS ${DBUS_GLIB_LIBRARIES} - ${UDEV_LIBRARIES} ${UUID_LIBRARIES}) +if (UDEV_FOUND AND UDEV_LIBRARIES) + set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} ${UDEV_LIBRARIES}) +endif() set(${MODULE_PREFIX}_LIBS ${${MODULE_PREFIX}_LIBS} winpr freerdp) diff --git a/channels/urbdrc/client/data_transfer.c b/channels/urbdrc/client/data_transfer.c index d4f624888..765b36068 100644 --- a/channels/urbdrc/client/data_transfer.c +++ b/channels/urbdrc/client/data_transfer.c @@ -1285,7 +1285,7 @@ static int urb_os_feature_descriptor_request(URBDRC_CHANNEL_CALLBACK * callback, data_read_UINT32(data + 0, RequestId); data_read_BYTE(data + 4, Recipient); /** Recipient */ - Recipient = Recipient && 0x1f; + Recipient = (Recipient & 0x1f); /* XXX: origin: Recipient && 0x1f !? */ data_read_BYTE(data + 5, InterfaceNumber); /** InterfaceNumber */ data_read_BYTE(data + 6, Ms_PageIndex); /** Ms_PageIndex */ data_read_UINT16(data + 7, Ms_featureDescIndex); /** Ms_featureDescIndex */ diff --git a/channels/urbdrc/client/libusb/libusb_udevice.c b/channels/urbdrc/client/libusb/libusb_udevice.c index d7cf55ff1..b7d17b2e5 100644 --- a/channels/urbdrc/client/libusb/libusb_udevice.c +++ b/channels/urbdrc/client/libusb/libusb_udevice.c @@ -22,7 +22,9 @@ #include #include #include +#if defined(__linux__) #include +#endif #include "libusb_udevice.h" @@ -455,8 +457,7 @@ static void print_status(enum libusb_transfer_status status) static LIBUSB_DEVICE* udev_get_libusb_dev(int bus_number, int dev_number) { - int i; - ssize_t total_device; + ssize_t i, total_device; LIBUSB_DEVICE** libusb_list; total_device = libusb_get_device_list(NULL, &libusb_list); @@ -492,7 +493,69 @@ static LIBUSB_DEVICE_DESCRIPTOR* udev_new_descript(LIBUSB_DEVICE* libusb_dev) return descriptor; } - /* Get HUB handle */ +/* Get HUB handle */ +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) +static int udev_get_hub_handle(UDEVICE* pdev, UINT16 bus_number, UINT16 dev_number) { + int error; + ssize_t i, total_device, ports_cnt; + uint8_t port_numbers[16]; + LIBUSB_DEVICE **libusb_list; + + total_device = libusb_get_device_list(NULL, &libusb_list); + /* Look for device. */ + error = -1; + for (i = 0; i < total_device; i ++) + { + if ((bus_number != libusb_get_bus_number(libusb_list[i])) || + (dev_number != libusb_get_device_address(libusb_list[i]))) + continue; + error = libusb_open(libusb_list[i], &pdev->hub_handle); + if (error < 0) + { + WLog_ERR(TAG,"libusb_open error: %i - %s", error, libusb_strerror(error)); + break; + } + /* get port number */ + error = libusb_get_port_numbers(libusb_list[i], port_numbers, sizeof(port_numbers)); + libusb_close(pdev->hub_handle); + if (error < 1) + { /* Prevent open hub, treat as error. */ + WLog_ERR(TAG,"libusb_get_port_numbers error: %i - %s", error, libusb_strerror(error)); + break; + } + pdev->port_number = port_numbers[(error - 1)]; + error = 0; + WLog_DBG(TAG, " Port: %d", pdev->port_number); + /* gen device path */ + sprintf(pdev->path, "ugen%d.%d", bus_number, dev_number); + WLog_DBG(TAG, " DevPath: %s", pdev->path); + break; + } + /* Look for device hub. */ + if (error == 0) + { + error = -1; + for (i = 0; i < total_device; i ++) + { + if ((bus_number != libusb_get_bus_number(libusb_list[i])) || + (1 != libusb_get_device_address(libusb_list[i]))) /* Root hub allways first on bus. */ + continue; + WLog_DBG(TAG, " Open hub: %d", bus_number); + error = libusb_open(libusb_list[i], &pdev->hub_handle); + if (error < 0) + WLog_ERR(TAG,"libusb_open error: %i - %s", error, libusb_strerror(error)); + break; + } + } + libusb_free_device_list(libusb_list, 1); + + if (error < 0) + return -1; + WLog_DBG(TAG, "libusb_open success!"); + return 0; +} +#endif +#if defined(__linux__) static int udev_get_hub_handle(UDEVICE* pdev, UINT16 bus_number, UINT16 dev_number) { struct udev* udev; @@ -627,6 +690,7 @@ static int udev_get_hub_handle(UDEVICE* pdev, UINT16 bus_number, UINT16 dev_numb /* Success! */ return 0; } +#endif static int libusb_udev_select_interface(IUDEVICE* idev, BYTE InterfaceNumber, BYTE AlternateSetting) { @@ -1211,6 +1275,7 @@ static int libusb_udev_query_device_port_status(IUDEVICE* idev, UINT32* UsbdStat UDEVICE* pdev = (UDEVICE*) idev; int success = 0, ret; + WLog_DBG(TAG,"..."); if (pdev->hub_handle != NULL) { ret = idev->control_transfer(idev, 0xffff, 0, 0, @@ -1815,10 +1880,10 @@ int udev_new_by_id(UINT16 idVendor, UINT16 idProduct, IUDEVICE*** devArray) UDEVICE** array; UINT16 bus_number; UINT16 dev_number; - ssize_t total_device; - int i, status, num = 0; + ssize_t i, total_device; + int status, num = 0; - WLog_ERR(TAG, "VID: 0x%04X PID: 0x%04X", idVendor, idProduct); + WLog_INFO(TAG, "VID: 0x%04X, PID: 0x%04X", idVendor, idProduct); array = (UDEVICE**) malloc(16 * sizeof(UDEVICE*)); @@ -1839,7 +1904,7 @@ int udev_new_by_id(UINT16 idVendor, UINT16 idProduct, IUDEVICE*** devArray) if (status < 0) { - WLog_ERR(TAG, "libusb_open: (by id) error: 0x%08X (%d)", status, status); + WLog_ERR(TAG, "libusb_open: (by id) error: 0x%08X (%d)", status, status); zfree(descriptor); zfree(array[num]); continue; diff --git a/channels/urbdrc/client/libusb/libusb_udevice.h b/channels/urbdrc/client/libusb/libusb_udevice.h index 5f8e9004b..d753039ce 100644 --- a/channels/urbdrc/client/libusb/libusb_udevice.h +++ b/channels/urbdrc/client/libusb/libusb_udevice.h @@ -23,7 +23,11 @@ #ifndef __LIBUSB_UDEVICE_H #define __LIBUSB_UDEVICE_H +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) +#include +#else #include +#endif #include "urbdrc_types.h" #include "request_queue.h" diff --git a/channels/urbdrc/client/libusb/libusb_udevman.c b/channels/urbdrc/client/libusb/libusb_udevman.c index b486414ed..7dfa505f2 100644 --- a/channels/urbdrc/client/libusb/libusb_udevman.c +++ b/channels/urbdrc/client/libusb/libusb_udevman.c @@ -612,5 +612,7 @@ int freerdp_urbdrc_client_subsystem_entry(PFREERDP_URBDRC_SERVICE_ENTRY_POINTS p pEntryPoints->pRegisterUDEVMAN(pEntryPoints->plugin, (IUDEVMAN*) udevman); + WLog_DBG(TAG, "UDEVMAN device registered."); + return 0; } diff --git a/channels/urbdrc/client/urbdrc_main.c b/channels/urbdrc/client/urbdrc_main.c index f9da1279c..3dd7ed7ae 100644 --- a/channels/urbdrc/client/urbdrc_main.c +++ b/channels/urbdrc/client/urbdrc_main.c @@ -24,10 +24,20 @@ #include #include #include +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) +#include +#include +#include +#include +#include +#endif +#if defined(__linux__) #include +#endif #include #include +#include #include #include @@ -48,10 +58,10 @@ static int func_hardware_id_format(IUDEVICE* pdev, char(*HardwareIds)[DEVICE_HAR idProduct = (UINT16)pdev->query_device_descriptor(pdev, ID_PRODUCT); bcdDevice = (UINT16)pdev->query_device_descriptor(pdev, BCD_DEVICE); - snprintf(str, sizeof(str), "USB\\VID_%04X&PID_%04X", idVendor, idProduct); + sprintf_s(str, sizeof(str), "USB\\VID_%04X&PID_%04X", idVendor, idProduct); strcpy(HardwareIds[1], str); - snprintf(str, sizeof(str), "%s&REV_%04X", HardwareIds[1], bcdDevice); + sprintf_s(str, sizeof(str), "%s&REV_%04X", HardwareIds[1], bcdDevice); strcpy(HardwareIds[0], str); return 0; @@ -68,20 +78,20 @@ static int func_compat_id_format(IUDEVICE* pdev, char (*CompatibilityIds)[DEVICE if(!(pdev->isCompositeDevice(pdev))) { - snprintf(str, sizeof(str),"USB\\Class_%02X", bDeviceClass); + sprintf_s(str, sizeof(str),"USB\\Class_%02X", bDeviceClass); strcpy(CompatibilityIds[2], str); - snprintf(str, sizeof(str),"%s&SubClass_%02X", CompatibilityIds[2], bDeviceSubClass); + sprintf_s(str, sizeof(str),"%s&SubClass_%02X", CompatibilityIds[2], bDeviceSubClass); strcpy(CompatibilityIds[1], str); - snprintf(str, sizeof(str),"%s&Prot_%02X", CompatibilityIds[1], bDeviceProtocol); + sprintf_s(str, sizeof(str),"%s&Prot_%02X", CompatibilityIds[1], bDeviceProtocol); strcpy(CompatibilityIds[0], str); } else { - snprintf(str, sizeof(str),"USB\\DevClass_00"); + sprintf_s(str, sizeof(str),"USB\\DevClass_00"); strcpy(CompatibilityIds[2], str); - snprintf(str, sizeof(str),"%s&SubClass_00", CompatibilityIds[2]); + sprintf_s(str, sizeof(str),"%s&SubClass_00", CompatibilityIds[2]); strcpy(CompatibilityIds[1], str); - snprintf(str, sizeof(str),"%s&Prot_00", CompatibilityIds[1]); + sprintf_s(str, sizeof(str),"%s&Prot_00", CompatibilityIds[1]); strcpy(CompatibilityIds[0], str); } @@ -152,10 +162,10 @@ static int func_container_id_generate(IUDEVICE* pdev, char* strContainerId) p = path; ZeroMemory(containerId, sizeof(containerId)); - snprintf((char*)containerId, sizeof(containerId), "%04X%04X%s", idVendor, idProduct, p); + sprintf_s((char*)containerId, sizeof(containerId), "%04X%04X%s", idVendor, idProduct, p); /* format */ - snprintf(strContainerId, DEVICE_CONTAINER_STR_SIZE, + sprintf_s(strContainerId, DEVICE_CONTAINER_STR_SIZE, "{%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x}", containerId[0], containerId[1],containerId[2], containerId[3], containerId[4], containerId[5], containerId[6], containerId[7], @@ -170,10 +180,10 @@ static int func_instance_id_generate(IUDEVICE* pdev, char* strInstanceId) UINT8 instanceId[17]; ZeroMemory(instanceId, sizeof(instanceId)); - snprintf((char*)instanceId, sizeof(instanceId), "\\%s", pdev->getPath(pdev)); + sprintf_s((char*)instanceId, sizeof(instanceId), "\\%s", pdev->getPath(pdev)); /* format */ - snprintf(strInstanceId, DEVICE_INSTANCE_STR_SIZE, + sprintf_s(strInstanceId, DEVICE_INSTANCE_STR_SIZE, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", instanceId[0], instanceId[1],instanceId[2], instanceId[3], instanceId[4], instanceId[5], instanceId[6], instanceId[7], @@ -449,6 +459,266 @@ static WIN32ERROR urbdrc_exchange_capabilities(URBDRC_CHANNEL_CALLBACK* callback return error; } +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) +static char *devd_get_val(char *buf, size_t buf_size, const char *val_name, size_t val_name_size, size_t *val_size) { + char *ret, *buf_end, *ptr; + + buf_end = (buf + buf_size); + for (ret = buf; ret != NULL && ret < buf_end;) + { + ret = memmem(ret, (buf_end - ret), val_name, val_name_size); + if (ret == NULL) + return NULL; + /* Found. */ + /* Check: space before or buf+1. */ + if ((buf + 1) < ret && ret[-1] != ' ') + { + ret += val_name_size; + continue; + } + /* Check: = after name and size for value. */ + ret += val_name_size; + if ((ret + 1) >= buf_end) + return NULL; + if (ret[0] != '=') + continue; + ret ++; + break; + } + if (ret == NULL || val_size == NULL) + return ret; + /* Calc value data size. */ + ptr = memchr(ret, ' ', (buf_end - ret)); + if (ptr == NULL) /* End of string/last value. */ + ptr = buf_end; + (*val_size) = (ptr - ret); + return ret; +} + +static void *urbdrc_search_usb_device(void *arg) { + USB_SEARCHMAN *searchman = (USB_SEARCHMAN*)arg; + URBDRC_PLUGIN *urbdrc = (URBDRC_PLUGIN*)searchman->urbdrc; + IUDEVMAN *udevman = urbdrc->udevman; + IWTSVirtualChannelManager *channel_mgr = urbdrc->listener_callback->channel_mgr; + IWTSVirtualChannel *dvc_channel; + USB_SEARCHDEV *sdev; + IUDEVICE *pdev; + HANDLE listobj[2]; + HANDLE mon_fd; + int devd_skt; + char buf[4096], *val, *ptr, *end_val; + ssize_t data_size; + size_t val_size, tm; + int idVendor, idProduct; + int busnum, devnum; + int action, success, error, found, on_close; + struct sockaddr_un sun; + + WLog_DBG(TAG, "urbdrc_search_usb_device - devd: start"); + + devd_skt = socket(PF_LOCAL, SOCK_SEQPACKET, 0); + if (devd_skt == -1) + { + WLog_ERR(TAG, "Can't create devd socket: error = %i", errno); + goto err_out; + } + memset(&sun, 0, sizeof(sun)); + sun.sun_family = PF_LOCAL; + sun.sun_len = sizeof(sun); + strlcpy(sun.sun_path, "/var/run/devd.seqpacket.pipe", sizeof(sun.sun_path)); + if (-1 == connect(devd_skt, (struct sockaddr*)&sun, sizeof(sun))) + { + WLog_ERR(TAG, "Can't connect devd socket: error = %i - %s", errno, strerror(errno)); + goto err_out; + } + + /* Get the file descriptor (fd) for the monitor. + This fd will get passed to select() */ + mon_fd = CreateFileDescriptorEvent(NULL, TRUE, FALSE, devd_skt); + listobj[0] = searchman->term_event; + listobj[1] = mon_fd; + + while (WaitForMultipleObjects(2, listobj, FALSE, INFINITE) != WAIT_OBJECT_0) + { + WLog_DBG(TAG, "======= SEARCH ======= "); + + /* !system=USB subsystem=DEVICE type=ATTACH ugen=ugen3.3 cdev=ugen3.3 vendor=0x046d product=0x082d devclass=0xef devsubclass=0x02 sernum="6E7D726F" release=0x0011 mode=host port=4 parent=ugen3.1 */ + /* !system=USB subsystem=DEVICE type=DETACH ugen=ugen3.3 cdev=ugen3.3 vendor=0x046d product=0x082d devclass=0xef devsubclass=0x02 sernum="6E7D726F" release=0x0011 mode=host port=4 parent=ugen3.1 */ + data_size = read(devd_skt, buf, (sizeof(buf) - 1)); + if (data_size == -1) + { + WLog_ERR(TAG, "devd socket read: error = %i", errno); + break; + } + buf[data_size] = 0; + WLog_DBG(TAG, "devd event: %s", buf); + + if (buf[0] != '!') /* Skeep non notify events. */ + continue; + /* Check: system=USB */ + val = devd_get_val(buf, data_size, "system", 6, &val_size); + if (val == NULL || val_size != 3 || memcmp(val, "USB", 3) != 0) + continue; + /* Check: subsystem=DEVICE */ + val = devd_get_val(buf, data_size, "subsystem", 9, &val_size); + if (val == NULL || val_size != 6 || memcmp(val, "DEVICE", 6) != 0) + continue; + /* Get event type. */ + val = devd_get_val(buf, data_size, "type", 4, &val_size); + if (val == NULL || val_size != 6) + continue; + action = -1; + if (memcmp(val, "ATTACH", 6) == 0) + action = 0; + if (memcmp(val, "DETACH", 6) == 0) + action = 1; + if (action == -1) + continue; /* Skeep other actions. */ + + /* Get bus and dev num. */ + /* ugen=ugen3.3 */ + val = devd_get_val(buf, data_size, "ugen", 4, &val_size); + if (val == NULL || val_size < 7 || memcmp(val, "ugen", 4) != 0) + continue; + val += 4; + val_size -= 4; + ptr = memchr(val, '.', val_size); + if (ptr == NULL) + continue; + /* Prepare strings. */ + ptr[0] = 0; + ptr ++; + val[val_size] = 0; + /* Extract numbers. */ + busnum = atoi(val); + devnum = atoi(ptr); + /* Restore spaces. */ + ptr[-1] = ' '; + val[val_size] = ' '; + + /* Handle event. */ + dvc_channel = NULL; + + switch (action) + { + case 0: /* ATTACH */ + sdev = NULL; + success = 0; + found = 0; + + /* vendor=0x046d */ + val = devd_get_val(buf, data_size, "vendor", 6, &val_size); + if (val == NULL || val_size < 1) + continue; + val[val_size] = 0; + idVendor = strtol(val, NULL, 16); + val[val_size] = ' '; + + /* product=0x082d */ + val = devd_get_val(buf, data_size, "product", 7, &val_size); + if (val == NULL || val_size < 1) + continue; + val[val_size] = 0; + idProduct = strtol(val, NULL, 16); + val[val_size] = ' '; + + WLog_DBG(TAG, "ATTACH: bus: %i, dev: %i, ven: %i, prod: %i", busnum, devnum, idVendor, idProduct); + + dvc_channel = channel_mgr->FindChannelById(channel_mgr, urbdrc->first_channel_id); + searchman->rewind(searchman); + while (dvc_channel && searchman->has_next(searchman)) + { + sdev = searchman->get_next(searchman); + if (sdev->idVendor == idVendor && + sdev->idProduct == idProduct) + { + WLog_VRB(TAG, "Searchman Found Device: %04x:%04x", + sdev->idVendor, sdev->idProduct); + found = 1; + break; + } + } + + if (!found && udevman->isAutoAdd(udevman)) + { + WLog_VRB(TAG, "Auto Find Device: %04x:%04x ", + idVendor, idProduct); + found = 2; + } + + if (found) + { + success = udevman->register_udevice(udevman, busnum, devnum, + searchman->UsbDevice, 0, 0, UDEVMAN_FLAG_ADD_BY_ADDR); + } + + if (success) + { + searchman->UsbDevice ++; + + usleep(400000); + error = urdbrc_send_virtual_channel_add(dvc_channel, 0); + if (found == 1) + searchman->remove(searchman, sdev->idVendor, sdev->idProduct); + } + break; + case 1: /* DETACH */ + pdev = NULL; + on_close = 0; + WLog_DBG(TAG, "DETACH: bus: %i, dev: %i", busnum, devnum); + + usleep(500000); + udevman->loading_lock(udevman); + udevman->rewind(udevman); + while (udevman->has_next(udevman)) + { + pdev = udevman->get_next(udevman); + if (pdev->get_bus_number(pdev) == busnum && + pdev->get_dev_number(pdev) == devnum) + { + dvc_channel = channel_mgr->FindChannelById(channel_mgr, pdev->get_channel_id(pdev)); + + if (dvc_channel == NULL) + { + WLog_ERR(TAG, "SEARCH: dvc_channel %d is NULL!!", pdev->get_channel_id(pdev)); + func_close_udevice(searchman, pdev); + break; + } + + if (!pdev->isSigToEnd(pdev)) + { + dvc_channel->Write(dvc_channel, 0, NULL, NULL); + pdev->SigToEnd(pdev); + } + + on_close = 1; + break; + } + } + + udevman->loading_unlock(udevman); + usleep(300000); + + if (pdev && on_close && dvc_channel && + pdev->isSigToEnd(pdev) && + !(pdev->isChannelClosed(pdev))) + { + dvc_channel->Close(dvc_channel); + } + break; + } + } + + CloseHandle(mon_fd); +err_out: + close(devd_skt); + sem_post(&searchman->sem_term); + WLog_DBG(TAG, "urbdrc_search_usb_device - devd: end"); + + return 0; +} +#endif +#if defined (__linux__) static void* urbdrc_search_usb_device(void* arg) { USB_SEARCHMAN* searchman = (USB_SEARCHMAN*) arg; @@ -486,7 +756,9 @@ static void* urbdrc_search_usb_device(void* arg) /* Get the file descriptor (fd) for the monitor. This fd will get passed to select() */ - if (!(mon_fd = CreateFileDescriptorEvent(NULL, TRUE, FALSE, udev_monitor_get_fd(mon)))) + mon_fd = CreateFileDescriptorEvent(NULL, TRUE, FALSE, + udev_monitor_get_fd(mon), WINPR_FD_READ); + if (!mon_fd) goto fail_create_monfd_event; while (1) @@ -672,6 +944,7 @@ fail_create_monfd_event: return 0; } +#endif void* urbdrc_new_device_create(void* arg) { @@ -688,8 +961,10 @@ void* urbdrc_new_device_create(void* arg) UINT32 FunctionId; int i = 0, found = 0; + WLog_DBG(TAG, "..."); + channel_mgr = urbdrc->listener_callback->channel_mgr; - ChannelId = channel_mgr->GetChannelId(callback->channel); + ChannelId = channel_mgr->GetChannelId(callback->channel); data_read_UINT32(pBuffer + 0, MessageId); data_read_UINT32(pBuffer + 4, FunctionId); @@ -762,6 +1037,8 @@ static WIN32ERROR urbdrc_process_channel_notification(URBDRC_CHANNEL_CALLBACK* c WIN32ERROR error = CHANNEL_RC_OK; URBDRC_PLUGIN* urbdrc = (URBDRC_PLUGIN*) callback->plugin; + WLog_DBG(TAG, "..."); + data_read_UINT32(pBuffer + 0, MessageId); data_read_UINT32(pBuffer + 4, FunctionId); @@ -824,7 +1101,7 @@ static WIN32ERROR urbdrc_on_data_received(IWTSVirtualChannelCallback* pChannelCa UINT32 Mask; WIN32ERROR error = CHANNEL_RC_OK; char* pBuffer = (char*)Stream_Pointer(data); - UINT32 cbSize = Stream_GetRemainingLength(data); + UINT32 cbSize = Stream_GetRemainingLength(data); if (callback == NULL) return 0; diff --git a/channels/urbdrc/client/urbdrc_types.h b/channels/urbdrc/client/urbdrc_types.h index 641478eea..a3219d7f4 100644 --- a/channels/urbdrc/client/urbdrc_types.h +++ b/channels/urbdrc/client/urbdrc_types.h @@ -30,7 +30,11 @@ #include #include +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) +#include +#else #include +#endif #include #include diff --git a/client/.gitignore b/client/.gitignore index 8a070de0c..e40f517bf 100644 --- a/client/.gitignore +++ b/client/.gitignore @@ -7,4 +7,5 @@ !/Sample !/Windows !/X11 +!/Wayland !/CMakeLists.txt diff --git a/client/Android/FreeRDPCore/jni/android_event.c b/client/Android/FreeRDPCore/jni/android_event.c index 2a74123b8..8e1b01bab 100644 --- a/client/Android/FreeRDPCore/jni/android_event.c +++ b/client/Android/FreeRDPCore/jni/android_event.c @@ -69,20 +69,20 @@ void android_clear_event(ANDROID_EVENT_QUEUE * queue) } } -void android_push_event(freerdp * inst, ANDROID_EVENT* event) +BOOL android_push_event(freerdp * inst, ANDROID_EVENT* event) { androidContext* aCtx = (androidContext*)inst->context; if (aCtx->event_queue->count >= aCtx->event_queue->size) { int new_size; - int new_events; + void* new_events; new_size = aCtx->event_queue->size * 2; new_events = realloc((void*) aCtx->event_queue->events, sizeof(ANDROID_EVENT*) * new_size); if (!new_events) - return; + return FALSE; aCtx->event_queue->events = new_events; aCtx->event_queue->size = new_size; } @@ -90,6 +90,7 @@ void android_push_event(freerdp * inst, ANDROID_EVENT* event) aCtx->event_queue->events[(aCtx->event_queue->count)++] = event; android_set_event(aCtx->event_queue); + return TRUE; } ANDROID_EVENT* android_peek_event(ANDROID_EVENT_QUEUE * queue) @@ -226,8 +227,9 @@ ANDROID_EVENT_KEY* android_event_key_new(int flags, UINT16 scancode) { ANDROID_EVENT_KEY* event; - event = (ANDROID_EVENT_KEY*) malloc(sizeof(ANDROID_EVENT_KEY)); - memset(event, 0, sizeof(ANDROID_EVENT_KEY)); + event = (ANDROID_EVENT_KEY*) calloc(1, sizeof(ANDROID_EVENT_KEY)); + if (!event) + return NULL; event->type = EVENT_TYPE_KEY; event->flags = flags; @@ -245,8 +247,9 @@ ANDROID_EVENT_KEY* android_event_unicodekey_new(UINT16 key) { ANDROID_EVENT_KEY* event; - event = (ANDROID_EVENT_KEY*) malloc(sizeof(ANDROID_EVENT_KEY)); - memset(event, 0, sizeof(ANDROID_EVENT_KEY)); + event = (ANDROID_EVENT_KEY*) calloc(1, sizeof(ANDROID_EVENT_KEY)); + if (!event) + return NULL; event->type = EVENT_TYPE_KEY_UNICODE; event->scancode = key; @@ -263,8 +266,9 @@ ANDROID_EVENT_CURSOR* android_event_cursor_new(UINT16 flags, UINT16 x, UINT16 y) { ANDROID_EVENT_CURSOR* event; - event = (ANDROID_EVENT_CURSOR*) malloc(sizeof(ANDROID_EVENT_CURSOR)); - memset(event, 0, sizeof(ANDROID_EVENT_CURSOR)); + event = (ANDROID_EVENT_CURSOR*) calloc(1, sizeof(ANDROID_EVENT_CURSOR)); + if (!event) + return NULL; event->type = EVENT_TYPE_CURSOR; event->x = x; @@ -283,8 +287,9 @@ ANDROID_EVENT* android_event_disconnect_new() { ANDROID_EVENT* event; - event = (ANDROID_EVENT*) malloc(sizeof(ANDROID_EVENT)); - memset(event, 0, sizeof(ANDROID_EVENT)); + event = (ANDROID_EVENT*) calloc(1, sizeof(ANDROID_EVENT)); + if (!event) + return NULL; event->type = EVENT_TYPE_DISCONNECT; return event; @@ -299,13 +304,19 @@ ANDROID_EVENT_CLIPBOARD* android_event_clipboard_new(void* data, int data_length { ANDROID_EVENT_CLIPBOARD* event; - event = (ANDROID_EVENT_CLIPBOARD*) malloc(sizeof(ANDROID_EVENT_CLIPBOARD)); - memset(event, 0, sizeof(ANDROID_EVENT_CLIPBOARD)); + event = (ANDROID_EVENT_CLIPBOARD*) calloc(1, sizeof(ANDROID_EVENT_CLIPBOARD)); + if (!event) + return NULL; event->type = EVENT_TYPE_CLIPBOARD; if (data) { event->data = malloc(data_length); + if (!event->data) + { + free(event); + return NULL; + } memcpy(event->data, data, data_length); event->data_length = data_length; } @@ -322,12 +333,16 @@ void android_event_clipboard_free(ANDROID_EVENT_CLIPBOARD* event) } } -void android_event_queue_init(freerdp * inst) +BOOL android_event_queue_init(freerdp * inst) { androidContext* aCtx = (androidContext*)inst->context; - aCtx->event_queue = (ANDROID_EVENT_QUEUE*) malloc(sizeof(ANDROID_EVENT_QUEUE)); - memset(aCtx->event_queue, 0, sizeof(ANDROID_EVENT_QUEUE)); + aCtx->event_queue = (ANDROID_EVENT_QUEUE*) calloc(1, sizeof(ANDROID_EVENT_QUEUE)); + if (!aCtx->event_queue) + { + WLog_ERR(TAG, "android_event_queue_init: memory allocation failed"); + return FALSE; + } aCtx->event_queue->pipe_fd[0] = -1; aCtx->event_queue->pipe_fd[1] = -1; @@ -335,9 +350,21 @@ void android_event_queue_init(freerdp * inst) aCtx->event_queue->size = 16; aCtx->event_queue->count = 0; aCtx->event_queue->events = (ANDROID_EVENT**) malloc(sizeof(ANDROID_EVENT*) * aCtx->event_queue->size); + if (!aCtx->event_queue->events) + { + WLog_ERR(TAG, "android_event_queue_init: memory allocation failed"); + free(aCtx->event_queue); + return FALSE; + } if (pipe(aCtx->event_queue->pipe_fd) < 0) - WLog_ERR(TAG, "android_pre_connect: pipe failed"); + { + WLog_ERR(TAG, "android_event_queue_init: pipe creation failed"); + free(aCtx->event_queue->events); + free(aCtx->event_queue); + return FALSE; + } + return TRUE; } void android_event_queue_uninit(freerdp * inst) diff --git a/client/Android/FreeRDPCore/jni/android_event.h b/client/Android/FreeRDPCore/jni/android_event.h index 7872ec770..d1cb147fe 100644 --- a/client/Android/FreeRDPCore/jni/android_event.h +++ b/client/Android/FreeRDPCore/jni/android_event.h @@ -62,7 +62,7 @@ typedef struct _ANDROID_EVENT_QUEUE ANDROID_EVENT_QUEUE; int android_is_event_set(ANDROID_EVENT_QUEUE * queue); void android_set_event(ANDROID_EVENT_QUEUE * queue); void android_clear_event(ANDROID_EVENT_QUEUE * queue); -void android_push_event(freerdp * inst, ANDROID_EVENT* event); +BOOL android_push_event(freerdp * inst, ANDROID_EVENT* event); ANDROID_EVENT* android_peek_event(ANDROID_EVENT_QUEUE * queue); ANDROID_EVENT* android_pop_event(ANDROID_EVENT_QUEUE * queue); int android_process_event(ANDROID_EVENT_QUEUE * queue, freerdp * inst); @@ -79,7 +79,7 @@ void android_event_unicodekey_free(ANDROID_EVENT_KEY* event); void android_event_cursor_free(ANDROID_EVENT_CURSOR* event); void android_event_disconnect_free(ANDROID_EVENT* event); void android_event_clipboard_free(ANDROID_EVENT_CLIPBOARD* event); -void android_event_queue_init(freerdp * inst); +BOOL android_event_queue_init(freerdp * inst); void android_event_queue_uninit(freerdp * inst); #endif /* FREERDP_ANDROID_EVENT_H */ diff --git a/client/Android/FreeRDPCore/jni/android_freerdp.c b/client/Android/FreeRDPCore/jni/android_freerdp.c index 3f876e787..ea6a0030b 100644 --- a/client/Android/FreeRDPCore/jni/android_freerdp.c +++ b/client/Android/FreeRDPCore/jni/android_freerdp.c @@ -4,6 +4,7 @@ Copyright 2010-2012 Marc-Andre Moreau Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz Copyright 2013 Thincast Technologies GmbH, Author: Armin Novak + Copyright 2015 Bernhard Miklautz This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. @@ -35,6 +36,7 @@ #include #include #include +#include #include @@ -48,15 +50,21 @@ #include "jni/prof.h" #endif -BOOL android_context_new(freerdp* instance, rdpContext* context) + +static BOOL android_context_new(freerdp* instance, rdpContext* context) { if (!(context->channels = freerdp_channels_new())) return FALSE; - android_event_queue_init(instance); + + if (!android_event_queue_init(instance)) + { + freerdp_channels_free(context->channels); + return FALSE; + } return TRUE; } -void android_context_free(freerdp* instance, rdpContext* context) +static void android_context_free(freerdp* instance, rdpContext* context) { if (context && context->channels) { @@ -67,14 +75,14 @@ void android_context_free(freerdp* instance, rdpContext* context) android_event_queue_uninit(instance); } -void android_OnChannelConnectedEventHandler(rdpContext* context, ChannelConnectedEventArgs* e) +static void android_OnChannelConnectedEventHandler(rdpContext* context, ChannelConnectedEventArgs* e) { rdpSettings* settings = context->settings; androidContext* afc = (androidContext*) context; if (strcmp(e->name, RDPEI_DVC_CHANNEL_NAME) == 0) { - + DEBUG_ANDROID("Unhandled case.. RDPEI_DVC_CHANNEL_NAME"); } else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) { @@ -87,14 +95,14 @@ void android_OnChannelConnectedEventHandler(rdpContext* context, ChannelConnecte } } -void android_OnChannelDisconnectedEventHandler(rdpContext* context, ChannelDisconnectedEventArgs* e) +static void android_OnChannelDisconnectedEventHandler(rdpContext* context, ChannelDisconnectedEventArgs* e) { rdpSettings* settings = context->settings; androidContext* afc = (androidContext*) context; if (strcmp(e->name, RDPEI_DVC_CHANNEL_NAME) == 0) { - + DEBUG_ANDROID("Unhandled case.. RDPEI_DVC_CHANNEL_NAME"); } else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) { @@ -107,7 +115,7 @@ void android_OnChannelDisconnectedEventHandler(rdpContext* context, ChannelDisco } } -BOOL android_begin_paint(rdpContext* context) +static BOOL android_begin_paint(rdpContext* context) { rdpGdi* gdi = context->gdi; gdi->primary->hdc->hwnd->invalid->null = 1; @@ -115,7 +123,7 @@ BOOL android_begin_paint(rdpContext* context) return TRUE; } -BOOL android_end_paint(rdpContext* context) +static BOOL android_end_paint(rdpContext* context) { int i; int ninvalid; @@ -158,7 +166,7 @@ BOOL android_end_paint(rdpContext* context) return TRUE; } -BOOL android_desktop_resize(rdpContext* context) +static BOOL android_desktop_resize(rdpContext* context) { DEBUG_ANDROID("ui_desktop_resize"); @@ -172,7 +180,7 @@ BOOL android_desktop_resize(rdpContext* context) return TRUE; } -BOOL android_pre_connect(freerdp* instance) +static BOOL android_pre_connect(freerdp* instance) { DEBUG_ANDROID("android_pre_connect"); @@ -233,7 +241,8 @@ static BOOL android_post_connect(freerdp* instance) settings->DesktopWidth, settings->DesktopHeight, settings->ColorDepth); - instance->context->cache = cache_new(settings); + if (!(instance->context->cache = cache_new(settings))) + return FALSE; if (instance->settings->ColorDepth > 16) gdi_flags = CLRBUF_32BPP | CLRCONV_ALPHA | CLRCONV_INVERT; @@ -247,7 +256,8 @@ static BOOL android_post_connect(freerdp* instance) instance->update->EndPaint = android_end_paint; instance->update->DesktopResize = android_desktop_resize; - freerdp_channels_post_connect(instance->context->channels, instance); + if (freerdp_channels_post_connect(instance->context->channels, instance) < 0) + return FALSE; freerdp_callback("OnConnectionSuccess", "(I)V", instance); @@ -256,11 +266,12 @@ static BOOL android_post_connect(freerdp* instance) static void android_post_disconnect(freerdp* instance) { + DEBUG_ANDROID("android_post_disconnect"); gdi_free(instance); cache_free(instance->context->cache); } -BOOL android_authenticate(freerdp* instance, char** username, char** password, char** domain) +static BOOL android_authenticate(freerdp* instance, char** username, char** password, char** domain) { DEBUG_ANDROID("Authenticate user:"); DEBUG_ANDROID(" Username: %s", *username); @@ -293,7 +304,7 @@ BOOL android_authenticate(freerdp* instance, char** username, char** password, c return ((res == JNI_TRUE) ? TRUE : FALSE); } -BOOL android_verify_certificate(freerdp* instance, char* subject, char* issuer, char* fingerprint) +static BOOL android_verify_certificate(freerdp* instance, char* subject, char* issuer, char* fingerprint) { DEBUG_ANDROID("Certificate details:"); DEBUG_ANDROID("\tSubject: %s", subject); @@ -317,7 +328,7 @@ BOOL android_verify_certificate(freerdp* instance, char* subject, char* issuer, return ((res == JNI_TRUE) ? TRUE : FALSE); } -BOOL android_verify_changed_certificate(freerdp* instance, char* subject, char* issuer, char* new_fingerprint, char* old_fingerprint) +static BOOL android_verify_changed_certificate(freerdp* instance, char* subject, char* issuer, char* new_fingerprint, char* old_fingerprint) { return android_verify_certificate(instance, subject, issuer, new_fingerprint); } @@ -332,15 +343,17 @@ static void* jni_input_thread(void* arg) assert(NULL != instance); assert(NULL != aCtx); - DEBUG_ANDROID("Start."); + DEBUG_ANDROID("input_thread Start."); if (!(queue = freerdp_get_message_queue(instance, FREERDP_INPUT_MESSAGE_QUEUE))) goto fail_get_message_queue; - if (!(event[0] = CreateFileDescriptorEvent(NULL, FALSE, FALSE, aCtx->event_queue->pipe_fd[0]))) + if (!(event[0] = CreateFileDescriptorEvent(NULL, FALSE, FALSE, + aCtx->event_queue->pipe_fd[0], WINPR_FD_READ))) goto fail_create_event_0; - if (!(event[1] = CreateFileDescriptorEvent(NULL, FALSE, FALSE, aCtx->event_queue->pipe_fd[1]))) + if (!(event[1] = CreateFileDescriptorEvent(NULL, FALSE, FALSE, + aCtx->event_queue->pipe_fd[1], WINPR_FD_READ))) goto fail_create_event_1; if (!(event[2] = freerdp_get_message_queue_event_handle(instance, FREERDP_INPUT_MESSAGE_QUEUE))) @@ -365,7 +378,7 @@ static void* jni_input_thread(void* arg) } while(1); - DEBUG_ANDROID("Quit."); + DEBUG_ANDROID("input_thread Quit."); fail_get_message_queue_event: CloseHandle(event[1]); @@ -388,7 +401,7 @@ static void* jni_channels_thread(void* arg) assert(NULL != instance); - DEBUG_ANDROID("Start."); + DEBUG_ANDROID("Channels_thread Start."); channels = instance->context->channels; event = freerdp_channels_get_event_handle(instance); @@ -401,7 +414,7 @@ static void* jni_channels_thread(void* arg) break; } - DEBUG_ANDROID("Quit."); + DEBUG_ANDROID("channels_thread Quit."); ExitThread(0); return NULL; @@ -613,11 +626,11 @@ disconnect: CloseHandle(input_thread); } - DEBUG_ANDROID("Disconnecting..."); + DEBUG_ANDROID("run Disconnecting..."); freerdp_disconnect(instance); freerdp_callback("OnDisconnected", "(I)V", instance); - DEBUG_ANDROID("Quit."); + DEBUG_ANDROID("run Quit."); return 0; } @@ -626,13 +639,13 @@ static void* android_thread_func(void* param) { freerdp* instance = param; - DEBUG_ANDROID("Start."); + DEBUG_ANDROID("android_thread_func Start."); assert(instance); android_freerdp_run(instance); - DEBUG_ANDROID("Quit."); + DEBUG_ANDROID("android_thread_func Quit."); ExitThread(0); return NULL; @@ -649,7 +662,7 @@ JNIEXPORT jint JNICALL jni_freerdp_new(JNIEnv *env, jclass cls) // create instance if (!(instance = freerdp_new())) - return NULL; + return (jint)NULL; instance->PreConnect = android_pre_connect; instance->PostConnect = android_post_connect; instance->PostDisconnect = android_post_disconnect; @@ -705,12 +718,20 @@ JNIEXPORT jboolean JNICALL jni_freerdp_disconnect(JNIEnv *env, jclass cls, jint freerdp* inst = (freerdp*)instance; androidContext* ctx = (androidContext*)inst->context; ANDROID_EVENT* event = (ANDROID_EVENT*)android_event_disconnect_new(); + if (!event) + return JNI_FALSE; + + DEBUG_ANDROID("DISCONNECT!"); assert(inst); assert(ctx); assert(event); - android_push_event(inst, event); + if (!android_push_event(inst, event)) + { + android_event_disconnect_free(event); + return JNI_FALSE; + } WaitForSingleObject(ctx->thread, INFINITE); CloseHandle(ctx->thread); @@ -721,43 +742,71 @@ JNIEXPORT jboolean JNICALL jni_freerdp_disconnect(JNIEnv *env, jclass cls, jint return (jboolean) JNI_TRUE; } -JNIEXPORT void JNICALL jni_freerdp_cancel_connection(JNIEnv *env, jclass cls, jint instance) +JNIEXPORT jboolean JNICALL jni_freerdp_cancel_connection(JNIEnv *env, jclass cls, jint instance) { - jni_freerdp_disconnect(env, cls, instance); + return jni_freerdp_disconnect(env, cls, instance); } -JNIEXPORT void JNICALL jni_freerdp_set_data_directory(JNIEnv *env, jclass cls, jint instance, jstring jdirectory) +JNIEXPORT jboolean JNICALL jni_freerdp_set_data_directory(JNIEnv *env, jclass cls, jint instance, jstring jdirectory) { freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; - const jbyte *directory = (*env)->GetStringUTFChars(env, jdirectory, NULL); + const jbyte* directory = (*env)->GetStringUTFChars(env, jdirectory, NULL); + if (!directory) + return JNI_FALSE; free(settings->HomePath); free(settings->ConfigPath); + settings->HomePath = settings->ConfigPath = NULL; int config_dir_len = strlen(directory) + 10; /* +9 chars for /.freerdp and +1 for \0 */ char* config_dir_buf = (char*)malloc(config_dir_len); + if (!config_dir_buf) + goto out_malloc_fail; + strcpy(config_dir_buf, directory); strcat(config_dir_buf, "/.freerdp"); settings->HomePath = strdup(directory); + if (!settings->HomePath) + goto out_strdup_fail; settings->ConfigPath = config_dir_buf; /* will be freed by freerdp library */ (*env)->ReleaseStringUTFChars(env, jdirectory, directory); + return JNI_TRUE; + +out_strdup_fail: + free(config_dir_buf); +out_malloc_fail: + (*env)->ReleaseStringUTFChars(env, jdirectory, directory); + return JNI_FALSE; + } -JNIEXPORT void JNICALL jni_freerdp_set_connection_info(JNIEnv *env, jclass cls, jint instance, +JNIEXPORT jboolean JNICALL jni_freerdp_set_connection_info(JNIEnv *env, jclass cls, jint instance, jstring jhostname, jstring jusername, jstring jpassword, jstring jdomain, jint width, jint height, jint color_depth, jint port, jboolean console, jint security, jstring jcertname) { freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; - const jbyte *hostname = (*env)->GetStringUTFChars(env, jhostname, NULL); - const jbyte *username = (*env)->GetStringUTFChars(env, jusername, NULL); - const jbyte *password = (*env)->GetStringUTFChars(env, jpassword, NULL); - const jbyte *domain = (*env)->GetStringUTFChars(env, jdomain, NULL); - const jbyte *certname = (*env)->GetStringUTFChars(env, jcertname, NULL); + const jbyte *hostname; + const jbyte *username; + const jbyte *password; + const jbyte *domain; + const jbyte *certname; + + if(!(hostname = (*env)->GetStringUTFChars(env, jhostname, NULL))) + return JNI_FALSE; + if (!(username = (*env)->GetStringUTFChars(env, jusername, NULL))) + goto out_fail_username; + if (!(password = (*env)->GetStringUTFChars(env, jpassword, NULL))) + goto out_fail_password; + if (!(domain = (*env)->GetStringUTFChars(env, jdomain, NULL))) + goto out_fail_domain; + if (!(certname = (*env)->GetStringUTFChars(env, jcertname, NULL))) + goto out_fail_certname; + DEBUG_ANDROID("hostname: %s", (char*) hostname); DEBUG_ANDROID("username: %s", (char*) username); @@ -779,21 +828,30 @@ JNIEXPORT void JNICALL jni_freerdp_set_connection_info(JNIEnv *env, jclass cls, if (color_depth <= 16) settings->DesktopWidth &= (~1); - settings->ServerHostname = strdup(hostname); + if (!(settings->ServerHostname = strdup(hostname))) + goto out_fail_strdup; if (username && strlen(username) > 0) - settings->Username = strdup(username); + { + if (!(settings->Username = strdup(username))) + goto out_fail_strdup; + } if (password && strlen(password) > 0) { - settings->Password = strdup(password); + if (!(settings->Password = strdup(password))) + goto out_fail_strdup; settings->AutoLogonEnabled = TRUE; } - settings->Domain = strdup(domain); + if (!(settings->Domain = strdup(domain))) + goto out_fail_strdup; if (certname && strlen(certname) > 0) - settings->CertificateName = strdup(certname); + { + if (!(settings->CertificateName = strdup(certname))) + goto out_fail_strdup; + } settings->ConsoleSession = (console == JNI_TRUE) ? TRUE : FALSE; @@ -840,7 +898,20 @@ JNIEXPORT void JNICALL jni_freerdp_set_connection_info(JNIEnv *env, jclass cls, (*env)->ReleaseStringUTFChars(env, jdomain, domain); (*env)->ReleaseStringUTFChars(env, jcertname, certname); - return; + return JNI_TRUE; + + +out_fail_strdup: + (*env)->ReleaseStringUTFChars(env, jcertname, certname); +out_fail_certname: + (*env)->ReleaseStringUTFChars(env, jdomain, domain); +out_fail_domain: + (*env)->ReleaseStringUTFChars(env, jpassword, password); +out_fail_password: + (*env)->ReleaseStringUTFChars(env, jusername, username); +out_fail_username: + (*env)->ReleaseStringUTFChars(env, jhostname, hostname); + return JNI_FALSE; } JNIEXPORT void JNICALL jni_freerdp_set_performance_flags( @@ -881,16 +952,23 @@ JNIEXPORT void JNICALL jni_freerdp_set_performance_flags( DEBUG_ANDROID("performance_flags: %04X", settings->PerformanceFlags); } -JNIEXPORT void JNICALL jni_freerdp_set_advanced_settings(JNIEnv *env, jclass cls, +JNIEXPORT jboolean JNICALL jni_freerdp_set_advanced_settings(JNIEnv *env, jclass cls, jint instance, jstring jRemoteProgram, jstring jWorkDir, jboolean async_channel, jboolean async_transport, jboolean async_input, jboolean async_update) { freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; + jboolean ret = JNI_FALSE; - const jbyte *remote_program = (*env)->GetStringUTFChars(env, jRemoteProgram, NULL); - const jbyte *work_dir = (*env)->GetStringUTFChars(env, jWorkDir, NULL); + const jbyte *remote_program; + const jbyte *work_dir; + + if (!(remote_program = (*env)->GetStringUTFChars(env, jRemoteProgram, NULL))) + return JNI_FALSE; + + if (!(work_dir = (*env)->GetStringUTFChars(env, jWorkDir, NULL))) + goto out_fail_work_dir; DEBUG_ANDROID("Remote Program: %s", (char*) remote_program); DEBUG_ANDROID("Work Dir: %s", (char*) work_dir); @@ -902,36 +980,56 @@ JNIEXPORT void JNICALL jni_freerdp_set_advanced_settings(JNIEnv *env, jclass cls settings->AsyncInput = async_input; if (remote_program && strlen(remote_program) > 0) - settings->AlternateShell = strdup(remote_program); + { + if (!(settings->AlternateShell = strdup(remote_program))) + goto out_fail_strdup; + } if (work_dir && strlen(work_dir) > 0) - settings->ShellWorkingDirectory = strdup(work_dir); + { + if (!(settings->ShellWorkingDirectory = strdup(work_dir))) + goto out_fail_strdup; + } - (*env)->ReleaseStringUTFChars(env, jRemoteProgram, remote_program); + ret = JNI_TRUE; + +out_fail_strdup: (*env)->ReleaseStringUTFChars(env, jWorkDir, work_dir); +out_fail_work_dir: + (*env)->ReleaseStringUTFChars(env, jRemoteProgram, remote_program); + return ret; } -JNIEXPORT void JNICALL jni_freerdp_set_drive_redirection(JNIEnv *env, jclass cls, jint instance, jstring jpath) +JNIEXPORT jboolean JNICALL jni_freerdp_set_drive_redirection(JNIEnv *env, jclass cls, jint instance, jstring jpath) { freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; char* args[] = {"drive", "Android", ""}; + jboolean ret = JNI_FALSE; const jbyte *path = (*env)->GetStringUTFChars(env, jpath, NULL); + if (!path) + return JNI_FALSE; DEBUG_ANDROID("drive redirect: %s", (char*)path); args[2] = (char*)path; - freerdp_client_add_device_channel(settings, 3, args); + if (freerdp_client_add_device_channel(settings, 3, args) == -1) + { + settings->DeviceRedirection = FALSE; + goto out_fail; + } + settings->DeviceRedirection = TRUE; + ret = JNI_TRUE; +out_fail: (*env)->ReleaseStringUTFChars(env, jpath, path); + return ret; } -JNIEXPORT void JNICALL jni_freerdp_set_sound_redirection(JNIEnv *env, +JNIEXPORT jboolean JNICALL jni_freerdp_set_sound_redirection(JNIEnv *env, jclass cls, jint instance, jint redirect) { - char** p; - int count = 1; freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; @@ -939,23 +1037,24 @@ JNIEXPORT void JNICALL jni_freerdp_set_sound_redirection(JNIEnv *env, redirect ? ((redirect == 1) ? "Server" : "Redirect") : "None"); settings->AudioPlayback = (redirect == 2) ? TRUE : FALSE; - settings->RemoteConsoleAudio = (redirect == 1) ? TRUE : FALSE; if (settings->AudioPlayback) { - p = malloc(sizeof(char*)); - p[0] = "rdpsnd"; + int ret; + char* p[1] = {"rdpsnd"}; + int count = 1; - freerdp_client_add_static_channel(settings, count, p); + ret = freerdp_client_add_static_channel(settings, count, p); - free(p); + if(ret == -1) + return JNI_FALSE; } + settings->RemoteConsoleAudio = (redirect == 1) ? TRUE : FALSE; + return JNI_TRUE; } -JNIEXPORT void JNICALL jni_freerdp_set_microphone_redirection(JNIEnv *env, +JNIEXPORT jboolean JNICALL jni_freerdp_set_microphone_redirection(JNIEnv *env, jclass cls, jint instance, jboolean enable) { - char** p; - int count = 1; freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; @@ -964,13 +1063,17 @@ JNIEXPORT void JNICALL jni_freerdp_set_microphone_redirection(JNIEnv *env, settings->AudioCapture = enable; if (enable) { - p = malloc(sizeof(char*)); - p[0] = "audin"; + int ret; + char* p[1] = {"audin"}; + int count = 1; - freerdp_client_add_dynamic_channel(settings, count, p); + ret = freerdp_client_add_dynamic_channel(settings, count, p); + + if (ret == -1) + return JNI_FALSE; - free(p); } + return JNI_TRUE; } JNIEXPORT void JNICALL jni_freerdp_set_clipboard_redirection(JNIEnv *env, jclass cls, jint instance, jboolean enable) @@ -983,16 +1086,26 @@ JNIEXPORT void JNICALL jni_freerdp_set_clipboard_redirection(JNIEnv *env, jclass settings->RedirectClipboard = enable ? TRUE : FALSE; } -JNIEXPORT void JNICALL jni_freerdp_set_gateway_info(JNIEnv *env, jclass cls, jint instance, jstring jgatewayhostname, jint port, +JNIEXPORT jboolean JNICALL jni_freerdp_set_gateway_info(JNIEnv *env, jclass cls, jint instance, jstring jgatewayhostname, jint port, jstring jgatewayusername, jstring jgatewaypassword, jstring jgatewaydomain) { freerdp* inst = (freerdp*)instance; rdpSettings * settings = inst->settings; + jboolean ret = JNI_FALSE; - const jbyte *gatewayhostname = (*env)->GetStringUTFChars(env, jgatewayhostname, NULL); - const jbyte *gatewayusername = (*env)->GetStringUTFChars(env, jgatewayusername, NULL); - const jbyte *gatewaypassword = (*env)->GetStringUTFChars(env, jgatewaypassword, NULL); - const jbyte *gatewaydomain = (*env)->GetStringUTFChars(env, jgatewaydomain, NULL); + const jbyte *gatewayhostname; + const jbyte *gatewayusername; + const jbyte *gatewaypassword; + const jbyte *gatewaydomain; + + if (!(gatewayhostname = (*env)->GetStringUTFChars(env, jgatewayhostname, NULL))) + return JNI_FALSE; + if (!(gatewayusername = (*env)->GetStringUTFChars(env, jgatewayusername, NULL))) + goto out_fail_username; + if (!(gatewaypassword = (*env)->GetStringUTFChars(env, jgatewaypassword, NULL))) + goto out_fail_password; + if (!(gatewaydomain = (*env)->GetStringUTFChars(env, jgatewaydomain, NULL))) + goto out_fail_domain; DEBUG_ANDROID("gatewayhostname: %s", (char*) gatewayhostname); DEBUG_ANDROID("gatewayport: %d", port); @@ -1000,19 +1113,33 @@ JNIEXPORT void JNICALL jni_freerdp_set_gateway_info(JNIEnv *env, jclass cls, jin DEBUG_ANDROID("gatewaypassword: %s", (char*) gatewaypassword); DEBUG_ANDROID("gatewaydomain: %s", (char*) gatewaydomain); - settings->GatewayHostname = strdup(gatewayhostname); settings->GatewayPort = port; - settings->GatewayUsername = strdup(gatewayusername); - settings->GatewayPassword = strdup(gatewaypassword); - settings->GatewayDomain = strdup(gatewaydomain); settings->GatewayUsageMethod = TSC_PROXY_MODE_DIRECT; settings->GatewayEnabled = TRUE; settings->GatewayUseSameCredentials = FALSE; + settings->GatewayHostname = strdup(gatewayhostname); + settings->GatewayUsername = strdup(gatewayusername); + settings->GatewayPassword = strdup(gatewaypassword); + settings->GatewayDomain = strdup(gatewaydomain); + if (!settings->GatewayHostname || !settings->GatewayUsername || + !settings->GatewayPassword || !settings->GatewayDomain) + { + goto out_fail_strdup; + } - (*env)->ReleaseStringUTFChars(env, jgatewayhostname, gatewayhostname); - (*env)->ReleaseStringUTFChars(env, jgatewayusername, gatewayusername); - (*env)->ReleaseStringUTFChars(env, jgatewaypassword, gatewaypassword); + + ret = JNI_TRUE; + +out_fail_strdup: (*env)->ReleaseStringUTFChars(env, jgatewaydomain, gatewaydomain); +out_fail_domain: + (*env)->ReleaseStringUTFChars(env, jgatewaypassword, gatewaypassword); +out_fail_password: + (*env)->ReleaseStringUTFChars(env, jgatewayusername, gatewayusername); +out_fail_username: + (*env)->ReleaseStringUTFChars(env, jgatewayhostname, gatewayhostname); + + return ret; } static void copy_pixel_buffer(UINT8* dstBuf, UINT8* srcBuf, int x, int y, int width, int height, int wBuf, int hBuf, int bpp) @@ -1065,7 +1192,7 @@ JNIEXPORT jboolean JNICALL jni_freerdp_update_graphics( return JNI_TRUE; } -JNIEXPORT void JNICALL jni_freerdp_send_key_event( +JNIEXPORT jboolean JNICALL jni_freerdp_send_key_event( JNIEnv *env, jclass cls, jint instance, jint keycode, jboolean down) { DWORD scancode; @@ -1077,54 +1204,86 @@ JNIEXPORT void JNICALL jni_freerdp_send_key_event( int flags = (down == JNI_TRUE) ? KBD_FLAGS_DOWN : KBD_FLAGS_RELEASE; flags |= (scancode & KBDEXT) ? KBD_FLAGS_EXTENDED : 0; event = (ANDROID_EVENT*) android_event_key_new(flags, scancode & 0xFF); + if (!event) + return JNI_FALSE; - android_push_event(inst, event); + if (!android_push_event(inst, event)) + { + android_event_key_free((ANDROID_EVENT_KEY *)event); + return JNI_FALSE; + } DEBUG_ANDROID("send_key_event: %d, %d", (int)scancode, flags); + return JNI_TRUE; } -JNIEXPORT void JNICALL jni_freerdp_send_unicodekey_event( +JNIEXPORT jboolean JNICALL jni_freerdp_send_unicodekey_event( JNIEnv *env, jclass cls, jint instance, jint keycode) { ANDROID_EVENT* event; freerdp* inst = (freerdp*)instance; event = (ANDROID_EVENT*) android_event_unicodekey_new(keycode); - android_push_event(inst, event); + if (!event) + return JNI_FALSE; + if (!android_push_event(inst, event)) + { + android_event_unicodekey_free((ANDROID_EVENT_KEY *)event); + return JNI_FALSE; + } DEBUG_ANDROID("send_unicodekey_event: %d", keycode); + return JNI_TRUE; } -JNIEXPORT void JNICALL jni_freerdp_send_cursor_event( +JNIEXPORT jboolean JNICALL jni_freerdp_send_cursor_event( JNIEnv *env, jclass cls, jint instance, jint x, jint y, jint flags) { ANDROID_EVENT* event; freerdp* inst = (freerdp*)instance; event = (ANDROID_EVENT*) android_event_cursor_new(flags, x, y); - android_push_event(inst, event); + if (!event) + return JNI_FALSE; + + if (!android_push_event(inst, event)) + { + android_event_cursor_free((ANDROID_EVENT_CURSOR *)event); + return JNI_FALSE; + } DEBUG_ANDROID("send_cursor_event: (%d, %d), %d", x, y, flags); + return JNI_TRUE; } -JNIEXPORT void JNICALL jni_freerdp_send_clipboard_data(JNIEnv *env, jclass cls, jint instance, jstring jdata) +JNIEXPORT jboolean JNICALL jni_freerdp_send_clipboard_data(JNIEnv *env, jclass cls, jint instance, jstring jdata) { ANDROID_EVENT* event; freerdp* inst = (freerdp*)instance; const jbyte *data = jdata != NULL ? (*env)->GetStringUTFChars(env, jdata, NULL) : NULL; int data_length = data ? strlen(data) : 0; + jboolean ret = JNI_FALSE;; event = (ANDROID_EVENT*) android_event_clipboard_new((void*)data, data_length); - android_push_event(inst, event); + if (!event) + goto out_fail; + + if (!android_push_event(inst, event)) + { + android_event_clipboard_free((ANDROID_EVENT_CLIPBOARD *)event); + goto out_fail; + } DEBUG_ANDROID("send_clipboard_data: (%s)", data); + ret = JNI_TRUE; +out_fail: if (data) (*env)->ReleaseStringUTFChars(env, jdata, data); + return ret; } JNIEXPORT jstring JNICALL jni_freerdp_get_version(JNIEnv *env, jclass cls) { return (*env)->NewStringUTF(env, GIT_REVISION); } - diff --git a/client/Android/FreeRDPCore/jni/android_freerdp.h b/client/Android/FreeRDPCore/jni/android_freerdp.h index dd36a65d1..d6f5f4dfe 100644 --- a/client/Android/FreeRDPCore/jni/android_freerdp.h +++ b/client/Android/FreeRDPCore/jni/android_freerdp.h @@ -44,27 +44,27 @@ JNIEXPORT jint JNICALL jni_freerdp_new(JNIEnv *env, jclass cls); JNIEXPORT void JNICALL jni_freerdp_free(JNIEnv *env, jclass cls, jint instance); JNIEXPORT jboolean JNICALL jni_freerdp_connect(JNIEnv *env, jclass cls, jint instance); JNIEXPORT jboolean JNICALL jni_freerdp_disconnect(JNIEnv *env, jclass cls, jint instance); -JNIEXPORT void JNICALL jni_freerdp_cancel_connection(JNIEnv *env, jclass cls, jint instance); -JNIEXPORT void JNICALL jni_freerdp_set_connection_info(JNIEnv *env, jclass cls, jint instance, +JNIEXPORT jboolean JNICALL jni_freerdp_cancel_connection(JNIEnv *env, jclass cls, jint instance); +JNIEXPORT jboolean JNICALL jni_freerdp_set_connection_info(JNIEnv *env, jclass cls, jint instance, jstring jhostname, jstring jusername, jstring jpassword, jstring jdomain, jint width, jint height, jint color_depth, jint port, jboolean console, jint security, jstring jcertname); JNIEXPORT void JNICALL jni_freerdp_set_performance_flags(JNIEnv *env, jclass cls, jint instance, jboolean remotefx, jboolean disableWallpaper, jboolean disableFullWindowDrag, jboolean disableMenuAnimations, jboolean disableTheming, jboolean enableFontSmoothing, jboolean enableDesktopComposition); -JNIEXPORT void JNICALL jni_freerdp_set_advanced_settings(JNIEnv *env, jclass cls, +JNIEXPORT jboolean JNICALL jni_freerdp_set_advanced_settings(JNIEnv *env, jclass cls, jint instance, jstring jRemoteProgram, jstring jWorkDir, jboolean async_channel, jboolean async_transport, jboolean async_input, jboolean async_update); -JNIEXPORT void JNICALL jni_freerdp_set_drive_redirection(JNIEnv *env, jclass cls, jint instance, jstring jpath); -JNIEXPORT void JNICALL jni_freerdp_set_sound_redirection(JNIEnv *env, jclass cls, jint instance, jint redirect); -JNIEXPORT void JNICALL jni_freerdp_set_microphone_redirection(JNIEnv *env, jclass cls, jint instance, jboolean enable); +JNIEXPORT jboolean JNICALL jni_freerdp_set_drive_redirection(JNIEnv *env, jclass cls, jint instance, jstring jpath); +JNIEXPORT jboolean JNICALL jni_freerdp_set_sound_redirection(JNIEnv *env, jclass cls, jint instance, jint redirect); +JNIEXPORT jboolean JNICALL jni_freerdp_set_microphone_redirection(JNIEnv *env, jclass cls, jint instance, jboolean enable); JNIEXPORT void JNICALL jni_freerdp_set_clipboard_redirection(JNIEnv *env, jclass cls, jint instance, jboolean enable); -JNIEXPORT void JNICALL jni_freerdp_set_gateway_info(JNIEnv *env, jclass cls, jint instance, jstring jgatewayhostname, jint port, jstring jgatewayusername, jstring jgatewaypassword, jstring jgatewaydomain); -JNIEXPORT void JNICALL jni_freerdp_set_data_directory(JNIEnv *env, jclass cls, jint instance, jstring jdirectory); +JNIEXPORT jboolean JNICALL jni_freerdp_set_gateway_info(JNIEnv *env, jclass cls, jint instance, jstring jgatewayhostname, jint port, jstring jgatewayusername, jstring jgatewaypassword, jstring jgatewaydomain); +JNIEXPORT jboolean JNICALL jni_freerdp_set_data_directory(JNIEnv *env, jclass cls, jint instance, jstring jdirectory); JNIEXPORT jboolean JNICALL jni_freerdp_update_graphics(JNIEnv *env, jclass cls, jint instance, jobject bitmap, jint x, jint y, jint width, jint height); -JNIEXPORT void JNICALL jni_freerdp_send_cursor_event(JNIEnv *env, jclass cls, jint instance, jint x, jint y, jint flags); -JNIEXPORT void JNICALL jni_freerdp_send_key_event(JNIEnv *env, jclass cls, jint instance, jint keycode, jboolean down); -JNIEXPORT void JNICALL jni_freerdp_send_unicodekey_event(JNIEnv *env, jclass cls, jint instance, jint keycode); -JNIEXPORT void JNICALL jni_freerdp_send_clipboard_data(JNIEnv *env, jclass cls, jint instance, jstring jdata); +JNIEXPORT jboolean JNICALL jni_freerdp_send_cursor_event(JNIEnv *env, jclass cls, jint instance, jint x, jint y, jint flags); +JNIEXPORT jboolean JNICALL jni_freerdp_send_key_event(JNIEnv *env, jclass cls, jint instance, jint keycode, jboolean down); +JNIEXPORT jboolean JNICALL jni_freerdp_send_unicodekey_event(JNIEnv *env, jclass cls, jint instance, jint keycode); +JNIEXPORT jboolean JNICALL jni_freerdp_send_clipboard_data(JNIEnv *env, jclass cls, jint instance, jstring jdata); JNIEXPORT jstring JNICALL jni_freerdp_get_version(JNIEnv *env, jclass cls); #endif /* __ANDROID_FREERDP_H */ diff --git a/client/Android/FreeRDPCore/jni/android_jni_utils.c b/client/Android/FreeRDPCore/jni/android_jni_utils.c index f83f74938..eef868789 100644 --- a/client/Android/FreeRDPCore/jni/android_jni_utils.c +++ b/client/Android/FreeRDPCore/jni/android_jni_utils.c @@ -99,6 +99,8 @@ char* get_string_from_string_builder(JNIEnv* env, jobject strBuilder) // read string native_str = (*env)->GetStringUTFChars(env, strObj, NULL); + if (!native_str) + return NULL; result = strdup(native_str); (*env)->ReleaseStringUTFChars(env, strObj, native_str); diff --git a/client/Android/FreeRDPCore/jni/generated/android_freerdp_jni.c b/client/Android/FreeRDPCore/jni/generated/android_freerdp_jni.c index bcc61ca94..77b9137fb 100644 --- a/client/Android/FreeRDPCore/jni/generated/android_freerdp_jni.c +++ b/client/Android/FreeRDPCore/jni/generated/android_freerdp_jni.c @@ -40,32 +40,32 @@ JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_free return jni_freerdp_disconnect(env, cls, instance); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1cancel_1connection(JNIEnv *env, jclass cls, jint instance) +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1cancel_1connection(JNIEnv *env, jclass cls, jint instance) { - jni_freerdp_cancel_connection(env, cls, instance); + return jni_freerdp_cancel_connection(env, cls, instance); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1connection_1info(JNIEnv *env, jclass cls, jint instance, +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1connection_1info(JNIEnv *env, jclass cls, jint instance, jstring jhostname, jstring jusername, jstring jpassword, jstring jdomain, jint width, jint height, jint color_depth, jint port, jboolean console, jint security, jstring certname) { - jni_freerdp_set_connection_info(env, cls, instance, jhostname, jusername, jpassword, jdomain, + return jni_freerdp_set_connection_info(env, cls, instance, jhostname, jusername, jpassword, jdomain, width, height, color_depth, port, console, security, certname); } -JNIEXPORT void JNICALL +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1advanced_1settings( JNIEnv *env, jclass cls, jint instance, jstring remote_program, jstring work_dir, jboolean async_channel, jboolean async_transport, jboolean async_input, jboolean async_update) { - jni_freerdp_set_advanced_settings(env, cls, instance, remote_program, work_dir, + return jni_freerdp_set_advanced_settings(env, cls, instance, remote_program, work_dir, async_channel, async_transport, async_input, async_update); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1data_1directory(JNIEnv *env, jclass cls, jint instance, jstring directory) +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1data_1directory(JNIEnv *env, jclass cls, jint instance, jstring directory) { - jni_freerdp_set_data_directory(env, cls, instance, directory); + return jni_freerdp_set_data_directory(env, cls, instance, directory); } JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1performance_1flags( @@ -81,28 +81,28 @@ JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_ jni_freerdp_set_clipboard_redirection(env, cls, inst, enable); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1sound_1redirection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1sound_1redirection (JNIEnv *env, jclass cls, jint inst, jint redirect) { - jni_freerdp_set_sound_redirection(env, cls, inst, redirect); + return jni_freerdp_set_sound_redirection(env, cls, inst, redirect); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1microphone_1redirection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1microphone_1redirection (JNIEnv *env, jclass cls, jint inst, jboolean redirect) { - jni_freerdp_set_microphone_redirection(env, cls, inst, redirect); + return jni_freerdp_set_microphone_redirection(env, cls, inst, redirect); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1drive_1redirection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1drive_1redirection (JNIEnv *env, jclass cls, jint inst, jstring path) { - jni_freerdp_set_drive_redirection(env, cls, inst, path); + return jni_freerdp_set_drive_redirection(env, cls, inst, path); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1gateway_1info +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1gateway_1info (JNIEnv *env, jclass cls, jint inst, jstring hostname, jint port, jstring username, jstring password, jstring domain) { - jni_freerdp_set_gateway_info(env, cls, inst, hostname, port, username, password, domain); + return jni_freerdp_set_gateway_info(env, cls, inst, hostname, port, username, password, domain); } JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1update_1graphics( @@ -111,28 +111,28 @@ JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_free return jni_freerdp_update_graphics(env, cls, instance, bitmap, x, y, width, height); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1cursor_1event( +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1cursor_1event( JNIEnv *env, jclass cls, jint instance, jint x, jint y, jint flags) { - jni_freerdp_send_cursor_event(env, cls, instance, x, y, flags); + return jni_freerdp_send_cursor_event(env, cls, instance, x, y, flags); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1key_1event( +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1key_1event( JNIEnv *env, jclass cls, jint instance, jint keycode, jboolean down) { - jni_freerdp_send_key_event(env, cls, instance, keycode, down); + return jni_freerdp_send_key_event(env, cls, instance, keycode, down); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1unicodekey_1event +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1unicodekey_1event (JNIEnv *env, jclass cls, jint instance, jint keycode) { - jni_freerdp_send_unicodekey_event(env, cls, instance, keycode); + return jni_freerdp_send_unicodekey_event(env, cls, instance, keycode); } -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1clipboard_1data +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1clipboard_1data (JNIEnv *env, jclass cls, jint instance, jstring data) { - jni_freerdp_send_clipboard_data(env, cls, instance, data); + return jni_freerdp_send_clipboard_data(env, cls, instance, data); } JNIEXPORT jstring JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1get_1version(JNIEnv *env, jclass cls) diff --git a/client/Android/FreeRDPCore/jni/generated/com_freerdp_freerdpcore_services_LibFreeRDP.h b/client/Android/FreeRDPCore/jni/generated/com_freerdp_freerdpcore_services_LibFreeRDP.h index 951567bbb..50b0c74f8 100644 --- a/client/Android/FreeRDPCore/jni/generated/com_freerdp_freerdpcore_services_LibFreeRDP.h +++ b/client/Android/FreeRDPCore/jni/generated/com_freerdp_freerdpcore_services_LibFreeRDP.h @@ -42,17 +42,17 @@ JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_free /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_cancel_connection - * Signature: (I)V + * Signature: (I)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1cancel_1connection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1cancel_1connection (JNIEnv *, jclass, jint); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_connection_info - * Signature: (ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIZILjava/lang/String;)V + * Signature: (ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIZILjava/lang/String;)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1connection_1info +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1connection_1info (JNIEnv *, jclass, jint, jstring, jstring, jstring, jstring, jint, jint, jint, jint, jboolean, jint, jstring); /* @@ -66,17 +66,17 @@ JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_ /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_advanced_settings - * Signature: (ILjava/lang/String;Ljava/lang/String;ZZZZ)V + * Signature: (ILjava/lang/String;Ljava/lang/String;ZZZZ)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1advanced_1settings +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1advanced_1settings (JNIEnv *, jclass, jint, jstring, jstring, jboolean, jboolean, jboolean, jboolean); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_data_directory - * Signature: (ILjava/lang/String;)V + * Signature: (ILjava/lang/String;)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1data_1directory +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1data_1directory (JNIEnv *, jclass, jint, jstring); /* @@ -90,33 +90,33 @@ JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_ /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_sound_redirection - * Signature: (IZ)V + * Signature: (II)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1sound_1redirection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1sound_1redirection (JNIEnv *, jclass, jint, jint); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_microphone_redirection - * Signature: (IZ)V + * Signature: (IZ)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1microphone_1redirection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1microphone_1redirection (JNIEnv *, jclass, jint, jboolean); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_drive_redirection - * Signature: (ILjava/lang/String;)V + * Signature: (ILjava/lang/String;)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1drive_1redirection +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1drive_1redirection (JNIEnv *, jclass, jint, jstring); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_set_gateway_info - * Signature: (ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + * Signature: (ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1gateway_1info +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1set_1gateway_1info (JNIEnv *, jclass, jint, jstring, jint, jstring, jstring, jstring); /* @@ -130,33 +130,33 @@ JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_free /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_send_cursor_event - * Signature: (IIII)V + * Signature: (IIII)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1cursor_1event +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1cursor_1event (JNIEnv *, jclass, jint, jint, jint, jint); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_send_key_event - * Signature: (IIZ)V + * Signature: (IIZ)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1key_1event +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1key_1event (JNIEnv *, jclass, jint, jint, jboolean); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_send_unicodekey_event - * Signature: (II)V + * Signature: (II)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1unicodekey_1event +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1unicodekey_1event (JNIEnv *, jclass, jint, jint); /* * Class: com_freerdp_freerdpcore_services_LibFreeRDP * Method: freerdp_send_clipboard_data - * Signature: (ILjava/lang/String;)V + * Signature: (ILjava/lang/String;)Z */ -JNIEXPORT void JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1clipboard_1data +JNIEXPORT jboolean JNICALL Java_com_freerdp_freerdpcore_services_LibFreeRDP_freerdp_1send_1clipboard_1data (JNIEnv *, jclass, jint, jstring); /* diff --git a/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/LibFreeRDP.java b/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/LibFreeRDP.java index 934404a7a..c5e896f34 100644 --- a/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/LibFreeRDP.java +++ b/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/LibFreeRDP.java @@ -23,9 +23,9 @@ public class LibFreeRDP private static native void freerdp_free(int inst); private static native boolean freerdp_connect(int inst); private static native boolean freerdp_disconnect(int inst); - private static native void freerdp_cancel_connection(int inst); + private static native boolean freerdp_cancel_connection(int inst); - private static native void freerdp_set_connection_info(int inst, + private static native boolean freerdp_set_connection_info(int inst, String hostname, String username, String password, String domain, int width, int height, int color_depth, int port, boolean console, int security, String certname); @@ -35,27 +35,27 @@ public class LibFreeRDP boolean disableMenuAnimations, boolean disableTheming, boolean enableFontSmoothing, boolean enableDesktopComposition); - private static native void freerdp_set_advanced_settings(int inst, + private static native boolean freerdp_set_advanced_settings(int inst, String remoteProgram, String workDir, boolean async_channel, boolean async_transport, boolean async_input, boolean async_update); - private static native void freerdp_set_data_directory(int inst, String directory); + private static native boolean freerdp_set_data_directory(int inst, String directory); private static native void freerdp_set_clipboard_redirection(int inst, boolean enable); - private static native void freerdp_set_sound_redirection(int inst, int redirect); - private static native void freerdp_set_microphone_redirection(int inst, boolean enable); - private static native void freerdp_set_drive_redirection(int inst, String path); + private static native boolean freerdp_set_sound_redirection(int inst, int redirect); + private static native boolean freerdp_set_microphone_redirection(int inst, boolean enable); + private static native boolean freerdp_set_drive_redirection(int inst, String path); - private static native void freerdp_set_gateway_info(int inst, String gatewayhostname, int port, + private static native boolean freerdp_set_gateway_info(int inst, String gatewayhostname, int port, String gatewayusername, String gatewaypassword, String gatewaydomain); private static native boolean freerdp_update_graphics(int inst, Bitmap bitmap, int x, int y, int width, int height); - private static native void freerdp_send_cursor_event(int inst, int x, int y, int flags); - private static native void freerdp_send_key_event(int inst, int keycode, boolean down); - private static native void freerdp_send_unicodekey_event(int inst, int keycode); - private static native void freerdp_send_clipboard_data(int inst, String data); + private static native boolean freerdp_send_cursor_event(int inst, int x, int y, int flags); + private static native boolean freerdp_send_key_event(int inst, int keycode, boolean down); + private static native boolean freerdp_send_unicodekey_event(int inst, int keycode); + private static native boolean freerdp_send_clipboard_data(int inst, String data); private static native String freerdp_get_version(); @@ -106,9 +106,9 @@ public class LibFreeRDP return freerdp_disconnect(inst); } - public static void cancelConnection(int inst) + public static boolean cancelConnection(int inst) { - freerdp_cancel_connection(inst); + return freerdp_cancel_connection(inst); } public static boolean setConnectionInfo(int inst, BookmarkBase bookmark) @@ -185,9 +185,9 @@ public class LibFreeRDP return true; } - public static void setDataDirectory(int inst, String directory) + public static boolean setDataDirectory(int inst, String directory) { - freerdp_set_data_directory(inst, directory); + return freerdp_set_data_directory(inst, directory); } public static boolean updateGraphics(int inst, Bitmap bitmap, int x, int y, int width, int height) @@ -195,24 +195,24 @@ public class LibFreeRDP return freerdp_update_graphics(inst, bitmap, x, y, width, height); } - public static void sendCursorEvent(int inst, int x, int y, int flags) + public static boolean sendCursorEvent(int inst, int x, int y, int flags) { - freerdp_send_cursor_event(inst, x, y, flags); + return freerdp_send_cursor_event(inst, x, y, flags); } - public static void sendKeyEvent(int inst, int keycode, boolean down) + public static boolean sendKeyEvent(int inst, int keycode, boolean down) { - freerdp_send_key_event(inst, keycode, down); + return freerdp_send_key_event(inst, keycode, down); } - public static void sendUnicodeKeyEvent(int inst, int keycode) + public static boolean sendUnicodeKeyEvent(int inst, int keycode) { - freerdp_send_unicodekey_event(inst, keycode); + return freerdp_send_unicodekey_event(inst, keycode); } - public static void sendClipboardData(int inst, String data) + public static boolean sendClipboardData(int inst, String data) { - freerdp_send_clipboard_data(inst, data); + return freerdp_send_clipboard_data(inst, data); } private static void OnConnectionSuccess(int inst) diff --git a/client/DirectFB/dfreerdp.c b/client/DirectFB/dfreerdp.c index 2c6d1ef27..56b9ff645 100644 --- a/client/DirectFB/dfreerdp.c +++ b/client/DirectFB/dfreerdp.c @@ -179,9 +179,7 @@ BOOL df_pre_connect(freerdp* instance) freerdp_channels_pre_connect(instance->context->channels, instance); - instance->context->cache = cache_new(instance->settings); - - return TRUE; + return (instance->context->cache = cache_new(instance->settings)) != NULL; } BOOL df_post_connect(freerdp* instance) @@ -237,9 +235,7 @@ BOOL df_post_connect(freerdp* instance) pointer_cache_register_callbacks(instance->update); df_register_graphics(instance->context->graphics); - freerdp_channels_post_connect(instance->context->channels, instance); - - return TRUE; + return freerdp_channels_post_connect(instance->context->channels, instance) >= 0; } BOOL df_verify_certificate(freerdp* instance, char* subject, char* issuer, char* fingerprint) diff --git a/client/Sample/freerdp.c b/client/Sample/freerdp.c index 4784e4b64..5291cb78b 100644 --- a/client/Sample/freerdp.c +++ b/client/Sample/freerdp.c @@ -122,9 +122,7 @@ static BOOL tf_post_connect(freerdp* instance) instance->update->BeginPaint = tf_begin_paint; instance->update->EndPaint = tf_end_paint; - freerdp_channels_post_connect(instance->context->channels, instance); - - return TRUE; + return (freerdp_channels_post_connect(instance->context->channels, instance) >= 0); } static void* tf_client_thread_proc(freerdp* instance) diff --git a/client/Wayland/wlf_window.c b/client/Wayland/wlf_window.c index fd73ede1a..72b57eaf3 100644 --- a/client/Wayland/wlf_window.c +++ b/client/Wayland/wlf_window.c @@ -149,9 +149,9 @@ wlfWindow* wlf_CreateDesktopWindow(wlfContext* wlfc, char* name, int width, int wlf_ResizeDesktopWindow(wlfc, window, width, height); wl_surface_damage(window->surface, 0, 0, window->width, window->height); - } - wlf_SetWindowText(wlfc, window, name); + wlf_SetWindowText(wlfc, window, name); + } return window; } diff --git a/client/Wayland/wlfreerdp.c b/client/Wayland/wlfreerdp.c index d29ce2c5c..456e64ac1 100644 --- a/client/Wayland/wlfreerdp.c +++ b/client/Wayland/wlfreerdp.c @@ -142,7 +142,7 @@ static BOOL wl_post_connect(freerdp* instance) /* put Wayland data in the context here */ context->window = window; - if (freerdp_channels_post_connect(instance->context->channels, instance)) + if (freerdp_channels_post_connect(instance->context->channels, instance) < 0) return FALSE; wlf_UpdateWindowArea(context, window, 0, 0, gdi->width, gdi->height); diff --git a/client/Windows/cli/wfreerdp.c b/client/Windows/cli/wfreerdp.c index b481bbac6..a9b3c1730 100644 --- a/client/Windows/cli/wfreerdp.c +++ b/client/Windows/cli/wfreerdp.c @@ -50,6 +50,7 @@ INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine rdpContext* context; rdpSettings* settings; RDP_CLIENT_ENTRY_POINTS clientEntryPoints; + int ret = 0; ZeroMemory(&clientEntryPoints, sizeof(RDP_CLIENT_ENTRY_POINTS)); clientEntryPoints.Size = sizeof(RDP_CLIENT_ENTRY_POINTS); @@ -66,9 +67,26 @@ INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine context->argc = __argc; context->argv = (char**) malloc(sizeof(char*) * __argc); + if (!context->argv) + { + ret = 1; + goto out; + } for (index = 0; index < context->argc; index++) + { context->argv[index] = _strdup(__argv[index]); + if (!context->argv[index]) + { + ret = 1; + for (--index; index >= 0; --index) + free(context->argv[index]); + free(context->argv); + context->argv = NULL; + goto out; + } + + } status = freerdp_client_settings_parse_command_line(settings, context->argc, context->argv, FALSE); @@ -89,8 +107,8 @@ INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine GetExitCodeThread(thread, &dwExitCode); freerdp_client_stop(context); - +out: freerdp_client_context_free(context); - return 0; + return ret; } diff --git a/client/Windows/wf_client.c b/client/Windows/wf_client.c index 4fdd56c87..a2fd6e4fc 100644 --- a/client/Windows/wf_client.c +++ b/client/Windows/wf_client.c @@ -275,7 +275,8 @@ BOOL wf_pre_connect(freerdp* instance) wfc->clrconv->palette = NULL; wfc->clrconv->alpha = FALSE; - instance->context->cache = cache_new(settings); + if (!(instance->context->cache = cache_new(settings))) + return FALSE; desktopWidth = settings->DesktopWidth; desktopHeight = settings->DesktopHeight; @@ -321,7 +322,7 @@ BOOL wf_pre_connect(freerdp* instance) (settings->DesktopWidth > 4096) || (settings->DesktopHeight > 4096)) { WLog_ERR(TAG, "invalid dimensions %d %d", settings->DesktopWidth, settings->DesktopHeight); - return 1; + return FALSE; } freerdp_set_param_uint32(settings, FreeRDP_KeyboardLayout, (int) GetKeyboardLayout(0) & 0x0000FFFF); @@ -484,7 +485,8 @@ BOOL wf_post_connect(freerdp* instance) instance->update->BitmapUpdate = wf_gdi_bitmap_update; } - freerdp_channels_post_connect(context->channels, instance); + if (freerdp_channels_post_connect(context->channels, instance) < 0) + return FALSE; if (wfc->fullscreen) floatbar_window_create(wfc); @@ -492,8 +494,6 @@ BOOL wf_post_connect(freerdp* instance) return TRUE; } -static const char wfTargetName[] = "TARGET"; - static CREDUI_INFOA wfUiInfo = { sizeof(CREDUI_INFOA), @@ -518,7 +518,9 @@ BOOL wf_authenticate(freerdp* instance, char** username, char** password, char** ZeroMemory(Password, sizeof(Password)); dwFlags = CREDUI_FLAGS_DO_NOT_PERSIST | CREDUI_FLAGS_EXCLUDE_CERTIFICATES; - status = CredUIPromptForCredentialsA(&wfUiInfo, wfTargetName, NULL, 0, + status = CredUIPromptForCredentialsA(&wfUiInfo, + instance->settings->ServerHostname, + NULL, 0, UserName, CREDUI_MAX_USERNAME_LENGTH + 1, Password, CREDUI_MAX_PASSWORD_LENGTH + 1, &fSave, dwFlags); @@ -534,11 +536,31 @@ BOOL wf_authenticate(freerdp* instance, char** username, char** password, char** status = CredUIParseUserNameA(UserName, User, sizeof(User), Domain, sizeof(Domain)); //WLog_ERR(TAG, "User: %s Domain: %s Password: %s", User, Domain, Password); *username = _strdup(User); + if (!(*username)) + { + WLog_ERR(TAG, "strdup failed", status); + return FALSE; + } if (strlen(Domain) > 0) *domain = _strdup(Domain); + else + *domain = _strdup("\0"); + + if (!(*domain)) + { + free(*username); + WLog_ERR(TAG, "strdup failed", status); + return FALSE; + } *password = _strdup(Password); + if (!(*password)) + { + free(*username); + free(*domain); + return FALSE; + } return TRUE; } @@ -871,6 +893,10 @@ int freerdp_client_load_settings_from_rdp_file(wfContext* wfc, char* filename) if (filename) { settings->ConnectionFile = _strdup(filename); + if (!settings->ConnectionFile) + { + return 3; + } // free old settings file freerdp_client_rdp_file_free(wfc->connectionRdpFile); diff --git a/client/X11/xf_client.c b/client/X11/xf_client.c index 1b771875e..f299d40fc 100644 --- a/client/X11/xf_client.c +++ b/client/X11/xf_client.c @@ -552,6 +552,8 @@ BOOL xf_create_window(xfContext* xfc) if (settings->WindowTitle) { windowTitle = _strdup(settings->WindowTitle); + if (!windowTitle) + return FALSE; } else if (settings->ServerPort == 3389) { @@ -999,6 +1001,8 @@ BOOL xf_pre_connect(freerdp* instance) if (login_name) { settings->Username = _strdup(login_name); + if (!settings->Username) + return FALSE; WLog_INFO(TAG, "No user name set. - Using login name: %s", settings->Username); } } @@ -1016,9 +1020,13 @@ BOOL xf_pre_connect(freerdp* instance) } if (!context->cache) - context->cache = cache_new(settings); + { + if (!(context->cache = cache_new(settings))) + return FALSE; + } - xf_keyboard_init(xfc); + if (!xf_keyboard_init(xfc)) + return FALSE; xf_detect_monitors(xfc, &maxWidth, &maxHeight); @@ -1165,7 +1173,8 @@ BOOL xf_post_connect(freerdp* instance) update->SetKeyboardIndicators = xf_keyboard_set_indicators; xfc->clipboard = xf_clipboard_new(xfc); - freerdp_channels_post_connect(channels, instance); + if (freerdp_channels_post_connect(channels, instance) < 0) + return FALSE; EventArgsInit(&e, "xfreerdp"); e.width = settings->DesktopWidth; @@ -1186,6 +1195,8 @@ static void xf_post_disconnect(freerdp* instance) context = instance->context; xfc = (xfContext*) context; + freerdp_channels_disconnect(context->channels, instance); + gdi_free(instance); if (xfc->clipboard) @@ -1203,8 +1214,6 @@ static void xf_post_disconnect(freerdp* instance) } xf_keyboard_free(xfc); - - freerdp_channels_disconnect(context->channels, instance); } /** Callback set in the rdp_freerdp structure, and used to get the user's password, @@ -1422,8 +1431,8 @@ void* xf_client_thread(void* param) xfContext* xfc; freerdp* instance; rdpContext* context; - HANDLE inputEvent; - HANDLE inputThread; + HANDLE inputEvent = NULL; + HANDLE inputThread = NULL; rdpChannels* channels; rdpSettings* settings; @@ -1781,7 +1790,7 @@ static BOOL xfreerdp_client_new(freerdp* instance, rdpContext* context) xfc->invert = (ImageByteOrder(xfc->display) == MSBFirst) ? TRUE : FALSE; xfc->complex_regions = TRUE; - xfc->x11event = CreateFileDescriptorEvent(NULL, FALSE, FALSE, xfc->xfds); + xfc->x11event = CreateFileDescriptorEvent(NULL, FALSE, FALSE, xfc->xfds, WINPR_FD_READ); if (!xfc->x11event) { WLog_ERR(TAG, "Could not create xfds event"); diff --git a/client/X11/xf_cliprdr.c b/client/X11/xf_cliprdr.c index e9b31650c..8977c9cb7 100644 --- a/client/X11/xf_cliprdr.c +++ b/client/X11/xf_cliprdr.c @@ -838,7 +838,20 @@ static WIN32ERROR xf_cliprdr_server_format_list(CliprdrClientContext* context, C { format = &formatList->formats[i]; clipboard->serverFormats[i].formatId = format->formatId; - clipboard->serverFormats[i].formatName = _strdup(format->formatName); + if (format->formatName) + { + clipboard->serverFormats[i].formatName = _strdup(format->formatName); + if (!clipboard->serverFormats[i].formatName) + { + for (--i; i >= 0; --i) + free(clipboard->serverFormats[i].formatName); + + clipboard->numServerFormats = 0; + free(clipboard->serverFormats); + clipboard->serverFormats = NULL; + return -1; + } + } } clipboard->numTargets = 2; @@ -1106,6 +1119,12 @@ xfClipboard* xf_clipboard_new(xfContext* xfc) clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "text/html", False); clipboard->clientFormats[n].formatId = CB_FORMAT_HTML; clipboard->clientFormats[n].formatName = _strdup("HTML Format"); + if (!clipboard->clientFormats[n].formatName) + { + ClipboardDestroy(clipboard->system); + free(clipboard); + return NULL; + } n++; clipboard->numClientFormats = n; diff --git a/client/X11/xf_event.c b/client/X11/xf_event.c index c6c700c3e..5f13d503d 100644 --- a/client/X11/xf_event.c +++ b/client/X11/xf_event.c @@ -87,7 +87,6 @@ const char* const X11_EVENT_STRINGS[] = BOOL xf_event_action_script_init(xfContext* xfc) { - int exitCode; char* xevent; FILE* actionScript; char buffer[1024] = { 0 }; @@ -102,18 +101,22 @@ BOOL xf_event_action_script_init(xfContext* xfc) actionScript = popen(command, "r"); - if (actionScript < 0) + if (!actionScript) return FALSE; while (fgets(buffer, sizeof(buffer), actionScript)) { strtok(buffer, "\n"); xevent = _strdup(buffer); - if (ArrayList_Add(xfc->xevents, xevent) < 0) + if (!xevent || ArrayList_Add(xfc->xevents, xevent) < 0) + { + ArrayList_Free(xfc->xevents); + xfc->xevents = NULL; return FALSE; + } } - exitCode = pclose(actionScript); + pclose(actionScript); return TRUE; } @@ -127,23 +130,22 @@ void xf_event_action_script_free(xfContext* xfc) } } -int xf_event_execute_action_script(xfContext* xfc, XEvent* event) +static BOOL xf_event_execute_action_script(xfContext* xfc, XEvent* event) { int index; int count; char* name; - int exitCode; FILE* actionScript; BOOL match = FALSE; const char* xeventName; char buffer[1024] = { 0 }; char command[1024] = { 0 }; - if (!xfc->actionScript) - return 1; + if (!xfc->actionScript || !xfc->xevents) + return FALSE; if (event->type > (sizeof(X11_EVENT_STRINGS) / sizeof(const char*))) - return 1; + return FALSE; xeventName = X11_EVENT_STRINGS[event->type]; @@ -161,24 +163,24 @@ int xf_event_execute_action_script(xfContext* xfc, XEvent* event) } if (!match) - return 1; + return FALSE; sprintf_s(command, sizeof(command), "%s xevent %s %d", xfc->actionScript, xeventName, (int) xfc->window->handle); actionScript = popen(command, "r"); - if (actionScript < 0) - return -1; + if (!actionScript) + return FALSE; while (fgets(buffer, sizeof(buffer), actionScript)) { strtok(buffer, "\n"); } - exitCode = pclose(actionScript); + pclose(actionScript); - return 1; + return TRUE; } void xf_event_adjust_coordinates(xfContext* xfc, int* x, int *y) diff --git a/client/X11/xf_gdi.c b/client/X11/xf_gdi.c index 6787f6f0a..96dd81196 100644 --- a/client/X11/xf_gdi.c +++ b/client/X11/xf_gdi.c @@ -221,7 +221,7 @@ BOOL xf_set_rop3(xfContext* xfc, int rop3) UINT32 xf_convert_rdp_order_color(xfContext* xfc, UINT32 color) { - UINT32 r, g, b; + UINT32 r = 0, g = 0, b = 0; switch (xfc->srcBpp) { diff --git a/client/X11/xf_gfx.c b/client/X11/xf_gfx.c index 98e7b4ac0..6c4f864aa 100644 --- a/client/X11/xf_gfx.c +++ b/client/X11/xf_gfx.c @@ -112,7 +112,7 @@ int xf_OutputUpdate(xfContext* xfc, xfGfxSurface* surface) region16_clear(&surface->invalidRegion); XSetClipMask(xfc->display, xfc->gc, None); - XSync(xfc->display, True); + XSync(xfc->display, False); return 1; } diff --git a/client/X11/xf_keyboard.c b/client/X11/xf_keyboard.c index 0bd1e081d..a85186f8a 100644 --- a/client/X11/xf_keyboard.c +++ b/client/X11/xf_keyboard.c @@ -45,7 +45,6 @@ BOOL xf_keyboard_action_script_init(xfContext* xfc) { - int exitCode; FILE* keyScript; char* keyCombination; char buffer[1024] = { 0 }; @@ -61,11 +60,11 @@ BOOL xf_keyboard_action_script_init(xfContext* xfc) xfc->actionScript = _strdup("/usr/share/freerdp/action.sh"); if (!xfc->actionScript) - return 0; + return FALSE; xfc->keyCombinations = ArrayList_New(TRUE); if (!xfc->keyCombinations) - return 0; + return FALSE; ArrayList_Object(xfc->keyCombinations)->fnObjectFree = free; @@ -73,24 +72,30 @@ BOOL xf_keyboard_action_script_init(xfContext* xfc) keyScript = popen(command, "r"); - if (keyScript < 0) + if (!keyScript) { free(xfc->actionScript); xfc->actionScript = NULL; - return 0; + return FALSE; } while (fgets(buffer, sizeof(buffer), keyScript) != NULL) { strtok(buffer, "\n"); keyCombination = _strdup(buffer); - if (ArrayList_Add(xfc->keyCombinations, keyCombination) < 0) - return 0; + if (!keyCombination || ArrayList_Add(xfc->keyCombinations, keyCombination) < 0) + { + ArrayList_Free(xfc->keyCombinations); + free(xfc->actionScript); + xfc->actionScript = NULL; + pclose(keyScript); + return FALSE; + } } - exitCode = pclose(keyScript); - + pclose(keyScript); return xf_event_action_script_init(xfc); + } void xf_keyboard_action_script_free(xfContext* xfc) @@ -110,7 +115,7 @@ void xf_keyboard_action_script_free(xfContext* xfc) } } -void xf_keyboard_init(xfContext* xfc) +BOOL xf_keyboard_init(xfContext* xfc) { xf_keyboard_clear(xfc); @@ -121,9 +126,11 @@ void xf_keyboard_init(xfContext* xfc) if (xfc->modifierMap) XFreeModifiermap(xfc->modifierMap); - xfc->modifierMap = XGetModifierMapping(xfc->display); + if (!(xfc->modifierMap = XGetModifierMapping(xfc->display))) + return FALSE; xf_keyboard_action_script_init(xfc); + return TRUE; } void xf_keyboard_free(xfContext* xfc) @@ -407,7 +414,7 @@ int xf_keyboard_execute_action_script(xfContext* xfc, XF_MODIFIER_KEYS* mod, Key keyScript = popen(command, "r"); - if (keyScript < 0) + if (!keyScript) return -1; while (fgets(buffer, sizeof(buffer), keyScript) != NULL) diff --git a/client/X11/xf_keyboard.h b/client/X11/xf_keyboard.h index 0261ed91a..606fdcff9 100644 --- a/client/X11/xf_keyboard.h +++ b/client/X11/xf_keyboard.h @@ -44,7 +44,7 @@ struct _XF_MODIFIER_KEYS }; typedef struct _XF_MODIFIER_KEYS XF_MODIFIER_KEYS; -void xf_keyboard_init(xfContext* xfc); +BOOL xf_keyboard_init(xfContext* xfc); void xf_keyboard_free(xfContext* xfc); void xf_keyboard_clear(xfContext* xfc); void xf_keyboard_key_press(xfContext* xfc, BYTE keycode, KeySym keysym); diff --git a/client/X11/xf_rail.c b/client/X11/xf_rail.c index c05e33804..ae5e269ef 100644 --- a/client/X11/xf_rail.c +++ b/client/X11/xf_rail.c @@ -312,6 +312,11 @@ static BOOL xf_rail_window_common(rdpContext* context, WINDOW_ORDER_INFO* orderI { appWindow->title = _strdup("RdpRailWindow"); } + if (!appWindow->title) + { + free(appWindow); + return FALSE; + } HashTable_Add(xfc->railWindows, (void*) (UINT_PTR) orderInfo->windowId, (void*) appWindow); diff --git a/client/X11/xf_tsmf.c b/client/X11/xf_tsmf.c index 450cc4150..a47bf132b 100644 --- a/client/X11/xf_tsmf.c +++ b/client/X11/xf_tsmf.c @@ -187,6 +187,7 @@ int xf_tsmf_xv_video_frame_event(TsmfClientContext* tsmf, TSMF_VIDEO_FRAME_EVENT else { WLog_DBG(TAG, "pixel format 0x%X not supported by hardware.", pixfmt); + free(xrects); return -1003; } @@ -213,6 +214,7 @@ int xf_tsmf_xv_video_frame_event(TsmfClientContext* tsmf, TSMF_VIDEO_FRAME_EVENT if (!XShmAttach(xfc->display, &shminfo)) { XFree(image); + free(xrects); WLog_DBG(TAG, "XShmAttach failed."); return -1004; } diff --git a/client/X11/xf_window.c b/client/X11/xf_window.c index 4c9e19d4f..fe8b367bd 100644 --- a/client/X11/xf_window.c +++ b/client/X11/xf_window.c @@ -36,6 +36,7 @@ #include #include +#include #include #include @@ -335,7 +336,7 @@ static void xf_SetWindowPID(xfContext* xfc, Window window, pid_t pid) static const char* get_shm_id() { static char shm_id[64]; - snprintf(shm_id, sizeof(shm_id), "com.freerdp.xfreerdp.tsmf_%016X", GetCurrentProcessId()); + sprintf_s(shm_id, sizeof(shm_id), "/com.freerdp.xfreerdp.tsmf_%016X", GetCurrentProcessId()); return shm_id; } @@ -368,7 +369,7 @@ xfWindow* xf_CreateDesktopWindow(xfContext* xfc, char* name, int width, int heig CWBackPixel | CWBackingStore | CWOverrideRedirect | CWColormap | CWBorderPixel | CWWinGravity | CWBitGravity, &xfc->attribs); - window->shmid = shm_open(get_shm_id(), O_CREAT | O_EXCL | O_RDWR, S_IREAD | S_IWRITE); + window->shmid = shm_open(get_shm_id(), (O_CREAT | O_RDWR), (S_IREAD | S_IWRITE)); if (window->shmid < 0) { @@ -382,7 +383,7 @@ xfWindow* xf_CreateDesktopWindow(xfContext* xfc, char* name, int width, int heig mem = mmap(0, sizeof(window->handle), PROT_READ | PROT_WRITE, MAP_SHARED, window->shmid, 0); - if (mem == ((int*) -1)) + if (mem == MAP_FAILED) { DEBUG_X11("xf_CreateDesktopWindow: failed to assign pointer to the memory address - shmat()\n"); } @@ -659,7 +660,7 @@ int xf_AppWindowInit(xfContext* xfc, xfAppWindow* appWindow) else { class = malloc(sizeof("RAIL:00000000")); - snprintf(class, sizeof("RAIL:00000000"), "RAIL:%08X", appWindow->windowId); + sprintf_s(class, sizeof("RAIL:00000000"), "RAIL:%08X", appWindow->windowId); class_hints->res_class = class; } diff --git a/client/common/client.c b/client/common/client.c index 53c441342..7d2e5c8d4 100644 --- a/client/common/client.c +++ b/client/common/client.c @@ -213,13 +213,20 @@ int freerdp_client_settings_parse_command_line(rdpSettings* settings, int argc, int freerdp_client_settings_parse_connection_file(rdpSettings* settings, const char* filename) { rdpFile* file; + int ret = -1; file = freerdp_client_rdp_file_new(); - freerdp_client_parse_rdp_file(file, filename); - freerdp_client_populate_settings_from_rdp_file(file, settings); - freerdp_client_rdp_file_free(file); + if (!file) + return -1; + if (!freerdp_client_parse_rdp_file(file, filename)) + goto out; + if (!freerdp_client_populate_settings_from_rdp_file(file, settings)) + goto out; - return 0; + ret = 0; +out: + freerdp_client_rdp_file_free(file); + return ret; } int freerdp_client_settings_parse_connection_file_buffer(rdpSettings* settings, const BYTE* buffer, size_t size) @@ -228,6 +235,8 @@ int freerdp_client_settings_parse_connection_file_buffer(rdpSettings* settings, int status = -1; file = freerdp_client_rdp_file_new(); + if (!file) + return -1; if (freerdp_client_parse_rdp_file_buffer(file, buffer, size) && freerdp_client_populate_settings_from_rdp_file(file, settings)) @@ -243,18 +252,23 @@ int freerdp_client_settings_parse_connection_file_buffer(rdpSettings* settings, int freerdp_client_settings_write_connection_file(const rdpSettings* settings, const char* filename, BOOL unicode) { rdpFile* file; + int ret = -1; file = freerdp_client_rdp_file_new(); + if (!file) + return -1; if (!freerdp_client_populate_rdp_file_from_settings(file, settings)) - return -1; + goto out; if (!freerdp_client_write_rdp_file(file, filename, unicode)) - return -1; + goto out; + ret = 0; +out: freerdp_client_rdp_file_free(file); - return 0; + return ret; } int freerdp_client_settings_parse_assistance_file(rdpSettings* settings, const char* filename) diff --git a/client/common/cmdline.c b/client/common/cmdline.c index 6b40ca630..b4d63a535 100644 --- a/client/common/cmdline.c +++ b/client/common/cmdline.c @@ -91,10 +91,10 @@ COMMAND_LINE_ARGUMENT_A args[] = { "compression-level", COMMAND_LINE_VALUE_REQUIRED, "", NULL, NULL, -1, NULL, "Compression level (0,1,2)" }, { "shell", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "Alternate shell" }, { "shell-dir", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "Shell working directory" }, - { "sound", COMMAND_LINE_VALUE_OPTIONAL, NULL, NULL, NULL, -1, "audio", "Audio output (sound)" }, - { "microphone", COMMAND_LINE_VALUE_OPTIONAL, NULL, NULL, NULL, -1, "mic", "Audio input (microphone)" }, + { "sound", COMMAND_LINE_VALUE_OPTIONAL, "[sys][dev][format][rate][channel][latency][quality]", NULL, NULL, -1, "audio", "Audio output (sound)" }, + { "microphone", COMMAND_LINE_VALUE_OPTIONAL, "[sys][dev][format][rate][channel]", NULL, NULL, -1, "mic", "Audio input (microphone)" }, { "audio-mode", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "Audio output mode" }, - { "multimedia", COMMAND_LINE_VALUE_OPTIONAL, NULL, NULL, NULL, -1, "mmr", "Redirect multimedia (video)" }, + { "multimedia", COMMAND_LINE_VALUE_OPTIONAL, "[sys][dev][decoder]", NULL, NULL, -1, "mmr", "Redirect multimedia (video)" }, { "network", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "Network connection type" }, { "drive", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "Redirect drive" }, { "drives", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, "Redirect all drives" }, @@ -104,7 +104,7 @@ COMMAND_LINE_ARGUMENT_A args[] = { "parallel", COMMAND_LINE_VALUE_OPTIONAL, NULL, NULL, NULL, -1, NULL, "Redirect parallel device" }, { "smartcard", COMMAND_LINE_VALUE_OPTIONAL, NULL, NULL, NULL, -1, NULL, "Redirect smartcard device" }, { "printer", COMMAND_LINE_VALUE_OPTIONAL, NULL, NULL, NULL, -1, NULL, "Redirect printer device" }, - { "usb", COMMAND_LINE_VALUE_REQUIRED, NULL, NULL, NULL, -1, NULL, "Redirect USB device" }, + { "usb", COMMAND_LINE_VALUE_REQUIRED, "[dbg][dev][id|addr][auto]", NULL, NULL, -1, NULL, "Redirect USB device" }, { "multitouch", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, "Redirect multitouch input" }, { "gestures", COMMAND_LINE_VALUE_BOOL, NULL, BoolValueFalse, NULL, -1, NULL, "Consume multitouch input locally" }, { "echo", COMMAND_LINE_VALUE_FLAG, NULL, NULL, NULL, -1, "echo", "Echo channel" }, @@ -216,6 +216,8 @@ int freerdp_client_print_command_line_help(int argc, char** argv) { length = (int)(strlen(arg->Name) + strlen(arg->Format) + 2); str = (char*) calloc(length + 1UL, sizeof(char)); + if (!str) + return -1; sprintf_s(str, length + 1, "%s:%s", arg->Name, arg->Format); printf("%-20s", str); free(str); @@ -231,6 +233,8 @@ int freerdp_client_print_command_line_help(int argc, char** argv) { length = (int) strlen(arg->Name) + 32; str = (char*) calloc(length + 1UL, sizeof(char)); + if (!str) + return -1; sprintf_s(str, length + 1, "%s (default:%s)", arg->Name, arg->Default ? "on" : "off"); @@ -264,10 +268,13 @@ int freerdp_client_print_command_line_help(int argc, char** argv) printf("Printer Redirection: /printer:,\n"); printf("\n"); + printf("Audio Output Redirection: /sound:sys:oss,dev:1,format:1\n"); printf("Audio Output Redirection: /sound:sys:alsa\n"); + printf("Audio Input Redirection: /microphone:sys:oss,dev:1,format:1\n"); printf("Audio Input Redirection: /microphone:sys:alsa\n"); printf("\n"); + printf("Multimedia Redirection: /multimedia:sys:oss,dev:/dev/dsp1,decoder:ffmpeg\n"); printf("Multimedia Redirection: /multimedia:sys:alsa\n"); printf("USB Device Redirection: /usb:id,dev:054c:0268\n"); printf("\n"); @@ -292,7 +299,8 @@ int freerdp_client_command_line_pre_filter(void* context, int index, int argc, L if (_stricmp(&(argv[index])[length - 4], ".rdp") == 0) { settings = (rdpSettings*) context; - settings->ConnectionFile = _strdup(argv[index]); + if (!(settings->ConnectionFile = _strdup(argv[index]))) + return COMMAND_LINE_ERROR_MEMORY; return 1; } @@ -303,7 +311,8 @@ int freerdp_client_command_line_pre_filter(void* context, int index, int argc, L if (_stricmp(&(argv[index])[length - 13], ".msrcIncident") == 0) { settings = (rdpSettings*) context; - settings->AssistanceFile = _strdup(argv[index]); + if (!(settings->AssistanceFile = _strdup(argv[index]))) + return COMMAND_LINE_ERROR_MEMORY; return 1; } @@ -332,12 +341,31 @@ int freerdp_client_add_device_channel(rdpSettings* settings, int count, char** p drive->Type = RDPDR_DTYP_FILESYSTEM; if (count > 1) - drive->Name = _strdup(params[1]); + { + if (!(drive->Name = _strdup(params[1]))) + { + free(drive); + return -1; + } + } if (count > 2) - drive->Path = _strdup(params[2]); + { + if (!(drive->Path = _strdup(params[2]))) + { + free(drive->Name); + free(drive); + return -1; + } + } - freerdp_device_collection_add(settings, (RDPDR_DEVICE*) drive); + if (!freerdp_device_collection_add(settings, (RDPDR_DEVICE*) drive)) + { + free(drive->Path); + free(drive->Name); + free(drive); + return -1; + } return 1; } @@ -361,12 +389,33 @@ int freerdp_client_add_device_channel(rdpSettings* settings, int count, char** p printer->Type = RDPDR_DTYP_PRINT; if (count > 1) - printer->Name = _strdup(params[1]); + { + if (!(printer->Name = _strdup(params[1]))) + { + free(printer); + return -1; + } + } if (count > 2) - printer->DriverName = _strdup(params[2]); + { + if (!(printer->DriverName = _strdup(params[2]))) + { + free(printer->Name); + free(printer); + return -1; + } + } + + + if (!freerdp_device_collection_add(settings, (RDPDR_DEVICE*) printer)) + { + free(printer->DriverName); + free(printer->Name); + free(printer); + return -1; + } - freerdp_device_collection_add(settings, (RDPDR_DEVICE*) printer); } return 1; @@ -391,12 +440,30 @@ int freerdp_client_add_device_channel(rdpSettings* settings, int count, char** p smartcard->Type = RDPDR_DTYP_SMARTCARD; if (count > 1) - smartcard->Name = _strdup(params[1]); + { + if (!(smartcard->Name = _strdup(params[1]))) + { + free(smartcard); + return -1; + } + } if (count > 2) - smartcard->Path = _strdup(params[2]); - - freerdp_device_collection_add(settings, (RDPDR_DEVICE*) smartcard); + { + if (!(smartcard->Path = _strdup(params[2]))) + { + free(smartcard->Name); + free(smartcard); + return -1; + } + } + if (!freerdp_device_collection_add(settings, (RDPDR_DEVICE*) smartcard)) + { + free(smartcard->Path); + free(smartcard->Name); + free(smartcard); + return -1; + } } return 1; @@ -419,18 +486,56 @@ int freerdp_client_add_device_channel(rdpSettings* settings, int count, char** p serial->Type = RDPDR_DTYP_SERIAL; if (count > 1) - serial->Name = _strdup(params[1]); + { + if (!(serial->Name = _strdup(params[1]))) + { + free(serial); + return -1; + } + } if (count > 2) - serial->Path = _strdup(params[2]); + { + if (!(serial->Path = _strdup(params[2]))) + { + free(serial->Name); + free(serial); + return -1; + } + } if (count > 3) - serial->Driver = _strdup(params[3]); + { + if (!(serial->Driver = _strdup(params[3]))) + { + free(serial->Path); + free(serial->Name); + free(serial); + return -1; + } + } if (count > 4) - serial->Permissive = _strdup(params[4]); + { + if (!(serial->Permissive = _strdup(params[4]))) + { + free(serial->Driver); + free(serial->Path); + free(serial->Name); + free(serial); + return -1; + } + } - freerdp_device_collection_add(settings, (RDPDR_DEVICE*) serial); + if (!freerdp_device_collection_add(settings, (RDPDR_DEVICE*) serial)) + { + free(serial->Permissive); + free(serial->Driver); + free(serial->Path); + free(serial->Name); + free(serial); + return -1; + } return 1; } @@ -452,12 +557,31 @@ int freerdp_client_add_device_channel(rdpSettings* settings, int count, char** p parallel->Type = RDPDR_DTYP_PARALLEL; if (count > 1) - parallel->Name = _strdup(params[1]); + { + if (!(parallel->Name = _strdup(params[1]))) + { + free(parallel); + return -1; + } + } if (count > 2) - parallel->Path = _strdup(params[2]); + { + if (!(parallel->Path = _strdup(params[2]))) + { + free(parallel->Name); + free(parallel); + return -1; + } + } - freerdp_device_collection_add(settings, (RDPDR_DEVICE*) parallel); + if (!freerdp_device_collection_add(settings, (RDPDR_DEVICE*) parallel)) + { + free(parallel->Path); + free(parallel->Name); + free(parallel); + return -1; + } return 1; } @@ -470,17 +594,40 @@ int freerdp_client_add_static_channel(rdpSettings* settings, int count, char** p int index; ADDIN_ARGV* args; - args = (ADDIN_ARGV*) malloc(sizeof(ADDIN_ARGV)); + args = (ADDIN_ARGV*) calloc(1, sizeof(ADDIN_ARGV)); + if (!args) + return -1; args->argc = count; args->argv = (char**) calloc(args->argc, sizeof(char*)); + if (!args->argv) + goto error_argv; for (index = 0; index < args->argc; index++) + { args->argv[index] = _strdup(params[index]); + if (!args->argv[index]) + { + for (--index; index >= 0; --index) + free(args->argv[index]); - freerdp_static_channel_collection_add(settings, args); + goto error_argv_strdup; + } + } + + if (!freerdp_static_channel_collection_add(settings, args)) + goto error_argv_index; return 0; + +error_argv_index: + for (index = 0; index < args->argc; index++) + free(args->argv[index]); +error_argv_strdup: + free(args->argv); +error_argv: + free(args); + return -1; } int freerdp_client_add_dynamic_channel(rdpSettings* settings, int count, char** params) @@ -489,16 +636,39 @@ int freerdp_client_add_dynamic_channel(rdpSettings* settings, int count, char** ADDIN_ARGV* args; args = (ADDIN_ARGV*) malloc(sizeof(ADDIN_ARGV)); + if (!args) + return -1; args->argc = count; args->argv = (char**) calloc(args->argc, sizeof(char*)); + if (!args->argv) + goto error_argv; for (index = 0; index < args->argc; index++) + { args->argv[index] = _strdup(params[index]); + if (!args->argv[index]) + { + for (--index; index >= 0; --index) + free(args->argv[index]); - freerdp_dynamic_channel_collection_add(settings, args); + goto error_argv_strdup; + } + } + + if (!freerdp_dynamic_channel_collection_add(settings, args)) + goto error_argv_index; return 0; + +error_argv_index: + for (index = 0; index < args->argc; index++) + free(args->argv[index]); +error_argv_strdup: + free(args->argv); +error_argv: + free(args); + return -1; } static char** freerdp_command_line_parse_comma_separated_values(char* list, int* count) @@ -522,6 +692,8 @@ static char** freerdp_command_line_parse_comma_separated_values(char* list, int* nArgs = nCommas + 1; p = (char**) calloc((nArgs + 1UL), sizeof(char*)); + if (!p) + return NULL; str = (char*) list; @@ -553,7 +725,7 @@ static char** freerdp_command_line_parse_comma_separated_values_offset(char* lis return NULL; p = t; if (count > 0) - MoveMemory(&p[1], p, sizeof(char*) * *count); + MoveMemory(&p[1], p, sizeof(char*) * *count); (*count)++; return p; @@ -562,6 +734,7 @@ static char** freerdp_command_line_parse_comma_separated_values_offset(char* lis int freerdp_client_command_line_post_filter(void* context, COMMAND_LINE_ARGUMENT_A* arg) { rdpSettings* settings = (rdpSettings*) context; + int status = 0; CommandLineSwitchStart(arg) @@ -586,7 +759,7 @@ int freerdp_client_command_line_post_filter(void* context, COMMAND_LINE_ARGUMENT p = freerdp_command_line_parse_comma_separated_values(arg->Value, &count); - freerdp_client_add_static_channel(settings, count, p); + status = freerdp_client_add_static_channel(settings, count, p); free(p); } @@ -712,7 +885,7 @@ int freerdp_client_command_line_post_filter(void* context, COMMAND_LINE_ARGUMENT p = freerdp_command_line_parse_comma_separated_values_offset(arg->Value, &count); p[0] = "rdpsnd"; - freerdp_client_add_static_channel(settings, count, p); + status = freerdp_client_add_static_channel(settings, count, p); free(p); } @@ -724,7 +897,7 @@ int freerdp_client_command_line_post_filter(void* context, COMMAND_LINE_ARGUMENT count = 1; p[0] = "rdpsnd"; - freerdp_client_add_static_channel(settings, count, p); + status = freerdp_client_add_static_channel(settings, count, p); } } CommandLineSwitchCase(arg, "microphone") @@ -789,33 +962,58 @@ int freerdp_client_command_line_post_filter(void* context, COMMAND_LINE_ARGUMENT CommandLineSwitchEnd(arg) - return 0; + return status; } int freerdp_parse_username(char* username, char** user, char** domain) { char* p; - int length; + int length = 0; p = strchr(username, '\\'); + *user = NULL; + *domain = NULL; + if (p) { length = (int) (p - username); + *user = _strdup(&p[1]); + if (!*user) + return -1; + *domain = (char*) calloc(length + 1UL, sizeof(char)); + if (!*domain) + { + free (*user); + *user = NULL; + return -1; + } + strncpy(*domain, username, length); (*domain)[length] = '\0'; - *user = _strdup(&p[1]); } - else + else if (username) { /* Do not break up the name for '@'; both credSSP and the * ClientInfo PDU expect 'user@corp.net' to be transmitted - * as username 'user@corp.net', domain empty. + * as username 'user@corp.net', domain empty (not NULL!). */ *user = _strdup(username); - *domain = NULL; + if (!*user) + return -1; + + *domain = _strdup("\0"); + + if (!*domain) + { + free(*user); + *user = NULL; + return -1; + } } + else + return -1; return 0; } @@ -932,6 +1130,8 @@ int freerdp_map_keyboard_layout_name_to_id(char* name) RDP_KEYBOARD_LAYOUT* layouts; layouts = freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_STANDARD); + if (!layouts) + return -1; for (i = 0; layouts[i].code; i++) { @@ -945,6 +1145,8 @@ int freerdp_map_keyboard_layout_name_to_id(char* name) return id; layouts = freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_VARIANT); + if (!layouts) + return -1; for (i = 0; layouts[i].code; i++) { @@ -958,6 +1160,8 @@ int freerdp_map_keyboard_layout_name_to_id(char* name) return id; layouts = freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_IME); + if (!layouts) + return -1; for (i = 0; layouts[i].code; i++) { @@ -1156,18 +1360,21 @@ int freerdp_client_settings_command_line_status_print(rdpSettings* settings, int RDP_KEYBOARD_LAYOUT* layouts; layouts = freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_STANDARD); + //if (!layouts) /* FIXME*/ printf("\nKeyboard Layouts\n"); for (i = 0; layouts[i].code; i++) printf("0x%08X\t%s\n", (int) layouts[i].code, layouts[i].name); free(layouts); layouts = freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_VARIANT); + //if (!layouts) /* FIXME*/ printf("\nKeyboard Layout Variants\n"); for (i = 0; layouts[i].code; i++) printf("0x%08X\t%s\n", (int) layouts[i].code, layouts[i].name); free(layouts); layouts = freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_IME); + //if (!layouts) /* FIXME*/ printf("\nKeyboard Input Method Editors (IMEs)\n"); for (i = 0; layouts[i].code; i++) printf("0x%08X\t%s\n", (int) layouts[i].code, layouts[i].name); @@ -1198,6 +1405,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, int argc, char** argv, BOOL allowUnknown) { char* p; + char* user = NULL; + char* gwUser = NULL; char* str; int length; int status; @@ -1209,7 +1418,7 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, if (compatibility) { - WLog_WARN(TAG, "Using deprecated command-line interface!"); + WLog_WARN(TAG, "Using deprecated command-line interface!"); return freerdp_client_parse_old_command_line_arguments(argc, argv, settings); } else @@ -1249,13 +1458,16 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, { length = (int) (p - arg->Value); settings->ServerPort = atoi(&p[1]); - settings->ServerHostname = (char*) calloc(length + 1UL, sizeof(char)); + if (!(settings->ServerHostname = (char*) calloc(length + 1UL, sizeof(char)))) + return COMMAND_LINE_ERROR_MEMORY; + strncpy(settings->ServerHostname, arg->Value, length); settings->ServerHostname[length] = '\0'; } else { - settings->ServerHostname = _strdup(arg->Value); + if (!(settings->ServerHostname = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } } else /* ipv6 */ @@ -1266,7 +1478,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, continue; length = p2 - p; - settings->ServerHostname = (char*) calloc(length, sizeof(char)); + if (!(settings->ServerHostname = (char*) calloc(length, sizeof(char)))) + return COMMAND_LINE_ERROR; strncpy(settings->ServerHostname, p+1, length-1); if (*(p2 + 1) == ':') { @@ -1277,7 +1490,9 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "spn-class") { - settings->AuthenticationServiceClass = _strdup(arg->Value); + if (!(settings->AuthenticationServiceClass = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; + } CommandLineSwitchCase(arg, "credentials-delegation") { @@ -1291,7 +1506,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) { settings->SendPreconnectionPdu = TRUE; - settings->PreconnectionBlob = _strdup(arg->Value); + if (!(settings->PreconnectionBlob = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } } CommandLineSwitchCase(arg, "w") @@ -1304,7 +1520,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "size") { - str = _strdup(arg->Value); + if (!(str = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; p = strchr(str, 'x'); @@ -1358,6 +1575,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, int count = 0; p = freerdp_command_line_parse_comma_separated_values(arg->Value, &count); + if (!p) + return COMMAND_LINE_ERROR_MEMORY; if (count > 16) count = 16; @@ -1378,7 +1597,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "t") { - settings->WindowTitle = _strdup(arg->Value); + if (!(settings->WindowTitle = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "decorations") { @@ -1390,7 +1610,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, if (arg->Value) { - str = _strdup(arg->Value); + if (!(str = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; if ((p = strchr(str, 'x'))) { *p = '\0'; @@ -1417,11 +1638,13 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, { settings->ConsoleSession = TRUE; settings->RestrictedAdminModeRequired = TRUE; - settings->PasswordHash = _strdup(arg->Value); + if (!(settings->PasswordHash = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "client-hostname") { - settings->ClientHostname = _strdup(arg->Value); + if (!(settings->ClientHostname = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "kbd") { @@ -1436,11 +1659,15 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, if (id == 0) { id = (unsigned long int) freerdp_map_keyboard_layout_name_to_id(arg->Value); - - if (!id) + if (id == -1) + WLog_ERR(TAG, "A problem occured while mapping the layout name to id"); + else if (id == 0) { - WLog_ERR(TAG, "Could not identify keyboard layout: %s", arg->Value); + WLog_ERR(TAG, "Could not identify keyboard layout: %s", arg->Value); + WLog_ERR(TAG, "Use /kbd-list to list available layouts"); } + if (id <= 0) + return COMMAND_LINE_STATUS_PRINT; } settings->KeyboardLayout = (UINT32) id; @@ -1459,21 +1686,17 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "u") { - char* user; - char* domain; - - freerdp_parse_username(arg->Value, &user, &domain); - - settings->Username = user; - settings->Domain = domain; + user = _strdup(arg->Value); } CommandLineSwitchCase(arg, "d") { - settings->Domain = _strdup(arg->Value); + if (!(settings->Domain = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "p") { - settings->Password = _strdup(arg->Value); + if (!(settings->Password = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "g") { @@ -1485,18 +1708,21 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, { length = (int) (p - arg->Value); settings->GatewayPort = atoi(&p[1]); - settings->GatewayHostname = (char*) calloc(length + 1UL, sizeof(char)); + if (!(settings->GatewayHostname = (char*) calloc(length + 1UL, sizeof(char)))) + return COMMAND_LINE_ERROR_MEMORY; strncpy(settings->GatewayHostname, arg->Value, length); settings->GatewayHostname[length] = '\0'; } else { - settings->GatewayHostname = _strdup(arg->Value); + if (!(settings->GatewayHostname = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } } else { - settings->GatewayHostname = _strdup(settings->ServerHostname); + if (!(settings->GatewayHostname = _strdup(settings->ServerHostname))) + return COMMAND_LINE_ERROR_MEMORY; } settings->GatewayEnabled = TRUE; @@ -1506,24 +1732,21 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "gu") { - char* user; - char* domain; - - freerdp_parse_username(arg->Value, &user, &domain); - - settings->GatewayUsername = user; - settings->GatewayDomain = domain; + if (!(gwUser = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; settings->GatewayUseSameCredentials = FALSE; } CommandLineSwitchCase(arg, "gd") { - settings->GatewayDomain = _strdup(arg->Value); + if (!(settings->GatewayDomain = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; settings->GatewayUseSameCredentials = FALSE; } CommandLineSwitchCase(arg, "gp") { - settings->GatewayPassword = _strdup(arg->Value); + if (!(settings->GatewayPassword = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; settings->GatewayUseSameCredentials = FALSE; } CommandLineSwitchCase(arg, "gt") @@ -1567,7 +1790,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "app") { - settings->RemoteApplicationProgram = _strdup(arg->Value); + if (!(settings->RemoteApplicationProgram = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; settings->RemoteApplicationMode = TRUE; settings->RemoteAppLanguageBarSupported = TRUE; @@ -1577,28 +1801,35 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "load-balance-info") { - settings->LoadBalanceInfo = (BYTE*) _strdup(arg->Value); + if (!(settings->LoadBalanceInfo = (BYTE*) _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; settings->LoadBalanceInfoLength = (UINT32) strlen((char*) settings->LoadBalanceInfo); } CommandLineSwitchCase(arg, "app-name") { - settings->RemoteApplicationName = _strdup(arg->Value); + if (!(settings->RemoteApplicationName = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; + } CommandLineSwitchCase(arg, "app-icon") { - settings->RemoteApplicationIcon = _strdup(arg->Value); + if (!(settings->RemoteApplicationIcon = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "app-cmd") { - settings->RemoteApplicationCmdLine = _strdup(arg->Value); + if (!(settings->RemoteApplicationCmdLine = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "app-file") { - settings->RemoteApplicationFile = _strdup(arg->Value); + if (!(settings->RemoteApplicationFile = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "app-guid") { - settings->RemoteApplicationGuid = _strdup(arg->Value); + if (!(settings->RemoteApplicationGuid = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "compression") { @@ -1622,11 +1853,13 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "shell") { - settings->AlternateShell = _strdup(arg->Value); + if (!(settings->AlternateShell = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "shell-dir") { - settings->ShellWorkingDirectory = _strdup(arg->Value); + if (!(settings->ShellWorkingDirectory = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "audio-mode") { @@ -1778,7 +2011,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, CommandLineSwitchCase(arg, "pcb") { settings->SendPreconnectionPdu = TRUE; - settings->PreconnectionBlob = _strdup(arg->Value); + if (!(settings->PreconnectionBlob = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "pcid") { @@ -1818,7 +2052,7 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } else { - WLog_ERR(TAG, "unknown protocol security: %s", arg->Value); + WLog_ERR(TAG, "unknown protocol security: %s", arg->Value); } } CommandLineSwitchCase(arg, "encryption-methods") @@ -1842,7 +2076,7 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, else if (!strcmp(p[i], "FIPS")) settings->EncryptionMethods |= ENCRYPTION_METHOD_FIPS; else - WLog_ERR(TAG, "unknown encryption method '%s'", p[i]); + WLog_ERR(TAG, "unknown encryption method '%s'", p[i]); } free(p); @@ -1868,20 +2102,24 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, { if (strcmp(arg->Value, "netmon") == 0) { - settings->AllowedTlsCiphers = _strdup("ALL:!ECDH"); + if (!(settings->AllowedTlsCiphers = _strdup("ALL:!ECDH"))) + return COMMAND_LINE_ERROR_MEMORY; } else if (strcmp(arg->Value, "ma") == 0) { - settings->AllowedTlsCiphers = _strdup("AES128-SHA"); + if (!(settings->AllowedTlsCiphers = _strdup("AES128-SHA"))) + return COMMAND_LINE_ERROR_MEMORY; } else { - settings->AllowedTlsCiphers = _strdup(arg->Value); + if (!(settings->AllowedTlsCiphers = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } } CommandLineSwitchCase(arg, "cert-name") { - settings->CertificateName = _strdup(arg->Value); + if (!(settings->CertificateName = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "cert-ignore") { @@ -1970,11 +2208,13 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } CommandLineSwitchCase(arg, "wm-class") { - settings->WmClass = _strdup(arg->Value); + if (!(settings->WmClass = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "play-rfx") { - settings->PlayRemoteFxFile = _strdup(arg->Value); + if (!(settings->PlayRemoteFxFile = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; settings->PlayRemoteFx = TRUE; } CommandLineSwitchCase(arg, "auth-only") @@ -1998,7 +2238,7 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } else { - WLog_ERR(TAG, "reconnect-cookie: invalid base64 '%s'", arg->Value); + WLog_ERR(TAG, "reconnect-cookie: invalid base64 '%s'", arg->Value); } } CommandLineSwitchCase(arg, "print-reconnect-cookie") @@ -2008,7 +2248,8 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, CommandLineSwitchCase(arg, "assistance") { settings->RemoteAssistanceMode = TRUE; - settings->RemoteAssistancePassword = _strdup(arg->Value); + if (!(settings->RemoteAssistancePassword = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchDefault(arg) { @@ -2018,6 +2259,29 @@ int freerdp_client_settings_parse_command_line_arguments(rdpSettings* settings, } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + if (!settings->Domain && user) + { + int ret; + ret = freerdp_parse_username(user, &settings->Username, &settings->Domain); + free(user); + if (ret != 0 ) + return COMMAND_LINE_ERROR; + } + else + settings->Username = user; + + if (!settings->GatewayDomain && gwUser) + { + int ret; + ret = freerdp_parse_username(gwUser, &settings->GatewayUsername, + &settings->GatewayDomain); + free(gwUser); + if (ret != 0) + return COMMAND_LINE_ERROR; + } + else + settings->GatewayUsername = gwUser; + freerdp_performance_flags_make(settings); if (settings->SupportGraphicsPipeline) @@ -2062,7 +2326,7 @@ int freerdp_client_load_static_channel_addin(rdpChannels* channels, rdpSettings* { if (freerdp_channels_client_load(channels, settings, entry, data) == 0) { - WLog_INFO(TAG, "loading channel %s", name); + WLog_INFO(TAG, "loading channel %s", name); return 0; } } diff --git a/client/common/compatibility.c b/client/common/compatibility.c index da2f4832b..1ec279091 100644 --- a/client/common/compatibility.c +++ b/client/common/compatibility.c @@ -89,7 +89,7 @@ COMMAND_LINE_ARGUMENT_A old_args[] = { NULL, 0, NULL, NULL, NULL, -1, NULL, NULL } }; -void freerdp_client_old_parse_hostname(char* str, char** ServerHostname, UINT32* ServerPort) +BOOL freerdp_client_old_parse_hostname(char* str, char** ServerHostname, UINT32* ServerPort) { char* p; @@ -97,7 +97,8 @@ void freerdp_client_old_parse_hostname(char* str, char** ServerHostname, UINT32* && (p[1] == 0 || (p[1] == ':' && !strchr(p + 2, ':')))) { /* Either "[...]" or "[...]:..." with at most one : after the brackets */ - *ServerHostname = _strdup(str + 1); + if (!(*ServerHostname = _strdup(str + 1))) + return FALSE; if ((p = strchr((char*) *ServerHostname, ']'))) { @@ -110,7 +111,8 @@ void freerdp_client_old_parse_hostname(char* str, char** ServerHostname, UINT32* else { /* Port number is cut off and used if exactly one : in the string */ - *ServerHostname = _strdup(str); + if (!(*ServerHostname = _strdup(str))) + return FALSE; if ((p = strchr((char*) *ServerHostname, ':')) && !strchr(p + 1, ':')) { @@ -118,6 +120,7 @@ void freerdp_client_old_parse_hostname(char* str, char** ServerHostname, UINT32* *ServerPort = atoi(p + 1); } } + return TRUE; } int freerdp_client_old_process_plugin(rdpSettings* settings, ADDIN_ARGV* args) @@ -183,7 +186,8 @@ int freerdp_client_old_process_plugin(rdpSettings* settings, ADDIN_ARGV* args) return 1; args_handled++; - settings->RemoteApplicationProgram = _strdup(args->argv[1]); + if (!(settings->RemoteApplicationProgram = _strdup(args->argv[1]))) + return -1; } else { @@ -211,8 +215,9 @@ int freerdp_client_old_command_line_pre_filter(void* context, int index, int arg return -1; } - freerdp_client_old_parse_hostname((char*) argv[index], - &settings->ServerHostname, &settings->ServerPort); + if (!freerdp_client_old_parse_hostname((char*) argv[index], + &settings->ServerHostname, &settings->ServerPort)) + return -1; return 2; } @@ -240,7 +245,14 @@ int freerdp_client_old_command_line_pre_filter(void* context, int index, int arg return -1; args = (ADDIN_ARGV*) malloc(sizeof(ADDIN_ARGV)); + if (!args) + return -1; args->argv = (char**) calloc(argc, sizeof(char*)); + if (!args->argv) + { + free(args); + return -1; + } args->argc = 1; if ((index < argc - 1) && strcmp("--data", argv[index + 1]) == 0) @@ -250,9 +262,14 @@ int freerdp_client_old_command_line_pre_filter(void* context, int index, int arg while ((index < argc) && (strcmp("--", argv[index]) != 0)) { - args_handled ++; + args_handled++; args->argc = 1; - args->argv[0] = _strdup(argv[t]); + if (!(args->argv[0] = _strdup(argv[t]))) + { + free(args->argv); + free(args); + return -1; + } for (j = 0, p = (char*) argv[index]; (j < 4) && (p != NULL); j++) { @@ -277,14 +294,31 @@ int freerdp_client_old_command_line_pre_filter(void* context, int index, int arg if (p != NULL) { length = (int) (p - a); - args->argv[j + 1] = (char*) malloc(length + 1); + if (!(args->argv[j + 1] = (char*) malloc(length + 1))) + { + for (; j >= 0; --j) + free(args->argv[j]); + + free(args->argv); + free(args); + return -1; + } CopyMemory(args->argv[j + 1], a, length); args->argv[j + 1][length] = '\0'; p++; } else { - args->argv[j + 1] = _strdup(a); + if (!(args->argv[j + 1] = _strdup(a))) + { + for (; j >= 0; --j) + free(args->argv[j]); + + free(args->argv); + free(args); + return -1; + + } } args->argc++; @@ -306,7 +340,12 @@ int freerdp_client_old_command_line_pre_filter(void* context, int index, int arg { if (settings) { - args->argv[0] = _strdup(argv[t]); + if (!(args->argv[0] = _strdup(argv[t]))) + { + free(args->argv); + free(args); + return -1; + } args_handled = freerdp_client_old_process_plugin(settings, args); free (args->argv[0]); } @@ -459,8 +498,9 @@ int freerdp_client_parse_old_command_line_arguments(int argc, char** argv, rdpSe } CommandLineSwitchCase(arg, "c") { - settings->ShellWorkingDirectory = _strdup(arg->Value); WLog_WARN(TAG, "-c %s -> /shell-dir:%s", arg->Value, arg->Value); + if (!(settings->ShellWorkingDirectory = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; } CommandLineSwitchCase(arg, "D") { @@ -469,12 +509,14 @@ int freerdp_client_parse_old_command_line_arguments(int argc, char** argv, rdpSe } CommandLineSwitchCase(arg, "T") { - settings->WindowTitle = _strdup(arg->Value); + if (!(settings->WindowTitle = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; WLog_WARN(TAG, "-T %s -> /title:%s", arg->Value, arg->Value); } CommandLineSwitchCase(arg, "d") { - settings->Domain = _strdup(arg->Value); + if (!(settings->Domain = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; WLog_WARN(TAG, "-d %s -> /d:%s", arg->Value, arg->Value); } CommandLineSwitchCase(arg, "f") @@ -484,7 +526,8 @@ int freerdp_client_parse_old_command_line_arguments(int argc, char** argv, rdpSe } CommandLineSwitchCase(arg, "g") { - str = _strdup(arg->Value); + if (!(str = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; p = strchr(str, 'x'); @@ -511,7 +554,8 @@ int freerdp_client_parse_old_command_line_arguments(int argc, char** argv, rdpSe } CommandLineSwitchCase(arg, "n") { - settings->ClientHostname = _strdup(arg->Value); + if (!(settings->ClientHostname = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; WLog_WARN(TAG, "-n -> /client-hostname:%s", arg->Value); } CommandLineSwitchCase(arg, "o") @@ -521,14 +565,16 @@ int freerdp_client_parse_old_command_line_arguments(int argc, char** argv, rdpSe } CommandLineSwitchCase(arg, "p") { - settings->Password = _strdup(arg->Value); + if (!(settings->Password = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; WLog_WARN(TAG, "-p ****** -> /p:******"); /* Hide the value from 'ps'. */ FillMemory(arg->Value, strlen(arg->Value), '*'); } CommandLineSwitchCase(arg, "s") { - settings->AlternateShell = _strdup(arg->Value); + if (!(settings->AlternateShell = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; WLog_WARN(TAG, "-s %s -> /shell:%s", arg->Value, arg->Value); } CommandLineSwitchCase(arg, "t") @@ -538,7 +584,8 @@ int freerdp_client_parse_old_command_line_arguments(int argc, char** argv, rdpSe } CommandLineSwitchCase(arg, "u") { - settings->Username = _strdup(arg->Value); + if (!(settings->Username = _strdup(arg->Value))) + return COMMAND_LINE_ERROR_MEMORY; WLog_WARN(TAG, "-u %s -> /u:%s", arg->Value, arg->Value); } CommandLineSwitchCase(arg, "x") diff --git a/client/common/file.c b/client/common/file.c index 7ac48022d..f4b23fa02 100644 --- a/client/common/file.c +++ b/client/common/file.c @@ -52,9 +52,16 @@ static WCHAR CR_LF_STR_W[] = { '\r', '\n', '\0' }; #define INVALID_INTEGER_VALUE 0xFFFFFFFF -BOOL freerdp_client_rdp_file_set_integer(rdpFile* file, const char* name, int value, int index) +/* + * Set an integer in a rdpFile + * + * @return 0 if a standard name was set, 1 for a non-standard name, -1 on error + * + */ + +static int freerdp_client_rdp_file_set_integer(rdpFile* file, const char* name, int value, int index) { - BOOL bStandard = TRUE; + int standard = 1; #ifdef DEBUG_CLIENT_FILE WLog_DBG(TAG, "%s:i:%d", name, value); @@ -189,122 +196,161 @@ BOOL freerdp_client_rdp_file_set_integer(rdpFile* file, const char* name, int va else if (_stricmp(name, "rdgiskdcproxy") == 0) file->RdgIsKdcProxy = value; else - bStandard = FALSE; + standard = 1; if (index >= 0) { file->lines[index].name = _strdup(name); + if (!file->lines[index].name) + return -1; file->lines[index].iValue = (DWORD) value; file->lines[index].flags = RDP_FILE_LINE_FLAG_FORMATTED; file->lines[index].flags |= RDP_FILE_LINE_FLAG_TYPE_INTEGER; - if (bStandard) + if (standard) file->lines[index].flags |= RDP_FILE_LINE_FLAG_STANDARD; file->lines[index].valueLength = 0; } - return bStandard; + return standard; } -void freerdp_client_parse_rdp_file_integer_unicode(rdpFile* file, WCHAR* name, WCHAR* value, int index) +static BOOL freerdp_client_parse_rdp_file_integer_unicode(rdpFile* file, WCHAR* name, WCHAR* value, int index) { int length; int ivalue; char* nameA; char* valueA; + BOOL ret = TRUE; length = (int) _wcslen(name); nameA = (char*) malloc(length + 1); + if (!nameA) + return FALSE; WideCharToMultiByte(CP_UTF8, 0, name, length, nameA, length, NULL, NULL); nameA[length] = '\0'; length = (int) _wcslen(value); valueA = (char*) malloc(length + 1); + if (!valueA) + { + free(nameA); + return FALSE; + } WideCharToMultiByte(CP_UTF8, 0, value, length, valueA, length, NULL, NULL); valueA[length] = '\0'; ivalue = atoi(valueA); - freerdp_client_rdp_file_set_integer(file, nameA, ivalue, index); + if (freerdp_client_rdp_file_set_integer(file, nameA, ivalue, index) < 0) + ret = FALSE; free(nameA); free(valueA); + return ret; } -void freerdp_client_parse_rdp_file_integer_ascii(rdpFile* file, const char* name, const char* value, int index) +static BOOL freerdp_client_parse_rdp_file_integer_ascii(rdpFile* file, const char* name, const char* value, int index) { int ivalue = atoi(value); - freerdp_client_rdp_file_set_integer(file, name, ivalue, index); + if (freerdp_client_rdp_file_set_integer(file, name, ivalue, index) < 0) + return FALSE; + return TRUE; } -BOOL freerdp_client_rdp_file_set_string(rdpFile* file, const char* name, const char* value, int index) +/** + * + * @param file rdpFile + * @param name name of the string + * @param value value of the string to set + * @param index line index of the rdpFile + * @return 0 on success, 1 if the key wasn't found (not a standard key), -1 on error + */ + +static int freerdp_client_rdp_file_set_string(rdpFile* file, const char* name, const char* value, int index) { - BOOL bStandard = TRUE; + int standard = 0; + LPSTR *tmp = NULL; #ifdef DEBUG_CLIENT_FILE WLog_DBG(TAG, "%s:s:%s", name, value); #endif + if (!file) + return -1; + if (_stricmp(name, "username") == 0) - file->Username = _strdup(value); + tmp = &file->Username; else if (_stricmp(name, "domain") == 0) - file->Domain = _strdup(value); + tmp = &file->Domain; else if (_stricmp(name, "full address") == 0) - file->FullAddress = _strdup(value); + tmp = &file->FullAddress; else if (_stricmp(name, "alternate full address") == 0) - file->AlternateFullAddress = _strdup(value); + tmp = &file->AlternateFullAddress; else if (_stricmp(name, "usbdevicestoredirect") == 0) - file->UsbDevicesToRedirect = _strdup(value); + tmp = &file->UsbDevicesToRedirect; else if (_stricmp(name, "loadbalanceinfo") == 0) - file->LoadBalanceInfo = _strdup(value); + tmp = &file->LoadBalanceInfo; else if (_stricmp(name, "remoteapplicationname") == 0) - file->RemoteApplicationName = _strdup(value); + tmp = &file->RemoteApplicationName; else if (_stricmp(name, "remoteapplicationicon") == 0) - file->RemoteApplicationIcon = _strdup(value); + tmp = &file->RemoteApplicationIcon; else if (_stricmp(name, "remoteapplicationprogram") == 0) - file->RemoteApplicationProgram = _strdup(value); + tmp = &file->RemoteApplicationProgram; else if (_stricmp(name, "remoteapplicationfile") == 0) - file->RemoteApplicationFile = _strdup(value); + tmp = &file->RemoteApplicationFile; else if (_stricmp(name, "remoteapplicationguid") == 0) - file->RemoteApplicationGuid = _strdup(value); + tmp = &file->RemoteApplicationGuid; else if (_stricmp(name, "remoteapplicationcmdline") == 0) - file->RemoteApplicationCmdLine = _strdup(value); + tmp = &file->RemoteApplicationCmdLine; else if (_stricmp(name, "alternate shell") == 0) - file->AlternateShell = _strdup(value); + tmp = &file->AlternateShell; else if (_stricmp(name, "shell working directory") == 0) - file->ShellWorkingDirectory = _strdup(value); + tmp = &file->ShellWorkingDirectory; else if (_stricmp(name, "gatewayhostname") == 0) - file->GatewayHostname = _strdup(value); + tmp = &file->GatewayHostname; else if (_stricmp(name, "kdcproxyname") == 0) - file->KdcProxyName = _strdup(value); + tmp = &file->KdcProxyName; else if (_stricmp(name, "drivestoredirect") == 0) - file->DrivesToRedirect = _strdup(value); + tmp = &file->DrivesToRedirect; else if (_stricmp(name, "devicestoredirect") == 0) - file->DevicesToRedirect = _strdup(value); + tmp = &file->DevicesToRedirect; else if (_stricmp(name, "winposstr") == 0) - file->WinPosStr = _strdup(value); + tmp = &file->WinPosStr; else - bStandard = FALSE; + standard = 1; + + if (tmp && !(*tmp = _strdup(value))) + return -1; if (index >= 0) { + if (!file->lines) + return -1; + file->lines[index].name = _strdup(name); file->lines[index].sValue = _strdup(value); + if (!file->lines[index].name || !file->lines[index].sValue) + { + free(file->lines[index].name); + free(file->lines[index].sValue); + return -1; + } file->lines[index].flags = RDP_FILE_LINE_FLAG_FORMATTED; file->lines[index].flags |= RDP_FILE_LINE_FLAG_TYPE_STRING; - if (bStandard) + if (standard == 0) file->lines[index].flags |= RDP_FILE_LINE_FLAG_STANDARD; file->lines[index].valueLength = 0; } - return bStandard; + return standard; } -void freerdp_client_add_option(rdpFile* file, char* option) +static BOOL freerdp_client_add_option(rdpFile* file, char* option) { while ((file->argc + 1) > file->argSize) { @@ -314,16 +360,19 @@ void freerdp_client_add_option(rdpFile* file, char* option) new_size = file->argSize * 2; new_argv = (char**) realloc(file->argv, new_size * sizeof(char*)); if (!new_argv) - return; + return FALSE; file->argv = new_argv; file->argSize = new_size; } file->argv[file->argc] = _strdup(option); + if (!file->argv[file->argc]) + return FALSE; (file->argc)++; + return TRUE; } -int freerdp_client_parse_rdp_file_add_line(rdpFile* file, char* line, int index) +static int freerdp_client_parse_rdp_file_add_line(rdpFile* file, char* line, int index) { if (index < 0) index = file->lineCount; @@ -343,72 +392,105 @@ int freerdp_client_parse_rdp_file_add_line(rdpFile* file, char* line, int index) ZeroMemory(&(file->lines[file->lineCount]), sizeof(rdpFileLine)); file->lines[file->lineCount].text = _strdup(line); + if (!file->lines[file->lineCount].text) + return -1; + file->lines[file->lineCount].index = index; (file->lineCount)++; return index; } -void freerdp_client_parse_rdp_file_add_line_unicode(rdpFile* file, WCHAR* line, int index) +static BOOL freerdp_client_parse_rdp_file_add_line_unicode(rdpFile* file, WCHAR* line, int index) { char* lineA = NULL; + BOOL ret = TRUE; ConvertFromUnicode(CP_UTF8, 0, line, -1, &lineA, 0, NULL, NULL); - freerdp_client_parse_rdp_file_add_line(file, lineA, index); + if (!lineA) + return FALSE; + + if (freerdp_client_parse_rdp_file_add_line(file, lineA, index) == -1) + ret = FALSE; free(lineA); + return ret; } -void freerdp_client_parse_rdp_file_add_line_ascii(rdpFile* file, char* line, int index) +static BOOL freerdp_client_parse_rdp_file_add_line_ascii(rdpFile* file, char* line, int index) { - freerdp_client_parse_rdp_file_add_line(file, line, index); + if (freerdp_client_parse_rdp_file_add_line(file, line, index) == -1) + return FALSE; + return TRUE; } -void freerdp_client_parse_rdp_file_string_unicode(rdpFile* file, WCHAR* name, WCHAR* value, int index) +static BOOL freerdp_client_parse_rdp_file_string_unicode(rdpFile* file, WCHAR* name, WCHAR* value, int index) { int length; char* nameA; char* valueA; + BOOL ret = TRUE; length = (int) _wcslen(name); nameA = (char*) malloc(length + 1); + if (!nameA) + return FALSE; WideCharToMultiByte(CP_UTF8, 0, name, length, nameA, length, NULL, NULL); nameA[length] = '\0'; length = (int) _wcslen(value); valueA = (char*) malloc(length + 1); + if (!valueA) + { + free(nameA); + return FALSE; + } WideCharToMultiByte(CP_UTF8, 0, value, length, valueA, length, NULL, NULL); valueA[length] = '\0'; - freerdp_client_rdp_file_set_string(file, nameA, valueA, index); + if (freerdp_client_rdp_file_set_string(file, nameA, valueA, index) == -1) + ret = FALSE; free(nameA); free(valueA); + return ret; } -void freerdp_client_parse_rdp_file_string_ascii(rdpFile* file, char* name, char* value, int index) +static BOOL freerdp_client_parse_rdp_file_string_ascii(rdpFile* file, char* name, char* value, int index) { + BOOL ret = TRUE; char* valueA = _strdup(value); - freerdp_client_rdp_file_set_string(file, name, valueA, index); + if (!valueA) + return FALSE; + + if (freerdp_client_rdp_file_set_string(file, name, valueA, index) == -1) + ret = FALSE; + free(valueA); + return ret; } -void freerdp_client_parse_rdp_file_option_unicode(rdpFile* file, WCHAR* option, int index) +static BOOL freerdp_client_parse_rdp_file_option_unicode(rdpFile* file, WCHAR* option, int index) { char* optionA = NULL; + BOOL ret; ConvertFromUnicode(CP_UTF8, 0, option, -1, &optionA, 0, NULL, NULL); - freerdp_client_add_option(file, optionA); + if (!optionA) + return FALSE; + ret = freerdp_client_add_option(file, optionA); free(optionA); + + return ret; } -void freerdp_client_parse_rdp_file_option_ascii(rdpFile* file, char* option, int index) +static BOOL freerdp_client_parse_rdp_file_option_ascii(rdpFile* file, char* option, int index) { - freerdp_client_add_option(file, option); + return freerdp_client_add_option(file, option); } -BOOL freerdp_client_parse_rdp_file_buffer_ascii(rdpFile* file, const BYTE* buffer, size_t size) +static BOOL freerdp_client_parse_rdp_file_buffer_ascii(rdpFile* file, const BYTE* buffer, size_t size) { int index; int length; @@ -431,11 +513,14 @@ BOOL freerdp_client_parse_rdp_file_buffer_ascii(rdpFile* file, const BYTE* buffe beg = line; end = &line[length - 1]; - freerdp_client_parse_rdp_file_add_line_ascii(file, line, index); + if (!freerdp_client_parse_rdp_file_add_line_ascii(file, line, index)) + return FALSE; if (beg[0] == '/') { - freerdp_client_parse_rdp_file_option_ascii(file, line, index); + if (!freerdp_client_parse_rdp_file_option_ascii(file, line, index)) + return FALSE; + goto next_line; /* FreeRDP option */ } @@ -462,12 +547,14 @@ BOOL freerdp_client_parse_rdp_file_buffer_ascii(rdpFile* file, const BYTE* buffe if (*type == 'i') { /* integer type */ - freerdp_client_parse_rdp_file_integer_ascii(file, name, value, index); + if (!freerdp_client_parse_rdp_file_integer_ascii(file, name, value, index)) + return FALSE; } else if (*type == 's') { /* string type */ - freerdp_client_parse_rdp_file_string_ascii(file, name, value, index); + if (!freerdp_client_parse_rdp_file_string_ascii(file, name, value, index)) + return FALSE; } else if (*type == 'b') { @@ -483,7 +570,7 @@ next_line: return TRUE; } -BOOL freerdp_client_parse_rdp_file_buffer_unicode(rdpFile* file, const BYTE* buffer, size_t size) +static BOOL freerdp_client_parse_rdp_file_buffer_unicode(rdpFile* file, const BYTE* buffer, size_t size) { int index; int length; @@ -506,7 +593,8 @@ BOOL freerdp_client_parse_rdp_file_buffer_unicode(rdpFile* file, const BYTE* buf beg = line; end = &line[length - 1]; - freerdp_client_parse_rdp_file_add_line_unicode(file, line, index); + if (!freerdp_client_parse_rdp_file_add_line_unicode(file, line, index)) + return FALSE; if (beg[0] == '/') { @@ -538,12 +626,14 @@ BOOL freerdp_client_parse_rdp_file_buffer_unicode(rdpFile* file, const BYTE* buf if (*type == 'i') { /* integer type */ - freerdp_client_parse_rdp_file_integer_unicode(file, name, value, index); + if (!freerdp_client_parse_rdp_file_integer_unicode(file, name, value, index)) + return FALSE; } else if (*type == 's') { /* string type */ - freerdp_client_parse_rdp_file_string_unicode(file, name, value, index); + if (!freerdp_client_parse_rdp_file_string_unicode(file, name, value, index)) + return FALSE; } else if (*type == 'b') { @@ -594,6 +684,11 @@ BOOL freerdp_client_parse_rdp_file(rdpFile* file, const char* name) } buffer = (BYTE*) malloc(file_size + 2); + if (!buffer) + { + fclose(fp); + return FALSE; + } read_size = fread(buffer, file_size, 1, fp); if (!read_size) @@ -606,7 +701,6 @@ BOOL freerdp_client_parse_rdp_file(rdpFile* file, const char* name) if (read_size < 1) { free(buffer); - buffer = NULL; return FALSE; } @@ -623,7 +717,9 @@ BOOL freerdp_client_parse_rdp_file(rdpFile* file, const char* name) #define WRITE_ALL_SETTINGS TRUE #define SETTING_MODIFIED(_settings, _field) (WRITE_ALL_SETTINGS || _settings->SettingsModified[FreeRDP_##_field]) #define SETTING_MODIFIED_SET(_target, _settings, _field) if SETTING_MODIFIED(_settings, _field) _target = _settings->_field -#define SETTING_MODIFIED_SET_STRING(_target, _settings, _field) if SETTING_MODIFIED(_settings, _field) _target = _strdup(_settings->_field) +#define SETTING_MODIFIED_SET_STRING(_target, _settings, _field) do { if SETTING_MODIFIED(_settings, _field) _target = _strdup(_settings->_field); \ + if (!_target) return FALSE; \ + } while (0) BOOL freerdp_client_populate_rdp_file_from_settings(rdpFile* file, const rdpSettings* settings) { @@ -704,17 +800,28 @@ BOOL freerdp_client_write_rdp_file(const rdpFile* file, const char* name, BOOL u ConvertToUnicode(CP_UTF8, 0, buffer, length, &unicodestr, 0); /* Write multi-byte header */ - fwrite(BOM_UTF16_LE, sizeof(BYTE), 2, fp); - fwrite(unicodestr, 2, length, fp); + if (fwrite(BOM_UTF16_LE, sizeof(BYTE), 2, fp) != 2 || + fwrite(unicodestr, 2, length, fp) != length) + { + free(buffer); + free(unicodestr); + fclose(fp); + return FALSE; + } free(unicodestr); } else { - fwrite(buffer, 1, length, fp); + if (fwrite(buffer, 1, length, fp) != length) + { + free(buffer); + fclose(fp); + return FALSE; + } } - status = fflush(fp); + fflush(fp); status = fclose(fp); } @@ -763,18 +870,26 @@ size_t freerdp_client_write_rdp_file_buffer(const rdpFile* file, char* buffer, s BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* settings) { if (~((size_t) file->Domain)) - freerdp_set_param_string(settings, FreeRDP_Domain, file->Domain); + { + if (freerdp_set_param_string(settings, FreeRDP_Domain, file->Domain) != 0) + return FALSE; + } if (~((size_t) file->Username)) { char* user = NULL; char* domain = NULL; - freerdp_parse_username(file->Username, &user, &domain); - freerdp_set_param_string(settings, FreeRDP_Username, user); + if (freerdp_parse_username(file->Username, &user, &domain) != 0) + return FALSE; + if (freerdp_set_param_string(settings, FreeRDP_Username, user) != 0) + return FALSE; if (domain) - freerdp_set_param_string(settings, FreeRDP_Domain, domain); + { + if (freerdp_set_param_string(settings, FreeRDP_Domain, domain) != 0) + return FALSE; + } free(user); free(domain); @@ -785,9 +900,11 @@ BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* int port = -1; char* host = NULL; - freerdp_parse_hostname(file->FullAddress, &host, &port); + if (freerdp_parse_hostname(file->FullAddress, &host, &port) != 0) + return FALSE; - freerdp_set_param_string(settings, FreeRDP_ServerHostname, host); + if (freerdp_set_param_string(settings, FreeRDP_ServerHostname, host) != 0) + return FALSE; if (port > 0) freerdp_set_param_uint32(settings, FreeRDP_ServerPort, (UINT32) port); @@ -813,9 +930,15 @@ BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* if (~file->EnableCredSSPSupport) freerdp_set_param_bool(settings, FreeRDP_NlaSecurity, file->EnableCredSSPSupport); if (~((size_t) file->AlternateShell)) - freerdp_set_param_string(settings, FreeRDP_AlternateShell, file->AlternateShell); + { + if(freerdp_set_param_string(settings, FreeRDP_AlternateShell, file->AlternateShell) != 0) + return FALSE; + } if (~((size_t) file->ShellWorkingDirectory)) - freerdp_set_param_string(settings, FreeRDP_ShellWorkingDirectory, file->ShellWorkingDirectory); + { + if (freerdp_set_param_string(settings, FreeRDP_ShellWorkingDirectory, file->ShellWorkingDirectory) != 0) + return FALSE; + } if (~file->ScreenModeId) { @@ -845,6 +968,8 @@ BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* if (~((size_t) file->LoadBalanceInfo)) { settings->LoadBalanceInfo = (BYTE*) _strdup(file->LoadBalanceInfo); + if (!settings->LoadBalanceInfo) + return FALSE; settings->LoadBalanceInfoLength = (int) strlen((char*) settings->LoadBalanceInfo); } @@ -897,9 +1022,11 @@ BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* int port = -1; char* host = NULL; - freerdp_parse_hostname(file->GatewayHostname, &host, &port); + if (freerdp_parse_hostname(file->GatewayHostname, &host, &port) != 0) + return FALSE; - freerdp_set_param_string(settings, FreeRDP_GatewayHostname, host); + if (freerdp_set_param_string(settings, FreeRDP_GatewayHostname, host) != 0) + return FALSE; if (port > 0) freerdp_set_param_uint32(settings, FreeRDP_GatewayPort, (UINT32) port); @@ -916,15 +1043,30 @@ BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* if (~file->RemoteApplicationMode) freerdp_set_param_bool(settings, FreeRDP_RemoteApplicationMode, file->RemoteApplicationMode); if (~((size_t) file->RemoteApplicationProgram)) - freerdp_set_param_string(settings, FreeRDP_RemoteApplicationProgram, file->RemoteApplicationProgram); + { + if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationProgram, file->RemoteApplicationProgram) != 0) + return FALSE; + } if (~((size_t) file->RemoteApplicationName)) - freerdp_set_param_string(settings, FreeRDP_RemoteApplicationName, file->RemoteApplicationName); + { + if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationName, file->RemoteApplicationName) != 0) + return FALSE; + } if (~((size_t) file->RemoteApplicationIcon)) - freerdp_set_param_string(settings, FreeRDP_RemoteApplicationIcon, file->RemoteApplicationIcon); + { + if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationIcon, file->RemoteApplicationIcon) != 0) + return FALSE; + } if (~((size_t) file->RemoteApplicationFile)) - freerdp_set_param_string(settings, FreeRDP_RemoteApplicationGuid, file->RemoteApplicationGuid); + { + if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationGuid, file->RemoteApplicationGuid) != 0) + return FALSE; + } if (~((size_t) file->RemoteApplicationCmdLine)) - freerdp_set_param_string(settings, FreeRDP_RemoteApplicationCmdLine, file->RemoteApplicationCmdLine); + { + if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationCmdLine, file->RemoteApplicationCmdLine) != 0) + return FALSE; + } if (~file->SpanMonitors) freerdp_set_param_bool(settings, FreeRDP_SpanMonitors, file->SpanMonitors); @@ -1036,14 +1178,15 @@ BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* char* ConnectionFile = settings->ConnectionFile; settings->ConnectionFile = NULL; - freerdp_client_settings_parse_command_line(settings, file->argc, file->argv, FALSE); + if (freerdp_client_settings_parse_command_line(settings, file->argc, file->argv, FALSE) < 0) + return FALSE; settings->ConnectionFile = ConnectionFile; } return TRUE; } -rdpFileLine* freerdp_client_rdp_file_find_line_index(rdpFile* file, int index) +static rdpFileLine* freerdp_client_rdp_file_find_line_index(rdpFile* file, int index) { rdpFileLine* line; @@ -1052,7 +1195,7 @@ rdpFileLine* freerdp_client_rdp_file_find_line_index(rdpFile* file, int index) return line; } -rdpFileLine* freerdp_client_rdp_file_find_line_by_name(rdpFile* file, const char* name) +static rdpFileLine* freerdp_client_rdp_file_find_line_by_name(rdpFile* file, const char* name) { int index; BOOL bFound = FALSE; @@ -1075,6 +1218,14 @@ rdpFileLine* freerdp_client_rdp_file_find_line_by_name(rdpFile* file, const char return (bFound) ? line : NULL; } +/** + * Set a string option to a rdpFile + * @param file rdpFile + * @param name name of the option + * @param value value of the option + * @return 0 on success + */ + int freerdp_client_rdp_file_set_string_option(rdpFile* file, const char* name, const char* value) { int index; @@ -1082,17 +1233,20 @@ int freerdp_client_rdp_file_set_string_option(rdpFile* file, const char* name, c char* text; rdpFileLine* line; - line = freerdp_client_rdp_file_find_line_by_name(file, name); - length = _scprintf("%s:s:%s", name, value); text = (char*) malloc(length + 1); + if (!text) + return -1; sprintf_s(text, length + 1, "%s:s:%s", name, value ? value : ""); text[length] = '\0'; + line = freerdp_client_rdp_file_find_line_by_name(file, name); if (line) { free(line->sValue); line->sValue = _strdup(value); + if (!line->sValue) + goto out_fail; free(line->text); line->text = text; @@ -1100,14 +1254,24 @@ int freerdp_client_rdp_file_set_string_option(rdpFile* file, const char* name, c else { index = freerdp_client_parse_rdp_file_add_line(file, text, -1); - line = freerdp_client_rdp_file_find_line_index(file, index); + if (index == -1) + goto out_fail; - freerdp_client_rdp_file_set_string(file, name, value, index); + if (!(line = freerdp_client_rdp_file_find_line_index(file, index))) + goto out_fail; + + if (freerdp_client_rdp_file_set_string(file, name, value, index) == -1) + goto out_fail; free(text); } return 0; + +out_fail: + free(text); + return -1; + } const char* freerdp_client_rdp_file_get_string_option(rdpFile* file, const char* name) @@ -1149,9 +1313,18 @@ int freerdp_client_rdp_file_set_integer_option(rdpFile* file, const char* name, else { index = freerdp_client_parse_rdp_file_add_line(file, text, -1); + if (index < 0) + { + free(text); + return -1; + } line = freerdp_client_rdp_file_find_line_index(file, index); - freerdp_client_rdp_file_set_integer(file, (char*) name, value, index); + if (freerdp_client_rdp_file_set_integer(file, (char*) name, value, index) < 0) + { + free(text); + return -1; + } free(text); } @@ -1174,7 +1347,7 @@ int freerdp_client_rdp_file_get_integer_option(rdpFile* file, const char* name) return line->iValue; } -void freerdp_client_file_string_check_free(LPSTR str) +static void freerdp_client_file_string_check_free(LPSTR str) { if (~((size_t) str)) free(str); @@ -1193,12 +1366,30 @@ rdpFile* freerdp_client_rdp_file_new() file->lineCount = 0; file->lineSize = 32; file->lines = (rdpFileLine*) malloc(file->lineSize * sizeof(rdpFileLine)); + if (!file->lines) + { + free(file); + return NULL; + } + file->argc = 0; file->argSize = 32; file->argv = (char**) malloc(file->argSize * sizeof(char*)); + if (!file->argv) + { + free(file->lines); + free(file); + return NULL; + } - freerdp_client_add_option(file, "freerdp"); + if (!freerdp_client_add_option(file, "freerdp")) + { + free(file->argv); + free(file->lines); + free(file); + return NULL; + } } return file; diff --git a/client/common/test/TestClientRdpFile.c b/client/common/test/TestClientRdpFile.c index 8d5c8fb9a..ce15e6942 100644 --- a/client/common/test/TestClientRdpFile.c +++ b/client/common/test/TestClientRdpFile.c @@ -271,6 +271,11 @@ int TestClientRdpFile(int argc, char* argv[]) /* Unicode */ file = freerdp_client_rdp_file_new(); + if (!file) + { + printf("rdp_file_new failed\n"); + return -1; + } freerdp_client_parse_rdp_file_buffer(file, testRdpFileUTF16, sizeof(testRdpFileUTF16)); if (file->UseMultiMon != 0) @@ -331,7 +336,12 @@ int TestClientRdpFile(int argc, char* argv[]) } iValue = freerdp_client_rdp_file_get_integer_option(file, "vendor integer"); - freerdp_client_rdp_file_set_integer_option(file, "vendor integer", 456); + if (freerdp_client_rdp_file_set_integer_option(file, "vendor integer", 456) == -1) + { + printf("failed to set integer: vendor integer"); + return -1; + } + iValue = freerdp_client_rdp_file_get_integer_option(file, "vendor integer"); sValue = (char*) freerdp_client_rdp_file_get_string_option(file, "vendor string"); @@ -339,7 +349,11 @@ int TestClientRdpFile(int argc, char* argv[]) sValue = (char*) freerdp_client_rdp_file_get_string_option(file, "vendor string"); freerdp_client_rdp_file_set_string_option(file, "fruits", "banana,oranges"); - freerdp_client_rdp_file_set_integer_option(file, "numbers", 123456789); + if (freerdp_client_rdp_file_set_integer_option(file, "numbers", 123456789) == -1) + { + printf("failed to set integer: numbers"); + return -1; + } for (index = 0; index < file->lineCount; index++) { diff --git a/client/iOS/FreeRDP/ios_freerdp.m b/client/iOS/FreeRDP/ios_freerdp.m index d309fa63d..f4ef32aab 100644 --- a/client/iOS/FreeRDP/ios_freerdp.m +++ b/client/iOS/FreeRDP/ios_freerdp.m @@ -11,6 +11,7 @@ #import #import #import +#import #import "ios_freerdp.h" #import "ios_freerdp_ui.h" @@ -19,7 +20,6 @@ #import "RDPSession.h" #import "Utils.h" - #pragma mark Connection helpers static BOOL ios_pre_connect(freerdp* instance) @@ -279,6 +279,8 @@ void ios_context_free(freerdp* instance, rdpContext* context) freerdp* ios_freerdp_new() { freerdp* inst = freerdp_new(); + if (!inst) + return NULL; inst->PreConnect = ios_pre_connect; inst->PostConnect = ios_post_connect; @@ -297,6 +299,14 @@ freerdp* ios_freerdp_new() free(inst->settings->ConfigPath); inst->settings->HomePath = strdup([home_path UTF8String]); inst->settings->ConfigPath = strdup([[home_path stringByAppendingPathComponent:@".freerdp"] UTF8String]); + if (!inst->settings->HomePath || !inst->settings->ConfigPath) + { + free(inst->settings->HomePath); + free(inst->settings->ConfigPath); + freerdp_context_free(inst); + freerdp_free(inst); + return NULL; + } return inst; } diff --git a/client/iOS/FreeRDP/ios_freerdp_ui.m b/client/iOS/FreeRDP/ios_freerdp_ui.m index 2ecdbbf8b..191b25ec2 100644 --- a/client/iOS/FreeRDP/ios_freerdp_ui.m +++ b/client/iOS/FreeRDP/ios_freerdp_ui.m @@ -51,6 +51,14 @@ BOOL ios_ui_authenticate(freerdp * instance, char** username, char** password, c *username = strdup([[params objectForKey:@"username"] UTF8String]); *password = strdup([[params objectForKey:@"password"] UTF8String]); *domain = strdup([[params objectForKey:@"domain"] UTF8String]); + + if (!(*username) || !(*password) || !(*domain)) + { + free(*username); + free(*password); + free(*domain); + return FALSE; + } return TRUE; } diff --git a/client/iOS/Models/RDPSession.m b/client/iOS/Models/RDPSession.m index d2ff9e361..124dca818 100644 --- a/client/iOS/Models/RDPSession.m +++ b/client/iOS/Models/RDPSession.m @@ -75,31 +75,46 @@ NSString* TSXSessionDidFailToConnectNotification = @"TSXSessionDidFailToConnect" settings->ConsoleSession = 1; // connection info - settings->ServerHostname = strdup([_params UTF8StringForKey:@"hostname"]); + if (!(settings->ServerHostname = strdup([_params UTF8StringForKey:@"hostname"]))) + goto out_free; // String settings if ([[_params StringForKey:@"username"] length]) + { settings->Username = strdup([_params UTF8StringForKey:@"username"]); - + if (!settings->Username) + goto out_free; + } + if ([[_params StringForKey:@"password"] length]) + { settings->Password = strdup([_params UTF8StringForKey:@"password"]); - + if (!settings->Password) + goto out_free; + } + if ([[_params StringForKey:@"domain"] length]) + { settings->Domain = strdup([_params UTF8StringForKey:@"domain"]); - + if (!settings->Domain) + goto out_free; + } + settings->ShellWorkingDirectory = strdup([_params UTF8StringForKey:@"working_directory"]); settings->AlternateShell = strdup([_params UTF8StringForKey:@"remote_program"]); - - // RemoteFX + if (!settings->ShellWorkingDirectory || !settings->AlternateShell) + goto out_free; + +// RemoteFX if ([_params boolForKey:@"perf_remotefx" with3GEnabled:connected_via_3g]) { settings->RemoteFxCodec = TRUE; settings->FastPathOutput = TRUE; settings->ColorDepth = 32; settings->LargePointerFlag = TRUE; - settings->FrameMarkerCommandEnabled = TRUE; - settings->FrameAcknowledge = 10; + settings->FrameMarkerCommandEnabled = TRUE; + settings->FrameAcknowledge = 10; } else { @@ -176,6 +191,12 @@ NSString* TSXSessionDidFailToConnectNotification = @"TSXSessionDidFailToConnect" settings->GatewayUsageMethod = TSC_PROXY_MODE_DIRECT; settings->GatewayEnabled = TRUE; settings->GatewayUseSameCredentials = FALSE; + + if (!settings->GatewayHostname || !settings->GatewayUsername || !settings->GatewayPassword + || !settings->GatewayDomain) + { + goto out_free; + } } // Remote keyboard layout @@ -187,6 +208,10 @@ NSString* TSXSessionDidFailToConnectNotification = @"TSXSessionDidFailToConnect" [self mfi]->session = self; return self; + +out_free: + [self release]; + return nil; } - (void)dealloc diff --git a/cmake/ConfigOptionsAndroid.cmake b/cmake/ConfigOptionsAndroid.cmake index 6bf171869..780b4e18b 100644 --- a/cmake/ConfigOptionsAndroid.cmake +++ b/cmake/ConfigOptionsAndroid.cmake @@ -28,6 +28,6 @@ option(ANDROID_BUILD_JAVA_DEBUG "Create a android debug package" ${JAVA_DEBUG_DE set(ANDROID_APP_VERSION 3 CACHE STRING "Application version") set(ANDROID_APP_TARGET_SDK 21 CACHE STRING "Application target android SDK") -set(ANDROID_APP_MIN_SDK 9 CACHE STRING "Application minimum android SDK requirement") +set(ANDROID_APP_MIN_SDK 14 CACHE STRING "Application minimum android SDK requirement") set(ANDROID_APP_GOOGLE_TARGET_SDK "16" CACHE STRING "Application target google SDK") diff --git a/cmake/FindDevD.cmake b/cmake/FindDevD.cmake new file mode 100644 index 000000000..5c5b606f9 --- /dev/null +++ b/cmake/FindDevD.cmake @@ -0,0 +1,31 @@ +# Configure devd environment +# +# DEVD_FOUND - system has a devd +# DEVD_BIN_DIR - devd bin dir +# DEVD_SKT_DIR - devd socket dir +# +# Copyright (c) 2015 Rozhuk Ivan +# Redistribution and use is allowed according to the terms of the BSD license. +# + + +FIND_PATH( + DEVD_BIN_DIR + NAMES devd + PATHS /sbin /usr/sbin /usr/local/sbin +) + +FIND_PATH( + DEVD_SKT_DIR + NAMES devd.seqpacket.pipe devd.pipe + PATHS /var/run/ +) + + +if (DEVD_BIN_DIR) + set(DEVD_FOUND "YES") + message(STATUS "devd found") + if (NOT DEVD_SKT_DIR) + message(STATUS "devd not running!") + endif (NOT DEVD_SKT_DIR) +endif (DEVD_BIN_DIR) diff --git a/cmake/FindUUID.cmake b/cmake/FindUUID.cmake index 330e5caba..88083df9d 100644 --- a/cmake/FindUUID.cmake +++ b/cmake/FindUUID.cmake @@ -20,6 +20,7 @@ set(UUID_FOUND TRUE) else (UUID_LIBRARIES AND UUID_INCLUDE_DIRS) find_path(UUID_INCLUDE_DIR NAMES +uuid.h uuid/uuid.h PATHS ${UUID_DIR}/include @@ -85,26 +86,27 @@ $ENV{OSG_ROOT}/lib /opt/lib /usr/freeware/lib64 ) +if (NOT UUID_LIBRARY AND BSD) + set(UUID_LIBRARY "") +endif(NOT UUID_LIBRARY AND BSD) -set(UUID_INCLUDE_DIRS -${UUID_INCLUDE_DIR} -) -set(UUID_LIBRARIES -${UUID_LIBRARY} -) +set(UUID_INCLUDE_DIRS ${UUID_INCLUDE_DIR}) +set(UUID_LIBRARIES ${UUID_LIBRARY}) -if (UUID_INCLUDE_DIRS AND UUID_LIBRARIES) -set(UUID_FOUND TRUE) -endif (UUID_INCLUDE_DIRS AND UUID_LIBRARIES) +if (UUID_INCLUDE_DIRS) + if (BSD OR UUID_LIBRARIES) + set(UUID_FOUND TRUE) + endif (BSD OR UUID_LIBRARIES) +endif (UUID_INCLUDE_DIRS) if (UUID_FOUND) -if (NOT UUID_FIND_QUIETLY) -message(STATUS "Found UUID: ${UUID_LIBRARIES}") -endif (NOT UUID_FIND_QUIETLY) + if (NOT UUID_FIND_QUIETLY) + message(STATUS "Found UUID: ${UUID_LIBRARIES}") + endif (NOT UUID_FIND_QUIETLY) else (UUID_FOUND) -if (UUID_FIND_REQUIRED) -message(FATAL_ERROR "Could not find UUID") -endif (UUID_FIND_REQUIRED) + if (UUID_FIND_REQUIRED) + message(FATAL_ERROR "Could not find UUID") + endif (UUID_FIND_REQUIRED) endif (UUID_FOUND) # show the UUID_INCLUDE_DIRS and UUID_LIBRARIES variables only in the advanced view diff --git a/docs/README.android b/docs/README.android index d64bbd5df..32ee242c8 100644 --- a/docs/README.android +++ b/docs/README.android @@ -209,6 +209,6 @@ After that FreeRDP and the Android package need to be rebuilt to include the lat Android CMake related Variables ------------------------------- -ANDROID_APP_TARGET_SDK ... specifies the desired android target SDK, currently 11 -ANDROID_APP_MIN_SDK ... specifies the minimum android SDK version supported, currently 8 +ANDROID_APP_TARGET_SDK ... specifies the desired android target SDK, currently 21 +ANDROID_APP_MIN_SDK ... specifies the minimum android SDK version supported, currently 14 ANDROID_APP_GOOGLE_TARGET_SDK ... specifies the minimum google SDK requirement, currently 16 diff --git a/docs/README.ios b/docs/README.ios index e8e76d24d..c4f767e47 100644 --- a/docs/README.ios +++ b/docs/README.ios @@ -30,10 +30,8 @@ different install/build directory you specify it as first parameter: In the example above the output can then be found in /tmp/openssl. -The script uses oldest iOS/iPhoneSimulator SDK found on the build machine per default. If you need to build against a different SDK you can set USER_OS_SDK -and/or USER_SIM_SDK in the top of the build script to the SDK version you need. E.g.: - -USER_SIM_SDK="iPhoneSimulator6.0.sdk" +The script uses oldest iOS/iPhoneSimulator SDK found on the build machine per default. If it is required to build against a specific SDK version +the variable SDK_VERSION can be used to specify it. The minimum SDK version that should be used can be set with MIN_SDK_VERSION within the script. When the script is finished you will find libcrypto.a and libssl.at, both universal libraries containing all openssl/lib subfolder in the specified diff --git a/include/freerdp/codec/planar.h b/include/freerdp/codec/planar.h index 64b741d1b..781ae0807 100644 --- a/include/freerdp/codec/planar.h +++ b/include/freerdp/codec/planar.h @@ -104,7 +104,7 @@ struct _BITMAP_PLANAR_CONTEXT FREERDP_API int freerdp_split_color_planes(BYTE* data, UINT32 format, int width, int height, int scanline, BYTE* planes[4]); FREERDP_API BYTE* freerdp_bitmap_planar_compress_plane_rle(BYTE* plane, int width, int height, BYTE* outPlane, int* dstSize); FREERDP_API BYTE* freerdp_bitmap_planar_delta_encode_plane(BYTE* inPlane, int width, int height, BYTE* outPlane); -FREERDP_API int freerdp_bitmap_planar_delta_encode_planes(BYTE* inPlanes[4], int width, int height, BYTE* outPlanes[4]); +FREERDP_API BOOL freerdp_bitmap_planar_delta_encode_planes(BYTE* inPlanes[4], int width, int height, BYTE* outPlanes[4]); FREERDP_API BYTE* freerdp_bitmap_compress_planar(BITMAP_PLANAR_CONTEXT* context, BYTE* data, UINT32 format, int width, int height, int scanline, BYTE* dstData, int* pDstSize); diff --git a/include/freerdp/codec/progressive.h b/include/freerdp/codec/progressive.h index 455126c4c..a2cc7ada7 100644 --- a/include/freerdp/codec/progressive.h +++ b/include/freerdp/codec/progressive.h @@ -46,10 +46,6 @@ typedef struct _PROGRESSIVE_CONTEXT PROGRESSIVE_CONTEXT; #define PROGRESSIVE_WBT_TILE_FIRST 0xCCC6 #define PROGRESSIVE_WBT_TILE_UPGRADE 0xCCC7 -#define PROGRESSIVE_BLOCKS_ALL 0x0001 -#define PROGRESSIVE_BLOCKS_REGION 0x0002 -#define PROGRESSIVE_BLOCKS_TILE 0x0004 - struct _RFX_COMPONENT_CODEC_QUANT { BYTE LL3; @@ -102,77 +98,6 @@ struct _PROGRESSIVE_BLOCK_CONTEXT }; typedef struct _PROGRESSIVE_BLOCK_CONTEXT PROGRESSIVE_BLOCK_CONTEXT; -struct _PROGRESSIVE_BLOCK_TILE_SIMPLE -{ - UINT16 blockType; - UINT32 blockLen; - - BYTE quantIdxY; - BYTE quantIdxCb; - BYTE quantIdxCr; - UINT16 xIdx; - UINT16 yIdx; - BYTE flags; - UINT16 yLen; - UINT16 cbLen; - UINT16 crLen; - UINT16 tailLen; - BYTE* yData; - BYTE* cbData; - BYTE* crData; - BYTE* tailData; -}; -typedef struct _PROGRESSIVE_BLOCK_TILE_SIMPLE PROGRESSIVE_BLOCK_TILE_SIMPLE; - -struct _PROGRESSIVE_BLOCK_TILE_FIRST -{ - UINT16 blockType; - UINT32 blockLen; - - BYTE quantIdxY; - BYTE quantIdxCb; - BYTE quantIdxCr; - UINT16 xIdx; - UINT16 yIdx; - BYTE flags; - BYTE quality; - UINT16 yLen; - UINT16 cbLen; - UINT16 crLen; - UINT16 tailLen; - BYTE* yData; - BYTE* cbData; - BYTE* crData; - BYTE* tailData; -}; -typedef struct _PROGRESSIVE_BLOCK_TILE_FIRST PROGRESSIVE_BLOCK_TILE_FIRST; - -struct _PROGRESSIVE_BLOCK_TILE_UPGRADE -{ - UINT16 blockType; - UINT32 blockLen; - - BYTE quantIdxY; - BYTE quantIdxCb; - BYTE quantIdxCr; - UINT16 xIdx; - UINT16 yIdx; - BYTE quality; - UINT16 ySrlLen; - UINT16 yRawLen; - UINT16 cbSrlLen; - UINT16 cbRawLen; - UINT16 crSrlLen; - UINT16 crRawLen; - BYTE* ySrlData; - BYTE* yRawData; - BYTE* cbSrlData; - BYTE* cbRawData; - BYTE* crSrlData; - BYTE* crRawData; -}; -typedef struct _PROGRESSIVE_BLOCK_TILE_UPGRADE PROGRESSIVE_BLOCK_TILE_UPGRADE; - struct _RFX_PROGRESSIVE_TILE { UINT16 blockType; @@ -285,7 +210,6 @@ struct _PROGRESSIVE_CONTEXT BOOL invert; - wLog* log; wBufferPool* bufferPool; UINT32 cRects; diff --git a/include/freerdp/crypto/certificate.h b/include/freerdp/crypto/certificate.h index 537d9210e..543014ec4 100644 --- a/include/freerdp/crypto/certificate.h +++ b/include/freerdp/crypto/certificate.h @@ -55,8 +55,8 @@ struct rdp_certificate_store #endif FREERDP_API rdpCertificateData* certificate_data_new( - char* hostname, UINT16 port, char*subject, - char*issuer, char* fingerprint); + char* hostname, UINT16 port, char* subject, + char* issuer, char* fingerprint); FREERDP_API void certificate_data_free( rdpCertificateData* certificate_data); FREERDP_API rdpCertificateStore* certificate_store_new( diff --git a/include/freerdp/gdi/16bpp.h b/include/freerdp/gdi/16bpp.h index afa10d2da..8193c86fe 100644 --- a/include/freerdp/gdi/16bpp.h +++ b/include/freerdp/gdi/16bpp.h @@ -24,7 +24,7 @@ #include #include -typedef int (*pLineTo_16bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); +typedef BOOL (*pLineTo_16bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); #ifdef __cplusplus extern "C" { @@ -32,10 +32,10 @@ typedef int (*pLineTo_16bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); FREERDP_API UINT16 gdi_get_color_16bpp(HGDI_DC hdc, GDI_COLOR color); -FREERDP_API int FillRect_16bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); -FREERDP_API int BitBlt_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop); -FREERDP_API int PatBlt_16bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop); -FREERDP_API int LineTo_16bpp(HGDI_DC hdc, int nXEnd, int nYEnd); +FREERDP_API BOOL FillRect_16bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); +FREERDP_API BOOL BitBlt_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop); +FREERDP_API BOOL PatBlt_16bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop); +FREERDP_API BOOL LineTo_16bpp(HGDI_DC hdc, int nXEnd, int nYEnd); #ifdef __cplusplus } diff --git a/include/freerdp/gdi/32bpp.h b/include/freerdp/gdi/32bpp.h index cb9139701..89a39863c 100644 --- a/include/freerdp/gdi/32bpp.h +++ b/include/freerdp/gdi/32bpp.h @@ -24,7 +24,7 @@ #include #include -typedef int (*pLineTo_32bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); +typedef BOOL (*pLineTo_32bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); #ifdef __cplusplus extern "C" { @@ -32,10 +32,10 @@ typedef int (*pLineTo_32bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); FREERDP_API UINT32 gdi_get_color_32bpp(HGDI_DC hdc, GDI_COLOR color); -FREERDP_API int FillRect_32bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); -FREERDP_API int BitBlt_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop); -FREERDP_API int PatBlt_32bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop); -FREERDP_API int LineTo_32bpp(HGDI_DC hdc, int nXEnd, int nYEnd); +FREERDP_API BOOL FillRect_32bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); +FREERDP_API BOOL BitBlt_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop); +FREERDP_API BOOL PatBlt_32bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop); +FREERDP_API BOOL LineTo_32bpp(HGDI_DC hdc, int nXEnd, int nYEnd); #ifdef __cplusplus } diff --git a/include/freerdp/gdi/8bpp.h b/include/freerdp/gdi/8bpp.h index b609eacd0..52f09bf87 100644 --- a/include/freerdp/gdi/8bpp.h +++ b/include/freerdp/gdi/8bpp.h @@ -24,7 +24,7 @@ #include #include -typedef int (*pLineTo_8bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); +typedef BOOL (*pLineTo_8bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); #ifdef __cplusplus extern "C" { @@ -32,10 +32,10 @@ typedef int (*pLineTo_8bpp)(HGDI_DC hdc, int nXEnd, int nYEnd); FREERDP_API BYTE gdi_get_color_8bpp(HGDI_DC hdc, GDI_COLOR color); -FREERDP_API int FillRect_8bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); -FREERDP_API int BitBlt_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop); -FREERDP_API int PatBlt_8bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop); -FREERDP_API int LineTo_8bpp(HGDI_DC hdc, int nXEnd, int nYEnd); +FREERDP_API BOOL FillRect_8bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); +FREERDP_API BOOL BitBlt_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop); +FREERDP_API BOOL PatBlt_8bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop); +FREERDP_API BOOL LineTo_8bpp(HGDI_DC hdc, int nXEnd, int nYEnd); #ifdef __cplusplus } diff --git a/include/freerdp/gdi/bitmap.h b/include/freerdp/gdi/bitmap.h index c34713c6c..42caf0b13 100644 --- a/include/freerdp/gdi/bitmap.h +++ b/include/freerdp/gdi/bitmap.h @@ -40,9 +40,9 @@ FREERDP_API void gdi_SetPixel_16bpp(HGDI_BITMAP hBmp, int X, int Y, UINT16 pixel FREERDP_API void gdi_SetPixel_32bpp(HGDI_BITMAP hBmp, int X, int Y, UINT32 pixel); FREERDP_API HGDI_BITMAP gdi_CreateBitmap(int nWidth, int nHeight, int cBitsPerPixel, BYTE* data); FREERDP_API HGDI_BITMAP gdi_CreateCompatibleBitmap(HGDI_DC hdc, int nWidth, int nHeight); -FREERDP_API int gdi_BitBlt(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop); +FREERDP_API BOOL gdi_BitBlt(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop); -typedef int (*p_BitBlt)(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop); +typedef BOOL (*p_BitBlt)(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop); #ifdef __cplusplus } diff --git a/include/freerdp/gdi/brush.h b/include/freerdp/gdi/brush.h index 5313664a8..6817c3949 100644 --- a/include/freerdp/gdi/brush.h +++ b/include/freerdp/gdi/brush.h @@ -30,12 +30,12 @@ FREERDP_API HGDI_BRUSH gdi_CreateSolidBrush(GDI_COLOR crColor); FREERDP_API HGDI_BRUSH gdi_CreatePatternBrush(HGDI_BITMAP hbmp); FREERDP_API HGDI_BRUSH gdi_CreateHatchBrush(HGDI_BITMAP hbmp); -FREERDP_API int gdi_PatBlt(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop); +FREERDP_API BOOL gdi_PatBlt(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop); #ifdef __cplusplus } #endif -typedef int (*p_PatBlt)(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop); +typedef BOOL (*p_PatBlt)(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop); #endif /* FREERDP_GDI_BRUSH_H */ diff --git a/include/freerdp/gdi/clipping.h b/include/freerdp/gdi/clipping.h index 75470f6e8..eb8dec39f 100644 --- a/include/freerdp/gdi/clipping.h +++ b/include/freerdp/gdi/clipping.h @@ -27,10 +27,10 @@ extern "C" { #endif -FREERDP_API int gdi_SetClipRgn(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight); +FREERDP_API BOOL gdi_SetClipRgn(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight); FREERDP_API HGDI_RGN gdi_GetClipRgn(HGDI_DC hdc); -FREERDP_API int gdi_SetNullClipRgn(HGDI_DC hdc); -FREERDP_API int gdi_ClipCoords(HGDI_DC hdc, int *x, int *y, int *w, int *h, int *srcx, int *srcy); +FREERDP_API BOOL gdi_SetNullClipRgn(HGDI_DC hdc); +FREERDP_API BOOL gdi_ClipCoords(HGDI_DC hdc, int *x, int *y, int *w, int *h, int *srcx, int *srcy); #ifdef __cplusplus } diff --git a/include/freerdp/gdi/dc.h b/include/freerdp/gdi/dc.h index 5c66903a6..ceca9d0b5 100644 --- a/include/freerdp/gdi/dc.h +++ b/include/freerdp/gdi/dc.h @@ -31,8 +31,8 @@ FREERDP_API HGDI_DC gdi_GetDC(void); FREERDP_API HGDI_DC gdi_CreateDC(UINT32 flags, int bpp); FREERDP_API HGDI_DC gdi_CreateCompatibleDC(HGDI_DC hdc); FREERDP_API HGDIOBJECT gdi_SelectObject(HGDI_DC hdc, HGDIOBJECT hgdiobject); -FREERDP_API int gdi_DeleteObject(HGDIOBJECT hgdiobject); -FREERDP_API int gdi_DeleteDC(HGDI_DC hdc); +FREERDP_API BOOL gdi_DeleteObject(HGDIOBJECT hgdiobject); +FREERDP_API BOOL gdi_DeleteDC(HGDI_DC hdc); #ifdef __cplusplus } diff --git a/include/freerdp/gdi/gdi.h b/include/freerdp/gdi/gdi.h index d640d973f..9736ba724 100644 --- a/include/freerdp/gdi/gdi.h +++ b/include/freerdp/gdi/gdi.h @@ -315,7 +315,7 @@ struct rdp_gdi extern "C" { #endif -FREERDP_API UINT32 gdi_rop3_code(BYTE code); +FREERDP_API DWORD gdi_rop3_code(BYTE code); FREERDP_API UINT32 gdi_get_pixel_format(UINT32 bitsPerPixel, BOOL vFlip); FREERDP_API BYTE* gdi_get_bitmap_pointer(HGDI_DC hdcBmp, int x, int y); FREERDP_API BYTE* gdi_get_brush_pointer(HGDI_DC hdcBrush, int x, int y); diff --git a/include/freerdp/gdi/line.h b/include/freerdp/gdi/line.h index 18014cfd5..daf8b8b59 100644 --- a/include/freerdp/gdi/line.h +++ b/include/freerdp/gdi/line.h @@ -27,16 +27,16 @@ extern "C" { #endif -FREERDP_API int gdi_LineTo(HGDI_DC hdc, int nXEnd, int nYEnd); -FREERDP_API int gdi_PolylineTo(HGDI_DC hdc, GDI_POINT *lppt, int cCount); -FREERDP_API int gdi_Polyline(HGDI_DC hdc, GDI_POINT *lppt, int cPoints); -FREERDP_API int gdi_PolyPolyline(HGDI_DC hdc, GDI_POINT *lppt, int *lpdwPolyPoints, int cCount); -FREERDP_API int gdi_MoveToEx(HGDI_DC hdc, int X, int Y, HGDI_POINT lpPoint); +FREERDP_API BOOL gdi_LineTo(HGDI_DC hdc, int nXEnd, int nYEnd); +FREERDP_API BOOL gdi_PolylineTo(HGDI_DC hdc, GDI_POINT *lppt, DWORD cCount); +FREERDP_API BOOL gdi_Polyline(HGDI_DC hdc, GDI_POINT *lppt, int cPoints); +FREERDP_API BOOL gdi_PolyPolyline(HGDI_DC hdc, GDI_POINT *lppt, int *lpdwPolyPoints, DWORD cCount); +FREERDP_API BOOL gdi_MoveToEx(HGDI_DC hdc, int X, int Y, HGDI_POINT lpPoint); #ifdef __cplusplus } #endif -typedef int (*p_LineTo)(HGDI_DC hdc, int nXEnd, int nYEnd); +typedef BOOL (*p_LineTo)(HGDI_DC hdc, int nXEnd, int nYEnd); #endif /* FREERDP_GDI_LINE_H */ diff --git a/include/freerdp/gdi/region.h b/include/freerdp/gdi/region.h index e57726352..8ef56aa8c 100644 --- a/include/freerdp/gdi/region.h +++ b/include/freerdp/gdi/region.h @@ -37,13 +37,13 @@ FREERDP_API void gdi_RgnToRect(HGDI_RGN rgn, HGDI_RECT rect); FREERDP_API void gdi_CRgnToRect(int x, int y, int w, int h, HGDI_RECT rect); FREERDP_API void gdi_RgnToCRect(HGDI_RGN rgn, int *left, int *top, int *right, int *bottom); FREERDP_API void gdi_CRgnToCRect(int x, int y, int w, int h, int *left, int *top, int *right, int *bottom); -FREERDP_API int gdi_CopyOverlap(int x, int y, int width, int height, int srcx, int srcy); -FREERDP_API int gdi_SetRect(HGDI_RECT rc, int xLeft, int yTop, int xRight, int yBottom); -FREERDP_API int gdi_SetRgn(HGDI_RGN hRgn, int nXLeft, int nYLeft, int nWidth, int nHeight); -FREERDP_API int gdi_SetRectRgn(HGDI_RGN hRgn, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); -FREERDP_API int gdi_EqualRgn(HGDI_RGN hSrcRgn1, HGDI_RGN hSrcRgn2); -FREERDP_API int gdi_CopyRect(HGDI_RECT dst, HGDI_RECT src); -FREERDP_API int gdi_PtInRect(HGDI_RECT rc, int x, int y); +FREERDP_API BOOL gdi_CopyOverlap(int x, int y, int width, int height, int srcx, int srcy); +FREERDP_API BOOL gdi_SetRect(HGDI_RECT rc, int xLeft, int yTop, int xRight, int yBottom); +FREERDP_API BOOL gdi_SetRgn(HGDI_RGN hRgn, int nXLeft, int nYLeft, int nWidth, int nHeight); +FREERDP_API BOOL gdi_SetRectRgn(HGDI_RGN hRgn, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); +FREERDP_API BOOL gdi_EqualRgn(HGDI_RGN hSrcRgn1, HGDI_RGN hSrcRgn2); +FREERDP_API BOOL gdi_CopyRect(HGDI_RECT dst, HGDI_RECT src); +FREERDP_API BOOL gdi_PtInRect(HGDI_RECT rc, int x, int y); FREERDP_API BOOL gdi_InvalidateRegion(HGDI_DC hdc, int x, int y, int w, int h); #ifdef __cplusplus diff --git a/include/freerdp/gdi/shape.h b/include/freerdp/gdi/shape.h index 9b96324dd..95bbbe567 100644 --- a/include/freerdp/gdi/shape.h +++ b/include/freerdp/gdi/shape.h @@ -27,13 +27,13 @@ extern "C" { #endif -FREERDP_API int gdi_Ellipse(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); -FREERDP_API int gdi_FillRect(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); -FREERDP_API int gdi_Polygon(HGDI_DC hdc, GDI_POINT *lpPoints, int nCount); -FREERDP_API int gdi_PolyPolygon(HGDI_DC hdc, GDI_POINT *lpPoints, int *lpPolyCounts, int nCount); -FREERDP_API int gdi_Rectangle(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); +FREERDP_API BOOL gdi_Ellipse(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); +FREERDP_API BOOL gdi_FillRect(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); +FREERDP_API BOOL gdi_Polygon(HGDI_DC hdc, GDI_POINT *lpPoints, int nCount); +FREERDP_API BOOL gdi_PolyPolygon(HGDI_DC hdc, GDI_POINT *lpPoints, int *lpPolyCounts, int nCount); +FREERDP_API BOOL gdi_Rectangle(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); -typedef int (*p_FillRect)(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); +typedef BOOL (*p_FillRect)(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr); #ifdef __cplusplus } diff --git a/include/freerdp/locale/keyboard.h b/include/freerdp/locale/keyboard.h index 97d000a91..7eeb85930 100644 --- a/include/freerdp/locale/keyboard.h +++ b/include/freerdp/locale/keyboard.h @@ -170,6 +170,7 @@ typedef struct _RDP_KEYBOARD_LAYOUT RDP_KEYBOARD_LAYOUT; #define KBD_GREEK_LATIN 0x00050408 #define KBD_US_ENGLISH_TABLE_FOR_IBM_ARABIC_238_L 0x00050409 #define KBD_GREEK_POLYTONIC 0x00060408 +#define KBD_FRENCH_BEPO 0xa000040c #define KBD_GERMAN_NEO 0xB0000407 /* Global Input Method Editor (IME) IDs */ diff --git a/include/freerdp/server/shadow.h b/include/freerdp/server/shadow.h index eb8233a04..bb024db0e 100644 --- a/include/freerdp/server/shadow.h +++ b/include/freerdp/server/shadow.h @@ -31,6 +31,8 @@ #include #include +#include +#include #include #include @@ -64,6 +66,8 @@ typedef int (*pfnShadowEnumMonitors)(MONITOR_DEF* monitors, int maxMonitors); typedef int (*pfnShadowAuthenticate)(rdpShadowSubsystem* subsystem, const char* user, const char* domain, const char* password); +typedef BOOL (*pfnShadowClientConnect)(rdpShadowSubsystem* subsystem, rdpShadowClient* client); +typedef void (*pfnShadowClientDisconnect)(rdpShadowSubsystem* subsystem, rdpShadowClient* client); typedef int (*pfnShadowSynchronizeEvent)(rdpShadowSubsystem* subsystem, UINT32 flags); typedef int (*pfnShadowKeyboardEvent)(rdpShadowSubsystem* subsystem, UINT16 flags, UINT16 code); @@ -71,6 +75,8 @@ typedef int (*pfnShadowUnicodeKeyboardEvent)(rdpShadowSubsystem* subsystem, UINT typedef int (*pfnShadowMouseEvent)(rdpShadowSubsystem* subsystem, UINT16 flags, UINT16 x, UINT16 y); typedef int (*pfnShadowExtendedMouseEvent)(rdpShadowSubsystem* subsystem, UINT16 flags, UINT16 x, UINT16 y); +typedef void (*pfnShadowChannelAudinServerReceiveSamples)(rdpShadowSubsystem* subsystem, const void* buf, int nframes); + struct rdp_shadow_client { rdpContext context; @@ -80,7 +86,7 @@ struct rdp_shadow_client BOOL inLobby; BOOL mayView; BOOL mayInteract; - HANDLE StopEvent; + wMessageQueue* MsgQueue; CRITICAL_SECTION lock; REGION16 invalidRegion; rdpShadowServer* server; @@ -94,6 +100,8 @@ struct rdp_shadow_client HANDLE vcm; EncomspServerContext* encomsp; RemdeskServerContext* remdesk; + RdpsndServerContext* rdpsnd; + audin_server_context* audin; }; struct rdp_shadow_server @@ -151,13 +159,21 @@ struct _RDP_SHADOW_ENTRY_POINTS UINT32 pointerX; \ UINT32 pointerY; \ \ + const AUDIO_FORMAT* rdpsndFormats; \ + int nRdpsndFormats; \ + const AUDIO_FORMAT* audinFormats; \ + int nAudinFormats; \ + \ pfnShadowSynchronizeEvent SynchronizeEvent; \ pfnShadowKeyboardEvent KeyboardEvent; \ pfnShadowUnicodeKeyboardEvent UnicodeKeyboardEvent; \ pfnShadowMouseEvent MouseEvent; \ pfnShadowExtendedMouseEvent ExtendedMouseEvent; \ + pfnShadowChannelAudinServerReceiveSamples AudinServerReceiveSamples; \ \ pfnShadowAuthenticate Authenticate; \ + pfnShadowClientConnect ClientConnect; \ + pfnShadowClientDisconnect ClientDisconnect; \ \ rdpShadowServer* server @@ -166,10 +182,85 @@ struct rdp_shadow_subsystem RDP_SHADOW_SUBSYSTEM_COMMON(); }; +/* Definition of message between subsystem and clients */ +#define SHADOW_MSG_IN_REFRESH_OUTPUT_ID 1001 +#define SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID 1002 + +struct _SHADOW_MSG_IN_REFRESH_OUTPUT +{ + UINT32 numRects; + RECTANGLE_16* rects; +}; +typedef struct _SHADOW_MSG_IN_REFRESH_OUTPUT SHADOW_MSG_IN_REFRESH_OUTPUT; + +struct _SHADOW_MSG_IN_SUPPRESS_OUTPUT +{ + BOOL allow; + RECTANGLE_16 rect; +}; +typedef struct _SHADOW_MSG_IN_SUPPRESS_OUTPUT SHADOW_MSG_IN_SUPPRESS_OUTPUT; + +typedef struct _SHADOW_MSG_OUT SHADOW_MSG_OUT; +typedef void (*MSG_OUT_FREE_FN)(UINT32 id, SHADOW_MSG_OUT* msg); +#define RDP_SHADOW_MSG_OUT_COMMON() \ + int refCount; \ + MSG_OUT_FREE_FN Free; /* function to free SHADOW_MSG_OUT */ + +struct _SHADOW_MSG_OUT +{ + RDP_SHADOW_MSG_OUT_COMMON(); +}; + +#define SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID 2001 +#define SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID 2002 +#define SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES_ID 2003 +#define SHADOW_MSG_OUT_AUDIO_OUT_VOLUME_ID 2004 + +struct _SHADOW_MSG_OUT_POINTER_POSITION_UPDATE +{ + RDP_SHADOW_MSG_OUT_COMMON(); + UINT32 xPos; + UINT32 yPos; +}; +typedef struct _SHADOW_MSG_OUT_POINTER_POSITION_UPDATE SHADOW_MSG_OUT_POINTER_POSITION_UPDATE; + +struct _SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE +{ + RDP_SHADOW_MSG_OUT_COMMON(); + UINT32 xHot; + UINT32 yHot; + UINT32 width; + UINT32 height; + BYTE* pixels; + int scanline; + BOOL premultiplied; +}; +typedef struct _SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE; + +struct _SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES +{ + RDP_SHADOW_MSG_OUT_COMMON(); + AUDIO_FORMAT audio_format; + void* buf; + int nFrames; + UINT16 wTimestamp; +}; +typedef struct _SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES; + +struct _SHADOW_MSG_OUT_AUDIO_OUT_VOLUME +{ + RDP_SHADOW_MSG_OUT_COMMON(); + int left; + int right; +}; +typedef struct _SHADOW_MSG_OUT_AUDIO_OUT_VOLUME SHADOW_MSG_OUT_AUDIO_OUT_VOLUME; + #ifdef __cplusplus extern "C" { #endif +FREERDP_API void shadow_subsystem_set_entry(pfnShadowSubsystemEntry pEntry); + FREERDP_API int shadow_server_parse_command_line(rdpShadowServer* server, int argc, char** argv); FREERDP_API int shadow_server_command_line_status_print(rdpShadowServer* server, int argc, char** argv, int status); @@ -179,11 +270,18 @@ FREERDP_API int shadow_server_stop(rdpShadowServer* server); FREERDP_API int shadow_server_init(rdpShadowServer* server); FREERDP_API int shadow_server_uninit(rdpShadowServer* server); -FREERDP_API int shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors, const char* name); +FREERDP_API int shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors); FREERDP_API rdpShadowServer* shadow_server_new(); FREERDP_API void shadow_server_free(rdpShadowServer* server); +FREERDP_API BOOL shadow_client_post_msg(rdpShadowClient* client, void* context, UINT32 type, SHADOW_MSG_OUT* msg, void* lParam); +FREERDP_API int shadow_client_boardcast_msg(rdpShadowServer* server, void* context, UINT32 type, SHADOW_MSG_OUT* msg, void* lParam); +FREERDP_API int shadow_client_boardcast_quit(rdpShadowServer* server, int nExitCode); + +FREERDP_API int shadow_encoder_preferred_fps(rdpShadowEncoder* encoder); +FREERDP_API UINT32 shadow_encoder_inflight_frames(rdpShadowEncoder* encoder); + #ifdef __cplusplus } #endif diff --git a/include/freerdp/settings.h b/include/freerdp/settings.h index c0f32e6b8..352a38d28 100644 --- a/include/freerdp/settings.h +++ b/include/freerdp/settings.h @@ -1435,17 +1435,17 @@ FREERDP_API int freerdp_addin_replace_argument(ADDIN_ARGV* args, char* previous, FREERDP_API int freerdp_addin_set_argument_value(ADDIN_ARGV* args, char* option, char* value); FREERDP_API int freerdp_addin_replace_argument_value(ADDIN_ARGV* args, char* previous, char* option, char* value); -FREERDP_API void freerdp_device_collection_add(rdpSettings* settings, RDPDR_DEVICE* device); +FREERDP_API BOOL freerdp_device_collection_add(rdpSettings* settings, RDPDR_DEVICE* device); FREERDP_API RDPDR_DEVICE* freerdp_device_collection_find(rdpSettings* settings, const char* name); FREERDP_API RDPDR_DEVICE* freerdp_device_clone(RDPDR_DEVICE* device); FREERDP_API void freerdp_device_collection_free(rdpSettings* settings); -FREERDP_API void freerdp_static_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel); +FREERDP_API BOOL freerdp_static_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel); FREERDP_API ADDIN_ARGV* freerdp_static_channel_collection_find(rdpSettings* settings, const char* name); FREERDP_API ADDIN_ARGV* freerdp_static_channel_clone(ADDIN_ARGV* channel); FREERDP_API void freerdp_static_channel_collection_free(rdpSettings* settings); -FREERDP_API void freerdp_dynamic_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel); +FREERDP_API BOOL freerdp_dynamic_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel); FREERDP_API ADDIN_ARGV* freerdp_dynamic_channel_collection_find(rdpSettings* settings, const char* name); FREERDP_API ADDIN_ARGV* freerdp_dynamic_channel_clone(ADDIN_ARGV* channel); FREERDP_API void freerdp_dynamic_channel_collection_free(rdpSettings* settings); diff --git a/include/freerdp/utils/pcap.h b/include/freerdp/utils/pcap.h index bf98bb5d3..5276de140 100644 --- a/include/freerdp/utils/pcap.h +++ b/include/freerdp/utils/pcap.h @@ -75,7 +75,7 @@ extern "C" { FREERDP_API rdpPcap* pcap_open(char* name, BOOL write); FREERDP_API void pcap_close(rdpPcap* pcap); -FREERDP_API void pcap_add_record(rdpPcap* pcap, void* data, UINT32 length); +FREERDP_API BOOL pcap_add_record(rdpPcap* pcap, void* data, UINT32 length); FREERDP_API BOOL pcap_has_next_record(rdpPcap* pcap); FREERDP_API BOOL pcap_get_next_record(rdpPcap* pcap, pcap_record* record); FREERDP_API BOOL pcap_get_next_record_header(rdpPcap* pcap, pcap_record* record); diff --git a/libfreerdp/cache/brush.c b/libfreerdp/cache/brush.c index 8b5ea43da..448a92d28 100644 --- a/libfreerdp/cache/brush.c +++ b/libfreerdp/cache/brush.c @@ -189,25 +189,31 @@ rdpBrushCache* brush_cache_new(rdpSettings* settings) { rdpBrushCache* brushCache; - brushCache = (rdpBrushCache*) malloc(sizeof(rdpBrushCache)); + brushCache = (rdpBrushCache*) calloc(1, sizeof(rdpBrushCache)); - if (brushCache) - { - ZeroMemory(brushCache, sizeof(rdpBrushCache)); + if (!brushCache) + return NULL; - brushCache->settings = settings; + brushCache->settings = settings; - brushCache->maxEntries = 64; - brushCache->maxMonoEntries = 64; + brushCache->maxEntries = 64; + brushCache->maxMonoEntries = 64; - brushCache->entries = (BRUSH_ENTRY*) malloc(sizeof(BRUSH_ENTRY) * brushCache->maxEntries); - ZeroMemory(brushCache->entries, sizeof(BRUSH_ENTRY) * brushCache->maxEntries); + brushCache->entries = (BRUSH_ENTRY*)calloc(brushCache->maxEntries, sizeof(BRUSH_ENTRY)); + if (!brushCache->entries) + goto error_entries; - brushCache->monoEntries = (BRUSH_ENTRY*) malloc(sizeof(BRUSH_ENTRY) * brushCache->maxMonoEntries); - ZeroMemory(brushCache->monoEntries, sizeof(BRUSH_ENTRY) * brushCache->maxMonoEntries); - } + brushCache->monoEntries = (BRUSH_ENTRY*) calloc(brushCache->maxMonoEntries, sizeof(BRUSH_ENTRY)); + if (!brushCache->monoEntries) + goto error_mono; return brushCache; + +error_mono: + free(brushCache->entries); +error_entries: + free(brushCache); + return NULL; } void brush_cache_free(rdpBrushCache* brushCache) diff --git a/libfreerdp/cache/cache.c b/libfreerdp/cache/cache.c index bc6563f17..0e42f6b6c 100644 --- a/libfreerdp/cache/cache.c +++ b/libfreerdp/cache/cache.c @@ -31,22 +31,50 @@ rdpCache* cache_new(rdpSettings* settings) { rdpCache* cache; - cache = (rdpCache*) malloc(sizeof(rdpCache)); - ZeroMemory(cache, sizeof(rdpCache)); + cache = (rdpCache*) calloc(1, sizeof(rdpCache)); + if (!cache) + return NULL; - if (cache != NULL) - { - cache->settings = settings; - cache->glyph = glyph_cache_new(settings); - cache->brush = brush_cache_new(settings); - cache->pointer = pointer_cache_new(settings); - cache->bitmap = bitmap_cache_new(settings); - cache->offscreen = offscreen_cache_new(settings); - cache->palette = palette_cache_new(settings); - cache->nine_grid = nine_grid_cache_new(settings); - } + cache->settings = settings; + cache->glyph = glyph_cache_new(settings); + if (!cache->glyph) + goto error_glyph; + cache->brush = brush_cache_new(settings); + if (!cache->brush) + goto error_brush; + cache->pointer = pointer_cache_new(settings); + if (!cache->pointer) + goto error_pointer; + cache->bitmap = bitmap_cache_new(settings); + if (!cache->bitmap) + goto error_bitmap; + cache->offscreen = offscreen_cache_new(settings); + if (!cache->offscreen) + goto error_offscreen; + cache->palette = palette_cache_new(settings); + if (!cache->palette) + goto error_palette; + cache->nine_grid = nine_grid_cache_new(settings); + if (!cache->nine_grid) + goto error_ninegrid; return cache; + +error_ninegrid: + palette_cache_free(cache->palette); +error_palette: + offscreen_cache_free(cache->offscreen); +error_offscreen: + bitmap_cache_free(cache->bitmap); +error_bitmap: + pointer_cache_free(cache->pointer); +error_pointer: + brush_cache_free(cache->brush); +error_brush: + glyph_cache_free(cache->glyph); +error_glyph: + free(cache); + return NULL; } void cache_free(rdpCache* cache) diff --git a/libfreerdp/cache/glyph.c b/libfreerdp/cache/glyph.c index 6b6445e51..037c5a5d9 100644 --- a/libfreerdp/cache/glyph.c +++ b/libfreerdp/cache/glyph.c @@ -57,7 +57,7 @@ void update_process_glyph(rdpContext* context, BYTE* data, int* index, if (offset & 0x80) { - offset = data[*index + 1] | (data[*index + 2] << 8); + offset = data[*index + 1] | ((int)((char)data[*index + 2]) << 8); (*index)++; (*index)++; } @@ -77,7 +77,7 @@ void update_process_glyph(rdpContext* context, BYTE* data, int* index, } } -void update_process_glyph_fragments(rdpContext* context, BYTE* data, UINT32 length, +BOOL update_process_glyph_fragments(rdpContext* context, BYTE* data, UINT32 length, UINT32 cacheId, UINT32 ulCharInc, UINT32 flAccel, UINT32 bgcolor, UINT32 fgcolor, int x, int y, int bkX, int bkY, int bkWidth, int bkHeight, int opX, int opY, int opWidth, int opHeight, BOOL fOpRedundant) { @@ -108,17 +108,20 @@ void update_process_glyph_fragments(rdpContext* context, BYTE* data, UINT32 leng if (opWidth > 0 && opHeight > 0) { - Glyph_BeginDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor, fOpRedundant); + if (!Glyph_BeginDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor, fOpRedundant)) + return FALSE; } else { if (fOpRedundant) { - Glyph_BeginDraw(context, bkX, bkY, bkWidth, bkHeight, bgcolor, fgcolor, fOpRedundant); + if (!Glyph_BeginDraw(context, bkX, bkY, bkWidth, bkHeight, bgcolor, fgcolor, fOpRedundant)) + return FALSE; } else { - Glyph_BeginDraw(context, 0, 0, 0, 0, bgcolor, fgcolor, fOpRedundant); + if (!Glyph_BeginDraw(context, 0, 0, 0, 0, bgcolor, fgcolor, fOpRedundant)) + return FALSE; } } @@ -175,6 +178,8 @@ void update_process_glyph_fragments(rdpContext* context, BYTE* data, UINT32 leng size = data[index + 2]; fragments = (BYTE*) malloc(size); + if (!fragments) + return FALSE; CopyMemory(fragments, data, size); glyph_cache_fragment_put(glyph_cache, id, size, fragments); @@ -194,9 +199,9 @@ void update_process_glyph_fragments(rdpContext* context, BYTE* data, UINT32 leng } if (opWidth > 0 && opHeight > 0) - Glyph_EndDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor); - else - Glyph_EndDraw(context, bkX, bkY, bkWidth, bkHeight, bgcolor, fgcolor); + return Glyph_EndDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor); + + return Glyph_EndDraw(context, bkX, bkY, bkWidth, bkHeight, bgcolor, fgcolor); } BOOL update_gdi_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyphIndex) @@ -211,14 +216,12 @@ BOOL update_gdi_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyphIndex) bkHeight = glyphIndex->bkBottom - glyphIndex->bkTop; opHeight = glyphIndex->opBottom - glyphIndex->opTop; - update_process_glyph_fragments(context, glyphIndex->data, glyphIndex->cbData, + return update_process_glyph_fragments(context, glyphIndex->data, glyphIndex->cbData, glyphIndex->cacheId, glyphIndex->ulCharInc, glyphIndex->flAccel, glyphIndex->backColor, glyphIndex->foreColor, glyphIndex->x, glyphIndex->y, glyphIndex->bkLeft, glyphIndex->bkTop, bkWidth, bkHeight, glyphIndex->opLeft, glyphIndex->opTop, opWidth, opHeight, glyphIndex->fOpRedundant); - - return TRUE; } BOOL update_gdi_fast_index(rdpContext* context, FAST_INDEX_ORDER* fastIndex) @@ -263,7 +266,7 @@ BOOL update_gdi_fast_index(rdpContext* context, FAST_INDEX_ORDER* fastIndex) if (y == -32768) y = fastIndex->bkTop; - update_process_glyph_fragments(context, fastIndex->data, fastIndex->cbData, + return update_process_glyph_fragments(context, fastIndex->data, fastIndex->cbData, fastIndex->cacheId, fastIndex->ulCharInc, fastIndex->flAccel, fastIndex->backColor, fastIndex->foreColor, x, y, fastIndex->bkLeft, fastIndex->bkTop, @@ -271,7 +274,6 @@ BOOL update_gdi_fast_index(rdpContext* context, FAST_INDEX_ORDER* fastIndex) opLeft, opTop, opRight - opLeft, opBottom - opTop, FALSE); - return TRUE; } BOOL update_gdi_fast_glyph(rdpContext* context, FAST_GLYPH_ORDER* fastGlyph) @@ -323,14 +325,20 @@ BOOL update_gdi_fast_glyph(rdpContext* context, FAST_GLYPH_ORDER* fastGlyph) glyphData = &fastGlyph->glyphData; glyph = Glyph_Alloc(context); + if (!glyph) + return FALSE; glyph->x = glyphData->x; glyph->y = glyphData->y; glyph->cx = glyphData->cx; glyph->cy = glyphData->cy; glyph->cb = glyphData->cb; glyph->aj = malloc(glyphData->cb); + if (!glyph->aj) + goto error_aj; CopyMemory(glyph->aj, glyphData->aj, glyph->cb); - Glyph_New(context, glyph); + + if (!Glyph_New(context, glyph)) + goto error_glyph_new; glyph_cache_put(cache->glyph, fastGlyph->cacheId, fastGlyph->data[0], glyph); } @@ -338,7 +346,7 @@ BOOL update_gdi_fast_glyph(rdpContext* context, FAST_GLYPH_ORDER* fastGlyph) text_data[0] = fastGlyph->data[0]; text_data[1] = 0; - update_process_glyph_fragments(context, text_data, 1, + return update_process_glyph_fragments(context, text_data, 1, fastGlyph->cacheId, fastGlyph->ulCharInc, fastGlyph->flAccel, fastGlyph->backColor, fastGlyph->foreColor, x, y, fastGlyph->bkLeft, fastGlyph->bkTop, @@ -346,7 +354,13 @@ BOOL update_gdi_fast_glyph(rdpContext* context, FAST_GLYPH_ORDER* fastGlyph) opLeft, opTop, opRight - opLeft, opBottom - opTop, FALSE); - return TRUE; + +error_glyph_new: + free(glyph->aj); + glyph->aj = NULL; +error_aj: + Glyph_Free(context, glyph); + return FALSE; } BOOL update_gdi_cache_glyph(rdpContext* context, CACHE_GLYPH_ORDER* cacheGlyph) @@ -362,10 +376,7 @@ BOOL update_gdi_cache_glyph(rdpContext* context, CACHE_GLYPH_ORDER* cacheGlyph) glyph = Glyph_Alloc(context); if (!glyph) - { - /* TODO: cleanup previously allocated memory */ return FALSE; - } glyph->x = glyph_data->x; glyph->y = glyph_data->y; @@ -373,7 +384,11 @@ BOOL update_gdi_cache_glyph(rdpContext* context, CACHE_GLYPH_ORDER* cacheGlyph) glyph->cy = glyph_data->cy; glyph->cb = glyph_data->cb; glyph->aj = glyph_data->aj; - Glyph_New(context, glyph); + if (!Glyph_New(context, glyph)) + { + Glyph_Free(context, glyph); + return FALSE; + } glyph_cache_put(cache->glyph, cacheGlyph->cacheId, glyph_data->cacheIndex, glyph); } diff --git a/libfreerdp/cache/nine_grid.c b/libfreerdp/cache/nine_grid.c index 5789a66e5..16b174718 100644 --- a/libfreerdp/cache/nine_grid.c +++ b/libfreerdp/cache/nine_grid.c @@ -95,21 +95,23 @@ rdpNineGridCache* nine_grid_cache_new(rdpSettings* settings) { rdpNineGridCache* nine_grid; - nine_grid = (rdpNineGridCache*) malloc(sizeof(rdpNineGridCache)); - ZeroMemory(nine_grid, sizeof(rdpNineGridCache)); + nine_grid = (rdpNineGridCache*) calloc(1, sizeof(rdpNineGridCache)); + if (!nine_grid) + return NULL; - if (nine_grid != NULL) + nine_grid->settings = settings; + + nine_grid->maxSize = 2560; + nine_grid->maxEntries = 256; + + nine_grid->settings->DrawNineGridCacheSize = nine_grid->maxSize; + nine_grid->settings->DrawNineGridCacheEntries = nine_grid->maxEntries; + + nine_grid->entries = (NINE_GRID_ENTRY*) calloc(nine_grid->maxEntries, sizeof(NINE_GRID_ENTRY)); + if (!nine_grid->entries) { - nine_grid->settings = settings; - - nine_grid->maxSize = 2560; - nine_grid->maxEntries = 256; - - nine_grid->settings->DrawNineGridCacheSize = nine_grid->maxSize; - nine_grid->settings->DrawNineGridCacheEntries = nine_grid->maxEntries; - - nine_grid->entries = (NINE_GRID_ENTRY*) malloc(sizeof(NINE_GRID_ENTRY) * nine_grid->maxEntries); - ZeroMemory(nine_grid->entries, sizeof(NINE_GRID_ENTRY) * nine_grid->maxEntries); + free(nine_grid); + return NULL; } return nine_grid; diff --git a/libfreerdp/cache/offscreen.c b/libfreerdp/cache/offscreen.c index 00d0429d6..76765e933 100644 --- a/libfreerdp/cache/offscreen.c +++ b/libfreerdp/cache/offscreen.c @@ -146,26 +146,27 @@ rdpOffscreenCache* offscreen_cache_new(rdpSettings* settings) { rdpOffscreenCache* offscreenCache; - offscreenCache = (rdpOffscreenCache*) malloc(sizeof(rdpOffscreenCache)); + offscreenCache = (rdpOffscreenCache*) calloc(1, sizeof(rdpOffscreenCache)); - if (offscreenCache) + if (!offscreenCache) + return NULL; + + offscreenCache->settings = settings; + offscreenCache->update = ((freerdp*) settings->instance)->update; + + offscreenCache->currentSurface = SCREEN_BITMAP_SURFACE; + offscreenCache->maxSize = 7680; + offscreenCache->maxEntries = 2000; + + settings->OffscreenCacheSize = offscreenCache->maxSize; + settings->OffscreenCacheEntries = offscreenCache->maxEntries; + + offscreenCache->entries = (rdpBitmap**) calloc(offscreenCache->maxEntries, sizeof(rdpBitmap*)); + if (!offscreenCache->entries) { - ZeroMemory(offscreenCache, sizeof(rdpOffscreenCache)); - - offscreenCache->settings = settings; - offscreenCache->update = ((freerdp*) settings->instance)->update; - - offscreenCache->currentSurface = SCREEN_BITMAP_SURFACE; - offscreenCache->maxSize = 7680; - offscreenCache->maxEntries = 2000; - - settings->OffscreenCacheSize = offscreenCache->maxSize; - settings->OffscreenCacheEntries = offscreenCache->maxEntries; - - offscreenCache->entries = (rdpBitmap**) malloc(sizeof(rdpBitmap*) * offscreenCache->maxEntries); - ZeroMemory(offscreenCache->entries, sizeof(rdpBitmap*) * offscreenCache->maxEntries); + free(offscreenCache); + return NULL; } - return offscreenCache; } diff --git a/libfreerdp/cache/pointer.c b/libfreerdp/cache/pointer.c index a36d92a95..302204d4b 100644 --- a/libfreerdp/cache/pointer.c +++ b/libfreerdp/cache/pointer.c @@ -109,39 +109,37 @@ BOOL update_pointer_new(rdpContext* context, POINTER_NEW_UPDATE* pointer_new) rdpCache* cache = context->cache; pointer = Pointer_Alloc(context); + if (!pointer) + return FALSE; - if (pointer != NULL) + pointer->xorBpp = pointer_new->xorBpp; + pointer->xPos = pointer_new->colorPtrAttr.xPos; + pointer->yPos = pointer_new->colorPtrAttr.yPos; + pointer->width = pointer_new->colorPtrAttr.width; + pointer->height = pointer_new->colorPtrAttr.height; + pointer->lengthAndMask = pointer_new->colorPtrAttr.lengthAndMask; + pointer->lengthXorMask = pointer_new->colorPtrAttr.lengthXorMask; + + if (pointer->lengthAndMask) { - pointer->xorBpp = pointer_new->xorBpp; - pointer->xPos = pointer_new->colorPtrAttr.xPos; - pointer->yPos = pointer_new->colorPtrAttr.yPos; - pointer->width = pointer_new->colorPtrAttr.width; - pointer->height = pointer_new->colorPtrAttr.height; - pointer->lengthAndMask = pointer_new->colorPtrAttr.lengthAndMask; - pointer->lengthXorMask = pointer_new->colorPtrAttr.lengthXorMask; - - pointer->andMaskData = pointer->xorMaskData = NULL; - - if (pointer->lengthAndMask) - { - pointer->andMaskData = (BYTE*) malloc(pointer->lengthAndMask); - if (!pointer->andMaskData) - goto out_fail; - CopyMemory(pointer->andMaskData, pointer_new->colorPtrAttr.andMaskData, pointer->lengthAndMask); - } - - if (pointer->lengthXorMask) - { - pointer->xorMaskData = (BYTE*) malloc(pointer->lengthXorMask); - CopyMemory(pointer->xorMaskData, pointer_new->colorPtrAttr.xorMaskData, pointer->lengthXorMask); - } - - pointer->New(context, pointer); - pointer_cache_put(cache->pointer, pointer_new->colorPtrAttr.cacheIndex, pointer); - Pointer_Set(context, pointer); - return TRUE; + pointer->andMaskData = (BYTE*) malloc(pointer->lengthAndMask); + if (!pointer->andMaskData) + goto out_fail; + CopyMemory(pointer->andMaskData, pointer_new->colorPtrAttr.andMaskData, pointer->lengthAndMask); } - return FALSE; + + if (pointer->lengthXorMask) + { + pointer->xorMaskData = (BYTE*) malloc(pointer->lengthXorMask); + if (!pointer->xorMaskData) + goto out_fail; + CopyMemory(pointer->xorMaskData, pointer_new->colorPtrAttr.xorMaskData, pointer->lengthXorMask); + } + + if (!pointer->New(context, pointer)) + goto out_fail; + pointer_cache_put(cache->pointer, pointer_new->colorPtrAttr.cacheIndex, pointer); + return Pointer_Set(context, pointer); out_fail: free(pointer->andMaskData); @@ -213,18 +211,19 @@ rdpPointerCache* pointer_cache_new(rdpSettings* settings) { rdpPointerCache* pointer_cache; - pointer_cache = (rdpPointerCache*) malloc(sizeof(rdpPointerCache)); + pointer_cache = (rdpPointerCache*) calloc(1, sizeof(rdpPointerCache)); + if (!pointer_cache) + return NULL; - if (pointer_cache != NULL) + pointer_cache->settings = settings; + pointer_cache->cacheSize = settings->PointerCacheSize; + pointer_cache->update = ((freerdp*) settings->instance)->update; + + pointer_cache->entries = (rdpPointer**) calloc(pointer_cache->cacheSize, sizeof(rdpPointer*)); + if (!pointer_cache->entries) { - ZeroMemory(pointer_cache, sizeof(rdpPointerCache)); - - pointer_cache->settings = settings; - pointer_cache->cacheSize = settings->PointerCacheSize; - pointer_cache->update = ((freerdp*) settings->instance)->update; - - pointer_cache->entries = (rdpPointer**) malloc(sizeof(rdpPointer*) * pointer_cache->cacheSize); - ZeroMemory(pointer_cache->entries, sizeof(rdpPointer*) * pointer_cache->cacheSize); + free(pointer_cache); + return NULL; } return pointer_cache; diff --git a/libfreerdp/codec/clear.c b/libfreerdp/codec/clear.c index f6540c6f7..922a83acd 100644 --- a/libfreerdp/codec/clear.c +++ b/libfreerdp/codec/clear.c @@ -377,12 +377,13 @@ int clear_decompress(CLEAR_CONTEXT* clear, BYTE* pSrcData, UINT32 SrcSize, if (vBarShortEntry->count > vBarShortEntry->size) { + UINT32 *tmp; vBarShortEntry->size = vBarShortEntry->count; - if (!vBarShortEntry->pixels) - vBarShortEntry->pixels = (UINT32*) malloc(vBarShortEntry->count * 4); - else - vBarShortEntry->pixels = (UINT32*) realloc(vBarShortEntry->pixels, vBarShortEntry->count * 4); + tmp = (UINT32*) realloc(vBarShortEntry->pixels, vBarShortEntry->count * 4); + if (!tmp) + return -1; + vBarShortEntry->pixels = tmp; } if (!vBarShortEntry->pixels && vBarShortEntry->size) @@ -442,12 +443,13 @@ int clear_decompress(CLEAR_CONTEXT* clear, BYTE* pSrcData, UINT32 SrcSize, if (vBarEntry->count > vBarEntry->size) { + UINT32 *tmp; vBarEntry->size = vBarEntry->count; - if (!vBarEntry->pixels) - vBarEntry->pixels = (UINT32*) malloc(vBarEntry->count * 4); - else - vBarEntry->pixels = (UINT32*) realloc(vBarEntry->pixels, vBarEntry->count * 4); + tmp = (UINT32*) realloc(vBarEntry->pixels, vBarEntry->count * 4); + if (!tmp) + return -1; + vBarEntry->pixels = tmp; } if (!vBarEntry->pixels && vBarEntry->size) @@ -791,12 +793,13 @@ int clear_decompress(CLEAR_CONTEXT* clear, BYTE* pSrcData, UINT32 SrcSize, if (glyphEntry->count > glyphEntry->size) { + UINT32 *tmp; glyphEntry->size = glyphEntry->count; - if (!glyphEntry->pixels) - glyphEntry->pixels = (UINT32*) malloc(glyphEntry->size * 4); - else - glyphEntry->pixels = (UINT32*) realloc(glyphEntry->pixels, glyphEntry->size * 4); + tmp = (UINT32*) realloc(glyphEntry->pixels, glyphEntry->size * 4); + if (!tmp) + return -1; + glyphEntry->pixels = tmp; } if (!glyphEntry->pixels) @@ -841,27 +844,31 @@ CLEAR_CONTEXT* clear_context_new(BOOL Compressor) clear = (CLEAR_CONTEXT*) calloc(1, sizeof(CLEAR_CONTEXT)); - if (clear) - { - clear->Compressor = Compressor; + if (!clear) + return NULL; - clear->nsc = nsc_context_new(); + clear->Compressor = Compressor; - if (!clear->nsc) - { - free (clear); - return NULL; - } + clear->nsc = nsc_context_new(); + if (!clear->nsc) + goto error_nsc; - nsc_context_set_pixel_format(clear->nsc, RDP_PIXEL_FORMAT_R8G8B8); + nsc_context_set_pixel_format(clear->nsc, RDP_PIXEL_FORMAT_R8G8B8); - clear->TempSize = 512 * 512 * 4; - clear->TempBuffer = (BYTE*) malloc(clear->TempSize); + clear->TempSize = 512 * 512 * 4; + clear->TempBuffer = (BYTE*) malloc(clear->TempSize); + if (!clear->TempBuffer) + goto error_temp_buffer; - clear_context_reset(clear); - } + clear_context_reset(clear); return clear; + +error_temp_buffer: + nsc_context_free(clear->nsc); +error_nsc: + free(clear); + return NULL; } void clear_context_free(CLEAR_CONTEXT* clear) diff --git a/libfreerdp/codec/h264.c b/libfreerdp/codec/h264.c index 45732ebe1..b170ca32d 100644 --- a/libfreerdp/codec/h264.c +++ b/libfreerdp/codec/h264.c @@ -679,7 +679,7 @@ int h264_decompress(H264_CONTEXT* h264, BYTE* pSrcData, UINT32 SrcSize, int h264_compress(H264_CONTEXT* h264, BYTE* pSrcData, DWORD SrcFormat, int nSrcStep, int nSrcWidth, int nSrcHeight, BYTE** ppDstData, UINT32* pDstSize) { - int status; + int status = -1; prim_size_t roi; int nWidth, nHeight; primitives_t *prims = primitives_get(); @@ -691,12 +691,19 @@ int h264_compress(H264_CONTEXT* h264, BYTE* pSrcData, DWORD SrcFormat, nWidth = (nSrcWidth + 1) & ~1; nHeight = (nSrcHeight + 1) & ~1; - h264->pYUVData[0] = (BYTE*) malloc(nWidth * nHeight); + + if (!(h264->pYUVData[0] = (BYTE*) malloc(nWidth * nHeight))) + return -1; h264->iStride[0] = nWidth; - h264->pYUVData[1] = (BYTE*) malloc(nWidth * nHeight / 4); + + if (!(h264->pYUVData[1] = (BYTE*) malloc(nWidth * nHeight / 4))) + goto error_1; h264->iStride[1] = nWidth / 2; - h264->pYUVData[2] = (BYTE*) malloc(nWidth * nHeight / 4); + + if (!(h264->pYUVData[2] = (BYTE*) malloc(nWidth * nHeight / 4))) + goto error_2; h264->iStride[2] = nWidth / 2; + h264->width = nWidth; h264->height = nHeight; roi.width = nSrcWidth; @@ -706,12 +713,14 @@ int h264_compress(H264_CONTEXT* h264, BYTE* pSrcData, DWORD SrcFormat, status = h264->subsystem->Compress(h264, ppDstData, pDstSize); - free(h264->pYUVData[0]); - free(h264->pYUVData[1]); free(h264->pYUVData[2]); - h264->pYUVData[0] = NULL; - h264->pYUVData[1] = NULL; h264->pYUVData[2] = NULL; +error_2: + free(h264->pYUVData[1]); + h264->pYUVData[1] = NULL; +error_1: + free(h264->pYUVData[0]); + h264->pYUVData[0] = NULL; return status; } diff --git a/libfreerdp/codec/planar.c b/libfreerdp/codec/planar.c index 2fcc022a7..37bd7bd52 100644 --- a/libfreerdp/codec/planar.c +++ b/libfreerdp/codec/planar.c @@ -873,6 +873,8 @@ BYTE* freerdp_bitmap_planar_compress_plane_rle(BYTE* inPlane, int width, int hei { outBufferSize = width * height; outPlane = malloc(outBufferSize); + if (!outPlane) + return NULL; } else { @@ -968,7 +970,10 @@ BYTE* freerdp_bitmap_planar_delta_encode_plane(BYTE* inPlane, int width, int hei BYTE *outPtr, *srcPtr, *prevLinePtr; if (!outPlane) - outPlane = (BYTE*) malloc(width * height); + { + if (!(outPlane = (BYTE*) malloc(width * height))) + return NULL; + } // first line is copied as is CopyMemory(outPlane, inPlane, width); @@ -994,14 +999,18 @@ BYTE* freerdp_bitmap_planar_delta_encode_plane(BYTE* inPlane, int width, int hei return outPlane; } -int freerdp_bitmap_planar_delta_encode_planes(BYTE* inPlanes[4], int width, int height, BYTE* outPlanes[4]) +BOOL freerdp_bitmap_planar_delta_encode_planes(BYTE* inPlanes[4], int width, int height, BYTE* outPlanes[4]) { - outPlanes[0] = freerdp_bitmap_planar_delta_encode_plane(inPlanes[0], width, height, outPlanes[0]); - outPlanes[1] = freerdp_bitmap_planar_delta_encode_plane(inPlanes[1], width, height, outPlanes[1]); - outPlanes[2] = freerdp_bitmap_planar_delta_encode_plane(inPlanes[2], width, height, outPlanes[2]); - outPlanes[3] = freerdp_bitmap_planar_delta_encode_plane(inPlanes[3], width, height, outPlanes[3]); + int i; - return 0; + for (i = 0; i < 4; i++) + { + outPlanes[i] = freerdp_bitmap_planar_delta_encode_plane(inPlanes[i], width, height, outPlanes[i]); + if (!outPlanes[i]) + return FALSE; + } + + return TRUE; } BYTE* freerdp_bitmap_compress_planar(BITMAP_PLANAR_CONTEXT* context, BYTE* data, UINT32 format, @@ -1025,7 +1034,8 @@ BYTE* freerdp_bitmap_compress_planar(BITMAP_PLANAR_CONTEXT* context, BYTE* data, if (context->AllowRunLengthEncoding) { - freerdp_bitmap_planar_delta_encode_planes(context->planes, width, height, context->deltaPlanes); + if (!freerdp_bitmap_planar_delta_encode_planes(context->planes, width, height, context->deltaPlanes)) + return NULL;; if (freerdp_bitmap_planar_compress_planes_rle(context->deltaPlanes, width, height, context->rlePlanesBuffer, (int*) &dstSizes, context->AllowSkipAlpha) > 0) @@ -1071,6 +1081,8 @@ BYTE* freerdp_bitmap_compress_planar(BITMAP_PLANAR_CONTEXT* context, BYTE* data, size++; dstData = malloc(size); + if (!dstData) + return NULL; *pDstSize = size; } @@ -1157,13 +1169,10 @@ BITMAP_PLANAR_CONTEXT* freerdp_bitmap_planar_context_new(DWORD flags, int maxWid { BITMAP_PLANAR_CONTEXT* context; - context = (BITMAP_PLANAR_CONTEXT*) malloc(sizeof(BITMAP_PLANAR_CONTEXT)); - + context = (BITMAP_PLANAR_CONTEXT*) calloc(1, sizeof(BITMAP_PLANAR_CONTEXT)); if (!context) return NULL; - ZeroMemory(context, sizeof(BITMAP_PLANAR_CONTEXT)); - if (flags & PLANAR_FORMAT_HEADER_NA) context->AllowSkipAlpha = TRUE; @@ -1183,20 +1192,34 @@ BITMAP_PLANAR_CONTEXT* freerdp_bitmap_planar_context_new(DWORD flags, int maxWid context->maxPlaneSize = context->maxWidth * context->maxHeight; context->planesBuffer = malloc(context->maxPlaneSize * 4); + if (!context->planesBuffer) + goto error_planesBuffer; context->planes[0] = &context->planesBuffer[context->maxPlaneSize * 0]; context->planes[1] = &context->planesBuffer[context->maxPlaneSize * 1]; context->planes[2] = &context->planesBuffer[context->maxPlaneSize * 2]; context->planes[3] = &context->planesBuffer[context->maxPlaneSize * 3]; context->deltaPlanesBuffer = malloc(context->maxPlaneSize * 4); + if (!context->deltaPlanesBuffer) + goto error_deltaPlanesBuffer; context->deltaPlanes[0] = &context->deltaPlanesBuffer[context->maxPlaneSize * 0]; context->deltaPlanes[1] = &context->deltaPlanesBuffer[context->maxPlaneSize * 1]; context->deltaPlanes[2] = &context->deltaPlanesBuffer[context->maxPlaneSize * 2]; context->deltaPlanes[3] = &context->deltaPlanesBuffer[context->maxPlaneSize * 3]; context->rlePlanesBuffer = malloc(context->maxPlaneSize * 4); + if (!context->rlePlanesBuffer) + goto error_rlePlanesBuffer; return context; + +error_rlePlanesBuffer: + free(context->deltaPlanesBuffer); +error_deltaPlanesBuffer: + free(context->planesBuffer); +error_planesBuffer: + free(context); + return NULL; } void freerdp_bitmap_planar_context_free(BITMAP_PLANAR_CONTEXT* context) diff --git a/libfreerdp/codec/progressive.c b/libfreerdp/codec/progressive.c index 36fc4158f..2923660b2 100644 --- a/libfreerdp/codec/progressive.c +++ b/libfreerdp/codec/progressive.c @@ -224,6 +224,12 @@ BOOL progressive_rfx_quant_cmp_equal(RFX_COMPONENT_CODEC_QUANT* q1, RFX_COMPONEN return TRUE; } +void progressive_rfx_quant_print(RFX_COMPONENT_CODEC_QUANT* q, const char* name) +{ + fprintf(stderr, "%s: HL1: %d LH1: %d HH1: %d HL2: %d LH2: %d HH2: %d HL3: %d LH3: %d HH3: %d LL3: %d\n", + name, q->HL1, q->LH1, q->HH1, q->HL2, q->LH2, q->HH2, q->HL3, q->LH3, q->HH3, q->LL3); +} + int progressive_set_surface_data(PROGRESSIVE_CONTEXT* progressive, UINT16 surfaceId, void* pData) { ULONG_PTR key; @@ -270,7 +276,7 @@ PROGRESSIVE_SURFACE_CONTEXT* progressive_surface_context_new(UINT16 surfaceId, U if (!surface->tiles) { - free (surface); + free(surface); return NULL; } @@ -727,10 +733,9 @@ int progressive_decompress_tile_first(PROGRESSIVE_CONTEXT* progressive, RFX_PROG diff = tile->flags & RFX_TILE_DIFFERENCE; -#if 0 - WLog_INFO(TAG, "ProgressiveTileFirst: quantIdx Y: %d Cb: %d Cr: %d xIdx: %d yIdx: %d flags: 0x%02X quality: %d yLen: %d cbLen: %d crLen: %d tailLen: %d", - tile->quantIdxY, tile->quantIdxCb, tile->quantIdxCr, tile->xIdx, tile->yIdx, tile->flags, tile->quality, tile->yLen, tile->cbLen, tile->crLen, tile->tailLen); -#endif + WLog_DBG(TAG, "ProgressiveTile%s: quantIdx Y: %d Cb: %d Cr: %d xIdx: %d yIdx: %d flags: 0x%02X quality: %d yLen: %d cbLen: %d crLen: %d tailLen: %d", + (tile->blockType == PROGRESSIVE_WBT_TILE_FIRST) ? "First" : "Simple", + tile->quantIdxY, tile->quantIdxCb, tile->quantIdxCr, tile->xIdx, tile->yIdx, tile->flags, tile->quality, tile->yLen, tile->cbLen, tile->crLen, tile->tailLen); region = &(progressive->region); @@ -825,8 +830,6 @@ int progressive_decompress_tile_first(PROGRESSIVE_CONTEXT* progressive, RFX_PROG BufferPool_Return(progressive->bufferPool, pBuffer); - //WLog_Image(progressive->log, WLOG_TRACE, tile->data, 64, 64, 32); - return 1; } @@ -1134,10 +1137,8 @@ int progressive_decompress_tile_upgrade(PROGRESSIVE_CONTEXT* progressive, RFX_PR tile->pass++; -#if 0 - WLog_INFO(TAG, "ProgressiveTileUpgrade: pass: %d quantIdx Y: %d Cb: %d Cr: %d xIdx: %d yIdx: %d quality: %d ySrlLen: %d yRawLen: %d cbSrlLen: %d cbRawLen: %d crSrlLen: %d crRawLen: %d", + WLog_DBG(TAG, "ProgressiveTileUpgrade: pass: %d quantIdx Y: %d Cb: %d Cr: %d xIdx: %d yIdx: %d quality: %d ySrlLen: %d yRawLen: %d cbSrlLen: %d cbRawLen: %d crSrlLen: %d crRawLen: %d", tile->pass, tile->quantIdxY, tile->quantIdxCb, tile->quantIdxCr, tile->xIdx, tile->yIdx, tile->quality, tile->ySrlLen, tile->yRawLen, tile->cbSrlLen, tile->cbRawLen, tile->crSrlLen, tile->crRawLen); -#endif region = &(progressive->region); @@ -1246,8 +1247,6 @@ int progressive_decompress_tile_upgrade(PROGRESSIVE_CONTEXT* progressive, RFX_PR BufferPool_Return(progressive->bufferPool, pBuffer); - //WLog_Image(progressive->log, WLOG_TRACE, tile->data, 64, 64, 32); - return 1; } @@ -1281,7 +1280,7 @@ int progressive_process_tiles(PROGRESSIVE_CONTEXT* progressive, BYTE* blocks, UI blockLen = *((UINT32*) &block[boffset + 2]); /* blockLen (4 bytes) */ boffset += 6; - //WLog_INFO(TAG, "%s", progressive_get_block_type_string(blockType)); + //WLog_DBG(TAG, "%s", progressive_get_block_type_string(blockType)); if ((blocksLen - offset) < blockLen) return -1003; @@ -1507,6 +1506,11 @@ int progressive_process_tiles(PROGRESSIVE_CONTEXT* progressive, BYTE* blocks, UI if (offset != blocksLen) return -1041; + if (count != region->numTiles) + { + WLog_WARN(TAG, "numTiles inconsistency: actual: %d, expected: %d\n", count, region->numTiles); + } + for (index = 0; index < region->numTiles; index++) { tile = tiles[index]; @@ -1537,6 +1541,14 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN BYTE* block; BYTE* blocks; UINT16 index; + UINT16 boxLeft; + UINT16 boxTop; + UINT16 boxRight; + UINT16 boxBottom; + UINT16 idxLeft; + UINT16 idxTop; + UINT16 idxRight; + UINT16 idxBottom; UINT32 boffset; UINT16 blockType; UINT32 blockLen; @@ -1573,7 +1585,6 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN blockType = *((UINT16*) &block[boffset + 0]); /* blockType (2 bytes) */ blockLen = *((UINT32*) &block[boffset + 2]); /* blockLen (4 bytes) */ boffset += 6; - //WLog_INFO(TAG, "%s", progressive_get_block_type_string(blockType)); if ((blocksLen - offset) < blockLen) return -1003; @@ -1582,6 +1593,8 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN { case PROGRESSIVE_WBT_SYNC: + WLog_DBG(TAG, "ProgressiveSync"); + sync.blockType = blockType; sync.blockLen = blockLen; @@ -1612,6 +1625,9 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN frameBegin.regionCount = (UINT32) *((UINT16*) &block[boffset + 4]); /* regionCount (2 bytes) */ boffset += 6; + WLog_DBG(TAG, "ProgressiveFrameBegin: frameIndex: %d regionCount: %d", + frameBegin.frameIndex, frameBegin.regionCount); + /** * If the number of elements specified by the regionCount field is * larger than the actual number of elements in the regions field, @@ -1622,6 +1638,8 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN case PROGRESSIVE_WBT_FRAME_END: + WLog_DBG(TAG, "ProgressiveFrameEnd"); + frameEnd.blockType = blockType; frameEnd.blockLen = blockLen; @@ -1646,6 +1664,13 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN if (context.tileSize != 64) return -1010; + WLog_DBG(TAG, "ProgressiveContext: flags: 0x%02X", context.flags); + + if (!(context.flags & RFX_SUBBAND_DIFFING)) + { + WLog_WARN(TAG, "RFX_SUBBAND_DIFFING is not set"); + } + break; case PROGRESSIVE_WBT_REGION: @@ -1755,11 +1780,11 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN if ((blockLen - boffset) < region->tileDataSize) return -1021; - if (region->numTiles > progressive->cTiles) + if (progressive->cTiles < surface->gridSize) { progressive->tiles = (RFX_PROGRESSIVE_TILE**) realloc(progressive->tiles, - region->numTiles * sizeof(RFX_PROGRESSIVE_TILE*)); - progressive->cTiles = region->numTiles; + surface->gridSize * sizeof(RFX_PROGRESSIVE_TILE*)); + progressive->cTiles = surface->gridSize; } region->tiles = progressive->tiles; @@ -1767,14 +1792,67 @@ int progressive_decompress(PROGRESSIVE_CONTEXT* progressive, BYTE* pSrcData, UIN if (!region->tiles) return -1; - //WLog_INFO(TAG, "numRects: %d numTiles: %d numQuant: %d numProgQuant: %d", - // region->numRects, region->numTiles, region->numQuant, region->numProgQuant); + WLog_DBG(TAG, "ProgressiveRegion: numRects: %d numTiles: %d tileDataSize: %d flags: 0x%02X numQuant: %d numProgQuant: %d", + region->numRects, region->numTiles, region->tileDataSize, region->flags, region->numQuant, region->numProgQuant); + + if (!(region->flags & RFX_DWT_REDUCE_EXTRAPOLATE)) + { + WLog_WARN(TAG, "RFX_DWT_REDUCE_EXTRAPOLATE is not set"); + } + + boxLeft = surface->gridWidth; + boxTop = surface->gridHeight; + boxRight = 0; + boxBottom = 0; + + for (index = 0; index < region->numRects; index++) + { + rect = &(region->rects[index]); + + idxLeft = rect->x / 64; + idxTop = rect->y / 64; + idxRight = (rect->x + rect->width + 63) / 64; + idxBottom = (rect->y + rect->height + 63) / 64; + + if (idxLeft < boxLeft) + boxLeft = idxLeft; + + if (idxTop < boxTop) + boxTop = idxTop; + + if (idxRight > boxRight) + boxRight = idxRight; + + if (idxBottom > boxBottom) + boxBottom = idxBottom; + + WLog_DBG(TAG, "rect[%d]: x: %d y: %d w: %d h: %d", + index, rect->x, rect->y, rect->width, rect->height); + } status = progressive_process_tiles(progressive, &block[boffset], region->tileDataSize, surface); if (status < 0) return status; + region->numTiles = 0; + + for (index = 0; index < surface->gridSize; index++) + { + RFX_PROGRESSIVE_TILE* tile = &(surface->tiles[index]); + + if (!tile->data) + continue; + + if ((tile->xIdx < boxLeft) || (tile->xIdx > boxRight)) + continue; + + if ((tile->yIdx < boxTop) || (tile->yIdx > boxBottom)) + continue; + + region->tiles[region->numTiles++] = tile; + } + boffset += (UINT32) status; break; @@ -1817,8 +1895,6 @@ PROGRESSIVE_CONTEXT* progressive_context_new(BOOL Compressor) { progressive->Compressor = Compressor; - progressive->log = WLog_Get(TAG); - progressive->bufferPool = BufferPool_New(TRUE, (8192 + 32) * 3, 16); progressive->cRects = 64; diff --git a/libfreerdp/codec/rfx.c b/libfreerdp/codec/rfx.c index 54e869977..c4ba2d3f8 100644 --- a/libfreerdp/codec/rfx.c +++ b/libfreerdp/codec/rfx.c @@ -61,6 +61,9 @@ #define RFX_INIT_SIMD(_rfx_context) do { } while (0) #endif +#define RFX_KEY "Software\\"FREERDP_VENDOR_STRING"\\" \ + FREERDP_PRODUCT_STRING"\\RemoteFX" + /** * The quantization values control the compression rate and quality. The value * range is between 6 and 15. The higher value, the higher compression rate @@ -251,7 +254,7 @@ RFX_CONTEXT* rfx_context_new(BOOL encoder) * dwt_buffer: 32 * 32 * 2 * 2 * sizeof(INT16) = 8192, maximum sub-band width is 32 * * Additionally we add 32 bytes (16 in front and 16 at the back of the buffer) - * in order to allow optimized functions (SEE, NEON) to read from positions + * in order to allow optimized functions (SEE, NEON) to read from positions * that are actually in front/beyond the buffer. Offset calculations are * performed at the BufferPool_Take function calls in rfx_encode/decode.c. * @@ -284,7 +287,7 @@ RFX_CONTEXT* rfx_context_new(BOOL encoder) priv->MinThreadCount = sysinfo.dwNumberOfProcessors; priv->MaxThreadCount = 0; - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\RemoteFX"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, RFX_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { @@ -328,15 +331,15 @@ RFX_CONTEXT* rfx_context_new(BOOL encoder) /* create profilers for default decoding routines */ rfx_profiler_create(context); - + /* set up default routines */ - context->quantization_decode = rfx_quantization_decode; - context->quantization_encode = rfx_quantization_encode; + context->quantization_decode = rfx_quantization_decode; + context->quantization_encode = rfx_quantization_encode; context->dwt_2d_decode = rfx_dwt_2d_decode; context->dwt_2d_encode = rfx_dwt_2d_encode; RFX_INIT_SIMD(context); - + context->state = RFX_STATE_SEND_HEADERS; return context; @@ -514,7 +517,7 @@ static BOOL rfx_process_message_channels(RFX_CONTEXT* context, wStream* s) Stream_Read_UINT8(s, numChannels); /* numChannels (1 byte), must bet set to 0x01 */ - /* In RDVH sessions, numChannels will represent the number of virtual monitors + /* In RDVH sessions, numChannels will represent the number of virtual monitors * configured and does not always be set to 0x01 as [MS-RDPRFX] said. */ if (numChannels < 1) @@ -966,10 +969,9 @@ static BOOL rfx_process_message_tileset(RFX_CONTEXT* context, RFX_MESSAGE* messa WaitForThreadpoolWorkCallbacks(work_objects[i], FALSE); CloseThreadpoolWork(work_objects[i]); } - - free(work_objects); - free(params); } + free(work_objects); + free(params); for (i = 0; i < message->numTiles; i++) { diff --git a/libfreerdp/codec/test/TestFreeRDPCodecPlanar.c b/libfreerdp/codec/test/TestFreeRDPCodecPlanar.c index b234af3a2..11e15a842 100644 --- a/libfreerdp/codec/test/TestFreeRDPCodecPlanar.c +++ b/libfreerdp/codec/test/TestFreeRDPCodecPlanar.c @@ -2960,9 +2960,14 @@ int test_individual_planes_encoding_rle() CopyMemory(planar->planes[1], (BYTE*) TEST_64X64_RED_PLANE, planeSize); /* Red */ CopyMemory(planar->planes[2], (BYTE*) TEST_64X64_GREEN_PLANE, planeSize); /* Green */ CopyMemory(planar->planes[3], (BYTE*) TEST_64X64_BLUE_PLANE, planeSize); /* Blue */ - freerdp_bitmap_planar_delta_encode_plane(planar->planes[1], width, height, planar->deltaPlanes[1]); /* Red */ - freerdp_bitmap_planar_delta_encode_plane(planar->planes[2], width, height, planar->deltaPlanes[2]); /* Green */ - freerdp_bitmap_planar_delta_encode_plane(planar->planes[3], width, height, planar->deltaPlanes[3]); /* Blue */ + + if (!freerdp_bitmap_planar_delta_encode_plane(planar->planes[1], width, height, planar->deltaPlanes[1]) || /* Red */ + !freerdp_bitmap_planar_delta_encode_plane(planar->planes[2], width, height, planar->deltaPlanes[2]) || /* Green */ + !freerdp_bitmap_planar_delta_encode_plane(planar->planes[3], width, height, planar->deltaPlanes[3])) /* Blue */ + { + return -1; + } + pOutput = planar->rlePlanesBuffer; availableSize = planeSize * 3; /* Red */ @@ -3101,11 +3106,15 @@ int TestFreeRDPCodecPlanar(int argc, char* argv[]) width = i; height = i; whiteBitmap = (BYTE*) malloc(width * height * 4); + if (!whiteBitmap) + return -1; FillMemory(whiteBitmap, width * height * 4, 0xFF); fill_bitmap_alpha_channel(whiteBitmap, width, height, 0x00); compressedBitmap = freerdp_bitmap_compress_planar(planar, whiteBitmap, format, width, height, width * 4, NULL, &dstSize); - decompressedBitmap = (BYTE*) malloc(width * height * 4); - ZeroMemory(decompressedBitmap, width * height * 4); + + decompressedBitmap = (BYTE*) calloc(width * height, 4); + if (!decompressedBitmap) + return -1; pDstData = decompressedBitmap; @@ -3138,12 +3147,14 @@ int TestFreeRDPCodecPlanar(int argc, char* argv[]) { width = i; height = i; - blackBitmap = (BYTE*) malloc(width * height * 4); - ZeroMemory(blackBitmap, width * height * 4); + blackBitmap = (BYTE*) calloc(width * height, 4); + if (!blackBitmap) + return -1; fill_bitmap_alpha_channel(blackBitmap, width, height, 0x00); compressedBitmap = freerdp_bitmap_compress_planar(planar, blackBitmap, format, width, height, width * 4, NULL, &dstSize); - decompressedBitmap = (BYTE*) malloc(width * height * 4); - ZeroMemory(decompressedBitmap, width * height * 4); + decompressedBitmap = (BYTE*) calloc(width * height, 4); + if (!decompressedBitmap) + return -1; pDstData = decompressedBitmap; @@ -3179,8 +3190,9 @@ int TestFreeRDPCodecPlanar(int argc, char* argv[]) height = 64; compressedBitmap = freerdp_bitmap_compress_planar(planar, (BYTE*) TEST_RLE_BITMAP_EXPERIMENTAL_01, format, width, height, width * 4, NULL, &dstSize); - decompressedBitmap = (BYTE*) malloc(width * height * 4); - ZeroMemory(decompressedBitmap, width * height * 4); + decompressedBitmap = (BYTE*) calloc(width * height, 4); + if (!decompressedBitmap) + return -1; pDstData = decompressedBitmap; @@ -3217,8 +3229,9 @@ int TestFreeRDPCodecPlanar(int argc, char* argv[]) height = 64; compressedBitmap = freerdp_bitmap_compress_planar(planar, (BYTE*) TEST_RLE_BITMAP_EXPERIMENTAL_02, format, width, height, width * 4, NULL, &dstSize); - decompressedBitmap = (BYTE*) malloc(width * height * 4); - ZeroMemory(decompressedBitmap, width * height * 4); + decompressedBitmap = (BYTE*) calloc(width * height, 4); + if (!decompressedBitmap) + return -1; pDstData = decompressedBitmap; @@ -3262,8 +3275,9 @@ int TestFreeRDPCodecPlanar(int argc, char* argv[]) height = 64; compressedBitmap = freerdp_bitmap_compress_planar(planar, (BYTE*) TEST_RLE_BITMAP_EXPERIMENTAL_03, format, width, height, width * 4, NULL, &dstSize); - decompressedBitmap = (BYTE*) malloc(width * height * 4); - ZeroMemory(decompressedBitmap, width * height * 4); + decompressedBitmap = (BYTE*) calloc(width * height, 4); + if (!decompressedBitmap) + return -1; pDstData = decompressedBitmap; diff --git a/libfreerdp/codec/test/TestFreeRDPCodecProgressive.c b/libfreerdp/codec/test/TestFreeRDPCodecProgressive.c index fe84a418c..60d3b34cf 100644 --- a/libfreerdp/codec/test/TestFreeRDPCodecProgressive.c +++ b/libfreerdp/codec/test/TestFreeRDPCodecProgressive.c @@ -134,6 +134,16 @@ static int g_Height = 0; static int g_DstStep = 0; static BYTE* g_DstData = NULL; +static void sample_file_free(EGFX_SAMPLE_FILE* file) +{ + if (!file) + return; + + free(file->buffer); + file->buffer = NULL; + file->size = 0; +} + static void test_fill_image_alpha_channel(BYTE* data, int width, int height, BYTE value) { int i, j; @@ -258,8 +268,11 @@ BYTE* test_progressive_load_file(char* path, char* file, UINT32* size) char* filename; filename = GetCombinedPath(path, file); + if (!filename) + return NULL; fp = fopen(filename, "r"); + free(filename); if (!fp) return NULL; @@ -271,12 +284,18 @@ BYTE* test_progressive_load_file(char* path, char* file, UINT32* size) buffer = (BYTE*) malloc(*size); if (!buffer) + { + fclose(fp); return NULL; + } if (fread(buffer, *size, 1, fp) != 1) + { + free(buffer); + fclose(fp); return NULL; + } - free(filename); fclose(fp); return buffer; @@ -931,6 +950,7 @@ int test_progressive_decode(PROGRESSIVE_CONTEXT* progressive, EGFX_SAMPLE_FILE f int test_progressive_ms_sample(char* ms_sample_path) { + int i, j, k; int count; int status; EGFX_SAMPLE_FILE files[3][4][4]; @@ -947,12 +967,34 @@ int test_progressive_ms_sample(char* ms_sample_path) status = test_progressive_load_files(ms_sample_path, files); if (status < 0) + { + for(i=0; i<3; i++) + { + for (j=0; j<4; j++) + { + for (k=0; k<4; k++) + sample_file_free(&files[i][j][k]); + } + } + return -1; + } status = test_progressive_load_bitmaps(ms_sample_path, bitmaps); if (status < 0) + { + for(i=0; i<3; i++) + { + for (j=0; j<4; j++) + { + for (k=0; k<4; k++) + sample_file_free(&files[i][j][k]); + } + } + return -1; + } count = 4; @@ -1000,6 +1042,18 @@ int test_progressive_ms_sample(char* ms_sample_path) progressive_context_free(progressive); + for(i=0; i<3; i++) + { + for (j=0; j<4; j++) + { + for (k=0; k<4; k++) + { + sample_file_free(&bitmaps[i][j][k]); + sample_file_free(&files[i][j][k]); + } + } + } + _aligned_free(g_DstData); return 0; @@ -1009,7 +1063,12 @@ int TestFreeRDPCodecProgressive(int argc, char* argv[]) { char* ms_sample_path; - ms_sample_path = _strdup("/tmp/EGFX_PROGRESSIVE_MS_SAMPLE"); + ms_sample_path = GetKnownSubPath(KNOWN_PATH_TEMP, "EGFX_PROGRESSIVE_MS_SAMPLE"); + if (!ms_sample_path) + { + printf("Memory allocation failed\n"); + return -1; + } if (PathFileExistsA(ms_sample_path)) return test_progressive_ms_sample(ms_sample_path); diff --git a/libfreerdp/codec/zgfx.c b/libfreerdp/codec/zgfx.c index 2d66e8f54..604947988 100644 --- a/libfreerdp/codec/zgfx.c +++ b/libfreerdp/codec/zgfx.c @@ -337,6 +337,8 @@ int zgfx_decompress(ZGFX_CONTEXT* zgfx, BYTE* pSrcData, UINT32 SrcSize, BYTE** p status = zgfx_decompress_segment(zgfx, &pSrcData[1], SrcSize - 1); *ppDstData = (BYTE*) malloc(zgfx->OutputCount); + if (!*ppDstData) + return -1; *pDstSize = zgfx->OutputCount; CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount); @@ -355,6 +357,8 @@ int zgfx_decompress(ZGFX_CONTEXT* zgfx, BYTE* pSrcData, UINT32 SrcSize, BYTE** p uncompressedSize = *((UINT32*) &pSrcData[3]); /* uncompressedSize (4 bytes) */ pConcatenated = (BYTE*) malloc(uncompressedSize); + if (!pConcatenated) + return -1; *ppDstData = pConcatenated; *pDstSize = uncompressedSize; diff --git a/libfreerdp/common/addin.c b/libfreerdp/common/addin.c index f5689c385..52197b418 100644 --- a/libfreerdp/common/addin.c +++ b/libfreerdp/common/addin.c @@ -46,11 +46,17 @@ LPSTR freerdp_get_library_install_path() cchPath = cchInstallPrefix + cchLibraryPath + 2; pszPath = (LPSTR) malloc(cchPath + 1); + if (!pszPath) + return NULL; CopyMemory(pszPath, pszInstallPrefix, cchInstallPrefix); pszPath[cchInstallPrefix] = '\0'; - NativePathCchAppendA(pszPath, cchPath + 1, pszLibraryPath); + if (FAILED(NativePathCchAppendA(pszPath, cchPath + 1, pszLibraryPath))) + { + free(pszPath); + return NULL; + } return pszPath; } @@ -69,11 +75,17 @@ LPSTR freerdp_get_dynamic_addin_install_path() cchPath = cchInstallPrefix + cchAddinPath + 2; pszPath = (LPSTR) malloc(cchPath + 1); + if (!pszPath) + return NULL; CopyMemory(pszPath, pszInstallPrefix, cchInstallPrefix); pszPath[cchInstallPrefix] = '\0'; - NativePathCchAppendA(pszPath, cchPath + 1, pszAddinPath); + if (FAILED(NativePathCchAppendA(pszPath, cchPath + 1, pszAddinPath))) + { + free(pszPath); + return NULL; + } return pszPath; } @@ -98,7 +110,7 @@ void* freerdp_load_dynamic_addin(LPCSTR pszFileName, LPCSTR pszPath, LPCSTR pszE bHasExt = TRUE; cchFileName = strlen(pszFileName); - if (PathCchFindExtensionA(pszFileName, cchFileName + 1, &pszExt) != S_OK) + if (FAILED(PathCchFindExtensionA(pszFileName, cchFileName + 1, &pszExt))) { pszExt = PathGetSharedLibraryExtensionA(PATH_SHARED_LIB_EXT_WITH_DOT); cchExt = strlen(pszExt); @@ -106,20 +118,39 @@ void* freerdp_load_dynamic_addin(LPCSTR pszFileName, LPCSTR pszPath, LPCSTR pszE } pszAddinInstallPath = freerdp_get_dynamic_addin_install_path(); + if (!pszAddinInstallPath) + return NULL; cchAddinInstallPath = strlen(pszAddinInstallPath); cchFilePath = cchAddinInstallPath + cchFileName + 32; pszFilePath = (LPSTR) malloc(cchFilePath + 1); + if (!pszFilePath) + { + free(pszAddinInstallPath); + return NULL; + } if (bHasExt) { pszAddinFile = _strdup(pszFileName); + if (!pszAddinFile) + { + free(pszAddinInstallPath); + free(pszFilePath); + return NULL; + } cchAddinFile = strlen(pszAddinFile); } else { cchAddinFile = cchFileName + cchExt + 2 + sizeof(CMAKE_SHARED_LIBRARY_PREFIX); pszAddinFile = (LPSTR) malloc(cchAddinFile + 1); + if (!pszAddinFile) + { + free(pszAddinInstallPath); + free(pszFilePath); + return NULL; + } sprintf_s(pszAddinFile, cchAddinFile, CMAKE_SHARED_LIBRARY_PREFIX"%s%s", pszFileName, pszExt); cchAddinFile = strlen(pszAddinFile); } @@ -161,6 +192,8 @@ void* freerdp_load_dynamic_channel_addin_entry(LPCSTR pszName, LPSTR pszSubsyste { cchFileName += strlen(pszName) + strlen(pszSubsystem) + strlen(pszType) + strlen(pszExtension); pszFileName = (LPSTR) malloc(cchFileName); + if (!pszFileName) + return NULL; sprintf_s(pszFileName, cchFileName, "%s%s-client-%s-%s.%s", pszPrefix, pszName, pszSubsystem, pszType, pszExtension); cchFileName = strlen(pszFileName); } @@ -168,6 +201,9 @@ void* freerdp_load_dynamic_channel_addin_entry(LPCSTR pszName, LPSTR pszSubsyste { cchFileName += strlen(pszName) + strlen(pszSubsystem) + strlen(pszExtension); pszFileName = (LPSTR) malloc(cchFileName); + if (!pszFileName) + return NULL; + sprintf_s(pszFileName, cchFileName, "%s%s-client-%s.%s", pszPrefix, pszName, pszSubsystem, pszExtension); cchFileName = strlen(pszFileName); } @@ -175,6 +211,9 @@ void* freerdp_load_dynamic_channel_addin_entry(LPCSTR pszName, LPSTR pszSubsyste { cchFileName += strlen(pszName) + strlen(pszExtension); pszFileName = (LPSTR) malloc(cchFileName); + if (!pszFileName) + return NULL; + sprintf_s(pszFileName, cchFileName, "%s%s-client.%s", pszPrefix, pszName, pszExtension); cchFileName = strlen(pszFileName); } @@ -192,6 +231,11 @@ void* freerdp_load_dynamic_channel_addin_entry(LPCSTR pszName, LPSTR pszSubsyste cchEntryName = 64 + strlen(pszName); pszEntryName = (LPSTR) malloc(cchEntryName + 1); + if (!pszEntryName) + { + free(pszFileName); + return NULL; + } sprintf_s(pszEntryName, cchEntryName + 1, "freerdp_%s_client_subsystem_entry", pszName); entry = freerdp_load_dynamic_addin(pszFileName, NULL, pszEntryName); @@ -199,29 +243,22 @@ void* freerdp_load_dynamic_channel_addin_entry(LPCSTR pszName, LPSTR pszSubsyste free(pszEntryName); free(pszFileName); - if (entry) - return entry; + return entry; } + + /* channel add-in */ + + if (dwFlags & FREERDP_ADDIN_CHANNEL_STATIC) + entry = freerdp_load_dynamic_addin(pszFileName, NULL, "VirtualChannelEntry"); + else if (dwFlags & FREERDP_ADDIN_CHANNEL_DYNAMIC) + entry = freerdp_load_dynamic_addin(pszFileName, NULL, "DVCPluginEntry"); + else if (dwFlags & FREERDP_ADDIN_CHANNEL_DEVICE) + entry = freerdp_load_dynamic_addin(pszFileName, NULL, "DeviceServiceEntry"); else - { - /* channel add-in */ + entry = freerdp_load_dynamic_addin(pszFileName, NULL, pszType); - if (dwFlags & FREERDP_ADDIN_CHANNEL_STATIC) - entry = freerdp_load_dynamic_addin(pszFileName, NULL, "VirtualChannelEntry"); - else if (dwFlags & FREERDP_ADDIN_CHANNEL_DYNAMIC) - entry = freerdp_load_dynamic_addin(pszFileName, NULL, "DVCPluginEntry"); - else if (dwFlags & FREERDP_ADDIN_CHANNEL_DEVICE) - entry = freerdp_load_dynamic_addin(pszFileName, NULL, "DeviceServiceEntry"); - else - entry = freerdp_load_dynamic_addin(pszFileName, NULL, pszType); - - free(pszFileName); - - if (entry) - return entry; - } - - return NULL; + free(pszFileName); + return entry; } static FREERDP_LOAD_CHANNEL_ADDIN_ENTRY_FN freerdp_load_static_channel_addin_entry = NULL; diff --git a/libfreerdp/common/assistance.c b/libfreerdp/common/assistance.c index 717edc9fc..da46d6f72 100644 --- a/libfreerdp/common/assistance.c +++ b/libfreerdp/common/assistance.c @@ -140,9 +140,11 @@ int freerdp_assistance_parse_address_list(rdpAssistanceFile* file, char* list) } tokens = (char**) malloc(sizeof(char*) * count); - if (!tokens) + { + free(str); return -1; + } count = 0; tokens[count++] = str; @@ -161,12 +163,7 @@ int freerdp_assistance_parse_address_list(rdpAssistanceFile* file, char* list) file->MachinePorts = (UINT32*) calloc(count, sizeof(UINT32)); if (!file->MachineAddresses || !file->MachinePorts) - { - free(file->MachineAddresses); - free(file->MachinePorts); - free(tokens); - return -1; - } + goto out; for (i = 0; i < count; i++) { @@ -177,10 +174,7 @@ int freerdp_assistance_parse_address_list(rdpAssistanceFile* file, char* list) q = strchr(p, ':'); if (!q) - { - free(tokens); - return -1; - } + goto out; q[0] = '\0'; q++; @@ -189,7 +183,7 @@ int freerdp_assistance_parse_address_list(rdpAssistanceFile* file, char* list) file->MachinePorts[i] = (UINT32) atoi(q); if (!file->MachineAddresses[i]) - return -1; + goto out; q[-1] = ':'; } @@ -209,26 +203,43 @@ int freerdp_assistance_parse_address_list(rdpAssistanceFile* file, char* list) q = strchr(p, ':'); if (!q) - { - free(tokens); - return -1; - } + goto out; q[0] = '\0'; q++; + if (file->MachineAddress) + free(file->MachineAddress); file->MachineAddress = _strdup(p); + if (!file->MachineAddress) + goto out; file->MachinePort = (UINT32) atoi(q); if (!file->MachineAddress) - return -1; + goto out; break; } free(tokens); - + free(str); return 1; +out: + if (file->MachineAddresses) + { + for (i=0; iMachineAddresses[i]); + } + free (file->MachineAddresses); + free (file->MachinePorts); + + file->MachineCount = 0; + file->MachinePorts = NULL; + file->MachineAddresses = NULL; + + free(tokens); + free(str); + return -1; } int freerdp_assistance_parse_connection_string1(rdpAssistanceFile* file) @@ -238,6 +249,7 @@ int freerdp_assistance_parse_connection_string1(rdpAssistanceFile* file) int count; int length; char* tokens[8]; + int ret; /** * ,,,, @@ -298,10 +310,13 @@ int freerdp_assistance_parse_connection_string1(rdpAssistanceFile* file) if (!file->RASpecificParams) return -1; - freerdp_assistance_parse_address_list(file, tokens[2]); + ret = freerdp_assistance_parse_address_list(file, tokens[2]); free(str); + if (ret != 1) + return -1; + return 1; } @@ -323,96 +338,92 @@ int freerdp_assistance_parse_connection_string1(rdpAssistanceFile* file) int freerdp_assistance_parse_connection_string2(rdpAssistanceFile* file) { - char* p; - char* q; - int port; char* str; - size_t length; + char* tag; + char* end; + char* p; + int ret = -1; + + + str = file->ConnectionString2; + + if (!strstr(str, "")) + return -1; + + if (!strstr(str, "")) + return -1; str = _strdup(file->ConnectionString2); - if (!str) return -1; - p = strstr(str, ""); + if (!(tag = strstr(str, ") */ + end = strstr(tag, "/>"); + if (!end) + goto out_fail; - p = strstr(str, ""); - - if (!p) - return -1; - - /* Auth String Node () */ - - p = strstr(str, "RASpecificParams); file->RASpecificParams = (char*) malloc(length + 1); - if (!file->RASpecificParams) - return -1; + goto out_fail; CopyMemory(file->RASpecificParams, p, length); file->RASpecificParams[length] = '\0'; - - p += length; } - if (p) - p = strstr(p, "ID=\""); - else - p = _strdup("ID=\""); - + p = strstr(tag, "ID=\""); if (p) { + char *q; + size_t length; p += sizeof("ID=\"") - 1; q = strchr(p, '"'); if (!q) - return -1; + goto out_fail; length = q - p; free(file->RASessionId); file->RASessionId = (char*) malloc(length + 1); - if (!file->RASessionId) - return -1; + goto out_fail; CopyMemory(file->RASessionId, p, length); file->RASessionId[length] = '\0'; - - p += length; } + *end = '/'; - if (p) - p = strstr(p, "MachineAddress) + free(file->MachineAddress); file->MachineAddress = _strdup(p); + if (!file->MachineAddress) + goto out_fail; file->MachinePort = (UINT32) port; break; } @@ -449,9 +464,11 @@ int freerdp_assistance_parse_connection_string2(rdpAssistanceFile* file) p = strstr(q, "RASessionId) + if (!file->RASessionId || !file->MachineAddress) return -1; - freerdp_set_param_string(settings, FreeRDP_RemoteAssistanceSessionId, file->RASessionId); - - if (file->RCTicket) - freerdp_set_param_string(settings, FreeRDP_RemoteAssistanceRCTicket, file->RCTicket); - - if (file->PassStub) - freerdp_set_param_string(settings, FreeRDP_RemoteAssistancePassStub, file->PassStub); - - if (!file->MachineAddress) + if (freerdp_set_param_string(settings, FreeRDP_RemoteAssistanceSessionId, file->RASessionId) != 0) + return -1; + + if (file->RCTicket && (freerdp_set_param_string(settings, FreeRDP_RemoteAssistanceRCTicket, file->RCTicket) != 0)) + return -1; + + if (file->PassStub && (freerdp_set_param_string(settings, FreeRDP_RemoteAssistancePassStub, file->PassStub) != 0)) + return -1; + + if (freerdp_set_param_string(settings, FreeRDP_ServerHostname, file->MachineAddress) != 0) return -1; - freerdp_set_param_string(settings, FreeRDP_ServerHostname, file->MachineAddress); freerdp_set_param_uint32(settings, FreeRDP_ServerPort, file->MachinePort); freerdp_target_net_addresses_free(settings); @@ -1173,16 +1192,7 @@ int freerdp_client_populate_settings_from_assistance_file(rdpAssistanceFile* fil rdpAssistanceFile* freerdp_assistance_file_new() { - rdpAssistanceFile* file; - - file = (rdpAssistanceFile*) calloc(1, sizeof(rdpAssistanceFile)); - - if (file) - { - - } - - return file; + return (rdpAssistanceFile*) calloc(1, sizeof(rdpAssistanceFile)); } void freerdp_assistance_file_free(rdpAssistanceFile* file) diff --git a/libfreerdp/common/settings.c b/libfreerdp/common/settings.c index f095d5dd2..b31d3b242 100644 --- a/libfreerdp/common/settings.c +++ b/libfreerdp/common/settings.c @@ -51,7 +51,8 @@ int freerdp_addin_set_argument(ADDIN_ARGV* args, char* argument) return -1; args->argv = new_argv; args->argc++; - args->argv[args->argc - 1] = _strdup(argument); + if (!(args->argv[args->argc - 1] = _strdup(argument))) + return -1; return 0; } @@ -66,7 +67,8 @@ int freerdp_addin_replace_argument(ADDIN_ARGV* args, char* previous, char* argum if (strcmp(args->argv[i], previous) == 0) { free(args->argv[i]); - args->argv[i] = _strdup(argument); + if (!(args->argv[i] = _strdup(argument))) + return -1; return 1; } @@ -77,7 +79,8 @@ int freerdp_addin_replace_argument(ADDIN_ARGV* args, char* previous, char* argum return -1; args->argv = new_argv; args->argc++; - args->argv[args->argc - 1] = _strdup(argument); + if (!(args->argv[args->argc - 1] = _strdup(argument))) + return -1; return 0; } @@ -92,6 +95,8 @@ int freerdp_addin_set_argument_value(ADDIN_ARGV* args, char* option, char* value length = strlen(option) + strlen(value) + 1; str = (char*) malloc(length + 1); + if (!str) + return -1; sprintf_s(str, length + 1, "%s:%s", option, value); for (i = 0; i < args->argc; i++) @@ -112,7 +117,11 @@ int freerdp_addin_set_argument_value(ADDIN_ARGV* args, char* option, char* value new_argv = (char**) realloc(args->argv, sizeof(char*) * (args->argc + 1)); if (!new_argv) + { + free(str); return -1; + } + args->argv = new_argv; args->argc++; args->argv[args->argc - 1] = str; @@ -129,6 +138,8 @@ int freerdp_addin_replace_argument_value(ADDIN_ARGV* args, char* previous, char* length = strlen(option) + strlen(value) + 1; str = (char*) malloc(length + 1); + if (!str) + return -1; sprintf_s(str, length + 1, "%s:%s", option, value); for (i = 0; i < args->argc; i++) @@ -144,7 +155,10 @@ int freerdp_addin_replace_argument_value(ADDIN_ARGV* args, char* previous, char* new_argv = (char**) realloc(args->argv, sizeof(char*) * (args->argc + 1)); if (!new_argv) + { + free(str); return -1; + } args->argv = new_argv; args->argc++; args->argv[args->argc - 1] = str; @@ -152,10 +166,10 @@ int freerdp_addin_replace_argument_value(ADDIN_ARGV* args, char* previous, char* return 0; } -void freerdp_device_collection_add(rdpSettings* settings, RDPDR_DEVICE* device) +BOOL freerdp_device_collection_add(rdpSettings* settings, RDPDR_DEVICE* device) { if (!settings->DeviceArray) - return; + return FALSE; if (settings->DeviceArraySize < (settings->DeviceCount + 1)) { @@ -166,12 +180,13 @@ void freerdp_device_collection_add(rdpSettings* settings, RDPDR_DEVICE* device) new_array = (RDPDR_DEVICE**) realloc(settings->DeviceArray, new_size * sizeof(RDPDR_DEVICE*)); if (!new_array) - return; + return FALSE; settings->DeviceArray = new_array; settings->DeviceArraySize = new_size; } settings->DeviceArray[settings->DeviceCount++] = device; + return TRUE; } RDPDR_DEVICE* freerdp_device_collection_find(rdpSettings* settings, const char* name) @@ -381,6 +396,9 @@ void freerdp_device_collection_free(rdpSettings* settings) { device = (RDPDR_DEVICE*) settings->DeviceArray[index]; + if (!device) + continue; + free(device->Name); if (settings->DeviceArray[index]->Type == RDPDR_DTYP_FILESYSTEM) @@ -415,10 +433,10 @@ void freerdp_device_collection_free(rdpSettings* settings) settings->DeviceCount = 0; } -void freerdp_static_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel) +BOOL freerdp_static_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel) { if (!settings->StaticChannelArray) - return; + return FALSE; if (settings->StaticChannelArraySize < (settings->StaticChannelCount + 1)) { @@ -429,12 +447,13 @@ void freerdp_static_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* ch new_array = (ADDIN_ARGV**) realloc(settings->StaticChannelArray, new_size * sizeof(ADDIN_ARGV*)); if (!new_array) - return; + return FALSE; settings->StaticChannelArray = new_array; settings->StaticChannelArraySize = new_size; } settings->StaticChannelArray[settings->StaticChannelCount++] = channel; + return TRUE; } ADDIN_ARGV* freerdp_static_channel_collection_find(rdpSettings* settings, const char* name) @@ -491,6 +510,9 @@ void freerdp_static_channel_collection_free(rdpSettings* settings) for (i = 0; i < settings->StaticChannelCount; i++) { + if (!settings->StaticChannelArray[i]) + continue; + for (j = 0; j < settings->StaticChannelArray[i]->argc; j++) free(settings->StaticChannelArray[i]->argv[j]); @@ -505,30 +527,25 @@ void freerdp_static_channel_collection_free(rdpSettings* settings) settings->StaticChannelCount = 0; } -void freerdp_dynamic_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel) +BOOL freerdp_dynamic_channel_collection_add(rdpSettings* settings, ADDIN_ARGV* channel) { if (!settings->DynamicChannelArray) - return; + return FALSE; if (settings->DynamicChannelArraySize < (settings->DynamicChannelCount + 1)) { - UINT32 new_size; ADDIN_ARGV **new_array; - settings->DynamicChannelArraySize *= 2; - settings->DynamicChannelArray = (ADDIN_ARGV**) - realloc(settings->DynamicChannelArray, settings->DynamicChannelArraySize * sizeof(ADDIN_ARGV*)); - - new_size = settings->DynamicChannelArraySize * 2; - new_array = (ADDIN_ARGV**) - realloc(settings->DynamicChannelArray, new_size * sizeof(ADDIN_ARGV*)); + new_array = realloc(settings->DynamicChannelArray, settings->DynamicChannelArraySize * sizeof(ADDIN_ARGV*) * 2); if (!new_array) - return; + return FALSE; + + settings->DynamicChannelArraySize *= 2; settings->DynamicChannelArray = new_array; - settings->DynamicChannelArraySize = new_size; } settings->DynamicChannelArray[settings->DynamicChannelCount++] = channel; + return TRUE; } ADDIN_ARGV* freerdp_dynamic_channel_collection_find(rdpSettings* settings, const char* name) @@ -588,6 +605,9 @@ void freerdp_dynamic_channel_collection_free(rdpSettings* settings) for (i = 0; i < settings->DynamicChannelCount; i++) { + if (!settings->DynamicChannelArray[i]) + continue; + for (j = 0; j < settings->DynamicChannelArray[i]->argc; j++) free(settings->DynamicChannelArray[i]->argv[j]); @@ -2432,231 +2452,191 @@ char* freerdp_get_param_string(rdpSettings* settings, int id) int freerdp_set_param_string(rdpSettings* settings, int id, const char* param) { + char **tmp = NULL; + + if (!param) + return -1; + switch (id) { case FreeRDP_ServerHostname: - free(settings->ServerHostname); - settings->ServerHostname = _strdup(param); + tmp = &settings->ServerHostname; break; case FreeRDP_Username: - free(settings->Username); - settings->Username = _strdup(param); + tmp = &settings->Username; break; case FreeRDP_Password: - free(settings->Password); - settings->Password = _strdup(param); + tmp = &settings->Password; break; case FreeRDP_Domain: - free(settings->Domain); - settings->Domain = _strdup(param); + tmp = &settings->Domain; break; case FreeRDP_PasswordHash: - free(settings->PasswordHash); - settings->PasswordHash = _strdup(param); + tmp = &settings->PasswordHash; break; case FreeRDP_ClientHostname: - free(settings->ClientHostname); - settings->ClientHostname = _strdup(param); + tmp = &settings->ClientHostname; break; case FreeRDP_ClientProductId: - free(settings->ClientProductId); - settings->ClientProductId = _strdup(param); + tmp = &settings->ClientProductId; break; case FreeRDP_AlternateShell: - free(settings->AlternateShell); - settings->AlternateShell = _strdup(param); + tmp = &settings->AlternateShell; break; case FreeRDP_ShellWorkingDirectory: - free(settings->ShellWorkingDirectory); - settings->ShellWorkingDirectory = _strdup(param); + tmp = &settings->ShellWorkingDirectory; break; case FreeRDP_ClientAddress: - free(settings->ClientAddress); - settings->ClientAddress = _strdup(param); + tmp = &settings->ClientAddress; break; case FreeRDP_ClientDir: - free(settings->ClientDir); - settings->ClientDir = _strdup(param); + tmp = &settings->ClientDir; break; case FreeRDP_DynamicDSTTimeZoneKeyName: - free(settings->DynamicDSTTimeZoneKeyName); - settings->DynamicDSTTimeZoneKeyName = _strdup(param); + tmp = &settings->DynamicDSTTimeZoneKeyName; break; case FreeRDP_RemoteAssistanceSessionId: - free(settings->RemoteAssistanceSessionId); - settings->RemoteAssistanceSessionId = _strdup(param); + tmp = &settings->RemoteAssistanceSessionId; break; case FreeRDP_RemoteAssistancePassStub: - free(settings->RemoteAssistancePassStub); - settings->RemoteAssistancePassStub = _strdup(param); + tmp = &settings->RemoteAssistancePassStub; break; case FreeRDP_RemoteAssistancePassword: - free(settings->RemoteAssistancePassword); - settings->RemoteAssistancePassword = _strdup(param); + tmp = &settings->RemoteAssistancePassword; break; case FreeRDP_RemoteAssistanceRCTicket: - free(settings->RemoteAssistanceRCTicket); - settings->RemoteAssistanceRCTicket = _strdup(param); + tmp = &settings->RemoteAssistanceRCTicket; break; case FreeRDP_AuthenticationServiceClass: - free(settings->AuthenticationServiceClass); - settings->AuthenticationServiceClass = _strdup(param); + tmp = &settings->AuthenticationServiceClass; break; case FreeRDP_PreconnectionBlob: - free(settings->PreconnectionBlob); - settings->PreconnectionBlob = _strdup(param); + tmp = &settings->PreconnectionBlob; break; case FreeRDP_KerberosKdc: - free(settings->KerberosKdc); - settings->KerberosKdc = _strdup(param); + tmp = &settings->KerberosKdc; break; case FreeRDP_KerberosRealm: - free(settings->KerberosRealm); - settings->KerberosRealm = _strdup(param); + tmp = &settings->KerberosRealm; break; case FreeRDP_CertificateName: - free(settings->CertificateName); - settings->CertificateName = _strdup(param); + tmp = &settings->CertificateName; break; case FreeRDP_CertificateFile: - free(settings->CertificateFile); - settings->CertificateFile = _strdup(param); + tmp = &settings->CertificateFile; break; case FreeRDP_PrivateKeyFile: - free(settings->PrivateKeyFile); - settings->PrivateKeyFile = _strdup(param); + tmp = &settings->PrivateKeyFile; break; case FreeRDP_RdpKeyFile: - free(settings->RdpKeyFile); - settings->RdpKeyFile = _strdup(param); + tmp = &settings->RdpKeyFile; break; case FreeRDP_WindowTitle: - free(settings->WindowTitle); - settings->WindowTitle = _strdup(param); + tmp = &settings->WindowTitle; break; case FreeRDP_ComputerName: - free(settings->ComputerName); - settings->ComputerName = _strdup(param); + tmp = &settings->ComputerName; break; case FreeRDP_ConnectionFile: - free(settings->ConnectionFile); - settings->ConnectionFile = _strdup(param); + tmp = &settings->ConnectionFile; break; case FreeRDP_AssistanceFile: - free(settings->AssistanceFile); - settings->AssistanceFile = _strdup(param); + tmp = &settings->AssistanceFile; break; case FreeRDP_HomePath: - free(settings->HomePath); - settings->HomePath = _strdup(param); + tmp = &settings->HomePath; break; case FreeRDP_ConfigPath: - free(settings->ConfigPath); - settings->ConfigPath = _strdup(param); + tmp = &settings->ConfigPath; break; case FreeRDP_CurrentPath: - free(settings->CurrentPath); - settings->CurrentPath = _strdup(param); + tmp = &settings->CurrentPath; break; case FreeRDP_DumpRemoteFxFile: - free(settings->DumpRemoteFxFile); - settings->DumpRemoteFxFile = _strdup(param); + tmp = &settings->DumpRemoteFxFile; break; case FreeRDP_PlayRemoteFxFile: - free(settings->PlayRemoteFxFile); - settings->PlayRemoteFxFile = _strdup(param); + tmp = &settings->PlayRemoteFxFile; break; case FreeRDP_GatewayHostname: - free(settings->GatewayHostname); - settings->GatewayHostname = _strdup(param); + tmp = &settings->GatewayHostname; break; case FreeRDP_GatewayUsername: - free(settings->GatewayUsername); - settings->GatewayUsername = _strdup(param); + tmp = &settings->GatewayUsername; break; case FreeRDP_GatewayPassword: - free(settings->GatewayPassword); - settings->GatewayPassword = _strdup(param); + tmp = &settings->GatewayPassword; break; case FreeRDP_GatewayDomain: - free(settings->GatewayDomain); - settings->GatewayDomain = _strdup(param); + tmp = &settings->GatewayDomain; break; case FreeRDP_RemoteApplicationName: - free(settings->RemoteApplicationName); - settings->RemoteApplicationName = _strdup(param); + tmp = &settings->RemoteApplicationName; break; case FreeRDP_RemoteApplicationIcon: - free(settings->RemoteApplicationIcon); - settings->RemoteApplicationIcon = _strdup(param); + tmp = &settings->RemoteApplicationIcon; break; case FreeRDP_RemoteApplicationProgram: - free(settings->RemoteApplicationProgram); - settings->RemoteApplicationProgram = _strdup(param); + tmp = &settings->RemoteApplicationProgram; break; case FreeRDP_RemoteApplicationFile: - free(settings->RemoteApplicationFile); - settings->RemoteApplicationFile = _strdup(param); + tmp = &settings->RemoteApplicationFile; break; case FreeRDP_RemoteApplicationGuid: - free(settings->RemoteApplicationGuid); - settings->RemoteApplicationGuid = _strdup(param); + tmp = &settings->RemoteApplicationGuid; break; case FreeRDP_RemoteApplicationCmdLine: - free(settings->RemoteApplicationCmdLine); - settings->RemoteApplicationCmdLine = _strdup(param); + tmp = &settings->RemoteApplicationCmdLine; break; case FreeRDP_ImeFileName: - free(settings->ImeFileName); - settings->ImeFileName = _strdup(param); + tmp = &settings->ImeFileName; break; case FreeRDP_DrivesToRedirect: - free(settings->DrivesToRedirect); - settings->DrivesToRedirect = _strdup(param); + tmp = &settings->DrivesToRedirect; break; default: @@ -2664,6 +2644,10 @@ int freerdp_set_param_string(rdpSettings* settings, int id, const char* param) return -1; } + free(*tmp); + if (!(*tmp = _strdup(param))) + return -1; + /* Mark field as modified */ settings->SettingsModified[id] = 1; diff --git a/libfreerdp/common/test/TestCommonAssistance.c b/libfreerdp/common/test/TestCommonAssistance.c index 411152508..7c8d977f1 100644 --- a/libfreerdp/common/test/TestCommonAssistance.c +++ b/libfreerdp/common/test/TestCommonAssistance.c @@ -4,9 +4,9 @@ #include -const char* TEST_MSRC_INCIDENT_PASSWORD_TYPE1 = "Password1"; +const char TEST_MSRC_INCIDENT_PASSWORD_TYPE1[] = "Password1"; -static const char* TEST_MSRC_INCIDENT_FILE_TYPE1 = +static const char TEST_MSRC_INCIDENT_FILE_TYPE1[] = "" "" "" "" "exponent, sizeof(key->exponent)); RSA_free(rsa); return key; + out_free_modulus: free(key->Modulus); out_free_rsa: @@ -791,6 +795,8 @@ rdpCertificate* certificate_clone(rdpCertificate* certificate) if (certificate->cert_info.ModulusLength) { _certificate->cert_info.Modulus = (BYTE*) malloc(certificate->cert_info.ModulusLength); + if (!_certificate->cert_info.Modulus) + goto out_fail; CopyMemory(_certificate->cert_info.Modulus, certificate->cert_info.Modulus, certificate->cert_info.ModulusLength); _certificate->cert_info.ModulusLength = certificate->cert_info.ModulusLength; } @@ -798,11 +804,15 @@ rdpCertificate* certificate_clone(rdpCertificate* certificate) if (certificate->x509_cert_chain) { _certificate->x509_cert_chain = (rdpX509CertChain*) malloc(sizeof(rdpX509CertChain)); + if (!_certificate->x509_cert_chain) + goto out_fail; CopyMemory(_certificate->x509_cert_chain, certificate->x509_cert_chain, sizeof(rdpX509CertChain)); if (certificate->x509_cert_chain->count) { _certificate->x509_cert_chain->array = (rdpCertBlob*) calloc(certificate->x509_cert_chain->count, sizeof(rdpCertBlob)); + if (!_certificate->x509_cert_chain->array) + goto out_fail; for (index = 0; index < certificate->x509_cert_chain->count; index++) { @@ -811,6 +821,15 @@ rdpCertificate* certificate_clone(rdpCertificate* certificate) if (certificate->x509_cert_chain->array[index].length) { _certificate->x509_cert_chain->array[index].data = (BYTE*) malloc(certificate->x509_cert_chain->array[index].length); + if (!_certificate->x509_cert_chain->array[index].data) + { + for (--index; index >= 0; --index) + { + if (certificate->x509_cert_chain->array[index].length) + free(_certificate->x509_cert_chain->array[index].data); + } + goto out_fail; + } CopyMemory(_certificate->x509_cert_chain->array[index].data, certificate->x509_cert_chain->array[index].data, _certificate->x509_cert_chain->array[index].length); } @@ -819,6 +838,16 @@ rdpCertificate* certificate_clone(rdpCertificate* certificate) } return _certificate; + +out_fail: + if (_certificate->x509_cert_chain) + { + free(_certificate->x509_cert_chain->array); + free(_certificate->x509_cert_chain); + } + free(_certificate->cert_info.Modulus); + free(_certificate); + return NULL; } /** diff --git a/libfreerdp/core/client.c b/libfreerdp/core/client.c index 5bbe1df79..243a8222d 100644 --- a/libfreerdp/core/client.c +++ b/libfreerdp/core/client.c @@ -240,6 +240,8 @@ int freerdp_channels_post_connect(rdpChannels* channels, freerdp* instance) pChannelClientData->pChannelInitEventProc(pChannelClientData->pInitHandle, CHANNEL_EVENT_CONNECTED, hostname, hostnameLength); name = (char*) malloc(9); + if (!name) + return -1; CopyMemory(name, pChannelOpenData->name, 8); name[8] = '\0'; @@ -452,6 +454,8 @@ int freerdp_channels_disconnect(rdpChannels* channels, freerdp* instance) pChannelOpenData = &channels->openDataList[index]; name = (char*) malloc(9); + if (!name) + return -1; CopyMemory(name, pChannelOpenData->name, 8); name[8] = '\0'; diff --git a/libfreerdp/core/connection.c b/libfreerdp/core/connection.c index ffd0be899..d4d5e23aa 100644 --- a/libfreerdp/core/connection.c +++ b/libfreerdp/core/connection.c @@ -334,11 +334,13 @@ BOOL rdp_client_redirect(rdpRdp* rdp) rdpSettings* settings = rdp->settings; rdp_client_disconnect(rdp); - rdp_redirection_apply_settings(rdp); + if (rdp_redirection_apply_settings(rdp) != 0) + return FALSE; if (settings->RedirectionFlags & LB_LOAD_BALANCE_INFO) { - nego_set_routing_token(rdp->nego, settings->LoadBalanceInfo, settings->LoadBalanceInfoLength); + if (!nego_set_routing_token(rdp->nego, settings->LoadBalanceInfo, settings->LoadBalanceInfoLength)) + return FALSE; } else { @@ -346,16 +348,22 @@ BOOL rdp_client_redirect(rdpRdp* rdp) { free(settings->ServerHostname); settings->ServerHostname = _strdup(settings->RedirectionTargetFQDN); + if (!settings->ServerHostname) + return FALSE; } else if (settings->RedirectionFlags & LB_TARGET_NET_ADDRESS) { free(settings->ServerHostname); settings->ServerHostname = _strdup(settings->TargetNetAddress); + if (!settings->ServerHostname) + return FALSE; } else if (settings->RedirectionFlags & LB_TARGET_NETBIOS_NAME) { free(settings->ServerHostname); settings->ServerHostname = _strdup(settings->RedirectionTargetNetBiosName); + if (!settings->ServerHostname) + return FALSE; } } @@ -363,12 +371,16 @@ BOOL rdp_client_redirect(rdpRdp* rdp) { free(settings->Username); settings->Username = _strdup(settings->RedirectionUsername); + if (!settings->Username) + return FALSE; } if (settings->RedirectionFlags & LB_DOMAIN) { free(settings->Domain); settings->Domain = _strdup(settings->RedirectionDomain); + if (!settings->Domain) + return FALSE; } status = rdp_client_connect(rdp); @@ -388,7 +400,7 @@ BOOL rdp_client_reconnect(rdpRdp* rdp) status = rdp_client_connect(rdp); if (status) - freerdp_channels_post_connect(channels, context->instance); + status = (freerdp_channels_post_connect(channels, context->instance) >= 0); return status; } @@ -755,7 +767,12 @@ BOOL rdp_client_connect_auto_detect(rdpRdp* rdp, wStream* s) { if (channelId == rdp->mcs->messageChannelId) { - if (rdp_recv_message_channel_pdu(rdp, s) == 0) + UINT16 securityFlags; + + if (!rdp_read_security_header(s, &securityFlags)) + return FALSE; + + if (rdp_recv_message_channel_pdu(rdp, s, securityFlags) == 0) return TRUE; } } @@ -821,7 +838,11 @@ int rdp_client_connect_demand_active(rdpRdp* rdp, wStream* s) if (!rdp_send_confirm_active(rdp)) return -1; - input_register_client_callbacks(rdp->input); + if (!input_register_client_callbacks(rdp->input)) + { + WLog_ERR(TAG, "error registering client callbacks"); + return -1; + } /** * The server may request a different desktop size during Deactivation-Reactivation sequence. diff --git a/libfreerdp/core/fastpath.c b/libfreerdp/core/fastpath.c index 905639372..79fa00d6e 100644 --- a/libfreerdp/core/fastpath.c +++ b/libfreerdp/core/fastpath.c @@ -263,13 +263,19 @@ static int fastpath_recv_update(rdpFastPath* fastpath, BYTE updateCode, UINT32 s { case FASTPATH_UPDATETYPE_ORDERS: if (!fastpath_recv_orders(fastpath, s)) + { + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_ORDERS - fastpath_recv_orders()"); return -1; + } break; case FASTPATH_UPDATETYPE_BITMAP: case FASTPATH_UPDATETYPE_PALETTE: if (!fastpath_recv_update_common(fastpath, s)) + { + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_ORDERS - fastpath_recv_orders()"); return -1; + } break; case FASTPATH_UPDATETYPE_SYNCHRONIZE: @@ -281,6 +287,8 @@ static int fastpath_recv_update(rdpFastPath* fastpath, BYTE updateCode, UINT32 s case FASTPATH_UPDATETYPE_SURFCMDS: status = update_recv_surfcmds(update, size, s); + if (status < 0) + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_SURFCMDS - update_recv_surfcmds() - %i", status); break; case FASTPATH_UPDATETYPE_PTR_NULL: @@ -291,30 +299,41 @@ static int fastpath_recv_update(rdpFastPath* fastpath, BYTE updateCode, UINT32 s case FASTPATH_UPDATETYPE_PTR_DEFAULT: update->pointer->pointer_system.type = SYSPTR_DEFAULT; IFCALL(pointer->PointerSystem, context, &pointer->pointer_system); - break; case FASTPATH_UPDATETYPE_PTR_POSITION: if (!update_read_pointer_position(s, &pointer->pointer_position)) + { + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_PTR_POSITION - update_read_pointer_position()"); return -1; + } IFCALL(pointer->PointerPosition, context, &pointer->pointer_position); break; case FASTPATH_UPDATETYPE_COLOR: if (!update_read_pointer_color(s, &pointer->pointer_color, 24)) + { + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_COLOR - update_read_pointer_color()"); return -1; + } IFCALL(pointer->PointerColor, context, &pointer->pointer_color); break; case FASTPATH_UPDATETYPE_CACHED: if (!update_read_pointer_cached(s, &pointer->pointer_cached)) + { + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_CACHED - update_read_pointer_cached()"); return -1; + } IFCALL(pointer->PointerCached, context, &pointer->pointer_cached); break; case FASTPATH_UPDATETYPE_POINTER: if (!update_read_pointer_new(s, &pointer->pointer_new)) + { + WLog_ERR(TAG, "FASTPATH_UPDATETYPE_POINTER - update_read_pointer_new()"); return -1; + } IFCALL(pointer->PointerNew, context, &pointer->pointer_new); break; @@ -371,7 +390,10 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) Stream_Read_UINT16(s, size); if (Stream_GetRemainingLength(s) < size) + { + WLog_ERR(TAG, "Stream_GetRemainingLength() < size"); return -1; + } cs = s; next_pos = Stream_GetPosition(s) + size; @@ -380,7 +402,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) if (bulkStatus < 0) { - WLog_ERR(TAG, "bulk_decompress() failed"); + WLog_ERR(TAG, "bulk_decompress() failed"); return -1; } @@ -402,7 +424,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) { if (fastpath->fragmentation != -1) { - WLog_ERR(TAG, "Unexpected FASTPATH_FRAGMENT_SINGLE"); + WLog_ERR(TAG, "Unexpected FASTPATH_FRAGMENT_SINGLE"); goto out_fail; } @@ -410,7 +432,10 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) status = fastpath_recv_update(fastpath, updateCode, totalSize, cs); if (status < 0) + { + WLog_ERR(TAG, "fastpath_recv_update() - %i", status); goto out_fail; + } } else { @@ -418,7 +443,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) { if (fastpath->fragmentation != -1) { - WLog_ERR(TAG, "Unexpected FASTPATH_FRAGMENT_FIRST"); + WLog_ERR(TAG, "fastpath_recv_update_data: Unexpected FASTPATH_FRAGMENT_FIRST"); goto out_fail; } @@ -428,7 +453,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) if (totalSize > transport->settings->MultifragMaxRequestSize) { - WLog_ERR(TAG, "Total size (%d) exceeds MultifragMaxRequestSize (%d)", + WLog_ERR(TAG, "Total size (%d) exceeds MultifragMaxRequestSize (%d)", totalSize, transport->settings->MultifragMaxRequestSize); goto out_fail; } @@ -445,7 +470,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) if ((fastpath->fragmentation != FASTPATH_FRAGMENT_FIRST) && (fastpath->fragmentation != FASTPATH_FRAGMENT_NEXT)) { - WLog_ERR(TAG, "Unexpected FASTPATH_FRAGMENT_NEXT"); + WLog_ERR(TAG, "fastpath_recv_update_data: Unexpected FASTPATH_FRAGMENT_NEXT"); goto out_fail; } @@ -455,7 +480,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) if (totalSize > transport->settings->MultifragMaxRequestSize) { - WLog_ERR(TAG, "Total size (%d) exceeds MultifragMaxRequestSize (%d)", + WLog_ERR(TAG, "Total size (%d) exceeds MultifragMaxRequestSize (%d)", totalSize, transport->settings->MultifragMaxRequestSize); goto out_fail; } @@ -473,7 +498,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) if ((fastpath->fragmentation != FASTPATH_FRAGMENT_FIRST) && (fastpath->fragmentation != FASTPATH_FRAGMENT_NEXT)) { - WLog_ERR(TAG, "Unexpected FASTPATH_FRAGMENT_LAST"); + WLog_ERR(TAG, "fastpath_recv_update_data: Unexpected FASTPATH_FRAGMENT_LAST"); goto out_fail; } @@ -483,7 +508,7 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) if (totalSize > transport->settings->MultifragMaxRequestSize) { - WLog_ERR(TAG, "Total size (%d) exceeds MultifragMaxRequestSize (%d)", + WLog_ERR(TAG, "Total size (%d) exceeds MultifragMaxRequestSize (%d)", totalSize, transport->settings->MultifragMaxRequestSize); goto out_fail; } @@ -504,7 +529,10 @@ static int fastpath_recv_update_data(rdpFastPath* fastpath, wStream* s) Stream_Release(fastpath->updateData); if (status < 0) + { + WLog_ERR(TAG, "fastpath_recv_update_data: fastpath_recv_update() - %i", status); goto out_fail; + } } } @@ -526,7 +554,6 @@ out_fail: int fastpath_recv_updates(rdpFastPath* fastpath, wStream* s) { - int status = 0; rdpUpdate* update = fastpath->rdp->update; IFCALL(update->BeginPaint, update->context); @@ -534,12 +561,15 @@ int fastpath_recv_updates(rdpFastPath* fastpath, wStream* s) while (Stream_GetRemainingLength(s) >= 3) { if (fastpath_recv_update_data(fastpath, s) < 0) + { + WLog_ERR(TAG, "fastpath_recv_update_data() fail"); return -1; + } } IFCALL(update->EndPaint, update->context); - return status; + return 0; } static BOOL fastpath_read_input_event_header(wStream* s, BYTE* eventFlags, BYTE* eventCode) @@ -683,7 +713,7 @@ static BOOL fastpath_recv_input_event(rdpFastPath* fastpath, wStream* s) break; default: - WLog_ERR(TAG, "Unknown eventCode %d", eventCode); + WLog_ERR(TAG, "Unknown eventCode %d", eventCode); break; } @@ -794,7 +824,7 @@ BOOL fastpath_send_multiple_input_pdu(rdpFastPath* fastpath, wStream* s, int iNu if (length >= (2 << 14)) { - WLog_ERR(TAG, "Maximum FastPath PDU length is 32767"); + WLog_ERR(TAG, "Maximum FastPath PDU length is 32767"); return FALSE; } diff --git a/libfreerdp/core/freerdp.c b/libfreerdp/core/freerdp.c index e1fa5cb46..010046b38 100644 --- a/libfreerdp/core/freerdp.c +++ b/libfreerdp/core/freerdp.c @@ -211,6 +211,7 @@ BOOL freerdp_check_fds(freerdp* instance) TerminateEventArgs e; rdpContext* context = instance->context; + WLog_DBG(TAG, "rdp_check_fds() - %i", status); EventArgsInit(&e, "freerdp"); e.code = 0; PubSub_OnTerminate(context->pubSub, context, &e); @@ -248,9 +249,17 @@ BOOL freerdp_check_event_handles(rdpContext* context) status = freerdp_check_fds(context->instance); if (!status) + { + WLog_ERR(TAG, "freerdp_check_fds() failed - %i", status); return FALSE; + } status = freerdp_channels_check_fds(context->channels, context->instance); + if (!status) + { + WLog_ERR(TAG, "freerdp_channels_check_fds() failed - %i", status); + return FALSE; + } if (!status) return FALSE; diff --git a/libfreerdp/core/gateway/http.c b/libfreerdp/core/gateway/http.c index d56636873..f12423f93 100644 --- a/libfreerdp/core/gateway/http.c +++ b/libfreerdp/core/gateway/http.c @@ -615,7 +615,7 @@ HttpResponse* http_response_recv(rdpTls* tls) int position; char* line; char* buffer; - char* header; + char* header = NULL; char* payload; int bodyLength; int payloadOffset; @@ -728,8 +728,6 @@ HttpResponse* http_response_recv(rdpTls* tls) count++; } - free(header); - if (!http_response_parse_header(response)) goto out_error; @@ -779,10 +777,12 @@ HttpResponse* http_response_recv(rdpTls* tls) } } + free(header); Stream_Free(s, TRUE); return response; out_error: http_response_free(response); + free(header); out_free: Stream_Free(s, TRUE); return NULL; diff --git a/libfreerdp/core/gateway/ncacn_http.c b/libfreerdp/core/gateway/ncacn_http.c index b67663788..175aab3c3 100644 --- a/libfreerdp/core/gateway/ncacn_http.c +++ b/libfreerdp/core/gateway/ncacn_http.c @@ -138,9 +138,24 @@ int rpc_ncacn_http_ntlm_init(rdpRpc* rpc, RpcChannel* channel) if (settings->GatewayUseSameCredentials) { - settings->Username = _strdup(settings->GatewayUsername); - settings->Domain = _strdup(settings->GatewayDomain); - settings->Password = _strdup(settings->GatewayPassword); + if (settings->GatewayUsername) + { + free(settings->Username); + if (!(settings->Username = _strdup(settings->GatewayUsername))) + return -1; + } + if (settings->GatewayDomain) + { + free(settings->Domain); + if (!(settings->Domain = _strdup(settings->GatewayDomain))) + return -1; + } + if (settings->GatewayPassword) + { + free(settings->Password); + if (!(settings->Password = _strdup(settings->GatewayPassword))) + return -1; + } } } } diff --git a/libfreerdp/core/gateway/ntlm.c b/libfreerdp/core/gateway/ntlm.c index 68add2c6e..fa6e8971b 100644 --- a/libfreerdp/core/gateway/ntlm.c +++ b/libfreerdp/core/gateway/ntlm.c @@ -43,7 +43,7 @@ BOOL ntlm_client_init(rdpNtlm* ntlm, BOOL http, char* user, char* domain, char* ntlm->http = http; ntlm->Bindings = Bindings; - ntlm->table = InitSecurityInterface(); + ntlm->table = InitSecurityInterfaceEx(0); if (!ntlm->table) return FALSE; diff --git a/libfreerdp/core/gateway/rdg.c b/libfreerdp/core/gateway/rdg.c index 1154ebf39..60efa47f4 100644 --- a/libfreerdp/core/gateway/rdg.c +++ b/libfreerdp/core/gateway/rdg.c @@ -780,9 +780,24 @@ BOOL rdg_ncacn_http_ntlm_init(rdpRdg* rdg, rdpTls* tls) if (settings->GatewayUseSameCredentials) { - settings->Username = _strdup(settings->GatewayUsername); - settings->Domain = _strdup(settings->GatewayDomain); - settings->Password = _strdup(settings->GatewayPassword); + if (settings->GatewayUsername) + { + free(settings->Username); + if (!(settings->Username = _strdup(settings->GatewayUsername))) + return FALSE; + } + if (settings->GatewayDomain) + { + free(settings->Domain); + if (!(settings->Domain = _strdup(settings->GatewayDomain))) + return FALSE; + } + if (settings->GatewayPassword) + { + free(settings->Password); + if (!(settings->Password = _strdup(settings->GatewayPassword))) + return FALSE; + } } } } diff --git a/libfreerdp/core/gcc.c b/libfreerdp/core/gcc.c index b31de85c1..542e3eeba 100644 --- a/libfreerdp/core/gcc.c +++ b/libfreerdp/core/gcc.c @@ -1590,11 +1590,12 @@ BOOL gcc_read_client_monitor_data(wStream* s, rdpMcs* mcs, UINT16 blockLength) Stream_Read_UINT32(s, flags); /* flags */ Stream_Read_UINT32(s, monitorCount); /* monitorCount */ - if (blockLength < (8 + (monitorCount * 20))) + if (((blockLength - 8) / 20) < monitorCount) return FALSE; - monitorDefArray = (MONITOR_DEF*) malloc(sizeof(MONITOR_DEF) * monitorCount); - ZeroMemory(monitorDefArray, sizeof(MONITOR_DEF) * monitorCount); + monitorDefArray = (MONITOR_DEF*) calloc(monitorCount, sizeof(MONITOR_DEF)); + if (!monitorDefArray) + return FALSE; for (index = 0; index < monitorCount; index++) { @@ -1657,7 +1658,7 @@ BOOL gcc_read_client_monitor_extended_data(wStream* s, rdpMcs* mcs, UINT16 block UINT32 monitorAttributeSize; MONITOR_ATTRIBUTES* monitorAttributesArray; - if (blockLength < 8) + if (blockLength < 12) return FALSE; Stream_Read_UINT32(s, flags); /* flags */ @@ -1667,11 +1668,12 @@ BOOL gcc_read_client_monitor_extended_data(wStream* s, rdpMcs* mcs, UINT16 block if (monitorAttributeSize != 20) return FALSE; - if (blockLength < (12 + (monitorCount * monitorAttributeSize))) + if ((blockLength - 12) / monitorAttributeSize < monitorCount) return FALSE; - monitorAttributesArray = (MONITOR_ATTRIBUTES*) malloc(sizeof(MONITOR_ATTRIBUTES) * monitorCount); - ZeroMemory(monitorAttributesArray, sizeof(MONITOR_ATTRIBUTES) * monitorCount); + monitorAttributesArray = (MONITOR_ATTRIBUTES*) calloc(monitorCount, sizeof(MONITOR_ATTRIBUTES)); + if (!monitorAttributesArray) + return FALSE; for (index = 0; index < monitorCount; index++) { diff --git a/libfreerdp/core/input.c b/libfreerdp/core/input.c index c965ae7f6..f52b0dc82 100644 --- a/libfreerdp/core/input.c +++ b/libfreerdp/core/input.c @@ -498,7 +498,7 @@ BOOL input_recv(rdpInput* input, wStream* s) return TRUE; } -void input_register_client_callbacks(rdpInput* input) +BOOL input_register_client_callbacks(rdpInput* input) { rdpSettings* settings = input->context->settings; @@ -528,7 +528,10 @@ void input_register_client_callbacks(rdpInput* input) if (input->asynchronous) { input->proxy = input_message_proxy_new(input); + if (!input->proxy) + return FALSE; } + return TRUE; } BOOL freerdp_input_send_synchronize_event(rdpInput* input, UINT32 flags) diff --git a/libfreerdp/core/input.h b/libfreerdp/core/input.h index 415f2be8d..30458804a 100644 --- a/libfreerdp/core/input.h +++ b/libfreerdp/core/input.h @@ -53,7 +53,7 @@ BOOL input_send_fastpath_extended_mouse_event(rdpInput* input, UINT16 flags, UIN BOOL input_recv(rdpInput* input, wStream* s); int input_process_events(rdpInput* input); -void input_register_client_callbacks(rdpInput* input); +BOOL input_register_client_callbacks(rdpInput* input); rdpInput* input_new(rdpRdp* rdp); void input_free(rdpInput* input); diff --git a/libfreerdp/core/license.c b/libfreerdp/core/license.c index 05be43fad..23de184bb 100644 --- a/libfreerdp/core/license.c +++ b/libfreerdp/core/license.c @@ -423,6 +423,8 @@ BOOL license_get_server_rsa_public_key(rdpLicense* license) CopyMemory(license->Exponent, Exponent, 4); license->ModulusLength = ModulusLength; license->Modulus = (BYTE*) malloc(ModulusLength); + if (!license->Modulus) + return FALSE; CopyMemory(license->Modulus, Modulus, ModulusLength); return TRUE; } @@ -501,19 +503,24 @@ BOOL license_read_product_info(wStream* s, LICENSE_PRODUCT_INFO* productInfo) return FALSE; productInfo->pbCompanyName = (BYTE*) malloc(productInfo->cbCompanyName); + if (!productInfo->pbCompanyName) + return FALSE; Stream_Read(s, productInfo->pbCompanyName, productInfo->cbCompanyName); Stream_Read_UINT32(s, productInfo->cbProductId); /* cbProductId (4 bytes) */ if (Stream_GetRemainingLength(s) < productInfo->cbProductId) - { - free(productInfo->pbCompanyName); - productInfo->pbCompanyName = NULL; - return FALSE; - } + goto out_fail; productInfo->pbProductId = (BYTE*) malloc(productInfo->cbProductId); + if (!productInfo->pbProductId) + goto out_fail; Stream_Read(s, productInfo->pbProductId, productInfo->cbProductId); return TRUE; + +out_fail: + free(productInfo->pbCompanyName); + productInfo->pbCompanyName = NULL; + return FALSE; } /** @@ -526,6 +533,8 @@ LICENSE_PRODUCT_INFO* license_new_product_info() { LICENSE_PRODUCT_INFO* productInfo; productInfo = (LICENSE_PRODUCT_INFO*) malloc(sizeof(LICENSE_PRODUCT_INFO)); + if (!productInfo) + return NULL; productInfo->dwVersion = 0; productInfo->cbCompanyName = 0; productInfo->pbCompanyName = NULL; @@ -584,6 +593,8 @@ BOOL license_read_binary_blob(wStream* s, LICENSE_BLOB* blob) blob->type = wBlobType; blob->data = (BYTE*) malloc(blob->length); + if (!blob->data) + return FALSE; Stream_Read(s, blob->data, blob->length); /* blobData */ return TRUE; } @@ -640,10 +651,9 @@ BOOL license_write_encrypted_premaster_secret_blob(wStream* s, LICENSE_BLOB* blo LICENSE_BLOB* license_new_binary_blob(UINT16 type) { LICENSE_BLOB* blob; - blob = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB)); - blob->type = type; - blob->length = 0; - blob->data = NULL; + blob = (LICENSE_BLOB*) calloc(1, sizeof(LICENSE_BLOB)); + if (blob) + blob->type = type; return blob; } @@ -684,6 +694,8 @@ BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList) scopeList->count = scopeCount; scopeList->array = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB) * scopeCount); + if (!scopeList->array) + return FALSE; /* ScopeArray */ for (i = 0; i < scopeCount; i++) @@ -705,11 +717,7 @@ BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList) SCOPE_LIST* license_new_scope_list() { - SCOPE_LIST* scopeList; - scopeList = (SCOPE_LIST*) malloc(sizeof(SCOPE_LIST)); - scopeList->count = 0; - scopeList->array = NULL; - return scopeList; + return (SCOPE_LIST*) calloc(1, sizeof(SCOPE_LIST)); } /** @@ -722,6 +730,9 @@ void license_free_scope_list(SCOPE_LIST* scopeList) { UINT32 i; + if (!scopeList) + return; + /* * We must NOT call license_free_binary_blob() on each scopelist->array[i] element, * because scopelist->array was allocated at once, by a single call to malloc. The elements @@ -1093,29 +1104,44 @@ BOOL license_send_valid_client_error_packet(rdpLicense* license) rdpLicense* license_new(rdpRdp* rdp) { rdpLicense* license; - license = (rdpLicense*) malloc(sizeof(rdpLicense)); + license = (rdpLicense*) calloc(1, sizeof(rdpLicense)); + if (!license) + return NULL; - if (license != NULL) - { - ZeroMemory(license, sizeof(rdpLicense)); - license->rdp = rdp; - license->state = LICENSE_STATE_AWAIT; - license->certificate = certificate_new(); - license->ProductInfo = license_new_product_info(); - license->ErrorInfo = license_new_binary_blob(BB_ERROR_BLOB); - license->KeyExchangeList = license_new_binary_blob(BB_KEY_EXCHG_ALG_BLOB); - license->ServerCertificate = license_new_binary_blob(BB_CERTIFICATE_BLOB); - license->ClientUserName = license_new_binary_blob(BB_CLIENT_USER_NAME_BLOB); - license->ClientMachineName = license_new_binary_blob(BB_CLIENT_MACHINE_NAME_BLOB); - license->PlatformChallenge = license_new_binary_blob(BB_ANY_BLOB); - license->EncryptedPlatformChallenge = license_new_binary_blob(BB_ANY_BLOB); - license->EncryptedPremasterSecret = license_new_binary_blob(BB_ANY_BLOB); - license->EncryptedHardwareId = license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB); - license->ScopeList = license_new_scope_list(); - license_generate_randoms(license); - } + license->rdp = rdp; + license->state = LICENSE_STATE_AWAIT; + if (!(license->certificate = certificate_new())) + goto out_error; + if (!(license->ProductInfo = license_new_product_info())) + goto out_error; + if (!(license->ErrorInfo = license_new_binary_blob(BB_ERROR_BLOB))) + goto out_error; + if (!(license->KeyExchangeList = license_new_binary_blob(BB_KEY_EXCHG_ALG_BLOB))) + goto out_error; + if (!(license->ServerCertificate = license_new_binary_blob(BB_CERTIFICATE_BLOB))) + goto out_error; + if (!(license->ClientUserName = license_new_binary_blob(BB_CLIENT_USER_NAME_BLOB))) + goto out_error; + if (!(license->ClientMachineName = license_new_binary_blob(BB_CLIENT_MACHINE_NAME_BLOB))) + goto out_error; + if (!(license->PlatformChallenge = license_new_binary_blob(BB_ANY_BLOB))) + goto out_error; + if (!(license->EncryptedPlatformChallenge = license_new_binary_blob(BB_ANY_BLOB))) + goto out_error; + if (!(license->EncryptedPremasterSecret = license_new_binary_blob(BB_ANY_BLOB))) + goto out_error; + if (!(license->EncryptedHardwareId = license_new_binary_blob(BB_ENCRYPTED_DATA_BLOB))) + goto out_error; + if (!(license->ScopeList = license_new_scope_list())) + goto out_error; + + license_generate_randoms(license); return license; + +out_error: + license_free(license); + return NULL; } /** diff --git a/libfreerdp/core/listener.c b/libfreerdp/core/listener.c index 832210651..af49da221 100644 --- a/libfreerdp/core/listener.c +++ b/libfreerdp/core/listener.c @@ -41,8 +41,11 @@ #include #endif +#include + #include "listener.h" + #define TAG FREERDP_TAG("core.listener") #ifdef _WIN32 @@ -168,7 +171,8 @@ static BOOL freerdp_listener_open(freerdp_listener* instance, const char* bind_a /* FIXME: these file descriptors do not work on Windows */ listener->sockfds[listener->num_sockfds] = sockfd; - listener->events[listener->num_sockfds] = CreateFileDescriptorEvent(NULL, FALSE, FALSE, sockfd); + listener->events[listener->num_sockfds] = + CreateFileDescriptorEvent(NULL, FALSE, FALSE, sockfd, WINPR_FD_READ); listener->num_sockfds++; WLog_INFO(TAG, "Listening on %s:%s", addr, servname); @@ -226,7 +230,8 @@ static BOOL freerdp_listener_open_local(freerdp_listener* instance, const char* return FALSE; } - if (!(hevent = CreateFileDescriptorEvent(NULL, FALSE, FALSE, sockfd))) + hevent = CreateFileDescriptorEvent(NULL, FALSE, FALSE, sockfd, WINPR_FD_READ); + if (!hevent) { WLog_ERR(TAG, "failed to create sockfd event"); closesocket((SOCKET) sockfd); @@ -258,7 +263,8 @@ static BOOL freerdp_listener_open_from_socket(freerdp_listener* instance, int fd return FALSE; listener->sockfds[listener->num_sockfds] = fd; - listener->events[listener->num_sockfds] = CreateFileDescriptorEvent(NULL, FALSE, FALSE, fd); + listener->events[listener->num_sockfds] = + CreateFileDescriptorEvent(NULL, FALSE, FALSE, fd, WINPR_FD_READ); if (!listener->events[listener->num_sockfds]) return FALSE; diff --git a/libfreerdp/core/message.c b/libfreerdp/core/message.c index fc158cadf..adc0e0f49 100644 --- a/libfreerdp/core/message.c +++ b/libfreerdp/core/message.c @@ -107,10 +107,9 @@ static BOOL update_message_BitmapUpdate(rdpContext* context, BITMAP_UPDATE* bitm wParam->rectangles[index].bitmapDataStream = (BYTE*) malloc(wParam->rectangles[index].bitmapLength); if (!wParam->rectangles[index].bitmapDataStream) { - for (index -= 1; index >= 0; --index) - { - free(wParam->rectangles[index].bitmapDataStream); - } + while(index) + free(wParam->rectangles[--index].bitmapDataStream); + free(wParam->rectangles); free(wParam); return FALSE; @@ -2770,15 +2769,13 @@ rdpInputProxy* input_message_proxy_new(rdpInput* input) { rdpInputProxy* proxy; - proxy = (rdpInputProxy*) malloc(sizeof(rdpInputProxy)); + proxy = (rdpInputProxy*) calloc(1, sizeof(rdpInputProxy)); - if (proxy) - { - ZeroMemory(proxy, sizeof(rdpInputProxy)); + if (!proxy) + return NULL; - proxy->input = input; - input_message_proxy_register(proxy, input); - } + proxy->input = input; + input_message_proxy_register(proxy, input); return proxy; } diff --git a/libfreerdp/core/metrics.c b/libfreerdp/core/metrics.c index bfcfd445e..1515b6083 100644 --- a/libfreerdp/core/metrics.c +++ b/libfreerdp/core/metrics.c @@ -25,13 +25,15 @@ double metrics_write_bytes(rdpMetrics* metrics, UINT32 UncompressedBytes, UINT32 CompressedBytes) { - double CompressionRatio; + double CompressionRatio = 0.0; metrics->TotalUncompressedBytes += UncompressedBytes; metrics->TotalCompressedBytes += CompressedBytes; - CompressionRatio = ((double) CompressedBytes) / ((double) UncompressedBytes); - metrics->TotalCompressionRatio = ((double) metrics->TotalCompressedBytes) / ((double) metrics->TotalUncompressedBytes); + if (UncompressedBytes != 0) + CompressionRatio = ((double) CompressedBytes) / ((double) UncompressedBytes); + if (metrics->TotalUncompressedBytes != 0) + metrics->TotalCompressionRatio = ((double) metrics->TotalCompressedBytes) / ((double) metrics->TotalUncompressedBytes); return CompressionRatio; } diff --git a/libfreerdp/core/multitransport.c b/libfreerdp/core/multitransport.c index 36d86f741..59d3d06bb 100644 --- a/libfreerdp/core/multitransport.c +++ b/libfreerdp/core/multitransport.c @@ -43,13 +43,7 @@ int rdp_recv_multitransport_packet(rdpRdp* rdp, wStream* s) rdpMultitransport* multitransport_new(void) { - rdpMultitransport* multitransport = (rdpMultitransport*)malloc(sizeof(rdpMultitransport)); - if (multitransport) - { - memset(multitransport, 0, sizeof(rdpMultitransport)); - } - - return multitransport; + return (rdpMultitransport*)calloc(1, sizeof(rdpMultitransport)); } void multitransport_free(rdpMultitransport* multitransport) diff --git a/libfreerdp/core/nla.c b/libfreerdp/core/nla.c index dbcffcdfc..88192b916 100644 --- a/libfreerdp/core/nla.c +++ b/libfreerdp/core/nla.c @@ -44,6 +44,9 @@ #define TAG FREERDP_TAG("core.nla") +#define SERVER_KEY "Software\\"FREERDP_VENDOR_STRING"\\" \ + FREERDP_PRODUCT_STRING"\\Server" + /** * TSRequest ::= SEQUENCE { * version [0] INTEGER, @@ -90,18 +93,44 @@ #define TERMSRV_SPN_PREFIX "TERMSRV/" -BOOL nla_send(rdpNla* nla); -int nla_recv(rdpNla* nla); -void nla_buffer_print(rdpNla* nla); -void nla_buffer_free(rdpNla* nla); -SECURITY_STATUS nla_encrypt_public_key_echo(rdpNla* nla); -SECURITY_STATUS nla_decrypt_public_key_echo(rdpNla* nla); -SECURITY_STATUS nla_encrypt_ts_credentials(rdpNla* nla); -SECURITY_STATUS nla_decrypt_ts_credentials(rdpNla* nla); +static BOOL nla_send(rdpNla* nla); +static int nla_recv(rdpNla* nla); +static void nla_buffer_print(rdpNla* nla); +static void nla_buffer_free(rdpNla* nla); +static SECURITY_STATUS nla_encrypt_public_key_echo(rdpNla* nla); +static SECURITY_STATUS nla_decrypt_public_key_echo(rdpNla* nla); +static SECURITY_STATUS nla_encrypt_ts_credentials(rdpNla* nla); +static SECURITY_STATUS nla_decrypt_ts_credentials(rdpNla* nla); +static BOOL nla_read_ts_password_creds(rdpNla* nla, wStream* s); +static void nla_identity_free(SEC_WINNT_AUTH_IDENTITY* identity); #define ber_sizeof_sequence_octet_string(length) ber_sizeof_contextual_tag(ber_sizeof_octet_string(length)) + ber_sizeof_octet_string(length) #define ber_write_sequence_octet_string(stream, context, value, length) ber_write_contextual_tag(stream, context, ber_sizeof_octet_string(length), TRUE) + ber_write_octet_string(stream, value, length) +void nla_identity_free(SEC_WINNT_AUTH_IDENTITY* identity) +{ + if (identity) + { + if (identity->User) + { + memset(identity->User, 0, identity->UserLength*2); + free(identity->User); + } + if (identity->Password) + { + memset(identity->Password, 0, identity->PasswordLength*2); + free(identity->Password); + } + if (identity->Domain) + { + memset(identity->Domain, 0, identity->DomainLength*2); + free(identity->Domain); + } + } + free(identity); + +} + /** * Initialize NTLMSSP authentication module (client). * @param credssp @@ -153,11 +182,24 @@ int nla_client_init(rdpNla* nla) } } - sspi_SetAuthIdentity(&(nla->identity), settings->Username, settings->Domain, settings->Password); + if (!settings->Username) + { + nla_identity_free(nla->identity); + nla->identity = NULL; + } + else + sspi_SetAuthIdentity(nla->identity, settings->Username, settings->Domain, + settings->Password); #ifndef _WIN32 { - SEC_WINNT_AUTH_IDENTITY* identity = &(nla->identity); + SEC_WINNT_AUTH_IDENTITY* identity = nla->identity; + + if (!identity) + { + WLog_ERR(TAG, "NLA identity=%p", identity); + return -1; + } if (settings->RestrictedAdminModeRequired) { @@ -211,7 +253,7 @@ int nla_client_init(rdpNla* nla) nla->ServicePrincipalName = spn; #endif - nla->table = InitSecurityInterface(); + nla->table = InitSecurityInterfaceEx(0); nla->status = nla->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &nla->pPackageInfo); if (nla->status != SEC_E_OK) @@ -222,7 +264,8 @@ int nla_client_init(rdpNla* nla) nla->cbMaxToken = nla->pPackageInfo->cbMaxToken; nla->status = nla->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME, - SECPKG_CRED_OUTBOUND, NULL, &nla->identity, NULL, NULL, &nla->credentials, &nla->expiration); + SECPKG_CRED_OUTBOUND, NULL, nla->identity, NULL, NULL, &nla->credentials, + &nla->expiration); if (nla->status != SEC_E_OK) { @@ -498,7 +541,7 @@ int nla_server_init(rdpNla* nla) } else { - nla->table = InitSecurityInterface(); + nla->table = InitSecurityInterfaceEx(0); } nla->status = nla->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &nla->pPackageInfo); @@ -854,46 +897,101 @@ SECURITY_STATUS nla_decrypt_public_key_echo(rdpNla* nla) int nla_sizeof_ts_password_creds(rdpNla* nla) { int length = 0; - length += ber_sizeof_sequence_octet_string(nla->identity.DomainLength * 2); - length += ber_sizeof_sequence_octet_string(nla->identity.UserLength * 2); - length += ber_sizeof_sequence_octet_string(nla->identity.PasswordLength * 2); + if (nla->identity) + { + length += ber_sizeof_sequence_octet_string(nla->identity->DomainLength * 2); + length += ber_sizeof_sequence_octet_string(nla->identity->UserLength * 2); + length += ber_sizeof_sequence_octet_string(nla->identity->PasswordLength * 2); + } return length; } -void nla_read_ts_password_creds(rdpNla* nla, wStream* s) +BOOL nla_read_ts_password_creds(rdpNla* nla, wStream* s) { int length; - /* TSPasswordCreds (SEQUENCE) */ - ber_read_sequence_tag(s, &length); + if (!nla->identity) + { + WLog_ERR(TAG, "nla->identity is NULL!"); + return FALSE; + } + + /* TSPasswordCreds (SEQUENCE) + * Initialise to default values. */ + nla->identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; + + nla->identity->UserLength = (UINT32) 0; + nla->identity->User = NULL; + + nla->identity->DomainLength = (UINT32) 0; + nla->identity->Domain = NULL; + + nla->identity->Password = NULL; + nla->identity->PasswordLength = (UINT32) 0; + + if (!ber_read_sequence_tag(s, &length)) + return FALSE; + + /* The sequence is empty, return early, + * TSPasswordCreds (SEQUENCE) is optional. */ + if (length == 0) + return TRUE; /* [0] domainName (OCTET STRING) */ - ber_read_contextual_tag(s, 0, &length, TRUE); - ber_read_octet_string_tag(s, &length); - nla->identity.DomainLength = (UINT32) length; - nla->identity.Domain = (UINT16*) malloc(length); - CopyMemory(nla->identity.Domain, Stream_Pointer(s), nla->identity.DomainLength); - Stream_Seek(s, nla->identity.DomainLength); - nla->identity.DomainLength /= 2; + if (!ber_read_contextual_tag(s, 0, &length, TRUE) || + !ber_read_octet_string_tag(s, &length)) + { + return FALSE; + } + + nla->identity->DomainLength = (UINT32) length; + if (nla->identity->DomainLength > 0) + { + nla->identity->Domain = (UINT16*) malloc(length); + if (!nla->identity->Domain) + return FALSE; + CopyMemory(nla->identity->Domain, Stream_Pointer(s), nla->identity->DomainLength); + Stream_Seek(s, nla->identity->DomainLength); + nla->identity->DomainLength /= 2; + } /* [1] userName (OCTET STRING) */ - ber_read_contextual_tag(s, 1, &length, TRUE); - ber_read_octet_string_tag(s, &length); - nla->identity.UserLength = (UINT32) length; - nla->identity.User = (UINT16*) malloc(length); - CopyMemory(nla->identity.User, Stream_Pointer(s), nla->identity.UserLength); - Stream_Seek(s, nla->identity.UserLength); - nla->identity.UserLength /= 2; + if (!ber_read_contextual_tag(s, 1, &length, TRUE) || + !ber_read_octet_string_tag(s, &length)) + { + return FALSE; + } + + nla->identity->UserLength = (UINT32) length; + if (nla->identity->UserLength > 0) + { + nla->identity->User = (UINT16 *) malloc(length); + if (!nla->identity->User) + return FALSE; + CopyMemory(nla->identity->User, Stream_Pointer(s), nla->identity->UserLength); + Stream_Seek(s, nla->identity->UserLength); + nla->identity->UserLength /= 2; + } /* [2] password (OCTET STRING) */ - ber_read_contextual_tag(s, 2, &length, TRUE); - ber_read_octet_string_tag(s, &length); - nla->identity.PasswordLength = (UINT32) length; - nla->identity.Password = (UINT16*) malloc(length); - CopyMemory(nla->identity.Password, Stream_Pointer(s), nla->identity.PasswordLength); - Stream_Seek(s, nla->identity.PasswordLength); - nla->identity.PasswordLength /= 2; - nla->identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; + if (!ber_read_contextual_tag(s, 2, &length, TRUE) || + !ber_read_octet_string_tag(s, &length)) + { + return FALSE; + } + + nla->identity->PasswordLength = (UINT32) length; + if (nla->identity->PasswordLength > 0) + { + nla->identity->Password = (UINT16 *) malloc(length); + if (!nla->identity->Password) + return FALSE; + CopyMemory(nla->identity->Password, Stream_Pointer(s), nla->identity->PasswordLength); + Stream_Seek(s, nla->identity->PasswordLength); + nla->identity->PasswordLength /= 2; + } + + return TRUE; } int nla_write_ts_password_creds(rdpNla* nla, wStream* s) @@ -902,12 +1000,21 @@ int nla_write_ts_password_creds(rdpNla* nla, wStream* s) int innerSize = nla_sizeof_ts_password_creds(nla); /* TSPasswordCreds (SEQUENCE) */ size += ber_write_sequence_tag(s, innerSize); - /* [0] domainName (OCTET STRING) */ - size += ber_write_sequence_octet_string(s, 0, (BYTE*) nla->identity.Domain, nla->identity.DomainLength * 2); - /* [1] userName (OCTET STRING) */ - size += ber_write_sequence_octet_string(s, 1, (BYTE*) nla->identity.User, nla->identity.UserLength * 2); - /* [2] password (OCTET STRING) */ - size += ber_write_sequence_octet_string(s, 2, (BYTE*) nla->identity.Password, nla->identity.PasswordLength * 2); + if (nla->identity) + { + /* [0] domainName (OCTET STRING) */ + size += ber_write_sequence_octet_string( + s, 0, (BYTE*) nla->identity->Domain, + nla->identity->DomainLength * 2); + /* [1] userName (OCTET STRING) */ + size += ber_write_sequence_octet_string( + s, 1, (BYTE*) nla->identity->User, + nla->identity->UserLength * 2); + /* [2] password (OCTET STRING) */ + size += ber_write_sequence_octet_string( + s, 2, (BYTE*) nla->identity->Password, + nla->identity->PasswordLength * 2); + } return size; } @@ -920,11 +1027,12 @@ int nla_sizeof_ts_credentials(rdpNla* nla) return size; } -BOOL nla_read_ts_credentials(rdpNla* nla, PSecBuffer ts_credentials) +static BOOL nla_read_ts_credentials(rdpNla* nla, PSecBuffer ts_credentials) { wStream* s; int length; int ts_password_creds_length; + BOOL ret; s = Stream_New(ts_credentials->pvBuffer, ts_credentials->cbBuffer); @@ -935,21 +1043,18 @@ BOOL nla_read_ts_credentials(rdpNla* nla, PSecBuffer ts_credentials) } - /* TSCredentials (SEQUENCE) */ - ber_read_sequence_tag(s, &length); - - /* [0] credType (INTEGER) */ - ber_read_contextual_tag(s, 0, &length, TRUE); - ber_read_integer(s, NULL); - - /* [1] credentials (OCTET STRING) */ - ber_read_contextual_tag(s, 1, &length, TRUE); - ber_read_octet_string_tag(s, &ts_password_creds_length); - - nla_read_ts_password_creds(nla, s); + /* TSCredentials (SEQUENCE) */ + ret = ber_read_sequence_tag(s, &length) && + /* [0] credType (INTEGER) */ + ber_read_contextual_tag(s, 0, &length, TRUE) && + ber_read_integer(s, NULL) && + /* [1] credentials (OCTET STRING) */ + ber_read_contextual_tag(s, 1, &length, TRUE) && + ber_read_octet_string_tag(s, &ts_password_creds_length) && + nla_read_ts_password_creds(nla, s); Stream_Free(s, FALSE); - return TRUE; + return ret; } int nla_write_ts_credentials(rdpNla* nla, wStream* s) @@ -983,19 +1088,22 @@ BOOL nla_encode_ts_credentials(rdpNla* nla) { wStream* s; int length; - int DomainLength; - int UserLength; - int PasswordLength; + int DomainLength = 0; + int UserLength = 0; + int PasswordLength = 0; - DomainLength = nla->identity.DomainLength; - UserLength = nla->identity.UserLength; - PasswordLength = nla->identity.PasswordLength; - - if (nla->settings->DisableCredentialsDelegation) + if (nla->identity) { - nla->identity.DomainLength = 0; - nla->identity.UserLength = 0; - nla->identity.PasswordLength = 0; + DomainLength = nla->identity->DomainLength; + UserLength = nla->identity->UserLength; + PasswordLength = nla->identity->PasswordLength; + } + + if (nla->settings->DisableCredentialsDelegation && nla->identity) + { + nla->identity->DomainLength = 0; + nla->identity->UserLength = 0; + nla->identity->PasswordLength = 0; } length = ber_sizeof_sequence(nla_sizeof_ts_credentials(nla)); @@ -1017,9 +1125,9 @@ BOOL nla_encode_ts_credentials(rdpNla* nla) if (nla->settings->DisableCredentialsDelegation) { - nla->identity.DomainLength = DomainLength; - nla->identity.UserLength = UserLength; - nla->identity.PasswordLength = PasswordLength; + nla->identity->DomainLength = DomainLength; + nla->identity->UserLength = UserLength; + nla->identity->PasswordLength = PasswordLength; } Stream_Free(s, FALSE); @@ -1365,6 +1473,12 @@ LPTSTR nla_make_spn(const char* ServiceClass, const char* hostname) hostnameX = _strdup(hostname); ServiceClassX = _strdup(ServiceClass); #endif + if (!hostnameX || !ServiceClassX) + { + free(hostnameX); + free(ServiceClassX); + return NULL; + } if (!ServiceClass) { @@ -1412,48 +1526,66 @@ LPTSTR nla_make_spn(const char* ServiceClass, const char* hostname) rdpNla* nla_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { + rdpNla* nla = (rdpNla*) calloc(1, sizeof(rdpNla)); - if (nla) + if (!nla) + return NULL; + + nla->identity = calloc(1, sizeof(SEC_WINNT_AUTH_IDENTITY)); + if (!nla->identity) + { + free (nla); + return NULL; + } + + nla->instance = instance; + nla->settings = settings; + nla->server = settings->ServerMode; + nla->transport = transport; + nla->sendSeqNum = 0; + nla->recvSeqNum = 0; + + ZeroMemory(&nla->negoToken, sizeof(SecBuffer)); + ZeroMemory(&nla->pubKeyAuth, sizeof(SecBuffer)); + ZeroMemory(&nla->authInfo, sizeof(SecBuffer)); + SecInvalidateHandle(&nla->context); + + if (nla->server) { - HKEY hKey; LONG status; + HKEY hKey; DWORD dwType; DWORD dwSize; - nla->instance = instance; - nla->settings = settings; - nla->server = settings->ServerMode; - nla->transport = transport; - nla->sendSeqNum = 0; - nla->recvSeqNum = 0; - ZeroMemory(&nla->negoToken, sizeof(SecBuffer)); - ZeroMemory(&nla->pubKeyAuth, sizeof(SecBuffer)); - ZeroMemory(&nla->authInfo, sizeof(SecBuffer)); - SecInvalidateHandle(&nla->context); - if (nla->server) + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, + 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + + if (status != ERROR_SUCCESS) + return nla; + + status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); + if (status != ERROR_SUCCESS) { - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), - 0, KEY_READ | KEY_WOW64_64KEY, &hKey); - - if (status == ERROR_SUCCESS) - { - status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); - - if (status == ERROR_SUCCESS) - { - nla->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); - status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, - (BYTE*) nla->SspiModule, &dwSize); - - if (status == ERROR_SUCCESS) - { - WLog_INFO(TAG, "Using SSPI Module: %s", nla->SspiModule); - RegCloseKey(hKey); - } - } - } + RegCloseKey(hKey); + return nla; } + + nla->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); + if (!nla->SspiModule) + { + RegCloseKey(hKey); + free(nla); + return NULL; + } + + status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, + (BYTE*) nla->SspiModule, &dwSize); + + if (status == ERROR_SUCCESS) + WLog_INFO(TAG, "Using SSPI Module: %s", nla->SspiModule); + + RegCloseKey(hKey); } return nla; @@ -1476,9 +1608,6 @@ void nla_free(rdpNla* nla) sspi_SecBufferFree(&nla->tsCredentials); free(nla->ServicePrincipalName); - free(nla->identity.User); - free(nla->identity.Domain); - free(nla->identity.Password); - + nla_identity_free(nla->identity); free(nla); } diff --git a/libfreerdp/core/nla.h b/libfreerdp/core/nla.h index 18f413eb8..774bcc985 100644 --- a/libfreerdp/core/nla.h +++ b/libfreerdp/core/nla.h @@ -77,7 +77,7 @@ struct rdp_nla SecBuffer tsCredentials; CryptoRc4 rc4SealState; LPTSTR ServicePrincipalName; - SEC_WINNT_AUTH_IDENTITY identity; + SEC_WINNT_AUTH_IDENTITY* identity; PSecurityFunctionTable table; SecPkgContext_Sizes ContextSizes; }; diff --git a/libfreerdp/core/orders.c b/libfreerdp/core/orders.c index 66531b52b..60aed90b8 100644 --- a/libfreerdp/core/orders.c +++ b/libfreerdp/core/orders.c @@ -500,7 +500,10 @@ static INLINE BOOL update_read_delta(wStream* s, INT32* value) BYTE byte; if (Stream_GetRemainingLength(s) < 1) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; + } Stream_Read_UINT8(s, byte); if (byte & 0x40) @@ -511,7 +514,10 @@ static INLINE BOOL update_read_delta(wStream* s, INT32* value) if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; + } Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } @@ -723,7 +729,10 @@ static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int zeroBitsSize = ((number + 3) / 4); if (Stream_GetRemainingLength(s) < zeroBitsSize) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %i", zeroBitsSize); return FALSE; + } Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); @@ -736,10 +745,16 @@ static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int flags = zeroBits[i / 4]; if ((~flags & 0x80) && !update_read_delta(s, &points[i].x)) + { + WLog_ERR(TAG, "update_read_delta(x) failed"); return FALSE; + } if ((~flags & 0x40) && !update_read_delta(s, &points[i].y)) + { + WLog_ERR(TAG, "update_read_delta(y) failed"); return FALSE; + } flags <<= 2; } @@ -1336,12 +1351,18 @@ BOOL update_read_polyline_order(wStream* s, ORDER_INFO* orderInfo, POLYLINE_ORDE DELTA_POINT *new_points; if (Stream_GetRemainingLength(s) < 1) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; + } Stream_Read_UINT8(s, polyline->cbData); new_points = (DELTA_POINT*) realloc(polyline->points, sizeof(DELTA_POINT) * new_num); if (!new_points) + { + WLog_ERR(TAG, "realloc(%i) failed", new_num); return FALSE; + } polyline->points = new_points; polyline->numDeltaEntries = new_num; @@ -2280,6 +2301,8 @@ BOOL update_read_cache_glyph_order(wStream* s, CACHE_GLYPH_ORDER* cache_glyph_or return FALSE; glyph->aj = (BYTE*) malloc(glyph->cb); + if (!glyph->aj) + return FALSE; Stream_Read(s, glyph->aj, glyph->cb); } @@ -2370,6 +2393,8 @@ BOOL update_read_cache_glyph_v2_order(wStream* s, CACHE_GLYPH_V2_ORDER* cache_gl return FALSE; glyph->aj = (BYTE*) malloc(glyph->cb); + if (!glyph->aj) + return FALSE; Stream_Read(s, glyph->aj, glyph->cb); } @@ -3135,14 +3160,20 @@ BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags) if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType])) + { + WLog_ERR(TAG, "update_read_field_flags() failed"); return FALSE; + } if (flags & ORDER_BOUNDS) { if (!(flags & ORDER_ZERO_BOUNDS_DELTAS)) { if (!update_read_bounds(s, &orderInfo->bounds)) + { + WLog_ERR(TAG, "update_read_bounds() failed"); return FALSE; + } } IFCALL(update->SetBounds, context, &orderInfo->bounds); @@ -3158,154 +3189,220 @@ BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags) { case ORDER_TYPE_DSTBLT: if (!update_read_dstblt_order(s, orderInfo, &(primary->dstblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_DSTBLT - update_read_dstblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DstBlt"); IFCALL(primary->DstBlt, context, &primary->dstblt); break; case ORDER_TYPE_PATBLT: if (!update_read_patblt_order(s, orderInfo, &(primary->patblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_PATBLT - update_read_patblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "PatBlt"); IFCALL(primary->PatBlt, context, &primary->patblt); break; case ORDER_TYPE_SCRBLT: if (!update_read_scrblt_order(s, orderInfo, &(primary->scrblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_SCRBLT - update_read_scrblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "ScrBlt"); IFCALL(primary->ScrBlt, context, &primary->scrblt); break; case ORDER_TYPE_OPAQUE_RECT: if (!update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect))) + { + WLog_ERR(TAG, "ORDER_TYPE_OPAQUE_RECT - update_read_opaque_rect_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "OpaqueRect"); IFCALL(primary->OpaqueRect, context, &primary->opaque_rect); break; case ORDER_TYPE_DRAW_NINE_GRID: if (!update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid))) + { + WLog_ERR(TAG, "ORDER_TYPE_DRAW_NINE_GRID - update_read_draw_nine_grid_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawNineGrid"); IFCALL(primary->DrawNineGrid, context, &primary->draw_nine_grid); break; case ORDER_TYPE_MULTI_DSTBLT: if (!update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_MULTI_DSTBLT - update_read_multi_dstblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "MultiDstBlt"); IFCALL(primary->MultiDstBlt, context, &primary->multi_dstblt); break; case ORDER_TYPE_MULTI_PATBLT: if (!update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_MULTI_PATBLT - update_read_multi_patblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "MultiPatBlt"); IFCALL(primary->MultiPatBlt, context, &primary->multi_patblt); break; case ORDER_TYPE_MULTI_SCRBLT: if (!update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_MULTI_SCRBLT - update_read_multi_scrblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "MultiScrBlt"); IFCALL(primary->MultiScrBlt, context, &primary->multi_scrblt); break; case ORDER_TYPE_MULTI_OPAQUE_RECT: if (!update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect))) + { + WLog_ERR(TAG, "ORDER_TYPE_MULTI_OPAQUE_RECT - update_read_multi_opaque_rect_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "MultiOpaqueRect"); IFCALL(primary->MultiOpaqueRect, context, &primary->multi_opaque_rect); break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: if (!update_read_multi_draw_nine_grid_order(s, orderInfo, &(primary->multi_draw_nine_grid))) + { + WLog_ERR(TAG, "ORDER_TYPE_MULTI_DRAW_NINE_GRID - update_read_multi_draw_nine_grid_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "MultiDrawNineGrid"); IFCALL(primary->MultiDrawNineGrid, context, &primary->multi_draw_nine_grid); break; case ORDER_TYPE_LINE_TO: if (!update_read_line_to_order(s, orderInfo, &(primary->line_to))) + { + WLog_ERR(TAG, "ORDER_TYPE_LINE_TO - update_read_line_to_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "LineTo"); IFCALL(primary->LineTo, context, &primary->line_to); break; case ORDER_TYPE_POLYLINE: if (!update_read_polyline_order(s, orderInfo, &(primary->polyline))) + { + WLog_ERR(TAG, "ORDER_TYPE_POLYLINE - update_read_polyline_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "Polyline"); IFCALL(primary->Polyline, context, &primary->polyline); break; case ORDER_TYPE_MEMBLT: if (!update_read_memblt_order(s, orderInfo, &(primary->memblt))) + { + WLog_ERR(TAG, "ORDER_TYPE_MEMBLT - update_read_memblt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "MemBlt"); IFCALL(primary->MemBlt, context, &primary->memblt); break; case ORDER_TYPE_MEM3BLT: if (!update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt))) + { + WLog_ERR(TAG, "ORDER_TYPE_MEM3BLT - update_read_mem3blt_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "Mem3Blt"); IFCALL(primary->Mem3Blt, context, &primary->mem3blt); break; case ORDER_TYPE_SAVE_BITMAP: if (!update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap))) + { + WLog_ERR(TAG, "ORDER_TYPE_SAVE_BITMAP - update_read_save_bitmap_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "SaveBitmap"); IFCALL(primary->SaveBitmap, context, &primary->save_bitmap); break; case ORDER_TYPE_GLYPH_INDEX: if (!update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index))) + { + WLog_ERR(TAG, "ORDER_TYPE_GLYPH_INDEX - update_read_glyph_index_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "GlyphIndex"); IFCALL(primary->GlyphIndex, context, &primary->glyph_index); break; case ORDER_TYPE_FAST_INDEX: if (!update_read_fast_index_order(s, orderInfo, &(primary->fast_index))) + { + WLog_ERR(TAG, "ORDER_TYPE_FAST_INDEX - update_read_fast_index_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "FastIndex"); IFCALL(primary->FastIndex, context, &primary->fast_index); break; case ORDER_TYPE_FAST_GLYPH: if (!update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph))) + { + WLog_ERR(TAG, "ORDER_TYPE_FAST_GLYPH - update_read_fast_glyph_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "FastGlyph"); IFCALL(primary->FastGlyph, context, &primary->fast_glyph); break; case ORDER_TYPE_POLYGON_SC: if (!update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc))) + { + WLog_ERR(TAG, "ORDER_TYPE_POLYGON_SC - update_read_polygon_sc_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "PolygonSC"); IFCALL(primary->PolygonSC, context, &primary->polygon_sc); break; case ORDER_TYPE_POLYGON_CB: if (!update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb))) + { + WLog_ERR(TAG, "ORDER_TYPE_POLYGON_CB - update_read_polygon_cb_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "PolygonCB"); IFCALL(primary->PolygonCB, context, &primary->polygon_cb); break; case ORDER_TYPE_ELLIPSE_SC: if (!update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc))) + { + WLog_ERR(TAG, "ORDER_TYPE_ELLIPSE_SC - update_read_ellipse_sc_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "EllipseSC"); IFCALL(primary->EllipseSC, context, &primary->ellipse_sc); break; case ORDER_TYPE_ELLIPSE_CB: if (!update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb))) + { + WLog_ERR(TAG, "ORDER_TYPE_ELLIPSE_CB - update_read_ellipse_cb_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "EllipseCB"); IFCALL(primary->EllipseCB, context, &primary->ellipse_cb); break; @@ -3332,7 +3429,10 @@ BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) rdpSecondaryUpdate* secondary = update->secondary; if (Stream_GetRemainingLength(s) < 5) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 5"); return FALSE; + } Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ @@ -3351,42 +3451,60 @@ BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: if (!update_read_cache_bitmap_order(s, &(secondary->cache_bitmap_order), FALSE, extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_BITMAP_UNCOMPRESSED - update_read_cache_bitmap_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheBitmapUncompressed"); IFCALL(secondary->CacheBitmap, context, &(secondary->cache_bitmap_order)); break; case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: if (!update_read_cache_bitmap_order(s, &(secondary->cache_bitmap_order), TRUE, extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_CACHE_BITMAP_COMPRESSED - update_read_cache_bitmap_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheBitmapCompressed"); IFCALL(secondary->CacheBitmap, context, &(secondary->cache_bitmap_order)); break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: if (!update_read_cache_bitmap_v2_order(s, &(secondary->cache_bitmap_v2_order), FALSE, extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_BITMAP_UNCOMPRESSED_V2 - update_read_cache_bitmap_v2_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheBitmapUncompressedV2"); IFCALL(secondary->CacheBitmapV2, context, &(secondary->cache_bitmap_v2_order)); break; case ORDER_TYPE_BITMAP_COMPRESSED_V2: if (!update_read_cache_bitmap_v2_order(s, &(secondary->cache_bitmap_v2_order), TRUE, extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_BITMAP_COMPRESSED_V2 - update_read_cache_bitmap_v2_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheBitmapCompressedV2"); IFCALL(secondary->CacheBitmapV2, context, &(secondary->cache_bitmap_v2_order)); break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: if (!update_read_cache_bitmap_v3_order(s, &(secondary->cache_bitmap_v3_order), extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_BITMAP_COMPRESSED_V3 - update_read_cache_bitmap_v3_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheBitmapCompressedV3"); IFCALL(secondary->CacheBitmapV3, context, &(secondary->cache_bitmap_v3_order)); break; case ORDER_TYPE_CACHE_COLOR_TABLE: if (!update_read_cache_color_table_order(s, &(secondary->cache_color_table_order), extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_CACHE_COLOR_TABLE - update_read_cache_color_table_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheColorTable"); IFCALL(secondary->CacheColorTable, context, &(secondary->cache_color_table_order)); break; @@ -3395,14 +3513,20 @@ BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) if (secondary->glyph_v2) { if (!update_read_cache_glyph_v2_order(s, &(secondary->cache_glyph_v2_order), extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_CACHE_GLYPH - update_read_cache_glyph_v2_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheGlyphV2"); IFCALL(secondary->CacheGlyphV2, context, &(secondary->cache_glyph_v2_order)); } else { if (!update_read_cache_glyph_order(s, &(secondary->cache_glyph_order), extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_CACHE_GLYPH - update_read_cache_glyph_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheGlyph"); IFCALL(secondary->CacheGlyph, context, &(secondary->cache_glyph_order)); } @@ -3410,7 +3534,10 @@ BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) case ORDER_TYPE_CACHE_BRUSH: if (!update_read_cache_brush_order(s, &(secondary->cache_brush_order), extraFlags)) + { + WLog_ERR(TAG, "ORDER_TYPE_CACHE_BRUSH - update_read_cache_brush_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CacheBrush"); IFCALL(secondary->CacheBrush, context, &(secondary->cache_brush_order)); break; @@ -3434,37 +3561,49 @@ BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags) #ifdef WITH_DEBUG_ORDERS if (orderType < ALTSEC_DRAWING_ORDER_COUNT) - WLog_DBG(TAG, "%s Alternate Secondary Drawing Order (0x%02X)", ALTSEC_DRAWING_ORDER_STRINGS[orderType], orderType); + WLog_DBG(TAG, "%s Alternate Secondary Drawing Order (0x%02X)", ALTSEC_DRAWING_ORDER_STRINGS[orderType], orderType); else - WLog_DBG(TAG, "Unknown Alternate Secondary Drawing Order: 0x%02X", orderType); + WLog_DBG(TAG, "Unknown Alternate Secondary Drawing Order: 0x%02X", orderType); #endif switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: if (!update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap))) + { + WLog_ERR(TAG, "ORDER_TYPE_CREATE_OFFSCREEN_BITMAP - update_read_create_offscreen_bitmap_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CreateOffscreenBitmap"); IFCALL(altsec->CreateOffscreenBitmap, context, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: if (!update_read_switch_surface_order(s, &(altsec->switch_surface))) + { + WLog_ERR(TAG, "ORDER_TYPE_SWITCH_SURFACE - update_read_switch_surface_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "SwitchSurface"); IFCALL(altsec->SwitchSurface, context, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: if (!update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap))) + { + WLog_ERR(TAG, "ORDER_TYPE_CREATE_NINE_GRID_BITMAP - update_read_create_nine_grid_bitmap_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "CreateNineGridBitmap"); IFCALL(altsec->CreateNineGridBitmap, context, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: if (!update_read_frame_marker_order(s, &(altsec->frame_marker))) + { + WLog_ERR(TAG, "ORDER_TYPE_FRAME_MARKER - update_read_frame_marker_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "AltSecFrameMarker: action: %s (%d)", (!altsec->frame_marker.action) ? "Begin" : "End", altsec->frame_marker.action); IFCALL(altsec->FrameMarker, context, &(altsec->frame_marker)); @@ -3472,56 +3611,80 @@ BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags) case ORDER_TYPE_STREAM_BITMAP_FIRST: if (!update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first))) + { + WLog_ERR(TAG, "ORDER_TYPE_STREAM_BITMAP_FIRST - update_read_stream_bitmap_first_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "StreamBitmapFirst"); IFCALL(altsec->StreamBitmapFirst, context, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: if (!update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next))) + { + WLog_ERR(TAG, "ORDER_TYPE_STREAM_BITMAP_NEXT - update_read_stream_bitmap_next_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "StreamBitmapNext"); IFCALL(altsec->StreamBitmapNext, context, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: if (!update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first))) + { + WLog_ERR(TAG, "ORDER_TYPE_GDIPLUS_FIRST - update_read_draw_gdiplus_first_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawGdiPlusFirst"); IFCALL(altsec->DrawGdiPlusFirst, context, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: if (!update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next))) + { + WLog_ERR(TAG, "ORDER_TYPE_GDIPLUS_NEXT - update_read_draw_gdiplus_next_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawGdiPlusNext"); IFCALL(altsec->DrawGdiPlusNext, context, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: if (update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end))) + { + WLog_ERR(TAG, "ORDER_TYPE_GDIPLUS_END - update_read_draw_gdiplus_end_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawGdiPlusEnd"); IFCALL(altsec->DrawGdiPlusEnd, context, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: if (!update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first))) + { + WLog_ERR(TAG, "ORDER_TYPE_GDIPLUS_CACHE_FIRST - update_read_draw_gdiplus_cache_first_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawGdiPlusCacheFirst"); IFCALL(altsec->DrawGdiPlusCacheFirst, context, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: if (!update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next))) + { + WLog_ERR(TAG, "ORDER_TYPE_GDIPLUS_CACHE_NEXT - update_read_draw_gdiplus_cache_next_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawGdiPlusCacheNext"); IFCALL(altsec->DrawGdiPlusCacheNext, context, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: if (!update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end))) + { + WLog_ERR(TAG, "ORDER_TYPE_GDIPLUS_CACHE_END - update_read_draw_gdiplus_cache_end_order() failed"); return FALSE; + } WLog_Print(update->log, WLOG_DEBUG, "DrawGdiPlusCacheEnd"); IFCALL(altsec->DrawGdiPlusCacheEnd, context, &(altsec->draw_gdiplus_cache_end)); break; @@ -3544,7 +3707,10 @@ BOOL update_recv_order(rdpUpdate* update, wStream* s) BYTE controlFlags; if (Stream_GetRemainingLength(s) < 1) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; + } Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */ diff --git a/libfreerdp/core/peer.c b/libfreerdp/core/peer.c index bbde82a65..f4c41ff97 100644 --- a/libfreerdp/core/peer.c +++ b/libfreerdp/core/peer.c @@ -331,7 +331,7 @@ static BOOL peer_recv_data_pdu(freerdp_peer* client, wStream* s) break; default: - WLog_ERR(TAG, "Data PDU type %d", type); + WLog_ERR(TAG, "Data PDU type %d", type); break; } @@ -352,7 +352,7 @@ static int peer_recv_tpkt_pdu(freerdp_peer* client, wStream* s) if (!rdp_read_header(rdp, s, &length, &channelId)) { - WLog_ERR(TAG, "Incorrect RDP header."); + WLog_ERR(TAG, "Incorrect RDP header."); return -1; } @@ -368,7 +368,7 @@ static int peer_recv_tpkt_pdu(freerdp_peer* client, wStream* s) { if (!rdp_decrypt(rdp, s, length - 4, securityFlags)) { - WLog_ERR(TAG, "rdp_decrypt failed"); + WLog_ERR(TAG, "rdp_decrypt failed"); return -1; } } @@ -399,13 +399,17 @@ static int peer_recv_tpkt_pdu(freerdp_peer* client, wStream* s) break; default: - WLog_ERR(TAG, "Client sent pduType %d", pduType); + WLog_ERR(TAG, "Client sent pduType %d", pduType); return -1; } } else if (rdp->mcs->messageChannelId && channelId == rdp->mcs->messageChannelId) { - return rdp_recv_message_channel_pdu(rdp, s); + if (!rdp->settings->UseRdpSecurityLayer) + if (!rdp_read_security_header(s, &securityFlags)) + return -1; + + return rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { @@ -429,7 +433,7 @@ static int peer_recv_fastpath_pdu(freerdp_peer* client, wStream* s) if ((length == 0) || (length > Stream_GetRemainingLength(s))) { - WLog_ERR(TAG, "incorrect FastPath PDU header length %d", length); + WLog_ERR(TAG, "incorrect FastPath PDU header length %d", length); return -1; } @@ -459,11 +463,14 @@ static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_INITIAL - rdp_server_accept_nego() fail"); return -1; + } if (rdp->nego->SelectedProtocol & PROTOCOL_NLA) { - sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->nla->identity)); + sspi_CopyAuthIdentity(&client->identity, rdp->nego->transport->nla->identity); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); nla_free(rdp->nego->transport->nla); rdp->nego->transport->nla = NULL; @@ -477,29 +484,44 @@ static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_NEGO - rdp_server_accept_mcs_connect_initial() fail"); return -1; + } break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_MCS_CONNECT - rdp_server_accept_mcs_erect_domain_request() fail"); return -1; + } break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_MCS_ERECT_DOMAIN - rdp_server_accept_mcs_attach_user_request() fail"); return -1; + } break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_MCS_ATTACH_USER - rdp_server_accept_mcs_channel_join_request() fail"); return -1; + } break; case CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT: if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_server_establish_keys(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT - rdp_server_establish_keys() fail"); return -1; + } } rdp_server_transition_to_state(rdp, CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE); @@ -508,9 +530,11 @@ static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) break; case CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE: - if (!rdp_recv_client_info(rdp, s)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE - rdp_recv_client_info() fail"); return -1; + } rdp_server_transition_to_state(rdp, CONNECTION_STATE_LICENSING); return peer_recv_callback(transport, NULL, extra); @@ -518,9 +542,11 @@ static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) break; case CONNECTION_STATE_LICENSING: - if (!license_send_valid_client_error_packet(rdp->license)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_LICENSING - license_send_valid_client_error_packet() fail"); return FALSE; + } rdp_server_transition_to_state(rdp, CONNECTION_STATE_CAPABILITIES_EXCHANGE); return peer_recv_callback(transport, NULL, extra); @@ -534,14 +560,20 @@ static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_CAPABILITIES_EXCHANGE - rdp_send_demand_active() fail"); return -1; + } rdp->AwaitCapabilities = TRUE; if (s) { if (peer_recv_pdu(client, s) < 0) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_CAPABILITIES_EXCHANGE - peer_recv_pdu() fail"); return -1; + } } } else @@ -552,23 +584,32 @@ static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) */ if (peer_recv_pdu(client, s) < 0) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_CAPABILITIES_EXCHANGE - peer_recv_pdu() fail"); return -1; + } } break; case CONNECTION_STATE_FINALIZATION: if (peer_recv_pdu(client, s) < 0) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_FINALIZATION - peer_recv_pdu() fail"); return -1; + } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) + { + WLog_ERR(TAG, "peer_recv_callback: CONNECTION_STATE_ACTIVE - peer_recv_pdu() fail"); return -1; + } break; default: - WLog_ERR(TAG, "Invalid state %d", rdp->state); + WLog_ERR(TAG, "Invalid state %d", rdp->state); return -1; } diff --git a/libfreerdp/core/rdp.c b/libfreerdp/core/rdp.c index 5d2ff7c52..fac827aab 100644 --- a/libfreerdp/core/rdp.c +++ b/libfreerdp/core/rdp.c @@ -768,7 +768,10 @@ int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) UINT16 compressedLength; if (!rdp_read_share_data_header(s, &length, &type, &shareId, &compressedType, &compressedLength)) + { + WLog_ERR(TAG, "rdp_read_share_data_header() failed"); return -1; + } cs = s; @@ -815,72 +818,114 @@ int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_UPDATE - update_recv() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_CONTROL - rdp_recv_server_control_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_POINTER - update_recv_pointer() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_SYNCHRONIZE - rdp_recv_synchronize_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_PLAY_SOUND - update_recv_play_sound() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: if (!rdp_recv_server_shutdown_denied_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_SHUTDOWN_DENIED - rdp_recv_server_shutdown_denied_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if (!rdp_recv_save_session_info(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_SAVE_SESSION_INFO - rdp_recv_save_session_info() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_FONT_MAP: if (!rdp_recv_font_map_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_FONT_MAP - rdp_recv_font_map_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: if (!rdp_recv_server_set_keyboard_indicators_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS - rdp_recv_server_set_keyboard_indicators_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: if (!rdp_recv_server_set_keyboard_ime_status_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS - rdp_recv_server_set_keyboard_ime_status_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_SET_ERROR_INFO - rdp_recv_set_error_info_data_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_ARC_STATUS: if (!rdp_recv_server_auto_reconnect_status_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_ARC_STATUS - rdp_recv_server_auto_reconnect_status_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_STATUS_INFO: if (!rdp_recv_server_status_info_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_STATUS_INFO - rdp_recv_server_status_info_pdu() failed"); goto out_fail; + } break; case DATA_PDU_TYPE_MONITOR_LAYOUT: if (!rdp_recv_monitor_layout_pdu(rdp, cs)) + { + WLog_ERR(TAG, "DATA_PDU_TYPE_MONITOR_LAYOUT - rdp_recv_monitor_layout_pdu() failed"); goto out_fail; + } break; default: @@ -898,13 +943,8 @@ out_fail: return -1; } -int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s) +int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags) { - UINT16 securityFlags; - - if (!rdp_read_security_header(s, &securityFlags)) - return -1; - if (securityFlags & SEC_AUTODETECT_REQ) { /* Server Auto-Detect Request PDU */ @@ -1092,7 +1132,10 @@ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags)) + { + WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_security_header() fail"); return -1; + } if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { @@ -1122,7 +1165,10 @@ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) nextPosition = Stream_GetPosition(s); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) + { + WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() fail"); return -1; + } nextPosition += pduLength; @@ -1133,14 +1179,17 @@ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) case PDU_TYPE_DATA: if (rdp_recv_data_pdu(rdp, s) < 0) { - WLog_ERR(TAG, "rdp_recv_data_pdu failed"); + WLog_ERR(TAG, "rdp_recv_data_pdu() failed"); return -1; } break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) + { + WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_recv_deactivate_all() fail"); return -1; + } break; case PDU_TYPE_SERVER_REDIRECTION: @@ -1162,12 +1211,19 @@ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) } else if (rdp->mcs->messageChannelId && channelId == rdp->mcs->messageChannelId) { - return rdp_recv_message_channel_pdu(rdp, s); + if (!rdp->settings->UseRdpSecurityLayer) + if (!rdp_read_security_header(s, &securityFlags)) + return -1; + + return rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { if (!freerdp_channel_process(rdp->instance, s, channelId)) + { + WLog_ERR(TAG, "rdp_recv_tpkt_pdu: freerdp_channel_process() fail"); return -1; + } } return 0; @@ -1181,7 +1237,10 @@ static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) + { + WLog_ERR(TAG, "rdp_recv_fastpath_pdu: fastpath_read_header_rdp() fail"); return -1; + } if ((length == 0) || (length > Stream_GetRemainingLength(s))) { @@ -1199,7 +1258,10 @@ static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, length, flags)) + { + WLog_ERR(TAG, "rdp_recv_fastpath_pdu: rdp_decrypt() fail"); return -1; + } } return fastpath_recv_updates(rdp->fastpath, s); @@ -1234,7 +1296,10 @@ int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) { case CONNECTION_STATE_NLA: if (nla_recv_pdu(rdp->nla, s) < 1) + { + WLog_ERR(TAG, "rdp_recv_callback: CONNECTION_STATE_NLA - nla_recv_pdu() fail"); return -1; + } if (rdp->nla->state == NLA_STATE_AUTH_INFO) { @@ -1244,7 +1309,10 @@ int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) rdp->nla = NULL; if (!mcs_client_begin(rdp->mcs)) + { + WLog_ERR(TAG, "rdp_recv_callback: CONNECTION_STATE_NLA - mcs_client_begin() fail"); return -1; + } } break; @@ -1289,15 +1357,22 @@ int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) + { + WLog_ERR(TAG, "rdp_recv_callback: CONNECTION_STATE_MCS_CHANNEL_JOIN - rdp_client_connect_mcs_channel_join_confirm() fail"); status = -1; + } break; case CONNECTION_STATE_LICENSING: status = rdp_client_connect_license(rdp, s); + if (status < 0) + WLog_DBG(TAG, "CONNECTION_STATE_LICENSING - rdp_client_connect_license() - %i", status); break; case CONNECTION_STATE_CAPABILITIES_EXCHANGE: status = rdp_client_connect_demand_active(rdp, s); + if (status < 0) + WLog_DBG(TAG, "CONNECTION_STATE_CAPABILITIES_EXCHANGE - rdp_client_connect_demand_active() - %i", status); break; case CONNECTION_STATE_FINALIZATION: @@ -1308,10 +1383,14 @@ int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) rdp_client_transition_to_state(rdp, CONNECTION_STATE_ACTIVE); return 2; } + if (status < 0) + WLog_DBG(TAG, "CONNECTION_STATE_FINALIZATION - rdp_recv_pdu() - %i", status); break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); + if (status < 0) + WLog_DBG(TAG, "CONNECTION_STATE_ACTIVE - rdp_recv_pdu() - %i", status); break; default: @@ -1357,7 +1436,10 @@ int rdp_check_fds(rdpRdp* rdp) status = tsg_check_event_handles(tsg); if (status < 0) + { + WLog_ERR(TAG, "rdp_check_fds: tsg_check_event_handles() - %i", status); return -1; + } if (tsg->state != TSG_STATE_PIPE_CREATED) return status; @@ -1369,6 +1451,8 @@ int rdp_check_fds(rdpRdp* rdp) { status = rdp_client_redirect(rdp); /* session redirection */ } + if (status < 0) + WLog_DBG(TAG, "transport_check_fds() - %i", status); return status; } diff --git a/libfreerdp/core/rdp.h b/libfreerdp/core/rdp.h index c53273f77..6ae6dc88b 100644 --- a/libfreerdp/core/rdp.h +++ b/libfreerdp/core/rdp.h @@ -209,7 +209,7 @@ int rdp_send_channel_data(rdpRdp* rdp, UINT16 channelId, BYTE* data, int size); wStream* rdp_message_channel_pdu_init(rdpRdp* rdp); BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags); -int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s); +int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags); int rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, wStream* s); diff --git a/libfreerdp/core/redirection.c b/libfreerdp/core/redirection.c index 2fdcff55d..f75a0945f 100644 --- a/libfreerdp/core/redirection.c +++ b/libfreerdp/core/redirection.c @@ -134,28 +134,38 @@ int rdp_redirection_apply_settings(rdpRdp* rdp) { free(settings->RedirectionTargetFQDN); settings->RedirectionTargetFQDN = _strdup(redirection->TargetFQDN); + if (!settings->RedirectionTargetFQDN) + return -1; } else if (settings->RedirectionFlags & LB_TARGET_NET_ADDRESS) { free(settings->TargetNetAddress); settings->TargetNetAddress = _strdup(redirection->TargetNetAddress); + if (!settings->TargetNetAddress) + return -1; } else if (settings->RedirectionFlags & LB_TARGET_NETBIOS_NAME) { free(settings->RedirectionTargetNetBiosName); settings->RedirectionTargetNetBiosName = _strdup(redirection->TargetNetBiosName); + if (!settings->RedirectionTargetNetBiosName) + return -1; } if (settings->RedirectionFlags & LB_USERNAME) { free(settings->RedirectionUsername); settings->RedirectionUsername = _strdup(redirection->Username); + if (!settings->RedirectionUsername) + return -1; } if (settings->RedirectionFlags & LB_DOMAIN) { free(settings->RedirectionDomain); settings->RedirectionDomain = _strdup(redirection->Domain); + if (!settings->RedirectionDomain) + return -1; } if (settings->RedirectionFlags & LB_PASSWORD) @@ -164,6 +174,8 @@ int rdp_redirection_apply_settings(rdpRdp* rdp) free(settings->RedirectionPassword); settings->RedirectionPasswordLength = redirection->PasswordLength; settings->RedirectionPassword = (BYTE*) malloc(settings->RedirectionPasswordLength); + if (!settings->RedirectionPassword) + return -1; CopyMemory(settings->RedirectionPassword, redirection->Password, settings->RedirectionPasswordLength); } @@ -173,6 +185,8 @@ int rdp_redirection_apply_settings(rdpRdp* rdp) free(settings->RedirectionTsvUrl); settings->RedirectionTsvUrlLength = redirection->TsvUrlLength; settings->RedirectionTsvUrl = (BYTE*) malloc(settings->RedirectionTsvUrlLength); + if (!settings->RedirectionTsvUrl) + return -1; CopyMemory(settings->RedirectionTsvUrl, redirection->TsvUrl, settings->RedirectionTsvUrlLength); } @@ -182,10 +196,23 @@ int rdp_redirection_apply_settings(rdpRdp* rdp) freerdp_target_net_addresses_free(settings); settings->TargetNetAddressCount = redirection->TargetNetAddressesCount; settings->TargetNetAddresses = (char**) malloc(sizeof(char*) * settings->TargetNetAddressCount); + if (!settings->TargetNetAddresses) + { + settings->TargetNetAddressCount = 0; + return -1; + } for (i = 0; i < settings->TargetNetAddressCount; i++) { settings->TargetNetAddresses[i] = _strdup(redirection->TargetNetAddresses[i]); + if (!settings->TargetNetAddresses[i]) + { + UINT32 j; + + for (j=0; j < i; j++) + free(settings->TargetNetAddresses[j]); + return -1; + } } } @@ -228,6 +255,8 @@ BOOL rdp_recv_server_redirection_pdu(rdpRdp* rdp, wStream* s) return -1; redirection->LoadBalanceInfo = (BYTE*) malloc(redirection->LoadBalanceInfoLength); + if (!redirection->LoadBalanceInfo) + return -1; Stream_Read(s, redirection->LoadBalanceInfo, redirection->LoadBalanceInfoLength); WLog_DBG(TAG, "loadBalanceInfo:"); @@ -258,6 +287,8 @@ BOOL rdp_recv_server_redirection_pdu(rdpRdp* rdp, wStream* s) Stream_Read_UINT32(s, redirection->PasswordLength); redirection->Password = (BYTE*) malloc(redirection->PasswordLength); + if (!redirection->Password) + return -1; Stream_Read(s, redirection->Password, redirection->PasswordLength); WLog_DBG(TAG, "PasswordCookie:"); @@ -291,6 +322,8 @@ BOOL rdp_recv_server_redirection_pdu(rdpRdp* rdp, wStream* s) return -1; redirection->TsvUrl = (BYTE*) malloc(redirection->TsvUrlLength); + if (!redirection->TsvUrl) + return -1; Stream_Read(s, redirection->TsvUrl, redirection->TsvUrlLength); WLog_DBG(TAG, "TsvUrl:"); diff --git a/libfreerdp/core/server.c b/libfreerdp/core/server.c index 20f6e8809..0806ab820 100644 --- a/libfreerdp/core/server.c +++ b/libfreerdp/core/server.c @@ -200,7 +200,7 @@ static BOOL wts_read_drdynvc_data_first(rdpPeerChannel* channel, wStream* s, int static BOOL wts_read_drdynvc_data(rdpPeerChannel* channel, wStream* s, UINT32 length) { - BOOL ret; + BOOL ret = FALSE; if (channel->dvc_total_length > 0) { if (Stream_GetPosition(channel->receiveData) + length > channel->dvc_total_length) @@ -852,6 +852,11 @@ BOOL WINAPI FreeRDP_WTSQuerySessionInformationA(HANDLE hServer, DWORD SessionId, BytesReturned = sizeof(ULONG); pBuffer = (ULONG*) malloc(sizeof(BytesReturned)); + if (!pBuffer) + { + SetLastError(E_OUTOFMEMORY); + return FALSE; + } *pBuffer = vcm->SessionId; @@ -1212,7 +1217,10 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, length = Length; buffer = (BYTE *)malloc(length); if (!buffer) + { + SetLastError(E_OUTOFMEMORY); return FALSE; + } CopyMemory(buffer, Buffer, length); ret = wts_queue_send_item(channel, buffer, length); @@ -1232,6 +1240,7 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelWrite(HANDLE hChannelHandle, PCHAR Buffer, if (!s) { WLog_ERR(TAG, "Stream_New failed!"); + SetLastError(E_OUTOFMEMORY); return FALSE; } @@ -1309,16 +1318,26 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelQuery(HANDLE hChannelHandle, WTS_VIRTUAL_CL } *ppBuffer = malloc(sizeof(void*)); - CopyMemory(*ppBuffer, &fds[0], sizeof(void*)); - *pBytesReturned = sizeof(void*); - status = TRUE; + if (!*ppBuffer) + { + SetLastError(E_OUTOFMEMORY); + } else { + CopyMemory(*ppBuffer, &fds[0], sizeof(void*)); + *pBytesReturned = sizeof(void*); + status = TRUE; + } break; case WTSVirtualEventHandle: *ppBuffer = malloc(sizeof(HANDLE)); - CopyMemory(*ppBuffer, &(hEvent), sizeof(HANDLE)); - *pBytesReturned = sizeof(void*); - status = TRUE; + if (!*ppBuffer) + { + SetLastError(E_OUTOFMEMORY); + } else { + CopyMemory(*ppBuffer, &(hEvent), sizeof(HANDLE)); + *pBytesReturned = sizeof(void*); + status = TRUE; + } break; case WTSVirtualChannelReady: @@ -1349,8 +1368,14 @@ BOOL WINAPI FreeRDP_WTSVirtualChannelQuery(HANDLE hChannelHandle, WTS_VIRTUAL_CL } *ppBuffer = malloc(sizeof(BOOL)); - CopyMemory(*ppBuffer, &bval, sizeof(BOOL)); - *pBytesReturned = sizeof(BOOL); + if (!*ppBuffer) + { + SetLastError(E_OUTOFMEMORY); + status = FALSE; + } else { + CopyMemory(*ppBuffer, &bval, sizeof(BOOL)); + *pBytesReturned = sizeof(BOOL); + } break; default: diff --git a/libfreerdp/core/settings.c b/libfreerdp/core/settings.c index 339baa684..9303aa7c7 100644 --- a/libfreerdp/core/settings.c +++ b/libfreerdp/core/settings.c @@ -37,6 +37,8 @@ #include #include +#include + #ifdef _WIN32 #pragma warning(push) @@ -55,6 +57,14 @@ static const char client_dll[] = "C:\\Windows\\System32\\mstscax.dll"; if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \ _result = _value ? TRUE : FALSE +#define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \ + FREERDP_PRODUCT_STRING "\\Server" +#define CLIENT_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \ + FREERDP_PRODUCT_STRING "\\Client" +#define BITMAP_CACHE_KEY CLIENT_KEY "\\BitmapCacheV2" +#define GLYPH_CACHE_KEY CLIENT_KEY "\\GlyphCache" +#define POINTER_CACHE_KEY CLIENT_KEY "\\PointerCache" + void settings_client_load_hkey_local_machine(rdpSettings* settings) { HKEY hKey; @@ -63,7 +73,7 @@ void settings_client_load_hkey_local_machine(rdpSettings* settings) DWORD dwSize; DWORD dwValue; - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Client"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, CLIENT_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { @@ -95,7 +105,8 @@ void settings_client_load_hkey_local_machine(rdpSettings* settings) RegCloseKey(hKey); } - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Client\\BitmapCacheV2"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, BITMAP_CACHE_KEY, 0, + KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { @@ -117,7 +128,8 @@ void settings_client_load_hkey_local_machine(rdpSettings* settings) RegCloseKey(hKey); } - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Client\\GlyphCache"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, GLYPH_CACHE_KEY, + 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { @@ -150,7 +162,8 @@ void settings_client_load_hkey_local_machine(rdpSettings* settings) RegCloseKey(hKey); } - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Client\\PointerCache"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, POINTER_CACHE_KEY, + 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { @@ -170,7 +183,8 @@ void settings_server_load_hkey_local_machine(rdpSettings* settings) DWORD dwSize; DWORD dwValue; - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, + 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status != ERROR_SUCCESS) return; @@ -191,15 +205,19 @@ void settings_load_hkey_local_machine(rdpSettings* settings) settings_client_load_hkey_local_machine(settings); } -void settings_get_computer_name(rdpSettings* settings) +BOOL settings_get_computer_name(rdpSettings* settings) { - DWORD nSize = 0; + DWORD nSize = MAX_COMPUTERNAME_LENGTH + 1; + CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1]; - GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize); - settings->ComputerName = (char*) malloc(nSize); + if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize)) + return FALSE; + + settings->ComputerName = _strdup(computerName); if (!settings->ComputerName) - return; - GetComputerNameExA(ComputerNameNetBIOS, settings->ComputerName, &nSize); + return FALSE; + + return TRUE; } rdpSettings* freerdp_settings_new(DWORD flags) @@ -288,7 +306,8 @@ rdpSettings* freerdp_settings_new(DWORD flags) if(!settings->MonitorIds) goto out_fail; - settings_get_computer_name(settings); + if (!settings_get_computer_name(settings)) + goto out_fail; settings->ReceivedCapabilities = calloc(1, 32); if (!settings->ReceivedCapabilities) @@ -549,59 +568,55 @@ rdpSettings* freerdp_settings_clone(rdpSettings* settings) { CopyMemory(_settings, settings, sizeof(rdpSettings)); - /** - * Generated Code - */ - /* char* values */ - - _settings->ServerHostname = _strdup(settings->ServerHostname); /* 20 */ - _settings->Username = _strdup(settings->Username); /* 21 */ - _settings->Password = _strdup(settings->Password); /* 22 */ - _settings->Domain = _strdup(settings->Domain); /* 23 */ - _settings->PasswordHash = _strdup(settings->PasswordHash); /* 24 */ +#define CHECKED_STRDUP(name) if (settings->name && !(_settings->name = _strdup(settings->name))) goto out_fail + CHECKED_STRDUP(ServerHostname); /* 20 */ + CHECKED_STRDUP(Username); /* 21 */ + CHECKED_STRDUP(Password); /* 22 */ + CHECKED_STRDUP(Domain); /* 23 */ + CHECKED_STRDUP(PasswordHash); /* 24 */ _settings->ClientHostname = NULL; /* 134 */ _settings->ClientProductId = NULL; /* 135 */ - _settings->AlternateShell = _strdup(settings->AlternateShell); /* 640 */ - _settings->ShellWorkingDirectory = _strdup(settings->ShellWorkingDirectory); /* 641 */ - _settings->ClientAddress = _strdup(settings->ClientAddress); /* 769 */ - _settings->ClientDir = _strdup(settings->ClientDir); /* 770 */ - _settings->DynamicDSTTimeZoneKeyName = _strdup(settings->DynamicDSTTimeZoneKeyName); /* 897 */ - _settings->RemoteAssistanceSessionId = _strdup(settings->RemoteAssistanceSessionId); /* 1025 */ - _settings->RemoteAssistancePassStub = _strdup(settings->RemoteAssistancePassStub); /* 1026 */ - _settings->RemoteAssistancePassword = _strdup(settings->RemoteAssistancePassword); /* 1027 */ - _settings->RemoteAssistanceRCTicket = _strdup(settings->RemoteAssistanceRCTicket); /* 1028 */ - _settings->AuthenticationServiceClass = _strdup(settings->AuthenticationServiceClass); /* 1098 */ - _settings->AllowedTlsCiphers = _strdup(settings->AllowedTlsCiphers); /* 1101 */ - _settings->PreconnectionBlob = _strdup(settings->PreconnectionBlob); /* 1155 */ - _settings->KerberosKdc = _strdup(settings->KerberosKdc); /* 1344 */ - _settings->KerberosRealm = _strdup(settings->KerberosRealm); /* 1345 */ - _settings->CertificateName = _strdup(settings->CertificateName); /* 1409 */ - _settings->CertificateFile = _strdup(settings->CertificateFile); /* 1410 */ - _settings->PrivateKeyFile = _strdup(settings->PrivateKeyFile); /* 1411 */ - _settings->RdpKeyFile = _strdup(settings->RdpKeyFile); /* 1412 */ - _settings->WindowTitle = _strdup(settings->WindowTitle); /* 1542 */ - _settings->WmClass = _strdup(settings->WmClass); /* 1549 */ - _settings->ComputerName = _strdup(settings->ComputerName); /* 1664 */ - _settings->ConnectionFile = _strdup(settings->ConnectionFile); /* 1728 */ - _settings->AssistanceFile = _strdup(settings->AssistanceFile); /* 1729 */ - _settings->HomePath = _strdup(settings->HomePath); /* 1792 */ - _settings->ConfigPath = _strdup(settings->ConfigPath); /* 1793 */ - _settings->CurrentPath = _strdup(settings->CurrentPath); /* 1794 */ - _settings->DumpRemoteFxFile = _strdup(settings->DumpRemoteFxFile); /* 1858 */ - _settings->PlayRemoteFxFile = _strdup(settings->PlayRemoteFxFile); /* 1859 */ - _settings->GatewayHostname = _strdup(settings->GatewayHostname); /* 1986 */ - _settings->GatewayUsername = _strdup(settings->GatewayUsername); /* 1987 */ - _settings->GatewayPassword = _strdup(settings->GatewayPassword); /* 1988 */ - _settings->GatewayDomain = _strdup(settings->GatewayDomain); /* 1989 */ - _settings->RemoteApplicationName = _strdup(settings->RemoteApplicationName); /* 2113 */ - _settings->RemoteApplicationIcon = _strdup(settings->RemoteApplicationIcon); /* 2114 */ - _settings->RemoteApplicationProgram = _strdup(settings->RemoteApplicationProgram); /* 2115 */ - _settings->RemoteApplicationFile = _strdup(settings->RemoteApplicationFile); /* 2116 */ - _settings->RemoteApplicationGuid = _strdup(settings->RemoteApplicationGuid); /* 2117 */ - _settings->RemoteApplicationCmdLine = _strdup(settings->RemoteApplicationCmdLine); /* 2118 */ - _settings->ImeFileName = _strdup(settings->ImeFileName); /* 2628 */ - _settings->DrivesToRedirect = _strdup(settings->DrivesToRedirect); /* 4290 */ + CHECKED_STRDUP(AlternateShell); /* 640 */ + CHECKED_STRDUP(ShellWorkingDirectory); /* 641 */ + CHECKED_STRDUP(ClientAddress); /* 769 */ + CHECKED_STRDUP(ClientDir); /* 770 */ + CHECKED_STRDUP(DynamicDSTTimeZoneKeyName); /* 897 */ + CHECKED_STRDUP(RemoteAssistanceSessionId); /* 1025 */ + CHECKED_STRDUP(RemoteAssistancePassStub); /* 1026 */ + CHECKED_STRDUP(RemoteAssistancePassword); /* 1027 */ + CHECKED_STRDUP(RemoteAssistanceRCTicket); /* 1028 */ + CHECKED_STRDUP(AuthenticationServiceClass); /* 1098 */ + CHECKED_STRDUP(AllowedTlsCiphers); /* 1101 */ + CHECKED_STRDUP(PreconnectionBlob); /* 1155 */ + CHECKED_STRDUP(KerberosKdc); /* 1344 */ + CHECKED_STRDUP(KerberosRealm); /* 1345 */ + CHECKED_STRDUP(CertificateName); /* 1409 */ + CHECKED_STRDUP(CertificateFile); /* 1410 */ + CHECKED_STRDUP(PrivateKeyFile); /* 1411 */ + CHECKED_STRDUP(RdpKeyFile); /* 1412 */ + CHECKED_STRDUP(WindowTitle); /* 1542 */ + CHECKED_STRDUP(WmClass); /* 1549 */ + CHECKED_STRDUP(ComputerName); /* 1664 */ + CHECKED_STRDUP(ConnectionFile); /* 1728 */ + CHECKED_STRDUP(AssistanceFile); /* 1729 */ + CHECKED_STRDUP(HomePath); /* 1792 */ + CHECKED_STRDUP(ConfigPath); /* 1793 */ + CHECKED_STRDUP(CurrentPath); /* 1794 */ + CHECKED_STRDUP(DumpRemoteFxFile); /* 1858 */ + CHECKED_STRDUP(PlayRemoteFxFile); /* 1859 */ + CHECKED_STRDUP(GatewayHostname); /* 1986 */ + CHECKED_STRDUP(GatewayUsername); /* 1987 */ + CHECKED_STRDUP(GatewayPassword); /* 1988 */ + CHECKED_STRDUP(GatewayDomain); /* 1989 */ + CHECKED_STRDUP(RemoteApplicationName); /* 2113 */ + CHECKED_STRDUP(RemoteApplicationIcon); /* 2114 */ + CHECKED_STRDUP(RemoteApplicationProgram); /* 2115 */ + CHECKED_STRDUP(RemoteApplicationFile); /* 2116 */ + CHECKED_STRDUP(RemoteApplicationGuid); /* 2117 */ + CHECKED_STRDUP(RemoteApplicationCmdLine); /* 2118 */ + CHECKED_STRDUP(ImeFileName); /* 2628 */ + CHECKED_STRDUP(DrivesToRedirect); /* 4290 */ /** * Manual Code @@ -666,15 +681,19 @@ rdpSettings* freerdp_settings_clone(rdpSettings* settings) _settings->ChannelCount = settings->ChannelCount; _settings->ChannelDefArraySize = settings->ChannelDefArraySize; _settings->ChannelDefArray = (CHANNEL_DEF*) malloc(sizeof(CHANNEL_DEF) * settings->ChannelDefArraySize); + if (!_settings->ChannelDefArray && _settings->ChannelDefArraySize) goto out_fail; + CopyMemory(_settings->ChannelDefArray, settings->ChannelDefArray, sizeof(CHANNEL_DEF) * settings->ChannelDefArraySize); _settings->MonitorCount = settings->MonitorCount; _settings->MonitorDefArraySize = settings->MonitorDefArraySize; _settings->MonitorDefArray = (rdpMonitor*) malloc(sizeof(rdpMonitor) * settings->MonitorDefArraySize); + if (!_settings->MonitorDefArray && _settings->MonitorDefArraySize) goto out_fail; + CopyMemory(_settings->MonitorDefArray, settings->MonitorDefArray, sizeof(rdpMonitor) * settings->MonitorDefArraySize); _settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32)); @@ -688,6 +707,10 @@ rdpSettings* freerdp_settings_clone(rdpSettings* settings) _settings->OrderSupport = malloc(32); if (!_settings->OrderSupport) goto out_fail; + + if (!_settings->ReceivedCapabilities || !_settings->OrderSupport) + goto out_fail; + CopyMemory(_settings->ReceivedCapabilities, settings->ReceivedCapabilities, 32); CopyMemory(_settings->OrderSupport, settings->OrderSupport, 32); @@ -733,16 +756,25 @@ rdpSettings* freerdp_settings_clone(rdpSettings* settings) if (settings->TargetNetAddressCount > 0) { _settings->TargetNetAddresses = (char**) calloc(settings->TargetNetAddressCount, sizeof(char*)); - if (!_settings->TargetNetAddresses) + { + _settings->TargetNetAddressCount = 0; goto out_fail; + } for (index = 0; index < settings->TargetNetAddressCount; index++) { _settings->TargetNetAddresses[index] = _strdup(settings->TargetNetAddresses[index]); - if (!_settings->TargetNetAddresses[index]) + { + while(index) + free(_settings->TargetNetAddresses[--index]); + + free(_settings->TargetNetAddresses); + _settings->TargetNetAddresses = NULL; + _settings->TargetNetAddressCount = 0; goto out_fail; + } } if (settings->TargetNetPorts) @@ -760,37 +792,73 @@ rdpSettings* freerdp_settings_clone(rdpSettings* settings) _settings->DeviceCount = settings->DeviceCount; _settings->DeviceArraySize = settings->DeviceArraySize; _settings->DeviceArray = (RDPDR_DEVICE**) calloc(_settings->DeviceArraySize, sizeof(RDPDR_DEVICE*)); - if (!_settings->DeviceArray && _settings->DeviceArraySize) + { + _settings->DeviceCount = 0; + _settings->DeviceArraySize = 0; goto out_fail; + } + + if (_settings->DeviceArraySize < _settings->DeviceCount) + { + _settings->DeviceCount = 0; + _settings->DeviceArraySize = 0; + goto out_fail; + } for (index = 0; index < _settings->DeviceCount; index++) { _settings->DeviceArray[index] = freerdp_device_clone(settings->DeviceArray[index]); + if (!_settings->DeviceArray[index]) + goto out_fail; } _settings->StaticChannelCount = settings->StaticChannelCount; _settings->StaticChannelArraySize = settings->StaticChannelArraySize; _settings->StaticChannelArray = (ADDIN_ARGV**) calloc(_settings->StaticChannelArraySize, sizeof(ADDIN_ARGV*)); - if (!_settings->StaticChannelArray && _settings->StaticChannelArraySize) + { + _settings->StaticChannelArraySize = 0; + _settings->ChannelCount = 0; goto out_fail; + } + + if (_settings->StaticChannelArraySize < _settings->StaticChannelCount) + { + _settings->StaticChannelArraySize = 0; + _settings->ChannelCount = 0; + goto out_fail; + } for (index = 0; index < _settings->StaticChannelCount; index++) { _settings->StaticChannelArray[index] = freerdp_static_channel_clone(settings->StaticChannelArray[index]); + if (!_settings->StaticChannelArray[index]) + goto out_fail; } _settings->DynamicChannelCount = settings->DynamicChannelCount; _settings->DynamicChannelArraySize = settings->DynamicChannelArraySize; _settings->DynamicChannelArray = (ADDIN_ARGV**) calloc(_settings->DynamicChannelArraySize, sizeof(ADDIN_ARGV*)); - if (!_settings->DynamicChannelArray && _settings->DynamicChannelArraySize) + { + _settings->DynamicChannelCount = 0; + _settings->DynamicChannelArraySize = 0; goto out_fail; + } + + if (_settings->DynamicChannelArraySize < _settings->DynamicChannelCount) + { + _settings->DynamicChannelCount = 0; + _settings->DynamicChannelArraySize = 0; + goto out_fail; + } for (index = 0; index < _settings->DynamicChannelCount; index++) { _settings->DynamicChannelArray[index] = freerdp_dynamic_channel_clone(settings->DynamicChannelArray[index]); + if (!_settings->DynamicChannelArray[index]) + goto out_fail; } _settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8); @@ -798,10 +866,16 @@ rdpSettings* freerdp_settings_clone(rdpSettings* settings) if (!_settings->SettingsModified) goto out_fail; } - return _settings; + out_fail: - freerdp_settings_free(_settings); + /* In case any memory allocation failed during clone, some bytes might leak. + * + * freerdp_settings_free can't be reliable used at this point since it could + * free memory of pointers copied by CopyMemory and detecting and freeing + * each allocation separately is quite painful. + */ + free(_settings); return NULL; } diff --git a/libfreerdp/core/surface.c b/libfreerdp/core/surface.c index 8a9fb7eba..c568fe005 100644 --- a/libfreerdp/core/surface.c +++ b/libfreerdp/core/surface.c @@ -128,6 +128,7 @@ int update_recv_surfcmds(rdpUpdate* update, UINT32 size, wStream* s) if (update->dump_rfx) { + /* TODO: treat return values */ pcap_add_record(update->pcap_rfx, mark, cmdLength + 2); pcap_flush(update->pcap_rfx); } diff --git a/libfreerdp/core/tcp.c b/libfreerdp/core/tcp.c index af92c6d79..271f84233 100644 --- a/libfreerdp/core/tcp.c +++ b/libfreerdp/core/tcp.c @@ -360,7 +360,7 @@ static int transport_bio_simple_init(BIO* bio, SOCKET socket, int shutdown) bio->init = 1; #ifdef _WIN32 - ptr->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + ptr->hEvent = WSACreateEvent(); if (!ptr->hEvent) return 0; @@ -368,7 +368,7 @@ static int transport_bio_simple_init(BIO* bio, SOCKET socket, int shutdown) /* WSAEventSelect automatically sets the socket in non-blocking mode */ WSAEventSelect(ptr->socket, ptr->hEvent, FD_READ | FD_WRITE | FD_CLOSE); #else - ptr->hEvent = CreateFileDescriptorEvent(NULL, FALSE, FALSE, (int) ptr->socket); + ptr->hEvent = CreateFileDescriptorEvent(NULL, FALSE, FALSE, (int) ptr->socket, WINPR_FD_READ); if (!ptr->hEvent) return 0; @@ -1283,8 +1283,9 @@ int freerdp_tcp_connect(rdpSettings* settings, const char* hostname, int port, i if (!freerdp_tcp_connect_timeout(sockfd, addr->ai_addr, addr->ai_addrlen, timeout)) { - fprintf(stderr, "failed to connect to %s\n", hostname); freeaddrinfo(result); + close(sockfd); + WLog_ERR(TAG, "failed to connect to %s", hostname); return -1; } @@ -1296,6 +1297,12 @@ int freerdp_tcp_connect(rdpSettings* settings, const char* hostname, int port, i free(settings->ClientAddress); settings->ClientAddress = freerdp_tcp_get_ip_address(sockfd); + if (!settings->ClientAddress) + { + close(sockfd); + WLog_ERR(TAG, "Couldn't get socket ip address"); + return -1; + } optval = 1; optlen = sizeof(optval); @@ -1316,6 +1323,7 @@ int freerdp_tcp_connect(rdpSettings* settings, const char* hostname, int port, i if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*) &optval, optlen) < 0) { + close(sockfd); WLog_ERR(TAG, "unable to set receive buffer len"); return -1; } @@ -1325,7 +1333,11 @@ int freerdp_tcp_connect(rdpSettings* settings, const char* hostname, int port, i if (!ipcSocket) { if (!freerdp_tcp_set_keep_alive_mode(sockfd)) + { + close(sockfd); + WLog_ERR(TAG, "Couldn't set keep alive mode."); return -1; + } } return sockfd; diff --git a/libfreerdp/core/test/CMakeLists.txt b/libfreerdp/core/test/CMakeLists.txt index 7b9853519..1c06ec601 100644 --- a/libfreerdp/core/test/CMakeLists.txt +++ b/libfreerdp/core/test/CMakeLists.txt @@ -5,7 +5,8 @@ set(MODULE_PREFIX "TEST_CORE") set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) set(${MODULE_PREFIX}_TESTS - TestVersion.c) + TestVersion.c + TestSettings.c) create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} diff --git a/libfreerdp/core/test/TestSettings.c b/libfreerdp/core/test/TestSettings.c new file mode 100644 index 000000000..3bfe5aa5a --- /dev/null +++ b/libfreerdp/core/test/TestSettings.c @@ -0,0 +1,28 @@ +#include + +int TestSettings(int argc, char* argv[]) +{ + rdpSettings *settings = NULL; + rdpSettings *cloned; + + settings = freerdp_settings_new(0); + if (!settings) + { + printf("Couldn't create settings\n"); + return -1; + } + settings->Username = _strdup("abcdefg"); + settings->Password = _strdup("xyz"); + cloned = freerdp_settings_clone(settings); + if (!cloned) + { + printf("Problem cloning settings\n"); + freerdp_settings_free(settings); + return -1; + } + + freerdp_settings_free(cloned); + freerdp_settings_free(settings); + return 0; +} + diff --git a/libfreerdp/core/transport.c b/libfreerdp/core/transport.c index 9097a4477..808264091 100644 --- a/libfreerdp/core/transport.c +++ b/libfreerdp/core/transport.c @@ -768,6 +768,9 @@ int transport_check_fds(rdpTransport* transport) */ if ((status = transport_read_pdu(transport, transport->ReceiveBuffer)) <= 0) { + if (status < 0) + WLog_DBG(TAG, "transport_check_fds: transport_read_pdu() - %i", status); + return status; } @@ -790,7 +793,10 @@ int transport_check_fds(rdpTransport* transport) } if (recv_status < 0) + { + WLog_ERR(TAG, "transport_check_fds: transport->ReceiveCallback() - %i", recv_status); return -1; + } } return 0; @@ -921,6 +927,7 @@ static void* transport_client_thread(void* arg) if (transport->layer == TRANSPORT_LAYER_CLOSED) { + WLog_DBG(TAG, "TRANSPORT_LAYER_CLOSED"); rdp_set_error_info(rdp, ERRINFO_PEER_DISCONNECTED); break; } @@ -934,6 +941,7 @@ static void* transport_client_thread(void* arg) { if (!freerdp_check_event_handles(context)) { + WLog_ERR(TAG, "freerdp_check_event_handles()"); rdp_set_error_info(rdp, ERRINFO_PEER_DISCONNECTED); break; } diff --git a/libfreerdp/core/update.c b/libfreerdp/core/update.c index 1bb5a8e73..90e183e1c 100644 --- a/libfreerdp/core/update.c +++ b/libfreerdp/core/update.c @@ -52,7 +52,10 @@ BOOL update_recv_orders(rdpUpdate* update, wStream* s) UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; + } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ @@ -61,7 +64,10 @@ BOOL update_recv_orders(rdpUpdate* update, wStream* s) while (numberOrders > 0) { if (!update_recv_order(update, s)) + { + WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; + } numberOrders--; } @@ -488,7 +494,10 @@ BOOL update_recv(rdpUpdate* update, wStream* s) rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; + } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ //WLog_DBG(TAG, "%s Update Data PDU", UPDATE_TYPE_STRINGS[updateType]); @@ -501,19 +510,26 @@ BOOL update_recv(rdpUpdate* update, wStream* s) if (!update_recv_orders(update, s)) { /* XXX: Do we have to call EndPaint? */ + WLog_ERR(TAG, "UPDATE_TYPE_ORDERS - update_recv_orders() failed"); return FALSE; } break; case UPDATE_TYPE_BITMAP: if (!update_read_bitmap_update(update, s, &update->bitmap_update)) + { + WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); return FALSE; + } IFCALL(update->BitmapUpdate, context, &update->bitmap_update); break; case UPDATE_TYPE_PALETTE: if (!update_read_palette(update, s, &update->palette_update)) + { + WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); return FALSE; + } IFCALL(update->Palette, context, &update->palette_update); break; @@ -1816,6 +1832,8 @@ BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) return FALSE; areas = (RECTANGLE_16*) malloc(sizeof(RECTANGLE_16) * numberOfAreas); + if (!areas) + return FALSE; for (index = 0; index < numberOfAreas; index++) { diff --git a/libfreerdp/core/window.c b/libfreerdp/core/window.c index 8c61ee9a6..e31fe4582 100644 --- a/libfreerdp/core/window.c +++ b/libfreerdp/core/window.c @@ -124,7 +124,11 @@ BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo) if (iconInfo->colorTable == NULL) { if (iconInfo->cbColorTable) + { iconInfo->colorTable = (BYTE*) malloc(iconInfo->cbColorTable); + if (!iconInfo->colorTable) + return FALSE; + } } else if (iconInfo->cbColorTable) { @@ -292,6 +296,8 @@ BOOL update_read_window_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo, WI size = sizeof(RECTANGLE_16) * windowState->numWindowRects; windowState->windowRects = (RECTANGLE_16*) malloc(size); + if (!windowState->windowRects) + return FALSE; if (Stream_GetRemainingLength(s) < 8 * windowState->numWindowRects) return FALSE; @@ -324,6 +330,8 @@ BOOL update_read_window_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo, WI size = sizeof(RECTANGLE_16) * windowState->numVisibilityRects; windowState->visibilityRects = (RECTANGLE_16*) malloc(size); + if (!windowState->visibilityRects) + return FALSE; if (Stream_GetRemainingLength(s) < windowState->numVisibilityRects * 8) return FALSE; @@ -342,8 +350,9 @@ BOOL update_read_window_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo, WI BOOL update_read_window_icon_order(wStream* s, WINDOW_ORDER_INFO* orderInfo, WINDOW_ICON_ORDER* window_icon) { - window_icon->iconInfo = (ICON_INFO*) malloc(sizeof(ICON_INFO)); - ZeroMemory(window_icon->iconInfo, sizeof(ICON_INFO)); + window_icon->iconInfo = (ICON_INFO*) calloc(1, sizeof(ICON_INFO)); + if (!window_icon->iconInfo) + return FALSE; return update_read_icon_info(s, window_icon->iconInfo); /* iconInfo (ICON_INFO) */ } diff --git a/libfreerdp/crypto/base64.c b/libfreerdp/crypto/base64.c index d492e8981..21f6f9273 100644 --- a/libfreerdp/crypto/base64.c +++ b/libfreerdp/crypto/base64.c @@ -125,6 +125,8 @@ static void* base64_decode(const char* s, int length, int* data_len) return NULL; q = data = (BYTE*) malloc(length / 4 * 3); + if (!q) + return NULL; /* first treat complete blocks */ nBlocks = (length / 4); diff --git a/libfreerdp/crypto/certificate.c b/libfreerdp/crypto/certificate.c index 74263467b..e8d292377 100644 --- a/libfreerdp/crypto/certificate.c +++ b/libfreerdp/crypto/certificate.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -128,9 +129,27 @@ static int certificate_data_match_legacy(rdpCertificateStore* certificate_store, if (!fp) return match; - fseek(fp, 0, SEEK_END); - size = ftell(fp); - fseek(fp, 0, SEEK_SET); + if (fseek(fp, 0, SEEK_END) < 0) + { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->legacy_file, strerror(errno), errno); + fclose(fp); + return match; + } + if ((size = ftell(fp)) < 0) + { + WLog_ERR(TAG, "ftell(%s) returned %s [%08X]", + certificate_store->legacy_file, strerror(errno), errno); + fclose(fp); + return match; + } + if (fseek(fp, 0, SEEK_SET) < 0) + { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->legacy_file, strerror(errno), errno); + fclose(fp); + return match; + } if (size < 1) { @@ -178,20 +197,41 @@ static int certificate_data_match_legacy(rdpCertificateStore* certificate_store, pline = StrSep(&data, "\r\n"); } - free(mdata); /* Found a valid fingerprint in legacy file, * copy to new file in new format. */ if (0 == match) { - rdpCertificateData* data = certificate_data_new(hostname, - certificate_data->port, - NULL, NULL, - pline); + rdpCertificateData* data = certificate_data_new( + hostname, + certificate_data->port, + NULL, NULL, + certificate_data->fingerprint); if (data) + { + free (data->subject); + free (data->issuer); + + data->subject = NULL; + data->issuer = NULL; + if (certificate_data->subject) + { + data->subject = _strdup(certificate_data->subject); + if (!data->subject) + goto out; + } + if (certificate_data->issuer) + { + data->issuer = _strdup(certificate_data->issuer); + if (!data->issuer) + goto out; + } match = certificate_data_print(certificate_store, data) ? 0 : 1; + } +out: certificate_data_free(data); } + free(mdata); return match; @@ -204,7 +244,7 @@ static int certificate_data_match_raw(rdpCertificateStore* certificate_store, { BOOL found = FALSE; FILE* fp; - int length; + size_t length; char* data; char* mdata; char* pline; @@ -221,9 +261,27 @@ static int certificate_data_match_raw(rdpCertificateStore* certificate_store, if (!fp) return match; - fseek(fp, 0, SEEK_END); - size = ftell(fp); - fseek(fp, 0, SEEK_SET); + if (fseek(fp, 0, SEEK_END) < 0) + { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return match; + } + if ((size = ftell(fp)) < 0) + { + WLog_ERR(TAG, "ftell(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return match; + } + if (fseek(fp, 0, SEEK_SET) < 0) + { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return match; + } if (size < 1) { @@ -268,7 +326,7 @@ static int certificate_data_match_raw(rdpCertificateStore* certificate_store, if (port == certificate_data->port) { found = TRUE; - match = strcmp(certificate_data->fingerprint, fingerprint); + match = (strcmp(certificate_data->fingerprint, fingerprint) == 0) ? 0 : -1; if (fingerprint && fprint) *fprint = _strdup(fingerprint); if (subject && psubject) @@ -315,7 +373,7 @@ BOOL certificate_data_replace(rdpCertificateStore* certificate_store, { FILE* fp; BOOL rc = FALSE; - int length; + size_t length; char* data; char* sdata; char* pline; @@ -325,14 +383,27 @@ BOOL certificate_data_replace(rdpCertificateStore* certificate_store, if (!fp) return FALSE; - /* Read the current contents of the file. */ - fseek(fp, 0, SEEK_END); - size = ftell(fp); - fseek(fp, 0, SEEK_SET); - - if (size < 1) + if (fseek(fp, 0, SEEK_END) < 0) { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return FALSE; + } + + if ((size = ftell(fp)) < 0) + { + WLog_ERR(TAG, "ftell(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return FALSE; + } + + if (fseek(fp, 0, SEEK_SET) < 0) + { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); fclose(fp); return FALSE; } @@ -355,8 +426,10 @@ BOOL certificate_data_replace(rdpCertificateStore* certificate_store, fp = fopen(certificate_store->file, "wb"); - if (!fp) + if (fp == NULL) { + WLog_ERR(TAG, "freopen(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); free(data); return FALSE; } @@ -391,13 +464,25 @@ BOOL certificate_data_replace(rdpCertificateStore* certificate_store, fingerprint = certificate_data->fingerprint; rc = TRUE; } - fprintf(fp, "%s %hu %s %s %s\n", hostname, port, fingerprint, subject, issuer); + if (fprintf(fp, "%s %hu %s %s %s\n", hostname, port, fingerprint, subject, issuer) < 0) + { + WLog_ERR(TAG, "fprintf(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return FALSE; + } } } pline = StrSep(&sdata, "\r\n"); } + if (fflush(fp) != 0) + { + WLog_WARN(TAG, "fflush(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + } + fclose(fp); free(data); @@ -456,9 +541,29 @@ BOOL certificate_data_print(rdpCertificateStore* certificate_store, rdpCertifica if (!fp) return FALSE; - fprintf(fp, "%s %hu %s %s %s\n", certificate_data->hostname, certificate_data->port, + if (fseek(fp, 0, SEEK_END) < 0) + { + WLog_ERR(TAG, "fseek(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return FALSE; + } + + if (fprintf(fp, "%s %hu %s %s %s\n", certificate_data->hostname, certificate_data->port, certificate_data->fingerprint, certificate_data->subject, - certificate_data->issuer); + certificate_data->issuer) < 0) + { + WLog_ERR(TAG, "fprintf(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + fclose(fp); + return FALSE; + } + + if (fflush(fp) != 0) + { + WLog_WARN(TAG, "fflush(%s) returned %s [%08X]", + certificate_store->file, strerror(errno), errno); + } fclose(fp); @@ -467,6 +572,7 @@ BOOL certificate_data_print(rdpCertificateStore* certificate_store, rdpCertifica rdpCertificateData* certificate_data_new(char* hostname, UINT16 port, char* subject, char* issuer, char* fingerprint) { + size_t i; rdpCertificateData* certdata; if (!hostname) @@ -486,7 +592,7 @@ rdpCertificateData* certificate_data_new(char* hostname, UINT16 port, char* subj else certdata->subject = crypto_base64_encode((BYTE*)"", 0); if (issuer) - certdata->issuer = crypto_base64_encode((BYTE*)issuer, strlen(subject)); + certdata->issuer = crypto_base64_encode((BYTE*)issuer, strlen(issuer)); else certdata->issuer = crypto_base64_encode((BYTE*)"", 0); certdata->fingerprint = _strdup(fingerprint); @@ -495,6 +601,9 @@ rdpCertificateData* certificate_data_new(char* hostname, UINT16 port, char* subj !certdata->issuer || !certdata->fingerprint) goto fail; + for (i=0; ihostname[i] = tolower(certdata->hostname[i]); + return certdata; fail: @@ -544,6 +653,7 @@ void certificate_store_free(rdpCertificateStore* certstore) { free(certstore->path); free(certstore->file); + free(certstore->legacy_file); free(certstore); } } diff --git a/libfreerdp/crypto/crypto.c b/libfreerdp/crypto/crypto.c index b82f38b54..26c69fdaf 100644 --- a/libfreerdp/crypto/crypto.c +++ b/libfreerdp/crypto/crypto.c @@ -231,6 +231,11 @@ BOOL crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* Public *PublicKeyLength = (DWORD) length; *PublicKey = (BYTE*) malloc(length); ptr = (BYTE*) (*PublicKey); + if (!ptr) + { + status = FALSE; + goto exit; + } i2d_PublicKey(pkey, &ptr); @@ -380,9 +385,9 @@ char* crypto_print_name(X509_NAME* name) if (X509_NAME_print_ex(outBIO, name, 0, XN_FLAG_ONELINE) > 0) { unsigned long size = BIO_number_written(outBIO); - buffer = malloc(size + 1); - ZeroMemory(buffer, size + 1); - memset(buffer, 0, size + 1); + buffer = calloc(1, size + 1); + if (!buffer) + return NULL; BIO_read(outBIO, buffer, size); } @@ -471,7 +476,16 @@ char** crypto_cert_subject_alt_name(X509* xcert, int* count, int** lengths) if (num_subject_alt_names) { strings = (char**) malloc(sizeof(char*) * num_subject_alt_names); + if (!strings) + goto out; + *lengths = (int*) malloc(sizeof(int) * num_subject_alt_names); + if (!*lengths) + { + free(strings); + strings = NULL; + goto out; + } } for (index = 0; index < num_subject_alt_names; ++index) @@ -494,6 +508,8 @@ char** crypto_cert_subject_alt_name(X509* xcert, int* count, int** lengths) *lengths = NULL ; return NULL; } + +out: GENERAL_NAMES_free(subject_alt_names); return strings; diff --git a/libfreerdp/crypto/test/TestKnownHosts.c b/libfreerdp/crypto/test/TestKnownHosts.c index 0adf02ddf..1c7623376 100644 --- a/libfreerdp/crypto/test/TestKnownHosts.c +++ b/libfreerdp/crypto/test/TestKnownHosts.c @@ -46,8 +46,9 @@ static int prepare(const char* currentFileV2, const char* legacyFileV2, const ch for (i=0; ipx509, hostname, port); + /* extra common name and alternative names */ common_name = crypto_cert_subject_common_name(cert->px509, &common_name_length); alt_names = crypto_cert_subject_alt_name(cert->px509, &alt_names_count, &alt_names_lengths); @@ -1217,12 +1223,7 @@ int tls_verify_certificate(rdpTls* tls, CryptoCert cert, char* hostname, int por free(fingerprint); } - if (certificate_data) - { - free(certificate_data->fingerprint); - free(certificate_data->hostname); - free(certificate_data); - } + certificate_data_free(certificate_data); #ifndef _WIN32 free(common_name); diff --git a/libfreerdp/gdi/16bpp.c b/libfreerdp/gdi/16bpp.c index f8980faa0..1ee8a0f6b 100644 --- a/libfreerdp/gdi/16bpp.c +++ b/libfreerdp/gdi/16bpp.c @@ -74,7 +74,7 @@ UINT16 gdi_get_color_16bpp(HGDI_DC hdc, GDI_COLOR color) return color16; } -int FillRect_16bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) +BOOL FillRect_16bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) { int x, y; UINT16 *dstp; @@ -85,8 +85,8 @@ int FillRect_16bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) gdi_RectToCRgn(rect, &nXDest, &nYDest, &nWidth, &nHeight); - if (gdi_ClipCoords(hdc, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdc, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL)) + return TRUE; color16 = gdi_get_color_16bpp(hdc, hbr->color); @@ -105,11 +105,12 @@ int FillRect_16bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) } if (!gdi_InvalidateRegion(hdc, nXDest, nYDest, nWidth, nHeight)) - return 0; - return 1; + return FALSE; + + return TRUE; } -static int BitBlt_BLACKNESS_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_BLACKNESS_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int y; BYTE* dstp; @@ -122,10 +123,10 @@ static int BitBlt_BLACKNESS_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n memset(dstp, 0, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } -static int BitBlt_WHITENESS_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_WHITENESS_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int y; BYTE* dstp; @@ -138,20 +139,20 @@ static int BitBlt_WHITENESS_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n memset(dstp, 0xFF, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } -static int BitBlt_SRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; if ((hdcDest->selectedObject != hdcSrc->selectedObject) || - gdi_CopyOverlap(nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc) == 0) + !gdi_CopyOverlap(nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc)) { for (y = 0; y < nHeight; y++) { @@ -162,7 +163,7 @@ static int BitBlt_SRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi memcpy(dstp, srcp, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } if (nYSrc < nYDest) @@ -202,17 +203,17 @@ static int BitBlt_SRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_NOTSRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_NOTSRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -230,10 +231,10 @@ static int BitBlt_NOTSRCCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_DSTINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_DSTINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT16* dstp; @@ -252,17 +253,17 @@ static int BitBlt_DSTINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_SRCERASE_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCERASE_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -280,17 +281,17 @@ static int BitBlt_SRCERASE_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_NOTSRCERASE_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_NOTSRCERASE_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -308,17 +309,17 @@ static int BitBlt_NOTSRCERASE_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_SRCINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -336,17 +337,17 @@ static int BitBlt_SRCINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_SRCAND_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCAND_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -364,17 +365,17 @@ static int BitBlt_SRCAND_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid } } - return 1; + return TRUE; } -static int BitBlt_SRCPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -392,10 +393,10 @@ static int BitBlt_SRCPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_DSPDxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_DSPDxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; @@ -405,7 +406,7 @@ static int BitBlt_DSPDxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi HGDI_BITMAP hSrcBmp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; /* D = (S & P) | (~S & D) */ /* DSPDxax, used to draw glyphs */ @@ -418,7 +419,7 @@ static int BitBlt_DSPDxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi { WLog_ERR(TAG, "BitBlt_DSPDxax expects 1 bpp, unimplemented for %d", hdcSrc->bytesPerPixel); - return 0; + return FALSE; } for (y = 0; y < nHeight; y++) @@ -438,10 +439,10 @@ static int BitBlt_DSPDxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_PSDPxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_PSDPxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; @@ -450,7 +451,7 @@ static int BitBlt_PSDPxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi UINT16 color16; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; /* D = (S & D) | (~S & P) */ @@ -495,10 +496,10 @@ static int BitBlt_PSDPxax_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_SPna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SPna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; @@ -506,7 +507,7 @@ static int BitBlt_SPna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth UINT16* patp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -525,10 +526,10 @@ static int BitBlt_SPna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth } } - return 1; + return TRUE; } -static int BitBlt_DPa_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_DPa_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT16* dstp; @@ -550,10 +551,10 @@ static int BitBlt_DPa_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, } } - return 1; + return TRUE; } -static int BitBlt_PDxn_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PDxn_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT16* dstp; @@ -574,17 +575,17 @@ static int BitBlt_PDxn_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth } } - return 1; + return TRUE; } -static int BitBlt_DSna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_DSna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -602,11 +603,11 @@ static int BitBlt_DSna_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth } } - return 1; + return TRUE; } -static int BitBlt_MERGECOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_MERGECOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; @@ -614,7 +615,7 @@ static int BitBlt_MERGECOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n UINT16* patp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -633,17 +634,17 @@ static int BitBlt_MERGECOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_MERGEPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_MERGEPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; UINT16* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -661,10 +662,10 @@ static int BitBlt_MERGEPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_PATCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PATCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y, xOffset, yOffset; UINT16* dstp; @@ -720,10 +721,10 @@ static int BitBlt_PATCOPY_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_PATINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PATINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT16* dstp; @@ -766,10 +767,10 @@ static int BitBlt_PATINVERT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_PATPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_PATPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT16* srcp; @@ -777,7 +778,7 @@ static int BitBlt_PATPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW UINT16* patp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -796,27 +797,27 @@ static int BitBlt_PATPAINT_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -int BitBlt_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop) +BOOL BitBlt_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop) { if (!hdcDest) - return 0; + return FALSE; if (hdcSrc != NULL) { - if (gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, &nXSrc, &nYSrc) == 0) - return 0; + if (!gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, &nXSrc, &nYSrc)) + return TRUE; } else { - if (gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL)) + return TRUE; } if (!gdi_InvalidateRegion(hdcDest, nXDest, nYDest, nWidth, nHeight)) - return 0; + return FALSE; switch (rop) { @@ -879,16 +880,16 @@ int BitBlt_16bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeigh } WLog_ERR(TAG, "BitBlt: unknown rop: 0x%08X", rop); - return 1; + return FALSE; } -int PatBlt_16bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop) +BOOL PatBlt_16bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop) { - if (gdi_ClipCoords(hdc, &nXLeft, &nYLeft, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdc, &nXLeft, &nYLeft, &nWidth, &nHeight, NULL, NULL)) + return TRUE; if (!gdi_InvalidateRegion(hdc, nXLeft, nYLeft, nWidth, nHeight)) - return 0; + return FALSE; switch (rop) { @@ -918,7 +919,7 @@ int PatBlt_16bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, i } WLog_ERR(TAG, "PatBlt: unknown rop: 0x%08X", rop); - return 1; + return FALSE; } static INLINE void SetPixel_BLACK_16bpp(UINT16 *pixel, UINT16 *pen) @@ -1140,15 +1141,15 @@ pLineTo_16bpp LineTo_ROP2_16bpp[32] = LineTo_WHITE_16bpp }; -int LineTo_16bpp(HGDI_DC hdc, int nXEnd, int nYEnd) +BOOL LineTo_16bpp(HGDI_DC hdc, int nXEnd, int nYEnd) { pLineTo_16bpp _LineTo; int rop2 = gdi_GetROP2(hdc) - 1; _LineTo = LineTo_ROP2_16bpp[rop2]; - if (_LineTo != NULL) - return _LineTo(hdc, nXEnd, nYEnd); - else - return 0; + if (_LineTo == NULL) + return FALSE; + + return _LineTo(hdc, nXEnd, nYEnd); } diff --git a/libfreerdp/gdi/32bpp.c b/libfreerdp/gdi/32bpp.c index 100be4326..f9124bbae 100644 --- a/libfreerdp/gdi/32bpp.c +++ b/libfreerdp/gdi/32bpp.c @@ -61,7 +61,7 @@ UINT32 gdi_get_color_32bpp(HGDI_DC hdc, GDI_COLOR color) return color32; } -int FillRect_32bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) +BOOL FillRect_32bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) { int x, y; UINT32 *dstp; @@ -71,8 +71,8 @@ int FillRect_32bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) gdi_RectToCRgn(rect, &nXDest, &nYDest, &nWidth, &nHeight); - if (gdi_ClipCoords(hdc, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdc, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL)) + return TRUE; color32 = gdi_get_color_32bpp(hdc, hbr->color); @@ -91,11 +91,12 @@ int FillRect_32bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) } if (!gdi_InvalidateRegion(hdc, nXDest, nYDest, nWidth, nHeight)) - return 0; - return 1; + return FALSE; + + return TRUE; } -static int BitBlt_BLACKNESS_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_BLACKNESS_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { if (hdcDest->alpha) { @@ -139,10 +140,10 @@ static int BitBlt_BLACKNESS_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_WHITENESS_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_WHITENESS_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int y; BYTE* dstp; @@ -155,20 +156,20 @@ static int BitBlt_WHITENESS_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n memset(dstp, 0xFF, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } -static int BitBlt_SRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int y; BYTE* srcp; BYTE* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; if ((hdcDest->selectedObject != hdcSrc->selectedObject) || - gdi_CopyOverlap(nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc) == 0) + !gdi_CopyOverlap(nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc)) { for (y = 0; y < nHeight; y++) { @@ -179,7 +180,7 @@ static int BitBlt_SRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi memmove(dstp, srcp, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } if (nYSrc < nYDest) @@ -219,17 +220,17 @@ static int BitBlt_SRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_NOTSRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_NOTSRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -247,10 +248,10 @@ static int BitBlt_NOTSRCCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_DSTINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_DSTINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT32* dstp; @@ -269,17 +270,17 @@ static int BitBlt_DSTINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_SRCERASE_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCERASE_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -297,17 +298,17 @@ static int BitBlt_SRCERASE_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_NOTSRCERASE_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_NOTSRCERASE_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -325,17 +326,17 @@ static int BitBlt_NOTSRCERASE_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_SRCINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -353,17 +354,17 @@ static int BitBlt_SRCINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_SRCAND_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCAND_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -381,17 +382,17 @@ static int BitBlt_SRCAND_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid } } - return 1; + return TRUE; } -static int BitBlt_SRCPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -409,10 +410,10 @@ static int BitBlt_SRCPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_DSPDxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_DSPDxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; @@ -424,7 +425,7 @@ static int BitBlt_DSPDxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi HGDI_BITMAP hSrcBmp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; /* D = (S & P) | (~S & D) */ @@ -477,10 +478,10 @@ static int BitBlt_DSPDxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_PSDPxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_PSDPxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; @@ -489,7 +490,7 @@ static int BitBlt_PSDPxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi UINT32 color32; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; /* D = (S & D) | (~S & P) */ @@ -534,10 +535,10 @@ static int BitBlt_PSDPxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_SPDSxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SPDSxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; @@ -546,7 +547,7 @@ static int BitBlt_SPDSxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi UINT32 color32; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; /* D = S ^ (P & (D ^ S)) */ @@ -591,10 +592,10 @@ static int BitBlt_SPDSxax_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_SPna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SPna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; @@ -602,7 +603,7 @@ static int BitBlt_SPna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth UINT32* patp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -622,17 +623,17 @@ static int BitBlt_SPna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth } } - return 1; + return TRUE; } -static int BitBlt_DSna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_DSna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -650,10 +651,10 @@ static int BitBlt_DSna_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth } } - return 1; + return TRUE; } -static int BitBlt_DPa_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_DPa_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT32* dstp; @@ -675,10 +676,10 @@ static int BitBlt_DPa_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, } } - return 1; + return TRUE; } -static int BitBlt_PDxn_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PDxn_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT32* dstp; @@ -700,10 +701,10 @@ static int BitBlt_PDxn_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth } } - return 1; + return TRUE; } -static int BitBlt_MERGECOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_MERGECOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; @@ -711,7 +712,7 @@ static int BitBlt_MERGECOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n UINT32* patp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -731,17 +732,17 @@ static int BitBlt_MERGECOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_MERGEPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_MERGEPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; UINT32* dstp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -759,10 +760,10 @@ static int BitBlt_MERGEPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_PATCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PATCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y, xOffset, yOffset; UINT32* dstp; @@ -818,10 +819,10 @@ static int BitBlt_PATCOPY_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_PATINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PATINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; UINT32* dstp; @@ -864,10 +865,10 @@ static int BitBlt_PATINVERT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_PATPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_PATPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; UINT32* srcp; @@ -875,7 +876,7 @@ static int BitBlt_PATPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW UINT32* patp; if (!hdcDest || !hdcSrc) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -894,27 +895,27 @@ static int BitBlt_PATPAINT_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -int BitBlt_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop) +BOOL BitBlt_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop) { if (!hdcDest) - return 0; + return FALSE; if (hdcSrc != NULL) { - if (gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, &nXSrc, &nYSrc) == 0) - return 0; + if (!gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, &nXSrc, &nYSrc)) + return TRUE; } else { - if (gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL)) + return TRUE; } if (!gdi_InvalidateRegion(hdcDest, nXDest, nYDest, nWidth, nHeight)) - return 0; + return FALSE; switch (rop) { @@ -980,16 +981,16 @@ int BitBlt_32bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeigh } WLog_ERR(TAG, "BitBlt: unknown rop: 0x%08X", rop); - return 1; + return FALSE; } -int PatBlt_32bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop) +BOOL PatBlt_32bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop) { - if (gdi_ClipCoords(hdc, &nXLeft, &nYLeft, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdc, &nXLeft, &nYLeft, &nWidth, &nHeight, NULL, NULL)) + return TRUE; if (!gdi_InvalidateRegion(hdc, nXLeft, nYLeft, nWidth, nHeight)) - return 0; + return FALSE; switch (rop) { @@ -1019,7 +1020,7 @@ int PatBlt_32bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, i } WLog_ERR(TAG, "PatBlt: unknown rop: 0x%08X", rop); - return 1; + return FALSE; } static INLINE void SetPixel_BLACK_32bpp(UINT32* pixel, UINT32* pen) @@ -1241,15 +1242,15 @@ pLineTo_32bpp LineTo_ROP2_32bpp[32] = LineTo_WHITE_32bpp }; -int LineTo_32bpp(HGDI_DC hdc, int nXEnd, int nYEnd) +BOOL LineTo_32bpp(HGDI_DC hdc, int nXEnd, int nYEnd) { pLineTo_32bpp _LineTo; int rop2 = gdi_GetROP2(hdc) - 1; _LineTo = LineTo_ROP2_32bpp[rop2]; - if (_LineTo != NULL) - return _LineTo(hdc, nXEnd, nYEnd); - else - return 0; + if (_LineTo == NULL) + return FALSE; + + return _LineTo(hdc, nXEnd, nYEnd); } diff --git a/libfreerdp/gdi/8bpp.c b/libfreerdp/gdi/8bpp.c index 697b5ead6..4299d38d3 100644 --- a/libfreerdp/gdi/8bpp.c +++ b/libfreerdp/gdi/8bpp.c @@ -44,16 +44,18 @@ BYTE gdi_get_color_8bpp(HGDI_DC hdc, GDI_COLOR color) { /* TODO: Implement 8bpp gdi_get_color_8bpp() */ + WLog_ERR(TAG, "%s: not implemented", __FUNCTION__); return 1; } -int FillRect_8bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) +BOOL FillRect_8bpp(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) { /* TODO: Implement 8bpp FillRect() */ - return 1; + WLog_ERR(TAG, "%s: not implemented", __FUNCTION__); + return TRUE; } -static int BitBlt_BLACKNESS_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_BLACKNESS_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int y; BYTE* dstp; @@ -66,10 +68,10 @@ static int BitBlt_BLACKNESS_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW memset(dstp, 0, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } -static int BitBlt_WHITENESS_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_WHITENESS_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int y; BYTE* dstp; @@ -82,20 +84,20 @@ static int BitBlt_WHITENESS_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW memset(dstp, 0xFF, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } -static int BitBlt_SRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; if ((hdcDest->selectedObject != hdcSrc->selectedObject) || - gdi_CopyOverlap(nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc) == 0) + !gdi_CopyOverlap(nXDest, nYDest, nWidth, nHeight, nXSrc, nYSrc)) { for (y = 0; y < nHeight; y++) { @@ -106,7 +108,7 @@ static int BitBlt_SRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid memcpy(dstp, srcp, nWidth * hdcDest->bytesPerPixel); } - return 1; + return TRUE; } if (nYSrc < nYDest) @@ -146,17 +148,17 @@ static int BitBlt_SRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid } } - return 1; + return TRUE; } -static int BitBlt_NOTSRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_NOTSRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -174,10 +176,10 @@ static int BitBlt_NOTSRCCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_DSTINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_DSTINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; BYTE* dstp; @@ -196,17 +198,17 @@ static int BitBlt_DSTINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_SRCERASE_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCERASE_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -224,17 +226,17 @@ static int BitBlt_SRCERASE_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_NOTSRCERASE_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_NOTSRCERASE_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -252,17 +254,17 @@ static int BitBlt_NOTSRCERASE_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int } } - return 1; + return TRUE; } -static int BitBlt_SRCINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -280,17 +282,17 @@ static int BitBlt_SRCINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_SRCAND_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCAND_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -308,17 +310,17 @@ static int BitBlt_SRCAND_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidt } } - return 1; + return TRUE; } -static int BitBlt_SRCPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SRCPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -336,19 +338,20 @@ static int BitBlt_SRCPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -static int BitBlt_DSPDxax_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_DSPDxax_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { if (!hdcSrc || !hdcDest) - return 0; + return FALSE; /* TODO: Implement 8bpp DSPDxax BitBlt */ - return 1; + WLog_ERR(TAG, "%s: not implemented", __FUNCTION__); + return TRUE; } -static int BitBlt_PSDPxax_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_PSDPxax_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; @@ -357,7 +360,7 @@ static int BitBlt_PSDPxax_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid BYTE color8; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; /* D = (S & D) | (~S & P) */ @@ -402,10 +405,10 @@ static int BitBlt_PSDPxax_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid } } - return 1; + return TRUE; } -static int BitBlt_SPna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_SPna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; @@ -413,7 +416,7 @@ static int BitBlt_SPna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, BYTE* patp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -434,10 +437,10 @@ static int BitBlt_SPna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, } } - return 1; + return TRUE; } -static int BitBlt_DPa_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_DPa_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; BYTE* dstp; @@ -459,10 +462,10 @@ static int BitBlt_DPa_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, } } - return 1; + return TRUE; } -static int BitBlt_PDxn_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PDxn_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; BYTE* dstp; @@ -485,17 +488,17 @@ static int BitBlt_PDxn_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, } } - return 1; + return TRUE; } -static int BitBlt_DSna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_DSna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -513,10 +516,10 @@ static int BitBlt_DSna_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, } } - return 1; + return TRUE; } -static int BitBlt_MERGECOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_MERGECOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; @@ -524,7 +527,7 @@ static int BitBlt_MERGECOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW BYTE* patp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -545,17 +548,17 @@ static int BitBlt_MERGECOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_MERGEPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_MERGEPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; BYTE* dstp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -573,10 +576,10 @@ static int BitBlt_MERGEPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int n } } - return 1; + return TRUE; } -static int BitBlt_PATCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PATCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y, xOffset, yOffset; BYTE* dstp; @@ -632,10 +635,10 @@ static int BitBlt_PATCOPY_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWid } } - return 1; + return TRUE; } -static int BitBlt_PATINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) +static BOOL BitBlt_PATINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight) { int x, y; BYTE* dstp; @@ -678,10 +681,10 @@ static int BitBlt_PATINVERT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nW } } - return 1; + return TRUE; } -static int BitBlt_PATPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) +static BOOL BitBlt_PATPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc) { int x, y; BYTE* srcp; @@ -689,7 +692,7 @@ static int BitBlt_PATPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi BYTE* patp; if (!hdcSrc || !hdcDest) - return 0; + return FALSE; for (y = 0; y < nHeight; y++) { @@ -710,27 +713,27 @@ static int BitBlt_PATPAINT_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWi } } - return 1; + return TRUE; } -int BitBlt_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop) +BOOL BitBlt_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop) { if (!hdcDest) - return 0; + return FALSE; if (hdcSrc != NULL) { - if (gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, &nXSrc, &nYSrc) == 0) - return 0; + if (!gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, &nXSrc, &nYSrc)) + return TRUE; } else { - if (gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdcDest, &nXDest, &nYDest, &nWidth, &nHeight, NULL, NULL)) + return TRUE; } if (!gdi_InvalidateRegion(hdcDest, nXDest, nYDest, nWidth, nHeight)) - return 0; + return FALSE; switch (rop) { @@ -793,16 +796,16 @@ int BitBlt_8bpp(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight } WLog_ERR(TAG, "BitBlt: unknown rop: 0x%08X", rop); - return 1; + return FALSE; } -int PatBlt_8bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop) +BOOL PatBlt_8bpp(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop) { - if (gdi_ClipCoords(hdc, &nXLeft, &nYLeft, &nWidth, &nHeight, NULL, NULL) == 0) - return 0; + if (!gdi_ClipCoords(hdc, &nXLeft, &nYLeft, &nWidth, &nHeight, NULL, NULL)) + return TRUE; if (!gdi_InvalidateRegion(hdc, nXLeft, nYLeft, nWidth, nHeight)) - return 0; + return FALSE; switch (rop) { @@ -1054,15 +1057,15 @@ pLineTo_8bpp LineTo_ROP2_8bpp[32] = LineTo_WHITE_8bpp }; -int LineTo_8bpp(HGDI_DC hdc, int nXEnd, int nYEnd) +BOOL LineTo_8bpp(HGDI_DC hdc, int nXEnd, int nYEnd) { pLineTo_8bpp _LineTo; int rop2 = gdi_GetROP2(hdc) - 1; _LineTo = LineTo_ROP2_8bpp[rop2]; - if (_LineTo != NULL) - return _LineTo(hdc, nXEnd, nYEnd); - else - return 0; + if (_LineTo == NULL) + return FALSE; + + return _LineTo(hdc, nXEnd, nYEnd); } diff --git a/libfreerdp/gdi/bitmap.c b/libfreerdp/gdi/bitmap.c index da150ec24..cc3ee84ed 100644 --- a/libfreerdp/gdi/bitmap.c +++ b/libfreerdp/gdi/bitmap.c @@ -198,12 +198,12 @@ HGDI_BITMAP gdi_CreateCompatibleBitmap(HGDI_DC hdc, int nWidth, int nHeight) * @return 0 on failure, non-zero otherwise */ -int gdi_BitBlt(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, int rop) +BOOL gdi_BitBlt(HGDI_DC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HGDI_DC hdcSrc, int nXSrc, int nYSrc, DWORD rop) { p_BitBlt _BitBlt = BitBlt_[IBPP(hdcDest->bitsPerPixel)]; - if (_BitBlt != NULL) - return _BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, rop); - else - return 0; + if (_BitBlt == NULL) + return FALSE; + + return _BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, rop); } diff --git a/libfreerdp/gdi/brush.c b/libfreerdp/gdi/brush.c index 2e62138d6..0fadb9768 100644 --- a/libfreerdp/gdi/brush.c +++ b/libfreerdp/gdi/brush.c @@ -100,15 +100,15 @@ HGDI_BRUSH gdi_CreateHatchBrush(HGDI_BITMAP hbmp) * @param nWidth width * @param nHeight height * @param rop raster operation code - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -int gdi_PatBlt(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, int rop) +BOOL gdi_PatBlt(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight, DWORD rop) { p_PatBlt _PatBlt = PatBlt_[IBPP(hdc->bitsPerPixel)]; - if (_PatBlt != NULL) - return _PatBlt(hdc, nXLeft, nYLeft, nWidth, nHeight, rop); - else - return 0; + if (_PatBlt == NULL) + return FALSE; + + return _PatBlt(hdc, nXLeft, nYLeft, nWidth, nHeight, rop); } diff --git a/libfreerdp/gdi/clipping.c b/libfreerdp/gdi/clipping.c index e6186a14f..74b259820 100644 --- a/libfreerdp/gdi/clipping.c +++ b/libfreerdp/gdi/clipping.c @@ -32,7 +32,7 @@ #include -int gdi_SetClipRgn(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight) +BOOL gdi_SetClipRgn(HGDI_DC hdc, int nXLeft, int nYLeft, int nWidth, int nHeight) { return gdi_SetRgn(hdc->clip, nXLeft, nYLeft, nWidth, nHeight); } @@ -52,14 +52,14 @@ HGDI_RGN gdi_GetClipRgn(HGDI_DC hdc) /** * Set the current clipping region to null. * @param hdc device context - * @return + * @return nonzero on success, 0 otherwise */ -int gdi_SetNullClipRgn(HGDI_DC hdc) +BOOL gdi_SetNullClipRgn(HGDI_DC hdc) { gdi_SetClipRgn(hdc, 0, 0, 0, 0); hdc->clip->null = 1; - return 0; + return TRUE; } /** @@ -71,10 +71,10 @@ int gdi_SetNullClipRgn(HGDI_DC hdc) * @param h height * @param srcx source x1 * @param srcy source y1 - * @return 1 if there is something to draw, 0 otherwise + * @return nonzero if there is something to draw, 0 otherwise */ -int gdi_ClipCoords(HGDI_DC hdc, int *x, int *y, int *w, int *h, int *srcx, int *srcy) +BOOL gdi_ClipCoords(HGDI_DC hdc, int *x, int *y, int *w, int *h, int *srcx, int *srcy) { GDI_RECT bmp; GDI_RECT clip; @@ -83,10 +83,10 @@ int gdi_ClipCoords(HGDI_DC hdc, int *x, int *y, int *w, int *h, int *srcx, int * int dx = 0; int dy = 0; - int draw = 1; + BOOL draw = TRUE; if (hdc == NULL) - return 0; + return FALSE; hBmp = (HGDI_BITMAP) hdc->selectedObject; @@ -152,7 +152,7 @@ int gdi_ClipCoords(HGDI_DC hdc, int *x, int *y, int *w, int *h, int *srcx, int * coords.right = 0; coords.top = 0; coords.bottom = 0; - draw = 0; + draw = FALSE; } if (srcx != NULL) diff --git a/libfreerdp/gdi/dc.c b/libfreerdp/gdi/dc.c index 037cfdbc7..b816a77b5 100644 --- a/libfreerdp/gdi/dc.c +++ b/libfreerdp/gdi/dc.c @@ -44,6 +44,7 @@ HGDI_DC gdi_GetDC() HGDI_DC hDC = (HGDI_DC) malloc(sizeof(GDI_DC)); if (!hDC) return NULL; + hDC->bytesPerPixel = 4; hDC->bitsPerPixel = 32; hDC->drawMode = GDI_R2_BLACK; @@ -104,7 +105,6 @@ HGDI_DC gdi_CreateDC(UINT32 flags, int bpp) fail: gdi_DeleteDC(hDC); - free(hDC); return NULL; } @@ -189,13 +189,13 @@ HGDIOBJECT gdi_SelectObject(HGDI_DC hdc, HGDIOBJECT hgdiobject) * Delete a GDI object.\n * @msdn{dd183539} * @param hgdiobject GDI object - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -int gdi_DeleteObject(HGDIOBJECT hgdiobject) +BOOL gdi_DeleteObject(HGDIOBJECT hgdiobject) { if (!hgdiobject) - return 0; + return FALSE; if (hgdiobject->objectType == GDIOBJECT_BITMAP) { @@ -235,20 +235,20 @@ int gdi_DeleteObject(HGDIOBJECT hgdiobject) { /* Unknown GDI Object Type */ free(hgdiobject); - return 0; + return FALSE; } - return 1; + return TRUE; } /** * Delete device context.\n * @msdn{dd183533} * @param hdc device context - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -int gdi_DeleteDC(HGDI_DC hdc) +BOOL gdi_DeleteDC(HGDI_DC hdc) { if (hdc) { @@ -262,5 +262,5 @@ int gdi_DeleteDC(HGDI_DC hdc) free(hdc); } - return 1; + return TRUE; } diff --git a/libfreerdp/gdi/drawing.c b/libfreerdp/gdi/drawing.c index 9b81d657d..1e1475dc7 100644 --- a/libfreerdp/gdi/drawing.c +++ b/libfreerdp/gdi/drawing.c @@ -107,16 +107,17 @@ int gdi_GetBkMode(HGDI_DC hdc) * @msdn{dd162965} * @param hdc device context * @param iBkMode background mode - * @return + * @return previous background mode on success, 0 on failure */ int gdi_SetBkMode(HGDI_DC hdc, int iBkMode) { if (iBkMode == GDI_OPAQUE || iBkMode == GDI_TRANSPARENT) + { + int previousBkMode = hdc->bkMode; hdc->bkMode = iBkMode; - else - hdc->bkMode = GDI_OPAQUE; - + return previousBkMode; + } return 0; } diff --git a/libfreerdp/gdi/gdi.c b/libfreerdp/gdi/gdi.c index fd17e8500..271ecd7ef 100644 --- a/libfreerdp/gdi/gdi.c +++ b/libfreerdp/gdi/gdi.c @@ -45,7 +45,7 @@ #define TAG FREERDP_TAG("gdi") /* Ternary Raster Operation Table */ -static const UINT32 rop3_code_table[] = +static const DWORD rop3_code_table[] = { 0x00000042, /* 0 */ 0x00010289, /* DPSoon */ @@ -318,7 +318,7 @@ static BYTE GDI_BS_HATCHED_PATTERNS[] = /* GDI Helper Functions */ -INLINE UINT32 gdi_rop3_code(BYTE code) +INLINE DWORD gdi_rop3_code(BYTE code) { return rop3_code_table[code]; } @@ -585,10 +585,9 @@ static BOOL gdi_dstblt(rdpContext* context, DSTBLT_ORDER* dstblt) { rdpGdi* gdi = context->gdi; - if (gdi_BitBlt(gdi->drawing->hdc, dstblt->nLeftRect, dstblt->nTopRect, - dstblt->nWidth, dstblt->nHeight, NULL, 0, 0, gdi_rop3_code(dstblt->bRop)) == 0) - return FALSE; - return TRUE; + return gdi_BitBlt(gdi->drawing->hdc, dstblt->nLeftRect, dstblt->nTopRect, + dstblt->nWidth, dstblt->nHeight, NULL, 0, 0, + gdi_rop3_code(dstblt->bRop)); } static BOOL gdi_patblt(rdpContext* context, PATBLT_ORDER* patblt) @@ -620,9 +619,11 @@ static BOOL gdi_patblt(rdpContext* context, PATBLT_ORDER* patblt) goto out_error; } - if (gdi_PatBlt(gdi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, - patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop)) == 0) + if (!gdi_PatBlt(gdi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, + patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop))) + { ret = FALSE; + } gdi_DeleteObject((HGDIOBJECT) gdi->drawing->hdc->brush); gdi->drawing->hdc->brush = originalBrush; @@ -661,9 +662,11 @@ static BOOL gdi_patblt(rdpContext* context, PATBLT_ORDER* patblt) goto out_error; } - if (gdi_PatBlt(gdi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, - patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop)) == 0) + if (!gdi_PatBlt(gdi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, + patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop))) + { ret = FALSE; + } gdi_DeleteObject((HGDIOBJECT) gdi->drawing->hdc->brush); gdi->drawing->hdc->brush = originalBrush; @@ -717,9 +720,11 @@ static BOOL gdi_patblt(rdpContext* context, PATBLT_ORDER* patblt) goto out_error; } - if (gdi_PatBlt(gdi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, - patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop)) == 0) + if (!gdi_PatBlt(gdi->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, + patblt->nWidth, patblt->nHeight, gdi_rop3_code(patblt->bRop))) + { ret = FALSE; + } gdi_DeleteObject((HGDIOBJECT) gdi->drawing->hdc->brush); gdi->drawing->hdc->brush = originalBrush; @@ -738,11 +743,9 @@ static BOOL gdi_scrblt(rdpContext* context, SCRBLT_ORDER* scrblt) { rdpGdi* gdi = context->gdi; - if (gdi_BitBlt(gdi->drawing->hdc, scrblt->nLeftRect, scrblt->nTopRect, + return gdi_BitBlt(gdi->drawing->hdc, scrblt->nLeftRect, scrblt->nTopRect, scrblt->nWidth, scrblt->nHeight, gdi->primary->hdc, - scrblt->nXSrc, scrblt->nYSrc, gdi_rop3_code(scrblt->bRop)) == 0) - return FALSE; - return TRUE; + scrblt->nXSrc, scrblt->nYSrc, gdi_rop3_code(scrblt->bRop)); } static BOOL gdi_opaque_rect(rdpContext* context, OPAQUE_RECT_ORDER* opaque_rect) @@ -751,20 +754,19 @@ static BOOL gdi_opaque_rect(rdpContext* context, OPAQUE_RECT_ORDER* opaque_rect) HGDI_BRUSH hBrush; UINT32 brush_color; rdpGdi* gdi = context->gdi; - BOOL ret = FALSE; + BOOL ret; gdi_CRgnToRect(opaque_rect->nLeftRect, opaque_rect->nTopRect, opaque_rect->nWidth, opaque_rect->nHeight, &rect); brush_color = freerdp_convert_gdi_order_color(opaque_rect->color, gdi->srcBpp, gdi->format, gdi->palette); - hBrush = gdi_CreateSolidBrush(brush_color); - if (hBrush) - { - if (gdi_FillRect(gdi->drawing->hdc, &rect, hBrush) == 0) - ret = TRUE; - gdi_DeleteObject((HGDIOBJECT) hBrush); - } + if (!(hBrush = gdi_CreateSolidBrush(brush_color))) + return FALSE; + + ret = gdi_FillRect(gdi->drawing->hdc, &rect, hBrush); + gdi_DeleteObject((HGDIOBJECT) hBrush); + return ret; } @@ -807,9 +809,9 @@ static BOOL gdi_line_to(rdpContext* context, LINE_TO_ORDER* lineTo) rdpGdi* gdi = context->gdi; color = freerdp_convert_gdi_order_color(lineTo->penColor, gdi->srcBpp, gdi->format, gdi->palette); - hPen = gdi_CreatePen(lineTo->penStyle, lineTo->penWidth, (GDI_COLOR) color); - if (!hPen) + if (!(hPen = gdi_CreatePen(lineTo->penStyle, lineTo->penWidth, (GDI_COLOR) color))) return FALSE; + gdi_SelectObject(gdi->drawing->hdc, (HGDIOBJECT) hPen); gdi_SetROP2(gdi->drawing->hdc, lineTo->bRop2); @@ -831,9 +833,9 @@ static BOOL gdi_polyline(rdpContext* context, POLYLINE_ORDER* polyline) rdpGdi* gdi = context->gdi; color = freerdp_convert_gdi_order_color(polyline->penColor, gdi->srcBpp, gdi->format, gdi->palette); - hPen = gdi_CreatePen(GDI_PS_SOLID, 1, (GDI_COLOR) color); - if (!hPen) + if (!(hPen = gdi_CreatePen(GDI_PS_SOLID, 1, (GDI_COLOR) color))) return FALSE; + gdi_SelectObject(gdi->drawing->hdc, (HGDIOBJECT) hPen); gdi_SetROP2(gdi->drawing->hdc, polyline->bRop2); @@ -861,11 +863,9 @@ static BOOL gdi_memblt(rdpContext* context, MEMBLT_ORDER* memblt) bitmap = (gdiBitmap*) memblt->bitmap; - if (gdi_BitBlt(gdi->drawing->hdc, memblt->nLeftRect, memblt->nTopRect, + return gdi_BitBlt(gdi->drawing->hdc, memblt->nLeftRect, memblt->nTopRect, memblt->nWidth, memblt->nHeight, bitmap->hdc, - memblt->nXSrc, memblt->nYSrc, gdi_rop3_code(memblt->bRop)) == 0) - return FALSE; - return TRUE; + memblt->nXSrc, memblt->nYSrc, gdi_rop3_code(memblt->bRop)); } static BOOL gdi_mem3blt(rdpContext* context, MEM3BLT_ORDER* mem3blt) @@ -972,25 +972,25 @@ out_fail: static BOOL gdi_polygon_sc(rdpContext* context, POLYGON_SC_ORDER* polygon_sc) { - WLog_VRB(TAG, "not implemented"); + WLog_VRB(TAG, "%s: not implemented", __FUNCTION__); return TRUE; } static BOOL gdi_polygon_cb(rdpContext* context, POLYGON_CB_ORDER* polygon_cb) { - WLog_VRB(TAG, "not implemented"); + WLog_VRB(TAG, "%s: not implemented", __FUNCTION__); return TRUE; } static BOOL gdi_ellipse_sc(rdpContext* context, ELLIPSE_SC_ORDER* ellipse_sc) { - WLog_VRB(TAG, "not implemented"); + WLog_VRB(TAG, "%s: not implemented", __FUNCTION__); return TRUE; } static BOOL gdi_ellipse_cb(rdpContext* context, ELLIPSE_CB_ORDER* ellipse_cb) { - WLog_VRB(TAG, "not implemented"); + WLog_VRB(TAG, "%s: not implemented", __FUNCTION__); return TRUE; } diff --git a/libfreerdp/gdi/graphics.c b/libfreerdp/gdi/graphics.c index 4ca13748c..8e53c5280 100644 --- a/libfreerdp/gdi/graphics.c +++ b/libfreerdp/gdi/graphics.c @@ -143,10 +143,8 @@ BOOL gdi_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap) width = bitmap->right - bitmap->left + 1; height = bitmap->bottom - bitmap->top + 1; - if (gdi_BitBlt(context->gdi->primary->hdc, bitmap->left, bitmap->top, - width, height, gdi_bitmap->hdc, 0, 0, GDI_SRCCOPY) == 0) - return FALSE; - return TRUE; + return gdi_BitBlt(context->gdi->primary->hdc, bitmap->left, bitmap->top, + width, height, gdi_bitmap->hdc, 0, 0, GDI_SRCCOPY); } BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap, @@ -279,10 +277,8 @@ BOOL gdi_Glyph_Draw(rdpContext* context, rdpGlyph* glyph, int x, int y) gdi_glyph = (gdiGlyph*) glyph; - if (gdi_BitBlt(gdi->drawing->hdc, x, y, gdi_glyph->bitmap->width, - gdi_glyph->bitmap->height, gdi_glyph->hdc, 0, 0, GDI_DSPDxax) == 0) - return FALSE; - return TRUE; + return gdi_BitBlt(gdi->drawing->hdc, x, y, gdi_glyph->bitmap->width, + gdi_glyph->bitmap->height, gdi_glyph->hdc, 0, 0, GDI_DSPDxax); } BOOL gdi_Glyph_BeginDraw(rdpContext* context, int x, int y, int width, int height, UINT32 bgcolor, UINT32 fgcolor, BOOL fOpRedundant) @@ -290,27 +286,23 @@ BOOL gdi_Glyph_BeginDraw(rdpContext* context, int x, int y, int width, int heigh GDI_RECT rect; HGDI_BRUSH brush; rdpGdi* gdi = context->gdi; - int ret = 0; + BOOL ret = FALSE; /* TODO: handle fOpRedundant! See xf_Glyph_BeginDraw() */ bgcolor = freerdp_convert_gdi_order_color(bgcolor, gdi->srcBpp, gdi->format, gdi->palette); fgcolor = freerdp_convert_gdi_order_color(fgcolor, gdi->srcBpp, gdi->format, gdi->palette); - brush = gdi_CreateSolidBrush(fgcolor); - if (!brush) - goto out_fail; + if (!(brush = gdi_CreateSolidBrush(fgcolor))) + goto out; gdi_CRgnToRect(x, y, width, height, &rect); ret = gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT) brush); -out_fail: +out: gdi->textColor = gdi_SetTextColor(gdi->drawing->hdc, bgcolor); - - if (ret == 0) - return FALSE; - return TRUE; + return ret; } BOOL gdi_Glyph_EndDraw(rdpContext* context, int x, int y, int width, int height, UINT32 bgcolor, UINT32 fgcolor) diff --git a/libfreerdp/gdi/include/line.c b/libfreerdp/gdi/include/line.c index fb48c2552..2df68c1c6 100644 --- a/libfreerdp/gdi/include/line.c +++ b/libfreerdp/gdi/include/line.c @@ -19,7 +19,7 @@ /* do not include this file directly! */ -int LINE_TO(HGDI_DC hdc, int nXEnd, int nYEnd) +BOOL LINE_TO(HGDI_DC hdc, int nXEnd, int nYEnd) { int x, y; int x1, y1; @@ -72,7 +72,7 @@ int LINE_TO(HGDI_DC hdc, int nXEnd, int nYEnd) by2 = MIN(by2, bmp->height - 1); if (!gdi_InvalidateRegion(hdc, bx1, by1, bx2 - bx1 + 1, by2 - by1 + 1)) - return 0; + return FALSE; pen = GDI_GET_PEN_COLOR(hdc->pen); @@ -106,7 +106,7 @@ int LINE_TO(HGDI_DC hdc, int nXEnd, int nYEnd) } } - return 1; + return TRUE; } /* diff --git a/libfreerdp/gdi/line.c b/libfreerdp/gdi/line.c index aef8b9e9b..9d1b4248a 100644 --- a/libfreerdp/gdi/line.c +++ b/libfreerdp/gdi/line.c @@ -49,17 +49,17 @@ p_LineTo LineTo_[5] = * @param hdc device context * @param nXEnd ending x position * @param nYEnd ending y position - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -int gdi_LineTo(HGDI_DC hdc, int nXEnd, int nYEnd) +BOOL gdi_LineTo(HGDI_DC hdc, int nXEnd, int nYEnd) { p_LineTo _LineTo = LineTo_[IBPP(hdc->bitsPerPixel)]; - if (_LineTo != NULL) - return _LineTo(hdc, nXEnd, nYEnd); - else - return 0; + if (_LineTo == NULL) + return FALSE; + + return _LineTo(hdc, nXEnd, nYEnd); } /** @@ -67,19 +67,21 @@ int gdi_LineTo(HGDI_DC hdc, int nXEnd, int nYEnd) * @param hdc device context * @param lppt array of points * @param cCount number of points - * @return + * @return nonzero on success, 0 otherwise */ -int gdi_PolylineTo(HGDI_DC hdc, GDI_POINT *lppt, int cCount) +BOOL gdi_PolylineTo(HGDI_DC hdc, GDI_POINT *lppt, DWORD cCount) { - int i; + DWORD i; for (i = 0; i < cCount; i++) { - gdi_LineTo(hdc, lppt[i].x, lppt[i].y); - gdi_MoveToEx(hdc, lppt[i].x, lppt[i].y, NULL); + if (!gdi_LineTo(hdc, lppt[i].x, lppt[i].y)) + return FALSE; + if (!gdi_MoveToEx(hdc, lppt[i].x, lppt[i].y, NULL)) + return FALSE; } - return 1; + return TRUE; } /** @@ -87,27 +89,31 @@ int gdi_PolylineTo(HGDI_DC hdc, GDI_POINT *lppt, int cCount) * @param hdc device context * @param lppt array of points * @param cPoints number of points - * @return + * @return nonzero on success, 0 otherwise */ -int gdi_Polyline(HGDI_DC hdc, GDI_POINT *lppt, int cPoints) +BOOL gdi_Polyline(HGDI_DC hdc, GDI_POINT *lppt, int cPoints) { if (cPoints > 0) { int i; GDI_POINT pt; - gdi_MoveToEx(hdc, lppt[0].x, lppt[0].y, &pt); + if (!gdi_MoveToEx(hdc, lppt[0].x, lppt[0].y, &pt)) + return FALSE; for (i = 0; i < cPoints; i++) { - gdi_LineTo(hdc, lppt[i].x, lppt[i].y); - gdi_MoveToEx(hdc, lppt[i].x, lppt[i].y, NULL); + if (!gdi_LineTo(hdc, lppt[i].x, lppt[i].y)) + return FALSE; + if (!gdi_MoveToEx(hdc, lppt[i].x, lppt[i].y, NULL)) + return FALSE; } - gdi_MoveToEx(hdc, pt.x, pt.y, NULL); + if (!gdi_MoveToEx(hdc, pt.x, pt.y, NULL)) + return FALSE; } - return 1; + return TRUE; } /** @@ -116,21 +122,22 @@ int gdi_Polyline(HGDI_DC hdc, GDI_POINT *lppt, int cPoints) * @param lppt array of points * @param lpdwPolyPoints array of numbers of points per series * @param cCount count of entries in lpdwPolyPoints - * @return + * @return nonzero on success, 0 otherwise */ -int gdi_PolyPolyline(HGDI_DC hdc, GDI_POINT *lppt, int *lpdwPolyPoints, int cCount) +BOOL gdi_PolyPolyline(HGDI_DC hdc, GDI_POINT *lppt, int *lpdwPolyPoints, DWORD cCount) { int cPoints; - int i, j = 0; + DWORD i, j = 0; for (i = 0; i < cCount; i++) { cPoints = lpdwPolyPoints[i]; - gdi_Polyline(hdc, &lppt[j], cPoints); + if (!gdi_Polyline(hdc, &lppt[j], cPoints)) + return FALSE; j += cPoints; } - return 1; + return TRUE; } /** @@ -138,10 +145,10 @@ int gdi_PolyPolyline(HGDI_DC hdc, GDI_POINT *lppt, int *lpdwPolyPoints, int cCou * @param hdc device context * @param X x position * @param Y y position - * @return 1 if successful, 0 otherwise + * @return nonzero on success, 0 otherwise */ -int gdi_MoveToEx(HGDI_DC hdc, int X, int Y, HGDI_POINT lpPoint) +BOOL gdi_MoveToEx(HGDI_DC hdc, int X, int Y, HGDI_POINT lpPoint) { if (lpPoint != NULL) { @@ -152,5 +159,5 @@ int gdi_MoveToEx(HGDI_DC hdc, int X, int Y, HGDI_POINT lpPoint) hdc->pen->posX = X; hdc->pen->posY = Y; - return 1; + return TRUE; } diff --git a/libfreerdp/gdi/region.c b/libfreerdp/gdi/region.c index 13cd0d549..888a8483f 100644 --- a/libfreerdp/gdi/region.c +++ b/libfreerdp/gdi/region.c @@ -46,6 +46,7 @@ HGDI_RGN gdi_CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBot HGDI_RGN hRgn = (HGDI_RGN) malloc(sizeof(GDI_RGN)); if (!hRgn) return NULL; + hRgn->objectType = GDIOBJECT_REGION; hRgn->x = nLeftRect; hRgn->y = nTopRect; @@ -69,6 +70,7 @@ HGDI_RECT gdi_CreateRect(int xLeft, int yTop, int xRight, int yBottom) HGDI_RECT hRect = (HGDI_RECT) malloc(sizeof(GDI_RECT)); if (!hRect) return NULL; + hRect->objectType = GDIOBJECT_RECT; hRect->left = xLeft; hRect->top = yTop; @@ -221,10 +223,10 @@ INLINE void gdi_CRgnToCRect(int x, int y, int w, int h, int *left, int *top, int * @param height height * @param srcx source x1 * @param srcy source y1 - * @return 1 if there is an overlap, 0 otherwise + * @return nonzero if there is an overlap, 0 otherwise */ -INLINE int gdi_CopyOverlap(int x, int y, int width, int height, int srcx, int srcy) +INLINE BOOL gdi_CopyOverlap(int x, int y, int width, int height, int srcx, int srcy) { GDI_RECT dst; GDI_RECT src; @@ -233,7 +235,7 @@ INLINE int gdi_CopyOverlap(int x, int y, int width, int height, int srcx, int sr gdi_CRgnToRect(srcx, srcy, width, height, &src); return (dst.right > src.left && dst.left < src.right && - dst.bottom > src.top && dst.top < src.bottom) ? 1 : 0; + dst.bottom > src.top && dst.top < src.bottom) ? TRUE : FALSE; } /** @@ -244,16 +246,16 @@ INLINE int gdi_CopyOverlap(int x, int y, int width, int height, int srcx, int sr * @param yTop y1 * @param xRight x2 * @param yBottom y2 - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -INLINE int gdi_SetRect(HGDI_RECT rc, int xLeft, int yTop, int xRight, int yBottom) +INLINE BOOL gdi_SetRect(HGDI_RECT rc, int xLeft, int yTop, int xRight, int yBottom) { rc->left = xLeft; rc->top = yTop; rc->right = xRight; rc->bottom = yBottom; - return 1; + return TRUE; } /** @@ -263,17 +265,17 @@ INLINE int gdi_SetRect(HGDI_RECT rc, int xLeft, int yTop, int xRight, int yBotto * @param nYLeft y1 * @param nWidth width * @param nHeight height - * @return + * @return nonzero if successful, 0 otherwise */ -INLINE int gdi_SetRgn(HGDI_RGN hRgn, int nXLeft, int nYLeft, int nWidth, int nHeight) +INLINE BOOL gdi_SetRgn(HGDI_RGN hRgn, int nXLeft, int nYLeft, int nWidth, int nHeight) { hRgn->x = nXLeft; hRgn->y = nYLeft; hRgn->w = nWidth; hRgn->h = nHeight; hRgn->null = 0; - return 0; + return TRUE; } /** @@ -283,14 +285,14 @@ INLINE int gdi_SetRgn(HGDI_RGN hRgn, int nXLeft, int nYLeft, int nWidth, int nHe * @param nTopRect y1 * @param nRightRect x2 * @param nBottomRect y2 - * @return + * @return nonzero if successful, 0 otherwise */ -INLINE int gdi_SetRectRgn(HGDI_RGN hRgn, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect) +INLINE BOOL gdi_SetRectRgn(HGDI_RGN hRgn, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect) { gdi_CRectToRgn(nLeftRect, nTopRect, nRightRect, nBottomRect, hRgn); hRgn->null = 0; - return 0; + return TRUE; } /** @@ -298,36 +300,37 @@ INLINE int gdi_SetRectRgn(HGDI_RGN hRgn, int nLeftRect, int nTopRect, int nRight * @msdn{dd162700} * @param hSrcRgn1 first region * @param hSrcRgn2 second region - * @return 1 if both regions are equal, 0 otherwise + * @return nonzero if both regions are equal, 0 otherwise */ -INLINE int gdi_EqualRgn(HGDI_RGN hSrcRgn1, HGDI_RGN hSrcRgn2) +INLINE BOOL gdi_EqualRgn(HGDI_RGN hSrcRgn1, HGDI_RGN hSrcRgn2) { if ((hSrcRgn1->x == hSrcRgn2->x) && (hSrcRgn1->y == hSrcRgn2->y) && (hSrcRgn1->w == hSrcRgn2->w) && (hSrcRgn1->h == hSrcRgn2->h)) { - return 1; + return TRUE; } - return 0; + return FALSE; } /** * Copy coordinates from a rectangle to another rectangle + * @msdn{dd183481} * @param dst destination rectangle * @param src source rectangle - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -INLINE int gdi_CopyRect(HGDI_RECT dst, HGDI_RECT src) +INLINE BOOL gdi_CopyRect(HGDI_RECT dst, HGDI_RECT src) { dst->left = src->left; dst->top = src->top; dst->right = src->right; dst->bottom = src->bottom; - return 1; + return TRUE; } /** @@ -336,10 +339,10 @@ INLINE int gdi_CopyRect(HGDI_RECT dst, HGDI_RECT src) * @param rc rectangle * @param x point x position * @param y point y position - * @return 1 if the point is inside, 0 otherwise + * @return nonzero if the point is inside, 0 otherwise */ -INLINE int gdi_PtInRect(HGDI_RECT rc, int x, int y) +INLINE BOOL gdi_PtInRect(HGDI_RECT rc, int x, int y) { /* * points on the left and top sides are considered in, @@ -350,11 +353,11 @@ INLINE int gdi_PtInRect(HGDI_RECT rc, int x, int y) { if (y >= rc->top && y <= rc->bottom) { - return 1; + return TRUE; } } - return 0; + return FALSE; } /** @@ -365,7 +368,7 @@ INLINE int gdi_PtInRect(HGDI_RECT rc, int x, int y) * @param y y1 * @param w width * @param h height - * @return FALSE on error + * @return nonzero on success, 0 otherwise */ INLINE BOOL gdi_InvalidateRegion(HGDI_DC hdc, int x, int y, int w, int h) diff --git a/libfreerdp/gdi/shape.c b/libfreerdp/gdi/shape.c index 840c68771..fc7d61908 100644 --- a/libfreerdp/gdi/shape.c +++ b/libfreerdp/gdi/shape.c @@ -156,17 +156,18 @@ static void Ellipse_Bresenham(HGDI_DC hdc, int x1, int y1, int x2, int y2) /** * Draw an ellipse + * @msdn{dd162510} * @param hdc device context * @param nLeftRect x1 * @param nTopRect y1 * @param nRightRect x2 * @param nBottomRect y2 - * @return + * @return nonzero if successful, 0 otherwise */ -int gdi_Ellipse(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect) +BOOL gdi_Ellipse(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect) { Ellipse_Bresenham(hdc, nLeftRect, nTopRect, nRightRect, nBottomRect); - return 1; + return TRUE; } /** @@ -175,54 +176,57 @@ int gdi_Ellipse(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nB * @param hdc device context * @param rect rectangle * @param hbr brush - * @return 1 if successful, 0 otherwise + * @return nonzero if successful, 0 otherwise */ -int gdi_FillRect(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) +BOOL gdi_FillRect(HGDI_DC hdc, HGDI_RECT rect, HGDI_BRUSH hbr) { p_FillRect _FillRect = FillRect_[IBPP(hdc->bitsPerPixel)]; - if (_FillRect != NULL) - return _FillRect(hdc, rect, hbr); - else - return 0; + if (_FillRect == NULL) + return FALSE; + + return _FillRect(hdc, rect, hbr); } /** - * + * Draw a polygon + * @msdn{dd162814} * @param hdc device context * @param lpPoints array of points * @param nCount number of points - * @return + * @return nonzero if successful, 0 otherwise */ -int gdi_Polygon(HGDI_DC hdc, GDI_POINT *lpPoints, int nCount) +BOOL gdi_Polygon(HGDI_DC hdc, GDI_POINT *lpPoints, int nCount) { - return 1; + return TRUE; } /** * Draw a series of closed polygons + * @msdn{dd162818} * @param hdc device context * @param lpPoints array of series of points * @param lpPolyCounts array of number of points in each series * @param nCount count of number of points in lpPolyCounts - * @return + * @return nonzero if successful, 0 otherwise */ -int gdi_PolyPolygon(HGDI_DC hdc, GDI_POINT *lpPoints, int *lpPolyCounts, int nCount) +BOOL gdi_PolyPolygon(HGDI_DC hdc, GDI_POINT *lpPoints, int *lpPolyCounts, int nCount) { - return 1; + return TRUE; } /** * Draw a rectangle + * @msdn{dd162898} * @param hdc device context * @param nLeftRect x1 * @param nTopRect y1 * @param nRightRect x2 * @param nBottomRect y2 - * @return + * @return nonzero if successful, 0 otherwise */ -int gdi_Rectangle(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect) +BOOL gdi_Rectangle(HGDI_DC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect) { - return 1; + return TRUE; } diff --git a/libfreerdp/gdi/test/TestGdiBitBlt.c b/libfreerdp/gdi/test/TestGdiBitBlt.c index 1ff1c086f..d9f51d79a 100644 --- a/libfreerdp/gdi/test/TestGdiBitBlt.c +++ b/libfreerdp/gdi/test/TestGdiBitBlt.c @@ -652,106 +652,184 @@ int test_gdi_BitBlt_32bpp(void) gdi_SelectObject(hdcDst, (HGDIOBJECT) hBmpDst); /* SRCCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCCOPY, "SRCCOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } + gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* BLACKNESS */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_BLACKNESS); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_BLACKNESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_BLACKNESS, "BLACKNESS") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* WHITENESS */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_WHITENESS, "WHITENESS") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCAND */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCAND); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCAND)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCAND, "SRCAND") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } + gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCPAINT, "SRCPAINT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCINVERT, "SRCINVERT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCERASE */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCERASE); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCERASE)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCERASE, "SRCERASE") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* NOTSRCCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_NOTSRCCOPY, "NOTSRCCOPY") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* NOTSRCERASE */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCERASE); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCERASE)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_NOTSRCERASE, "NOTSRCERASE") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* DSTINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_DSTINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_DSTINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_DSTINVERT, "DSTINVERT") < 0) // return -1; @@ -762,66 +840,114 @@ int test_gdi_BitBlt_32bpp(void) /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* MERGECOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGECOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGECOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_MERGECOPY, "MERGECOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* MERGEPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGEPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGEPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_MERGEPAINT, "MERGEPAINT") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATCOPY, "PATCOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATINVERT, "PATINVERT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATPAINT, "PATPAINT") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SPna */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SPna); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SPna)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SPna, "SPna") < 0) return -1; @@ -950,106 +1076,182 @@ int test_gdi_BitBlt_16bpp(void) gdi_SelectObject(hdcDst, (HGDIOBJECT) hBmpDst); /* SRCCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCCOPY, "SRCCOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* BLACKNESS */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_BLACKNESS); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_BLACKNESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_BLACKNESS, "BLACKNESS") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* WHITENESS */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_WHITENESS, "WHITENESS") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCAND */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCAND); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCAND)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCAND, "SRCAND") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCPAINT, "SRCPAINT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCINVERT, "SRCINVERT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCERASE */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCERASE); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCERASE)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCERASE, "SRCERASE") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* NOTSRCCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_NOTSRCCOPY, "NOTSRCCOPY") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* NOTSRCERASE */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCERASE); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCERASE)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_NOTSRCERASE, "NOTSRCERASE") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* DSTINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_DSTINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_DSTINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_DSTINVERT, "DSTINVERT") < 0) // return -1; @@ -1060,66 +1262,114 @@ int test_gdi_BitBlt_16bpp(void) /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* MERGECOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGECOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGECOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_MERGECOPY, "MERGECOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* MERGEPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGEPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGEPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_MERGEPAINT, "MERGEPAINT") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATCOPY, "PATCOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATINVERT, "PATINVERT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATPAINT, "PATPAINT") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SPna */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SPna); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SPna)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SPna, "SPna") < 0) return -1; @@ -1248,106 +1498,182 @@ int test_gdi_BitBlt_8bpp(void) gdi_SelectObject(hdcDst, (HGDIOBJECT) hBmpDst); /* SRCCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (CompareBitmaps(hBmpDst, hBmp_SRCCOPY) != 1) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* BLACKNESS */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_BLACKNESS); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_BLACKNESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_BLACKNESS, "BLACKNESS") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* WHITENESS */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } //if (test_assert_bitmaps_equal(hBmpDst, hBmp_WHITENESS, "WHITENESS") < 0) // return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCAND */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCAND); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCAND)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCAND, "SRCAND") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCPAINT, "SRCPAINT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCINVERT, "SRCINVERT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SRCERASE */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCERASE); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCERASE)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SRCERASE, "SRCERASE") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* NOTSRCCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_NOTSRCCOPY, "NOTSRCCOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* NOTSRCERASE */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCERASE); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_NOTSRCERASE)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_NOTSRCERASE, "NOTSRCERASE") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* DSTINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_DSTINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_DSTINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_DSTINVERT, "DSTINVERT") < 0) return -1; @@ -1358,66 +1684,114 @@ int test_gdi_BitBlt_8bpp(void) /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* MERGECOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGECOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGECOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_MERGECOPY, "MERGECOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* MERGEPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGEPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_MERGEPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_MERGEPAINT, "MERGEPAINT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATCOPY */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATCOPY, "PATCOPY") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATINVERT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATINVERT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATINVERT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATINVERT, "PATINVERT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* PATPAINT */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATPAINT); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_PATPAINT)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_PATPAINT, "PATPAINT") < 0) return -1; /* restore original destination bitmap */ gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpDstOriginal); - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SRCCOPY)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SelectObject(hdcSrc, (HGDIOBJECT) hBmpSrc); /* SPna */ - gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SPna); + if (!gdi_BitBlt(hdcDst, 0, 0, 16, 16, hdcSrc, 0, 0, GDI_SPna)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } if (test_assert_bitmaps_equal(hBmpDst, hBmp_SPna, "SPna") < 0) return -1; diff --git a/libfreerdp/gdi/test/TestGdiClip.c b/libfreerdp/gdi/test/TestGdiClip.c index 98a62efdc..0bc95258b 100644 --- a/libfreerdp/gdi/test/TestGdiClip.c +++ b/libfreerdp/gdi/test/TestGdiClip.c @@ -14,7 +14,7 @@ int test_gdi_ClipCoords(void) { - int draw; + BOOL draw; HGDI_DC hdc; HGDI_RGN rgn1; HGDI_RGN rgn2; @@ -44,7 +44,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* region all inside clipping region */ @@ -54,7 +54,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* region all outside clipping region, on the left */ @@ -64,7 +64,7 @@ int test_gdi_ClipCoords(void) draw = gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (draw != 0) + if (draw) return -1; /* region all outside clipping region, on the right */ @@ -74,7 +74,7 @@ int test_gdi_ClipCoords(void) draw = gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (draw != 0) + if (draw) return -1; /* region all outside clipping region, on top */ @@ -84,7 +84,7 @@ int test_gdi_ClipCoords(void) draw = gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (draw != 0) + if (draw) return -1; /* region all outside clipping region, at the bottom */ @@ -94,7 +94,7 @@ int test_gdi_ClipCoords(void) draw = gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (draw != 0) + if (draw) return -1; /* left outside, right = clip, top = clip, bottom = clip */ @@ -104,7 +104,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* left outside, right inside, top = clip, bottom = clip */ @@ -114,7 +114,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* left = clip, right outside, top = clip, bottom = clip */ @@ -124,7 +124,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* left inside, right outside, top = clip, bottom = clip */ @@ -134,7 +134,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* top outside, bottom = clip, left = clip, right = clip */ @@ -144,7 +144,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* top = clip, bottom outside, left = clip, right = clip */ @@ -154,7 +154,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; /* top = clip, bottom = clip, top = clip, bottom = clip */ @@ -164,7 +164,7 @@ int test_gdi_ClipCoords(void) gdi_ClipCoords(hdc, &(rgn1->x), &(rgn1->y), &(rgn1->w), &(rgn1->h), NULL, NULL); - if (gdi_EqualRgn(rgn1, rgn2) != 1) + if (!gdi_EqualRgn(rgn1, rgn2)) return -1; return 0; @@ -210,7 +210,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* region same as invalid region */ @@ -220,7 +220,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* left outside */ @@ -230,7 +230,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* right outside */ @@ -240,7 +240,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* top outside */ @@ -250,7 +250,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* bottom outside */ @@ -260,7 +260,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* left outside, right outside */ @@ -270,7 +270,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* top outside, bottom outside */ @@ -280,7 +280,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* all outside, left */ @@ -290,7 +290,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* all outside, right */ @@ -300,7 +300,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* all outside, top */ @@ -310,7 +310,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* all outside, bottom */ @@ -320,7 +320,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* all outside */ @@ -330,7 +330,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; /* everything */ @@ -340,7 +340,7 @@ int test_gdi_InvalidateRegion(void) gdi_InvalidateRegion(hdc, rgn1->x, rgn1->y, rgn1->w, rgn1->h); - if (gdi_EqualRgn(invalid, rgn2) != 1) + if (!gdi_EqualRgn(invalid, rgn2)) return -1; return 0; diff --git a/libfreerdp/gdi/test/TestGdiCreate.c b/libfreerdp/gdi/test/TestGdiCreate.c index 6dd55dfd2..584d68362 100644 --- a/libfreerdp/gdi/test/TestGdiCreate.c +++ b/libfreerdp/gdi/test/TestGdiCreate.c @@ -48,7 +48,11 @@ int test_gdi_CreateCompatibleDC(void) hdc->bitsPerPixel = 16; hdc->drawMode = GDI_R2_XORPEN; - chdc = gdi_CreateCompatibleDC(hdc); + if (!(chdc = gdi_CreateCompatibleDC(hdc))) + { + printf("gdi_CreateCompatibleDC failed\n"); + return -1; + } if (chdc->bytesPerPixel != hdc->bytesPerPixel) return -1; @@ -73,8 +77,17 @@ int test_gdi_CreateBitmap(void) bpp = 32; width = 32; height = 16; - data = (BYTE*) malloc(width * height * 4); - hBitmap = gdi_CreateBitmap(width, height, bpp, data); + if (!(data = (BYTE*) _aligned_malloc(width * height * 4, 16))) + { + printf("failed to allocate aligned bitmap data memory\n"); + return -1; + } + + if (!(hBitmap = gdi_CreateBitmap(width, height, bpp, data))) + { + printf("gdi_CreateBitmap failed\n"); + return -1; + } if (hBitmap->objectType != GDIOBJECT_BITMAP) return -1; @@ -143,6 +156,12 @@ int test_gdi_CreatePen(void) { HGDI_PEN hPen = gdi_CreatePen(GDI_PS_SOLID, 8, 0xAABBCCDD); + if (!hPen) + { + printf("gdi_CreatePen failed\n"); + return -1; + } + if (hPen->style != GDI_PS_SOLID) return -1; @@ -231,14 +250,17 @@ int test_gdi_CreateRectRgn(void) int test_gdi_CreateRect(void) { + HGDI_RECT hRect; int x1 = 32; int y1 = 64; int x2 = 128; int y2 = 256; - HGDI_RECT hRect = gdi_CreateRect(x1, y1, x2, y2); - if (!hRect) + if (!(hRect = gdi_CreateRect(x1, y1, x2, y2))) + { + printf("gdi_CreateRect failed\n"); return -1; + } if (hRect->objectType != GDIOBJECT_RECT) return -1; @@ -356,7 +378,12 @@ int test_gdi_MoveToEx(void) return -1; } - hPen = gdi_CreatePen(GDI_PS_SOLID, 8, 0xAABBCCDD); + if (!(hPen = gdi_CreatePen(GDI_PS_SOLID, 8, 0xAABBCCDD))) + { + printf("gdi_CreatePen failed\n"); + return -1; + } + gdi_SelectObject(hdc, (HGDIOBJECT) hPen); gdi_MoveToEx(hdc, 128, 256, NULL); diff --git a/libfreerdp/gdi/test/TestGdiEllipse.c b/libfreerdp/gdi/test/TestGdiEllipse.c index fcebb9feb..7d3b107e6 100644 --- a/libfreerdp/gdi/test/TestGdiEllipse.c +++ b/libfreerdp/gdi/test/TestGdiEllipse.c @@ -101,7 +101,12 @@ int TestGdiEllipse(int argc, char* argv[]) hdc->bytesPerPixel = bytesPerPixel; gdi_SetNullClipRgn(hdc); - pen = gdi_CreatePen(1, 1, 0); + if (!(pen = gdi_CreatePen(1, 1, 0))) + { + printf("gdi_CreatePen failed\n"); + return -1; + } + gdi_SelectObject(hdc, (HGDIOBJECT) pen); hBmp = gdi_CreateCompatibleBitmap(hdc, 16, 16); @@ -124,7 +129,11 @@ int TestGdiEllipse(int argc, char* argv[]) hBmp_Ellipse_3 = gdi_CreateBitmap(16, 16, bitsPerPixel, data); /* Test Case 1: (0,0) -> (16, 16) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_Ellipse(hdc, 0, 0, 16, 16); return 0; diff --git a/libfreerdp/gdi/test/TestGdiLine.c b/libfreerdp/gdi/test/TestGdiLine.c index 77ca2fe4a..1ae64a030 100644 --- a/libfreerdp/gdi/test/TestGdiLine.c +++ b/libfreerdp/gdi/test/TestGdiLine.c @@ -648,7 +648,12 @@ int TestGdiLine(int argc, char* argv[]) hdc->bytesPerPixel = bytesPerPixel; gdi_SetNullClipRgn(hdc); - pen = gdi_CreatePen(1, 1, 0); + if (!(pen = gdi_CreatePen(1, 1, 0))) + { + printf("gdi_CreatePen failed\n"); + return -1; + } + gdi_SelectObject(hdc, (HGDIOBJECT) pen); hBmp = gdi_CreateCompatibleBitmap(hdc, 16, 16); @@ -746,7 +751,11 @@ int TestGdiLine(int argc, char* argv[]) hBmp_LineTo_R2_WHITE = gdi_CreateBitmap(16, 16, bitsPerPixel, data); /* Test Case 1: (0,0) -> (15, 15) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 0, 0, NULL); gdi_LineTo(hdc, 15, 15); @@ -754,7 +763,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 2: (15,15) -> (0,0) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 15, 15, NULL); gdi_LineTo(hdc, 0, 0); @@ -762,7 +775,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 3: (15,0) -> (0,15) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 15, 0, NULL); gdi_LineTo(hdc, 0, 15); @@ -770,7 +787,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 4: (0,15) -> (15,0) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 0, 15, NULL); gdi_LineTo(hdc, 15, 0); @@ -778,7 +799,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 5: (0,8) -> (15,8) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 0, 8, NULL); gdi_LineTo(hdc, 15, 8); @@ -786,7 +811,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 6: (15,8) -> (0,8) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 15, 8, NULL); gdi_LineTo(hdc, 0, 8); @@ -794,7 +823,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 7: (8,0) -> (8,15) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 8, 0, NULL); gdi_LineTo(hdc, 8, 15); @@ -802,7 +835,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 8: (8,15) -> (8,0) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 8, 15, NULL); gdi_LineTo(hdc, 8, 0); @@ -810,7 +847,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 9: (4,4) -> (12,12) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 4, 4, NULL); gdi_LineTo(hdc, 12, 12); @@ -818,7 +859,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 10: (12,12) -> (4,4) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_MoveToEx(hdc, 12, 12, NULL); gdi_LineTo(hdc, 4, 4); @@ -826,7 +871,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 11: (0,0) -> (+10,+10) */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_LineTo(hdc, 16 + 10, 16 + 10); @@ -835,7 +884,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 12: (0,0) -> (16,16), R2_BLACK */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_BLACK); @@ -845,7 +898,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 13: (0,0) -> (16,16), R2_NOTMERGEPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_NOTMERGEPEN); @@ -855,7 +912,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 14: (0,0) -> (16,16), R2_MASKNOTPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_MASKNOTPEN); @@ -865,7 +926,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 15: (0,0) -> (16,16), R2_NOTCOPYPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_NOTCOPYPEN); @@ -875,7 +940,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 16: (0,0) -> (16,16), R2_MASKPENNOT */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_MASKPENNOT); @@ -885,7 +954,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 17: (0,0) -> (16,16), R2_NOT */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_NOT); @@ -895,7 +968,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 18: (0,0) -> (16,16), R2_XORPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_XORPEN); @@ -905,7 +982,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 19: (0,0) -> (16,16), R2_NOTMASKPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_NOTMASKPEN); @@ -915,7 +996,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 20: (0,0) -> (16,16), R2_MASKPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_MASKPEN); @@ -925,7 +1010,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 21: (0,0) -> (16,16), R2_NOTXORPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_NOTXORPEN); @@ -935,7 +1024,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 22: (0,0) -> (16,16), R2_NOP */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_NOP); @@ -945,7 +1038,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 23: (0,0) -> (16,16), R2_MERGENOTPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_MERGENOTPEN); @@ -955,7 +1052,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 24: (0,0) -> (16,16), R2_COPYPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_COPYPEN); @@ -965,7 +1066,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 25: (0,0) -> (16,16), R2_MERGEPENNOT */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_MERGEPENNOT); @@ -975,7 +1080,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 26: (0,0) -> (16,16), R2_MERGEPEN */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_MERGEPEN); @@ -985,7 +1094,11 @@ int TestGdiLine(int argc, char* argv[]) return -1; /* Test Case 27: (0,0) -> (16,16), R2_WHITE */ - gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS); + if (!gdi_BitBlt(hdc, 0, 0, 16, 16, hdc, 0, 0, GDI_WHITENESS)) + { + printf("gdi_BitBlt failed (line #%u)\n", __LINE__); + return -1; + } gdi_SetClipRgn(hdc, 0, 0, 16, 16); gdi_MoveToEx(hdc, 0, 0, NULL); gdi_SetROP2(hdc, GDI_R2_WHITE); diff --git a/libfreerdp/gdi/test/TestGdiRect.c b/libfreerdp/gdi/test/TestGdiRect.c index e5f7dfab4..e653e8608 100644 --- a/libfreerdp/gdi/test/TestGdiRect.c +++ b/libfreerdp/gdi/test/TestGdiRect.c @@ -24,33 +24,37 @@ int test_gdi_PtInRect(void) int right = 60; int bottom = 80; - hRect = gdi_CreateRect(left, top, right, bottom); + if (!(hRect = gdi_CreateRect(left, top, right, bottom))) + { + printf("gdi_CreateRect failed\n"); + return -1; + } - if (gdi_PtInRect(hRect, 0, 0) != 0) + if (gdi_PtInRect(hRect, 0, 0)) return -1; - if (gdi_PtInRect(hRect, 500, 500) != 0) + if (gdi_PtInRect(hRect, 500, 500)) return -1; - if (gdi_PtInRect(hRect, 40, 100) != 0) + if (gdi_PtInRect(hRect, 40, 100)) return -1; - if (gdi_PtInRect(hRect, 10, 40) != 0) + if (gdi_PtInRect(hRect, 10, 40)) return -1; - if (gdi_PtInRect(hRect, 30, 50) != 1) + if (!gdi_PtInRect(hRect, 30, 50)) return -1; - if (gdi_PtInRect(hRect, left, top) != 1) + if (!gdi_PtInRect(hRect, left, top)) return -1; - if (gdi_PtInRect(hRect, right, bottom) != 1) + if (!gdi_PtInRect(hRect, right, bottom)) return -1; - if (gdi_PtInRect(hRect, right, 60) != 1) + if (!gdi_PtInRect(hRect, right, 60)) return -1; - if (gdi_PtInRect(hRect, 40, bottom) != 1) + if (!gdi_PtInRect(hRect, 40, bottom)) return -1; return 0; @@ -86,7 +90,11 @@ int test_gdi_FillRect(void) hdc->bytesPerPixel = 4; hdc->bitsPerPixel = 32; - hRect = gdi_CreateRect(left, top, right, bottom); + if (!(hRect = gdi_CreateRect(left, top, right, bottom))) + { + printf("gdi_CreateRect failed\n"); + return -1; + } hBitmap = gdi_CreateCompatibleBitmap(hdc, width, height); ZeroMemory(hBitmap->data, width * height * hdc->bytesPerPixel); diff --git a/libfreerdp/locale/keyboard.c b/libfreerdp/locale/keyboard.c index 30c14a49a..708737f51 100644 --- a/libfreerdp/locale/keyboard.c +++ b/libfreerdp/locale/keyboard.c @@ -98,7 +98,9 @@ int freerdp_keyboard_init_x11_evdev(DWORD* keyboardLayoutId, DWORD x11_keycode_t DWORD freerdp_keyboard_init(DWORD keyboardLayoutId) { DWORD keycode; +#if defined(__APPLE__) || defined(WITH_X11) int status = -1; +#endif #ifdef __APPLE__ if (status < 0) diff --git a/libfreerdp/locale/keyboard_layout.c b/libfreerdp/locale/keyboard_layout.c index 269b2197d..91bec80f8 100644 --- a/libfreerdp/locale/keyboard_layout.c +++ b/libfreerdp/locale/keyboard_layout.c @@ -180,6 +180,7 @@ static const RDP_KEYBOARD_LAYOUT_VARIANT RDP_KEYBOARD_LAYOUT_VARIANT_TABLE[] = { KBD_GREEK_LATIN, 0x0019, "Greek Latin" }, { KBD_US_ENGLISH_TABLE_FOR_IBM_ARABIC_238_L, 0x000B, "US English Table for IBM Arabic 238_L" }, { KBD_GREEK_POLYTONIC, 0x001F, "Greek Polytonic" }, + { KBD_FRENCH_BEPO, 0x00C0, "French Bépo" }, { KBD_GERMAN_NEO, 0x00C0, "German Neo" } }; @@ -247,6 +248,14 @@ RDP_KEYBOARD_LAYOUT* freerdp_keyboard_get_layouts(DWORD types) { layouts[num].code = RDP_KEYBOARD_LAYOUT_TABLE[i].code; layouts[num].name = _strdup(RDP_KEYBOARD_LAYOUT_TABLE[i].name); + if (!layouts[num].name) + { + for (--i; i >=0; --i) + free(layouts[num].name); + + free(layouts); + return NULL; + } } } if ((types & RDP_KEYBOARD_LAYOUT_TYPE_VARIANT) != 0) @@ -264,6 +273,14 @@ RDP_KEYBOARD_LAYOUT* freerdp_keyboard_get_layouts(DWORD types) { layouts[num].code = RDP_KEYBOARD_LAYOUT_VARIANT_TABLE[i].code; layouts[num].name = _strdup(RDP_KEYBOARD_LAYOUT_VARIANT_TABLE[i].name); + if (!layouts[num].name) + { + for (--i; i >=0; --i) + free(layouts[num].name); + + free(layouts); + return NULL; + } } } if ((types & RDP_KEYBOARD_LAYOUT_TYPE_IME) != 0) @@ -281,6 +298,14 @@ RDP_KEYBOARD_LAYOUT* freerdp_keyboard_get_layouts(DWORD types) { layouts[num].code = RDP_KEYBOARD_IME_TABLE[i].code; layouts[num].name = _strdup(RDP_KEYBOARD_IME_TABLE[i].name); + if (!layouts[num].name) + { + for (--i; i >=0; --i) + free(layouts[num].name); + + free(layouts); + return NULL; + } } } diff --git a/libfreerdp/locale/keyboard_sun.c b/libfreerdp/locale/keyboard_sun.c index 5f8b62e17..111abf7bd 100644 --- a/libfreerdp/locale/keyboard_sun.c +++ b/libfreerdp/locale/keyboard_sun.c @@ -227,7 +227,7 @@ int freerdp_get_solaris_keyboard_layout_and_type(int* type, int* layout) kbd = popen("kbd -t -l", "r"); - if (kbd < 0) + if (!kbd) return -1; while (fgets(buffer, sizeof(buffer), kbd) != NULL) diff --git a/libfreerdp/locale/keyboard_x11.c b/libfreerdp/locale/keyboard_x11.c index 0187de9bf..e9ca41f2a 100644 --- a/libfreerdp/locale/keyboard_x11.c +++ b/libfreerdp/locale/keyboard_x11.c @@ -48,7 +48,8 @@ int freerdp_detect_keyboard_layout_from_xkb(DWORD* keyboardLayoutId) /* We start by looking for _XKB_RULES_NAMES_BACKUP which appears to be used by libxklavier */ - xprop = popen("xprop -root _XKB_RULES_NAMES_BACKUP", "r"); + if (!(xprop = popen("xprop -root _XKB_RULES_NAMES_BACKUP", "r"))) + return 0; /* Sample output for "Canadian Multilingual Standard" * @@ -100,7 +101,8 @@ int freerdp_detect_keyboard_layout_from_xkb(DWORD* keyboardLayoutId) /* Check _XKB_RULES_NAMES if _XKB_RULES_NAMES_BACKUP fails */ - xprop = popen("xprop -root _XKB_RULES_NAMES", "r"); + if (!(xprop = popen("xprop -root _XKB_RULES_NAMES", "r"))) + return 0; while (fgets(buffer, sizeof(buffer), xprop) != NULL) { @@ -157,6 +159,9 @@ char* freerdp_detect_keymap_from_xkb() /* this tells us about the current XKB configuration, if XKB is available */ setxkbmap = popen("setxkbmap -print", "r"); + if (!setxkbmap) + return NULL; + while (fgets(buffer, sizeof(buffer), setxkbmap) != NULL) { /* the line with xkb_keycodes is what interests us */ @@ -182,8 +187,10 @@ char* freerdp_detect_keymap_from_xkb() length = (end - beg); keymap = (char*) malloc(length + 1); - strncpy(keymap, beg, length); - keymap[length] = '\0'; + if (keymap) { + strncpy(keymap, beg, length); + keymap[length] = '\0'; + } break; } diff --git a/libfreerdp/locale/timezone.c b/libfreerdp/locale/timezone.c index 78a8cf121..573504956 100644 --- a/libfreerdp/locale/timezone.c +++ b/libfreerdp/locale/timezone.c @@ -1541,7 +1541,18 @@ char* freerdp_get_unix_timezone_identifier() } tzid = (char*) malloc(length + 1); - fread(tzid, length, 1, fp); + if (!tzid) + { + fclose(fp); + return NULL; + } + + if (fread(tzid, length, 1, fp) != 1) + { + free(tzid); + fclose(fp); + return NULL; + } tzid[length] = '\0'; if (tzid[length - 1] == '\n') @@ -1579,6 +1590,9 @@ char* freerdp_get_unix_timezone_identifier() } tzid = (char*) malloc(len - pos + 1); + if (!tzid) + return NULL; + strncpy(tzid, buf + pos + 1, len - pos); return tzid; @@ -1597,6 +1611,8 @@ BOOL freerdp_match_unix_timezone_identifier_with_list(const char* tzid, const ch char* list_copy; list_copy = _strdup(list); + if (!list_copy) + return FALSE; p = strtok(list_copy, " "); @@ -1636,10 +1652,13 @@ TIME_ZONE_ENTRY* freerdp_detect_windows_time_zone(UINT32 bias) if (freerdp_match_unix_timezone_identifier_with_list(tzid, WindowsTimeZoneIdTable[j].tzid)) { + free(tzid); + timezone = (TIME_ZONE_ENTRY*) malloc(sizeof(TIME_ZONE_ENTRY)); + if (!timezone) + return NULL; memcpy((void*) timezone, (void*) &TimeZoneTable[i], sizeof(TIME_ZONE_ENTRY)); timezone->Bias = bias; - free(tzid); return timezone; } } diff --git a/libfreerdp/locale/xkb_layout_ids.c b/libfreerdp/locale/xkb_layout_ids.c index 7481d1324..c1a43cdb1 100644 --- a/libfreerdp/locale/xkb_layout_ids.c +++ b/libfreerdp/locale/xkb_layout_ids.c @@ -329,7 +329,7 @@ static const XKB_VARIANT fr_variants[] = { "latin9", 0 }, /* (Legacy) Alternative */ { "latin9_nodeadkeys", 0 }, /* (Legacy) Alternative, eliminate dead keys */ { "latin9_sundeadkeys", 0 }, /* (Legacy) Alternative, Sun dead keys */ - { "bepo", 0 }, /* Bepo, ergonomic, Dvorak way */ + { "bepo", KBD_FRENCH_BEPO }, /* Bepo, ergonomic, Dvorak way */ { "bepo_latin9", 0 }, /* Bepo, ergonomic, Dvorak way, latin-9 only */ { "dvorak", 0 }, /* Dvorak */ { "mac", 0 }, /* Macintosh */ diff --git a/libfreerdp/utils/msusb.c b/libfreerdp/utils/msusb.c index 4d75d74c4..870c2e20c 100644 --- a/libfreerdp/utils/msusb.c +++ b/libfreerdp/utils/msusb.c @@ -36,9 +36,7 @@ static MSUSB_PIPE_DESCRIPTOR* msusb_mspipe_new() { - MSUSB_PIPE_DESCRIPTOR* MsPipe = (MSUSB_PIPE_DESCRIPTOR*) malloc(sizeof(MSUSB_PIPE_DESCRIPTOR)); - memset(MsPipe, 0, sizeof(MSUSB_PIPE_DESCRIPTOR)); - return MsPipe; + return (MSUSB_PIPE_DESCRIPTOR*) calloc(1, sizeof(MSUSB_PIPE_DESCRIPTOR)); } static void msusb_mspipes_free(MSUSB_PIPE_DESCRIPTOR** MsPipes, UINT32 NumberOfPipes) @@ -69,11 +67,15 @@ static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(BYTE* data, UINT32 data_size, int pnum, move = 0; MSUSB_PIPE_DESCRIPTOR** MsPipes; - MsPipes = (MSUSB_PIPE_DESCRIPTOR**) malloc(NumberOfPipes * sizeof(MSUSB_PIPE_DESCRIPTOR*)); + MsPipes = (MSUSB_PIPE_DESCRIPTOR**) calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*)); + if (!MsPipes) + return NULL; for (pnum = 0; pnum < NumberOfPipes; pnum++) { - MSUSB_PIPE_DESCRIPTOR * MsPipe = msusb_mspipe_new(); + MSUSB_PIPE_DESCRIPTOR *MsPipe = msusb_mspipe_new(); + if (!MsPipe) + goto out_error; data_read_UINT16(data + move, MsPipe->MaximumPacketSize); data_read_UINT32(data + move + 4, MsPipe->MaximumTransferSize); @@ -92,13 +94,19 @@ static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(BYTE* data, UINT32 data_size, *offset += move; return MsPipes; + +out_error: + for (pnum = 0; pnum < NumberOfPipes; pnum++) + { + free(MsPipes[pnum]); + } + free(MsPipes); + return NULL; } static MSUSB_INTERFACE_DESCRIPTOR* msusb_msinterface_new() { - MSUSB_INTERFACE_DESCRIPTOR* MsInterface = (MSUSB_INTERFACE_DESCRIPTOR*) malloc(sizeof(MSUSB_INTERFACE_DESCRIPTOR)); - memset(MsInterface, 0, sizeof(MSUSB_INTERFACE_DESCRIPTOR)); - return MsInterface; + return (MSUSB_INTERFACE_DESCRIPTOR*) calloc(1, sizeof(MSUSB_INTERFACE_DESCRIPTOR)); } static void msusb_msinterface_free(MSUSB_INTERFACE_DESCRIPTOR* MsInterface) @@ -137,6 +145,8 @@ MSUSB_INTERFACE_DESCRIPTOR* msusb_msinterface_read(BYTE* data, UINT32 data_size, MSUSB_INTERFACE_DESCRIPTOR* MsInterface; MsInterface = msusb_msinterface_new(); + if (!MsInterface) + return NULL; data_read_UINT16(data, MsInterface->Length); data_read_UINT16(data + 2, MsInterface->NumberOfPipesExpected); @@ -156,9 +166,15 @@ MSUSB_INTERFACE_DESCRIPTOR* msusb_msinterface_read(BYTE* data, UINT32 data_size, { MsInterface->MsPipes = msusb_mspipes_read(data+(*offset), data_size-(*offset), MsInterface->NumberOfPipes, offset); + if (!MsInterface->MsPipes) + goto out_error; } return MsInterface; + +out_error: + msusb_msinterface_free(MsInterface); + return NULL; } int msusb_msinterface_write(MSUSB_INTERFACE_DESCRIPTOR* MsInterface, BYTE* data, int* offset) @@ -219,7 +235,9 @@ static MSUSB_INTERFACE_DESCRIPTOR** msusb_msinterface_read_list(BYTE * data, UIN int inum, offset = 0; MSUSB_INTERFACE_DESCRIPTOR** MsInterfaces; - MsInterfaces = (MSUSB_INTERFACE_DESCRIPTOR**) malloc(NumInterfaces * sizeof(MSUSB_INTERFACE_DESCRIPTOR*)); + MsInterfaces = (MSUSB_INTERFACE_DESCRIPTOR**) calloc(NumInterfaces, sizeof(MSUSB_INTERFACE_DESCRIPTOR*)); + if (!MsInterfaces) + return NULL; for (inum = 0; inum < NumInterfaces; inum++) { @@ -257,11 +275,7 @@ int msusb_msconfig_write(MSUSB_CONFIG_DESCRIPTOR* MsConfg, BYTE* data, int* offs MSUSB_CONFIG_DESCRIPTOR* msusb_msconfig_new() { - MSUSB_CONFIG_DESCRIPTOR* MsConfig = NULL; - MsConfig = (MSUSB_CONFIG_DESCRIPTOR*) malloc(sizeof(MSUSB_CONFIG_DESCRIPTOR)); - memset(MsConfig, 0, sizeof(MSUSB_CONFIG_DESCRIPTOR)); - - return MsConfig; + return (MSUSB_CONFIG_DESCRIPTOR*) calloc(1, sizeof(MSUSB_CONFIG_DESCRIPTOR)); } void msusb_msconfig_free(MSUSB_CONFIG_DESCRIPTOR* MsConfig) diff --git a/libfreerdp/utils/pcap.c b/libfreerdp/utils/pcap.c index 21e906e6c..e6224ce45 100644 --- a/libfreerdp/utils/pcap.c +++ b/libfreerdp/utils/pcap.c @@ -52,49 +52,61 @@ int gettimeofday(struct timeval* tp, void* tz) #define PCAP_MAGIC 0xA1B2C3D4 -void pcap_read_header(rdpPcap* pcap, pcap_header* header) +static BOOL pcap_read_header(rdpPcap* pcap, pcap_header* header) { - fread((void*) header, sizeof(pcap_header), 1, pcap->fp); + return fread((void*) header, sizeof(pcap_header), 1, pcap->fp) == 1; } -void pcap_write_header(rdpPcap* pcap, pcap_header* header) +static BOOL pcap_write_header(rdpPcap* pcap, pcap_header* header) { - fwrite((void*) header, sizeof(pcap_header), 1, pcap->fp); + return fwrite((void*) header, sizeof(pcap_header), 1, pcap->fp) == 1; } -void pcap_read_record_header(rdpPcap* pcap, pcap_record_header* record) +static BOOL pcap_read_record_header(rdpPcap* pcap, pcap_record_header* record) { - fread((void*) record, sizeof(pcap_record_header), 1, pcap->fp); + return fread((void*) record, sizeof(pcap_record_header), 1, pcap->fp) == 1; } -void pcap_write_record_header(rdpPcap* pcap, pcap_record_header* record) +static BOOL pcap_write_record_header(rdpPcap* pcap, pcap_record_header* record) { - fwrite((void*) record, sizeof(pcap_record_header), 1, pcap->fp); + return fwrite((void*) record, sizeof(pcap_record_header), 1, pcap->fp) == 1; } -void pcap_read_record(rdpPcap* pcap, pcap_record* record) +static BOOL pcap_read_record(rdpPcap* pcap, pcap_record* record) { - pcap_read_record_header(pcap, &record->header); + if (!pcap_read_record_header(pcap, &record->header)) + return FALSE; + record->length = record->header.incl_len; record->data = malloc(record->length); - fread(record->data, record->length, 1, pcap->fp); + if (!record->data) + return FALSE; + + if (fread(record->data, record->length, 1, pcap->fp) != 1) + { + free(record->data); + record->data = NULL; + return FALSE; + } + return TRUE; } -void pcap_write_record(rdpPcap* pcap, pcap_record* record) +static BOOL pcap_write_record(rdpPcap* pcap, pcap_record* record) { - pcap_write_record_header(pcap, &record->header); - fwrite(record->data, record->length, 1, pcap->fp); + return pcap_write_record_header(pcap, &record->header) && + (fwrite(record->data, record->length, 1, pcap->fp) == 1); } -void pcap_add_record(rdpPcap* pcap, void* data, UINT32 length) +BOOL pcap_add_record(rdpPcap* pcap, void* data, UINT32 length) { pcap_record* record; struct timeval tp; if (pcap->tail == NULL) { - pcap->tail = (pcap_record*) malloc(sizeof(pcap_record)); - ZeroMemory(pcap->tail, sizeof(pcap_record)); + pcap->tail = (pcap_record*) calloc(1, sizeof(pcap_record)); + if (!pcap->tail) + return FALSE; pcap->head = pcap->tail; pcap->record = pcap->head; @@ -102,8 +114,9 @@ void pcap_add_record(rdpPcap* pcap, void* data, UINT32 length) } else { - record = (pcap_record*) malloc(sizeof(pcap_record)); - ZeroMemory(record, sizeof(pcap_record)); + record = (pcap_record*) calloc(1, sizeof(pcap_record)); + if (!record) + return FALSE; pcap->tail->next = record; pcap->tail = record; @@ -120,6 +133,7 @@ void pcap_add_record(rdpPcap* pcap, void* data, UINT32 length) gettimeofday(&tp, 0); record->header.ts_sec = tp.tv_sec; record->header.ts_usec = tp.tv_usec; + return TRUE; } BOOL pcap_has_next_record(rdpPcap* pcap) @@ -143,18 +157,13 @@ BOOL pcap_get_next_record_header(rdpPcap* pcap, pcap_record* record) BOOL pcap_get_next_record_content(rdpPcap* pcap, pcap_record* record) { - fread(record->data, record->length, 1, pcap->fp); - return TRUE; + return fread(record->data, record->length, 1, pcap->fp) == 1; } BOOL pcap_get_next_record(rdpPcap* pcap, pcap_record* record) { - if (pcap_has_next_record(pcap) != TRUE) - return FALSE; - - pcap_read_record(pcap, record); - - return TRUE; + return pcap_has_next_record(pcap) && + pcap_read_record(pcap, record); } rdpPcap* pcap_open(char* name, BOOL write) @@ -169,38 +178,43 @@ rdpPcap* pcap_open(char* name, BOOL write) return NULL; } - pcap = (rdpPcap*) malloc(sizeof(rdpPcap)); + pcap = (rdpPcap*) calloc(1, sizeof(rdpPcap)); + if (!pcap) + goto fail_close; - if (pcap != NULL) + pcap->name = name; + pcap->write = write; + pcap->record_count = 0; + pcap->fp = pcap_fp; + + if (write) { - ZeroMemory(pcap, sizeof(rdpPcap)); - - pcap->name = name; - pcap->write = write; - pcap->record_count = 0; - pcap->fp = pcap_fp; - - if (write) - { - pcap->header.magic_number = 0xA1B2C3D4; - pcap->header.version_major = 2; - pcap->header.version_minor = 4; - pcap->header.thiszone = 0; - pcap->header.sigfigs = 0; - pcap->header.snaplen = 0xFFFFFFFF; - pcap->header.network = 0; - pcap_write_header(pcap, &pcap->header); - } - else - { - fseek(pcap->fp, 0, SEEK_END); - pcap->file_size = (int) ftell(pcap->fp); - fseek(pcap->fp, 0, SEEK_SET); - pcap_read_header(pcap, &pcap->header); - } + pcap->header.magic_number = 0xA1B2C3D4; + pcap->header.version_major = 2; + pcap->header.version_minor = 4; + pcap->header.thiszone = 0; + pcap->header.sigfigs = 0; + pcap->header.snaplen = 0xFFFFFFFF; + pcap->header.network = 0; + if (!pcap_write_header(pcap, &pcap->header)) + goto fail; + } + else + { + fseek(pcap->fp, 0, SEEK_END); + pcap->file_size = (int) ftell(pcap->fp); + fseek(pcap->fp, 0, SEEK_SET); + if (!pcap_read_header(pcap, &pcap->header)) + goto fail; } return pcap; + +fail: + free(pcap); +fail_close: + fclose(pcap_fp); + return NULL; } void pcap_flush(rdpPcap* pcap) diff --git a/libfreerdp/utils/profiler.c b/libfreerdp/utils/profiler.c index 11737a210..7ceb67125 100644 --- a/libfreerdp/utils/profiler.c +++ b/libfreerdp/utils/profiler.c @@ -34,9 +34,16 @@ PROFILER* profiler_create(char* name) PROFILER* profiler; profiler = (PROFILER*) malloc(sizeof(PROFILER)); + if (!profiler) + return NULL; profiler->name = name; profiler->stopwatch = stopwatch_create(); + if (!profiler->stopwatch) + { + free(profiler); + return NULL; + } return profiler; } diff --git a/libfreerdp/utils/stopwatch.c b/libfreerdp/utils/stopwatch.c index a45ee9a73..4026dd812 100644 --- a/libfreerdp/utils/stopwatch.c +++ b/libfreerdp/utils/stopwatch.c @@ -55,6 +55,8 @@ STOPWATCH* stopwatch_create() #endif sw = (STOPWATCH*) malloc(sizeof(STOPWATCH)); + if (!sw) + return NULL; stopwatch_reset(sw); return sw; diff --git a/rdtk/librdtk/rdtk_font.c b/rdtk/librdtk/rdtk_font.c index 3f8014e52..2d81ccdda 100644 --- a/rdtk/librdtk/rdtk_font.c +++ b/rdtk/librdtk/rdtk_font.c @@ -404,7 +404,9 @@ int rdtk_font_parse_descriptor_buffer(rdtkFont* font, BYTE* buffer, int size) } font->glyphCount = count; - font->glyphs = (rdtkGlyph*) calloc(font->glyphCount, sizeof(rdtkGlyph)); + font->glyphs = NULL; + if (count > 0) + font->glyphs = (rdtkGlyph*) calloc(font->glyphCount, sizeof(rdtkGlyph)); if (!font->glyphs) return -1; diff --git a/rdtk/sample/rdtk_x11.c b/rdtk/sample/rdtk_x11.c index 2e115ee94..c632e5529 100644 --- a/rdtk/sample/rdtk_x11.c +++ b/rdtk/sample/rdtk_x11.c @@ -95,9 +95,13 @@ int main(int argc, char** argv) XFree(pfs); engine = rdtk_engine_new(); + if (!engine) + return 1; scanline = width * 4; buffer = (BYTE*) malloc(scanline * height); + if (!buffer) + return 1; surface = rdtk_surface_new(engine, buffer, width, height, scanline); diff --git a/scripts/OpenSSL-DownloadAndBuild.command b/scripts/OpenSSL-DownloadAndBuild.command index eeaaca75b..96a5e3132 100755 --- a/scripts/OpenSSL-DownloadAndBuild.command +++ b/scripts/OpenSSL-DownloadAndBuild.command @@ -1,44 +1,87 @@ #!/bin/bash # -# Copyright 2013 Thincast Technologies GmbH +# Copyright 2015 Thincast Technologies GmbH # # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. # If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. # -# This script will download and build openssl for iOS (armv7, armv7s) and simulator (i386) +# This script will download and build openssl for iOS and simulator - see ARCHS for architectures built -# Settings and definitions -USER_OS_SDK="" -USER_SIM_SDK="" +## Settings +# openssl version to use +OPENSSLVERSION="1.0.2a" +MD5SUM="a06c547dac9044161a477211049f60ef" +# SDK version to use - if not set latest version found is used +SDK_VERSION="" -OPENSSLVERSION="1.0.0e" -MD5SUM="7040b89c4c58c7a1016c0dfa6e821c86" -OPENSSLPATCH="OpenSSL-iFreeRDP.diff" +# Minimum SDK version the application supports +MIN_SDK_VERSION="" + + +## Defaults INSTALLDIR="external" +# Architectures to build +ARCHS="i386 x86_64 armv7 armv7s arm64" + +# Use default SDK version if not set +if [ -z ${SDK_VERSION} ]; then + SDK_VERSION=`xcrun -sdk iphoneos --show-sdk-version` +fi + +CORES=`sysctl hw.ncpu | awk '{print $2}'` MAKEOPTS="-j $CORES" # disable parallell builds since openssl build # fails sometimes MAKEOPTS="" -CORES=`sysctl hw.ncpu | awk '{print $2}'` -SCRIPTDIR=$(dirname `cd ${0%/*} && echo $PWD/${0##*/}`) -OS_SDK="" -SIM_SDK="" -OS_SDK_PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs" -SIM_SDK_PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs" + +DEVELOPER=`xcode-select -print-path` +if [ ! -d "$DEVELOPER" ]; then + echo "xcode path is not set correctly $DEVELOPER does not exist (most likely because of xcode > 4.3)" + echo "run" + echo "sudo xcode-select -switch " + echo "for default installation:" + echo "sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer" + exit 1 +fi # Functions function buildArch(){ ARCH=$1 + if [[ "${ARCH}" == "i386" || "${ARCH}" == "x86_64" ]]; + then + PLATFORM="iPhoneSimulator" + else + sed -ie "s!static volatile sig_atomic_t intr_signal;!static volatile intr_signal;!" "crypto/ui/ui_openssl.c" + PLATFORM="iPhoneOS" + fi + + export CROSS_TOP="${DEVELOPER}/Platforms/${PLATFORM}.platform/Developer" + export CROSS_SDK="${PLATFORM}${SDK_VERSION}.sdk" + export BUILD_TOOLS="${DEVELOPER}" + export CC="${BUILD_TOOLS}/usr/bin/gcc -arch ${ARCH}" + if [ ! -z $MIN_SDK_VERSION ]; then + export CC="$CC -miphoneos-version-min=${MIN_SDK_VERSION}" + fi + echo "Building openssl-${OPENSSLVERSION} for ${PLATFORM} ${SDK_VERSION} ${ARCH} (min SDK set: ${MIN_SDK_VERSION:-"none"})" + LOGFILE="BuildLog.darwin-${ARCH}.txt" - echo "Building architecture ${ARCH}. Please wait ..." - ./Configure darwin-${ARCH}-cc > ${LOGFILE} + echo -n " Please wait ..." + if [[ "$OPENSSLVERSION" =~ 1.0.0. ]]; then + ./Configure BSD-generic32 > "${LOGFILE}" 2>&1 + elif [ "${ARCH}" == "x86_64" ]; then + ./Configure darwin64-x86_64-cc > "${LOGFILE}" 2>&1 + elif [ "${ARCH}" == "i386" ]; then + ./Configure iphoneos-cross no-asm > "${LOGFILE}" 2>&1 + else + ./Configure iphoneos-cross > "${LOGFILE}" 2>&1 + fi + make ${MAKEOPTS} >> ${LOGFILE} 2>&1 - echo "Done. Build log saved in ${LOGFILE}" + echo " Done. Build log saved in ${LOGFILE}" cp libcrypto.a ../../lib/libcrypto_${ARCH}.a cp libssl.a ../../lib/libssl_${ARCH}.a make clean >/dev/null 2>&1 - echo } # main @@ -50,38 +93,6 @@ if [ $# -gt 0 ];then fi fi -echo "Detecting SDKs..." -if [ "x${USER_OS_SDK}" == "x" ];then - OS_SDK=`ls -1 ${OS_SDK_PATH} | sort -n | head -1` - if [ "x${OS_SDK}" == "x" ];then - echo "No iPhoneOS SDK found" - exit 1; - fi -else - OS_SDK=${USER_OS_SDK} - if [ ! -d "${OS_SDK_PATH}/${OS_SDK}" ];then - echo "User specified iPhoneOS SDK not found" - exit 1 - fi -fi -echo "Using iPhoneOS SDK: ${OS_SDK}" - -if [ "x${USER_SIM_SDK}" == "x" ];then - SIM_SDK=`ls -1 ${SIM_SDK_PATH} | sort -n | head -1` - if [ "x${SIM_SDK}" == "x" ];then - echo "No iPhoneSimulator SDK found" - exit 1; - fi -else - SIM_SDK=${USER_SIM_SDK} - if [ ! -d "${SIM_SDK_PATH}/${SIM_SDK}" ];then - echo "User specified iPhoneSimulator SDK not found" - exit 1 - fi -fi -echo "Using iPhoneSimulator SDK: ${SIM_SDK}" -echo - cd $INSTALLDIR if [ ! -d openssl ];then mkdir openssl @@ -113,19 +124,14 @@ if [ ! $? = 0 ]; then fi echo -echo "Applying iFreeRDP patch ..." cd "openssl-$OPENSSLVERSION" -cp ${SCRIPTDIR}/${OPENSSLPATCH} . -sed -ie "s#__ISIMSDK__#${SIM_SDK}#" ${OPENSSLPATCH} -sed -ie "s#__IOSSDK__#${OS_SDK}#" ${OPENSSLPATCH} -patch -p1 < $OPENSSLPATCH - -if [ ! $? = 0 ]; then - echo "Patch failed." - exit 1 -fi -echo +case `pwd` in + *\ * ) + echo "The build path (`pwd`) contains whitepsaces - fix this." + exit 1 + ;; +esac # Cleanup old build artifacts mkdir -p ../../include/openssl @@ -134,13 +140,13 @@ rm -f ../../include/openssl/*.h mkdir -p ../../lib rm -f ../../lib/*.a -echo "Copying header hiles ..." +echo "Copying header files ..." cp include/openssl/*.h ../../include/openssl/ echo -buildArch i386 -buildArch armv7 -buildArch armv7s +for i in ${ARCHS}; do + buildArch $i +done echo "Combining to unversal binary" lipo -create ../../lib/libcrypto_*.a -o ../../lib/libcrypto.a diff --git a/scripts/OpenSSL-iFreeRDP.diff b/scripts/OpenSSL-iFreeRDP.diff deleted file mode 100644 index a282d70a1..000000000 --- a/scripts/OpenSSL-iFreeRDP.diff +++ /dev/null @@ -1,25 +0,0 @@ -diff -rupN openssl-1.0.0e-ori/Configure openssl-1.0.0e/Configure ---- openssl-1.0.0e-ori/Configure 2012-02-06 14:44:42.000000000 +0100 -+++ openssl-1.0.0e/Configure 2012-02-06 14:45:31.000000000 +0100 -@@ -555,6 +555,9 @@ my %table=( - "debug-darwin-i386-cc","cc:-arch i386 -g3 -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:${x86_asm}:macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", - "darwin64-x86_64-cc","cc:-arch x86_64 -O3 -DL_ENDIAN -DMD32_REG_T=int -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", - "debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", -+"darwin-armv7s-cc","/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang:-arch armv7s -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/__IOSSDK__ -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-arch armv4 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", -+"darwin-armv7-cc","/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang:-arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/__IOSSDK__ -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-arch armv4 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", -+"darwin-i386-cc","/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang: -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/__ISIMSDK__ -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common: -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", - - ##### A/UX - "aux3-gcc","gcc:-O2 -DTERMIO::(unknown):AUX:-lbsd:RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:::", -diff -rupN openssl-1.0.0e-ori/crypto/ui/ui_openssl.c openssl-1.0.0e/crypto/ui/ui_openssl.c ---- openssl-1.0.0e-ori/crypto/ui/ui_openssl.c 2012-02-06 14:44:43.000000000 +0100 -+++ openssl-1.0.0e/crypto/ui/ui_openssl.c 2012-02-06 14:46:10.000000000 +0100 -@@ -404,7 +404,7 @@ static int read_till_nl(FILE *in) - return 1; - } - --static volatile sig_atomic_t intr_signal; -+static volatile int intr_signal; - #endif - - static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) diff --git a/server/Mac/mf_event.c b/server/Mac/mf_event.c index 70971e1ab..5379e7391 100644 --- a/server/Mac/mf_event.c +++ b/server/Mac/mf_event.c @@ -167,6 +167,8 @@ void mf_event_region_free(mfEventRegion* event_region) mfEvent* mf_event_new(int type) { mfEvent* event = malloc(sizeof(mfEvent)); + if (!event) + return NULL; event->type = type; return event; } diff --git a/server/Mac/mf_info.c b/server/Mac/mf_info.c index c65fbe7d0..13254445d 100644 --- a/server/Mac/mf_info.c +++ b/server/Mac/mf_info.c @@ -92,18 +92,20 @@ mfInfo* mf_info_init() { mfInfo* mfi; - mfi = (mfInfo*) malloc(sizeof(mfInfo)); - memset(mfi, 0, sizeof(mfInfo)); + mfi = (mfInfo*) calloc(1, sizeof(mfInfo)); if (mfi != NULL) { pthread_mutex_init(&mfi->mutex, NULL); - mfi->peers = (freerdp_peer**) malloc(sizeof(freerdp_peer*) * MF_INFO_MAXPEERS); - memset(mfi->peers, 0, sizeof(freerdp_peer*) * MF_INFO_MAXPEERS); + mfi->peers = (freerdp_peer**) calloc(MF_INFO_MAXPEERS, sizeof(freerdp_peer*)); + if (!mfi->peers) + { + free(mfi); + return NULL; + } mfi->framesPerSecond = MF_INFO_DEFAULT_FPS; - mfi->input_disabled = FALSE; } diff --git a/server/Mac/mf_mountain_lion.c b/server/Mac/mf_mountain_lion.c index 0b8c9125c..ba3fdb125 100644 --- a/server/Mac/mf_mountain_lion.c +++ b/server/Mac/mf_mountain_lion.c @@ -155,6 +155,8 @@ int mf_mlion_screen_updates_init() mf_mlion_display_info(&pixelWidth, &pixelHeight, &scale); localBuf = malloc(pixelWidth * pixelHeight * 4); + if (!localBuf) + return -1; CFDictionaryRef opts; diff --git a/server/Mac/mf_peer.c b/server/Mac/mf_peer.c index 9a837e528..f67e2c4c1 100644 --- a/server/Mac/mf_peer.c +++ b/server/Mac/mf_peer.c @@ -24,6 +24,7 @@ #include #include #include +#include #include @@ -388,6 +389,13 @@ void* mf_peer_main_loop(void* arg) /* Initialize the real server settings here */ client->settings->CertificateFile = _strdup("server.crt"); client->settings->PrivateKeyFile = _strdup("server.key"); + if (!client->settings->CertificateFile || !client->settings->PrivateKeyFile) + { + freerdp_peer_free(client); + return NULL; + } + + client->settings->NlaSecurity = FALSE; client->settings->RemoteFxCodec = TRUE; client->settings->ColorDepth = 32; diff --git a/server/Sample/sfreerdp.c b/server/Sample/sfreerdp.c index 7d5355151..ba2cf9ecc 100644 --- a/server/Sample/sfreerdp.c +++ b/server/Sample/sfreerdp.c @@ -28,6 +28,8 @@ #include #include +#include +#include #include #include @@ -167,7 +169,7 @@ static void test_peer_end_frame(freerdp_peer* client) context->frame_id++; } -static void test_peer_draw_background(freerdp_peer* client) +static BOOL test_peer_draw_background(freerdp_peer* client) { int size; wStream* s; @@ -176,9 +178,10 @@ static void test_peer_draw_background(freerdp_peer* client) rdpUpdate* update = client->update; SURFACE_BITS_COMMAND* cmd = &update->surface_bits_command; testPeerContext* context = (testPeerContext*) client->context; + BOOL ret= FALSE; if (!client->settings->RemoteFxCodec && !client->settings->NSCodec) - return; + return FALSE; s = test_peer_stream_init(context); @@ -189,7 +192,10 @@ static void test_peer_draw_background(freerdp_peer* client) size = rect.width * rect.height * 3; if (!(rgb_data = malloc(size))) - return; + { + WLog_ERR(TAG, "Problem allocating memory"); + return FALSE; + } memset(rgb_data, 0xA0, size); @@ -223,24 +229,32 @@ static void test_peer_draw_background(freerdp_peer* client) update->SurfaceBits(update->context, cmd); test_peer_end_frame(client); + ret = TRUE; out: free(rgb_data); + return ret; } -static void test_peer_load_icon(freerdp_peer* client) +static BOOL test_peer_load_icon(freerdp_peer* client) { testPeerContext* context = (testPeerContext*) client->context; FILE* fp; int i; char line[50]; - BYTE* rgb_data; + BYTE* rgb_data = NULL; int c; if (!client->settings->RemoteFxCodec && !client->settings->NSCodec) - return; + { + WLog_ERR(TAG, "Client doesn't support RemoteFX or NSCodec"); + return FALSE; + } if ((fp = fopen("test_icon.ppm", "r")) == NULL) - return; + { + WLog_ERR(TAG, "Unable to open test icon"); + return FALSE; + } /* P3 */ fgets(line, sizeof(line), fp); @@ -248,26 +262,40 @@ static void test_peer_load_icon(freerdp_peer* client) fgets(line, sizeof(line), fp); /* width height */ fgets(line, sizeof(line), fp); - sscanf(line, "%d %d", &context->icon_width, &context->icon_height); + if (sscanf(line, "%d %d", &context->icon_width, &context->icon_height) < 2) + { + WLog_ERR(TAG, "Problem while extracting width/height from the icon file"); + goto out_fail; + } /* Max */ fgets(line, sizeof(line), fp); - rgb_data = malloc(context->icon_width * context->icon_height * 3); + if (!(rgb_data = malloc(context->icon_width * context->icon_height * 3))) + goto out_fail; for (i = 0; i < context->icon_width * context->icon_height * 3; i++) { - if (fgets(line, sizeof(line), fp)) - { - sscanf(line, "%d", &c); - rgb_data[i] = (BYTE)c; - } + if (!fgets(line, sizeof(line), fp) || (sscanf(line, "%d", &c) != 1)) + goto out_fail; + + rgb_data[i] = (BYTE)c; } - context->icon_data = rgb_data; /* background with same size, which will be used to erase the icon from old position */ - context->bg_data = malloc(context->icon_width * context->icon_height * 3); + if (!(context->bg_data = malloc(context->icon_width * context->icon_height * 3))) + goto out_fail; memset(context->bg_data, 0xA0, context->icon_width * context->icon_height * 3); + context->icon_data = rgb_data; + + fclose(fp); + return TRUE; + +out_fail: + free(rgb_data); + context->bg_data = NULL; + fclose(fp); + return FALSE; } static void test_peer_draw_icon(freerdp_peer* client, int x, int y) @@ -392,7 +420,7 @@ static BOOL test_sleep_tsdiff(UINT32 *old_sec, UINT32 *old_usec, UINT32 new_sec, return TRUE; } -void tf_peer_dump_rfx(freerdp_peer* client) +BOOL tf_peer_dump_rfx(freerdp_peer* client) { wStream* s; UINT32 prev_seconds; @@ -402,20 +430,26 @@ void tf_peer_dump_rfx(freerdp_peer* client) pcap_record record; s = Stream_New(NULL, 512); - update = client->update; - client->update->pcap_rfx = pcap_open(test_pcap_file, FALSE); - pcap_rfx = client->update->pcap_rfx; + if (!s) + return FALSE; - if (pcap_rfx == NULL) - return; + update = client->update; + if (!(pcap_rfx = pcap_open(test_pcap_file, FALSE))) + return FALSE; prev_seconds = prev_useconds = 0; while (pcap_has_next_record(pcap_rfx)) { - pcap_get_next_record_header(pcap_rfx, &record); + BYTE* tmp = NULL; + if (!pcap_get_next_record_header(pcap_rfx, &record)) + break; - Stream_Buffer(s) = realloc(Stream_Buffer(s), record.length); + tmp = realloc(Stream_Buffer(s), record.length); + if (!tmp) + break; + + Stream_Buffer(s) = tmp; record.data = Stream_Buffer(s); Stream_Capacity(s) = record.length; @@ -430,6 +464,11 @@ void tf_peer_dump_rfx(freerdp_peer* client) if (client->CheckFileDescriptor(client) != TRUE) break; } + + + Stream_Free(s, TRUE); + pcap_close(pcap_rfx); + return TRUE; } static void* tf_debug_channel_thread_func(void* arg) @@ -524,7 +563,12 @@ BOOL tf_peer_post_connect(freerdp_peer* client) #endif /* A real server should tag the peer as activated here and start sending updates in main loop. */ - test_peer_load_icon(client); + if (!test_peer_load_icon(client)) + { + WLog_DBG(TAG, "Unable to load icon"); + return FALSE; + } + if (WTSVirtualChannelManagerIsChannelJoined(context->vcm, "rdpdbg")) { @@ -584,12 +628,11 @@ BOOL tf_peer_activate(freerdp_peer* client) if (test_pcap_file != NULL) { client->update->dump_rfx = TRUE; - tf_peer_dump_rfx(client); + if (!tf_peer_dump_rfx(client)) + return FALSE; } else - { test_peer_draw_background(client); - } return TRUE; } @@ -718,6 +761,12 @@ static void* test_peer_mainloop(void* arg) client->settings->CertificateFile = _strdup("server.crt"); client->settings->PrivateKeyFile = _strdup("server.key"); client->settings->RdpKeyFile = _strdup("server.key"); + if (!client->settings->CertificateFile || !client->settings->PrivateKeyFile || !client->settings->RdpKeyFile) + { + WLog_ERR(TAG, "Memory allocation failed (strdup)"); + freerdp_peer_free(client); + return NULL; + } client->settings->RdpSecurity = TRUE; client->settings->TlsSecurity = TRUE; client->settings->NlaSecurity = FALSE; @@ -826,30 +875,61 @@ int main(int argc, char* argv[]) { WSADATA wsaData; freerdp_listener* instance; + char* file; + char name[MAX_PATH]; + int port = 3389, i; + + for (i=1; i 0xFFFF)) + return -1; + } + else if (strncmp(arg, "--", 2)) + test_pcap_file = arg; + } WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); instance = freerdp_listener_new(); + if (!instance) + return -1; instance->PeerAccepted = test_peer_accepted; - if (argc > 1) - test_pcap_file = argv[1]; - - if (argc > 2 && !strcmp(argv[2], "--fast")) - test_dump_rfx_realtime = FALSE; - if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) - return 0; + { + freerdp_listener_free(instance); + return -1; + } /* Open the server socket and start listening. */ + sprintf_s(name, sizeof(name), "tfreerdp-server.%d", port); + file = GetKnownSubPath(KNOWN_PATH_TEMP, name); + if (!file) + { + freerdp_listener_free(instance); + WSACleanup(); + return -1; + } - if (instance->Open(instance, NULL, 3389) && - instance->OpenLocal(instance, "/tmp/tfreerdp-server.0")) + if (instance->Open(instance, NULL, port) && + instance->OpenLocal(instance, file)) { /* Entering the server main loop. In a real server the listener can be run in its own thread. */ test_server_mainloop(instance); } + free (file); freerdp_listener_free(instance); WSACleanup(); diff --git a/server/Windows/wf_info.c b/server/Windows/wf_info.c index 1194b5098..460154bb7 100644 --- a/server/Windows/wf_info.c +++ b/server/Windows/wf_info.c @@ -34,6 +34,9 @@ #include #define TAG SERVER_TAG("windows") +#define SERVER_KEY "Software\\"FREERDP_VENDOR_STRING"\\" \ + FREERDP_PRODUCT_STRING"\\Server" + static wfInfo* wfInfoInstance = NULL; static int _IDcount = 0; @@ -151,7 +154,8 @@ wfInfo* wf_info_init() //Set FPS wfi->framesPerSecond = WF_INFO_DEFAULT_FPS; - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, 0, + KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, _T("FramesPerSecond"), NULL, &dwType, (BYTE*) &dwValue, &dwSize) == ERROR_SUCCESS) @@ -162,7 +166,8 @@ wfInfo* wf_info_init() //Set input toggle wfi->input_disabled = FALSE; - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY, + 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, _T("DisableInput"), NULL, &dwType, (BYTE*) &dwValue, &dwSize) == ERROR_SUCCESS) diff --git a/server/Windows/wf_interface.c b/server/Windows/wf_interface.c index b8ce8183a..216d3cae5 100644 --- a/server/Windows/wf_interface.c +++ b/server/Windows/wf_interface.c @@ -38,6 +38,9 @@ #include "wf_interface.h" +#define SERVER_KEY "Software\\"FREERDP_VENDOR_STRING"\\" \ + FREERDP_PRODUCT_STRING"\\Server" + cbCallback cbEvent; int get_screen_info(int id, _TCHAR* name, int* width, int* height, int* bpp) @@ -130,7 +133,7 @@ DWORD WINAPI wf_server_main_loop(LPVOID lpParam) if (max_fds == 0) break; - + select(max_fds + 1, &rfds_set, NULL, NULL, NULL); if (instance->CheckFileDescriptor(instance) != TRUE) @@ -154,7 +157,8 @@ BOOL wfreerdp_server_start(wfServer* server) server->instance->PeerAccepted = wf_peer_accepted; instance = server->instance; - wf_settings_read_dword(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), _T("DefaultPort"), &server->port); + wf_settings_read_dword(HKEY_LOCAL_MACHINE, SERVER_KEY, + _T("DefaultPort"), &server->port); if (!instance->Open(instance, NULL, (UINT16) server->port)) return FALSE; @@ -289,7 +293,7 @@ FREERDP_API BOOL wfreerdp_server_peer_is_connected(int pId) return FALSE; peer = wfi->peers[pId]; - + if (peer) { return peer->connected; @@ -309,7 +313,7 @@ FREERDP_API BOOL wfreerdp_server_peer_is_activated(int pId) if (!wfi) return FALSE; peer = wfi->peers[pId]; - + if (peer) { return peer->activated; diff --git a/server/Windows/wf_mirage.c b/server/Windows/wf_mirage.c index b3fa6c504..cd048e398 100644 --- a/server/Windows/wf_mirage.c +++ b/server/Windows/wf_mirage.c @@ -54,6 +54,8 @@ BOOL wf_mirror_driver_find_display_device(wfInfo* wfi) { deviceKeyLength = _tcslen(deviceInfo.DeviceKey) - deviceKeyPrefixLength; wfi->deviceKey = (LPTSTR) malloc((deviceKeyLength + 1) * sizeof(TCHAR)); + if (!wfi->deviceKey) + return FALSE; _tcsncpy_s(wfi->deviceKey, deviceKeyLength + 1, &deviceInfo.DeviceKey[deviceKeyPrefixLength], deviceKeyLength); @@ -210,6 +212,8 @@ BOOL wf_mirror_driver_update(wfInfo* wfi, int mode) } deviceMode = (DEVMODE*) malloc(sizeof(DEVMODE) + EXT_DEVMODE_SIZE_MAX); + if (!deviceMode) + return FALSE; deviceMode->dmDriverExtra = 2 * sizeof(DWORD); extHdr = (DWORD*)((BYTE*) &deviceMode + sizeof(DEVMODE)); @@ -278,8 +282,9 @@ BOOL wf_mirror_driver_map_memory(wfInfo* wfi) return FALSE; } - wfi->changeBuffer = malloc(sizeof(GETCHANGESBUF)); - ZeroMemory(wfi->changeBuffer, sizeof(GETCHANGESBUF)); + wfi->changeBuffer = calloc(1, sizeof(GETCHANGESBUF)); + if (!wfi->changeBuffer) + return FALSE; status = ExtEscape(wfi->driverDC, dmf_esc_usm_pipe_map, 0, 0, sizeof(GETCHANGESBUF), (LPSTR) wfi->changeBuffer); @@ -365,4 +370,4 @@ void wf_mirror_driver_deactivate(wfInfo* wfi) wf_mirror_driver_update(wfi, MIRROR_UNLOAD); wfi->mirrorDriverActive = FALSE; } -} \ No newline at end of file +} diff --git a/server/Windows/wf_peer.c b/server/Windows/wf_peer.c index 598080e68..4a4c493c9 100644 --- a/server/Windows/wf_peer.c +++ b/server/Windows/wf_peer.c @@ -37,6 +37,10 @@ #include "wf_rdpsnd.h" #include "wf_peer.h" +#include + +#define SERVER_KEY "Software\\"FREERDP_VENDOR_STRING"\\" \ + FREERDP_PRODUCT_STRING BOOL wf_peer_context_new(freerdp_peer* client, wfPeerContext* context) { @@ -211,13 +215,25 @@ DWORD WINAPI wf_peer_socket_listener(LPVOID lpParam) return 0; } -void wf_peer_read_settings(freerdp_peer* client) +BOOL wf_peer_read_settings(freerdp_peer* client) { - if (!wf_settings_read_string_ascii(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), _T("CertificateFile"), &(client->settings->CertificateFile))) + if (!wf_settings_read_string_ascii(HKEY_LOCAL_MACHINE, SERVER_KEY, + _T("CertificateFile"), &(client->settings->CertificateFile))) + { client->settings->CertificateFile = _strdup("server.crt"); + if (!client->settings->CertificateFile) + return FALSE; + } - if (!wf_settings_read_string_ascii(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), _T("PrivateKeyFile"), &(client->settings->PrivateKeyFile))) + if (!wf_settings_read_string_ascii(HKEY_LOCAL_MACHINE, SERVER_KEY, + _T("PrivateKeyFile"), &(client->settings->PrivateKeyFile))) + { client->settings->PrivateKeyFile = _strdup("server.key"); + if (!client->settings->PrivateKeyFile) + return FALSE; + } + + return TRUE; } DWORD WINAPI wf_peer_main_loop(LPVOID lpParam) @@ -246,7 +262,8 @@ DWORD WINAPI wf_peer_main_loop(LPVOID lpParam) settings->ColorDepth = 32; settings->NSCodec = FALSE; settings->JpegCodec = FALSE; - wf_peer_read_settings(client); + if (!wf_peer_read_settings(client)) + goto fail_peer_init; client->PostConnect = wf_peer_post_connect; client->Activate = wf_peer_activate; diff --git a/server/Windows/wf_settings.c b/server/Windows/wf_settings.c index 84a4de2be..bbbdedd4c 100644 --- a/server/Windows/wf_settings.c +++ b/server/Windows/wf_settings.c @@ -26,7 +26,7 @@ #include "wf_settings.h" -BOOL wf_settings_read_dword(HKEY key, LPTSTR subkey, LPTSTR name, DWORD* value) +BOOL wf_settings_read_dword(HKEY key, LPCSTR subkey, LPTSTR name, DWORD* value) { HKEY hKey; LONG status; @@ -34,7 +34,7 @@ BOOL wf_settings_read_dword(HKEY key, LPTSTR subkey, LPTSTR name, DWORD* value) DWORD dwSize; DWORD dwValue; - status = RegOpenKeyEx(key, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(key, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { @@ -53,7 +53,7 @@ BOOL wf_settings_read_dword(HKEY key, LPTSTR subkey, LPTSTR name, DWORD* value) return FALSE; } -BOOL wf_settings_read_string_ascii(HKEY key, LPTSTR subkey, LPTSTR name, char** value) +BOOL wf_settings_read_string_ascii(HKEY key, LPCSTR subkey, LPTSTR name, char** value) { HKEY hKey; int length; @@ -63,7 +63,7 @@ BOOL wf_settings_read_string_ascii(HKEY key, LPTSTR subkey, LPTSTR name, char** char* strA; TCHAR* strX = NULL; - status = RegOpenKeyEx(key, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(key, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status != ERROR_SUCCESS) return FALSE; @@ -73,6 +73,8 @@ BOOL wf_settings_read_string_ascii(HKEY key, LPTSTR subkey, LPTSTR name, char** if (status == ERROR_SUCCESS) { strX = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); + if (!strX) + return FALSE; status = RegQueryValueEx(hKey, name, NULL, &dwType, (BYTE*) strX, &dwSize); if (status != ERROR_SUCCESS) @@ -99,4 +101,4 @@ BOOL wf_settings_read_string_ascii(HKEY key, LPTSTR subkey, LPTSTR name, char** } return FALSE; -} \ No newline at end of file +} diff --git a/server/Windows/wf_settings.h b/server/Windows/wf_settings.h index c116fa20b..205ab97e0 100644 --- a/server/Windows/wf_settings.h +++ b/server/Windows/wf_settings.h @@ -22,7 +22,7 @@ #include "wf_interface.h" -BOOL wf_settings_read_dword(HKEY key, LPTSTR subkey, LPTSTR name, DWORD* value); -BOOL wf_settings_read_string_ascii(HKEY key, LPTSTR subkey, LPTSTR name, char** value); +BOOL wf_settings_read_dword(HKEY key, LPCSTR subkey, LPTSTR name, DWORD* value); +BOOL wf_settings_read_string_ascii(HKEY key, LPCSTR subkey, LPTSTR name, char** value); #endif /* WF_SETTINGS_H */ diff --git a/server/Windows/wf_wasapi.c b/server/Windows/wf_wasapi.c index 1a484a4f4..99ea764be 100644 --- a/server/Windows/wf_wasapi.c +++ b/server/Windows/wf_wasapi.c @@ -131,8 +131,9 @@ int wf_wasapi_get_device_string(LPWSTR pattern, LPWSTR * deviceStr) WLog_INFO(TAG, "Using sound ouput endpoint: [%s] (%s)", nameVar.pwszVal, pwszID); //WLog_INFO(TAG, "matched %d characters", wcscmp(pattern, nameVar.pwszVal); devStrLen = wcslen(pwszID); - *deviceStr = (LPWSTR) malloc((devStrLen * 2) + 2); - ZeroMemory(*deviceStr, (devStrLen * 2) + 2); + *deviceStr = (LPWSTR) calloc(1, (devStrLen * 2) + 2); + if (!deviceStr) + return -1; wcscpy_s(*deviceStr, devStrLen+1, pwszID); } CoTaskMemFree(pwszID); diff --git a/server/shadow/CMakeLists.txt b/server/shadow/CMakeLists.txt index 06c60f5d1..eda2f617d 100644 --- a/server/shadow/CMakeLists.txt +++ b/server/shadow/CMakeLists.txt @@ -169,6 +169,10 @@ set(${MODULE_PREFIX}_SRCS shadow_encomsp.h shadow_remdesk.c shadow_remdesk.h + shadow_rdpsnd.c + shadow_rdpsnd.h + shadow_audin.c + shadow_audin.h shadow_subsystem.c shadow_subsystem.h shadow_mcevent.c diff --git a/server/shadow/Mac/mac_shadow.c b/server/shadow/Mac/mac_shadow.c index f4e25c984..519b06542 100644 --- a/server/shadow/Mac/mac_shadow.c +++ b/server/shadow/Mac/mac_shadow.c @@ -29,7 +29,6 @@ #include "../shadow_client.h" #include "../shadow_surface.h" #include "../shadow_capture.h" -#include "../shadow_encoder.h" #include "../shadow_subsystem.h" #include "../shadow_mcevent.h" @@ -377,7 +376,7 @@ void (^mac_capture_stream_handler)(CGDisplayStreamFrameStatus, uint64_t, IOSurfa if (client) { - subsystem->captureFrameRate = client->encoder->fps; + subsystem->captureFrameRate = shadow_encoder_preferred_fps(client->encoder); } } @@ -452,48 +451,56 @@ int mac_shadow_screen_grab(macShadowSubsystem* subsystem) int mac_shadow_subsystem_process_message(macShadowSubsystem* subsystem, wMessage* message) { - if (message->id == SHADOW_MSG_IN_REFRESH_OUTPUT_ID) + switch(message->id) { - UINT32 index; - SHADOW_MSG_IN_REFRESH_OUTPUT* msg = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam; - - if (msg->numRects) + case SHADOW_MSG_IN_REFRESH_OUTPUT_ID: { - for (index = 0; index < msg->numRects; index++) + UINT32 index; + SHADOW_MSG_IN_REFRESH_OUTPUT* msg = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam; + + if (msg->numRects) + { + for (index = 0; index < msg->numRects; index++) + { + region16_union_rect(&(subsystem->invalidRegion), + &(subsystem->invalidRegion), &msg->rects[index]); + } + } + else + { + RECTANGLE_16 refreshRect; + + refreshRect.left = 0; + refreshRect.top = 0; + refreshRect.right = subsystem->width; + refreshRect.bottom = subsystem->height; + + region16_union_rect(&(subsystem->invalidRegion), + &(subsystem->invalidRegion), &refreshRect); + } + break; + } + case SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID: + { + SHADOW_MSG_IN_SUPPRESS_OUTPUT* msg = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam; + + subsystem->suppressOutput = (msg->allow) ? FALSE : TRUE; + + if (msg->allow) { region16_union_rect(&(subsystem->invalidRegion), - &(subsystem->invalidRegion), &msg->rects[index]); + &(subsystem->invalidRegion), &(msg->rect)); } + break; } - else - { - RECTANGLE_16 refreshRect; - - refreshRect.left = 0; - refreshRect.top = 0; - refreshRect.right = subsystem->width; - refreshRect.bottom = subsystem->height; - - region16_union_rect(&(subsystem->invalidRegion), - &(subsystem->invalidRegion), &refreshRect); - } + default: + WLog_ERR(TAG, "Unknown message id: %u", message->id); + break; } - else if (message->id == SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID) - { - SHADOW_MSG_IN_SUPPRESS_OUTPUT* msg = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam; - - subsystem->suppressOutput = (msg->allow) ? FALSE : TRUE; - - if (msg->allow) - { - region16_union_rect(&(subsystem->invalidRegion), - &(subsystem->invalidRegion), &(msg->rect)); - } - } - + if (message->Free) message->Free(message); - + return 1; } diff --git a/server/shadow/Win/win_rdp.c b/server/shadow/Win/win_rdp.c index bda1877a8..d9e0b34bb 100644 --- a/server/shadow/Win/win_rdp.c +++ b/server/shadow/Win/win_rdp.c @@ -157,9 +157,7 @@ BOOL shw_post_connect(freerdp* instance) instance->update->DesktopResize = shw_desktop_resize; instance->update->SurfaceFrameMarker = shw_surface_frame_marker; - freerdp_channels_post_connect(instance->context->channels, instance); - - return TRUE; + return (freerdp_channels_post_connect(instance->context->channels, instance) >= 0) ; } void* shw_client_thread(void* arg) diff --git a/server/shadow/Win/win_wds.c b/server/shadow/Win/win_wds.c index 1ec82172f..44a12d286 100644 --- a/server/shadow/Win/win_wds.c +++ b/server/shadow/Win/win_wds.c @@ -764,21 +764,24 @@ int win_shadow_wds_init(winShadowSubsystem* subsystem) WLog_INFO(TAG, "ConnectionString: %s", file->ConnectionString2); - if (0) +#if 0 + FILE* fp; + size_t size; + + fp = fopen("inv.xml", "w+b"); + + if (fp) { - FILE* fp; - size_t size; - - fp = fopen("inv.xml", "w+b"); - - if (fp) + size = strlen(file->ConnectionString2); + if (fwrite(file->ConnectionString2, size, 1, fp) != 1 || fwrite("\r\n", 2, 1, fp) != 1) { - size = strlen(file->ConnectionString2); - fwrite(file->ConnectionString2, 1, size, fp); - fwrite("\r\n", 1, 2, fp); fclose(fp); + WLog_ERR(TAG, "Problem writing to inv.xml"); + return -1; } + fclose(fp); } +#endif status = win_shadow_rdp_init(subsystem); diff --git a/server/shadow/X11/x11_shadow.c b/server/shadow/X11/x11_shadow.c index 70fc36ab6..00b58b4ea 100644 --- a/server/shadow/X11/x11_shadow.c +++ b/server/shadow/X11/x11_shadow.c @@ -42,7 +42,6 @@ #include "../shadow_screen.h" #include "../shadow_client.h" -#include "../shadow_encoder.h" #include "../shadow_capture.h" #include "../shadow_surface.h" #include "../shadow_subsystem.h" @@ -76,16 +75,14 @@ typedef struct _SHADOW_PAM_AUTH_INFO SHADOW_PAM_AUTH_INFO; int x11_shadow_pam_conv(int num_msg, const struct pam_message** msg, struct pam_response** resp, void* appdata_ptr) { int index; - int pam_status = PAM_SUCCESS; + int pam_status = PAM_BUF_ERR; SHADOW_PAM_AUTH_DATA* appdata; struct pam_response* response; appdata = (SHADOW_PAM_AUTH_DATA*) appdata_ptr; - response = (struct pam_response*) calloc(num_msg, sizeof(struct pam_response)); - - if (!response) - return PAM_CONV_ERR; + if (!(response = (struct pam_response*) calloc(num_msg, sizeof(struct pam_response)))) + return PAM_BUF_ERR; for (index = 0; index < num_msg; index++) { @@ -93,29 +90,40 @@ int x11_shadow_pam_conv(int num_msg, const struct pam_message** msg, struct pam_ { case PAM_PROMPT_ECHO_ON: response[index].resp = _strdup(appdata->user); + if (!response[index].resp) + goto out_fail; response[index].resp_retcode = PAM_SUCCESS; break; case PAM_PROMPT_ECHO_OFF: response[index].resp = _strdup(appdata->password); + if (!response[index].resp) + goto out_fail; response[index].resp_retcode = PAM_SUCCESS; break; default: pam_status = PAM_CONV_ERR; - break; + goto out_fail; } } - if (pam_status != PAM_SUCCESS) - { - free(response); - return pam_status; - } - *resp = response; + return PAM_SUCCESS; - return pam_status; +out_fail: + for (index = 0; index < num_msg; ++index) + { + if (response[index].resp) + { + memset(response[index].resp, 0, strlen(response[index].resp)); + free(response[index].resp); + } + } + memset(response, 0, sizeof(struct pam_response) * num_msg); + free(response); + *resp = NULL; + return PAM_CONV_ERR; } int x11_shadow_pam_get_service_name(SHADOW_PAM_AUTH_INFO* info) @@ -145,6 +153,9 @@ int x11_shadow_pam_get_service_name(SHADOW_PAM_AUTH_INFO* info) return -1; } + if (!info->service_name) + return -1; + return 1; } @@ -348,11 +359,30 @@ void x11_shadow_input_extended_mouse_event(x11ShadowSubsystem* subsystem, UINT16 #endif } +static void x11_shadow_message_free(UINT32 id, SHADOW_MSG_OUT* msg) +{ + switch(id) + { + case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID: + free(msg); + break; + + case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID: + free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->pixels); + free(msg); + break; + + default: + WLog_ERR(TAG, "Unknown message id: %u", id); + free(msg); + break; + } +} + int x11_shadow_pointer_position_update(x11ShadowSubsystem* subsystem) { SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg; UINT32 msgId = SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID; - wMessagePipe* MsgPipe = subsystem->MsgPipe; msg = (SHADOW_MSG_OUT_POINTER_POSITION_UPDATE*) calloc(1, sizeof(SHADOW_MSG_OUT_POINTER_POSITION_UPDATE)); @@ -361,15 +391,15 @@ int x11_shadow_pointer_position_update(x11ShadowSubsystem* subsystem) msg->xPos = subsystem->pointerX; msg->yPos = subsystem->pointerY; + msg->Free = x11_shadow_message_free; - return MessageQueue_Post(MsgPipe->Out, NULL, msgId, (void*) msg, NULL) ? 1 : -1; + return shadow_client_boardcast_msg(subsystem->server, NULL, msgId, (SHADOW_MSG_OUT*) msg, NULL) ? 1 : -1; } int x11_shadow_pointer_alpha_update(x11ShadowSubsystem* subsystem) { SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg; UINT32 msgId = SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID; - wMessagePipe* MsgPipe = subsystem->MsgPipe; msg = (SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*) calloc(1, sizeof(SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE)); @@ -392,8 +422,9 @@ int x11_shadow_pointer_alpha_update(x11ShadowSubsystem* subsystem) CopyMemory(msg->pixels, subsystem->cursorPixels, msg->scanline * msg->height); msg->premultiplied = TRUE; + msg->Free = x11_shadow_message_free; - return MessageQueue_Post(MsgPipe->Out, NULL, msgId, (void*) msg, NULL) ? 1 : -1; + return shadow_client_boardcast_msg(subsystem->server, NULL, msgId, (SHADOW_MSG_OUT*) msg, NULL) ? 1 : -1; } int x11_shadow_query_cursor(x11ShadowSubsystem* subsystem, BOOL getImage) @@ -715,7 +746,7 @@ int x11_shadow_screen_grab(x11ShadowSubsystem* subsystem) if (client) { - subsystem->captureFrameRate = client->encoder->fps; + subsystem->captureFrameRate = shadow_encoder_preferred_fps(client->encoder); } } @@ -730,43 +761,51 @@ int x11_shadow_screen_grab(x11ShadowSubsystem* subsystem) int x11_shadow_subsystem_process_message(x11ShadowSubsystem* subsystem, wMessage* message) { - if (message->id == SHADOW_MSG_IN_REFRESH_OUTPUT_ID) + switch(message->id) { - UINT32 index; - SHADOW_MSG_IN_REFRESH_OUTPUT* msg = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam; - - if (msg->numRects) + case SHADOW_MSG_IN_REFRESH_OUTPUT_ID: { - for (index = 0; index < msg->numRects; index++) + UINT32 index; + SHADOW_MSG_IN_REFRESH_OUTPUT* msg = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam; + + if (msg->numRects) + { + for (index = 0; index < msg->numRects; index++) + { + region16_union_rect(&(subsystem->invalidRegion), + &(subsystem->invalidRegion), &msg->rects[index]); + } + } + else + { + RECTANGLE_16 refreshRect; + + refreshRect.left = 0; + refreshRect.top = 0; + refreshRect.right = subsystem->width; + refreshRect.bottom = subsystem->height; + + region16_union_rect(&(subsystem->invalidRegion), + &(subsystem->invalidRegion), &refreshRect); + } + break; + } + case SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID: + { + SHADOW_MSG_IN_SUPPRESS_OUTPUT* msg = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam; + + subsystem->suppressOutput = (msg->allow) ? FALSE : TRUE; + + if (msg->allow) { region16_union_rect(&(subsystem->invalidRegion), - &(subsystem->invalidRegion), &msg->rects[index]); + &(subsystem->invalidRegion), &(msg->rect)); } + break; } - else - { - RECTANGLE_16 refreshRect; - - refreshRect.left = 0; - refreshRect.top = 0; - refreshRect.right = subsystem->width; - refreshRect.bottom = subsystem->height; - - region16_union_rect(&(subsystem->invalidRegion), - &(subsystem->invalidRegion), &refreshRect); - } - } - else if (message->id == SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID) - { - SHADOW_MSG_IN_SUPPRESS_OUTPUT* msg = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam; - - subsystem->suppressOutput = (msg->allow) ? FALSE : TRUE; - - if (msg->allow) - { - region16_union_rect(&(subsystem->invalidRegion), - &(subsystem->invalidRegion), &(msg->rect)); - } + default: + WLog_ERR(TAG, "Unknown message id: %u", message->id); + break; } if (message->Free) @@ -1225,7 +1264,8 @@ int x11_shadow_subsystem_init(x11ShadowSubsystem* subsystem) subsystem->use_xdamage = FALSE; } - if (!(subsystem->event = CreateFileDescriptorEvent(NULL, FALSE, FALSE, subsystem->xfds))) + if (!(subsystem->event = CreateFileDescriptorEvent(NULL, FALSE, FALSE, + subsystem->xfds, WINPR_FD_READ))) return -1; virtualScreen = &(subsystem->virtualScreen); diff --git a/server/shadow/shadow.c b/server/shadow/shadow.c index 0bba8d8ee..83a834bc0 100644 --- a/server/shadow/shadow.c +++ b/server/shadow/shadow.c @@ -37,17 +37,50 @@ static BOOL g_MessagePump = FALSE; #include +#ifdef WITH_SHADOW_X11 +extern int X11_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +#endif + +#ifdef WITH_SHADOW_MAC +extern int Mac_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +#endif + +#ifdef WITH_SHADOW_WIN +extern int Win_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); +#endif + int main(int argc, char** argv) { MSG msg; - int status; + int status = 0; DWORD dwExitCode; rdpShadowServer* server; +#ifdef WITH_SHADOW_X11 + shadow_subsystem_set_entry(X11_ShadowSubsystemEntry); +#endif + +#ifdef WITH_SHADOW_MAC + shadow_subsystem_set_entry(Mac_ShadowSubsystemEntry); +#endif + +#ifdef WITH_SHADOW_WIN + shadow_subsystem_set_entry(Win_ShadowSubsystemEntry); +#endif + server = shadow_server_new(); if (!server) + { + status = -1; goto fail_server_new; + } + +#ifdef WITH_SHADOW_X11 + server->authentication = TRUE; +#else + server->authentication = FALSE; +#endif if ((status = shadow_server_parse_command_line(server, argc, argv)) < 0) { diff --git a/server/shadow/shadow_audin.c b/server/shadow/shadow_audin.c new file mode 100644 index 000000000..87184bdd0 --- /dev/null +++ b/server/shadow/shadow_audin.c @@ -0,0 +1,124 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "shadow.h" + +#include "shadow_audin.h" + +#define TAG SERVER_TAG("shadow") + +/* Default supported audio formats */ +static const AUDIO_FORMAT default_supported_audio_formats[] = +{ + { WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_ALAW, 2, 22050, 44100, 2, 8, 0, NULL } +}; + +static WIN32ERROR AudinServerOpening(audin_server_context* context) +{ + AUDIO_FORMAT* agreed_format = NULL; + int i = 0, j = 0; + for (i = 0; i < context->num_client_formats; i++) + { + for (j = 0; j < context->num_server_formats; j++) + { + if ((context->client_formats[i].wFormatTag == context->server_formats[j].wFormatTag) && + (context->client_formats[i].nChannels == context->server_formats[j].nChannels) && + (context->client_formats[i].nSamplesPerSec == context->server_formats[j].nSamplesPerSec)) + { + agreed_format = (AUDIO_FORMAT*) &context->server_formats[j]; + break; + } + } + if (agreed_format != NULL) + break; + + } + + if (agreed_format == NULL) + { + WLog_ERR(TAG, "Could not agree on a audio format with the server\n"); + return CHANNEL_RC_OK; + } + + context->SelectFormat(context, i); + return CHANNEL_RC_OK; +} +static WIN32ERROR AudinServerOpenResult(audin_server_context* context, UINT32 result) +{ + WLog_INFO(TAG, "AUDIN open result %u.\n", result); + return CHANNEL_RC_OK; +} +static WIN32ERROR AudinServerReceiveSamples(audin_server_context* context, const void* buf, int nframes) +{ + rdpShadowClient* client = (rdpShadowClient* )context->data; + rdpShadowSubsystem* subsystem = client->server->subsystem; + + if (!client->mayInteract) + return CHANNEL_RC_OK; + + if (subsystem->AudinServerReceiveSamples) + subsystem->AudinServerReceiveSamples(subsystem, buf, nframes); + return CHANNEL_RC_OK; +} + +int shadow_client_audin_init(rdpShadowClient* client) +{ + audin_server_context* audin; + audin = client->audin = audin_server_context_new(client->vcm); + if (!audin) + { + return 0; + } + + audin->data = client; + + if (client->subsystem->audinFormats) + { + audin->server_formats = client->subsystem->audinFormats; + audin->num_server_formats = client->subsystem->nAudinFormats; + } + else + { + /* Set default audio formats. */ + audin->server_formats = default_supported_audio_formats; + audin->num_server_formats = sizeof(default_supported_audio_formats) / sizeof(default_supported_audio_formats[0]); + } + + audin->dst_format = audin->server_formats[0]; + + audin->Opening = AudinServerOpening; + audin->OpenResult = AudinServerOpenResult; + audin->ReceiveSamples = AudinServerReceiveSamples; + + return 1; +} + +void shadow_client_audin_uninit(rdpShadowClient* client) +{ + if (client->audin) + { + audin_server_context_free(client->audin); + client->audin = NULL; + } +} diff --git a/server/shadow/shadow_audin.h b/server/shadow/shadow_audin.h new file mode 100644 index 000000000..a02bd3b4e --- /dev/null +++ b/server/shadow/shadow_audin.h @@ -0,0 +1,38 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_SHADOW_SERVER_AUDIN_H +#define FREERDP_SHADOW_SERVER_AUDIN_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int shadow_client_audin_init(rdpShadowClient* client); +void shadow_client_audin_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SHADOW_SERVER_AUDIN_H */ diff --git a/server/shadow/shadow_channels.c b/server/shadow/shadow_channels.c index 5a2e4bb03..eaf787e34 100644 --- a/server/shadow/shadow_channels.c +++ b/server/shadow/shadow_channels.c @@ -36,5 +36,23 @@ int shadow_client_channels_post_connect(rdpShadowClient* client) shadow_client_remdesk_init(client); } + if (WTSVirtualChannelManagerIsChannelJoined(client->vcm, "rdpsnd")) + { + shadow_client_rdpsnd_init(client); + } + + shadow_client_audin_init(client); + return 1; } + +void shadow_client_channels_free(rdpShadowClient* client) +{ + shadow_client_audin_uninit(client); + + shadow_client_rdpsnd_uninit(client); + + shadow_client_remdesk_uninit(client); + + shadow_client_encomsp_uninit(client); +} diff --git a/server/shadow/shadow_channels.h b/server/shadow/shadow_channels.h index 7c11eb84e..d6abef9c7 100644 --- a/server/shadow/shadow_channels.h +++ b/server/shadow/shadow_channels.h @@ -26,12 +26,15 @@ #include "shadow_encomsp.h" #include "shadow_remdesk.h" +#include "shadow_rdpsnd.h" +#include "shadow_audin.h" #ifdef __cplusplus extern "C" { #endif int shadow_client_channels_post_connect(rdpShadowClient* client); +void shadow_client_channels_free(rdpShadowClient* client); #ifdef __cplusplus } diff --git a/server/shadow/shadow_client.c b/server/shadow/shadow_client.c index e332688d9..694289985 100644 --- a/server/shadow/shadow_client.c +++ b/server/shadow/shadow_client.c @@ -26,6 +26,7 @@ #include #include #include +#include #include @@ -33,10 +34,21 @@ #define TAG CLIENT_TAG("shadow") +static void shadow_client_free_queued_message(void *obj) +{ + wMessage *message = (wMessage*)obj; + if (message->Free) + { + message->Free(message); + message->Free = NULL; + } +} + BOOL shadow_client_context_new(freerdp_peer* peer, rdpShadowClient* client) { rdpSettings* settings; rdpShadowServer* server; + const wObject cb = { NULL, NULL, NULL, shadow_client_free_queued_message, NULL }; server = (rdpShadowServer*) peer->ContextExtra; client->server = server; @@ -89,8 +101,8 @@ BOOL shadow_client_context_new(freerdp_peer* peer, rdpShadowClient* client) if (!client->vcm || client->vcm == INVALID_HANDLE_VALUE) goto fail_open_server; - if (!(client->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) - goto fail_stop_event; + if (!(client->MsgQueue = MessageQueue_New(&cb))) + goto fail_message_queue; if (!(client->encoder = shadow_encoder_new(client))) goto fail_encoder_new; @@ -101,9 +113,9 @@ BOOL shadow_client_context_new(freerdp_peer* peer, rdpShadowClient* client) shadow_encoder_free(client->encoder); client->encoder = NULL; fail_encoder_new: - CloseHandle(client->StopEvent); - client->StopEvent = NULL; -fail_stop_event: + MessageQueue_Free(client->MsgQueue); + client->MsgQueue = NULL; +fail_message_queue: WTSCloseServer((HANDLE) client->vcm); client->vcm = NULL; fail_open_server: @@ -134,7 +146,9 @@ void shadow_client_context_free(freerdp_peer* peer, rdpShadowClient* client) WTSCloseServer((HANDLE) client->vcm); - CloseHandle(client->StopEvent); + /* Clear queued messages and free resource */ + MessageQueue_Clear(client->MsgQueue); + MessageQueue_Free(client->MsgQueue); if (client->lobby) { @@ -147,25 +161,25 @@ void shadow_client_context_free(freerdp_peer* peer, rdpShadowClient* client) shadow_encoder_free(client->encoder); client->encoder = NULL; } - - shadow_client_encomsp_uninit(client); - - shadow_client_remdesk_uninit(client); } void shadow_client_message_free(wMessage* message) { - if (message->id == SHADOW_MSG_IN_REFRESH_OUTPUT_ID) + switch(message->id) { - SHADOW_MSG_IN_REFRESH_OUTPUT* wParam = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam; + case SHADOW_MSG_IN_REFRESH_OUTPUT_ID: + free(((SHADOW_MSG_IN_REFRESH_OUTPUT*)message->wParam)->rects); + free(message->wParam); + break; - free(wParam->rects); - free(wParam); - } - else if (message->id == SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID) - { - SHADOW_MSG_IN_SUPPRESS_OUTPUT* wParam = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam; - free(wParam); + case SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID: + free(message->wParam); + break; + + default: + WLog_ERR(TAG, "Unknown message id: %u", message->id); + free(message->wParam); + break; } } @@ -248,6 +262,11 @@ BOOL shadow_client_post_connect(freerdp_peer* peer) } } + if (subsystem->ClientConnect) + { + return subsystem->ClientConnect(subsystem, client); + } + return TRUE; } @@ -338,17 +357,16 @@ BOOL shadow_client_activate(freerdp_peer* peer) BOOL shadow_client_surface_frame_acknowledge(rdpShadowClient* client, UINT32 frameId) { - SURFACE_FRAME* frame; - wListDictionary* frameList; + /* + * Record the last client acknowledged frame id to + * calculate how much frames are in progress. + * Some rdp clients (win7 mstsc) skips frame ACK if it is + * inactive, we should not expect ACK for each frame. + * So it is OK to calculate inflight frame count according to + * a latest acknowledged frame id. + */ + client->encoder->lastAckframeId = frameId; - frameList = client->encoder->frameList; - frame = (SURFACE_FRAME*) ListDictionary_GetItemValue(frameList, (void*) (size_t) frameId); - - if (frame) - { - ListDictionary_Remove(frameList, (void*) (size_t) frameId); - free(frame); - } return TRUE; } @@ -409,7 +427,7 @@ int shadow_client_send_surface_bits(rdpShadowClient* client, rdpShadowSurface* s } if (encoder->frameAck) - frameId = (UINT32) shadow_encoder_create_frame_id(encoder); + frameId = shadow_encoder_create_frame_id(encoder); if (settings->RemoteFxCodec) { @@ -570,11 +588,9 @@ int shadow_client_send_bitmap_update(rdpShadowClient* client, rdpShadowSurface* totalBitmapSize = 0; bitmapUpdate.count = bitmapUpdate.number = rows * cols; - bitmapData = (BITMAP_DATA*) malloc(sizeof(BITMAP_DATA) * bitmapUpdate.number); - bitmapUpdate.rectangles = bitmapData; - - if (!bitmapData) + if (!(bitmapData = (BITMAP_DATA*) malloc(sizeof(BITMAP_DATA) * bitmapUpdate.number))) return -1; + bitmapUpdate.rectangles = bitmapData; if ((nWidth % 4) != 0) { @@ -666,6 +682,11 @@ int shadow_client_send_bitmap_update(rdpShadowClient* client, rdpShadowSurface* BITMAP_DATA* fragBitmapData; fragBitmapData = (BITMAP_DATA*) malloc(sizeof(BITMAP_DATA) * k); + if (!fragBitmapData) + { + free(bitmapData); + return -1; + } bitmapUpdate.rectangles = fragBitmapData; i = j = 0; @@ -884,63 +905,87 @@ int shadow_client_subsystem_process_message(rdpShadowClient* client, wMessage* m /* FIXME: the pointer updates appear to be broken when used with bulk compression and mstsc */ - if (message->id == SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID) + switch(message->id) { - POINTER_POSITION_UPDATE pointerPosition; - SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg = (SHADOW_MSG_OUT_POINTER_POSITION_UPDATE*) message->wParam; - - pointerPosition.xPos = msg->xPos; - pointerPosition.yPos = msg->yPos; - - if (client->activated) + case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID: { - if ((msg->xPos != client->pointerX) || (msg->yPos != client->pointerY)) + POINTER_POSITION_UPDATE pointerPosition; + SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg = (SHADOW_MSG_OUT_POINTER_POSITION_UPDATE*) message->wParam; + + pointerPosition.xPos = msg->xPos; + pointerPosition.yPos = msg->yPos; + + if (client->activated) { - IFCALL(update->pointer->PointerPosition, context, &pointerPosition); + if ((msg->xPos != client->pointerX) || (msg->yPos != client->pointerY)) + { + IFCALL(update->pointer->PointerPosition, context, &pointerPosition); - client->pointerX = msg->xPos; - client->pointerY = msg->yPos; + client->pointerX = msg->xPos; + client->pointerY = msg->yPos; + } } + break; } - - free(msg); - } - else if (message->id == SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID) - { - POINTER_NEW_UPDATE pointerNew; - POINTER_COLOR_UPDATE* pointerColor; - POINTER_CACHED_UPDATE pointerCached; - SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg = (SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*) message->wParam; - - ZeroMemory(&pointerNew, sizeof(POINTER_NEW_UPDATE)); - - pointerNew.xorBpp = 24; - pointerColor = &(pointerNew.colorPtrAttr); - - pointerColor->cacheIndex = 0; - pointerColor->xPos = msg->xHot; - pointerColor->yPos = msg->yHot; - pointerColor->width = msg->width; - pointerColor->height = msg->height; - - pointerCached.cacheIndex = pointerColor->cacheIndex; - - if (client->activated) + case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID: { - shadow_client_convert_alpha_pointer_data(msg->pixels, msg->premultiplied, - msg->width, msg->height, pointerColor); + POINTER_NEW_UPDATE pointerNew; + POINTER_COLOR_UPDATE* pointerColor; + POINTER_CACHED_UPDATE pointerCached; + SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg = (SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*) message->wParam; - IFCALL(update->pointer->PointerNew, context, &pointerNew); - IFCALL(update->pointer->PointerCached, context, &pointerCached); + ZeroMemory(&pointerNew, sizeof(POINTER_NEW_UPDATE)); - free(pointerColor->xorMaskData); - free(pointerColor->andMaskData); + pointerNew.xorBpp = 24; + pointerColor = &(pointerNew.colorPtrAttr); + + pointerColor->cacheIndex = 0; + pointerColor->xPos = msg->xHot; + pointerColor->yPos = msg->yHot; + pointerColor->width = msg->width; + pointerColor->height = msg->height; + + pointerCached.cacheIndex = pointerColor->cacheIndex; + + if (client->activated) + { + shadow_client_convert_alpha_pointer_data(msg->pixels, msg->premultiplied, + msg->width, msg->height, pointerColor); + + IFCALL(update->pointer->PointerNew, context, &pointerNew); + IFCALL(update->pointer->PointerCached, context, &pointerCached); + + free(pointerColor->xorMaskData); + free(pointerColor->andMaskData); + } + break; } - - free(msg->pixels); - free(msg); + case SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES_ID: + { + SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES* msg = (SHADOW_MSG_OUT_AUDIO_OUT_SAMPLES*) message->wParam; + if (client->activated && client->rdpsnd && client->rdpsnd->Activated) + { + client->rdpsnd->src_format = msg->audio_format; + IFCALL(client->rdpsnd->SendSamples, client->rdpsnd, msg->buf, msg->nFrames, msg->wTimestamp); + } + break; + } + case SHADOW_MSG_OUT_AUDIO_OUT_VOLUME_ID: + { + SHADOW_MSG_OUT_AUDIO_OUT_VOLUME* msg = (SHADOW_MSG_OUT_AUDIO_OUT_VOLUME*) message->wParam; + if (client->activated && client->rdpsnd && client->rdpsnd->Activated) + { + IFCALL(client->rdpsnd->SetVolume, client->rdpsnd, msg->left, msg->right); + } + break; + } + default: + WLog_ERR(TAG, "Unknown message id: %u", message->id); + break; } + shadow_client_free_queued_message(message); + return 1; } @@ -949,8 +994,10 @@ void* shadow_client_thread(rdpShadowClient* client) DWORD status; DWORD nCount; wMessage message; + wMessage pointerPositionMsg; + wMessage pointerAlphaMsg; + wMessage audioVolumeMsg; HANDLE events[32]; - HANDLE StopEvent; HANDLE ClientEvent; HANDLE ChannelEvent; void* UpdateSubscriber; @@ -962,7 +1009,7 @@ void* shadow_client_thread(rdpShadowClient* client) rdpShadowScreen* screen; rdpShadowEncoder* encoder; rdpShadowSubsystem* subsystem; - wMessagePipe* MsgPipe = client->subsystem->MsgPipe; + wMessageQueue* MsgQueue = client->MsgQueue; server = client->server; screen = server->screen; @@ -985,14 +1032,13 @@ void* shadow_client_thread(rdpShadowClient* client) peer->update->SuppressOutput = (pSuppressOutput)shadow_client_suppress_output; peer->update->SurfaceFrameAcknowledge = (pSurfaceFrameAcknowledge)shadow_client_surface_frame_acknowledge; - if ((!client->StopEvent) || (!client->vcm) || (!subsystem->updateEvent)) + if ((!client->vcm) || (!subsystem->updateEvent)) goto out; UpdateSubscriber = shadow_multiclient_get_subscriber(subsystem->updateEvent); if (!UpdateSubscriber) goto out; - StopEvent = client->StopEvent; UpdateEvent = shadow_multiclient_getevent(UpdateSubscriber); ClientEvent = peer->GetEventHandle(peer); ChannelEvent = WTSVirtualChannelManagerGetEventHandle(client->vcm); @@ -1000,19 +1046,13 @@ void* shadow_client_thread(rdpShadowClient* client) while (1) { nCount = 0; - events[nCount++] = StopEvent; events[nCount++] = UpdateEvent; events[nCount++] = ClientEvent; events[nCount++] = ChannelEvent; - events[nCount++] = MessageQueue_Event(MsgPipe->Out); + events[nCount++] = MessageQueue_Event(MsgQueue); status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); - if (WaitForSingleObject(StopEvent, 0) == WAIT_OBJECT_0) - { - break; - } - if (WaitForSingleObject(UpdateEvent, 0) == WAIT_OBJECT_0) { if (client->activated) @@ -1056,24 +1096,89 @@ void* shadow_client_thread(rdpShadowClient* client) } } - if (WaitForSingleObject(MessageQueue_Event(MsgPipe->Out), 0) == WAIT_OBJECT_0) + if (WaitForSingleObject(MessageQueue_Event(MsgQueue), 0) == WAIT_OBJECT_0) { - if (MessageQueue_Peek(MsgPipe->Out, &message, TRUE)) + /* Drain messages. Pointer update could be accumulated. */ + pointerPositionMsg.id = 0; + pointerPositionMsg.Free= NULL; + pointerAlphaMsg.id = 0; + pointerAlphaMsg.Free = NULL; + audioVolumeMsg.id = 0; + audioVolumeMsg.Free = NULL; + while (MessageQueue_Peek(MsgQueue, &message, TRUE)) { if (message.id == WMQ_QUIT) + { break; + } - shadow_client_subsystem_process_message(client, &message); + switch(message.id) + { + case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID: + /* Abandon previous message */ + shadow_client_free_queued_message(&pointerPositionMsg); + CopyMemory(&pointerPositionMsg, &message, sizeof(wMessage)); + break; + + case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID: + /* Abandon previous message */ + shadow_client_free_queued_message(&pointerAlphaMsg); + CopyMemory(&pointerAlphaMsg, &message, sizeof(wMessage)); + break; + + case SHADOW_MSG_OUT_AUDIO_OUT_VOLUME_ID: + /* Abandon previous message */ + shadow_client_free_queued_message(&audioVolumeMsg); + CopyMemory(&audioVolumeMsg, &message, sizeof(wMessage)); + break; + + default: + shadow_client_subsystem_process_message(client, &message); + break; + } + } + + if (message.id == WMQ_QUIT) + { + /* Release stored message */ + shadow_client_free_queued_message(&pointerPositionMsg); + shadow_client_free_queued_message(&pointerAlphaMsg); + shadow_client_free_queued_message(&audioVolumeMsg); + break; + } + else + { + /* Process accumulated messages if needed */ + if (pointerPositionMsg.id) + { + shadow_client_subsystem_process_message(client, &pointerPositionMsg); + } + if (pointerAlphaMsg.id) + { + shadow_client_subsystem_process_message(client, &pointerAlphaMsg); + } + if (audioVolumeMsg.id) + { + shadow_client_subsystem_process_message(client, &audioVolumeMsg); + } } } } + /* Free channels early because we establish channels in post connect */ + shadow_client_channels_free(client); + if (UpdateSubscriber) { shadow_multiclient_release_subscriber(UpdateSubscriber); UpdateSubscriber = NULL; } + if (peer->connected && subsystem->ClientDisconnect) + { + subsystem->ClientDisconnect(subsystem, client); + } + out: peer->Disconnect(peer); @@ -1109,3 +1214,102 @@ BOOL shadow_client_accepted(freerdp_listener* listener, freerdp_peer* peer) return TRUE; } + +static void shadow_msg_out_addref(wMessage* message) +{ + SHADOW_MSG_OUT* msg = (SHADOW_MSG_OUT *)message->wParam; + InterlockedIncrement(&(msg->refCount)); +} + +static void shadow_msg_out_release(wMessage* message) +{ + SHADOW_MSG_OUT* msg = (SHADOW_MSG_OUT *)message->wParam; + if (InterlockedDecrement(&(msg->refCount)) <= 0) + { + if (msg->Free) + msg->Free(message->id, msg); + } +} + +static BOOL shadow_client_dispatch_msg(rdpShadowClient* client, wMessage* message) +{ + /* Add reference when it is posted */ + shadow_msg_out_addref(message); + if (MessageQueue_Dispatch(client->MsgQueue, message)) + { + return TRUE; + } + else + { + /* Release the reference since post failed */ + shadow_msg_out_release(message); + return FALSE; + } +} + +BOOL shadow_client_post_msg(rdpShadowClient* client, void* context, UINT32 type, SHADOW_MSG_OUT* msg, void* lParam) +{ + wMessage message = {0}; + + message.context = context; + message.id = type; + message.wParam = (void *)msg; + message.lParam = lParam; + message.Free = shadow_msg_out_release; + + return shadow_client_dispatch_msg(client, &message); +} + +int shadow_client_boardcast_msg(rdpShadowServer* server, void* context, UINT32 type, SHADOW_MSG_OUT* msg, void* lParam) +{ + wMessage message = {0}; + rdpShadowClient* client = NULL; + int count = 0; + int index = 0; + + message.context = context; + message.id = type; + message.wParam = (void *)msg; + message.lParam = lParam; + message.Free = shadow_msg_out_release; + + /* First add reference as we reference it in this function. + * Therefore it would not be free'ed during post. */ + shadow_msg_out_addref(&message); + + ArrayList_Lock(server->clients); + for (index = 0; index < ArrayList_Count(server->clients); index++) + { + client = (rdpShadowClient*)ArrayList_GetItem(server->clients, index); + if (shadow_client_dispatch_msg(client, &message)) + { + count++; + } + } + ArrayList_Unlock(server->clients); + + /* Release the reference for this function */ + shadow_msg_out_release(&message); + + return count; +} + +int shadow_client_boardcast_quit(rdpShadowServer* server, int nExitCode) +{ + wMessageQueue* queue = NULL; + int count = 0; + int index = 0; + + ArrayList_Lock(server->clients); + for (index = 0; index < ArrayList_Count(server->clients); index++) + { + queue = ((rdpShadowClient*)ArrayList_GetItem(server->clients, index))->MsgQueue; + if (MessageQueue_PostQuit(queue, nExitCode)) + { + count++; + } + } + ArrayList_Unlock(server->clients); + + return count; +} diff --git a/server/shadow/shadow_encoder.c b/server/shadow/shadow_encoder.c index 65171e2a1..17ae041bf 100644 --- a/server/shadow/shadow_encoder.c +++ b/server/shadow/shadow_encoder.c @@ -24,15 +24,37 @@ #include "shadow_encoder.h" -int shadow_encoder_create_frame_id(rdpShadowEncoder* encoder) +int shadow_encoder_preferred_fps(rdpShadowEncoder* encoder) +{ + /* Return preferred fps calculated according to the last + * sent frame id and last client-acknowledged frame id. + */ + return encoder->fps; +} + +UINT32 shadow_encoder_inflight_frames(rdpShadowEncoder* encoder) +{ + /* Return inflight frame count = + * - + * Note: This function is exported so that subsystem could + * implement its own strategy to tune fps. + */ + return encoder->frameId - encoder->lastAckframeId; +} + +UINT32 shadow_encoder_create_frame_id(rdpShadowEncoder* encoder) { UINT32 frameId; int inFlightFrames; - SURFACE_FRAME* frame; - inFlightFrames = ListDictionary_Count(encoder->frameList); + inFlightFrames = shadow_encoder_inflight_frames(encoder); - if (inFlightFrames > encoder->frameAck) + /* + * Calculate preferred fps according to how much frames are + * in-progress. Note that it only works when subsytem implementation + * calls shadow_encoder_preferred_fps and takes the suggestion. + */ + if (inFlightFrames > 1) { encoder->fps = (100 / (inFlightFrames + 1) * encoder->maxFps) / 100; } @@ -47,16 +69,9 @@ int shadow_encoder_create_frame_id(rdpShadowEncoder* encoder) if (encoder->fps < 1) encoder->fps = 1; - frame = (SURFACE_FRAME*) malloc(sizeof(SURFACE_FRAME)); + frameId = ++encoder->frameId; - if (!frame) - return -1; - - frameId = frame->frameId = ++encoder->frameId; - if (!ListDictionary_Add(encoder->frameList, (void*) (size_t) frame->frameId, frame)) - return -1; - - return (int) frame->frameId; + return frameId; } int shadow_encoder_init_grid(rdpShadowEncoder* encoder) @@ -130,16 +145,11 @@ int shadow_encoder_init_rfx(rdpShadowEncoder* encoder) rfx_context_set_pixel_format(encoder->rfx, RDP_PIXEL_FORMAT_B8G8R8A8); - if (!encoder->frameList) - { - encoder->fps = 16; - encoder->maxFps = 32; - encoder->frameId = 0; - encoder->frameList = ListDictionary_New(TRUE); - if (!encoder->frameList) - return -1; - encoder->frameAck = settings->SurfaceFrameMarkerEnabled; - } + encoder->fps = 16; + encoder->maxFps = 32; + encoder->frameId = 0; + encoder->lastAckframeId = 0; + encoder->frameAck = settings->SurfaceFrameMarkerEnabled; encoder->codecs |= FREERDP_CODEC_REMOTEFX; @@ -159,16 +169,11 @@ int shadow_encoder_init_nsc(rdpShadowEncoder* encoder) nsc_context_set_pixel_format(encoder->nsc, RDP_PIXEL_FORMAT_B8G8R8A8); - if (!encoder->frameList) - { - encoder->fps = 16; - encoder->maxFps = 32; - encoder->frameId = 0; - encoder->frameList = ListDictionary_New(TRUE); - if (!encoder->frameList) - return -1; - encoder->frameAck = settings->SurfaceFrameMarkerEnabled; - } + encoder->fps = 16; + encoder->maxFps = 32; + encoder->frameId = 0; + encoder->lastAckframeId = 0; + encoder->frameAck = settings->SurfaceFrameMarkerEnabled; encoder->nsc->ColorLossLevel = settings->NSCodecColorLossLevel; encoder->nsc->ChromaSubsamplingLevel = settings->NSCodecAllowSubsampling ? 1 : 0; @@ -241,12 +246,6 @@ int shadow_encoder_uninit_rfx(rdpShadowEncoder* encoder) encoder->rfx = NULL; } - if (encoder->frameList) - { - ListDictionary_Free(encoder->frameList); - encoder->frameList = NULL; - } - encoder->codecs &= ~FREERDP_CODEC_REMOTEFX; return 1; @@ -260,12 +259,6 @@ int shadow_encoder_uninit_nsc(rdpShadowEncoder* encoder) encoder->nsc = NULL; } - if (encoder->frameList) - { - ListDictionary_Free(encoder->frameList); - encoder->frameList = NULL; - } - encoder->codecs &= ~FREERDP_CODEC_NSCODEC; return 1; diff --git a/server/shadow/shadow_encoder.h b/server/shadow/shadow_encoder.h index 34b8d0ef5..fd7d46a11 100644 --- a/server/shadow/shadow_encoder.h +++ b/server/shadow/shadow_encoder.h @@ -54,7 +54,7 @@ struct rdp_shadow_encoder int maxFps; BOOL frameAck; UINT32 frameId; - wListDictionary* frameList; + UINT32 lastAckframeId; }; #ifdef __cplusplus @@ -63,7 +63,7 @@ extern "C" { int shadow_encoder_reset(rdpShadowEncoder* encoder); int shadow_encoder_prepare(rdpShadowEncoder* encoder, UINT32 codecs); -int shadow_encoder_create_frame_id(rdpShadowEncoder* encoder); +UINT32 shadow_encoder_create_frame_id(rdpShadowEncoder* encoder); rdpShadowEncoder* shadow_encoder_new(rdpShadowClient* client); void shadow_encoder_free(rdpShadowEncoder* encoder); diff --git a/server/shadow/shadow_encomsp.c b/server/shadow/shadow_encomsp.c index 8fa9a372f..cabcc86a3 100644 --- a/server/shadow/shadow_encomsp.c +++ b/server/shadow/shadow_encomsp.c @@ -117,6 +117,7 @@ void shadow_client_encomsp_uninit(rdpShadowClient* client) { if (client->encomsp) { client->encomsp->Stop(client->encomsp); + encomsp_server_context_free(client->encomsp); client->encomsp = NULL; } } diff --git a/server/shadow/shadow_rdpsnd.c b/server/shadow/shadow_rdpsnd.c new file mode 100644 index 000000000..15428c655 --- /dev/null +++ b/server/shadow/shadow_rdpsnd.c @@ -0,0 +1,111 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "shadow.h" + +#include "shadow_rdpsnd.h" + +#define TAG SERVER_TAG("shadow") + +/* Default supported audio formats */ +static const AUDIO_FORMAT default_supported_audio_formats[] = +{ + { WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0, NULL }, + { WAVE_FORMAT_ALAW, 2, 22050, 44100, 2, 8, 0, NULL } +}; + +static void rdpsnd_activated(RdpsndServerContext* context) +{ + AUDIO_FORMAT* agreed_format = NULL; + int i = 0, j = 0; + for (i = 0; i < context->num_client_formats; i++) + { + for (j = 0; j < context->num_server_formats; j++) + { + if ((context->client_formats[i].wFormatTag == context->server_formats[j].wFormatTag) && + (context->client_formats[i].nChannels == context->server_formats[j].nChannels) && + (context->client_formats[i].nSamplesPerSec == context->server_formats[j].nSamplesPerSec)) + { + agreed_format = (AUDIO_FORMAT*) &context->server_formats[j]; + break; + } + } + if (agreed_format != NULL) + break; + + } + + if (agreed_format == NULL) + { + WLog_ERR(TAG, "Could not agree on a audio format with the server\n"); + return; + } + + context->SelectFormat(context, i); + context->SetVolume(context, 0x7FFF, 0x7FFF); +} + +int shadow_client_rdpsnd_init(rdpShadowClient* client) +{ + RdpsndServerContext* rdpsnd; + + rdpsnd = client->rdpsnd = rdpsnd_server_context_new(client->vcm); + if (!rdpsnd) + { + return 0; + } + + rdpsnd->data = client; + + if (client->subsystem->rdpsndFormats) + { + rdpsnd->server_formats = client->subsystem->rdpsndFormats; + rdpsnd->num_server_formats = client->subsystem->nRdpsndFormats; + } + else + { + /* Set default audio formats. */ + rdpsnd->server_formats = default_supported_audio_formats; + rdpsnd->num_server_formats = + sizeof(default_supported_audio_formats) / sizeof(default_supported_audio_formats[0]); + } + + rdpsnd->src_format = rdpsnd->server_formats[0]; + + rdpsnd->Activated = rdpsnd_activated; + + rdpsnd->Initialize(rdpsnd, TRUE); + + return 1; + +} + +void shadow_client_rdpsnd_uninit(rdpShadowClient* client) +{ + if (client->rdpsnd) + { + client->rdpsnd->Stop(client->rdpsnd); + rdpsnd_server_context_free(client->rdpsnd); + client->rdpsnd = NULL; + } +} diff --git a/server/shadow/shadow_rdpsnd.h b/server/shadow/shadow_rdpsnd.h new file mode 100644 index 000000000..b95e9ce3b --- /dev/null +++ b/server/shadow/shadow_rdpsnd.h @@ -0,0 +1,38 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2015 Jiang Zihao + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_SHADOW_SERVER_RDPSND_H +#define FREERDP_SHADOW_SERVER_RDPSND_H + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int shadow_client_rdpsnd_init(rdpShadowClient* client); +void shadow_client_rdpsnd_uninit(rdpShadowClient* client); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_SHADOW_SERVER_RDPSND_H */ diff --git a/server/shadow/shadow_remdesk.c b/server/shadow/shadow_remdesk.c index 977f05170..72c3a1408 100644 --- a/server/shadow/shadow_remdesk.c +++ b/server/shadow/shadow_remdesk.c @@ -45,6 +45,7 @@ void shadow_client_remdesk_uninit(rdpShadowClient* client) { if (client->remdesk) { client->remdesk->Stop(client->remdesk); + remdesk_server_context_free(client->remdesk); client->remdesk = NULL; } } diff --git a/server/shadow/shadow_server.c b/server/shadow/shadow_server.c index 79568f1dd..33e97743e 100644 --- a/server/shadow/shadow_server.c +++ b/server/shadow/shadow_server.c @@ -88,6 +88,8 @@ int shadow_server_print_command_line_help(int argc, char** argv) { length = (int) (strlen(arg->Name) + strlen(arg->Format) + 2); str = (char*) malloc(length + 1); + if (!str) + return -1; sprintf_s(str, length + 1, "%s:%s", arg->Name, arg->Format); WLog_INFO(TAG, "%-20s", str); free(str); @@ -103,6 +105,8 @@ int shadow_server_print_command_line_help(int argc, char** argv) { length = (int) strlen(arg->Name) + 32; str = (char*) malloc(length + 1); + if (!str) + return -1; sprintf_s(str, length + 1, "%s (default:%s)", arg->Name, arg->Default ? "on" : "off"); @@ -132,7 +136,8 @@ int shadow_server_command_line_status_print(rdpShadowServer* server, int argc, c } else if (status < 0) { - shadow_server_print_command_line_help(argc, argv); + if (shadow_server_print_command_line_help(argc, argv) < 0) + return -1; return COMMAND_LINE_STATUS_PRINT_HELP; } @@ -174,6 +179,8 @@ int shadow_server_parse_command_line(rdpShadowServer* server, int argc, char** a CommandLineSwitchCase(arg, "ipc-socket") { server->ipcSocket = _strdup(arg->Value); + if (!server->ipcSocket) + return -1; } CommandLineSwitchCase(arg, "may-view") { @@ -189,7 +196,6 @@ int shadow_server_parse_command_line(rdpShadowServer* server, int argc, char** a char* tok[4]; int x, y, w, h; char* str = _strdup(arg->Value); - if (!str) return -1; @@ -254,7 +260,7 @@ int shadow_server_parse_command_line(rdpShadowServer* server, int argc, char** a int numMonitors; MONITOR_DEF monitors[16]; - numMonitors = shadow_enum_monitors(monitors, 16, 0); + numMonitors = shadow_enum_monitors(monitors, 16); if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) { @@ -346,7 +352,7 @@ void* shadow_server_thread(rdpShadowServer* server) /* Signal to the clients that server is being stopped and wait for them * to disconnect. */ - if (MessageQueue_PostQuit(subsystem->MsgPipe->Out, 0)) + if (shadow_client_boardcast_quit(server, 0)) { while(ArrayList_Count(server->clients) > 0) { @@ -499,10 +505,11 @@ int shadow_server_init_config_path(rdpShadowServer* server) return 1; } -int shadow_server_init_certificate(rdpShadowServer* server) +static BOOL shadow_server_init_certificate(rdpShadowServer* server) { char* filepath; - MAKECERT_CONTEXT* makecert; + MAKECERT_CONTEXT* makecert = NULL; + BOOL ret = FALSE; const char* makecert_argv[6] = { @@ -519,44 +526,58 @@ int shadow_server_init_certificate(rdpShadowServer* server) !PathMakePathA(server->ConfigPath, 0)) { WLog_ERR(TAG, "Failed to create directory '%s'", server->ConfigPath); - return -1; + return FALSE; } if (!(filepath = GetCombinedPath(server->ConfigPath, "shadow"))) - return -1; + return FALSE; if (!PathFileExistsA(filepath) && !PathMakePathA(filepath, 0)) { - WLog_ERR(TAG, "Failed to create directory '%s'", filepath); - free(filepath); - return -1; + if (!CreateDirectoryA(filepath, 0)) + { + WLog_ERR(TAG, "Failed to create directory '%s'", filepath); + goto out_fail; + } } server->CertificateFile = GetCombinedPath(filepath, "shadow.crt"); server->PrivateKeyFile = GetCombinedPath(filepath, "shadow.key"); + if (!server->CertificateFile || !server->PrivateKeyFile) + goto out_fail; if ((!PathFileExistsA(server->CertificateFile)) || (!PathFileExistsA(server->PrivateKeyFile))) { makecert = makecert_context_new(); + if (!makecert) + goto out_fail; - makecert_context_process(makecert, makecert_argc, (char**) makecert_argv); + if (makecert_context_process(makecert, makecert_argc, (char**) makecert_argv) < 0) + goto out_fail; - makecert_context_set_output_file_name(makecert, "shadow"); + if (makecert_context_set_output_file_name(makecert, "shadow") != 1) + goto out_fail; if (!PathFileExistsA(server->CertificateFile)) - makecert_context_output_certificate_file(makecert, filepath); + { + if (makecert_context_output_certificate_file(makecert, filepath) != 1) + goto out_fail; + } if (!PathFileExistsA(server->PrivateKeyFile)) - makecert_context_output_private_key_file(makecert, filepath); - - makecert_context_free(makecert); + { + if (makecert_context_output_private_key_file(makecert, filepath) != 1) + goto out_fail; + } } - + ret = TRUE; +out_fail: + makecert_context_free(makecert); free(filepath); - return 1; + return ret; } int shadow_server_init(rdpShadowServer* server) @@ -594,7 +615,7 @@ int shadow_server_init(rdpShadowServer* server) server->listener->info = (void*) server; server->listener->PeerAccepted = shadow_client_accepted; - server->subsystem = shadow_subsystem_new(NULL); + server->subsystem = shadow_subsystem_new(); if (!server->subsystem) goto fail_subsystem_new; @@ -674,11 +695,7 @@ rdpShadowServer* shadow_server_new() server->mayView = TRUE; server->mayInteract = TRUE; -#ifdef WITH_SHADOW_X11 - server->authentication = TRUE; -#else server->authentication = FALSE; -#endif return server; } diff --git a/server/shadow/shadow_subsystem.c b/server/shadow/shadow_subsystem.c index 5316e45fc..04775c936 100644 --- a/server/shadow/shadow_subsystem.c +++ b/server/shadow/shadow_subsystem.c @@ -24,92 +24,32 @@ #include "shadow_subsystem.h" -struct _RDP_SHADOW_SUBSYSTEM +static pfnShadowSubsystemEntry pSubsystemEntry = NULL; + +void shadow_subsystem_set_entry(pfnShadowSubsystemEntry pEntry) { - const char* name; - pfnShadowSubsystemEntry entry; -}; -typedef struct _RDP_SHADOW_SUBSYSTEM RDP_SHADOW_SUBSYSTEM; - - -#ifdef WITH_SHADOW_X11 -extern int X11_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); -#endif - -#ifdef WITH_SHADOW_MAC -extern int Mac_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); -#endif - -#ifdef WITH_SHADOW_WIN -extern int Win_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints); -#endif - - -static RDP_SHADOW_SUBSYSTEM g_Subsystems[] = -{ - -#ifdef WITH_SHADOW_X11 - { "X11", X11_ShadowSubsystemEntry }, -#endif - -#ifdef WITH_SHADOW_MAC - { "Mac", Mac_ShadowSubsystemEntry }, -#endif - -#ifdef WITH_SHADOW_WIN - { "Win", Win_ShadowSubsystemEntry }, -#endif - - { "", NULL } -}; - -static int g_SubsystemCount = (sizeof(g_Subsystems) / sizeof(g_Subsystems[0])); - -pfnShadowSubsystemEntry shadow_subsystem_load_static_entry(const char* name) -{ - int index; - - if (!name) - { - for (index = 0; index < g_SubsystemCount; index++) - { - if (g_Subsystems[index].name) - return g_Subsystems[index].entry; - } - } - - for (index = 0; index < g_SubsystemCount; index++) - { - if (strcmp(name, g_Subsystems[index].name) == 0) - return g_Subsystems[index].entry; - } - - return NULL; + pSubsystemEntry = pEntry; } -int shadow_subsystem_load_entry_points(RDP_SHADOW_ENTRY_POINTS* pEntryPoints, const char* name) +static int shadow_subsystem_load_entry_points(RDP_SHADOW_ENTRY_POINTS* pEntryPoints) { - pfnShadowSubsystemEntry entry; - - entry = shadow_subsystem_load_static_entry(name); - ZeroMemory(pEntryPoints, sizeof(RDP_SHADOW_ENTRY_POINTS)); - if (!entry) + if (!pSubsystemEntry) return -1; - if (entry(pEntryPoints) < 0) + if (pSubsystemEntry(pEntryPoints) < 0) return -1; return 1; } -rdpShadowSubsystem* shadow_subsystem_new(const char* name) +rdpShadowSubsystem* shadow_subsystem_new() { RDP_SHADOW_ENTRY_POINTS ep; rdpShadowSubsystem* subsystem = NULL; - shadow_subsystem_load_entry_points(&ep, name); + shadow_subsystem_load_entry_points(&ep); if (!ep.New) return NULL; @@ -167,6 +107,16 @@ fail: return status; } +static void shadow_subsystem_free_queued_message(void *obj) +{ + wMessage *message = (wMessage*)obj; + if (message->Free) + { + message->Free(message); + message->Free = NULL; + } +} + void shadow_subsystem_uninit(rdpShadowSubsystem* subsystem) { if (!subsystem) @@ -177,6 +127,11 @@ void shadow_subsystem_uninit(rdpShadowSubsystem* subsystem) if (subsystem->MsgPipe) { + /* Release resource in messages before free */ + subsystem->MsgPipe->In->object.fnObjectFree = shadow_subsystem_free_queued_message; + MessageQueue_Clear(subsystem->MsgPipe->In); + subsystem->MsgPipe->Out->object.fnObjectFree = shadow_subsystem_free_queued_message; + MessageQueue_Clear(subsystem->MsgPipe->Out); MessagePipe_Free(subsystem->MsgPipe); subsystem->MsgPipe = NULL; } @@ -215,12 +170,12 @@ int shadow_subsystem_stop(rdpShadowSubsystem* subsystem) return status; } -int shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors, const char* name) +int shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors) { int numMonitors = 0; RDP_SHADOW_ENTRY_POINTS ep; - if (shadow_subsystem_load_entry_points(&ep, name) < 0) + if (shadow_subsystem_load_entry_points(&ep) < 0) return -1; numMonitors = ep.EnumMonitors(monitors, maxMonitors); diff --git a/server/shadow/shadow_subsystem.h b/server/shadow/shadow_subsystem.h index 9ad710475..7170cf207 100644 --- a/server/shadow/shadow_subsystem.h +++ b/server/shadow/shadow_subsystem.h @@ -24,50 +24,11 @@ #include #include -#define SHADOW_MSG_IN_REFRESH_OUTPUT_ID 1001 -#define SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID 1002 - -struct _SHADOW_MSG_IN_REFRESH_OUTPUT -{ - UINT32 numRects; - RECTANGLE_16* rects; -}; -typedef struct _SHADOW_MSG_IN_REFRESH_OUTPUT SHADOW_MSG_IN_REFRESH_OUTPUT; - -struct _SHADOW_MSG_IN_SUPPRESS_OUTPUT -{ - BOOL allow; - RECTANGLE_16 rect; -}; -typedef struct _SHADOW_MSG_IN_SUPPRESS_OUTPUT SHADOW_MSG_IN_SUPPRESS_OUTPUT; - -#define SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID 2001 -#define SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID 2002 - -struct _SHADOW_MSG_OUT_POINTER_POSITION_UPDATE -{ - UINT32 xPos; - UINT32 yPos; -}; -typedef struct _SHADOW_MSG_OUT_POINTER_POSITION_UPDATE SHADOW_MSG_OUT_POINTER_POSITION_UPDATE; - -struct _SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE -{ - UINT32 xHot; - UINT32 yHot; - UINT32 width; - UINT32 height; - BYTE* pixels; - int scanline; - BOOL premultiplied; -}; -typedef struct _SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE; - #ifdef __cplusplus extern "C" { #endif -rdpShadowSubsystem* shadow_subsystem_new(const char* name); +rdpShadowSubsystem* shadow_subsystem_new(); void shadow_subsystem_free(rdpShadowSubsystem* subsystem); int shadow_subsystem_init(rdpShadowSubsystem* subsystem, rdpShadowServer* server); diff --git a/winpr/include/winpr/cmdline.h b/winpr/include/winpr/cmdline.h index 48db262d0..ef41a6be8 100644 --- a/winpr/include/winpr/cmdline.h +++ b/winpr/include/winpr/cmdline.h @@ -64,13 +64,14 @@ /* Command-Line Parsing Error Codes */ -#define COMMAND_LINE_ERROR -1000 +#define COMMAND_LINE_ERROR -1000 #define COMMAND_LINE_ERROR_NO_KEYWORD -1001 #define COMMAND_LINE_ERROR_UNEXPECTED_VALUE -1002 #define COMMAND_LINE_ERROR_MISSING_VALUE -1003 #define COMMAND_LINE_ERROR_MISSING_ARGUMENT -1004 #define COMMAND_LINE_ERROR_UNEXPECTED_SIGIL -1005 -#define COMMAND_LINE_ERROR_LAST -1006 +#define COMMAND_LINE_ERROR_MEMORY -1006 +#define COMMAND_LINE_ERROR_LAST -1999 /* Command-Line Parsing Status Codes */ diff --git a/winpr/include/winpr/debug.h b/winpr/include/winpr/debug.h index 063f10829..3d2cde68a 100644 --- a/winpr/include/winpr/debug.h +++ b/winpr/include/winpr/debug.h @@ -27,6 +27,7 @@ extern "C" { #include +WINPR_API void winpr_log_backtrace(const char* tag, DWORD level, DWORD size); WINPR_API void* winpr_backtrace(DWORD size); WINPR_API void winpr_backtrace_free(void* buffer); WINPR_API char** winpr_backtrace_symbols(void* buffer, size_t* used); diff --git a/winpr/include/winpr/handle.h b/winpr/include/winpr/handle.h index 3a278e93a..cf69532ad 100644 --- a/winpr/include/winpr/handle.h +++ b/winpr/include/winpr/handle.h @@ -31,6 +31,12 @@ extern "C" { #endif +#define WINPR_FD_READ_BIT 0 +#define WINPR_FD_READ (1 << WINPR_FD_READ_BIT) + +#define WINPR_FD_WRITE_BIT 1 +#define WINPR_FD_WRITE (1 << WINPR_FD_WRITE_BIT) + #ifndef _WIN32 #define DUPLICATE_CLOSE_SOURCE 0x00000001 @@ -41,8 +47,12 @@ extern "C" { WINPR_API BOOL CloseHandle(HANDLE hObject); -WINPR_API BOOL DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, - LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions); +WINPR_API BOOL DuplicateHandle(HANDLE hSourceProcessHandle, + HANDLE hSourceHandle, + HANDLE hTargetProcessHandle, + LPHANDLE lpTargetHandle, + DWORD dwDesiredAccess, + BOOL bInheritHandle, DWORD dwOptions); WINPR_API BOOL GetHandleInformation(HANDLE hObject, LPDWORD lpdwFlags); WINPR_API BOOL SetHandleInformation(HANDLE hObject, DWORD dwMask, DWORD dwFlags); diff --git a/winpr/include/winpr/synch.h b/winpr/include/winpr/synch.h index 4b554431d..d5abb80dd 100644 --- a/winpr/include/winpr/synch.h +++ b/winpr/include/winpr/synch.h @@ -332,15 +332,14 @@ WINPR_API BOOL WINAPI EnterSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBa WINPR_API BOOL WINAPI DeleteSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier); #endif - /* Extended API */ WINPR_API VOID USleep(DWORD dwMicroseconds); WINPR_API HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, - BOOL bManualReset, BOOL bInitialState, int FileDescriptor); + BOOL bManualReset, BOOL bInitialState, int FileDescriptor, ULONG mode); WINPR_API HANDLE CreateFileDescriptorEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, - BOOL bManualReset, BOOL bInitialState, int FileDescriptor); + BOOL bManualReset, BOOL bInitialState, int FileDescriptor, ULONG mode); WINPR_API HANDLE CreateWaitObjectEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, void* pObject); @@ -352,7 +351,7 @@ WINPR_API HANDLE CreateWaitObjectEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, #endif WINPR_API int GetEventFileDescriptor(HANDLE hEvent); -WINPR_API int SetEventFileDescriptor(HANDLE hEvent, int FileDescriptor); +WINPR_API int SetEventFileDescriptor(HANDLE hEvent, int FileDescriptor, ULONG mode); WINPR_API void* GetEventWaitObject(HANDLE hEvent); diff --git a/winpr/include/winpr/sysinfo.h b/winpr/include/winpr/sysinfo.h index a72297ffa..53f500328 100644 --- a/winpr/include/winpr/sysinfo.h +++ b/winpr/include/winpr/sysinfo.h @@ -94,6 +94,8 @@ typedef struct _SYSTEM_INFO WORD wProcessorRevision; } SYSTEM_INFO, *LPSYSTEM_INFO; +#define MAX_COMPUTERNAME_LENGTH 31 + WINPR_API void GetSystemInfo(LPSYSTEM_INFO lpSystemInfo); WINPR_API void GetNativeSystemInfo(LPSYSTEM_INFO lpSystemInfo); diff --git a/winpr/include/winpr/wlog.h b/winpr/include/winpr/wlog.h index 5c5bef56b..88e2f4a3c 100644 --- a/winpr/include/winpr/wlog.h +++ b/winpr/include/winpr/wlog.h @@ -317,27 +317,27 @@ WINPR_API DWORD WLog_GetLogLevel(wLog* log); WINPR_API void WLog_SetLogLevel(wLog* log, DWORD logLevel); WINPR_API wLogAppender* WLog_GetLogAppender(wLog* log); -WINPR_API void WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType); +WINPR_API BOOL WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType); WINPR_API int WLog_OpenAppender(wLog* log); WINPR_API int WLog_CloseAppender(wLog* log); WINPR_API void WLog_ConsoleAppender_SetOutputStream(wLog* log, wLogConsoleAppender* appender, int outputStream); -WINPR_API void WLog_FileAppender_SetOutputFileName(wLog* log, wLogFileAppender* appender, const char* filename); -WINPR_API void WLog_FileAppender_SetOutputFilePath(wLog* log, wLogFileAppender* appender, const char* filepath); +WINPR_API BOOL WLog_FileAppender_SetOutputFileName(wLog* log, wLogFileAppender* appender, const char* filename); +WINPR_API BOOL WLog_FileAppender_SetOutputFilePath(wLog* log, wLogFileAppender* appender, const char* filepath); WINPR_API void WLog_CallbackAppender_SetCallbacks(wLog* log, wLogCallbackAppender* appender, CallbackAppenderMessage_t msg, CallbackAppenderImage_t img, CallbackAppenderPackage_t pkg, CallbackAppenderData_t data); WINPR_API wLogLayout* WLog_GetLogLayout(wLog* log); -WINPR_API void WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format); +WINPR_API BOOL WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format); WINPR_API wLog* WLog_GetRoot(void); WINPR_API wLog* WLog_Get(LPCSTR name); -WINPR_API void WLog_Init(void); +WINPR_API BOOL WLog_Init(void); WINPR_API void WLog_Uninit(void); #ifdef __cplusplus diff --git a/winpr/libwinpr/asn1/asn1.c b/winpr/libwinpr/asn1/asn1.c index 966934a6c..2b981b24b 100644 --- a/winpr/libwinpr/asn1/asn1.c +++ b/winpr/libwinpr/asn1/asn1.c @@ -73,11 +73,10 @@ ASN1error_e ASN1_CreateEncoder(ASN1module_t pModule, ASN1encoding_t* ppEncoderIn if (pModule && ppEncoderInfo) { *ppEncoderInfo = 0; - encoder = (ASN1encoding_t) malloc(sizeof(struct ASN1encoding_s)); + encoder = (ASN1encoding_t) calloc(1, sizeof(struct ASN1encoding_s)); if (encoder) { - ZeroMemory(encoder, sizeof(struct ASN1encoding_s)); encoder->magic = 0x44434E45; encoder->err = ASN1_SUCCESS; encoder->dwFlags = pModule->dwFlags; @@ -118,7 +117,8 @@ LABEL_ENCODER_COMPLETE: { //if (ASN1BEREncCheck(encoder, 1)) { - *encoder->buf = 0; + if (encoder->buf) + *encoder->buf = 0; LABEL_SET_BUFFER: if (pParent) pParent[1].version = (ASN1uint32_t) encoder; diff --git a/winpr/libwinpr/clipboard/clipboard.c b/winpr/libwinpr/clipboard/clipboard.c index e363e7692..01a75503b 100644 --- a/winpr/libwinpr/clipboard/clipboard.c +++ b/winpr/libwinpr/clipboard/clipboard.c @@ -364,16 +364,24 @@ BOOL ClipboardInitFormats(wClipboard* clipboard) if (!clipboard) return FALSE; - for (formatId = 0; formatId < CF_MAX; formatId++) + for (formatId = 0; formatId < CF_MAX; formatId++, clipboard->numFormats++) { - format = &(clipboard->formats[clipboard->numFormats++]); + format = &(clipboard->formats[clipboard->numFormats]); ZeroMemory(format, sizeof(wClipboardFormat)); format->formatId = formatId; format->formatName = _strdup(CF_STANDARD_STRINGS[formatId]); if (!format->formatName) + { + int i; + for (i = formatId-1; i >= 0; --i) + { + format = &(clipboard->formats[--clipboard->numFormats]); + free((void *)format->formatName); + } return FALSE; + } } ClipboardInitSynthesizers(clipboard); @@ -511,7 +519,11 @@ wClipboard* ClipboardCreate() clipboard->nextFormatId = 0xC000; clipboard->sequenceNumber = 0; - InitializeCriticalSectionAndSpinCount(&(clipboard->lock), 4000); + if (!InitializeCriticalSectionAndSpinCount(&(clipboard->lock), 4000)) + { + free(clipboard); + return NULL; + } clipboard->numFormats = 0; clipboard->maxFormats = 64; @@ -519,11 +531,17 @@ wClipboard* ClipboardCreate() if (!clipboard->formats) { + DeleteCriticalSection(&(clipboard->lock)); free(clipboard); return NULL; } - ClipboardInitFormats(clipboard); + if(!ClipboardInitFormats(clipboard)) + { + DeleteCriticalSection(&(clipboard->lock)); + free(clipboard); + return NULL; + } } return clipboard; diff --git a/winpr/libwinpr/clipboard/synthetic.c b/winpr/libwinpr/clipboard/synthetic.c index 0fb12da68..f7c6782b8 100644 --- a/winpr/libwinpr/clipboard/synthetic.c +++ b/winpr/libwinpr/clipboard/synthetic.c @@ -381,7 +381,7 @@ static void* clipboard_synthesize_html_format(wClipboard* clipboard, UINT32 form body = strstr(pSrcData, ""); /* StartFragment */ - sprintf_s(num, sizeof(num), "%010lu", strlen(pDstData)); + sprintf_s(num, sizeof(num), "%010lu", (unsigned long int)strlen(pDstData)); CopyMemory(&pDstData[69], num, 10); strcat(pDstData, pSrcData); /* EndFragment */ - sprintf_s(num, sizeof(num), "%010lu", strlen(pDstData)); + sprintf_s(num, sizeof(num), "%010lu", (unsigned long int)strlen(pDstData)); CopyMemory(&pDstData[93], num, 10); strcat(pDstData, ""); @@ -403,7 +403,7 @@ static void* clipboard_synthesize_html_format(wClipboard* clipboard, UINT32 form strcat(pDstData, ""); /* EndHTML */ - sprintf_s(num, sizeof(num), "%010lu", strlen(pDstData)); + sprintf_s(num, sizeof(num), "%010lu", (unsigned long int)strlen(pDstData)); CopyMemory(&pDstData[43], num, 10); *pSize = (UINT32) strlen(pDstData) + 1; diff --git a/winpr/libwinpr/clipboard/test/TestClipboardFormats.c b/winpr/libwinpr/clipboard/test/TestClipboardFormats.c index 2242bcd2a..474eb37e1 100644 --- a/winpr/libwinpr/clipboard/test/TestClipboardFormats.c +++ b/winpr/libwinpr/clipboard/test/TestClipboardFormats.c @@ -42,6 +42,11 @@ int TestClipboardFormats(int argc, char* argv[]) char* pDstData; pSrcData = _strdup("this is a test string"); + if (!pSrcData) + { + fprintf(stderr, "Memory allocation failed\n"); + return -1; + } SrcSize = (UINT32) (strlen(pSrcData) + 1); bSuccess = ClipboardSetData(clipboard, utf8StringFormatId, (void*) pSrcData, SrcSize); diff --git a/winpr/libwinpr/comm/comm.c b/winpr/libwinpr/comm/comm.c index 3376ee8a1..5f84e04bb 100644 --- a/winpr/libwinpr/comm/comm.c +++ b/winpr/libwinpr/comm/comm.c @@ -41,6 +41,7 @@ #include #include #include +#include #include "comm_ioctl.h" @@ -1221,7 +1222,7 @@ BOOL IsCommDevice(LPCTSTR lpDeviceName) void _comm_setServerSerialDriver(HANDLE hComm, SERIAL_DRIVER_ID driverId) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_COMM* pComm; if (!CommInitialized()) @@ -1344,7 +1345,7 @@ HANDLE CommCreateFileA(LPCSTR lpDeviceName, DWORD dwDesiredAccess, DWORD dwShare return INVALID_HANDLE_VALUE; } - WINPR_HANDLE_SET_TYPE(pComm, HANDLE_TYPE_COMM); + WINPR_HANDLE_SET_TYPE_AND_MODE(pComm, HANDLE_TYPE_COMM, WINPR_FD_READ); pComm->ops = &ops; diff --git a/winpr/libwinpr/crt/conversion.c b/winpr/libwinpr/crt/conversion.c index fb1d3d4ab..c2d19ae99 100644 --- a/winpr/libwinpr/crt/conversion.c +++ b/winpr/libwinpr/crt/conversion.c @@ -22,6 +22,7 @@ #endif #include +#include /* Data Conversion: http://msdn.microsoft.com/en-us/library/0heszx3w/ */ @@ -31,12 +32,12 @@ errno_t _itoa_s(int value, char* buffer, size_t sizeInCharacters, int radix) { int length; - length = snprintf(NULL, 0, "%d", value); + length = sprintf_s(NULL, 0, "%d", value); if (sizeInCharacters < length) return -1; - snprintf(buffer, length + 1, "%d", value); + sprintf_s(buffer, length + 1, "%d", value); return 0; } diff --git a/winpr/libwinpr/crypto/cert.c b/winpr/libwinpr/crypto/cert.c index b2df52b5e..820e2507f 100644 --- a/winpr/libwinpr/crypto/cert.c +++ b/winpr/libwinpr/crypto/cert.c @@ -161,12 +161,10 @@ HCERTSTORE CertOpenStore(LPCSTR lpszStoreProvider, DWORD dwMsgAndCertEncodingTyp { WINPR_CERTSTORE* certstore; - certstore = (WINPR_CERTSTORE*) malloc(sizeof(WINPR_CERTSTORE)); + certstore = (WINPR_CERTSTORE*) calloc(1, sizeof(WINPR_CERTSTORE)); if (certstore) { - ZeroMemory(certstore, sizeof(WINPR_CERTSTORE)); - certstore->lpszStoreProvider = lpszStoreProvider; certstore->dwMsgAndCertEncodingType = dwMsgAndCertEncodingType; } diff --git a/winpr/libwinpr/file/file.c b/winpr/libwinpr/file/file.c index 291ee23e0..c154df6f3 100644 --- a/winpr/libwinpr/file/file.c +++ b/winpr/libwinpr/file/file.c @@ -42,6 +42,7 @@ #include "../log.h" #define TAG WINPR_TAG("file") +#include /** * api-ms-win-core-file-l1-2-0.dll: @@ -414,7 +415,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, } hNamedPipe = (HANDLE) pNamedPipe; - WINPR_HANDLE_SET_TYPE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE); + WINPR_HANDLE_SET_TYPE_AND_MODE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE, WINPR_FD_READ); pNamedPipe->name = _strdup(lpFileName); if (!pNamedPipe->name) { @@ -502,7 +503,6 @@ BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { ULONG Type; - PVOID Object; WINPR_HANDLE *handle; if (hFile == INVALID_HANDLE_VALUE) @@ -516,12 +516,12 @@ BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, if (!lpNumberOfBytesRead && !lpOverlapped) return FALSE; - if (!winpr_Handle_GetInfo(hFile, &Type, &Object)) + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) return FALSE; handle = (WINPR_HANDLE *)hFile; if (handle->ops->ReadFile) - return handle->ops->ReadFile(Object, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); + return handle->ops->ReadFile(handle, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); WLog_ERR(TAG, "ReadFile operation not implemented"); return FALSE; @@ -543,18 +543,17 @@ BOOL WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { ULONG Type; - PVOID Object; WINPR_HANDLE *handle; if (hFile == INVALID_HANDLE_VALUE) return FALSE; - if (!winpr_Handle_GetInfo(hFile, &Type, &Object)) + if (!winpr_Handle_GetInfo(hFile, &Type, &handle)) return FALSE; handle = (WINPR_HANDLE *)hFile; if (handle->ops->WriteFile) - return handle->ops->WriteFile(Object, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); + return handle->ops->WriteFile(handle, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); WLog_ERR(TAG, "ReadFile operation not implemented"); return FALSE; diff --git a/winpr/libwinpr/file/test/TestFileFindFirstFile.c b/winpr/libwinpr/file/test/TestFileFindFirstFile.c index 9b6922db5..917cf3930 100644 --- a/winpr/libwinpr/file/test/TestFileFindFirstFile.c +++ b/winpr/libwinpr/file/test/TestFileFindFirstFile.c @@ -31,6 +31,11 @@ int TestFileFindFirstFile(int argc, char* argv[]) BasePath[length] = 0; #else BasePath = _strdup(str); + if (!BasePath) + { + printf("Unable to allocate memory\n"); + return -1; + } length = strlen(BasePath); #endif diff --git a/winpr/libwinpr/file/test/TestFileFindNextFile.c b/winpr/libwinpr/file/test/TestFileFindNextFile.c index cc8dd2a88..23b9fcc80 100644 --- a/winpr/libwinpr/file/test/TestFileFindNextFile.c +++ b/winpr/libwinpr/file/test/TestFileFindNextFile.c @@ -33,6 +33,11 @@ int TestFileFindNextFile(int argc, char* argv[]) BasePath[length] = 0; #else BasePath = _strdup(str); + if (!BasePath) + { + printf("Unable to allocate memory"); + return -1; + } length = strlen(BasePath); #endif diff --git a/winpr/libwinpr/handle/handle.c b/winpr/libwinpr/handle/handle.c index 5cc5e4178..b57dacd95 100644 --- a/winpr/libwinpr/handle/handle.c +++ b/winpr/libwinpr/handle/handle.c @@ -48,7 +48,7 @@ BOOL CloseHandle(HANDLE hObject) ULONG Type; WINPR_HANDLE *Object; - if (!winpr_Handle_GetInfo(hObject, &Type, (PVOID*) &Object)) + if (!winpr_Handle_GetInfo(hObject, &Type, &Object)) return FALSE; if (!Object) diff --git a/winpr/libwinpr/handle/handle.h b/winpr/libwinpr/handle/handle.h index faaea58dd..728cd8160 100644 --- a/winpr/libwinpr/handle/handle.h +++ b/winpr/libwinpr/handle/handle.h @@ -23,6 +23,7 @@ #include #include #include +#include #define HANDLE_TYPE_NONE 0 #define HANDLE_TYPE_PROCESS 1 @@ -41,6 +42,7 @@ #define WINPR_HANDLE_DEF() \ ULONG Type; \ + ULONG Mode; \ HANDLE_OPS *ops typedef BOOL (*pcIsHandled)(HANDLE handle); @@ -68,10 +70,16 @@ struct winpr_handle }; typedef struct winpr_handle WINPR_HANDLE; -#define WINPR_HANDLE_SET_TYPE(_handle, _type) \ - _handle->Type = _type +static INLINE void WINPR_HANDLE_SET_TYPE_AND_MODE(void* _handle, + ULONG _type, ULONG _mode) +{ + WINPR_HANDLE* hdl = (WINPR_HANDLE*)_handle; -static INLINE BOOL winpr_Handle_GetInfo(HANDLE handle, ULONG* pType, PVOID* pObject) + hdl->Type = _type; + hdl->Mode = _mode; +} + +static INLINE BOOL winpr_Handle_GetInfo(HANDLE handle, ULONG* pType, WINPR_HANDLE** pObject) { WINPR_HANDLE* wHandle; @@ -91,7 +99,7 @@ static INLINE int winpr_Handle_getFd(HANDLE handle) WINPR_HANDLE *hdl; ULONG type; - if (!winpr_Handle_GetInfo(handle, &type, (PVOID*)&hdl)) + if (!winpr_Handle_GetInfo(handle, &type, &hdl)) return -1; if (!hdl || !hdl->ops->GetFd) @@ -105,7 +113,7 @@ static INLINE DWORD winpr_Handle_cleanup(HANDLE handle) WINPR_HANDLE *hdl; ULONG type; - if (!winpr_Handle_GetInfo(handle, &type, (PVOID*)&hdl)) + if (!winpr_Handle_GetInfo(handle, &type, &hdl)) return WAIT_FAILED; if (!hdl) diff --git a/winpr/libwinpr/io/device.c b/winpr/libwinpr/io/device.c index 6e26ccaf7..0e13092d7 100644 --- a/winpr/libwinpr/io/device.c +++ b/winpr/libwinpr/io/device.c @@ -30,6 +30,7 @@ #include #include #include +#include #ifdef HAVE_UNISTD_H #include @@ -95,13 +96,21 @@ char* GetDeviceFileUnixDomainSocketBaseFilePathA() char* GetDeviceFileUnixDomainSocketFilePathA(LPCSTR lpName) { - char* lpPipePath; - char* lpFileName; - char* lpFilePath; + char* lpPipePath = NULL; + char* lpFileName = NULL; + char* lpFilePath = NULL; lpPipePath = GetDeviceFileUnixDomainSocketBaseFilePathA(); + if (!lpPipePath) + return NULL; lpFileName = GetDeviceFileNameWithoutPrefixA(lpName); + if (!lpFileName) + { + free(lpFilePath); + return NULL; + } + lpFilePath = GetCombinedPath(lpPipePath, (char*) lpFileName); free(lpPipePath); @@ -124,6 +133,9 @@ NTSTATUS _IoCreateDeviceEx(PDRIVER_OBJECT_EX DriverObject, ULONG DeviceExtension DeviceBasePath = GetDeviceFileUnixDomainSocketBaseFilePathA(); + if (!DeviceBasePath) + return STATUS_NO_MEMORY; + if (!PathFileExistsA(DeviceBasePath)) { if (!mkdir(DeviceBasePath, S_IRUSR | S_IWUSR | S_IXUSR)) @@ -132,26 +144,63 @@ NTSTATUS _IoCreateDeviceEx(PDRIVER_OBJECT_EX DriverObject, ULONG DeviceExtension return STATUS_ACCESS_DENIED; } } + free(DeviceBasePath); - pDeviceObjectEx = (DEVICE_OBJECT_EX*) malloc(sizeof(DEVICE_OBJECT_EX)); + pDeviceObjectEx = (DEVICE_OBJECT_EX*) calloc(1, sizeof(DEVICE_OBJECT_EX)); if (!pDeviceObjectEx) + return STATUS_NO_MEMORY; + + ConvertFromUnicode(CP_UTF8, 0, DeviceName->Buffer, DeviceName->Length / 2, &(pDeviceObjectEx->DeviceName), 0, NULL, NULL); + if (!pDeviceObjectEx->DeviceName) { + free(pDeviceObjectEx); return STATUS_NO_MEMORY; } - ZeroMemory(pDeviceObjectEx, sizeof(DEVICE_OBJECT_EX)); - - ConvertFromUnicode(CP_UTF8, 0, DeviceName->Buffer, DeviceName->Length / 2, &(pDeviceObjectEx->DeviceName), 0, NULL, NULL); - pDeviceObjectEx->DeviceFileName = GetDeviceFileUnixDomainSocketFilePathA(pDeviceObjectEx->DeviceName); + if (!pDeviceObjectEx->DeviceFileName) + { + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx); + return STATUS_NO_MEMORY; + } if (PathFileExistsA(pDeviceObjectEx->DeviceFileName)) { - unlink(pDeviceObjectEx->DeviceFileName); + if (unlink(pDeviceObjectEx->DeviceFileName) == -1) + { + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx->DeviceFileName); + free(pDeviceObjectEx); + return STATUS_ACCESS_DENIED; + } + } status = mkfifo(pDeviceObjectEx->DeviceFileName, 0666); + if (status != 0) + { + free(pDeviceObjectEx->DeviceName); + free(pDeviceObjectEx->DeviceFileName); + free(pDeviceObjectEx); + switch (errno) + { + case EACCES: + return STATUS_ACCESS_DENIED; + case EEXIST: + return STATUS_OBJECT_NAME_EXISTS; + case ENAMETOOLONG: + return STATUS_NAME_TOO_LONG; + case ENOENT: + case ENOTDIR: + return STATUS_NOT_A_DIRECTORY; + case ENOSPC: + return STATUS_DISK_FULL; + default: + return STATUS_INTERNAL_ERROR; + } + } *((ULONG_PTR*) (DeviceObject)) = (ULONG_PTR) pDeviceObjectEx; diff --git a/winpr/libwinpr/io/io.c b/winpr/libwinpr/io/io.c index 3fa4fc207..434032074 100644 --- a/winpr/libwinpr/io/io.c +++ b/winpr/libwinpr/io/io.c @@ -50,7 +50,7 @@ BOOL GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped, LPDWORD lpNumberOfBytesTransferred, BOOL bWait) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; if (!winpr_Handle_GetInfo(hFile, &Type, &Object)) return FALSE; diff --git a/winpr/libwinpr/io/test/TestIoDevice.c b/winpr/libwinpr/io/test/TestIoDevice.c index 97d8ea80e..d6feb633b 100644 --- a/winpr/libwinpr/io/test/TestIoDevice.c +++ b/winpr/libwinpr/io/test/TestIoDevice.c @@ -19,6 +19,9 @@ int TestIoDevice(int argc, char* argv[]) &uString, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); + if (NtStatus != STATUS_SUCCESS) + return -1; + _IoDeleteDeviceEx(pDeviceObject); _RtlFreeUnicodeString(&uString); diff --git a/winpr/libwinpr/library/test/TestLibraryFreeLibrary.c b/winpr/libwinpr/library/test/TestLibraryFreeLibrary.c index a1df01638..a90988449 100644 --- a/winpr/libwinpr/library/test/TestLibraryFreeLibrary.c +++ b/winpr/libwinpr/library/test/TestLibraryFreeLibrary.c @@ -29,6 +29,11 @@ int TestLibraryFreeLibrary(int argc, char* argv[]) BasePath[length] = 0; #else BasePath = _strdup(str); + if (!BasePath) + { + printf("Memory allocation failed"); + return -1; + } length = strlen(BasePath); #endif diff --git a/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c b/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c index 52e3f6d24..ff0303f0a 100644 --- a/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c +++ b/winpr/libwinpr/library/test/TestLibraryGetProcAddress.c @@ -34,6 +34,11 @@ int TestLibraryGetProcAddress(int argc, char* argv[]) BasePath[length] = 0; #else BasePath = _strdup(str); + if (!BasePath) + { + printf("Memory allocation failed"); + return -1; + } length = strlen(BasePath); #endif diff --git a/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c b/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c index 0b5cac353..9256a38d1 100644 --- a/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c +++ b/winpr/libwinpr/library/test/TestLibraryLoadLibrary.c @@ -29,6 +29,12 @@ int TestLibraryLoadLibrary(int argc, char* argv[]) BasePath[length] = 0; #else BasePath = _strdup(str); + if (!BasePath) + { + printf("Memory allocation failed"); + return -1; + } + length = strlen(BasePath); #endif diff --git a/winpr/libwinpr/nt/nt.c b/winpr/libwinpr/nt/nt.c index a3976f270..b45509ff0 100644 --- a/winpr/libwinpr/nt/nt.c +++ b/winpr/libwinpr/nt/nt.c @@ -84,12 +84,9 @@ PTEB NtCurrentTeb(void) { if ((teb = pthread_getspecific(_TebKey)) == NULL) { - teb = malloc(sizeof(TEB)); + teb = calloc(1, sizeof(TEB)); if (teb) - { - ZeroMemory(teb, sizeof(TEB)); pthread_setspecific(_TebKey, teb); - } } } return teb; diff --git a/winpr/libwinpr/path/shell.c b/winpr/libwinpr/path/shell.c index 69841a1c1..dd529863c 100644 --- a/winpr/libwinpr/path/shell.c +++ b/winpr/libwinpr/path/shell.c @@ -152,8 +152,8 @@ static char* GetPath_XDG_CONFIG_HOME(void) if (!path) return NULL; - if (SHGetFolderPathA(0, CSIDL_APPDATA, NULL, - SHGFP_TYPE_CURRENT, path) != S_OK) + if (FAILED(SHGetFolderPathA(0, CSIDL_APPDATA, NULL, + SHGFP_TYPE_CURRENT, path))) { free(path); return NULL; @@ -250,8 +250,8 @@ char* GetPath_XDG_RUNTIME_DIR(void) if (!path) return NULL; - if (SHGetFolderPathA(0, CSIDL_LOCAL_APPDATA, NULL, - SHGFP_TYPE_CURRENT, path) != S_OK) + if (FAILED(SHGetFolderPathA(0, CSIDL_LOCAL_APPDATA, NULL, + SHGFP_TYPE_CURRENT, path))) { free(path); return NULL; @@ -307,6 +307,7 @@ char* GetKnownPath(int id) case KNOWN_PATH_TEMP: path = GetPath_TEMP(); + break; case KNOWN_PATH_XDG_DATA_HOME: @@ -406,19 +407,39 @@ char* GetCombinedPath(const char* basePath, const char* subPath) CopyMemory(path, basePath, basePathLength); path[basePathLength] = '\0'; - PathCchConvertStyleA(path, basePathLength, PATH_STYLE_NATIVE); + if (FAILED(PathCchConvertStyleA(path, basePathLength, PATH_STYLE_NATIVE))) + { + free(path); + return NULL; + } if (!subPath) return path; subPathCpy = _strdup(subPath); - PathCchConvertStyleA(subPathCpy, subPathLength, PATH_STYLE_NATIVE); + if (!subPathCpy) + { + free(path); + return NULL; + } + if (FAILED(PathCchConvertStyleA(subPathCpy, subPathLength, PATH_STYLE_NATIVE))) + { + free(path); + free(subPathCpy); + return NULL; + } status = NativePathCchAppendA(path, length + 1, subPathCpy); free(subPathCpy); - return path; + if (FAILED(status)) + { + free(path); + return NULL; + } + else + return path; } BOOL PathMakePathA(LPCSTR path, LPSECURITY_ATTRIBUTES lpAttributes) diff --git a/winpr/libwinpr/path/test/TestPathShell.c b/winpr/libwinpr/path/test/TestPathShell.c index 9887a8adf..e311f1ba8 100644 --- a/winpr/libwinpr/path/test/TestPathShell.c +++ b/winpr/libwinpr/path/test/TestPathShell.c @@ -10,24 +10,38 @@ int TestPathShell(int argc, char* argv[]) char* path; path = GetKnownPath(KNOWN_PATH_HOME); + if (!path) + return -1; printf("KNOWN_PATH_HOME: %s\n", path); path = GetKnownPath(KNOWN_PATH_TEMP); + if (!path) + return -1; printf("KNOWN_PATH_TEMP: %s\n", path); path = GetKnownPath(KNOWN_PATH_XDG_DATA_HOME); + if (!path) + return -1; printf("KNOWN_PATH_DATA: %s\n", path); path = GetKnownPath(KNOWN_PATH_XDG_CONFIG_HOME); + if (!path) + return -1; printf("KNOWN_PATH_CONFIG: %s\n", path); path = GetKnownPath(KNOWN_PATH_XDG_CACHE_HOME); + if (!path) + return -1; printf("KNOWN_PATH_CACHE: %s\n", path); path = GetKnownPath(KNOWN_PATH_XDG_RUNTIME_DIR); + if (!path) + return -1; printf("KNOWN_PATH_RUNTIME: %s\n", path); path = GetKnownSubPath(KNOWN_PATH_XDG_CONFIG_HOME, "freerdp"); + if (!path) + return -1; printf("KNOWN_PATH_CONFIG SubPath: %s\n", path); return 0; diff --git a/winpr/libwinpr/pipe/pipe.c b/winpr/libwinpr/pipe/pipe.c index aaab49c53..28d9eede3 100644 --- a/winpr/libwinpr/pipe/pipe.c +++ b/winpr/libwinpr/pipe/pipe.c @@ -454,11 +454,11 @@ BOOL CreatePipe(PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpP pReadPipe->fd = pipe_fd[0]; pWritePipe->fd = pipe_fd[1]; - WINPR_HANDLE_SET_TYPE(pReadPipe, HANDLE_TYPE_ANONYMOUS_PIPE); + WINPR_HANDLE_SET_TYPE_AND_MODE(pReadPipe, HANDLE_TYPE_ANONYMOUS_PIPE, WINPR_FD_READ); pReadPipe->ops = &ops; *((ULONG_PTR*) hReadPipe) = (ULONG_PTR) pReadPipe; - WINPR_HANDLE_SET_TYPE(pWritePipe, HANDLE_TYPE_ANONYMOUS_PIPE); + WINPR_HANDLE_SET_TYPE_AND_MODE(pWritePipe, HANDLE_TYPE_ANONYMOUS_PIPE, WINPR_FD_READ); pWritePipe->ops = &ops; *((ULONG_PTR*) hWritePipe) = (ULONG_PTR) pWritePipe; return TRUE; @@ -531,7 +531,7 @@ HANDLE CreateNamedPipeA(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD if (!pNamedPipe) return INVALID_HANDLE_VALUE; - WINPR_HANDLE_SET_TYPE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE); + WINPR_HANDLE_SET_TYPE_AND_MODE(pNamedPipe, HANDLE_TYPE_NAMED_PIPE, WINPR_FD_READ); pNamedPipe->serverfd = -1; pNamedPipe->clientfd = -1; diff --git a/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c b/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c index c9e7b2bc9..abb1800b1 100644 --- a/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c +++ b/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipe.c @@ -135,7 +135,7 @@ static void* named_pipe_server_thread(void* arg) goto out; } - if (!(lpReadBuffer = (BYTE*) malloc(PIPE_BUFFER_SIZE))) + if (!(lpReadBuffer = (BYTE*) calloc(1, PIPE_BUFFER_SIZE))) { printf("%s: Error allocating read buffer\n", __FUNCTION__); goto out; @@ -149,7 +149,6 @@ static void* named_pipe_server_thread(void* arg) lpNumberOfBytesRead = 0; nNumberOfBytesToRead = PIPE_BUFFER_SIZE; - ZeroMemory(lpReadBuffer, PIPE_BUFFER_SIZE); if (!ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, &lpNumberOfBytesRead, NULL) || lpNumberOfBytesRead != nNumberOfBytesToRead) diff --git a/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c b/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c index 6bda1f35e..ecb8bdf5b 100644 --- a/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c +++ b/winpr/libwinpr/pipe/test/TestPipeCreateNamedPipeOverlapped.c @@ -19,28 +19,30 @@ static LPTSTR lpszPipeName = _T("\\\\.\\pipe\\winpr_test_pipe_overlapped"); static void* named_pipe_client_thread(void* arg) { DWORD status; - HANDLE hEvent; - HANDLE hNamedPipe; - BYTE* lpReadBuffer; - BYTE* lpWriteBuffer; + HANDLE hEvent = NULL; + HANDLE hNamedPipe = NULL; + BYTE* lpReadBuffer = NULL; + BYTE* lpWriteBuffer = NULL; BOOL fSuccess = FALSE; OVERLAPPED overlapped; DWORD nNumberOfBytesToRead; DWORD nNumberOfBytesToWrite; DWORD NumberOfBytesTransferred; + WaitForSingleObject(ReadyEvent, INFINITE); - hNamedPipe = CreateFile(lpszPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + hNamedPipe = CreateFile(lpszPipeName, GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (!hNamedPipe) { printf("Named Pipe CreateFile failure: NULL handle\n"); - return NULL; + goto finish; } if (hNamedPipe == INVALID_HANDLE_VALUE) { printf("Named Pipe CreateFile failure: INVALID_HANDLE_VALUE\n"); - return NULL; + goto finish; } lpReadBuffer = (BYTE*) malloc(PIPE_BUFFER_SIZE); @@ -48,16 +50,14 @@ static void* named_pipe_client_thread(void* arg) if (!lpReadBuffer || !lpWriteBuffer) { printf("Error allocating memory\n"); - free(lpReadBuffer); - free(lpWriteBuffer); - return NULL; + goto finish; } ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!(hEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) { printf("CreateEvent failure: (%d)\n", GetLastError()); - return NULL; + goto finish; } overlapped.hEvent = hEvent; @@ -71,17 +71,14 @@ static void* named_pipe_client_thread(void* arg) if (!fSuccess) { printf("Client NamedPipe WriteFile failure: %d\n", GetLastError()); - free(lpReadBuffer); - free(lpWriteBuffer); - CloseHandle(hNamedPipe); - CloseHandle(hEvent); - return NULL; + goto finish; } status = WaitForMultipleObjects(1, &hEvent, FALSE, INFINITE); NumberOfBytesTransferred = 0; fSuccess = GetOverlappedResult(hNamedPipe, &overlapped, &NumberOfBytesTransferred, TRUE); - printf("Client GetOverlappedResult: fSuccess: %d NumberOfBytesTransferred: %d\n", fSuccess, NumberOfBytesTransferred); + printf("Client GetOverlappedResult: fSuccess: %d NumberOfBytesTransferred: %d\n", + fSuccess, NumberOfBytesTransferred); nNumberOfBytesToRead = PIPE_BUFFER_SIZE; ZeroMemory(lpReadBuffer, PIPE_BUFFER_SIZE); fSuccess = ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, NULL, &overlapped); @@ -92,23 +89,25 @@ static void* named_pipe_client_thread(void* arg) if (!fSuccess) { printf("Client NamedPipe ReadFile failure: %d\n", GetLastError()); - free(lpReadBuffer); - free(lpWriteBuffer); - CloseHandle(hNamedPipe); - CloseHandle(hEvent); - return NULL; + goto finish; } status = WaitForMultipleObjects(1, &hEvent, FALSE, INFINITE); NumberOfBytesTransferred = 0; fSuccess = GetOverlappedResult(hNamedPipe, &overlapped, &NumberOfBytesTransferred, TRUE); - printf("Client GetOverlappedResult: fSuccess: %d NumberOfBytesTransferred: %d\n", fSuccess, NumberOfBytesTransferred); + printf("Client GetOverlappedResult: fSuccess: %d NumberOfBytesTransferred: %d\n", + fSuccess, NumberOfBytesTransferred); printf("Client ReadFile (%d):\n", NumberOfBytesTransferred); winpr_HexDump("pipe.test", WLOG_DEBUG, lpReadBuffer, NumberOfBytesTransferred); + +finish: free(lpReadBuffer); free(lpWriteBuffer); - CloseHandle(hNamedPipe); - CloseHandle(hEvent); + if (hNamedPipe) + CloseHandle(hNamedPipe); + if (hEvent) + CloseHandle(hEvent); + return NULL; } @@ -170,7 +169,7 @@ static void* named_pipe_server_thread(void* arg) return NULL; } - lpReadBuffer = (BYTE*) malloc(PIPE_BUFFER_SIZE); + lpReadBuffer = (BYTE*) calloc(1, PIPE_BUFFER_SIZE); lpWriteBuffer = (BYTE*) malloc(PIPE_BUFFER_SIZE); if (!lpReadBuffer || !lpWriteBuffer) { @@ -180,7 +179,6 @@ static void* named_pipe_server_thread(void* arg) return NULL; } nNumberOfBytesToRead = PIPE_BUFFER_SIZE; - ZeroMemory(lpReadBuffer, PIPE_BUFFER_SIZE); fSuccess = ReadFile(hNamedPipe, lpReadBuffer, nNumberOfBytesToRead, NULL, &overlapped); if (!fSuccess) diff --git a/winpr/libwinpr/registry/registry_reg.c b/winpr/libwinpr/registry/registry_reg.c index 79e072011..3b4e00b28 100644 --- a/winpr/libwinpr/registry/registry_reg.c +++ b/winpr/libwinpr/registry/registry_reg.c @@ -169,6 +169,12 @@ static RegVal* reg_load_value(Reg* reg, RegKey* key) p[4] = strchr(data, '"'); p[4][0] = '\0'; value->data.string = _strdup(data); + if (!value->data.string) + { + free(value); + free(name); + return NULL; + } } else { @@ -226,6 +232,8 @@ static void reg_insert_key(Reg* reg, RegKey* key, RegKey* subkey) char* save; int length; path = _strdup(subkey->name); + if (!path) + return; name = strtok_s(path, "\\", &save); while (name != NULL) @@ -235,6 +243,12 @@ static void reg_insert_key(Reg* reg, RegKey* key, RegKey* subkey) length = strlen(name); name += length + 1; subkey->subname = _strdup(name); + /* TODO: free allocated memory in error case */ + if (!subkey->subname) + { + free(path); + return; + } } name = strtok_s(NULL, "\\", &save); diff --git a/winpr/libwinpr/shell/shell.c b/winpr/libwinpr/shell/shell.c index ebe90189c..bcbf5b04b 100644 --- a/winpr/libwinpr/shell/shell.c +++ b/winpr/libwinpr/shell/shell.c @@ -78,6 +78,7 @@ BOOL GetUserProfileDirectoryA(HANDLE hToken, LPSTR lpProfileDir, LPDWORD lpcchSi if ((status != 0) || !pw) { SetLastError(ERROR_INVALID_PARAMETER); + free (buf); return FALSE; } diff --git a/winpr/libwinpr/smartcard/smartcard_pcsc.c b/winpr/libwinpr/smartcard/smartcard_pcsc.c index cd98f9b3b..61c5160b3 100644 --- a/winpr/libwinpr/smartcard/smartcard_pcsc.c +++ b/winpr/libwinpr/smartcard/smartcard_pcsc.c @@ -651,7 +651,7 @@ BOOL PCSC_AddReaderNameAlias(char* namePCSC, char* nameWinSCard) reader = (PCSC_READER*) calloc(1, sizeof(PCSC_READER)); if (!reader) - goto error_reader; + return FALSE; reader->namePCSC = _strdup(namePCSC); if (!reader->namePCSC) @@ -670,9 +670,7 @@ error_nameWinSCard: free(reader->namePCSC); error_namePSC: free(reader); -error_reader: return FALSE; - } static int PCSC_AtoiWithLength(const char* str, int length) diff --git a/winpr/libwinpr/sspi/NTLM/ntlm.c b/winpr/libwinpr/sspi/NTLM/ntlm.c index b6f7085a6..3dcaed6ae 100644 --- a/winpr/libwinpr/sspi/NTLM/ntlm.c +++ b/winpr/libwinpr/sspi/NTLM/ntlm.c @@ -33,6 +33,7 @@ #include #include #include +#include #include "ntlm.h" #include "../sspi.h" @@ -42,27 +43,25 @@ #include "../../log.h" #define TAG WINPR_TAG("sspi.NTLM") +#define WINPR_KEY "Software\\"FREERDP_VENDOR_STRING \ + "\\"FREERDP_PRODUCT_STRING"\\WinPR\\NTLM" + char* NTLM_PACKAGE_NAME = "NTLM"; int ntlm_SetContextWorkstation(NTLM_CONTEXT* context, char* Workstation) { int status; - DWORD nSize = 0; + DWORD nSize = MAX_COMPUTERNAME_LENGTH; char* ws = Workstation; + CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1]; if (!Workstation) { - GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize); - ws = (char*) malloc(nSize); - + if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize)) + return -1; + ws = _strdup(computerName); if (!ws) return -1; - - if (!GetComputerNameExA(ComputerNameNetBIOS, ws, &nSize)) - { - free(ws); - return 0; - } } context->Workstation.Buffer = NULL; @@ -114,26 +113,21 @@ int ntlm_SetContextServicePrincipalNameA(NTLM_CONTEXT* context, char* ServicePri int ntlm_SetContextTargetName(NTLM_CONTEXT* context, char* TargetName) { int status; - DWORD nSize = 0; + CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD nSize = MAX_COMPUTERNAME_LENGTH; char* name = TargetName; - if (!TargetName) + if (!name) { - if (!GetComputerNameExA(ComputerNameDnsHostname, NULL, &nSize)) + + if (!GetComputerNameExA(ComputerNameDnsHostname, computerName, &nSize)) return -1; - name = (char*) malloc(nSize); - + name = _strdup(computerName); if (!name) return -1; - if (!GetComputerNameExA(ComputerNameDnsHostname, name, &nSize)) - { - free(name); - return -1; - } - - CharUpperA(TargetName); + CharUpperA(name); } context->TargetName.pvBuffer = NULL; @@ -141,7 +135,8 @@ int ntlm_SetContextTargetName(NTLM_CONTEXT* context, char* TargetName) if (status <= 0) { - free(TargetName); + if (!TargetName) + free(name); return -1; } @@ -173,7 +168,7 @@ NTLM_CONTEXT* ntlm_ContextNew() context->SendWorkstationName = TRUE; context->NegotiateKeyExchange = TRUE; context->UseSamFileDatabase = TRUE; - status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\WinPR\\NTLM"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); + status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, WINPR_KEY, 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { diff --git a/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c b/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c index 190c28931..8a5f89066 100644 --- a/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c +++ b/winpr/libwinpr/sspi/NTLM/ntlm_av_pairs.c @@ -29,6 +29,7 @@ #include #include #include +#include #include "ntlm_compute.h" @@ -171,14 +172,14 @@ int ntlm_get_target_computer_name(PUNICODE_STRING pName, COMPUTER_NAME_FORMAT ty { char* name; int status; - DWORD nSize = 0; - GetComputerNameExA(type, NULL, &nSize); - name = (char*) malloc(nSize); + CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD nSize = MAX_COMPUTERNAME_LENGTH; - if (!name) + if (!GetComputerNameExA(type, computerName, &nSize)) return -1; - if (!GetComputerNameExA(type, name, &nSize)) + name = _strdup(computerName); + if (!name) return -1; if (type == ComputerNameNetBIOS) @@ -187,7 +188,10 @@ int ntlm_get_target_computer_name(PUNICODE_STRING pName, COMPUTER_NAME_FORMAT ty status = ConvertToUnicode(CP_UTF8, 0, name, -1, &pName->Buffer, 0); if (status <= 0) + { + free(name); return status; + } pName->Length = (USHORT)((status - 1) * 2); pName->MaximumLength = pName->Length; diff --git a/winpr/libwinpr/sspi/Schannel/schannel.c b/winpr/libwinpr/sspi/Schannel/schannel.c index 352a057c5..e52526cec 100644 --- a/winpr/libwinpr/sspi/Schannel/schannel.c +++ b/winpr/libwinpr/sspi/Schannel/schannel.c @@ -34,13 +34,15 @@ SCHANNEL_CONTEXT* schannel_ContextNew() { SCHANNEL_CONTEXT* context; - context = (SCHANNEL_CONTEXT*) malloc(sizeof(SCHANNEL_CONTEXT)); + context = (SCHANNEL_CONTEXT*) calloc(1, sizeof(SCHANNEL_CONTEXT)); + if (!context) + return NULL; - if (context != NULL) + context->openssl = schannel_openssl_new(); + if (!context->openssl) { - ZeroMemory(context, sizeof(SCHANNEL_CONTEXT)); - - context->openssl = schannel_openssl_new(); + free(context); + return NULL; } return context; @@ -60,12 +62,7 @@ SCHANNEL_CREDENTIALS* schannel_CredentialsNew() { SCHANNEL_CREDENTIALS* credentials; - credentials = (SCHANNEL_CREDENTIALS*) malloc(sizeof(SCHANNEL_CREDENTIALS)); - - if (credentials != NULL) - { - ZeroMemory(credentials, sizeof(SCHANNEL_CREDENTIALS)); - } + credentials = (SCHANNEL_CREDENTIALS*) calloc(1, sizeof(SCHANNEL_CREDENTIALS)); return credentials; } diff --git a/winpr/libwinpr/sspi/sspi.c b/winpr/libwinpr/sspi/sspi.c index e2d495a25..bcc8fd841 100644 --- a/winpr/libwinpr/sspi/sspi.c +++ b/winpr/libwinpr/sspi/sspi.c @@ -35,15 +35,21 @@ static wLog* g_Log = NULL; static BOOL g_Initialized = FALSE; +#if defined(WITH_NATIVE_SSPI) static HMODULE g_SspiModule = NULL; +#endif static SecurityFunctionTableW* g_SspiW = NULL; static SecurityFunctionTableA* g_SspiA = NULL; -SecurityFunctionTableA sspi_SecurityFunctionTableA; -SecurityFunctionTableW sspi_SecurityFunctionTableW; +#if defined(WITH_NATIVE_SSPI) +static BOOL ShouldUseNativeSspi(void); +static BOOL InitializeSspiModule_Native(void); +#endif +static void InitializeSspiModule(DWORD flags); -BOOL ShouldUseNativeSspi() +#if defined(WITH_NATIVE_SSPI) +BOOL ShouldUseNativeSspi(void) { BOOL status = FALSE; #ifdef _WIN32 @@ -69,7 +75,9 @@ BOOL ShouldUseNativeSspi() #endif return status; } +#endif +#if defined(WITH_NATIVE_SSPI) BOOL InitializeSspiModule_Native(void) { INIT_SECURITY_INTERFACE_W pInitSecurityInterfaceW; @@ -94,6 +102,7 @@ BOOL InitializeSspiModule_Native(void) return TRUE; } +#endif void InitializeSspiModule(DWORD flags) { @@ -108,6 +117,7 @@ void InitializeSspiModule(DWORD flags) g_Log = WLog_Get("com.winpr.sspi"); +#if defined(WITH_NATIVE_SSPI) if (flags && (flags & SSPI_INTERFACE_NATIVE)) { status = InitializeSspiModule_Native(); @@ -123,6 +133,7 @@ void InitializeSspiModule(DWORD flags) { status = InitializeSspiModule_Native(); } +#endif if (!status) { @@ -315,7 +326,7 @@ SecurityFunctionTableW* SEC_ENTRY InitSecurityInterfaceExW(DWORD flags) WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceExW"); - return &sspi_SecurityFunctionTableW; + return g_SspiW; } SecurityFunctionTableA* SEC_ENTRY InitSecurityInterfaceExA(DWORD flags) @@ -325,7 +336,7 @@ SecurityFunctionTableA* SEC_ENTRY InitSecurityInterfaceExA(DWORD flags) WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceExA"); - return &sspi_SecurityFunctionTableA; + return g_SspiA; } /** @@ -375,7 +386,7 @@ SecurityFunctionTableW* SEC_ENTRY sspi_InitSecurityInterfaceW(void) WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceW"); - return &sspi_SecurityFunctionTableW; + return g_SspiW; } SecurityFunctionTableA* SEC_ENTRY sspi_InitSecurityInterfaceA(void) @@ -385,7 +396,7 @@ SecurityFunctionTableA* SEC_ENTRY sspi_InitSecurityInterfaceA(void) WLog_Print(g_Log, WLOG_DEBUG, "InitSecurityInterfaceA"); - return &sspi_SecurityFunctionTableA; + return g_SspiA; } SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityPackageInfoW(SEC_WCHAR* pszPackageName, PSecPkgInfoW* ppPackageInfo) @@ -425,8 +436,8 @@ SECURITY_STATUS SEC_ENTRY sspi_QuerySecurityPackageInfoA(SEC_CHAR* pszPackageNam /* Credential Management */ SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleW(SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, - ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, - void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry) + ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, + void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry) { SECURITY_STATUS status; @@ -437,7 +448,7 @@ SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleW(SEC_WCHAR* pszPrincipal return SEC_E_UNSUPPORTED_FUNCTION; status = g_SspiW->AcquireCredentialsHandleW(pszPrincipal, pszPackage, fCredentialUse, - pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); + pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); WLog_Print(g_Log, WLOG_DEBUG, "AcquireCredentialsHandleW: %s (0x%04X)", GetSecurityStatusString(status), status); @@ -445,8 +456,8 @@ SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleW(SEC_WCHAR* pszPrincipal } SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleA(SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, - ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, - void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry) + ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, + void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry) { SECURITY_STATUS status; @@ -457,7 +468,7 @@ SECURITY_STATUS SEC_ENTRY sspi_AcquireCredentialsHandleA(SEC_CHAR* pszPrincipal, return SEC_E_UNSUPPORTED_FUNCTION; status = g_SspiA->AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse, - pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); + pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); WLog_Print(g_Log, WLOG_DEBUG, "AcquireCredentialsHandleA: %s (0x%04X)", GetSecurityStatusString(status), status); @@ -569,8 +580,8 @@ SECURITY_STATUS SEC_ENTRY sspi_QueryCredentialsAttributesA(PCredHandle phCredent /* Context Management */ SECURITY_STATUS SEC_ENTRY sspi_AcceptSecurityContext(PCredHandle phCredential, PCtxtHandle phContext, - PSecBufferDesc pInput, ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, - PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp) + PSecBufferDesc pInput, ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp) { SECURITY_STATUS status; @@ -581,7 +592,7 @@ SECURITY_STATUS SEC_ENTRY sspi_AcceptSecurityContext(PCredHandle phCredential, P return SEC_E_UNSUPPORTED_FUNCTION; status = g_SspiW->AcceptSecurityContext(phCredential, phContext, pInput, fContextReq, - TargetDataRep, phNewContext, pOutput, pfContextAttr, ptsTimeStamp); + TargetDataRep, phNewContext, pOutput, pfContextAttr, ptsTimeStamp); WLog_Print(g_Log, WLOG_DEBUG, "AcceptSecurityContext: %s (0x%04X)", GetSecurityStatusString(status), status); @@ -674,9 +685,9 @@ SECURITY_STATUS SEC_ENTRY sspi_ImpersonateSecurityContext(PCtxtHandle phContext) } SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextW(PCredHandle phCredential, PCtxtHandle phContext, - SEC_WCHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, - PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, - PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) + SEC_WCHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, + PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) { SECURITY_STATUS status; @@ -687,8 +698,8 @@ SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextW(PCredHandle phCredenti return SEC_E_UNSUPPORTED_FUNCTION; status = g_SspiW->InitializeSecurityContextW(phCredential, phContext, - pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, - Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); + pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, + Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); WLog_Print(g_Log, WLOG_DEBUG, "InitializeSecurityContextW: %s (0x%04X)", GetSecurityStatusString(status), status); @@ -696,9 +707,9 @@ SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextW(PCredHandle phCredenti } SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextA(PCredHandle phCredential, PCtxtHandle phContext, - SEC_CHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, - PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, - PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) + SEC_CHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, + PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, + PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) { SECURITY_STATUS status; @@ -709,8 +720,8 @@ SECURITY_STATUS SEC_ENTRY sspi_InitializeSecurityContextA(PCredHandle phCredenti return SEC_E_UNSUPPORTED_FUNCTION; status = g_SspiA->InitializeSecurityContextA(phCredential, phContext, - pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, - Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); + pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, + Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); WLog_Print(g_Log, WLOG_DEBUG, "InitializeSecurityContextA: %s (0x%04X)", GetSecurityStatusString(status), status); diff --git a/winpr/libwinpr/sspi/sspi_winpr.c b/winpr/libwinpr/sspi/sspi_winpr.c index 70af02644..3b3618317 100644 --- a/winpr/libwinpr/sspi/sspi_winpr.c +++ b/winpr/libwinpr/sspi/sspi_winpr.c @@ -632,6 +632,11 @@ SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesA(ULONG* pcPackages, PS pPackageInfo[index].cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken; pPackageInfo[index].Name = _strdup(SecPkgInfoA_LIST[index]->Name); pPackageInfo[index].Comment = _strdup(SecPkgInfoA_LIST[index]->Comment); + if (!pPackageInfo[index].Name || !pPackageInfo[index].Comment) + { + sspi_ContextBufferFree(pPackageInfo); + return SEC_E_INSUFFICIENT_MEMORY; + } } *(pcPackages) = cPackages; @@ -729,6 +734,11 @@ SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoA(SEC_CHAR* pszPackageNa pPackageInfo->cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken; pPackageInfo->Name = _strdup(SecPkgInfoA_LIST[index]->Name); pPackageInfo->Comment = _strdup(SecPkgInfoA_LIST[index]->Comment); + if (!pPackageInfo->Name || !pPackageInfo->Comment) + { + sspi_ContextBufferFree(pPackageInfo); + return SEC_E_INSUFFICIENT_MEMORY; + } *(ppPackageInfo) = pPackageInfo; diff --git a/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c b/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c index e9d60ea3f..66ebacac7 100644 --- a/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c +++ b/winpr/libwinpr/sspi/test/TestAcquireCredentialsHandle.c @@ -22,11 +22,19 @@ int TestAcquireCredentialsHandle(int argc, char* argv[]) table = InitSecurityInterface(); identity.User = (UINT16*) _strdup(test_User); - identity.UserLength = sizeof(test_User); identity.Domain = (UINT16*) _strdup(test_Domain); - identity.DomainLength = sizeof(test_Domain); identity.Password = (UINT16*) _strdup(test_Password); - identity.PasswordLength = sizeof(test_Password); + if (!identity.User || !identity.Domain || !identity.Password) + { + free(identity.User); + free(identity.Domain); + free(identity.Password); + fprintf(stderr, "Memory allocation failed\n"); + return -1; + } + identity.UserLength = strlen(test_User); + identity.DomainLength = strlen(test_Domain); + identity.PasswordLength = strlen(test_Password); identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; status = table->AcquireCredentialsHandle(NULL, NTLMSP_NAME, diff --git a/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c b/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c index e250a36dc..1fe213f9f 100644 --- a/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c +++ b/winpr/libwinpr/sspi/test/TestInitializeSecurityContext.c @@ -40,11 +40,20 @@ int TestInitializeSecurityContext(int argc, char* argv[]) cbMaxLen = pPackageInfo->cbMaxToken; identity.User = (UINT16*) _strdup(test_User); - identity.UserLength = sizeof(test_User); identity.Domain = (UINT16*) _strdup(test_Domain); - identity.DomainLength = sizeof(test_Domain); identity.Password = (UINT16*) _strdup(test_Password); - identity.PasswordLength = sizeof(test_Password); + if (!identity.User || !identity.Domain || !identity.Password) + { + free(identity.User); + free(identity.Domain); + free(identity.Password); + fprintf(stderr, "Memory allocation failed\n"); + return -1; + } + + identity.UserLength = strlen(test_User); + identity.DomainLength = strlen(test_Domain); + identity.PasswordLength = strlen(test_Password); identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; status = table->AcquireCredentialsHandle(NULL, NTLMSP_NAME, diff --git a/winpr/libwinpr/sspi/test/TestSchannel.c b/winpr/libwinpr/sspi/test/TestSchannel.c index 61decbfc8..6ffbb70cc 100644 --- a/winpr/libwinpr/sspi/test/TestSchannel.c +++ b/winpr/libwinpr/sspi/test/TestSchannel.c @@ -240,10 +240,9 @@ int schannel_send(PSecurityFunctionTable table, HANDLE hPipe, PCtxtHandle phCont ZeroMemory(&StreamSizes, sizeof(SecPkgContext_StreamSizes)); status = table->QueryContextAttributes(phContext, SECPKG_ATTR_STREAM_SIZES, &StreamSizes); ioBufferLength = StreamSizes.cbHeader + StreamSizes.cbMaximumMessage + StreamSizes.cbTrailer; - ioBuffer = (BYTE*) malloc(ioBufferLength); + ioBuffer = (BYTE*) calloc(1, ioBufferLength); if (!ioBuffer) return -1; - ZeroMemory(ioBuffer, ioBufferLength); pMessageBuffer = ioBuffer + StreamSizes.cbHeader; CopyMemory(pMessageBuffer, buffer, length); Buffers[0].pvBuffer = ioBuffer; @@ -298,10 +297,9 @@ int schannel_recv(PSecurityFunctionTable table, HANDLE hPipe, PCtxtHandle phCont ZeroMemory(&StreamSizes, sizeof(SecPkgContext_StreamSizes)); status = table->QueryContextAttributes(phContext, SECPKG_ATTR_STREAM_SIZES, &StreamSizes); ioBufferLength = StreamSizes.cbHeader + StreamSizes.cbMaximumMessage + StreamSizes.cbTrailer; - ioBuffer = (BYTE*) malloc(ioBufferLength); + ioBuffer = (BYTE*) calloc(1, ioBufferLength); if (!ioBuffer) return -1; - ZeroMemory(ioBuffer, ioBufferLength); if (!ReadFile(hPipe, ioBuffer, ioBufferLength, &NumberOfBytesRead, NULL)) { @@ -551,34 +549,42 @@ static void* schannel_test_server_thread(void* arg) int dump_test_certificate_files() { FILE* fp; - char* fullpath; + char* fullpath = NULL; + int ret = -1; + /* * Output Certificate File */ fullpath = GetCombinedPath("/tmp", "localhost.crt"); - fp = fopen(fullpath, "w+"); + if (!fullpath) + return -1; + fp = fopen(fullpath, "w+"); if (fp) { - fwrite((void*) test_localhost_crt, sizeof(test_localhost_crt), 1, fp); + if (fwrite((void*) test_localhost_crt, sizeof(test_localhost_crt), 1, fp) != 1) + goto out_fail; fclose(fp); + fp = NULL; } - free(fullpath); + /* * Output Private Key File */ fullpath = GetCombinedPath("/tmp", "localhost.key"); + if (!fullpath) + return -1; fp = fopen(fullpath, "w+"); + if (fp && fwrite((void*) test_localhost_key, sizeof(test_localhost_key), 1, fp) != 1) + goto out_fail; - if (fp) - { - fwrite((void*) test_localhost_key, sizeof(test_localhost_key), 1, fp); - fclose(fp); - } - + ret = 1; +out_fail: free(fullpath); - return 1; + if (fp) + fclose(fp); + return ret; } int TestSchannel(int argc, char* argv[]) diff --git a/winpr/libwinpr/sspicli/sspicli.c b/winpr/libwinpr/sspicli/sspicli.c index 1ea1c55c2..98017035f 100644 --- a/winpr/libwinpr/sspicli/sspicli.c +++ b/winpr/libwinpr/sspicli/sspicli.c @@ -131,14 +131,27 @@ BOOL LogonUserA(LPCSTR lpszUsername, LPCSTR lpszDomain, LPCSTR lpszPassword, if (!token) return FALSE; - WINPR_HANDLE_SET_TYPE(token, HANDLE_TYPE_ACCESS_TOKEN); + WINPR_HANDLE_SET_TYPE_AND_MODE(token, HANDLE_TYPE_ACCESS_TOKEN, WINPR_FD_READ); token->ops = &ops; token->Username = _strdup(lpszUsername); + if (!token->Username) + { + free(token); + return FALSE; + } if (lpszDomain) + { token->Domain = _strdup(lpszDomain); + if (!token->Domain) + { + free(token->Username); + free(token); + return FALSE; + } + } pw = getpwnam(lpszUsername); diff --git a/winpr/libwinpr/synch/barrier.c b/winpr/libwinpr/synch/barrier.c index f8d75cb5d..225df0837 100644 --- a/winpr/libwinpr/synch/barrier.c +++ b/winpr/libwinpr/synch/barrier.c @@ -145,6 +145,8 @@ BOOL WINAPI EnterSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier, DWO status = TRUE; } + InterlockedDecrement(&(pBarrier->count)); + return status; } @@ -165,6 +167,9 @@ BOOL WINAPI DeleteSynchronizationBarrier(LPSYNCHRONIZATION_BARRIER lpBarrier) if (!pBarrier) return TRUE; + while (InterlockedCompareExchange(&pBarrier->count, 0, 0) != 0) + Sleep(100); + CloseHandle(pBarrier->event); free(pBarrier); diff --git a/winpr/libwinpr/synch/event.c b/winpr/libwinpr/synch/event.c index 0157c652b..8ebed7eb6 100644 --- a/winpr/libwinpr/synch/event.c +++ b/winpr/libwinpr/synch/event.c @@ -78,23 +78,22 @@ BOOL EventCloseHandle(HANDLE handle) { if (!EventIsHandled(handle)) return FALSE; - if (!event->bAttached) - { - if (event->pipe_fd[0] != -1) - { - close(event->pipe_fd[0]); - event->pipe_fd[0] = -1; - } + if (!event->bAttached) + { + if (event->pipe_fd[0] != -1) + { + close(event->pipe_fd[0]); + event->pipe_fd[0] = -1; + } + if (event->pipe_fd[1] != -1) + { + close(event->pipe_fd[1]); + event->pipe_fd[1] = -1; + } + } - if (event->pipe_fd[1] != -1) - { - close(event->pipe_fd[1]); - event->pipe_fd[1] = -1; - } - } - - free(event); - return TRUE; + free(event); + return TRUE; } static HANDLE_OPS ops = { @@ -114,7 +113,7 @@ HANDLE CreateEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, event->bAttached = FALSE; event->bManualReset = bManualReset; event->ops = &ops; - WINPR_HANDLE_SET_TYPE(event, HANDLE_TYPE_EVENT); + WINPR_HANDLE_SET_TYPE_AND_MODE(event, HANDLE_TYPE_EVENT, FD_READ); if (!event->bManualReset) { @@ -200,7 +199,7 @@ static int eventfd_write(int fd, eventfd_t value) BOOL SetEvent(HANDLE hEvent) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; int length; BOOL status; WINPR_EVENT* event; @@ -241,7 +240,7 @@ BOOL SetEvent(HANDLE hEvent) BOOL ResetEvent(HANDLE hEvent) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; int length; BOOL status = TRUE; WINPR_EVENT* event; @@ -274,7 +273,9 @@ BOOL ResetEvent(HANDLE hEvent) #endif -HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, int FileDescriptor) +HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, + BOOL bManualReset, BOOL bInitialState, + int FileDescriptor, ULONG mode) { #ifndef _WIN32 WINPR_EVENT* event; @@ -288,7 +289,7 @@ HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL event->pipe_fd[0] = FileDescriptor; event->pipe_fd[1] = -1; event->ops = &ops; - WINPR_HANDLE_SET_TYPE(event, HANDLE_TYPE_EVENT); + WINPR_HANDLE_SET_TYPE_AND_MODE(event, HANDLE_TYPE_EVENT, mode); handle = (HANDLE) event; } @@ -298,9 +299,12 @@ HANDLE CreateFileDescriptorEventW(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL #endif } -HANDLE CreateFileDescriptorEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, int FileDescriptor) +HANDLE CreateFileDescriptorEventA(LPSECURITY_ATTRIBUTES lpEventAttributes, + BOOL bManualReset, BOOL bInitialState, + int FileDescriptor, ULONG mode) { - return CreateFileDescriptorEventW(lpEventAttributes, bManualReset, bInitialState, FileDescriptor); + return CreateFileDescriptorEventW(lpEventAttributes, bManualReset, + bInitialState, FileDescriptor, mode); } /** @@ -310,7 +314,8 @@ HANDLE CreateWaitObjectEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, void* pObject) { #ifndef _WIN32 - return CreateFileDescriptorEventW(lpEventAttributes, bManualReset, bInitialState, (int)(ULONG_PTR) pObject); + return CreateFileDescriptorEventW(lpEventAttributes, bManualReset, + bInitialState, (int)(ULONG_PTR) pObject, WINPR_FD_READ); #else HANDLE hEvent = NULL; DuplicateHandle(GetCurrentProcess(), pObject, GetCurrentProcess(), &hEvent, 0, FALSE, DUPLICATE_SAME_ACCESS); @@ -327,7 +332,7 @@ int GetEventFileDescriptor(HANDLE hEvent) { #ifndef _WIN32 ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_EVENT* event; if (!winpr_Handle_GetInfo(hEvent, &Type, &Object)) @@ -360,17 +365,19 @@ int GetEventFileDescriptor(HANDLE hEvent) * This file descriptor is not usable on Windows */ -int SetEventFileDescriptor(HANDLE hEvent, int FileDescriptor) +int SetEventFileDescriptor(HANDLE hEvent, int FileDescriptor, ULONG mode) { #ifndef _WIN32 ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_EVENT* event; if (!winpr_Handle_GetInfo(hEvent, &Type, &Object)) return -1; event = (WINPR_EVENT*) Object; + event->bAttached = TRUE; + event->Mode = mode; event->pipe_fd[0] = FileDescriptor; return 0; #else diff --git a/winpr/libwinpr/synch/mutex.c b/winpr/libwinpr/synch/mutex.c index 8591d9b6b..a6de42fa3 100644 --- a/winpr/libwinpr/synch/mutex.c +++ b/winpr/libwinpr/synch/mutex.c @@ -73,6 +73,8 @@ BOOL MutexCloseHandle(HANDLE handle) rc = pthread_mutex_trylock(&mutex->mutex); switch(rc) { + case 0: /* The mutex is now locked. */ + break; /* If we already own the mutex consider it a success. */ case EDEADLK: case EBUSY: @@ -138,7 +140,7 @@ HANDLE CreateMutexW(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, { pthread_mutex_init(&mutex->mutex, 0); - WINPR_HANDLE_SET_TYPE(mutex, HANDLE_TYPE_MUTEX); + WINPR_HANDLE_SET_TYPE_AND_MODE(mutex, HANDLE_TYPE_MUTEX, WINPR_FD_READ); mutex->ops = &ops; handle = (HANDLE) mutex; @@ -178,7 +180,7 @@ HANDLE OpenMutexW(DWORD dwDesiredAccess, BOOL bInheritHandle,LPCWSTR lpName) BOOL ReleaseMutex(HANDLE hMutex) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_MUTEX* mutex; if (!winpr_Handle_GetInfo(hMutex, &Type, &Object)) diff --git a/winpr/libwinpr/synch/semaphore.c b/winpr/libwinpr/synch/semaphore.c index d1fb5f9d0..ba7bb275b 100644 --- a/winpr/libwinpr/synch/semaphore.c +++ b/winpr/libwinpr/synch/semaphore.c @@ -179,7 +179,7 @@ HANDLE CreateSemaphoreW(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lIniti #endif } - WINPR_HANDLE_SET_TYPE(semaphore, HANDLE_TYPE_SEMAPHORE); + WINPR_HANDLE_SET_TYPE_AND_MODE(semaphore, HANDLE_TYPE_SEMAPHORE, WINPR_FD_READ); handle = (HANDLE) semaphore; return handle; } @@ -204,7 +204,7 @@ HANDLE OpenSemaphoreA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) BOOL ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_SEMAPHORE* semaphore; if (!winpr_Handle_GetInfo(hSemaphore, &Type, &Object)) diff --git a/winpr/libwinpr/synch/test/TestSynchBarrier.c b/winpr/libwinpr/synch/test/TestSynchBarrier.c index 9f804eea0..9a7529e74 100644 --- a/winpr/libwinpr/synch/test/TestSynchBarrier.c +++ b/winpr/libwinpr/synch/test/TestSynchBarrier.c @@ -3,6 +3,8 @@ #include #include +#include "../synch.h" + static int g_Count; static HANDLE g_Event; static CRITICAL_SECTION g_Lock; @@ -29,10 +31,19 @@ static void* test_synch_barrier_thread_func(void* arg) return NULL; } +static void* barrier_deleter_thread_func(void* arg) +{ + /* Blocks until all threads are released from the barrier. */ + DeleteSynchronizationBarrier(&g_Barrier); + + return NULL; +} + int TestSynchBarrier(int argc, char* argv[]) { int index; HANDLE threads[5]; + HANDLE deleter_thread = NULL; g_Count = 0; @@ -65,10 +76,30 @@ int TestSynchBarrier(int argc, char* argv[]) printf("%s: CreateThread failed for thread #%d. GetLastError() = 0x%08x\n", __FUNCTION__, index, GetLastError()); while (index) CloseHandle(threads[--index]); + CloseHandle(deleter_thread); DeleteCriticalSection(&g_Lock); CloseHandle(g_Event); return -1; } + + if (index == 0) + { + /* Make sure first thread has already entered the barrier... */ + while (((WINPR_BARRIER*) g_Barrier.Reserved3[0])->count == 0) + Sleep(100); + + /* Now spawn the deleter thread. */ + if (!(deleter_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) + barrier_deleter_thread_func, NULL, 0, NULL))) + { + printf("%s: CreateThread failed for deleter thread. GetLastError() = 0x%08x\n", __FUNCTION__, GetLastError()); + while (index) + CloseHandle(threads[--index]); + DeleteCriticalSection(&g_Lock); + CloseHandle(g_Event); + return -1; + } + } } WaitForSingleObject(g_Event, INFINITE); @@ -83,7 +114,7 @@ int TestSynchBarrier(int argc, char* argv[]) CloseHandle(threads[index]); } - DeleteSynchronizationBarrier(&g_Barrier); + CloseHandle(deleter_thread); DeleteCriticalSection(&g_Lock); diff --git a/winpr/libwinpr/synch/timer.c b/winpr/libwinpr/synch/timer.c index a488a16fc..17b1fb368 100644 --- a/winpr/libwinpr/synch/timer.c +++ b/winpr/libwinpr/synch/timer.c @@ -230,7 +230,7 @@ HANDLE CreateWaitableTimerA(LPSECURITY_ATTRIBUTES lpTimerAttributes, BOOL bManua timer = (WINPR_TIMER*) calloc(1, sizeof(WINPR_TIMER)); if (timer) { - WINPR_HANDLE_SET_TYPE(timer, HANDLE_TYPE_TIMER); + WINPR_HANDLE_SET_TYPE_AND_MODE(timer, HANDLE_TYPE_TIMER, WINPR_FD_READ); handle = (HANDLE) timer; timer->fd = -1; timer->lPeriod = 0; @@ -265,7 +265,7 @@ BOOL SetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPerio PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, BOOL fResume) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_TIMER* timer; #ifdef WITH_POSIX_TIMER LONGLONG seconds = 0; @@ -365,7 +365,7 @@ BOOL SetWaitableTimerEx(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPer PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, PREASON_CONTEXT WakeContext, ULONG TolerableDelay) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_TIMER* timer; if (!winpr_Handle_GetInfo(hTimer, &Type, &Object)) @@ -608,12 +608,11 @@ HANDLE CreateTimerQueue(void) { HANDLE handle = NULL; WINPR_TIMER_QUEUE* timerQueue; - timerQueue = (WINPR_TIMER_QUEUE*) malloc(sizeof(WINPR_TIMER_QUEUE)); + timerQueue = (WINPR_TIMER_QUEUE*) calloc(1, sizeof(WINPR_TIMER_QUEUE)); if (timerQueue) { - ZeroMemory(timerQueue, sizeof(WINPR_TIMER_QUEUE)); - WINPR_HANDLE_SET_TYPE(timerQueue, HANDLE_TYPE_TIMER_QUEUE); + WINPR_HANDLE_SET_TYPE_AND_MODE(timerQueue, HANDLE_TYPE_TIMER_QUEUE, WINPR_FD_READ); handle = (HANDLE) timerQueue; timerQueue->activeHead = NULL; timerQueue->inactiveHead = NULL; @@ -707,7 +706,7 @@ BOOL CreateTimerQueueTimer(PHANDLE phNewTimer, HANDLE TimerQueue, if (!timer) return FALSE; - WINPR_HANDLE_SET_TYPE(timer, HANDLE_TYPE_TIMER_QUEUE_TIMER); + WINPR_HANDLE_SET_TYPE_AND_MODE(timer, HANDLE_TYPE_TIMER_QUEUE_TIMER, WINPR_FD_READ); *((UINT_PTR*) phNewTimer) = (UINT_PTR)(HANDLE) timer; timespec_copy(&(timer->StartTime), &CurrentTime); timespec_add_ms(&(timer->StartTime), DueTime); diff --git a/winpr/libwinpr/synch/wait.c b/winpr/libwinpr/synch/wait.c index 9a33487dc..8c0b8f22d 100644 --- a/winpr/libwinpr/synch/wait.c +++ b/winpr/libwinpr/synch/wait.c @@ -44,6 +44,7 @@ #include "synch.h" #include "../thread/thread.h" #include +#include #include "../log.h" #define TAG WINPR_TAG("sync.wait") @@ -132,6 +133,19 @@ static int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec } #endif +#ifdef HAVE_POLL_H +static DWORD handle_mode_to_pollevent(ULONG mode) +{ + DWORD event = 0; + if (mode & WINPR_FD_READ) + event |= POLLIN; + if (mode & WINPR_FD_WRITE) + event |= POLLOUT; + + return event; +} +#endif + static void ts_add_ms(struct timespec *ts, DWORD dwMilliseconds) { ts->tv_sec += dwMilliseconds / 1000L; @@ -140,13 +154,13 @@ static void ts_add_ms(struct timespec *ts, DWORD dwMilliseconds) ts->tv_nsec = ts->tv_nsec % 1000000000L; } -static int waitOnFd(int fd, DWORD dwMilliseconds) +static int waitOnFd(int fd, ULONG mode, DWORD dwMilliseconds) { int status; #ifdef HAVE_POLL_H struct pollfd pollfds; pollfds.fd = fd; - pollfds.events = POLLIN; + pollfds.events = handle_mode_to_pollevent(mode); pollfds.revents = 0; do @@ -157,11 +171,21 @@ static int waitOnFd(int fd, DWORD dwMilliseconds) #else struct timeval timeout; - fd_set rfds; + fd_set rfds, wfds; + fd_set* prfds = NULL; + fd_set* pwfds = NULL; + fd_set* pefds = NULL; FD_ZERO(&rfds); FD_SET(fd, &rfds); + FD_ZERO(&wfds); + FD_SET(fd, &wfds); ZeroMemory(&timeout, sizeof(timeout)); + if (mode & WINPR_FD_READ) + prfds = &rfds; + if (mode & WINPR_FD_WRITE) + pwfds = &wfds; + if ((dwMilliseconds != INFINITE) && (dwMilliseconds != 0)) { timeout.tv_sec = dwMilliseconds / 1000; @@ -170,7 +194,7 @@ static int waitOnFd(int fd, DWORD dwMilliseconds) do { - status = select(fd + 1, &rfds, NULL, NULL, (dwMilliseconds == INFINITE) ? NULL : &timeout); + status = select(fd + 1, prfds, pwfds, pefds, (dwMilliseconds == INFINITE) ? NULL : &timeout); } while (status < 0 && (errno == EINTR)); @@ -181,7 +205,7 @@ static int waitOnFd(int fd, DWORD dwMilliseconds) DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; if (!winpr_Handle_GetInfo(hHandle, &Type, &Object)) { @@ -194,7 +218,7 @@ DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) WINPR_PROCESS *process; process = (WINPR_PROCESS *) Object; - if (waitpid(process->pid, &(process->status), 0) != -1) + if (process->pid != waitpid(process->pid, &(process->status), 0)) { WLog_ERR(TAG, "waitpid failure [%d] %s", errno, strerror(errno)); return WAIT_FAILED; @@ -233,7 +257,7 @@ DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) if (fd < 0) return WAIT_FAILED; - status = waitOnFd(fd, dwMilliseconds); + status = waitOnFd(fd, Object->Mode, dwMilliseconds); if (status < 0) { @@ -270,12 +294,14 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl int index; int status; ULONG Type; - PVOID Object; + BOOL signal_handled = FALSE; + WINPR_HANDLE* Object; #ifdef HAVE_POLL_H struct pollfd *pollfds; #else int maxfd; - fd_set fds; + fd_set rfds; + fd_set wfds; struct timeval timeout; #endif @@ -300,14 +326,18 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl do { +#ifndef HAVE_POLL_H + fd_set* prfds = NULL; + fd_set* pwfds = NULL; + maxfd = 0; + + FD_ZERO(&rfds); + FD_ZERO(&wfds); + ZeroMemory(&timeout, sizeof(timeout)); +#endif if (bWaitAll && (dwMilliseconds != INFINITE)) clock_gettime(CLOCK_MONOTONIC, &starttime); -#ifndef HAVE_POLL_H - maxfd = 0; - FD_ZERO(&fds); - ZeroMemory(&timeout, sizeof(timeout)); -#endif polled = 0; for (index = 0; index < nCount; index++) @@ -336,10 +366,16 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl #ifdef HAVE_POLL_H pollfds[polled].fd = fd; - pollfds[polled].events = POLLIN; + pollfds[polled].events = handle_mode_to_pollevent(Object->Mode); pollfds[polled].revents = 0; #else - FD_SET(fd, &fds); + FD_SET(fd, &rfds); + FD_SET(fd, &wfds); + + if (Object->Mode & WINPR_FD_READ) + prfds = &rfds; + if (Object->Mode & WINPR_FD_WRITE) + pwfds = &wfds; if (fd > maxfd) maxfd = fd; @@ -366,8 +402,8 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl do { - status = select(maxfd + 1, &fds, 0, 0, - (dwMilliseconds == INFINITE) ? NULL : &timeout); + status = select(maxfd + 1, prfds, pwfds, 0, + (dwMilliseconds == INFINITE) ? NULL : &timeout); } while (status < 0 && errno == EINTR); @@ -376,12 +412,13 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl if (status < 0) { #ifdef HAVE_POLL_H - WLog_ERR(TAG, "poll() failure [%d] %s", errno, + WLog_ERR(TAG, "poll() handle %d (%d) failure [%d] %s", index, nCount, errno, strerror(errno)); #else - WLog_ERR(TAG, "select() failure [%d] %s", errno, + WLog_ERR(TAG, "select() handle %d (%d) failure [%d] %s", index, nCount, errno, strerror(errno)); #endif + winpr_log_backtrace(TAG, WLOG_ERROR, 20); return WAIT_FAILED; } @@ -399,9 +436,11 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl dwMilliseconds -= (diff / 1000); } + signal_handled = FALSE; for (index = 0; index < polled; index++) { DWORD idx; + BOOL signal_set = FALSE; if (bWaitAll) idx = poll_map[index]; @@ -423,11 +462,14 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl } #ifdef HAVE_POLL_H - - if (pollfds[index].revents & POLLIN) + signal_set = pollfds[index].revents & pollfds[index].events; #else - if (FD_ISSET(fd, &fds)) + if (Object->Mode & WINPR_FD_READ) + signal_set = FD_ISSET(fd, &rfds); + if (Object->Mode & WINPR_FD_WRITE) + signal_set = FD_ISSET(fd, &wfds); #endif + if (signal_set) { DWORD rc = winpr_Handle_cleanup(lpHandles[idx]); if (rc != WAIT_OBJECT_0) @@ -450,10 +492,12 @@ DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAl if (bWaitAll && (signalled >= nCount)) return (WAIT_OBJECT_0); + + signal_handled = TRUE; } } } - while (bWaitAll); + while (bWaitAll || !signal_handled); WLog_ERR(TAG, "failed (unknown error)"); return WAIT_FAILED; diff --git a/winpr/libwinpr/sysinfo/sysinfo.c b/winpr/libwinpr/sysinfo/sysinfo.c index 8c7234b32..7f1dfd25d 100644 --- a/winpr/libwinpr/sysinfo/sysinfo.c +++ b/winpr/libwinpr/sysinfo/sysinfo.c @@ -188,17 +188,20 @@ BOOL GetComputerNameA(LPSTR lpBuffer, LPDWORD lpnSize) if (dot) length = dot - hostname; - if (*lpnSize <= length) - { - *lpnSize = length + 1; - return FALSE; - } - if (!lpBuffer) return FALSE; + if (*lpnSize <= length) + { + SetLastError(ERROR_BUFFER_OVERFLOW); + *lpnSize = length; + return FALSE; + } + + CopyMemory(lpBuffer, hostname, length); lpBuffer[length] = '\0'; + *lpnSize = length; return TRUE; } @@ -224,7 +227,7 @@ BOOL GetComputerNameExA(COMPUTER_NAME_FORMAT NameType, LPSTR lpBuffer, LPDWORD l case ComputerNamePhysicalDnsFullyQualified: if (*lpnSize <= length) { - *lpnSize = length + 1; + *lpnSize = length; return FALSE; } diff --git a/winpr/libwinpr/thread/process.c b/winpr/libwinpr/thread/process.c index fb1729f6e..4dca0f4d0 100644 --- a/winpr/libwinpr/thread/process.c +++ b/winpr/libwinpr/thread/process.c @@ -80,6 +80,14 @@ #include "../handle/handle.h" #include "../security/security.h" +#ifndef NSIG +#ifdef SIGMAX +#define NSIG SIGMAX +#else +#define NSIG 64 +#endif +#endif + char** EnvironmentBlockToEnvpA(LPCH lpszEnvironmentBlock) { char* p; @@ -210,6 +218,9 @@ BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags, WINPR_ACCESS_TOKEN* token; LPTCH lpszEnvironmentBlock; BOOL ret = FALSE; + sigset_t oldSigMask; + sigset_t newSigMask; + BOOL restoreSigMask = FALSE; pid = 0; numArgs = 0; @@ -230,7 +241,7 @@ BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags, else { lpszEnvironmentBlock = GetEnvironmentStrings(); - if (lpszEnvironmentBlock) + if (!lpszEnvironmentBlock) goto finish; envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock); } @@ -241,6 +252,10 @@ BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags, if (NULL == filename) goto finish; + /* block all signals so that the child can safely reset the caller's handlers */ + sigfillset(&newSigMask); + restoreSigMask = !pthread_sigmask(SIG_SETMASK, &newSigMask, &oldSigMask); + /* fork and exec */ pid = fork(); @@ -254,16 +269,33 @@ BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags, if (pid == 0) { /* child process */ +#ifndef __sun + int maxfd; +#endif + int fd; + int sig; + sigset_t set; + struct sigaction act; + + /* set default signal handlers */ + memset(&act, 0, sizeof(act)); + act.sa_handler = SIG_DFL; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + for (sig = 1; sig < NSIG; sig++) + sigaction(sig, &act, NULL); + /* unblock all signals */ + sigfillset(&set); + pthread_sigmask(SIG_UNBLOCK, &set, NULL); + #ifdef __sun closefrom(3); #else - int maxfd; #ifdef F_MAXFD // on some BSD derivates maxfd = fcntl(0, F_MAXFD); #else maxfd = sysconf(_SC_OPEN_MAX); #endif - int fd; for(fd=3; fdUserId) setuid((uid_t) token->UserId); - /* TODO: add better cwd handling and error checking */ - if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0) - chdir(lpCurrentDirectory); } + /* TODO: add better cwd handling and error checking */ + if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0) + chdir(lpCurrentDirectory); + if (execve(filename, pArgs, envp) < 0) { /* execve failed - end the process */ @@ -324,6 +357,12 @@ BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags, ret = TRUE; finish: + + /* restore caller's original signal mask */ + if (restoreSigMask) + pthread_sigmask(SIG_SETMASK, &oldSigMask, NULL); + + free(filename); if (pArgs) diff --git a/winpr/libwinpr/thread/test/TestThreadExitThread.c b/winpr/libwinpr/thread/test/TestThreadExitThread.c index 9b372769a..2376bd124 100644 --- a/winpr/libwinpr/thread/test/TestThreadExitThread.c +++ b/winpr/libwinpr/thread/test/TestThreadExitThread.c @@ -14,7 +14,7 @@ static void* thread_func(void* arg) int TestThreadExitThread(int argc, char* argv[]) { HANDLE thread; - QWORD waitResult; + DWORD waitResult; int i; /* FIXME: create some noise to better guaranty the test validity and diff --git a/winpr/libwinpr/thread/thread.c b/winpr/libwinpr/thread/thread.c index e327b1e56..9ddbc6702 100644 --- a/winpr/libwinpr/thread/thread.c +++ b/winpr/libwinpr/thread/thread.c @@ -431,7 +431,7 @@ HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize goto error_thread_ready; } - WINPR_HANDLE_SET_TYPE(thread, HANDLE_TYPE_THREAD); + WINPR_HANDLE_SET_TYPE_AND_MODE(thread, HANDLE_TYPE_THREAD, WINPR_FD_READ); handle = (HANDLE) thread; if (!thread_list) @@ -613,7 +613,7 @@ VOID ExitThread(DWORD dwExitCode) BOOL GetExitCodeThread(HANDLE hThread, LPDWORD lpExitCode) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_THREAD* thread; if (!winpr_Handle_GetInfo(hThread, &Type, &Object)) @@ -665,8 +665,8 @@ DWORD GetCurrentThreadId(VOID) DWORD ResumeThread(HANDLE hThread) { ULONG Type; - PVOID Object; - WINPR_THREAD *thread; + WINPR_HANDLE* Object; + WINPR_THREAD* thread; if (!winpr_Handle_GetInfo(hThread, &Type, &Object)) return 0; @@ -697,7 +697,7 @@ BOOL SwitchToThread(VOID) BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode) { ULONG Type; - PVOID Object; + WINPR_HANDLE* Object; WINPR_THREAD* thread; if (!winpr_Handle_GetInfo(hThread, &Type, &Object)) diff --git a/winpr/libwinpr/utils/collections/LinkedList.c b/winpr/libwinpr/utils/collections/LinkedList.c index 939e85189..aafb32514 100644 --- a/winpr/libwinpr/utils/collections/LinkedList.c +++ b/winpr/libwinpr/utils/collections/LinkedList.c @@ -323,16 +323,7 @@ wLinkedList* LinkedList_New() { wLinkedList* list = NULL; - list = (wLinkedList*) malloc(sizeof(wLinkedList)); - - if (list) - { - list->count = 0; - list->initial = 0; - list->head = NULL; - list->tail = NULL; - list->current = NULL; - } + list = (wLinkedList*) calloc(1, sizeof(wLinkedList)); return list; } diff --git a/winpr/libwinpr/utils/collections/Reference.c b/winpr/libwinpr/utils/collections/Reference.c index 10a554294..0ca4e6a63 100644 --- a/winpr/libwinpr/utils/collections/Reference.c +++ b/winpr/libwinpr/utils/collections/Reference.c @@ -157,32 +157,39 @@ wReferenceTable* ReferenceTable_New(BOOL synchronized, void* context, REFERENCE_ { wReferenceTable* referenceTable; - referenceTable = (wReferenceTable*) malloc(sizeof(wReferenceTable)); + referenceTable = (wReferenceTable*) calloc(1, sizeof(wReferenceTable)); + if (!referenceTable) + return NULL; - if (referenceTable) - { - referenceTable->array = (wReference*) calloc(1, sizeof(wReference) * referenceTable->size); - if (!referenceTable->array) - { - free(referenceTable); - return NULL; - } - referenceTable->context = context; - referenceTable->ReferenceFree = ReferenceFree; + referenceTable->context = context; + referenceTable->ReferenceFree = ReferenceFree; - referenceTable->size = 32; + referenceTable->size = 32; - referenceTable->synchronized = synchronized; - InitializeCriticalSectionAndSpinCount(&referenceTable->lock, 4000); - } + referenceTable->array = (wReference*) calloc(referenceTable->size, sizeof(wReference)); + if (!referenceTable->array) + goto error_array; + + referenceTable->synchronized = synchronized; + if (synchronized && !InitializeCriticalSectionAndSpinCount(&referenceTable->lock, 4000)) + goto error_critical_section; return referenceTable; + +error_critical_section: + free(referenceTable->array); +error_array: + free(referenceTable); + return NULL; } void ReferenceTable_Free(wReferenceTable* referenceTable) { if (referenceTable) { + if (referenceTable->synchronized) + DeleteCriticalSection(&referenceTable->lock); + DeleteCriticalSection(&referenceTable->lock); free(referenceTable->array); free(referenceTable); diff --git a/winpr/libwinpr/utils/debug.c b/winpr/libwinpr/utils/debug.c index 09413d0a0..d90d1e021 100644 --- a/winpr/libwinpr/utils/debug.c +++ b/winpr/libwinpr/utils/debug.c @@ -24,6 +24,7 @@ #include #include +#include #if defined(HAVE_EXECINFO_H) #include @@ -394,10 +395,10 @@ char** winpr_backtrace_symbols(void* buffer, size_t* used) if (SymGetLineFromAddr64(process, address, &displacement, line)) { - _snprintf(vlines[i], line_len, "%08lX: %s in %s:%lu", symbol->Address, symbol->Name, line->FileName, line->LineNumber); + sprintf_s(vlines[i], line_len, "%08lX: %s in %s:%lu", symbol->Address, symbol->Name, line->FileName, line->LineNumber); } else - _snprintf(vlines[i], line_len, "%08lX: %s", symbol->Address, symbol->Name); + sprintf_s(vlines[i], line_len, "%08lX: %s", symbol->Address, symbol->Name); } if (used) @@ -434,7 +435,7 @@ void winpr_backtrace_symbols_fd(void* buffer, int fd) DWORD i; size_t used; char** lines; - + lines = winpr_backtrace_symbols(buffer, &used); if (lines) @@ -447,3 +448,26 @@ void winpr_backtrace_symbols_fd(void* buffer, int fd) LOGF(support_msg); #endif } + +void winpr_log_backtrace(const char* tag, DWORD level, DWORD size) +{ + size_t used, x; + char **msg; + void *stack = winpr_backtrace(20); + + if (!stack) + { + WLog_ERR(tag, "winpr_backtrace failed!\n"); + winpr_backtrace_free(stack); + return; + } + + msg = winpr_backtrace_symbols(stack, &used); + if (msg) + { + for (x=0; xdata), &width, &height, data, size); @@ -163,14 +164,16 @@ int winpr_image_bitmap_read_fp(wImage* image, FILE* fp) WINPR_BITMAP_FILE_HEADER bf; WINPR_BITMAP_INFO_HEADER bi; - fread((void*) &bf, sizeof(WINPR_BITMAP_FILE_HEADER), 1, fp); + if (fread((void*) &bf, sizeof(WINPR_BITMAP_FILE_HEADER), 1, fp) != 1) + return -1; if ((bf.bfType[0] != 'B') || (bf.bfType[1] != 'M')) return -1; image->type = WINPR_IMAGE_BITMAP; - fread((void*) &bi, sizeof(WINPR_BITMAP_INFO_HEADER), 1, fp); + if (fread((void*) &bi, sizeof(WINPR_BITMAP_INFO_HEADER), 1, fp) != 1) + return -1; if (ftell(fp) != bf.bfOffBits) { @@ -201,7 +204,12 @@ int winpr_image_bitmap_read_fp(wImage* image, FILE* fp) if (!vFlip) { - fread((void*) image->data, bi.biSizeImage, 1, fp); + if (fread((void*) image->data, bi.biSizeImage, 1, fp) != 1) + { + free(image->data); + image->data = NULL; + return -1; + } } else { @@ -209,13 +217,16 @@ int winpr_image_bitmap_read_fp(wImage* image, FILE* fp) for (index = 0; index < image->height; index++) { - fread((void*) pDstData, image->scanline, 1, fp); + if (fread((void*) pDstData, image->scanline, 1, fp) != 1) + { + free(image->data); + image->data = NULL; + return -1; + } pDstData -= image->scanline; } } - fclose(fp); - return 1; } @@ -302,8 +313,11 @@ int winpr_image_read(wImage* image, const char* filename) return -1; } - fread((void*) &sig, sizeof(sig), 1, fp); - fseek(fp, 0, SEEK_SET); + if (fread((void*) &sig, sizeof(sig), 1, fp) != 1 || fseek(fp, 0, SEEK_SET) < 0) + { + fclose(fp); + return -1; + } if ((sig[0] == 'B') && (sig[1] == 'M')) { @@ -316,10 +330,7 @@ int winpr_image_read(wImage* image, const char* filename) image->type = WINPR_IMAGE_PNG; status = winpr_image_png_read_fp(image, fp); } - else - { - fclose(fp); - } + fclose(fp); return status; } diff --git a/winpr/libwinpr/utils/ini.c b/winpr/libwinpr/utils/ini.c index f46e41d7b..09c0ee74c 100644 --- a/winpr/libwinpr/utils/ini.c +++ b/winpr/libwinpr/utils/ini.c @@ -77,28 +77,28 @@ int IniFile_Load_File(wIniFile* ini, const char* filename) if (IniFile_Open_File(ini, filename) < 0) return -1; - fseek(ini->fp, 0, SEEK_END); + if (fseek(ini->fp, 0, SEEK_END) < 0) + goto out_file; fileSize = ftell(ini->fp); - fseek(ini->fp, 0, SEEK_SET); + if (fileSize < 0) + goto out_file; + if (fseek(ini->fp, 0, SEEK_SET) < 0) + goto out_file; ini->line = NULL; ini->nextLine = NULL; ini->buffer = NULL; if (fileSize < 1) - return -1; + goto out_file; ini->buffer = (char*) malloc(fileSize + 2); if (!ini->buffer) - return -1; + goto out_file; if (fread(ini->buffer, fileSize, 1, ini->fp) != 1) - { - free(ini->buffer); - ini->buffer = NULL; - return -1; - } + goto out_buffer; fclose(ini->fp); ini->fp = NULL; @@ -107,8 +107,16 @@ int IniFile_Load_File(wIniFile* ini, const char* filename) ini->buffer[fileSize + 1] = '\0'; ini->nextLine = strtok(ini->buffer, "\n"); - + return 1; + +out_buffer: + free(ini->buffer); + ini->buffer = NULL; +out_file: + fclose(ini->fp); + ini->fp = NULL; + return -1; } void IniFile_Load_Finish(wIniFile* ini) @@ -151,6 +159,13 @@ wIniFileKey* IniFile_Key_New(const char* name, const char* value) { key->name = _strdup(name); key->value = _strdup(value); + if (!key->name || !key->value) + { + free(key->name); + free(key->value); + free(key); + return NULL; + } } return key; @@ -278,12 +293,9 @@ wIniFileKey* IniFile_AddKey(wIniFile* ini, wIniFileSection* section, const char* { wIniFileKey* key; - if (!section) + if (!section || !name) return NULL; - if (!name) - return NULL; - key = IniFile_GetKey(ini, section, name); if (!key) @@ -302,6 +314,8 @@ wIniFileKey* IniFile_AddKey(wIniFile* ini, wIniFileSection* section, const char* } key = IniFile_Key_New(name, value); + if (!key) + return NULL; section->keys[section->nKeys] = key; section->nKeys++; } @@ -309,6 +323,8 @@ wIniFileKey* IniFile_AddKey(wIniFile* ini, wIniFileSection* section, const char* { free(key->value); key->value = _strdup(value); + if (!key->value) + return NULL; } return key; @@ -375,7 +391,11 @@ int IniFile_Load(wIniFile* ini) value = beg; - IniFile_AddKey(ini, section, name, value); + if (!IniFile_AddKey(ini, section, name, value)) + { + return -1; + } + key = NULL; if (section && section->keys) key = section->keys[section->nKeys - 1]; @@ -412,6 +432,8 @@ int IniFile_ReadFile(wIniFile* ini, const char* filename) free(ini->filename); ini->filename = _strdup(filename); + if (!ini->filename) + return -1; status = IniFile_Load_File(ini, filename); @@ -657,6 +679,7 @@ int IniFile_WriteFile(wIniFile* ini, const char* filename) { int length; char* buffer; + int ret = 1; buffer = IniFile_WriteBuffer(ini); @@ -676,13 +699,14 @@ int IniFile_WriteFile(wIniFile* ini, const char* filename) return -1; } - fwrite((void*) buffer, length, 1, ini->fp); + if (fwrite((void*) buffer, length, 1, ini->fp) != 1) + ret = -1; fclose(ini->fp); free(buffer); - return 1; + return ret; } wIniFile* IniFile_New() diff --git a/winpr/libwinpr/utils/lodepng/lodepng.c b/winpr/libwinpr/utils/lodepng/lodepng.c index ed4bb1482..4af9f6d8c 100644 --- a/winpr/libwinpr/utils/lodepng/lodepng.c +++ b/winpr/libwinpr/utils/lodepng/lodepng.c @@ -362,6 +362,7 @@ unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* fil if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file); fclose(file); + if (*outsize != size) return 91; if(!(*out) && size) return 83; /*the above malloc failed*/ return 0; } @@ -370,11 +371,13 @@ unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* fil unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) { FILE* file; + int ret = 0; file = fopen(filename, "wb" ); if(!file) return 79; - fwrite((char*)buffer , 1 , buffersize, file); + if (fwrite((char*)buffer , 1 , buffersize, file) != buffersize) + ret = 91; fclose(file); - return 0; + return ret; } #endif /*LODEPNG_COMPILE_DISK*/ @@ -5894,6 +5897,7 @@ const char* lodepng_error_text(unsigned code) case 89: return "text chunk keyword too short or long: must have size 1-79"; /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ case 90: return "windowsize must be a power of two"; + case 91: return "fwrite failed"; } return "unknown error code"; } diff --git a/winpr/libwinpr/utils/sam.c b/winpr/libwinpr/utils/sam.c index 937ecf02f..08c5b1441 100644 --- a/winpr/libwinpr/utils/sam.c +++ b/winpr/libwinpr/utils/sam.c @@ -239,7 +239,10 @@ WINPR_SAM_ENTRY* SamLookupUserA(WINPR_SAM* sam, LPSTR User, UINT32 UserLength, L return NULL; if (!SamLookupStart(sam)) + { + free(entry); return NULL; + } while (sam->line != NULL) { diff --git a/winpr/libwinpr/utils/wlog/Appender.c b/winpr/libwinpr/utils/wlog/Appender.c index b8e5ab4c7..d54ec52ab 100644 --- a/winpr/libwinpr/utils/wlog/Appender.c +++ b/winpr/libwinpr/utils/wlog/Appender.c @@ -109,7 +109,7 @@ wLogAppender* WLog_GetLogAppender(wLog* log) return log->Appender; } -void WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType) +BOOL WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType) { if (log->Appender) { @@ -118,6 +118,7 @@ void WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType) } log->Appender = WLog_Appender_New(log, logAppenderType); + return log->Appender != NULL; } int WLog_OpenAppender(wLog* log) diff --git a/winpr/libwinpr/utils/wlog/BinaryAppender.c b/winpr/libwinpr/utils/wlog/BinaryAppender.c index 4bc64270d..50d9c86cd 100644 --- a/winpr/libwinpr/utils/wlog/BinaryAppender.c +++ b/winpr/libwinpr/utils/wlog/BinaryAppender.c @@ -41,32 +41,32 @@ * Binary Appender */ -void WLog_BinaryAppender_SetOutputFileName(wLog* log, wLogBinaryAppender* appender, const char* filename) +BOOL WLog_BinaryAppender_SetOutputFileName(wLog* log, wLogBinaryAppender* appender, const char* filename) { - if (!appender) - return; + if (!appender || !filename) + return FALSE; if (appender->Type != WLOG_APPENDER_BINARY) - return; - - if (!filename) - return; + return FALSE; appender->FileName = _strdup(filename); + if (!appender->FileName) + return FALSE; + return TRUE; } -void WLog_BinaryAppender_SetOutputFilePath(wLog* log, wLogBinaryAppender* appender, const char* filepath) +BOOL WLog_BinaryAppender_SetOutputFilePath(wLog* log, wLogBinaryAppender* appender, const char* filepath) { - if (!appender) - return; + if (!appender || !filepath) + return FALSE; if (appender->Type != WLOG_APPENDER_BINARY) - return; - - if (!filepath) - return; + return FALSE; appender->FilePath = _strdup(filepath); + if (!appender->FilePath) + return FALSE; + return TRUE; } int WLog_BinaryAppender_Open(wLog* log, wLogBinaryAppender* appender) @@ -131,6 +131,7 @@ int WLog_BinaryAppender_WriteMessage(wLog* log, wLogBinaryAppender* appender, wL int FileNameLength; int FunctionNameLength; int TextStringLength; + int ret = 1; if (!log || !appender || !message) return -1; @@ -171,11 +172,12 @@ int WLog_BinaryAppender_WriteMessage(wLog* log, wLogBinaryAppender* appender, wL Stream_SealLength(s); - fwrite(Stream_Buffer(s), MessageLength, 1, fp); + if (fwrite(Stream_Buffer(s), MessageLength, 1, fp) != 1) + ret = -1; Stream_Free(s, TRUE); - return 1; + return ret; } int WLog_BinaryAppender_WriteDataMessage(wLog* log, wLogBinaryAppender* appender, wLogMessage* message) @@ -192,28 +194,19 @@ wLogBinaryAppender* WLog_BinaryAppender_New(wLog* log) { wLogBinaryAppender* BinaryAppender; - BinaryAppender = (wLogBinaryAppender*) malloc(sizeof(wLogBinaryAppender)); + BinaryAppender = (wLogBinaryAppender*) calloc(1, sizeof(wLogBinaryAppender)); + if (!BinaryAppender) + return NULL; - if (BinaryAppender) - { - ZeroMemory(BinaryAppender, sizeof(wLogBinaryAppender)); - - BinaryAppender->Type = WLOG_APPENDER_BINARY; - - BinaryAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_BinaryAppender_Open; - BinaryAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_BinaryAppender_Close; - - BinaryAppender->WriteMessage = - (WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_BinaryAppender_WriteMessage; - BinaryAppender->WriteDataMessage = - (WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_BinaryAppender_WriteDataMessage; - BinaryAppender->WriteImageMessage = - (WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_BinaryAppender_WriteImageMessage; - - BinaryAppender->FileName = NULL; - BinaryAppender->FilePath = NULL; - BinaryAppender->FullFileName = NULL; - } + BinaryAppender->Type = WLOG_APPENDER_BINARY; + BinaryAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_BinaryAppender_Open; + BinaryAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_BinaryAppender_Close; + BinaryAppender->WriteMessage = + (WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_BinaryAppender_WriteMessage; + BinaryAppender->WriteDataMessage = + (WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_BinaryAppender_WriteDataMessage; + BinaryAppender->WriteImageMessage = + (WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_BinaryAppender_WriteImageMessage; return BinaryAppender; } diff --git a/winpr/libwinpr/utils/wlog/CallbackAppender.c b/winpr/libwinpr/utils/wlog/CallbackAppender.c index b6d3d70b8..907191789 100644 --- a/winpr/libwinpr/utils/wlog/CallbackAppender.c +++ b/winpr/libwinpr/utils/wlog/CallbackAppender.c @@ -125,31 +125,22 @@ wLogCallbackAppender* WLog_CallbackAppender_New(wLog* log) { wLogCallbackAppender* CallbackAppender; - CallbackAppender = (wLogCallbackAppender*) malloc(sizeof(wLogCallbackAppender)); + CallbackAppender = (wLogCallbackAppender*) calloc(1, sizeof(wLogCallbackAppender)); + if (!CallbackAppender) + return NULL; - if (CallbackAppender) - { - ZeroMemory(CallbackAppender, sizeof(wLogCallbackAppender)); + CallbackAppender->Type = WLOG_APPENDER_CALLBACK; - CallbackAppender->Type = WLOG_APPENDER_CALLBACK; - - CallbackAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_CallbackAppender_Open; - CallbackAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_CallbackAppender_Close; - - CallbackAppender->WriteMessage = - (WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_CallbackAppender_WriteMessage; - CallbackAppender->WriteDataMessage = - (WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_CallbackAppender_WriteDataMessage; - CallbackAppender->WriteImageMessage = - (WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_CallbackAppender_WriteImageMessage; - CallbackAppender->WritePacketMessage = - (WLOG_APPENDER_WRITE_PACKET_MESSAGE_FN) WLog_CallbackAppender_WritePacketMessage; - - CallbackAppender->message = NULL; - CallbackAppender->image = NULL; - CallbackAppender->package = NULL; - CallbackAppender->data = NULL; - } + CallbackAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_CallbackAppender_Open; + CallbackAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_CallbackAppender_Close; + CallbackAppender->WriteMessage = + (WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_CallbackAppender_WriteMessage; + CallbackAppender->WriteDataMessage = + (WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_CallbackAppender_WriteDataMessage; + CallbackAppender->WriteImageMessage = + (WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_CallbackAppender_WriteImageMessage; + CallbackAppender->WritePacketMessage = + (WLOG_APPENDER_WRITE_PACKET_MESSAGE_FN) WLog_CallbackAppender_WritePacketMessage; return CallbackAppender; } diff --git a/winpr/libwinpr/utils/wlog/DataMessage.c b/winpr/libwinpr/utils/wlog/DataMessage.c index 892050425..6cd5cea16 100644 --- a/winpr/libwinpr/utils/wlog/DataMessage.c +++ b/winpr/libwinpr/utils/wlog/DataMessage.c @@ -31,6 +31,8 @@ int WLog_DataMessage_Write(char* filename, void* data, int length) { FILE* fp; + int ret = 0; + fp = fopen(filename, "w+b"); if (!fp) @@ -39,7 +41,8 @@ int WLog_DataMessage_Write(char* filename, void* data, int length) return -1; } - fwrite(data, length, 1, fp); + if (fwrite(data, length, 1, fp) != 1) + ret = -1; fclose(fp); - return 0; + return ret; } diff --git a/winpr/libwinpr/utils/wlog/FileAppender.c b/winpr/libwinpr/utils/wlog/FileAppender.c index 64a9239be..46d13bbad 100644 --- a/winpr/libwinpr/utils/wlog/FileAppender.c +++ b/winpr/libwinpr/utils/wlog/FileAppender.c @@ -37,32 +37,34 @@ * File Appender */ -void WLog_FileAppender_SetOutputFileName(wLog* log, wLogFileAppender* appender, const char* filename) +BOOL WLog_FileAppender_SetOutputFileName(wLog* log, wLogFileAppender* appender, const char* filename) { - if (!appender) - return; + if (!appender || !filename) + return FALSE; if (appender->Type != WLOG_APPENDER_FILE) - return; - - if (!filename) - return; + return FALSE; appender->FileName = _strdup(filename); + if (!appender->FileName) + return FALSE; + + return TRUE; } -void WLog_FileAppender_SetOutputFilePath(wLog* log, wLogFileAppender* appender, const char* filepath) +BOOL WLog_FileAppender_SetOutputFilePath(wLog* log, wLogFileAppender* appender, const char* filepath) { - if (!appender) - return; + if (!appender || !filepath) + return FALSE; if (appender->Type != WLOG_APPENDER_FILE) - return; - - if (!filepath) - return; + return FALSE; appender->FilePath = _strdup(filepath); + if (!appender->FilePath) + return FALSE; + + return TRUE; } int WLog_FileAppender_Open(wLog* log, wLogFileAppender* appender) @@ -193,57 +195,62 @@ wLogFileAppender* WLog_FileAppender_New(wLog* log) LPCSTR name; DWORD nSize; wLogFileAppender* FileAppender; + BOOL status; - FileAppender = (wLogFileAppender*) malloc(sizeof(wLogFileAppender)); + FileAppender = (wLogFileAppender*) calloc(1, sizeof(wLogFileAppender)); + if (!FileAppender) + return NULL; - if (FileAppender) + FileAppender->Type = WLOG_APPENDER_FILE; + + FileAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_FileAppender_Open; + FileAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_FileAppender_Close; + FileAppender->WriteMessage = + (WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_FileAppender_WriteMessage; + FileAppender->WriteDataMessage = + (WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_FileAppender_WriteDataMessage; + FileAppender->WriteImageMessage = + (WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_FileAppender_WriteImageMessage; + + name = "WLOG_FILEAPPENDER_OUTPUT_FILE_PATH"; + nSize = GetEnvironmentVariableA(name, NULL, 0); + if (nSize) { - ZeroMemory(FileAppender, sizeof(wLogFileAppender)); + env = (LPSTR) malloc(nSize); + if (!env) + goto error_free; - FileAppender->Type = WLOG_APPENDER_FILE; + nSize = GetEnvironmentVariableA(name, env, nSize); + status = WLog_FileAppender_SetOutputFilePath(log, FileAppender, env); + free(env); - FileAppender->Open = (WLOG_APPENDER_OPEN_FN) WLog_FileAppender_Open; - FileAppender->Close = (WLOG_APPENDER_OPEN_FN) WLog_FileAppender_Close; + if (!status) + goto error_free; + } - FileAppender->WriteMessage = - (WLOG_APPENDER_WRITE_MESSAGE_FN) WLog_FileAppender_WriteMessage; - FileAppender->WriteDataMessage = - (WLOG_APPENDER_WRITE_DATA_MESSAGE_FN) WLog_FileAppender_WriteDataMessage; - FileAppender->WriteImageMessage = - (WLOG_APPENDER_WRITE_IMAGE_MESSAGE_FN) WLog_FileAppender_WriteImageMessage; + name = "WLOG_FILEAPPENDER_OUTPUT_FILE_NAME"; + nSize = GetEnvironmentVariableA(name, NULL, 0); + if (nSize) + { + env = (LPSTR) malloc(nSize); + if (!env) + goto error_output_file_name; - FileAppender->FileName = NULL; - FileAppender->FilePath = NULL; - FileAppender->FullFileName = NULL; + nSize = GetEnvironmentVariableA(name, env, nSize); + status = WLog_FileAppender_SetOutputFileName(log, FileAppender, env); + free(env); - name = "WLOG_FILEAPPENDER_OUTPUT_FILE_PATH"; - nSize = GetEnvironmentVariableA(name, NULL, 0); - if (nSize) - { - env = (LPSTR) malloc(nSize); - if (env) - { - nSize = GetEnvironmentVariableA(name, env, nSize); - WLog_FileAppender_SetOutputFilePath(log, FileAppender, env); - free(env); - } - } - - name = "WLOG_FILEAPPENDER_OUTPUT_FILE_NAME"; - nSize = GetEnvironmentVariableA(name, NULL, 0); - if (nSize) - { - env = (LPSTR) malloc(nSize); - if (env) - { - nSize = GetEnvironmentVariableA(name, env, nSize); - WLog_FileAppender_SetOutputFileName(log, FileAppender, env); - free(env); - } - } - } + if (!status) + goto error_output_file_name; + } return FileAppender; + +error_output_file_name: + free(FileAppender->FilePath); +error_free: + free(FileAppender); + return NULL; } void WLog_FileAppender_Free(wLog* log, wLogFileAppender* appender) diff --git a/winpr/libwinpr/utils/wlog/Layout.c b/winpr/libwinpr/utils/wlog/Layout.c index 8183c16bc..d28a8cee7 100644 --- a/winpr/libwinpr/utils/wlog/Layout.c +++ b/winpr/libwinpr/utils/wlog/Layout.c @@ -338,13 +338,18 @@ wLogLayout* WLog_GetLogLayout(wLog* log) return appender->Layout; } -void WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format) +BOOL WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format) { free(layout->FormatString); layout->FormatString = NULL; if (format) + { layout->FormatString = _strdup(format); + if (!layout->FormatString) + return FALSE; + } + return TRUE; } wLogLayout* WLog_Layout_New(wLog* log) @@ -354,39 +359,38 @@ wLogLayout* WLog_Layout_New(wLog* log) wLogLayout* layout; layout = (wLogLayout*) calloc(1, sizeof(wLogLayout)); + if (!layout) + return NULL; - if (layout) + nSize = GetEnvironmentVariableA("WLOG_PREFIX", NULL, 0); + if (nSize) { - nSize = GetEnvironmentVariableA("WLOG_PREFIX", NULL, 0); - - if (nSize) + env = (LPSTR) malloc(nSize); + if (!env) { - env = (LPSTR) malloc(nSize); - if (!env) - { - free(layout); - return NULL; - } - nSize = GetEnvironmentVariableA("WLOG_PREFIX", env, nSize); + free(layout); + return NULL; } + nSize = GetEnvironmentVariableA("WLOG_PREFIX", env, nSize); + } - if (env) - layout->FormatString = env; - else - { + if (env) + layout->FormatString = env; + else + { #ifdef ANDROID - layout->FormatString = _strdup("[pid=%pid:tid=%tid] - "); + layout->FormatString = _strdup("[pid=%pid:tid=%tid] - "); #else - layout->FormatString = _strdup("[%hr:%mi:%se:%ml] [%pid:%tid] [%lv][%mn] - "); + layout->FormatString = _strdup("[%hr:%mi:%se:%ml] [%pid:%tid] [%lv][%mn] - "); #endif - if (!layout->FormatString) - { - free(layout); - return NULL; - } + if (!layout->FormatString) + { + free(layout); + return NULL; } } + return layout; } diff --git a/winpr/libwinpr/utils/wlog/PacketMessage.c b/winpr/libwinpr/utils/wlog/PacketMessage.c index c816660a9..eb1edfb7f 100644 --- a/winpr/libwinpr/utils/wlog/PacketMessage.c +++ b/winpr/libwinpr/utils/wlog/PacketMessage.c @@ -50,56 +50,44 @@ static int gettimeofday(struct timeval* tp, void* tz) } #endif -void Pcap_Read_Header(wPcap* pcap, wPcapHeader* header) +static BOOL Pcap_Read_Header(wPcap* pcap, wPcapHeader* header) { - if (pcap && pcap->fp) - fread((void*) header, sizeof(wPcapHeader), 1, pcap->fp); + if (pcap && pcap->fp && fread((void*) header, sizeof(wPcapHeader), 1, pcap->fp) == 1) + return TRUE; + return FALSE; } -void Pcap_Write_Header(wPcap* pcap, wPcapHeader* header) +/* currently unused code */ +# if 0 +static BOOL Pcap_Read_RecordHeader(wPcap* pcap, wPcapRecordHeader* record) { - if (pcap && pcap->fp) - fwrite((void*) header, sizeof(wPcapHeader), 1, pcap->fp); + if (pcap && pcap->fp && (fread((void*) record, sizeof(wPcapRecordHeader), 1, pcap->fp) == 1)) + return TRUE; + return FALSE; } -void Pcap_Read_RecordHeader(wPcap* pcap, wPcapRecordHeader* record) -{ - if (pcap && pcap->fp) - fread((void*) record, sizeof(wPcapRecordHeader), 1, pcap->fp); -} - -void Pcap_Write_RecordHeader(wPcap* pcap, wPcapRecordHeader* record) -{ - if (pcap && pcap->fp) - fwrite((void*) record, sizeof(wPcapRecordHeader), 1, pcap->fp); -} - -void Pcap_Write_RecordContent(wPcap* pcap, wPcapRecord* record) -{ - if (pcap && pcap->fp) - fwrite(record->data, record->length, 1, pcap->fp); -} - -void Pcap_Read_Record(wPcap* pcap, wPcapRecord* record) +static BOOL Pcap_Read_Record(wPcap* pcap, wPcapRecord* record) { if (pcap && pcap->fp) { - Pcap_Read_RecordHeader(pcap, &record->header); + if (!Pcap_Read_RecordHeader(pcap, &record->header)) + return FALSE; record->length = record->header.incl_len; record->data = malloc(record->length); if (!record->data) - return; - fread(record->data, record->length, 1, pcap->fp); + return FALSE; + if (fread(record->data, record->length, 1, pcap->fp) != 1) + { + free(record->data); + record->length = 0; + record->data = NULL; + return FALSE; + } } + return TRUE; } -void Pcap_Write_Record(wPcap* pcap, wPcapRecord* record) -{ - Pcap_Write_RecordHeader(pcap, &record->header); - Pcap_Write_RecordContent(pcap, record); -} - -void Pcap_Add_Record(wPcap* pcap, void* data, UINT32 length) +static BOOL Pcap_Add_Record(wPcap* pcap, void* data, UINT32 length) { wPcapRecord* record; struct timeval tp; @@ -108,7 +96,7 @@ void Pcap_Add_Record(wPcap* pcap, void* data, UINT32 length) { pcap->tail = (wPcapRecord*) calloc(1, sizeof(wPcapRecord)); if (!pcap->tail) - return; + return FALSE; pcap->head = pcap->tail; pcap->record = pcap->head; record = pcap->tail; @@ -117,7 +105,7 @@ void Pcap_Add_Record(wPcap* pcap, void* data, UINT32 length) { record = (wPcapRecord*) calloc(1, sizeof(wPcapRecord)); if (!record) - return; + return FALSE; pcap->tail->next = record; pcap->tail = record; } @@ -132,9 +120,10 @@ void Pcap_Add_Record(wPcap* pcap, void* data, UINT32 length) gettimeofday(&tp, 0); record->header.ts_sec = tp.tv_sec; record->header.ts_usec = tp.tv_usec; + return TRUE; } -BOOL Pcap_HasNext_Record(wPcap* pcap) +static BOOL Pcap_HasNext_Record(wPcap* pcap) { if (pcap->file_size - (ftell(pcap->fp)) <= 16) return FALSE; @@ -142,34 +131,58 @@ BOOL Pcap_HasNext_Record(wPcap* pcap) return TRUE; } -BOOL Pcap_GetNext_RecordHeader(wPcap* pcap, wPcapRecord* record) +static BOOL Pcap_GetNext_RecordHeader(wPcap* pcap, wPcapRecord* record) { - if (Pcap_HasNext_Record(pcap) != TRUE) + if (!Pcap_HasNext_Record(pcap) || !Pcap_Read_RecordHeader(pcap, &record->header)) return FALSE; - Pcap_Read_RecordHeader(pcap, &record->header); record->length = record->header.incl_len; return TRUE; } -BOOL Pcap_GetNext_RecordContent(wPcap* pcap, wPcapRecord* record) +static BOOL Pcap_GetNext_RecordContent(wPcap* pcap, wPcapRecord* record) { - if (pcap && pcap->fp) - { - fread(record->data, record->length, 1, pcap->fp); + if (pcap && pcap->fp && fread(record->data, record->length, 1, pcap->fp) == 1) return TRUE; - } return FALSE; } -BOOL Pcap_GetNext_Record(wPcap* pcap, wPcapRecord* record) +static BOOL Pcap_GetNext_Record(wPcap* pcap, wPcapRecord* record) { - if (Pcap_HasNext_Record(pcap) != TRUE) + if (!Pcap_HasNext_Record(pcap)) return FALSE; - Pcap_Read_Record(pcap, record); - return TRUE; + return Pcap_Read_Record(pcap, record); +} +#endif + + +static BOOL Pcap_Write_Header(wPcap* pcap, wPcapHeader* header) +{ + if (pcap && pcap->fp && fwrite((void*) header, sizeof(wPcapHeader), 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Write_RecordHeader(wPcap* pcap, wPcapRecordHeader* record) +{ + if (pcap && pcap->fp && fwrite((void *) record, sizeof(wPcapRecordHeader), 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Write_RecordContent(wPcap* pcap, wPcapRecord* record) +{ + if (pcap && pcap->fp && fwrite(record->data, record->length, 1, pcap->fp) == 1) + return TRUE; + return FALSE; +} + +static BOOL Pcap_Write_Record(wPcap* pcap, wPcapRecord* record) +{ + return Pcap_Write_RecordHeader(pcap, &record->header) && + Pcap_Write_RecordContent(pcap, record); } wPcap* Pcap_Open(char* name, BOOL write) @@ -185,33 +198,45 @@ wPcap* Pcap_Open(char* name, BOOL write) pcap = (wPcap*) calloc(1, sizeof(wPcap)); - if (pcap) - { - pcap->name = name; - pcap->write = write; - pcap->record_count = 0; - pcap->fp = pcap_fp; + if (!pcap) + return NULL; - if (write) - { - pcap->header.magic_number = PCAP_MAGIC_NUMBER; - pcap->header.version_major = 2; - pcap->header.version_minor = 4; - pcap->header.thiszone = 0; - pcap->header.sigfigs = 0; - pcap->header.snaplen = 0xFFFFFFFF; - pcap->header.network = 1; /* ethernet */ - Pcap_Write_Header(pcap, &pcap->header); - } - else - { - fseek(pcap->fp, 0, SEEK_END); - pcap->file_size = (int) ftell(pcap->fp); - fseek(pcap->fp, 0, SEEK_SET); - Pcap_Read_Header(pcap, &pcap->header); - } + pcap->name = name; + pcap->write = write; + pcap->record_count = 0; + pcap->fp = pcap_fp; + + if (write) + { + pcap->header.magic_number = PCAP_MAGIC_NUMBER; + pcap->header.version_major = 2; + pcap->header.version_minor = 4; + pcap->header.thiszone = 0; + pcap->header.sigfigs = 0; + pcap->header.snaplen = 0xFFFFFFFF; + pcap->header.network = 1; /* ethernet */ + if (!Pcap_Write_Header(pcap, &pcap->header)) + goto out_fail; } + else + { + if (fseek(pcap->fp, 0, SEEK_END) < 0) + goto out_fail; + pcap->file_size = (int) ftell(pcap->fp); + if (pcap->file_size < 0) + goto out_fail; + if (fseek(pcap->fp, 0, SEEK_SET) < 0) + goto out_fail; + if (!Pcap_Read_Header(pcap, &pcap->header)) + goto out_fail; + } + return pcap; + +out_fail: + fclose(pcap_fp); + free(pcap); + return NULL; } void Pcap_Flush(wPcap* pcap) @@ -221,11 +246,13 @@ void Pcap_Flush(wPcap* pcap) while (pcap->record) { - Pcap_Write_Record(pcap, pcap->record); + if (!Pcap_Write_Record(pcap, pcap->record)) + return; pcap->record = pcap->record->next; } fflush(pcap->fp); + return; } void Pcap_Close(wPcap* pcap) @@ -238,26 +265,28 @@ void Pcap_Close(wPcap* pcap) free(pcap); } -int WLog_PacketMessage_Write_EthernetHeader(wPcap* pcap, wEthernetHeader* ethernet) +static BOOL WLog_PacketMessage_Write_EthernetHeader(wPcap* pcap, wEthernetHeader* ethernet) { wStream* s; BYTE buffer[14]; + BOOL ret = TRUE; if (!pcap || !pcap->fp || !ethernet) - return -1; + return FALSE; s = Stream_New(buffer, 14); if (!s) - return -1; + return FALSE; Stream_Write(s, ethernet->Destination, 6); Stream_Write(s, ethernet->Source, 6); Stream_Write_UINT16_BE(s, ethernet->Type); - fwrite(buffer, 14, 1, pcap->fp); + if (fwrite(buffer, 14, 1, pcap->fp) != 1) + ret = FALSE; Stream_Free(s, FALSE); - return 0; + return ret; } -UINT16 IPv4Checksum(BYTE* ipv4, int length) +static UINT16 IPv4Checksum(BYTE* ipv4, int length) { UINT16 tmp16; long checksum = 0; @@ -279,17 +308,18 @@ UINT16 IPv4Checksum(BYTE* ipv4, int length) return (UINT16)(~checksum); } -int WLog_PacketMessage_Write_IPv4Header(wPcap* pcap, wIPv4Header* ipv4) +static BOOL WLog_PacketMessage_Write_IPv4Header(wPcap* pcap, wIPv4Header* ipv4) { wStream* s; BYTE buffer[20]; + int ret = TRUE; if (!pcap || !pcap->fp || !ipv4) - return -1; + return FALSE; s = Stream_New(buffer, 20); if (!s) - return -1; + return FALSE; Stream_Write_UINT8(s, (ipv4->Version << 4) | ipv4->InternetHeaderLength); Stream_Write_UINT8(s, ipv4->TypeOfService); Stream_Write_UINT16_BE(s, ipv4->TotalLength); @@ -304,22 +334,24 @@ int WLog_PacketMessage_Write_IPv4Header(wPcap* pcap, wIPv4Header* ipv4) Stream_Rewind(s, 10); Stream_Write_UINT16(s, ipv4->HeaderChecksum); Stream_Seek(s, 8); - fwrite(buffer, 20, 1, pcap->fp); + if (fwrite(buffer, 20, 1, pcap->fp) != 1) + ret = FALSE; Stream_Free(s, FALSE); - return 0; + return ret; } -int WLog_PacketMessage_Write_TcpHeader(wPcap* pcap, wTcpHeader* tcp) +static BOOL WLog_PacketMessage_Write_TcpHeader(wPcap* pcap, wTcpHeader* tcp) { wStream* s; BYTE buffer[20]; + BOOL ret = TRUE; if (!pcap || !pcap->fp || !tcp) - return -1; + return FALSE; s = Stream_New(buffer, 20); if (!s) - return -1; + return FALSE; Stream_Write_UINT16_BE(s, tcp->SourcePort); Stream_Write_UINT16_BE(s, tcp->DestinationPort); Stream_Write_UINT32_BE(s, tcp->SequenceNumber); @@ -331,10 +363,13 @@ int WLog_PacketMessage_Write_TcpHeader(wPcap* pcap, wTcpHeader* tcp) Stream_Write_UINT16_BE(s, tcp->UrgentPointer); if (pcap->fp) - fwrite(buffer, 20, 1, pcap->fp); + { + if (fwrite(buffer, 20, 1, pcap->fp) != 1) + ret = FALSE; + } Stream_Free(s, FALSE); - return 0; + return ret; } static UINT32 g_InboundSequenceNumber = 0; @@ -439,11 +474,12 @@ int WLog_PacketMessage_Write(wPcap* pcap, void* data, DWORD length, DWORD flags) gettimeofday(&tp, 0); record.header.ts_sec = tp.tv_sec; record.header.ts_usec = tp.tv_usec; - Pcap_Write_RecordHeader(pcap, &record.header); - WLog_PacketMessage_Write_EthernetHeader(pcap, ðernet); - WLog_PacketMessage_Write_IPv4Header(pcap, &ipv4); - WLog_PacketMessage_Write_TcpHeader(pcap, &tcp); - Pcap_Write_RecordContent(pcap, &record); + if (!Pcap_Write_RecordHeader(pcap, &record.header) || + !WLog_PacketMessage_Write_EthernetHeader(pcap, ðernet) || + !WLog_PacketMessage_Write_IPv4Header(pcap, &ipv4) || + !WLog_PacketMessage_Write_TcpHeader(pcap, &tcp) || + !Pcap_Write_RecordContent(pcap, &record)) + return -1; fflush(pcap->fp); return 0; } diff --git a/winpr/libwinpr/utils/wlog/wlog.c b/winpr/libwinpr/utils/wlog/wlog.c index 7cf7fdeb5..b91c42ffd 100644 --- a/winpr/libwinpr/utils/wlog/wlog.c +++ b/winpr/libwinpr/utils/wlog/wlog.c @@ -552,8 +552,8 @@ wLog* WLog_New(LPCSTR name, wLog* rootLogger) char* env = NULL; DWORD nSize; int iLevel; - log = (wLog*) calloc(1, sizeof(wLog)); + log = (wLog*) calloc(1, sizeof(wLog)); if (!log) return NULL; @@ -586,18 +586,21 @@ wLog* WLog_New(LPCSTR name, wLog* rootLogger) if (nSize) { env = (LPSTR) malloc(nSize); - if (env) + if (!env) + goto out_fail; + + if (!GetEnvironmentVariableA("WLOG_LEVEL", env, nSize)) { - if (GetEnvironmentVariableA("WLOG_LEVEL", env, nSize)) - { - iLevel = WLog_ParseLogLevel(env); - - if (iLevel >= 0) - log->Level = (DWORD) iLevel; - - } + fprintf(stderr, "WLOG_LEVEL environment variable changed in my back !\n"); free(env); + goto out_fail; } + + iLevel = WLog_ParseLogLevel(env); + free(env); + + if (iLevel >= 0) + log->Level = (DWORD) iLevel; } } @@ -654,25 +657,36 @@ wLog* WLog_GetRoot() if (nSize) { env = (LPSTR) malloc(nSize); - if (env) + if (!env) + goto fail; + + if (!GetEnvironmentVariableA("WLOG_APPENDER", env, nSize)) { - if (GetEnvironmentVariableA("WLOG_APPENDER", env, nSize)) - { - if (_stricmp(env, "CONSOLE") == 0) - logAppenderType = WLOG_APPENDER_CONSOLE; - else if (_stricmp(env, "FILE") == 0) - logAppenderType = WLOG_APPENDER_FILE; - else if (_stricmp(env, "BINARY") == 0) - logAppenderType = WLOG_APPENDER_BINARY; - } + fprintf(stderr, "WLOG_APPENDER environment variable modified in my back"); free(env); + goto fail; } + + if (_stricmp(env, "CONSOLE") == 0) + logAppenderType = WLOG_APPENDER_CONSOLE; + else if (_stricmp(env, "FILE") == 0) + logAppenderType = WLOG_APPENDER_FILE; + else if (_stricmp(env, "BINARY") == 0) + logAppenderType = WLOG_APPENDER_BINARY; + + free(env); } - WLog_SetLogAppenderType(g_RootLog, logAppenderType); + if (!WLog_SetLogAppenderType(g_RootLog, logAppenderType)) + goto fail; } return g_RootLog; + +fail: + free(g_RootLog); + g_RootLog = NULL; + return NULL; } int WLog_AddChild(wLog* parent, wLog* child) @@ -747,9 +761,9 @@ wLog* WLog_Get(LPCSTR name) return log; } -void WLog_Init() +BOOL WLog_Init() { - WLog_GetRoot(); + return WLog_GetRoot() != NULL; } void WLog_Uninit() diff --git a/winpr/libwinpr/winsock/winsock.c b/winpr/libwinpr/winsock/winsock.c index 5f75c2883..e6cb9b9ab 100644 --- a/winpr/libwinpr/winsock/winsock.c +++ b/winpr/libwinpr/winsock/winsock.c @@ -40,6 +40,11 @@ #include #endif +#ifdef __APPLE__ +#define WSAIOCTL_IFADDRS +#include +#endif + /** * ws2_32.dll: * @@ -642,12 +647,21 @@ BOOL WSACloseEvent(HANDLE hEvent) int WSAEventSelect(SOCKET s, WSAEVENT hEventObject, LONG lNetworkEvents) { - u_long arg = 1; + u_long arg = lNetworkEvents ? 1 : 0; + ULONG mode = 0; if (_ioctlsocket(s, FIONBIO, &arg) != 0) return SOCKET_ERROR; - if (SetEventFileDescriptor(hEventObject, s) < 0) + if (arg == 0) + return 0; + + if (lNetworkEvents & FD_READ) + mode |= WINPR_FD_READ; + if (lNetworkEvents & FD_WRITE) + mode |= WINPR_FD_WRITE; + + if (SetEventFileDescriptor(hEventObject, s, mode) < 0) return SOCKET_ERROR; return 0; @@ -707,6 +721,103 @@ int WSAIoctl(SOCKET s, DWORD dwIoControlCode, LPVOID lpvInBuffer, pInterfaces = (INTERFACE_INFO*) lpvOutBuffer; maxNumInterfaces = cbOutBuffer / sizeof(INTERFACE_INFO); +#ifdef WSAIOCTL_IFADDRS + { + struct ifaddrs* ifa = NULL; + struct ifaddrs* ifap = NULL; + + if (getifaddrs(&ifap) != 0) + { + WSASetLastError(WSAENETDOWN); + return SOCKET_ERROR; + } + + index = 0; + numInterfaces = 0; + + for (ifa = ifap; ifa; ifa = ifa->ifa_next) + { + pInterface = &pInterfaces[index]; + pAddress = (struct sockaddr_in*) &pInterface->iiAddress; + pBroadcast = (struct sockaddr_in*) &pInterface->iiBroadcastAddress; + pNetmask = (struct sockaddr_in*) &pInterface->iiNetmask; + + nFlags = 0; + + if (ifa->ifa_flags & IFF_UP) + nFlags |= _IFF_UP; + + if (ifa->ifa_flags & IFF_BROADCAST) + nFlags |= _IFF_BROADCAST; + + if (ifa->ifa_flags & IFF_LOOPBACK) + nFlags |= _IFF_LOOPBACK; + + if (ifa->ifa_flags & IFF_POINTOPOINT) + nFlags |= _IFF_POINTTOPOINT; + + if (ifa->ifa_flags & IFF_MULTICAST) + nFlags |= _IFF_MULTICAST; + + pInterface->iiFlags = nFlags; + + if (ifa->ifa_addr) + { + if ((ifa->ifa_addr->sa_family != AF_INET) && (ifa->ifa_addr->sa_family != AF_INET6)) + continue; + + getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr), + address, sizeof(address), 0, 0, NI_NUMERICHOST); + + inet_pton(ifa->ifa_addr->sa_family, address, (void*) &pAddress->sin_addr); + } + else + { + ZeroMemory(pAddress, sizeof(struct sockaddr_in)); + } + + if (ifa->ifa_dstaddr) + { + if ((ifa->ifa_dstaddr->sa_family != AF_INET) && (ifa->ifa_dstaddr->sa_family != AF_INET6)) + continue; + + getnameinfo(ifa->ifa_dstaddr, sizeof(struct sockaddr), + broadcast, sizeof(broadcast), 0, 0, NI_NUMERICHOST); + + inet_pton(ifa->ifa_dstaddr->sa_family, broadcast, (void*) &pBroadcast->sin_addr); + } + else + { + ZeroMemory(pBroadcast, sizeof(struct sockaddr_in)); + } + + if (ifa->ifa_netmask) + { + if ((ifa->ifa_netmask->sa_family != AF_INET) && (ifa->ifa_netmask->sa_family != AF_INET6)) + continue; + + getnameinfo(ifa->ifa_netmask, sizeof(struct sockaddr), + netmask, sizeof(netmask), 0, 0, NI_NUMERICHOST); + + inet_pton(ifa->ifa_netmask->sa_family, netmask, (void*) &pNetmask->sin_addr); + } + else + { + ZeroMemory(pNetmask, sizeof(struct sockaddr_in)); + } + + numInterfaces++; + index++; + } + + *lpcbBytesReturned = (DWORD) (numInterfaces * sizeof(INTERFACE_INFO)); + + freeifaddrs(ifap); + + return 0; + } +#endif + ifconf.ifc_len = sizeof(buffer); ifconf.ifc_buf = buffer; diff --git a/winpr/libwinpr/wnd/wnd.c b/winpr/libwinpr/wnd/wnd.c index e94ebc018..480ea07b5 100644 --- a/winpr/libwinpr/wnd/wnd.c +++ b/winpr/libwinpr/wnd/wnd.c @@ -58,6 +58,13 @@ WNDCLASSEXA* CloneWindowClass(CONST WNDCLASSEXA* lpwcx) _lpwcx->lpszClassName = _strdup(lpwcx->lpszClassName); _lpwcx->lpszMenuName = _strdup(lpwcx->lpszMenuName); + if (!_lpwcx->lpszClassName || !_lpwcx->lpszMenuName) + { + free((LPSTR)_lpwcx->lpszClassName); + free((LPSTR)_lpwcx->lpszMenuName); + free(_lpwcx); + return NULL; + } return _lpwcx; } @@ -233,9 +240,15 @@ HWND WINAPI CreateWindowExA(DWORD dwExStyle, LPCSTR lpClassName, pWnd->nWidth = nWidth; pWnd->nHeight = nHeight; pWnd->lpClassName = _strdup(lpClassName); + if (!pWnd->lpClassName) + goto out_fail; if (lpWindowName) + { pWnd->lpWindowName = _strdup(lpWindowName); + if (!pWnd->lpWindowName) + goto out_fail; + } pWnd->hWndParent = hWndParent; pWnd->hMenu = hMenu; @@ -244,6 +257,12 @@ HWND WINAPI CreateWindowExA(DWORD dwExStyle, LPCSTR lpClassName, pWnd->lpwcx = lpwcx; return hWnd; + +out_fail: + free(pWnd->lpClassName); + free(pWnd->lpWindowName); + free(pWnd); + return NULL; } HWND WINAPI CreateWindowExW(DWORD dwExStyle, LPCWSTR lpClassName, diff --git a/winpr/libwinpr/wtsapi/test/CMakeLists.txt b/winpr/libwinpr/wtsapi/test/CMakeLists.txt index 3e7e955a8..d5bf76c29 100644 --- a/winpr/libwinpr/wtsapi/test/CMakeLists.txt +++ b/winpr/libwinpr/wtsapi/test/CMakeLists.txt @@ -4,15 +4,22 @@ set(MODULE_PREFIX "TEST_WTSAPI") set(${MODULE_PREFIX}_DRIVER ${MODULE_NAME}.c) +set(UNIX_ONLY + TestWtsApiShutdownSystem.c + TestWtsApiWaitSystemEvent.c + ) + set(${MODULE_PREFIX}_TESTS TestWtsApiEnumerateProcesses.c TestWtsApiEnumerateSessions.c TestWtsApiQuerySessionInformation.c - TestWtsApiShutdownSystem.c TestWtsApiSessionNotification.c - TestWtsApiWaitSystemEvent.c ) +if(NOT WIN32) + set(${MODULE_PREFIX}_TESTS ${${MODULE_PREFIX}_TESTS} ${UNIX_ONLY}) +endif() + create_test_sourcelist(${MODULE_PREFIX}_SRCS ${${MODULE_PREFIX}_DRIVER} ${${MODULE_PREFIX}_TESTS}) diff --git a/winpr/libwinpr/wtsapi/wtsapi_win32.c b/winpr/libwinpr/wtsapi/wtsapi_win32.c index b114b41bb..998ccfb18 100644 --- a/winpr/libwinpr/wtsapi/wtsapi_win32.c +++ b/winpr/libwinpr/wtsapi/wtsapi_win32.c @@ -157,6 +157,13 @@ HANDLE WINAPI Win32_WTSVirtualChannelOpen_Internal(HANDLE hServer, DWORD Session pChannel->SessionId = SessionId; pChannel->hFile = hFile; pChannel->VirtualName = _strdup(pVirtualName); + if (!pChannel->VirtualName) + { + CloseHandle(hFile); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + free(pChannel); + return NULL; + } pChannel->flags = flags; pChannel->dynamic = (flags & WTS_CHANNEL_OPTION_DYNAMIC) ? TRUE : FALSE; diff --git a/winpr/tools/makecert/cli/main.c b/winpr/tools/makecert/cli/main.c index 446442ca2..553a20cde 100644 --- a/winpr/tools/makecert/cli/main.c +++ b/winpr/tools/makecert/cli/main.c @@ -30,12 +30,16 @@ int main(int argc, char* argv[]) { MAKECERT_CONTEXT* context; + int ret = 0; context = makecert_context_new(); + if (!context) + return 1; - makecert_context_process(context, argc, argv); + if (makecert_context_process(context, argc, argv) < 0) + ret = 1; makecert_context_free(context); - return 0; + return ret; } diff --git a/winpr/tools/makecert/makecert.c b/winpr/tools/makecert/makecert.c index 17f56dc4f..0c8ba032e 100644 --- a/winpr/tools/makecert/makecert.c +++ b/winpr/tools/makecert/makecert.c @@ -306,16 +306,19 @@ char* x509_name_parse(char* name, char* txt, int* length) char* x509_get_default_name() { - DWORD nSize = 0; - char* ComputerName; + CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD nSize = MAX_COMPUTERNAME_LENGTH; - GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize); - ComputerName = (char*) malloc(nSize); - if (!ComputerName) + char* ret; + + if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize)) return NULL; - GetComputerNameExA(ComputerNameNetBIOS, ComputerName, &nSize); - return ComputerName; + ret = _strdup(computerName); + if (!ret) + return NULL; + + return ret; } int command_line_pre_filter(MAKECERT_CONTEXT* context, int index, int argc, LPCSTR* argv) @@ -323,7 +326,11 @@ int command_line_pre_filter(MAKECERT_CONTEXT* context, int index, int argc, LPCS if (index == (argc - 1)) { if (argv[index][0] != '-') - context->output_file = (char*) argv[index]; + { + context->output_file = _strdup(argv[index]); + if (!context->output_file) + return -1; + } return 1; } @@ -396,6 +403,8 @@ int makecert_context_parse_arguments(MAKECERT_CONTEXT* context, int argc, char** context->pemFormat = FALSE; context->pfxFormat = TRUE; } + else + return -1; } CommandLineSwitchCase(arg, "path") { @@ -403,6 +412,8 @@ int makecert_context_parse_arguments(MAKECERT_CONTEXT* context, int argc, char** continue; context->output_path = _strdup(arg->Value); + if (!context->output_path) + return -1; } CommandLineSwitchCase(arg, "p") { @@ -410,6 +421,8 @@ int makecert_context_parse_arguments(MAKECERT_CONTEXT* context, int argc, char** continue; context->password = _strdup(arg->Value); + if (!context->password) + return -1; } CommandLineSwitchCase(arg, "n") { @@ -417,6 +430,8 @@ int makecert_context_parse_arguments(MAKECERT_CONTEXT* context, int argc, char** continue; context->common_name = _strdup(arg->Value); + if (!context->common_name) + return -1; } CommandLineSwitchCase(arg, "y") { @@ -450,17 +465,22 @@ int makecert_context_set_output_file_name(MAKECERT_CONTEXT* context, char* name) { free(context->output_file); context->output_file = _strdup(name); + if (!context->output_file) + return -1; return 1; } int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, char* path) { - FILE* fp; + FILE* fp = NULL; int status; int length; int offset; - char* filename; - char* fullpath; + char* filename = NULL; + char* fullpath = NULL; + int ret = -1; + BIO* bio = NULL; + BYTE* x509_str = NULL; if (!context->output_file) { @@ -491,18 +511,21 @@ int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, char* pa else fullpath = _strdup(filename); + if (!fullpath) + goto out_fail; + fp = fopen(fullpath, "w+"); if (fp) { - BIO* bio; - BYTE* x509_str = NULL; if (context->pfxFormat) { if (!context->password) { context->password = _strdup("password"); + if (!context->password) + goto out_fail; printf("Using default export password \"password\"\n"); } @@ -512,41 +535,29 @@ int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, char* pa context->pkcs12 = PKCS12_create(context->password, context->default_name, context->pkey, context->x509, NULL, 0, 0, 0, 0, 0); + if (!context->pkcs12) + goto out_fail; bio = BIO_new(BIO_s_mem()); if (!bio) - { - free(filename); - free(fullpath); - fclose (fp); - return -1; - } + goto out_fail; status = i2d_PKCS12_bio(bio, context->pkcs12); + if (status != 1) + goto out_fail; offset = 0; length = 2048; x509_str = (BYTE*) malloc(length); if (!x509_str) - { - free(filename); - free(fullpath); - fclose (fp); - return -1; - } + goto out_fail; status = BIO_read(bio, x509_str, length); if (status < 0) - { - free(x509_str); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } - + goto out_fail; + offset += status; while (offset >= length) @@ -574,57 +585,34 @@ int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, char* pa } if (status < 0) - { - free(x509_str); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } + goto out_fail; length = offset; - fwrite((void*) x509_str, length, 1, fp); + if (fwrite((void*) x509_str, length, 1, fp) != 1) + goto out_fail; - free(x509_str); - BIO_free(bio); } else { bio = BIO_new(BIO_s_mem()); if (!bio) - { - free(filename); - free(fullpath); - fclose (fp); - return -1; - } + goto out_fail; - status = PEM_write_bio_X509(bio, context->x509); + if (!PEM_write_bio_X509(bio, context->x509)) + goto out_fail; offset = 0; length = 2048; x509_str = (BYTE*) malloc(length); if (!x509_str) - { - BIO_free(bio); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } + goto out_fail; status = BIO_read(bio, x509_str, length); if (status < 0) - { - BIO_free(bio); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } - + goto out_fail; + offset += status; while (offset >= length) @@ -652,58 +640,37 @@ int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, char* pa } if (status < 0) - { - free (x509_str); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } - + goto out_fail; + length = offset; - fwrite((void*) x509_str, length, 1, fp); + if (fwrite((void*) x509_str, length, 1, fp) != 1) + goto out_fail; free(x509_str); + x509_str = NULL; BIO_free(bio); + bio = NULL; if (context->pemFormat) { bio = BIO_new(BIO_s_mem()); if (!bio) - { - free(filename); - free(fullpath); - fclose (fp); - return -1; - } + goto out_fail; status = PEM_write_bio_PrivateKey(bio, context->pkey, NULL, NULL, 0, NULL, NULL); offset = 0; length = 2048; if (!(x509_str = (BYTE*) malloc(length))) - { - BIO_free(bio); - free(filename); - free(fullpath); - fclose (fp); - return -1; - - } + goto out_fail; status = BIO_read(bio, x509_str, length); if (status < 0) - { - free(x509_str); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } - + goto out_fail; + offset += status; while (offset >= length) @@ -731,46 +698,51 @@ int makecert_context_output_certificate_file(MAKECERT_CONTEXT* context, char* pa } if (status < 0) - { - free(x509_str); - free(filename); - free(fullpath); - fclose (fp); - return -1; - } - + goto out_fail; + length = offset; - fwrite((void*) x509_str, length, 1, fp); - - free(x509_str); - BIO_free(bio); + if (fwrite((void*) x509_str, length, 1, fp) != 1) + goto out_fail; } } - fclose(fp); } + ret = 1; +out_fail: + if (bio) + BIO_free(bio); + if (fp) + fclose(fp); + free(x509_str); free(filename); free(fullpath); - return 1; + return ret; } int makecert_context_output_private_key_file(MAKECERT_CONTEXT* context, char* path) { - FILE* fp; + FILE* fp = NULL; int status; int length; int offset; - char* filename; - char* fullpath; + char* filename = NULL; + char* fullpath = NULL; + int ret = -1; + BIO* bio = NULL; + BYTE* x509_str = NULL; if (!context->crtFormat) return 1; if (!context->output_file) - context->output_file = context->default_name; + { + context->output_file = _strdup(context->default_name); + if (!context->output_file) + return -1; + } /** * Output Private Key File @@ -782,101 +754,84 @@ int makecert_context_output_private_key_file(MAKECERT_CONTEXT* context, char* pa return -1; strcpy(filename, context->output_file); strcpy(&filename[length], ".key"); - length = strlen(filename); if (path) fullpath = GetCombinedPath(path, filename); else fullpath = _strdup(filename); + if (!fullpath) + goto out_fail; + fp = fopen(fullpath, "w+"); + if (!fp) + goto out_fail; - if (fp) + bio = BIO_new(BIO_s_mem()); + + if (!bio) + goto out_fail; + + if (!PEM_write_bio_PrivateKey(bio, context->pkey, NULL, NULL, 0, NULL, NULL)) + goto out_fail; + + offset = 0; + length = 2048; + x509_str = (BYTE*) malloc(length); + if (!x509_str) + goto out_fail; + + status = BIO_read(bio, x509_str, length); + + if (status < 0) + goto out_fail; + + offset += status; + + while (offset >= length) { - BIO* bio; - BYTE* x509_str; + int new_len; + BYTE *new_str; - bio = BIO_new(BIO_s_mem()); - - if (!bio) + new_len = length * 2; + new_str = (BYTE*) realloc(x509_str, new_len); + if (!new_str) { - free (filename); - free(fullpath); - fclose(fp); - return -1; + status = -1; + break; } - status = PEM_write_bio_PrivateKey(bio, context->pkey, NULL, NULL, 0, NULL, NULL); + length = new_len; + x509_str = new_str; - offset = 0; - length = 2048; - x509_str = (BYTE*) malloc(length); - if (!x509_str) - { - free (filename); - free(fullpath); - fclose(fp); - return -1; - } + status = BIO_read(bio, &x509_str[offset], length); - status = BIO_read(bio, x509_str, length); - if (status < 0) - { - free (filename); - free(fullpath); - fclose(fp); - return -1; - } - + break; + offset += status; - - while (offset >= length) - { - int new_len; - BYTE *new_str; - - new_len = length * 2; - new_str = (BYTE*) realloc(x509_str, new_len); - if (!new_str) - { - status = -1; - break; - } - - length = new_len; - x509_str = new_str; - - status = BIO_read(bio, &x509_str[offset], length); - - if (status < 0) - break; - - offset += status; - } - - if (status < 0) - { - free (filename); - free(fullpath); - fclose(fp); - return -1; - } - - length = offset; - - fwrite((void*) x509_str, length, 1, fp); - - free(x509_str); - BIO_free(bio); - - fclose(fp); } + if (status < 0) + goto out_fail; + + length = offset; + + if (fwrite((void*) x509_str, length, 1, fp) != 1) + goto out_fail; + + ret = 1; + +out_fail: + if (fp) + fclose(fp); + if (bio) + BIO_free(bio); + free(x509_str); free(filename); free(fullpath); - return 1; + return ret; } int makecert_context_process(MAKECERT_CONTEXT* context, int argc, char** argv) @@ -888,17 +843,31 @@ int makecert_context_process(MAKECERT_CONTEXT* context, int argc, char** argv) X509_NAME* name = NULL; const EVP_MD* md = NULL; COMMAND_LINE_ARGUMENT_A* arg; + int ret; - if (makecert_context_parse_arguments(context, argc, argv) < 1) - return 0; + ret = makecert_context_parse_arguments(context, argc, argv); + if (ret < 1) + return ret; if (!context->default_name && !context->common_name) + { context->default_name = x509_get_default_name(); + if (!context->default_name) + return -1; + } else + { context->default_name = _strdup(context->common_name); + if (!context->default_name) + return -1; + } if (!context->common_name) + { context->common_name = _strdup(context->default_name); + if (!context->common_name) + return -1; + } if (!context->pkey) context->pkey = EVP_PKEY_new(); @@ -1105,7 +1074,10 @@ int makecert_context_process(MAKECERT_CONTEXT* context, int argc, char** argv) makecert_context_output_certificate_file(context, context->output_path); if (context->crtFormat) - makecert_context_output_private_key_file(context, context->output_path); + { + if (makecert_context_output_private_key_file(context, context->output_path) < 0) + return -1; + } } return 0; @@ -1137,6 +1109,8 @@ void makecert_context_free(MAKECERT_CONTEXT* context) free(context->default_name); free(context->common_name); + free(context->output_file); + free(context->output_path); CRYPTO_cleanup_all_ex_data();