Beispiel #1
0
int main() {

  int levelNum, pathNum;
  getPathAndLevelNumbers(&levelNum, &pathNum);

  char *filePath = makeFilePath(levelNum, pathNum);

  checkForDuplicateFile(filePath);
  
  initSDL();
  
  Display d = (Display)malloc(sizeof(struct display));

  openMapInSDLWindow(d);
  
  FILE *tmpFP = createTempFile();
  
  int numberOfCoords = recordStepsInTempFile(tmpFP, d);
  
  writeCoordsToFile(numberOfCoords, tmpFP, filePath);
  
  
  
  return 0;

}
// return "" or "-CMFN=modNamList_" where modNamList_ is a temp file that 
// has the list of module names to be extracted by MDFWriter.
// requires: cmfn is long enough to hold "-CMFN=modNamList_".
char* SQLJFile::getModuleNamesOption(Cmdline_Args &args, char *cmfn)
{
  ExtQualModuleNames* EQMNs = args.getModuleNames();
  Int32 count;
  if (!EQMNs || (count=EQMNs->count()) <= 0) {
    return ""; // means extract all
  }
  else {
    // create a temporary file 
    char *modNamFil, modNam[L_tmpnam+20], templNam[L_tmpnam+26];
    modNamFil = getTempFileName(modNam);
    if (!modNamFil) {
      return NULL;
    }
    FILE *tFil = createTempFile(modNamFil, templNam);
    if (!tFil) {
      return NULL;
    }
    // write into temp file the names of modules to be extracted
    for (Int32 x=0; x<count; x++) {
      const ThreePartModuleName& modNam = EQMNs->at(x);
      fprintf(tFil, "%s\n", modNam.catalog.c_str());
      fprintf(tFil, "%s\n", modNam.schema.c_str());
      fprintf(tFil, "%s\n", modNam.module.c_str());
    }
    fclose(tFil);
    // return "-CMFN=modNamList_"
    strcpy(cmfn, "-CMFN=");
    strcat(cmfn, templNam);
    strcat(cmfn, " ");
    modNamList_ = templNam;
    return cmfn;
  }
}
Beispiel #3
0
/** \brief Creates temporary file containing sensitive DB info.
 *
 *   So we don't have to specify the password on the command line, use
 *   --defaults-extra-file to specify a temporary file with a [client] and
 *  [mysqldump] section that provides the password.  This will fail if the
 *   user's ~/.my.cnf (which is read after the --defaults-extra-file)
 *  specifies a different password that's incorrect for dbUserName
 */
bool DBUtil::CreateTemporaryDBConf(
    const QString &privateinfo, QString &filename)
{
    bool ok = true;
    filename = createTempFile("/tmp/mythtv_db_backup_conf_XXXXXX");
    const QByteArray     tmpfile     = filename.toLocal8Bit();
    const DatabaseParams dbParams    = gCoreContext->GetDatabaseParams();
    const QString        dbSchemaVer = gCoreContext->GetSetting("DBSchemaVer");

    FILE *fp = fopen(tmpfile.constData(), "w");
    if (!fp)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Unable to create temporary "
                    "configuration file for creating DB backup: %1")
                .arg(tmpfile.constData()));
        filename = "";
        ok = false;
    }
    else
    {
        chmod(tmpfile.constData(), S_IRUSR);

        QByteArray outarr = privateinfo.toLocal8Bit();
        fprintf(fp, "%s", outarr.constData());

        if (fclose(fp))
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + QString("Error closing '%1'")
                    .arg(tmpfile.constData()) + ENO);
        }
    }

    return ok;
}
TemporaryFile::TemporaryFile (const File& target, const int optionFlags)
    : temporaryFile (createTempFile (target.getParentDirectory(),
                                     target.getFileNameWithoutExtension()
                                       + "_temp" + String::toHexString (Random::getSystemRandom().nextInt()),
                                     target.getFileExtension(), optionFlags)),
      targetFile (target)
{
    // If you use this constructor, you need to give it a valid target file!
    jassert (targetFile != File());
}
	TITANIUM_FUNCTION(FilesystemModule, createTempFile)
	{
		const auto js_context = this_object.get_context();
		const auto filesystem_ptr = GetStaticObject(js_context).GetPrivate<FilesystemModule>();
		const auto object_ptr = filesystem_ptr->createTempFile(this_object.get_context());
		if (object_ptr != nullptr) {
			return object_ptr->get_object();
		}
		return this_object.get_context().CreateUndefined();
	}
