int write (const char* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
    {
        int bytesWritten = -1;
        const uint32 timeoutEnd = getTimeoutEnd (timeOutMilliseconds);

        if (pipeOut == -1)
        {
            pipeOut = openPipe (createdPipe ? pipeOutName : pipeInName, O_WRONLY, timeoutEnd);

            if (pipeOut == -1)
                return -1;
        }

        bytesWritten = 0;

        while (bytesWritten < numBytesToWrite && ! hasExpired (timeoutEnd))
        {
            const int bytesThisTime = numBytesToWrite - bytesWritten;
            const int numWritten = (int) ::write (pipeOut, sourceBuffer, bytesThisTime);

            if (numWritten <= 0)
            {
                bytesWritten = -1;
                break;
            }

            bytesWritten += numWritten;
            sourceBuffer += numWritten;
        }

        return bytesWritten;
    }
Exemplo n.º 2
0
void testSIGPIPE1(void)
{
    acp_char_t sBuffer[10000];
    acp_rc_t   sRC;

    acpMemSet(sBuffer, 1, sizeof(sBuffer));

    sRC = openPipe();
    ACT_CHECK(ACP_RC_IS_SUCCESS(sRC));

    (void)acpSockSend(&gSockClient, sBuffer, sizeof(sBuffer), NULL, 0);
    (void)acpSockSend(&gSockClient, sBuffer, sizeof(sBuffer), NULL, 0);
    (void)acpSockSend(&gSockClient, sBuffer, sizeof(sBuffer), NULL, 0);
    (void)acpSockSend(&gSockClient, sBuffer, sizeof(sBuffer), NULL, 0);
    sRC = acpSockSend(&gSockClient, sBuffer, sizeof(sBuffer), NULL, 0);
#if defined (ALTI_CFG_OS_WINDOWS)
    ACT_CHECK_DESC(ACP_RC_IS_ECONNABORTED(sRC),
                   ("acpSockSend should return ECONNABORTED but %d", sRC));
#else
    ACT_CHECK_DESC(ACP_RC_IS_EPIPE(sRC),
                   ("acpSockSend should return EPIPE but %d", sRC));
#endif

    sRC = acpSockClose(&gSockClient);
#if defined(ALTI_CFG_OS_TRU64)
    ACT_CHECK(ACP_RC_IS_ECONNRESET(sRC));
#else
    ACT_CHECK(ACP_RC_IS_SUCCESS(sRC));
#endif
}
Exemplo n.º 3
0
static int pipe_dup(File *fp, File *newfp, size_t szfile)
{
	File *x = openPipe((Pipe*)fp->fsdata, fp->oflag & O_RDWR);
	memcpy(newfp, x, sizeof(File));
	kfree(x);
	return 0;
};
Exemplo n.º 4
0
    int write (const char* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
    {
        const uint32 timeoutEnd = getTimeoutEnd (timeOutMilliseconds);

        if (pipeOut == -1)
        {
            //bob: added O_NONBLOCK to prevent deadlocks when no client is connected for reading before we kill the PIPE
            pipeOut = openPipe (createdPipe ? pipeOutName : pipeInName, O_WRONLY|O_NONBLOCK, timeoutEnd);

            if (pipeOut == -1)
                return -1;
        }

        int bytesWritten = 0;

        while (bytesWritten < numBytesToWrite && ! hasExpired (timeoutEnd))
        {
            const int bytesThisTime = numBytesToWrite - bytesWritten;
            const int numWritten = (int) ::write (pipeOut, sourceBuffer, (size_t) bytesThisTime);

            if (numWritten <= 0)
                return -1;

            bytesWritten += numWritten;
            sourceBuffer += numWritten;
        }

        return bytesWritten;
    }
Exemplo n.º 5
0
int sys_pipe(int *pipefd)
{
	int rfd=-1, wfd=-1;

	FileTable *ftab = getCurrentThread()->ftab;
	spinlockAcquire(&ftab->spinlock);

	int i;
	for (i=0; i<MAX_OPEN_FILES; i++)
	{
		if (ftab->entries[i] == NULL)
		{
			if (rfd == -1)
			{
				rfd = i;
			}
			else if (wfd == -1)
			{
				wfd = i;
				break;
			};
		};
	};

	if ((rfd == -1) || (wfd == -1))
	{
		getCurrentThread()->therrno = EMFILE;
		return -1;
	};

	Pipe *pipe = (Pipe*) kmalloc(sizeof(Pipe));
	semInit(&pipe->sem);
	pipe->readcount = 0;
	pipe->writecount = 0;
	pipe->offRead = 0;
	pipe->offWrite = 0;
	pipe->size = 0;

	ftab->entries[rfd] = openPipe(pipe, O_RDONLY);
	ftab->entries[wfd] = openPipe(pipe, O_WRONLY);

	pipefd[0] = rfd;
	pipefd[1] = wfd;

	spinlockRelease(&ftab->spinlock);
	return 0;
};
Exemplo n.º 6
0
QVFbMousePipe::QVFbMousePipe(int display_id)
    : QVFbMouseProtocol(display_id)
{
    fileName = QT_VFB_MOUSE_PIPE(display_id);
    fd = openPipe(fileName.toLocal8Bit().constData());

    if (fd == -1)
	qFatal("Cannot open mouse pipe %s", fileName.toLocal8Bit().data());
}
Exemplo n.º 7
0
QVFbKeyPipeProtocol::QVFbKeyPipeProtocol(int display_id)
    : QVFbKeyProtocol(display_id)
{
    fileName = QT_VFB_KEYBOARD_PIPE(display_id);
    fd = openPipe(fileName.toLocal8Bit().constData());

    if (fd == -1)
	qFatal("Cannot open keyboard pipe %s", fileName.toLocal8Bit().data());
}
Exemplo n.º 8
0
static FILE *writeZippedFile(char *fileName, char append) {
  char buf[MAX_FILENAME];
  const char *op = (append) ? ">>" : ">";
  if (stringEndsIn(fileName, ".bz2") || stringEndsIn(fileName, ".bz"))
    sprintf(buf, "%s %s \"%s\"", BZIP2, op, fileName);
  else if (stringEndsIn(fileName, ".Z"))
    sprintf(buf, "%s %s \"%s\"", COMPRESS, op, fileName);
  else
    sprintf(buf, "%s %s \"%s\"", ZIP, op, fileName);
  return openPipe(buf, "w");
}
Exemplo n.º 9
0
FILE *svd_writeFile(char *fileName, char append) {
  /* Special file name */
  if (!strcmp(fileName, "-"))
    return stdout;
  
  /* If it is a pipe */
  if (fileName[0] == '|')
    return openPipe(fileName + 1, "w");

  /* Check if ends in .gz, .Z, .bz, .bz2 */
  if (stringEndsIn(fileName, ".gz") || stringEndsIn(fileName, ".Z") ||
      stringEndsIn(fileName, ".bz") || stringEndsIn(fileName, ".bz2"))
    return writeZippedFile(fileName, append);
  return (append) ? fopen(fileName, "a") : fopen(fileName, "w");
}
    int read (char* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
    {
        int bytesRead = -1;
        blocked = true;
        const uint32 timeoutEnd = getTimeoutEnd (timeOutMilliseconds);

        if (pipeIn == -1)
        {
            pipeIn = openPipe (createdPipe ? pipeInName : pipeOutName, O_RDWR | O_NONBLOCK, timeoutEnd);

            if (pipeIn == -1)
            {
                blocked = false;
                return -1;
            }
        }

        bytesRead = 0;

        while (bytesRead < maxBytesToRead)
        {
            const int bytesThisTime = maxBytesToRead - bytesRead;
            const int numRead = (int) ::read (pipeIn, destBuffer, bytesThisTime);

            if (numRead <= 0)
            {
                if (errno != EWOULDBLOCK || stopReadOperation || hasExpired (timeoutEnd))
                {
                    bytesRead = -1;
                    break;
                }

                const int maxWaitingTime = 30;
                waitForInput (pipeIn, timeoutEnd == 0 ? maxWaitingTime
                                                      : jmin (maxWaitingTime,
                                                              (int) (timeoutEnd - Time::getMillisecondCounter())));
                continue;
            }

            bytesRead += numRead;
            destBuffer += numRead;
        }

        blocked = false;
        return bytesRead;
    }
Exemplo n.º 11
0
/* Will silently return NULL if file couldn't be opened */
FILE *svd_readFile(char *fileName) {
  char fileBuf[MAX_FILENAME];
  struct stat statbuf;

  /* Special file name */
  if (!strcmp(fileName, "-"))
    return stdin;
  
  /* If it is a pipe */
  if (fileName[0] == '|')
    return openPipe(fileName + 1, "r");

  /* Check if already ends in .gz or .Z and assume compressed */
  if (stringEndsIn(fileName, ".gz") || stringEndsIn(fileName, ".Z")) {
    if (!stat(fileName, &statbuf))
      return readZippedFile(UNZIP, fileName);
    return NULL;
  }
  /* Check if already ends in .bz or .bz2 and assume compressed */
  if (stringEndsIn(fileName, ".bz") || stringEndsIn(fileName, ".bz2")) {
    if (!stat(fileName, &statbuf))
      return readZippedFile(BUNZIP2, fileName);
    return NULL;
  }
  /* Try just opening normally */
  if (!stat(fileName, &statbuf))
    return fopen(fileName, "r");
  /* Try adding .gz */
  sprintf(fileBuf, "%s.gz", fileName);
  if (!stat(fileBuf, &statbuf))
    return readZippedFile(UNZIP, fileBuf);
  /* Try adding .Z */
  sprintf(fileBuf, "%s.Z", fileName);
  if (!stat(fileBuf, &statbuf))
    return readZippedFile(UNZIP, fileBuf);
  /* Try adding .bz2 */
  sprintf(fileBuf, "%s.bz2", fileName);
  if (!stat(fileBuf, &statbuf))
    return readZippedFile(BUNZIP2, fileBuf);
  /* Try adding .bz */
  sprintf(fileBuf, "%s.bz", fileName);
  if (!stat(fileBuf, &statbuf))
    return readZippedFile(BUNZIP2, fileBuf);

  return NULL;
}
Exemplo n.º 12
0
int GetIpv6VifGateway(int skt, const char *ifname)
{
    char pathBuf[MAX_NICINFO_LENGTH] = {0};
    char pszGateway[VIF_NAME_LENGTH] = {0};
    char pszGatewayBuf[VIF_NAME_LENGTH] = {0};
    FILE *iRet;

    if(NULL == ifname)
    {
        return ERROR;
    }

    if(SUCC != CheckName(ifname))
    {
        return ERROR;
    }

    (void)memset_s(pathBuf, MAX_NICINFO_LENGTH, 0, MAX_NICINFO_LENGTH);
     /*exec shell command to get ipv6 route gataway info*/
    (void)snprintf_s(pathBuf, MAX_NICINFO_LENGTH, MAX_NICINFO_LENGTH,
                "route -A inet6 -n | grep -w \"%s\" | grep UG | awk '{print $2}'", ifname);
    iRet = openPipe(pathBuf, "r");
    if (NULL == iRet)
    {
       INFO_LOG("Failed to execute route shell command, pathBuf=%s.", pathBuf);
       gtNicIpv6Info.info[gtNicIpv6Info.count].gateway[0] = '\0';
       return ERROR;
    }

    /*save default gw*/
    if(NULL != fgets(pszGatewayBuf,sizeof(pszGatewayBuf),iRet))
    {
       (void)sscanf_s(pszGatewayBuf,"%s",pszGateway,sizeof(pszGateway));
    }
    trim(pszGateway);

    /*if strlen(pszGateway) < 1, then 0*/
    if(strlen(pszGateway) < 1)
    {
       pszGateway[0]='0';
       pszGateway[1]='\0';
    }
    (void)pclose(iRet);
    (void)strncpy_s(gtNicIpv6Info.info[gtNicIpv6Info.count].gateway, IPV6_ADDR_LEN, pszGateway, strlen(pszGateway));
    return SUCC;
}
Exemplo n.º 13
0
void testSIGPIPE2(void)
{
    acp_char_t sBuffer[10];
    acp_rc_t   sRC;

    acpMemSet(sBuffer, 1, sizeof(sBuffer));

    sRC = acpSignalBlockDefault();
    ACT_CHECK(ACP_RC_IS_SUCCESS(sRC));

    sRC = openPipe();
    ACT_CHECK(ACP_RC_IS_SUCCESS(sRC));

    sRC = acpSockSend(&gSockClient, sBuffer, sizeof(sBuffer), NULL, 0);
    ACT_CHECK_DESC(ACP_RC_IS_EPIPE(sRC),
                   ("acpSockSend should return EPIPE but %d", sRC));

    sRC = acpSockClose(&gSockClient);
    ACT_CHECK(ACP_RC_IS_SUCCESS(sRC));
}
Exemplo n.º 14
0
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		// Create a pipe to send data
		openPipe();
		break;
	case DLL_PROCESS_DETACH:
		closePipe();
		break;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:	
		break;
	}
	return TRUE;
}
Exemplo n.º 15
0
void Interface::test() {
	std::cout << "Testing Interface Class START!..." << std::endl;
	std::cout << "TData Path: " << dataPath << std::endl;
	std::cout << "Fifo IN Path: " << pathFifoIn << std::endl;
	std::cout << "Fifo OUT Path: " << pathFifoOut << std::endl;

	std::cout << "Max Number of Frames: " << maxNumFrame << " Max Number of Actions: " << numAction << std::endl;
	for(int i = 0; i < numAction; ++i) {
		std::cout << "Index: " << i << " Action: " << ind2Act[i] << std::endl;
		std::cout << "Action: " << ind2Act[i] << " Index: " << act2Ind[ind2Act[i]] << std::endl;
	}

	std::cout << "Reset Button:Interface:: " << resetButton << std::endl;
	std::cout << "Num frame stack: " << numFrmStack << std::endl;
	std::cout << "crop Height: " << cropH << std::endl;
	std::cout << "crop Width: " << cropW << std::endl;
	std::cout << "crop Left: " << cropL << std::endl;
	std::cout << "crop Top: " << cropT << std::endl;

	std::cout << "GEN frame info Path: " << frmInfo << std::endl;
	std::cout << "GEN Episode info Path: " << EpInfo << std::endl;
	std::cout << "Opening and Initializing pipe: " << std::endl;
	openPipe();
	initInPipe();
	initOutPipe();
	std::cout << "Writing Random actions to InPipe and reading from OutPipe with data storage..." << std::endl;
	while(!isToEnd()) {
		resetVals(0);
		int x = rand()%numAction;
		writeInPipe(toString(ind2Act[x]));
		readFromPipe();
		saveFrameInfo();
		saveEpisodeInfo();
	}
	finalizePipe();
	std::cout << "Testing Interface Class END!..." << std::endl;
}
Exemplo n.º 16
0
void SketchingTool::loadCurvesCallback(Misc::CallbackData* cbData)
	{
	/* Create a file selection dialog to select a curve file: */
	GLMotif::FileSelectionDialog* loadCurvesDialog=new GLMotif::FileSelectionDialog(getWidgetManager(),"Load Curves...",0,".curves",openPipe());
	loadCurvesDialog->getOKCallbacks().add(this,&SketchingTool::loadCurvesOKCallback);
	loadCurvesDialog->getCancelCallbacks().add(loadCurvesDialog,&GLMotif::FileSelectionDialog::defaultCloseCallback);
	
	/* Show the file selection dialog: */
	popupPrimaryWidget(loadCurvesDialog);
	}
Exemplo n.º 17
0
/* Run the test suite. This must be called with exactly one parameter, the
 * name of the test suite. For details, see file header comment at the top
 * of this file.
 * rgerhards, 2009-04-03
 */
int main(int argc, char *argv[])
{
	int fd;
	int opt;
	int ret = 0;
	FILE *fp;
	char buf[4096];
	char testcases[4096];

	while((opt = getopt(argc, argv, "dc:i:p:t:v")) != EOF) {
		switch((char)opt) {
                case 'c':
			pszCustomConf = optarg;
			break;
                case 'd': 
			useDebugEnv = 1;
			break;
                case 'i':
			if(!strcmp(optarg, "udp"))
				inputMode = inputUDP;
			else if(!strcmp(optarg, "tcp"))
				inputMode = inputTCP;
			else {
				printf("error: unsupported input mode '%s'\n", optarg);
				exit(1);
			}
			break;
                case 'p':
			iPort = atoi(optarg);
			break;
                case 't':
			testSuite = optarg;
			break;
                case 'v':
			verbose = 1;
			break;
		default:printf("Invalid call of nettester, invalid option '%c'.\n", opt);
			printf("Usage: nettester -d -ttestsuite-name -iudp|tcp [-pport] [-ccustomConfFile] \n");
			exit(1);
		}
	}
	
	if(testSuite == NULL) {
		printf("error: no testsuite given, need to specify -t testsuite!\n");
		exit(1);
	}

	atexit(doAtExit);

	if((srcdir = getenv("srcdir")) == NULL)
		srcdir = ".";

	if(verbose) printf("Start of nettester run ($srcdir=%s, testsuite=%s, input=%s/%d)\n",
		srcdir, testSuite, inputMode2Str(inputMode), iPort);

	/* create input config file */
	if((fp = fopen(NETTEST_INPUT_CONF_FILE, "w")) == NULL) {
		perror(NETTEST_INPUT_CONF_FILE);
		printf("error opening input configuration file\n");
		exit(1);
	}
	if(inputMode == inputUDP) {
		fputs("$ModLoad ../plugins/imudp/.libs/imudp\n", fp);
		fprintf(fp, "$UDPServerRun %d\n", iPort);
	} else {
		fputs("$ModLoad ../plugins/imtcp/.libs/imtcp\n", fp);
		fprintf(fp, "$InputTCPServerRun %d\n", iPort);
	}
	fclose(fp);

	/* start to be tested rsyslogd */
	openPipe(testSuite, &rsyslogdPid, &fd);
	readLine(fd, buf);

	/* generate filename */
	sprintf(testcases, "%s/testsuites/*.%s", srcdir, testSuite);
	if(doTests(fd, testcases) != 0)
		ret = 1;

	if(verbose) printf("End of nettester run (%d).\n", ret);
	exit(ret);
}
Exemplo n.º 18
0
int pintoolInit()
{ 
    int returnValue = INIT_ERROR;

    // option du pintool('taint' ou 'checkscore')    
    g_option = KOption.Value();
    
    /**** OPTION TAINT ***/
    if ("taint" == g_option)
    {
        returnValue = OPTION_TAINT;

        // instanciation des classes globales : marquage mémoire et formule SMT2
        pTmgrGlobal   = new TaintManager_Global;
        g_pFormula    = new TranslateIR;
        if (!pTmgrGlobal || !g_pFormula)  return (INIT_ERROR);

        /*** RECUPERATION DES ARGUMENTS DE LA LIGNE DE COMMANDE ***/
        // 1) si pipe => ouverture, sinon récupération de l'option 'input'
        g_nopipe = KNoPipe.Value();
        if (!g_nopipe)
        {
            // erreur si pipe ne peut pas être ouvert
            if (EXIT_FAILURE == openPipe()) return (INIT_ERROR);
            // récupération de l'entrée étudiée via le pipe
            g_inputFile = readFromPipe();
            if (g_inputFile.empty()) return (INIT_ERROR);
        }
        else
        {
            // si pas de pipe, nom de l'entrée passée par ligne de commande
            g_inputFile = KInputFile.Value();    
            // l'écriture des resultats (formule SMT2) se fera dans un fichier
            // donc récupérer le handle du fichier qui sera utilisé
            std::string formulaFile(g_inputFile + "_formula.smt2");
            g_hPipe = WINDOWS::CreateFile(
                formulaFile.c_str(), // nom du fichier 
                GENERIC_WRITE, // acces en ecriture
                0,             // pas de partage 
                nullptr,       // attributs de sécurité par défaut
                CREATE_ALWAYS, // écrasement du précédent fichier, si existant
                0,             // attributs par défaut
                nullptr);	   // pas de modèle

            if ((HANDLE)(WINDOWS::LONG_PTR) (-1) == g_hPipe)  return (INIT_ERROR);
        }

        // 2) mode verbeux : création des fichiers de log
        g_verbose = KVerbose.Value();
        if (g_verbose)
        {
            // création et ouverture du fichier de log dessasemblage
            std::string logfile(g_inputFile + "_asm.log");
            g_debug.open(logfile); 

            // création et ouverture du fichier de log de marquage
            std::string taintfile(g_inputFile + "_taint.log");
            g_taint.open(taintfile);
            if (!g_taint.good() || !g_debug.good()) return (INIT_ERROR);

            // stockage de l'heure du top départ pour statistiques
            g_timeBegin = clock();
        }

        // 4) intervalles d'octets source à marquer, si option présente
        if (!KBytes.Value().empty())  pTmgrGlobal->setBytesToTaint(KBytes.Value());

        // 5) nombre maximal de contraintes ((0 si aucune)
        g_maxConstraints = KMaxConstr.Value();
        
        // 6) type d'OS hote (déterminé par le programme appelant)
        g_osType = static_cast<OSTYPE>(KOsType.Value());
        // détermination des numéros de syscalls à monitorer (dépend de l'OS)
        if (HOST_UNKNOWN == g_osType) return (INIT_ERROR);
        else SYSCALLS::defineSyscallsNumbers(g_osType);
            
        // initialisation de variable globale indiquant le départ de l'instrumentation
        // est mise à vrai par la partie syscalls lorsque les premières données
        // marquées sont créées (= lecture dans l'entrée)
        g_beginInstrumentationOfInstructions = false;

        // création des clefs pour les TLS, pas de fonction de destruction
        g_tlsKeyTaint       = PIN_CreateThreadDataKey(nullptr);
        g_tlsKeySyscallData = PIN_CreateThreadDataKey(nullptr);
    }
    else if ("checkscore" == g_option) // option....checkscore :)   
    {
        // erreur si pipe ne peut pas être ouvert
        if (EXIT_FAILURE == openPipe()) return (INIT_ERROR);
        returnValue = OPTION_CHECKSCORE;
    }
    else return (INIT_ERROR); // option inconnue : erreur

    /**** DERNIERES INITIALISATIONS COMMUNES AUX DEUX OPTIONS **/

    // Initialisation des verrous pour le multithreading
    PIN_InitLock(&g_lock);
  
    // temps maximal d'exécution (valable en 'taint' et en 'checkscore')
    g_maxTime = KMaxTime.Value();
    // si non nul, création d'un thread interne au pintool : 
    // sert à la surveillance du temps maximal d'execution 
    if (g_maxTime)
    {
        THREADID tid = PIN_SpawnInternalThread(maxTimeThread, nullptr, 0, nullptr);
        if (INVALID_THREADID == tid)   return (INIT_ERROR);  
    }

    return (returnValue); // option choisie (taint ou checkScore), ou erreur d'init
} // pintoolInit()
Exemplo n.º 19
0
/**
 * \brief Reopen pipe to read again
 */
void PipeListener::reopenPipe()
{
    closePipe();
    openPipe();
}
Exemplo n.º 20
0
static FILE *readZippedFile(char *command, char *fileName) {
  char buf[MAX_FILENAME];
  sprintf(buf, "%s < %s 2>/dev/null", command, fileName);
  return openPipe(buf, "r");
}
Exemplo n.º 21
0
int startReceiver(int doWarn,
		  struct disk_config *disk_config,
		  struct net_config *net_config,
		  struct stat_config *stat_config,
		  const char *ifName)
{
    char ipBuffer[16];
    union serverControlMsg Msg;
    int connectReqSent=0;
    struct client_config client_config;
    int outFile=1;
    int pipedOutFile;
    struct sockaddr_in myIp;
    int pipePid = 0;
    int origOutFile;
    int haveServerAddress;

    client_config.sender_is_newgen = 0;

    net_config->net_if = getNetIf(ifName);
    zeroSockArray(client_config.socks, NR_CLIENT_SOCKS);

    client_config.S_UCAST = makeSocket(ADDR_TYPE_UCAST,
				       net_config->net_if,
				       0, RECEIVER_PORT(net_config->portBase));
    client_config.S_BCAST = makeSocket(ADDR_TYPE_BCAST,
				       net_config->net_if,
				       0, RECEIVER_PORT(net_config->portBase));

    if(net_config->ttl == 1 && net_config->mcastRdv == NULL) {
	getBroadCastAddress(net_config->net_if,
			    &net_config->controlMcastAddr,
			    SENDER_PORT(net_config->portBase));
	setSocketToBroadcast(client_config.S_UCAST);
    } else {
	getMcastAllAddress(&net_config->controlMcastAddr,
			   net_config->mcastRdv,
			   SENDER_PORT(net_config->portBase));
	if(isMcastAddress(&net_config->controlMcastAddr)) {
	    setMcastDestination(client_config.S_UCAST, net_config->net_if,
				&net_config->controlMcastAddr);
	    setTtl(client_config.S_UCAST, net_config->ttl);
	    
	    client_config.S_MCAST_CTRL =
		makeSocket(ADDR_TYPE_MCAST,
			   net_config->net_if,
			   &net_config->controlMcastAddr,
			   RECEIVER_PORT(net_config->portBase));
	    // TODO: subscribe address as receiver to!
	}
    }
    clearIp(&net_config->dataMcastAddr);
    udpc_flprintf("%sUDP receiver for %s at ", 
		  disk_config->pipeName == NULL ? "" :  "Compressed ",
		  disk_config->fileName == NULL ? "(stdout)":disk_config->fileName);
    printMyIp(net_config->net_if);
    udpc_flprintf(" on %s\n", net_config->net_if->name);

    connectReqSent = 0;
    haveServerAddress = 0;

    client_config.clientNumber= 0; /*default number for asynchronous transfer*/
    while(1) {
	// int len;
	int msglen;
	int sock;

	if (!connectReqSent) {
	    if (sendConnectReq(&client_config, net_config,
			       haveServerAddress) < 0) {
		perror("sendto to locate server");
	    }
	    connectReqSent = 1;
	}

	haveServerAddress=0;

	sock = udpc_selectSock(client_config.socks, NR_CLIENT_SOCKS,
			       net_config->startTimeout);
	if(sock < 0) {
		return -1;
	}

	// len = sizeof(server);
	msglen=RECV(sock, 
		    Msg, client_config.serverAddr, net_config->portBase);
	if (msglen < 0) {
	    perror("recvfrom to locate server");
	    exit(1);
	}
	
	if(getPort(&client_config.serverAddr) != 
	   SENDER_PORT(net_config->portBase))
	    /* not from the right port */
	    continue;

	switch(ntohs(Msg.opCode)) {
	    case CMD_CONNECT_REPLY:
		client_config.clientNumber = ntohl(Msg.connectReply.clNr);
		net_config->blockSize = ntohl(Msg.connectReply.blockSize);

		udpc_flprintf("received message, cap=%08lx\n",
			      (long) ntohl(Msg.connectReply.capabilities));
		if(ntohl(Msg.connectReply.capabilities) & CAP_NEW_GEN) {
		    client_config.sender_is_newgen = 1;
		    copyFromMessage(&net_config->dataMcastAddr,
				    Msg.connectReply.mcastAddr);
		}
		if (client_config.clientNumber == -1) {
		    udpc_fatal(1, "Too many clients already connected\n");
		}
		goto break_loop;

	    case CMD_HELLO_STREAMING:
	    case CMD_HELLO_NEW:
	    case CMD_HELLO:
		connectReqSent = 0;
		if(ntohs(Msg.opCode) == CMD_HELLO_STREAMING)
			net_config->flags |= FLAG_STREAMING;
		if(ntohl(Msg.hello.capabilities) & CAP_NEW_GEN) {
		    client_config.sender_is_newgen = 1;
		    copyFromMessage(&net_config->dataMcastAddr,
				    Msg.hello.mcastAddr);
		    net_config->blockSize = ntohs(Msg.hello.blockSize);
		    if(ntohl(Msg.hello.capabilities) & CAP_ASYNC)
			net_config->flags |= FLAG_PASSIVE;
		    if(net_config->flags & FLAG_PASSIVE)
			goto break_loop;
		}
		haveServerAddress=1;
		continue;
	    case CMD_CONNECT_REQ:
	    case CMD_DATA:
	    case CMD_FEC:
		continue;
	    default:
		break;
	}


	udpc_fatal(1, 
		   "Bad server reply %04x. Other transfer in progress?\n",
		   (unsigned short) ntohs(Msg.opCode));
    }

 break_loop:
    udpc_flprintf("Connected as #%d to %s\n", 
		  client_config.clientNumber, 
		  getIpString(&client_config.serverAddr, ipBuffer));

    getMyAddress(net_config->net_if, &myIp);

    if(!ipIsZero(&net_config->dataMcastAddr)  &&
       !ipIsEqual(&net_config->dataMcastAddr, &myIp) &&
       (ipIsZero(&net_config->controlMcastAddr) ||
       !ipIsEqual(&net_config->dataMcastAddr, &net_config->controlMcastAddr)
	)) {
	udpc_flprintf("Listening to multicast on %s\n",
		      getIpString(&net_config->dataMcastAddr, ipBuffer));
	client_config.S_MCAST_DATA = 
	  makeSocket(ADDR_TYPE_MCAST, net_config->net_if, 
		     &net_config->dataMcastAddr, 
		     RECEIVER_PORT(net_config->portBase));
    }


    if(net_config->requestedBufSize) {
      int i;
      for(i=0; i<NR_CLIENT_SOCKS; i++)
	if(client_config.socks[i] != -1)
	  setRcvBuf(client_config.socks[i],net_config->requestedBufSize);
    }

    outFile=openOutFile(disk_config);
    origOutFile = outFile;
    pipedOutFile = openPipe(outFile, disk_config, &pipePid);

    global_client_config= &client_config;
    atexit(sendDisconnectWrapper);
    {
	struct fifo fifo;
	int printUncompressedPos =
	    udpc_shouldPrintUncompressedPos(stat_config->printUncompressedPos,
					    origOutFile, pipedOutFile);

	receiver_stats_t stats = allocReadStats(origOutFile,
						stat_config->statPeriod,
						printUncompressedPos);
	
	udpc_initFifo(&fifo, net_config->blockSize);

	fifo.data = pc_makeProduconsum(fifo.dataBufSize, "receive");

	client_config.isStarted = 0;

	if((net_config->flags & (FLAG_PASSIVE|FLAG_NOKBD))) {
	  /* No console used */
	  client_config.console = NULL;
	} else {
	  if(doWarn)
	    udpc_flprintf("WARNING: This will overwrite the hard disk of this machine\n");
	  client_config.console = prepareConsole(0);
	  atexit(fixConsole);
	}

	spawnNetReceiver(&fifo,&client_config, net_config, stats);
	writer(&fifo, pipedOutFile);
	if(pipePid) {
	    close(pipedOutFile);
	}
	pthread_join(client_config.thread, NULL);

	/* if we have a pipe, now wait for that too */
	if(pipePid) {
	    udpc_waitForProcess(pipePid, "Pipe");
	}
#ifndef __MINGW32__
	fsync(origOutFile);
#endif /* __MINGW32__ */
	displayReceiverStats(stats, 1);

    }
    fixConsole();
    sendDisconnectWrapper();
    global_client_config= NULL;
    return 0;
}
Exemplo n.º 22
0
void SketchingTool::loadCurvesOKCallback(GLMotif::FileSelectionDialog::OKCallbackData* cbData)
	{
	/* Deactivate the tool just in case: */
	active=false;
	
	/* Delete all curves: */
	for(std::vector<Curve*>::iterator cIt=curves.begin();cIt!=curves.end();++cIt)
		delete *cIt;
	curves.clear();
	
	try
		{
		/* Open the curve file: */
		Comm::ClusterFileCharacterSource curvesFile(cbData->selectedFileName.c_str(),openPipe());
		Misc::ValueSource curvesSource(curvesFile);
		curvesSource.setPunctuation(',',true);
		
		/* Read the curve file header: */
		if(!curvesSource.isString("Vrui Curve Editor Tool Curve File"))
			Misc::throwStdErr("SketchingTool::loadCurvesOKCallback: File %s is not a curve file",cbData->selectedFileName.c_str());
		
		/* Read all curvesSource: */
		unsigned int numCurves=curvesSource.readUnsignedInteger();
		for(unsigned int curveIndex=0;curveIndex<numCurves;++curveIndex)
			{
			/* Create a new curve: */
			Curve* c=new Curve;
			
			/* Read the curve's line width and color: */
			c->lineWidth=GLfloat(curvesSource.readNumber());
			if(curvesSource.readChar()!=',')
				Misc::throwStdErr("SketchingTool::loadCurvesOKCallback: File %s is not a curve file",cbData->selectedFileName.c_str());
			for(int i=0;i<3;++i)
				c->color[i]=Curve::Color::Scalar(curvesSource.readUnsignedInteger());
			c->color[3]=Curve::Color::Scalar(255);
			
			/* Read the curve's control points: */
			unsigned int numControlPoints=curvesSource.readUnsignedInteger();
			for(unsigned int controlPointIndex=0;controlPointIndex<numControlPoints;++controlPointIndex)
				{
				Curve::ControlPoint cp;
				cp.t=Scalar(curvesSource.readNumber());
				if(curvesSource.readChar()!=',')
					Misc::throwStdErr("SketchingTool::loadCurvesOKCallback: File %s is not a curve file",cbData->selectedFileName.c_str());
				for(int i=0;i<3;++i)
					cp.pos[i]=Point::Scalar(curvesSource.readNumber());
				c->controlPoints.push_back(cp);
				}
			
			/* Store the curve: */
			curves.push_back(c);
			}
		}
	catch(std::runtime_error err)
		{
		/* Ignore the error */
		}
	
	/* Destroy the file selection dialog: */
	getWidgetManager()->deleteWidget(cbData->fileSelectionDialog);
	}