summaryrefslogblamecommitdiffstats
path: root/src/pwgui/main.cpp
blob: 264f0df4d267e0a62834ead5dbca10c67c6e4bff (plain) (tree)
1
2
3
4
5
6
7
                  
                        

                       
                      
                         
                  








                         



                   
                  

                       
 

                             






                          
                   
                   

                    

                                         


                                                                     
 

                                      





                                                                         
                                       
 

                                                                                                                                                
                             


                                                      
                                             
                                                  
                                            
                                                                                               
 

                                                 







                                                                                                     

                                




                              

 
                                                                   
                                                                                                 






                                                               
                                           









                                                         
                                           








                                                                  
                                                                     

                                                                                                       
                                           

         

                                                                    

                                                                                                           


                                                                                      
                                                                          
                                           
                 



                                           



                                                 
                                                                                                                                      


                                                                                                                    

                                                                                                         





                                                                   


                                         

                                                                                                                  
                                                                                                              
                                          
                                                
                                                           


                                                                                                                        
                                                                                                                                                  
                                          
                                                
                                                           







                                                            
                                                                     



                                                                                                            
                                                   






                                          











                                                                                                                                                        
 
                         
                                                     
                                

                                                          


                                   
                          
                       
 
 



                                                                           
                                                                                                                                
                                                                                
                                                   





                                           
                                             




                                                                                                           
                                                   







                                                            
                                 
                                       
                                                   
                 
                         














                                                                                                      


                                               
                                                    
                                                                                                                                                              



                                                
                         
                               



                                                                                                                                               







                                                                  









                                                                                          
                                                                      





                                                             


                                                                                  
                                   
                                                 
                 
 
                                      
                                                     
                 




                                                                                                 





                                                              
                                                                                                                                                                                       
                                                                                                               
                        
                                            
                 




                                                




                                                        

                                                                                                      
                                                                         
                                                                       

                                                                     
                                                                   

                                 




                                                                                          
 
 



                                




                                                     

                                          



                                        

                                  
                                        


                                


                                                                          













                                                                   
                                        
                                                  











                                                                                                                  
                         



                                                                   

                 
         


















                                                                                                             
                                           

                                     


                                                       
                      

 







                            

                                                     















































                                                                                                                


                                                  








                                                



                               
                                           


                             


                          



                              


                        



                                                                             


                                       
                                          
         

 
                                            
 





                                                



                                                                                



                                       

 




                                                      











                                                                                                        




                                                            




                           

 






                                                                                               
                       
                             
                                                                                                                       











































                                                                                                                                                                                                                                                                    

                    

 
                                                                                      
 
                         



                                                
                              
                                       
                               

                                   
                                     
                                           


                                                                  
                                                                                                 
                            
                                                              
                        
                                                                 
                 
                                                                              


                                                                       



                                        
                              





                                
 





























































                                                                             
#include "pwgui.h"
#include "../backdrop.h"
#include "config.h"
#include <QApplication>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QLayout>
#include <cups/backend.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>

#include "../x11workaround.h"

#define ARG_JOBID 1
#define ARG_USER 2
#define ARG_JOBTITLE 3
#define ARG_NUMCOPIES 4
#define ARG_PRINTOPTIONS 5
#define ARG_FILENAME 6

#define NAMELEN 400
#define BUFLEN 9000
#define ENVLEN 20000

#define ENV_USERPREFIX "PWGUI_USERPREFIX"

#define DEBUG(...) fprintf(stderr, "DEBUG: [pwgui] " __VA_ARGS__)
#define WARNING(...) fprintf(stderr, "WARNING: [pwgui] " __VA_ARGS__)
#define ERROR(...) fprintf(stderr, "ERROR: [pwgui] " __VA_ARGS__)

#define CUSTOM_CUPS_NO_SUCH_PRINTER 50

static int pid = -1;
// UID and GUI of user we should drop privileges to
static int ruid = 65534, rgid = 65534;
static char ruser[NAMELEN] = "";
// Copy of the GUIs environment, so we can access X
// Whatever you do, make sure this has at least two nullchars at the end!
static char gui_env[ENVLEN] = "\0\0\0";

static int run_backend(char *backend, char *uri, char *jobid, char *user, char *title, char *copies, char *options, char *file, char *password);