void CppToolsPlugin::test_headersource()
{
    QFETCH(QString, sourceFileName);
    QFETCH(QString, headerFileName);

    Tests::TemporaryDir temporaryDir;
    QVERIFY(temporaryDir.isValid());

    const QDir path = QDir(temporaryDir.path() + QLatin1Char('/') + _(QTest::currentDataTag()));
    const QString sourcePath = path.absoluteFilePath(sourceFileName);
    const QString headerPath = path.absoluteFilePath(headerFileName);
    createTempFile(sourcePath);
    createTempFile(headerPath);

    bool wasHeader;
    clearHeaderSourceCache();
    QCOMPARE(correspondingHeaderOrSource(sourcePath, &wasHeader), headerPath);
    QVERIFY(!wasHeader);
    clearHeaderSourceCache();
    QCOMPARE(correspondingHeaderOrSource(headerPath, &wasHeader), sourcePath);
    QVERIFY(wasHeader);
}
Beispiel #7
0
SystemServices::SystemServices(int iLogLevel, int job_id, char* user_name) : m_iLogLevel(iLogLevel)
{
    m_fp = NULL;
    if (iLogLevel & SAVE_PCL_FILE)
    {
        char    fname[MAX_FILE_PATH_LEN];
        sprintf(fname, "%s/hp_%s_cups_out_job%d_XXXXXX",CUPS_TMP_DIR, user_name, job_id);
        
        createTempFile(fname, &m_fp);
        if (m_fp)
            chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
    }
}
Beispiel #8
0
imeth char * BufferedTempFile_im_gName(object self)
{ BufferedTempFile_iv_t *iv = GetIVs(BufferedTempFile, self);
	if (iv->iTmpFile) 
		return gName(iv->iTmpFile); 
	else 
	{ 



		createTempFile(self); 
		return gName(self); 
	} 
} 
Beispiel #9
0
imeth void * BufferedTempFile_im_gPointerValue(object self)
{ BufferedTempFile_iv_t *iv = GetIVs(BufferedTempFile, self);
	if (iv->iTmpFile) 
		return gPointerValue(iv->iTmpFile); 
	else 
	{ 



		createTempFile(self); 
		return gPointerValue(self); 
	} 
} 
QgsRasterLayer* QgsSentDataSourceBuilder::rasterLayerFromSentRDS( const QDomElement& sentRDSElem, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove ) const
{
  QgsMSDebugMsg( "Entering" );
  QString tempFilePath = createTempFile();
  if ( tempFilePath.isEmpty() )
  {
    return 0;
  }
  QFile tempFile( tempFilePath );

  QTemporaryFile* tmpFile = new QTemporaryFile();

  QString encoding = sentRDSElem.attribute( "encoding" );

  if ( encoding == "base64" )
  {
    if ( tmpFile->open() )
    {
      QByteArray binaryContent = QByteArray::fromBase64( sentRDSElem.text().toAscii() );
      QDataStream ds( tmpFile );
      ds.writeRawData( binaryContent.data(), binaryContent.length() );
    }
    else
    {
      delete tmpFile;
      return 0;
    }

  }
  else //assume text (e.g. ascii grid)
  {
    if ( tmpFile->open() )
    {
      QTextStream tempFileStream( tmpFile );
      tempFileStream << sentRDSElem.text();
    }
    else
    {
      delete tmpFile;
      return 0;
    }
  }

  QgsMSDebugMsg( "TempFilePath is: " + tempFilePath );
  tmpFile->close();

  QgsRasterLayer* rl = new QgsRasterLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ) );
  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
}
Beispiel #11
0
TempOctree::TempOctree(char* fileNameTemplate,unsigned int sMaxNumPointsPerNode,LidarPoint* points,size_t numPoints)
	:tempFileName(new char[strlen(fileNameTemplate)+1]),
	 file(createTempFile(fileNameTemplate),File::ReadWrite),
	 maxNumPointsPerNode(sMaxNumPointsPerNode),
	 pointBbox(Box::empty),
	 writerThreadRun(true),writerThread(this,&TempOctree::writerThreadMethod)
	{
	/* Save the temporary file name: */
	strcpy(tempFileName,fileNameTemplate);
	
	/* Immediately unlink the temporary file; it will stay alive until the file handle is closed: */
	unlink(tempFileName);
	
	/* Calculate the point set's bounding box: */
	for(unsigned int i=0;i<numPoints;++i)
		pointBbox.addPoint(points[i]);
	
	/* Extend the bounding box by a small delta to include all points in a half-open box: */
	Point newMax=pointBbox.max;
	for(int i=0;i<3;++i)
		{
		Scalar delta=Scalar(1);
		if(newMax[i]+delta!=newMax[i])
			{
			while(newMax[i]+(delta*Scalar(0.5))!=newMax[i])
				delta*=Scalar(0.5);
			}
		else
			{
			while(newMax[i]+delta==newMax[i])
				delta*=Scalar(2);
			}
		newMax[i]+=delta;
		}
	pointBbox=Box(pointBbox.min,newMax);
	
	/* Set the root's domain to contain all points: */
	root.domain=Cube(pointBbox);
	
	/* Create the root node's subtree: */
	root.numPoints=numPoints;
	root.points=points;
	createSubTree(root);
	
	/* Wait until the octree file is finished: */
	writerThreadRun=false;
	writeQueueCond.signal();
	writerThread.join();
	file.flush();
	}
Beispiel #12
0
 void write(rfs_fpos_t pos, size_t len, const void *in)
 {
     if (!writeok)
         base.throwError(EACCES,"invalid mode for write");
     if (tempfile==-1)
         tempfile = createTempFile(base,tempfilename);
     long ret = (long)_lseek(tempfile,(long)pos,SEEK_SET);
     if (ret!=pos)
         base.throwError(errno,"write.1");
     int wr = _write(tempfile,in,len);
     if (wr==-1)
         base.throwError(errno,"write.2");
     if (wr!=len)  // disk full
         base.throwError(ENOSPC,"write.3");
     if (pos+wr>savesize)
         savesize = pos+wr;
 }
Beispiel #13
0
void loadZipFile2(const char* ipsw, OutputState** output, const char* file, int useMemory) {
	char* fileName;
	void* buffer;
	unzFile zip;
	unz_file_info pfile_info;

	ASSERT(zip = unzOpen(ipsw), "cannot open input ipsw");
	ASSERT(unzGoToFirstFile(zip) == UNZ_OK, "cannot seek to first file in input ipsw");

	do {
		ASSERT(unzGetCurrentFileInfo(zip, &pfile_info, NULL, 0, NULL, 0, NULL, 0) == UNZ_OK, "cannot get current file info from ipsw");
		fileName = (char*) malloc(pfile_info.size_filename + 1);
		ASSERT(unzGetCurrentFileInfo(zip, NULL, fileName, pfile_info.size_filename + 1, NULL, 0, NULL, 0) == UNZ_OK, "cannot get current file name from ipsw");
		if((file == NULL && fileName[strlen(fileName) - 1] != '/') || (file != NULL && strcmp(fileName, file)) == 0) {
			printf("loading: %s (%ld)\n", fileName, pfile_info.uncompressed_size); fflush(stdout);
			ASSERT(unzOpenCurrentFile(zip) == UNZ_OK, "cannot open compressed file in IPSW");
			if(useMemory) {
				buffer = malloc((pfile_info.uncompressed_size > 0) ? pfile_info.uncompressed_size : 1);
				ASSERT(unzReadCurrentFile(zip, buffer, pfile_info.uncompressed_size) == pfile_info.uncompressed_size, "cannot read file from ipsw");
				addToOutput(output, fileName, buffer, pfile_info.uncompressed_size);
			} else {
				char* tmpFileName = createTempFile();
				FILE* tmpFile = fopen(tmpFileName, "wb");
				buffer = malloc(DEFAULT_BUFFER_SIZE);
				size_t left = pfile_info.uncompressed_size;
				while(left > 0) {
					size_t toRead;
					if(left > DEFAULT_BUFFER_SIZE)
						toRead = DEFAULT_BUFFER_SIZE;
					else
						toRead = left;
					ASSERT(unzReadCurrentFile(zip, buffer, toRead) == toRead, "cannot read file from ipsw");
					fwrite(buffer, toRead, 1, tmpFile);
					left -= toRead;
				}
				fclose(tmpFile);
				free(buffer);
				addToOutput2(output, fileName, NULL, pfile_info.uncompressed_size, tmpFileName);
			}
			ASSERT(unzCloseCurrentFile(zip) == UNZ_OK, "cannot close compressed file in IPSW");
		}
		free(fileName);
	} while(unzGoToNextFile(zip) == UNZ_OK);

	ASSERT(unzClose(zip) == UNZ_OK, "cannot close input ipsw file");
}
Beispiel #14
0
int main(int argc, char *argv[])
{
	if (argc < 2)
	{
		return error(
			"usage: [path] [extensions]\n"
			"\tOR [filename]\n"
			//"usage: [filenames]\n"
			//"\tOR [path] -ext [extensions]\n"
			"Available options are: \n"
			"  -mode         EOL mode (unix, dos, mac)\n"
			"  -skiperrors   skip any errors when processing files\n"
			"  -nolog        hide logs (can increase speed)"
			// TODO:
			//"  -depth        max directory depth (-1 by default)\n"
			//"  -b            make backups\n"
			//"  -bext         backup extension (\"bak\" by default)\n"
			//"  -bdir         backup directory\n"

			//"  -perf         output processing time\n"
		);
	}

	if (processArgs(argc, argv))
		return 1;

	if (!createTempFile())
		return error("failed to create a temporary file");

	int res = 0;

	if (SearchFiles)
	{
		res = searchRecursive(searchpath, extensions);
	}
	else
	{
		if (!processFile(searchpath))
			res = error("unable to open file");
	}

	deleteTempFile();

	return res;
}
Beispiel #15
0
/*!
 * Saves the settings to a file. The settings are first
 * saved to a temporary file, and then that file is copied
 * over the original settings. This avoids clearing settings
 * when there's no disk space.
 * \param originalSettings Settings to save.
 */
