Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorza committed Jul 30, 2022
1 parent d28fa2c commit 16bce4d
Show file tree
Hide file tree
Showing 6 changed files with 379 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,6 @@
*.exe
*.out
*.app
/WinPrintServer/x64/Debug
/x64/Debug
/.vs
31 changes: 31 additions & 0 deletions WinPrintServer.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32328.378
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinPrintServer", "WinPrintServer\WinPrintServer.vcxproj", "{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Debug|x64.ActiveCfg = Debug|x64
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Debug|x64.Build.0 = Debug|x64
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Debug|x86.ActiveCfg = Debug|Win32
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Debug|x86.Build.0 = Debug|Win32
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Release|x64.ActiveCfg = Release|x64
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Release|x64.Build.0 = Release|x64
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Release|x86.ActiveCfg = Release|Win32
{F2450B87-DEB4-4C6D-A824-96A2C9D66A36}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {304135C2-4351-4D6E-8BF6-4F76748B8922}
EndGlobalSection
EndGlobal
167 changes: 167 additions & 0 deletions WinPrintServer/WinPrintServer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// WinPrintServer.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <WinSock2.h>
#include <stdarg.h>

std::wstring printerName = L"EPSON098CEF (WF-3520 Series)";
int printerPort = 9100;

void log(LPCWSTR format, ...);
void logFatal(LPCWSTR msg, int errCode);
void logError(LPCWSTR msg, int errCode);

void showUsage();

int wmain(int argc, wchar_t* argv[])
{
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;

int status = WSAStartup(wVersionRequested, &wsaData);
if (status != 0)
{
logFatal(L"failed to initialize the socket library", status);
}

if (argc == 1)
{
DWORD cb;
if (!GetDefaultPrinter(NULL, &cb) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
logFatal(L"no default printer defined", GetLastError());
}
LPWSTR szBuffer = new WCHAR[cb];
GetDefaultPrinter(szBuffer, &cb);
printerName = szBuffer;
delete[]szBuffer;
}
else if (argc == 2)
{
if (_wcsicmp(argv[1], L"-h") == 0)
{
showUsage();
}
printerName = argv[1];
}
else
{
showUsage();
}

SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET)
{
logFatal(L"failed to create server socket", WSAGetLastError());
}

sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(printerPort);
addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

if (bind(serverSocket, (const sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
closesocket(serverSocket);
logFatal(L"failed to bind server socket", WSAGetLastError());
}

sockaddr_in client{};
int size = sizeof(client);
SOCKET clientSocket = INVALID_SOCKET;
HANDLE hPrinter = INVALID_HANDLE_VALUE;

log(L"Print Server Started for '%s'", printerName.c_str());
while (listen(serverSocket, 5) != SOCKET_ERROR)
{
log(L"waiting for connection");
clientSocket = accept(serverSocket, (sockaddr*)&client, &size);
if (clientSocket == INVALID_SOCKET)
{
logError(L"failed to accept client connection", WSAGetLastError());
continue;
}
log(L"connection from %d.%d.%d.%d", client.sin_addr.S_un.S_un_b.s_b1, client.sin_addr.S_un.S_un_b.s_b2, client.sin_addr.S_un.S_un_b.s_b3, client.sin_addr.S_un.S_un_b.s_b4);

DOC_INFO_1 di{};
di.pDocName = const_cast<LPWSTR>(L"RAW Print Job");
di.pOutputFile = NULL;
di.pDatatype = const_cast<LPWSTR>(L"XPS_PASS");

if (!OpenPrinter(const_cast<LPWSTR>(printerName.c_str()), &hPrinter, NULL))
{
logError(L"printer not available", GetLastError());
goto cleanup; // Yes, yes I am sure you can do better.
}

if (StartDocPrinter(hPrinter, 1, (LPBYTE)&di) <= 0)
{
logError(L"failed to start the print job", GetLastError());
goto cleanup;
}

log(L"print job started");
char buffer[4096];
DWORD bytesWritten;
while (true)
{
int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesRead <= 0)
{
break;
}
BOOL result = WritePrinter(hPrinter, buffer, bytesRead, &bytesWritten);
if (!result || bytesWritten != bytesRead)
{
logError(L"print failed", GetLastError());
break;
}
}
EndDocPrinter(hPrinter);
log(L"print job completed");

cleanup:
if (clientSocket != INVALID_SOCKET)
{
closesocket(clientSocket);
}

if (hPrinter != INVALID_HANDLE_VALUE)
{
ClosePrinter(hPrinter);
}
}
closesocket(serverSocket);
WSACleanup();
}

void logFatal(LPCWSTR msg, int errCode)
{
std::wcerr << L"fatal: " << msg << L"(" << errCode << L")" << std::endl;
exit(-1);
}

void logError(LPCWSTR msg, int errCode)
{
std::wcerr << L"error: " << msg << L"(" << errCode << L")" << std::endl;
}

void log(LPCWSTR format, ...)
{
va_list args;
va_start(args, format);
vwprintf(format, args);
va_end(args);
printf("\r\n");
}

void showUsage()
{
log(L"WinPrintServer v1.0\r\n");
log(L"WinPrintServer [options] [printername]");
log(L" -h Show this help information");
log(L" printername The name of the printer to print. If not specified the default printer is used");
exit(-1);
}

149 changes: 149 additions & 0 deletions WinPrintServer/WinPrintServer.vcxproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{f2450b87-deb4-4c6d-a824-96a2c9d66a36}</ProjectGuid>
<RootNamespace>WinPrintServer</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>Ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>Ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="WinPrintServer.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
22 changes: 22 additions & 0 deletions WinPrintServer/WinPrintServer.vcxproj.filters
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="WinPrintServer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
7 changes: 7 additions & 0 deletions WinPrintServer/WinPrintServer.vcxproj.user
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommandArguments>-h</LocalDebuggerCommandArguments>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

0 comments on commit 16bce4d

Please sign in to comment.