static void helper_killGui();
static bool helper_getpiduid(char *user, char *title);
static bool helper_loadlpuser();
static void helper_dropprivs();
static void helper_copyenv(const char *only);
static char *helper_urlencode(char *s, char *enc);
static int helper_cupsError(const int code);
static void helper_messageBox(const char *caption, const char *text, const bool error = false);

static void query_pwdaemon(int pfd, char *creds);

/*
 * Note to the next HiWi who wants to refactor this to use something like boost::program_options:
 * Don't do it unless you are certain that you understood the behaviour described here:
 * > https://www.samba.org/samba/docs/man/manpages/smbspool.8.html
 *
 * Making all arguments positional and making the *first* argument optional was just not a good idea.
 * 
 * */
int main(int argc, char *argv[])
{
	char tmpfile[NAMELEN];
	char device[NAMELEN];
	char backend[NAMELEN];
	int spoolres;



	// Pretty much what smbspool does, but in a generalized way
	if (argc > 2 && strstr(argv[0], ":/") == NULL && strstr(argv[ARG_JOBID], ":/") != NULL) {
		argv++;
		argc--;
	}

	// First check parameter count
	if (argc != 6 && argc != 7) {
		ERROR("Invalid number of arguments passed.\n");
		return CUPS_BACKEND_CANCEL;
	}

	// Determine device uri
	char *env = getenv("DEVICE_URI");
	if (env != NULL && strchr(env, ':') != NULL) {
		snprintf(device, NAMELEN, "%s", env);
	} else if (strstr(argv[0], ":/") != NULL)  {
		snprintf(device, NAMELEN, "%s", argv[0]);
	} else {
		ERROR("No device URI given.\n");
		return CUPS_BACKEND_CANCEL;
	}

	// Get backend from uri
	char *colon = strchr(device, ':');
	*colon = '\0';
	snprintf(backend, NAMELEN, "%s/%s", BACKEND_PATH, device);
	*colon = ':';
	// Is valid?
	if (access(backend, X_OK | R_OK) != 0) {
		helper_getpiduid(argv[ARG_USER], argv[ARG_JOBTITLE]);
		helper_messageBox("PrinterGUI", "Kein Backend für den gewählten Drucker vorhanden.");
		ERROR("Backend %s is not executable. Over and out.\n", backend);
		return CUPS_BACKEND_CANCEL;
	}

	// argv[ARG_JOBTITLE] is title, get printergui pid from it
	if (!helper_getpiduid(argv[ARG_USER], argv[ARG_JOBTITLE])) {
		// El cheapo validation failed. Don't enable "smart mode" (GUI etc), just exec real backend
		ERROR("Dumb mode - will exec actual backend.\n");
		// Mimic cups behaviour wrt dropping privs (Only 0700 or 0500 == root)
		helper_loadlpuser();
		struct stat st;
		if (stat(backend, &st) != 0 || (st.st_mode & 0011) != 0) {
			helper_dropprivs();
		}
		WARNING("Over and out.\n");
		execv(backend, argv);
		exit(127);
	}

	// Get document to print
	if (argc == 6) {
		// Data comes from stdin, save...
		snprintf(tmpfile, NAMELEN, "/tmp/print-%s-%d-%s-%d", argv[ARG_JOBID], (int)time(NULL), argv[ARG_USER], (int)getpid());
		int fh = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0600);
		if (fh < 0) {
			helper_messageBox("PrinterGUI", "Konnte temporäre Datei für den Druckjob nicht anlegen.");
			ERROR("Could not open %s for writing (err:%d). Over and out.\n", tmpfile, errno);
			return CUPS_BACKEND_CANCEL;
		}
		char buffer[BUFLEN];
		int bytes, ret;
		int total = 0;
		for (;;) {
			bytes = read(STDIN_FILENO, buffer, BUFLEN);
			if (bytes == 0) {
				break;
			}
			if (bytes < 0) {
				helper_messageBox("PrinterGUI", "Konnte den Druckjob nicht auf STDIN empfangen.");
				ERROR("Could not read print job from STDIN (err:%d). Over and out.\n", errno);
				close(fh);
				remove(tmpfile);
				return CUPS_BACKEND_CANCEL;
			}
			if ((ret = write(fh, buffer, bytes)) != bytes) {
				helper_messageBox("PrinterGUI", "Konnte Druckjob nicht in temporäre Datei schreiben.");
				ERROR("Could not write %d bytes to %s (wrote %d, err:%d). Over and out.\n", (int)bytes, tmpfile, (int)ret, errno);
				close(fh);
				remove(tmpfile);
				return CUPS_BACKEND_CANCEL;
			}
			total += bytes;
		}
		close(fh);
		DEBUG("Read %d bytes from stdin.\n", total);
		//
	} else {
		// File given, check if file exists
		snprintf(tmpfile, NAMELEN, "%s", argv[ARG_FILENAME]);
		int fh = open(tmpfile, O_RDONLY);
		if (fh < 0) {
			helper_messageBox("PrinterGUI", "Konnte den Druckjob nicht vom Dateisystem lesen.");
			ERROR("Could not open %s for reading. Over and out.\n", tmpfile);
			return CUPS_BACKEND_CANCEL;
		}
		close(fh);
		//
	}
	chown(tmpfile, ruid, rgid);

	// Try right away with what we got
	char creds[NAMELEN];
	/* copy the username but prefix it with the content of PRINTERGUI_USERPREFIX env var */
	helper_copyenv(ENV_USERPREFIX);
	char* user_prefix = getenv(ENV_USERPREFIX);
	if (user_prefix == NULL) {
		/* ok, user_prefix is empty */
		snprintf(creds, NAMELEN, "%s", argv[ARG_USER]);
	} else {
		/* use prefix */
		snprintf(creds, NAMELEN, "%s%s", user_prefix, argv[ARG_USER]);
	}
	spoolres = run_backend(backend, device, argv[ARG_JOBID], creds, argv[ARG_JOBTITLE], argv[ARG_NUMCOPIES], argv[ARG_PRINTOPTIONS], tmpfile, NULL);

	helper_killGui();
	if (spoolres != CUPS_BACKEND_AUTH_REQUIRED) {
		remove(tmpfile);
		return helper_cupsError(spoolres);  // Yay
	}

	// Seems we need the dialog
	int status;
	char *pass = NULL;
	int numRun = 0;


	do {
		WARNING("Direct printing failed. Opening PW dialog....\n");
		int pfd[2];
		if (pipe(pfd) != 0) {
			helper_messageBox("PrinterGUI", "Konnte pipe für die GUI nicht anlegen. Druckvorgang fehlgeschlagen.");
			ERROR("Could not create pipe for GUI. Over and out.\n");
			return CUPS_BACKEND_CANCEL;
		}
		const pid_t pid = fork();
		if (pid == 0) {
			// Child - GUI
			close(pfd[0]);
			helper_dropprivs();
			helper_copyenv(NULL);
			// .... but first, try pwdaemon
			if (numRun == 0) {
				query_pwdaemon(pfd[1], creds);
				// if the function returned, nothing was queried and we should show the gui
			}
			QApplication a(argc, argv);
			Backdrop *bg = new Backdrop;
			bg->show();
			bg->raise();
			bg->activateWindow();
			bg->move(0, 0);
			PwGui *w = new PwGui(pfd[1], creds);
			bg->setMainWindow(w);
			w->show();
			wiggle();
			exit(a.exec());
			return CUPS_BACKEND_CANCEL;
		}
		numRun++;
		// Main (Parent)
		close(pfd[1]);
		// Read from pipe
		int bytes = read(pfd[0], creds, NAMELEN - 1);
		close(pfd[0]);
		// Wait for child to die
		waitpid(pid, NULL, 0); // Don't check status, just look at pipe data
		if (bytes <= 0) { // Probably means user pressed cancel
			helper_messageBox("PrinterGUI", "Druckauftrag abgebrochen.");
			ERROR("Could not read anything from pipe after showing GUI. Over and out.\n");
			remove(tmpfile);
			return CUPS_BACKEND_CANCEL;
		}
		creds[bytes] = '\0';
		int len = strlen(creds);
		if (len < bytes) {
			pass = creds + len + 1;
		}
		// Run backend with pimped user/pass
		status = run_backend(backend, device, argv[ARG_JOBID], creds, argv[ARG_JOBTITLE], argv[ARG_NUMCOPIES], argv[ARG_PRINTOPTIONS], tmpfile, pass);
		helper_cupsError(status);
	} while (status != CUPS_BACKEND_OK);
	remove(tmpfile);
	ERROR("Job submitted. Over and out.\n");
	helper_killGui();
	return CUPS_BACKEND_OK;
}