static bool doSync(QSettings &originalSettings, QScopedPointer<QFileSystemWatcher>& watcher)
{
    bool returnValue = false;
    QString tempFileName = createTempFile(originalSettings.fileName());
    if (!tempFileName.isEmpty()) {
        QSettings copiedSettings(tempFileName, QSettings::IniFormat);
        if (copySettings(originalSettings, copiedSettings)) {
            copiedSettings.sync();
            if (copiedSettings.status() == QSettings::NoError) {
                renameSettingFile(tempFileName, originalSettings.fileName());
                originalSettings.sync();
                returnValue = true;
            }
        }
    }
    addPathsToWatcher(originalSettings.fileName(), watcher);
    return returnValue;
}
Beispiel #16
0
imeth int BufferedTempFile_im_gWrite(object self, char *buf, unsigned n)
{ BufferedTempFile_iv_t *iv = GetIVs(BufferedTempFile, self);
	if (iv->iTmpFile) 
		return gWrite(iv->iTmpFile, buf, n); 
	else 
	{ 
		if (n + iv->iCurrentOffset > iv->iBufSize) 
		{ 
			createTempFile(self); 
			return gWrite(self, buf, n); 
		} 
		else 
		{ 
			memcpy(iv->iBuffer + iv->iCurrentOffset, buf, n); 
			iv->iCurrentOffset += n; 
			iv->iSize = max(iv->iCurrentOffset, iv->iSize); 
			return n; 
		} 
	} 
} 
Beispiel #17
0
void setLogLevel(UXServices *pSS, char*user_name)
{
    FILE    *fp;
    char    str[258];
    char    *p;
    fp = fopen ("/etc/cups/cupsd.conf", "r");
    if (fp == NULL)
        return;
    while (!feof (fp))
    {
        if (!fgets (str, 256, fp))
	{
	    break;
	}
	if ((p = strstr (str, "hpLogLevel")))
	{
	    p += strlen ("hpLogLevel") + 1;
	    pSS->m_iLogLevel = atoi (p);
	    break;
	}
    }
    fclose (fp);

    if (pSS->m_iLogLevel & SAVE_PCL_FILE)
    {
        char    szFileName[MAX_FILE_PATH_LEN];
        snprintf (szFileName,sizeof(szFileName), "%s/hp_%s_ijs_%d_XXXXXX", CUPS_TMP_DIR, user_name,  getpid());
        createTempFile(szFileName, &pSS->outfp);

//	pSS->outfp = fopen (szFileName, "w");
	if (pSS->outfp)
	{
	    chmod (szFileName, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	}
    }
}
Beispiel #18
0
int doPatch(StringValue* patchValue, StringValue* fileValue, const char* bundlePath, OutputState** state, unsigned int* key, unsigned int* iv, int useMemory, int isPlain) {
	char* patchPath;
	size_t bufferSize;
	void* buffer;
	
	AbstractFile* patchFile;
	AbstractFile* file;
	AbstractFile* out;
	AbstractFile* outRaw;

	char* tmpFileName;

	if(useMemory) {
		bufferSize = 0;
		buffer = malloc(1);
		outRaw = createAbstractFileFromMemoryFile((void**)&buffer, &bufferSize);
	} else {
		tmpFileName = createTempFile();
		outRaw = createAbstractFileFromFile(fopen(tmpFileName, "wb"));
	}
			
	patchPath = malloc(sizeof(char) * (strlen(bundlePath) + strlen(patchValue->value) + 2));
	strcpy(patchPath, bundlePath);
	strcat(patchPath, "/");
	strcat(patchPath, patchValue->value);
	
	XLOG(0, "%s (%s)... ", fileValue->value, patchPath); fflush(stdout);
	
	patchFile = createAbstractFileFromFile(fopen(patchPath, "rb"));

	if (isPlain) {
		out = outRaw;
		file = getFileFromOutputState(state, fileValue->value);
	} else {
		if(key != NULL) {
			XLOG(0, "encrypted input... ");
			out = duplicateAbstractFile2(getFileFromOutputState(state, fileValue->value), outRaw, key, iv, NULL);
		} else {
			out = duplicateAbstractFile(getFileFromOutputState(state, fileValue->value), outRaw);
		}

		if(key != NULL) {
			XLOG(0, "encrypted output... ");
			file = openAbstractFile2(getFileFromOutputState(state, fileValue->value), key, iv);
		} else {
			file = openAbstractFile(getFileFromOutputState(state, fileValue->value));
		}
	}
	
	if(!patchFile || !file || !out) {
		XLOG(0, "file error\n");
		exit(0);
	}

	if(patch(file, out, patchFile) != 0) {
		XLOG(0, "patch failed\n");
		exit(0);
	}

	if(strstr(fileValue->value, "WTF.s5l8900xall.RELEASE")) {
		XLOG(0, "Exploiting 8900 vulnerability... ;)\n");
		AbstractFile* exploited;
		if(useMemory) {
			exploited = createAbstractFileFrom8900(createAbstractFileFromMemoryFile((void**)&buffer, &bufferSize));
		} else {
			exploited = createAbstractFileFrom8900(createAbstractFileFromFile(fopen(tmpFileName, "r+b")));
		}
		exploit8900(exploited);
		exploited->close(exploited);
	}
	
	XLOG(0, "writing... "); fflush(stdout);
	
	if(useMemory) {
		addToOutput(state, fileValue->value, buffer, bufferSize);
	} else {
		outRaw = createAbstractFileFromFile(fopen(tmpFileName, "rb"));
		size_t length = outRaw->getLength(outRaw);
		outRaw->close(outRaw);
		addToOutput2(state, fileValue->value, NULL, length, tmpFileName);
	}

	XLOG(0, "success\n"); fflush(stdout);

	free(patchPath);

	return 0;
}
Beispiel #19
0
/* Worker should:
 * 0. Get the bounds from the master
 * 1. Receive a message for the total number of rounds
 * 2. Wait for a message with the centroids
 * 3. Perform work to calculate the new centroids
 * 4. Send a message back with the new centroids
 * 5. Repeat 2 through 4 for the number of rounds found in 1
 */
void runWorker(int rank){
    int bounds[2];
    int numRounds = 0;
    int numCentroids;
    int strandLength;
    Strand* centroids;
    Histogram* hists;
    FILE* tempFile;
    char fileName[30];

    worker_getBounds(bounds);

    sprintf(fileName,"temp%d_%d",bounds[0], bounds[1]);
    //Create a temporary file (if it doesn't already exist) to
    //store the points used by this worker and open it
    tempFile = createTempFile(fileName,bounds);

    numRounds = worker_getNumRounds();
    // printf("Got num rounds %d\n",rank);
    numCentroids = worker_getNumCentroids();
    // printf("Got %d for num centroids\n %d",numCentroids, rank);
    strandLength = worker_getStrandLength();
    centroids = malloc(sizeof(Strand) * numCentroids);
    int i;
    for(i = 0; i < numCentroids; i++)
    {
        centroids[i]= malloc(sizeof(base) * strandLength);
    }
    if(centroids == null){
        printf("Couldn't malloc!\n\n");
            return;
    }
    hists = malloc(sizeof(Histogram) * numCentroids);
    for(i = 0; i < numCentroids; i++)
    {
        hists[i]= getEmptyHist(strandLength);
    }
    if(hists == null){
        printf("null from malloc!\n");
        return;
    }
    for(i = 0; i < numRounds; i++){
        printf("worker starting round %d!\n",i);
        worker_getCentroids(numCentroids, centroids, strandLength);
        int j;
        // for(j=0;j<numCentroids;j++){
        //     printf("received centroids at %e,%e \n",centroids[j].x,centroids[j].y);
        // }

        worker_calculateCentroidData(tempFile,centroids,numCentroids,
                                    strandLength, hists);
        printf("farting\n");
        worker_sendCentroidData(numCentroids, hists,strandLength);
        printf("worker done with round %d!\n",i);
    }



    //Cleanup
    // fclose(tempFile);
    // free(centroids);
    // free(data);
}
Beispiel #20
0
int main(int ac, char *av[])
{
	//TODO extract the serial port codes into another source file, this is too ugly!
	uint16_t i, j, len;
	int16_t res=0, result=0;
	uint8_t destination_ip[32];
	uint8_t outbuf[512];
	uint8_t linebuf[32];
	uint8_t local_filename[32]="\0";
	FILE* sptr;

	if(ac == 1)
		usage();

	//for(i=0; i<ac; i++)
	//	printf("%s\n",av[i]);

	if(!strcmp("uhf", av[1]))
	{
		mode=RADIOTFTP_MODE_UHF;
		preamble_length=RADIOTFTP_BIM2A_PREAMBLE_LENGTH;
		baud=RADIOTFTP_BIM2A_BAUD_RATE;
		printf("Running with UHF band 19200 baud version\n");
		openLogFile(RADIOTFTP_BIM2A_EVENTLOG);
	}
	else if(!strcmp("vhf", av[1]))
	{
		mode=RADIOTFTP_MODE_VHF;
		preamble_length=RADIOTFTP_UHX1_PREAMBLE_LENGTH;
		baud=RADIOTFTP_UHX1_BAUD_RATE;
		printf("Running with VHF band 2400 baud version\n");
		openLogFile(RADIOTFTP_UHX1_EVENTLOG);
	}
	else if(!strcmp("serial", av[1]))
	{
		mode=RADIOTFTP_MODE_SERIAL;
		preamble_length=RADIOTFTP_SERIAL_PREAMBLE_LENGTH;
		baud=RADIOTFTP_SERIAL_BAUD_RATE;
		printf("Couldn't understand the uhf/vhf mode: using %d mode\n", mode);
		printf("Running with NO BAND %d baud version\n", baud);
		printf("Opening file %s for logging\n",RADIOTFTP_SERIAL_EVENTLOG);
		openLogFile(RADIOTFTP_SERIAL_EVENTLOG);
	}
	else
	{
		printf("Mode not entered, exiting...\n");
		return 0;
	}

	//setting defaults
	udp_get_broadcast_ip(destination_ip);
	strcpy(dial_tty, "/dev/ttyUSB0");

	//scanning command line parameters
	for(i=2; (i < ac) && (av[i][0] == '-'); i++)
	{
		if(strcmp(av[i], "-b") == 0)
		{
			background=1;
		}
		else if(strncmp(av[i], "-f", 2) == 0)
		{
			strncpy(local_filename, av[i] + 2, 32);
			printf("different filename = '%s'\n", local_filename);
		}
		else if(strncmp(av[i], "-dst", 4) == 0)
		{
			memset(destination_ip, 0, 32);
			memcpy(destination_ip, av[i] + 4, strlen(av[i]) - 4);
			/*! convert text ip to numerical */
			text_to_ip(destination_ip, strlen(av[i]) - 4 + 1);
			printf("Destination: ");
			print_addr_dec(destination_ip);
		}
		else
		{
			printf("unknown parameter: %s\n", av[i]);
			usage();
		}
	}
	res=0;
	result=0;

	strncpy(dial_tty, devtag_get(av[i]), sizeof(dial_tty));

	while(!get_lock(dial_tty))
	{
		if(decrementLockRetries() == 0)
			exit(-1);
		sleep(1);
	}

	if((serialportFd=open(devtag_get(av[i]), O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
	{
		perror("bad terminal device, try another");
		exit(-1);
	}
	signal(SIGIO, SIG_IGN);
	signal(SIGINT, sigINT_handler);
	// Make the file descriptor asynchronous (the manual page says only
	// O_APPEND and O_NONBLOCK, will work with F_SETFL...)
	fcntl(serialportFd, F_GETFL);
	fcntl(serialportFd, F_SETFL, O_RDWR | O_SYNC);

	if(tcgetattr(serialportFd, &tp) < 0)
	{
		perror("Couldn't get term attributes");
		exit(-1);
	}
	old=tp;

	/*
	 SANE is a composite flag that sets the following parameters from termio(M):

	 CREAD BRKINT IGNPAR ISTRIP ICRNL IXON ISIG ICANON
	 ECHO ECHOK OPOST ONLCR

	 SANE also clears the following modes:

	 CLOCAL
	 IGNBRK PARMRK INPCK INLCR IUCLC IXOFF
	 XCASE ECHOE ECHONL NOFLSH
	 OLCUC OCRNL ONOCR ONLRET OFILL OFDEL NLDLY CRDLY
	 TABDLY BSDLY VTDLY FFDLY

	 */
	/* 8 bits + baud rate + local control */
	tp.c_cflag=baud | CS8 | CLOCAL | CREAD;
	tp.c_cflag&=~PARENB;
	tp.c_cflag&=~CSTOPB;
	tp.c_cflag&=~CSIZE;
	tp.c_cflag|=CS8;
	tp.c_cflag|=CRTSCTS;
	tp.c_oflag=0; /* Raw Input */
	tp.c_lflag=0; /* No conoical */
	tp.c_cc[VTIME]=0;
	tp.c_cc[VMIN]=1;

	/* ignore CR, ignore parity */
	//ISTRIP is a dangerous flag, it strips the 8th bit of bytes
	//tp.c_iflag= ~( ISTRIP ) | IGNPAR | IGNBRK;
	tp.c_iflag=~(IGNBRK | PARMRK | INPCK | ISTRIP | INLCR | IUCLC | IXOFF) | BRKINT | IGNPAR | ICRNL | IXON | ISIG | ICANON;

	/* set output and input baud rates */

	cfsetospeed(&tp, baud);
	cfsetispeed(&tp, baud);

	tcflush(serialportFd, TCIFLUSH);
	tcflush(serialportFd, TCOFLUSH);

	if(tcsetattr(serialportFd, TCSANOW, &tp) < 0)
	{
		perror("Couldn't set term attributes");
		goto error;
	}

	restore=1;

	//TODO go over the background codes
	if(background)
	{
		int i;
		if(getppid() == 1)
			return 0; /* Already a daemon */

		i=fork();

		if(i < 0)
			exit(1); /* error */

		if(i > 0)
			_exit(0); /* parent exits */

		/* child */

		setsid(); /* obtain a new process group */
		for(i=getdtablesize(); i >= 0; --i)
		{
			if(i == serialportFd)
				continue;
			if(i == 1)
				continue;
			close(i); /* close all descriptors */
		}

		i=open("/dev/null", O_RDWR);
		dup(i);
		dup(i); /* handle standard I/O */
		umask(027); /* set newly created file permissions */
		chdir("/"); /* change running directory */

	}

	srand((unsigned) time(NULL));

	j=0;
	i++;
	for(; i < ac; i++)
	{
		len=strlen(av[i]);
		memcpy(command_buffer + j, av[i], len);
		j+=len;
		if(i != ac - 1)
		{
			command_buffer[j++]=' ';
		}
	}

	//process the escape characters
	for(i=0; i < j; i++)
	{
		if(command_buffer[i] == '\\')
		{
			if(i + 1 < j)
			{
				if(command_buffer[i + 1] == 'n')
				{
					command_buffer[i]='\r';
					command_buffer[i + 1]='\n';
				}
			}
		}
	}

	timers_initialize(&sigRTALRM_handler);

	/*! read settings from radiotftp.conf file */
	sptr=fopen("radiotftp.conf", "r");
	if(sptr != NULL)
	{
		readnline(sptr, linebuf, 32);
		linebuf[6]=atoi(linebuf + 6);
		linebuf[8]=0;
		printf("AX.25 Callsign: ");
		print_callsign(linebuf);
#if AX25_ENABLED==1
		ax25_initialize_network(linebuf);
		printf("USING AX25 LINK LAYER!!!\n");
#else AX25_ENABLED==0
		printf("NOT USING ANY LINK LAYER!!!\n");
#endif
		readnline(sptr, linebuf, 32);
		text_to_ip(linebuf, strlen(linebuf));
		printf("IPv4 Address: ");
		print_addr_dec(linebuf);
		udp_initialize_ip_network(linebuf, &queueSerialData);
	}
	else
	{
#if AX25_ENABLED==1
		ax25_initialize_network(my_ax25_callsign);
		printf("AX.25 CALLSIGN = ");
		print_callsign(ax25_get_local_callsign(NULL));
#endif
		udp_initialize_ip_network(my_ip_address, &queueSerialData);
		printf("IPv4 Address = ");
		print_addr_dec(udp_get_localhost_ip(NULL));
	}

	switch(mode)
	{
		case RADIOTFTP_MODE_UHF:
			tftp_initialize(udp_get_data_queuer_fptr(), RADIOTFTP_BIM2A_ACK_TIMEOUT_MIN, RADIOTFTP_BIM2A_ACK_TIMEOUT_MAX, RADIOTFTP_BIM2A_READ_TIMEOUT);
			break;
		case RADIOTFTP_MODE_VHF:
			tftp_initialize(udp_get_data_queuer_fptr(), RADIOTFTP_UHX1_ACK_TIMEOUT_MIN, RADIOTFTP_UHX1_ACK_TIMEOUT_MAX, RADIOTFTP_UHX1_READ_TIMEOUT);
			break;
		case RADIOTFTP_MODE_SERIAL:
			tftp_initialize(udp_get_data_queuer_fptr(), RADIOTFTP_SERIAL_ACK_TIMEOUT_MIN, RADIOTFTP_SERIAL_ACK_TIMEOUT_MAX, RADIOTFTP_SERIAL_READ_TIMEOUT);
			break;
		default:
			perror("unknown baud rate");
			safe_exit(-1);
			break;
	}

	if(!strncasecmp(RADIOTFTP_COMMAND_PUT, command_buffer, strlen(RADIOTFTP_COMMAND_PUT)))
	{
		printf(RADIOTFTP_COMMAND_PUT"\n");
		registerEvent(RADIOTFTP_COMMAND_PUT, command_buffer + strlen(RADIOTFTP_COMMAND_PUT) + 1);
		if((res=tftp_sendRequest(TFTP_OPCODE_WRQ, destination_ip, local_filename, command_buffer + strlen(RADIOTFTP_COMMAND_PUT) + 1, j - strlen(RADIOTFTP_COMMAND_PUT) - 1, 0)))
		{
			printf("%d\n", res);
			perror("tftp request fail");
			goto error;
		}
	}
	else if(!strncasecmp(RADIOTFTP_COMMAND_BEACON, command_buffer, strlen(RADIOTFTP_COMMAND_BEACON)))
	{
		printf(RADIOTFTP_COMMAND_BEACON"\n");
		registerEvent(RADIOTFTP_COMMAND_BEACON, command_buffer + strlen(RADIOTFTP_COMMAND_BEACON) + 1);
		if((res=tftp_sendSingleBlockData(destination_ip, command_buffer + strlen(RADIOTFTP_COMMAND_BEACON) + 1, j - strlen(RADIOTFTP_COMMAND_BEACON) - 1, local_filename)))
		{
			printf("%d\n", res);
			perror("tftp request fail");
			goto error;
		}
	}
	else if(!strncasecmp(RADIOTFTP_COMMAND_APPEND_LINE, command_buffer, strlen(RADIOTFTP_COMMAND_APPEND_LINE)))
	{
		printf(RADIOTFTP_COMMAND_APPEND_LINE"\n");
		registerEvent(RADIOTFTP_COMMAND_APPEND_LINE, command_buffer + strlen(RADIOTFTP_COMMAND_APPEND_LINE) + 1);
		i=createTempFile(TEMPFILE_PREFIX, TEMPFILE_POSTFIX);
		if(tempFile == NULL)
		{
			perror("couldn't create temp file to store the line feed");
			goto error;
		}
		fwrite(command_buffer + strlen(RADIOTFTP_COMMAND_APPEND_LINE) + 1, 1, j - strlen(RADIOTFTP_COMMAND_APPEND_LINE) - 1, tempFile);
		fflush(tempFile);
		fclose(tempFile);
		printf("tempfileName=%s\nlocal_filename=%s\n", tempFileName, local_filename);
		if((res=tftp_sendRequest(TFTP_OPCODE_WRQ, destination_ip, tempFileName, local_filename, strlen(local_filename), 1)))
		{
			printf("%d\n", res);
			perror("tftp request fail");
			goto error;
		}
	}
	else if(!strncasecmp(RADIOTFTP_COMMAND_APPEND_FILE, command_buffer, strlen(RADIOTFTP_COMMAND_APPEND_FILE)))
	{
		printf(RADIOTFTP_COMMAND_APPEND_FILE"\n");
		registerEvent(RADIOTFTP_COMMAND_APPEND_FILE, command_buffer + strlen(RADIOTFTP_COMMAND_APPEND_FILE) + 1);
		if((res=tftp_sendRequest(TFTP_OPCODE_WRQ, destination_ip, local_filename, command_buffer + strlen(RADIOTFTP_COMMAND_APPEND_FILE) + 1, j - strlen(RADIOTFTP_COMMAND_APPEND_FILE) - 1, 1)))
		{
			printf("%d\n", res);
			perror("tftp request fail");
			goto error;
		}
	}
	else if(!strncasecmp(RADIOTFTP_COMMAND_GET, command_buffer, strlen(RADIOTFTP_COMMAND_GET)))
	{
		printf(RADIOTFTP_COMMAND_GET"\n");
		registerEvent(RADIOTFTP_COMMAND_GET, command_buffer + strlen(RADIOTFTP_COMMAND_GET) + 1);
		if((res=tftp_sendRequest(TFTP_OPCODE_RRQ, destination_ip, local_filename, command_buffer + strlen(RADIOTFTP_COMMAND_GET) + 1, j - strlen(RADIOTFTP_COMMAND_GET) - 1, 0)))
		{
			printf("%d\n", res);
			perror("tftp request fail");
			goto error;
		}
	}
	else
	{
		printf("hello radio world!\n");
		registerEvent("helloWorld", "");
		if((res=queueSerialData(udp_get_localhost_ip(NULL), HELLO_WORLD_PORT, udp_get_broadcast_ip(NULL), HELLO_WORLD_PORT, "hello world\n\0x00", strlen("hello world\n\0x00"))))
		{
			printf("%d\n", res);
			perror("tftp request fail");
			goto error;
		}
	}

	int sync_counter=0;
	int sync_passed=0;
	int save_index=0;

	//entering the main while loop
	printf("started listening...\n");
	while(1)
	{
		if(timer_flag)
		{
			idle_timer_handler();
			tftp_timer_handler();
			timer_flag=0;
		}
		if(idle_flag)
		{
			//print_time("System Idle");
			idle_flag=0;
		}
		if(queue_flag)
		{
//			printf("queue flag\n");
			if(!sync_passed && sync_counter < 1)
			{
				//wait_some
				switch(mode)
				{
					case RADIOTFTP_MODE_UHF:
						usleep(RADIOTFTP_BIM2A_TX_MESSAGE_INTERVAL);
						break;
					case RADIOTFTP_MODE_VHF:
						usleep(RADIOTFTP_UHX1_TX_MESSAGE_INTERVAL);
						break;
					case RADIOTFTP_MODE_SERIAL:
						usleep(RADIOTFTP_SERIAL_TX_MESSAGE_INTERVAL);
						break;
					default:
						perror("unknown baud rate");
						safe_exit(-1);
						break;
				}
				transmitSerialData();
				queue_flag=0;
			}
		}
		if((res=read(serialportFd, io, IO_BUFSIZE)) > 0)
		{
			io_index=0;
			//printf("# of bytes read = %d\n", res);
			for(i=0; i < res; i++)
			{
				//putchar(io[i]);
				//printf("%\n",io[i]);
				if(sync_counter < SYNC_LENGTH && io[i] == syncword[sync_counter])
				{
					sync_counter++; /* sync continued */
					//printf("sync counting %d\n",sync_counter);
				}
				else
				{
					//printf("sync reset %d\n",sync_counter);
					sync_counter=0; /* not a preamble, reset counter */
				}
				if(sync_counter >= SYNC_LENGTH && sync_passed == 0)
				{ /* preamble passed */
					sync_passed=1;
				}
				if(sync_passed)
				{
					//printf("getting data '%c'\n", io[i]);
					if(io[i] == END_OF_FILE && !isManchester_encoded(io[i]))
					{
//							printf("non-manchester character received\n");
						outbuf[0]=0;
						result=manchester_decode(buf + 1, manchester_buffer, save_index);
#if AX25_ENABLED==1
						result=ax25_open_ui_packet(NULL, NULL, ax25_buffer, manchester_buffer, result);
#else
						result=1;
#endif
						if(result)
						{
//								printf("opened link-layer packet\n");
#if AX25_ENABLED==1
							result=udp_open_packet(udp_src, &udp_src_prt, udp_dst, &udp_dst_prt, udp_buffer, ax25_buffer);
#else
							result = udp_open_packet(udp_src, &udp_src_prt, udp_dst, &udp_dst_prt, udp_buffer, manchester_buffer);
#endif
							if(result)
							{
//									printf("opened transport-layer packet\n");
								udp_packet_demultiplexer(udp_src, udp_src_prt, udp_dst, udp_dst_prt, udp_buffer, result);
							}
							else
							{
								strcat(outbuf, "!udp discarded!");
								if(write(1, outbuf, strlen(outbuf)) <= 0)
								{
									fputs("couldn't write to tty\n", stderr);
								}
								if(write(1, "\n", 1) <= 0)
								{
									fputs("couldn't write to tty\n", stderr);
								}
							}
						}
						else
						{
							strcat(outbuf, "!ax25 discarded!");
							if(write(1, outbuf, strlen(outbuf)) <= 0)
							{
								fputs("couldn't write to tty\n", stderr);
							}
							if(write(1, "\n", 1) <= 0)
							{
								fputs("couldn't write to tty\n", stderr);
							}
						}
						sync_passed=0;
						sync_counter=0;
						save_index=0;
					}
					else
					{
//						printf("saved data '%c'\n", io[i]);
//						printf("save_index=%d/%d\n",save_index, sizeof(buf));
						if(save_index >= sizeof(buf))
						{
							sync_passed=0;
							sync_counter=0;
							save_index=0;
						}
						buf[save_index++]=io[i];
						buf[save_index + 1]=0;
//						printf("-\n%s\n-\n", buf);
					}
				}
			}
			io_flag=0;
		}
	}

	safe_exit(0);
	error: safe_exit(-1);

	return -2;
}
TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
    : temporaryFile (createTempFile (File::getSpecialLocation (File::tempDirectory),
                                     "temp_" + String::toHexString (Random::getSystemRandom().nextInt()),
                                     suffix, optionFlags))
{
}
QgsRasterLayer* QgsRemoteOWSBuilder::wcsLayerFromUrl( const QString &url,
    const QString &layerName,
    QList<QTemporaryFile*> &filesToRemove,
    QList<QgsMapLayer*> &layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( layerName );
  Q_UNUSED( allowCaching );

#if QT_VERSION < 0x050000
  QgsDebugMsg( "Entering" );

  //write server url and coverage name to a temporary file
  QString fileName = createTempFile();
  if ( fileName.isEmpty() )
  {
    return nullptr;
  }

  QFile tempFile( fileName );

  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( !tmpFile->open() )
  {
    delete tmpFile;
    return nullptr;
  }

  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request

  QgsDebugMsg( "opening successful" );
  QgsDebugMsg( "url: " + url );
  //extract server url and coverage name from string
  QStringList serverSplit = url.split( "?" );
  if ( serverSplit.size() < 2 )
  {
    QgsDebugMsg( "error, no '?' contained in url" );
    return nullptr;
  }
  QString serverUrl = serverSplit.at( 0 );
  QString request = serverSplit.at( 1 );
  QStringList parameterSplit = request.split( "&" );
  QString coverageName;
  QString format;
  for ( int i = 0; i < parameterSplit.size(); ++i )
  {
    if ( parameterSplit.at( i ).startsWith( "COVERAGE", Qt::CaseInsensitive ) )
    {
      coverageName = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
    else if ( parameterSplit.at( i ).startsWith( "FORMAT", Qt::CaseInsensitive ) )
    {
      format = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
  }

  if ( coverageName.isEmpty() )
  {
    QgsDebugMsg( "coverage name is empty" );
    return nullptr;
  }

  if ( format.isEmpty() )
  {
    format = "GeoTIFF"; //use geotiff as default
  }

  QgsDebugMsg( "wcs server url: " + serverUrl );
  QgsDebugMsg( "coverage name: " + coverageName );

  //fetch WCS layer in the current resolution as geotiff
  QString wcsRequest = serverUrl + "?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=" + coverageName + "&FORMAT=" + format;

  //CRS (or SRS)
  QString crs = mParameterMap.value( "CRS", mParameterMap.value( "SRS" ) );
  if ( crs.isEmpty() )
  {
    QgsDebugMsg( "No CRS or SRS parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&CRS=" + crs;

  //width
  QString width = mParameterMap.value( "WIDTH" );
  if ( width.isEmpty() )
  {
    QgsDebugMsg( "No WIDTH parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&WIDTH=" + width;

  //height
  QString height = mParameterMap.value( "HEIGHT" );
  if ( height.isEmpty() )
  {
    QgsDebugMsg( "No HEIGHT parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&HEIGHT=" + height;

  //bbox
  QString bbox = mParameterMap.value( "BBOX" );
  if ( bbox.isEmpty() )
  {
    QgsDebugMsg( "No BBOX parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&BBOX=" + bbox;

  QgsDebugMsg( "WCS request is: " + wcsRequest );
  //make request and store byte array into temporary file
  QgsHttpTransaction httpTransaction( wcsRequest );
  QByteArray result;
  if ( !httpTransaction.getSynchronously( result ) )
  {
    return nullptr;
  }

  QDataStream tempFileStream( &tempFile );
  tempFileStream.writeRawData( result.data(), result.size() );
  tempFile.close();

  QgsRasterLayer* rl = new QgsRasterLayer( fileName, layerNameFromUri( fileName ) );
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
#else
  Q_UNUSED( url )
  Q_UNUSED( filesToRemove )
  Q_UNUSED( layersToRemove )
  QgsDebugMsg( "remote http not supported with Qt5" );
  return nullptr;
#endif

}
Beispiel #23
0
int doDecrypt(StringValue* decryptValue, StringValue* fileValue, const char* bundlePath, OutputState** state, unsigned int* key, unsigned int* iv, int useMemory) {
	size_t bufferSize;
	void* buffer;
	
	AbstractFile* file;
	AbstractFile* out;
	AbstractFile* outRaw;

	char* tmpFileName;

	if(useMemory) {
		bufferSize = 0;
		buffer = malloc(1);
		outRaw = createAbstractFileFromMemoryFile((void**)&buffer, &bufferSize);
	} else {
		tmpFileName = createTempFile();
		outRaw = createAbstractFileFromFile(fopen(tmpFileName, "wb"));
	}

	out = duplicateAbstractFile(getFileFromOutputState(state, fileValue->value), outRaw);
	file = openAbstractFile3(getFileFromOutputState(state, fileValue->value), key, iv, 0);
	
	if(!file || !out) {
		XLOG(0, "file error\n");
		exit(0);
	}

	char *buf = malloc(1024 * 1024);
	off_t inDataSize = file->getLength(file);
	while (inDataSize > 0) {
		off_t avail, chunk = 1024 * 1024;
		if (chunk > inDataSize) {
			chunk = inDataSize;
		}
		if (chunk < 0) {
			XLOG(0, "decrypt failed\n");
			exit(0);
		}
		avail = file->read(file, buf, chunk);
		out->write(out, buf, avail);
		if (avail < chunk) {
			break;
		}
		inDataSize -= chunk;
	}
	out->close(out);
	file->close(file);
	free(buf);

	XLOG(0, "writing... "); fflush(stdout);
	
	if (decryptValue) {
		fileValue = decryptValue;
	}
	if(useMemory) {
		addToOutput(state, fileValue->value, buffer, bufferSize);
	} else {
		outRaw = createAbstractFileFromFile(fopen(tmpFileName, "rb"));
		size_t length = outRaw->getLength(outRaw);
		outRaw->close(outRaw);
		addToOutput2(state, fileValue->value, NULL, length, tmpFileName);
	}

	XLOG(0, "success\n"); fflush(stdout);

	return 0;
}
Beispiel #24
0
int HPCupsFilter::processRasterData(cups_raster_t *cups_raster)
{
    FILE                   *kfp = NULL;
    FILE                   *cfp = NULL;
    BYTE                   *kRaster = NULL;
    BYTE                   *rgbRaster = NULL;
    int                    current_page_number = 0;
    cups_page_header2_t    cups_header;
    DRIVER_ERROR           err;
    int                    ret_status = 0;

    char hpPreProcessedRasterFile[MAX_FILE_PATH_LEN]; //temp file needed to store raster data with swaped pages.


    sprintf(hpPreProcessedRasterFile, "%s/hp_%s_cups_SwapedPagesXXXXXX",CUPS_TMP_DIR, m_JA.user_name);


    while (cupsRasterReadHeader2(cups_raster, &cups_header))
    {
        current_page_number++;

        if (current_page_number == 1) {

            if (startPage(&cups_header) != NO_ERROR) {
                return JOB_CANCELED;
            }

            if (m_JA.pre_process_raster) {
		    	// CC ToDo: Why pSwapedPagesFileName should be sent as a parameter? 
                  	// Remove if not required to send it as parameter
                err = m_Job.preProcessRasterData(&cups_raster, &cups_header, hpPreProcessedRasterFile);
                if (err != NO_ERROR) {
                    if (m_iLogLevel & BASIC_LOG) {
                        dbglog ("DEBUG: Job::StartPage failed with err = %d\n", err);
                    }
                    ret_status = JOB_CANCELED;
                    break;
                }
            }

            if (cups_header.cupsColorSpace == CUPS_CSPACE_RGBW) {
                rgbRaster = new BYTE[cups_header.cupsWidth * 3];
                if (rgbRaster == NULL) {
                    return ALLOCMEM_ERROR;
                }
                kRaster = new BYTE[cups_header.cupsWidth];
                if (kRaster == NULL) {
                    delete [] rgbRaster;
                    return ALLOCMEM_ERROR;
                }
                memset (kRaster, 0, cups_header.cupsWidth);
                memset (rgbRaster, 0xFF, cups_header.cupsWidth * 3);
            }
        } // end of if(current_page_number == 1)

        if (cups_header.cupsColorSpace == CUPS_CSPACE_K) {
            kRaster = m_pPrinterBuffer;
            rgbRaster = NULL;
        }
        else if (cups_header.cupsColorSpace != CUPS_CSPACE_RGBW) {
            rgbRaster = m_pPrinterBuffer;
            kRaster = NULL;
        }

        BYTE    *color_raster = NULL;
        BYTE    *black_raster = NULL;

        err = m_Job.StartPage(&m_JA);
        if (err != NO_ERROR) {
            if (m_iLogLevel & BASIC_LOG) {
                dbglog ("DEBUG: Job::StartPage failed with err = %d\n", err);
            }
            ret_status = JOB_CANCELED;
            break;
        }

        // Save Raster file for Debugging
        if (m_iLogLevel & SAVE_INPUT_RASTERS)
        {
            char    szFileName[MAX_FILE_PATH_LEN];
            memset(szFileName, 0, sizeof(szFileName));

            if (cups_header.cupsColorSpace == CUPS_CSPACE_RGBW ||
                cups_header.cupsColorSpace == CUPS_CSPACE_RGB)
            {

                snprintf (szFileName, sizeof(szFileName), "%s/hpcups_%s_c_bmp_%d_XXXXXX", CUPS_TMP_DIR, m_JA.user_name, current_page_number);
                createTempFile(szFileName, &cfp);
                if (cfp)
                {
                    chmod (szFileName, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
                }
            }

            if (cups_header.cupsColorSpace == CUPS_CSPACE_RGBW ||
                cups_header.cupsColorSpace == CUPS_CSPACE_K)
            {
                snprintf (szFileName, sizeof(szFileName), "%s/hpcups_%s_k_bmp_%d_XXXXXX", CUPS_TMP_DIR, m_JA.user_name, current_page_number);
                createTempFile(szFileName, &kfp);
                if (kfp)
                {
                    chmod (szFileName, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
                }
            }

            WriteBMPHeader (cfp, cups_header.cupsWidth, cups_header.cupsHeight, COLOR_RASTER);
            WriteBMPHeader (kfp, cups_header.cupsWidth, cups_header.cupsHeight, BLACK_RASTER);
        }

        fprintf(stderr, "PAGE: %d %s\r\n", current_page_number, m_argv[4]);
        // Iterating through the raster per page
        bool is_ljmono = strcmp(m_JA.printer_language, "ljmono");
        for (int y = 0; y < (int) cups_header.cupsHeight; y++) {
            cupsRasterReadPixels (cups_raster, m_pPrinterBuffer, cups_header.cupsBytesPerLine);
            color_raster = rgbRaster;
            black_raster = kRaster;

            if ((y == 0) && !is_ljmono) {
                //For ljmono, make sure that first line is not a blankRaster line.Otherwise printer
                //may not skip blank lines before actual data
                //Need to revisit to cross check if it is a firmware issue.

                *m_pPrinterBuffer = 0x01;
                dbglog("First raster data plane..\n" );
            }

            if (this->isBlankRaster((BYTE *) m_pPrinterBuffer, &cups_header)) {
                color_raster = NULL;
                black_raster = NULL;
            }

            extractBlackPixels(&cups_header, black_raster, color_raster);

            //! Sending Raster bits off to encapsulation
            err = m_Job.SendRasters (black_raster, color_raster);
            if (err != NO_ERROR) {
                break;
            }

            if (m_iLogLevel & SAVE_INPUT_RASTERS)
            {
                WriteBMPRaster (cfp, color_raster, cups_header.cupsWidth, COLOR_RASTER);
                WriteBMPRaster (kfp, black_raster, cups_header.cupsWidth/8, BLACK_RASTER);
            }
        }  // for() loop end

        m_Job.NewPage();
        if (err != NO_ERROR) {
            break;
        }
    }  // while() loop end

    //! Remove the old processing band data...
    if (cups_header.cupsColorSpace == CUPS_CSPACE_RGBW) {
        delete [] kRaster;
        delete [] rgbRaster;
        kRaster = NULL;
        rgbRaster = NULL;
    }

    unlink(hpPreProcessedRasterFile);
    return ret_status;
}