static int run_backend(char *backend, char *uri, char *jobid, char *user, char *title, char *copies, char *options, char *file, char *password)
{
	int pipefd[2];
	pipe(pipefd);
	pid_t pid = fork();
	if (pid == 0) {
		// Child
		close(pipefd[0]);    // close reading end
		dup2(pipefd[1], 2);  // send stderr to pipe
		close(pipefd[1]);    // no longer needed after dup
		// Write tmpfile to stdin to mimic what cups usually does
		int tfd = open(file, O_RDONLY);
		if (tfd == -1) {
			fprintf(stderr, "Could not open tmpfile as stdin for backend!\n");
			exit(1);
		}
		if (dup2(tfd, 0) == -1) {
			fprintf(stderr, "Could not dup infile to stin of backend\n");
			exit(1);
		}
		// Newer backend can read credentials from environment
		if (user != NULL) {
			setenv("AUTH_USERNAME", user, 1);
		}
		if (password != NULL) {
			setenv("AUTH_PASSWORD", password, 1);
		}

		// Compute proper string length
		int len = strlen(uri) + 20 + strlen("?waitprinter=no&waitjob=no");
		if (user != NULL) {
			len +=  strlen(user) * 3;
		}

		if(password != NULL) {
			len +=  strlen(password) * 3;
		}

		char *newstr = (char*)malloc(len);

		// For ipp14 (at least) we need to build a new URI with ://username:password@....
		if (user != NULL && password != NULL && strncmp(uri, "ipp14:", 6) == 0) {
			char *ptr = newstr;
			ptr += sprintf(ptr, "ipp14://");
			ptr = helper_urlencode(user, ptr);
			*ptr++ = ':';
			ptr = helper_urlencode(password, ptr);
			*ptr++ = '@';
			ptr += sprintf(ptr, "%s", uri + 8); // TODO: If uri already contains credentials, skip over them (check if there's a @ before the first /, starting at index 8)
			// Since we've already forked and execv anyways there's no need to clean up anything...
		} else {
			strcpy(newstr, uri);
		}

		uri = newstr;

		// Append wait options
		if (strncmp(uri, "ipp:", 4) == 0
		    || strncmp(uri, "ipp14:", 6) == 0
		    || strncmp(uri, "ipps:", 5) == 0
		    || strncmp(uri, "http:", 5) == 0
		    || strncmp(uri, "https:", 6) == 0) {
			if (strchr(uri, '?') != NULL) {
				// Question mark has been found, parse the options for waitprinter and
				// waitjob.
				if(strstr(uri, "waitprinter=") == NULL) {
					strcat(uri, "&waitprinter=no");
				}
				if(strstr(uri, "waitjob=") == NULL) {
					strcat(uri, "&waitjob=no");
				}
			} else {
				// No question mark found. Fine hence just add the options
				strcat(uri, "?waitprinter=no&waitjob=no");
			}
		}
		setenv("DEVICE_URI", uri, 1);


		char *args[8];
		args[0] = uri;
		args[1] = jobid;
		args[2] = user;
		// Fix job title if possible
		if (strncmp(title, "gui-", 4) == 0) {
			args[3] = strchr(title, ' ');
			if (args[3] == NULL) {
				args[3] = title;
			} else {
				args[3]++;
			}
		} else {
			args[3] = title;
		}
		args[4] = copies;
		args[5] = options;
		args[6] = NULL; // file;
		args[7] = NULL;
		// Priv dropping
		struct stat st;
		if (stat(backend, &st) != 0 || (st.st_mode & 0011) != 0) {
			helper_dropprivs();
		}
		// Exec
		execv(backend, args);
		exit(127);
		return 127;
	}

	// Main - wait for it...
	close(pipefd[1]); // close writing end
	char buffer[BUFLEN];
	bool needAuth = false;
	bool nonexistent = false;
	int readlen = 0;
	while ((readlen = read(pipefd[0], buffer, BUFLEN-1)) > 0) {
		buffer[readlen] = '\0';
		char *ptr = buffer, *nl;
		while ((nl = strchr(ptr, '\n'))) {
			*nl = '\0';
			ERROR("BACKEND: %s\n", buffer);
			if (strstr(buffer, "Unable to get printer status (Unauthorized)") != NULL) {
				needAuth = true;
				if (kill(pid, SIGTERM) < 0) {
					ERROR("Sending SIGTERM to backend %d failed: %d\n", (int)pid, (int)errno);
				}
				goto loopend;
			} else if (strstr(buffer, "Destination printer does not exist") != NULL) {
				nonexistent = true;
				kill(pid, SIGTERM);
				goto loopend;
			}
			ptr = nl + 1;
		}
		if (*ptr != '\0') {
			ERROR("LINEWRAP: Ignoring cutoff line!\n");
		}
	}
loopend:;
	close(pipefd[0]);
	int status;
	if (waitpid(pid, &status, WNOHANG) == 0) {
		if (kill(pid, SIGKILL) == 0) {
			// Try to reap zombie
			sleep(1);
			waitpid(pid, &status, WNOHANG);
		}
	}
	if (needAuth) {
		ERROR("Killed backend because of 'unauthorized' message (iprint crap?), trying with auth\n");
		return CUPS_BACKEND_AUTH_REQUIRED;
	}
	if (nonexistent) {
		ERROR("Destination printer does not exist!\n");
		return CUSTOM_CUPS_NO_SUCH_PRINTER;
	}
	if (!WIFEXITED(status)) {
		ERROR("Running backend %s failed!\n", backend);
		return CUPS_BACKEND_CANCEL;
	}
	status = WEXITSTATUS(status);
	if (status != CUPS_BACKEND_OK) {
		ERROR("Backend returned %d\n", status);
	}
	return status;
}

static void helper_killGui()
{
	if (pid == -1)
		return;
	kill(pid, SIGTERM);
	pid = -1;
}

static bool helper_getpiduid(char *user, char *title)
{
	// it has to be gui-<PID>, PID has to be an instance of printergui
	// and we have to be able to kill it, only then we assume we should bother the user
	// with an authentication dialog
	if (strncmp(title, "gui-", 4) != 0) {
		WARNING("Job Title doesnt start with 'gui-' (Is: %s)\n", title);
		return false; // Wrong job title
	}
	int p = atoi(title + 4);
	struct stat st;
	struct passwd *pw = getpwnam(user);
	if (pw == NULL) {
		WARNING("Cannot getpwnam %s\n", user);
		return false;
	}
	char bin[PATH_MAX+1], tmp[100];
	snprintf(tmp, 100, "/proc/%d/exe", p);
	if (realpath(tmp, bin) == NULL) {
		WARNING("Cannot get realpath of %s\n", tmp);
		return false;
	}
	char *last = strrchr(bin, '/');
	if (last == NULL || strcmp(last, "/printergui") != 0) {
		WARNING("%s does not end in /printergui\n", bin);
		return false; // Wrong process
	}
	// PID passed via job title seems to be the printergui
	if (lstat(tmp, &st) < 0) {
		WARNING("Could not lstat() %s\n", tmp);
		return false;
	}
	if (st.st_uid != pw->pw_uid) {
		WARNING("Owner of %s: %d, owner of job: %d (%s)\n", tmp, (int)st.st_uid, (int)pw->pw_uid, user);
		return false; // Print job user doesn't match printergui process owner
	}
	// All checks passed, make stuff global
	pid = p;
	ruid = pw->pw_uid;
	rgid = pw->pw_gid;
	snprintf(ruser, NAMELEN, "%s", user);
	// Finally, try to copy the environment of the process
	snprintf(tmp, 100, "/proc/%d/environ", p);
	int fh = open(tmp, O_RDONLY);
	if (fh >= 0) {
		char *ptr = gui_env;
		int bytes = 0, ret;
		while ((ret = read(fh, ptr, ENVLEN - (ptr - gui_env) - 2)) > 0) {
			bytes += ret;
			ptr += ret;
			if (bytes + 3 >= ENVLEN) {
				break;
			}
		}
		close(fh);
		if (bytes >= 0) {
			gui_env[bytes+0] = '\0';
			gui_env[bytes+1] = '\0';
		}
	}
	DEBUG("getpiduid successful!\n");
	return true;
}

static bool helper_loadlpuser()
{
	struct passwd *pw = getpwnam("lp");
	if (pw == NULL) {
		return false;
	}
	ruid = pw->pw_uid;
	rgid = pw->pw_gid;
	return true;
}

static void helper_dropprivs()
{
	if (ruid == 0) {
		return;
	}
	initgroups(ruser, rgid);
	setgid(rgid);
	setuid(ruid);
	ERROR("Set UID to %d and GID to %d.\n", (int)getuid(),(int)getgid());
	chdir("/");
	if (setuid(0) != -1) {
		ERROR("setuid-fu!?\n");
		exit(CUPS_BACKEND_CANCEL);
	}
}

static void helper_copyenv(const char *only)
{
	char *ptr = gui_env;
	while (strlen(ptr) > 0) {
		char *equal = strchr(ptr, '=');
		if (equal != NULL) {
			char *value = equal + 1;
			*equal = '\0';
			if (only == NULL || strcmp(only, ptr) == 0) {
				setenv(ptr, value, 1);
				DEBUG("Setting Env: '%s' = '%s'\n", ptr, value);
			}
			*equal = '=';
		}
		ptr += strlen(ptr) + 1;
	}
}

/**
 * Make sure enc is 3 times as large as s
 */
static char *helper_urlencode(char *source, char *enc)
{
	static char table[256] = {3};
	int len;

	if (table[0] == 3) {
		int i;
		for (i = 0; i < 256; i++) {
			table[i] = (isalnum(i) || i == '~' || i == '-' || i == '.' || i == '_') ? i : 0;
		}
	}

	unsigned char *s = (unsigned char*)source;
	for (; *s != '\0'; s++) {
		if (table[*s] != '\0') {
			len = sprintf(enc, "%c", table[*s]);
		} else {
			len = sprintf(enc, "%%%02X", *s);
		}
		enc += len;
	}
	*enc = '\0';

	return enc;
}

/**
 * Show an error message according to the given cups return code (coming from the real backend)
 * Return a suitable cups return code to pass back to cups. This will be "hold job" in most
 * cases, so the job will still be visible in cups for debugging.
 */
static int helper_cupsError(const int code)
{
	switch (code) {
	case CUPS_BACKEND_OK:
		helper_messageBox("CUPS", "Der Druckauftrag wurde erfolgreich an den Druckserver übermittelt", false);
		return CUPS_BACKEND_OK;

	case CUPS_BACKEND_FAILED:
		// The print file was not successfully transmitted to the device or remote server. The scheduler will respond to this by canceling the job, retrying the job, or stopping the queue depending on the state of the error-policy attribute.
		helper_messageBox("CUPS Fehler", "Fehler beim lokalen Verarbeiten des Druckauftrags");
		return CUPS_BACKEND_HOLD;

	case CUPS_BACKEND_AUTH_REQUIRED:
		// The print file was not successfully transmitted because valid authentication information is required. The scheduler will respond to this by holding the job and adding the "cups-held-for-authentication" keyword to the "job-reasons" attribute.
		helper_messageBox("CUPS Fehler", "Authentifizierung am Druckserver/Drucker fehlgeschlagen");
		break;

	case CUPS_BACKEND_HOLD:
		// The print file was not successfully transmitted because it cannot be printed at this time. The scheduler will respond to this by holding the job.
		helper_messageBox("CUPS Fehler", "Der Drucker hat die Annahme des Druckauftrags verweigert (3)");
		break;

	case CUPS_BACKEND_STOP:
		// The print file was not successfully transmitted because it cannot be printed at this time. The scheduler will respond to this by stopping the queue.
		helper_messageBox("CUPS Fehler", "Der Drucker hat die Annahme des Druckauftrags verweigert (4)");
		return CUPS_BACKEND_HOLD;

	case CUPS_BACKEND_CANCEL:
		// The print file was not successfully transmitted because one or more attributes are not supported or the job was canceled at the printer. The scheduler will respond to this by canceling the job.
		helper_messageBox("CUPS Fehler", "Fehler 5 beim lokalen Verarbeiten des Druckauftrags");
		return CUPS_BACKEND_HOLD;

	case CUPS_BACKEND_RETRY:
		// The print file was not successfully transmitted because of a temporary issue. The scheduler will retry the job at a future time - other jobs may print before this one.
		helper_messageBox("CUPS Fehler", "Fehler 6 beim lokalen Verarbeiten des Druckauftrags");
		return CUPS_BACKEND_HOLD;

	case CUPS_BACKEND_RETRY_CURRENT:
		// The print file was not successfully transmitted because of a temporary issue. The scheduler will retry the job immediately without allowing intervening jobs.
		helper_messageBox("CUPS Fehler", "Fehler 7 beim lokalen Verarbeiten des Druckauftrags");
		return CUPS_BACKEND_HOLD;

	case CUSTOM_CUPS_NO_SUCH_PRINTER:
		helper_messageBox("CUPS Fehler", "Die Druckerwarteschlange existiert nicht auf dem print server. Fehlerhafte lokale printers.conf?");
		return CUPS_BACKEND_CANCEL;
	default:
		ERROR("Unknown cupsError code %d\n", code);
		helper_messageBox("CUPS Fehler", "Unbekannter Fehler beim Drucken", true);
		break;
	}
	return code;
}

static void helper_messageBox(const char *caption, const char *text, const bool error)
{
	helper_killGui();
	WARNING("Trying to MsgBox: %s\n", text);
	const pid_t pid = fork();
	if (pid == 0) {
		// Child - Qt
		char *argv[2];
		argv[0] = (char*)"bla";
		argv[1] = NULL;
		int argc = 1;
		helper_dropprivs();
		helper_copyenv(NULL);
		QApplication a(argc, argv);
		QMessageBox msgBox;
		msgBox.setWindowTitle(QString::fromUtf8(caption));
		msgBox.setText(QString::fromUtf8(text));
		msgBox.setWindowFlags(Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
		if (error) {
			msgBox.setIcon(QMessageBox::Critical);
		} else {
			msgBox.setIcon(QMessageBox::Information);
		}
		QRect desktopRect = QApplication::desktop()->screenGeometry();
		QSize msgBoxSize = msgBox.sizeHint();
		msgBox.move(desktopRect.width()/2-msgBoxSize.width()/2,
			desktopRect.height()/2-msgBoxSize.height()/2);
		msgBox.show();
		msgBox.showNormal();
		msgBox.raise();
		msgBox.activateWindow();
		msgBox.exec();
		exit(0);
		return;
	}
	// Main (Parent)
	// Wait for child to die
	waitpid(pid, NULL, 0);
}

static void query_pwdaemon(int pfd, char *creds)
{
	char homedir[NAMELEN];
	char daemon_data[NAMELEN];
	char *e = getenv("HOME");
	if (e == NULL) {
		struct passwd *p = getpwuid(getuid());
		if (p != nullptr) {
			e = p->pw_dir;
		}
	}
	if (e == nullptr) {
		return;
	}
	snprintf(homedir, NAMELEN, "%s/.pwsocket", e);
	// KONNEKT
	struct sockaddr_un remote;
	struct timeval tv;
	int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	if (fd == -1) {
		perror("Cannot create unix socket");
	   return;
	}
	memset(&remote, 0, sizeof(remote));
	remote.sun_family = AF_UNIX;
	strncpy(remote.sun_path, homedir, sizeof(remote.sun_path)-1);
	tv.tv_sec = 2;
	tv.tv_usec = 0;
	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
	setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
	if (connect(fd, (struct sockaddr*)&remote, sizeof(remote)) == -1) {
		perror("Cannot connect to pw daemon");
		close(fd);
		return;
	}
	write(fd, "PW", 2);
	ssize_t ret = read(fd, daemon_data, NAMELEN - 5);
	if (ret == -1) {
		perror("Cannot read reply from pwdaemon");
		close(fd);
		return;
	}
	if (ret == 0) {
		fprintf(stderr, "pwdaemon is configured to not reveal pw\n");
		close(fd);
		return;
	}
	daemon_data[ret] = '\0';
	char *ptr = daemon_data;
	int i = strlen(creds);
	while (++i < NAMELEN - 5) {
		creds[i] = *ptr++;
		if (creds[i] == '\0')
			break;
	}
	creds[NAMELEN-1] = '\0';
	close(fd);
	::write(pfd, creds, qMin(i+1, NAMELEN));
	::close(pfd);
	exit(0);
}